repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
DingYusong/General | Example/Pods/libqrencode/mmask.c | 34 | 4103 | /*
* qrencode - QR Code encoder
*
* Masking for Micro QR Code.
* Copyright (C) 2006-2011 Kentaro Fukuchi <kentaro@fukuchi.org>
*
* 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 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
*/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include "qrencode.h"
#include "mqrspec.h"
#include "mmask.h"
__STATIC void MMask_writeFormatInformation(int version, int width, unsigned char *frame, int mask, QRecLevel level)
{
unsigned int format;
unsigned char v;
int i;
format = MQRspec_getFormatInfo(mask, version, level);
for(i=0; i<8; i++) {
v = 0x84 | (format & 1);
frame[width * (i + 1) + 8] = v;
format = format >> 1;
}
for(i=0; i<7; i++) {
v = 0x84 | (format & 1);
frame[width * 8 + 7 - i] = v;
format = format >> 1;
}
}
#define MASKMAKER(__exp__) \
int x, y;\
\
for(y=0; y<width; y++) {\
for(x=0; x<width; x++) {\
if(*s & 0x80) {\
*d = *s;\
} else {\
*d = *s ^ ((__exp__) == 0);\
}\
s++; d++;\
}\
}
static void Mask_mask0(int width, const unsigned char *s, unsigned char *d)
{
MASKMAKER(y&1)
}
static void Mask_mask1(int width, const unsigned char *s, unsigned char *d)
{
MASKMAKER(((y/2)+(x/3))&1)
}
static void Mask_mask2(int width, const unsigned char *s, unsigned char *d)
{
MASKMAKER((((x*y)&1)+(x*y)%3)&1)
}
static void Mask_mask3(int width, const unsigned char *s, unsigned char *d)
{
MASKMAKER((((x+y)&1)+((x*y)%3))&1)
}
#define maskNum (4)
typedef void MaskMaker(int, const unsigned char *, unsigned char *);
static MaskMaker *maskMakers[maskNum] = {
Mask_mask0, Mask_mask1, Mask_mask2, Mask_mask3
};
#ifdef WITH_TESTS
unsigned char *MMask_makeMaskedFrame(int width, unsigned char *frame, int mask)
{
unsigned char *masked;
masked = (unsigned char *)malloc(width * width);
if(masked == NULL) return NULL;
maskMakers[mask](width, frame, masked);
return masked;
}
#endif
unsigned char *MMask_makeMask(int version, unsigned char *frame, int mask, QRecLevel level)
{
unsigned char *masked;
int width;
if(mask < 0 || mask >= maskNum) {
errno = EINVAL;
return NULL;
}
width = MQRspec_getWidth(version);
masked = (unsigned char *)malloc(width * width);
if(masked == NULL) return NULL;
maskMakers[mask](width, frame, masked);
MMask_writeFormatInformation(version, width, masked, mask, level);
return masked;
}
__STATIC int MMask_evaluateSymbol(int width, unsigned char *frame)
{
int x, y;
unsigned char *p;
int sum1 = 0, sum2 = 0;
p = frame + width * (width - 1);
for(x=1; x<width; x++) {
sum1 += (p[x] & 1);
}
p = frame + width * 2 - 1;
for(y=1; y<width; y++) {
sum2 += (*p & 1);
p += width;
}
return (sum1 <= sum2)?(sum1 * 16 + sum2):(sum2 * 16 + sum1);
}
unsigned char *MMask_mask(int version, unsigned char *frame, QRecLevel level)
{
int i;
unsigned char *mask, *bestMask;
int maxScore = 0;
int score;
int width;
width = MQRspec_getWidth(version);
mask = (unsigned char *)malloc(width * width);
if(mask == NULL) return NULL;
bestMask = NULL;
for(i=0; i<maskNum; i++) {
score = 0;
maskMakers[i](width, frame, mask);
MMask_writeFormatInformation(version, width, mask, i, level);
score = MMask_evaluateSymbol(width, mask);
if(score > maxScore) {
maxScore = score;
free(bestMask);
bestMask = mask;
mask = (unsigned char *)malloc(width * width);
if(mask == NULL) break;
}
}
free(mask);
return bestMask;
}
| mit |
neeting/neeting.github.io | vendor/bundler/ruby/2.0.0/gems/ffi-1.9.8-x64-mingw32/ext/ffi_c/libffi/testsuite/libffi.call/closure_loc_fn0.c | 803 | 3096 | /* Area: closure_call
Purpose: Check multiple values passing from different type.
Also, exceed the limit of gpr and fpr registers on PowerPC
Darwin.
Limitations: none.
PR: none.
Originator: <andreast@gcc.gnu.org> 20030828 */
/* { dg-do run } */
#include "ffitest.h"
static void
closure_loc_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args,
void* userdata)
{
*(ffi_arg*)resp =
(int)*(unsigned long long *)args[0] + (int)(*(int *)args[1]) +
(int)(*(unsigned long long *)args[2]) + (int)*(int *)args[3] +
(int)(*(signed short *)args[4]) +
(int)(*(unsigned long long *)args[5]) +
(int)*(int *)args[6] + (int)(*(int *)args[7]) +
(int)(*(double *)args[8]) + (int)*(int *)args[9] +
(int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
(int)*(int *)args[12] + (int)(*(int *)args[13]) +
(int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
(int)*(unsigned long long *)args[0], (int)(*(int *)args[1]),
(int)(*(unsigned long long *)args[2]),
(int)*(int *)args[3], (int)(*(signed short *)args[4]),
(int)(*(unsigned long long *)args[5]),
(int)*(int *)args[6], (int)(*(int *)args[7]),
(int)(*(double *)args[8]), (int)*(int *)args[9],
(int)(*(int *)args[10]), (int)(*(float *)args[11]),
(int)*(int *)args[12], (int)(*(int *)args[13]),
(int)(*(int *)args[14]),*(int *)args[15],
(int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
}
typedef int (*closure_loc_test_type0)(unsigned long long, int, unsigned long long,
int, signed short, unsigned long long, int,
int, double, int, int, float, int, int,
int, int);
int main (void)
{
ffi_cif cif;
ffi_closure *pcl;
ffi_type * cl_arg_types[17];
int res;
void *codeloc;
cl_arg_types[0] = &ffi_type_uint64;
cl_arg_types[1] = &ffi_type_sint;
cl_arg_types[2] = &ffi_type_uint64;
cl_arg_types[3] = &ffi_type_sint;
cl_arg_types[4] = &ffi_type_sshort;
cl_arg_types[5] = &ffi_type_uint64;
cl_arg_types[6] = &ffi_type_sint;
cl_arg_types[7] = &ffi_type_sint;
cl_arg_types[8] = &ffi_type_double;
cl_arg_types[9] = &ffi_type_sint;
cl_arg_types[10] = &ffi_type_sint;
cl_arg_types[11] = &ffi_type_float;
cl_arg_types[12] = &ffi_type_sint;
cl_arg_types[13] = &ffi_type_sint;
cl_arg_types[14] = &ffi_type_sint;
cl_arg_types[15] = &ffi_type_sint;
cl_arg_types[16] = NULL;
/* Initialize the cif */
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
&ffi_type_sint, cl_arg_types) == FFI_OK);
pcl = ffi_closure_alloc(sizeof(ffi_closure), &codeloc);
CHECK(pcl != NULL);
CHECK(codeloc != NULL);
CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0,
(void *) 3 /* userdata */, codeloc) == FFI_OK);
CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0);
res = (*((closure_loc_test_type0)codeloc))
(1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13,
19, 21, 1);
/* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
printf("res: %d\n",res);
/* { dg-output "\nres: 680" } */
exit(0);
}
| mit |
CompendiumSoftware/beanstalkd | sd-daemon.c | 36 | 11388 | /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
Copyright 2010 Lennart Poettering
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.
***/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/fcntl.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include "sd-daemon.h"
int sd_listen_fds(int unset_environment) {
#if defined(DISABLE_SYSTEMD) || !defined(__linux__)
return 0;
#else
int r, fd;
const char *e;
char *p = NULL;
unsigned long l;
if (!(e = getenv("LISTEN_PID"))) {
r = 0;
goto finish;
}
errno = 0;
l = strtoul(e, &p, 10);
if (errno != 0) {
r = -errno;
goto finish;
}
if (!p || *p || l <= 0) {
r = -EINVAL;
goto finish;
}
/* Is this for us? */
if (getpid() != (pid_t) l) {
r = 0;
goto finish;
}
if (!(e = getenv("LISTEN_FDS"))) {
r = 0;
goto finish;
}
errno = 0;
l = strtoul(e, &p, 10);
if (errno != 0) {
r = -errno;
goto finish;
}
if (!p || *p) {
r = -EINVAL;
goto finish;
}
for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + (int) l; fd ++) {
int flags;
if ((flags = fcntl(fd, F_GETFD)) < 0) {
r = -errno;
goto finish;
}
if (flags & FD_CLOEXEC)
continue;
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
r = -errno;
goto finish;
}
}
r = (int) l;
finish:
if (unset_environment) {
unsetenv("LISTEN_PID");
unsetenv("LISTEN_FDS");
}
return r;
#endif
}
int sd_is_fifo(int fd, const char *path) {
struct stat st_fd;
if (fd < 0)
return -EINVAL;
memset(&st_fd, 0, sizeof(st_fd));
if (fstat(fd, &st_fd) < 0)
return -errno;
if (!S_ISFIFO(st_fd.st_mode))
return 0;
if (path) {
struct stat st_path;
memset(&st_path, 0, sizeof(st_path));
if (stat(path, &st_path) < 0) {
if (errno == ENOENT || errno == ENOTDIR)
return 0;
return -errno;
}
return
st_path.st_dev == st_fd.st_dev &&
st_path.st_ino == st_fd.st_ino;
}
return 1;
}
static int sd_is_socket_internal(int fd, int type, int listening) {
struct stat st_fd;
if (fd < 0 || type < 0)
return -EINVAL;
if (fstat(fd, &st_fd) < 0)
return -errno;
if (!S_ISSOCK(st_fd.st_mode))
return 0;
if (type != 0) {
int other_type = 0;
socklen_t l = sizeof(other_type);
if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &other_type, &l) < 0)
return -errno;
if (l != sizeof(other_type))
return -EINVAL;
if (other_type != type)
return 0;
}
if (listening >= 0) {
int accepting = 0;
socklen_t l = sizeof(accepting);
if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &accepting, &l) < 0)
return -errno;
if (l != sizeof(accepting))
return -EINVAL;
if (!accepting != !listening)
return 0;
}
return 1;
}
union sockaddr_union {
struct sockaddr sa;
struct sockaddr_in in4;
struct sockaddr_in6 in6;
struct sockaddr_un un;
struct sockaddr_storage storage;
};
int sd_is_socket(int fd, int family, int type, int listening) {
int r;
if (family < 0)
return -EINVAL;
if ((r = sd_is_socket_internal(fd, type, listening)) <= 0)
return r;
if (family > 0) {
union sockaddr_union sockaddr;
socklen_t l;
memset(&sockaddr, 0, sizeof(sockaddr));
l = sizeof(sockaddr);
if (getsockname(fd, &sockaddr.sa, &l) < 0)
return -errno;
if (l < sizeof(sa_family_t))
return -EINVAL;
return sockaddr.sa.sa_family == family;
}
return 1;
}
int sd_is_socket_inet(int fd, int family, int type, int listening, uint16_t port) {
union sockaddr_union sockaddr;
socklen_t l;
int r;
if (family != 0 && family != AF_INET && family != AF_INET6)
return -EINVAL;
if ((r = sd_is_socket_internal(fd, type, listening)) <= 0)
return r;
memset(&sockaddr, 0, sizeof(sockaddr));
l = sizeof(sockaddr);
if (getsockname(fd, &sockaddr.sa, &l) < 0)
return -errno;
if (l < sizeof(sa_family_t))
return -EINVAL;
if (sockaddr.sa.sa_family != AF_INET &&
sockaddr.sa.sa_family != AF_INET6)
return 0;
if (family > 0)
if (sockaddr.sa.sa_family != family)
return 0;
if (port > 0) {
if (sockaddr.sa.sa_family == AF_INET) {
if (l < sizeof(struct sockaddr_in))
return -EINVAL;
return htons(port) == sockaddr.in4.sin_port;
} else {
if (l < sizeof(struct sockaddr_in6))
return -EINVAL;
return htons(port) == sockaddr.in6.sin6_port;
}
}
return 1;
}
int sd_is_socket_unix(int fd, int type, int listening, const char *path, size_t length) {
union sockaddr_union sockaddr;
socklen_t l;
int r;
if ((r = sd_is_socket_internal(fd, type, listening)) <= 0)
return r;
memset(&sockaddr, 0, sizeof(sockaddr));
l = sizeof(sockaddr);
if (getsockname(fd, &sockaddr.sa, &l) < 0)
return -errno;
if (l < sizeof(sa_family_t))
return -EINVAL;
if (sockaddr.sa.sa_family != AF_UNIX)
return 0;
if (path) {
if (length <= 0)
length = strlen(path);
if (length <= 0)
/* Unnamed socket */
return l == sizeof(sa_family_t);
if (path[0])
/* Normal path socket */
return
(l >= sizeof(sa_family_t) + length + 1) &&
memcmp(path, sockaddr.un.sun_path, length+1) == 0;
else
/* Abstract namespace socket */
return
(l == sizeof(sa_family_t) + length) &&
memcmp(path, sockaddr.un.sun_path, length) == 0;
}
return 1;
}
int sd_notify(int unset_environment, const char *state) {
#if defined(DISABLE_SYSTEMD) || !defined(__linux__) || !defined(SOCK_CLOEXEC)
return 0;
#else
int fd = -1, r;
struct msghdr msghdr;
struct iovec iovec;
union sockaddr_union sockaddr;
const char *e;
if (!state) {
r = -EINVAL;
goto finish;
}
if (!(e = getenv("NOTIFY_SOCKET")))
return 0;
/* Must be an abstract socket, or an absolute path */
if ((e[0] != '@' && e[0] != '/') || e[1] == 0) {
r = -EINVAL;
goto finish;
}
if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
r = -errno;
goto finish;
}
memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sa.sa_family = AF_UNIX;
strncpy(sockaddr.un.sun_path, e, sizeof(sockaddr.un.sun_path));
if (sockaddr.un.sun_path[0] == '@')
sockaddr.un.sun_path[0] = 0;
memset(&iovec, 0, sizeof(iovec));
iovec.iov_base = (char*) state;
iovec.iov_len = strlen(state);
memset(&msghdr, 0, sizeof(msghdr));
msghdr.msg_name = &sockaddr;
msghdr.msg_namelen = sizeof(sa_family_t) + strlen(e);
if (msghdr.msg_namelen > sizeof(struct sockaddr_un))
msghdr.msg_namelen = sizeof(struct sockaddr_un);
msghdr.msg_iov = &iovec;
msghdr.msg_iovlen = 1;
if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
r = -errno;
goto finish;
}
r = 1;
finish:
if (unset_environment)
unsetenv("NOTIFY_SOCKET");
if (fd >= 0)
close(fd);
return r;
#endif
}
int sd_notifyf(int unset_environment, const char *format, ...) {
#if defined(DISABLE_SYSTEMD) || !defined(__linux__)
return 0;
#else
va_list ap;
char *p = NULL;
int r;
va_start(ap, format);
r = vasprintf(&p, format, ap);
va_end(ap);
if (r < 0 || !p)
return -ENOMEM;
r = sd_notify(unset_environment, p);
free(p);
return r;
#endif
}
int sd_booted(void) {
#if defined(DISABLE_SYSTEMD) || !defined(__linux__)
return 0;
#else
struct stat a, b;
/* We simply test whether the systemd cgroup hierarchy is
* mounted */
if (lstat("/sys/fs/cgroup", &a) < 0)
return 0;
if (lstat("/sys/fs/cgroup/systemd", &b) < 0)
return 0;
return a.st_dev != b.st_dev;
#endif
}
| mit |
blackdwarf/coreclr | src/ToolBox/SOS/Strike/WatchCmd.cpp | 37 | 11257 | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#include "WatchCmd.h"
#ifndef IfFailRet
#define IfFailRet(EXPR) do { Status = (EXPR); if(FAILED(Status)) { return (Status); } } while (0)
#endif
_PersistList::~_PersistList()
{
PersistWatchExpression* pCur = pHeadExpr;
while(pCur != NULL)
{
PersistWatchExpression* toDelete = pCur;
pCur = pCur->pNext;
delete toDelete;
}
}
WatchCmd::WatchCmd() :
pExpressionListHead(NULL)
{ }
WatchCmd::~WatchCmd()
{
Clear();
PersistList* pCur = pPersistListHead;
while(pCur != NULL)
{
PersistList* toDelete = pCur;
pCur = pCur->pNext;
delete toDelete;
}
}
// Deletes all current watch expressions from the watch list
// (does not delete persisted watch lists though)
HRESULT WatchCmd::Clear()
{
WatchExpression* pCurrent = pExpressionListHead;
while(pCurrent != NULL)
{
WatchExpression* toDelete = pCurrent;
pCurrent = pCurrent->pNext;
delete toDelete;
}
pExpressionListHead = NULL;
return S_OK;
}
// Adds a new expression to the active watch list
HRESULT WatchCmd::Add(__in_z WCHAR* pExpression)
{
WatchExpression* pExpr = new WatchExpression;
if(pExpr == NULL)
return E_OUTOFMEMORY;
wcsncpy_s(pExpr->pExpression, MAX_EXPRESSION, pExpression, _TRUNCATE);
pExpr->pNext = NULL;
WatchExpression** ppCurrent = &pExpressionListHead;
while(*ppCurrent != NULL)
ppCurrent = &((*ppCurrent)->pNext);
*ppCurrent = pExpr;
return S_OK;
}
// removes an expression at the given index in the active watch list
HRESULT WatchCmd::Remove(int index)
{
HRESULT Status = S_FALSE;
WatchExpression** ppCurrent = &pExpressionListHead;
for(int i=1; *ppCurrent != NULL; i++)
{
if(i == index)
{
WatchExpression* toDelete = *ppCurrent;
*ppCurrent = (*ppCurrent)->pNext;
delete toDelete;
Status = S_OK;
break;
}
ppCurrent = &((*ppCurrent)->pNext);
}
return Status;
}
// Evaluates and prints a tree version of the active watch list
// The tree will be expanded along the nodes in expansionPath
// Optionally the list is filtered to only show differences from pFilterName (the name of a persisted watch list)
HRESULT WatchCmd::Print(int expansionIndex, __in_z WCHAR* expansionPath, __in_z WCHAR* pFilterName)
{
HRESULT Status = S_OK;
if ((Status = CheckEEDll()) != S_OK)
{
EENotLoadedMessage(Status);
return Status;
}
if ((Status = LoadClrDebugDll()) != S_OK)
{
DACMessage(Status);
return Status;
}
EnableDMLHolder dmlHolder(TRUE);
IfFailRet(InitCorDebugInterface());
PersistList* pFilterList = NULL;
if(pFilterName != NULL)
{
pFilterList = pPersistListHead;
while(pFilterList != NULL)
{
if(_wcscmp(pFilterList->pName, pFilterName)==0)
break;
pFilterList = pFilterList->pNext;
}
}
PersistWatchExpression* pHeadFilterExpr = (pFilterList != NULL) ? pFilterList->pHeadExpr : NULL;
WatchExpression* pExpression = pExpressionListHead;
int index = 1;
while(pExpression != NULL)
{
ExpressionNode* pResult = NULL;
if(FAILED(Status = ExpressionNode::CreateExpressionNode(pExpression->pExpression, &pResult)))
{
ExtOut(" %d) Error: HRESULT 0x%x while evaluating expression \'%S\'", index, Status, pExpression->pExpression);
}
else
{
//check for matching absolute expression
PersistWatchExpression* pCurFilterExpr = pHeadFilterExpr;
while(pCurFilterExpr != NULL)
{
if(_wcscmp(pCurFilterExpr->pExpression, pResult->GetAbsoluteExpression())==0)
break;
pCurFilterExpr = pCurFilterExpr->pNext;
}
// check for matching persist evaluation on the matching expression
BOOL print = TRUE;
if(pCurFilterExpr != NULL)
{
WCHAR pCurPersistResult[MAX_EXPRESSION];
FormatPersistResult(pCurPersistResult, MAX_EXPRESSION, pResult);
if(_wcscmp(pCurPersistResult, pCurFilterExpr->pPersistResult)==0)
{
print = FALSE;
}
}
//expand and print
if(print)
{
if(index == expansionIndex)
pResult->Expand(expansionPath);
PrintCallbackData data;
data.index = index;
WCHAR pCommand[MAX_EXPRESSION];
swprintf_s(pCommand, MAX_EXPRESSION, L"!watch -expand %d", index);
data.pCommand = pCommand;
pResult->DFSVisit(EvalPrintCallback, (VOID*)&data);
}
delete pResult;
}
pExpression = pExpression->pNext;
index++;
}
return Status;
}
// Deletes an persisted watch list by name
HRESULT WatchCmd::RemoveList(__in_z WCHAR* pListName)
{
PersistList** ppList = &pPersistListHead;
while(*ppList != NULL)
{
if(_wcscmp((*ppList)->pName, pListName) == 0)
{
PersistList* toDelete = *ppList;
*ppList = (*ppList)->pNext;
delete toDelete;
return S_OK;
}
ppList = &((*ppList)->pNext);
}
return S_FALSE;
}
// Renames a previously saved persisted watch list
HRESULT WatchCmd::RenameList(__in_z WCHAR* pOldName, __in_z WCHAR* pNewName)
{
if(_wcscmp(pOldName, pNewName)==0)
return S_OK;
PersistList** ppList = &pPersistListHead;
while(*ppList != NULL)
{
if(_wcscmp((*ppList)->pName, pOldName) == 0)
{
PersistList* pListToChangeName = *ppList;
RemoveList(pNewName);
wcsncpy_s(pListToChangeName->pName, MAX_EXPRESSION, pNewName, _TRUNCATE);
return S_OK;
}
ppList = &((*ppList)->pNext);
}
return S_FALSE;
}
// Saves the active watch list together with the current evaluations as
// a new persisted watch list
HRESULT WatchCmd::SaveList(__in_z WCHAR* pSaveName)
{
HRESULT Status = S_OK;
IfFailRet(InitCorDebugInterface());
RemoveList(pSaveName);
PersistList* pList = new PersistList();
wcsncpy_s(pList->pName, MAX_EXPRESSION, pSaveName, _TRUNCATE);
pList->pHeadExpr = NULL;
PersistCallbackData data;
data.ppNext = &(pList->pHeadExpr);
WatchExpression* pExpression = pExpressionListHead;
while(pExpression != NULL)
{
ExpressionNode* pResult = NULL;
if(SUCCEEDED(Status = ExpressionNode::CreateExpressionNode(pExpression->pExpression, &pResult)))
{
pResult->DFSVisit(PersistCallback, (VOID*)&data);
delete pResult;
}
pExpression = pExpression->pNext;
}
pList->pNext = pPersistListHead;
pPersistListHead = pList;
return Status;
}
// Saves the current watch list to file as a sequence of commands that will
// recreate the list
HRESULT WatchCmd::SaveListToFile(FILE* pFile)
{
WatchExpression* pExpression = pExpressionListHead;
while(pExpression != NULL)
{
fprintf_s(pFile, "!watch -a %S\n", pExpression->pExpression);
pExpression = pExpression->pNext;
}
return S_OK;
}
// Escapes characters that would be interpretted as DML markup, namely angle brackets
// that often appear in generic type names
VOID WatchCmd::DmlEscape(__in_ecount(cchInput) WCHAR* pInput, int cchInput, __in_ecount(cchOutput) WCHAR* pEscapedOutput, int cchOutput)
{
pEscapedOutput[0] = L'\0';
for(int i = 0; i < cchInput; i++)
{
if(pInput[i] == L'<')
{
if(0 != wcscat_s(pEscapedOutput, cchOutput, L"<")) return;
pEscapedOutput += 4;
cchOutput -= 4;
}
else if(pInput[i] == L'>')
{
if(0 != wcscat_s(pEscapedOutput, cchOutput, L">")) return;
pEscapedOutput += 4;
cchOutput -= 4;
}
else if(cchOutput > 1)
{
pEscapedOutput[0] = pInput[i];
pEscapedOutput[1] = '\0';
pEscapedOutput++;
cchOutput--;
}
if(pInput[i] == L'\0' || cchOutput == 1) break;
}
}
// A DFS traversal callback for the expression node tree that prints it
VOID WatchCmd::EvalPrintCallback(ExpressionNode* pExpressionNode, int depth, VOID* pUserData)
{
PrintCallbackData* pData = (PrintCallbackData*)pUserData;
for(int i = 0; i < depth; i++) ExtOut(" ");
if(depth == 0)
ExtOut(" %d) ", pData->index);
else
ExtOut(" |- ");
if(pExpressionNode->GetErrorMessage()[0] != 0)
{
ExtOut("%S (%S)\n", pExpressionNode->GetRelativeExpression(), pExpressionNode->GetErrorMessage());
}
else
{
// names can have '<' and '>' in them, need to escape
WCHAR pEscapedTypeName[MAX_EXPRESSION];
DmlEscape(pExpressionNode->GetTypeName(), (int)_wcslen(pExpressionNode->GetTypeName()), pEscapedTypeName, MAX_EXPRESSION);
WCHAR pRelativeExpression[MAX_EXPRESSION];
DmlEscape(pExpressionNode->GetRelativeExpression(), (int)_wcslen(pExpressionNode->GetRelativeExpression()), pRelativeExpression, MAX_EXPRESSION);
DMLOut("%S <exec cmd=\"%S (%S)%S\">%S</exec> %S\n", pEscapedTypeName, pData->pCommand, pEscapedTypeName, pExpressionNode->GetAbsoluteExpression(), pRelativeExpression, pExpressionNode->GetTextValue());
}
}
// A DFS traversal callback for the expression node tree that saves all the values into a new
// persisted watch list
VOID WatchCmd::PersistCallback(ExpressionNode* pExpressionNode, int depth, VOID* pUserData)
{
PersistCallbackData* pData = (PersistCallbackData*)pUserData;
if(depth != 0)
return;
PersistWatchExpression* pPersistExpr = new PersistWatchExpression();
wcsncpy_s(pPersistExpr->pExpression, MAX_EXPRESSION, pExpressionNode->GetAbsoluteExpression(), _TRUNCATE);
FormatPersistResult(pPersistExpr->pPersistResult, MAX_EXPRESSION, pExpressionNode);
pPersistExpr->pNext = NULL;
*(pData->ppNext) = pPersistExpr;
pData->ppNext = &(pPersistExpr->pNext);
}
// Determines how the value of an expression node is saved as a persisted result. This effectively determines
// the definition of equality when determining if an expression has changed value
VOID WatchCmd::FormatPersistResult(__inout_ecount(cchPersistResult) WCHAR* pPersistResult, DWORD cchPersistResult, ExpressionNode* pExpressionNode)
{
if(pExpressionNode->GetErrorMessage()[0] != 0)
{
_snwprintf_s(pPersistResult, MAX_EXPRESSION, _TRUNCATE, L"%s (%s)\n", pExpressionNode->GetRelativeExpression(), pExpressionNode->GetErrorMessage());
}
else
{
_snwprintf_s(pPersistResult, MAX_EXPRESSION, _TRUNCATE, L"%s %s %s\n", pExpressionNode->GetTypeName(), pExpressionNode->GetRelativeExpression(), pExpressionNode->GetTextValue());
}
}
| mit |
someapp/spark_test_im | openssl-1.0.1e/crypto/rsa/rsa_test.c | 805 | 10894 | /* test vectors from p1ovect1.txt */
#include <stdio.h>
#include <string.h>
#include "e_os.h"
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/bn.h>
#ifdef OPENSSL_NO_RSA
int main(int argc, char *argv[])
{
printf("No RSA support\n");
return(0);
}
#else
#include <openssl/rsa.h>
#define SetKey \
key->n = BN_bin2bn(n, sizeof(n)-1, key->n); \
key->e = BN_bin2bn(e, sizeof(e)-1, key->e); \
key->d = BN_bin2bn(d, sizeof(d)-1, key->d); \
key->p = BN_bin2bn(p, sizeof(p)-1, key->p); \
key->q = BN_bin2bn(q, sizeof(q)-1, key->q); \
key->dmp1 = BN_bin2bn(dmp1, sizeof(dmp1)-1, key->dmp1); \
key->dmq1 = BN_bin2bn(dmq1, sizeof(dmq1)-1, key->dmq1); \
key->iqmp = BN_bin2bn(iqmp, sizeof(iqmp)-1, key->iqmp); \
memcpy(c, ctext_ex, sizeof(ctext_ex) - 1); \
return (sizeof(ctext_ex) - 1);
static int key1(RSA *key, unsigned char *c)
{
static unsigned char n[] =
"\x00\xAA\x36\xAB\xCE\x88\xAC\xFD\xFF\x55\x52\x3C\x7F\xC4\x52\x3F"
"\x90\xEF\xA0\x0D\xF3\x77\x4A\x25\x9F\x2E\x62\xB4\xC5\xD9\x9C\xB5"
"\xAD\xB3\x00\xA0\x28\x5E\x53\x01\x93\x0E\x0C\x70\xFB\x68\x76\x93"
"\x9C\xE6\x16\xCE\x62\x4A\x11\xE0\x08\x6D\x34\x1E\xBC\xAC\xA0\xA1"
"\xF5";
static unsigned char e[] = "\x11";
static unsigned char d[] =
"\x0A\x03\x37\x48\x62\x64\x87\x69\x5F\x5F\x30\xBC\x38\xB9\x8B\x44"
"\xC2\xCD\x2D\xFF\x43\x40\x98\xCD\x20\xD8\xA1\x38\xD0\x90\xBF\x64"
"\x79\x7C\x3F\xA7\xA2\xCD\xCB\x3C\xD1\xE0\xBD\xBA\x26\x54\xB4\xF9"
"\xDF\x8E\x8A\xE5\x9D\x73\x3D\x9F\x33\xB3\x01\x62\x4A\xFD\x1D\x51";
static unsigned char p[] =
"\x00\xD8\x40\xB4\x16\x66\xB4\x2E\x92\xEA\x0D\xA3\xB4\x32\x04\xB5"
"\xCF\xCE\x33\x52\x52\x4D\x04\x16\xA5\xA4\x41\xE7\x00\xAF\x46\x12"
"\x0D";
static unsigned char q[] =
"\x00\xC9\x7F\xB1\xF0\x27\xF4\x53\xF6\x34\x12\x33\xEA\xAA\xD1\xD9"
"\x35\x3F\x6C\x42\xD0\x88\x66\xB1\xD0\x5A\x0F\x20\x35\x02\x8B\x9D"
"\x89";
static unsigned char dmp1[] =
"\x59\x0B\x95\x72\xA2\xC2\xA9\xC4\x06\x05\x9D\xC2\xAB\x2F\x1D\xAF"
"\xEB\x7E\x8B\x4F\x10\xA7\x54\x9E\x8E\xED\xF5\xB4\xFC\xE0\x9E\x05";
static unsigned char dmq1[] =
"\x00\x8E\x3C\x05\x21\xFE\x15\xE0\xEA\x06\xA3\x6F\xF0\xF1\x0C\x99"
"\x52\xC3\x5B\x7A\x75\x14\xFD\x32\x38\xB8\x0A\xAD\x52\x98\x62\x8D"
"\x51";
static unsigned char iqmp[] =
"\x36\x3F\xF7\x18\x9D\xA8\xE9\x0B\x1D\x34\x1F\x71\xD0\x9B\x76\xA8"
"\xA9\x43\xE1\x1D\x10\xB2\x4D\x24\x9F\x2D\xEA\xFE\xF8\x0C\x18\x26";
static unsigned char ctext_ex[] =
"\x1b\x8f\x05\xf9\xca\x1a\x79\x52\x6e\x53\xf3\xcc\x51\x4f\xdb\x89"
"\x2b\xfb\x91\x93\x23\x1e\x78\xb9\x92\xe6\x8d\x50\xa4\x80\xcb\x52"
"\x33\x89\x5c\x74\x95\x8d\x5d\x02\xab\x8c\x0f\xd0\x40\xeb\x58\x44"
"\xb0\x05\xc3\x9e\xd8\x27\x4a\x9d\xbf\xa8\x06\x71\x40\x94\x39\xd2";
SetKey;
}
static int key2(RSA *key, unsigned char *c)
{
static unsigned char n[] =
"\x00\xA3\x07\x9A\x90\xDF\x0D\xFD\x72\xAC\x09\x0C\xCC\x2A\x78\xB8"
"\x74\x13\x13\x3E\x40\x75\x9C\x98\xFA\xF8\x20\x4F\x35\x8A\x0B\x26"
"\x3C\x67\x70\xE7\x83\xA9\x3B\x69\x71\xB7\x37\x79\xD2\x71\x7B\xE8"
"\x34\x77\xCF";
static unsigned char e[] = "\x3";
static unsigned char d[] =
"\x6C\xAF\xBC\x60\x94\xB3\xFE\x4C\x72\xB0\xB3\x32\xC6\xFB\x25\xA2"
"\xB7\x62\x29\x80\x4E\x68\x65\xFC\xA4\x5A\x74\xDF\x0F\x8F\xB8\x41"
"\x3B\x52\xC0\xD0\xE5\x3D\x9B\x59\x0F\xF1\x9B\xE7\x9F\x49\xDD\x21"
"\xE5\xEB";
static unsigned char p[] =
"\x00\xCF\x20\x35\x02\x8B\x9D\x86\x98\x40\xB4\x16\x66\xB4\x2E\x92"
"\xEA\x0D\xA3\xB4\x32\x04\xB5\xCF\xCE\x91";
static unsigned char q[] =
"\x00\xC9\x7F\xB1\xF0\x27\xF4\x53\xF6\x34\x12\x33\xEA\xAA\xD1\xD9"
"\x35\x3F\x6C\x42\xD0\x88\x66\xB1\xD0\x5F";
static unsigned char dmp1[] =
"\x00\x8A\x15\x78\xAC\x5D\x13\xAF\x10\x2B\x22\xB9\x99\xCD\x74\x61"
"\xF1\x5E\x6D\x22\xCC\x03\x23\xDF\xDF\x0B";
static unsigned char dmq1[] =
"\x00\x86\x55\x21\x4A\xC5\x4D\x8D\x4E\xCD\x61\x77\xF1\xC7\x36\x90"
"\xCE\x2A\x48\x2C\x8B\x05\x99\xCB\xE0\x3F";
static unsigned char iqmp[] =
"\x00\x83\xEF\xEF\xB8\xA9\xA4\x0D\x1D\xB6\xED\x98\xAD\x84\xED\x13"
"\x35\xDC\xC1\x08\xF3\x22\xD0\x57\xCF\x8D";
static unsigned char ctext_ex[] =
"\x14\xbd\xdd\x28\xc9\x83\x35\x19\x23\x80\xe8\xe5\x49\xb1\x58\x2a"
"\x8b\x40\xb4\x48\x6d\x03\xa6\xa5\x31\x1f\x1f\xd5\xf0\xa1\x80\xe4"
"\x17\x53\x03\x29\xa9\x34\x90\x74\xb1\x52\x13\x54\x29\x08\x24\x52"
"\x62\x51";
SetKey;
}
static int key3(RSA *key, unsigned char *c)
{
static unsigned char n[] =
"\x00\xBB\xF8\x2F\x09\x06\x82\xCE\x9C\x23\x38\xAC\x2B\x9D\xA8\x71"
"\xF7\x36\x8D\x07\xEE\xD4\x10\x43\xA4\x40\xD6\xB6\xF0\x74\x54\xF5"
"\x1F\xB8\xDF\xBA\xAF\x03\x5C\x02\xAB\x61\xEA\x48\xCE\xEB\x6F\xCD"
"\x48\x76\xED\x52\x0D\x60\xE1\xEC\x46\x19\x71\x9D\x8A\x5B\x8B\x80"
"\x7F\xAF\xB8\xE0\xA3\xDF\xC7\x37\x72\x3E\xE6\xB4\xB7\xD9\x3A\x25"
"\x84\xEE\x6A\x64\x9D\x06\x09\x53\x74\x88\x34\xB2\x45\x45\x98\x39"
"\x4E\xE0\xAA\xB1\x2D\x7B\x61\xA5\x1F\x52\x7A\x9A\x41\xF6\xC1\x68"
"\x7F\xE2\x53\x72\x98\xCA\x2A\x8F\x59\x46\xF8\xE5\xFD\x09\x1D\xBD"
"\xCB";
static unsigned char e[] = "\x11";
static unsigned char d[] =
"\x00\xA5\xDA\xFC\x53\x41\xFA\xF2\x89\xC4\xB9\x88\xDB\x30\xC1\xCD"
"\xF8\x3F\x31\x25\x1E\x06\x68\xB4\x27\x84\x81\x38\x01\x57\x96\x41"
"\xB2\x94\x10\xB3\xC7\x99\x8D\x6B\xC4\x65\x74\x5E\x5C\x39\x26\x69"
"\xD6\x87\x0D\xA2\xC0\x82\xA9\x39\xE3\x7F\xDC\xB8\x2E\xC9\x3E\xDA"
"\xC9\x7F\xF3\xAD\x59\x50\xAC\xCF\xBC\x11\x1C\x76\xF1\xA9\x52\x94"
"\x44\xE5\x6A\xAF\x68\xC5\x6C\x09\x2C\xD3\x8D\xC3\xBE\xF5\xD2\x0A"
"\x93\x99\x26\xED\x4F\x74\xA1\x3E\xDD\xFB\xE1\xA1\xCE\xCC\x48\x94"
"\xAF\x94\x28\xC2\xB7\xB8\x88\x3F\xE4\x46\x3A\x4B\xC8\x5B\x1C\xB3"
"\xC1";
static unsigned char p[] =
"\x00\xEE\xCF\xAE\x81\xB1\xB9\xB3\xC9\x08\x81\x0B\x10\xA1\xB5\x60"
"\x01\x99\xEB\x9F\x44\xAE\xF4\xFD\xA4\x93\xB8\x1A\x9E\x3D\x84\xF6"
"\x32\x12\x4E\xF0\x23\x6E\x5D\x1E\x3B\x7E\x28\xFA\xE7\xAA\x04\x0A"
"\x2D\x5B\x25\x21\x76\x45\x9D\x1F\x39\x75\x41\xBA\x2A\x58\xFB\x65"
"\x99";
static unsigned char q[] =
"\x00\xC9\x7F\xB1\xF0\x27\xF4\x53\xF6\x34\x12\x33\xEA\xAA\xD1\xD9"
"\x35\x3F\x6C\x42\xD0\x88\x66\xB1\xD0\x5A\x0F\x20\x35\x02\x8B\x9D"
"\x86\x98\x40\xB4\x16\x66\xB4\x2E\x92\xEA\x0D\xA3\xB4\x32\x04\xB5"
"\xCF\xCE\x33\x52\x52\x4D\x04\x16\xA5\xA4\x41\xE7\x00\xAF\x46\x15"
"\x03";
static unsigned char dmp1[] =
"\x54\x49\x4C\xA6\x3E\xBA\x03\x37\xE4\xE2\x40\x23\xFC\xD6\x9A\x5A"
"\xEB\x07\xDD\xDC\x01\x83\xA4\xD0\xAC\x9B\x54\xB0\x51\xF2\xB1\x3E"
"\xD9\x49\x09\x75\xEA\xB7\x74\x14\xFF\x59\xC1\xF7\x69\x2E\x9A\x2E"
"\x20\x2B\x38\xFC\x91\x0A\x47\x41\x74\xAD\xC9\x3C\x1F\x67\xC9\x81";
static unsigned char dmq1[] =
"\x47\x1E\x02\x90\xFF\x0A\xF0\x75\x03\x51\xB7\xF8\x78\x86\x4C\xA9"
"\x61\xAD\xBD\x3A\x8A\x7E\x99\x1C\x5C\x05\x56\xA9\x4C\x31\x46\xA7"
"\xF9\x80\x3F\x8F\x6F\x8A\xE3\x42\xE9\x31\xFD\x8A\xE4\x7A\x22\x0D"
"\x1B\x99\xA4\x95\x84\x98\x07\xFE\x39\xF9\x24\x5A\x98\x36\xDA\x3D";
static unsigned char iqmp[] =
"\x00\xB0\x6C\x4F\xDA\xBB\x63\x01\x19\x8D\x26\x5B\xDB\xAE\x94\x23"
"\xB3\x80\xF2\x71\xF7\x34\x53\x88\x50\x93\x07\x7F\xCD\x39\xE2\x11"
"\x9F\xC9\x86\x32\x15\x4F\x58\x83\xB1\x67\xA9\x67\xBF\x40\x2B\x4E"
"\x9E\x2E\x0F\x96\x56\xE6\x98\xEA\x36\x66\xED\xFB\x25\x79\x80\x39"
"\xF7";
static unsigned char ctext_ex[] =
"\xb8\x24\x6b\x56\xa6\xed\x58\x81\xae\xb5\x85\xd9\xa2\x5b\x2a\xd7"
"\x90\xc4\x17\xe0\x80\x68\x1b\xf1\xac\x2b\xc3\xde\xb6\x9d\x8b\xce"
"\xf0\xc4\x36\x6f\xec\x40\x0a\xf0\x52\xa7\x2e\x9b\x0e\xff\xb5\xb3"
"\xf2\xf1\x92\xdb\xea\xca\x03\xc1\x27\x40\x05\x71\x13\xbf\x1f\x06"
"\x69\xac\x22\xe9\xf3\xa7\x85\x2e\x3c\x15\xd9\x13\xca\xb0\xb8\x86"
"\x3a\x95\xc9\x92\x94\xce\x86\x74\x21\x49\x54\x61\x03\x46\xf4\xd4"
"\x74\xb2\x6f\x7c\x48\xb4\x2e\xe6\x8e\x1f\x57\x2a\x1f\xc4\x02\x6a"
"\xc4\x56\xb4\xf5\x9f\x7b\x62\x1e\xa1\xb9\xd8\x8f\x64\x20\x2f\xb1";
SetKey;
}
static int pad_unknown(void)
{
unsigned long l;
while ((l = ERR_get_error()) != 0)
if (ERR_GET_REASON(l) == RSA_R_UNKNOWN_PADDING_TYPE)
return(1);
return(0);
}
static const char rnd_seed[] = "string to make the random number generator think it has entropy";
int main(int argc, char *argv[])
{
int err=0;
int v;
RSA *key;
unsigned char ptext[256];
unsigned char ctext[256];
static unsigned char ptext_ex[] = "\x54\x85\x9b\x34\x2c\x49\xea\x2a";
unsigned char ctext_ex[256];
int plen;
int clen = 0;
int num;
int n;
CRYPTO_malloc_debug_init();
CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
RAND_seed(rnd_seed, sizeof rnd_seed); /* or OAEP may fail */
plen = sizeof(ptext_ex) - 1;
for (v = 0; v < 6; v++)
{
key = RSA_new();
switch (v%3) {
case 0:
clen = key1(key, ctext_ex);
break;
case 1:
clen = key2(key, ctext_ex);
break;
case 2:
clen = key3(key, ctext_ex);
break;
}
if (v/3 >= 1) key->flags |= RSA_FLAG_NO_CONSTTIME;
num = RSA_public_encrypt(plen, ptext_ex, ctext, key,
RSA_PKCS1_PADDING);
if (num != clen)
{
printf("PKCS#1 v1.5 encryption failed!\n");
err=1;
goto oaep;
}
num = RSA_private_decrypt(num, ctext, ptext, key,
RSA_PKCS1_PADDING);
if (num != plen || memcmp(ptext, ptext_ex, num) != 0)
{
printf("PKCS#1 v1.5 decryption failed!\n");
err=1;
}
else
printf("PKCS #1 v1.5 encryption/decryption ok\n");
oaep:
ERR_clear_error();
num = RSA_public_encrypt(plen, ptext_ex, ctext, key,
RSA_PKCS1_OAEP_PADDING);
if (num == -1 && pad_unknown())
{
printf("No OAEP support\n");
goto next;
}
if (num != clen)
{
printf("OAEP encryption failed!\n");
err=1;
goto next;
}
num = RSA_private_decrypt(num, ctext, ptext, key,
RSA_PKCS1_OAEP_PADDING);
if (num != plen || memcmp(ptext, ptext_ex, num) != 0)
{
printf("OAEP decryption (encrypted data) failed!\n");
err=1;
}
else if (memcmp(ctext, ctext_ex, num) == 0)
printf("OAEP test vector %d passed!\n", v);
/* Different ciphertexts (rsa_oaep.c without -DPKCS_TESTVECT).
Try decrypting ctext_ex */
num = RSA_private_decrypt(clen, ctext_ex, ptext, key,
RSA_PKCS1_OAEP_PADDING);
if (num != plen || memcmp(ptext, ptext_ex, num) != 0)
{
printf("OAEP decryption (test vector data) failed!\n");
err=1;
}
else
printf("OAEP encryption/decryption ok\n");
/* Try decrypting corrupted ciphertexts */
for(n = 0 ; n < clen ; ++n)
{
int b;
unsigned char saved = ctext[n];
for(b = 0 ; b < 256 ; ++b)
{
if(b == saved)
continue;
ctext[n] = b;
num = RSA_private_decrypt(num, ctext, ptext, key,
RSA_PKCS1_OAEP_PADDING);
if(num > 0)
{
printf("Corrupt data decrypted!\n");
err = 1;
}
}
}
next:
RSA_free(key);
}
CRYPTO_cleanup_all_ex_data();
ERR_remove_thread_state(NULL);
CRYPTO_mem_leaks_fp(stderr);
#ifdef OPENSSL_SYS_NETWARE
if (err) printf("ERROR: %d\n", err);
#endif
return err;
}
#endif
| mit |
youprofit/godot | scene/3d/physics_joint.cpp | 39 | 50831 | /*************************************************************************/
/* physics_joint.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/*************************************************************************/
#include "physics_joint.h"
void Joint::_update_joint(bool p_only_free) {
if (joint.is_valid()) {
if (ba.is_valid() && bb.is_valid())
PhysicsServer::get_singleton()->body_remove_collision_exception(ba,bb);
PhysicsServer::get_singleton()->free(joint);
joint=RID();
ba=RID();
bb=RID();
}
if (p_only_free || !is_inside_tree())
return;
Node *node_a = has_node( get_node_a() ) ? get_node( get_node_a() ) : (Node*)NULL;
Node *node_b = has_node( get_node_b() ) ? get_node( get_node_b() ) : (Node*)NULL;
if (!node_a && !node_b)
return;
PhysicsBody *body_a=node_a ? node_a->cast_to<PhysicsBody>() : (PhysicsBody*)NULL;
PhysicsBody *body_b=node_b ? node_b->cast_to<PhysicsBody>() : (PhysicsBody*)NULL;
if (!body_a && !body_b)
return;
if (!body_a) {
SWAP(body_a,body_b);
} else if (body_b) {
//add a collision exception between both
PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid());
}
joint = _configure_joint(body_a,body_b);
if (joint.is_valid())
PhysicsServer::get_singleton()->joint_set_solver_priority(joint,solver_priority);
if (body_b && joint.is_valid()) {
ba=body_a->get_rid();
bb=body_b->get_rid();
PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid());
}
}
void Joint::set_node_a(const NodePath& p_node_a) {
if (a==p_node_a)
return;
a=p_node_a;
_update_joint();
}
NodePath Joint::get_node_a() const{
return a;
}
void Joint::set_node_b(const NodePath& p_node_b){
if (b==p_node_b)
return;
b=p_node_b;
_update_joint();
}
NodePath Joint::get_node_b() const{
return b;
}
void Joint::set_solver_priority(int p_priority) {
solver_priority=p_priority;
if (joint.is_valid())
PhysicsServer::get_singleton()->joint_set_solver_priority(joint,solver_priority);
}
int Joint::get_solver_priority() const {
return solver_priority;
}
void Joint::_notification(int p_what) {
switch(p_what) {
case NOTIFICATION_READY: {
_update_joint();
} break;
case NOTIFICATION_EXIT_TREE: {
if (joint.is_valid()) {
_update_joint(true);
PhysicsServer::get_singleton()->free(joint);
joint=RID();
}
} break;
}
}
void Joint::_bind_methods() {
ObjectTypeDB::bind_method( _MD("set_node_a","node"), &Joint::set_node_a );
ObjectTypeDB::bind_method( _MD("get_node_a"), &Joint::get_node_a );
ObjectTypeDB::bind_method( _MD("set_node_b","node"), &Joint::set_node_b );
ObjectTypeDB::bind_method( _MD("get_node_b"), &Joint::get_node_b );
ObjectTypeDB::bind_method( _MD("set_solver_priority","priority"), &Joint::set_solver_priority );
ObjectTypeDB::bind_method( _MD("get_solver_priority"), &Joint::get_solver_priority );
ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "nodes/node_a"), _SCS("set_node_a"),_SCS("get_node_a") );
ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "nodes/node_b"), _SCS("set_node_b"),_SCS("get_node_b") );
ADD_PROPERTY( PropertyInfo( Variant::INT, "solver/priority",PROPERTY_HINT_RANGE,"1,8,1"), _SCS("set_solver_priority"),_SCS("get_solver_priority") );
}
Joint::Joint() {
solver_priority=1;
}
///////////////////////////////////
void PinJoint::_bind_methods() {
ObjectTypeDB::bind_method(_MD("set_param","param","value"),&PinJoint::set_param);
ObjectTypeDB::bind_method(_MD("get_param","param"),&PinJoint::get_param);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/bias",PROPERTY_HINT_RANGE,"0.01,0.99,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_BIAS );
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/damping",PROPERTY_HINT_RANGE,"0.01,8.0,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_DAMPING );
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/impulse_clamp",PROPERTY_HINT_RANGE,"0.0,64.0,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_IMPULSE_CLAMP );
BIND_CONSTANT( PARAM_BIAS );
BIND_CONSTANT( PARAM_DAMPING );
BIND_CONSTANT( PARAM_IMPULSE_CLAMP );
}
void PinJoint::set_param(Param p_param,float p_value){
ERR_FAIL_INDEX(p_param,3);
params[p_param]=p_value;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->pin_joint_set_param(get_joint(),PhysicsServer::PinJointParam(p_param),p_value);
}
float PinJoint::get_param(Param p_param) const{
ERR_FAIL_INDEX_V(p_param,3,0);
return params[p_param];
}
RID PinJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
Vector3 pinpos = get_global_transform().origin;
Vector3 local_a = body_a->get_global_transform().affine_inverse().xform(pinpos);
Vector3 local_b;
if (body_b)
local_b = body_b->get_global_transform().affine_inverse().xform(pinpos);
else
local_b=pinpos;
RID j = PhysicsServer::get_singleton()->joint_create_pin(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b);
for(int i=0;i<3;i++) {
PhysicsServer::get_singleton()->pin_joint_set_param(j,PhysicsServer::PinJointParam(i),params[i]);
}
return j;
}
PinJoint::PinJoint() {
params[PARAM_BIAS]=0.3;
params[PARAM_DAMPING]=1;
params[PARAM_IMPULSE_CLAMP]=0;
}
/////////////////////////////////////////////////
///////////////////////////////////
void HingeJoint::_set_upper_limit(float p_limit) {
set_param(PARAM_LIMIT_UPPER,Math::deg2rad(p_limit));
}
float HingeJoint::_get_upper_limit() const {
return Math::rad2deg(get_param(PARAM_LIMIT_UPPER));
}
void HingeJoint::_set_lower_limit(float p_limit) {
set_param(PARAM_LIMIT_LOWER,Math::deg2rad(p_limit));
}
float HingeJoint::_get_lower_limit() const {
return Math::rad2deg(get_param(PARAM_LIMIT_LOWER));
}
void HingeJoint::_bind_methods() {
ObjectTypeDB::bind_method(_MD("set_param","param","value"),&HingeJoint::set_param);
ObjectTypeDB::bind_method(_MD("get_param","param"),&HingeJoint::get_param);
ObjectTypeDB::bind_method(_MD("set_flag","flag","enabled"),&HingeJoint::set_flag);
ObjectTypeDB::bind_method(_MD("get_flag","flag"),&HingeJoint::get_flag);
ObjectTypeDB::bind_method(_MD("_set_upper_limit","upper_limit"),&HingeJoint::_set_upper_limit);
ObjectTypeDB::bind_method(_MD("_get_upper_limit"),&HingeJoint::_get_upper_limit);
ObjectTypeDB::bind_method(_MD("_set_lower_limit","lower_limit"),&HingeJoint::_set_lower_limit);
ObjectTypeDB::bind_method(_MD("_get_lower_limit"),&HingeJoint::_get_lower_limit);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/bias",PROPERTY_HINT_RANGE,"0.01,0.99,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_BIAS );
ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"angular_limit/enable"),_SCS("set_flag"),_SCS("get_flag"), FLAG_USE_LIMIT );
ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/upper",PROPERTY_HINT_RANGE,"-180,180,0.1"),_SCS("_set_upper_limit"),_SCS("_get_upper_limit") );
ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/lower",PROPERTY_HINT_RANGE,"-180,180,0.1"),_SCS("_set_lower_limit"),_SCS("_get_lower_limit") );
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/bias",PROPERTY_HINT_RANGE,"0.01,0.99,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_LIMIT_BIAS );
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_LIMIT_SOFTNESS );
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/relaxation",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_LIMIT_RELAXATION );
ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"motor/enable"),_SCS("set_flag"),_SCS("get_flag"), FLAG_ENABLE_MOTOR );
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"motor/target_velocity",PROPERTY_HINT_RANGE,"0.01,4096,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_MOTOR_TARGET_VELOCITY );
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"motor/max_impulse",PROPERTY_HINT_RANGE,"0.01,1024,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_MOTOR_MAX_IMPULSE);
BIND_CONSTANT( PARAM_BIAS );
BIND_CONSTANT( PARAM_LIMIT_UPPER );
BIND_CONSTANT( PARAM_LIMIT_LOWER );
BIND_CONSTANT( PARAM_LIMIT_BIAS );
BIND_CONSTANT( PARAM_LIMIT_SOFTNESS );
BIND_CONSTANT( PARAM_LIMIT_RELAXATION );
BIND_CONSTANT( PARAM_MOTOR_TARGET_VELOCITY );
BIND_CONSTANT( PARAM_MOTOR_MAX_IMPULSE );
BIND_CONSTANT( PARAM_MAX );
BIND_CONSTANT( FLAG_USE_LIMIT );
BIND_CONSTANT( FLAG_ENABLE_MOTOR );
BIND_CONSTANT( FLAG_MAX );
}
void HingeJoint::set_param(Param p_param,float p_value){
ERR_FAIL_INDEX(p_param,PARAM_MAX);
params[p_param]=p_value;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->hinge_joint_set_param(get_joint(),PhysicsServer::HingeJointParam(p_param),p_value);
update_gizmo();
}
float HingeJoint::get_param(Param p_param) const{
ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
return params[p_param];
}
void HingeJoint::set_flag(Flag p_flag,bool p_value){
ERR_FAIL_INDEX(p_flag,FLAG_MAX);
flags[p_flag]=p_value;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->hinge_joint_set_flag(get_joint(),PhysicsServer::HingeJointFlag(p_flag),p_value);
update_gizmo();
}
bool HingeJoint::get_flag(Flag p_flag) const{
ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
return flags[p_flag];
}
RID HingeJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
Transform gt = get_global_transform();
Vector3 hingepos = gt.origin;
Vector3 hingedir = gt.basis.get_axis(2);
Transform ainv = body_a->get_global_transform().affine_inverse();
Transform local_a = ainv * gt;
local_a.orthonormalize();
Transform local_b = gt;
if (body_b) {
Transform binv = body_b->get_global_transform().affine_inverse();
local_b = binv * gt;
}
local_b.orthonormalize();
RID j = PhysicsServer::get_singleton()->joint_create_hinge(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b);
for(int i=0;i<PARAM_MAX;i++) {
PhysicsServer::get_singleton()->hinge_joint_set_param(j,PhysicsServer::HingeJointParam(i),params[i]);
}
for(int i=0;i<FLAG_MAX;i++) {
set_flag(Flag(i),flags[i]);
PhysicsServer::get_singleton()->hinge_joint_set_flag(j,PhysicsServer::HingeJointFlag(i),flags[i]);
}
return j;
}
HingeJoint::HingeJoint() {
params[PARAM_BIAS]=0.3;
params[PARAM_LIMIT_UPPER]=Math_PI*0.5;
params[PARAM_LIMIT_LOWER]=-Math_PI*0.5;
params[PARAM_LIMIT_BIAS]=0.3;
params[PARAM_LIMIT_SOFTNESS]=0.9;
params[PARAM_LIMIT_RELAXATION]=1.0;
params[PARAM_MOTOR_TARGET_VELOCITY]=1;
params[PARAM_MOTOR_MAX_IMPULSE]=1;
flags[FLAG_USE_LIMIT]=false;
flags[FLAG_ENABLE_MOTOR]=false;
}
/////////////////////////////////////////////////
//////////////////////////////////
void SliderJoint::_set_upper_limit_angular(float p_limit_angular) {
set_param(PARAM_ANGULAR_LIMIT_UPPER,Math::deg2rad(p_limit_angular));
}
float SliderJoint::_get_upper_limit_angular() const {
return Math::rad2deg(get_param(PARAM_ANGULAR_LIMIT_UPPER));
}
void SliderJoint::_set_lower_limit_angular(float p_limit_angular) {
set_param(PARAM_ANGULAR_LIMIT_LOWER,Math::deg2rad(p_limit_angular));
}
float SliderJoint::_get_lower_limit_angular() const {
return Math::rad2deg(get_param(PARAM_ANGULAR_LIMIT_LOWER));
}
void SliderJoint::_bind_methods() {
ObjectTypeDB::bind_method(_MD("set_param","param","value"),&SliderJoint::set_param);
ObjectTypeDB::bind_method(_MD("get_param","param"),&SliderJoint::get_param);
ObjectTypeDB::bind_method(_MD("_set_upper_limit_angular","upper_limit_angular"),&SliderJoint::_set_upper_limit_angular);
ObjectTypeDB::bind_method(_MD("_get_upper_limit_angular"),&SliderJoint::_get_upper_limit_angular);
ObjectTypeDB::bind_method(_MD("_set_lower_limit_angular","lower_limit_angular"),&SliderJoint::_set_lower_limit_angular);
ObjectTypeDB::bind_method(_MD("_get_lower_limit_angular"),&SliderJoint::_get_lower_limit_angular);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/upper_distance",PROPERTY_HINT_RANGE,"-1024,1024,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_LIMIT_UPPER);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/lower_distance",PROPERTY_HINT_RANGE,"-1024,1024,0.01"),_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_LIMIT_LOWER);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_LIMIT_SOFTNESS);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_LIMIT_RESTITUTION);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_LIMIT_DAMPING);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_motion/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_MOTION_SOFTNESS);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_motion/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_MOTION_RESTITUTION);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_motion/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_MOTION_DAMPING);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_ortho/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_ORTHOGONAL_SOFTNESS);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_ortho/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_ORTHOGONAL_RESTITUTION);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_ortho/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_LINEAR_ORTHOGONAL_DAMPING);
ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.1"),_SCS("_set_upper_limit_angular"),_SCS("_get_upper_limit_angular") );
ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.1"),_SCS("_set_lower_limit_angular"),_SCS("_get_lower_limit_angular") );
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_ANGULAR_LIMIT_SOFTNESS);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_ANGULAR_LIMIT_RESTITUTION);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_ANGULAR_LIMIT_DAMPING);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_motion/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_ANGULAR_MOTION_SOFTNESS);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_motion/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_ANGULAR_MOTION_RESTITUTION);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_motion/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_ANGULAR_MOTION_DAMPING);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_ortho/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_ANGULAR_ORTHOGONAL_SOFTNESS);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_ortho/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_ANGULAR_ORTHOGONAL_RESTITUTION);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_ortho/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_ANGULAR_ORTHOGONAL_DAMPING);
BIND_CONSTANT( PARAM_LINEAR_LIMIT_UPPER);
BIND_CONSTANT( PARAM_LINEAR_LIMIT_LOWER);
BIND_CONSTANT( PARAM_LINEAR_LIMIT_SOFTNESS);
BIND_CONSTANT( PARAM_LINEAR_LIMIT_RESTITUTION);
BIND_CONSTANT( PARAM_LINEAR_LIMIT_DAMPING);
BIND_CONSTANT( PARAM_LINEAR_MOTION_SOFTNESS);
BIND_CONSTANT( PARAM_LINEAR_MOTION_RESTITUTION);
BIND_CONSTANT( PARAM_LINEAR_MOTION_DAMPING);
BIND_CONSTANT( PARAM_LINEAR_ORTHOGONAL_SOFTNESS);
BIND_CONSTANT( PARAM_LINEAR_ORTHOGONAL_RESTITUTION);
BIND_CONSTANT( PARAM_LINEAR_ORTHOGONAL_DAMPING);
BIND_CONSTANT( PARAM_ANGULAR_LIMIT_UPPER);
BIND_CONSTANT( PARAM_ANGULAR_LIMIT_LOWER);
BIND_CONSTANT( PARAM_ANGULAR_LIMIT_SOFTNESS);
BIND_CONSTANT( PARAM_ANGULAR_LIMIT_RESTITUTION);
BIND_CONSTANT( PARAM_ANGULAR_LIMIT_DAMPING);
BIND_CONSTANT( PARAM_ANGULAR_MOTION_SOFTNESS);
BIND_CONSTANT( PARAM_ANGULAR_MOTION_RESTITUTION);
BIND_CONSTANT( PARAM_ANGULAR_MOTION_DAMPING);
BIND_CONSTANT( PARAM_ANGULAR_ORTHOGONAL_SOFTNESS);
BIND_CONSTANT( PARAM_ANGULAR_ORTHOGONAL_RESTITUTION);
BIND_CONSTANT( PARAM_ANGULAR_ORTHOGONAL_DAMPING);
BIND_CONSTANT( PARAM_MAX);
}
void SliderJoint::set_param(Param p_param,float p_value){
ERR_FAIL_INDEX(p_param,PARAM_MAX);
params[p_param]=p_value;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->slider_joint_set_param(get_joint(),PhysicsServer::SliderJointParam(p_param),p_value);
update_gizmo();
}
float SliderJoint::get_param(Param p_param) const{
ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
return params[p_param];
}
RID SliderJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
Transform gt = get_global_transform();
Vector3 sliderpos = gt.origin;
Vector3 sliderdir = gt.basis.get_axis(2);
Transform ainv = body_a->get_global_transform().affine_inverse();
Transform local_a = ainv * gt;
local_a.orthonormalize();
Transform local_b = gt;
if (body_b) {
Transform binv = body_b->get_global_transform().affine_inverse();
local_b = binv * gt;
}
local_b.orthonormalize();
RID j = PhysicsServer::get_singleton()->joint_create_slider(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b);
for(int i=0;i<PARAM_MAX;i++) {
PhysicsServer::get_singleton()->slider_joint_set_param(j,PhysicsServer::SliderJointParam(i),params[i]);
}
return j;
}
SliderJoint::SliderJoint() {
params[ PARAM_LINEAR_LIMIT_UPPER ]=1.0;
params[ PARAM_LINEAR_LIMIT_LOWER ]=-1.0;
params[ PARAM_LINEAR_LIMIT_SOFTNESS ]=1.0;
params[ PARAM_LINEAR_LIMIT_RESTITUTION]=0.7;
params[ PARAM_LINEAR_LIMIT_DAMPING]=1.0;
params[ PARAM_LINEAR_MOTION_SOFTNESS ]=1.0;
params[ PARAM_LINEAR_MOTION_RESTITUTION]=0.7;
params[ PARAM_LINEAR_MOTION_DAMPING]=0;//1.0;
params[ PARAM_LINEAR_ORTHOGONAL_SOFTNESS ]=1.0;
params[ PARAM_LINEAR_ORTHOGONAL_RESTITUTION]=0.7;
params[ PARAM_LINEAR_ORTHOGONAL_DAMPING]=1.0;
params[ PARAM_ANGULAR_LIMIT_UPPER ]=0 ;
params[ PARAM_ANGULAR_LIMIT_LOWER ]=0 ;
params[ PARAM_ANGULAR_LIMIT_SOFTNESS ]=1.0;
params[ PARAM_ANGULAR_LIMIT_RESTITUTION]=0.7;
params[ PARAM_ANGULAR_LIMIT_DAMPING]=0;//1.0;
params[ PARAM_ANGULAR_MOTION_SOFTNESS ]=1.0;
params[ PARAM_ANGULAR_MOTION_RESTITUTION]=0.7;
params[ PARAM_ANGULAR_MOTION_DAMPING]=1.0;
params[ PARAM_ANGULAR_ORTHOGONAL_SOFTNESS ]=1.0;
params[ PARAM_ANGULAR_ORTHOGONAL_RESTITUTION]=0.7;
params[ PARAM_ANGULAR_ORTHOGONAL_DAMPING]=1.0;
}
//////////////////////////////////
void ConeTwistJoint::_set_swing_span(float p_limit_angular) {
set_param(PARAM_SWING_SPAN,Math::deg2rad(p_limit_angular));
}
float ConeTwistJoint::_get_swing_span() const {
return Math::rad2deg(get_param(PARAM_SWING_SPAN));
}
void ConeTwistJoint::_set_twist_span(float p_limit_angular) {
set_param(PARAM_TWIST_SPAN,Math::deg2rad(p_limit_angular));
}
float ConeTwistJoint::_get_twist_span() const {
return Math::rad2deg(get_param(PARAM_TWIST_SPAN));
}
void ConeTwistJoint::_bind_methods() {
ObjectTypeDB::bind_method(_MD("set_param","param","value"),&ConeTwistJoint::set_param);
ObjectTypeDB::bind_method(_MD("get_param","param"),&ConeTwistJoint::get_param);
ObjectTypeDB::bind_method(_MD("_set_swing_span","swing_span"),&ConeTwistJoint::_set_swing_span);
ObjectTypeDB::bind_method(_MD("_get_swing_span"),&ConeTwistJoint::_get_swing_span);
ObjectTypeDB::bind_method(_MD("_set_twist_span","twist_span"),&ConeTwistJoint::_set_twist_span);
ObjectTypeDB::bind_method(_MD("_get_twist_span"),&ConeTwistJoint::_get_twist_span);
ADD_PROPERTY( PropertyInfo(Variant::REAL,"swing_span",PROPERTY_HINT_RANGE,"-180,180,0.1"),_SCS("_set_swing_span"),_SCS("_get_swing_span") );
ADD_PROPERTY( PropertyInfo(Variant::REAL,"twist_span",PROPERTY_HINT_RANGE,"-40000,40000,0.1"),_SCS("_set_twist_span"),_SCS("_get_twist_span") );
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"bias",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_BIAS );
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_SOFTNESS);
ADD_PROPERTYI( PropertyInfo(Variant::REAL,"relaxation",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,_SCS("set_param"),_SCS("get_param"), PARAM_RELAXATION);
BIND_CONSTANT( PARAM_SWING_SPAN );
BIND_CONSTANT( PARAM_TWIST_SPAN );
BIND_CONSTANT( PARAM_BIAS );
BIND_CONSTANT( PARAM_SOFTNESS );
BIND_CONSTANT( PARAM_RELAXATION );
BIND_CONSTANT( PARAM_MAX );
}
void ConeTwistJoint::set_param(Param p_param,float p_value){
ERR_FAIL_INDEX(p_param,PARAM_MAX);
params[p_param]=p_value;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->cone_twist_joint_set_param(get_joint(),PhysicsServer::ConeTwistJointParam(p_param),p_value);
update_gizmo();
}
float ConeTwistJoint::get_param(Param p_param) const{
ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
return params[p_param];
}
RID ConeTwistJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
Transform gt = get_global_transform();
//Vector3 cone_twistpos = gt.origin;
//Vector3 cone_twistdir = gt.basis.get_axis(2);
Transform ainv = body_a->get_global_transform().affine_inverse();
Transform local_a = ainv * gt;
local_a.orthonormalize();
Transform local_b = gt;
if (body_b) {
Transform binv = body_b->get_global_transform().affine_inverse();
local_b = binv * gt;
}
local_b.orthonormalize();
RID j = PhysicsServer::get_singleton()->joint_create_cone_twist(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b);
for(int i=0;i<PARAM_MAX;i++) {
PhysicsServer::get_singleton()->cone_twist_joint_set_param(j,PhysicsServer::ConeTwistJointParam(i),params[i]);
}
return j;
}
ConeTwistJoint::ConeTwistJoint() {
params[ PARAM_SWING_SPAN ]=Math_PI*0.25;
params[ PARAM_TWIST_SPAN ]=Math_PI;
params[ PARAM_BIAS ]=0.3;
params[ PARAM_SOFTNESS ]=0.8;
params[ PARAM_RELAXATION ]=1.0;
}
/////////////////////////////////////////////////////////////////////
void Generic6DOFJoint::_set_angular_hi_limit_x(float p_limit_angular) {
set_param_x(PARAM_ANGULAR_UPPER_LIMIT,Math::deg2rad(p_limit_angular));
}
float Generic6DOFJoint::_get_angular_hi_limit_x() const{
return Math::rad2deg(get_param_x(PARAM_ANGULAR_UPPER_LIMIT));
}
void Generic6DOFJoint::_set_angular_lo_limit_x(float p_limit_angular) {
set_param_x(PARAM_ANGULAR_LOWER_LIMIT,Math::deg2rad(p_limit_angular));
}
float Generic6DOFJoint::_get_angular_lo_limit_x() const{
return Math::rad2deg(get_param_x(PARAM_ANGULAR_LOWER_LIMIT));
}
void Generic6DOFJoint::_set_angular_hi_limit_y(float p_limit_angular) {
set_param_y(PARAM_ANGULAR_UPPER_LIMIT,Math::deg2rad(p_limit_angular));
}
float Generic6DOFJoint::_get_angular_hi_limit_y() const{
return Math::rad2deg(get_param_y(PARAM_ANGULAR_UPPER_LIMIT));
}
void Generic6DOFJoint::_set_angular_lo_limit_y(float p_limit_angular) {
set_param_y(PARAM_ANGULAR_LOWER_LIMIT,Math::deg2rad(p_limit_angular));
}
float Generic6DOFJoint::_get_angular_lo_limit_y() const{
return Math::rad2deg(get_param_y(PARAM_ANGULAR_LOWER_LIMIT));
}
void Generic6DOFJoint::_set_angular_hi_limit_z(float p_limit_angular) {
set_param_z(PARAM_ANGULAR_UPPER_LIMIT,Math::deg2rad(p_limit_angular));
}
float Generic6DOFJoint::_get_angular_hi_limit_z() const{
return Math::rad2deg(get_param_z(PARAM_ANGULAR_UPPER_LIMIT));
}
void Generic6DOFJoint::_set_angular_lo_limit_z(float p_limit_angular) {
set_param_z(PARAM_ANGULAR_LOWER_LIMIT,Math::deg2rad(p_limit_angular));
}
float Generic6DOFJoint::_get_angular_lo_limit_z() const{
return Math::rad2deg(get_param_z(PARAM_ANGULAR_LOWER_LIMIT));
}
void Generic6DOFJoint::_bind_methods(){
ObjectTypeDB::bind_method(_MD("_set_angular_hi_limit_x","angle"),&Generic6DOFJoint::_set_angular_hi_limit_x);
ObjectTypeDB::bind_method(_MD("_get_angular_hi_limit_x"),&Generic6DOFJoint::_get_angular_hi_limit_x);
ObjectTypeDB::bind_method(_MD("_set_angular_lo_limit_x","angle"),&Generic6DOFJoint::_set_angular_lo_limit_x);
ObjectTypeDB::bind_method(_MD("_get_angular_lo_limit_x"),&Generic6DOFJoint::_get_angular_lo_limit_x);
ObjectTypeDB::bind_method(_MD("_set_angular_hi_limit_y","angle"),&Generic6DOFJoint::_set_angular_hi_limit_y);
ObjectTypeDB::bind_method(_MD("_get_angular_hi_limit_y"),&Generic6DOFJoint::_get_angular_hi_limit_y);
ObjectTypeDB::bind_method(_MD("_set_angular_lo_limit_y","angle"),&Generic6DOFJoint::_set_angular_lo_limit_y);
ObjectTypeDB::bind_method(_MD("_get_angular_lo_limit_y"),&Generic6DOFJoint::_get_angular_lo_limit_y);
ObjectTypeDB::bind_method(_MD("_set_angular_hi_limit_z","angle"),&Generic6DOFJoint::_set_angular_hi_limit_z);
ObjectTypeDB::bind_method(_MD("_get_angular_hi_limit_z"),&Generic6DOFJoint::_get_angular_hi_limit_z);
ObjectTypeDB::bind_method(_MD("_set_angular_lo_limit_z","angle"),&Generic6DOFJoint::_set_angular_lo_limit_z);
ObjectTypeDB::bind_method(_MD("_get_angular_lo_limit_z"),&Generic6DOFJoint::_get_angular_lo_limit_z);
ObjectTypeDB::bind_method(_MD("set_param_x","param","value"),&Generic6DOFJoint::set_param_x);
ObjectTypeDB::bind_method(_MD("get_param_x","param"),&Generic6DOFJoint::get_param_x);
ObjectTypeDB::bind_method(_MD("set_param_y","param","value"),&Generic6DOFJoint::set_param_y);
ObjectTypeDB::bind_method(_MD("get_param_y","param"),&Generic6DOFJoint::get_param_y);
ObjectTypeDB::bind_method(_MD("set_param_z","param","value"),&Generic6DOFJoint::set_param_z);
ObjectTypeDB::bind_method(_MD("get_param_z","param"),&Generic6DOFJoint::get_param_z);
ObjectTypeDB::bind_method(_MD("set_flag_x","flag","value"),&Generic6DOFJoint::set_flag_x);
ObjectTypeDB::bind_method(_MD("get_flag_x","flag"),&Generic6DOFJoint::get_flag_x);
ObjectTypeDB::bind_method(_MD("set_flag_y","flag","value"),&Generic6DOFJoint::set_flag_y);
ObjectTypeDB::bind_method(_MD("get_flag_y","flag"),&Generic6DOFJoint::get_flag_y);
ObjectTypeDB::bind_method(_MD("set_flag_z","flag","value"),&Generic6DOFJoint::set_flag_z);
ObjectTypeDB::bind_method(_MD("get_flag_z","flag"),&Generic6DOFJoint::get_flag_z);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"linear_limit_x/enabled"),_SCS("set_flag_x"),_SCS("get_flag_x"),FLAG_ENABLE_LINEAR_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/upper_distance"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_LINEAR_UPPER_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/lower_distance"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_LINEAR_LOWER_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_LINEAR_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_LINEAR_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_LINEAR_DAMPING);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_limit_x/enabled"),_SCS("set_flag_x"),_SCS("get_flag_x"),FLAG_ENABLE_ANGULAR_LIMIT);
ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_x/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),_SCS("_set_angular_hi_limit_x"),_SCS("_get_angular_hi_limit_x"));
ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_x/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),_SCS("_set_angular_lo_limit_x"),_SCS("_get_angular_lo_limit_x"));
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_ANGULAR_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_ANGULAR_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_ANGULAR_DAMPING);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/force_limit"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_ANGULAR_FORCE_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/erp"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_ANGULAR_ERP);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_motor_x/enabled"),_SCS("set_flag_x"),_SCS("get_flag_x"),FLAG_ENABLE_MOTOR);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_x/target_velocity"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_x/force_limit"),_SCS("set_param_x"),_SCS("get_param_x"),PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"linear_limit_y/enabled"),_SCS("set_flag_y"),_SCS("get_flag_y"),FLAG_ENABLE_LINEAR_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/upper_distance"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_LINEAR_UPPER_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/lower_distance"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_LINEAR_LOWER_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_LINEAR_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_LINEAR_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_LINEAR_DAMPING);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_limit_y/enabled"),_SCS("set_flag_y"),_SCS("get_flag_y"),FLAG_ENABLE_ANGULAR_LIMIT);
ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_y/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),_SCS("_set_angular_hi_limit_y"),_SCS("_get_angular_hi_limit_y"));
ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_y/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),_SCS("_set_angular_lo_limit_y"),_SCS("_get_angular_lo_limit_y"));
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_ANGULAR_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_ANGULAR_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_ANGULAR_DAMPING);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/force_limit"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_ANGULAR_FORCE_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/erp"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_ANGULAR_ERP);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_motor_y/enabled"),_SCS("set_flag_y"),_SCS("get_flag_y"),FLAG_ENABLE_MOTOR);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_y/target_velocity"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_y/force_limit"),_SCS("set_param_y"),_SCS("get_param_y"),PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"linear_limit_z/enabled"),_SCS("set_flag_z"),_SCS("get_flag_z"),FLAG_ENABLE_LINEAR_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/upper_distance"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_LINEAR_UPPER_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/lower_distance"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_LINEAR_LOWER_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_LINEAR_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_LINEAR_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_LINEAR_DAMPING);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_limit_z/enabled"),_SCS("set_flag_z"),_SCS("get_flag_z"),FLAG_ENABLE_ANGULAR_LIMIT);
ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_z/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),_SCS("_set_angular_hi_limit_z"),_SCS("_get_angular_hi_limit_z"));
ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_z/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),_SCS("_set_angular_lo_limit_z"),_SCS("_get_angular_lo_limit_z"));
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_ANGULAR_LIMIT_SOFTNESS);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_ANGULAR_RESTITUTION);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_ANGULAR_DAMPING);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/force_limit"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_ANGULAR_FORCE_LIMIT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/erp"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_ANGULAR_ERP);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_motor_z/enabled"),_SCS("set_flag_z"),_SCS("get_flag_z"),FLAG_ENABLE_MOTOR);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_z/target_velocity"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_z/force_limit"),_SCS("set_param_z"),_SCS("get_param_z"),PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
BIND_CONSTANT( PARAM_LINEAR_LOWER_LIMIT);
BIND_CONSTANT( PARAM_LINEAR_UPPER_LIMIT);
BIND_CONSTANT( PARAM_LINEAR_LIMIT_SOFTNESS);
BIND_CONSTANT( PARAM_LINEAR_RESTITUTION);
BIND_CONSTANT( PARAM_LINEAR_DAMPING);
BIND_CONSTANT( PARAM_ANGULAR_LOWER_LIMIT);
BIND_CONSTANT( PARAM_ANGULAR_UPPER_LIMIT);
BIND_CONSTANT( PARAM_ANGULAR_LIMIT_SOFTNESS);
BIND_CONSTANT( PARAM_ANGULAR_DAMPING);
BIND_CONSTANT( PARAM_ANGULAR_RESTITUTION);
BIND_CONSTANT( PARAM_ANGULAR_FORCE_LIMIT);
BIND_CONSTANT( PARAM_ANGULAR_ERP);
BIND_CONSTANT( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
BIND_CONSTANT( PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
BIND_CONSTANT( PARAM_MAX);
BIND_CONSTANT( FLAG_ENABLE_LINEAR_LIMIT);
BIND_CONSTANT( FLAG_ENABLE_ANGULAR_LIMIT);
BIND_CONSTANT( FLAG_ENABLE_MOTOR);
BIND_CONSTANT( FLAG_MAX );
}
void Generic6DOFJoint::set_param_x(Param p_param,float p_value){
ERR_FAIL_INDEX(p_param,PARAM_MAX);
params_x[p_param]=p_value;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(),Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisParam(p_param),p_value);
update_gizmo();
}
float Generic6DOFJoint::get_param_x(Param p_param) const{
ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
return params_x[p_param];
}
void Generic6DOFJoint::set_param_y(Param p_param,float p_value){
ERR_FAIL_INDEX(p_param,PARAM_MAX);
params_y[p_param]=p_value;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(),Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisParam(p_param),p_value);
update_gizmo();
}
float Generic6DOFJoint::get_param_y(Param p_param) const{
ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
return params_y[p_param];
}
void Generic6DOFJoint::set_param_z(Param p_param,float p_value){
ERR_FAIL_INDEX(p_param,PARAM_MAX);
params_z[p_param]=p_value;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(),Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisParam(p_param),p_value);
update_gizmo();
}
float Generic6DOFJoint::get_param_z(Param p_param) const{
ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
return params_z[p_param];
}
void Generic6DOFJoint::set_flag_x(Flag p_flag,bool p_enabled){
ERR_FAIL_INDEX(p_flag,FLAG_MAX);
flags_x[p_flag]=p_enabled;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(),Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisFlag(p_flag),p_enabled);
update_gizmo();
}
bool Generic6DOFJoint::get_flag_x(Flag p_flag) const{
ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
return flags_x[p_flag];
}
void Generic6DOFJoint::set_flag_y(Flag p_flag,bool p_enabled){
ERR_FAIL_INDEX(p_flag,FLAG_MAX);
flags_y[p_flag]=p_enabled;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(),Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisFlag(p_flag),p_enabled);
update_gizmo();
}
bool Generic6DOFJoint::get_flag_y(Flag p_flag) const{
ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
return flags_y[p_flag];
}
void Generic6DOFJoint::set_flag_z(Flag p_flag,bool p_enabled){
ERR_FAIL_INDEX(p_flag,FLAG_MAX);
flags_z[p_flag]=p_enabled;
if (get_joint().is_valid())
PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(),Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisFlag(p_flag),p_enabled);
update_gizmo();
}
bool Generic6DOFJoint::get_flag_z(Flag p_flag) const{
ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
return flags_z[p_flag];
}
RID Generic6DOFJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
Transform gt = get_global_transform();
//Vector3 cone_twistpos = gt.origin;
//Vector3 cone_twistdir = gt.basis.get_axis(2);
Transform ainv = body_a->get_global_transform().affine_inverse();
Transform local_a = ainv * gt;
local_a.orthonormalize();
Transform local_b = gt;
if (body_b) {
Transform binv = body_b->get_global_transform().affine_inverse();
local_b = binv * gt;
}
local_b.orthonormalize();
RID j = PhysicsServer::get_singleton()->joint_create_generic_6dof(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b);
for(int i=0;i<PARAM_MAX;i++) {
PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j,Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisParam(i),params_x[i]);
PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j,Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisParam(i),params_y[i]);
PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j,Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisParam(i),params_z[i]);
}
for(int i=0;i<FLAG_MAX;i++) {
PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j,Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisFlag(i),flags_x[i]);
PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j,Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisFlag(i),flags_y[i]);
PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j,Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisFlag(i),flags_z[i]);
}
return j;
}
Generic6DOFJoint::Generic6DOFJoint() {
set_param_x( PARAM_LINEAR_LOWER_LIMIT,0);
set_param_x( PARAM_LINEAR_UPPER_LIMIT,0);
set_param_x( PARAM_LINEAR_LIMIT_SOFTNESS,0.7);
set_param_x( PARAM_LINEAR_RESTITUTION,0.5);
set_param_x( PARAM_LINEAR_DAMPING,1.0);
set_param_x( PARAM_ANGULAR_LOWER_LIMIT,0);
set_param_x( PARAM_ANGULAR_UPPER_LIMIT,0);
set_param_x( PARAM_ANGULAR_LIMIT_SOFTNESS,0.5f);
set_param_x( PARAM_ANGULAR_DAMPING,1.0f);
set_param_x( PARAM_ANGULAR_RESTITUTION,0);
set_param_x( PARAM_ANGULAR_FORCE_LIMIT,0);
set_param_x( PARAM_ANGULAR_ERP,0.5);
set_param_x( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY,0);
set_param_x( PARAM_ANGULAR_MOTOR_FORCE_LIMIT,300);
set_flag_x( FLAG_ENABLE_ANGULAR_LIMIT,true);
set_flag_x( FLAG_ENABLE_LINEAR_LIMIT,true);
set_flag_x( FLAG_ENABLE_MOTOR,false);
set_param_y( PARAM_LINEAR_LOWER_LIMIT,0);
set_param_y( PARAM_LINEAR_UPPER_LIMIT,0);
set_param_y( PARAM_LINEAR_LIMIT_SOFTNESS,0.7);
set_param_y( PARAM_LINEAR_RESTITUTION,0.5);
set_param_y( PARAM_LINEAR_DAMPING,1.0);
set_param_y( PARAM_ANGULAR_LOWER_LIMIT,0);
set_param_y( PARAM_ANGULAR_UPPER_LIMIT,0);
set_param_y( PARAM_ANGULAR_LIMIT_SOFTNESS,0.5f);
set_param_y( PARAM_ANGULAR_DAMPING,1.0f);
set_param_y( PARAM_ANGULAR_RESTITUTION,0);
set_param_y( PARAM_ANGULAR_FORCE_LIMIT,0);
set_param_y( PARAM_ANGULAR_ERP,0.5);
set_param_y( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY,0);
set_param_y( PARAM_ANGULAR_MOTOR_FORCE_LIMIT,300);
set_flag_y( FLAG_ENABLE_ANGULAR_LIMIT,true);
set_flag_y( FLAG_ENABLE_LINEAR_LIMIT,true);
set_flag_y( FLAG_ENABLE_MOTOR,false);
set_param_z( PARAM_LINEAR_LOWER_LIMIT,0);
set_param_z( PARAM_LINEAR_UPPER_LIMIT,0);
set_param_z( PARAM_LINEAR_LIMIT_SOFTNESS,0.7);
set_param_z( PARAM_LINEAR_RESTITUTION,0.5);
set_param_z( PARAM_LINEAR_DAMPING,1.0);
set_param_z( PARAM_ANGULAR_LOWER_LIMIT,0);
set_param_z( PARAM_ANGULAR_UPPER_LIMIT,0);
set_param_z( PARAM_ANGULAR_LIMIT_SOFTNESS,0.5f);
set_param_z( PARAM_ANGULAR_DAMPING,1.0f);
set_param_z( PARAM_ANGULAR_RESTITUTION,0);
set_param_z( PARAM_ANGULAR_FORCE_LIMIT,0);
set_param_z( PARAM_ANGULAR_ERP,0.5);
set_param_z( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY,0);
set_param_z( PARAM_ANGULAR_MOTOR_FORCE_LIMIT,300);
set_flag_z( FLAG_ENABLE_ANGULAR_LIMIT,true);
set_flag_z( FLAG_ENABLE_LINEAR_LIMIT,true);
set_flag_z( FLAG_ENABLE_MOTOR,false);
}
#if 0
void PhysicsJoint::_set(const String& p_name, const Variant& p_value) {
if (p_name=="body_A")
set_body_A(p_value);
else if (p_name=="body_B")
set_body_B(p_value);
else if (p_name=="active")
set_active(p_value);
else if (p_name=="no_collision")
set_disable_collision(p_value);
}
Variant PhysicsJoint::_get(const String& p_name) const {
if (p_name=="body_A")
return get_body_A();
else if (p_name=="body_B")
return get_body_B();
else if (p_name=="active")
return is_active();
else if (p_name=="no_collision")
return has_disable_collision();
return Variant();
}
void PhysicsJoint::_get_property_list( List<PropertyInfo> *p_list) const {
p_list->push_back( PropertyInfo( Variant::NODE_PATH, "body_A" ) );
p_list->push_back( PropertyInfo( Variant::NODE_PATH, "body_B" ) );
p_list->push_back( PropertyInfo( Variant::BOOL, "active" ) );
p_list->push_back( PropertyInfo( Variant::BOOL, "no_collision" ) );
}
void PhysicsJoint::_notification(int p_what) {
switch(p_what) {
case NOTIFICATION_PARENT_CONFIGURED: {
_connect();
if (get_root_node()->get_editor() && !indicator.is_valid()) {
indicator=VisualServer::get_singleton()->poly_create();
RID mat=VisualServer::get_singleton()->fixed_material_create();
VisualServer::get_singleton()->material_set_flag( mat, VisualServer::MATERIAL_FLAG_UNSHADED, true );
VisualServer::get_singleton()->material_set_flag( mat, VisualServer::MATERIAL_FLAG_ONTOP, true );
VisualServer::get_singleton()->material_set_flag( mat, VisualServer::MATERIAL_FLAG_WIREFRAME, true );
VisualServer::get_singleton()->material_set_flag( mat, VisualServer::MATERIAL_FLAG_DOUBLE_SIDED, true );
VisualServer::get_singleton()->material_set_line_width( mat, 3 );
VisualServer::get_singleton()->poly_set_material(indicator,mat,true);
_update_indicator();
}
if (indicator.is_valid()) {
indicator_instance=VisualServer::get_singleton()->instance_create(indicator,get_world()->get_scenario());
VisualServer::get_singleton()->instance_attach_object_instance_ID( indicator_instance,get_instance_ID() );
}
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
if (indicator_instance.is_valid()) {
VisualServer::get_singleton()->instance_set_transform(indicator_instance,get_global_transform());
}
} break;
case NOTIFICATION_EXIT_SCENE: {
if (indicator_instance.is_valid()) {
VisualServer::get_singleton()->free(indicator_instance);
}
_disconnect();
} break;
}
}
RID PhysicsJoint::_get_visual_instance_rid() const {
return indicator_instance;
}
void PhysicsJoint::_bind_methods() {
ObjectTypeDB::bind_method(_MD("_get_visual_instance_rid"),&PhysicsJoint::_get_visual_instance_rid);
ObjectTypeDB::bind_method(_MD("set_body_A","path"),&PhysicsJoint::set_body_A);
ObjectTypeDB::bind_method(_MD("set_body_B"),&PhysicsJoint::set_body_B);
ObjectTypeDB::bind_method(_MD("get_body_A","path"),&PhysicsJoint::get_body_A);
ObjectTypeDB::bind_method(_MD("get_body_B"),&PhysicsJoint::get_body_B);
ObjectTypeDB::bind_method(_MD("set_active","active"),&PhysicsJoint::set_active);
ObjectTypeDB::bind_method(_MD("is_active"),&PhysicsJoint::is_active);
ObjectTypeDB::bind_method(_MD("set_disable_collision","disable"),&PhysicsJoint::set_disable_collision);
ObjectTypeDB::bind_method(_MD("has_disable_collision"),&PhysicsJoint::has_disable_collision);
ObjectTypeDB::bind_method("reconnect",&PhysicsJoint::reconnect);
ObjectTypeDB::bind_method(_MD("get_rid"),&PhysicsJoint::get_rid);
}
void PhysicsJoint::set_body_A(const NodePath& p_path) {
_disconnect();
body_A=p_path;
_connect();
_change_notify("body_A");
}
void PhysicsJoint::set_body_B(const NodePath& p_path) {
_disconnect();
body_B=p_path;
_connect();
_change_notify("body_B");
}
NodePath PhysicsJoint::get_body_A() const {
return body_A;
}
NodePath PhysicsJoint::get_body_B() const {
return body_B;
}
void PhysicsJoint::set_active(bool p_active) {
active=p_active;
if (is_inside_scene()) {
PhysicsServer::get_singleton()->joint_set_active(joint,active);
}
_change_notify("active");
}
void PhysicsJoint::set_disable_collision(bool p_active) {
if (no_collision==p_active)
return;
_disconnect();
no_collision=p_active;
_connect();
_change_notify("no_collision");
}
bool PhysicsJoint::has_disable_collision() const {
return no_collision;
}
bool PhysicsJoint::is_active() const {
return active;
}
void PhysicsJoint::_disconnect() {
if (!is_inside_scene())
return;
if (joint.is_valid())
PhysicsServer::get_singleton()->free(joint);
joint=RID();
Node *nA = get_node(body_A);
Node *nB = get_node(body_B);
PhysicsBody *A = nA?nA->cast_to<PhysicsBody>():NULL;
PhysicsBody *B = nA?nB->cast_to<PhysicsBody>():NULL;
if (!A ||!B)
return;
if (no_collision)
PhysicsServer::get_singleton()->body_remove_collision_exception(A->get_body(),B->get_body());
}
void PhysicsJoint::_connect() {
if (!is_inside_scene())
return;
ERR_FAIL_COND(joint.is_valid());
Node *nA = get_node(body_A);
Node *nB = get_node(body_B);
PhysicsBody *A = nA?nA->cast_to<PhysicsBody>():NULL;
PhysicsBody *B = nA?nB->cast_to<PhysicsBody>():NULL;
if (!A && !B)
return;
if (B && !A)
SWAP(B,A);
joint = create(A,B);
if (A<B)
SWAP(A,B);
if (no_collision)
PhysicsServer::get_singleton()->body_add_collision_exception(A->get_body(),B->get_body());
}
void PhysicsJoint::reconnect() {
_disconnect();
_connect();
}
RID PhysicsJoint::get_rid() {
return joint;
}
PhysicsJoint::PhysicsJoint() {
active=true;
no_collision=true;
}
PhysicsJoint::~PhysicsJoint() {
if (indicator.is_valid()) {
VisualServer::get_singleton()->free(indicator);
}
}
/* PIN */
void PhysicsJointPin::_update_indicator() {
VisualServer::get_singleton()->poly_clear(indicator);
Vector<Color> colors;
colors.push_back( Color(0.3,0.9,0.2,0.7) );
colors.push_back( Color(0.3,0.9,0.2,0.7) );
Vector<Vector3> points;
points.resize(2);
points[0]=Vector3(Vector3(-0.2,0,0));
points[1]=Vector3(Vector3(0.2,0,0));
VisualServer::get_singleton()->poly_add_primitive(indicator,points,Vector<Vector3>(),colors,Vector<Vector3>());
points[0]=Vector3(Vector3(0,-0.2,0));
points[1]=Vector3(Vector3(0,0.2,0));
VisualServer::get_singleton()->poly_add_primitive(indicator,points,Vector<Vector3>(),colors,Vector<Vector3>());
points[0]=Vector3(Vector3(0,0,-0.2));
points[1]=Vector3(Vector3(0,0,0.2));
VisualServer::get_singleton()->poly_add_primitive(indicator,points,Vector<Vector3>(),colors,Vector<Vector3>());
}
RID PhysicsJointPin::create(PhysicsBody*A,PhysicsBody*B) {
RID body_A = A->get_body();
RID body_B = B?B->get_body():RID();
ERR_FAIL_COND_V( !body_A.is_valid(), RID() );
Vector3 pin_pos = get_global_transform().origin;
if (body_B.is_valid())
return PhysicsServer::get_singleton()->joint_create_double_pin_global(body_A,pin_pos,body_B,pin_pos);
else
return PhysicsServer::get_singleton()->joint_create_pin(body_A,A->get_global_transform().xform_inv(pin_pos),pin_pos);
}
PhysicsJointPin::PhysicsJointPin() {
}
#endif
| mit |
SpotLabsNET/coreclr | src/vm/methodtable.cpp | 44 | 311938 | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// File: methodtable.cpp
//
//
//
// ============================================================================
#include "common.h"
#include "clsload.hpp"
#include "method.hpp"
#include "class.h"
#include "classcompat.h"
#include "object.h"
#include "field.h"
#include "util.hpp"
#include "excep.h"
#include "siginfo.hpp"
#include "threads.h"
#include "stublink.h"
#include "ecall.h"
#include "dllimport.h"
#include "gcdesc.h"
#include "verifier.hpp"
#include "jitinterface.h"
#include "eeconfig.h"
#include "log.h"
#include "fieldmarshaler.h"
#include "cgensys.h"
#include "gc.h"
#include "security.h"
#include "dbginterface.h"
#include "comdelegate.h"
#include "eventtrace.h"
#ifdef FEATURE_REMOTING
#include "remoting.h"
#endif
#include "eeprofinterfaces.h"
#include "dllimportcallback.h"
#include "listlock.h"
#include "methodimpl.h"
#include "guidfromname.h"
#include "stackprobe.h"
#include "encee.h"
#include "encee.h"
#include "comsynchronizable.h"
#include "customattribute.h"
#include "virtualcallstub.h"
#include "contractimpl.h"
#ifdef FEATURE_PREJIT
#include "zapsig.h"
#endif //FEATURE_PREJIT
#include "hostexecutioncontext.h"
#ifdef FEATURE_COMINTEROP
#include "comcallablewrapper.h"
#include "clrtocomcall.h"
#include "runtimecallablewrapper.h"
#include "winrttypenameconverter.h"
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_TYPEEQUIVALENCE
#include "typeequivalencehash.hpp"
#endif
#include "listlock.inl"
#include "generics.h"
#include "genericdict.h"
#include "typestring.h"
#include "typedesc.h"
#ifdef FEATURE_REMOTING
#include "crossdomaincalls.h"
#endif
#include "array.h"
#ifdef FEATURE_INTERPRETER
#include "interpreter.h"
#endif // FEATURE_INTERPRETER
#ifndef DACCESS_COMPILE
// Typedef for string comparition functions.
typedef int (__cdecl *UTF8StringCompareFuncPtr)(const char *, const char *);
MethodDataCache *MethodTable::s_pMethodDataCache = NULL;
BOOL MethodTable::s_fUseMethodDataCache = FALSE;
BOOL MethodTable::s_fUseParentMethodData = FALSE;
#ifdef _DEBUG
extern unsigned g_dupMethods;
#endif
#endif // !DACCESS_COMPILE
#ifndef DACCESS_COMPILE
//==========================================================================================
class MethodDataCache
{
typedef MethodTable::MethodData MethodData;
public: // Ctor. Allocates cEntries entries. Throws.
static UINT32 GetObjectSize(UINT32 cEntries);
MethodDataCache(UINT32 cEntries);
MethodData *Find(MethodTable *pMT);
MethodData *Find(MethodTable *pMTDecl, MethodTable *pMTImpl);
void Insert(MethodData *pMData);
void Clear();
protected:
// This describes each entry in the cache.
struct Entry
{
MethodData *m_pMData;
UINT32 m_iTimestamp;
};
MethodData *FindHelper(MethodTable *pMTDecl, MethodTable *pMTImpl, UINT32 idx);
inline UINT32 GetNextTimestamp()
{ return ++m_iCurTimestamp; }
inline UINT32 NumEntries()
{ LIMITED_METHOD_CONTRACT; return m_cEntries; }
inline void TouchEntry(UINT32 i)
{ WRAPPER_NO_CONTRACT; m_iLastTouched = i; GetEntry(i)->m_iTimestamp = GetNextTimestamp(); }
inline UINT32 GetLastTouchedEntryIndex()
{ WRAPPER_NO_CONTRACT; return m_iLastTouched; }
// The end of this object contains an array of Entry
inline Entry *GetEntryData()
{ LIMITED_METHOD_CONTRACT; return (Entry *)(this + 1); }
inline Entry *GetEntry(UINT32 i)
{ WRAPPER_NO_CONTRACT; return GetEntryData() + i; }
private:
// This serializes access to the cache
SimpleRWLock m_lock;
// This allows ageing of entries to decide which to punt when
// inserting a new entry.
UINT32 m_iCurTimestamp;
// The number of entries in the cache
UINT32 m_cEntries;
UINT32 m_iLastTouched;
#ifdef _WIN64
UINT32 pad; // insures that we are a multiple of 8-bytes
#endif
}; // class MethodDataCache
//==========================================================================================
UINT32 MethodDataCache::GetObjectSize(UINT32 cEntries)
{
LIMITED_METHOD_CONTRACT;
return sizeof(MethodDataCache) + (sizeof(Entry) * cEntries);
}
//==========================================================================================
MethodDataCache::MethodDataCache(UINT32 cEntries)
: m_lock(COOPERATIVE_OR_PREEMPTIVE, LOCK_TYPE_DEFAULT),
m_iCurTimestamp(0),
m_cEntries(cEntries),
m_iLastTouched(0)
{
WRAPPER_NO_CONTRACT;
ZeroMemory(GetEntryData(), cEntries * sizeof(Entry));
}
//==========================================================================================
MethodTable::MethodData *MethodDataCache::FindHelper(
MethodTable *pMTDecl, MethodTable *pMTImpl, UINT32 idx)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
INSTANCE_CHECK;
} CONTRACTL_END;
MethodData *pEntry = GetEntry(idx)->m_pMData;
if (pEntry != NULL) {
MethodTable *pMTDeclEntry = pEntry->GetDeclMethodTable();
MethodTable *pMTImplEntry = pEntry->GetImplMethodTable();
if (pMTDeclEntry == pMTDecl && pMTImplEntry == pMTImpl) {
return pEntry;
}
else if (pMTDecl == pMTImpl) {
if (pMTDeclEntry == pMTDecl) {
return pEntry->GetDeclMethodData();
}
if (pMTImplEntry == pMTDecl) {
return pEntry->GetImplMethodData();
}
}
}
return NULL;
}
//==========================================================================================
MethodTable::MethodData *MethodDataCache::Find(MethodTable *pMTDecl, MethodTable *pMTImpl)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
INSTANCE_CHECK;
} CONTRACTL_END;
#ifdef LOGGING
g_sdStats.m_cCacheLookups++;
#endif
SimpleReadLockHolder lh(&m_lock);
// Check the last touched entry.
MethodData *pEntry = FindHelper(pMTDecl, pMTImpl, GetLastTouchedEntryIndex());
// Now search the entire cache.
if (pEntry == NULL) {
for (UINT32 i = 0; i < NumEntries(); i++) {
pEntry = FindHelper(pMTDecl, pMTImpl, i);
if (pEntry != NULL) {
TouchEntry(i);
break;
}
}
}
if (pEntry != NULL) {
pEntry->AddRef();
}
#ifdef LOGGING
else {
// Failure to find the entry in the cache.
g_sdStats.m_cCacheMisses++;
}
#endif // LOGGING
return pEntry;
}
//==========================================================================================
MethodTable::MethodData *MethodDataCache::Find(MethodTable *pMT)
{
WRAPPER_NO_CONTRACT;
return Find(pMT, pMT);
}
//==========================================================================================
void MethodDataCache::Insert(MethodData *pMData)
{
CONTRACTL {
NOTHROW; // for now, because it does not yet resize.
GC_NOTRIGGER;
INSTANCE_CHECK;
} CONTRACTL_END;
SimpleWriteLockHolder hLock(&m_lock);
UINT32 iMin = UINT32_MAX;
UINT32 idxMin = UINT32_MAX;
for (UINT32 i = 0; i < NumEntries(); i++) {
if (GetEntry(i)->m_iTimestamp < iMin) {
idxMin = i;
iMin = GetEntry(i)->m_iTimestamp;
}
}
Entry *pEntry = GetEntry(idxMin);
if (pEntry->m_pMData != NULL) {
pEntry->m_pMData->Release();
}
pMData->AddRef();
pEntry->m_pMData = pMData;
pEntry->m_iTimestamp = GetNextTimestamp();
}
//==========================================================================================
void MethodDataCache::Clear()
{
CONTRACTL {
NOTHROW; // for now, because it does not yet resize.
GC_NOTRIGGER;
INSTANCE_CHECK;
} CONTRACTL_END;
// Taking the lock here is just a precaution. Really, the runtime
// should be suspended because this is called while unloading an
// AppDomain at the SysSuspendEE stage. But, if someone calls it
// outside of that context, we should be extra cautious.
SimpleWriteLockHolder lh(&m_lock);
for (UINT32 i = 0; i < NumEntries(); i++) {
Entry *pEntry = GetEntry(i);
if (pEntry->m_pMData != NULL) {
pEntry->m_pMData->Release();
}
}
ZeroMemory(GetEntryData(), NumEntries() * sizeof(Entry));
m_iCurTimestamp = 0;
} // MethodDataCache::Clear
#endif // !DACCESS_COMPILE
//==========================================================================================
//
// Initialize the offsets of multipurpose slots at compile time using template metaprogramming
//
template<int N>
struct CountBitsAtCompileTime
{
enum { value = (N & 1) + CountBitsAtCompileTime<(N >> 1)>::value };
};
template<>
struct CountBitsAtCompileTime<0>
{
enum { value = 0 };
};
// "mask" is mask of used slots.
template<int mask>
struct MethodTable::MultipurposeSlotOffset
{
// This is raw index of the slot assigned on first come first served basis
enum { raw = CountBitsAtCompileTime<mask>::value };
// This is actual index of the slot. It is equal to raw index except for the case
// where the first fixed slot is not used, but the second one is. The first fixed
// slot has to be assigned instead of the second one in this case. This assumes that
// there are exactly two fixed slots.
enum { index = (((mask & 3) == 2) && (raw == 1)) ? 0 : raw };
// Offset of slot
enum { slotOffset = (index == 0) ? offsetof(MethodTable, m_pMultipurposeSlot1) :
(index == 1) ? offsetof(MethodTable, m_pMultipurposeSlot2) :
(sizeof(MethodTable) + index * sizeof(TADDR) - 2 * sizeof(TADDR)) };
// Size of methodtable with overflow slots. It is used to compute start offset of optional members.
enum { totalSize = (slotOffset >= sizeof(MethodTable)) ? slotOffset : sizeof(MethodTable) };
};
//
// These macros recursively expand to create 2^N values for the offset arrays
//
#define MULTIPURPOSE_SLOT_OFFSET_1(mask) MULTIPURPOSE_SLOT_OFFSET (mask) MULTIPURPOSE_SLOT_OFFSET (mask | 0x01)
#define MULTIPURPOSE_SLOT_OFFSET_2(mask) MULTIPURPOSE_SLOT_OFFSET_1(mask) MULTIPURPOSE_SLOT_OFFSET_1(mask | 0x02)
#define MULTIPURPOSE_SLOT_OFFSET_3(mask) MULTIPURPOSE_SLOT_OFFSET_2(mask) MULTIPURPOSE_SLOT_OFFSET_2(mask | 0x04)
#define MULTIPURPOSE_SLOT_OFFSET_4(mask) MULTIPURPOSE_SLOT_OFFSET_3(mask) MULTIPURPOSE_SLOT_OFFSET_3(mask | 0x08)
#define MULTIPURPOSE_SLOT_OFFSET_5(mask) MULTIPURPOSE_SLOT_OFFSET_4(mask) MULTIPURPOSE_SLOT_OFFSET_4(mask | 0x10)
#define MULTIPURPOSE_SLOT_OFFSET(mask) MultipurposeSlotOffset<mask>::slotOffset,
const BYTE MethodTable::c_DispatchMapSlotOffsets[] = {
MULTIPURPOSE_SLOT_OFFSET_2(0)
};
const BYTE MethodTable::c_NonVirtualSlotsOffsets[] = {
MULTIPURPOSE_SLOT_OFFSET_3(0)
};
const BYTE MethodTable::c_ModuleOverrideOffsets[] = {
MULTIPURPOSE_SLOT_OFFSET_4(0)
};
#undef MULTIPURPOSE_SLOT_OFFSET
#define MULTIPURPOSE_SLOT_OFFSET(mask) MultipurposeSlotOffset<mask>::totalSize,
const BYTE MethodTable::c_OptionalMembersStartOffsets[] = {
MULTIPURPOSE_SLOT_OFFSET_5(0)
};
#undef MULTIPURPOSE_SLOT_OFFSET
//==========================================================================================
// Optimization intended for MethodTable::GetModule, MethodTable::GetDispatchMap and MethodTable::GetNonVirtualSlotsPtr
#include <optsmallperfcritical.h>
PTR_Module MethodTable::GetModule()
{
LIMITED_METHOD_DAC_CONTRACT;
g_IBCLogger.LogMethodTableAccess(this);
// Fast path for non-generic non-array case
if ((m_dwFlags & (enum_flag_HasComponentSize | enum_flag_GenericsMask)) == 0)
return GetLoaderModule();
MethodTable * pMTForModule = IsArray() ? this : GetCanonicalMethodTable();
if (!pMTForModule->HasModuleOverride())
return pMTForModule->GetLoaderModule();
TADDR pSlot = pMTForModule->GetMultipurposeSlotPtr(enum_flag_HasModuleOverride, c_ModuleOverrideOffsets);
return RelativeFixupPointer<PTR_Module>::GetValueAtPtr(pSlot);
}
//==========================================================================================
PTR_Module MethodTable::GetModule_NoLogging()
{
LIMITED_METHOD_DAC_CONTRACT;
// Fast path for non-generic non-array case
if ((m_dwFlags & (enum_flag_HasComponentSize | enum_flag_GenericsMask)) == 0)
return GetLoaderModule();
MethodTable * pMTForModule = IsArray() ? this : GetCanonicalMethodTable();
if (!pMTForModule->HasModuleOverride())
return pMTForModule->GetLoaderModule();
TADDR pSlot = pMTForModule->GetMultipurposeSlotPtr(enum_flag_HasModuleOverride, c_ModuleOverrideOffsets);
return RelativeFixupPointer<PTR_Module>::GetValueAtPtr(pSlot);
}
//==========================================================================================
PTR_DispatchMap MethodTable::GetDispatchMap()
{
LIMITED_METHOD_DAC_CONTRACT;
MethodTable * pMT = this;
if (!pMT->HasDispatchMapSlot())
{
pMT = pMT->GetCanonicalMethodTable();
if (!pMT->HasDispatchMapSlot())
return NULL;
}
g_IBCLogger.LogDispatchMapAccess(pMT);
TADDR pSlot = pMT->GetMultipurposeSlotPtr(enum_flag_HasDispatchMapSlot, c_DispatchMapSlotOffsets);
return RelativePointer<PTR_DispatchMap>::GetValueAtPtr(pSlot);
}
//==========================================================================================
TADDR MethodTable::GetNonVirtualSlotsPtr()
{
LIMITED_METHOD_DAC_CONTRACT;
_ASSERTE(GetFlag(enum_flag_HasNonVirtualSlots));
return GetMultipurposeSlotPtr(enum_flag_HasNonVirtualSlots, c_NonVirtualSlotsOffsets);
}
#include <optdefault.h>
//==========================================================================================
PTR_Module MethodTable::GetModuleIfLoaded()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END;
g_IBCLogger.LogMethodTableAccess(this);
MethodTable * pMTForModule = IsArray() ? this : GetCanonicalMethodTable();
if (!pMTForModule->HasModuleOverride())
return pMTForModule->GetLoaderModule();
return Module::RestoreModulePointerIfLoaded(pMTForModule->GetModuleOverridePtr(), pMTForModule->GetLoaderModule());
}
#ifndef DACCESS_COMPILE
//==========================================================================================
void MethodTable::SetModule(Module * pModule)
{
LIMITED_METHOD_CONTRACT;
if (HasModuleOverride())
{
GetModuleOverridePtr()->SetValue(pModule);
}
_ASSERTE(GetModule() == pModule);
}
#endif // DACCESS_COMPILE
//==========================================================================================
BOOL MethodTable::ValidateWithPossibleAV()
{
CANNOT_HAVE_CONTRACT;
SUPPORTS_DAC;
// MethodTables have the canonicalization property below.
// i.e. canonicalize, and canonicalize again, and check the result are
// the same. This is a property that holds for every single valid object in
// the system, but which should hold for very few other addresses.
// For non-generic classes, we can rely on comparing
// object->methodtable->class->methodtable
// to
// object->methodtable
//
// However, for generic instantiation this does not work. There we must
// compare
//
// object->methodtable->class->methodtable->class
// to
// object->methodtable->class
//
// Of course, that's not necessarily enough to verify that the method
// table and class are absolutely valid - we rely on type soundness
// for that. We need to do more sanity checking to
// make sure that our pointer here is in fact a valid object.
PTR_EEClass pEEClass = this->GetClassWithPossibleAV();
return ((this == pEEClass->GetMethodTableWithPossibleAV()) ||
((HasInstantiation() || IsArray()) &&
(pEEClass->GetMethodTableWithPossibleAV()->GetClassWithPossibleAV() == pEEClass)));
}
#ifndef DACCESS_COMPILE
//==========================================================================================
BOOL MethodTable::IsClassInited(AppDomain* pAppDomain /* = NULL */)
{
WRAPPER_NO_CONTRACT;
if (IsClassPreInited())
return TRUE;
if (IsSharedByGenericInstantiations())
return FALSE;
DomainLocalModule *pLocalModule;
if (pAppDomain == NULL)
{
pLocalModule = GetDomainLocalModule();
}
else
{
pLocalModule = GetDomainLocalModule(pAppDomain);
}
_ASSERTE(pLocalModule != NULL);
return pLocalModule->IsClassInitialized(this);
}
//==========================================================================================
BOOL MethodTable::IsInitError()
{
WRAPPER_NO_CONTRACT;
DomainLocalModule *pLocalModule = GetDomainLocalModule();
_ASSERTE(pLocalModule != NULL);
return pLocalModule->IsClassInitError(this);
}
//==========================================================================================
// mark the class as having its .cctor run
void MethodTable::SetClassInited()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(!IsClassPreInited() || MscorlibBinder::IsClass(this, CLASS__SHARED_STATICS));
GetDomainLocalModule()->SetClassInitialized(this);
}
//==========================================================================================
void MethodTable::SetClassInitError()
{
WRAPPER_NO_CONTRACT;
GetDomainLocalModule()->SetClassInitError(this);
}
//==========================================================================================
// mark the class as having been restored.
void MethodTable::SetIsRestored()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END
PRECONDITION(!IsFullyLoaded());
// If functions on this type have already been requested for rejit, then give the rejit
// manager a chance to jump-stamp the code we are implicitly restoring. This ensures the
// first thread entering the function will jump to the prestub and trigger the
// rejit. Note that the PublishMethodTableHolder may take a lock to avoid a rejit race.
// See code:ReJitManager::PublishMethodHolder::PublishMethodHolder#PublishCode
// for details on the race.
//
{
ReJitPublishMethodTableHolder(this);
FastInterlockAnd(EnsureWritablePages(&(GetWriteableDataForWrite()->m_dwFlags)), ~MethodTableWriteableData::enum_flag_Unrestored);
}
#ifndef DACCESS_COMPILE
#if defined(FEATURE_EVENT_TRACE)
if (MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_Context.IsEnabled)
#endif
{
ETW::MethodLog::MethodTableRestored(this);
}
#endif
}
#ifdef FEATURE_COMINTEROP
//==========================================================================================
// mark as COM object type (System.__ComObject and types deriving from it)
void MethodTable::SetComObjectType()
{
LIMITED_METHOD_CONTRACT;
SetFlag(enum_flag_ComObject);
}
#endif // FEATURE_COMINTEROP
#if defined(FEATURE_TYPEEQUIVALENCE) || defined(FEATURE_REMOTING)
void MethodTable::SetHasTypeEquivalence()
{
LIMITED_METHOD_CONTRACT;
SetFlag(enum_flag_HasTypeEquivalence);
}
#endif
#ifdef FEATURE_ICASTABLE
void MethodTable::SetICastable()
{
LIMITED_METHOD_CONTRACT;
SetFlag(enum_flag_ICastable);
}
#endif
BOOL MethodTable::IsICastable()
{
LIMITED_METHOD_DAC_CONTRACT;
#ifdef FEATURE_ICASTABLE
return GetFlag(enum_flag_ICastable);
#else
return FALSE;
#endif
}
#endif // !DACCESS_COMPILE
//==========================================================================================
WORD MethodTable::GetNumMethods()
{
LIMITED_METHOD_DAC_CONTRACT;
return GetClass()->GetNumMethods();
}
//==========================================================================================
PTR_BaseDomain MethodTable::GetDomain()
{
LIMITED_METHOD_DAC_CONTRACT;
g_IBCLogger.LogMethodTableAccess(this);
return GetLoaderModule()->GetDomain();
}
//==========================================================================================
BOOL MethodTable::IsDomainNeutral()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_SO_TOLERANT;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_SUPPORTS_DAC;
BOOL ret = GetLoaderModule()->GetAssembly()->IsDomainNeutral();
#ifndef DACCESS_COMPILE
_ASSERTE(!ret == !GetLoaderAllocator()->IsDomainNeutral());
#endif
return ret;
}
//==========================================================================================
BOOL MethodTable::HasSameTypeDefAs(MethodTable *pMT)
{
LIMITED_METHOD_DAC_CONTRACT;
if (this == pMT)
return TRUE;
// optimize for the negative case where we expect RID mismatch
if (GetTypeDefRid() != pMT->GetTypeDefRid())
return FALSE;
if (GetCanonicalMethodTable() == pMT->GetCanonicalMethodTable())
return TRUE;
return (GetModule() == pMT->GetModule());
}
//==========================================================================================
BOOL MethodTable::HasSameTypeDefAs_NoLogging(MethodTable *pMT)
{
LIMITED_METHOD_DAC_CONTRACT;
if (this == pMT)
return TRUE;
// optimize for the negative case where we expect RID mismatch
if (GetTypeDefRid_NoLogging() != pMT->GetTypeDefRid_NoLogging())
return FALSE;
if (GetCanonicalMethodTable() == pMT->GetCanonicalMethodTable())
return TRUE;
return (GetModule_NoLogging() == pMT->GetModule_NoLogging());
}
#ifndef DACCESS_COMPILE
//==========================================================================================
PTR_MethodTable InterfaceInfo_t::GetApproxMethodTable(Module * pContainingModule)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
#ifdef FEATURE_PREJIT
if (m_pMethodTable.IsTagged())
{
// Ideally, we would use Module::RestoreMethodTablePointer here. Unfortunately, it is not
// possible because of the current type loader architecture that restores types incrementally
// even in the NGen case.
MethodTable * pItfMT = *(m_pMethodTable.GetValuePtr());
// Restore the method table, but do not write it back if it has instantiation. We do not want
// to write back the approximate instantiations.
Module::RestoreMethodTablePointerRaw(&pItfMT, pContainingModule, CLASS_LOAD_APPROXPARENTS);
if (!pItfMT->HasInstantiation())
{
// m_pMethodTable.SetValue() is not used here since we want to update the indirection cell
*EnsureWritablePages(m_pMethodTable.GetValuePtr()) = pItfMT;
}
return pItfMT;
}
#endif
MethodTable * pItfMT = m_pMethodTable.GetValue();
ClassLoader::EnsureLoaded(TypeHandle(pItfMT), CLASS_LOAD_APPROXPARENTS);
return pItfMT;
}
#ifndef CROSSGEN_COMPILE
//==========================================================================================
// get the method desc given the interface method desc
/* static */ MethodDesc *MethodTable::GetMethodDescForInterfaceMethodAndServer(
TypeHandle ownerType, MethodDesc *pItfMD, OBJECTREF *pServer)
{
CONTRACT(MethodDesc*)
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pItfMD));
PRECONDITION(pItfMD->IsInterface());
PRECONDITION(!ownerType.IsNull());
PRECONDITION(ownerType.GetMethodTable()->HasSameTypeDefAs(pItfMD->GetMethodTable()));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
VALIDATEOBJECTREF(*pServer);
#ifdef _DEBUG
MethodTable * pItfMT = ownerType.GetMethodTable();
PREFIX_ASSUME(pItfMT != NULL);
#endif // _DEBUG
MethodTable *pServerMT = (*pServer)->GetMethodTable();
PREFIX_ASSUME(pServerMT != NULL);
if (pServerMT->IsTransparentProxy())
{
// If pServer is a TP, then the interface method desc is the one to
// use to dispatch the call.
RETURN(pItfMD);
}
#ifdef FEATURE_ICASTABLE
// In case of ICastable, instead of trying to find method implementation in the real object type
// we call pObj.GetValueInternal() and call GetMethodDescForInterfaceMethod() again with whatever type it returns.
// It allows objects that implement ICastable to mimic behavior of other types.
if (pServerMT->IsICastable() &&
!pItfMD->HasMethodInstantiation() &&
!TypeHandle(pServerMT).CanCastTo(ownerType)) // we need to make sure object doesn't implement this interface in a natural way
{
GCStress<cfg_any>::MaybeTrigger();
// Make call to obj.GetImplType(interfaceTypeObj)
MethodDesc *pGetImplTypeMD = pServerMT->GetMethodDescForInterfaceMethod(MscorlibBinder::GetMethod(METHOD__ICASTABLE__GETIMPLTYPE));
OBJECTREF ownerManagedType = ownerType.GetManagedClassObject(); //GC triggers
PREPARE_NONVIRTUAL_CALLSITE_USING_METHODDESC(pGetImplTypeMD);
DECLARE_ARGHOLDER_ARRAY(args, 2);
args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(*pServer);
args[ARGNUM_1] = OBJECTREF_TO_ARGHOLDER(ownerManagedType);
OBJECTREF impTypeObj = NULL;
CALL_MANAGED_METHOD_RETREF(impTypeObj, OBJECTREF, args);
INDEBUG(ownerManagedType = NULL); //ownerManagedType wasn't protected during the call
if (impTypeObj == NULL) // GetImplType returns default(RuntimeTypeHandle)
{
COMPlusThrow(kEntryPointNotFoundException);
}
ReflectClassBaseObject* resultTypeObj = ((ReflectClassBaseObject*)OBJECTREFToObject(impTypeObj));
TypeHandle resulTypeHnd = resultTypeObj->GetType();
MethodTable *pResultMT = resulTypeHnd.GetMethodTable();
RETURN(pResultMT->GetMethodDescForInterfaceMethod(ownerType, pItfMD));
}
#endif
#ifdef FEATURE_COMINTEROP
if (pServerMT->IsComObjectType() && !pItfMD->HasMethodInstantiation())
{
// interop needs an exact MethodDesc
pItfMD = MethodDesc::FindOrCreateAssociatedMethodDesc(
pItfMD,
ownerType.GetMethodTable(),
FALSE, // forceBoxedEntryPoint
Instantiation(), // methodInst
FALSE, // allowInstParam
TRUE); // forceRemotableMethod
RETURN(pServerMT->GetMethodDescForComInterfaceMethod(pItfMD, false));
}
#endif // !FEATURE_COMINTEROP
// Handle pure COM+ types.
RETURN (pServerMT->GetMethodDescForInterfaceMethod(ownerType, pItfMD));
}
#ifdef FEATURE_COMINTEROP
//==========================================================================================
// get the method desc given the interface method desc on a COM implemented server
// (if fNullOk is set then NULL is an allowable return value)
MethodDesc *MethodTable::GetMethodDescForComInterfaceMethod(MethodDesc *pItfMD, bool fNullOk)
{
CONTRACT(MethodDesc*)
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pItfMD));
PRECONDITION(pItfMD->IsInterface());
PRECONDITION(IsComObjectType());
POSTCONDITION(fNullOk || CheckPointer(RETVAL));
}
CONTRACT_END;
MethodTable * pItfMT = pItfMD->GetMethodTable();
PREFIX_ASSUME(pItfMT != NULL);
// We now handle __ComObject class that doesn't have Dynamic Interface Map
if (!HasDynamicInterfaceMap())
{
RETURN(pItfMD);
}
else
{
// Now we handle the more complex extensible RCW's. The first thing to do is check
// to see if the static definition of the extensible RCW specifies that the class
// implements the interface.
DWORD slot = (DWORD) -1;
// Calling GetTarget here instead of FindDispatchImpl gives us caching functionality to increase speed.
PCODE tgt = VirtualCallStubManager::GetTarget(
pItfMT->GetLoaderAllocator()->GetDispatchToken(pItfMT->GetTypeID(), pItfMD->GetSlot()), this);
if (tgt != NULL)
{
RETURN(MethodTable::GetMethodDescForSlotAddress(tgt));
}
// The interface is not in the static class definition so we need to look at the
// dynamic interfaces.
else if (FindDynamicallyAddedInterface(pItfMT))
{
// This interface was added to the class dynamically so it is implemented
// by the COM object. We treat this dynamically added interfaces the same
// way we treat COM objects. That is by using the interface vtable.
RETURN(pItfMD);
}
else
{
RETURN(NULL);
}
}
}
#endif // FEATURE_COMINTEROP
#endif // CROSSGEN_COMPILE
//---------------------------------------------------------------------------------------
//
MethodTable* CreateMinimalMethodTable(Module* pContainingModule,
LoaderHeap* pCreationHeap,
AllocMemTracker* pamTracker)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
EEClass* pClass = EEClass::CreateMinimalClass(pCreationHeap, pamTracker);
LOG((LF_BCL, LL_INFO100, "Level2 - Creating MethodTable {0x%p}...\n", pClass));
MethodTable* pMT = (MethodTable *)(void *)pamTracker->Track(pCreationHeap->AllocMem(S_SIZE_T(sizeof(MethodTable))));
// Note: Memory allocated on loader heap is zero filled
// memset(pMT, 0, sizeof(MethodTable));
// Allocate the private data block ("private" during runtime in the ngen'ed case).
BYTE* pMTWriteableData = (BYTE *)
pamTracker->Track(pCreationHeap->AllocMem(S_SIZE_T(sizeof(MethodTableWriteableData))));
pMT->SetWriteableData((PTR_MethodTableWriteableData)pMTWriteableData);
//
// Set up the EEClass
//
pClass->SetMethodTable(pMT); // in the EEClass set the pointer to this MethodTable
pClass->SetAttrClass(tdPublic | tdSealed);
//
// Set up the MethodTable
//
// Does not need parent. Note that MethodTable for COR_GLOBAL_PARENT_TOKEN does not have parent either,
// so the system has to be wired for dealing with no parent anyway.
pMT->SetParentMethodTable(NULL);
pMT->SetClass(pClass);
pMT->SetLoaderModule(pContainingModule);
pMT->SetLoaderAllocator(pContainingModule->GetLoaderAllocator());
pMT->SetInternalCorElementType(ELEMENT_TYPE_CLASS);
pMT->SetBaseSize(ObjSizeOf(Object));
#ifdef _DEBUG
pClass->SetDebugClassName("dynamicClass");
pMT->SetDebugClassName("dynamicClass");
#endif
LOG((LF_BCL, LL_INFO10, "Level1 - MethodTable created {0x%p}\n", pClass));
return pMT;
}
#ifdef FEATURE_REMOTING
//==========================================================================================
void MethodTable::SetupRemotableMethodInfo(AllocMemTracker *pamTracker)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Make RMI for a method table.
CrossDomainOptimizationInfo *pRMIBegin = NULL;
if (GetNumMethods() > 0)
{
SIZE_T requiredSize = CrossDomainOptimizationInfo::SizeOf(GetNumVtableSlots());
pRMIBegin = (CrossDomainOptimizationInfo*) pamTracker->Track(GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(requiredSize)));
_ASSERTE(IS_ALIGNED(pRMIBegin, sizeof(void*)));
}
*(GetRemotableMethodInfoPtr()) = pRMIBegin;
}
//==========================================================================================
PTR_RemotingVtsInfo MethodTable::AllocateRemotingVtsInfo(AllocMemTracker *pamTracker, DWORD dwNumFields)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Size the data structure to contain enough bit flags for all the
// instance fields.
DWORD cbInfo = RemotingVtsInfo::GetSize(dwNumFields);
RemotingVtsInfo *pInfo = (RemotingVtsInfo*)pamTracker->Track(GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(cbInfo)));
// Note: Memory allocated on loader heap is zero filled
// ZeroMemory(pInfo, cbInfo);
#ifdef _DEBUG
pInfo->m_dwNumFields = dwNumFields;
#endif
*(GetRemotingVtsInfoPtr()) = pInfo;
return pInfo;
}
#endif // FEATURE_REMOTING
#ifdef FEATURE_COMINTEROP
#ifndef CROSSGEN_COMPILE
//==========================================================================================
OBJECTREF MethodTable::GetObjCreateDelegate()
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
_ASSERT(!IsInterface());
if (GetOHDelegate())
return ObjectFromHandle(GetOHDelegate());
else
return NULL;
}
//==========================================================================================
void MethodTable::SetObjCreateDelegate(OBJECTREF orDelegate)
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_NOTRIGGER;
THROWS; // From CreateHandle
}
CONTRACTL_END;
if (GetOHDelegate())
StoreObjectInHandle(GetOHDelegate(), orDelegate);
else
SetOHDelegate (GetAppDomain()->CreateHandle(orDelegate));
}
#endif //CROSSGEN_COMPILE
#endif // FEATURE_COMINTEROP
//==========================================================================================
void MethodTable::SetInterfaceMap(WORD wNumInterfaces, InterfaceInfo_t* iMap)
{
LIMITED_METHOD_CONTRACT;
if (wNumInterfaces == 0)
{
_ASSERTE(!HasInterfaceMap());
return;
}
m_wNumInterfaces = wNumInterfaces;
CONSISTENCY_CHECK(IS_ALIGNED(iMap, sizeof(void*)));
m_pInterfaceMap = iMap;
}
//==========================================================================================
// Called after GetExtraInterfaceInfoSize above to setup a new MethodTable with the additional memory to track
// extra interface info. If there are a non-zero number of interfaces implemented on this class but
// GetExtraInterfaceInfoSize() returned zero, this call must still be made (with a NULL argument).
void MethodTable::InitializeExtraInterfaceInfo(PVOID pInfo)
{
STANDARD_VM_CONTRACT;
// Check that memory was allocated or not allocated in the right scenarios.
_ASSERTE(((pInfo == NULL) && (GetExtraInterfaceInfoSize(GetNumInterfaces()) == 0)) ||
((pInfo != NULL) && (GetExtraInterfaceInfoSize(GetNumInterfaces()) != 0)));
// This call is a no-op if we don't require extra interface info (in which case a buffer should never have
// been allocated).
if (!HasExtraInterfaceInfo())
{
_ASSERTE(pInfo == NULL);
return;
}
// Get pointer to optional slot that holds either a small inlined bitmap of flags or the pointer to a
// larger bitmap.
PTR_TADDR pInfoSlot = GetExtraInterfaceInfoPtr();
// In either case, data inlined or held in an external buffer, the correct thing to do is to write pInfo
// to the slot. In the inlined case we wish to set all flags to their default value (zero, false) and
// writing NULL does that. Otherwise we simply want to dump the buffer pointer directly into the slot (no
// need for a discriminator bit, we can always infer which format we're using based on the interface
// count).
*pInfoSlot = (TADDR)pInfo;
// There shouldn't be any need for further initialization in the buffered case since loader heap
// allocation zeroes data.
#ifdef _DEBUG
if (pInfo != NULL)
for (DWORD i = 0; i < GetExtraInterfaceInfoSize(GetNumInterfaces()); i++)
_ASSERTE(*((BYTE*)pInfo + i) == 0);
#endif // _DEBUG
}
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
// Ngen support.
void MethodTable::SaveExtraInterfaceInfo(DataImage *pImage)
{
STANDARD_VM_CONTRACT;
// No extra data to save if the number of interfaces is below the threshhold -- there is either no data or
// it all fits into the optional members inline.
if (GetNumInterfaces() <= kInlinedInterfaceInfoThreshhold)
return;
pImage->StoreStructure((LPVOID)*GetExtraInterfaceInfoPtr(),
GetExtraInterfaceInfoSize(GetNumInterfaces()),
DataImage::ITEM_INTERFACE_MAP);
}
void MethodTable::FixupExtraInterfaceInfo(DataImage *pImage)
{
STANDARD_VM_CONTRACT;
// No pointer to extra data to fixup if the number of interfaces is below the threshhold -- there is
// either no data or it all fits into the optional members inline.
if (GetNumInterfaces() <= kInlinedInterfaceInfoThreshhold)
return;
pImage->FixupPointerField(this, (BYTE*)GetExtraInterfaceInfoPtr() - (BYTE*)this);
}
#endif // FEATURE_NATIVE_IMAGE_GENERATION
// Define a macro that generates a mask for a given bit in a TADDR correctly on either 32 or 64 bit platforms.
#ifdef _WIN64
#define SELECT_TADDR_BIT(_index) (1ULL << (_index))
#else
#define SELECT_TADDR_BIT(_index) (1U << (_index))
#endif
//==========================================================================================
// For the given interface in the map (specified via map index) mark the interface as declared explicitly on
// this class. This is not legal for dynamically added interfaces (as used by RCWs).
void MethodTable::SetInterfaceDeclaredOnClass(DWORD index)
{
STANDARD_VM_CONTRACT;
_ASSERTE(HasExtraInterfaceInfo());
_ASSERTE(index < GetNumInterfaces());
// Get address of optional slot for extra info.
PTR_TADDR pInfoSlot = GetExtraInterfaceInfoPtr();
if (GetNumInterfaces() <= kInlinedInterfaceInfoThreshhold)
{
// Bitmap of flags is stored inline in the optional slot.
*pInfoSlot |= SELECT_TADDR_BIT(index);
}
else
{
// Slot points to a buffer containing a larger bitmap.
TADDR *pBitmap = (PTR_TADDR)*pInfoSlot;
DWORD idxTaddr = index / (sizeof(TADDR) * 8); // Select TADDR in array that covers the target bit
DWORD idxInTaddr = index % (sizeof(TADDR) * 8);
TADDR bitmask = SELECT_TADDR_BIT(idxInTaddr);
pBitmap[idxTaddr] |= bitmask;
_ASSERTE((pBitmap[idxTaddr] & bitmask) == bitmask);
}
}
//==========================================================================================
// For the given interface return true if the interface was declared explicitly on this class.
bool MethodTable::IsInterfaceDeclaredOnClass(DWORD index)
{
STANDARD_VM_CONTRACT;
_ASSERTE(HasExtraInterfaceInfo());
// Dynamic interfaces are always marked as not DeclaredOnClass (I don't know why but this is how the code
// was originally authored).
if (index >= GetNumInterfaces())
{
#ifdef FEATURE_COMINTEROP
_ASSERTE(HasDynamicInterfaceMap());
#endif // FEATURE_COMINTEROP
return false;
}
// Get data from the optional extra info slot.
TADDR taddrInfo = *GetExtraInterfaceInfoPtr();
if (GetNumInterfaces() <= kInlinedInterfaceInfoThreshhold)
{
// Bitmap of flags is stored directly in the value.
return (taddrInfo & SELECT_TADDR_BIT(index)) != 0;
}
else
{
// Slot points to a buffer containing a larger bitmap.
TADDR *pBitmap = (PTR_TADDR)taddrInfo;
DWORD idxTaddr = index / (sizeof(TADDR) * 8); // Select TADDR in array that covers the target bit
DWORD idxInTaddr = index % (sizeof(TADDR) * 8);
TADDR bitmask = SELECT_TADDR_BIT(idxInTaddr);
return (pBitmap[idxTaddr] & bitmask) != 0;
}
}
#ifdef FEATURE_COMINTEROP
//==========================================================================================
PTR_InterfaceInfo MethodTable::GetDynamicallyAddedInterfaceMap()
{
LIMITED_METHOD_DAC_CONTRACT;
PRECONDITION(HasDynamicInterfaceMap());
return GetInterfaceMap() + GetNumInterfaces();
}
//==========================================================================================
unsigned MethodTable::GetNumDynamicallyAddedInterfaces()
{
LIMITED_METHOD_DAC_CONTRACT;
PRECONDITION(HasDynamicInterfaceMap());
PTR_InterfaceInfo pInterfaces = GetInterfaceMap();
PREFIX_ASSUME(pInterfaces != NULL);
return (unsigned)*(dac_cast<PTR_SIZE_T>(pInterfaces) - 1);
}
//==========================================================================================
BOOL MethodTable::FindDynamicallyAddedInterface(MethodTable *pInterface)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(IsRestored_NoLogging());
_ASSERTE(HasDynamicInterfaceMap()); // This should never be called on for a type that is not an extensible RCW.
unsigned cDynInterfaces = GetNumDynamicallyAddedInterfaces();
InterfaceInfo_t *pDynItfMap = GetDynamicallyAddedInterfaceMap();
for (unsigned i = 0; i < cDynInterfaces; i++)
{
if (pDynItfMap[i].GetMethodTable() == pInterface)
return TRUE;
}
return FALSE;
}
//==========================================================================================
void MethodTable::AddDynamicInterface(MethodTable *pItfMT)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(IsRestored_NoLogging());
PRECONDITION(HasDynamicInterfaceMap()); // This should never be called on for a type that is not an extensible RCW.
}
CONTRACTL_END;
unsigned NumDynAddedInterfaces = GetNumDynamicallyAddedInterfaces();
unsigned TotalNumInterfaces = GetNumInterfaces() + NumDynAddedInterfaces;
InterfaceInfo_t *pNewItfMap = NULL;
S_SIZE_T AllocSize = (S_SIZE_T(S_UINT32(TotalNumInterfaces) + S_UINT32(1)) * S_SIZE_T(sizeof(InterfaceInfo_t))) + S_SIZE_T(sizeof(DWORD_PTR));
if (AllocSize.IsOverflow())
ThrowHR(COR_E_OVERFLOW);
// Allocate the new interface table adding one for the new interface and one
// more for the dummy slot before the start of the table..
pNewItfMap = (InterfaceInfo_t*)(void*)GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(AllocSize);
pNewItfMap = (InterfaceInfo_t*)(((BYTE *)pNewItfMap) + sizeof(DWORD_PTR));
// Copy the old map into the new one.
if (TotalNumInterfaces > 0) {
InterfaceInfo_t *pInterfaceMap = GetInterfaceMap();
PREFIX_ASSUME(pInterfaceMap != NULL);
memcpy(pNewItfMap, pInterfaceMap, TotalNumInterfaces * sizeof(InterfaceInfo_t));
}
// Add the new interface at the end of the map.
pNewItfMap[TotalNumInterfaces].SetMethodTable(pItfMT);
// Update the count of dynamically added interfaces.
*(((DWORD_PTR *)pNewItfMap) - 1) = NumDynAddedInterfaces + 1;
// Switch the old interface map with the new one.
VolatileStore(EnsureWritablePages(&m_pInterfaceMap), pNewItfMap);
// Log the fact that we leaked the interface vtable map.
#ifdef _DEBUG
LOG((LF_INTEROP, LL_EVERYTHING,
"Extensible RCW %s being cast to interface %s caused an interface vtable map leak",
GetClass()->GetDebugClassName(), pItfMT->GetClass()->m_szDebugClassName));
#else // !_DEBUG
LOG((LF_INTEROP, LL_EVERYTHING,
"Extensible RCW being cast to an interface caused an interface vtable map leak"));
#endif // !_DEBUG
} // MethodTable::AddDynamicInterface
#endif // FEATURE_COMINTEROP
void MethodTable::SetupGenericsStaticsInfo(FieldDesc* pStaticFieldDescs)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
// No need to generate IDs for open types. Indeed since we don't save them
// in the NGEN image it would be actively incorrect to do so. However
// we still leave the optional member in the MethodTable holding the value -1 for the ID.
GenericsStaticsInfo *pInfo = GetGenericsStaticsInfo();
if (!ContainsGenericVariables() && !IsSharedByGenericInstantiations())
{
Module * pModuleForStatics = GetLoaderModule();
pInfo->m_DynamicTypeID = pModuleForStatics->AllocateDynamicEntry(this);
}
else
{
pInfo->m_DynamicTypeID = (SIZE_T)-1;
}
pInfo->m_pFieldDescs = pStaticFieldDescs;
}
#endif // !DACCESS_COMPILE
//==========================================================================================
// Calculate how many bytes of storage will be required to track additional information for interfaces. This
// will be zero if there are no interfaces, but can also be zero for small numbers of interfaces as well, and
// callers should be ready to handle this.
/* static */ SIZE_T MethodTable::GetExtraInterfaceInfoSize(DWORD cInterfaces)
{
LIMITED_METHOD_DAC_CONTRACT;
// For small numbers of interfaces we can record the info in the TADDR of the optional member itself (use
// the TADDR as a bitmap).
if (cInterfaces <= kInlinedInterfaceInfoThreshhold)
return 0;
// Otherwise we'll cause an array of TADDRs to be allocated (use TADDRs since the heap space allocated
// will almost certainly need to be TADDR aligned anyway).
return ALIGN_UP(cInterfaces, sizeof(TADDR) * 8) / 8;
}
#ifdef DACCESS_COMPILE
//==========================================================================================
void MethodTable::EnumMemoryRegionsForExtraInterfaceInfo()
{
SUPPORTS_DAC;
// No extra data to enum if the number of interfaces is below the threshhold -- there is either no data or
// it all fits into the optional members inline.
if (GetNumInterfaces() <= kInlinedInterfaceInfoThreshhold)
return;
DacEnumMemoryRegion(*GetExtraInterfaceInfoPtr(), GetExtraInterfaceInfoSize(GetNumInterfaces()));
}
#endif // DACCESS_COMPILE
//==========================================================================================
Module* MethodTable::GetModuleForStatics()
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
g_IBCLogger.LogMethodTableAccess(this);
if (HasGenericsStaticsInfo())
{
DWORD dwDynamicClassDomainID;
return GetGenericsStaticsModuleAndID(&dwDynamicClassDomainID);
}
else
{
return GetLoaderModule();
}
}
//==========================================================================================
DWORD MethodTable::GetModuleDynamicEntryID()
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(IsDynamicStatics() && "Only memory reflection emit types and generics can have a dynamic ID");
if (HasGenericsStaticsInfo())
{
DWORD dwDynamicClassDomainID;
GetGenericsStaticsModuleAndID(&dwDynamicClassDomainID);
return dwDynamicClassDomainID;
}
else
{
return GetClass()->GetModuleDynamicID();
}
}
#ifndef DACCESS_COMPILE
#ifdef FEATURE_TYPEEQUIVALENCE
//==========================================================================================
// Equivalence based on Guid and TypeIdentifier attributes to support the "no-PIA" feature.
BOOL MethodTable::IsEquivalentTo_Worker(MethodTable *pOtherMT COMMA_INDEBUG(TypeHandlePairList *pVisited))
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
SO_TOLERANT; // we are called from MethodTable::CanCastToClass
}
CONTRACTL_END;
_ASSERTE(HasTypeEquivalence() && pOtherMT->HasTypeEquivalence());
#ifdef _DEBUG
if (TypeHandlePairList::Exists(pVisited, TypeHandle(this), TypeHandle(pOtherMT)))
{
_ASSERTE(!"We are in the process of comparing these types already. That should never happen!");
return TRUE;
}
TypeHandlePairList newVisited(TypeHandle(this), TypeHandle(pOtherMT), pVisited);
#endif
if (HasInstantiation() != pOtherMT->HasInstantiation())
return FALSE;
if (IsArray())
{
if (!pOtherMT->IsArray() || GetRank() != pOtherMT->GetRank())
return FALSE;
// arrays of structures have their own unshared MTs and will take this path
return (GetApproxArrayElementTypeHandle().IsEquivalentTo(pOtherMT->GetApproxArrayElementTypeHandle() COMMA_INDEBUG(&newVisited)));
}
BOOL bResult = FALSE;
BEGIN_SO_INTOLERANT_CODE(GetThread());
bResult = IsEquivalentTo_WorkerInner(pOtherMT COMMA_INDEBUG(&newVisited));
END_SO_INTOLERANT_CODE;
return bResult;
}
//==========================================================================================
// Type equivalence - SO intolerant part.
BOOL MethodTable::IsEquivalentTo_WorkerInner(MethodTable *pOtherMT COMMA_INDEBUG(TypeHandlePairList *pVisited))
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
SO_INTOLERANT;
LOADS_TYPE(CLASS_DEPENDENCIES_LOADED);
}
CONTRACTL_END;
AppDomain *pDomain = GetAppDomain();
if (pDomain != NULL)
{
TypeEquivalenceHashTable::EquivalenceMatch match = pDomain->GetTypeEquivalenceCache()->CheckEquivalence(TypeHandle(this), TypeHandle(pOtherMT));
switch (match)
{
case TypeEquivalenceHashTable::Match:
return TRUE;
case TypeEquivalenceHashTable::NoMatch:
return FALSE;
case TypeEquivalenceHashTable::MatchUnknown:
break;
default:
_ASSERTE(FALSE);
break;
}
}
BOOL fEquivalent = FALSE;
if (HasInstantiation())
{
// we limit variance on generics only to interfaces
if (!IsInterface() || !pOtherMT->IsInterface())
{
fEquivalent = FALSE;
goto EquivalenceCalculated;
}
// check whether the instantiations are equivalent
Instantiation inst1 = GetInstantiation();
Instantiation inst2 = pOtherMT->GetInstantiation();
if (inst1.GetNumArgs() != inst2.GetNumArgs())
{
fEquivalent = FALSE;
goto EquivalenceCalculated;
}
for (DWORD i = 0; i < inst1.GetNumArgs(); i++)
{
if (!inst1[i].IsEquivalentTo(inst2[i] COMMA_INDEBUG(pVisited)))
{
fEquivalent = FALSE;
goto EquivalenceCalculated;
}
}
if (GetTypeDefRid() == pOtherMT->GetTypeDefRid() && GetModule() == pOtherMT->GetModule())
{
// it's OK to declare the MTs equivalent at this point; the cases we care
// about are IList<IFoo> and IList<IBar> where IFoo and IBar are equivalent
fEquivalent = TRUE;
}
else
{
fEquivalent = FALSE;
}
goto EquivalenceCalculated;
}
if (IsArray())
{
if (!pOtherMT->IsArray() || GetRank() != pOtherMT->GetRank())
{
fEquivalent = FALSE;
goto EquivalenceCalculated;
}
// arrays of structures have their own unshared MTs and will take this path
fEquivalent = (GetApproxArrayElementTypeHandle().IsEquivalentTo(pOtherMT->GetApproxArrayElementTypeHandle() COMMA_INDEBUG(pVisited)));
goto EquivalenceCalculated;
}
fEquivalent = CompareTypeDefsForEquivalence(GetCl(), pOtherMT->GetCl(), GetModule(), pOtherMT->GetModule(), NULL);
EquivalenceCalculated:
// Only record equivalence matches if we are in an AppDomain
if (pDomain != NULL)
{
// Collectible type results will not get cached.
if ((!this->Collectible() && !pOtherMT->Collectible()))
{
TypeEquivalenceHashTable::EquivalenceMatch match;
match = fEquivalent ? TypeEquivalenceHashTable::Match : TypeEquivalenceHashTable::NoMatch;
pDomain->GetTypeEquivalenceCache()->RecordEquivalence(TypeHandle(this), TypeHandle(pOtherMT), match);
}
}
return fEquivalent;
}
#endif // FEATURE_TYPEEQUIVALENCE
//==========================================================================================
BOOL MethodTable::CanCastToInterface(MethodTable *pTargetMT, TypeHandlePairList *pVisited)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pTargetMT));
PRECONDITION(pTargetMT->IsInterface());
PRECONDITION(!IsTransparentProxy());
PRECONDITION(IsRestored_NoLogging());
}
CONTRACTL_END
if (!pTargetMT->HasVariance())
{
if (HasTypeEquivalence() || pTargetMT->HasTypeEquivalence())
{
if (IsInterface() && IsEquivalentTo(pTargetMT))
return TRUE;
return ImplementsEquivalentInterface(pTargetMT);
}
return CanCastToNonVariantInterface(pTargetMT);
}
else
{
if (CanCastByVarianceToInterfaceOrDelegate(pTargetMT, pVisited))
return TRUE;
InterfaceMapIterator it = IterateInterfaceMap();
while (it.Next())
{
if (it.GetInterface()->CanCastByVarianceToInterfaceOrDelegate(pTargetMT, pVisited))
return TRUE;
}
}
return FALSE;
}
//==========================================================================================
BOOL MethodTable::CanCastByVarianceToInterfaceOrDelegate(MethodTable *pTargetMT, TypeHandlePairList *pVisited)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pTargetMT));
PRECONDITION(pTargetMT->HasVariance());
PRECONDITION(pTargetMT->IsInterface() || pTargetMT->IsDelegate());
PRECONDITION(IsRestored_NoLogging());
}
CONTRACTL_END
BOOL returnValue = FALSE;
EEClass *pClass = NULL;
TypeHandlePairList pairList(this, pTargetMT, pVisited);
if (TypeHandlePairList::Exists(pVisited, this, pTargetMT))
goto Exit;
if (GetTypeDefRid() != pTargetMT->GetTypeDefRid() || GetModule() != pTargetMT->GetModule())
{
goto Exit;
}
{
pClass = pTargetMT->GetClass();
Instantiation inst = GetInstantiation();
Instantiation targetInst = pTargetMT->GetInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
TypeHandle thArg = inst[i];
TypeHandle thTargetArg = targetInst[i];
// If argument types are not equivalent, test them for compatibility
// in accordance with the the variance annotation
if (!thArg.IsEquivalentTo(thTargetArg))
{
switch (pClass->GetVarianceOfTypeParameter(i))
{
case gpCovariant :
if (!thArg.IsBoxedAndCanCastTo(thTargetArg, &pairList))
goto Exit;
break;
case gpContravariant :
if (!thTargetArg.IsBoxedAndCanCastTo(thArg, &pairList))
goto Exit;
break;
case gpNonVariant :
goto Exit;
default :
_ASSERTE(!"Illegal variance annotation");
goto Exit;
}
}
}
}
returnValue = TRUE;
Exit:
return returnValue;
}
//==========================================================================================
BOOL MethodTable::CanCastToClass(MethodTable *pTargetMT, TypeHandlePairList *pVisited)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pTargetMT));
PRECONDITION(!pTargetMT->IsArray());
PRECONDITION(!pTargetMT->IsInterface());
}
CONTRACTL_END
MethodTable *pMT = this;
// If the target type has variant type parameters, we take a slower path
if (pTargetMT->HasVariance())
{
// At present, we support variance only on delegates and interfaces
CONSISTENCY_CHECK(pTargetMT->IsDelegate());
// First chase inheritance hierarchy until we hit a class that only differs in its instantiation
do {
// Cheap check for equivalence
if (pMT->IsEquivalentTo(pTargetMT))
return TRUE;
g_IBCLogger.LogMethodTableAccess(pMT);
if (pMT->CanCastByVarianceToInterfaceOrDelegate(pTargetMT, pVisited))
return TRUE;
pMT = pMT->GetParentMethodTable();
} while (pMT);
}
// If there are no variant type parameters, just chase the hierarchy
else
{
do {
if (pMT->IsEquivalentTo(pTargetMT))
return TRUE;
g_IBCLogger.LogMethodTableAccess(pMT);
pMT = pMT->GetParentMethodTable();
} while (pMT);
}
return FALSE;
}
#include <optsmallperfcritical.h>
//==========================================================================================
BOOL MethodTable::CanCastToNonVariantInterface(MethodTable *pTargetMT)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
INSTANCE_CHECK;
SO_TOLERANT;
PRECONDITION(CheckPointer(pTargetMT));
PRECONDITION(pTargetMT->IsInterface());
PRECONDITION(!pTargetMT->HasVariance());
PRECONDITION(!IsTransparentProxy());
PRECONDITION(IsRestored_NoLogging());
}
CONTRACTL_END
// Check to see if the current class is for the interface passed in.
if (this == pTargetMT)
return TRUE;
// Check to see if the static class definition indicates we implement the interface.
return ImplementsInterfaceInline(pTargetMT);
}
//==========================================================================================
TypeHandle::CastResult MethodTable::CanCastToInterfaceNoGC(MethodTable *pTargetMT)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
INSTANCE_CHECK;
SO_TOLERANT;
PRECONDITION(CheckPointer(pTargetMT));
PRECONDITION(pTargetMT->IsInterface());
PRECONDITION(!IsTransparentProxy());
PRECONDITION(IsRestored_NoLogging());
}
CONTRACTL_END
if (!pTargetMT->HasVariance() && !IsArray() && !HasTypeEquivalence() && !pTargetMT->HasTypeEquivalence())
{
return CanCastToNonVariantInterface(pTargetMT) ? TypeHandle::CanCast : TypeHandle::CannotCast;
}
else
{
// We're conservative on variant interfaces and types with equivalence
return TypeHandle::MaybeCast;
}
}
//==========================================================================================
TypeHandle::CastResult MethodTable::CanCastToClassNoGC(MethodTable *pTargetMT)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
INSTANCE_CHECK;
SO_TOLERANT;
PRECONDITION(CheckPointer(pTargetMT));
PRECONDITION(!pTargetMT->IsArray());
PRECONDITION(!pTargetMT->IsInterface());
}
CONTRACTL_END
// We're conservative on variant classes
if (pTargetMT->HasVariance() || g_IBCLogger.InstrEnabled())
{
return TypeHandle::MaybeCast;
}
// Type equivalence needs the slow path
if (HasTypeEquivalence() || pTargetMT->HasTypeEquivalence())
{
return TypeHandle::MaybeCast;
}
// If there are no variant type parameters, just chase the hierarchy
else
{
PTR_VOID pMT = this;
do {
if (pMT == pTargetMT)
return TypeHandle::CanCast;
pMT = MethodTable::GetParentMethodTableOrIndirection(pMT);
} while (pMT);
}
return TypeHandle::CannotCast;
}
#include <optdefault.h>
BOOL
MethodTable::IsExternallyVisible()
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_TRIGGERS;
SO_INTOLERANT;
}
CONTRACTL_END;
BOOL bIsVisible = IsTypeDefExternallyVisible(GetCl(), GetModule(), GetClass()->GetAttrClass());
if (bIsVisible && HasInstantiation() && !IsGenericTypeDefinition())
{
for (COUNT_T i = 0; i < GetNumGenericArgs(); i++)
{
if (!GetInstantiation()[i].IsExternallyVisible())
return FALSE;
}
}
return bIsVisible;
} // MethodTable::IsExternallyVisible
#ifdef FEATURE_PREJIT
BOOL MethodTable::CanShareVtableChunksFrom(MethodTable *pTargetMT, Module *pCurrentLoaderModule, Module *pCurrentPreferredZapModule)
{
WRAPPER_NO_CONTRACT;
// These constraints come from two places:
// 1. A non-zapped MT cannot share with a zapped MT since it may result in SetSlot() on a read-only slot
// 2. Zapping this MT in MethodTable::Save cannot "unshare" something we decide to share now
//
// We could fix both of these and allow non-zapped MTs to share chunks fully by doing the following
// 1. Fix the few dangerous callers of SetSlot to first check whether the chunk itself is zapped
// (see MethodTableBuilder::CopyExactParentSlots, or we could use ExecutionManager::FindZapModule)
// 2. Have this function return FALSE if IsCompilationProcess and rely on MethodTable::Save to do all sharing for the NGen case
return !pTargetMT->IsZapped() &&
pTargetMT->GetLoaderModule() == pCurrentLoaderModule &&
pCurrentLoaderModule == pCurrentPreferredZapModule &&
pCurrentPreferredZapModule == Module::GetPreferredZapModuleForMethodTable(pTargetMT);
}
#else
BOOL MethodTable::CanShareVtableChunksFrom(MethodTable *pTargetMT, Module *pCurrentLoaderModule)
{
WRAPPER_NO_CONTRACT;
return pTargetMT->GetLoaderModule() == pCurrentLoaderModule;
}
#endif
#ifdef _DEBUG
void
MethodTable::DebugDumpVtable(LPCUTF8 szClassName, BOOL fDebug)
{
//diag functions shouldn't affect normal behavior
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
}
CONTRACTL_END;
CQuickBytes qb;
const size_t cchBuff = MAX_CLASSNAME_LENGTH + 30;
LPWSTR buff = fDebug ? (LPWSTR) qb.AllocNoThrow(cchBuff * sizeof(WCHAR)) : NULL;
if ((buff == NULL) && fDebug)
{
WszOutputDebugString(W("OOM when dumping VTable - falling back to logging"));
fDebug = FALSE;
}
if (fDebug)
{
swprintf_s(buff, cchBuff, W("Vtable (with interface dupes) for '%S':\n"), szClassName);
#ifdef _DEBUG
swprintf_s(&buff[wcslen(buff)], cchBuff - wcslen(buff) , W(" Total duplicate slots = %d\n"), g_dupMethods);
#endif
WszOutputDebugString(buff);
}
else
{
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS, "Vtable (with interface dupes) for '%s':\n", szClassName));
LOG((LF_ALWAYS, LL_ALWAYS, " Total duplicate slots = %d\n", g_dupMethods));
}
HRESULT hr;
EX_TRY
{
MethodIterator it(this);
for (; it.IsValid(); it.Next())
{
MethodDesc *pMD = it.GetMethodDesc();
LPCUTF8 pszName = pMD->GetName((USHORT) it.GetSlotNumber());
DWORD dwAttrs = pMD->GetAttrs();
if (fDebug)
{
DefineFullyQualifiedNameForClass();
LPCUTF8 name = GetFullyQualifiedNameForClass(pMD->GetMethodTable());
swprintf_s(buff, cchBuff,
W(" slot %2d: %S::%S%S 0x%p (slot = %2d)\n"),
it.GetSlotNumber(),
name,
pszName,
IsMdFinal(dwAttrs) ? " (final)" : "",
pMD->GetMethodEntryPoint(),
pMD->GetSlot()
);
WszOutputDebugString(buff);
}
else
{
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS,
" slot %2d: %s::%s%s 0x%p (slot = %2d)\n",
it.GetSlotNumber(),
pMD->GetClass()->GetDebugClassName(),
pszName,
IsMdFinal(dwAttrs) ? " (final)" : "",
pMD->GetMethodEntryPoint(),
pMD->GetSlot()
));
}
if (it.GetSlotNumber() == (DWORD)(GetNumMethods()-1))
{
if (fDebug)
{
WszOutputDebugString(W(" <-- vtable ends here\n"));
}
else
{
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS, " <-- vtable ends here\n"));
}
}
}
}
EX_CATCH_HRESULT(hr);
if (fDebug)
{
WszOutputDebugString(W("\n"));
}
else
{
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS, "\n"));
}
} // MethodTable::DebugDumpVtable
void
MethodTable::Debug_DumpInterfaceMap(
LPCSTR szInterfaceMapPrefix)
{
// Diagnostic functions shouldn't affect normal behavior
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
}
CONTRACTL_END;
if (GetNumInterfaces() == 0)
{ // There are no interfaces, no point in printing interface map info
return;
}
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS,
"%s Interface Map for '%s':\n",
szInterfaceMapPrefix,
GetDebugClassName()));
LOG((LF_ALWAYS, LL_ALWAYS,
" Number of interfaces = %d\n",
GetNumInterfaces()));
HRESULT hr;
EX_TRY
{
InterfaceMapIterator it(this, false);
while (it.Next())
{
MethodTable *pInterfaceMT = it.GetInterface();
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS,
" index %2d: %s 0x%p\n",
it.GetIndex(),
pInterfaceMT->GetDebugClassName(),
pInterfaceMT));
}
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS, " <-- interface map ends here\n"));
}
EX_CATCH_HRESULT(hr);
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS, "\n"));
} // MethodTable::Debug_DumpInterfaceMap
void
MethodTable::Debug_DumpDispatchMap()
{
WRAPPER_NO_CONTRACT; // It's a dev helper, we don't care about contracts
if (!HasDispatchMap())
{ // There is no dipstch map for this type, no point in printing the info
return;
}
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS, "Dispatch Map for '%s':\n", GetDebugClassName()));
InterfaceInfo_t * pInterfaceMap = GetInterfaceMap();
DispatchMap::EncodedMapIterator it(this);
while (it.IsValid())
{
DispatchMapEntry *pEntry = it.Entry();
UINT32 nInterfaceIndex = pEntry->GetTypeID().GetInterfaceNum();
_ASSERTE(nInterfaceIndex < GetNumInterfaces());
MethodTable * pInterface = pInterfaceMap[nInterfaceIndex].GetMethodTable();
UINT32 nInterfaceSlotNumber = pEntry->GetSlotNumber();
UINT32 nImplementationSlotNumber = pEntry->GetTargetSlotNumber();
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS,
" Interface %d (%s) slot %d (%s) implemented in slot %d (%s)\n",
nInterfaceIndex,
pInterface->GetDebugClassName(),
nInterfaceSlotNumber,
pInterface->GetMethodDescForSlot(nInterfaceSlotNumber)->GetName(),
nImplementationSlotNumber,
GetMethodDescForSlot(nImplementationSlotNumber)->GetName()));
it.Next();
}
//LF_ALWAYS allowed here because this is controlled by special env var code:EEConfig::ShouldDumpOnClassLoad
LOG((LF_ALWAYS, LL_ALWAYS, " <-- Dispatch map ends here\n"));
} // MethodTable::Debug_DumpDispatchMap
#endif //_DEBUG
//==========================================================================================
NOINLINE BOOL MethodTable::ImplementsInterface(MethodTable *pInterface)
{
WRAPPER_NO_CONTRACT;
return ImplementsInterfaceInline(pInterface);
}
//==========================================================================================
BOOL MethodTable::ImplementsEquivalentInterface(MethodTable *pInterface)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
SO_TOLERANT;
PRECONDITION(pInterface->IsInterface()); // class we are looking up should be an interface
}
CONTRACTL_END;
// look for exact match first (optimize for success)
if (ImplementsInterfaceInline(pInterface))
return TRUE;
if (!pInterface->HasTypeEquivalence())
return FALSE;
DWORD numInterfaces = GetNumInterfaces();
if (numInterfaces == 0)
return FALSE;
InterfaceInfo_t *pInfo = GetInterfaceMap();
do
{
if (pInfo->GetMethodTable()->IsEquivalentTo(pInterface))
return TRUE;
pInfo++;
}
while (--numInterfaces);
return FALSE;
}
//==========================================================================================
MethodDesc *MethodTable::GetMethodDescForInterfaceMethod(MethodDesc *pInterfaceMD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(!pInterfaceMD->HasClassOrMethodInstantiation());
}
CONTRACTL_END;
WRAPPER_NO_CONTRACT;
return GetMethodDescForInterfaceMethod(TypeHandle(pInterfaceMD->GetMethodTable()), pInterfaceMD);
}
//==========================================================================================
MethodDesc *MethodTable::GetMethodDescForInterfaceMethod(TypeHandle ownerType, MethodDesc *pInterfaceMD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(!ownerType.IsNull());
PRECONDITION(ownerType.GetMethodTable()->IsInterface());
PRECONDITION(ownerType.GetMethodTable()->HasSameTypeDefAs(pInterfaceMD->GetMethodTable()));
PRECONDITION(IsArray() || ImplementsEquivalentInterface(ownerType.GetMethodTable()) || ownerType.GetMethodTable()->HasVariance());
}
CONTRACTL_END;
MethodDesc *pMD = NULL;
MethodTable *pInterfaceMT = ownerType.AsMethodTable();
#ifdef CROSSGEN_COMPILE
DispatchSlot implSlot(FindDispatchSlot(pInterfaceMT->GetTypeID(), pInterfaceMD->GetSlot()));
PCODE pTgt = implSlot.GetTarget();
#else
PCODE pTgt = VirtualCallStubManager::GetTarget(
pInterfaceMT->GetLoaderAllocator()->GetDispatchToken(pInterfaceMT->GetTypeID(), pInterfaceMD->GetSlot()),
this);
#endif
pMD = MethodTable::GetMethodDescForSlotAddress(pTgt);
#ifdef _DEBUG
MethodDesc *pDispSlotMD = FindDispatchSlotForInterfaceMD(ownerType, pInterfaceMD).GetMethodDesc();
_ASSERTE(pDispSlotMD == pMD);
#endif // _DEBUG
pMD->CheckRestore();
return pMD;
}
#endif // DACCESS_COMPILE
//==========================================================================================
PTR_FieldDesc MethodTable::GetFieldDescByIndex(DWORD fieldIndex)
{
LIMITED_METHOD_CONTRACT;
if (HasGenericsStaticsInfo() &&
fieldIndex >= GetNumIntroducedInstanceFields())
{
return GetGenericsStaticFieldDescs() + (fieldIndex - GetNumIntroducedInstanceFields());
}
else
{
return GetClass()->GetFieldDescList() + fieldIndex;
}
}
//==========================================================================================
DWORD MethodTable::GetIndexForFieldDesc(FieldDesc *pField)
{
LIMITED_METHOD_CONTRACT;
if (pField->IsStatic() && HasGenericsStaticsInfo())
{
FieldDesc *pStaticFields = GetGenericsStaticFieldDescs();
return GetNumIntroducedInstanceFields() + DWORD(pField - pStaticFields);
}
else
{
FieldDesc *pFields = GetClass()->GetFieldDescList();
return DWORD(pField - pFields);
}
}
//==========================================================================================
#ifdef _MSC_VER
#pragma optimize("t", on)
#endif // _MSC_VER
// compute whether the type can be considered to have had its
// static initialization run without doing anything at all, i.e. whether we know
// immediately that the type requires nothing to do for initialization
//
// If a type used as a representiative during JITting is PreInit then
// any types that it may represent within a code-sharing
// group are also PreInit. For example, if List<object> is PreInit then List<string>
// and List<MyType> are also PreInit. This is because the dynamicStatics, staticRefHandles
// and hasCCtor are all identical given a head type, and weakening the domainNeutrality
// to DomainSpecific only makes more types PreInit.
BOOL MethodTable::IsClassPreInited()
{
LIMITED_METHOD_CONTRACT;
if (ContainsGenericVariables())
return TRUE;
if (HasClassConstructor())
return FALSE;
if (HasBoxedRegularStatics())
return FALSE;
if (IsDynamicStatics())
return FALSE;
return TRUE;
}
#ifdef _MSC_VER
#pragma optimize("", on)
#endif // _MSC_VER
#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
//==========================================================================================
void MethodTable::AllocateRegularStaticBoxes()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(!ContainsGenericVariables());
PRECONDITION(HasBoxedRegularStatics());
MODE_ANY;
}
CONTRACTL_END;
LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: Instantiating static handles for %s\n", GetDebugClassName()));
GCX_COOP();
PTR_BYTE pStaticBase = GetGCStaticsBasePointer();
GCPROTECT_BEGININTERIOR(pStaticBase);
// In ngened case, we have cached array with boxed statics MTs. In JITed case, we have just the FieldDescs
ClassCtorInfoEntry *pClassCtorInfoEntry = GetClassCtorInfoIfExists();
if (pClassCtorInfoEntry != NULL)
{
OBJECTREF* pStaticSlots = (OBJECTREF*)(pStaticBase + pClassCtorInfoEntry->firstBoxedStaticOffset);
GCPROTECT_BEGININTERIOR(pStaticSlots);
ArrayDPTR(FixupPointer<PTR_MethodTable>) ppMTs = GetLoaderModule()->GetZapModuleCtorInfo()->
GetGCStaticMTs(pClassCtorInfoEntry->firstBoxedStaticMTIndex);
DWORD numBoxedStatics = pClassCtorInfoEntry->numBoxedStatics;
for (DWORD i = 0; i < numBoxedStatics; i++)
{
#ifdef FEATURE_PREJIT
Module::RestoreMethodTablePointer(&(ppMTs[i]), GetLoaderModule());
#endif
MethodTable *pFieldMT = ppMTs[i].GetValue();
_ASSERTE(pFieldMT);
LOG((LF_CLASSLOADER, LL_INFO10000, "\tInstantiating static of type %s\n", pFieldMT->GetDebugClassName()));
OBJECTREF obj = AllocateStaticBox(pFieldMT, pClassCtorInfoEntry->hasFixedAddressVTStatics);
SetObjectReference( &(pStaticSlots[i]), obj, GetAppDomain() );
}
GCPROTECT_END();
}
else
{
// We should never take this codepath in zapped images.
_ASSERTE(!IsZapped());
FieldDesc *pField = HasGenericsStaticsInfo() ?
GetGenericsStaticFieldDescs() : (GetApproxFieldDescListRaw() + GetNumIntroducedInstanceFields());
FieldDesc *pFieldEnd = pField + GetNumStaticFields();
while (pField < pFieldEnd)
{
_ASSERTE(pField->IsStatic());
if (!pField->IsSpecialStatic() && pField->IsByValue())
{
TypeHandle th = pField->GetFieldTypeHandleThrowing();
MethodTable* pFieldMT = th.GetMethodTable();
LOG((LF_CLASSLOADER, LL_INFO10000, "\tInstantiating static of type %s\n", pFieldMT->GetDebugClassName()));
OBJECTREF obj = AllocateStaticBox(pFieldMT, HasFixedAddressVTStatics());
SetObjectReference( (OBJECTREF*)(pStaticBase + pField->GetOffset()), obj, GetAppDomain() );
}
pField++;
}
}
GCPROTECT_END();
}
//==========================================================================================
OBJECTREF MethodTable::AllocateStaticBox(MethodTable* pFieldMT, BOOL fPinned, OBJECTHANDLE* pHandle)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
CONTRACTL_END;
}
_ASSERTE(pFieldMT->IsValueType());
// Activate any dependent modules if necessary
pFieldMT->EnsureInstanceActive();
OBJECTREF obj = AllocateObject(pFieldMT);
// Pin the object if necessary
if (fPinned)
{
LOG((LF_CLASSLOADER, LL_INFO10000, "\tSTATICS:Pinning static (VT fixed address attribute) of type %s\n", pFieldMT->GetDebugClassName()));
OBJECTHANDLE oh = GetAppDomain()->CreatePinningHandle(obj);
if (pHandle)
{
*pHandle = oh;
}
}
else
{
if (pHandle)
{
*pHandle = NULL;
}
}
return obj;
}
//==========================================================================================
BOOL MethodTable::RunClassInitEx(OBJECTREF *pThrowable)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(IsFullyLoaded());
PRECONDITION(IsProtectedByGCFrame(pThrowable));
}
CONTRACTL_END;
// A somewhat unusual function, can both return throwable and throw.
// The difference is, we throw on restartable operations and just return throwable
// on exceptions fatal for the .cctor
// (Of course in the latter case the caller is supposed to throw pThrowable)
// Doing the opposite ( i.e. throwing on fatal and returning on nonfatal)
// would be more intuitive but it's more convenient the way it is
BOOL fRet = FALSE;
// During the <clinit>, this thread must not be asynchronously
// stopped or interrupted. That would leave the class unavailable
// and is therefore a security hole. We don't have to worry about
// multithreading, since we only manipulate the current thread's count.
ThreadPreventAsyncHolder preventAsync;
// If the static initialiser throws an exception that it doesn't catch, it has failed
EX_TRY
{
// Activate our module if necessary
EnsureInstanceActive();
STRESS_LOG1(LF_CLASSLOADER, LL_INFO1000, "RunClassInit: Calling class contructor for type %pT\n", this);
MethodTable * pCanonMT = GetCanonicalMethodTable();
// Call the code method without touching MethodDesc if possible
PCODE pCctorCode = pCanonMT->GetSlot(pCanonMT->GetClassConstructorSlot());
if (pCanonMT->IsSharedByGenericInstantiations())
{
PREPARE_NONVIRTUAL_CALLSITE_USING_CODE(pCctorCode);
DECLARE_ARGHOLDER_ARRAY(args, 1);
args[ARGNUM_0] = PTR_TO_ARGHOLDER(this);
CATCH_HANDLER_FOUND_NOTIFICATION_CALLSITE;
CALL_MANAGED_METHOD_NORET(args);
}
else
{
PREPARE_NONVIRTUAL_CALLSITE_USING_CODE(pCctorCode);
DECLARE_ARGHOLDER_ARRAY(args, 0);
CATCH_HANDLER_FOUND_NOTIFICATION_CALLSITE;
CALL_MANAGED_METHOD_NORET(args);
}
STRESS_LOG1(LF_CLASSLOADER, LL_INFO100000, "RunClassInit: Returned Successfully from class contructor for type %pT\n", this);
fRet = TRUE;
}
EX_CATCH
{
// Exception set by parent
// <TODO>@TODO: We should make this an ExceptionInInitializerError if the exception thrown is not
// a subclass of Error</TODO>
*pThrowable = GET_THROWABLE();
_ASSERTE(fRet == FALSE);
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
// If active thread state does not have a CorruptionSeverity set for the exception,
// then set one up based upon the current exception code and/or the throwable.
//
// When can we be here and current exception tracker may not have corruption severity set?
// Incase of SO in managed code, SO is never seen by CLR's exception handler for managed code
// and if this happens in cctor, we can end up here without the corruption severity set.
Thread *pThread = GetThread();
_ASSERTE(pThread != NULL);
ThreadExceptionState *pCurTES = pThread->GetExceptionState();
_ASSERTE(pCurTES != NULL);
if (pCurTES->GetLastActiveExceptionCorruptionSeverity() == NotSet)
{
if (CEHelper::IsProcessCorruptedStateException(GetCurrentExceptionCode()) ||
CEHelper::IsProcessCorruptedStateException(*pThrowable))
{
// Process Corrupting
pCurTES->SetLastActiveExceptionCorruptionSeverity(ProcessCorrupting);
LOG((LF_EH, LL_INFO100, "MethodTable::RunClassInitEx - Exception treated as ProcessCorrupting.\n"));
}
else
{
// Not Corrupting
pCurTES->SetLastActiveExceptionCorruptionSeverity(NotCorrupting);
LOG((LF_EH, LL_INFO100, "MethodTable::RunClassInitEx - Exception treated as non-corrupting.\n"));
}
}
else
{
LOG((LF_EH, LL_INFO100, "MethodTable::RunClassInitEx - Exception already has corruption severity set.\n"));
}
#endif // FEATURE_CORRUPTING_EXCEPTIONS
}
EX_END_CATCH(SwallowAllExceptions)
return fRet;
}
//==========================================================================================
void MethodTable::DoRunClassInitThrowing()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
SO_TOLERANT;
}
CONTRACTL_END;
GCX_COOP();
// This is a fairly aggressive policy. Merely asking that the class be initialized is grounds for kicking you out.
// Alternately, we could simply NOP out the class initialization. Since the aggressive policy is also the more secure
// policy, keep this unless it proves intractable to remove all premature classinits in the system.
EnsureActive();
Thread *pThread;
pThread = GetThread();
_ASSERTE(pThread);
INTERIOR_STACK_PROBE_FOR(pThread, 8);
AppDomain *pDomain = GetAppDomain();
HRESULT hrResult = E_FAIL;
const char *description;
STRESS_LOG2(LF_CLASSLOADER, LL_INFO100000, "DoRunClassInit: Request to init %pT in appdomain %p\n", this, pDomain);
//
// Take the global lock
//
ListLock *_pLock = pDomain->GetClassInitLock();
ListLockHolder pInitLock(_pLock);
// Check again
if (IsClassInited())
goto Exit;
//
// Handle cases where the .cctor has already tried to run but failed.
//
if (IsInitError())
{
// Some error occurred trying to init this class
ListLockEntry* pEntry= (ListLockEntry *) _pLock->Find(this);
_ASSERTE(pEntry!=NULL);
_ASSERTE(pEntry->m_pLoaderAllocator == (GetDomain()->IsSharedDomain() ? pDomain->GetLoaderAllocator() : GetLoaderAllocator()));
// If this isn't a TypeInitializationException, then its creation failed
// somehow previously, so we should make one last attempt to create it. If
// that fails, just throw the exception that was originally thrown.
// Primarily, this deals with the problem that the exception is a
// ThreadAbortException, because this must be executing on a different
// thread. If in fact this thread is also aborting, then rethrowing the
// other thread's exception will not do any worse.
// If we need to create the type init exception object, we'll need to
// GC protect these, so might as well create the structure now.
struct _gc {
OBJECTREF pInitException;
OBJECTREF pNewInitException;
OBJECTREF pThrowable;
} gc;
gc.pInitException = pEntry->m_pLoaderAllocator->GetHandleValue(pEntry->m_hInitException);
gc.pNewInitException = NULL;
gc.pThrowable = NULL;
GCPROTECT_BEGIN(gc);
// We need to release this lock because CreateTypeInitializationExceptionObject and fetching the TypeLoad exception can cause
// managed code to re-enter into this codepath, causing a locking order violation.
pInitLock.Release();
if (MscorlibBinder::GetException(kTypeInitializationException) != gc.pInitException->GetMethodTable())
{
DefineFullyQualifiedNameForClassWOnStack();
LPCWSTR wszName = GetFullyQualifiedNameForClassW(this);
CreateTypeInitializationExceptionObject(wszName, &gc.pInitException, &gc.pNewInitException, &gc.pThrowable);
LOADERHANDLE hOrigInitException = pEntry->m_hInitException;
if (!CLRException::IsPreallocatedExceptionObject(pEntry->m_pLoaderAllocator->GetHandleValue(hOrigInitException)))
{
// Now put the new init exception in the handle. If another thread beat us (because we released the
// lock above), then we'll just let the extra init exception object get collected later.
pEntry->m_pLoaderAllocator->CompareExchangeValueInHandle(pEntry->m_hInitException, gc.pNewInitException, gc.pInitException);
} else {
// if the stored exception is a preallocated one we cannot store the new Exception object in it.
// we'll attempt to create a new handle for the new TypeInitializationException object
LOADERHANDLE hNewInitException = NULL;
// CreateHandle can throw due to OOM. We need to catch this so that we make sure to set the
// init error. Whatever exception was thrown will be rethrown below, so no worries.
EX_TRY {
hNewInitException = pEntry->m_pLoaderAllocator->AllocateHandle(gc.pNewInitException);
} EX_CATCH {
// If we failed to create the handle we'll just leave the originally alloc'd one in place.
} EX_END_CATCH(SwallowAllExceptions);
// if two threads are racing to set m_hInitException, clear the handle created by the loser
if (hNewInitException != NULL &&
InterlockedCompareExchangeT((&pEntry->m_hInitException), hNewInitException, hOrigInitException) != hOrigInitException)
{
pEntry->m_pLoaderAllocator->ClearHandle(hNewInitException);
}
}
}
else {
gc.pThrowable = gc.pInitException;
}
GCPROTECT_END();
// Throw the saved exception. Since we may be rethrowing a previously cached exception, must clear the stack trace first.
// Rethrowing a previously cached exception is distasteful but is required for appcompat with Everett.
//
// (The IsException() is probably more appropriate as an assert but as this isn't a heavily tested code path,
// I prefer to be defensive here.)
if (IsException(gc.pThrowable->GetMethodTable()))
{
((EXCEPTIONREF)(gc.pThrowable))->ClearStackTraceForThrow();
}
// <FEATURE_CORRUPTING_EXCEPTIONS>
// Specify the corruption severity to be used to raise this exception in COMPlusThrow below.
// This will ensure that when the exception is seen by the managed code personality routine,
// it will setup the correct corruption severity in the exception tracker.
// </FEATURE_CORRUPTING_EXCEPTIONS>
COMPlusThrow(gc.pThrowable
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
, pEntry->m_CorruptionSeverity
#endif // FEATURE_CORRUPTING_EXCEPTIONS
);
}
description = ".cctor lock";
#if _DEBUG
description = GetDebugClassName();
#endif
// Take the lock
{
//nontrivial holder, might take a lock in destructor
ListLockEntryHolder pEntry(ListLockEntry::Find(pInitLock, this, description));
ListLockEntryLockHolder pLock(pEntry, FALSE);
// We have a list entry, we can release the global lock now
pInitLock.Release();
if (pLock.DeadlockAwareAcquire())
{
if (pEntry->m_hrResultCode == S_FALSE)
{
if (!NingenEnabled())
{
if (HasBoxedRegularStatics())
{
// First, instantiate any objects needed for value type statics
AllocateRegularStaticBoxes();
}
// Nobody has run the .cctor yet
if (HasClassConstructor())
{
struct _gc {
OBJECTREF pInnerException;
OBJECTREF pInitException;
OBJECTREF pThrowable;
} gc;
gc.pInnerException = NULL;
gc.pInitException = NULL;
gc.pThrowable = NULL;
GCPROTECT_BEGIN(gc);
if (!RunClassInitEx(&gc.pInnerException))
{
// The .cctor failed and we want to store the exception that resulted
// in the entry. Increment the ref count to keep the entry alive for
// subsequent attempts to run the .cctor.
pEntry->AddRef();
// For collectible types, register the entry for cleanup.
if (GetLoaderAllocator()->IsCollectible())
{
GetLoaderAllocator()->RegisterFailedTypeInitForCleanup(pEntry);
}
_ASSERTE(g_pThreadAbortExceptionClass == MscorlibBinder::GetException(kThreadAbortException));
if(gc.pInnerException->GetMethodTable() == g_pThreadAbortExceptionClass)
{
gc.pThrowable = gc.pInnerException;
gc.pInitException = gc.pInnerException;
gc.pInnerException = NULL;
}
else
{
DefineFullyQualifiedNameForClassWOnStack();
LPCWSTR wszName = GetFullyQualifiedNameForClassW(this);
// Note that this may not succeed due to problems creating the exception
// object. On failure, it will first try to
CreateTypeInitializationExceptionObject(
wszName, &gc.pInnerException, &gc.pInitException, &gc.pThrowable);
}
pEntry->m_pLoaderAllocator = GetDomain()->IsSharedDomain() ? pDomain->GetLoaderAllocator() : GetLoaderAllocator();
// CreateHandle can throw due to OOM. We need to catch this so that we make sure to set the
// init error. Whatever exception was thrown will be rethrown below, so no worries.
EX_TRY {
// Save the exception object, and return to caller as well.
pEntry->m_hInitException = pEntry->m_pLoaderAllocator->AllocateHandle(gc.pInitException);
} EX_CATCH {
// If we failed to create the handle (due to OOM), we'll just store the preallocated OOM
// handle here instead.
pEntry->m_hInitException = pEntry->m_pLoaderAllocator->AllocateHandle(CLRException::GetPreallocatedOutOfMemoryException());
} EX_END_CATCH(SwallowAllExceptions);
pEntry->m_hrResultCode = E_FAIL;
SetClassInitError();
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
// Save the corruption severity of the exception so that if the type system
// attempts to pick it up from its cache list and throw again, it should
// treat the exception as corrupting, if applicable.
pEntry->m_CorruptionSeverity = pThread->GetExceptionState()->GetLastActiveExceptionCorruptionSeverity();
// We should be having a valid corruption severity at this point
_ASSERTE(pEntry->m_CorruptionSeverity != NotSet);
#endif // FEATURE_CORRUPTING_EXCEPTIONS
COMPlusThrow(gc.pThrowable
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
, pEntry->m_CorruptionSeverity
#endif // FEATURE_CORRUPTING_EXCEPTIONS
);
}
GCPROTECT_END();
}
}
pEntry->m_hrResultCode = S_OK;
// Set the initialization flags in the DLS and on domain-specific types.
// Note we also set the flag for dynamic statics, which use the DynamicStatics part
// of the DLS irrespective of whether the type is domain neutral or not.
SetClassInited();
}
else
{
// Use previous result
hrResult = pEntry->m_hrResultCode;
if(FAILED(hrResult))
{
// An exception may have occurred in the cctor. DoRunClassInit() should return FALSE in that
// case.
_ASSERTE(pEntry->m_hInitException);
_ASSERTE(pEntry->m_pLoaderAllocator == (GetDomain()->IsSharedDomain() ? pDomain->GetLoaderAllocator() : GetLoaderAllocator()));
_ASSERTE(IsInitError());
// Throw the saved exception. Since we are rethrowing a previously cached exception, must clear the stack trace first.
// Rethrowing a previously cached exception is distasteful but is required for appcompat with Everett.
//
// (The IsException() is probably more appropriate as an assert but as this isn't a heavily tested code path,
// I prefer to be defensive here.)
if (IsException(pEntry->m_pLoaderAllocator->GetHandleValue(pEntry->m_hInitException)->GetMethodTable()))
{
((EXCEPTIONREF)(pEntry->m_pLoaderAllocator->GetHandleValue(pEntry->m_hInitException)))->ClearStackTraceForThrow();
}
COMPlusThrow(pEntry->m_pLoaderAllocator->GetHandleValue(pEntry->m_hInitException));
}
}
}
}
//
// Notify any entries waiting on the current entry and wait for the required entries.
//
// We need to take the global lock before we play with the list of entries.
STRESS_LOG2(LF_CLASSLOADER, LL_INFO100000, "DoRunClassInit: returning SUCCESS for init %pT in appdomain %p\n", this, pDomain);
// No need to set pThrowable in case of error it will already have been set.
g_IBCLogger.LogMethodTableAccess(this);
Exit:
;
END_INTERIOR_STACK_PROBE;
}
//==========================================================================================
void MethodTable::CheckRunClassInitThrowing()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
SO_TOLERANT;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(IsFullyLoaded());
}
CONTRACTL_END;
{ // Debug-only code causes SO volation, so add exception.
CONTRACT_VIOLATION(SOToleranceViolation);
CONSISTENCY_CHECK(CheckActivated());
}
// To find GC hole easier...
TRIGGERSGC();
if (IsClassPreInited())
return;
// Don't initialize shared generic instantiations (e.g. MyClass<__Canon>)
if (IsSharedByGenericInstantiations())
return;
DomainLocalModule *pLocalModule = GetDomainLocalModule();
_ASSERTE(pLocalModule);
DWORD iClassIndex = GetClassIndex();
// Check to see if we have already run the .cctor for this class.
if (!pLocalModule->IsClassAllocated(this, iClassIndex))
pLocalModule->PopulateClass(this);
if (!pLocalModule->IsClassInitialized(this, iClassIndex))
DoRunClassInitThrowing();
}
//==========================================================================================
void MethodTable::CheckRunClassInitAsIfConstructingThrowing()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
if (HasPreciseInitCctors())
{
MethodTable *pMTCur = this;
while (pMTCur != NULL)
{
if (!pMTCur->GetClass()->IsBeforeFieldInit())
pMTCur->CheckRunClassInitThrowing();
pMTCur = pMTCur->GetParentMethodTable();
}
}
}
//==========================================================================================
OBJECTREF MethodTable::Allocate()
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_TRIGGERS;
THROWS;
}
CONTRACTL_END;
CONSISTENCY_CHECK(IsFullyLoaded());
EnsureInstanceActive();
if (HasPreciseInitCctors())
{
CheckRunClassInitAsIfConstructingThrowing();
}
return AllocateObject(this);
}
//==========================================================================================
// box 'data' creating a new object and return it. This routine understands the special
// handling needed for Nullable values.
// see code:Nullable#NullableVerification
OBJECTREF MethodTable::Box(void* data)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(IsValueType());
}
CONTRACTL_END;
OBJECTREF ref;
GCPROTECT_BEGININTERIOR (data);
if (ContainsStackPtr())
{
// We should never box a type that contains stack pointers.
COMPlusThrow(kInvalidOperationException, W("InvalidOperation_TypeCannotBeBoxed"));
}
ref = FastBox(&data);
GCPROTECT_END ();
return ref;
}
OBJECTREF MethodTable::FastBox(void** data)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(IsValueType());
}
CONTRACTL_END;
// See code:Nullable#NullableArchitecture for more
if (IsNullable())
return Nullable::Box(*data, this);
OBJECTREF ref = Allocate();
CopyValueClass(ref->UnBox(), *data, this, ref->GetAppDomain());
return ref;
}
#if _TARGET_X86_ || _TARGET_AMD64_
//==========================================================================================
static void FastCallFinalize(Object *obj, PCODE funcPtr, BOOL fCriticalCall)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_SO_INTOLERANT;
BEGIN_CALL_TO_MANAGEDEX(fCriticalCall ? EEToManagedCriticalCall : EEToManagedDefault);
#if defined(_TARGET_X86_)
__asm
{
mov ecx, [obj]
call [funcPtr]
INDEBUG(nop) // Mark the fact that we can call managed code
}
#else // _TARGET_X86_
FastCallFinalizeWorker(obj, funcPtr);
#endif // _TARGET_X86_
END_CALL_TO_MANAGED();
}
#endif // _TARGET_X86_ || _TARGET_AMD64_
void CallFinalizerOnThreadObject(Object *obj)
{
STATIC_CONTRACT_MODE_COOPERATIVE;
THREADBASEREF refThis = (THREADBASEREF)ObjectToOBJECTREF(obj);
Thread* thread = refThis->GetInternal();
// Prevent multiple calls to Finalize
// Objects can be resurrected after being finalized. However, there is no
// race condition here. We always check whether an exposed thread object is
// still attached to the internal Thread object, before proceeding.
if (thread)
{
refThis->SetDelegate(NULL);
// During process shutdown, we finalize even reachable objects. But if we break
// the link between the System.Thread and the internal Thread object, the runtime
// may not work correctly. In particular, we won't be able to transition between
// contexts and domains to finalize other objects. Since the runtime doesn't
// require that Threads finalize during shutdown, we need to disable this. If
// we wait until phase 2 of shutdown finalization (when the EE is suspended and
// will never resume) then we can simply skip the side effects of Thread
// finalization.
if ((g_fEEShutDown & ShutDown_Finalize2) == 0)
{
if (GetThread() != thread)
{
refThis->ClearInternal();
}
FastInterlockOr ((ULONG *)&thread->m_State, Thread::TS_Finalized);
Thread::SetCleanupNeededForFinalizedThread();
}
}
}
//==========================================================================================
// From the GC finalizer thread, invoke the Finalize() method on an object.
void MethodTable::CallFinalizer(Object *obj)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(obj->GetMethodTable()->HasFinalizer() ||
obj->GetMethodTable()->IsTransparentProxy());
}
CONTRACTL_END;
// Never call any finalizers under ngen for determinism
if (IsCompilationProcess())
{
return;
}
MethodTable *pMT = obj->GetMethodTable();
// Check for precise init class constructors that have failed, if any have failed, then we didn't run the
// constructor for the object, and running the finalizer for the object would violate the CLI spec by running
// instance code without having successfully run the precise-init class constructor.
if (pMT->HasPreciseInitCctors())
{
MethodTable *pMTCur = pMT;
do
{
if ((!pMTCur->GetClass()->IsBeforeFieldInit()) && pMTCur->IsInitError())
{
// Precise init Type Initializer for type failed... do not run finalizer
return;
}
pMTCur = pMTCur->GetParentMethodTable();
}
while (pMTCur != NULL);
}
if (pMT == g_pThreadClass)
{
// Finalizing Thread object requires ThreadStoreLock. It is expensive if
// we keep taking ThreadStoreLock. This is very bad if we have high retiring
// rate of Thread objects.
// To avoid taking ThreadStoreLock multiple times, we mark Thread with TS_Finalized
// and clean up a batch of them when we take ThreadStoreLock next time.
// To avoid possible hierarchy requirement between critical finalizers, we call cleanup
// code directly.
CallFinalizerOnThreadObject(obj);
return;
}
#ifdef FEATURE_CAS_POLICY
// Notify the host to setup the restricted context before finalizing each object
HostExecutionContextManager::SetHostRestrictedContext();
#endif // FEATURE_CAS_POLICY
// Determine if the object has a critical or normal finalizer.
BOOL fCriticalFinalizer = pMT->HasCriticalFinalizer();
// There's no reason to actually set up a frame here. If we crawl out of the
// Finalize() method on this thread, we will see FRAME_TOP which indicates
// that the crawl should terminate. This is analogous to how KickOffThread()
// starts new threads in the runtime.
PCODE funcPtr = pMT->GetRestoredSlot(g_pObjectFinalizerMD->GetSlot());
#ifdef STRESS_LOG
if (fCriticalFinalizer)
{
STRESS_LOG2(LF_GCALLOC, LL_INFO100, "Finalizing CriticalFinalizer %pM in domain %d\n",
pMT, GetAppDomain()->GetId().m_dwId);
}
#endif
#if defined(_TARGET_X86_) || defined(_TARGET_AMD64_)
#ifdef DEBUGGING_SUPPORTED
if (CORDebuggerTraceCall())
g_pDebugInterface->TraceCall((const BYTE *) funcPtr);
#endif // DEBUGGING_SUPPORTED
FastCallFinalize(obj, funcPtr, fCriticalFinalizer);
#else // defined(_TARGET_X86_) || defined(_TARGET_AMD64_)
PREPARE_NONVIRTUAL_CALLSITE_USING_CODE(funcPtr);
DECLARE_ARGHOLDER_ARRAY(args, 1);
args[ARGNUM_0] = PTR_TO_ARGHOLDER(obj);
if (fCriticalFinalizer)
{
CRITICAL_CALLSITE;
}
CALL_MANAGED_METHOD_NORET(args);
#endif // (defined(_TARGET_X86_) && defined(_TARGET_AMD64_)
#ifdef STRESS_LOG
if (fCriticalFinalizer)
{
STRESS_LOG2(LF_GCALLOC, LL_INFO100, "Finalized CriticalFinalizer %pM in domain %d without exception\n",
pMT, GetAppDomain()->GetId().m_dwId);
}
#endif
}
//==========================================================================
// If the MethodTable doesn't yet know the Exposed class that represents it via
// Reflection, acquire that class now. Regardless, return it to the caller.
//==========================================================================
OBJECTREF MethodTable::GetManagedClassObject()
{
CONTRACT(OBJECTREF) {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(!IsTransparentProxy() && !IsArray()); // Arrays and remoted objects can't go through this path.
POSTCONDITION(GetWriteableData()->m_hExposedClassObject != 0);
//REENTRANT
}
CONTRACT_END;
#ifdef _DEBUG
// Force a GC here because GetManagedClassObject could trigger GC nondeterminsticaly
GCStress<cfg_any, PulseGcTriggerPolicy>::MaybeTrigger();
#endif // _DEBUG
if (GetWriteableData()->m_hExposedClassObject == NULL)
{
// Make sure that we have been restored
CheckRestore();
if (IsTransparentProxy()) // Extra protection in a retail build against doing this on a transparent proxy.
return NULL;
REFLECTCLASSBASEREF refClass = NULL;
GCPROTECT_BEGIN(refClass);
if (GetAssembly()->IsIntrospectionOnly())
refClass = (REFLECTCLASSBASEREF) AllocateObject(MscorlibBinder::GetClass(CLASS__CLASS_INTROSPECTION_ONLY));
else
refClass = (REFLECTCLASSBASEREF) AllocateObject(g_pRuntimeTypeClass);
LoaderAllocator *pLoaderAllocator = GetLoaderAllocator();
((ReflectClassBaseObject*)OBJECTREFToObject(refClass))->SetType(TypeHandle(this));
((ReflectClassBaseObject*)OBJECTREFToObject(refClass))->SetKeepAlive(pLoaderAllocator->GetExposedObject());
// Let all threads fight over who wins using InterlockedCompareExchange.
// Only the winner can set m_ExposedClassObject from NULL.
LOADERHANDLE exposedClassObjectHandle = pLoaderAllocator->AllocateHandle(refClass);
if (FastInterlockCompareExchangePointer(&(EnsureWritablePages(GetWriteableDataForWrite())->m_hExposedClassObject), exposedClassObjectHandle, static_cast<LOADERHANDLE>(NULL)))
{
pLoaderAllocator->ClearHandle(exposedClassObjectHandle);
}
GCPROTECT_END();
}
RETURN(GetManagedClassObjectIfExists());
}
#endif //!DACCESS_COMPILE && !CROSSGEN_COMPILE
//==========================================================================================
// This needs to stay consistent with AllocateNewMT() and MethodTable::Save()
//
// <TODO> protect this via some asserts as we've had one hard-to-track-down
// bug already </TODO>
//
void MethodTable::GetSavedExtent(TADDR *pStart, TADDR *pEnd)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
TADDR start;
if (ContainsPointersOrCollectible())
start = dac_cast<TADDR>(this) - CGCDesc::GetCGCDescFromMT(this)->GetSize();
else
start = dac_cast<TADDR>(this);
TADDR end = dac_cast<TADDR>(this) + GetEndOffsetOfOptionalMembers();
_ASSERTE(start && end && (start < end));
*pStart = start;
*pEnd = end;
}
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
#ifndef DACCESS_COMPILE
BOOL MethodTable::CanInternVtableChunk(DataImage *image, VtableIndirectionSlotIterator it)
{
STANDARD_VM_CONTRACT;
_ASSERTE(IsCompilationProcess());
BOOL canBeSharedWith = TRUE;
// We allow full sharing except that which would break MethodTable::Fixup -- when the slots are Fixup'd
// we need to ensure that regardless of who is doing the Fixup the same target is decided on.
// Note that if this requirement is not met, an assert will fire in ZapStoredStructure::Save
if (GetFlag(enum_flag_NotInPZM))
{
canBeSharedWith = FALSE;
}
if (canBeSharedWith)
{
for (DWORD slotNumber = it.GetStartSlot(); slotNumber < it.GetEndSlot(); slotNumber++)
{
MethodDesc *pMD = GetMethodDescForSlot(slotNumber);
_ASSERTE(pMD != NULL);
pMD->CheckRestore();
if (!image->CanEagerBindToMethodDesc(pMD))
{
canBeSharedWith = FALSE;
break;
}
}
}
return canBeSharedWith;
}
//==========================================================================================
void MethodTable::PrepopulateDictionary(DataImage * image, BOOL nonExpansive)
{
STANDARD_VM_CONTRACT;
if (GetDictionary())
{
// We can only save elements of the dictionary if we are sure of its
// layout, which means we must be either tightly-knit to the EEClass
// (i.e. be the owner of the EEClass) or else we can hard-bind to the EEClass.
// There's no point in prepopulating the dictionary if we can't save the entries.
//
// This corresponds to the canSaveSlots which we pass to the Dictionary::Fixup
if (!IsCanonicalMethodTable() && image->CanEagerBindToMethodTable(GetCanonicalMethodTable()))
{
LOG((LF_JIT, LL_INFO10000, "GENERICS: Prepopulating dictionary for MT %s\n", GetDebugClassName()));
GetDictionary()->PrepopulateDictionary(NULL, this, nonExpansive);
}
}
}
//==========================================================================================
void ModuleCtorInfo::AddElement(MethodTable *pMethodTable)
{
STANDARD_VM_CONTRACT;
// Get the values for the new entry before we update the
// cache in the Module
// Expand the table if needed. No lock is needed because this is at NGEN time
if (numElements >= numLastAllocated)
{
_ASSERTE(numElements == numLastAllocated);
MethodTable ** ppOldMTEntries = ppMT;
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:22011) // Suppress PREFast warning about integer overflows or underflows
#endif // _PREFAST_
DWORD numNewAllocated = max(2 * numLastAllocated, MODULE_CTOR_ELEMENTS);
#ifdef _PREFAST_
#pragma warning(pop)
#endif // _PREFAST_
ppMT = new MethodTable* [numNewAllocated];
_ASSERTE(ppMT);
memcpy(ppMT, ppOldMTEntries, sizeof(MethodTable *) * numLastAllocated);
memset(ppMT + numLastAllocated, 0, sizeof(MethodTable *) * (numNewAllocated - numLastAllocated));
delete[] ppOldMTEntries;
numLastAllocated = numNewAllocated;
}
// Assign the new entry
//
// Note the use of two "parallel" arrays. We do this to keep the workingset smaller since we
// often search (in GetClassCtorInfoIfExists) for a methodtable pointer but never actually find it.
ppMT[numElements] = pMethodTable;
numElements++;
}
//==========================================================================================
void MethodTable::Save(DataImage *image, DWORD profilingFlags)
{
CONTRACTL {
STANDARD_VM_CHECK;
PRECONDITION(IsRestored_NoLogging());
PRECONDITION(IsFullyLoaded());
PRECONDITION(image->GetModule()->GetAssembly() ==
GetAppDomain()->ToCompilationDomain()->GetTargetAssembly());
} CONTRACTL_END;
LOG((LF_ZAP, LL_INFO10000, "MethodTable::Save %s (%p)\n", GetDebugClassName(), this));
// Be careful about calling DictionaryLayout::Trim - strict conditions apply.
// See note on that method.
if (GetDictionary() &&
GetClass()->GetDictionaryLayout() &&
image->CanEagerBindToMethodTable(GetCanonicalMethodTable()))
{
GetClass()->GetDictionaryLayout()->Trim();
}
// Set the "restore" flags. They may not have been set yet.
// We don't need the return value of this call.
NeedsRestore(image);
//check if this is actually in the PZM
if (Module::GetPreferredZapModuleForMethodTable(this) != GetLoaderModule())
{
_ASSERTE(!IsStringOrArray());
SetFlag(enum_flag_NotInPZM);
}
// Set the IsStructMarshallable Bit
if (::IsStructMarshalable(this))
{
SetStructMarshalable();
}
TADDR start, end;
GetSavedExtent(&start, &end);
#ifdef FEATURE_COMINTEROP
if (HasGuidInfo())
{
// Make sure our GUID is computed
// Generic WinRT types can have their GUID computed only if the instantiation is WinRT-legal
if (IsLegalNonArrayWinRTType())
{
GUID dummy;
if (SUCCEEDED(GetGuidNoThrow(&dummy, TRUE, FALSE)))
{
GuidInfo* pGuidInfo = GetGuidInfo();
_ASSERTE(pGuidInfo != NULL);
image->StoreStructure(pGuidInfo,
sizeof(GuidInfo),
DataImage::ITEM_GUID_INFO);
Module *pModule = GetModule();
if (pModule->CanCacheWinRTTypeByGuid(this))
{
pModule->CacheWinRTTypeByGuid(this, pGuidInfo);
}
}
else
{
GuidInfo** ppGuidInfo = GetGuidInfoPtr();
*ppGuidInfo = NULL;
}
}
}
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_REMOTING
if (HasRemotableMethodInfo())
{
if (GetNumMethods() > 0)
{
// The CrossDomainOptimizationInfo was populated earlier in Module::PrepareTypesForSave
CrossDomainOptimizationInfo* pRMI = GetRemotableMethodInfo();
SIZE_T sizeToBeSaved = CrossDomainOptimizationInfo::SizeOf(this);
image->StoreStructure(pRMI, sizeToBeSaved,
DataImage::ITEM_CROSS_DOMAIN_INFO);
}
}
// Store any optional VTS (Version Tolerant Serialization) info.
if (HasRemotingVtsInfo())
image->StoreStructure(GetRemotingVtsInfo(),
RemotingVtsInfo::GetSize(GetNumIntroducedInstanceFields()),
DataImage::ITEM_VTS_INFO);
#endif //FEATURE_REMOTING
#ifdef _DEBUG
if (GetDebugClassName() != NULL && !image->IsStored(GetDebugClassName()))
image->StoreStructure(debug_m_szClassName, (ULONG)(strlen(GetDebugClassName())+1),
DataImage::ITEM_DEBUG,
1);
#endif // _DEBUG
DataImage::ItemKind kindBasic = DataImage::ITEM_METHOD_TABLE;
if (IsWriteable())
kindBasic = DataImage::ITEM_METHOD_TABLE_SPECIAL_WRITEABLE;
ZapStoredStructure * pMTNode = image->StoreStructure((void*) start, (ULONG)(end - start), kindBasic);
if ((void *)this != (void *)start)
image->BindPointer(this, pMTNode, (BYTE *)this - (BYTE *)start);
// Store the vtable chunks
VtableIndirectionSlotIterator it = IterateVtableIndirectionSlots();
while (it.Next())
{
if (!image->IsStored(it.GetIndirectionSlot()))
{
if (CanInternVtableChunk(image, it))
image->StoreInternedStructure(it.GetIndirectionSlot(), it.GetSize(), DataImage::ITEM_VTABLE_CHUNK);
else
image->StoreStructure(it.GetIndirectionSlot(), it.GetSize(), DataImage::ITEM_VTABLE_CHUNK);
}
else
{
// Tell the interning system that we have already shared this structure without its help
image->NoteReusedStructure(it.GetIndirectionSlot());
}
}
if (HasNonVirtualSlotsArray())
{
image->StoreStructure(GetNonVirtualSlotsArray(), GetNonVirtualSlotsArraySize(), DataImage::ITEM_VTABLE_CHUNK);
}
if (HasInterfaceMap())
{
#ifdef FEATURE_COMINTEROP
// Dynamic interface maps have an additional DWORD_PTR preceding the InterfaceInfo_t array
if (HasDynamicInterfaceMap())
{
ZapStoredStructure * pInterfaceMapNode = image->StoreInternedStructure(((DWORD_PTR *)GetInterfaceMap()) - 1,
GetInterfaceMapSize(),
DataImage::ITEM_INTERFACE_MAP);
image->BindPointer(GetInterfaceMap(), pInterfaceMapNode, sizeof(DWORD_PTR));
}
else
#endif // FEATURE_COMINTEROP
{
image->StoreInternedStructure(GetInterfaceMap(), GetInterfaceMapSize(), DataImage::ITEM_INTERFACE_MAP);
}
SaveExtraInterfaceInfo(image);
}
// If we have a dispatch map, save it.
if (HasDispatchMapSlot())
{
GetDispatchMap()->Save(image);
}
if (HasPerInstInfo())
{
ZapStoredStructure * pPerInstInfoNode;
if (CanEagerBindToParentDictionaries(image, NULL))
{
pPerInstInfoNode = image->StoreInternedStructure((BYTE *)GetPerInstInfo() - sizeof(GenericsDictInfo), GetPerInstInfoSize() + sizeof(GenericsDictInfo), DataImage::ITEM_DICTIONARY);
}
else
{
pPerInstInfoNode = image->StoreStructure((BYTE *)GetPerInstInfo() - sizeof(GenericsDictInfo), GetPerInstInfoSize() + sizeof(GenericsDictInfo), DataImage::ITEM_DICTIONARY_WRITEABLE);
}
image->BindPointer(GetPerInstInfo(), pPerInstInfoNode, sizeof(GenericsDictInfo));
}
Dictionary * pDictionary = GetDictionary();
if (pDictionary != NULL)
{
BOOL fIsWriteable;
if (!IsCanonicalMethodTable())
{
// CanEagerBindToMethodTable would not work for targeted patching here. The dictionary
// layout is sensitive to compilation order that can be changed by TP compatible changes.
BOOL canSaveSlots = (image->GetModule() == GetCanonicalMethodTable()->GetLoaderModule());
fIsWriteable = pDictionary->IsWriteable(image, canSaveSlots,
GetNumGenericArgs(),
GetModule(),
GetClass()->GetDictionaryLayout());
}
else
{
fIsWriteable = FALSE;
}
if (!fIsWriteable)
{
image->StoreInternedStructure(pDictionary, GetInstAndDictSize(), DataImage::ITEM_DICTIONARY);
}
else
{
image->StoreStructure(pDictionary, GetInstAndDictSize(), DataImage::ITEM_DICTIONARY_WRITEABLE);
}
}
WORD numStaticFields = GetClass()->GetNumStaticFields();
if (!IsCanonicalMethodTable() && HasGenericsStaticsInfo() && numStaticFields != 0)
{
FieldDesc * pGenericsFieldDescs = GetGenericsStaticFieldDescs();
for (DWORD i = 0; i < numStaticFields; i++)
{
FieldDesc *pFld = pGenericsFieldDescs + i;
pFld->PrecomputeNameHash();
}
ZapStoredStructure * pFDNode = image->StoreStructure(pGenericsFieldDescs, sizeof(FieldDesc) * numStaticFields,
DataImage::ITEM_GENERICS_STATIC_FIELDDESCS);
for (DWORD i = 0; i < numStaticFields; i++)
{
FieldDesc *pFld = pGenericsFieldDescs + i;
pFld->SaveContents(image);
if (pFld != pGenericsFieldDescs)
image->BindPointer(pFld, pFDNode, (BYTE *)pFld - (BYTE *)pGenericsFieldDescs);
}
}
// Allocate a ModuleCtorInfo entry in the NGEN image if necessary
if (HasBoxedRegularStatics())
{
image->GetModule()->GetZapModuleCtorInfo()->AddElement(this);
}
// MethodTable WriteableData
#ifdef FEATURE_REMOTING
// Store any context static info.
if (HasContextStatics())
{
DataImage::ItemKind kindWriteable = DataImage::ITEM_METHOD_TABLE_DATA_COLD_WRITEABLE;
if ((profilingFlags & (1 << WriteMethodTableWriteableData)) != 0)
kindWriteable = DataImage::ITEM_METHOD_TABLE_DATA_HOT_WRITEABLE;
image->StoreStructure(GetContextStaticsBucket(),
sizeof(ContextStaticsBucket),
kindWriteable);
}
#endif // FEATURE_REMOTING
PTR_Const_MethodTableWriteableData pWriteableData = GetWriteableData_NoLogging();
_ASSERTE(pWriteableData != NULL);
if (pWriteableData != NULL)
{
pWriteableData->Save(image, this, profilingFlags);
}
LOG((LF_ZAP, LL_INFO10000, "MethodTable::Save %s (%p) complete.\n", GetDebugClassName(), this));
// Save the EEClass at the same time as the method table if this is the canonical method table
if (IsCanonicalMethodTable())
GetClass()->Save(image, this);
} // MethodTable::Save
//==========================================================================
// The NeedsRestore Computation.
//
// WARNING: The NeedsRestore predicate on MethodTable and EEClass
// MUST be computable immediately after we have loaded a type.
// It must NOT depend on any additions or changes made to the
// MethodTable as a result of compiling code, or
// later steps such as prepopulating dictionaries.
//==========================================================================
BOOL MethodTable::ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited)
{
CONTRACTL
{
STANDARD_VM_CHECK;
// See comment in ComputeNeedsRestoreWorker
PRECONDITION(GetLoaderModule()->HasNativeImage() || GetLoaderModule() == GetAppDomain()->ToCompilationDomain()->GetTargetModule());
}
CONTRACTL_END;
_ASSERTE(GetAppDomain()->IsCompilationDomain()); // only used at ngen time!
if (GetWriteableData()->IsNeedsRestoreCached())
{
return GetWriteableData()->GetCachedNeedsRestore();
}
// We may speculatively assume that any types we've visited on this run of
// the ComputeNeedsRestore algorithm don't need a restore. If they
// do need a restore then we will check that when we first visit that method
// table.
if (TypeHandleList::Exists(pVisited, TypeHandle(this)))
{
pVisited->MarkBrokenCycle(this);
return FALSE;
}
TypeHandleList newVisited(this, pVisited);
BOOL needsRestore = ComputeNeedsRestoreWorker(image, &newVisited);
// Cache the results of running the algorithm.
// We can only cache the result if we have not speculatively assumed
// that any types are not NeedsRestore
if (!newVisited.HasBrokenCycleMark())
{
GetWriteableDataForWrite()->SetCachedNeedsRestore(needsRestore);
}
else
{
_ASSERTE(pVisited != NULL);
}
return needsRestore;
}
//==========================================================================================
BOOL MethodTable::ComputeNeedsRestoreWorker(DataImage *image, TypeHandleList *pVisited)
{
STANDARD_VM_CONTRACT;
#ifdef _DEBUG
// You should only call ComputeNeedsRestoreWorker on things being saved into
// the current LoaderModule - the NeedsRestore flag should have been computed
// for all items from NGEN images, and we should never compute NeedsRestore
// on anything that is not related to an NGEN image. If this fails then
// there is probably a CanEagerBindTo check missing as we trace through a
// pointer from one data structure to another.
// Trace back on the call stack and work out where this condition first fails.
Module* myModule = GetLoaderModule();
AppDomain* myAppDomain = GetAppDomain();
CompilationDomain* myCompilationDomain = myAppDomain->ToCompilationDomain();
Module* myCompilationModule = myCompilationDomain->GetTargetModule();
if (myModule != myCompilationModule)
{
_ASSERTE(!"You should only call ComputeNeedsRestoreWorker on things being saved into the current LoaderModule");
}
#endif
if (g_CorCompileVerboseLevel == CORCOMPILE_VERBOSE)
{
DefineFullyQualifiedNameForClass();
LPCUTF8 name = GetFullyQualifiedNameForClass(this);
printf ("MethodTable %s needs restore? ", name);
}
if (g_CorCompileVerboseLevel >= CORCOMPILE_STATS && GetModule()->GetNgenStats())
GetModule()->GetNgenStats()->MethodTableRestoreNumReasons[TotalMethodTables]++;
#define UPDATE_RESTORE_REASON(c) \
if (g_CorCompileVerboseLevel == CORCOMPILE_VERBOSE) \
printf ("Yes, " #c " \n"); \
if (g_CorCompileVerboseLevel >= CORCOMPILE_STATS && GetModule()->GetNgenStats()) \
GetModule()->GetNgenStats()->MethodTableRestoreNumReasons[c]++;
// The special method table for IL stubs has to be prerestored. Restore is not able to handle it
// because of it does not have a token. In particular, this is a problem for /profiling native images.
if (this == image->GetModule()->GetILStubCache()->GetStubMethodTable())
{
return FALSE;
}
// When profiling, we always want to perform the restore.
if (GetAppDomain()->ToCompilationDomain()->m_fForceProfiling)
{
UPDATE_RESTORE_REASON(ProfilingEnabled);
return TRUE;
}
if (DependsOnEquivalentOrForwardedStructs())
{
UPDATE_RESTORE_REASON(ComImportStructDependenciesNeedRestore);
return TRUE;
}
if (!IsCanonicalMethodTable() && !image->CanPrerestoreEagerBindToMethodTable(GetCanonicalMethodTable(), pVisited))
{
UPDATE_RESTORE_REASON(CanNotPreRestoreHardBindToCanonicalMethodTable);
return TRUE;
}
if (!image->CanEagerBindToModule(GetModule()))
{
UPDATE_RESTORE_REASON(CrossAssembly);
return TRUE;
}
if (GetParentMethodTable())
{
if (!image->CanPrerestoreEagerBindToMethodTable(GetParentMethodTable(), pVisited))
{
UPDATE_RESTORE_REASON(CanNotPreRestoreHardBindToParentMethodTable);
return TRUE;
}
}
// Check per-inst pointers-to-dictionaries.
if (!CanEagerBindToParentDictionaries(image, pVisited))
{
UPDATE_RESTORE_REASON(CanNotHardBindToInstanceMethodTableChain);
return TRUE;
}
// Now check if the dictionary (if any) owned by this methodtable needs a restore.
if (GetDictionary())
{
if (GetDictionary()->ComputeNeedsRestore(image, pVisited, GetNumGenericArgs()))
{
UPDATE_RESTORE_REASON(GenericsDictionaryNeedsRestore);
return TRUE;
}
}
// The interface chain is traversed without doing CheckRestore's. Thus
// if any of the types in the inherited interfaces hierarchy need a restore
// or are cross-module pointers then this methodtable will also need a restore.
InterfaceMapIterator it = IterateInterfaceMap();
while (it.Next())
{
if (!image->CanPrerestoreEagerBindToMethodTable(it.GetInterface(), pVisited))
{
UPDATE_RESTORE_REASON(InterfaceIsGeneric);
return TRUE;
}
}
if (NeedsCrossModuleGenericsStaticsInfo())
{
UPDATE_RESTORE_REASON(CrossModuleGenericsStatics);
return TRUE;
}
if (IsArray())
{
if(!image->CanPrerestoreEagerBindToTypeHandle(GetApproxArrayElementTypeHandle(), pVisited))
{
UPDATE_RESTORE_REASON(ArrayElement);
return TRUE;
}
}
if (g_CorCompileVerboseLevel == CORCOMPILE_VERBOSE)
printf ("No \n");
return FALSE;
}
//==========================================================================================
BOOL MethodTable::CanEagerBindToParentDictionaries(DataImage *image, TypeHandleList *pVisited)
{
STANDARD_VM_CONTRACT;
MethodTable *pChain = GetParentMethodTable();
while (pChain != NULL)
{
// This is for the case were the method table contains a pointer to
// an inherited dictionary, e.g. given the case D : C, C : B<int>
// where B<int> is in another module then D contains a pointer to the
// dictionary for B<int>. Note that in this case we might still be
// able to hadbind to C.
if (pChain->HasInstantiation())
{
if (!image->CanEagerBindToMethodTable(pChain, FALSE, pVisited) ||
!image->CanHardBindToZapModule(pChain->GetLoaderModule()))
{
return FALSE;
}
}
pChain = pChain->GetParentMethodTable();
}
return TRUE;
}
//==========================================================================================
BOOL MethodTable::NeedsCrossModuleGenericsStaticsInfo()
{
STANDARD_VM_CONTRACT;
return HasGenericsStaticsInfo() && !ContainsGenericVariables() && !IsSharedByGenericInstantiations() &&
(Module::GetPreferredZapModuleForMethodTable(this) != GetLoaderModule());
}
//==========================================================================================
BOOL MethodTable::IsWriteable()
{
STANDARD_VM_CONTRACT;
// Overlapped method table is written into in hosted scenarios
// (see code:CorHost2::GetHostOverlappedExtensionSize)
if (MscorlibBinder::IsClass(this, CLASS__OVERLAPPEDDATA))
return TRUE;
#ifdef FEATURE_COMINTEROP
// Dynamic expansion of interface map writes into method table
// (see code:MethodTable::AddDynamicInterface)
if (HasDynamicInterfaceMap())
return TRUE;
// CCW template is created lazily and when that happens, the
// pointer is written directly into the method table.
if (HasCCWTemplate())
return TRUE;
// RCW per-type data is created lazily at run-time.
if (HasRCWPerTypeData())
return TRUE;
#endif
return FALSE;
}
//==========================================================================================
// This is used when non-canonical (i.e. duplicated) method tables
// attempt to bind to items logically belonging to an EEClass or MethodTable.
// i.e. the contract map in the EEClass and the generic dictionary stored in the canonical
// method table.
//
// We want to check if we can hard bind to the containing structure before
// deciding to hardbind to the inside of it. This is because we may not be able
// to hardbind to all EEClass and/or MethodTables even if they live in a hradbindable
// target module. Thus we want to call CanEagerBindToMethodTable
// to check we can hardbind to the containing structure.
static
void HardBindOrClearDictionaryPointer(DataImage *image, MethodTable *pMT, void * p, SSIZE_T offset)
{
WRAPPER_NO_CONTRACT;
if (image->CanEagerBindToMethodTable(pMT) &&
image->CanHardBindToZapModule(pMT->GetLoaderModule()))
{
image->FixupPointerField(p, offset);
}
else
{
image->ZeroPointerField(p, offset);
}
}
//==========================================================================================
void MethodTable::Fixup(DataImage *image)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(IsFullyLoaded());
}
CONTRACTL_END;
LOG((LF_ZAP, LL_INFO10000, "MethodTable::Fixup %s\n", GetDebugClassName()));
if (GetWriteableData()->IsFixedUp())
return;
BOOL needsRestore = NeedsRestore(image);
LOG((LF_ZAP, LL_INFO10000, "MethodTable::Fixup %s (%p), needsRestore=%d\n", GetDebugClassName(), this, needsRestore));
BOOL isCanonical = IsCanonicalMethodTable();
Module *pZapModule = image->GetModule();
MethodTable *pNewMT = (MethodTable *) image->GetImagePointer(this);
// For canonical method tables, the pointer to the EEClass is never encoded as a fixup
// even if this method table is not in its preferred zap module, i.e. the two are
// "tightly-bound".
if (IsCanonicalMethodTable())
{
// Pointer to EEClass
image->FixupPointerField(this, offsetof(MethodTable, m_pEEClass));
}
else
{
//
// Encode m_pEEClassOrCanonMT
//
MethodTable * pCanonMT = GetCanonicalMethodTable();
ZapNode * pImport = NULL;
if (image->CanEagerBindToMethodTable(pCanonMT))
{
if (image->CanHardBindToZapModule(pCanonMT->GetLoaderModule()))
{
// Pointer to canonical methodtable
image->FixupField(this, offsetof(MethodTable, m_pCanonMT), pCanonMT, UNION_METHODTABLE);
}
else
{
// Pointer to lazy bound indirection cell to canonical methodtable
pImport = image->GetTypeHandleImport(pCanonMT);
}
}
else
{
// Pointer to eager bound indirection cell to canonical methodtable
_ASSERTE(pCanonMT->IsTypicalTypeDefinition() ||
!pCanonMT->ContainsGenericVariables());
pImport = image->GetTypeHandleImport(pCanonMT);
}
if (pImport != NULL)
{
image->FixupFieldToNode(this, offsetof(MethodTable, m_pCanonMT), pImport, UNION_INDIRECTION);
}
}
image->FixupField(this, offsetof(MethodTable, m_pLoaderModule), pZapModule);
#ifdef _DEBUG
image->FixupPointerField(this, offsetof(MethodTable, debug_m_szClassName));
#endif // _DEBUG
MethodTable * pParentMT = GetParentMethodTable();
_ASSERTE(!pNewMT->GetFlag(enum_flag_HasIndirectParent));
if (pParentMT != NULL)
{
//
// Encode m_pParentMethodTable
//
ZapNode * pImport = NULL;
if (image->CanEagerBindToMethodTable(pParentMT))
{
if (image->CanHardBindToZapModule(pParentMT->GetLoaderModule()))
{
image->FixupPointerField(this, offsetof(MethodTable, m_pParentMethodTable));
}
else
{
pImport = image->GetTypeHandleImport(pParentMT);
}
}
else
{
if (!pParentMT->IsCanonicalMethodTable())
{
#ifdef _DEBUG
IMDInternalImport *pInternalImport = GetModule()->GetMDImport();
mdToken crExtends;
pInternalImport->GetTypeDefProps(GetCl(),
NULL,
&crExtends);
_ASSERTE(TypeFromToken(crExtends) == mdtTypeSpec);
#endif
// Use unique cell for now since we are first going to set the parent method table to
// approx one first, and then to the exact one later. This would mess up the shared cell.
// It would be nice to clean it up to use the shared cell - we should set the parent method table
// just once at the end.
pImport = image->GetTypeHandleImport(pParentMT, this /* pUniqueId */);
}
else
{
pImport = image->GetTypeHandleImport(pParentMT);
}
}
if (pImport != NULL)
{
image->FixupFieldToNode(this, offsetof(MethodTable, m_pParentMethodTable), pImport, -(SSIZE_T)offsetof(MethodTable, m_pParentMethodTable));
pNewMT->SetFlag(enum_flag_HasIndirectParent);
}
}
if (HasNonVirtualSlotsArray())
{
TADDR ppNonVirtualSlots = GetNonVirtualSlotsPtr();
PREFIX_ASSUME(ppNonVirtualSlots != NULL);
image->FixupRelativePointerField(this, (BYTE *)ppNonVirtualSlots - (BYTE *)this);
}
if (HasInterfaceMap())
{
image->FixupPointerField(this, offsetof(MethodTable, m_pMultipurposeSlot2));
FixupExtraInterfaceInfo(image);
}
_ASSERTE(GetWriteableData());
image->FixupPointerField(this, offsetof(MethodTable, m_pWriteableData));
m_pWriteableData->Fixup(image, this, needsRestore);
#ifdef FEATURE_COMINTEROP
if (HasGuidInfo())
{
GuidInfo **ppGuidInfo = GetGuidInfoPtr();
if (*ppGuidInfo != NULL)
{
image->FixupPointerField(this, (BYTE *)ppGuidInfo - (BYTE *)this);
}
else
{
image->ZeroPointerField(this, (BYTE *)ppGuidInfo - (BYTE *)this);
}
}
if (HasCCWTemplate())
{
ComCallWrapperTemplate **ppTemplate = GetCCWTemplatePtr();
image->ZeroPointerField(this, (BYTE *)ppTemplate - (BYTE *)this);
}
if (HasRCWPerTypeData())
{
// it would be nice to save these but the impact on mscorlib.ni size is prohibitive
RCWPerTypeData **ppData = GetRCWPerTypeDataPtr();
image->ZeroPointerField(this, (BYTE *)ppData - (BYTE *)this);
}
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_REMOTING
if (HasRemotableMethodInfo())
{
CrossDomainOptimizationInfo **pRMI = GetRemotableMethodInfoPtr();
if (*pRMI != NULL)
{
image->FixupPointerField(this, (BYTE *)pRMI - (BYTE *)this);
}
}
// Optional VTS (Version Tolerant Serialization) fixups.
if (HasRemotingVtsInfo())
{
RemotingVtsInfo **ppVtsInfo = GetRemotingVtsInfoPtr();
image->FixupPointerField(this, (BYTE *)ppVtsInfo - (BYTE *)this);
RemotingVtsInfo *pVtsInfo = *ppVtsInfo;
for (DWORD i = 0; i < RemotingVtsInfo::VTS_NUM_CALLBACK_TYPES; i++)
image->FixupMethodDescPointer(pVtsInfo, &pVtsInfo->m_pCallbacks[i]);
}
#endif //FEATURE_REMOTING
//
// Fix flags
//
_ASSERTE((pNewMT->GetFlag(enum_flag_IsZapped) == 0));
pNewMT->SetFlag(enum_flag_IsZapped);
_ASSERTE((pNewMT->GetFlag(enum_flag_IsPreRestored) == 0));
if (!needsRestore)
pNewMT->SetFlag(enum_flag_IsPreRestored);
//
// Fixup vtable
// If the canonical method table lives in a different loader module
// then just zero out the entries and copy them across from the canonical
// vtable on restore.
//
// Note the canonical method table will be the same as the current method table
// if the method table is not a generic instantiation.
if (HasDispatchMapSlot())
{
TADDR pSlot = GetMultipurposeSlotPtr(enum_flag_HasDispatchMapSlot, c_DispatchMapSlotOffsets);
DispatchMap * pDispatchMap = RelativePointer<PTR_DispatchMap>::GetValueAtPtr(pSlot);
image->FixupField(this, pSlot - (TADDR)this, pDispatchMap, 0, IMAGE_REL_BASED_RelativePointer);
pDispatchMap->Fixup(image);
}
if (HasModuleOverride())
{
image->FixupModulePointer(this, GetModuleOverridePtr());
}
{
VtableIndirectionSlotIterator it = IterateVtableIndirectionSlots();
while (it.Next())
{
image->FixupPointerField(this, it.GetOffsetFromMethodTable());
}
}
unsigned numVTableSlots = GetNumVtableSlots();
for (unsigned slotNumber = 0; slotNumber < numVTableSlots; slotNumber++)
{
//
// Find the method desc from the slot.
//
MethodDesc *pMD = GetMethodDescForSlot(slotNumber);
_ASSERTE(pMD != NULL);
pMD->CheckRestore();
PVOID slotBase;
SSIZE_T slotOffset;
if (slotNumber < GetNumVirtuals())
{
// Virtual slots live in chunks pointed to by vtable indirections
slotBase = (PVOID) GetVtableIndirections()[GetIndexOfVtableIndirection(slotNumber)];
slotOffset = GetIndexAfterVtableIndirection(slotNumber) * sizeof(PCODE);
}
else if (HasSingleNonVirtualSlot())
{
// Non-virtual slots < GetNumVtableSlots live in a single chunk pointed to by an optional member,
// except when there is only one in which case it lives in the optional member itself
_ASSERTE(slotNumber == GetNumVirtuals());
slotBase = (PVOID) this;
slotOffset = (BYTE *)GetSlotPtr(slotNumber) - (BYTE *)this;
}
else
{
// Non-virtual slots < GetNumVtableSlots live in a single chunk pointed to by an optional member
_ASSERTE(HasNonVirtualSlotsArray());
slotBase = (PVOID) GetNonVirtualSlotsArray();
slotOffset = (slotNumber - GetNumVirtuals()) * sizeof(PCODE);
}
// Attempt to make the slot point directly at the prejitted code.
// Note that changes to this logic may require or enable an update to CanInternVtableChunk.
// If a necessary update is not made, an assert will fire in ZapStoredStructure::Save.
if (pMD->GetMethodTable() == this)
{
ZapRelocationType relocType;
if (slotNumber >= GetNumVirtuals())
relocType = IMAGE_REL_BASED_RelativePointer;
else
relocType = IMAGE_REL_BASED_PTR;
pMD->FixupSlot(image, slotBase, slotOffset, relocType);
}
else
{
#ifdef _DEBUG
// Static method should be in the owning methodtable only.
_ASSERTE(!pMD->IsStatic());
MethodTable *pSourceMT = isCanonical
? GetParentMethodTable()
: GetCanonicalMethodTable();
// It must be inherited from the parent or copied from the canonical
_ASSERTE(pSourceMT->GetMethodDescForSlot(slotNumber) == pMD);
#endif
if (image->CanEagerBindToMethodDesc(pMD) && pMD->GetLoaderModule() == pZapModule)
{
pMD->FixupSlot(image, slotBase, slotOffset);
}
else
{
if (!pMD->IsGenericMethodDefinition())
{
ZapNode * importThunk = image->GetVirtualImportThunk(pMD->GetMethodTable(), pMD, slotNumber);
// On ARM, make sure that the address to the virtual thunk that we write into the
// vtable "chunk" has the Thumb bit set.
image->FixupFieldToNode(slotBase, slotOffset, importThunk ARM_ARG(THUMB_CODE));
}
else
{
// Virtual generic methods don't/can't use their vtable slot
image->ZeroPointerField(slotBase, slotOffset);
}
}
}
}
//
// Fixup Interface map
//
InterfaceMapIterator it = IterateInterfaceMap();
while (it.Next())
{
image->FixupMethodTablePointer(GetInterfaceMap(), &it.GetInterfaceInfo()->m_pMethodTable);
}
if (IsArray())
{
image->HardBindTypeHandlePointer(this, offsetof(MethodTable, m_ElementTypeHnd));
}
//
// Fixup per-inst pointers for this method table
//
if (HasPerInstInfo())
{
// Fixup the pointer to the per-inst table
image->FixupPointerField(this, offsetof(MethodTable, m_pPerInstInfo));
for (MethodTable *pChain = this; pChain != NULL; pChain = pChain->GetParentMethodTable())
{
if (pChain->HasInstantiation())
{
DWORD dictNum = pChain->GetNumDicts()-1;
// If we can't hardbind then the value will be copied down from
// the parent upon restore.
// We special-case the dictionary for this method table because we must always
// hard bind to it even if it's not in its preferred zap module
if (pChain == this)
image->FixupPointerField(GetPerInstInfo(), dictNum * sizeof(Dictionary *));
else
HardBindOrClearDictionaryPointer(image, pChain, GetPerInstInfo(), dictNum * sizeof(Dictionary *));
}
}
}
//
// Fixup instantiation+dictionary for this method table (if any)
//
if (GetDictionary())
{
LOG((LF_JIT, LL_INFO10000, "GENERICS: Fixup dictionary for MT %s\n", GetDebugClassName()));
// CanEagerBindToMethodTable would not work for targeted patching here. The dictionary
// layout is sensitive to compilation order that can be changed by TP compatible changes.
BOOL canSaveSlots = !IsCanonicalMethodTable() && (image->GetModule() == GetCanonicalMethodTable()->GetLoaderModule());
// See comment on Dictionary::Fixup
GetDictionary()->Fixup(image,
TRUE,
canSaveSlots,
GetNumGenericArgs(),
GetModule(),
GetClass()->GetDictionaryLayout());
}
// Fixup per-inst statics info
if (HasGenericsStaticsInfo())
{
GenericsStaticsInfo *pInfo = GetGenericsStaticsInfo();
image->FixupPointerField(this, (BYTE *)&pInfo->m_pFieldDescs - (BYTE *)this);
if (!isCanonical)
{
for (DWORD i = 0; i < GetClass()->GetNumStaticFields(); i++)
{
FieldDesc *pFld = GetGenericsStaticFieldDescs() + i;
pFld->Fixup(image);
}
}
if (NeedsCrossModuleGenericsStaticsInfo())
{
MethodTableWriteableData * pNewWriteableData = (MethodTableWriteableData *)image->GetImagePointer(m_pWriteableData);
CrossModuleGenericsStaticsInfo * pNewCrossModuleGenericsStaticsInfo = pNewWriteableData->GetCrossModuleGenericsStaticsInfo();
pNewCrossModuleGenericsStaticsInfo->m_DynamicTypeID = pInfo->m_DynamicTypeID;
image->ZeroPointerField(m_pWriteableData, sizeof(MethodTableWriteableData) + offsetof(CrossModuleGenericsStaticsInfo, m_pModuleForStatics));
pNewMT->SetFlag(enum_flag_StaticsMask_IfGenericsThenCrossModule);
}
}
else
{
_ASSERTE(!NeedsCrossModuleGenericsStaticsInfo());
}
#ifdef FEATURE_REMOTING
if (HasContextStatics())
{
ContextStaticsBucket **ppInfo = GetContextStaticsBucketPtr();
image->FixupPointerField(this, (BYTE *)ppInfo - (BYTE *)this);
ContextStaticsBucket *pNewInfo = (ContextStaticsBucket*)image->GetImagePointer(*ppInfo);
pNewInfo->m_dwContextStaticsOffset = (DWORD)-1;
}
#endif // FEATURE_REMOTING
LOG((LF_ZAP, LL_INFO10000, "MethodTable::Fixup %s (%p) complete\n", GetDebugClassName(), this));
// If this method table is canonical (one-to-one with EEClass) then fix up the EEClass also
if (isCanonical)
GetClass()->Fixup(image, this);
// Mark method table as fixed-up
GetWriteableDataForWrite()->SetFixedUp();
} // MethodTable::Fixup
//==========================================================================================
void MethodTableWriteableData::Save(DataImage *image, MethodTable *pMT, DWORD profilingFlags) const
{
STANDARD_VM_CONTRACT;
SIZE_T size = sizeof(MethodTableWriteableData);
// MethodTableWriteableData is followed by optional CrossModuleGenericsStaticsInfo in NGen images
if (pMT->NeedsCrossModuleGenericsStaticsInfo())
size += sizeof(CrossModuleGenericsStaticsInfo);
DataImage::ItemKind kindWriteable = DataImage::ITEM_METHOD_TABLE_DATA_COLD_WRITEABLE;
if ((profilingFlags & (1 << WriteMethodTableWriteableData)) != 0)
kindWriteable = DataImage::ITEM_METHOD_TABLE_DATA_HOT_WRITEABLE;
ZapStoredStructure * pNode = image->StoreStructure(NULL, size, kindWriteable);
image->BindPointer(this, pNode, 0);
image->CopyData(pNode, this, sizeof(MethodTableWriteableData));
}
//==========================================================================================
void MethodTableWriteableData::Fixup(DataImage *image, MethodTable *pMT, BOOL needsRestore)
{
STANDARD_VM_CONTRACT;
image->ZeroField(this, offsetof(MethodTableWriteableData, m_hExposedClassObject), sizeof(m_hExposedClassObject));
MethodTableWriteableData *pNewNgenPrivateMT = (MethodTableWriteableData*) image->GetImagePointer(this);
_ASSERTE(pNewNgenPrivateMT != NULL);
pNewNgenPrivateMT->m_dwFlags &= ~(enum_flag_RemotingConfigChecked |
enum_flag_CriticalTypePrepared);
if (needsRestore)
pNewNgenPrivateMT->m_dwFlags |= (enum_flag_UnrestoredTypeKey |
enum_flag_Unrestored |
enum_flag_HasApproxParent |
enum_flag_IsNotFullyLoaded);
#ifdef _DEBUG
pNewNgenPrivateMT->m_dwLastVerifedGCCnt = (DWORD)-1;
#endif
}
#endif // !DACCESS_COMPILE
#endif // FEATURE_NATIVE_IMAGE_GENERATION
#ifdef FEATURE_PREJIT
//==========================================================================================
void MethodTable::CheckRestore()
{
CONTRACTL
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
}
CONTRACTL_END
if (!IsFullyLoaded())
{
ClassLoader::EnsureLoaded(this);
_ASSERTE(IsFullyLoaded());
}
g_IBCLogger.LogMethodTableAccess(this);
}
#else // !FEATURE_PREJIT
//==========================================================================================
void MethodTable::CheckRestore()
{
LIMITED_METHOD_CONTRACT;
}
#endif // !FEATURE_PREJIT
#ifndef DACCESS_COMPILE
BOOL SatisfiesClassConstraints(TypeHandle instanceTypeHnd, TypeHandle typicalTypeHnd,
const InstantiationContext *pInstContext);
static VOID DoAccessibilityCheck(MethodTable *pAskingMT, MethodTable *pTargetMT, UINT resIDWhy, BOOL checkTargetTypeTransparency)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END;
StaticAccessCheckContext accessContext(NULL, pAskingMT);
if (!ClassLoader::CanAccessClass(&accessContext,
pTargetMT, //the desired class
pTargetMT->GetAssembly(), //the desired class's assembly
*AccessCheckOptions::s_pNormalAccessChecks,
checkTargetTypeTransparency
))
{
SString displayName;
pAskingMT->GetAssembly()->GetDisplayName(displayName);
SString targetName;
// Error string is either E_ACCESSDENIED which requires the type name of the target, vs
// a more normal TypeLoadException which displays the requesting type.
_ASSERTE((resIDWhy == (UINT)E_ACCESSDENIED) || (resIDWhy == (UINT)IDS_CLASSLOAD_INTERFACE_NO_ACCESS));
TypeString::AppendType(targetName, TypeHandle((resIDWhy == (UINT)E_ACCESSDENIED) ? pTargetMT : pAskingMT));
COMPlusThrow(kTypeLoadException, resIDWhy, targetName.GetUnicode(), displayName.GetUnicode());
}
}
VOID DoAccessibilityCheckForConstraint(MethodTable *pAskingMT, TypeHandle thConstraint, UINT resIDWhy)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END;
if (thConstraint.IsTypeDesc())
{
TypeDesc *pTypeDesc = thConstraint.AsTypeDesc();
if (pTypeDesc->IsGenericVariable())
{
// since the metadata respresents a generic type param constraint as an index into
// the declaring type's list of generic params, it is structurally impossible
// to express a violation this way. So there's no check to be done here.
}
else
if (pTypeDesc->HasTypeParam())
{
DoAccessibilityCheckForConstraint(pAskingMT, pTypeDesc->GetTypeParam(), resIDWhy);
}
else
{
COMPlusThrow(kTypeLoadException, E_ACCESSDENIED);
}
}
else
{
DoAccessibilityCheck(pAskingMT, thConstraint.GetMethodTable(), resIDWhy, FALSE);
}
}
VOID DoAccessibilityCheckForConstraints(MethodTable *pAskingMT, TypeVarTypeDesc *pTyVar, UINT resIDWhy)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END;
DWORD numConstraints;
TypeHandle *pthConstraints = pTyVar->GetCachedConstraints(&numConstraints);
for (DWORD cidx = 0; cidx < numConstraints; cidx++)
{
TypeHandle thConstraint = pthConstraints[cidx];
DoAccessibilityCheckForConstraint(pAskingMT, thConstraint, resIDWhy);
}
}
// Recursive worker that pumps the transitive closure of a type's dependencies to the specified target level.
// Dependencies include:
//
// - parent
// - interfaces
// - canonical type, for non-canonical instantiations
// - typical type, for non-typical instantiations
//
// Parameters:
//
// pVisited - used to prevent endless recursion in the case of cyclic dependencies
//
// level - target level to pump to - must be CLASS_DEPENDENCIES_LOADED or CLASS_LOADED
//
// if CLASS_DEPENDENCIES_LOADED, all transitive dependencies are resolved to their
// exact types.
//
// if CLASS_LOADED, all type-safety checks are done on the type and all its transitive
// dependencies. Note that for the CLASS_LOADED case, some types may be left
// on the pending list rather that pushed to CLASS_LOADED in the case of cyclic
// dependencies - the root caller must handle this.
//
// pfBailed - if we or one of our depedencies bails early due to cyclic dependencies, we
// must set *pfBailed to TRUE. Otherwise, we must *leave it unchanged* (thus, the
// boolean acts as a cumulative OR.)
//
// pPending - if one of our dependencies bailed, the type cannot yet be promoted to CLASS_LOADED
// as the dependencies will be checked later and may fail a security check then.
// Instead, DoFullyLoad() will add the type to the pending list - the root caller
// is responsible for promoting the type after the full transitive closure has been
// walked. Note that it would be just as correct to always defer to the pending list -
// however, that is a little less performant.
//
// Closure of locals necessary for implementing CheckForEquivalenceAndFullyLoadType.
// Used so that we can have one valuetype walking algorithm used for type equivalence walking of the parameters of the method.
struct DoFullyLoadLocals
{
DoFullyLoadLocals(DFLPendingList *pPendingParam, ClassLoadLevel levelParam, MethodTable *pMT, Generics::RecursionGraph *pVisited) :
newVisited(pVisited, TypeHandle(pMT)),
pPending(pPendingParam),
level(levelParam),
fBailed(FALSE)
#ifdef FEATURE_COMINTEROP
, fHasEquivalentStructParameter(FALSE)
#endif
, fHasTypeForwarderDependentStructParameter(FALSE)
, fDependsOnEquivalentOrForwardedStructs(FALSE)
{
LIMITED_METHOD_CONTRACT;
}
Generics::RecursionGraph newVisited;
DFLPendingList * const pPending;
const ClassLoadLevel level;
BOOL fBailed;
#ifdef FEATURE_COMINTEROP
BOOL fHasEquivalentStructParameter;
#endif
BOOL fHasTypeForwarderDependentStructParameter;
BOOL fDependsOnEquivalentOrForwardedStructs;
};
#if defined(FEATURE_TYPEEQUIVALENCE) && !defined(DACCESS_COMPILE)
static void CheckForEquivalenceAndFullyLoadType(Module *pModule, mdToken token, Module *pDefModule, mdToken defToken, const SigParser *ptr, SigTypeContext *pTypeContext, void *pData)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
SO_INTOLERANT;
}
CONTRACTL_END;
SigPointer sigPtr(*ptr);
DoFullyLoadLocals *pLocals = (DoFullyLoadLocals *)pData;
if (IsTypeDefEquivalent(defToken, pDefModule))
{
TypeHandle th = sigPtr.GetTypeHandleThrowing(pModule, pTypeContext, ClassLoader::LoadTypes, (ClassLoadLevel)(pLocals->level - 1));
CONSISTENCY_CHECK(!th.IsNull());
th.DoFullyLoad(&pLocals->newVisited, pLocals->level, pLocals->pPending, &pLocals->fBailed, NULL);
pLocals->fDependsOnEquivalentOrForwardedStructs = TRUE;
pLocals->fHasEquivalentStructParameter = TRUE;
}
}
#endif // defined(FEATURE_TYPEEQUIVALENCE) && !defined(DACCESS_COMPILE)
struct CheckForTypeForwardedTypeRefParameterLocals
{
Module * pModule;
BOOL * pfTypeForwarderFound;
};
// Callback for code:WalkValueTypeTypeDefOrRefs of type code:PFN_WalkValueTypeTypeDefOrRefs
static void CheckForTypeForwardedTypeRef(
mdToken tkTypeDefOrRef,
void * pData)
{
STANDARD_VM_CONTRACT;
CheckForTypeForwardedTypeRefParameterLocals * pLocals = (CheckForTypeForwardedTypeRefParameterLocals *)pData;
// If a type forwarder was found, return - we're done
if ((pLocals->pfTypeForwarderFound != NULL) && (*(pLocals->pfTypeForwarderFound)))
return;
// Only type ref's are interesting
if (TypeFromToken(tkTypeDefOrRef) == mdtTypeRef)
{
Module * pDummyModule;
mdToken tkDummy;
ClassLoader::ResolveTokenToTypeDefThrowing(
pLocals->pModule,
tkTypeDefOrRef,
&pDummyModule,
&tkDummy,
Loader::Load,
pLocals->pfTypeForwarderFound);
}
}
typedef void (* PFN_WalkValueTypeTypeDefOrRefs)(mdToken tkTypeDefOrRef, void * pData);
// Call 'function' for ValueType in the signature.
void WalkValueTypeTypeDefOrRefs(
const SigParser * pSig,
PFN_WalkValueTypeTypeDefOrRefs function,
void * pData)
{
STANDARD_VM_CONTRACT;
SigParser sig(*pSig);
CorElementType typ;
IfFailThrow(sig.GetElemType(&typ));
switch (typ)
{
case ELEMENT_TYPE_VALUETYPE:
mdToken token;
IfFailThrow(sig.GetToken(&token));
function(token, pData);
break;
case ELEMENT_TYPE_GENERICINST:
// Process and skip generic type
WalkValueTypeTypeDefOrRefs(&sig, function, pData);
IfFailThrow(sig.SkipExactlyOne());
// Get number of parameters
ULONG argCnt;
IfFailThrow(sig.GetData(&argCnt));
while (argCnt-- != 0)
{ // Process and skip generic parameter
WalkValueTypeTypeDefOrRefs(&sig, function, pData);
IfFailThrow(sig.SkipExactlyOne());
}
break;
default:
break;
}
}
// Callback for code:MethodDesc::WalkValueTypeParameters (of type code:WalkValueTypeParameterFnPtr)
static void CheckForTypeForwardedTypeRefParameter(
Module * pModule,
mdToken token,
Module * pDefModule,
mdToken defToken,
const SigParser *ptr,
SigTypeContext * pTypeContext,
void * pData)
{
STANDARD_VM_CONTRACT;
DoFullyLoadLocals * pLocals = (DoFullyLoadLocals *)pData;
// If a type forwarder was found, return - we're done
if (pLocals->fHasTypeForwarderDependentStructParameter)
return;
CheckForTypeForwardedTypeRefParameterLocals locals;
locals.pModule = pModule;
locals.pfTypeForwarderFound = &pLocals->fHasTypeForwarderDependentStructParameter; // By not passing NULL here, we determine if there is a type forwarder involved.
WalkValueTypeTypeDefOrRefs(ptr, CheckForTypeForwardedTypeRef, &locals);
if (pLocals->fHasTypeForwarderDependentStructParameter)
pLocals->fDependsOnEquivalentOrForwardedStructs = TRUE;
}
// Callback for code:MethodDesc::WalkValueTypeParameters (of type code:WalkValueTypeParameterFnPtr)
static void LoadTypeDefOrRefAssembly(
Module * pModule,
mdToken token,
Module * pDefModule,
mdToken defToken,
const SigParser *ptr,
SigTypeContext * pTypeContext,
void * pData)
{
STANDARD_VM_CONTRACT;
DoFullyLoadLocals * pLocals = (DoFullyLoadLocals *)pData;
CheckForTypeForwardedTypeRefParameterLocals locals;
locals.pModule = pModule;
locals.pfTypeForwarderFound = NULL; // By passing NULL here, we simply resolve the token to TypeDef.
WalkValueTypeTypeDefOrRefs(ptr, CheckForTypeForwardedTypeRef, &locals);
}
#endif //!DACCESS_COMPILE
void MethodTable::DoFullyLoad(Generics::RecursionGraph * const pVisited, const ClassLoadLevel level, DFLPendingList * const pPending,
BOOL * const pfBailed, const InstantiationContext * const pInstContext)
{
STANDARD_VM_CONTRACT;
_ASSERTE(level == CLASS_LOADED || level == CLASS_DEPENDENCIES_LOADED);
_ASSERTE(pfBailed != NULL);
_ASSERTE(!(level == CLASS_LOADED && pPending == NULL));
#ifndef DACCESS_COMPILE
if (Generics::RecursionGraph::HasSeenType(pVisited, TypeHandle(this)))
{
*pfBailed = TRUE;
return;
}
if (GetLoadLevel() >= level)
{
return;
}
if (level == CLASS_LOADED)
{
UINT numTH = pPending->Count();
TypeHandle *pTypeHndPending = pPending->Table();
for (UINT idxPending = 0; idxPending < numTH; idxPending++)
{
if (pTypeHndPending[idxPending] == this)
{
*pfBailed = TRUE;
return;
}
}
}
BEGIN_SO_INTOLERANT_CODE(GetThread());
// First ensure that we're loaded to just below CLASS_DEPENDENCIES_LOADED
ClassLoader::EnsureLoaded(this, (ClassLoadLevel) (level-1));
CONSISTENCY_CHECK(IsRestored_NoLogging());
CONSISTENCY_CHECK(!HasApproxParent());
DoFullyLoadLocals locals(pPending, level, this, pVisited);
bool fNeedsSanityChecks = !IsZapped(); // Validation has been performed for NGened classes already
#ifdef FEATURE_READYTORUN
if (fNeedsSanityChecks)
{
Module * pModule = GetModule();
// No sanity checks for ready-to-run compiled images if possible
if (pModule->IsReadyToRun() && pModule->GetReadyToRunInfo()->SkipTypeValidation())
fNeedsSanityChecks = false;
}
#endif
bool fNeedAccessChecks = (level == CLASS_LOADED) &&
fNeedsSanityChecks &&
IsTypicalTypeDefinition();
TypeHandle typicalTypeHnd;
if (!IsZapped()) // Validation has been performed for NGened classes already
{
// Fully load the typical instantiation. Make sure that this is done before loading other dependencies
// as the recursive generics detection algorithm needs to examine typical instantiations of the types
// in the closure.
if (!IsTypicalTypeDefinition())
{
typicalTypeHnd = ClassLoader::LoadTypeDefThrowing(GetModule(), GetCl(),
ClassLoader::ThrowIfNotFound, ClassLoader::PermitUninstDefOrRef, tdNoTypes,
(ClassLoadLevel) (level - 1));
CONSISTENCY_CHECK(!typicalTypeHnd.IsNull());
typicalTypeHnd.DoFullyLoad(&locals.newVisited, level, pPending, &locals.fBailed, pInstContext);
}
else if (level == CLASS_DEPENDENCIES_LOADED && HasInstantiation())
{
// This is a typical instantiation of a generic type. When attaining CLASS_DEPENDENCIES_LOADED, the
// recursive inheritance graph (ECMA part.II Section 9.2) will be constructed and checked for "expanding
// cycles" to detect infinite recursion, e.g. A<T> : B<A<A<T>>>.
//
// The dependencies loaded by this method (parent type, implemented interfaces, generic arguments)
// ensure that we will generate the finite instantiation closure as defined in ECMA. This load level
// is not being attained under lock so it's not possible to use TypeVarTypeDesc to represent graph
// nodes because multiple threads trying to fully load types from the closure at the same time would
// interfere with each other. In addition, the graph is only used for loading and can be discarded
// when the closure is fully loaded (TypeVarTypeDesc need to stay).
//
// The graph is represented by Generics::RecursionGraph instances organized in a linked list with
// each of them holding part of the graph. They live on the stack and are cleaned up automatically
// before returning from DoFullyLoad.
if (locals.newVisited.CheckForIllegalRecursion())
{
// An expanding cycle was detected, this type is part of a closure that is defined recursively.
IMDInternalImport* pInternalImport = GetModule()->GetMDImport();
GetModule()->GetAssembly()->ThrowTypeLoadException(pInternalImport, GetCl(), IDS_CLASSLOAD_GENERICTYPE_RECURSIVE);
}
}
}
// Fully load the parent
MethodTable *pParentMT = GetParentMethodTable();
if (pParentMT)
{
pParentMT->DoFullyLoad(&locals.newVisited, level, pPending, &locals.fBailed, pInstContext);
if (fNeedAccessChecks)
{
if (!IsComObjectType()) //RCW's are special - they are manufactured by the runtime and derive from the non-public type System.__ComObject
{
// A transparenct type should not be allowed to derive from a critical type.
// However since this has never been enforced before we have many classes that
// violate this rule. Enforcing it now will be a breaking change.
DoAccessibilityCheck(this, pParentMT, E_ACCESSDENIED, /* checkTargetTypeTransparency*/ FALSE);
}
}
}
// Fully load the interfaces
MethodTable::InterfaceMapIterator it = IterateInterfaceMap();
while (it.Next())
{
it.GetInterface()->DoFullyLoad(&locals.newVisited, level, pPending, &locals.fBailed, pInstContext);
if (fNeedAccessChecks)
{
if (IsInterfaceDeclaredOnClass(it.GetIndex())) // only test directly implemented interfaces (it's
// legal for an inherited interface to be private.)
{
// A transparenct type should not be allowed to implement a critical interface.
// However since this has never been enforced before we have many classes that
// violate this rule. Enforcing it now will be a breaking change.
DoAccessibilityCheck(this, it.GetInterface(), IDS_CLASSLOAD_INTERFACE_NO_ACCESS, /* checkTargetTypeTransparency*/ FALSE);
}
}
}
// Fully load the generic arguments
Instantiation inst = GetInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
inst[i].DoFullyLoad(&locals.newVisited, level, pPending, &locals.fBailed, pInstContext);
}
// Fully load the canonical methodtable
if (!IsCanonicalMethodTable())
{
GetCanonicalMethodTable()->DoFullyLoad(&locals.newVisited, level, pPending, &locals.fBailed, NULL);
}
if (fNeedsSanityChecks)
{
// Fully load the exact field types for value type fields
// Note that MethodTableBuilder::InitializeFieldDescs() loads the type of the
// field only upto level CLASS_LOAD_APPROXPARENTS.
FieldDesc *pField = GetApproxFieldDescListRaw();
FieldDesc *pFieldEnd = pField + GetNumStaticFields() + GetNumIntroducedInstanceFields();
while (pField < pFieldEnd)
{
g_IBCLogger.LogFieldDescsAccess(pField);
if (pField->GetFieldType() == ELEMENT_TYPE_VALUETYPE)
{
TypeHandle th = pField->GetFieldTypeHandleThrowing((ClassLoadLevel) (level - 1));
CONSISTENCY_CHECK(!th.IsNull());
th.DoFullyLoad(&locals.newVisited, level, pPending, &locals.fBailed, pInstContext);
if (fNeedAccessChecks)
{
DoAccessibilityCheck(this, th.GetMethodTable(), E_ACCESSDENIED, FALSE);
}
}
pField++;
}
// Fully load the exact field types for generic value type fields
if (HasGenericsStaticsInfo())
{
FieldDesc *pGenStaticField = GetGenericsStaticFieldDescs();
FieldDesc *pGenStaticFieldEnd = pGenStaticField + GetNumStaticFields();
while (pGenStaticField < pGenStaticFieldEnd)
{
if (pGenStaticField->GetFieldType() == ELEMENT_TYPE_VALUETYPE)
{
TypeHandle th = pGenStaticField->GetFieldTypeHandleThrowing((ClassLoadLevel) (level - 1));
CONSISTENCY_CHECK(!th.IsNull());
th.DoFullyLoad(&locals.newVisited, level, pPending, &locals.fBailed, pInstContext);
// The accessibility check is not necessary for generic fields. The generic fields are copy
// of the regular fields, the only difference is that they have the exact type.
}
pGenStaticField++;
}
}
}
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
// Fully load the types of fields associated with a field marshaler when ngenning
if (HasLayout() && GetAppDomain()->IsCompilationDomain() && !IsZapped())
{
FieldMarshaler* pFM = this->GetLayoutInfo()->GetFieldMarshalers();
UINT numReferenceFields = this->GetLayoutInfo()->GetNumCTMFields();
while (numReferenceFields--)
{
FieldDesc *pMarshalerField = pFM->GetFieldDesc();
// If the fielddesc pointer here is a token tagged pointer, then the field marshaler that we are
// working with will not need to be saved into this ngen image. And as that was the reason that we
// needed to load this type, thus we will not need to fully load the type associated with this field desc.
//
if (!CORCOMPILE_IS_POINTER_TAGGED(pMarshalerField))
{
TypeHandle th = pMarshalerField->GetFieldTypeHandleThrowing((ClassLoadLevel) (level-1));
CONSISTENCY_CHECK(!th.IsNull());
th.DoFullyLoad(&locals.newVisited, level, pPending, &locals.fBailed, pInstContext);
}
// The accessibility check is not used here to prevent functional differences between ngen and non-ngen scenarios.
((BYTE*&)pFM) += MAXFIELDMARSHALERSIZE;
}
}
#endif //FEATURE_NATIVE_IMAGE_GENERATION
// Fully load exact parameter types for value type parameters opted into equivalence. This is required in case GC is
// triggered during prestub. GC needs to know where references are on the stack and if the parameter (as read from
// the method signature) is a structure, it relies on the loaded type to get the layout information from. For ordinary
// structures we are guaranteed to have loaded the type before entering prestub - the caller must have loaded it.
// However due to type equivalence, the caller may work with a different type than what's in the method signature.
//
// We deal with situation by eagerly loading types that may cause these problems, i.e. value types in signatures of
// methods introduced by this type. To avoid the perf hit for scenarios without type equivalence, we only preload
// structures that marked as type equivalent. In the no-PIA world
// these structures are called "local types" and are usually generated automatically by the compiler. Note that there
// is a related logic in code:CompareTypeDefsForEquivalence that declares two tokens corresponding to structures as
// equivalent based on an extensive set of equivalency checks..
//
// To address this situation for NGENed types and methods, we prevent pre-restoring them - see code:ComputeNeedsRestoreWorker
// for details. That forces them to go through the final stages of loading at run-time and hit the same code below.
if ((level == CLASS_LOADED)
&& (GetCl() != mdTypeDefNil)
&& !ContainsGenericVariables()
&& (!IsZapped()
|| DependsOnEquivalentOrForwardedStructs()
#ifdef DEBUG
|| TRUE // Always load types in debug builds so that we calculate fDependsOnEquivalentOrForwardedStructs all of the time
#endif
)
)
{
MethodTable::IntroducedMethodIterator itMethods(this, FALSE);
for (; itMethods.IsValid(); itMethods.Next())
{
MethodDesc * pMD = itMethods.GetMethodDesc();
if (IsCompilationProcess())
{
locals.fHasTypeForwarderDependentStructParameter = FALSE;
EX_TRY
{
pMD->WalkValueTypeParameters(this, CheckForTypeForwardedTypeRefParameter, &locals);
}
EX_CATCH
{
}
EX_END_CATCH(RethrowTerminalExceptions);
// This marks the class as needing restore.
if (locals.fHasTypeForwarderDependentStructParameter && !pMD->IsZapped())
pMD->SetHasForwardedValuetypeParameter();
}
else if (pMD->IsZapped() && pMD->HasForwardedValuetypeParameter())
{
pMD->WalkValueTypeParameters(this, LoadTypeDefOrRefAssembly, NULL);
locals.fDependsOnEquivalentOrForwardedStructs = TRUE;
}
#ifdef FEATURE_TYPEEQUIVALENCE
if (!pMD->DoesNotHaveEquivalentValuetypeParameters() && pMD->IsVirtual())
{
locals.fHasEquivalentStructParameter = FALSE;
pMD->WalkValueTypeParameters(this, CheckForEquivalenceAndFullyLoadType, &locals);
if (!locals.fHasEquivalentStructParameter && !IsZapped())
pMD->SetDoesNotHaveEquivalentValuetypeParameters();
}
#else
#ifdef FEATURE_PREJIT
if (!IsZapped() && pMD->IsVirtual() && !IsCompilationProcess() )
{
pMD->PrepareForUseAsADependencyOfANativeImage();
}
#endif
#endif //FEATURE_TYPEEQUIVALENCE
}
}
_ASSERTE(!IsZapped() || !IsCanonicalMethodTable() || (level != CLASS_LOADED) || ((!!locals.fDependsOnEquivalentOrForwardedStructs) == (!!DependsOnEquivalentOrForwardedStructs())));
if (locals.fDependsOnEquivalentOrForwardedStructs)
{
if (!IsZapped())
{
// if this type declares a method that has an equivalent or type forwarded structure as a parameter type,
// make sure we come here and pre-load these structure types in NGENed cases as well
SetDependsOnEquivalentOrForwardedStructs();
}
}
// The rules for constraint cycles are same as rules for acccess checks
if (fNeedAccessChecks)
{
// Check for cyclical class constraints
{
Instantiation formalParams = GetInstantiation();
for (DWORD i = 0; i < formalParams.GetNumArgs(); i++)
{
BOOL Bounded(TypeVarTypeDesc *tyvar, DWORD depth);
TypeVarTypeDesc *pTyVar = formalParams[i].AsGenericVariable();
pTyVar->LoadConstraints(CLASS_DEPENDENCIES_LOADED);
if (!Bounded(pTyVar, formalParams.GetNumArgs()))
{
COMPlusThrow(kTypeLoadException, VER_E_CIRCULAR_VAR_CONSTRAINTS);
}
DoAccessibilityCheckForConstraints(this, pTyVar, E_ACCESSDENIED);
}
}
// Check for cyclical method constraints
{
if (GetCl() != mdTypeDefNil) // Make sure this is actually a metadata type!
{
MethodTable::IntroducedMethodIterator itMethods(this, FALSE);
for (; itMethods.IsValid(); itMethods.Next())
{
MethodDesc * pMD = itMethods.GetMethodDesc();
if (pMD->IsGenericMethodDefinition() && pMD->IsTypicalMethodDefinition())
{
BOOL fHasCircularClassConstraints = TRUE;
BOOL fHasCircularMethodConstraints = TRUE;
pMD->LoadConstraintsForTypicalMethodDefinition(&fHasCircularClassConstraints, &fHasCircularMethodConstraints, CLASS_DEPENDENCIES_LOADED);
if (fHasCircularClassConstraints)
{
COMPlusThrow(kTypeLoadException, VER_E_CIRCULAR_VAR_CONSTRAINTS);
}
if (fHasCircularMethodConstraints)
{
COMPlusThrow(kTypeLoadException, VER_E_CIRCULAR_MVAR_CONSTRAINTS);
}
}
}
}
}
}
#ifdef _DEBUG
if (LoggingOn(LF_CLASSLOADER, LL_INFO10000))
{
SString name;
TypeString::AppendTypeDebug(name, this);
LOG((LF_CLASSLOADER, LL_INFO10000, "PHASEDLOAD: Completed full dependency load of type %S\n", name.GetUnicode()));
}
#endif
switch (level)
{
case CLASS_DEPENDENCIES_LOADED:
SetIsDependenciesLoaded();
#if defined(FEATURE_COMINTEROP) && !defined(DACCESS_COMPILE)
if (WinRTSupported() && g_fEEStarted && !ContainsIntrospectionOnlyTypes())
{
_ASSERTE(GetAppDomain() != NULL);
AppDomain* pAppDomain = GetAppDomain();
if (pAppDomain->CanCacheWinRTTypeByGuid(this))
{
pAppDomain->CacheWinRTTypeByGuid(this);
}
}
#endif // FEATURE_COMINTEROP && !DACCESS_COMPILE
break;
case CLASS_LOADED:
if (!IsZapped() && // Constraint checks have been performed for NGened classes already
!IsTypicalTypeDefinition() &&
!IsSharedByGenericInstantiations())
{
TypeHandle thThis = TypeHandle(this);
// If we got here, we about to mark a generic instantiation as fully loaded. Before we do so,
// check to see if has constraints that aren't being satisfied.
SatisfiesClassConstraints(thThis, typicalTypeHnd, pInstContext);
}
if (locals.fBailed)
{
// We couldn't complete security checks on some dependency because he is already being processed by one of our callers.
// Do not mark this class fully loaded yet. Put him on the pending list and he will be marked fully loaded when
// everything unwinds.
*pfBailed = TRUE;
TypeHandle *pTHPending = pPending->AppendThrowing();
*pTHPending = TypeHandle(this);
}
else
{
// Finally, mark this method table as fully loaded
SetIsFullyLoaded();
}
break;
default:
_ASSERTE(!"Can't get here.");
break;
}
END_SO_INTOLERANT_CODE;
#endif //!DACCESS_COMPILE
} //MethodTable::DoFullyLoad
#ifndef DACCESS_COMPILE
#ifdef FEATURE_PREJIT
// For a MethodTable in a native image, decode sufficient encoded pointers
// that the TypeKey for this type is recoverable.
//
// For instantiated generic types, we need the generic type arguments,
// the EEClass pointer, and its Module pointer.
// (For non-generic types, the EEClass and Module are always hard bound).
//
// The process is applied recursively e.g. consider C<D<string>[]>.
// It is guaranteed to terminate because types cannot contain cycles in their structure.
//
// Also note that no lock is required; the process of restoring this information is idempotent.
// (Note the atomic action at the end though)
//
void MethodTable::DoRestoreTypeKey()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END;
// If we have an indirection cell then restore the m_pCanonMT and its module pointer
//
if (union_getLowBits(m_pCanonMT) == UNION_INDIRECTION)
{
Module::RestoreMethodTablePointerRaw((MethodTable **)(union_getPointer(m_pCanonMT)),
GetLoaderModule(), CLASS_LOAD_UNRESTORED);
}
MethodTable * pMTForModule = IsArray() ? this : GetCanonicalMethodTable();
if (pMTForModule->HasModuleOverride())
{
Module::RestoreModulePointer(pMTForModule->GetModuleOverridePtr(), pMTForModule->GetLoaderModule());
}
if (IsArray())
{
//
// Restore array element type handle
//
Module::RestoreTypeHandlePointerRaw(GetApproxArrayElementTypeHandlePtr(),
GetLoaderModule(), CLASS_LOAD_UNRESTORED);
}
// Next restore the instantiation and recurse
Instantiation inst = GetInstantiation();
for (DWORD j = 0; j < inst.GetNumArgs(); j++)
{
Module::RestoreTypeHandlePointer(&inst.GetRawArgs()[j], GetLoaderModule(), CLASS_LOAD_UNRESTORED);
}
FastInterlockAnd(&(EnsureWritablePages(GetWriteableDataForWrite())->m_dwFlags), ~MethodTableWriteableData::enum_flag_UnrestoredTypeKey);
}
//==========================================================================================
// For a MethodTable in a native image, apply Restore actions
// * Decode any encoded pointers
// * Instantiate static handles
// * Propagate Restore to EEClass
// For array method tables, Restore MUST BE IDEMPOTENT as it can be entered from multiple threads
// For other classes, restore cannot be entered twice because the loader maintains locks
//
// When you actually restore the MethodTable for a generic type, the generic
// dictionary is restored. That means:
// * Parent slots in the PerInstInfo are restored by this method eagerly. They are copied down from the
// parent in code:ClassLoader.LoadExactParentAndInterfacesTransitively
// * Instantiation parameters in the dictionary are restored eagerly when the type is restored. These are
// either hard bound pointers, or tagged tokens (fixups).
// * All other dictionary entries are either hard bound pointers or they are NULL (they are cleared when we
// freeze the Ngen image). They are *never* tagged tokens.
void MethodTable::Restore()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(IsZapped());
PRECONDITION(!IsRestored_NoLogging());
PRECONDITION(!HasUnrestoredTypeKey());
}
CONTRACTL_END;
g_IBCLogger.LogMethodTableAccess(this);
STRESS_LOG1(LF_ZAP, LL_INFO10000, "MethodTable::Restore: Restoring type %pT\n", this);
LOG((LF_ZAP, LL_INFO10000,
"Restoring methodtable %s at " FMT_ADDR ".\n", GetDebugClassName(), DBG_ADDR(this)));
// Class pointer should be restored already (in DoRestoreTypeKey)
CONSISTENCY_CHECK(IsClassPointerValid());
// If this isn't the canonical method table itself, then restore the canonical method table
// We will load the canonical method table to level EXACTPARENTS in LoadExactParents
if (!IsCanonicalMethodTable())
{
ClassLoader::EnsureLoaded(GetCanonicalMethodTable(), CLASS_LOAD_APPROXPARENTS);
}
//
// Restore parent method table
//
Module::RestoreMethodTablePointerRaw(GetParentMethodTablePtr(), GetLoaderModule(), CLASS_LOAD_APPROXPARENTS);
//
// Restore interface classes
//
InterfaceMapIterator it = IterateInterfaceMap();
while (it.Next())
{
// Just make sure that approximate interface is loaded. LoadExactParents fill in the exact interface later.
MethodTable * pIftMT;
pIftMT = it.GetInterfaceInfo()->GetApproxMethodTable(GetLoaderModule());
_ASSERTE(pIftMT != NULL);
}
if (HasCrossModuleGenericStaticsInfo())
{
MethodTableWriteableData * pWriteableData = GetWriteableDataForWrite();
CrossModuleGenericsStaticsInfo * pInfo = pWriteableData->GetCrossModuleGenericsStaticsInfo();
EnsureWritablePages(pWriteableData, sizeof(MethodTableWriteableData) + sizeof(CrossModuleGenericsStaticsInfo));
if (IsDomainNeutral())
{
// If we are domain neutral, we have to use constituent of the instantiation to store
// statics. We need to ensure that we can create DomainModule in all domains
// that this instantiations may get activated in. PZM is good approximation of such constituent.
Module * pModuleForStatics = Module::GetPreferredZapModuleForMethodTable(this);
pInfo->m_pModuleForStatics = pModuleForStatics;
pInfo->m_DynamicTypeID = pModuleForStatics->AllocateDynamicEntry(this);
}
else
{
pInfo->m_pModuleForStatics = GetLoaderModule();
}
}
LOG((LF_ZAP, LL_INFO10000,
"Restored methodtable %s at " FMT_ADDR ".\n", GetDebugClassName(), DBG_ADDR(this)));
// This has to be last!
SetIsRestored();
}
#endif // FEATURE_PREJIT
#ifdef FEATURE_COMINTEROP
//==========================================================================================
BOOL MethodTable::IsExtensibleRCW()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(GetClass());
return IsComObjectType() && !GetClass()->IsComImport();
}
//==========================================================================================
OBJECTHANDLE MethodTable::GetOHDelegate()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(GetClass());
return GetClass()->GetOHDelegate();
}
//==========================================================================================
void MethodTable::SetOHDelegate (OBJECTHANDLE _ohDelegate)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(GetClass());
g_IBCLogger.LogEEClassCOWTableAccess(this);
GetClass_NoLogging()->SetOHDelegate(_ohDelegate);
}
//==========================================================================================
// Helper to skip over COM class in the hierarchy
MethodTable* MethodTable::GetComPlusParentMethodTable()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END
MethodTable* pParent = GetParentMethodTable();
if (pParent && pParent->IsComImport())
{
if (pParent->IsProjectedFromWinRT())
{
// skip all Com Import classes
do
{
pParent = pParent->GetParentMethodTable();
_ASSERTE(pParent != NULL);
}while(pParent->IsComImport());
// Now we have either System.__ComObject or WindowsRuntime.RuntimeClass
if (pParent != g_pBaseCOMObject)
{
return pParent;
}
}
else
{
// Skip the single ComImport class we expect
_ASSERTE(pParent->GetParentMethodTable() != NULL);
pParent = pParent->GetParentMethodTable();
}
_ASSERTE(!pParent->IsComImport());
// Skip over System.__ComObject, expect System.MarshalByRefObject
pParent=pParent->GetParentMethodTable();
_ASSERTE(pParent != NULL);
#ifdef FEATURE_REMOTING
_ASSERTE(pParent->IsMarshaledByRef());
#endif
_ASSERTE(pParent->GetParentMethodTable() != NULL);
_ASSERTE(pParent->GetParentMethodTable() == g_pObjectClass);
}
return pParent;
}
BOOL MethodTable::IsWinRTObjectType()
{
LIMITED_METHOD_CONTRACT;
// Try to determine if this object represents a WindowsRuntime object - i.e. is either
// ProjectedFromWinRT or derived from a class that is
if (!IsComObjectType())
return FALSE;
// Ideally we'd compute this once in BuildMethodTable and track it with another
// flag, but we're now out of bits on m_dwFlags, and this is used very rarely
// so for now we'll just recompute it when necessary.
MethodTable* pMT = this;
do
{
if (pMT->IsProjectedFromWinRT())
{
// Found a WinRT COM object
return TRUE;
}
if (pMT->IsComImport())
{
// Found a class that is actually imported from COM but not WinRT
// this is definitely a non-WinRT COM object
return FALSE;
}
pMT = pMT->GetParentMethodTable();
}while(pMT != NULL);
return FALSE;
}
#endif // FEATURE_COMINTEROP
#endif // !DACCESS_COMPILE
//==========================================================================================
// Return a pointer to the dictionary for an instantiated type
// Return NULL if not instantiated
Dictionary* MethodTable::GetDictionary()
{
LIMITED_METHOD_DAC_CONTRACT;
if (HasInstantiation())
{
// The instantiation for this class is stored in the type slots table
// *after* any inherited slots
return GetPerInstInfo()[GetNumDicts()-1];
}
else
{
return NULL;
}
}
//==========================================================================================
// As above, but assert if an instantiated type is not restored
Instantiation MethodTable::GetInstantiation()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
if (HasInstantiation())
{
PTR_GenericsDictInfo pDictInfo = GetGenericsDictInfo();
return Instantiation(GetPerInstInfo()[pDictInfo->m_wNumDicts-1]->GetInstantiation(), pDictInfo->m_wNumTyPars);
}
else
{
return Instantiation();
}
}
//==========================================================================================
// Obtain instantiation from an instantiated type or a pointer to the
// element type of an array
Instantiation MethodTable::GetClassOrArrayInstantiation()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
if (IsArray()) {
return GetArrayInstantiation();
}
else {
return GetInstantiation();
}
}
//==========================================================================================
Instantiation MethodTable::GetArrayInstantiation()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(IsArray());
return Instantiation((TypeHandle *)&m_ElementTypeHnd, 1);
}
//==========================================================================================
CorElementType MethodTable::GetInternalCorElementType()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
// This should not touch the EEClass, at least not in the
// common cases of ELEMENT_TYPE_CLASS and ELEMENT_TYPE_VALUETYPE.
g_IBCLogger.LogMethodTableAccess(this);
CorElementType ret;
switch (GetFlag(enum_flag_Category_ElementTypeMask))
{
case enum_flag_Category_Array:
ret = ELEMENT_TYPE_ARRAY;
break;
case enum_flag_Category_Array | enum_flag_Category_IfArrayThenSzArray:
ret = ELEMENT_TYPE_SZARRAY;
break;
case enum_flag_Category_ValueType:
ret = ELEMENT_TYPE_VALUETYPE;
break;
case enum_flag_Category_PrimitiveValueType:
// This path should only be taken for the builtin mscorlib types
// and primitive valuetypes
ret = GetClass()->GetInternalCorElementType();
_ASSERTE((ret != ELEMENT_TYPE_CLASS) &&
(ret != ELEMENT_TYPE_VALUETYPE));
break;
default:
ret = ELEMENT_TYPE_CLASS;
break;
}
// DAC may be targetting a dump; dumps do not guarantee you can retrieve the EEClass from
// the MethodTable so this is not expected to work in a DAC build.
#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
if (IsRestored_NoLogging())
{
PTR_EEClass pClass = GetClass_NoLogging();
if (ret != pClass->GetInternalCorElementType())
{
_ASSERTE(!"Mismatched results in MethodTable::GetInternalCorElementType");
}
}
#endif // defined(_DEBUG) && !defined(DACCESS_COMPILE)
return ret;
}
//==========================================================================================
CorElementType MethodTable::GetVerifierCorElementType()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
// This should not touch the EEClass, at least not in the
// common cases of ELEMENT_TYPE_CLASS and ELEMENT_TYPE_VALUETYPE.
g_IBCLogger.LogMethodTableAccess(this);
CorElementType ret;
switch (GetFlag(enum_flag_Category_ElementTypeMask))
{
case enum_flag_Category_Array:
ret = ELEMENT_TYPE_ARRAY;
break;
case enum_flag_Category_Array | enum_flag_Category_IfArrayThenSzArray:
ret = ELEMENT_TYPE_SZARRAY;
break;
case enum_flag_Category_ValueType:
ret = ELEMENT_TYPE_VALUETYPE;
break;
case enum_flag_Category_PrimitiveValueType:
//
// This is the only difference from MethodTable::GetInternalCorElementType()
//
if (IsTruePrimitive() || IsEnum())
ret = GetClass()->GetInternalCorElementType();
else
ret = ELEMENT_TYPE_VALUETYPE;
break;
default:
ret = ELEMENT_TYPE_CLASS;
break;
}
return ret;
}
//==========================================================================================
CorElementType MethodTable::GetSignatureCorElementType()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
// This should not touch the EEClass, at least not in the
// common cases of ELEMENT_TYPE_CLASS and ELEMENT_TYPE_VALUETYPE.
g_IBCLogger.LogMethodTableAccess(this);
CorElementType ret;
switch (GetFlag(enum_flag_Category_ElementTypeMask))
{
case enum_flag_Category_Array:
ret = ELEMENT_TYPE_ARRAY;
break;
case enum_flag_Category_Array | enum_flag_Category_IfArrayThenSzArray:
ret = ELEMENT_TYPE_SZARRAY;
break;
case enum_flag_Category_ValueType:
ret = ELEMENT_TYPE_VALUETYPE;
break;
case enum_flag_Category_PrimitiveValueType:
//
// This is the only difference from MethodTable::GetInternalCorElementType()
//
if (IsTruePrimitive())
ret = GetClass()->GetInternalCorElementType();
else
ret = ELEMENT_TYPE_VALUETYPE;
break;
default:
ret = ELEMENT_TYPE_CLASS;
break;
}
return ret;
}
#ifndef DACCESS_COMPILE
//==========================================================================================
void MethodTable::SetInternalCorElementType (CorElementType _NormType)
{
WRAPPER_NO_CONTRACT;
switch (_NormType)
{
case ELEMENT_TYPE_CLASS:
_ASSERTE(!IsArray());
// Nothing to do
break;
case ELEMENT_TYPE_VALUETYPE:
SetFlag(enum_flag_Category_ValueType);
_ASSERTE(GetFlag(enum_flag_Category_Mask) == enum_flag_Category_ValueType);
break;
default:
SetFlag(enum_flag_Category_PrimitiveValueType);
_ASSERTE(GetFlag(enum_flag_Category_Mask) == enum_flag_Category_PrimitiveValueType);
break;
}
GetClass_NoLogging()->SetInternalCorElementType(_NormType);
_ASSERTE(GetInternalCorElementType() == _NormType);
}
#endif // !DACCESS_COMPILE
#ifdef FEATURE_COMINTEROP
#ifndef DACCESS_COMPILE
#ifndef CROSSGEN_COMPILE
BOOL MethodTable::IsLegalWinRTType(OBJECTREF *poref)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(IsProtectedByGCFrame(poref));
PRECONDITION(CheckPointer(poref));
PRECONDITION((*poref) != NULL);
}
CONTRACTL_END
if (IsArray())
{
BASEARRAYREF arrayRef = (BASEARRAYREF)(*poref);
// WinRT array must be one-dimensional array with 0 lower-bound
if (arrayRef->GetRank() == 1 && arrayRef->GetLowerBoundsPtr()[0] == 0)
{
MethodTable *pElementMT = ((BASEARRAYREF)(*poref))->GetArrayElementTypeHandle().GetMethodTable();
// Element must be a legal WinRT type and not an array
if (!pElementMT->IsArray() && pElementMT->IsLegalNonArrayWinRTType())
return TRUE;
}
return FALSE;
}
else
{
// Non-Array version of IsLegalNonArrayWinRTType
return IsLegalNonArrayWinRTType();
}
}
#endif //#ifndef CROSSGEN_COMPILE
BOOL MethodTable::IsLegalNonArrayWinRTType()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(!IsArray()); // arrays are not fully described by MethodTable
}
CONTRACTL_END
if (WinRTTypeNameConverter::IsWinRTPrimitiveType(this))
return TRUE;
// Attributes are not legal
MethodTable *pParentMT = GetParentMethodTable();
if (pParentMT == MscorlibBinder::GetExistingClass(CLASS__ATTRIBUTE))
{
return FALSE;
}
bool fIsRedirected = false;
if (!IsProjectedFromWinRT() && !IsExportedToWinRT())
{
// If the type is not primitive and not coming from .winmd, it can still be legal if
// it's one of the redirected types (e.g. IEnumerable<T>).
if (!WinRTTypeNameConverter::IsRedirectedType(this))
return FALSE;
fIsRedirected = true;
}
if (IsValueType())
{
if (!fIsRedirected)
{
// check fields
ApproxFieldDescIterator fieldIterator(this, ApproxFieldDescIterator::INSTANCE_FIELDS);
for (FieldDesc *pFD = fieldIterator.Next(); pFD != NULL; pFD = fieldIterator.Next())
{
TypeHandle thField = pFD->GetFieldTypeHandleThrowing(CLASS_LOAD_EXACTPARENTS);
if (thField.IsTypeDesc())
return FALSE;
MethodTable *pFieldMT = thField.GetMethodTable();
// the only allowed reference types are System.String and types projected from WinRT value types
if (!pFieldMT->IsValueType() && !pFieldMT->IsString())
{
WinMDAdapter::RedirectedTypeIndex index;
if (!WinRTTypeNameConverter::ResolveRedirectedType(pFieldMT, &index))
return FALSE;
WinMDAdapter::WinMDTypeKind typeKind;
WinMDAdapter::GetRedirectedTypeInfo(index, NULL, NULL, NULL, NULL, NULL, &typeKind);
if (typeKind != WinMDAdapter::WinMDTypeKind_Struct && typeKind != WinMDAdapter::WinMDTypeKind_Enum)
return FALSE;
}
if (!pFieldMT->IsLegalNonArrayWinRTType())
return FALSE;
}
}
}
if (IsInterface() || IsDelegate() || (IsValueType() && fIsRedirected))
{
// interfaces, delegates, and redirected structures can be generic - check the instantiation
if (HasInstantiation())
{
Instantiation inst = GetInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
// arrays are not allowed as generic arguments
if (inst[i].IsArrayType())
return FALSE;
if (inst[i].IsTypeDesc())
return FALSE;
if (!inst[i].AsMethodTable()->IsLegalNonArrayWinRTType())
return FALSE;
}
}
}
else
{
// generic structures and runtime clases are not supported
if (HasInstantiation())
return FALSE;
}
return TRUE;
}
//==========================================================================================
// Returns the default WinRT interface if this is a WinRT class, NULL otherwise.
MethodTable *MethodTable::GetDefaultWinRTInterface()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END
if (!IsProjectedFromWinRT() && !IsExportedToWinRT())
return NULL;
if (IsInterface())
return NULL;
// System.Runtime.InteropServices.WindowsRuntime.RuntimeClass is weird
// It is ProjectedFromWinRT but isn't really a WinRT class
if (this == g_pBaseRuntimeClass)
return NULL;
WinRTClassFactory *pFactory = ::GetComClassFactory(this)->AsWinRTClassFactory();
return pFactory->GetDefaultInterface();
}
#endif // !DACCESS_COMPILE
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_COMINTEROP
#ifndef DACCESS_COMPILE
WORD GetEquivalentMethodSlot(MethodTable * pOldMT, MethodTable * pNewMT, WORD wMTslot, BOOL *pfFound)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
MethodDesc * pMDRet = NULL;
*pfFound = FALSE;
// Get the COM vtable slot corresponding to the given MT slot
WORD wVTslot;
if (pOldMT->IsSparseForCOMInterop())
{
wVTslot = pOldMT->GetClass()->GetSparseCOMInteropVTableMap()->LookupVTSlot(wMTslot);
}
else
{
wVTslot = wMTslot;
}
// If the other MT is not sparse, we can return the COM slot directly
if (!pNewMT->IsSparseForCOMInterop())
{
if (wVTslot < pNewMT->GetNumVirtuals())
*pfFound = TRUE;
return wVTslot;
}
// Otherwise we iterate over all virtuals in the other MT trying to find a match
for (WORD wSlot = 0; wSlot < pNewMT->GetNumVirtuals(); wSlot++)
{
if (wVTslot == pNewMT->GetClass()->GetSparseCOMInteropVTableMap()->LookupVTSlot(wSlot))
{
*pfFound = TRUE;
return wSlot;
}
}
_ASSERTE(!*pfFound);
return 0;
}
#endif // #ifdef DACCESS_COMPILE
#endif // #ifdef FEATURE_COMINTEROP
//==========================================================================================
BOOL
MethodTable::FindEncodedMapDispatchEntry(
UINT32 typeID,
UINT32 slotNumber,
DispatchMapEntry * pEntry)
{
CONTRACTL {
// NOTE: LookupDispatchMapType may or may not throw. Currently, it
// should never throw because lazy interface restore is disabled.
THROWS;
GC_TRIGGERS;
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pEntry));
PRECONDITION(typeID != TYPE_ID_THIS_CLASS);
} CONTRACTL_END;
CONSISTENCY_CHECK(HasDispatchMap());
MethodTable * dispatchTokenType = GetThread()->GetDomain()->LookupType(typeID);
// Search for an exact type match.
{
DispatchMap::EncodedMapIterator it(this);
for (; it.IsValid(); it.Next())
{
DispatchMapEntry * pCurEntry = it.Entry();
if (pCurEntry->GetSlotNumber() == slotNumber)
{
MethodTable * pCurEntryType = LookupDispatchMapType(pCurEntry->GetTypeID());
if (pCurEntryType == dispatchTokenType)
{
*pEntry = *pCurEntry;
return TRUE;
}
}
}
}
// Repeat the search if any variance is involved, allowing a CanCastTo match. (We do
// this in a separate pass because we want to avoid touching the type
// to see if it has variance or not)
//
// NOTE: CERs are not guaranteed for interfaces with co- and contra-variance involved.
if (dispatchTokenType->HasVariance() || dispatchTokenType->HasTypeEquivalence())
{
DispatchMap::EncodedMapIterator it(this);
for (; it.IsValid(); it.Next())
{
DispatchMapEntry * pCurEntry = it.Entry();
if (pCurEntry->GetSlotNumber() == slotNumber)
{
#ifndef DACCESS_COMPILE
MethodTable * pCurEntryType = LookupDispatchMapType(pCurEntry->GetTypeID());
//@TODO: This is currently not guaranteed to work without throwing,
//@TODO: even with lazy interface restore disabled.
if (dispatchTokenType->HasVariance() &&
pCurEntryType->CanCastByVarianceToInterfaceOrDelegate(dispatchTokenType, NULL))
{
*pEntry = *pCurEntry;
return TRUE;
}
if (dispatchTokenType->HasInstantiation() && dispatchTokenType->HasTypeEquivalence())
{
if (dispatchTokenType->IsEquivalentTo(pCurEntryType))
{
*pEntry = *pCurEntry;
return TRUE;
}
}
#endif // !DACCESS_COMPILE
}
#if !defined(DACCESS_COMPILE) && defined(FEATURE_TYPEEQUIVALENCE)
if (this->HasTypeEquivalence() &&
!dispatchTokenType->HasInstantiation() &&
dispatchTokenType->HasTypeEquivalence() &&
dispatchTokenType->GetClass()->IsEquivalentType())
{
_ASSERTE(dispatchTokenType->IsInterface());
MethodTable * pCurEntryType = LookupDispatchMapType(pCurEntry->GetTypeID());
if (pCurEntryType->IsEquivalentTo(dispatchTokenType))
{
MethodDesc * pMD = dispatchTokenType->GetMethodDescForSlot(slotNumber);
_ASSERTE(FitsIn<WORD>(slotNumber));
BOOL fNewSlotFound = FALSE;
DWORD newSlot = GetEquivalentMethodSlot(
dispatchTokenType,
pCurEntryType,
static_cast<WORD>(slotNumber),
&fNewSlotFound);
if (fNewSlotFound && (newSlot == pCurEntry->GetSlotNumber()))
{
MethodDesc * pNewMD = pCurEntryType->GetMethodDescForSlot(newSlot);
MetaSig msig(pMD);
MetaSig msignew(pNewMD);
if (MetaSig::CompareMethodSigs(msig, msignew, FALSE))
{
*pEntry = *pCurEntry;
return TRUE;
}
}
}
}
#endif
}
}
return FALSE;
} // MethodTable::FindEncodedMapDispatchEntry
//==========================================================================================
BOOL MethodTable::FindDispatchEntryForCurrentType(UINT32 typeID,
UINT32 slotNumber,
DispatchMapEntry *pEntry)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pEntry));
PRECONDITION(typeID != TYPE_ID_THIS_CLASS);
} CONTRACTL_END;
BOOL fRes = FALSE;
if (HasDispatchMap())
{
fRes = FindEncodedMapDispatchEntry(
typeID, slotNumber, pEntry);
}
return fRes;
}
//==========================================================================================
BOOL MethodTable::FindDispatchEntry(UINT32 typeID,
UINT32 slotNumber,
DispatchMapEntry *pEntry)
{
CONTRACT (BOOL) {
INSTANCE_CHECK;
MODE_ANY;
THROWS;
GC_TRIGGERS;
POSTCONDITION(!RETVAL || pEntry->IsValid());
PRECONDITION(typeID != TYPE_ID_THIS_CLASS);
} CONTRACT_END;
// Start at the current type and work up the inheritance chain
MethodTable *pCurMT = this;
UINT32 iCurInheritanceChainDelta = 0;
while (pCurMT != NULL)
{
g_IBCLogger.LogMethodTableAccess(pCurMT);
if (pCurMT->FindDispatchEntryForCurrentType(
typeID, slotNumber, pEntry))
{
RETURN (TRUE);
}
pCurMT = pCurMT->GetParentMethodTable();
iCurInheritanceChainDelta++;
}
RETURN (FALSE);
}
//==========================================================================================
// Possible cases:
// 1. Typed (interface) contract
// a. To non-virtual implementation (NYI). Just
// return the DispatchSlot as the implementation
// b. Mapped virtually to virtual slot on 'this'. Need to
// further resolve the new 'this' virtual slot.
// 2. 'this' contract
// a. To non-virtual implementation. Return the DispatchSlot
// as the implementation.
// b. Mapped virtually to another virtual slot. Need to further
// resolve the new slot on 'this'.
BOOL
MethodTable::FindDispatchImpl(
UINT32 typeID,
UINT32 slotNumber,
DispatchSlot * pImplSlot)
{
CONTRACT (BOOL) {
INSTANCE_CHECK;
MODE_ANY;
THROWS;
GC_TRIGGERS;
PRECONDITION(CheckPointer(pImplSlot));
POSTCONDITION(!RETVAL || !pImplSlot->IsNull() || IsComObjectType());
} CONTRACT_END;
LOG((LF_LOADER, LL_INFO10000, "SD: MT::FindDispatchImpl: searching %s.\n", GetClass()->GetDebugClassName()));
///////////////////////////////////
// 1. Typed (interface) contract
INDEBUG(MethodTable *dbg_pMTTok = NULL; dbg_pMTTok = this;)
DispatchMapEntry declEntry;
DispatchMapEntry implEntry;
#ifndef DACCESS_COMPILE
if (typeID != TYPE_ID_THIS_CLASS)
{
INDEBUG(dbg_pMTTok = GetThread()->GetDomain()->LookupType(typeID));
DispatchMapEntry e;
if (!FindDispatchEntry(typeID, slotNumber, &e))
{
// A call to an array thru IList<T> (or IEnumerable<T> or ICollection<T>) has to be handled specially.
// These interfaces are "magic" (mostly due to working set concerned - they are created on demand internally
// even though semantically, these are static interfaces.)
//
// NOTE: CERs are not currently supported with generic array interfaces.
if (IsArray())
{
// At this, we know that we're trying to cast an array to an interface and that the normal static lookup failed.
// FindDispatchImpl assumes that the cast is legal so we should be able to assume now that it is a valid
// IList<T> call thru an array.
// Get the MT of IList<T> or IReadOnlyList<T>
MethodTable *pIfcMT = GetThread()->GetDomain()->LookupType(typeID);
// Quick sanity check
if (!(pIfcMT->HasInstantiation()))
{
_ASSERTE(!"Should not have gotten here. If you did, it's probably because multiple interface instantiation hasn't been checked in yet. This code only works on top of that.");
RETURN(FALSE);
}
// Get the type of T (as in IList<T>)
TypeHandle theT = pIfcMT->GetInstantiation()[0];
// Figure out which method of IList<T> the caller requested.
MethodDesc * pIfcMD = pIfcMT->GetMethodDescForSlot(slotNumber);
// Retrieve the corresponding method of SZArrayHelper. This is the guy that will actually execute.
// This method will be an instantiation of a generic method. I.e. if the caller requested
// IList<T>.Meth(), he will actually be diverted to SZArrayHelper.Meth<T>().
MethodDesc * pActualImplementor = GetActualImplementationForArrayGenericIListOrIReadOnlyListMethod(pIfcMD, theT);
// Now, construct a DispatchSlot to return in *pImplSlot
DispatchSlot ds(pActualImplementor->GetMethodEntryPoint());
if (pImplSlot != NULL)
{
*pImplSlot = ds;
}
RETURN(TRUE);
}
// This contract is not implemented by this class or any parent class.
RETURN(FALSE);
}
/////////////////////////////////
// 1.1. Update the typeID and slotNumber so that the full search can commense below
typeID = TYPE_ID_THIS_CLASS;
slotNumber = e.GetTargetSlotNumber();
}
#endif // !DACCESS_COMPILE
//////////////////////////////////
// 2. 'this' contract
// Just grab the target out of the vtable
*pImplSlot = GetRestoredSlot(slotNumber);
// Successfully determined the target for the given target
RETURN (TRUE);
}
//==========================================================================================
DispatchSlot MethodTable::FindDispatchSlot(UINT32 typeID, UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
DispatchSlot implSlot(NULL);
FindDispatchImpl(typeID, slotNumber, &implSlot);
return implSlot;
}
//==========================================================================================
DispatchSlot MethodTable::FindDispatchSlot(DispatchToken tok)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
return FindDispatchSlot(tok.GetTypeID(), tok.GetSlotNumber());
}
#ifndef DACCESS_COMPILE
//==========================================================================================
DispatchSlot MethodTable::FindDispatchSlotForInterfaceMD(MethodDesc *pMD)
{
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(CheckPointer(pMD));
CONSISTENCY_CHECK(pMD->IsInterface());
return FindDispatchSlotForInterfaceMD(TypeHandle(pMD->GetMethodTable()), pMD);
}
//==========================================================================================
DispatchSlot MethodTable::FindDispatchSlotForInterfaceMD(TypeHandle ownerType, MethodDesc *pMD)
{
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(!ownerType.IsNull());
CONSISTENCY_CHECK(CheckPointer(pMD));
CONSISTENCY_CHECK(pMD->IsInterface());
return FindDispatchSlot(ownerType.GetMethodTable()->GetTypeID(), pMD->GetSlot());
}
//==========================================================================================
// This is used for reverse methodimpl lookups by ComPlusMethodCall MDs.
// This assumes the following:
// The methodimpl is for an interfaceToken->slotNumber
// There is ONLY ONE such mapping for this slot number
// The mapping exists in this type, not a parent type.
MethodDesc * MethodTable::ReverseInterfaceMDLookup(UINT32 slotNumber)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
DispatchMap::Iterator it(this);
for (; it.IsValid(); it.Next())
{
if (it.Entry()->GetTargetSlotNumber() == slotNumber)
{
DispatchMapTypeID typeID = it.Entry()->GetTypeID();
_ASSERTE(!typeID.IsThisClass());
UINT32 slotNum = it.Entry()->GetSlotNumber();
MethodTable * pMTItf = LookupDispatchMapType(typeID);
CONSISTENCY_CHECK(CheckPointer(pMTItf));
MethodDesc *pCanonMD = pMTItf->GetMethodDescForSlot((DWORD)slotNum);
return MethodDesc::FindOrCreateAssociatedMethodDesc(
pCanonMD,
pMTItf,
FALSE, // forceBoxedEntryPoint
Instantiation(), // methodInst
FALSE, // allowInstParam
TRUE); // forceRemotableMethod
}
}
return NULL;
}
//==========================================================================================
UINT32 MethodTable::GetTypeID()
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
PTR_MethodTable pMT = PTR_MethodTable(this);
return GetDomain()->GetTypeID(pMT);
}
//==========================================================================================
UINT32 MethodTable::LookupTypeID()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
PTR_MethodTable pMT = PTR_MethodTable(this);
return GetDomain()->LookupTypeID(pMT);
}
//==========================================================================================
BOOL MethodTable::ImplementsInterfaceWithSameSlotsAsParent(MethodTable *pItfMT, MethodTable *pParentMT)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(!IsInterface() && !pParentMT->IsInterface());
PRECONDITION(pItfMT->IsInterface());
} CONTRACTL_END;
MethodTable *pMT = this;
do
{
DispatchMap::EncodedMapIterator it(pMT);
for (; it.IsValid(); it.Next())
{
DispatchMapEntry *pCurEntry = it.Entry();
if (LookupDispatchMapType(pCurEntry->GetTypeID()) == pItfMT)
{
// this class and its parents up to pParentMT must have no mappings for the interface
return FALSE;
}
}
pMT = pMT->GetParentMethodTable();
_ASSERTE(pMT != NULL);
}
while (pMT != pParentMT);
return TRUE;
}
//==========================================================================================
BOOL MethodTable::HasSameInterfaceImplementationAsParent(MethodTable *pItfMT, MethodTable *pParentMT)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(!IsInterface() && !pParentMT->IsInterface());
PRECONDITION(pItfMT->IsInterface());
} CONTRACTL_END;
if (!ImplementsInterfaceWithSameSlotsAsParent(pItfMT, pParentMT))
{
// if the slots are not same, this class reimplements the interface
return FALSE;
}
// The target slots are the same, but they can still be overriden. We'll iterate
// the dispatch map beginning with pParentMT up the hierarchy and for each pItfMT
// entry check the target slot contents (pParentMT vs. this class). A mismatch
// means that there is an override. We'll keep track of source (interface) slots
// we have seen so that we can ignore entries higher in the hierarchy that are no
// longer in effect at pParentMT level.
BitMask bitMask;
WORD wSeenSlots = 0;
WORD wTotalSlots = pItfMT->GetNumVtableSlots();
MethodTable *pMT = pParentMT;
do
{
DispatchMap::EncodedMapIterator it(pMT);
for (; it.IsValid(); it.Next())
{
DispatchMapEntry *pCurEntry = it.Entry();
if (LookupDispatchMapType(pCurEntry->GetTypeID()) == pItfMT)
{
UINT32 ifaceSlot = pCurEntry->GetSlotNumber();
if (!bitMask.TestBit(ifaceSlot))
{
bitMask.SetBit(ifaceSlot);
UINT32 targetSlot = pCurEntry->GetTargetSlotNumber();
if (GetRestoredSlot(targetSlot) != pParentMT->GetRestoredSlot(targetSlot))
{
// the target slot is overriden
return FALSE;
}
if (++wSeenSlots == wTotalSlots)
{
// we've resolved all slots, no reason to continue
break;
}
}
}
}
pMT = pMT->GetParentMethodTable();
}
while (pMT != NULL);
return TRUE;
}
#endif // !DACCESS_COMPILE
//==========================================================================================
MethodTable * MethodTable::LookupDispatchMapType(DispatchMapTypeID typeID)
{
CONTRACTL {
WRAPPER(THROWS);
GC_TRIGGERS;
} CONTRACTL_END;
_ASSERTE(!typeID.IsThisClass());
InterfaceMapIterator intIt = IterateInterfaceMapFrom(typeID.GetInterfaceNum());
return intIt.GetInterface();
}
//==========================================================================================
MethodDesc * MethodTable::GetIntroducingMethodDesc(DWORD slotNumber)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
MethodDesc * pCurrentMD = GetMethodDescForSlot(slotNumber);
DWORD dwSlot = pCurrentMD->GetSlot();
MethodDesc * pIntroducingMD = NULL;
MethodTable * pParentType = GetParentMethodTable();
MethodTable * pPrevParentType = NULL;
// Find this method in the parent.
// If it does exist in the parent, it would be at the same vtable slot.
while ((pParentType != NULL) &&
(dwSlot < pParentType->GetNumVirtuals()))
{
pPrevParentType = pParentType;
pParentType = pParentType->GetParentMethodTable();
}
if (pPrevParentType != NULL)
{
pIntroducingMD = pPrevParentType->GetMethodDescForSlot(dwSlot);
}
return pIntroducingMD;
}
//==========================================================================================
// There is a case where a method declared in a type can be explicitly
// overridden by a methodImpl on another method within the same type. In
// this case, we need to call the methodImpl target, and this will map
// things appropriately for us.
MethodDesc * MethodTable::MapMethodDeclToMethodImpl(MethodDesc * pMDDecl)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
MethodTable * pMT = pMDDecl->GetMethodTable();
//
// Fast negative case check
//
// If it's not virtual, then it could not have been methodImpl'd.
if (!pMDDecl->IsVirtual() ||
// Is it a non-virtual call to the instantiating stub
(pMT->IsValueType() && !pMDDecl->IsUnboxingStub()))
{
return pMDDecl;
}
MethodDesc * pMDImpl = pMT->GetParallelMethodDesc(pMDDecl);
// If the method is instantiated, then we need to resolve to the corresponding
// instantiated MD for the new slot number.
if (pMDDecl->HasMethodInstantiation())
{
if (pMDDecl->GetSlot() != pMDImpl->GetSlot())
{
if (!pMDDecl->IsGenericMethodDefinition())
{
#ifndef DACCESS_COMPILE
pMDImpl = pMDDecl->FindOrCreateAssociatedMethodDesc(
pMDImpl,
pMT,
pMDDecl->IsUnboxingStub(),
pMDDecl->GetMethodInstantiation(),
pMDDecl->IsInstantiatingStub());
#else
DacNotImpl();
#endif
}
}
else
{
// Since the generic method definition is always in the actual
// slot for the method table, and since the slot numbers for
// the Decl and Impl MDs are the same, then the call to
// FindOrCreateAssociatedMethodDesc would just result in the
// same pMDDecl being returned. In this case, we can skip all
// the work.
pMDImpl = pMDDecl;
}
}
CONSISTENCY_CHECK(CheckPointer(pMDImpl));
CONSISTENCY_CHECK(!pMDImpl->IsGenericMethodDefinition());
return pMDImpl;
} // MethodTable::MapMethodDeclToMethodImpl
//==========================================================================================
HRESULT MethodTable::GetGuidNoThrow(GUID *pGuid, BOOL bGenerateIfNotFound, BOOL bClassic /*= TRUE*/)
{
CONTRACTL {
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
SUPPORTS_DAC;
} CONTRACTL_END;
HRESULT hr = S_OK;
EX_TRY
{
GetGuid(pGuid, bGenerateIfNotFound, bClassic);
}
EX_CATCH_HRESULT(hr);
// ensure we return a failure hr when pGuid is not filled in
if (SUCCEEDED(hr) && (*pGuid == GUID_NULL))
hr = E_FAIL;
return hr;
}
//==========================================================================================
// Returns the GUID of this MethodTable.
// If metadata does not specify GUID for the type, GUID_NULL is returned (if bGenerateIfNotFound
// is FALSE) or a GUID is auto-generated on the fly from the name and members of the type
// (bGenerateIfNotFound is TRUE).
//
// Redirected WinRT types may have two GUIDs, the "classic" one which matches the return value
// of Type.Guid, and the new one which is the GUID of the WinRT type to which it is redirected.
// The bClassic parameter controls which one is returned from this method. Note that the parameter
// is ignored for genuine WinRT types, i.e. types loaded from .winmd files, those always return
// the new GUID.
//
void MethodTable::GetGuid(GUID *pGuid, BOOL bGenerateIfNotFound, BOOL bClassic /*=TRUE*/)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_ANY;
SUPPORTS_DAC;
} CONTRACTL_END;
#ifdef DACCESS_COMPILE
_ASSERTE(pGuid != NULL);
PTR_GuidInfo pGuidInfo = (bClassic ? GetClass()->GetGuidInfo() : GetGuidInfo());
if (pGuidInfo != NULL)
*pGuid = pGuidInfo->m_Guid;
else
*pGuid = GUID_NULL;
#else // DACCESS_COMPILE
SIZE_T cchName = 0; // Length of the name (possibly after decoration).
SIZE_T cbCur; // Current offset.
LPCWSTR szName = NULL; // Name to turn to a guid.
CQuickArray<BYTE> rName; // Buffer to accumulate signatures.
BOOL bGenerated = FALSE; // A flag indicating if we generated the GUID from name.
_ASSERTE(pGuid != NULL);
// Use the per-EEClass GuidInfo if we are asked for the "classic" non-WinRT GUID of non-WinRT type
GuidInfo *pInfo = ((bClassic && !IsProjectedFromWinRT()) ? GetClass()->GetGuidInfo() : GetGuidInfo());
// First check to see if we have already cached the guid for this type.
// We currently only cache guids on interfaces and WinRT delegates.
// In classic mode, though, ensure we don't retrieve the GuidInfo for redirected interfaces
if ((IsInterface() || IsWinRTDelegate()) && pInfo != NULL
&& (!bClassic || !SupportsGenericInterop(TypeHandle::Interop_NativeToManaged, modeRedirected)))
{
if (pInfo->m_bGeneratedFromName)
{
// If the GUID was generated from the name then only return it
// if bGenerateIfNotFound is set.
if (bGenerateIfNotFound)
*pGuid = pInfo->m_Guid;
else
*pGuid = GUID_NULL;
}
else
{
*pGuid = pInfo->m_Guid;
}
return;
}
#ifdef FEATURE_COMINTEROP
if ((SupportsGenericInterop(TypeHandle::Interop_NativeToManaged, modeProjected))
|| (!bClassic
&& SupportsGenericInterop(TypeHandle::Interop_NativeToManaged, modeRedirected)
&& IsLegalNonArrayWinRTType()))
{
// Closed generic WinRT interfaces/delegates have their GUID computed
// based on the "PIID" in metadata and the instantiation.
// Note that we explicitly do this computation for redirected mscorlib
// interfaces only if !bClassic, so typeof(Enumerable<T>).GUID
// for example still returns the same result as pre-v4.5 runtimes.
// ComputeGuidForGenericType() may throw for generics nested beyond 64 levels.
WinRTGuidGenerator::ComputeGuidForGenericType(this, pGuid);
// This GUID is per-instantiation so make sure that the cache
// where we are going to keep it is per-instantiation as well.
_ASSERTE(IsCanonicalMethodTable() || HasGuidInfo());
}
else
#endif // FEATURE_COMINTEROP
if (GetClass()->HasNoGuid())
{
*pGuid = GUID_NULL;
}
else
{
// If there is a GUID in the metadata then return that.
IfFailThrow(GetMDImport()->GetItemGuid(GetCl(), pGuid));
if (*pGuid == GUID_NULL)
{
// Remember that we didn't find the GUID, so we can skip looking during
// future checks. (Note that this is a very important optimization in the
// prejit case.)
g_IBCLogger.LogEEClassCOWTableAccess(this);
GetClass_NoLogging()->SetHasNoGuid();
}
}
if (*pGuid == GUID_NULL && bGenerateIfNotFound)
{
// For interfaces, concatenate the signatures of the methods and fields.
if (!IsNilToken(GetCl()) && IsInterface())
{
// Retrieve the stringized interface definition.
cbCur = GetStringizedItfDef(TypeHandle(this), rName);
// Pad up to a whole WCHAR.
if (cbCur % sizeof(WCHAR))
{
SIZE_T cbDelta = sizeof(WCHAR) - (cbCur % sizeof(WCHAR));
rName.ReSizeThrows(cbCur + cbDelta);
memset(rName.Ptr() + cbCur, 0, cbDelta);
cbCur += cbDelta;
}
// Point to the new buffer.
cchName = cbCur / sizeof(WCHAR);
szName = reinterpret_cast<LPWSTR>(rName.Ptr());
}
else
{
// Get the name of the class.
DefineFullyQualifiedNameForClassW();
szName = GetFullyQualifiedNameForClassNestedAwareW(this);
if (szName == NULL)
return;
cchName = wcslen(szName);
// Enlarge buffer for class name.
cbCur = cchName * sizeof(WCHAR);
rName.ReSizeThrows(cbCur + sizeof(WCHAR));
wcscpy_s(reinterpret_cast<LPWSTR>(rName.Ptr()), cchName + 1, szName);
// Add the assembly guid string to the class name.
ULONG cbCurOUT = (ULONG)cbCur;
IfFailThrow(GetStringizedTypeLibGuidForAssembly(GetAssembly(), rName, (ULONG)cbCur, &cbCurOUT));
cbCur = (SIZE_T) cbCurOUT;
// Pad to a whole WCHAR.
if (cbCur % sizeof(WCHAR))
{
rName.ReSizeThrows(cbCur + sizeof(WCHAR)-(cbCur%sizeof(WCHAR)));
while (cbCur % sizeof(WCHAR))
rName[cbCur++] = 0;
}
// Point to the new buffer.
szName = reinterpret_cast<LPWSTR>(rName.Ptr());
cchName = cbCur / sizeof(WCHAR);
// Dont' want to have to pad.
_ASSERTE((sizeof(GUID) % sizeof(WCHAR)) == 0);
}
// Generate guid from name.
CorGuidFromNameW(pGuid, szName, cchName);
// Remeber we generated the guid from the type name.
bGenerated = TRUE;
}
// Cache the guid in the type, if not already cached.
// We currently only do this for interfaces.
// Also, in classic mode do NOT cache GUID for redirected interfaces.
if ((IsInterface() || IsWinRTDelegate()) && (pInfo == NULL) && (*pGuid != GUID_NULL)
#ifdef FEATURE_COMINTEROP
&& !(bClassic
&& SupportsGenericInterop(TypeHandle::Interop_NativeToManaged, modeRedirected)
&& IsLegalNonArrayWinRTType())
#endif // FEATURE_COMINTEROP
)
{
AllocMemTracker amTracker;
BOOL bStoreGuidInfoOnEEClass = false;
PTR_LoaderAllocator pLoaderAllocator;
#if FEATURE_COMINTEROP
if ((bClassic && !IsProjectedFromWinRT()) || !HasGuidInfo())
{
bStoreGuidInfoOnEEClass = true;
}
#else
// We will always store the GuidInfo on the methodTable.
bStoreGuidInfoOnEEClass = true;
#endif
if(bStoreGuidInfoOnEEClass)
{
// Since the GUIDInfo will be stored on the EEClass,
// the memory should be allocated on the loaderAllocator of the class.
// The definining module and the loaded module could be different in some scenarios.
// For example - in case of shared generic instantiations
// a shared generic i.e. System.__Canon which would be loaded in shared domain
// but the this->GetLoaderAllocator will be the loader allocator for the definining
// module which can get unloaded anytime.
_ASSERTE(GetClass());
_ASSERTE(GetClass()->GetMethodTable());
pLoaderAllocator = GetClass()->GetMethodTable()->GetLoaderAllocator();
}
else
{
pLoaderAllocator = GetLoaderAllocator();
}
_ASSERTE(pLoaderAllocator);
// Allocate the guid information.
pInfo = (GuidInfo *)amTracker.Track(
pLoaderAllocator->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(GuidInfo))));
pInfo->m_Guid = *pGuid;
pInfo->m_bGeneratedFromName = bGenerated;
// Set in in the interface method table.
if (bClassic && !IsProjectedFromWinRT())
{
// Set the per-EEClass GuidInfo if we are asked for the "classic" non-WinRT GUID.
// The MethodTable may be NGENed and read-only - and there's no point in saving
// classic GUIDs in non-WinRT MethodTables anyway.
_ASSERTE(bStoreGuidInfoOnEEClass);
GetClass()->SetGuidInfo(pInfo);
}
else
{
#if FEATURE_COMINTEROP
_ASSERTE(bStoreGuidInfoOnEEClass || HasGuidInfo());
#else
_ASSERTE(bStoreGuidInfoOnEEClass);
#endif
SetGuidInfo(pInfo);
}
amTracker.SuppressRelease();
}
#endif // !DACCESS_COMPILE
}
//==========================================================================================
MethodDesc* MethodTable::GetMethodDescForSlotAddress(PCODE addr, BOOL fSpeculative /*=FALSE*/)
{
CONTRACT(MethodDesc *)
{
GC_NOTRIGGER;
NOTHROW;
SO_TOLERANT;
POSTCONDITION(CheckPointer(RETVAL, NULL_NOT_OK));
POSTCONDITION(RETVAL->m_pDebugMethodTable.IsNull() || // We must be in BuildMethdTableThrowing()
RETVAL->SanityCheck());
}
CONTRACT_END;
// If we see shared fcall implementation as an argument to this
// function, it means that a vtable slot for the shared fcall
// got backpatched when it shouldn't have. The reason we can't
// backpatch this method is that it is an FCall that has many
// MethodDescs for one implementation. If we backpatch delegate
// constructors, this function will not be able to recover the
// MethodDesc for the method.
//
_ASSERTE_IMPL(!ECall::IsSharedFCallImpl(addr) &&
"someone backpatched shared fcall implementation -- "
"see comment in code");
MethodDesc* pMethodDesc = ExecutionManager::GetCodeMethodDesc(addr);
if (NULL != pMethodDesc)
{
goto lExit;
}
#ifdef FEATURE_INTERPRETER
// I don't really know why this helps. Figure it out.
#ifndef DACCESS_COMPILE
// If we didn't find it above, try as an Interpretation stub...
pMethodDesc = Interpreter::InterpretationStubToMethodInfo(addr);
if (NULL != pMethodDesc)
{
goto lExit;
}
#endif
#endif // FEATURE_INTERPRETER
// Is it an FCALL?
pMethodDesc = ECall::MapTargetBackToMethod(addr);
if (pMethodDesc != 0)
{
goto lExit;
}
pMethodDesc = MethodDesc::GetMethodDescFromStubAddr(addr, fSpeculative);
lExit:
RETURN(pMethodDesc);
}
//==========================================================================================
/* static*/
BOOL MethodTable::ComputeContainsGenericVariables(Instantiation inst)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
for (DWORD j = 0; j < inst.GetNumArgs(); j++)
{
if (inst[j].ContainsGenericVariables())
{
return TRUE;
}
}
return FALSE;
}
//==========================================================================================
BOOL MethodTable::SanityCheck()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
// strings have component size2, all other non-arrays should have 0
_ASSERTE((GetComponentSize() <= 2) || IsArray());
if (m_pEEClass == NULL)
{
if (IsAsyncPinType())
{
return TRUE;
}
else
{
return FALSE;
}
}
EEClass * pClass = GetClass();
MethodTable * pCanonMT = pClass->GetMethodTable();
// Let's try to make sure we have a valid EEClass pointer.
if (pCanonMT == NULL)
return FALSE;
if (GetNumGenericArgs() != 0)
return (pCanonMT->GetClass() == pClass);
else
return (pCanonMT == this) || IsArray() || IsTransparentProxy();
}
//==========================================================================================
// Structs containing GC pointers whose size is at most this are always stack-allocated.
const unsigned MaxStructBytesForLocalVarRetBuffBytes = 2 * sizeof(void*); // 4 pointer-widths.
BOOL MethodTable::IsStructRequiringStackAllocRetBuf()
{
LIMITED_METHOD_DAC_CONTRACT;
// Disable this optimization. It has limited value (only kicks in on x86, and only for less common structs),
// causes bugs and introduces odd ABI differences not compatible with ReadyToRun.
return FALSE;
#if 0
#if defined(_WIN64)
// We have not yet updated the 64-bit JIT compiler to follow this directive, so there's
// no reason to stack-allocate the return buffers.
return FALSE;
#elif defined(MDIL) || defined(_TARGET_ARM_)
// WPB 481466 RetBuf GC hole (When jitting on ARM32 CoreCLR.dll MDIL is not defined)
//
// This optimization causes versioning problems for MDIL which we haven't addressed yet
return FALSE;
#else
return IsValueType()
&& ContainsPointers()
&& GetNumInstanceFieldBytes() <= MaxStructBytesForLocalVarRetBuffBytes;
#endif
#endif
}
//==========================================================================================
unsigned MethodTable::GetTypeDefRid()
{
LIMITED_METHOD_DAC_CONTRACT;
g_IBCLogger.LogMethodTableAccess(this);
return GetTypeDefRid_NoLogging();
}
//==========================================================================================
unsigned MethodTable::GetTypeDefRid_NoLogging()
{
LIMITED_METHOD_DAC_CONTRACT;
WORD token = m_wToken;
if (token == METHODTABLE_TOKEN_OVERFLOW)
return (unsigned)*GetTokenOverflowPtr();
return token;
}
//==========================================================================================
void MethodTable::SetCl(mdTypeDef token)
{
LIMITED_METHOD_CONTRACT;
unsigned rid = RidFromToken(token);
if (rid >= METHODTABLE_TOKEN_OVERFLOW)
{
m_wToken = METHODTABLE_TOKEN_OVERFLOW;
*GetTokenOverflowPtr() = rid;
}
else
{
_ASSERTE(FitsIn<U2>(rid));
m_wToken = (WORD)rid;
}
_ASSERTE(GetCl() == token);
}
//==========================================================================================
MethodDesc * MethodTable::GetClassConstructor()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
return GetMethodDescForSlot(GetClassConstructorSlot());
}
//==========================================================================================
DWORD MethodTable::HasFixedAddressVTStatics()
{
LIMITED_METHOD_CONTRACT;
return GetClass()->HasFixedAddressVTStatics();
}
//==========================================================================================
WORD MethodTable::GetNumHandleRegularStatics()
{
LIMITED_METHOD_CONTRACT;
return GetClass()->GetNumHandleRegularStatics();
}
//==========================================================================================
WORD MethodTable::GetNumBoxedRegularStatics()
{
LIMITED_METHOD_CONTRACT;
return GetClass()->GetNumBoxedRegularStatics();
}
//==========================================================================================
WORD MethodTable::GetNumBoxedThreadStatics ()
{
LIMITED_METHOD_CONTRACT;
return GetClass()->GetNumBoxedThreadStatics();
}
//==========================================================================================
ClassCtorInfoEntry* MethodTable::GetClassCtorInfoIfExists()
{
LIMITED_METHOD_CONTRACT;
if (!IsZapped())
return NULL;
g_IBCLogger.LogCCtorInfoReadAccess(this);
if (HasBoxedRegularStatics())
{
ModuleCtorInfo *pModuleCtorInfo = GetZapModule()->GetZapModuleCtorInfo();
DPTR(PTR_MethodTable) ppMT = pModuleCtorInfo->ppMT;
PTR_DWORD hotHashOffsets = pModuleCtorInfo->hotHashOffsets;
PTR_DWORD coldHashOffsets = pModuleCtorInfo->coldHashOffsets;
if (pModuleCtorInfo->numHotHashes)
{
DWORD hash = pModuleCtorInfo->GenerateHash(PTR_MethodTable(this), ModuleCtorInfo::HOT);
_ASSERTE(hash < pModuleCtorInfo->numHotHashes);
for (DWORD i = hotHashOffsets[hash]; i != hotHashOffsets[hash + 1]; i++)
{
_ASSERTE(ppMT[i]);
if (dac_cast<TADDR>(ppMT[i]) == dac_cast<TADDR>(this))
{
return pModuleCtorInfo->cctorInfoHot + i;
}
}
}
if (pModuleCtorInfo->numColdHashes)
{
DWORD hash = pModuleCtorInfo->GenerateHash(PTR_MethodTable(this), ModuleCtorInfo::COLD);
_ASSERTE(hash < pModuleCtorInfo->numColdHashes);
for (DWORD i = coldHashOffsets[hash]; i != coldHashOffsets[hash + 1]; i++)
{
_ASSERTE(ppMT[i]);
if (dac_cast<TADDR>(ppMT[i]) == dac_cast<TADDR>(this))
{
return pModuleCtorInfo->cctorInfoCold + (i - pModuleCtorInfo->numElementsHot);
}
}
}
}
return NULL;
}
#ifdef _DEBUG
//==========================================================================================
// Returns true if pointer to the parent method table has been initialized/restored already.
BOOL MethodTable::IsParentMethodTablePointerValid()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
// workaround: Type loader accesses partially initialized datastructures that interferes with IBC logging.
// Once type loader is fixed to do not access partially initialized datastructures, this can go away.
if (!GetWriteableData_NoLogging()->IsParentMethodTablePointerValid())
return FALSE;
if (!GetFlag(enum_flag_HasIndirectParent))
{
return TRUE;
}
TADDR pMT;
pMT = *PTR_TADDR(m_pParentMethodTable + offsetof(MethodTable, m_pParentMethodTable));
return !CORCOMPILE_IS_POINTER_TAGGED(pMT);
}
#endif
//---------------------------------------------------------------------------------------
//
// Ascends the parent class chain of "this", until a MethodTable is found whose typeDef
// matches that of the specified pWhichParent. Why is this useful? See
// code:MethodTable::GetInstantiationOfParentClass below and
// code:Generics::GetExactInstantiationsOfMethodAndItsClassFromCallInformation for use
// cases.
//
// Arguments:
// pWhichParent - MethodTable whose typeDef we're trying to match as we go up
// "this"'s parent chain.
//
// Return Value:
// If a matching parent MethodTable is found, it is returned. Else, NULL is
// returned.
//
MethodTable * MethodTable::GetMethodTableMatchingParentClass(MethodTable * pWhichParent)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
PRECONDITION(CheckPointer(pWhichParent));
PRECONDITION(IsRestored_NoLogging());
PRECONDITION(pWhichParent->IsRestored_NoLogging());
SUPPORTS_DAC;
} CONTRACTL_END;
MethodTable *pMethodTableSearch = this;
#ifdef DACCESS_COMPILE
unsigned parentCount = 0;
MethodTable *pOldMethodTable = NULL;
#endif // DACCESS_COMPILE
while (pMethodTableSearch != NULL)
{
#ifdef DACCESS_COMPILE
if (pMethodTableSearch == pOldMethodTable ||
parentCount > 1000)
{
break;
}
pOldMethodTable = pMethodTableSearch;
parentCount++;
#endif // DACCESS_COMPILE
if (pMethodTableSearch->HasSameTypeDefAs(pWhichParent))
{
return pMethodTableSearch;
}
pMethodTableSearch = pMethodTableSearch->GetParentMethodTable();
}
return NULL;
}
//==========================================================================================
// Given D<T> : C<List<T>> and a type handle D<string> we sometimes
// need to find the corresponding type handle
// C<List<string>> (C may also be some type
// further up the inheritance hierarchy). GetInstantiationOfParentClass
// helps us do this by getting the corresponding instantiation of C, i.e.
// <List<string>>.
//
// pWhichParent: this is used identify which parent type we're interested in.
// It must be a canonical EEClass, e.g. for C<ref>. This is used as a token for
// C<List<T>>. This method can also be called with the minimal methodtable used
// for dynamic methods. In that case, we need to return an empty instantiation.
//
// Note this only works for parent classes, not parent interfaces.
Instantiation MethodTable::GetInstantiationOfParentClass(MethodTable *pWhichParent)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
PRECONDITION(CheckPointer(pWhichParent));
PRECONDITION(IsRestored_NoLogging());
PRECONDITION(pWhichParent->IsRestored_NoLogging());
SUPPORTS_DAC;
} CONTRACTL_END;
MethodTable * pMatchingParent = GetMethodTableMatchingParentClass(pWhichParent);
if (pMatchingParent != NULL)
{
return pMatchingParent->GetInstantiation();
}
// The parameter should always be a parent class or the dynamic method
// class. Since there is no bit on the dynamicclass methodtable to indicate
// that it is the dynamic method methodtable, we simply check the debug name
// This is good enough for an assert.
_ASSERTE(strcmp(pWhichParent->GetDebugClassName(), "dynamicClass") == 0);
return Instantiation();
}
#ifndef DACCESS_COMPILE
#ifdef FEATURE_COMINTEROP
//
// This is for COM Interop backwards compatibility
//
//==========================================================================================
// Returns the data pointer if present, NULL otherwise
InteropMethodTableData *MethodTable::LookupComInteropData()
{
WRAPPER_NO_CONTRACT;
return GetDomain()->LookupComInteropData(this);
}
//==========================================================================================
// Returns TRUE if successfully inserted, FALSE if this would be a duplicate entry
BOOL MethodTable::InsertComInteropData(InteropMethodTableData *pData)
{
WRAPPER_NO_CONTRACT;
return GetDomain()->InsertComInteropData(this, pData);
}
//==========================================================================================
InteropMethodTableData *MethodTable::CreateComInteropData(AllocMemTracker *pamTracker)
{
CONTRACTL {
STANDARD_VM_CHECK;
PRECONDITION(GetParentMethodTable() == NULL || GetParentMethodTable()->LookupComInteropData() != NULL);
} CONTRACTL_END;
ClassCompat::MethodTableBuilder builder(this);
InteropMethodTableData *pData = builder.BuildInteropVTable(pamTracker);
_ASSERTE(pData);
return (pData);
}
//==========================================================================================
InteropMethodTableData *MethodTable::GetComInteropData()
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
InteropMethodTableData *pData = LookupComInteropData();
if (!pData)
{
GCX_PREEMP();
// Make sure that the parent's interop data has been created
MethodTable *pParentMT = GetParentMethodTable();
if (pParentMT)
pParentMT->GetComInteropData();
AllocMemTracker amTracker;
pData = CreateComInteropData(&amTracker);
if (InsertComInteropData(pData))
{
amTracker.SuppressRelease();
}
else
{
pData = LookupComInteropData();
}
}
_ASSERTE(pData);
return (pData);
}
#endif // FEATURE_COMINTEROP
//==========================================================================================
ULONG MethodTable::MethodData::Release()
{
LIMITED_METHOD_CONTRACT;
//@TODO: Must adjust this to use an alternate allocator so that we don't
//@TODO: potentially cause deadlocks on the debug thread.
SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE;
ULONG cRef = (ULONG) InterlockedDecrement((LONG*)&m_cRef);
if (cRef == 0) {
delete this;
}
return (cRef);
}
//==========================================================================================
void
MethodTable::MethodData::ProcessMap(
const DispatchMapTypeID * rgTypeIDs,
UINT32 cTypeIDs,
MethodTable * pMT,
UINT32 iCurrentChainDepth,
MethodDataEntry * rgWorkingData)
{
LIMITED_METHOD_CONTRACT;
for (DispatchMap::EncodedMapIterator it(pMT); it.IsValid(); it.Next())
{
for (UINT32 nTypeIDIndex = 0; nTypeIDIndex < cTypeIDs; nTypeIDIndex++)
{
if (it.Entry()->GetTypeID() == rgTypeIDs[nTypeIDIndex])
{
UINT32 curSlot = it.Entry()->GetSlotNumber();
// If we're processing an interface, or it's for a virtual, or it's for a non-virtual
// for the most derived type, we want to process the entry. In other words, we
// want to ignore non-virtuals for parent classes.
if ((curSlot < pMT->GetNumVirtuals()) || (iCurrentChainDepth == 0))
{
MethodDataEntry * pCurEntry = &rgWorkingData[curSlot];
if (!pCurEntry->IsDeclInit() && !pCurEntry->IsImplInit())
{
pCurEntry->SetImplData(it.Entry()->GetTargetSlotNumber());
}
}
}
}
}
} // MethodTable::MethodData::ProcessMap
//==========================================================================================
UINT32 MethodTable::MethodDataObject::GetObjectSize(MethodTable *pMT)
{
WRAPPER_NO_CONTRACT;
UINT32 cb = sizeof(MethodTable::MethodDataObject);
cb += pMT->GetCanonicalMethodTable()->GetNumMethods() * sizeof(MethodDataObjectEntry);
return cb;
}
//==========================================================================================
// This will fill in all the MethodEntry slots present in the current MethodTable
void MethodTable::MethodDataObject::Init(MethodTable *pMT, MethodData *pParentData)
{
CONTRACTL {
THROWS;
WRAPPER(GC_TRIGGERS);
PRECONDITION(CheckPointer(pMT));
PRECONDITION(CheckPointer(pParentData, NULL_OK));
PRECONDITION(!pMT->IsInterface());
PRECONDITION(pParentData == NULL ||
(pMT->ParentEquals(pParentData->GetDeclMethodTable()) &&
pMT->ParentEquals(pParentData->GetImplMethodTable())));
} CONTRACTL_END;
m_pMT = pMT;
m_iNextChainDepth = 0;
m_containsMethodImpl = FALSE;
ZeroMemory(GetEntryData(), sizeof(MethodDataObjectEntry) * GetNumMethods());
} // MethodTable::MethodDataObject::Init
//==========================================================================================
BOOL MethodTable::MethodDataObject::PopulateNextLevel()
{
LIMITED_METHOD_CONTRACT;
// Get the chain depth to next decode.
UINT32 iChainDepth = GetNextChainDepth();
// If the chain depth is MAX_CHAIN_DEPTH, then we've already parsed every parent.
if (iChainDepth == MAX_CHAIN_DEPTH) {
return FALSE;
}
// Now move up the chain to the target.
MethodTable *pMTCur = m_pMT;
for (UINT32 i = 0; pMTCur != NULL && i < iChainDepth; i++) {
pMTCur = pMTCur->GetParentMethodTable();
}
// If we reached the end, then we're done.
if (pMTCur == NULL) {
SetNextChainDepth(MAX_CHAIN_DEPTH);
return FALSE;
}
FillEntryDataForAncestor(pMTCur);
SetNextChainDepth(iChainDepth + 1);
return TRUE;
} // MethodTable::MethodDataObject::PopulateNextLevel
//==========================================================================================
void MethodTable::MethodDataObject::FillEntryDataForAncestor(MethodTable * pMT)
{
LIMITED_METHOD_CONTRACT;
// Since we traverse ancestors from lowest in the inheritance hierarchy
// to highest, the first method we come across for a slot is normally
// both the declaring and implementing method desc.
//
// However if this slot is the target of a methodImpl, pMD is not
// necessarily either. Rather than track this on a per-slot basis,
// we conservatively avoid filling out virtual methods once we
// have found that this inheritance chain contains a methodImpl.
//
// Note that there may be a methodImpl higher in the inheritance chain
// that we have not seen yet, and so we will fill out virtual methods
// until we reach that level. We are safe doing that because the slots
// we fill have been introduced/overridden by a subclass and so take
// precedence over any inherited methodImpl.
// Before we fill the entry data, find if the current ancestor has any methodImpls
if (pMT->GetClass()->ContainsMethodImpls())
m_containsMethodImpl = TRUE;
if (m_containsMethodImpl && pMT != m_pMT)
return;
unsigned nVirtuals = pMT->GetNumVirtuals();
MethodTable::IntroducedMethodIterator it(pMT, FALSE);
for (; it.IsValid(); it.Next())
{
MethodDesc * pMD = it.GetMethodDesc();
g_IBCLogger.LogMethodDescAccess(pMD);
unsigned slot = pMD->GetSlot();
if (slot == MethodTable::NO_SLOT)
continue;
// We want to fill all methods introduced by the actual type we're gathering
// data for, and the virtual methods of the parent and above
if (pMT == m_pMT)
{
if (m_containsMethodImpl && slot < nVirtuals)
continue;
}
else
{
if (slot >= nVirtuals)
continue;
}
MethodDataObjectEntry * pEntry = GetEntry(slot);
if (pEntry->GetDeclMethodDesc() == NULL)
{
pEntry->SetDeclMethodDesc(pMD);
}
if (pEntry->GetImplMethodDesc() == NULL)
{
pEntry->SetImplMethodDesc(pMD);
}
}
} // MethodTable::MethodDataObject::FillEntryDataForAncestor
//==========================================================================================
MethodDesc * MethodTable::MethodDataObject::GetDeclMethodDesc(UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(slotNumber < GetNumMethods());
MethodDataObjectEntry * pEntry = GetEntry(slotNumber);
// Fill the entries one level of inheritance at a time,
// stopping when we have filled the MD we are looking for.
while (!pEntry->GetDeclMethodDesc() && PopulateNextLevel());
MethodDesc * pMDRet = pEntry->GetDeclMethodDesc();
if (pMDRet == NULL)
{
pMDRet = GetImplMethodDesc(slotNumber)->GetDeclMethodDesc(slotNumber);
_ASSERTE(CheckPointer(pMDRet));
pEntry->SetDeclMethodDesc(pMDRet);
}
else
{
_ASSERTE(pMDRet == GetImplMethodDesc(slotNumber)->GetDeclMethodDesc(slotNumber));
}
return pMDRet;
}
//==========================================================================================
DispatchSlot MethodTable::MethodDataObject::GetImplSlot(UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(slotNumber < GetNumMethods());
return DispatchSlot(m_pMT->GetRestoredSlot(slotNumber));
}
//==========================================================================================
UINT32 MethodTable::MethodDataObject::GetImplSlotNumber(UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(slotNumber < GetNumMethods());
return slotNumber;
}
//==========================================================================================
MethodDesc *MethodTable::MethodDataObject::GetImplMethodDesc(UINT32 slotNumber)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE(slotNumber < GetNumMethods());
MethodDataObjectEntry *pEntry = GetEntry(slotNumber);
// Fill the entries one level of inheritance at a time,
// stopping when we have filled the MD we are looking for.
while (!pEntry->GetImplMethodDesc() && PopulateNextLevel());
MethodDesc *pMDRet = pEntry->GetImplMethodDesc();
if (pMDRet == NULL)
{
_ASSERTE(slotNumber < GetNumVirtuals());
pMDRet = m_pMT->GetMethodDescForSlot(slotNumber);
_ASSERTE(CheckPointer(pMDRet));
pEntry->SetImplMethodDesc(pMDRet);
}
else
{
_ASSERTE(slotNumber >= GetNumVirtuals() || pMDRet == m_pMT->GetMethodDescForSlot(slotNumber));
}
return pMDRet;
}
//==========================================================================================
void MethodTable::MethodDataObject::InvalidateCachedVirtualSlot(UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(slotNumber < GetNumVirtuals());
MethodDataObjectEntry *pEntry = GetEntry(slotNumber);
pEntry->SetImplMethodDesc(NULL);
}
//==========================================================================================
MethodDesc *MethodTable::MethodDataInterface::GetDeclMethodDesc(UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
return m_pMT->GetMethodDescForSlot(slotNumber);
}
//==========================================================================================
MethodDesc *MethodTable::MethodDataInterface::GetImplMethodDesc(UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
return MethodTable::MethodDataInterface::GetDeclMethodDesc(slotNumber);
}
//==========================================================================================
void MethodTable::MethodDataInterface::InvalidateCachedVirtualSlot(UINT32 slotNumber)
{
LIMITED_METHOD_CONTRACT;
// MethodDataInterface does not store any cached MethodDesc values
return;
}
//==========================================================================================
UINT32 MethodTable::MethodDataInterfaceImpl::GetObjectSize(MethodTable *pMTDecl)
{
WRAPPER_NO_CONTRACT;
UINT32 cb = sizeof(MethodDataInterfaceImpl);
cb += pMTDecl->GetNumMethods() * sizeof(MethodDataEntry);
return cb;
}
//==========================================================================================
// This will fill in all the MethodEntry slots present in the current MethodTable
void
MethodTable::MethodDataInterfaceImpl::Init(
const DispatchMapTypeID * rgDeclTypeIDs,
UINT32 cDeclTypeIDs,
MethodData * pDecl,
MethodData * pImpl)
{
CONTRACTL {
THROWS;
WRAPPER(GC_TRIGGERS);
PRECONDITION(CheckPointer(pDecl));
PRECONDITION(CheckPointer(pImpl));
PRECONDITION(pDecl->GetDeclMethodTable()->IsInterface());
PRECONDITION(!pImpl->GetDeclMethodTable()->IsInterface());
PRECONDITION(pDecl->GetDeclMethodTable() == pDecl->GetImplMethodTable());
PRECONDITION(pImpl->GetDeclMethodTable() == pImpl->GetImplMethodTable());
PRECONDITION(pDecl != pImpl);
} CONTRACTL_END;
// Store and AddRef the decl and impl data.
m_pDecl = pDecl;
m_pDecl->AddRef();
m_pImpl = pImpl;
m_pImpl->AddRef();
m_iNextChainDepth = 0;
// Need side effects of the calls, but not the result.
/* MethodTable *pDeclMT = */ pDecl->GetDeclMethodTable();
/* MethodTable *pImplMT = */ pImpl->GetImplMethodTable();
m_rgDeclTypeIDs = rgDeclTypeIDs;
m_cDeclTypeIDs = cDeclTypeIDs;
// Initialize each entry.
for (UINT32 i = 0; i < GetNumMethods(); i++) {
// Initialize the entry
GetEntry(i)->Init();
}
} // MethodTable::MethodDataInterfaceImpl::Init
//==========================================================================================
MethodTable::MethodDataInterfaceImpl::MethodDataInterfaceImpl(
const DispatchMapTypeID * rgDeclTypeIDs,
UINT32 cDeclTypeIDs,
MethodData * pDecl,
MethodData * pImpl)
{
WRAPPER_NO_CONTRACT;
Init(rgDeclTypeIDs, cDeclTypeIDs, pDecl, pImpl);
}
//==========================================================================================
MethodTable::MethodDataInterfaceImpl::~MethodDataInterfaceImpl()
{
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(CheckPointer(m_pDecl));
CONSISTENCY_CHECK(CheckPointer(m_pImpl));
m_pDecl->Release();
m_pImpl->Release();
}
//==========================================================================================
BOOL
MethodTable::MethodDataInterfaceImpl::PopulateNextLevel()
{
LIMITED_METHOD_CONTRACT;
// Get the chain depth to next decode.
UINT32 iChainDepth = GetNextChainDepth();
// If the chain depth is MAX_CHAIN_DEPTH, then we've already parsed every parent.
if (iChainDepth == MAX_CHAIN_DEPTH) {
return FALSE;
}
// Now move up the chain to the target.
MethodTable *pMTCur = m_pImpl->GetImplMethodTable();
for (UINT32 i = 0; pMTCur != NULL && i < iChainDepth; i++) {
pMTCur = pMTCur->GetParentMethodTable();
}
// If we reached the end, then we're done.
if (pMTCur == NULL) {
SetNextChainDepth(MAX_CHAIN_DEPTH);
return FALSE;
}
if (m_cDeclTypeIDs != 0)
{ // We got the TypeIDs from TypeLoader, use them
ProcessMap(m_rgDeclTypeIDs, m_cDeclTypeIDs, pMTCur, iChainDepth, GetEntryData());
}
else
{ // We should decode all interface duplicates of code:m_pDecl
MethodTable * pDeclMT = m_pDecl->GetImplMethodTable();
INDEBUG(BOOL dbg_fInterfaceFound = FALSE);
// Call code:ProcessMap for every (duplicate) occurence of interface code:pDeclMT in the interface
// map of code:m_pImpl
MethodTable::InterfaceMapIterator it = m_pImpl->GetImplMethodTable()->IterateInterfaceMap();
while (it.Next())
{
if (pDeclMT == it.GetInterface())
{ // We found the interface
INDEBUG(dbg_fInterfaceFound = TRUE);
DispatchMapTypeID declTypeID = DispatchMapTypeID::InterfaceClassID(it.GetIndex());
ProcessMap(&declTypeID, 1, pMTCur, iChainDepth, GetEntryData());
}
}
// The interface code:m_Decl should be found at least once in the interface map of code:m_pImpl,
// otherwise someone passed wrong information
_ASSERTE(dbg_fInterfaceFound);
}
SetNextChainDepth(iChainDepth + 1);
return TRUE;
} // MethodTable::MethodDataInterfaceImpl::PopulateNextLevel
//==========================================================================================
UINT32 MethodTable::MethodDataInterfaceImpl::MapToImplSlotNumber(UINT32 slotNumber)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(slotNumber < GetNumMethods());
MethodDataEntry *pEntry = GetEntry(slotNumber);
while (!pEntry->IsImplInit() && PopulateNextLevel()) {}
if (pEntry->IsImplInit()) {
return pEntry->GetImplSlotNum();
}
else {
return INVALID_SLOT_NUMBER;
}
}
//==========================================================================================
DispatchSlot MethodTable::MethodDataInterfaceImpl::GetImplSlot(UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
UINT32 implSlotNumber = MapToImplSlotNumber(slotNumber);
if (implSlotNumber == INVALID_SLOT_NUMBER) {
return DispatchSlot(NULL);
}
return m_pImpl->GetImplSlot(implSlotNumber);
}
//==========================================================================================
UINT32 MethodTable::MethodDataInterfaceImpl::GetImplSlotNumber(UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
return MapToImplSlotNumber(slotNumber);
}
//==========================================================================================
MethodDesc *MethodTable::MethodDataInterfaceImpl::GetImplMethodDesc(UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
UINT32 implSlotNumber = MapToImplSlotNumber(slotNumber);
if (implSlotNumber == INVALID_SLOT_NUMBER) {
return NULL;
}
return m_pImpl->GetImplMethodDesc(MapToImplSlotNumber(slotNumber));
}
//==========================================================================================
void MethodTable::MethodDataInterfaceImpl::InvalidateCachedVirtualSlot(UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
UINT32 implSlotNumber = MapToImplSlotNumber(slotNumber);
if (implSlotNumber == INVALID_SLOT_NUMBER) {
return;
}
return m_pImpl->InvalidateCachedVirtualSlot(MapToImplSlotNumber(slotNumber));
}
//==========================================================================================
void MethodTable::CheckInitMethodDataCache()
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
SO_TOLERANT;
} CONTRACTL_END;
if (s_pMethodDataCache == NULL)
{
UINT32 cb = MethodDataCache::GetObjectSize(8);
NewHolder<BYTE> hb(new BYTE[cb]);
MethodDataCache *pCache = new (hb.GetValue()) MethodDataCache(8);
if (InterlockedCompareExchangeT(
&s_pMethodDataCache, pCache, NULL) == NULL)
{
hb.SuppressRelease();
}
// If somebody beat us, return and allow the holders to take care of cleanup.
else
{
return;
}
}
}
//==========================================================================================
void MethodTable::ClearMethodDataCache()
{
LIMITED_METHOD_CONTRACT;
if (s_pMethodDataCache != NULL) {
s_pMethodDataCache->Clear();
}
}
//==========================================================================================
MethodTable::MethodData *MethodTable::FindMethodDataHelper(MethodTable *pMTDecl, MethodTable *pMTImpl)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
CONSISTENCY_CHECK(s_fUseMethodDataCache);
} CONTRACTL_END;
return s_pMethodDataCache->Find(pMTDecl, pMTImpl);
}
//==========================================================================================
MethodTable::MethodData *MethodTable::FindParentMethodDataHelper(MethodTable *pMT)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
MethodData *pData = NULL;
if (s_fUseMethodDataCache && s_fUseParentMethodData) {
if (!pMT->IsInterface()) {
//@todo : this won't be correct for non-shared code
MethodTable *pMTParent = pMT->GetParentMethodTable();
if (pMTParent != NULL) {
pData = FindMethodDataHelper(pMTParent, pMTParent);
}
}
}
return pData;
}
//==========================================================================================
// This method does not cache the resulting MethodData object in the global MethodDataCache.
// The TypeIDs (rgDeclTypeIDs with cDeclTypeIDs items) have to be sorted.
MethodTable::MethodData *
MethodTable::GetMethodDataHelper(
const DispatchMapTypeID * rgDeclTypeIDs,
UINT32 cDeclTypeIDs,
MethodTable * pMTDecl,
MethodTable * pMTImpl)
{
CONTRACTL {
THROWS;
WRAPPER(GC_TRIGGERS);
PRECONDITION(CheckPointer(pMTDecl));
PRECONDITION(CheckPointer(pMTImpl));
} CONTRACTL_END;
//@TODO: Must adjust this to use an alternate allocator so that we don't
//@TODO: potentially cause deadlocks on the debug thread.
SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE;
CONSISTENCY_CHECK(pMTDecl->IsInterface() && !pMTImpl->IsInterface());
#ifdef _DEBUG
// Check that rgDeclTypeIDs are sorted, are valid interface indexes and reference only pMTDecl interface
{
InterfaceInfo_t * rgImplInterfaceMap = pMTImpl->GetInterfaceMap();
UINT32 cImplInterfaceMap = pMTImpl->GetNumInterfaces();
// Verify that all types referenced by code:rgDeclTypeIDs are code:pMTDecl (declared interface)
for (UINT32 nDeclTypeIDIndex = 0; nDeclTypeIDIndex < cDeclTypeIDs; nDeclTypeIDIndex++)
{
if (nDeclTypeIDIndex > 0)
{ // Verify that interface indexes are sorted
_ASSERTE(rgDeclTypeIDs[nDeclTypeIDIndex - 1].GetInterfaceNum() < rgDeclTypeIDs[nDeclTypeIDIndex].GetInterfaceNum());
}
UINT32 nInterfaceIndex = rgDeclTypeIDs[nDeclTypeIDIndex].GetInterfaceNum();
_ASSERTE(nInterfaceIndex <= cImplInterfaceMap);
{
OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOAD_APPROXPARENTS);
_ASSERTE(rgImplInterfaceMap[nInterfaceIndex].GetApproxMethodTable(pMTImpl->GetLoaderModule())->HasSameTypeDefAs(pMTDecl));
}
}
}
#endif //_DEBUG
// Can't cache, since this is a custom method used in BuildMethodTable
MethodDataWrapper hDecl(GetMethodData(pMTDecl, FALSE));
MethodDataWrapper hImpl(GetMethodData(pMTImpl, FALSE));
UINT32 cb = MethodDataInterfaceImpl::GetObjectSize(pMTDecl);
NewHolder<BYTE> pb(new BYTE[cb]);
MethodDataInterfaceImpl * pData = new (pb.GetValue()) MethodDataInterfaceImpl(rgDeclTypeIDs, cDeclTypeIDs, hDecl, hImpl);
pb.SuppressRelease();
return pData;
} // MethodTable::GetMethodDataHelper
//==========================================================================================
// The fCanCache argument determines if the resulting MethodData object can
// be added to the global MethodDataCache. This is used when requesting a
// MethodData object for a type currently being built.
MethodTable::MethodData *MethodTable::GetMethodDataHelper(MethodTable *pMTDecl,
MethodTable *pMTImpl,
BOOL fCanCache)
{
CONTRACTL {
THROWS;
WRAPPER(GC_TRIGGERS);
PRECONDITION(CheckPointer(pMTDecl));
PRECONDITION(CheckPointer(pMTImpl));
PRECONDITION(pMTDecl == pMTImpl ||
(pMTDecl->IsInterface() && !pMTImpl->IsInterface()));
} CONTRACTL_END;
//@TODO: Must adjust this to use an alternate allocator so that we don't
//@TODO: potentially cause deadlocks on the debug thread.
SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE;
if (s_fUseMethodDataCache) {
MethodData *pData = FindMethodDataHelper(pMTDecl, pMTImpl);
if (pData != NULL) {
return pData;
}
}
// If we get here, there are no entries in the cache.
MethodData *pData = NULL;
if (pMTDecl == pMTImpl) {
if (pMTDecl->IsInterface()) {
pData = new MethodDataInterface(pMTDecl);
}
else {
UINT32 cb = MethodDataObject::GetObjectSize(pMTDecl);
NewHolder<BYTE> pb(new BYTE[cb]);
MethodDataHolder h(FindParentMethodDataHelper(pMTDecl));
pData = new (pb.GetValue()) MethodDataObject(pMTDecl, h.GetValue());
pb.SuppressRelease();
}
}
else {
pData = GetMethodDataHelper(
NULL,
0,
pMTDecl,
pMTImpl);
}
// Insert in the cache if it is active.
if (fCanCache && s_fUseMethodDataCache) {
s_pMethodDataCache->Insert(pData);
}
// Do not AddRef, already initialized to 1.
return pData;
}
//==========================================================================================
// The fCanCache argument determines if the resulting MethodData object can
// be added to the global MethodDataCache. This is used when requesting a
// MethodData object for a type currently being built.
MethodTable::MethodData *MethodTable::GetMethodData(MethodTable *pMTDecl,
MethodTable *pMTImpl,
BOOL fCanCache)
{
CONTRACTL {
THROWS;
WRAPPER(GC_TRIGGERS);
} CONTRACTL_END;
MethodDataWrapper hData(GetMethodDataHelper(pMTDecl, pMTImpl, fCanCache));
hData.SuppressRelease();
return hData;
}
//==========================================================================================
// This method does not cache the resulting MethodData object in the global MethodDataCache.
MethodTable::MethodData *
MethodTable::GetMethodData(
const DispatchMapTypeID * rgDeclTypeIDs,
UINT32 cDeclTypeIDs,
MethodTable * pMTDecl,
MethodTable * pMTImpl)
{
CONTRACTL {
THROWS;
WRAPPER(GC_TRIGGERS);
PRECONDITION(pMTDecl != pMTImpl);
PRECONDITION(pMTDecl->IsInterface());
PRECONDITION(!pMTImpl->IsInterface());
} CONTRACTL_END;
MethodDataWrapper hData(GetMethodDataHelper(rgDeclTypeIDs, cDeclTypeIDs, pMTDecl, pMTImpl));
hData.SuppressRelease();
return hData;
}
//==========================================================================================
// The fCanCache argument determines if the resulting MethodData object can
// be added to the global MethodDataCache. This is used when requesting a
// MethodData object for a type currently being built.
MethodTable::MethodData *MethodTable::GetMethodData(MethodTable *pMT,
BOOL fCanCache)
{
WRAPPER_NO_CONTRACT;
return GetMethodData(pMT, pMT, fCanCache);
}
//==========================================================================================
MethodTable::MethodIterator::MethodIterator(MethodTable *pMTDecl, MethodTable *pMTImpl)
{
WRAPPER_NO_CONTRACT;
Init(pMTDecl, pMTImpl);
}
//==========================================================================================
MethodTable::MethodIterator::MethodIterator(MethodTable *pMT)
{
WRAPPER_NO_CONTRACT;
Init(pMT, pMT);
}
//==========================================================================================
MethodTable::MethodIterator::MethodIterator(MethodData *pMethodData)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(CheckPointer(pMethodData));
} CONTRACTL_END;
m_pMethodData = pMethodData;
m_pMethodData->AddRef();
m_iCur = 0;
m_iMethods = (INT32)m_pMethodData->GetNumMethods();
}
//==========================================================================================
MethodTable::MethodIterator::MethodIterator(const MethodIterator &it)
{
WRAPPER_NO_CONTRACT;
m_pMethodData = it.m_pMethodData;
m_pMethodData->AddRef();
m_iCur = it.m_iCur;
m_iMethods = it.m_iMethods;
}
//==========================================================================================
void MethodTable::MethodIterator::Init(MethodTable *pMTDecl, MethodTable *pMTImpl)
{
CONTRACTL {
THROWS;
WRAPPER(GC_TRIGGERS);
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(CheckPointer(pMTDecl));
PRECONDITION(CheckPointer(pMTImpl));
} CONTRACTL_END;
LOG((LF_LOADER, LL_INFO10000, "SD: MT::MethodIterator created for %s.\n", pMTDecl->GetDebugClassName()));
m_pMethodData = MethodTable::GetMethodData(pMTDecl, pMTImpl);
CONSISTENCY_CHECK(CheckPointer(m_pMethodData));
m_iCur = 0;
m_iMethods = (INT32)m_pMethodData->GetNumMethods();
}
#endif // !DACCESS_COMPILE
//==========================================================================================
void MethodTable::IntroducedMethodIterator::SetChunk(MethodDescChunk * pChunk)
{
LIMITED_METHOD_CONTRACT;
if (pChunk)
{
m_pMethodDesc = pChunk->GetFirstMethodDesc();
m_pChunk = pChunk;
m_pChunkEnd = dac_cast<TADDR>(pChunk) + pChunk->SizeOf();
}
else
{
m_pMethodDesc = NULL;
}
}
//==========================================================================================
MethodDesc * MethodTable::IntroducedMethodIterator::GetFirst(MethodTable *pMT)
{
LIMITED_METHOD_CONTRACT;
MethodDescChunk * pChunk = pMT->GetClass()->GetChunks();
return (pChunk != NULL) ? pChunk->GetFirstMethodDesc() : NULL;
}
//==========================================================================================
MethodDesc * MethodTable::IntroducedMethodIterator::GetNext(MethodDesc * pMD)
{
WRAPPER_NO_CONTRACT;
MethodDescChunk * pChunk = pMD->GetMethodDescChunk();
// Check whether the next MethodDesc is still within the bounds of the current chunk
TADDR pNext = dac_cast<TADDR>(pMD) + pMD->SizeOf();
TADDR pEnd = dac_cast<TADDR>(pChunk) + pChunk->SizeOf();
if (pNext < pEnd)
{
// Just skip to the next method in the same chunk
pMD = PTR_MethodDesc(pNext);
}
else
{
_ASSERTE(pNext == pEnd);
// We have walked all the methods in the current chunk. Move on
// to the next chunk.
pChunk = pChunk->GetNextChunk();
pMD = (pChunk != NULL) ? pChunk->GetFirstMethodDesc() : NULL;
}
return pMD;
}
//==========================================================================================
PTR_GuidInfo MethodTable::GetGuidInfo()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifdef FEATURE_COMINTEROP
if (HasGuidInfo())
{
return *GetGuidInfoPtr();
}
#endif // FEATURE_COMINTEROP
_ASSERTE(GetClass());
return GetClass()->GetGuidInfo();
}
//==========================================================================================
void MethodTable::SetGuidInfo(GuidInfo* pGuidInfo)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifndef DACCESS_COMPILE
#ifdef FEATURE_COMINTEROP
if (HasGuidInfo())
{
*EnsureWritablePages(GetGuidInfoPtr()) = pGuidInfo;
return;
}
#endif // FEATURE_COMINTEROP
_ASSERTE(GetClass());
GetClass()->SetGuidInfo (pGuidInfo);
#endif // DACCESS_COMPILE
}
#if defined(FEATURE_COMINTEROP) && !defined(DACCESS_COMPILE)
//==========================================================================================
RCWPerTypeData *MethodTable::CreateRCWPerTypeData(bool bThrowOnOOM)
{
CONTRACTL
{
if (bThrowOnOOM) THROWS; else NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(HasRCWPerTypeData());
}
CONTRACTL_END;
AllocMemTracker amTracker;
RCWPerTypeData *pData;
if (bThrowOnOOM)
{
TaggedMemAllocPtr ptr = GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(RCWPerTypeData)));
pData = (RCWPerTypeData *)amTracker.Track(ptr);
}
else
{
TaggedMemAllocPtr ptr = GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem_NoThrow(S_SIZE_T(sizeof(RCWPerTypeData)));
pData = (RCWPerTypeData *)amTracker.Track_NoThrow(ptr);
if (pData == NULL)
{
return NULL;
}
}
// memory is zero-inited which means that nothing has been computed yet
_ASSERTE(pData->m_dwFlags == 0);
RCWPerTypeData **pDataPtr = GetRCWPerTypeDataPtr();
if (bThrowOnOOM)
{
EnsureWritablePages(pDataPtr);
}
else
{
if (!EnsureWritablePagesNoThrow(pDataPtr, sizeof(*pDataPtr)))
{
return NULL;
}
}
if (InterlockedCompareExchangeT(pDataPtr, pData, NULL) == NULL)
{
amTracker.SuppressRelease();
}
else
{
// another thread already published the pointer
pData = *pDataPtr;
}
return pData;
}
//==========================================================================================
RCWPerTypeData *MethodTable::GetRCWPerTypeData(bool bThrowOnOOM /*= true*/)
{
CONTRACTL
{
if (bThrowOnOOM) THROWS; else NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
if (!HasRCWPerTypeData())
return NULL;
RCWPerTypeData *pData = *GetRCWPerTypeDataPtr();
if (pData == NULL)
{
// creation is factored out into a separate routine to avoid paying the EH cost here
pData = CreateRCWPerTypeData(bThrowOnOOM);
}
return pData;
}
#endif // FEATURE_COMINTEROP && !DACCESS_COMPILE
//==========================================================================================
CHECK MethodTable::CheckActivated()
{
WRAPPER_NO_CONTRACT;
if (!IsArray())
{
CHECK(GetModule()->CheckActivated());
}
// <TODO> Check all generic type parameters as well </TODO>
CHECK_OK;
}
#ifdef _MSC_VER
// Optimization intended for EnsureInstanceActive, IsIntrospectionOnly, EnsureActive only
#pragma optimize("t", on)
#endif // _MSC_VER
//==========================================================================================
#ifndef DACCESS_COMPILE
VOID MethodTable::EnsureInstanceActive()
{
CONTRACTL
{
GC_TRIGGERS;
THROWS;
MODE_ANY;
}
CONTRACTL_END;
Module * pModule = GetModule();
pModule->EnsureActive();
MethodTable * pMT = this;
while (pMT->HasModuleDependencies())
{
pMT = pMT->GetParentMethodTable();
_ASSERTE(pMT != NULL);
Module * pParentModule = pMT->GetModule();
if (pParentModule != pModule)
{
pModule = pParentModule;
pModule->EnsureActive();
}
}
if (HasInstantiation())
{
// This is going to go recursive, so we need to use an interior stack probe
INTERIOR_STACK_PROBE(GetThread());
{
Instantiation inst = GetInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
TypeHandle thArg = inst[i];
if (!thArg.IsTypeDesc())
{
thArg.AsMethodTable()->EnsureInstanceActive();
}
}
}
END_INTERIOR_STACK_PROBE;
}
}
#endif //!DACCESS_COMPILE
//==========================================================================================
BOOL MethodTable::IsIntrospectionOnly()
{
WRAPPER_NO_CONTRACT;
return GetAssembly()->IsIntrospectionOnly();
}
//==========================================================================================
BOOL MethodTable::ContainsIntrospectionOnlyTypes()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END
// check this type
if (IsIntrospectionOnly())
return TRUE;
// check the instantiation
Instantiation inst = GetInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
CONSISTENCY_CHECK(!inst[i].IsEncodedFixup());
if (inst[i].ContainsIntrospectionOnlyTypes())
return TRUE;
}
return FALSE;
}
//==========================================================================================
#ifndef DACCESS_COMPILE
VOID MethodTable::EnsureActive()
{
WRAPPER_NO_CONTRACT;
GetModule()->EnsureActive();
}
#endif
#ifdef _MSC_VER
#pragma optimize("", on)
#endif // _MSC_VER
//==========================================================================================
CHECK MethodTable::CheckInstanceActivated()
{
WRAPPER_NO_CONTRACT;
if (IsArray())
CHECK_OK;
Module * pModule = GetModule();
CHECK(pModule->CheckActivated());
MethodTable * pMT = this;
while (pMT->HasModuleDependencies())
{
pMT = pMT->GetParentMethodTable();
_ASSERTE(pMT != NULL);
Module * pParentModule = pMT->GetModule();
if (pParentModule != pModule)
{
pModule = pParentModule;
CHECK(pModule->CheckActivated());
}
}
CHECK_OK;
}
#ifdef DACCESS_COMPILE
//==========================================================================================
void
MethodTable::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
DAC_CHECK_ENUM_THIS();
EMEM_OUT(("MEM: %p MethodTable\n", dac_cast<TADDR>(this)));
DWORD size = GetEndOffsetOfOptionalMembers();
DacEnumMemoryRegion(dac_cast<TADDR>(this), size);
if (!IsCanonicalMethodTable())
{
PTR_MethodTable pMTCanonical = GetCanonicalMethodTable();
if (pMTCanonical.IsValid())
{
pMTCanonical->EnumMemoryRegions(flags);
}
}
else
{
PTR_EEClass pClass = GetClass();
if (pClass.IsValid())
{
if (IsArray())
{
// This is kind of a workaround, in that ArrayClass is derived from EEClass, but
// it's not virtual, we only cast if the IsArray() predicate holds above.
// For minidumps, DAC will choke if we don't have the full size given
// by ArrayClass available. If ArrayClass becomes more complex, it
// should get it's own EnumMemoryRegions().
DacEnumMemoryRegion(dac_cast<TADDR>(pClass), sizeof(ArrayClass));
}
pClass->EnumMemoryRegions(flags, this);
}
}
PTR_MethodTable pMTParent = GetParentMethodTable();
if (pMTParent.IsValid())
{
pMTParent->EnumMemoryRegions(flags);
}
if (HasNonVirtualSlotsArray())
{
DacEnumMemoryRegion(dac_cast<TADDR>(GetNonVirtualSlotsArray()), GetNonVirtualSlotsArraySize());
}
if (HasInterfaceMap())
{
#ifdef FEATURE_COMINTEROP
if (HasDynamicInterfaceMap())
DacEnumMemoryRegion(dac_cast<TADDR>(GetInterfaceMap()) - sizeof(DWORD_PTR), GetInterfaceMapSize());
else
#endif // FEATURE_COMINTEROP
DacEnumMemoryRegion(dac_cast<TADDR>(GetInterfaceMap()), GetInterfaceMapSize());
EnumMemoryRegionsForExtraInterfaceInfo();
}
if (HasPerInstInfo() != NULL)
{
DacEnumMemoryRegion(dac_cast<TADDR>(GetPerInstInfo()) - sizeof(GenericsDictInfo), GetPerInstInfoSize() + sizeof(GenericsDictInfo));
}
if (GetDictionary() != NULL)
{
DacEnumMemoryRegion(dac_cast<TADDR>(GetDictionary()), GetInstAndDictSize());
}
VtableIndirectionSlotIterator it = IterateVtableIndirectionSlots();
while (it.Next())
{
DacEnumMemoryRegion(dac_cast<TADDR>(it.GetIndirectionSlot()), it.GetSize());
}
if (m_pWriteableData.IsValid())
{
m_pWriteableData.EnumMem();
}
if (flags != CLRDATA_ENUM_MEM_MINI && flags != CLRDATA_ENUM_MEM_TRIAGE)
{
DispatchMap * pMap = GetDispatchMap();
if (pMap != NULL)
{
pMap->EnumMemoryRegions(flags);
}
}
} // MethodTable::EnumMemoryRegions
#endif // DACCESS_COMPILE
//==========================================================================================
BOOL MethodTable::ContainsGenericMethodVariables()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END
Instantiation inst = GetInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
CONSISTENCY_CHECK(!inst[i].IsEncodedFixup());
if (inst[i].ContainsGenericVariables(TRUE))
return TRUE;
}
return FALSE;
}
//==========================================================================================
Module *MethodTable::GetDefiningModuleForOpenType()
{
CONTRACT(Module*)
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
POSTCONDITION((ContainsGenericVariables() != 0) == (RETVAL != NULL));
SUPPORTS_DAC;
}
CONTRACT_END
if (ContainsGenericVariables())
{
Instantiation inst = GetInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
// Encoded fixups are never open types
if (!inst[i].IsEncodedFixup())
{
Module *pModule = inst[i].GetDefiningModuleForOpenType();
if (pModule != NULL)
RETURN pModule;
}
}
}
RETURN NULL;
}
//==========================================================================================
PCODE MethodTable::GetRestoredSlot(DWORD slotNumber)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SO_TOLERANT;
SUPPORTS_DAC;
} CONTRACTL_END;
//
// Keep in sync with code:MethodTable::GetRestoredSlotMT
//
MethodTable * pMT = this;
while (true)
{
g_IBCLogger.LogMethodTableAccess(pMT);
pMT = pMT->GetCanonicalMethodTable();
_ASSERTE(pMT != NULL);
PCODE slot = pMT->GetSlot(slotNumber);
if ((slot != NULL)
#ifdef FEATURE_PREJIT
&& !pMT->GetLoaderModule()->IsVirtualImportThunk(slot)
#endif
)
{
return slot;
}
// This is inherited slot that has not been fixed up yet. Find
// the value by walking up the inheritance chain
pMT = pMT->GetParentMethodTable();
}
}
//==========================================================================================
MethodTable * MethodTable::GetRestoredSlotMT(DWORD slotNumber)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SO_TOLERANT;
SUPPORTS_DAC;
} CONTRACTL_END;
//
// Keep in sync with code:MethodTable::GetRestoredSlot
//
MethodTable * pMT = this;
while (true)
{
g_IBCLogger.LogMethodTableAccess(pMT);
pMT = pMT->GetCanonicalMethodTable();
_ASSERTE(pMT != NULL);
PCODE slot = pMT->GetSlot(slotNumber);
if ((slot != NULL)
#ifdef FEATURE_PREJIT
&& !pMT->GetLoaderModule()->IsVirtualImportThunk(slot)
#endif
)
{
return pMT;
}
// This is inherited slot that has not been fixed up yet. Find
// the value by walking up the inheritance chain
pMT = pMT->GetParentMethodTable();
}
}
//==========================================================================================
MethodDesc * MethodTable::GetParallelMethodDesc(MethodDesc * pDefMD)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
return GetMethodDescForSlot(pDefMD->GetSlot());
}
#ifndef DACCESS_COMPILE
//==========================================================================================
void MethodTable::SetSlot(UINT32 slotNumber, PCODE slotCode)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
#ifdef _DEBUG
if (slotNumber < GetNumVirtuals())
{
//
// Verify that slots in shared vtable chunks not owned by this methodtable are only ever patched to stable entrypoint.
// This invariant is required to prevent races with code:MethodDesc::SetStableEntryPointInterlocked.
//
BOOL fSharedVtableChunk = FALSE;
DWORD indirectionIndex = MethodTable::GetIndexOfVtableIndirection(slotNumber);
if (!IsCanonicalMethodTable())
{
if (GetVtableIndirections()[indirectionIndex] == GetCanonicalMethodTable()->GetVtableIndirections()[indirectionIndex])
fSharedVtableChunk = TRUE;
}
if (slotNumber < GetNumParentVirtuals())
{
if (GetVtableIndirections()[indirectionIndex] == GetParentMethodTable()->GetVtableIndirections()[indirectionIndex])
fSharedVtableChunk = TRUE;
}
if (fSharedVtableChunk)
{
MethodDesc* pMD = GetMethodDescForSlotAddress(slotCode);
#ifndef FEATURE_INTERPRETER
// TBD: Make this take a "stable" debug arg, determining whether to make these assertions.
_ASSERTE(pMD->HasStableEntryPoint());
_ASSERTE(pMD->GetStableEntryPoint() == slotCode);
#endif // FEATURE_INTERPRETER
}
}
#endif
// IBC logging is not needed here - slots in ngen images are immutable.
#ifdef _TARGET_ARM_
// Ensure on ARM that all target addresses are marked as thumb code.
_ASSERTE(IsThumbCode(slotCode));
#endif
*GetSlotPtrRaw(slotNumber) = slotCode;
}
//==========================================================================================
BOOL MethodTable::HasExplicitOrImplicitPublicDefaultConstructor()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END
if (IsValueType())
{
// valuetypes have public default ctors implicitly
return TRUE;
}
if (!HasDefaultConstructor())
{
return FALSE;
}
MethodDesc * pCanonMD = GetMethodDescForSlot(GetDefaultConstructorSlot());
return pCanonMD != NULL && pCanonMD->IsPublic();
}
//==========================================================================================
MethodDesc *MethodTable::GetDefaultConstructor()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(HasDefaultConstructor());
MethodDesc *pCanonMD = GetMethodDescForSlot(GetDefaultConstructorSlot());
// The default constructor for a value type is an instantiating stub.
// The easiest way to find the right stub is to use the following function,
// which in the simple case of the default constructor for a class simply
// returns pCanonMD immediately.
return MethodDesc::FindOrCreateAssociatedMethodDesc(pCanonMD,
this,
FALSE /* no BoxedEntryPointStub */,
Instantiation(), /* no method instantiation */
FALSE /* no allowInstParam */);
}
//==========================================================================================
// Finds the (non-unboxing) MethodDesc that implements the interface method pInterfaceMD.
//
// Note our ability to resolve constraint methods is affected by the degree of code sharing we are
// performing for generic code.
//
// Return Value:
// MethodDesc which can be used as unvirtualized call. Returns NULL if VSD has to be used.
MethodDesc *
MethodTable::TryResolveConstraintMethodApprox(
TypeHandle thInterfaceType,
MethodDesc * pInterfaceMD,
BOOL * pfForceUseRuntimeLookup) // = NULL
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
// We can't resolve constraint calls effectively for reference types, and there's
// not a lot of perf. benefit in doing it anyway.
//
if (!IsValueType())
{
LOG((LF_JIT, LL_INFO10000, "TryResolveConstraintmethodApprox: not a value type %s\n", GetDebugClassName()));
return NULL;
}
// 1. Find the (possibly generic) method that would implement the
// constraint if we were making a call on a boxed value type.
MethodTable * pCanonMT = GetCanonicalMethodTable();
MethodDesc * pGenInterfaceMD = pInterfaceMD->StripMethodInstantiation();
MethodDesc * pMD = NULL;
if (pGenInterfaceMD->IsInterface())
{
// Sometimes (when compiling shared generic code)
// we don't have enough exact type information at JIT time
// even to decide whether we will be able to resolve to an unboxed entry point...
// To cope with this case we always go via the helper function if there's any
// chance of this happening by checking for all interfaces which might possibly
// be compatible with the call (verification will have ensured that
// at least one of them will be)
// Enumerate all potential interface instantiations
MethodTable::InterfaceMapIterator it = pCanonMT->IterateInterfaceMap();
DWORD cPotentialMatchingInterfaces = 0;
while (it.Next())
{
TypeHandle thPotentialInterfaceType(it.GetInterface());
if (thPotentialInterfaceType.AsMethodTable()->GetCanonicalMethodTable() ==
thInterfaceType.AsMethodTable()->GetCanonicalMethodTable())
{
cPotentialMatchingInterfaces++;
pMD = pCanonMT->GetMethodDescForInterfaceMethod(thPotentialInterfaceType, pGenInterfaceMD);
// See code:#TryResolveConstraintMethodApprox_DoNotReturnParentMethod
if ((pMD != NULL) && !pMD->GetMethodTable()->IsValueType())
{
LOG((LF_JIT, LL_INFO10000, "TryResolveConstraintMethodApprox: %s::%s not a value type method\n",
pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
return NULL;
}
}
}
_ASSERTE_MSG((cPotentialMatchingInterfaces != 0),
"At least one interface has to implement the method, otherwise there's a bug in JIT/verification.");
if (cPotentialMatchingInterfaces > 1)
{ // We have more potentially matching interfaces
MethodTable * pInterfaceMT = thInterfaceType.GetMethodTable();
_ASSERTE(pInterfaceMT->HasInstantiation());
BOOL fIsExactMethodResolved = FALSE;
if (!pInterfaceMT->IsSharedByGenericInstantiations() &&
!pInterfaceMT->IsGenericTypeDefinition() &&
!this->IsSharedByGenericInstantiations() &&
!this->IsGenericTypeDefinition())
{ // We have exact interface and type instantiations (no generic variables and __Canon used
// anywhere)
if (this->CanCastToInterface(pInterfaceMT))
{
// We can resolve to exact method
pMD = this->GetMethodDescForInterfaceMethod(pInterfaceMT, pInterfaceMD);
_ASSERTE(pMD != NULL);
fIsExactMethodResolved = TRUE;
}
}
if (!fIsExactMethodResolved)
{ // We couldn't resolve the interface statically
_ASSERTE(pfForceUseRuntimeLookup != NULL);
// Notify the caller that it should use runtime lookup
// Note that we can leave pMD incorrect, because we will use runtime lookup
*pfForceUseRuntimeLookup = TRUE;
}
}
else
{
// If we can resolve the interface exactly then do so (e.g. when doing the exact
// lookup at runtime, or when not sharing generic code).
if (pCanonMT->CanCastToInterface(thInterfaceType.GetMethodTable()))
{
pMD = pCanonMT->GetMethodDescForInterfaceMethod(thInterfaceType, pGenInterfaceMD);
if (pMD == NULL)
{
LOG((LF_JIT, LL_INFO10000, "TryResolveConstraintMethodApprox: failed to find method desc for interface method\n"));
}
}
}
}
else if (pGenInterfaceMD->IsVirtual())
{
if (pGenInterfaceMD->HasNonVtableSlot() && pGenInterfaceMD->GetMethodTable()->IsValueType())
{ // GetMethodDescForSlot would AV for this slot
// We can get here for (invalid and unverifiable) IL:
// constrained. int32
// callvirt System.Int32::GetHashCode()
pMD = pGenInterfaceMD;
}
else
{
pMD = GetMethodDescForSlot(pGenInterfaceMD->GetSlot());
}
}
else
{
// The pMD will be NULL if calling a non-virtual instance
// methods on System.Object, i.e. when these are used as a constraint.
pMD = NULL;
}
if (pMD == NULL)
{ // Fall back to VSD
return NULL;
}
//#TryResolveConstraintMethodApprox_DoNotReturnParentMethod
// Only return a method if the value type itself declares the method,
// otherwise we might get a method from Object or System.ValueType
if (!pMD->GetMethodTable()->IsValueType())
{ // Fall back to VSD
return NULL;
}
// We've resolved the method, ignoring its generic method arguments
// If the method is a generic method then go and get the instantiated descriptor
pMD = MethodDesc::FindOrCreateAssociatedMethodDesc(
pMD,
this,
FALSE /* no BoxedEntryPointStub */ ,
pInterfaceMD->GetMethodInstantiation(),
FALSE /* no allowInstParam */ );
// FindOrCreateAssociatedMethodDesc won't return an BoxedEntryPointStub.
_ASSERTE(pMD != NULL);
_ASSERTE(!pMD->IsUnboxingStub());
return pMD;
} // MethodTable::TryResolveConstraintMethodApprox
//==========================================================================================
// Make best-case effort to obtain an image name for use in an error message.
//
// This routine must expect to be called before the this object is fully loaded.
// It can return an empty if the name isn't available or the object isn't initialized
// enough to get a name, but it mustn't crash.
//==========================================================================================
LPCWSTR MethodTable::GetPathForErrorMessages()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
Module *pModule = GetModule();
if (pModule)
{
return pModule->GetPathForErrorMessages();
}
else
{
return W("");
}
}
#ifdef FEATURE_REMOTING
//==========================================================================================
// context static functions
void MethodTable::SetupContextStatics(AllocMemTracker *pamTracker, WORD wContextStaticsSize)
{
STANDARD_VM_CONTRACT;
ContextStaticsBucket* pCSInfo = (ContextStaticsBucket*) pamTracker->Track(GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(ContextStaticsBucket))));
*(GetContextStaticsBucketPtr()) = pCSInfo;
pCSInfo->m_dwContextStaticsOffset = (DWORD)-1; // Initialized lazily
pCSInfo->m_wContextStaticsSize = wContextStaticsSize;
}
#ifndef CROSSGEN_COMPILE
//==========================================================================================
DWORD MethodTable::AllocateContextStaticsOffset()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
g_IBCLogger.LogMethodTableWriteableDataWriteAccess(this);
BaseDomain* pDomain = IsDomainNeutral() ? SystemDomain::System() : GetDomain();
ContextStaticsBucket* pCSInfo = GetContextStaticsBucket();
DWORD* pOffsetSlot = &pCSInfo->m_dwContextStaticsOffset;
return pDomain->AllocateContextStaticsOffset(pOffsetSlot);
}
#endif // CROSSGEN_COMPILE
#endif // FEATURE_REMOTING
bool MethodTable::ClassRequiresUnmanagedCodeCheck()
{
LIMITED_METHOD_CONTRACT;
#ifdef FEATURE_CORECLR
return false;
#else
// all WinRT types have an imaginary [SuppressUnmanagedCodeSecurity] attribute on them
if (IsProjectedFromWinRT())
return false;
// In AppX processes, there is only one full trust AppDomain, so there is never any need to do a security
// callout on interop stubs
if (AppX::IsAppXProcess())
return false;
return GetMDImport()->GetCustomAttributeByName(GetCl(),
COR_SUPPRESS_UNMANAGED_CODE_CHECK_ATTRIBUTE_ANSI,
NULL,
NULL) == S_FALSE;
#endif // FEATURE_CORECLR
}
#endif // !DACCESS_COMPILE
BOOL MethodTable::Validate()
{
LIMITED_METHOD_CONTRACT;
ASSERT_AND_CHECK(SanityCheck());
#ifdef _DEBUG
if (m_pWriteableData == NULL)
{
_ASSERTE(IsAsyncPinType());
return TRUE;
}
DWORD dwLastVerifiedGCCnt = m_pWriteableData->m_dwLastVerifedGCCnt;
// Here we used to assert that (dwLastVerifiedGCCnt <= GCHeap::GetGCHeap()->GetGcCount()) but
// this is no longer true because with background gc. Since the purpose of having
// m_dwLastVerifedGCCnt is just to only verify the same method table once for each GC
// I am getting rid of the assert.
if (g_pConfig->FastGCStressLevel () > 1 && dwLastVerifiedGCCnt == GCHeap::GetGCHeap()->GetGcCount())
return TRUE;
#endif //_DEBUG
if (IsArray())
{
if (!IsAsyncPinType())
{
if (!SanityCheck())
{
ASSERT_AND_CHECK(!"Detected use of a corrupted OBJECTREF. Possible GC hole.");
}
}
}
else if (!IsCanonicalMethodTable())
{
// Non-canonical method tables has to have non-empty instantiation
if (GetInstantiation().IsEmpty())
{
ASSERT_AND_CHECK(!"Detected use of a corrupted OBJECTREF. Possible GC hole.");
}
}
#ifdef _DEBUG
// It is not a fatal error to fail the update the counter. We will run slower and retry next time,
// but the system will function properly.
if (EnsureWritablePagesNoThrow(m_pWriteableData, sizeof(MethodTableWriteableData)))
m_pWriteableData->m_dwLastVerifedGCCnt = GCHeap::GetGCHeap()->GetGcCount();
#endif //_DEBUG
return TRUE;
}
NOINLINE BYTE *MethodTable::GetLoaderAllocatorObjectForGC()
{
WRAPPER_NO_CONTRACT;
if (!Collectible() || ((PTR_AppDomain)GetLoaderModule()->GetDomain())->NoAccessToHandleTable())
{
return NULL;
}
BYTE * retVal = *(BYTE**)GetLoaderAllocatorObjectHandle();
return retVal;
}
#ifdef FEATURE_COMINTEROP
//==========================================================================================
BOOL MethodTable::IsWinRTRedirectedDelegate()
{
LIMITED_METHOD_DAC_CONTRACT;
if (!IsDelegate())
{
return FALSE;
}
return !!WinRTDelegateRedirector::ResolveRedirectedDelegate(this, nullptr);
}
//==========================================================================================
BOOL MethodTable::IsWinRTRedirectedInterface(TypeHandle::InteropKind interopKind)
{
LIMITED_METHOD_CONTRACT;
if (!IsInterface())
return FALSE;
if (!HasRCWPerTypeData())
{
// All redirected interfaces have per-type RCW data
return FALSE;
}
#ifdef DACCESS_COMPILE
RCWPerTypeData *pData = NULL;
#else // DACCESS_COMPILE
// We want to keep this function LIMITED_METHOD_CONTRACT so we call GetRCWPerTypeData with
// the non-throwing flag. pData can be NULL if it could not be allocated.
RCWPerTypeData *pData = GetRCWPerTypeData(false);
#endif // DACCESS_COMPILE
DWORD dwFlags = (pData != NULL ? pData->m_dwFlags : 0);
if ((dwFlags & RCWPerTypeData::InterfaceFlagsInited) == 0)
{
dwFlags = RCWPerTypeData::InterfaceFlagsInited;
if (WinRTInterfaceRedirector::ResolveRedirectedInterface(this, NULL))
{
dwFlags |= RCWPerTypeData::IsRedirectedInterface;
}
else if (HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__ICOLLECTIONGENERIC)) ||
HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__IREADONLYCOLLECTIONGENERIC)) ||
this == MscorlibBinder::GetExistingClass(CLASS__ICOLLECTION))
{
dwFlags |= RCWPerTypeData::IsICollectionGeneric;
}
if (pData != NULL)
{
FastInterlockOr(&pData->m_dwFlags, dwFlags);
}
}
if ((dwFlags & RCWPerTypeData::IsRedirectedInterface) != 0)
return TRUE;
if (interopKind == TypeHandle::Interop_ManagedToNative)
{
// ICollection<T> is redirected in the managed->WinRT direction (i.e. we have stubs
// that implement ICollection<T> methods in terms of IVector/IMap), but it is not
// treated specially in the WinRT->managed direction (we don't build a WinRT vtable
// for a class that only implements ICollection<T>). IReadOnlyCollection<T> is
// treated similarly.
if ((dwFlags & RCWPerTypeData::IsICollectionGeneric) != 0)
return TRUE;
}
return FALSE;
}
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_READYTORUN_COMPILER
static BOOL ComputeIsLayoutFixedInCurrentVersionBubble(MethodTable * pMT)
{
STANDARD_VM_CONTRACT;
// Primitive types and enums have fixed layout
if (pMT->IsTruePrimitive() || pMT->IsEnum())
return TRUE;
if (!pMT->GetModule()->IsInCurrentVersionBubble())
{
if (!pMT->IsValueType())
{
// Eventually, we may respect the non-versionable attribute for reference types too. For now, we are going
// to play is safe and ignore it.
return FALSE;
}
// Valuetypes with non-versionable attribute are candidates for fixed layout. Reject the rest.
if (pMT->GetModule()->GetMDImport()->GetCustomAttributeByName(pMT->GetCl(),
NONVERSIONABLE_TYPE, NULL, NULL) != S_OK)
{
return FALSE;
}
}
// If the above condition passed, check that all instance fields have fixed layout as well. In particular,
// it is important for generic types with non-versionable layout (e.g. Nullable<T>)
ApproxFieldDescIterator fieldIterator(pMT, ApproxFieldDescIterator::INSTANCE_FIELDS);
for (FieldDesc *pFD = fieldIterator.Next(); pFD != NULL; pFD = fieldIterator.Next())
{
if (pFD->GetFieldType() != ELEMENT_TYPE_VALUETYPE)
continue;
MethodTable * pFieldMT = pFD->GetApproxFieldTypeHandleThrowing().AsMethodTable();
if (!pFieldMT->IsLayoutFixedInCurrentVersionBubble())
return FALSE;
}
return TRUE;
}
//
// Is field layout in this type fixed within the current version bubble?
// This check does not take the inheritance chain into account.
//
BOOL MethodTable::IsLayoutFixedInCurrentVersionBubble()
{
STANDARD_VM_CONTRACT;
const MethodTableWriteableData * pWriteableData = GetWriteableData();
if (!(pWriteableData->m_dwFlags & MethodTableWriteableData::enum_flag_NGEN_IsLayoutFixedComputed))
{
MethodTableWriteableData * pWriteableDataForWrite = GetWriteableDataForWrite();
if (ComputeIsLayoutFixedInCurrentVersionBubble(this))
*EnsureWritablePages(&pWriteableDataForWrite->m_dwFlags) |= MethodTableWriteableData::enum_flag_NGEN_IsLayoutFixed;
*EnsureWritablePages(&pWriteableDataForWrite->m_dwFlags) |= MethodTableWriteableData::enum_flag_NGEN_IsLayoutFixedComputed;
}
return (pWriteableData->m_dwFlags & MethodTableWriteableData::enum_flag_NGEN_IsLayoutFixed) != 0;
}
//
// Is field layout of the inheritance chain fixed within the current version bubble?
//
BOOL MethodTable::IsInheritanceChainLayoutFixedInCurrentVersionBubble()
{
STANDARD_VM_CONTRACT;
// This method is not expected to be called for value types
_ASSERTE(!IsValueType());
MethodTable * pMT = this;
while ((pMT != g_pObjectClass) && (pMT != NULL))
{
if (!pMT->IsLayoutFixedInCurrentVersionBubble())
return FALSE;
pMT = pMT->GetParentMethodTable();
}
return TRUE;
}
#endif // FEATURE_READYTORUN_COMPILER
| mit |
AMCcoin/AmericanCoin | src/qt/sendcoinsdialog.cpp | 1076 | 8664 | #include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include <QMessageBox>
#include <QLocale>
#include <QTextDocument>
#include <QScrollBar>
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_WS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
fNewRecipientAllowed = true;
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
if(model && model->getOptionsModel())
{
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
QList<SendCoinsRecipient> recipients;
bool valid = true;
if(!model)
return;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recepient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
delete ui->entries->takeAt(0)->widget();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
QCoreApplication::instance()->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
setupTabChain(0);
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
bool SendCoinsDialog::handleURI(const QString &uri)
{
SendCoinsRecipient rv;
// URI has to be valid
if (GUIUtil::parseBitcoinURI(uri, &rv))
{
pasteEntry(rv);
return true;
}
return false;
}
void SendCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(!model || !model->getOptionsModel())
return;
int unit = model->getOptionsModel()->getDisplayUnit();
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
}
void SendCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update labelBalance with the current balance and the current unit
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));
}
}
| mit |
jakesays/coreclr | src/md/compiler/assemblymd.cpp | 61 | 28485 | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//*****************************************************************************
// AssemblyMD.cpp
//
//
// Implementation for the assembly meta data import code (code:IMetaDataAssemblyImport).
//
//*****************************************************************************
#include "stdafx.h"
#include "regmeta.h"
#include "mdutil.h"
#include "rwutil.h"
#include "mdlog.h"
#include "importhelper.h"
#include <strongname.h>
#ifdef _MSC_VER
#pragma warning(disable: 4102)
#endif
//*******************************************************************************
// Get the properties for the given Assembly token.
//*******************************************************************************
STDMETHODIMP RegMeta::GetAssemblyProps( // S_OK or error.
mdAssembly mda, // [IN] The Assembly for which to get the properties.
const void **ppbPublicKey, // [OUT] Pointer to the public key.
ULONG *pcbPublicKey, // [OUT] Count of bytes in the public key.
ULONG *pulHashAlgId, // [OUT] Hash Algorithm.
__out_ecount_part_opt(cchName, *pchName) LPWSTR szName, // [OUT] Buffer to fill with name.
ULONG cchName, // [IN] Size of buffer in wide chars.
ULONG *pchName, // [OUT] Actual # of wide chars in name.
ASSEMBLYMETADATA *pMetaData, // [OUT] Assembly MetaData.
DWORD *pdwAssemblyFlags) // [OUT] Flags.
{
HRESULT hr = S_OK;
BEGIN_ENTRYPOINT_NOTHROW;
AssemblyRec *pRecord;
CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd);
LOG((LOGMD, "RegMeta::GetAssemblyProps(0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x)\n",
mda, ppbPublicKey, pcbPublicKey, pulHashAlgId, szName, cchName, pchName, pMetaData,
pdwAssemblyFlags));
START_MD_PERF();
LOCKREAD();
_ASSERTE(TypeFromToken(mda) == mdtAssembly && RidFromToken(mda));
IfFailGo(pMiniMd->GetAssemblyRecord(RidFromToken(mda), &pRecord));
if (ppbPublicKey != NULL)
{
IfFailGo(pMiniMd->getPublicKeyOfAssembly(pRecord, (const BYTE **)ppbPublicKey, pcbPublicKey));
}
if (pulHashAlgId)
*pulHashAlgId = pMiniMd->getHashAlgIdOfAssembly(pRecord);
if (pMetaData)
{
pMetaData->usMajorVersion = pMiniMd->getMajorVersionOfAssembly(pRecord);
pMetaData->usMinorVersion = pMiniMd->getMinorVersionOfAssembly(pRecord);
pMetaData->usBuildNumber = pMiniMd->getBuildNumberOfAssembly(pRecord);
pMetaData->usRevisionNumber = pMiniMd->getRevisionNumberOfAssembly(pRecord);
IfFailGo(pMiniMd->getLocaleOfAssembly(pRecord, pMetaData->szLocale,
pMetaData->cbLocale, &pMetaData->cbLocale));
pMetaData->ulProcessor = 0;
pMetaData->ulOS = 0;
}
if (pdwAssemblyFlags)
{
*pdwAssemblyFlags = pMiniMd->getFlagsOfAssembly(pRecord);
#ifdef FEATURE_WINDOWSPHONE
// Turn on the afPublicKey if PublicKey blob is not empty
DWORD cbPublicKey;
const BYTE *pbPublicKey;
IfFailGo(pMiniMd->getPublicKeyOfAssembly(pRecord, &pbPublicKey, &cbPublicKey));
if (cbPublicKey != 0)
*pdwAssemblyFlags |= afPublicKey;
#else
if (ppbPublicKey)
{
if (pcbPublicKey && *pcbPublicKey)
*pdwAssemblyFlags |= afPublicKey;
}
else
{
#ifdef _DEBUG
// Assert that afPublicKey is set if PublicKey blob is not empty
DWORD cbPublicKey;
const BYTE *pbPublicKey;
IfFailGo(pMiniMd->getPublicKeyOfAssembly(pRecord, &pbPublicKey, &cbPublicKey));
bool hasPublicKey = cbPublicKey != 0;
bool hasPublicKeyFlag = ( *pdwAssemblyFlags & afPublicKey ) != 0;
_ASSERTE( hasPublicKey == hasPublicKeyFlag );
#endif
}
#endif // FEATURE_WINDOWSPHONE
}
// This call has to be last to set 'hr', so CLDB_S_TRUNCATION is not rewritten with S_OK
if (szName || pchName)
IfFailGo(pMiniMd->getNameOfAssembly(pRecord, szName, cchName, pchName));
ErrExit:
STOP_MD_PERF(GetAssemblyProps);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::GetAssemblyProps
//*******************************************************************************
// Get the properties for the given AssemblyRef token.
//*******************************************************************************
STDMETHODIMP RegMeta::GetAssemblyRefProps( // S_OK or error.
mdAssemblyRef mdar, // [IN] The AssemblyRef for which to get the properties.
const void **ppbPublicKeyOrToken, // [OUT] Pointer to the public key or token.
ULONG *pcbPublicKeyOrToken, // [OUT] Count of bytes in the public key or token.
__out_ecount_part_opt(cchName, *pchName) LPWSTR szName, // [OUT] Buffer to fill with name.
ULONG cchName, // [IN] Size of buffer in wide chars.
ULONG *pchName, // [OUT] Actual # of wide chars in name.
ASSEMBLYMETADATA *pMetaData, // [OUT] Assembly MetaData.
const void **ppbHashValue, // [OUT] Hash blob.
ULONG *pcbHashValue, // [OUT] Count of bytes in the hash blob.
DWORD *pdwAssemblyRefFlags) // [OUT] Flags.
{
HRESULT hr = S_OK;
BEGIN_ENTRYPOINT_NOTHROW;
AssemblyRefRec *pRecord;
CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd);
LOG((LOGMD, "RegMeta::GetAssemblyRefProps(0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x)\n",
mdar, ppbPublicKeyOrToken, pcbPublicKeyOrToken, szName, cchName,
pchName, pMetaData, ppbHashValue, pdwAssemblyRefFlags));
START_MD_PERF();
LOCKREAD();
_ASSERTE(TypeFromToken(mdar) == mdtAssemblyRef && RidFromToken(mdar));
IfFailGo(pMiniMd->GetAssemblyRefRecord(RidFromToken(mdar), &pRecord));
if (ppbPublicKeyOrToken != NULL)
{
IfFailGo(pMiniMd->getPublicKeyOrTokenOfAssemblyRef(pRecord, (const BYTE **)ppbPublicKeyOrToken, pcbPublicKeyOrToken));
}
if (pMetaData)
{
pMetaData->usMajorVersion = pMiniMd->getMajorVersionOfAssemblyRef(pRecord);
pMetaData->usMinorVersion = pMiniMd->getMinorVersionOfAssemblyRef(pRecord);
pMetaData->usBuildNumber = pMiniMd->getBuildNumberOfAssemblyRef(pRecord);
pMetaData->usRevisionNumber = pMiniMd->getRevisionNumberOfAssemblyRef(pRecord);
IfFailGo(pMiniMd->getLocaleOfAssemblyRef(pRecord, pMetaData->szLocale,
pMetaData->cbLocale, &pMetaData->cbLocale));
pMetaData->ulProcessor = 0;
pMetaData->ulOS = 0;
}
if (ppbHashValue != NULL)
{
IfFailGo(pMiniMd->getHashValueOfAssemblyRef(pRecord, (const BYTE **)ppbHashValue, pcbHashValue));
}
if (pdwAssemblyRefFlags)
*pdwAssemblyRefFlags = pMiniMd->getFlagsOfAssemblyRef(pRecord);
// This call has to be last to set 'hr', so CLDB_S_TRUNCATION is not rewritten with S_OK
if (szName || pchName)
IfFailGo(pMiniMd->getNameOfAssemblyRef(pRecord, szName, cchName, pchName));
ErrExit:
STOP_MD_PERF(GetAssemblyRefProps);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::GetAssemblyRefProps
//*******************************************************************************
// Get the properties for the given File token.
//*******************************************************************************
STDMETHODIMP RegMeta::GetFileProps( // S_OK or error.
mdFile mdf, // [IN] The File for which to get the properties.
__out_ecount_part_opt(cchName, *pchName) LPWSTR szName, // [OUT] Buffer to fill with name.
ULONG cchName, // [IN] Size of buffer in wide chars.
ULONG *pchName, // [OUT] Actual # of wide chars in name.
const void **ppbHashValue, // [OUT] Pointer to the Hash Value Blob.
ULONG *pcbHashValue, // [OUT] Count of bytes in the Hash Value Blob.
DWORD *pdwFileFlags) // [OUT] Flags.
{
HRESULT hr = S_OK;
BEGIN_ENTRYPOINT_NOTHROW;
FileRec *pRecord;
CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd);
LOG((LOGMD, "RegMeta::GetFileProps(%#08x, %#08x, %#08x, %#08x, %#08x, %#08x, %#08x)\n",
mdf, szName, cchName, pchName, ppbHashValue, pcbHashValue, pdwFileFlags));
START_MD_PERF();
LOCKREAD();
_ASSERTE(TypeFromToken(mdf) == mdtFile && RidFromToken(mdf));
IfFailGo(pMiniMd->GetFileRecord(RidFromToken(mdf), &pRecord));
if (ppbHashValue != NULL)
{
IfFailGo(pMiniMd->getHashValueOfFile(pRecord, (const BYTE **)ppbHashValue, pcbHashValue));
}
if (pdwFileFlags != NULL)
*pdwFileFlags = pMiniMd->getFlagsOfFile(pRecord);
// This call has to be last to set 'hr', so CLDB_S_TRUNCATION is not rewritten with S_OK
if ((szName != NULL) || (pchName != NULL))
{
IfFailGo(pMiniMd->getNameOfFile(pRecord, szName, cchName, pchName));
}
ErrExit:
STOP_MD_PERF(GetFileProps);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::GetFileProps
//*******************************************************************************
// Get the properties for the given ExportedType token.
//*******************************************************************************
STDMETHODIMP RegMeta::GetExportedTypeProps( // S_OK or error.
mdExportedType mdct, // [IN] The ExportedType for which to get the properties.
__out_ecount_part_opt(cchName, *pchName) LPWSTR szName, // [OUT] Buffer to fill with name.
ULONG cchName, // [IN] Size of buffer in wide chars.
ULONG *pchName, // [OUT] Actual # of wide chars in name.
mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef that provides the ExportedType.
mdTypeDef *ptkTypeDef, // [OUT] TypeDef token within the file.
DWORD *pdwExportedTypeFlags) // [OUT] Flags.
{
HRESULT hr = S_OK; // A result.
BEGIN_ENTRYPOINT_NOTHROW;
ExportedTypeRec *pRecord; // The exported type.
CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd);
int bTruncation=0; // Was there name truncation?
LOG((LOGMD, "RegMeta::GetExportedTypeProps(%#08x, %#08x, %#08x, %#08x, %#08x, %#08x, %#08x)\n",
mdct, szName, cchName, pchName,
ptkImplementation, ptkTypeDef, pdwExportedTypeFlags));
START_MD_PERF();
LOCKREAD();
_ASSERTE(TypeFromToken(mdct) == mdtExportedType && RidFromToken(mdct));
IfFailGo(pMiniMd->GetExportedTypeRecord(RidFromToken(mdct), &pRecord));
if (szName || pchName)
{
LPCSTR szTypeNamespace;
LPCSTR szTypeName;
IfFailGo(pMiniMd->getTypeNamespaceOfExportedType(pRecord, &szTypeNamespace));
PREFIX_ASSUME(szTypeNamespace != NULL);
MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzTypeNamespace, szTypeNamespace);
IfNullGo(wzTypeNamespace);
IfFailGo(pMiniMd->getTypeNameOfExportedType(pRecord, &szTypeName));
_ASSERTE(*szTypeName);
MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzTypeName, szTypeName);
IfNullGo(wzTypeName);
if (szName)
bTruncation = ! (ns::MakePath(szName, cchName, wzTypeNamespace, wzTypeName));
if (pchName)
{
if (bTruncation || !szName)
*pchName = ns::GetFullLength(wzTypeNamespace, wzTypeName);
else
*pchName = (ULONG)(wcslen(szName) + 1);
}
}
if (ptkImplementation)
*ptkImplementation = pMiniMd->getImplementationOfExportedType(pRecord);
if (ptkTypeDef)
*ptkTypeDef = pMiniMd->getTypeDefIdOfExportedType(pRecord);
if (pdwExportedTypeFlags)
*pdwExportedTypeFlags = pMiniMd->getFlagsOfExportedType(pRecord);
if (bTruncation && hr == S_OK)
{
if ((szName != NULL) && (cchName > 0))
{ // null-terminate the truncated output string
szName[cchName - 1] = W('\0');
}
hr = CLDB_S_TRUNCATION;
}
ErrExit:
STOP_MD_PERF(GetExportedTypeProps);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::GetExportedTypeProps
//*******************************************************************************
// Get the properties for the given Resource token.
//*******************************************************************************
STDMETHODIMP RegMeta::GetManifestResourceProps( // S_OK or error.
mdManifestResource mdmr, // [IN] The ManifestResource for which to get the properties.
__out_ecount_part_opt(cchName, *pchName)LPWSTR szName, // [OUT] Buffer to fill with name.
ULONG cchName, // [IN] Size of buffer in wide chars.
ULONG *pchName, // [OUT] Actual # of wide chars in name.
mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef that provides the ExportedType.
DWORD *pdwOffset, // [OUT] Offset to the beginning of the resource within the file.
DWORD *pdwResourceFlags) // [OUT] Flags.
{
HRESULT hr = S_OK;
BEGIN_ENTRYPOINT_NOTHROW;
ManifestResourceRec *pRecord;
CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd);
LOG((LOGMD, "RegMeta::GetManifestResourceProps("
"%#08x, %#08x, %#08x, %#08x, %#08x, %#08x, %#08x)\n",
mdmr, szName, cchName, pchName,
ptkImplementation, pdwOffset,
pdwResourceFlags));
START_MD_PERF();
LOCKREAD();
_ASSERTE(TypeFromToken(mdmr) == mdtManifestResource && RidFromToken(mdmr));
IfFailGo(pMiniMd->GetManifestResourceRecord(RidFromToken(mdmr), &pRecord));
if (ptkImplementation)
*ptkImplementation = pMiniMd->getImplementationOfManifestResource(pRecord);
if (pdwOffset)
*pdwOffset = pMiniMd->getOffsetOfManifestResource(pRecord);
if (pdwResourceFlags)
*pdwResourceFlags = pMiniMd->getFlagsOfManifestResource(pRecord);
// This call has to be last to set 'hr', so CLDB_S_TRUNCATION is not rewritten with S_OK
if (szName || pchName)
IfFailGo(pMiniMd->getNameOfManifestResource(pRecord, szName, cchName, pchName));
ErrExit:
STOP_MD_PERF(GetManifestResourceProps);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::GetManifestResourceProps
//*******************************************************************************
// Enumerating through all of the AssemblyRefs.
//*******************************************************************************
STDMETHODIMP RegMeta::EnumAssemblyRefs( // S_OK or error
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdAssemblyRef rAssemblyRefs[], // [OUT] Put AssemblyRefs here.
ULONG cMax, // [IN] Max AssemblyRefs to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
HRESULT hr = NOERROR;
BEGIN_ENTRYPOINT_NOTHROW;
HENUMInternal **ppmdEnum = reinterpret_cast<HENUMInternal **> (phEnum);
HENUMInternal *pEnum;
LOG((LOGMD, "MD RegMeta::EnumAssemblyRefs(%#08x, %#08x, %#08x, %#08x)\n",
phEnum, rAssemblyRefs, cMax, pcTokens));
START_MD_PERF();
LOCKREAD();
if (*ppmdEnum == 0)
{
// instantiate a new ENUM.
CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd);
// create the enumerator.
IfFailGo(HENUMInternal::CreateSimpleEnum(
mdtAssemblyRef,
1,
pMiniMd->getCountAssemblyRefs() + 1,
&pEnum) );
// set the output parameter.
*ppmdEnum = pEnum;
}
else
pEnum = *ppmdEnum;
// we can only fill the minimum of what the caller asked for or what we have left.
IfFailGo(HENUMInternal::EnumWithCount(pEnum, cMax, rAssemblyRefs, pcTokens));
ErrExit:
HENUMInternal::DestroyEnumIfEmpty(ppmdEnum);
STOP_MD_PERF(EnumAssemblyRefs);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::EnumAssemblyRefs
//*******************************************************************************
// Enumerating through all of the Files.
//*******************************************************************************
STDMETHODIMP RegMeta::EnumFiles( // S_OK or error
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdFile rFiles[], // [OUT] Put Files here.
ULONG cMax, // [IN] Max Files to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
HRESULT hr = NOERROR;
BEGIN_ENTRYPOINT_NOTHROW;
HENUMInternal **ppmdEnum = reinterpret_cast<HENUMInternal **> (phEnum);
HENUMInternal *pEnum;
LOG((LOGMD, "MD RegMeta::EnumFiles(%#08x, %#08x, %#08x, %#08x)\n",
phEnum, rFiles, cMax, pcTokens));
START_MD_PERF();
LOCKREAD();
if (*ppmdEnum == 0)
{
// instantiate a new ENUM.
CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd);
// create the enumerator.
IfFailGo(HENUMInternal::CreateSimpleEnum(
mdtFile,
1,
pMiniMd->getCountFiles() + 1,
&pEnum) );
// set the output parameter.
*ppmdEnum = pEnum;
}
else
pEnum = *ppmdEnum;
// we can only fill the minimum of what the caller asked for or what we have left.
IfFailGo(HENUMInternal::EnumWithCount(pEnum, cMax, rFiles, pcTokens));
ErrExit:
HENUMInternal::DestroyEnumIfEmpty(ppmdEnum);
STOP_MD_PERF(EnumFiles);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::EnumFiles
//*******************************************************************************
// Enumerating through all of the ExportedTypes.
//*******************************************************************************
STDMETHODIMP RegMeta::EnumExportedTypes( // S_OK or error
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdExportedType rExportedTypes[], // [OUT] Put ExportedTypes here.
ULONG cMax, // [IN] Max ExportedTypes to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
HRESULT hr = NOERROR;
BEGIN_ENTRYPOINT_NOTHROW;
HENUMInternal **ppmdEnum = reinterpret_cast<HENUMInternal **> (phEnum);
HENUMInternal *pEnum;
LOG((LOGMD, "MD RegMeta::EnumExportedTypes(%#08x, %#08x, %#08x, %#08x)\n",
phEnum, rExportedTypes, cMax, pcTokens));
START_MD_PERF();
LOCKREAD();
if (*ppmdEnum == 0)
{
// instantiate a new ENUM.
CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd);
if (pMiniMd->HasDelete() &&
((m_OptionValue.m_ImportOption & MDImportOptionAllExportedTypes) == 0))
{
IfFailGo( HENUMInternal::CreateDynamicArrayEnum( mdtExportedType, &pEnum) );
// add all Types to the dynamic array if name is not _Delete
for (ULONG index = 1; index <= pMiniMd->getCountExportedTypes(); index ++ )
{
ExportedTypeRec *pRec;
IfFailGo(pMiniMd->GetExportedTypeRecord(index, &pRec));
LPCSTR szTypeName;
IfFailGo(pMiniMd->getTypeNameOfExportedType(pRec, &szTypeName));
if (IsDeletedName(szTypeName))
{
continue;
}
IfFailGo( HENUMInternal::AddElementToEnum(pEnum, TokenFromRid(index, mdtExportedType) ) );
}
}
else
{
// create the enumerator.
IfFailGo(HENUMInternal::CreateSimpleEnum(
mdtExportedType,
1,
pMiniMd->getCountExportedTypes() + 1,
&pEnum) );
}
// set the output parameter.
*ppmdEnum = pEnum;
}
else
pEnum = *ppmdEnum;
// we can only fill the minimum of what the caller asked for or what we have left.
IfFailGo(HENUMInternal::EnumWithCount(pEnum, cMax, rExportedTypes, pcTokens));
ErrExit:
HENUMInternal::DestroyEnumIfEmpty(ppmdEnum);
STOP_MD_PERF(EnumExportedTypes);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::EnumExportedTypes
//*******************************************************************************
// Enumerating through all of the Resources.
//*******************************************************************************
STDMETHODIMP RegMeta::EnumManifestResources( // S_OK or error
HCORENUM *phEnum, // [IN|OUT] Pointer to the enum.
mdManifestResource rManifestResources[], // [OUT] Put ManifestResources here.
ULONG cMax, // [IN] Max Resources to put.
ULONG *pcTokens) // [OUT] Put # put here.
{
HRESULT hr = NOERROR;
BEGIN_ENTRYPOINT_NOTHROW;
HENUMInternal **ppmdEnum = reinterpret_cast<HENUMInternal **> (phEnum);
HENUMInternal *pEnum;
LOG((LOGMD, "MD RegMeta::EnumManifestResources(%#08x, %#08x, %#08x, %#08x)\n",
phEnum, rManifestResources, cMax, pcTokens));
START_MD_PERF();
LOCKREAD();
if (*ppmdEnum == 0)
{
// instantiate a new ENUM.
CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd);
// create the enumerator.
IfFailGo(HENUMInternal::CreateSimpleEnum(
mdtManifestResource,
1,
pMiniMd->getCountManifestResources() + 1,
&pEnum) );
// set the output parameter.
*ppmdEnum = pEnum;
}
else
pEnum = *ppmdEnum;
// we can only fill the minimum of what the caller asked for or what we have left.
IfFailGo(HENUMInternal::EnumWithCount(pEnum, cMax, rManifestResources, pcTokens));
ErrExit:
HENUMInternal::DestroyEnumIfEmpty(ppmdEnum);
STOP_MD_PERF(EnumManifestResources);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::EnumManifestResources
//*******************************************************************************
// Get the Assembly token for the given scope..
//*******************************************************************************
STDMETHODIMP RegMeta::GetAssemblyFromScope( // S_OK or error
mdAssembly *ptkAssembly) // [OUT] Put token here.
{
HRESULT hr = NOERROR;
CMiniMdRW *pMiniMd = NULL;
BEGIN_ENTRYPOINT_NOTHROW;
LOG((LOGMD, "MD RegMeta::GetAssemblyFromScope(%#08x)\n", ptkAssembly));
START_MD_PERF();
LOCKREAD();
_ASSERTE(ptkAssembly);
pMiniMd = &(m_pStgdb->m_MiniMd);
if (pMiniMd->getCountAssemblys())
{
*ptkAssembly = TokenFromRid(1, mdtAssembly);
}
else
{
IfFailGo( CLDB_E_RECORD_NOTFOUND );
}
ErrExit:
STOP_MD_PERF(GetAssemblyFromScope);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::GetAssemblyFromScope
//*******************************************************************************
// Find the ExportedType given the name.
//*******************************************************************************
STDMETHODIMP RegMeta::FindExportedTypeByName( // S_OK or error
LPCWSTR szName, // [IN] Name of the ExportedType.
mdExportedType tkEnclosingType, // [IN] Enclosing ExportedType.
mdExportedType *ptkExportedType) // [OUT] Put the ExportedType token here.
{
HRESULT hr = S_OK; // A result.
BEGIN_ENTRYPOINT_NOTHROW;
CMiniMdRW *pMiniMd = NULL;
LPSTR szNameUTF8 = NULL;
LOG((LOGMD, "MD RegMeta::FindExportedTypeByName(%S, %#08x, %#08x)\n",
MDSTR(szName), tkEnclosingType, ptkExportedType));
START_MD_PERF();
LOCKREAD();
// Validate name for prefix.
if (!szName)
IfFailGo(E_INVALIDARG);
_ASSERTE(szName && ptkExportedType);
pMiniMd = &(m_pStgdb->m_MiniMd);
UTF8STR(szName, szNameUTF8);
LPCSTR szTypeName;
LPCSTR szTypeNamespace;
ns::SplitInline(szNameUTF8, szTypeNamespace, szTypeName);
IfFailGo(ImportHelper::FindExportedType(pMiniMd,
szTypeNamespace,
szTypeName,
tkEnclosingType,
ptkExportedType));
ErrExit:
STOP_MD_PERF(FindExportedTypeByName);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::FindExportedTypeByName
//*******************************************************************************
// Find the ManifestResource given the name.
//*******************************************************************************
STDMETHODIMP RegMeta::FindManifestResourceByName( // S_OK or error
LPCWSTR szName, // [IN] Name of the ManifestResource.
mdManifestResource *ptkManifestResource) // [OUT] Put the ManifestResource token here.
{
HRESULT hr = S_OK;
BEGIN_ENTRYPOINT_NOTHROW;
LPCUTF8 szNameTmp = NULL;
CMiniMdRW *pMiniMd = NULL;
LOG((LOGMD, "MD RegMeta::FindManifestResourceByName(%S, %#08x)\n",
MDSTR(szName), ptkManifestResource));
START_MD_PERF();
LOCKREAD();
// Validate name for prefix.
if (!szName)
IfFailGo(E_INVALIDARG);
_ASSERTE(szName && ptkManifestResource);
ManifestResourceRec *pRecord;
ULONG cRecords; // Count of records.
LPUTF8 szUTF8Name; // UTF8 version of the name passed in.
ULONG i;
pMiniMd = &(m_pStgdb->m_MiniMd);
*ptkManifestResource = mdManifestResourceNil;
cRecords = pMiniMd->getCountManifestResources();
UTF8STR(szName, szUTF8Name);
// Search for the TypeRef.
for (i = 1; i <= cRecords; i++)
{
IfFailGo(pMiniMd->GetManifestResourceRecord(i, &pRecord));
IfFailGo(pMiniMd->getNameOfManifestResource(pRecord, &szNameTmp));
if (! strcmp(szUTF8Name, szNameTmp))
{
*ptkManifestResource = TokenFromRid(i, mdtManifestResource);
goto ErrExit;
}
}
IfFailGo( CLDB_E_RECORD_NOTFOUND );
ErrExit:
STOP_MD_PERF(FindManifestResourceByName);
END_ENTRYPOINT_NOTHROW;
return hr;
} // RegMeta::FindManifestResourceByName
extern HRESULT STDMETHODCALLTYPE
GetAssembliesByName(LPCWSTR szAppBase,
LPCWSTR szPrivateBin,
LPCWSTR szAssemblyName,
IUnknown *ppIUnk[],
ULONG cMax,
ULONG *pcAssemblies);
//*******************************************************************************
// Used to find assemblies either in Fusion cache or on disk at build time.
//*******************************************************************************
STDMETHODIMP RegMeta::FindAssembliesByName( // S_OK or error
LPCWSTR szAppBase, // [IN] optional - can be NULL
LPCWSTR szPrivateBin, // [IN] optional - can be NULL
LPCWSTR szAssemblyName, // [IN] required - this is the assembly you are requesting
IUnknown *ppIUnk[], // [OUT] put IMetaDataAssemblyImport pointers here
ULONG cMax, // [IN] The max number to put
ULONG *pcAssemblies) // [OUT] The number of assemblies returned.
{
#ifdef FEATURE_METADATA_IN_VM
HRESULT hr = S_OK;
BEGIN_ENTRYPOINT_NOTHROW;
LOG((LOGMD, "RegMeta::FindAssembliesByName(0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x)\n",
szAppBase, szPrivateBin, szAssemblyName, ppIUnk, cMax, pcAssemblies));
START_MD_PERF();
// No need to lock this function. It is going through fusion to find the matching Assemblies by name
IfFailGo(GetAssembliesByName(szAppBase, szPrivateBin,
szAssemblyName, ppIUnk, cMax, pcAssemblies));
ErrExit:
STOP_MD_PERF(FindAssembliesByName);
END_ENTRYPOINT_NOTHROW;
return hr;
#else //!FEATURE_METADATA_IN_VM
// Calls to fusion are not suported outside VM
return E_NOTIMPL;
#endif //!FEATURE_METADATA_IN_VM
} // RegMeta::FindAssembliesByName
| mit |
stormleoxia/coreclr | src/pal/tests/palsuite/file_io/GetFileTime/test3/GetFileTime.c | 62 | 3892 | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*=====================================================================
**
** Source: GetFileTime.c
**
** Purpose: Tests the PAL implementation of the GetFileTime function
** Test to see that creation time is changed when two different files
** are created.
**
** Depends:
** CreateFile
** ReadFile
** CloseHandle
**
**
**===================================================================*/
#include <palsuite.h>
int __cdecl main(int argc, char **argv)
{
FILETIME Creation;
HANDLE TheFileHandle, SecondFileHandle;
ULONG64 FirstCreationTime, SecondCreationTime;
BOOL result;
if (0 != PAL_Initialize(argc,argv))
{
return FAIL;
}
/* Open the file to get a HANDLE */
TheFileHandle =
CreateFile(
"the_file",
GENERIC_READ,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(TheFileHandle == INVALID_HANDLE_VALUE)
{
Fail("ERROR: Failed to open the file. The error number "
"returned was %d.",GetLastError());
}
/* Get the Creation time of the File */
if(GetFileTime(TheFileHandle,&Creation,NULL,NULL)==0)
{
Fail("ERROR: GetFileTime returned 0, indicating failure. "
"Two of the params were NULL in this case, did they "
"cause the probleM?");
}
/* Convert the structure to an ULONG64 */
FirstCreationTime = ( (((ULONG64)Creation.dwHighDateTime)<<32) |
((ULONG64)Creation.dwLowDateTime));
/* Close the File, so the changes are recorded */
result = CloseHandle(TheFileHandle);
if(result == 0)
{
Fail("ERROR: Failed to close the file handle.");
}
/* Sleep for 3 seconds, this will ensure the time changes */
Sleep(3000);
/* Open another file */
SecondFileHandle =
CreateFile("the_other_file", /* file name */
GENERIC_READ, /* access mode */
0, /* share mode */
NULL, /* SD */
CREATE_ALWAYS, /* how to create */
FILE_ATTRIBUTE_NORMAL, /* file attributes */
NULL /* handle to template file */
);
if(SecondFileHandle == INVALID_HANDLE_VALUE)
{
Fail("ERROR: Failed to open the second file. The error number "
"returned was %d.",GetLastError());
}
/* Call GetFileTime again */
if(GetFileTime(SecondFileHandle,&Creation,NULL,NULL) == 0)
{
Fail("ERROR: GetFileTime returned 0, indicating failure. "
"Perhaps the NULLs in the function broke it?");
}
/* Close the File*/
result = CloseHandle(SecondFileHandle);
if(result == 0)
{
Fail("ERROR: Failed to close the file handle.");
}
/* Store the results in a ULONG64 */
SecondCreationTime = ( (((ULONG64)Creation.dwHighDateTime)<<32) |
((ULONG64)Creation.dwLowDateTime));
/* Now -- to test. We ensure that the FirstCreationTime is
less than the SecondCreationTime
*/
if(FirstCreationTime >= SecondCreationTime)
{
Fail("ERROR: The creation time of the two files should be "
"different. The first file should have a creation "
"time less than the second.");
}
PAL_Terminate();
return PASS;
}
| mit |
keesdewit82/LasVegasCoin | src/crypto/keccak.c | 1087 | 54977 | /* $Id: keccak.c 259 2011-07-19 22:11:27Z tp $ */
/*
* Keccak implementation.
*
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* 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.
*
* ===========================(LICENSE END)=============================
*
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
*/
#include <stddef.h>
#include <string.h>
#include "sph_keccak.h"
#ifdef __cplusplus
extern "C"{
#endif
/*
* Parameters:
*
* SPH_KECCAK_64 use a 64-bit type
* SPH_KECCAK_UNROLL number of loops to unroll (0/undef for full unroll)
* SPH_KECCAK_INTERLEAVE use bit-interleaving (32-bit type only)
* SPH_KECCAK_NOCOPY do not copy the state into local variables
*
* If there is no usable 64-bit type, the code automatically switches
* back to the 32-bit implementation.
*
* Some tests on an Intel Core2 Q6600 (both 64-bit and 32-bit, 32 kB L1
* code cache), a PowerPC (G3, 32 kB L1 code cache), an ARM920T core
* (16 kB L1 code cache), and a small MIPS-compatible CPU (Broadcom BCM3302,
* 8 kB L1 code cache), seem to show that the following are optimal:
*
* -- x86, 64-bit: use the 64-bit implementation, unroll 8 rounds,
* do not copy the state; unrolling 2, 6 or all rounds also provides
* near-optimal performance.
* -- x86, 32-bit: use the 32-bit implementation, unroll 6 rounds,
* interleave, do not copy the state. Unrolling 1, 2, 4 or 8 rounds
* also provides near-optimal performance.
* -- PowerPC: use the 64-bit implementation, unroll 8 rounds,
* copy the state. Unrolling 4 or 6 rounds is near-optimal.
* -- ARM: use the 64-bit implementation, unroll 2 or 4 rounds,
* copy the state.
* -- MIPS: use the 64-bit implementation, unroll 2 rounds, copy
* the state. Unrolling only 1 round is also near-optimal.
*
* Also, interleaving does not always yield actual improvements when
* using a 32-bit implementation; in particular when the architecture
* does not offer a native rotation opcode (interleaving replaces one
* 64-bit rotation with two 32-bit rotations, which is a gain only if
* there is a native 32-bit rotation opcode and not a native 64-bit
* rotation opcode; also, interleaving implies a small overhead when
* processing input words).
*
* To sum up:
* -- when possible, use the 64-bit code
* -- exception: on 32-bit x86, use 32-bit code
* -- when using 32-bit code, use interleaving
* -- copy the state, except on x86
* -- unroll 8 rounds on "big" machine, 2 rounds on "small" machines
*/
#if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_KECCAK
#define SPH_SMALL_FOOTPRINT_KECCAK 1
#endif
/*
* By default, we select the 64-bit implementation if a 64-bit type
* is available, unless a 32-bit x86 is detected.
*/
#if !defined SPH_KECCAK_64 && SPH_64 \
&& !(defined __i386__ || SPH_I386_GCC || SPH_I386_MSVC)
#define SPH_KECCAK_64 1
#endif
/*
* If using a 32-bit implementation, we prefer to interleave.
*/
#if !SPH_KECCAK_64 && !defined SPH_KECCAK_INTERLEAVE
#define SPH_KECCAK_INTERLEAVE 1
#endif
/*
* Unroll 8 rounds on big systems, 2 rounds on small systems.
*/
#ifndef SPH_KECCAK_UNROLL
#if SPH_SMALL_FOOTPRINT_KECCAK
#define SPH_KECCAK_UNROLL 2
#else
#define SPH_KECCAK_UNROLL 8
#endif
#endif
/*
* We do not want to copy the state to local variables on x86 (32-bit
* and 64-bit alike).
*/
#ifndef SPH_KECCAK_NOCOPY
#if defined __i386__ || defined __x86_64 || SPH_I386_MSVC || SPH_I386_GCC
#define SPH_KECCAK_NOCOPY 1
#else
#define SPH_KECCAK_NOCOPY 0
#endif
#endif
#ifdef _MSC_VER
#pragma warning (disable: 4146)
#endif
#if SPH_KECCAK_64
static const sph_u64 RC[] = {
SPH_C64(0x0000000000000001), SPH_C64(0x0000000000008082),
SPH_C64(0x800000000000808A), SPH_C64(0x8000000080008000),
SPH_C64(0x000000000000808B), SPH_C64(0x0000000080000001),
SPH_C64(0x8000000080008081), SPH_C64(0x8000000000008009),
SPH_C64(0x000000000000008A), SPH_C64(0x0000000000000088),
SPH_C64(0x0000000080008009), SPH_C64(0x000000008000000A),
SPH_C64(0x000000008000808B), SPH_C64(0x800000000000008B),
SPH_C64(0x8000000000008089), SPH_C64(0x8000000000008003),
SPH_C64(0x8000000000008002), SPH_C64(0x8000000000000080),
SPH_C64(0x000000000000800A), SPH_C64(0x800000008000000A),
SPH_C64(0x8000000080008081), SPH_C64(0x8000000000008080),
SPH_C64(0x0000000080000001), SPH_C64(0x8000000080008008)
};
#if SPH_KECCAK_NOCOPY
#define a00 (kc->u.wide[ 0])
#define a10 (kc->u.wide[ 1])
#define a20 (kc->u.wide[ 2])
#define a30 (kc->u.wide[ 3])
#define a40 (kc->u.wide[ 4])
#define a01 (kc->u.wide[ 5])
#define a11 (kc->u.wide[ 6])
#define a21 (kc->u.wide[ 7])
#define a31 (kc->u.wide[ 8])
#define a41 (kc->u.wide[ 9])
#define a02 (kc->u.wide[10])
#define a12 (kc->u.wide[11])
#define a22 (kc->u.wide[12])
#define a32 (kc->u.wide[13])
#define a42 (kc->u.wide[14])
#define a03 (kc->u.wide[15])
#define a13 (kc->u.wide[16])
#define a23 (kc->u.wide[17])
#define a33 (kc->u.wide[18])
#define a43 (kc->u.wide[19])
#define a04 (kc->u.wide[20])
#define a14 (kc->u.wide[21])
#define a24 (kc->u.wide[22])
#define a34 (kc->u.wide[23])
#define a44 (kc->u.wide[24])
#define DECL_STATE
#define READ_STATE(sc)
#define WRITE_STATE(sc)
#define INPUT_BUF(size) do { \
size_t j; \
for (j = 0; j < (size); j += 8) { \
kc->u.wide[j >> 3] ^= sph_dec64le_aligned(buf + j); \
} \
} while (0)
#define INPUT_BUF144 INPUT_BUF(144)
#define INPUT_BUF136 INPUT_BUF(136)
#define INPUT_BUF104 INPUT_BUF(104)
#define INPUT_BUF72 INPUT_BUF(72)
#else
#define DECL_STATE \
sph_u64 a00, a01, a02, a03, a04; \
sph_u64 a10, a11, a12, a13, a14; \
sph_u64 a20, a21, a22, a23, a24; \
sph_u64 a30, a31, a32, a33, a34; \
sph_u64 a40, a41, a42, a43, a44;
#define READ_STATE(state) do { \
a00 = (state)->u.wide[ 0]; \
a10 = (state)->u.wide[ 1]; \
a20 = (state)->u.wide[ 2]; \
a30 = (state)->u.wide[ 3]; \
a40 = (state)->u.wide[ 4]; \
a01 = (state)->u.wide[ 5]; \
a11 = (state)->u.wide[ 6]; \
a21 = (state)->u.wide[ 7]; \
a31 = (state)->u.wide[ 8]; \
a41 = (state)->u.wide[ 9]; \
a02 = (state)->u.wide[10]; \
a12 = (state)->u.wide[11]; \
a22 = (state)->u.wide[12]; \
a32 = (state)->u.wide[13]; \
a42 = (state)->u.wide[14]; \
a03 = (state)->u.wide[15]; \
a13 = (state)->u.wide[16]; \
a23 = (state)->u.wide[17]; \
a33 = (state)->u.wide[18]; \
a43 = (state)->u.wide[19]; \
a04 = (state)->u.wide[20]; \
a14 = (state)->u.wide[21]; \
a24 = (state)->u.wide[22]; \
a34 = (state)->u.wide[23]; \
a44 = (state)->u.wide[24]; \
} while (0)
#define WRITE_STATE(state) do { \
(state)->u.wide[ 0] = a00; \
(state)->u.wide[ 1] = a10; \
(state)->u.wide[ 2] = a20; \
(state)->u.wide[ 3] = a30; \
(state)->u.wide[ 4] = a40; \
(state)->u.wide[ 5] = a01; \
(state)->u.wide[ 6] = a11; \
(state)->u.wide[ 7] = a21; \
(state)->u.wide[ 8] = a31; \
(state)->u.wide[ 9] = a41; \
(state)->u.wide[10] = a02; \
(state)->u.wide[11] = a12; \
(state)->u.wide[12] = a22; \
(state)->u.wide[13] = a32; \
(state)->u.wide[14] = a42; \
(state)->u.wide[15] = a03; \
(state)->u.wide[16] = a13; \
(state)->u.wide[17] = a23; \
(state)->u.wide[18] = a33; \
(state)->u.wide[19] = a43; \
(state)->u.wide[20] = a04; \
(state)->u.wide[21] = a14; \
(state)->u.wide[22] = a24; \
(state)->u.wide[23] = a34; \
(state)->u.wide[24] = a44; \
} while (0)
#define INPUT_BUF144 do { \
a00 ^= sph_dec64le_aligned(buf + 0); \
a10 ^= sph_dec64le_aligned(buf + 8); \
a20 ^= sph_dec64le_aligned(buf + 16); \
a30 ^= sph_dec64le_aligned(buf + 24); \
a40 ^= sph_dec64le_aligned(buf + 32); \
a01 ^= sph_dec64le_aligned(buf + 40); \
a11 ^= sph_dec64le_aligned(buf + 48); \
a21 ^= sph_dec64le_aligned(buf + 56); \
a31 ^= sph_dec64le_aligned(buf + 64); \
a41 ^= sph_dec64le_aligned(buf + 72); \
a02 ^= sph_dec64le_aligned(buf + 80); \
a12 ^= sph_dec64le_aligned(buf + 88); \
a22 ^= sph_dec64le_aligned(buf + 96); \
a32 ^= sph_dec64le_aligned(buf + 104); \
a42 ^= sph_dec64le_aligned(buf + 112); \
a03 ^= sph_dec64le_aligned(buf + 120); \
a13 ^= sph_dec64le_aligned(buf + 128); \
a23 ^= sph_dec64le_aligned(buf + 136); \
} while (0)
#define INPUT_BUF136 do { \
a00 ^= sph_dec64le_aligned(buf + 0); \
a10 ^= sph_dec64le_aligned(buf + 8); \
a20 ^= sph_dec64le_aligned(buf + 16); \
a30 ^= sph_dec64le_aligned(buf + 24); \
a40 ^= sph_dec64le_aligned(buf + 32); \
a01 ^= sph_dec64le_aligned(buf + 40); \
a11 ^= sph_dec64le_aligned(buf + 48); \
a21 ^= sph_dec64le_aligned(buf + 56); \
a31 ^= sph_dec64le_aligned(buf + 64); \
a41 ^= sph_dec64le_aligned(buf + 72); \
a02 ^= sph_dec64le_aligned(buf + 80); \
a12 ^= sph_dec64le_aligned(buf + 88); \
a22 ^= sph_dec64le_aligned(buf + 96); \
a32 ^= sph_dec64le_aligned(buf + 104); \
a42 ^= sph_dec64le_aligned(buf + 112); \
a03 ^= sph_dec64le_aligned(buf + 120); \
a13 ^= sph_dec64le_aligned(buf + 128); \
} while (0)
#define INPUT_BUF104 do { \
a00 ^= sph_dec64le_aligned(buf + 0); \
a10 ^= sph_dec64le_aligned(buf + 8); \
a20 ^= sph_dec64le_aligned(buf + 16); \
a30 ^= sph_dec64le_aligned(buf + 24); \
a40 ^= sph_dec64le_aligned(buf + 32); \
a01 ^= sph_dec64le_aligned(buf + 40); \
a11 ^= sph_dec64le_aligned(buf + 48); \
a21 ^= sph_dec64le_aligned(buf + 56); \
a31 ^= sph_dec64le_aligned(buf + 64); \
a41 ^= sph_dec64le_aligned(buf + 72); \
a02 ^= sph_dec64le_aligned(buf + 80); \
a12 ^= sph_dec64le_aligned(buf + 88); \
a22 ^= sph_dec64le_aligned(buf + 96); \
} while (0)
#define INPUT_BUF72 do { \
a00 ^= sph_dec64le_aligned(buf + 0); \
a10 ^= sph_dec64le_aligned(buf + 8); \
a20 ^= sph_dec64le_aligned(buf + 16); \
a30 ^= sph_dec64le_aligned(buf + 24); \
a40 ^= sph_dec64le_aligned(buf + 32); \
a01 ^= sph_dec64le_aligned(buf + 40); \
a11 ^= sph_dec64le_aligned(buf + 48); \
a21 ^= sph_dec64le_aligned(buf + 56); \
a31 ^= sph_dec64le_aligned(buf + 64); \
} while (0)
#define INPUT_BUF(lim) do { \
a00 ^= sph_dec64le_aligned(buf + 0); \
a10 ^= sph_dec64le_aligned(buf + 8); \
a20 ^= sph_dec64le_aligned(buf + 16); \
a30 ^= sph_dec64le_aligned(buf + 24); \
a40 ^= sph_dec64le_aligned(buf + 32); \
a01 ^= sph_dec64le_aligned(buf + 40); \
a11 ^= sph_dec64le_aligned(buf + 48); \
a21 ^= sph_dec64le_aligned(buf + 56); \
a31 ^= sph_dec64le_aligned(buf + 64); \
if ((lim) == 72) \
break; \
a41 ^= sph_dec64le_aligned(buf + 72); \
a02 ^= sph_dec64le_aligned(buf + 80); \
a12 ^= sph_dec64le_aligned(buf + 88); \
a22 ^= sph_dec64le_aligned(buf + 96); \
if ((lim) == 104) \
break; \
a32 ^= sph_dec64le_aligned(buf + 104); \
a42 ^= sph_dec64le_aligned(buf + 112); \
a03 ^= sph_dec64le_aligned(buf + 120); \
a13 ^= sph_dec64le_aligned(buf + 128); \
if ((lim) == 136) \
break; \
a23 ^= sph_dec64le_aligned(buf + 136); \
} while (0)
#endif
#define DECL64(x) sph_u64 x
#define MOV64(d, s) (d = s)
#define XOR64(d, a, b) (d = a ^ b)
#define AND64(d, a, b) (d = a & b)
#define OR64(d, a, b) (d = a | b)
#define NOT64(d, s) (d = SPH_T64(~s))
#define ROL64(d, v, n) (d = SPH_ROTL64(v, n))
#define XOR64_IOTA XOR64
#else
static const struct {
sph_u32 high, low;
} RC[] = {
#if SPH_KECCAK_INTERLEAVE
{ SPH_C32(0x00000000), SPH_C32(0x00000001) },
{ SPH_C32(0x00000089), SPH_C32(0x00000000) },
{ SPH_C32(0x8000008B), SPH_C32(0x00000000) },
{ SPH_C32(0x80008080), SPH_C32(0x00000000) },
{ SPH_C32(0x0000008B), SPH_C32(0x00000001) },
{ SPH_C32(0x00008000), SPH_C32(0x00000001) },
{ SPH_C32(0x80008088), SPH_C32(0x00000001) },
{ SPH_C32(0x80000082), SPH_C32(0x00000001) },
{ SPH_C32(0x0000000B), SPH_C32(0x00000000) },
{ SPH_C32(0x0000000A), SPH_C32(0x00000000) },
{ SPH_C32(0x00008082), SPH_C32(0x00000001) },
{ SPH_C32(0x00008003), SPH_C32(0x00000000) },
{ SPH_C32(0x0000808B), SPH_C32(0x00000001) },
{ SPH_C32(0x8000000B), SPH_C32(0x00000001) },
{ SPH_C32(0x8000008A), SPH_C32(0x00000001) },
{ SPH_C32(0x80000081), SPH_C32(0x00000001) },
{ SPH_C32(0x80000081), SPH_C32(0x00000000) },
{ SPH_C32(0x80000008), SPH_C32(0x00000000) },
{ SPH_C32(0x00000083), SPH_C32(0x00000000) },
{ SPH_C32(0x80008003), SPH_C32(0x00000000) },
{ SPH_C32(0x80008088), SPH_C32(0x00000001) },
{ SPH_C32(0x80000088), SPH_C32(0x00000000) },
{ SPH_C32(0x00008000), SPH_C32(0x00000001) },
{ SPH_C32(0x80008082), SPH_C32(0x00000000) }
#else
{ SPH_C32(0x00000000), SPH_C32(0x00000001) },
{ SPH_C32(0x00000000), SPH_C32(0x00008082) },
{ SPH_C32(0x80000000), SPH_C32(0x0000808A) },
{ SPH_C32(0x80000000), SPH_C32(0x80008000) },
{ SPH_C32(0x00000000), SPH_C32(0x0000808B) },
{ SPH_C32(0x00000000), SPH_C32(0x80000001) },
{ SPH_C32(0x80000000), SPH_C32(0x80008081) },
{ SPH_C32(0x80000000), SPH_C32(0x00008009) },
{ SPH_C32(0x00000000), SPH_C32(0x0000008A) },
{ SPH_C32(0x00000000), SPH_C32(0x00000088) },
{ SPH_C32(0x00000000), SPH_C32(0x80008009) },
{ SPH_C32(0x00000000), SPH_C32(0x8000000A) },
{ SPH_C32(0x00000000), SPH_C32(0x8000808B) },
{ SPH_C32(0x80000000), SPH_C32(0x0000008B) },
{ SPH_C32(0x80000000), SPH_C32(0x00008089) },
{ SPH_C32(0x80000000), SPH_C32(0x00008003) },
{ SPH_C32(0x80000000), SPH_C32(0x00008002) },
{ SPH_C32(0x80000000), SPH_C32(0x00000080) },
{ SPH_C32(0x00000000), SPH_C32(0x0000800A) },
{ SPH_C32(0x80000000), SPH_C32(0x8000000A) },
{ SPH_C32(0x80000000), SPH_C32(0x80008081) },
{ SPH_C32(0x80000000), SPH_C32(0x00008080) },
{ SPH_C32(0x00000000), SPH_C32(0x80000001) },
{ SPH_C32(0x80000000), SPH_C32(0x80008008) }
#endif
};
#if SPH_KECCAK_INTERLEAVE
#define INTERLEAVE(xl, xh) do { \
sph_u32 l, h, t; \
l = (xl); h = (xh); \
t = (l ^ (l >> 1)) & SPH_C32(0x22222222); l ^= t ^ (t << 1); \
t = (h ^ (h >> 1)) & SPH_C32(0x22222222); h ^= t ^ (t << 1); \
t = (l ^ (l >> 2)) & SPH_C32(0x0C0C0C0C); l ^= t ^ (t << 2); \
t = (h ^ (h >> 2)) & SPH_C32(0x0C0C0C0C); h ^= t ^ (t << 2); \
t = (l ^ (l >> 4)) & SPH_C32(0x00F000F0); l ^= t ^ (t << 4); \
t = (h ^ (h >> 4)) & SPH_C32(0x00F000F0); h ^= t ^ (t << 4); \
t = (l ^ (l >> 8)) & SPH_C32(0x0000FF00); l ^= t ^ (t << 8); \
t = (h ^ (h >> 8)) & SPH_C32(0x0000FF00); h ^= t ^ (t << 8); \
t = (l ^ SPH_T32(h << 16)) & SPH_C32(0xFFFF0000); \
l ^= t; h ^= t >> 16; \
(xl) = l; (xh) = h; \
} while (0)
#define UNINTERLEAVE(xl, xh) do { \
sph_u32 l, h, t; \
l = (xl); h = (xh); \
t = (l ^ SPH_T32(h << 16)) & SPH_C32(0xFFFF0000); \
l ^= t; h ^= t >> 16; \
t = (l ^ (l >> 8)) & SPH_C32(0x0000FF00); l ^= t ^ (t << 8); \
t = (h ^ (h >> 8)) & SPH_C32(0x0000FF00); h ^= t ^ (t << 8); \
t = (l ^ (l >> 4)) & SPH_C32(0x00F000F0); l ^= t ^ (t << 4); \
t = (h ^ (h >> 4)) & SPH_C32(0x00F000F0); h ^= t ^ (t << 4); \
t = (l ^ (l >> 2)) & SPH_C32(0x0C0C0C0C); l ^= t ^ (t << 2); \
t = (h ^ (h >> 2)) & SPH_C32(0x0C0C0C0C); h ^= t ^ (t << 2); \
t = (l ^ (l >> 1)) & SPH_C32(0x22222222); l ^= t ^ (t << 1); \
t = (h ^ (h >> 1)) & SPH_C32(0x22222222); h ^= t ^ (t << 1); \
(xl) = l; (xh) = h; \
} while (0)
#else
#define INTERLEAVE(l, h)
#define UNINTERLEAVE(l, h)
#endif
#if SPH_KECCAK_NOCOPY
#define a00l (kc->u.narrow[2 * 0 + 0])
#define a00h (kc->u.narrow[2 * 0 + 1])
#define a10l (kc->u.narrow[2 * 1 + 0])
#define a10h (kc->u.narrow[2 * 1 + 1])
#define a20l (kc->u.narrow[2 * 2 + 0])
#define a20h (kc->u.narrow[2 * 2 + 1])
#define a30l (kc->u.narrow[2 * 3 + 0])
#define a30h (kc->u.narrow[2 * 3 + 1])
#define a40l (kc->u.narrow[2 * 4 + 0])
#define a40h (kc->u.narrow[2 * 4 + 1])
#define a01l (kc->u.narrow[2 * 5 + 0])
#define a01h (kc->u.narrow[2 * 5 + 1])
#define a11l (kc->u.narrow[2 * 6 + 0])
#define a11h (kc->u.narrow[2 * 6 + 1])
#define a21l (kc->u.narrow[2 * 7 + 0])
#define a21h (kc->u.narrow[2 * 7 + 1])
#define a31l (kc->u.narrow[2 * 8 + 0])
#define a31h (kc->u.narrow[2 * 8 + 1])
#define a41l (kc->u.narrow[2 * 9 + 0])
#define a41h (kc->u.narrow[2 * 9 + 1])
#define a02l (kc->u.narrow[2 * 10 + 0])
#define a02h (kc->u.narrow[2 * 10 + 1])
#define a12l (kc->u.narrow[2 * 11 + 0])
#define a12h (kc->u.narrow[2 * 11 + 1])
#define a22l (kc->u.narrow[2 * 12 + 0])
#define a22h (kc->u.narrow[2 * 12 + 1])
#define a32l (kc->u.narrow[2 * 13 + 0])
#define a32h (kc->u.narrow[2 * 13 + 1])
#define a42l (kc->u.narrow[2 * 14 + 0])
#define a42h (kc->u.narrow[2 * 14 + 1])
#define a03l (kc->u.narrow[2 * 15 + 0])
#define a03h (kc->u.narrow[2 * 15 + 1])
#define a13l (kc->u.narrow[2 * 16 + 0])
#define a13h (kc->u.narrow[2 * 16 + 1])
#define a23l (kc->u.narrow[2 * 17 + 0])
#define a23h (kc->u.narrow[2 * 17 + 1])
#define a33l (kc->u.narrow[2 * 18 + 0])
#define a33h (kc->u.narrow[2 * 18 + 1])
#define a43l (kc->u.narrow[2 * 19 + 0])
#define a43h (kc->u.narrow[2 * 19 + 1])
#define a04l (kc->u.narrow[2 * 20 + 0])
#define a04h (kc->u.narrow[2 * 20 + 1])
#define a14l (kc->u.narrow[2 * 21 + 0])
#define a14h (kc->u.narrow[2 * 21 + 1])
#define a24l (kc->u.narrow[2 * 22 + 0])
#define a24h (kc->u.narrow[2 * 22 + 1])
#define a34l (kc->u.narrow[2 * 23 + 0])
#define a34h (kc->u.narrow[2 * 23 + 1])
#define a44l (kc->u.narrow[2 * 24 + 0])
#define a44h (kc->u.narrow[2 * 24 + 1])
#define DECL_STATE
#define READ_STATE(state)
#define WRITE_STATE(state)
#define INPUT_BUF(size) do { \
size_t j; \
for (j = 0; j < (size); j += 8) { \
sph_u32 tl, th; \
tl = sph_dec32le_aligned(buf + j + 0); \
th = sph_dec32le_aligned(buf + j + 4); \
INTERLEAVE(tl, th); \
kc->u.narrow[(j >> 2) + 0] ^= tl; \
kc->u.narrow[(j >> 2) + 1] ^= th; \
} \
} while (0)
#define INPUT_BUF144 INPUT_BUF(144)
#define INPUT_BUF136 INPUT_BUF(136)
#define INPUT_BUF104 INPUT_BUF(104)
#define INPUT_BUF72 INPUT_BUF(72)
#else
#define DECL_STATE \
sph_u32 a00l, a00h, a01l, a01h, a02l, a02h, a03l, a03h, a04l, a04h; \
sph_u32 a10l, a10h, a11l, a11h, a12l, a12h, a13l, a13h, a14l, a14h; \
sph_u32 a20l, a20h, a21l, a21h, a22l, a22h, a23l, a23h, a24l, a24h; \
sph_u32 a30l, a30h, a31l, a31h, a32l, a32h, a33l, a33h, a34l, a34h; \
sph_u32 a40l, a40h, a41l, a41h, a42l, a42h, a43l, a43h, a44l, a44h;
#define READ_STATE(state) do { \
a00l = (state)->u.narrow[2 * 0 + 0]; \
a00h = (state)->u.narrow[2 * 0 + 1]; \
a10l = (state)->u.narrow[2 * 1 + 0]; \
a10h = (state)->u.narrow[2 * 1 + 1]; \
a20l = (state)->u.narrow[2 * 2 + 0]; \
a20h = (state)->u.narrow[2 * 2 + 1]; \
a30l = (state)->u.narrow[2 * 3 + 0]; \
a30h = (state)->u.narrow[2 * 3 + 1]; \
a40l = (state)->u.narrow[2 * 4 + 0]; \
a40h = (state)->u.narrow[2 * 4 + 1]; \
a01l = (state)->u.narrow[2 * 5 + 0]; \
a01h = (state)->u.narrow[2 * 5 + 1]; \
a11l = (state)->u.narrow[2 * 6 + 0]; \
a11h = (state)->u.narrow[2 * 6 + 1]; \
a21l = (state)->u.narrow[2 * 7 + 0]; \
a21h = (state)->u.narrow[2 * 7 + 1]; \
a31l = (state)->u.narrow[2 * 8 + 0]; \
a31h = (state)->u.narrow[2 * 8 + 1]; \
a41l = (state)->u.narrow[2 * 9 + 0]; \
a41h = (state)->u.narrow[2 * 9 + 1]; \
a02l = (state)->u.narrow[2 * 10 + 0]; \
a02h = (state)->u.narrow[2 * 10 + 1]; \
a12l = (state)->u.narrow[2 * 11 + 0]; \
a12h = (state)->u.narrow[2 * 11 + 1]; \
a22l = (state)->u.narrow[2 * 12 + 0]; \
a22h = (state)->u.narrow[2 * 12 + 1]; \
a32l = (state)->u.narrow[2 * 13 + 0]; \
a32h = (state)->u.narrow[2 * 13 + 1]; \
a42l = (state)->u.narrow[2 * 14 + 0]; \
a42h = (state)->u.narrow[2 * 14 + 1]; \
a03l = (state)->u.narrow[2 * 15 + 0]; \
a03h = (state)->u.narrow[2 * 15 + 1]; \
a13l = (state)->u.narrow[2 * 16 + 0]; \
a13h = (state)->u.narrow[2 * 16 + 1]; \
a23l = (state)->u.narrow[2 * 17 + 0]; \
a23h = (state)->u.narrow[2 * 17 + 1]; \
a33l = (state)->u.narrow[2 * 18 + 0]; \
a33h = (state)->u.narrow[2 * 18 + 1]; \
a43l = (state)->u.narrow[2 * 19 + 0]; \
a43h = (state)->u.narrow[2 * 19 + 1]; \
a04l = (state)->u.narrow[2 * 20 + 0]; \
a04h = (state)->u.narrow[2 * 20 + 1]; \
a14l = (state)->u.narrow[2 * 21 + 0]; \
a14h = (state)->u.narrow[2 * 21 + 1]; \
a24l = (state)->u.narrow[2 * 22 + 0]; \
a24h = (state)->u.narrow[2 * 22 + 1]; \
a34l = (state)->u.narrow[2 * 23 + 0]; \
a34h = (state)->u.narrow[2 * 23 + 1]; \
a44l = (state)->u.narrow[2 * 24 + 0]; \
a44h = (state)->u.narrow[2 * 24 + 1]; \
} while (0)
#define WRITE_STATE(state) do { \
(state)->u.narrow[2 * 0 + 0] = a00l; \
(state)->u.narrow[2 * 0 + 1] = a00h; \
(state)->u.narrow[2 * 1 + 0] = a10l; \
(state)->u.narrow[2 * 1 + 1] = a10h; \
(state)->u.narrow[2 * 2 + 0] = a20l; \
(state)->u.narrow[2 * 2 + 1] = a20h; \
(state)->u.narrow[2 * 3 + 0] = a30l; \
(state)->u.narrow[2 * 3 + 1] = a30h; \
(state)->u.narrow[2 * 4 + 0] = a40l; \
(state)->u.narrow[2 * 4 + 1] = a40h; \
(state)->u.narrow[2 * 5 + 0] = a01l; \
(state)->u.narrow[2 * 5 + 1] = a01h; \
(state)->u.narrow[2 * 6 + 0] = a11l; \
(state)->u.narrow[2 * 6 + 1] = a11h; \
(state)->u.narrow[2 * 7 + 0] = a21l; \
(state)->u.narrow[2 * 7 + 1] = a21h; \
(state)->u.narrow[2 * 8 + 0] = a31l; \
(state)->u.narrow[2 * 8 + 1] = a31h; \
(state)->u.narrow[2 * 9 + 0] = a41l; \
(state)->u.narrow[2 * 9 + 1] = a41h; \
(state)->u.narrow[2 * 10 + 0] = a02l; \
(state)->u.narrow[2 * 10 + 1] = a02h; \
(state)->u.narrow[2 * 11 + 0] = a12l; \
(state)->u.narrow[2 * 11 + 1] = a12h; \
(state)->u.narrow[2 * 12 + 0] = a22l; \
(state)->u.narrow[2 * 12 + 1] = a22h; \
(state)->u.narrow[2 * 13 + 0] = a32l; \
(state)->u.narrow[2 * 13 + 1] = a32h; \
(state)->u.narrow[2 * 14 + 0] = a42l; \
(state)->u.narrow[2 * 14 + 1] = a42h; \
(state)->u.narrow[2 * 15 + 0] = a03l; \
(state)->u.narrow[2 * 15 + 1] = a03h; \
(state)->u.narrow[2 * 16 + 0] = a13l; \
(state)->u.narrow[2 * 16 + 1] = a13h; \
(state)->u.narrow[2 * 17 + 0] = a23l; \
(state)->u.narrow[2 * 17 + 1] = a23h; \
(state)->u.narrow[2 * 18 + 0] = a33l; \
(state)->u.narrow[2 * 18 + 1] = a33h; \
(state)->u.narrow[2 * 19 + 0] = a43l; \
(state)->u.narrow[2 * 19 + 1] = a43h; \
(state)->u.narrow[2 * 20 + 0] = a04l; \
(state)->u.narrow[2 * 20 + 1] = a04h; \
(state)->u.narrow[2 * 21 + 0] = a14l; \
(state)->u.narrow[2 * 21 + 1] = a14h; \
(state)->u.narrow[2 * 22 + 0] = a24l; \
(state)->u.narrow[2 * 22 + 1] = a24h; \
(state)->u.narrow[2 * 23 + 0] = a34l; \
(state)->u.narrow[2 * 23 + 1] = a34h; \
(state)->u.narrow[2 * 24 + 0] = a44l; \
(state)->u.narrow[2 * 24 + 1] = a44h; \
} while (0)
#define READ64(d, off) do { \
sph_u32 tl, th; \
tl = sph_dec32le_aligned(buf + (off)); \
th = sph_dec32le_aligned(buf + (off) + 4); \
INTERLEAVE(tl, th); \
d ## l ^= tl; \
d ## h ^= th; \
} while (0)
#define INPUT_BUF144 do { \
READ64(a00, 0); \
READ64(a10, 8); \
READ64(a20, 16); \
READ64(a30, 24); \
READ64(a40, 32); \
READ64(a01, 40); \
READ64(a11, 48); \
READ64(a21, 56); \
READ64(a31, 64); \
READ64(a41, 72); \
READ64(a02, 80); \
READ64(a12, 88); \
READ64(a22, 96); \
READ64(a32, 104); \
READ64(a42, 112); \
READ64(a03, 120); \
READ64(a13, 128); \
READ64(a23, 136); \
} while (0)
#define INPUT_BUF136 do { \
READ64(a00, 0); \
READ64(a10, 8); \
READ64(a20, 16); \
READ64(a30, 24); \
READ64(a40, 32); \
READ64(a01, 40); \
READ64(a11, 48); \
READ64(a21, 56); \
READ64(a31, 64); \
READ64(a41, 72); \
READ64(a02, 80); \
READ64(a12, 88); \
READ64(a22, 96); \
READ64(a32, 104); \
READ64(a42, 112); \
READ64(a03, 120); \
READ64(a13, 128); \
} while (0)
#define INPUT_BUF104 do { \
READ64(a00, 0); \
READ64(a10, 8); \
READ64(a20, 16); \
READ64(a30, 24); \
READ64(a40, 32); \
READ64(a01, 40); \
READ64(a11, 48); \
READ64(a21, 56); \
READ64(a31, 64); \
READ64(a41, 72); \
READ64(a02, 80); \
READ64(a12, 88); \
READ64(a22, 96); \
} while (0)
#define INPUT_BUF72 do { \
READ64(a00, 0); \
READ64(a10, 8); \
READ64(a20, 16); \
READ64(a30, 24); \
READ64(a40, 32); \
READ64(a01, 40); \
READ64(a11, 48); \
READ64(a21, 56); \
READ64(a31, 64); \
} while (0)
#define INPUT_BUF(lim) do { \
READ64(a00, 0); \
READ64(a10, 8); \
READ64(a20, 16); \
READ64(a30, 24); \
READ64(a40, 32); \
READ64(a01, 40); \
READ64(a11, 48); \
READ64(a21, 56); \
READ64(a31, 64); \
if ((lim) == 72) \
break; \
READ64(a41, 72); \
READ64(a02, 80); \
READ64(a12, 88); \
READ64(a22, 96); \
if ((lim) == 104) \
break; \
READ64(a32, 104); \
READ64(a42, 112); \
READ64(a03, 120); \
READ64(a13, 128); \
if ((lim) == 136) \
break; \
READ64(a23, 136); \
} while (0)
#endif
#define DECL64(x) sph_u64 x ## l, x ## h
#define MOV64(d, s) (d ## l = s ## l, d ## h = s ## h)
#define XOR64(d, a, b) (d ## l = a ## l ^ b ## l, d ## h = a ## h ^ b ## h)
#define AND64(d, a, b) (d ## l = a ## l & b ## l, d ## h = a ## h & b ## h)
#define OR64(d, a, b) (d ## l = a ## l | b ## l, d ## h = a ## h | b ## h)
#define NOT64(d, s) (d ## l = SPH_T32(~s ## l), d ## h = SPH_T32(~s ## h))
#define ROL64(d, v, n) ROL64_ ## n(d, v)
#if SPH_KECCAK_INTERLEAVE
#define ROL64_odd1(d, v) do { \
sph_u32 tmp; \
tmp = v ## l; \
d ## l = SPH_T32(v ## h << 1) | (v ## h >> 31); \
d ## h = tmp; \
} while (0)
#define ROL64_odd63(d, v) do { \
sph_u32 tmp; \
tmp = SPH_T32(v ## l << 31) | (v ## l >> 1); \
d ## l = v ## h; \
d ## h = tmp; \
} while (0)
#define ROL64_odd(d, v, n) do { \
sph_u32 tmp; \
tmp = SPH_T32(v ## l << (n - 1)) | (v ## l >> (33 - n)); \
d ## l = SPH_T32(v ## h << n) | (v ## h >> (32 - n)); \
d ## h = tmp; \
} while (0)
#define ROL64_even(d, v, n) do { \
d ## l = SPH_T32(v ## l << n) | (v ## l >> (32 - n)); \
d ## h = SPH_T32(v ## h << n) | (v ## h >> (32 - n)); \
} while (0)
#define ROL64_0(d, v)
#define ROL64_1(d, v) ROL64_odd1(d, v)
#define ROL64_2(d, v) ROL64_even(d, v, 1)
#define ROL64_3(d, v) ROL64_odd( d, v, 2)
#define ROL64_4(d, v) ROL64_even(d, v, 2)
#define ROL64_5(d, v) ROL64_odd( d, v, 3)
#define ROL64_6(d, v) ROL64_even(d, v, 3)
#define ROL64_7(d, v) ROL64_odd( d, v, 4)
#define ROL64_8(d, v) ROL64_even(d, v, 4)
#define ROL64_9(d, v) ROL64_odd( d, v, 5)
#define ROL64_10(d, v) ROL64_even(d, v, 5)
#define ROL64_11(d, v) ROL64_odd( d, v, 6)
#define ROL64_12(d, v) ROL64_even(d, v, 6)
#define ROL64_13(d, v) ROL64_odd( d, v, 7)
#define ROL64_14(d, v) ROL64_even(d, v, 7)
#define ROL64_15(d, v) ROL64_odd( d, v, 8)
#define ROL64_16(d, v) ROL64_even(d, v, 8)
#define ROL64_17(d, v) ROL64_odd( d, v, 9)
#define ROL64_18(d, v) ROL64_even(d, v, 9)
#define ROL64_19(d, v) ROL64_odd( d, v, 10)
#define ROL64_20(d, v) ROL64_even(d, v, 10)
#define ROL64_21(d, v) ROL64_odd( d, v, 11)
#define ROL64_22(d, v) ROL64_even(d, v, 11)
#define ROL64_23(d, v) ROL64_odd( d, v, 12)
#define ROL64_24(d, v) ROL64_even(d, v, 12)
#define ROL64_25(d, v) ROL64_odd( d, v, 13)
#define ROL64_26(d, v) ROL64_even(d, v, 13)
#define ROL64_27(d, v) ROL64_odd( d, v, 14)
#define ROL64_28(d, v) ROL64_even(d, v, 14)
#define ROL64_29(d, v) ROL64_odd( d, v, 15)
#define ROL64_30(d, v) ROL64_even(d, v, 15)
#define ROL64_31(d, v) ROL64_odd( d, v, 16)
#define ROL64_32(d, v) ROL64_even(d, v, 16)
#define ROL64_33(d, v) ROL64_odd( d, v, 17)
#define ROL64_34(d, v) ROL64_even(d, v, 17)
#define ROL64_35(d, v) ROL64_odd( d, v, 18)
#define ROL64_36(d, v) ROL64_even(d, v, 18)
#define ROL64_37(d, v) ROL64_odd( d, v, 19)
#define ROL64_38(d, v) ROL64_even(d, v, 19)
#define ROL64_39(d, v) ROL64_odd( d, v, 20)
#define ROL64_40(d, v) ROL64_even(d, v, 20)
#define ROL64_41(d, v) ROL64_odd( d, v, 21)
#define ROL64_42(d, v) ROL64_even(d, v, 21)
#define ROL64_43(d, v) ROL64_odd( d, v, 22)
#define ROL64_44(d, v) ROL64_even(d, v, 22)
#define ROL64_45(d, v) ROL64_odd( d, v, 23)
#define ROL64_46(d, v) ROL64_even(d, v, 23)
#define ROL64_47(d, v) ROL64_odd( d, v, 24)
#define ROL64_48(d, v) ROL64_even(d, v, 24)
#define ROL64_49(d, v) ROL64_odd( d, v, 25)
#define ROL64_50(d, v) ROL64_even(d, v, 25)
#define ROL64_51(d, v) ROL64_odd( d, v, 26)
#define ROL64_52(d, v) ROL64_even(d, v, 26)
#define ROL64_53(d, v) ROL64_odd( d, v, 27)
#define ROL64_54(d, v) ROL64_even(d, v, 27)
#define ROL64_55(d, v) ROL64_odd( d, v, 28)
#define ROL64_56(d, v) ROL64_even(d, v, 28)
#define ROL64_57(d, v) ROL64_odd( d, v, 29)
#define ROL64_58(d, v) ROL64_even(d, v, 29)
#define ROL64_59(d, v) ROL64_odd( d, v, 30)
#define ROL64_60(d, v) ROL64_even(d, v, 30)
#define ROL64_61(d, v) ROL64_odd( d, v, 31)
#define ROL64_62(d, v) ROL64_even(d, v, 31)
#define ROL64_63(d, v) ROL64_odd63(d, v)
#else
#define ROL64_small(d, v, n) do { \
sph_u32 tmp; \
tmp = SPH_T32(v ## l << n) | (v ## h >> (32 - n)); \
d ## h = SPH_T32(v ## h << n) | (v ## l >> (32 - n)); \
d ## l = tmp; \
} while (0)
#define ROL64_0(d, v) 0
#define ROL64_1(d, v) ROL64_small(d, v, 1)
#define ROL64_2(d, v) ROL64_small(d, v, 2)
#define ROL64_3(d, v) ROL64_small(d, v, 3)
#define ROL64_4(d, v) ROL64_small(d, v, 4)
#define ROL64_5(d, v) ROL64_small(d, v, 5)
#define ROL64_6(d, v) ROL64_small(d, v, 6)
#define ROL64_7(d, v) ROL64_small(d, v, 7)
#define ROL64_8(d, v) ROL64_small(d, v, 8)
#define ROL64_9(d, v) ROL64_small(d, v, 9)
#define ROL64_10(d, v) ROL64_small(d, v, 10)
#define ROL64_11(d, v) ROL64_small(d, v, 11)
#define ROL64_12(d, v) ROL64_small(d, v, 12)
#define ROL64_13(d, v) ROL64_small(d, v, 13)
#define ROL64_14(d, v) ROL64_small(d, v, 14)
#define ROL64_15(d, v) ROL64_small(d, v, 15)
#define ROL64_16(d, v) ROL64_small(d, v, 16)
#define ROL64_17(d, v) ROL64_small(d, v, 17)
#define ROL64_18(d, v) ROL64_small(d, v, 18)
#define ROL64_19(d, v) ROL64_small(d, v, 19)
#define ROL64_20(d, v) ROL64_small(d, v, 20)
#define ROL64_21(d, v) ROL64_small(d, v, 21)
#define ROL64_22(d, v) ROL64_small(d, v, 22)
#define ROL64_23(d, v) ROL64_small(d, v, 23)
#define ROL64_24(d, v) ROL64_small(d, v, 24)
#define ROL64_25(d, v) ROL64_small(d, v, 25)
#define ROL64_26(d, v) ROL64_small(d, v, 26)
#define ROL64_27(d, v) ROL64_small(d, v, 27)
#define ROL64_28(d, v) ROL64_small(d, v, 28)
#define ROL64_29(d, v) ROL64_small(d, v, 29)
#define ROL64_30(d, v) ROL64_small(d, v, 30)
#define ROL64_31(d, v) ROL64_small(d, v, 31)
#define ROL64_32(d, v) do { \
sph_u32 tmp; \
tmp = v ## l; \
d ## l = v ## h; \
d ## h = tmp; \
} while (0)
#define ROL64_big(d, v, n) do { \
sph_u32 trl, trh; \
ROL64_small(tr, v, n); \
d ## h = trl; \
d ## l = trh; \
} while (0)
#define ROL64_33(d, v) ROL64_big(d, v, 1)
#define ROL64_34(d, v) ROL64_big(d, v, 2)
#define ROL64_35(d, v) ROL64_big(d, v, 3)
#define ROL64_36(d, v) ROL64_big(d, v, 4)
#define ROL64_37(d, v) ROL64_big(d, v, 5)
#define ROL64_38(d, v) ROL64_big(d, v, 6)
#define ROL64_39(d, v) ROL64_big(d, v, 7)
#define ROL64_40(d, v) ROL64_big(d, v, 8)
#define ROL64_41(d, v) ROL64_big(d, v, 9)
#define ROL64_42(d, v) ROL64_big(d, v, 10)
#define ROL64_43(d, v) ROL64_big(d, v, 11)
#define ROL64_44(d, v) ROL64_big(d, v, 12)
#define ROL64_45(d, v) ROL64_big(d, v, 13)
#define ROL64_46(d, v) ROL64_big(d, v, 14)
#define ROL64_47(d, v) ROL64_big(d, v, 15)
#define ROL64_48(d, v) ROL64_big(d, v, 16)
#define ROL64_49(d, v) ROL64_big(d, v, 17)
#define ROL64_50(d, v) ROL64_big(d, v, 18)
#define ROL64_51(d, v) ROL64_big(d, v, 19)
#define ROL64_52(d, v) ROL64_big(d, v, 20)
#define ROL64_53(d, v) ROL64_big(d, v, 21)
#define ROL64_54(d, v) ROL64_big(d, v, 22)
#define ROL64_55(d, v) ROL64_big(d, v, 23)
#define ROL64_56(d, v) ROL64_big(d, v, 24)
#define ROL64_57(d, v) ROL64_big(d, v, 25)
#define ROL64_58(d, v) ROL64_big(d, v, 26)
#define ROL64_59(d, v) ROL64_big(d, v, 27)
#define ROL64_60(d, v) ROL64_big(d, v, 28)
#define ROL64_61(d, v) ROL64_big(d, v, 29)
#define ROL64_62(d, v) ROL64_big(d, v, 30)
#define ROL64_63(d, v) ROL64_big(d, v, 31)
#endif
#define XOR64_IOTA(d, s, k) \
(d ## l = s ## l ^ k.low, d ## h = s ## h ^ k.high)
#endif
#define TH_ELT(t, c0, c1, c2, c3, c4, d0, d1, d2, d3, d4) do { \
DECL64(tt0); \
DECL64(tt1); \
DECL64(tt2); \
DECL64(tt3); \
XOR64(tt0, d0, d1); \
XOR64(tt1, d2, d3); \
XOR64(tt0, tt0, d4); \
XOR64(tt0, tt0, tt1); \
ROL64(tt0, tt0, 1); \
XOR64(tt2, c0, c1); \
XOR64(tt3, c2, c3); \
XOR64(tt0, tt0, c4); \
XOR64(tt2, tt2, tt3); \
XOR64(t, tt0, tt2); \
} while (0)
#define THETA(b00, b01, b02, b03, b04, b10, b11, b12, b13, b14, \
b20, b21, b22, b23, b24, b30, b31, b32, b33, b34, \
b40, b41, b42, b43, b44) \
do { \
DECL64(t0); \
DECL64(t1); \
DECL64(t2); \
DECL64(t3); \
DECL64(t4); \
TH_ELT(t0, b40, b41, b42, b43, b44, b10, b11, b12, b13, b14); \
TH_ELT(t1, b00, b01, b02, b03, b04, b20, b21, b22, b23, b24); \
TH_ELT(t2, b10, b11, b12, b13, b14, b30, b31, b32, b33, b34); \
TH_ELT(t3, b20, b21, b22, b23, b24, b40, b41, b42, b43, b44); \
TH_ELT(t4, b30, b31, b32, b33, b34, b00, b01, b02, b03, b04); \
XOR64(b00, b00, t0); \
XOR64(b01, b01, t0); \
XOR64(b02, b02, t0); \
XOR64(b03, b03, t0); \
XOR64(b04, b04, t0); \
XOR64(b10, b10, t1); \
XOR64(b11, b11, t1); \
XOR64(b12, b12, t1); \
XOR64(b13, b13, t1); \
XOR64(b14, b14, t1); \
XOR64(b20, b20, t2); \
XOR64(b21, b21, t2); \
XOR64(b22, b22, t2); \
XOR64(b23, b23, t2); \
XOR64(b24, b24, t2); \
XOR64(b30, b30, t3); \
XOR64(b31, b31, t3); \
XOR64(b32, b32, t3); \
XOR64(b33, b33, t3); \
XOR64(b34, b34, t3); \
XOR64(b40, b40, t4); \
XOR64(b41, b41, t4); \
XOR64(b42, b42, t4); \
XOR64(b43, b43, t4); \
XOR64(b44, b44, t4); \
} while (0)
#define RHO(b00, b01, b02, b03, b04, b10, b11, b12, b13, b14, \
b20, b21, b22, b23, b24, b30, b31, b32, b33, b34, \
b40, b41, b42, b43, b44) \
do { \
/* ROL64(b00, b00, 0); */ \
ROL64(b01, b01, 36); \
ROL64(b02, b02, 3); \
ROL64(b03, b03, 41); \
ROL64(b04, b04, 18); \
ROL64(b10, b10, 1); \
ROL64(b11, b11, 44); \
ROL64(b12, b12, 10); \
ROL64(b13, b13, 45); \
ROL64(b14, b14, 2); \
ROL64(b20, b20, 62); \
ROL64(b21, b21, 6); \
ROL64(b22, b22, 43); \
ROL64(b23, b23, 15); \
ROL64(b24, b24, 61); \
ROL64(b30, b30, 28); \
ROL64(b31, b31, 55); \
ROL64(b32, b32, 25); \
ROL64(b33, b33, 21); \
ROL64(b34, b34, 56); \
ROL64(b40, b40, 27); \
ROL64(b41, b41, 20); \
ROL64(b42, b42, 39); \
ROL64(b43, b43, 8); \
ROL64(b44, b44, 14); \
} while (0)
/*
* The KHI macro integrates the "lane complement" optimization. On input,
* some words are complemented:
* a00 a01 a02 a04 a13 a20 a21 a22 a30 a33 a34 a43
* On output, the following words are complemented:
* a04 a10 a20 a22 a23 a31
*
* The (implicit) permutation and the theta expansion will bring back
* the input mask for the next round.
*/
#define KHI_XO(d, a, b, c) do { \
DECL64(kt); \
OR64(kt, b, c); \
XOR64(d, a, kt); \
} while (0)
#define KHI_XA(d, a, b, c) do { \
DECL64(kt); \
AND64(kt, b, c); \
XOR64(d, a, kt); \
} while (0)
#define KHI(b00, b01, b02, b03, b04, b10, b11, b12, b13, b14, \
b20, b21, b22, b23, b24, b30, b31, b32, b33, b34, \
b40, b41, b42, b43, b44) \
do { \
DECL64(c0); \
DECL64(c1); \
DECL64(c2); \
DECL64(c3); \
DECL64(c4); \
DECL64(bnn); \
NOT64(bnn, b20); \
KHI_XO(c0, b00, b10, b20); \
KHI_XO(c1, b10, bnn, b30); \
KHI_XA(c2, b20, b30, b40); \
KHI_XO(c3, b30, b40, b00); \
KHI_XA(c4, b40, b00, b10); \
MOV64(b00, c0); \
MOV64(b10, c1); \
MOV64(b20, c2); \
MOV64(b30, c3); \
MOV64(b40, c4); \
NOT64(bnn, b41); \
KHI_XO(c0, b01, b11, b21); \
KHI_XA(c1, b11, b21, b31); \
KHI_XO(c2, b21, b31, bnn); \
KHI_XO(c3, b31, b41, b01); \
KHI_XA(c4, b41, b01, b11); \
MOV64(b01, c0); \
MOV64(b11, c1); \
MOV64(b21, c2); \
MOV64(b31, c3); \
MOV64(b41, c4); \
NOT64(bnn, b32); \
KHI_XO(c0, b02, b12, b22); \
KHI_XA(c1, b12, b22, b32); \
KHI_XA(c2, b22, bnn, b42); \
KHI_XO(c3, bnn, b42, b02); \
KHI_XA(c4, b42, b02, b12); \
MOV64(b02, c0); \
MOV64(b12, c1); \
MOV64(b22, c2); \
MOV64(b32, c3); \
MOV64(b42, c4); \
NOT64(bnn, b33); \
KHI_XA(c0, b03, b13, b23); \
KHI_XO(c1, b13, b23, b33); \
KHI_XO(c2, b23, bnn, b43); \
KHI_XA(c3, bnn, b43, b03); \
KHI_XO(c4, b43, b03, b13); \
MOV64(b03, c0); \
MOV64(b13, c1); \
MOV64(b23, c2); \
MOV64(b33, c3); \
MOV64(b43, c4); \
NOT64(bnn, b14); \
KHI_XA(c0, b04, bnn, b24); \
KHI_XO(c1, bnn, b24, b34); \
KHI_XA(c2, b24, b34, b44); \
KHI_XO(c3, b34, b44, b04); \
KHI_XA(c4, b44, b04, b14); \
MOV64(b04, c0); \
MOV64(b14, c1); \
MOV64(b24, c2); \
MOV64(b34, c3); \
MOV64(b44, c4); \
} while (0)
#define IOTA(r) XOR64_IOTA(a00, a00, r)
#define P0 a00, a01, a02, a03, a04, a10, a11, a12, a13, a14, a20, a21, \
a22, a23, a24, a30, a31, a32, a33, a34, a40, a41, a42, a43, a44
#define P1 a00, a30, a10, a40, a20, a11, a41, a21, a01, a31, a22, a02, \
a32, a12, a42, a33, a13, a43, a23, a03, a44, a24, a04, a34, a14
#define P2 a00, a33, a11, a44, a22, a41, a24, a02, a30, a13, a32, a10, \
a43, a21, a04, a23, a01, a34, a12, a40, a14, a42, a20, a03, a31
#define P3 a00, a23, a41, a14, a32, a24, a42, a10, a33, a01, a43, a11, \
a34, a02, a20, a12, a30, a03, a21, a44, a31, a04, a22, a40, a13
#define P4 a00, a12, a24, a31, a43, a42, a04, a11, a23, a30, a34, a41, \
a03, a10, a22, a21, a33, a40, a02, a14, a13, a20, a32, a44, a01
#define P5 a00, a21, a42, a13, a34, a04, a20, a41, a12, a33, a03, a24, \
a40, a11, a32, a02, a23, a44, a10, a31, a01, a22, a43, a14, a30
#define P6 a00, a02, a04, a01, a03, a20, a22, a24, a21, a23, a40, a42, \
a44, a41, a43, a10, a12, a14, a11, a13, a30, a32, a34, a31, a33
#define P7 a00, a10, a20, a30, a40, a22, a32, a42, a02, a12, a44, a04, \
a14, a24, a34, a11, a21, a31, a41, a01, a33, a43, a03, a13, a23
#define P8 a00, a11, a22, a33, a44, a32, a43, a04, a10, a21, a14, a20, \
a31, a42, a03, a41, a02, a13, a24, a30, a23, a34, a40, a01, a12
#define P9 a00, a41, a32, a23, a14, a43, a34, a20, a11, a02, a31, a22, \
a13, a04, a40, a24, a10, a01, a42, a33, a12, a03, a44, a30, a21
#define P10 a00, a24, a43, a12, a31, a34, a03, a22, a41, a10, a13, a32, \
a01, a20, a44, a42, a11, a30, a04, a23, a21, a40, a14, a33, a02
#define P11 a00, a42, a34, a21, a13, a03, a40, a32, a24, a11, a01, a43, \
a30, a22, a14, a04, a41, a33, a20, a12, a02, a44, a31, a23, a10
#define P12 a00, a04, a03, a02, a01, a40, a44, a43, a42, a41, a30, a34, \
a33, a32, a31, a20, a24, a23, a22, a21, a10, a14, a13, a12, a11
#define P13 a00, a20, a40, a10, a30, a44, a14, a34, a04, a24, a33, a03, \
a23, a43, a13, a22, a42, a12, a32, a02, a11, a31, a01, a21, a41
#define P14 a00, a22, a44, a11, a33, a14, a31, a03, a20, a42, a23, a40, \
a12, a34, a01, a32, a04, a21, a43, a10, a41, a13, a30, a02, a24
#define P15 a00, a32, a14, a41, a23, a31, a13, a40, a22, a04, a12, a44, \
a21, a03, a30, a43, a20, a02, a34, a11, a24, a01, a33, a10, a42
#define P16 a00, a43, a31, a24, a12, a13, a01, a44, a32, a20, a21, a14, \
a02, a40, a33, a34, a22, a10, a03, a41, a42, a30, a23, a11, a04
#define P17 a00, a34, a13, a42, a21, a01, a30, a14, a43, a22, a02, a31, \
a10, a44, a23, a03, a32, a11, a40, a24, a04, a33, a12, a41, a20
#define P18 a00, a03, a01, a04, a02, a30, a33, a31, a34, a32, a10, a13, \
a11, a14, a12, a40, a43, a41, a44, a42, a20, a23, a21, a24, a22
#define P19 a00, a40, a30, a20, a10, a33, a23, a13, a03, a43, a11, a01, \
a41, a31, a21, a44, a34, a24, a14, a04, a22, a12, a02, a42, a32
#define P20 a00, a44, a33, a22, a11, a23, a12, a01, a40, a34, a41, a30, \
a24, a13, a02, a14, a03, a42, a31, a20, a32, a21, a10, a04, a43
#define P21 a00, a14, a23, a32, a41, a12, a21, a30, a44, a03, a24, a33, \
a42, a01, a10, a31, a40, a04, a13, a22, a43, a02, a11, a20, a34
#define P22 a00, a31, a12, a43, a24, a21, a02, a33, a14, a40, a42, a23, \
a04, a30, a11, a13, a44, a20, a01, a32, a34, a10, a41, a22, a03
#define P23 a00, a13, a21, a34, a42, a02, a10, a23, a31, a44, a04, a12, \
a20, a33, a41, a01, a14, a22, a30, a43, a03, a11, a24, a32, a40
#define P1_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a30); \
MOV64(a30, a33); \
MOV64(a33, a23); \
MOV64(a23, a12); \
MOV64(a12, a21); \
MOV64(a21, a02); \
MOV64(a02, a10); \
MOV64(a10, a11); \
MOV64(a11, a41); \
MOV64(a41, a24); \
MOV64(a24, a42); \
MOV64(a42, a04); \
MOV64(a04, a20); \
MOV64(a20, a22); \
MOV64(a22, a32); \
MOV64(a32, a43); \
MOV64(a43, a34); \
MOV64(a34, a03); \
MOV64(a03, a40); \
MOV64(a40, a44); \
MOV64(a44, a14); \
MOV64(a14, a31); \
MOV64(a31, a13); \
MOV64(a13, t); \
} while (0)
#define P2_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a33); \
MOV64(a33, a12); \
MOV64(a12, a02); \
MOV64(a02, a11); \
MOV64(a11, a24); \
MOV64(a24, a04); \
MOV64(a04, a22); \
MOV64(a22, a43); \
MOV64(a43, a03); \
MOV64(a03, a44); \
MOV64(a44, a31); \
MOV64(a31, t); \
MOV64(t, a10); \
MOV64(a10, a41); \
MOV64(a41, a42); \
MOV64(a42, a20); \
MOV64(a20, a32); \
MOV64(a32, a34); \
MOV64(a34, a40); \
MOV64(a40, a14); \
MOV64(a14, a13); \
MOV64(a13, a30); \
MOV64(a30, a23); \
MOV64(a23, a21); \
MOV64(a21, t); \
} while (0)
#define P4_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a12); \
MOV64(a12, a11); \
MOV64(a11, a04); \
MOV64(a04, a43); \
MOV64(a43, a44); \
MOV64(a44, t); \
MOV64(t, a02); \
MOV64(a02, a24); \
MOV64(a24, a22); \
MOV64(a22, a03); \
MOV64(a03, a31); \
MOV64(a31, a33); \
MOV64(a33, t); \
MOV64(t, a10); \
MOV64(a10, a42); \
MOV64(a42, a32); \
MOV64(a32, a40); \
MOV64(a40, a13); \
MOV64(a13, a23); \
MOV64(a23, t); \
MOV64(t, a14); \
MOV64(a14, a30); \
MOV64(a30, a21); \
MOV64(a21, a41); \
MOV64(a41, a20); \
MOV64(a20, a34); \
MOV64(a34, t); \
} while (0)
#define P6_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a02); \
MOV64(a02, a04); \
MOV64(a04, a03); \
MOV64(a03, t); \
MOV64(t, a10); \
MOV64(a10, a20); \
MOV64(a20, a40); \
MOV64(a40, a30); \
MOV64(a30, t); \
MOV64(t, a11); \
MOV64(a11, a22); \
MOV64(a22, a44); \
MOV64(a44, a33); \
MOV64(a33, t); \
MOV64(t, a12); \
MOV64(a12, a24); \
MOV64(a24, a43); \
MOV64(a43, a31); \
MOV64(a31, t); \
MOV64(t, a13); \
MOV64(a13, a21); \
MOV64(a21, a42); \
MOV64(a42, a34); \
MOV64(a34, t); \
MOV64(t, a14); \
MOV64(a14, a23); \
MOV64(a23, a41); \
MOV64(a41, a32); \
MOV64(a32, t); \
} while (0)
#define P8_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a11); \
MOV64(a11, a43); \
MOV64(a43, t); \
MOV64(t, a02); \
MOV64(a02, a22); \
MOV64(a22, a31); \
MOV64(a31, t); \
MOV64(t, a03); \
MOV64(a03, a33); \
MOV64(a33, a24); \
MOV64(a24, t); \
MOV64(t, a04); \
MOV64(a04, a44); \
MOV64(a44, a12); \
MOV64(a12, t); \
MOV64(t, a10); \
MOV64(a10, a32); \
MOV64(a32, a13); \
MOV64(a13, t); \
MOV64(t, a14); \
MOV64(a14, a21); \
MOV64(a21, a20); \
MOV64(a20, t); \
MOV64(t, a23); \
MOV64(a23, a42); \
MOV64(a42, a40); \
MOV64(a40, t); \
MOV64(t, a30); \
MOV64(a30, a41); \
MOV64(a41, a34); \
MOV64(a34, t); \
} while (0)
#define P12_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a04); \
MOV64(a04, t); \
MOV64(t, a02); \
MOV64(a02, a03); \
MOV64(a03, t); \
MOV64(t, a10); \
MOV64(a10, a40); \
MOV64(a40, t); \
MOV64(t, a11); \
MOV64(a11, a44); \
MOV64(a44, t); \
MOV64(t, a12); \
MOV64(a12, a43); \
MOV64(a43, t); \
MOV64(t, a13); \
MOV64(a13, a42); \
MOV64(a42, t); \
MOV64(t, a14); \
MOV64(a14, a41); \
MOV64(a41, t); \
MOV64(t, a20); \
MOV64(a20, a30); \
MOV64(a30, t); \
MOV64(t, a21); \
MOV64(a21, a34); \
MOV64(a34, t); \
MOV64(t, a22); \
MOV64(a22, a33); \
MOV64(a33, t); \
MOV64(t, a23); \
MOV64(a23, a32); \
MOV64(a32, t); \
MOV64(t, a24); \
MOV64(a24, a31); \
MOV64(a31, t); \
} while (0)
#define LPAR (
#define RPAR )
#define KF_ELT(r, s, k) do { \
THETA LPAR P ## r RPAR; \
RHO LPAR P ## r RPAR; \
KHI LPAR P ## s RPAR; \
IOTA(k); \
} while (0)
#define DO(x) x
#define KECCAK_F_1600 DO(KECCAK_F_1600_)
#if SPH_KECCAK_UNROLL == 1
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j ++) { \
KF_ELT( 0, 1, RC[j + 0]); \
P1_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 2
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j += 2) { \
KF_ELT( 0, 1, RC[j + 0]); \
KF_ELT( 1, 2, RC[j + 1]); \
P2_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 4
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j += 4) { \
KF_ELT( 0, 1, RC[j + 0]); \
KF_ELT( 1, 2, RC[j + 1]); \
KF_ELT( 2, 3, RC[j + 2]); \
KF_ELT( 3, 4, RC[j + 3]); \
P4_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 6
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j += 6) { \
KF_ELT( 0, 1, RC[j + 0]); \
KF_ELT( 1, 2, RC[j + 1]); \
KF_ELT( 2, 3, RC[j + 2]); \
KF_ELT( 3, 4, RC[j + 3]); \
KF_ELT( 4, 5, RC[j + 4]); \
KF_ELT( 5, 6, RC[j + 5]); \
P6_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 8
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j += 8) { \
KF_ELT( 0, 1, RC[j + 0]); \
KF_ELT( 1, 2, RC[j + 1]); \
KF_ELT( 2, 3, RC[j + 2]); \
KF_ELT( 3, 4, RC[j + 3]); \
KF_ELT( 4, 5, RC[j + 4]); \
KF_ELT( 5, 6, RC[j + 5]); \
KF_ELT( 6, 7, RC[j + 6]); \
KF_ELT( 7, 8, RC[j + 7]); \
P8_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 12
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j += 12) { \
KF_ELT( 0, 1, RC[j + 0]); \
KF_ELT( 1, 2, RC[j + 1]); \
KF_ELT( 2, 3, RC[j + 2]); \
KF_ELT( 3, 4, RC[j + 3]); \
KF_ELT( 4, 5, RC[j + 4]); \
KF_ELT( 5, 6, RC[j + 5]); \
KF_ELT( 6, 7, RC[j + 6]); \
KF_ELT( 7, 8, RC[j + 7]); \
KF_ELT( 8, 9, RC[j + 8]); \
KF_ELT( 9, 10, RC[j + 9]); \
KF_ELT(10, 11, RC[j + 10]); \
KF_ELT(11, 12, RC[j + 11]); \
P12_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 0
#define KECCAK_F_1600_ do { \
KF_ELT( 0, 1, RC[ 0]); \
KF_ELT( 1, 2, RC[ 1]); \
KF_ELT( 2, 3, RC[ 2]); \
KF_ELT( 3, 4, RC[ 3]); \
KF_ELT( 4, 5, RC[ 4]); \
KF_ELT( 5, 6, RC[ 5]); \
KF_ELT( 6, 7, RC[ 6]); \
KF_ELT( 7, 8, RC[ 7]); \
KF_ELT( 8, 9, RC[ 8]); \
KF_ELT( 9, 10, RC[ 9]); \
KF_ELT(10, 11, RC[10]); \
KF_ELT(11, 12, RC[11]); \
KF_ELT(12, 13, RC[12]); \
KF_ELT(13, 14, RC[13]); \
KF_ELT(14, 15, RC[14]); \
KF_ELT(15, 16, RC[15]); \
KF_ELT(16, 17, RC[16]); \
KF_ELT(17, 18, RC[17]); \
KF_ELT(18, 19, RC[18]); \
KF_ELT(19, 20, RC[19]); \
KF_ELT(20, 21, RC[20]); \
KF_ELT(21, 22, RC[21]); \
KF_ELT(22, 23, RC[22]); \
KF_ELT(23, 0, RC[23]); \
} while (0)
#else
#error Unimplemented unroll count for Keccak.
#endif
static void
keccak_init(sph_keccak_context *kc, unsigned out_size)
{
int i;
#if SPH_KECCAK_64
for (i = 0; i < 25; i ++)
kc->u.wide[i] = 0;
/*
* Initialization for the "lane complement".
*/
kc->u.wide[ 1] = SPH_C64(0xFFFFFFFFFFFFFFFF);
kc->u.wide[ 2] = SPH_C64(0xFFFFFFFFFFFFFFFF);
kc->u.wide[ 8] = SPH_C64(0xFFFFFFFFFFFFFFFF);
kc->u.wide[12] = SPH_C64(0xFFFFFFFFFFFFFFFF);
kc->u.wide[17] = SPH_C64(0xFFFFFFFFFFFFFFFF);
kc->u.wide[20] = SPH_C64(0xFFFFFFFFFFFFFFFF);
#else
for (i = 0; i < 50; i ++)
kc->u.narrow[i] = 0;
/*
* Initialization for the "lane complement".
* Note: since we set to all-one full 64-bit words,
* interleaving (if applicable) is a no-op.
*/
kc->u.narrow[ 2] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[ 3] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[ 4] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[ 5] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[16] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[17] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[24] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[25] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[34] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[35] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[40] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[41] = SPH_C32(0xFFFFFFFF);
#endif
kc->ptr = 0;
kc->lim = 200 - (out_size >> 2);
}
static void
keccak_core(sph_keccak_context *kc, const void *data, size_t len, size_t lim)
{
unsigned char *buf;
size_t ptr;
DECL_STATE
buf = kc->buf;
ptr = kc->ptr;
if (len < (lim - ptr)) {
memcpy(buf + ptr, data, len);
kc->ptr = ptr + len;
return;
}
READ_STATE(kc);
while (len > 0) {
size_t clen;
clen = (lim - ptr);
if (clen > len)
clen = len;
memcpy(buf + ptr, data, clen);
ptr += clen;
data = (const unsigned char *)data + clen;
len -= clen;
if (ptr == lim) {
INPUT_BUF(lim);
KECCAK_F_1600;
ptr = 0;
}
}
WRITE_STATE(kc);
kc->ptr = ptr;
}
#if SPH_KECCAK_64
#define DEFCLOSE(d, lim) \
static void keccak_close ## d( \
sph_keccak_context *kc, unsigned ub, unsigned n, void *dst) \
{ \
unsigned eb; \
union { \
unsigned char tmp[lim + 1]; \
sph_u64 dummy; /* for alignment */ \
} u; \
size_t j; \
\
eb = (0x100 | (ub & 0xFF)) >> (8 - n); \
if (kc->ptr == (lim - 1)) { \
if (n == 7) { \
u.tmp[0] = eb; \
memset(u.tmp + 1, 0, lim - 1); \
u.tmp[lim] = 0x80; \
j = 1 + lim; \
} else { \
u.tmp[0] = eb | 0x80; \
j = 1; \
} \
} else { \
j = lim - kc->ptr; \
u.tmp[0] = eb; \
memset(u.tmp + 1, 0, j - 2); \
u.tmp[j - 1] = 0x80; \
} \
keccak_core(kc, u.tmp, j, lim); \
/* Finalize the "lane complement" */ \
kc->u.wide[ 1] = ~kc->u.wide[ 1]; \
kc->u.wide[ 2] = ~kc->u.wide[ 2]; \
kc->u.wide[ 8] = ~kc->u.wide[ 8]; \
kc->u.wide[12] = ~kc->u.wide[12]; \
kc->u.wide[17] = ~kc->u.wide[17]; \
kc->u.wide[20] = ~kc->u.wide[20]; \
for (j = 0; j < d; j += 8) \
sph_enc64le_aligned(u.tmp + j, kc->u.wide[j >> 3]); \
memcpy(dst, u.tmp, d); \
keccak_init(kc, (unsigned)d << 3); \
} \
#else
#define DEFCLOSE(d, lim) \
static void keccak_close ## d( \
sph_keccak_context *kc, unsigned ub, unsigned n, void *dst) \
{ \
unsigned eb; \
union { \
unsigned char tmp[lim + 1]; \
sph_u64 dummy; /* for alignment */ \
} u; \
size_t j; \
\
eb = (0x100 | (ub & 0xFF)) >> (8 - n); \
if (kc->ptr == (lim - 1)) { \
if (n == 7) { \
u.tmp[0] = eb; \
memset(u.tmp + 1, 0, lim - 1); \
u.tmp[lim] = 0x80; \
j = 1 + lim; \
} else { \
u.tmp[0] = eb | 0x80; \
j = 1; \
} \
} else { \
j = lim - kc->ptr; \
u.tmp[0] = eb; \
memset(u.tmp + 1, 0, j - 2); \
u.tmp[j - 1] = 0x80; \
} \
keccak_core(kc, u.tmp, j, lim); \
/* Finalize the "lane complement" */ \
kc->u.narrow[ 2] = ~kc->u.narrow[ 2]; \
kc->u.narrow[ 3] = ~kc->u.narrow[ 3]; \
kc->u.narrow[ 4] = ~kc->u.narrow[ 4]; \
kc->u.narrow[ 5] = ~kc->u.narrow[ 5]; \
kc->u.narrow[16] = ~kc->u.narrow[16]; \
kc->u.narrow[17] = ~kc->u.narrow[17]; \
kc->u.narrow[24] = ~kc->u.narrow[24]; \
kc->u.narrow[25] = ~kc->u.narrow[25]; \
kc->u.narrow[34] = ~kc->u.narrow[34]; \
kc->u.narrow[35] = ~kc->u.narrow[35]; \
kc->u.narrow[40] = ~kc->u.narrow[40]; \
kc->u.narrow[41] = ~kc->u.narrow[41]; \
/* un-interleave */ \
for (j = 0; j < 50; j += 2) \
UNINTERLEAVE(kc->u.narrow[j], kc->u.narrow[j + 1]); \
for (j = 0; j < d; j += 4) \
sph_enc32le_aligned(u.tmp + j, kc->u.narrow[j >> 2]); \
memcpy(dst, u.tmp, d); \
keccak_init(kc, (unsigned)d << 3); \
} \
#endif
DEFCLOSE(28, 144)
DEFCLOSE(32, 136)
DEFCLOSE(48, 104)
DEFCLOSE(64, 72)
/* see sph_keccak.h */
void
sph_keccak224_init(void *cc)
{
keccak_init(cc, 224);
}
/* see sph_keccak.h */
void
sph_keccak224(void *cc, const void *data, size_t len)
{
keccak_core(cc, data, len, 144);
}
/* see sph_keccak.h */
void
sph_keccak224_close(void *cc, void *dst)
{
sph_keccak224_addbits_and_close(cc, 0, 0, dst);
}
/* see sph_keccak.h */
void
sph_keccak224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
keccak_close28(cc, ub, n, dst);
}
/* see sph_keccak.h */
void
sph_keccak256_init(void *cc)
{
keccak_init(cc, 256);
}
/* see sph_keccak.h */
void
sph_keccak256(void *cc, const void *data, size_t len)
{
keccak_core(cc, data, len, 136);
}
/* see sph_keccak.h */
void
sph_keccak256_close(void *cc, void *dst)
{
sph_keccak256_addbits_and_close(cc, 0, 0, dst);
}
/* see sph_keccak.h */
void
sph_keccak256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
keccak_close32(cc, ub, n, dst);
}
/* see sph_keccak.h */
void
sph_keccak384_init(void *cc)
{
keccak_init(cc, 384);
}
/* see sph_keccak.h */
void
sph_keccak384(void *cc, const void *data, size_t len)
{
keccak_core(cc, data, len, 104);
}
/* see sph_keccak.h */
void
sph_keccak384_close(void *cc, void *dst)
{
sph_keccak384_addbits_and_close(cc, 0, 0, dst);
}
/* see sph_keccak.h */
void
sph_keccak384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
keccak_close48(cc, ub, n, dst);
}
/* see sph_keccak.h */
void
sph_keccak512_init(void *cc)
{
keccak_init(cc, 512);
}
/* see sph_keccak.h */
void
sph_keccak512(void *cc, const void *data, size_t len)
{
keccak_core(cc, data, len, 72);
}
/* see sph_keccak.h */
void
sph_keccak512_close(void *cc, void *dst)
{
sph_keccak512_addbits_and_close(cc, 0, 0, dst);
}
/* see sph_keccak.h */
void
sph_keccak512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
keccak_close64(cc, ub, n, dst);
}
#ifdef __cplusplus
}
#endif
| mit |
zdl411437734/ZBarBuildProj | ZBarBuildProj/jni/svg.c | 71 | 5916 | /*------------------------------------------------------------------------
* Copyright 2009 (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 <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include "svg.h"
static const char svg_head[] =
"<?xml version='1.0'?>\n"
"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'"
" 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n"
"<svg version='1.1' id='top' width='8in' height='8in'"
" preserveAspectRatio='xMidYMid' overflow='visible'"
" viewBox='%g,%g %g,%g' xmlns:xlink='http://www.w3.org/1999/xlink'"
" xmlns='http://www.w3.org/2000/svg'>\n"
"<defs><style type='text/css'><![CDATA[\n"
"* { image-rendering: optimizeSpeed }\n"
"image { opacity: .9 }\n"
"path, line, circle { fill: none; stroke-width: .5;"
" stroke-linejoin: round; stroke-linecap: butt;"
" stroke-opacity: .666; fill-opacity: .666 }\n"
/*"#hedge line, #vedge line { stroke: #34f }\n"*/
"#hedge, #vedge { stroke: yellow }\n"
"#target * { fill: none; stroke: #f24 }\n"
"#mdot * { fill: #e2f; stroke: none }\n"
"#ydot * { fill: yellow; stroke: none }\n"
"#cross * { stroke: #44f }\n"
".hedge { marker: url(#hedge) }\n"
".vedge { marker: url(#vedge) }\n"
".scanner .hedge, .scanner .vedge { stroke-width: 8 }\n"
".finder .hedge, .finder .vedge { /*stroke: #a0c;*/ stroke-width: .9 }\n"
".cluster { stroke: #a0c; stroke-width: 1; stroke-opacity: .45 }\n"
".cluster.valid { stroke: #c0a; stroke-width: 1; stroke-opacity: .666 }\n"
".h.cluster { marker: url(#vedge) }\n"
".v.cluster { marker: url(#hedge) }\n"
".centers { marker: url(#target); stroke-width: 3 }\n"
".edge-pts { marker: url(#ydot); stroke-width: .5 }\n"
".align { marker: url(#mdot); stroke-width: 1.5 }\n"
".sampling-grid { stroke-width: .75; marker: url(#cross) }\n"
"]]></style>\n"
"<marker id='hedge' overflow='visible'><line x1='-2' x2='2'/></marker>\n"
"<marker id='vedge' overflow='visible'><line y1='-2' y2='2'/></marker>\n"
"<marker id='ydot' overflow='visible'><circle r='2'/></marker>\n"
"<marker id='mdot' overflow='visible'><circle r='2'/></marker>\n"
"<marker id='cross' overflow='visible'><path d='M-2,0h4 M0,-2v4'/></marker>\n"
"<marker id='target' overflow='visible'><path d='M-4,0h8 M0,-4v8'/><circle r='2'/></marker>\n"
"</defs>\n";
static FILE *svg = NULL;
void svg_open (const char *name, double x, double y, double w, double h)
{
svg = fopen(name, "w");
if(!svg) return;
/* FIXME calc scaled size */
fprintf(svg, svg_head, x, y, w, h);
}
void svg_close ()
{
if(!svg) return;
fprintf(svg, "</svg>\n");
fclose(svg);
svg = NULL;
}
void svg_commentf (const char *format, ...)
{
if(!svg) return;
fprintf(svg, "<!-- ");
va_list args;
va_start(args, format);
vfprintf(svg, format, args);
va_end(args);
fprintf(svg, " -->\n");
}
void svg_image (const char *name, double width, double height)
{
if(!svg) return;
fprintf(svg, "<image width='%g' height='%g' xlink:href='%s'/>\n",
width, height, name);
}
void svg_group_start (const char *cls,
double deg,
double sx,
double sy,
double x,
double y)
{
if(!svg) return;
fprintf(svg, "<g class='%s'", cls);
if(sx != 1. || sy != 1 || deg || x || y) {
fprintf(svg, " transform='");
if(deg)
fprintf(svg, "rotate(%g)", deg);
if(x || y)
fprintf(svg, "translate(%g,%g)", x, y);
if(sx != 1. || sy != 1.) {
if(!sy)
fprintf(svg, "scale(%g)", sx);
else
fprintf(svg, "scale(%g,%g)", sx, sy);
}
fprintf(svg, "'");
}
fprintf(svg, ">\n");
}
void svg_group_end ()
{
fprintf(svg, "</g>\n");
}
void svg_path_start (const char *cls,
double scale,
double x,
double y)
{
if(!svg) return;
fprintf(svg, "<path class='%s'", cls);
if(scale != 1. || x || y) {
fprintf(svg, " transform='");
if(x || y)
fprintf(svg, "translate(%g,%g)", x, y);
if(scale != 1.)
fprintf(svg, "scale(%g)", scale);
fprintf(svg, "'");
}
fprintf(svg, " d='");
}
void svg_path_end ()
{
if(!svg) return;
fprintf(svg, "'/>\n");
}
void svg_path_close ()
{
if(!svg) return;
fprintf(svg, "z");
}
void svg_path_moveto (svg_absrel_t abs, double x, double y)
{
if(!svg) return;
fprintf(svg, " %c%g,%g", (abs) ? 'M' : 'm', x, y);
}
void svg_path_lineto(svg_absrel_t abs, double x, double y)
{
if(!svg) return;
if(x && y)
fprintf(svg, "%c%g,%g", (abs) ? 'L' : 'l', x, y);
else if(x)
fprintf(svg, "%c%g", (abs) ? 'H' : 'h', x);
else if(y)
fprintf(svg, "%c%g", (abs) ? 'V' : 'v', y);
}
| mit |
cwahbong/nodegit | vendor/openssl/openssl/crypto/evp/names.c | 598 | 6678 | /* crypto/evp/names.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/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
int EVP_add_cipher(const EVP_CIPHER *c)
{
int r;
if (c == NULL) return 0;
OPENSSL_init();
r=OBJ_NAME_add(OBJ_nid2sn(c->nid),OBJ_NAME_TYPE_CIPHER_METH,(const char *)c);
if (r == 0) return(0);
check_defer(c->nid);
r=OBJ_NAME_add(OBJ_nid2ln(c->nid),OBJ_NAME_TYPE_CIPHER_METH,(const char *)c);
return(r);
}
int EVP_add_digest(const EVP_MD *md)
{
int r;
const char *name;
OPENSSL_init();
name=OBJ_nid2sn(md->type);
r=OBJ_NAME_add(name,OBJ_NAME_TYPE_MD_METH,(const char *)md);
if (r == 0) return(0);
check_defer(md->type);
r=OBJ_NAME_add(OBJ_nid2ln(md->type),OBJ_NAME_TYPE_MD_METH,(const char *)md);
if (r == 0) return(0);
if (md->pkey_type && md->type != md->pkey_type)
{
r=OBJ_NAME_add(OBJ_nid2sn(md->pkey_type),
OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS,name);
if (r == 0) return(0);
check_defer(md->pkey_type);
r=OBJ_NAME_add(OBJ_nid2ln(md->pkey_type),
OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS,name);
}
return(r);
}
const EVP_CIPHER *EVP_get_cipherbyname(const char *name)
{
const EVP_CIPHER *cp;
cp=(const EVP_CIPHER *)OBJ_NAME_get(name,OBJ_NAME_TYPE_CIPHER_METH);
return(cp);
}
const EVP_MD *EVP_get_digestbyname(const char *name)
{
const EVP_MD *cp;
cp=(const EVP_MD *)OBJ_NAME_get(name,OBJ_NAME_TYPE_MD_METH);
return(cp);
}
void EVP_cleanup(void)
{
OBJ_NAME_cleanup(OBJ_NAME_TYPE_CIPHER_METH);
OBJ_NAME_cleanup(OBJ_NAME_TYPE_MD_METH);
/* The above calls will only clean out the contents of the name
hash table, but not the hash table itself. The following line
does that part. -- Richard Levitte */
OBJ_NAME_cleanup(-1);
EVP_PBE_cleanup();
if (obj_cleanup_defer == 2)
{
obj_cleanup_defer = 0;
OBJ_cleanup();
}
OBJ_sigid_free();
}
struct doall_cipher
{
void *arg;
void (*fn)(const EVP_CIPHER *ciph,
const char *from, const char *to, void *arg);
};
static void do_all_cipher_fn(const OBJ_NAME *nm, void *arg)
{
struct doall_cipher *dc = arg;
if (nm->alias)
dc->fn(NULL, nm->name, nm->data, dc->arg);
else
dc->fn((const EVP_CIPHER *)nm->data, nm->name, NULL, dc->arg);
}
void EVP_CIPHER_do_all(void (*fn)(const EVP_CIPHER *ciph,
const char *from, const char *to, void *x), void *arg)
{
struct doall_cipher dc;
dc.fn = fn;
dc.arg = arg;
OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH, do_all_cipher_fn, &dc);
}
void EVP_CIPHER_do_all_sorted(void (*fn)(const EVP_CIPHER *ciph,
const char *from, const char *to, void *x), void *arg)
{
struct doall_cipher dc;
dc.fn = fn;
dc.arg = arg;
OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, do_all_cipher_fn,&dc);
}
struct doall_md
{
void *arg;
void (*fn)(const EVP_MD *ciph,
const char *from, const char *to, void *arg);
};
static void do_all_md_fn(const OBJ_NAME *nm, void *arg)
{
struct doall_md *dc = arg;
if (nm->alias)
dc->fn(NULL, nm->name, nm->data, dc->arg);
else
dc->fn((const EVP_MD *)nm->data, nm->name, NULL, dc->arg);
}
void EVP_MD_do_all(void (*fn)(const EVP_MD *md,
const char *from, const char *to, void *x), void *arg)
{
struct doall_md dc;
dc.fn = fn;
dc.arg = arg;
OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH, do_all_md_fn, &dc);
}
void EVP_MD_do_all_sorted(void (*fn)(const EVP_MD *md,
const char *from, const char *to, void *x), void *arg)
{
struct doall_md dc;
dc.fn = fn;
dc.arg = arg;
OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, do_all_md_fn, &dc);
}
| mit |
fringebits/Windows-universal-samples | Samples/EasProtocol/cpp/Scenario2_CheckCompliance.xaml.cpp | 88 | 6100 | // Copyright (c) Microsoft. All rights reserved.
#include "pch.h"
#include "Scenario2_CheckCompliance.xaml.h"
using namespace SDKTemplate;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Security::ExchangeActiveSyncProvisioning;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
Scenario2_CheckCompliance::Scenario2_CheckCompliance() : rootPage(MainPage::Current)
{
InitializeComponent();
}
void Scenario2_CheckCompliance::Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
try
{
EasClientSecurityPolicy^ RequestedPolicy = ref new EasClientSecurityPolicy;
if (RequireEncryptionValue == nullptr)
{
RequestedPolicy->RequireEncryption = false;
}
else
{
if (RequireEncryptionValue->SelectedIndex == 1)
{
RequestedPolicy->RequireEncryption = true;
}
else
{
RequestedPolicy->RequireEncryption = false;
}
}
if (RequireEncryptionValue == nullptr || MinPasswordLengthValue->Text == "")
{
RequestedPolicy->MinPasswordLength = 0;
}
else
{
RequestedPolicy->MinPasswordLength = _wtoi(MinPasswordLengthValue->Text->Data());
}
if (DisallowConvenienceLogonValue == nullptr)
{
RequestedPolicy->DisallowConvenienceLogon = false;
}
else
{
if (DisallowConvenienceLogonValue->SelectedIndex == 1)
{
RequestedPolicy->DisallowConvenienceLogon = true;
}
else
{
RequestedPolicy->DisallowConvenienceLogon = false;
}
}
if (MinPasswordComplexCharactersValue == nullptr || MinPasswordComplexCharactersValue->Text == "")
{
RequestedPolicy->MinPasswordComplexCharacters = 0;
}
else
{
RequestedPolicy->MinPasswordComplexCharacters = _wtoi(MinPasswordComplexCharactersValue->Text->Data());
}
TimeSpan ExpirationDays;
if (PasswordExpirationValue == nullptr || PasswordExpirationValue->Text == "")
{
ExpirationDays.Duration = 0;
RequestedPolicy->PasswordExpiration = ExpirationDays;
}
else
{
ExpirationDays.Duration = _wtoi(PasswordExpirationValue->Text->Data()) * 86400000;
RequestedPolicy->PasswordExpiration = ExpirationDays;
}
if (PasswordHistoryValue == nullptr || PasswordHistoryValue->Text == "")
{
RequestedPolicy->PasswordHistory = 0;
}
else
{
RequestedPolicy->PasswordHistory = _wtoi(PasswordHistoryValue->Text->Data());
}
if (MaxPasswordFailedAttemptsValue == nullptr || MaxPasswordFailedAttemptsValue->Text == "")
{
RequestedPolicy->MaxPasswordFailedAttempts = 0;
}
else
{
RequestedPolicy->MaxPasswordFailedAttempts = _wtoi(MaxPasswordFailedAttemptsValue->Text->Data());
}
TimeSpan Inactiveseconds;
if (MaxInactivityTimeLockValue == nullptr || MaxInactivityTimeLockValue->Text == "")
{
Inactiveseconds.Duration = 0;
RequestedPolicy->MaxInactivityTimeLock = Inactiveseconds;
}
else
{
Inactiveseconds.Duration = _wtoi(MaxInactivityTimeLockValue->Text->Data()) * 1000;
RequestedPolicy->MaxInactivityTimeLock = Inactiveseconds;
}
EasComplianceResults^ CheckResult = RequestedPolicy->CheckCompliance();
RequireEncryptionResult->Text = CheckResult->RequireEncryptionResult.ToString();
EncryptionProviderTypeResult->Text = CheckResult->EncryptionProviderType.ToString();
MinPasswordLengthResult->Text = CheckResult->MinPasswordLengthResult.ToString();
DisallowConvenienceLogonResult->Text = CheckResult->DisallowConvenienceLogonResult.ToString();
MinPasswordComplexCharactersResult->Text = CheckResult->MinPasswordComplexCharactersResult.ToString();
PasswordExpirationResult->Text = CheckResult->PasswordExpirationResult.ToString();
PasswordHistoryResult->Text = CheckResult->PasswordHistoryResult.ToString();
MaxPasswordFailedAttemptsResult->Text = CheckResult->MaxPasswordFailedAttemptsResult.ToString();
MaxInactivityTimeLockResult->Text = CheckResult->MaxInactivityTimeLockResult.ToString();
}
catch (Platform::Exception^ ex)
{
MainPage::Current->NotifyUser(ex->Message, NotifyType::ErrorMessage);
}
}
void Scenario2_CheckCompliance::Reset_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
try
{
RequireEncryptionValue->SelectedIndex = 0;
MinPasswordLengthValue->Text = "";
DisallowConvenienceLogonValue->SelectedIndex = 0;
MinPasswordComplexCharactersValue->Text = "";
PasswordExpirationValue->Text = "";
PasswordHistoryValue->Text = "";
MaxPasswordFailedAttemptsValue->Text = "";
MaxInactivityTimeLockValue->Text = "";
RequireEncryptionResult->Text = "";
EncryptionProviderTypeResult->Text = "";
MinPasswordLengthResult->Text = "";
DisallowConvenienceLogonResult->Text = "";
MinPasswordComplexCharactersResult->Text = "";
PasswordExpirationResult->Text = "";
PasswordHistoryResult->Text = "";
MaxPasswordFailedAttemptsResult->Text = "";
MaxInactivityTimeLockResult->Text = "";
}
catch (Platform::Exception^ ex)
{
MainPage::Current->NotifyUser(ex->Message, NotifyType::ErrorMessage);
}
}
| mit |
Ziftr/litecoin | src/qt/clientmodel.cpp | 344 | 6316 | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"
#include "alert.h"
#include "main.h"
#include "checkpoints.h"
#include "ui_interface.h"
#include <QDateTime>
#include <QTimer>
static const int64 nClientStartupTime = GetTime();
ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
QObject(parent), optionsModel(optionsModel),
cachedNumBlocks(0), cachedNumBlocksOfPeers(0),
cachedReindexing(0), cachedImporting(0),
numBlocksAtStartup(-1), pollTimer(0)
{
pollTimer = new QTimer(this);
pollTimer->setInterval(MODEL_UPDATE_DELAY);
pollTimer->start();
connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));
subscribeToCoreSignals();
}
ClientModel::~ClientModel()
{
unsubscribeFromCoreSignals();
}
int ClientModel::getNumConnections() const
{
return vNodes.size();
}
int ClientModel::getNumBlocks() const
{
return nBestHeight;
}
int ClientModel::getNumBlocksAtStartup()
{
if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
return numBlocksAtStartup;
}
QDateTime ClientModel::getLastBlockDate() const
{
if (pindexBest)
return QDateTime::fromTime_t(pindexBest->GetBlockTime());
else if(!isTestNet())
return QDateTime::fromTime_t(1231006505); // Genesis block's time
else
return QDateTime::fromTime_t(1296688602); // Genesis block's time (testnet)
}
double ClientModel::getVerificationProgress() const
{
return Checkpoints::GuessVerificationProgress(pindexBest);
}
void ClientModel::updateTimer()
{
// Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change.
// Periodically check and update with a timer.
int newNumBlocks = getNumBlocks();
int newNumBlocksOfPeers = getNumBlocksOfPeers();
// check for changed number of blocks we have, number of blocks peers claim to have, reindexing state and importing state
if (cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers ||
cachedReindexing != fReindex || cachedImporting != fImporting)
{
cachedNumBlocks = newNumBlocks;
cachedNumBlocksOfPeers = newNumBlocksOfPeers;
cachedReindexing = fReindex;
cachedImporting = fImporting;
// ensure we return the maximum of newNumBlocksOfPeers and newNumBlocks to not create weird displays in the GUI
emit numBlocksChanged(newNumBlocks, std::max(newNumBlocksOfPeers, newNumBlocks));
}
}
void ClientModel::updateNumConnections(int numConnections)
{
emit numConnectionsChanged(numConnections);
}
void ClientModel::updateAlert(const QString &hash, int status)
{
// Show error message notification for new alert
if(status == CT_NEW)
{
uint256 hash_256;
hash_256.SetHex(hash.toStdString());
CAlert alert = CAlert::getAlertByHash(hash_256);
if(!alert.IsNull())
{
emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR);
}
}
emit alertsChanged(getStatusBarWarnings());
}
bool ClientModel::isTestNet() const
{
return fTestNet;
}
bool ClientModel::inInitialBlockDownload() const
{
return IsInitialBlockDownload();
}
enum BlockSource ClientModel::getBlockSource() const
{
if (fReindex)
return BLOCK_SOURCE_REINDEX;
else if (fImporting)
return BLOCK_SOURCE_DISK;
else if (getNumConnections() > 0)
return BLOCK_SOURCE_NETWORK;
return BLOCK_SOURCE_NONE;
}
int ClientModel::getNumBlocksOfPeers() const
{
return GetNumBlocksOfPeers();
}
QString ClientModel::getStatusBarWarnings() const
{
return QString::fromStdString(GetWarnings("statusbar"));
}
OptionsModel *ClientModel::getOptionsModel()
{
return optionsModel;
}
QString ClientModel::formatFullVersion() const
{
return QString::fromStdString(FormatFullVersion());
}
QString ClientModel::formatBuildDate() const
{
return QString::fromStdString(CLIENT_DATE);
}
bool ClientModel::isReleaseVersion() const
{
return CLIENT_VERSION_IS_RELEASE;
}
QString ClientModel::clientName() const
{
return QString::fromStdString(CLIENT_NAME);
}
QString ClientModel::formatClientStartupTime() const
{
return QDateTime::fromTime_t(nClientStartupTime).toString();
}
// Handlers for core signals
static void NotifyBlocksChanged(ClientModel *clientmodel)
{
// This notification is too frequent. Don't trigger a signal.
// Don't remove it, though, as it might be useful later.
}
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
// Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections);
QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
Q_ARG(int, newNumConnections));
}
static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status)
{
OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status);
QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(hash.GetHex())),
Q_ARG(int, status));
}
void ClientModel::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this));
uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
void ClientModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this));
uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
| mit |
nburkley/linguist | samples/C/rfc_string.c | 90 | 85695 | /**
** Copyright (c) 2011-2012, Karapetsas Eleftherios
** 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 Original Author of Refu nor the names of its contributors may be used to endorse or promote products derived from
**
** 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 <errno.h>
#include <String/rfc_string.h>
// include bitwise operations
#include <rf_utils.h>
// include the private functions and macros
#include "string_private.h"
// include io_private only for the write check
#include "../IO/io_private.h"
// include the extended strin
#include <String/rfc_stringx.h>
// for HUGE_VAL definition
#include <math.h>
#include <rf_localmem.h> // for the local stack memory
/*********************************************************************** Start of the RF_String functions *****************************************************************************************/
/*-------------------------------------------------------------------------Methods to create an RF_String-------------------------------------------------------------------------------*/
// Allocates and returns a string with the given characters a refu string with the given characters. Given characters have to be in UTF-8. A check for valide sequence of bytes is performed.
#ifndef RF_OPTION_DEFAULT_ARGUMENTS
RF_String* rfString_Create(const char* s,...)
#else
RF_String* i_rfString_Create(const char* s,...)
#endif
{
READ_VSNPRINTF_ARGS(s,s,0)
// check for validity of the given sequence and get the character length
uint32_t byteLength;
if( rfUTF8_VerifySequence(buff,&byteLength) == RF_FAILURE)
{
LOG_ERROR("Error at String Allocation due to invalid UTF-8 byte sequence",RE_STRING_INIT_FAILURE);
if(buffAllocated == true)
free(buff);
return 0;
}
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
// get length
ret->byteLength = byteLength;
// now that we know the length we can allocate the buffer and copy the bytes
RF_MALLOC(ret->bytes,ret->byteLength+1);
memcpy(ret->bytes,buff,ret->byteLength+1);
if(buffAllocated==true)
free(buff);
return ret;
}
#ifdef RF_OPTION_DEFAULT_ARGUMENTS
RF_String* i_NVrfString_Create(const char* s)
{
// check for validity of the given sequence and get the character length
uint32_t byteLength;
if( rfUTF8_VerifySequence(s,&byteLength) == RF_FAILURE)
{
LOG_ERROR("Error at String Allocation due to invalid UTF-8 byte sequence",RE_STRING_INIT_FAILURE);
return 0;
}
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
// get length
ret->byteLength = byteLength;
// now that we know the length we can allocate the buffer and copy the bytes
RF_MALLOC(ret->bytes,ret->byteLength+1);
memcpy(ret->bytes,s,ret->byteLength+1);
return ret;
}
#endif
// Allocates and returns a string with the given characters a refu string with the given characters. Given characters have to be in UTF-8. A check for valid sequence of bytes is performed.
RF_String* i_rfString_CreateLocal1(const char* s,...)
{
#if RF_OPTION_SOURCE_ENCODING != RF_UTF8
uint32_t characterLength,*codepoints,i=0,j;
#endif
// remember the stack pointer before this macro evaluation
rfLMS_MacroEvalPtr(RF_LMS);
// read the var args
READ_VSNPRINTF_ARGS(s,s,0)
// /===Start of Non-UTF-8 code===// /
#if (RF_OPTION_SOURCE_ENCODING == RF_UTF16_LE) || (RF_OPTION_SOURCE_ENCODING == RF_UTF16_BE)
// find the bytelength of the UTF-16 buffer
while(buff[i] != '\0' && buff[i+1]!= '\0')
i++;
i+=2;
// allocate the codepoint buffer
RF_MALLOC(codepoints,i/2)
#elif (RF_OPTION_SOURCE_ENCODING == RF_UTF32_LE) || (RF_OPTION_SOURCE_ENCODING == RF_UTF32_BE)
// find the bytelength of the UTF-32 buffer
while(buff[i] != '\0' && buff[i+1]!= '\0' && buff[i+2]!= '\0' && buff[i+3]!= '\0')
i++;
i+=4;
// allocate the codepoint buffer
RF_MALLOC(codepoints,i)
#endif
#if (RF_OPTION_SOURCE_ENCODING == RF_UTF16_LE)// decode the UTF16
if(rfUTILS_Endianess() == RF_LITTLE_ENDIAN)
if(rfUTF16_Decode(buff,&characterLength,codepoints) == false)
goto cleanup;
else
if(rfUTF16_Decode_swap(buff,&characterLength,codepoints)==false)
goto cleanup;
#elif RF_OPTION_SOURCE_ENCODING == RF_UTF16_BE// decode the UTF16
if(rfUTILS_Endianess() == RF_LITTLE_ENDIAN)
if(rfUTF16_Decode_swap(buff,&characterLength,codepoints) == false)
goto cleanup;
else
if(rfUTF16_Decode(buff,&characterLength,codepoints)==false)
goto cleanup;
#elif RF_OPTION_SOURCE_ENCODING == RF_UTF32_LE// copy the UTF32 into the codepoint
memcpy(codepoints,buff,i);
if(rfUTILS_Endianess != RF_LITTLE_ENDIAN)
{
for(j=0;j<i;j+=4)
{
rfUTILS_SwapEndianUI((uint32_t*)(codepoints+j))
}
}
#elif RF_OPTION_SOURCE_ENCODING == RF_UTF32_BE// copy the UTF32 into the codepoint
memcpy(codepoints,buff,i);
if(rfUTILS_Endianess !RF_BIG_ENDIAN RF_LITTLE_ENDIAN)
{
for(j=0;j<i;j+=4)
{
rfUTILS_SwapEndianUI((uint32_t*)(codepoints+j))
}
}
#endif
#if RF_OPTION_SOURCE_ENCODING != RF_UTF8 // in any case other than UTF-8 encode the codepoints into UTF-8 , and free them
if(buffAllocated == true)
free(buff);
buffAllocated = true;
if((buff = rfUTF8_Encode(codepoints,characterLength,&byteLength)) == 0)
{
LOG_ERROR("While attempting to create a temporary RF_String the given byte sequence could not be properly encoded into UTF-8",RE_UTF8_ENCODING);
free(codepoints);
return 0;
}
free(codepoints);
#endif
// /===End of Non-UTF-8 code===// /
// /progress normally since here we have a UTF-8 buffer
// check for validity of the given sequence and get the character length
uint32_t byteLength;
if( rfUTF8_VerifySequence(buff,&byteLength) == RF_FAILURE)
{
LOG_ERROR("Error at String Allocation due to invalid UTF-8 byte sequence",RE_STRING_INIT_FAILURE);
if(buffAllocated == true)
free(buff);
return 0;
}
RF_String* ret;
ret = rfLMS_Push(RF_LMS,sizeof(RF_String));
if(ret == 0)
{
LOG_ERROR("Memory allocation from the Local Memory Stack failed. Insufficient local memory stack space. Consider compiling the library with bigger stack space. Quitting proccess...",
RE_LOCALMEMSTACK_INSUFFICIENT);
exit(RE_LOCALMEMSTACK_INSUFFICIENT);
}
// get length
ret->byteLength = byteLength;
// now that we know the length we can allocate the buffer and copy the bytes
ret->bytes = rfLMS_Push(RF_LMS,ret->byteLength+1);
if(ret->bytes == 0)
{
LOG_ERROR("Memory allocation from the Local Memory Stack failed. Insufficient local memory stack space. Consider compiling the library with bigger stack space. Quitting proccess...",
RE_LOCALMEMSTACK_INSUFFICIENT);
exit(RE_LOCALMEMSTACK_INSUFFICIENT);
}
memcpy(ret->bytes,buff,ret->byteLength+1);
// finally free stuff if needed
if(buffAllocated == true)
free(buff);
return ret;
// /cleanup code for non-UTF-8 cases
#if (RF_OPTION_SOURCE_ENCODING == RF_UTF16_LE) || (RF_OPTION_SOURCE_ENCODING == RF_UTF16_BE)
cleanup:
#if RF_OPTION_SOURCE_ENCODING == RF_UTF16_LE
LOG_ERROR("Temporary RF_String creation from a UTF-16 Little Endian buffer failed due to UTF-16 decoding failure",RE_UTF16_INVALID_SEQUENCE);
#elif RF_OPTION_SOURCE_ENCODING == RF_UTF16_BE
LOG_ERROR("Temporary RF_String creation from a UTF-16 Big Endian buffer failed due to UTF-16 decoding failure",RE_UTF16_INVALID_SEQUENCE);
#endif
free(codepoints);
if(buffAllocated == true)
free(buff);
return 0;
#endif
}
RF_String* i_NVrfString_CreateLocal(const char* s)
{
#if RF_OPTION_SOURCE_ENCODING != RF_UTF8
uint32_t characterLength,*codepoints,i=0,j;
char* buff;
#endif
// remember the stack pointer before this macro evaluation
rfLMS_MacroEvalPtr(RF_LMS);
// /===Start of Non-UTF-8 code===// /
#if (RF_OPTION_SOURCE_ENCODING == RF_UTF16_LE) || (RF_OPTION_SOURCE_ENCODING == RF_UTF16_BE)
// find the bytelength of the UTF-16 buffer
while(s[i] != '\0' &&s[i+1]!= '\0')
i++;
i+=2;
// allocate the codepoint buffer
RF_MALLOC(codepoints,i/2)
#elif (RF_OPTION_SOURCE_ENCODING == RF_UTF32_LE) || (RF_OPTION_SOURCE_ENCODING == RF_UTF32_BE)
// find the bytelength of the UTF-32 buffer
while(s[i] != '\0' && s[i+1]!= '\0' && s[i+2]!= '\0' && s[i+3]!= '\0')
i++;
i+=4;
// allocate the codepoint buffer
RF_MALLOC(codepoints,i)
#endif
#if (RF_OPTION_SOURCE_ENCODING == RF_UTF16_LE)// decode the UTF16
if(rfUTILS_Endianess() == RF_LITTLE_ENDIAN)
if(rfUTF16_Decode(s,&characterLength,codepoints) == false)
goto cleanup;
else
if(rfUTF16_Decode_swap(s,&characterLength,codepoints)==false)
goto cleanup;
#elif RF_OPTION_SOURCE_ENCODING == RF_UTF16_BE// decode the UTF16
if(rfUTILS_Endianess() == RF_LITTLE_ENDIAN)
if(rfUTF16_Decode_swap(s,&characterLength,codepoints) == false)
goto cleanup;
else
if(rfUTF16_Decode(s,&characterLength,codepoints)==false)
goto cleanup;
#elif RF_OPTION_SOURCE_ENCODING == RF_UTF32_LE// copy the UTF32 into the codepoint
memcpy(codepoints,s,i);
if(rfUTILS_Endianess != RF_LITTLE_ENDIAN)
{
for(j=0;j<i;j+=4)
{
rfUTILS_SwapEndianUI((uint32_t*)(codepoints+j))
}
}
#elif RF_OPTION_SOURCE_ENCODING == RF_UTF32_BE// copy the UTF32 into the codepoint
memcpy(codepoints,s,i);
if(rfUTILS_Endianess !RF_BIG_ENDIAN RF_LITTLE_ENDIAN)
{
for(j=0;j<i;j+=4)
{
rfUTILS_SwapEndianUI((uint32_t*)(codepoints+j))
}
}
#endif
#if RF_OPTION_SOURCE_ENCODING != RF_UTF8 // in any case other than UTF-8 encode the codepoints into UTF-8 , and free them
if((buff = rfUTF8_Encode(codepoints,characterLength,&byteLength)) == 0)
{
LOG_ERROR("While attempting to create a temporary RF_String the given byte sequence could not be properly encoded into UTF-8",RE_UTF8_ENCODING);
free(codepoints);
return 0;
}
free(codepoints);
#endif
// /===End of Non-UTF-8 code===// /
// check for validity of the given sequence and get the character length
uint32_t byteLength;
#if RF_OPTION_SOURCE_ENCODING == RF_UTF8
if( rfUTF8_VerifySequence(s,&byteLength) == RF_FAILURE)
#else
if( rfUTF8_VerifySequence(buff,&byteLength) == RF_FAILURE)
#endif
{
LOG_ERROR("Error at String Allocation due to invalid UTF-8 byte sequence",RE_STRING_INIT_FAILURE);
return 0;
}
RF_String* ret;
ret = rfLMS_Push(RF_LMS,sizeof(RF_String));
if(ret == 0)
{
LOG_ERROR("Memory allocation from the Local Memory Stack failed during string allocation. Insufficient local memory stack space. Consider compiling the library with bigger stack space. Quitting proccess...",
RE_LOCALMEMSTACK_INSUFFICIENT);
exit(RE_LOCALMEMSTACK_INSUFFICIENT);
}
// get length
ret->byteLength = byteLength;
ret->bytes = rfLMS_Push(RF_LMS,ret->byteLength+1);
if(ret->bytes == 0)
{
LOG_ERROR("Memory allocation from the Local Memory Stack failed during string allocation. Insufficient local memory stack space. Consider compiling the library with bigger stack space. Quitting proccess...",
RE_LOCALMEMSTACK_INSUFFICIENT);
exit(RE_LOCALMEMSTACK_INSUFFICIENT);
}
#if RF_OPTION_SOURCE_ENCODING == RF_UTF8
memcpy(ret->bytes,s,ret->byteLength+1);
#else
memcpy(ret->bytes,buff,ret->byteLength+1);
#endif
return ret;
// /cleanup code for non-UTF-8 cases
#if (RF_OPTION_SOURCE_ENCODING == RF_UTF16_LE) || (RF_OPTION_SOURCE_ENCODING == RF_UTF16_BE)
cleanup:
#if RF_OPTION_SOURCE_ENCODING == RF_UTF16_LE
LOG_ERROR("Temporary RF_String creation from a UTF-16 Little Endian buffer failed due to UTF-16 decoding failure",RE_UTF16_INVALID_SEQUENCE);
#elif RF_OPTION_SOURCE_ENCODING == RF_UTF16_BE
LOG_ERROR("Temporary RF_String creation from a UTF-16 Big Endian buffer failed due to UTF-16 decoding failure",RE_UTF16_INVALID_SEQUENCE);
#endif
free(codepoints);
return 0;
#endif
}
// Initializes a string with the given characters. Given characters have to be in UTF-8. A check for valide sequence of bytes is performed.<b>Can't be used with RF_StringX</b>
#ifndef RF_OPTION_DEFAULT_ARGUMENTS
char rfString_Init(RF_String* str,const char* s,...)
#else
char i_rfString_Init(RF_String* str,const char* s,...)
#endif
{
READ_VSNPRINTF_ARGS(s,s,false)
// check for validity of the given sequence and get the character length
uint32_t byteLength;
if( rfUTF8_VerifySequence(buff,&byteLength) == RF_FAILURE)
{
LOG_ERROR("Error at String Initialization due to invalid UTF-8 byte sequence",RE_STRING_INIT_FAILURE);
if(buffAllocated==true)
free(buff);
return false;
}
// get length
str->byteLength = byteLength;
// now that we know the length we can allocate the buffer and copy the bytes
RF_MALLOC(str->bytes,str->byteLength+1);
memcpy(str->bytes,buff,str->byteLength+1);
if(buffAllocated == true)
free(buff);
return true;
}
#ifdef RF_OPTION_DEFAULT_ARGUMENTS
char i_NVrfString_Init(RF_String* str,const char* s)
{
// check for validity of the given sequence and get the character length
uint32_t byteLength;
if( rfUTF8_VerifySequence(s,&byteLength) == RF_FAILURE)
{
LOG_ERROR("Error at String Initialization due to invalid UTF-8 byte sequence",RE_STRING_INIT_FAILURE);
return false;
}
// get length
str->byteLength = byteLength;
// now that we know the length we can allocate the buffer and copy the bytes
RF_MALLOC(str->bytes,str->byteLength+1);
memcpy(str->bytes,s,str->byteLength+1);
return true;
}
#endif
// Allocates a String by turning a unicode code point in a String (encoded in UTF-8).
RF_String* rfString_Create_cp(uint32_t codepoint)
{
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
if(rfString_Init_cp(ret,codepoint) == true)
{
return ret;
}
// failure
free(ret);
return 0;
}
// Initializes a string by turning a unicode code point in a String (encoded in UTF-8).
char rfString_Init_cp(RF_String* str, uint32_t codepoint)
{
// alloc enough for a character
RF_MALLOC(str->bytes,5)
// if we only need a byte to encode it
if(RF_HEXLE_UI(codepoint,0x007f))
{
str->bytes[0] = codepoint;
str->bytes[1] = '\0';
str->byteLength = 1;
}
// if we need 2 bytes to encode it
else if( RF_HEXGE_UI(codepoint,0x0080) && RF_HEXLE_UI(codepoint,0x07ff))
{
// get the first bits of the first byte and encode them to the first byte
str->bytes[1] = (codepoint & 0x3F)|(0x02<<6);
// get the 5 following bits and encode them in the second byte
str->bytes[0] = ((codepoint & 0x7C0) >> 6) | (0x6<<5);
str->bytes[2] = '\0';
str->byteLength = 2;
}
// if we need 3 bytes to encode it
else if( RF_HEXGE_UI(codepoint,0x0800) && RF_HEXLE_UI(codepoint,0x0ffff))
{
// get the first bits of the first byte and encode them to the first byte
str->bytes[2] = (codepoint & 0x3F)|(0x02<<6);
// get the 6 following bits and encode them in the second byte
str->bytes[1] = ((codepoint & 0xFC0) >> 6) | (0x02<<6);
// get the 4 following bits and encode them in the third byte
str->bytes[0] = (((codepoint & 0xF000))>>12) | (0xE<<4);
str->bytes[3] = '\0';
str->byteLength = 3;
}
// if we need 4 bytes to encode it
else if( RF_HEXGE_UI(codepoint,0x10000) && RF_HEXLE_UI(codepoint,0x10ffff))
{
// get the first bits of the first byte and encode them to the first byte
str->bytes[3] = (codepoint & 0x3F)|(0x02<<6);
// get the 6 following bits and encode them in the second byte
str->bytes[2] = ((codepoint & 0xFC0) >> 6) | (0x02<<6);
// get the 6 following bits and encode them in the third byte
str->bytes[1] = (((codepoint & 0x3F000))>>12) | (0x02<<6);
// get the 3 following bits and encode them in the fourth byte
str->bytes[0] = (((codepoint & 0x1C0000))>>18) | (0x1E<<3);
str->bytes[4] = '\0';
str->byteLength = 4;
}
else
{
LOG_ERROR("Attempted to encode an invalid unicode code point into a string",RE_UTF8_INVALID_CODE_POINT);
free(str->bytes);
return false;
}
return true;
}
// Allocates and returns a string with the given integer
RF_String* rfString_Create_i(int32_t i)
{
// the size of the int32_t buffer
int32_t numLen;
// put the int32_t into a buffer and turn it in a char*
char buff[12];// max uint32_t is 4,294,967,295 in most environment so 12 chars will certainly fit it
sprintf(buff,"%d",i);
numLen = strlen(buff);
// initialize the string and return it
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
ret->byteLength = numLen;
RF_MALLOC(ret->bytes,numLen+1);
strcpy(ret->bytes,buff);
return ret;
}
// Initializes a string with the given integer.
char rfString_Init_i(RF_String* str, int32_t i)
{
// the size of the int32_t buffer
int32_t numLen;
// put the int32_t into a buffer and turn it in a char*
char buff[12];// max uint32_t is 4,294,967,295 in most environment so 12 chars will certainly fit it
sprintf(buff,"%d",i);
numLen = strlen(buff);
str->byteLength = numLen;
RF_MALLOC(str->bytes,numLen+1);
strcpy(str->bytes,buff);
return true;
}
// Allocates and returns a string with the given float
RF_String* rfString_Create_f(float f)
{
// allocate a buffer for the float in characters
char* buff;
RF_MALLOC(buff,128);
sprintf(buff,"%f",f);
uint32_t len = strlen(buff);
// initialize and return the string
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
ret->byteLength = len;
RF_MALLOC(ret->bytes,len+1);
strcpy(ret->bytes,buff);
free(buff);
return ret;
}
// Initializes a string with the given float
char rfString_Init_f(RF_String* str,float f)
{
// allocate a buffer for the float in characters
char* buff;
RF_MALLOC(buff,128);
sprintf(buff,"%f",f);
uint32_t len = strlen(buff);
str->byteLength = len;
RF_MALLOC(str->bytes,len+1);
strcpy(str->bytes,buff);
free(buff);
// success
return true;
}
// Allocates and returns a string with the given UTF-16 byte sequence. Given characters have to be in UTF-16. A check for valid sequence of bytes is performed.<b>Can't be used with RF_StringX</b>
RF_String* rfString_Create_UTF16(const char* s,char endianess)
{
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
if(rfString_Init_UTF16(ret,s,endianess)==false)
{
free(ret);
return 0;
}
return ret;
}
// Initializes a string with the given UTF-16 byte sequence. Given characters have to be in UTF-16. A check for valid sequence of bytes is performed.<b>Can't be used with RF_StringX</b>
char rfString_Init_UTF16(RF_String* str,const char* s,char endianess)
{
// decode the utf-16 and get the code points
uint32_t* codepoints;
uint32_t byteLength,characterLength,utf8ByteLength;
char* utf8;
byteLength = 0;
while(s[byteLength]!= 0 || s[byteLength+1]!=0)
{
byteLength++;
}
byteLength+=3;// for the last utf-16 null termination character
RF_MALLOC(codepoints,byteLength*2) // allocate the codepoints
// parse the given byte stream depending on the endianess parameter
switch(endianess)
{
case RF_LITTLE_ENDIAN:
case RF_BIG_ENDIAN:
if(rfUTILS_Endianess() == endianess)// same endianess as the local
{
if(rfUTF16_Decode(s,&characterLength,codepoints) == false)
{
free(codepoints);
LOG_ERROR("String initialization failed due to invalide UTF-16 sequence",RE_STRING_INIT_FAILURE);
return false;
}
}
else// different
{
if(rfUTF16_Decode_swap(s,&characterLength,codepoints) == false)
{
free(codepoints);
LOG_ERROR("String initialization failed due to invalide UTF-16 sequence",RE_STRING_INIT_FAILURE);
return false;
}
}
break;
default:
LOG_ERROR("Illegal endianess value provided",RE_INPUT);
free(codepoints);
return false;
break;
}// switch ends
// now encode these codepoints into UTF8
if( (utf8 = rfUTF8_Encode(codepoints,characterLength,&utf8ByteLength))==0)
{
free(codepoints);
return false;
}
// success
free(codepoints);
str->bytes = utf8;
str->byteLength = utf8ByteLength;
return true;
}
// Allocates and returns a string with the given UTF-32 byte sequence. Given characters have to be in UTF-32.
RF_String* rfString_Create_UTF32(const char* s)
{
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
if(rfString_Init_UTF32(ret,s)==false)
{
free(ret);
return 0;
}
return ret;
}
// Initializes a string with the given UTF-32 byte sequence. Given characters have to be in UTF-32.
char rfString_Init_UTF32(RF_String* str,const char* s)
{
char swapE = false;
uint32_t off = 0;
int32_t i = 0;
// get the buffer and if swapping is needed do it for all character
uint32_t* codeBuffer = (uint32_t*)(s+off);
// first of all check for existence of BOM in the beginning of the sequence
if(RF_HEXEQ_UI(codeBuffer[0],0xFEFF))// big endian
{
if(rfUTILS_Endianess()==RF_LITTLE_ENDIAN)
swapE = true;
}
if(RF_HEXEQ_UI(codeBuffer[0],0xFFFE0000))// little
{
if(rfUTILS_Endianess()==RF_BIG_ENDIAN)
swapE = true;
}
else// according to the standard no BOM means big endian
{
if(rfUTILS_Endianess() == RF_LITTLE_ENDIAN)
swapE = true;
}
// if we need to have endianess swapped do it
if(swapE==true)
{
while(codeBuffer[i] != 0)
{
rfUTILS_SwapEndianUI(codeBuffer+i);
i++;
}
}
// find the length of the utf32 buffer in characters
uint32_t length;
rfUTF32_Length(codeBuffer,length);
// turn the codepoints into a utf-8 encoded buffer
char* utf8;uint32_t utf8ByteLength;
if((utf8=rfUTF8_Encode(codeBuffer,length,&utf8ByteLength)) == 0)
{
return false;// error
}
// if the encoding happened correctly
if(codeBuffer != 0)
{
str->bytes = (char*)codeBuffer;
str->byteLength = utf8ByteLength;
return true;
}
// else return failure
return false;
}
// Assigns the value of the source string to the destination.Both strings should already be initialized and hold a value. It is an error to give null parameters.
void i_rfString_Assign(RF_String* dest,void* sourceP)
{
RF_String* source = (RF_String*)sourceP;
// only if the new string value won't fit in the buffer reallocate the buffer (let's avoid unecessary reallocs)
if(source->byteLength > dest->byteLength)
{
RF_REALLOC(dest->bytes,char,source->byteLength+1);
}
// now copy the value
memcpy(dest->bytes,source->bytes,source->byteLength+1);
// and fix the lengths
dest->byteLength = source->byteLength;
}
// Assigns the value of a unicode character to the string
char rfString_Assign_char(RF_String* str,uint32_t codepoint)
{
// realloc if needed
if(str->byteLength <5)
{
RF_REALLOC(str->bytes,char,5);
}
// if we only need a byte to encode it
if(RF_HEXLE_UI(codepoint,0x007f))
{
str->bytes[0] = codepoint;
str->bytes[1] = '\0';
str->byteLength = 1;
}
// if we need 2 bytes to encode it
else if( RF_HEXGE_UI(codepoint,0x0080) && RF_HEXLE_UI(codepoint,0x07ff))
{
// get the first bits of the first byte and encode them to the first byte
str->bytes[1] = (codepoint & 0x3F)|(0x02<<6);
// get the 5 following bits and encode them in the second byte
str->bytes[0] = ((codepoint & 0x7C0) >> 6) | (0x6<<5);
str->bytes[2] = '\0';
str->byteLength = 2;
}
// if we need 3 bytes to encode it
else if( RF_HEXGE_UI(codepoint,0x0800) && RF_HEXLE_UI(codepoint,0x0ffff))
{
// get the first bits of the first byte and encode them to the first byte
str->bytes[2] = (codepoint & 0x3F)|(0x02<<6);
// get the 6 following bits and encode them in the second byte
str->bytes[1] = ((codepoint & 0xFC0) >> 6) | (0x02<<6);
// get the 4 following bits and encode them in the third byte
str->bytes[0] = (((codepoint & 0xF000))>>12) | (0xE<<4);
str->bytes[3] = '\0';
str->byteLength = 3;
}
// if we need 4 bytes to encode it
else if( RF_HEXGE_UI(codepoint,0x10000) && RF_HEXLE_UI(codepoint,0x10ffff))
{
// get the first bits of the first byte and encode them to the first byte
str->bytes[3] = (codepoint & 0x3F)|(0x02<<6);
// get the 6 following bits and encode them in the second byte
str->bytes[2] = ((codepoint & 0xFC0) >> 6) | (0x02<<6);
// get the 6 following bits and encode them in the third byte
str->bytes[1] = (((codepoint & 0x3F000))>>12) | (0x02<<6);
// get the 3 following bits and encode them in the fourth byte
str->bytes[0] = (((codepoint & 0x1C0000))>>18) | (0x1E<<3);
str->bytes[4] = '\0';
str->byteLength = 4;
}
else
{
LOG_ERROR("Attempted to encode an invalid unicode code point into a string",RE_UTF8_INVALID_CODE_POINT);
return false;
}
return true;
}
// Allocates and returns a string with the given characters. NO VALID-UTF8 check is performed
#ifndef RF_OPTION_DEFAULT_ARGUMENTS
RF_String* rfString_Create_nc(const char* s,...)
#else
RF_String* i_rfString_Create_nc(const char* s,...)
#endif
{
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
// get the formatted string
READ_VSNPRINTF_ARGS(s,s,0);
// get the lengt of the byte buffer
ret->byteLength = bytesWritten;
// now that we know the length we can allocate the buffer and copy the bytes
RF_MALLOC(ret->bytes,ret->byteLength+1);
memcpy(ret->bytes,buff,ret->byteLength+1);
if(buffAllocated)
free(buff);
return ret;
}
#ifdef RF_OPTION_DEFAULT_ARGUMENTS
RF_String* i_NVrfString_Create_nc(const char* s)
{
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
// get length
ret->byteLength = strlen(s);
// now that we know the length we can allocate the buffer and copy the bytes
RF_MALLOC(ret->bytes,ret->byteLength+1);
memcpy(ret->bytes,s,ret->byteLength+1);
return ret;
}
#endif
// Initializes a string with the given characters. NO VALID-UTF8 check is performed
#ifndef RF_OPTION_DEFAULT_ARGUMENTS
char rfString_Init_nc(struct RF_String* str,const char* s,...)
#else
char i_rfString_Init_nc(struct RF_String* str,const char* s,...)
#endif
{
// get the formatted string
READ_VSNPRINTF_ARGS(s,s,false)
// get its length
str->byteLength = bytesWritten;
// now that we know the length we can allocate the buffer and copy the bytes
RF_MALLOC(str->bytes,str->byteLength+1);
memcpy(str->bytes,buff,str->byteLength+1);
if(buffAllocated == true)
free(buff);
return true;
}
#ifdef RF_OPTION_DEFAULT_ARGUMENTS
char i_NVrfString_Init_nc(struct RF_String* str,const char* s)
{
// get its length
str->byteLength = strlen(s);
// now that we know the length we can allocate the buffer and copy the bytes
RF_MALLOC(str->bytes,str->byteLength+1);
memcpy(str->bytes,s,str->byteLength+1);
return true;
}
#endif
/*-------------------------------------------------------------------------Methods to get rid of an RF_String-------------------------------------------------------------------------------*/
// Deletes a string object and also frees its pointer.It is an error to give a NULL(0x0) string for deleting. Will most probably lead to a segmentation fault
void rfString_Destroy(RF_String* s)
{
free(s->bytes);
free(s);
}
// Deletes a string object only, not its memory.It is an error to give a NULL(0x0) string for deleting. Will most probably lead to a segmentation fault
void rfString_Deinit(RF_String* s)
{
free(s->bytes);
}
/*------------------------------------------------------------------------ RF_String unicode conversio functions-------------------------------------------------------------------------------*/
// Returns the strings contents as a UTF-16 buffer
uint16_t* rfString_ToUTF16(RF_String* s,uint32_t* length)
{
uint32_t* codepoints,charsN;
// get the unicode codepoints, no check here since RF_String is always guaranteed to have valid UTF=8 and as such valid codepoints
codepoints = rfUTF8_Decode(s->bytes,s->byteLength,&charsN);
// encode them in UTF-16, no check here since it comes from an RF_String which is always guaranteed to have valid UTF-8 and as such valid codepoints
return rfUTF16_Encode(codepoints,charsN,length);
}
// Returns the strings contents as a UTF-32 buffer
uint32_t* rfString_ToUTF32(RF_String* s,uint32_t* length)
{
// get the unicode codepoints, no check here since RF_String is always guaranteed to have valid UTF=8 and as such valid codepoints
return rfUTF8_Decode(s->bytes,s->byteLength,length);
}
/*------------------------------------------------------------------------ RF_String retrieval functions-------------------------------------------------------------------------------*/
// Finds the length of the string in characters
uint32_t rfString_Length(void* str)
{
RF_String* s = (RF_String*)str;
uint32_t length,i;
RF_STRING_ITERATE_START(s,length,i)
RF_STRING_ITERATE_END(length,i);
return length;
}
// Retrieves the unicode code point of the parameter character.
uint32_t rfString_GetChar(void* str,uint32_t c)
{
RF_String* thisstr = (RF_String*)str;
uint32_t length,i;
uint32_t codePoint = RF_STRING_INDEX_OUT_OF_BOUNDS;
RF_STRING_ITERATE_START(thisstr,length,i)
// if we found the character,inspect the 4 different cases
if(length == c)
{
// take the codepoint from the byte position and break from the loop
codePoint = rfString_BytePosToCodePoint(thisstr,i);
break;
}
RF_STRING_ITERATE_END(length,i)
// and return the code point. Notice that if the character was not found this will return RF_STRING_INDEX_OUT_OF_BOUNDS
return codePoint;
}
// Retrieves the unicode code point of the parameter bytepos of the string. If the byte position is not the start of a character 0 is returned. This is an internal function, there is no need to use it. <i>Can be used with StringX</i>
uint32_t rfString_BytePosToCodePoint(void* str,uint32_t i)
{
uint32_t codePoint=0;
RF_String* thisstr = (RF_String*)str;
// /Here I am not checking if byte position 'i' is withing bounds and especially if it is a start of a character
// / This is assumed to have been checked or to be known beforehand by the programmer. That's one of the reasons
// / why this is an internal function and should not be used unless you know what you are doing
// if the lead bit of the byte is 0 then range is : U+0000 to U+0007F (1 byte)
if( ((thisstr->bytes[i] & 0x80)>>7) == 0 )
{
// and the code point is this whole byte only
codePoint = thisstr->bytes[i];
}
// if the leading bits are in the form of 0b110xxxxx then range is: U+0080 to U+07FF (2 bytes)
else if ( RF_HEXEQ_C( ( (~(thisstr->bytes[i] ^ 0xC0))>>5),0x7) )
{
codePoint =0;
// from the second byte take the first 6 bits
codePoint = (thisstr->bytes[i+1] & 0x3F) ;
// from the first byte take the first 5 bits and put them in the start
codePoint |= ((thisstr->bytes[i] & 0x1F) << 6);
}
// if the leading bits are in the form of 0b1110xxxx then range is U+0800 to U+FFFF (3 bytes)
else if( RF_HEXEQ_C( ( (~(thisstr->bytes[i] ^ 0xE0))>>4),0xF) )
{
codePoint = 0;
// from the third byte take the first 6 bits
codePoint = (thisstr->bytes[i+2] & 0x3F) ;
// from the second byte take the first 6 bits and put them to the left of the previous 6 bits
codePoint |= ((thisstr->bytes[i+1] & 0x3F) << 6);
// from the first byte take the first 4 bits and put them to the left of the previous 6 bits
codePoint |= ((thisstr->bytes[i] & 0xF) << 12);
}
// if the leading bits are in the form of 0b11110xxx then range is U+010000 to U+10FFFF (4 bytes)
else if( RF_HEXEQ_C( ( (~(thisstr->bytes[i] ^ 0xF0))>>3), 0x1F))
{
codePoint = 0;
// from the fourth byte take the first 6 bits
codePoint = (thisstr->bytes[i+3] & 0x3F) ;
// from the third byte take the first 6 bits and put them to the left of the previous 6 bits
codePoint |= ((thisstr->bytes[i+2] & 0x3F) << 6);
// from the second byte take the first 6 bits and put them to the left of the previous 6 bits
codePoint |= ((thisstr->bytes[i+1] & 0x3F) << 12);
// from the first byte take the first 3 bits and put them to the left of the previous 6 bits
codePoint |= ((thisstr->bytes[i] & 0x7) << 18);
}
return codePoint;
}
// Retrieves character position of a byte position
uint32_t rfString_BytePosToCharPos(void* thisstrP,uint32_t bytepos,char before)
{
// /here there is no check if this is actually a byte pos inside the string's
// /byte buffer. The programmer should have made sure it is before hand. This is why it is
// / an internal function and should only be used if you know what you are doing
RF_String* thisstr = (RF_String*)thisstrP;
uint32_t charPos = 0;
uint32_t byteI = 0;
// iterate the string's bytes until you get to the required byte
// if it is not a continuation byte, return the position
if(rfUTF8_IsContinuationByte(thisstr->bytes[bytepos])==false)
{
RF_STRING_ITERATE_START(thisstr,charPos,byteI)
if(byteI == bytepos)
return charPos;
RF_STRING_ITERATE_END(charPos,byteI)
}
// else iterate the string's bytes until you get anything bigger than the required byte
RF_STRING_ITERATE_START(thisstr,charPos,byteI)
if(byteI > bytepos)
break;
RF_STRING_ITERATE_END(charPos,byteI)
// if we need the previous one return it
if(before == true)
return charPos-1;
// else return this
return charPos;
}
// Compares two Strings and returns true if they are equal and false otherwise
char i_rfString_Equal(void* s1P,void* s2P)
{
RF_String* s1 = (RF_String*)s1P;
RF_String* s2 = (RF_String*)s2P;
if( strcmp(s1->bytes,s2->bytes)==0)
{
return true;
}
return false;
}
// Finds the existence of String sstr inside this string, either matching case or not
int32_t i_rfString_Find(const void* str,const void* sstrP,const char* optionsP)
{
// / @note TO SELF: If I make any changes to this function do not forget to change the private version that returns byte position too
// / located at string_private.c and called rfString_FindByte and rfString_FindByte_s
RF_String* thisstr = (RF_String*)str;
RF_String* sstr = (RF_String*)sstrP;
char options = *optionsP;
char* found = 0;
// if we want to match the case of the string then it's a simple search of matching characters
if( (RF_BITFLAG_ON( options,RF_CASE_IGNORE)) == false)
{
// if it is not found
if( (found = strstr(thisstr->bytes,sstr->bytes)) == 0)
{
return RF_FAILURE;
}
// get the byte position
uint32_t bytepos = found-thisstr->bytes;
// if we need the exact string as it is given
if(RF_BITFLAG_ON( options,RF_MATCH_WORD))
{
// check before the found string
if(bytepos != 0)
{
// if is is not a character
switch(thisstr->bytes[bytepos-1])
{
case ' ':case '\t':case '\n':
break;
default:
return RF_FAILURE;
break;
}
}
// check after the found string
if(bytepos+sstr->byteLength != thisstr->byteLength)
{
// if is is not a character
switch(thisstr->bytes[bytepos+sstr->byteLength])
{
case ' ':case '\t':case '\n':
break;
default:
return RF_FAILURE;
break;
}
}
}// end of the exact string option
// success
return rfString_BytePosToCharPos(thisstr,bytepos,false);
}
// else ignore case matching
uint32_t i,j;
// if(cstr[0] >= 0x41 && cstr[0] <= 0x5a)
for(i=0;i<thisstr->byteLength; i ++)
{
// if i matches the start of the substring
for(j = 0; j < sstr->byteLength; j++)
{
// if the jth char is a big letter
if(sstr->bytes[j] >= 0x41 && sstr->bytes[j] <= 0x5a)
{
// no match
if(sstr->bytes[j] != thisstr->bytes[i+j] && sstr->bytes[j]+32 != thisstr->bytes[i+j])
break;
// there is a match in the jth character so let's perform additional checks if needed
if(RF_BITFLAG_ON( options,RF_MATCH_WORD))
{
// if it's the first substring character and if the string we search is not in it's beginning, check for EXACT string before
if(j == 0 && i != 0)
{
switch(thisstr->bytes[i-1])
{
case ' ':case '\t':case '\n':
break;
default:
return RF_FAILURE;
break;
}
}
}// exact string check if ends
}
// small letter
else if(sstr->bytes[j] >= 0x61 && sstr->bytes[j] <= 0x7a)
{
// no match
if(sstr->bytes[j] != thisstr->bytes[i+j] && sstr->bytes[j]-32 != thisstr->bytes[i+j])
break;
// there is a match in the jth character so let's perform additional checks if needed
if(RF_BITFLAG_ON(options,RF_MATCH_WORD))
{
// if it's the first substring character and if the string we search is not in it's beginning, check for EXACT string before
if(j == 0 && i != 0)
{
switch(thisstr->bytes[i-1])
{
case ' ':case '\t':case '\n':
break;
default:
return RF_FAILURE;
break;
}
}
}// exact string check if ends
}
// not a letter and no match
else if(sstr->bytes[j] != thisstr->bytes[i+j])
break;// break off the substring search loop
// if we get here and it's the last char of the substring we either found it or need to perform one last check for exact string
if(j == sstr->byteLength-1)
{
// only if the end of the string is not right after the substring
if( RF_BITFLAG_ON(options,RF_MATCH_WORD) && i+sstr->byteLength < thisstr->byteLength)
{
switch(thisstr->bytes[i+sstr->byteLength])
{
case ' ':case '\t':case '\n':
break;
default:
return RF_FAILURE;
break;
}
}// end of the exact string check
// succes
return rfString_BytePosToCharPos(thisstr,i,false);
}// end of it's the last char of the substring check
}// substring iteration ends
}// this string iteration ends
return RF_FAILURE;
}
// Returns the integer value of the string if and only if it contains only numbers. If it contains anything else the function fails.
char rfString_ToInt(void* str,int32_t* v)
{
RF_String* thisstr = (RF_String*)str;
char* end;
// get the integer
*v = strtol ( thisstr->bytes, &end,10);
// /This is the non-strict case. Takes the number out of the string no matter what else it has inside
/* // if we did get something
if(strlen(end) < this->length())
return true;
*/
// /This is the strict case, and the one we will go with. The non-strict case might be moved to its own function, if ever in the future
if(end[0] == '\0')
return true;
// else false
return false;
}
// Returns the float value of a String
int rfString_ToDouble(void* thisstrP,double* f)
{
RF_String* str = (RF_String*)thisstrP;
*f = strtod(str->bytes,NULL);
// check the result
if(*f == 0.0)
{
// if it's zero and the string equals to zero then we are okay
if(rfString_Equal(str,RFS_("0")) || rfString_Equal(str,RFS_("0.0")))
return RF_SUCCESS;
// underflow error
if(errno == ERANGE)
return RE_STRING_TOFLOAT_UNDERFLOW;
// in any other case it's a conversion error
return RE_STRING_TOFLOAT;
}
// if the result is a HUGE_VAL and errno is set,the number is not representable by a double
if(*f == HUGE_VAL && errno == ERANGE)
return RE_STRING_TOFLOAT_RANGE;
// any other case success
return RF_SUCCESS;
}
// Returns a cstring version of the string.
const char* rfString_ToCstr(const void* str)
{
RF_String* thisstr = (RF_String*)str;
return thisstr->bytes;
}
// Creates and returns an allocated copy of the given string
RF_String* rfString_Copy_OUT(void* srcP)
{
RF_String* src = (RF_String*)srcP;
// create the new string
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
// get the length
ret->byteLength = src->byteLength;
// copy the bytes
RF_MALLOC(ret->bytes,ret->byteLength+1);
memcpy(ret->bytes,src->bytes,ret->byteLength+1);
return ret;
}
// Copies all the contents of a string to another
void rfString_Copy_IN(RF_String* dst,void* srcP)
{
RF_String* src = (RF_String*)srcP;
// get the length
dst->byteLength = src->byteLength;
// copy the bytes
RF_MALLOC(dst->bytes,src->byteLength+1);
memcpy(dst->bytes,src->bytes,dst->byteLength+1);
return;
}
// Copies a certain number of characters from a string
void rfString_Copy_chars(RF_String* dst,void* srcP,uint32_t charsN)
{
uint32_t i = 0,bytePos;
RF_String* src = (RF_String*)srcP;
// find the byte position until which we need to copy
RF_STRING_ITERATE_START(src,i,bytePos)
if(i == charsN)
break;
RF_STRING_ITERATE_END(i,bytePos)
dst->byteLength = bytePos;
RF_MALLOC(dst->bytes,dst->byteLength+1);
memcpy(dst->bytes,src->bytes,dst->byteLength+1);
dst->bytes[dst->byteLength] = '\0';// null terminate it
}
// Applies a limited version of sscanf after the specified substring
char i_rfString_ScanfAfter(void* str,void* afterstrP,const char* format,void* var)
{
RF_String* thisstr = (RF_String*)str;
RF_String* afterstr = (RF_String*)afterstrP;
// return false if the substring is not found
char* found,*s;
if( (found = strstr(thisstr->bytes,afterstr->bytes)) ==0 )
{
return false;
}
// get a pointer to the start of the position where sscanf will be used
s = thisstr->bytes + (found-thisstr->bytes+afterstr->byteLength);
// use sscanf
if(sscanf(s,format,var) <=0)
{
return false;
}
return true;
}
// Counts how many times a substring s occurs inside the string
int32_t i_rfString_Count(void* str,void* sstr2,const char* optionsP)
{
RF_String* thisstr = (RF_String*)str;
RF_String* sstr = (RF_String*)sstr2;
char options = *optionsP;
int32_t index = 0;
int32_t move;
int32_t n = 0;
// as long as the substring is found in the string
while ((move = rfString_FindBytePos(thisstr,sstr,options)) != RF_FAILURE)
{
move+= sstr->byteLength;
// proceed searching inside the string and also increase the counter
n++;
thisstr->bytes+=move;
index +=move;
thisstr->byteLength -=move;
}
// return string to its original state and return the number of occurences, also returns 0 if not found
thisstr->bytes-=index;
thisstr->byteLength += index;
// success
return n;
}
// Tokenizes the given string. Separates it into @c tokensN depending on how many substrings can be created from the @c sep separatior and stores them
// into the Array of RF_String* that should be passed to the function
i_DECLIMEX_ char rfString_Tokenize(void* str,char* sep,uint32_t* tokensN,RF_String** tokens)
{
RF_String* thisstr = (RF_String*)str;
uint32_t i;
// first find the occurences of the separator, and then the number of tokens
*tokensN = rfString_Count(thisstr,RFS_(sep),0)+1;
// error checking
if(*tokensN == 0)
return false;
// allocate the tokens
RF_MALLOC(*tokens,sizeof(RF_String) *(*tokensN));
// find the length of the separator
uint32_t sepLen = strlen(sep);
char* s,*e;
s = thisstr->bytes;
for(i = 0; i < (*tokensN)-1; i ++)
{
// find each substring
e = strstr(s,sep);
(*tokens)[i].byteLength = e-s;
RF_MALLOC((*tokens)[i].bytes,(*tokens)[i].byteLength+1);
// put in the data
strncpy((*tokens)[i].bytes,s,(*tokens)[i].byteLength);
// null terminate
(*tokens)[i].bytes[(*tokens)[i].byteLength] = '\0';
// prepare for next sub-string
s = e+sepLen;
}
// /make sure that if it's the last substring we change strategy
(*tokens)[i].byteLength = strlen(s);
RF_MALLOC((*tokens)[i].bytes,(*tokens)[i].byteLength+1);
// put in the data
strncpy((*tokens)[i].bytes,s,(*tokens)[i].byteLength);
// null terminate
(*tokens)[i].bytes[(*tokens)[i].byteLength] = '\0';
// success
return true;
}
// Initializes the given string as the first substring existing between the left and right parameter substrings.
char i_rfString_Between(void* thisstrP,void* lstrP,void* rstrP,RF_String* result,const char* optionsP)
{
int32_t start,end;
RF_String* thisstr = (RF_String*)thisstrP;
RF_String* lstr = (RF_String*)lstrP;
RF_String* rstr = (RF_String*)rstrP;
char options = *optionsP;
RF_String temp;
// find the left substring
if( (start = rfString_FindBytePos(thisstr,lstr,options))== RF_FAILURE)
{
return false;
}
// get what is after it
rfString_After(thisstr,lstr,&temp,options);
// find the right substring in the remaining part
if( (end = rfString_FindBytePos(&temp,rstr,options))== RF_FAILURE)
{
return false;
}
// free temp string
rfString_Deinit(&temp);
// initialize the string to return
result->byteLength = end;
RF_MALLOC(result->bytes,result->byteLength+1);
memcpy(result->bytes,thisstr->bytes+start+lstr->byteLength,result->byteLength+1);
result->bytes[end]= '\0';
// success
return true;
}
// Initializes the given string as the substring from the start until any of the given Strings are found.
#ifndef RF_OPTION_DEFAULT_ARGUMENTS
char rfString_Beforev(void* thisstrP,RF_String* result,const char* optionsP,const unsigned char* parNP, ...)
#else
char i_rfString_Beforev(void* thisstrP,RF_String* result,const char* optionsP,const unsigned char* parNP, ...)
#endif
{
RF_String* thisstr = (RF_String*)thisstrP;
RF_String* s;
char options = *optionsP;
unsigned char parN = *parNP;
int32_t i,minPos,thisPos;
// will keep the argument list
va_list argList;
// get the parameter characters
va_start(argList,parNP);
minPos = 9999999;
for(i = 0; i < parN; i++)
{
s = (RF_String*) va_arg(argList,RF_String*);
if( (thisPos= rfString_FindBytePos(thisstr,s,options))!= RF_FAILURE)
{
if(thisPos < minPos)
minPos = thisPos;
}
}
va_end(argList);
// if it is not found
if(minPos == 9999999)
{
return false;
}
// if it is found initialize the substring
result->byteLength = minPos;
RF_MALLOC(result->bytes,minPos+1);
memcpy(result->bytes,thisstr->bytes,minPos);
result->bytes[minPos] = '\0';
// success
return true;
}
// Initializes the given string as the substring from the start until the given string is found
char i_rfString_Before(void* thisstrP,void* sstrP,RF_String* result,const char* optionsP)
{
RF_String* thisstr = (RF_String*)thisstrP;
RF_String* sstr = (RF_String*) sstrP;
char options = *optionsP;
int32_t ret;
// find the substring
if( (ret = rfString_FindBytePos(thisstr,sstr,options)) == RF_FAILURE)
{
return false;
}
// if it is found get the result initialize the substring
result->byteLength = ret;
RF_MALLOC(result->bytes,result->byteLength+1);
memcpy(result->bytes,thisstr->bytes,result->byteLength);
result->bytes[result->byteLength] = '\0';
// success
return true;
}
// Initializes the given String with the substring located after (and not including) the after substring inside the parameter string. If the substring is not located the function returns false.
char i_rfString_After(void* thisstrP,void* afterP,RF_String* out,const char* optionsP)
{
RF_String* thisstr = (RF_String*)thisstrP;
RF_String* after = (RF_String*)afterP;
char options = *optionsP;
int32_t bytePos;
// check for substring existence
if( (bytePos = rfString_FindBytePos(thisstr,after,options)) == RF_FAILURE)
{
return false;
}
// done so let's get it. Notice the use of the non-checking initialization
rfString_Init_nc(out,thisstr->bytes+bytePos+after->byteLength);
// success
return true;
}
// Initialize a string after the first of the given substrings found
#ifndef RF_OPTION_DEFAULT_ARGUMENTS
char rfString_Afterv(void* thisstrP,RF_String* result,const char* optionsP,const unsigned char* parNP,...)
#else
char i_rfString_Afterv(void* thisstrP,RF_String* result,const char* optionsP,const unsigned char* parNP,...)
#endif
{
RF_String* thisstr = (RF_String*)thisstrP;
RF_String* s;
char options = *optionsP;
unsigned char parN = *parNP;
int32_t i,minPos,thisPos;
uint32_t minPosLength;
// will keep the argument list
va_list argList;
// get the parameter characters
va_start(argList,parNP);
minPos = 9999999;
for(i = 0; i < parN; i++)
{
s = (RF_String*) va_arg(argList,RF_String*);
if( (thisPos= rfString_FindBytePos(thisstr,s,options))!= RF_FAILURE)
{
if(thisPos < minPos)
{
minPos = thisPos;
minPosLength = s->byteLength;
}
}
}
va_end(argList);
// if it is not found
if(minPos == 9999999)
{
return false;
}
// if it is found initialize the substring
minPos += minPosLength;// go after the found substring
result->byteLength = thisstr->byteLength-minPos;
RF_MALLOC(result->bytes,result->byteLength);
memcpy(result->bytes,thisstr->bytes+minPos,result->byteLength);
result->bytes[result->byteLength] = '\0';
// success
return true;
}
/*------------------------------------------------------------------------ RF_String manipulation functions-------------------------------------------------------------------------------*/
// Appends the parameter String to this one
void i_rfString_Append(RF_String* thisstr,void* otherP)
{
RF_String* other = (RF_String*)otherP;
// /@note Here if a null addition is given lots of actions are done but the result is safe and the same string as the one entered.
// /A check here would result in an additional check for every appending so I decided against it
// calculate the new length
thisstr->byteLength +=other->byteLength;
// reallocate this string to fit the new addition
RF_REALLOC(thisstr->bytes,char,thisstr->byteLength+1);
// add the string to this one
strncat(thisstr->bytes,other->bytes,other->byteLength);
}
// Appends an integer to the string
void rfString_Append_i(RF_String* thisstr,const int32_t i)
{
// create a new buffer for the string big enough to fit any number plus the original string
char* buff;
RF_MALLOC(buff,thisstr->byteLength+15);// max uint32_t is 4,294,967,295 in most environment so 12 chars will certainly fit it
// put the int32_t inside the string
sprintf(buff,"%s%i",thisstr->bytes,i);
// free the previous c string
free(thisstr->bytes);
// point the string pointer to the new string
thisstr->bytes = buff;
thisstr->byteLength = strlen(thisstr->bytes);
}
// Appends a float to the string. <b>Can't be used with RF_StringX</b>
void rfString_Append_f(RF_String* thisstr,const float f)
{
// a temporary buffer to hold the float and the string
char* buff;
RF_MALLOC(buff,thisstr->byteLength+64);
// put the float inside the string
sprintf(buff,"%s%f",thisstr->bytes,f);
// free the previous c string
free(thisstr->bytes);
// point the string pointer to the new string
thisstr->bytes = buff;
thisstr->byteLength = strlen(thisstr->bytes);
}
// Prepends the parameter String to this string
void i_rfString_Prepend(RF_String* thisstr,void* otherP)
{
RF_String* other = (RF_String*)otherP;
uint32_t size;
int32_t i;// is not unsigned since it goes to -1 in the loop
// keeep the original byte size of the string
size = thisstr->byteLength;
// calculate the new lengths
thisstr->byteLength += other->byteLength;
// reallocate this string to fit the new addition
RF_REALLOC(thisstr->bytes,char,thisstr->byteLength+1);
// move the pre-existing string to the end of the buffer, by dislocating each byte by cstrlen
for(i =size; i >=0 ; i--)
thisstr->bytes[i+other->byteLength] = thisstr->bytes[i];
// and now add the new string to the start
memcpy(thisstr->bytes,other->bytes,other->byteLength);
}
// Removes all of the specifed string occurences from this String matching case or not, DOES NOT reallocate buffer size.
char i_rfString_Remove(void* thisstrP,void* rstrP,uint32_t* numberP,const char* optionsP)
{
RF_String* thisstr = (RF_String*)thisstrP;
RF_String* rstr = (RF_String*)rstrP;
char options = *optionsP;
uint32_t number = *numberP;
uint32_t i,count,occurences=0;
int32_t bytePos;
char found = false;
// as long as we keep finding rstr in the string keep removing it
do
{ // if the substring is not found
if( (bytePos = rfString_FindBytePos(thisstr,rstr,options)) == RF_FAILURE)
{
// if we have not even found it once , we fail
if(found == false)
{
return false;
}
else // else we are done
break;
}
// substring found
found = true;
// move all of the string a position back
count = 0;
for(i = bytePos; i <=thisstr->byteLength; i ++)
{
thisstr->bytes[i] = thisstr->bytes[i+rstr->byteLength];
count++;
}
// now change the byte length
thisstr->byteLength -= rstr->byteLength;
// count the number of occurences and if we reached the required amount, stop
occurences++;
if(occurences == number)
break;
}while(bytePos != RF_FAILURE);
// succcess
return true;
}
// Removes all of the characters of the string except those specified
void i_rfString_KeepOnly(void* thisstrP,void* keepstrP)
{
uint32_t keepLength,i,j,charValue,temp;
uint32_t *keepChars;
RF_String* thisstr = (RF_String*)thisstrP;
RF_String* keepstr = (RF_String*)keepstrP;
char exists,charBLength;
// first let's get all of the characters of the keep string in an array
i=0;
keepLength = rfString_Length(keepstr);
RF_MALLOC(keepChars,4*keepLength);
rfString_Iterate_Start(keepstr,i,charValue)
keepChars[i] = charValue;
rfString_Iterate_End(i)
// now iterate every character of this string
i=0;
rfString_Iterate_Start(thisstr,i,charValue)
// for every character check if it exists in the keep str
exists = false;
for(j=0;j<keepLength; j++)
{
if(keepChars[j] == charValue)
exists = true;
}
// if it does not exist, move the string back to cover it so that it effectively gets deleted
if(exists == false)
{
charBLength = rfUTF8_FromCodepoint(charValue,&temp);
// this is kind of a non-clean way to do it. the rfString_Iterate_Start macro internally uses a byteIndex_ variable
// we use that here to determine the current byteIndex_ of the string in the iteration and move the string backs
memmove(thisstr->bytes+byteIndex_,thisstr->bytes+byteIndex_+charBLength,thisstr->byteLength-byteIndex_+charBLength);
thisstr->byteLength-=charBLength;
continue;// by contiuing here we make sure that the current string position won't be moved to assure that we also check the newly move characters
}
rfString_Iterate_End(i)
// before returning free the keep string's character array
free(keepChars);
}
// Removes the first n characters from the start of the string
char rfString_PruneStart(void* thisstrP,uint32_t n)
{
RF_String* thisstr = (RF_String*)thisstrP;
// iterate the characters of the string
uint32_t i;
uint32_t length = 0;
unsigned nBytePos = 0;
char found = false;
RF_STRING_ITERATE_START(thisstr,length,i);
// if we reach the number of characters passed as a parameter, note it
if(length == n)
{
// remember that now i is the byte position we need
nBytePos = i;
found = true;
break;
}
RF_STRING_ITERATE_END(length,i)
// if the string does not have n chars to remove it becomes an empty string and we return failure
if(found == false)
{
thisstr->bytes[0] = '\0';
thisstr->byteLength = 0;
return false;
}
// move the string back to cover the empty places.reallocation here would be an overkill, everything will be freed together when the string gets freed
for(i =0; i < thisstr->byteLength-nBytePos+1;i++ )
thisstr->bytes[i] = thisstr->bytes[i+nBytePos];
// get the new bytelength
thisstr->byteLength -= nBytePos;
return true;
}
// Removes the last n characters from the end of the string
char rfString_PruneEnd(void* thisstrP,uint32_t n)
{
RF_String* thisstr = (RF_String*)thisstrP;
// start the iteration of the characters from the end of the string
int32_t nBytePos = -1;
uint32_t length,i;
RF_STRING_ITERATEB_START(thisstr,length,i)
// if we found the requested number of characters from the end of the string
if(length == n)
{
// remember that now i is the byte position we need
nBytePos = i;
break;
}
RF_STRING_ITERATEB_END(length,i)
// if the string does not have n chars to remove it becomes an empty string and we return failure
if(nBytePos == -1)
{
thisstr->bytes[0] = '\0';
return false;
}
// just set the end of string character characters back, reallocation here would be an overkill, everything will be freed together when the string gets freed
thisstr->bytes[nBytePos] = '\0';
// and also set the new byte length
thisstr->byteLength -= (thisstr->byteLength - nBytePos);
// success
return true;
}
// Removes n characters from the position p of the string counting backwards. If there is no space to do so, nothing is done and returns false.
char rfString_PruneMiddleB(void* thisstrP,uint32_t p,uint32_t n)
{
RF_String* thisstr = (RF_String*)thisstrP;
// if we ask to remove more characters from the position that it would be possible do nothign and return false
if(n>p+1)
return false;
// iterate the characters of the string
uint32_t j,i,length;
int32_t pBytePos,nBytePos;
pBytePos = nBytePos = -1;
RF_STRING_ITERATE_START(thisstr,length,i)
// if we reach the number of characters passed as a parameter, note it
if(length == p+1)
{
// we search for p+1 because we want to include all of the p character
pBytePos = i;
// also break since we don't care after position p
break;
}
if(length == p-n+1)// +1 is to make sure that indexing works from 0
nBytePos = i;
RF_STRING_ITERATE_END(length,i)
// if the position was not found in the string do nothing
if(pBytePos == -1 || nBytePos == -1)
return false;
// move the bytes in the buffer to remove the requested characters
for(i=nBytePos,j=0;j<= thisstr->byteLength-pBytePos+1; i ++,j++) // here +2 is for (+1 for pbytePos to go to the start of pth character) (+1 for the byteLength to include the null termination character)
{
thisstr->bytes[i] = thisstr->bytes[pBytePos+j];
}
// find the new byte length
thisstr->byteLength -= (nBytePos - pBytePos);
return true;
}
// Removes n characters from the position p of the string counting forwards. If there is no space, nothing is done and returns false.
char rfString_PruneMiddleF(void* thisstrP,uint32_t p,uint32_t n)
{
RF_String* thisstr = (RF_String*)thisstrP;
// iterate the characters of the string
uint32_t j,i,length;
int32_t pBytePos,nBytePos;
pBytePos = nBytePos = -1;
RF_STRING_ITERATE_START(thisstr,length,i)
// if we reach the number of characters passed as a parameter, note it
if(length == p)
pBytePos = i;
if(length == p+n)
{
nBytePos = i;
break;// since we got all the data we needed
}
RF_STRING_ITERATE_END(length,i)
// if the position was not found in the string do nothing
if(pBytePos == -1 )
return false;
// if we did not find the byte position of p+n then we remove everything from pBytePos until the end of the string
if(nBytePos == -1)
{
thisstr->bytes[pBytePos] = '\0';
thisstr->byteLength -= (thisstr->byteLength-pBytePos);
return true;
}
// move the bytes in the buffer to remove the requested characters
for(i=pBytePos,j=0;j<= thisstr->byteLength-nBytePos+1; i ++,j++) // here +2 is for (+1 for pbytePos to go to the start of pth character) (+1 for the byteLength to include the null termination character)
{
thisstr->bytes[i] = thisstr->bytes[nBytePos+j];
}
// find the new byte length
thisstr->byteLength -= (nBytePos - pBytePos);
return true;
}
// Replaces all of the specified sstr substring from the String with rstr and reallocates size, unless the new size is smaller
char i_rfString_Replace(RF_String* thisstr,void* sstrP,void* rstrP,const uint32_t* numP,const char* optionsP)
{
RF_String* sstr = (RF_String*)sstrP;
RF_String* rstr = (RF_String*)rstrP;
char options = *optionsP;
uint32_t num = *numP;
RF_StringX temp;// just a temporary string for finding the occurences
// will keep the number of found instances of the substring
uint32_t foundN = 0;
// will keep the number of given instances to find
uint32_t number = num;
uint32_t diff,i,j;
// if the substring string is not even found return false
if(rfString_FindBytePos(thisstr,sstr,options) == RF_FAILURE)
{
return false;
}
// create a buffer that will keep the byte positions
uint32_t bSize = 50;
int32_t * bytePositions;
RF_MALLOC(bytePositions,bSize*sizeof(int32_t));
// if the given num is 0 just make sure we replace all
if(number == 0)
number = 999999;// max number of occurences
// find how many occurences exist
rfStringX_FromString_IN(&temp,thisstr);
while( (bytePositions[foundN] = rfString_FindBytePos(&temp,sstr,options)) != RF_FAILURE)
{
int32_t move = bytePositions[foundN] + sstr->byteLength;
bytePositions[foundN] = bytePositions[foundN]+temp.bIndex;
temp.bIndex += move;
temp.bytes += move;
temp.byteLength -= move;
foundN++;
// if buffer is in danger of overflow realloc it
if(foundN > bSize)
{
bSize *=2;
RF_REALLOC(bytePositions,int32_t,bSize);
}
// if we found the required number of occurences break;
if(foundN >= number)
break;
}
rfStringX_Deinit(&temp);
// make sure that the number of occurence to replace do not exceed the actual number of occurences
if(number > foundN)
number = foundN;
// act depending on the size difference of rstr and sstr
if(rstr->byteLength > sstr->byteLength) // replace string is bigger than the removed one
{
int32_t orSize,nSize;
diff = rstr->byteLength - sstr->byteLength;
// will keep the original size in bytes
orSize = thisstr->byteLength +1;
// reallocate the string to fit the new bigger size
nSize= orSize + number*diff;
RF_REALLOC(thisstr->bytes,char,nSize)
// now replace all the substrings one by one
for(i = 0; i < number; i ++)
{
// move all of the contents of the string to fit the replacement
for(j =orSize+diff-1; j > bytePositions[i]+sstr->byteLength; j -- )
thisstr->bytes[j] = thisstr->bytes[j-diff];
// copy in the replacement
strncpy(thisstr->bytes+bytePositions[i],rstr->bytes,rstr->byteLength);
// also increase the original size (since now we moved the whole string by one replacement)
orSize += diff;
// also increase all the subsequent found byte positions since there is a change of string size
for(j = i+1; j < number; j ++)
bytePositions[j] = bytePositions[j]+diff;
}
// finally let's keep the new byte length
thisstr->byteLength = nSize-1;
}
else if( rstr->byteLength < sstr->byteLength) // replace string is smaller than the removed one
{
// get the differenc in byte length of removed substring and replace string
diff = sstr->byteLength-rstr->byteLength;
// now replace all the substrings one by one
for(i =0; i < number; i ++)
{
// copy in the replacement
strncpy(thisstr->bytes+bytePositions[i],rstr->bytes,rstr->byteLength);
// move all of the contents of the string to fit the replacement
for(j =bytePositions[i]+rstr->byteLength; j < thisstr->byteLength; j ++ )
thisstr->bytes[j] = thisstr->bytes[j+diff];
// also decrease all the subsequent found byte positions since there is a change of string size
for(j = i+1; j < number; j ++)
bytePositions[j] = bytePositions[j]-diff;
}
// finally let's keep the new byte length
thisstr->byteLength -= diff*number;
// just note that reallocating downwards is not necessary
}
else // replace and remove strings are equal
{
for(i = 0; i < number; i ++)
strncpy(thisstr->bytes+bytePositions[i],rstr->bytes,rstr->byteLength);
}
free(bytePositions);
// success
return true;
}
// Removes all characters of a substring only from the start of the String
char i_rfString_StripStart(void* thisstrP,void* subP)
{
RF_String* thisstr = (RF_String*) thisstrP;
RF_String*sub = (RF_String*) subP;
char ret = false,noMatch;
uint32_t charValue,i = 0,*subValues,j,subLength,bytePos;
// firstly get all of the characters of the substring in an array
subLength = rfString_Length(sub);
RF_MALLOC(subValues,4*subLength)
rfString_Iterate_Start(sub,i,charValue)
subValues[i] = charValue;
rfString_Iterate_End(i)
// iterate thisstring from the beginning
i = 0;
RF_STRING_ITERATE_START(thisstr,i,bytePos)
noMatch = true;
// for every substring character
for(j = 0;j < subLength; j++)
{
// if we got a match
if(rfString_BytePosToCodePoint(thisstr,bytePos) == subValues[j])
{
ret = true;
noMatch = false;
break;
}
}
// if we get out of iterating the substring without having found a match, we get out of the iteration in general
if(noMatch)
break;
RF_STRING_ITERATE_END(i,bytePos)
// if we had any match
if(ret == true)
{
// remove the characters
for(i =0; i < thisstr->byteLength-bytePos+1;i++ )
thisstr->bytes[i] = thisstr->bytes[i+bytePos];
// also change bytelength
thisstr->byteLength -= bytePos;
}
// free stuff and return
free(subValues);
return ret;
}
// Removes all characters of a substring starting from the end of the String
char i_rfString_StripEnd(void* thisstrP,void* subP)
{
RF_String* thisstr = (RF_String*) thisstrP;
RF_String*sub = (RF_String*) subP;
char ret = false,noMatch;
uint32_t charValue,i = 0,*subValues,j,subLength,bytePos,lastBytePos,testity;
// firstly get all of the characters of the substring in an array
subLength = rfString_Length(sub);
RF_MALLOC(subValues,4*subLength)
rfString_Iterate_Start(sub,i,charValue)
subValues[i] = charValue;
rfString_Iterate_End(i)
// iterate thisstring from the end
i = 0;
RF_STRING_ITERATEB_START(thisstr,i,bytePos)
noMatch = true;
// for every substring character
for(j = 0;j < subLength; j++)
{
// if we got a match
if((testity=rfString_BytePosToCodePoint(thisstr,bytePos)) == subValues[j])
{
ret = true;
noMatch = false;
lastBytePos = bytePos;
break;
}
}
// if we get out of iterating the substring without having found a match, we get out of the iteration in general
if(noMatch)
break;
RF_STRING_ITERATEB_END(i,bytePos)
// if we had any match
if(ret == true)
{
// just set the end of string there
thisstr->bytes[lastBytePos] = '\0';
// and also set the new byte length
thisstr->byteLength -= (thisstr->byteLength - lastBytePos);
}
// free stuff and return
free(subValues);
return ret;
}
// Removes all characters of a substring from both ends of the given String
char i_rfString_Strip(void* thisstrP,void* subP)
{
char res1 = rfString_StripStart(thisstrP,subP);
char res2 = rfString_StripEnd(thisstrP,subP);
return res1|res2;
}
/*------------------------------------------------------------------------ RF_String File I/O functions-------------------------------------------------------------------------------*/
// Allocates and returns a string from file parsing. The file's encoding must be UTF-8.If for some reason (like EOF reached) no string can be read then null is returned
RF_String* rfString_Create_fUTF8(FILE* f, char* eof)
{
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
if(rfString_Init_fUTF8(ret,f,eof) < 0)
{
free(ret);
return 0;
}
return ret;
}
// Initializes a string from file parsing. The file's encoding must be UTF-8.If for some reason (like EOF reached) no string can be read then null is returned
int32_t rfString_Init_fUTF8(RF_String* str,FILE* f,char* eof)
{
int32_t bytesN;
uint32_t bufferSize;// unused
if((bytesN=rfFReadLine_UTF8(f,&str->bytes,&str->byteLength,&bufferSize,eof)) < 0)
{
LOG_ERROR("Failed to initialize String from a UTF-8 file",bytesN);
return bytesN;
}
// success
return bytesN;
}
// Assigns to a String from UTF-8 file parsing
int32_t rfString_Assign_fUTF8(RF_String* str,FILE*f,char* eof)
{
int32_t bytesN;
uint32_t utf8ByteLength,utf8BufferSize;// bufferSize unused in this function
char* utf8 = 0;
if((bytesN=rfFReadLine_UTF8(f,&utf8,&utf8ByteLength,&utf8BufferSize,eof)) < 0)
{
LOG_ERROR("Failed to assign the contents of a UTF-8 file to a String",bytesN);
return bytesN;
}
// success
// assign it to the string
if(str->byteLength <= utf8ByteLength)
{
RF_REALLOC(str->bytes,char,utf8ByteLength+1);
}
memcpy(str->bytes,utf8,utf8ByteLength+1);
str->byteLength = utf8ByteLength;
// free the file's utf8 buffer
free(utf8);
return bytesN;
}
// Appends to a String from UTF-8 file parsing
int32_t rfString_Append_fUTF8(RF_String* str,FILE*f,char* eof)
{
int32_t bytesN;
uint32_t utf8ByteLength,utf8BufferSize;// bufferSize unused in this function
char* utf8 = 0;
if((bytesN=rfFReadLine_UTF8(f,&utf8,&utf8ByteLength,&utf8BufferSize,eof)) < 0)
{
LOG_ERROR("Failed to assign the contents of a UTF-8 file to a String",bytesN);
return bytesN;
}
// append the utf8 to the given string
rfString_Append(str,RFS_(utf8));
// free the file's utf8 buffer
free(utf8);
return bytesN;
}
// Allocates and returns a string from file parsing. The file's encoding must be UTF-16.If for some reason (like EOF reached) no string can be read then null is returned. A check for a valid sequence of bytes is performed.
RF_String* rfString_Create_fUTF16(FILE* f,char endianess,char* eof)
{
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
if(rfString_Init_fUTF16(ret,f,endianess,eof) < 0)
return 0;
return ret;
}
// Initializes a string from file parsing. The file's encoding must be UTF-16.If for some reason (like EOF reached) no string can be read then null is returned. A check for a valid sequence of bytes is performed.
int32_t rfString_Init_fUTF16(RF_String* str,FILE* f, char endianess,char* eof)
{
int32_t bytesN;
// depending on the file's endianess
if(endianess == RF_LITTLE_ENDIAN)
{
if((bytesN=rfFReadLine_UTF16LE(f,&str->bytes,&str->byteLength,eof)) < 0)
{
LOG_ERROR("Failure to initialize a String from reading a UTF-16 file",bytesN);
return bytesN;
}
}// end of little endian
else// big endian
{
if((bytesN=rfFReadLine_UTF16BE(f,&str->bytes,&str->byteLength,eof)) < 0)
{
LOG_ERROR("Failure to initialize a String from reading a UTF-16 file",bytesN);
return bytesN;
}
}// end of big endian case
// success
return bytesN;
}
// Assigns to an already initialized String from File parsing
int32_t rfString_Assign_fUTF16(RF_String* str,FILE* f, char endianess,char* eof)
{
uint32_t utf8ByteLength;
int32_t bytesN;
char* utf8 = 0;
// depending on the file's endianess
if(endianess == RF_LITTLE_ENDIAN)
{
if((bytesN=rfFReadLine_UTF16LE(f,&utf8,&utf8ByteLength,eof)) < 0)
{
LOG_ERROR("Failure to assign the contents of a Little Endian UTF-16 file to a String",bytesN);
return bytesN;
}
}// end of little endian
else// big endian
{
if((bytesN=rfFReadLine_UTF16BE(f,&utf8,&utf8ByteLength,eof)) < 0)
{
LOG_ERROR("Failure to assign the contents of a Big Endian UTF-16 file to a String",bytesN);
return bytesN;
}
}// end of big endian case
// success
// assign it to the string
if(str->byteLength <= utf8ByteLength)
{
RF_REALLOC(str->bytes,char,utf8ByteLength+1);
}
memcpy(str->bytes,utf8,utf8ByteLength+1);
str->byteLength = utf8ByteLength;
// free the file's utf8 buffer
free(utf8);
return bytesN;
}
// Appends to an already initialized String from File parsing
int32_t rfString_Append_fUTF16(RF_String* str,FILE* f, char endianess,char* eof)
{
char*utf8;
uint32_t utf8ByteLength;
int32_t bytesN;
// depending on the file's endianess
if(endianess == RF_LITTLE_ENDIAN)
{
if((bytesN=rfFReadLine_UTF16LE(f,&utf8,&utf8ByteLength,eof)) < 0)
{
LOG_ERROR("Failure to append the contents of a Little Endian UTF-16 file to a String",bytesN);
return bytesN;
}
}// end of little endian
else// big endian
{
if((bytesN=rfFReadLine_UTF16BE(f,&utf8,&utf8ByteLength,eof)) < 0)
{
LOG_ERROR("Failure to append the contents of a Big Endian UTF-16 file to a String",bytesN);
return bytesN;
}
}// end of big endian case
// success
rfString_Append(str,RFS_(utf8));
free(utf8);
return bytesN;
}
// Allocates and returns a string from file parsing. The file's encoding must be UTF-32.If for some reason (like EOF reached) no string can be read then null is returned. A check for a valid sequence of bytes is performed.
RF_String* rfString_Create_fUTF32(FILE* f,char endianess,char* eof)
{
RF_String* ret;
RF_MALLOC(ret,sizeof(RF_String));
if(rfString_Init_fUTF32(ret,f,endianess,eof) < 0)
{
free(ret);
return 0;
}
return ret;
}
// Initializes a string from file parsing. The file's encoding must be UTF-32.If for some reason (like EOF reached) no string can be read then null is returned. A check for a valid sequence of bytes is performed.
int32_t rfString_Init_fUTF32(RF_String* str,FILE* f,char endianess,char* eof)
{
int32_t bytesN;
// depending on the file's endianess
if(endianess == RF_LITTLE_ENDIAN)
{
if((bytesN=rfFReadLine_UTF32LE(f,&str->bytes,&str->byteLength,eof)) <0)
{
LOG_ERROR("Failure to initialize a String from reading a Little Endian UTF-32 file",bytesN);
return bytesN;
}
}// end of little endian
else// big endian
{
if((bytesN=rfFReadLine_UTF16BE(f,&str->bytes,&str->byteLength,eof)) < 0)
{
LOG_ERROR("Failure to initialize a String from reading a Big Endian UTF-32 file",bytesN);
return bytesN;
}
}// end of big endian case
// success
return bytesN;
}
// Assigns the contents of a UTF-32 file to a string
int32_t rfString_Assign_fUTF32(RF_String* str,FILE* f,char endianess, char* eof)
{
int32_t bytesN;
char*utf8;
uint32_t utf8ByteLength;
// depending on the file's endianess
if(endianess == RF_LITTLE_ENDIAN)
{
if((bytesN=rfFReadLine_UTF32LE(f,&utf8,&utf8ByteLength,eof)) < 0)
{
LOG_ERROR("Failure to assign to a String from reading a Little Endian UTF-32 file",bytesN);
return bytesN;
}
}// end of little endian
else// big endian
{
if((bytesN=rfFReadLine_UTF16BE(f,&utf8,&utf8ByteLength,eof)) < 0)
{
LOG_ERROR("Failure to assign to a String from reading a Big Endian UTF-32 file",bytesN);
return bytesN;
}
}// end of big endian case
// success
// assign it to the string
if(str->byteLength <= utf8ByteLength)
{
RF_REALLOC(str->bytes,char,utf8ByteLength+1);
}
memcpy(str->bytes,utf8,utf8ByteLength+1);
str->byteLength = utf8ByteLength;
// free the file's utf8 buffer
free(utf8);
return bytesN;
}
// Appends the contents of a UTF-32 file to a string
int32_t rfString_Append_fUTF32(RF_String* str,FILE* f,char endianess, char* eof)
{
int32_t bytesN;
char*utf8;
uint32_t utf8ByteLength;
// depending on the file's endianess
if(endianess == RF_LITTLE_ENDIAN)
{
if((bytesN=rfFReadLine_UTF32LE(f,&utf8,&utf8ByteLength,eof)) < 0)
{
LOG_ERROR("Failure to append to a String from reading a Little Endian UTF-32 file",bytesN);
return bytesN;
}
}// end of little endian
else// big endian
{
if((bytesN=rfFReadLine_UTF16BE(f,&utf8,&utf8ByteLength,eof)) < 0)
{
LOG_ERROR("Failure to append to a String from reading a Big Endian UTF-32 file",bytesN);
return bytesN;
}
}// end of big endian case
// success
// append it
rfString_Append(str,RFS_(utf8));
// free the file'sutf8 buffer
free(utf8);
return bytesN;
}
// Writes a string to a file in UTF-8 encoding.
int32_t i_rfString_Fwrite(void* sP,FILE* f,char* encodingP)
{
uint32_t *utf32,length,i;
uint16_t* utf16;
RF_String* s = (RF_String*)sP;
char encoding = *encodingP;
// depending on the encoding
switch(encoding)
{
case RF_UTF8:
if(fwrite(s->bytes,1,s->byteLength,f) != s->byteLength)
break;// and go to error logging
return RF_SUCCESS;
break;
case RF_UTF16_LE:
utf16 = rfString_ToUTF16(s,&length);
if(rfUTILS_Endianess() != RF_LITTLE_ENDIAN)
{
for(i=0;i<length;i++)
{
rfUTILS_SwapEndianUS(&utf16[i]);
}
}
if(fwrite(utf16,2,length,f) != length)
{
free(utf16);
break;// and go to error logging
}
free(utf16);
return RF_SUCCESS;
break;
case RF_UTF16_BE:
utf16 = rfString_ToUTF16(s,&length);
if(rfUTILS_Endianess() != RF_BIG_ENDIAN)
{
for(i=0;i<length;i++)
{
rfUTILS_SwapEndianUS(&utf16[i]);
}
}
if(fwrite(utf16,2,length,f) != length)
{
free(utf16);
break;// and go to error logging
}
free(utf16);
return RF_SUCCESS;
break;
case RF_UTF32_LE:
utf32 = rfString_ToUTF32(s,&length);
if(rfUTILS_Endianess() != RF_LITTLE_ENDIAN)
{
for(i=0;i<length;i++)
{
rfUTILS_SwapEndianUI(&utf32[i]);
}
}
if(fwrite(utf32,4,length,f) != length)
{
free(utf32);
break;// and go to error logging
}
free(utf32);
return RF_SUCCESS;
break;
case RF_UTF32_BE:
utf32 = rfString_ToUTF32(s,&length);
if(rfUTILS_Endianess() != RF_BIG_ENDIAN)
{
for(i=0;i<length;i++)
{
rfUTILS_SwapEndianUI(&utf32[i]);
}
}
if(fwrite(utf32,4,length,f) != length)
{
free(utf32);
break;// and go to error logging
}
free(utf32);
return RF_SUCCESS;
break;
}
// if we get here it means an error, and we log it with the macro
i_WRITE_CHECK(f,"Writting a string to a file")
return RE_FILE_WRITE;
}
| mit |
8thlight/nodo_tanku | vendor/socket_io/support/expresso/deps/jscoverage/instrument-js.cpp | 98 | 54534 | /*
instrument-js.cpp - JavaScript instrumentation routines
Copyright (C) 2007, 2008 siliconforks.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <config.h>
#include "instrument-js.h"
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <jsapi.h>
#include <jsarena.h>
#include <jsatom.h>
#include <jsemit.h>
#include <jsexn.h>
#include <jsfun.h>
#include <jsinterp.h>
#include <jsiter.h>
#include <jsparse.h>
#include <jsregexp.h>
#include <jsscope.h>
#include <jsstr.h>
#include "encoding.h"
#include "global.h"
#include "highlight.h"
#include "resource-manager.h"
#include "util.h"
struct IfDirective {
const jschar * condition_start;
const jschar * condition_end;
uint16_t start_line;
uint16_t end_line;
struct IfDirective * next;
};
bool jscoverage_mozilla = false;
static bool * exclusive_directives = NULL;
static JSRuntime * runtime = NULL;
static JSContext * context = NULL;
static JSObject * global = NULL;
static JSVersion js_version = JSVERSION_ECMA_3;
/*
JSParseNode objects store line numbers starting from 1.
The lines array stores line numbers starting from 0.
*/
static const char * file_id = NULL;
static char * lines = NULL;
static uint16_t num_lines = 0;
void jscoverage_set_js_version(const char * version) {
js_version = JS_StringToVersion(version);
if (js_version != JSVERSION_UNKNOWN) {
return;
}
char * end;
js_version = (JSVersion) strtol(version, &end, 10);
if ((size_t) (end - version) != strlen(version)) {
fatal("invalid version: %s", version);
}
}
void jscoverage_init(void) {
runtime = JS_NewRuntime(8L * 1024L * 1024L);
if (runtime == NULL) {
fatal("cannot create runtime");
}
context = JS_NewContext(runtime, 8192);
if (context == NULL) {
fatal("cannot create context");
}
JS_SetVersion(context, js_version);
global = JS_NewObject(context, NULL, NULL, NULL);
if (global == NULL) {
fatal("cannot create global object");
}
if (! JS_InitStandardClasses(context, global)) {
fatal("cannot initialize standard classes");
}
}
void jscoverage_cleanup(void) {
JS_DestroyContext(context);
JS_DestroyRuntime(runtime);
}
static void print_javascript(const jschar * characters, size_t num_characters, Stream * f) {
for (size_t i = 0; i < num_characters; i++) {
jschar c = characters[i];
/*
XXX does not handle no-break space, other unicode "space separator"
*/
switch (c) {
case 0x9:
case 0xB:
case 0xC:
Stream_write_char(f, c);
break;
default:
if (32 <= c && c <= 126) {
Stream_write_char(f, c);
}
else {
Stream_printf(f, "\\u%04x", c);
}
break;
}
}
}
static void print_string(JSString * s, Stream * f) {
size_t length = JSSTRING_LENGTH(s);
jschar * characters = JSSTRING_CHARS(s);
for (size_t i = 0; i < length; i++) {
jschar c = characters[i];
if (32 <= c && c <= 126) {
switch (c) {
case '"':
Stream_write_string(f, "\\\"");
break;
/*
case '\'':
Stream_write_string(f, "\\'");
break;
*/
case '\\':
Stream_write_string(f, "\\\\");
break;
default:
Stream_write_char(f, c);
break;
}
}
else {
switch (c) {
case 0x8:
Stream_write_string(f, "\\b");
break;
case 0x9:
Stream_write_string(f, "\\t");
break;
case 0xa:
Stream_write_string(f, "\\n");
break;
/* IE doesn't support this */
/*
case 0xb:
Stream_write_string(f, "\\v");
break;
*/
case 0xc:
Stream_write_string(f, "\\f");
break;
case 0xd:
Stream_write_string(f, "\\r");
break;
default:
Stream_printf(f, "\\u%04x", c);
break;
}
}
}
}
static void print_string_atom(JSAtom * atom, Stream * f) {
assert(ATOM_IS_STRING(atom));
JSString * s = ATOM_TO_STRING(atom);
print_string(s, f);
}
static void print_regex(jsval value, Stream * f) {
assert(JSVAL_IS_STRING(value));
JSString * s = JSVAL_TO_STRING(value);
size_t length = JSSTRING_LENGTH(s);
jschar * characters = JSSTRING_CHARS(s);
for (size_t i = 0; i < length; i++) {
jschar c = characters[i];
if (32 <= c && c <= 126) {
Stream_write_char(f, c);
}
else {
Stream_printf(f, "\\u%04x", c);
}
}
}
static void print_quoted_string_atom(JSAtom * atom, Stream * f) {
assert(ATOM_IS_STRING(atom));
JSString * s = ATOM_TO_STRING(atom);
Stream_write_char(f, '"');
print_string(s, f);
Stream_write_char(f, '"');
}
static const char * get_op(uint8 op) {
switch(op) {
case JSOP_OR:
return "||";
case JSOP_AND:
return "&&";
case JSOP_BITOR:
return "|";
case JSOP_BITXOR:
return "^";
case JSOP_BITAND:
return "&";
case JSOP_EQ:
return "==";
case JSOP_NE:
return "!=";
case JSOP_STRICTEQ:
return "===";
case JSOP_STRICTNE:
return "!==";
case JSOP_LT:
return "<";
case JSOP_LE:
return "<=";
case JSOP_GT:
return ">";
case JSOP_GE:
return ">=";
case JSOP_LSH:
return "<<";
case JSOP_RSH:
return ">>";
case JSOP_URSH:
return ">>>";
case JSOP_ADD:
return "+";
case JSOP_SUB:
return "-";
case JSOP_MUL:
return "*";
case JSOP_DIV:
return "/";
case JSOP_MOD:
return "%";
default:
abort();
}
}
static void output_expression(JSParseNode * node, Stream * f, bool parenthesize_object_literals);
static void instrument_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if);
static void output_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if);
enum FunctionType {
FUNCTION_NORMAL,
FUNCTION_GETTER_OR_SETTER
};
static void output_for_in(JSParseNode * node, Stream * f) {
assert(node->pn_type == TOK_FOR);
assert(node->pn_arity == PN_BINARY);
Stream_write_string(f, "for ");
if (node->pn_iflags & JSITER_FOREACH) {
Stream_write_string(f, "each ");
}
Stream_write_char(f, '(');
output_expression(node->pn_left, f, false);
Stream_write_char(f, ')');
}
static void output_array_comprehension_or_generator_expression(JSParseNode * node, Stream * f) {
assert(node->pn_type == TOK_LEXICALSCOPE);
assert(node->pn_arity == PN_NAME);
JSParseNode * for_node = node->pn_expr;
assert(for_node->pn_type == TOK_FOR);
assert(for_node->pn_arity == PN_BINARY);
JSParseNode * p = for_node;
while (p->pn_type == TOK_FOR) {
p = p->pn_right;
}
JSParseNode * if_node = NULL;
if (p->pn_type == TOK_IF) {
if_node = p;
assert(if_node->pn_arity == PN_TERNARY);
p = if_node->pn_kid2;
}
switch (p->pn_arity) {
case PN_UNARY:
p = p->pn_kid;
if (p->pn_type == TOK_YIELD) {
/* for generator expressions */
p = p->pn_kid;
}
output_expression(p, f, false);
break;
case PN_LIST:
/*
When the array comprehension contains "if (0)", it will be optimized away and
the result will be an empty TOK_LC list.
*/
assert(p->pn_type == TOK_LC);
assert(p->pn_head == NULL);
/* the "1" is arbitrary (since the list is empty) */
Stream_write_char(f, '1');
break;
default:
abort();
break;
}
p = for_node;
while (p->pn_type == TOK_FOR) {
Stream_write_char(f, ' ');
output_for_in(p, f);
p = p->pn_right;
}
if (p->pn_type == TOK_LC) {
/* this is the optimized-away "if (0)" */
Stream_write_string(f, " if (0)");
}
else if (if_node) {
Stream_write_string(f, " if (");
output_expression(if_node->pn_kid1, f, false);
Stream_write_char(f, ')');
}
}
static void instrument_function(JSParseNode * node, Stream * f, int indent, enum FunctionType type) {
assert(node->pn_type == TOK_FUNCTION);
assert(node->pn_arity == PN_FUNC);
JSObject * object = node->pn_funpob->object;
assert(JS_ObjectIsFunction(context, object));
JSFunction * function = (JSFunction *) JS_GetPrivate(context, object);
assert(function);
assert(object == &function->object);
Stream_printf(f, "%*s", indent, "");
if (type == FUNCTION_NORMAL) {
Stream_write_string(f, "function ");
}
/* function name */
if (function->atom) {
print_string_atom(function->atom, f);
}
/*
function parameters - see JS_DecompileFunction in jsapi.cpp, which calls
js_DecompileFunction in jsopcode.cpp
*/
Stream_write_char(f, '(');
JSArenaPool pool;
JS_INIT_ARENA_POOL(&pool, "instrument_function", 256, 1, &context->scriptStackQuota);
jsuword * local_names = NULL;
if (JS_GET_LOCAL_NAME_COUNT(function)) {
local_names = js_GetLocalNameArray(context, function, &pool);
if (local_names == NULL) {
fatal("out of memory");
}
}
bool destructuring = false;
for (int i = 0; i < function->nargs; i++) {
if (i > 0) {
Stream_write_string(f, ", ");
}
JSAtom * param = JS_LOCAL_NAME_TO_ATOM(local_names[i]);
if (param == NULL) {
destructuring = true;
JSParseNode * expression = NULL;
assert(node->pn_body->pn_type == TOK_LC || node->pn_body->pn_type == TOK_SEQ);
JSParseNode * semi = node->pn_body->pn_head;
assert(semi->pn_type == TOK_SEMI);
JSParseNode * comma = semi->pn_kid;
assert(comma->pn_type == TOK_COMMA);
for (JSParseNode * p = comma->pn_head; p != NULL; p = p->pn_next) {
assert(p->pn_type == TOK_ASSIGN);
JSParseNode * rhs = p->pn_right;
assert(JSSTRING_LENGTH(ATOM_TO_STRING(rhs->pn_atom)) == 0);
if (rhs->pn_slot == i) {
expression = p->pn_left;
break;
}
}
assert(expression != NULL);
output_expression(expression, f, false);
}
else {
print_string_atom(param, f);
}
}
JS_FinishArenaPool(&pool);
Stream_write_string(f, ") {\n");
/* function body */
if (function->flags & JSFUN_EXPR_CLOSURE) {
/* expression closure - use output_statement instead of instrument_statement */
if (node->pn_body->pn_type == TOK_SEQ) {
assert(node->pn_body->pn_arity == PN_LIST);
assert(node->pn_body->pn_count == 2);
output_statement(node->pn_body->pn_head->pn_next, f, indent + 2, false);
}
else {
output_statement(node->pn_body, f, indent + 2, false);
}
}
else {
assert(node->pn_body->pn_type == TOK_LC);
assert(node->pn_body->pn_arity == PN_LIST);
JSParseNode * p = node->pn_body->pn_head;
if (destructuring) {
p = p->pn_next;
}
for (; p != NULL; p = p->pn_next) {
instrument_statement(p, f, indent + 2, false);
}
}
Stream_write_char(f, '}');
}
static void instrument_function_call(JSParseNode * node, Stream * f) {
JSParseNode * function_node = node->pn_head;
if (function_node->pn_type == TOK_FUNCTION) {
JSObject * object = function_node->pn_funpob->object;
assert(JS_ObjectIsFunction(context, object));
JSFunction * function = (JSFunction *) JS_GetPrivate(context, object);
assert(function);
assert(object == &function->object);
if (function_node->pn_flags & TCF_GENEXP_LAMBDA) {
/* it's a generator expression */
Stream_write_char(f, '(');
output_array_comprehension_or_generator_expression(function_node->pn_body, f);
Stream_write_char(f, ')');
return;
}
}
output_expression(function_node, f, false);
Stream_write_char(f, '(');
for (struct JSParseNode * p = function_node->pn_next; p != NULL; p = p->pn_next) {
if (p != node->pn_head->pn_next) {
Stream_write_string(f, ", ");
}
output_expression(p, f, false);
}
Stream_write_char(f, ')');
}
static void instrument_declarations(JSParseNode * list, Stream * f) {
assert(list->pn_arity == PN_LIST);
for (JSParseNode * p = list->pn_head; p != NULL; p = p->pn_next) {
if (p != list->pn_head) {
Stream_write_string(f, ", ");
}
output_expression(p, f, false);
}
}
/*
See <Expressions> in jsparse.h.
TOK_FUNCTION is handled as a statement and as an expression.
TOK_DBLDOT is not handled (XML op).
TOK_DEFSHARP and TOK_USESHARP are not handled.
TOK_ANYNAME is not handled (XML op).
TOK_AT is not handled (XML op).
TOK_DBLCOLON is not handled.
TOK_XML* are not handled.
There seem to be some undocumented expressions:
TOK_INSTANCEOF binary
TOK_IN binary
*/
static void output_expression(JSParseNode * node, Stream * f, bool parenthesize_object_literals) {
switch (node->pn_type) {
case TOK_FUNCTION:
Stream_write_char(f, '(');
instrument_function(node, f, 0, FUNCTION_NORMAL);
Stream_write_char(f, ')');
break;
case TOK_COMMA:
for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
if (p != node->pn_head) {
Stream_write_string(f, ", ");
}
output_expression(p, f, parenthesize_object_literals);
}
break;
case TOK_ASSIGN:
output_expression(node->pn_left, f, parenthesize_object_literals);
Stream_write_char(f, ' ');
switch (node->pn_op) {
case JSOP_ADD:
case JSOP_SUB:
case JSOP_MUL:
case JSOP_MOD:
case JSOP_LSH:
case JSOP_RSH:
case JSOP_URSH:
case JSOP_BITAND:
case JSOP_BITOR:
case JSOP_BITXOR:
case JSOP_DIV:
Stream_printf(f, "%s", get_op(node->pn_op));
break;
default:
/* do nothing - it must be a simple assignment */
break;
}
Stream_write_string(f, "= ");
output_expression(node->pn_right, f, false);
break;
case TOK_HOOK:
output_expression(node->pn_kid1, f, parenthesize_object_literals);
Stream_write_string(f, "? ");
output_expression(node->pn_kid2, f, false);
Stream_write_string(f, ": ");
output_expression(node->pn_kid3, f, false);
break;
case TOK_OR:
case TOK_AND:
case TOK_BITOR:
case TOK_BITXOR:
case TOK_BITAND:
case TOK_EQOP:
case TOK_RELOP:
case TOK_SHOP:
case TOK_PLUS:
case TOK_MINUS:
case TOK_STAR:
case TOK_DIVOP:
switch (node->pn_arity) {
case PN_BINARY:
output_expression(node->pn_left, f, parenthesize_object_literals);
Stream_printf(f, " %s ", get_op(node->pn_op));
output_expression(node->pn_right, f, false);
break;
case PN_LIST:
for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
if (p == node->pn_head) {
output_expression(p, f, parenthesize_object_literals);
}
else {
Stream_printf(f, " %s ", get_op(node->pn_op));
output_expression(p, f, false);
}
}
break;
default:
abort();
}
break;
case TOK_UNARYOP:
switch (node->pn_op) {
case JSOP_NEG:
Stream_write_string(f, "- ");
output_expression(node->pn_kid, f, false);
break;
case JSOP_POS:
Stream_write_string(f, "+ ");
output_expression(node->pn_kid, f, false);
break;
case JSOP_NOT:
Stream_write_string(f, "! ");
output_expression(node->pn_kid, f, false);
break;
case JSOP_BITNOT:
Stream_write_string(f, "~ ");
output_expression(node->pn_kid, f, false);
break;
case JSOP_TYPEOF:
Stream_write_string(f, "typeof ");
output_expression(node->pn_kid, f, false);
break;
case JSOP_VOID:
Stream_write_string(f, "void ");
output_expression(node->pn_kid, f, false);
break;
default:
fatal_source(file_id, node->pn_pos.begin.lineno, "unknown operator (%d)", node->pn_op);
break;
}
break;
case TOK_INC:
case TOK_DEC:
/*
This is not documented, but node->pn_op tells whether it is pre- or post-increment.
*/
switch (node->pn_op) {
case JSOP_INCNAME:
case JSOP_INCPROP:
case JSOP_INCELEM:
Stream_write_string(f, "++");
output_expression(node->pn_kid, f, false);
break;
case JSOP_DECNAME:
case JSOP_DECPROP:
case JSOP_DECELEM:
Stream_write_string(f, "--");
output_expression(node->pn_kid, f, false);
break;
case JSOP_NAMEINC:
case JSOP_PROPINC:
case JSOP_ELEMINC:
output_expression(node->pn_kid, f, parenthesize_object_literals);
Stream_write_string(f, "++");
break;
case JSOP_NAMEDEC:
case JSOP_PROPDEC:
case JSOP_ELEMDEC:
output_expression(node->pn_kid, f, parenthesize_object_literals);
Stream_write_string(f, "--");
break;
default:
abort();
break;
}
break;
case TOK_NEW:
Stream_write_string(f, "new ");
instrument_function_call(node, f);
break;
case TOK_DELETE:
Stream_write_string(f, "delete ");
output_expression(node->pn_kid, f, false);
break;
case TOK_DOT:
/* numeric literals must be parenthesized */
switch (node->pn_expr->pn_type) {
case TOK_NUMBER:
Stream_write_char(f, '(');
output_expression(node->pn_expr, f, false);
Stream_write_char(f, ')');
break;
default:
output_expression(node->pn_expr, f, true);
break;
}
/*
This may have originally been x['foo-bar']. Because the string 'foo-bar'
contains illegal characters, we have to use the subscript syntax instead of
the dot syntax.
*/
assert(ATOM_IS_STRING(node->pn_atom));
{
JSString * s = ATOM_TO_STRING(node->pn_atom);
bool must_quote;
if (JSSTRING_LENGTH(s) == 0) {
must_quote = true;
}
else if (js_CheckKeyword(JSSTRING_CHARS(s), JSSTRING_LENGTH(s)) != TOK_EOF) {
must_quote = true;
}
else if (! js_IsIdentifier(s)) {
must_quote = true;
}
else {
must_quote = false;
}
if (must_quote) {
Stream_write_char(f, '[');
print_quoted_string_atom(node->pn_atom, f);
Stream_write_char(f, ']');
}
else {
Stream_write_char(f, '.');
print_string_atom(node->pn_atom, f);
}
}
break;
case TOK_LB:
output_expression(node->pn_left, f, false);
Stream_write_char(f, '[');
output_expression(node->pn_right, f, false);
Stream_write_char(f, ']');
break;
case TOK_LP:
instrument_function_call(node, f);
break;
case TOK_RB:
Stream_write_char(f, '[');
for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
if (p != node->pn_head) {
Stream_write_string(f, ", ");
}
/* TOK_COMMA is a special case: a hole in the array */
if (p->pn_type != TOK_COMMA) {
output_expression(p, f, false);
}
}
if (node->pn_extra == PNX_ENDCOMMA) {
Stream_write_char(f, ',');
}
Stream_write_char(f, ']');
break;
case TOK_RC:
if (parenthesize_object_literals) {
Stream_write_char(f, '(');
}
Stream_write_char(f, '{');
for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
if (p->pn_type != TOK_COLON) {
fatal_source(file_id, p->pn_pos.begin.lineno, "unsupported node type (%d)", p->pn_type);
}
if (p != node->pn_head) {
Stream_write_string(f, ", ");
}
/* check whether this is a getter or setter */
switch (p->pn_op) {
case JSOP_GETTER:
case JSOP_SETTER:
if (p->pn_op == JSOP_GETTER) {
Stream_write_string(f, "get ");
}
else {
Stream_write_string(f, "set ");
}
output_expression(p->pn_left, f, false);
Stream_write_char(f, ' ');
if (p->pn_right->pn_type != TOK_FUNCTION) {
fatal_source(file_id, p->pn_pos.begin.lineno, "expected function");
}
instrument_function(p->pn_right, f, 0, FUNCTION_GETTER_OR_SETTER);
break;
default:
output_expression(p->pn_left, f, false);
Stream_write_string(f, ": ");
output_expression(p->pn_right, f, false);
break;
}
}
Stream_write_char(f, '}');
if (parenthesize_object_literals) {
Stream_write_char(f, ')');
}
break;
case TOK_RP:
Stream_write_char(f, '(');
output_expression(node->pn_kid, f, false);
Stream_write_char(f, ')');
break;
case TOK_NAME:
print_string_atom(node->pn_atom, f);
if (node->pn_expr != NULL) {
Stream_write_string(f, " = ");
output_expression(node->pn_expr, f, false);
}
break;
case TOK_STRING:
print_quoted_string_atom(node->pn_atom, f);
break;
case TOK_REGEXP:
assert(node->pn_op == JSOP_REGEXP);
{
JSObject * object = node->pn_pob->object;
jsval result;
js_regexp_toString(context, object, &result);
print_regex(result, f);
}
break;
case TOK_NUMBER:
/*
A 64-bit IEEE 754 floating point number has a 52-bit fraction.
2^(-52) = 2.22 x 10^(-16)
Thus there are 16 significant digits.
To keep the output simple, special-case zero.
*/
if (node->pn_dval == 0.0) {
if (signbit(node->pn_dval)) {
Stream_write_string(f, "-0");
}
else {
Stream_write_string(f, "0");
}
}
else if (node->pn_dval == INFINITY) {
Stream_write_string(f, "Number.POSITIVE_INFINITY");
}
else if (node->pn_dval == -INFINITY) {
Stream_write_string(f, "Number.NEGATIVE_INFINITY");
}
else if (isnan(node->pn_dval)) {
Stream_write_string(f, "Number.NaN");
}
else {
Stream_printf(f, "%.15g", node->pn_dval);
}
break;
case TOK_PRIMARY:
switch (node->pn_op) {
case JSOP_TRUE:
Stream_write_string(f, "true");
break;
case JSOP_FALSE:
Stream_write_string(f, "false");
break;
case JSOP_NULL:
Stream_write_string(f, "null");
break;
case JSOP_THIS:
Stream_write_string(f, "this");
break;
/* jsscan.h mentions `super' ??? */
default:
abort();
}
break;
case TOK_INSTANCEOF:
output_expression(node->pn_left, f, parenthesize_object_literals);
Stream_write_string(f, " instanceof ");
output_expression(node->pn_right, f, false);
break;
case TOK_IN:
output_expression(node->pn_left, f, false);
Stream_write_string(f, " in ");
output_expression(node->pn_right, f, false);
break;
case TOK_LEXICALSCOPE:
assert(node->pn_arity == PN_NAME);
assert(node->pn_expr->pn_type == TOK_LET);
assert(node->pn_expr->pn_arity == PN_BINARY);
Stream_write_string(f, "let(");
assert(node->pn_expr->pn_left->pn_type == TOK_LP);
assert(node->pn_expr->pn_left->pn_arity == PN_LIST);
instrument_declarations(node->pn_expr->pn_left, f);
Stream_write_string(f, ") ");
output_expression(node->pn_expr->pn_right, f, true);
break;
case TOK_YIELD:
assert(node->pn_arity == PN_UNARY);
Stream_write_string(f, "yield");
if (node->pn_kid != NULL) {
Stream_write_char(f, ' ');
output_expression(node->pn_kid, f, true);
}
break;
case TOK_ARRAYCOMP:
assert(node->pn_arity == PN_LIST);
{
JSParseNode * block_node;
switch (node->pn_count) {
case 1:
block_node = node->pn_head;
break;
case 2:
block_node = node->pn_head->pn_next;
break;
default:
abort();
break;
}
Stream_write_char(f, '[');
output_array_comprehension_or_generator_expression(block_node, f);
Stream_write_char(f, ']');
}
break;
case TOK_VAR:
assert(node->pn_arity == PN_LIST);
Stream_write_string(f, "var ");
instrument_declarations(node, f);
break;
case TOK_LET:
assert(node->pn_arity == PN_LIST);
Stream_write_string(f, "let ");
instrument_declarations(node, f);
break;
default:
fatal_source(file_id, node->pn_pos.begin.lineno, "unsupported node type (%d)", node->pn_type);
}
}
static void output_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if) {
switch (node->pn_type) {
case TOK_FUNCTION:
instrument_function(node, f, indent, FUNCTION_NORMAL);
Stream_write_char(f, '\n');
break;
case TOK_LC:
assert(node->pn_arity == PN_LIST);
/*
Stream_write_string(f, "{\n");
*/
for (struct JSParseNode * p = node->pn_u.list.head; p != NULL; p = p->pn_next) {
instrument_statement(p, f, indent, false);
}
/*
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
*/
break;
case TOK_IF:
{
assert(node->pn_arity == PN_TERNARY);
uint16_t line = node->pn_pos.begin.lineno;
if (! is_jscoverage_if) {
if (line > num_lines) {
fatal("file %s contains more than 65,535 lines", file_id);
}
if (line >= 2 && exclusive_directives[line - 2]) {
is_jscoverage_if = true;
}
}
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "if (");
output_expression(node->pn_kid1, f, false);
Stream_write_string(f, ") {\n");
if (is_jscoverage_if && node->pn_kid3) {
uint16_t else_start = node->pn_kid3->pn_pos.begin.lineno;
uint16_t else_end = node->pn_kid3->pn_pos.end.lineno + 1;
Stream_printf(f, "%*s", indent + 2, "");
Stream_printf(f, "_$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, else_start, else_end);
}
instrument_statement(node->pn_kid2, f, indent + 2, false);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
if (node->pn_kid3 || is_jscoverage_if) {
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "else {\n");
if (is_jscoverage_if) {
uint16_t if_start = node->pn_kid2->pn_pos.begin.lineno + 1;
uint16_t if_end = node->pn_kid2->pn_pos.end.lineno + 1;
Stream_printf(f, "%*s", indent + 2, "");
Stream_printf(f, "_$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, if_start, if_end);
}
if (node->pn_kid3) {
instrument_statement(node->pn_kid3, f, indent + 2, is_jscoverage_if);
}
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
}
break;
}
case TOK_SWITCH:
assert(node->pn_arity == PN_BINARY);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "switch (");
output_expression(node->pn_left, f, false);
Stream_write_string(f, ") {\n");
{
JSParseNode * list = node->pn_right;
if (list->pn_type == TOK_LEXICALSCOPE) {
list = list->pn_expr;
}
for (struct JSParseNode * p = list->pn_head; p != NULL; p = p->pn_next) {
Stream_printf(f, "%*s", indent, "");
switch (p->pn_type) {
case TOK_CASE:
Stream_write_string(f, "case ");
output_expression(p->pn_left, f, false);
Stream_write_string(f, ":\n");
break;
case TOK_DEFAULT:
Stream_write_string(f, "default:\n");
break;
default:
abort();
break;
}
instrument_statement(p->pn_right, f, indent + 2, false);
}
}
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
break;
case TOK_CASE:
case TOK_DEFAULT:
abort();
break;
case TOK_WHILE:
assert(node->pn_arity == PN_BINARY);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "while (");
output_expression(node->pn_left, f, false);
Stream_write_string(f, ") {\n");
instrument_statement(node->pn_right, f, indent + 2, false);
Stream_write_string(f, "}\n");
break;
case TOK_DO:
assert(node->pn_arity == PN_BINARY);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "do {\n");
instrument_statement(node->pn_left, f, indent + 2, false);
Stream_write_string(f, "}\n");
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "while (");
output_expression(node->pn_right, f, false);
Stream_write_string(f, ");\n");
break;
case TOK_FOR:
assert(node->pn_arity == PN_BINARY);
Stream_printf(f, "%*s", indent, "");
switch (node->pn_left->pn_type) {
case TOK_IN:
/* for/in */
assert(node->pn_left->pn_arity == PN_BINARY);
output_for_in(node, f);
break;
case TOK_FORHEAD:
/* for (;;) */
assert(node->pn_left->pn_arity == PN_TERNARY);
Stream_write_string(f, "for (");
if (node->pn_left->pn_kid1) {
output_expression(node->pn_left->pn_kid1, f, false);
}
Stream_write_string(f, ";");
if (node->pn_left->pn_kid2) {
Stream_write_char(f, ' ');
output_expression(node->pn_left->pn_kid2, f, false);
}
Stream_write_string(f, ";");
if (node->pn_left->pn_kid3) {
Stream_write_char(f, ' ');
output_expression(node->pn_left->pn_kid3, f, false);
}
Stream_write_char(f, ')');
break;
default:
abort();
break;
}
Stream_write_string(f, " {\n");
instrument_statement(node->pn_right, f, indent + 2, false);
Stream_write_string(f, "}\n");
break;
case TOK_THROW:
assert(node->pn_arity == PN_UNARY);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "throw ");
output_expression(node->pn_u.unary.kid, f, false);
Stream_write_string(f, ";\n");
break;
case TOK_TRY:
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "try {\n");
instrument_statement(node->pn_kid1, f, indent + 2, false);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
if (node->pn_kid2) {
assert(node->pn_kid2->pn_type == TOK_RESERVED);
for (JSParseNode * scope = node->pn_kid2->pn_head; scope != NULL; scope = scope->pn_next) {
assert(scope->pn_type == TOK_LEXICALSCOPE);
JSParseNode * catch_node = scope->pn_expr;
assert(catch_node->pn_type == TOK_CATCH);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "catch (");
output_expression(catch_node->pn_kid1, f, false);
if (catch_node->pn_kid2) {
Stream_write_string(f, " if ");
output_expression(catch_node->pn_kid2, f, false);
}
Stream_write_string(f, ") {\n");
instrument_statement(catch_node->pn_kid3, f, indent + 2, false);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
}
}
if (node->pn_kid3) {
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "finally {\n");
instrument_statement(node->pn_kid3, f, indent + 2, false);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
}
break;
case TOK_CATCH:
abort();
break;
case TOK_BREAK:
case TOK_CONTINUE:
assert(node->pn_arity == PN_NAME || node->pn_arity == PN_NULLARY);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, node->pn_type == TOK_BREAK? "break": "continue");
if (node->pn_atom != NULL) {
Stream_write_char(f, ' ');
print_string_atom(node->pn_atom, f);
}
Stream_write_string(f, ";\n");
break;
case TOK_WITH:
assert(node->pn_arity == PN_BINARY);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "with (");
output_expression(node->pn_left, f, false);
Stream_write_string(f, ") {\n");
instrument_statement(node->pn_right, f, indent + 2, false);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
break;
case TOK_VAR:
Stream_printf(f, "%*s", indent, "");
output_expression(node, f, false);
Stream_write_string(f, ";\n");
break;
case TOK_RETURN:
assert(node->pn_arity == PN_UNARY);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "return");
if (node->pn_kid != NULL) {
Stream_write_char(f, ' ');
output_expression(node->pn_kid, f, true);
}
Stream_write_string(f, ";\n");
break;
case TOK_SEMI:
assert(node->pn_arity == PN_UNARY);
Stream_printf(f, "%*s", indent, "");
if (node->pn_kid != NULL) {
output_expression(node->pn_kid, f, true);
}
Stream_write_string(f, ";\n");
break;
case TOK_COLON:
{
assert(node->pn_arity == PN_NAME);
Stream_printf(f, "%*s", indent < 2? 0: indent - 2, "");
print_string_atom(node->pn_atom, f);
Stream_write_string(f, ":\n");
JSParseNode * labelled = node->pn_expr;
if (labelled->pn_type == TOK_LEXICALSCOPE) {
labelled = labelled->pn_expr;
}
if (labelled->pn_type == TOK_LC) {
/* labelled block */
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "{\n");
instrument_statement(labelled, f, indent + 2, false);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
}
else {
/*
This one is tricky: can't output instrumentation between the label and the
statement it's supposed to label, so use output_statement instead of
instrument_statement.
*/
output_statement(labelled, f, indent, false);
}
break;
}
case TOK_LEXICALSCOPE:
/* let statement */
assert(node->pn_arity == PN_NAME);
switch (node->pn_expr->pn_type) {
case TOK_LET:
/* let statement */
assert(node->pn_expr->pn_arity == PN_BINARY);
instrument_statement(node->pn_expr, f, indent, false);
break;
case TOK_LC:
/* block */
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "{\n");
instrument_statement(node->pn_expr, f, indent + 2, false);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
break;
case TOK_FOR:
instrument_statement(node->pn_expr, f, indent, false);
break;
default:
abort();
break;
}
break;
case TOK_LET:
switch (node->pn_arity) {
case PN_BINARY:
/* let statement */
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "let (");
assert(node->pn_left->pn_type == TOK_LP);
assert(node->pn_left->pn_arity == PN_LIST);
instrument_declarations(node->pn_left, f);
Stream_write_string(f, ") {\n");
instrument_statement(node->pn_right, f, indent + 2, false);
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "}\n");
break;
case PN_LIST:
/* let definition */
Stream_printf(f, "%*s", indent, "");
output_expression(node, f, false);
Stream_write_string(f, ";\n");
break;
default:
abort();
break;
}
break;
case TOK_DEBUGGER:
Stream_printf(f, "%*s", indent, "");
Stream_write_string(f, "debugger;\n");
break;
case TOK_SEQ:
/*
This occurs with the statement:
for (var a = b in c) {}
*/
assert(node->pn_arity == PN_LIST);
for (JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
instrument_statement(p, f, indent, false);
}
break;
default:
fatal_source(file_id, node->pn_pos.begin.lineno, "unsupported node type (%d)", node->pn_type);
}
}
/*
See <Statements> in jsparse.h.
TOK_FUNCTION is handled as a statement and as an expression.
TOK_EXPORT, TOK_IMPORT are not handled.
*/
static void instrument_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if) {
if (node->pn_type != TOK_LC && node->pn_type != TOK_LEXICALSCOPE) {
uint16_t line = node->pn_pos.begin.lineno;
if (line > num_lines) {
fatal("file %s contains more than 65,535 lines", file_id);
}
/* the root node has line number 0 */
if (line != 0) {
Stream_printf(f, "%*s", indent, "");
Stream_printf(f, "_$jscoverage['%s'][%d]++;\n", file_id, line);
lines[line - 1] = 1;
}
}
output_statement(node, f, indent, is_jscoverage_if);
}
static bool characters_start_with(const jschar * characters, size_t line_start, size_t line_end, const char * prefix) {
const jschar * characters_end = characters + line_end;
const jschar * cp = characters + line_start;
const char * bp = prefix;
for (;;) {
if (*bp == '\0') {
return true;
}
else if (cp == characters_end) {
return false;
}
else if (*cp != *bp) {
return false;
}
bp++;
cp++;
}
}
static bool characters_are_white_space(const jschar * characters, size_t line_start, size_t line_end) {
/* XXX - other Unicode space */
const jschar * end = characters + line_end;
for (const jschar * p = characters + line_start; p < end; p++) {
jschar c = *p;
if (c == 0x9 || c == 0xB || c == 0xC || c == 0x20 || c == 0xA0) {
continue;
}
else {
return false;
}
}
return true;
}
static void error_reporter(JSContext * context, const char * message, JSErrorReport * report) {
warn_source(file_id, report->lineno, "%s", message);
}
void jscoverage_instrument_js(const char * id, const uint16_t * characters, size_t num_characters, Stream * output) {
file_id = id;
/* parse the javascript */
JSParseContext parse_context;
if (! js_InitParseContext(context, &parse_context, NULL, NULL, characters, num_characters, NULL, NULL, 1)) {
fatal("cannot create token stream from file %s", file_id);
}
JSErrorReporter old_error_reporter = JS_SetErrorReporter(context, error_reporter);
JSParseNode * node = js_ParseScript(context, global, &parse_context);
if (node == NULL) {
js_ReportUncaughtException(context);
fatal("parse error in file %s", file_id);
}
JS_SetErrorReporter(context, old_error_reporter);
num_lines = node->pn_pos.end.lineno;
lines = (char *) xmalloc(num_lines);
for (unsigned int i = 0; i < num_lines; i++) {
lines[i] = 0;
}
/* search code for conditionals */
exclusive_directives = xnew(bool, num_lines);
for (unsigned int i = 0; i < num_lines; i++) {
exclusive_directives[i] = false;
}
bool has_conditionals = false;
struct IfDirective * if_directives = NULL;
size_t line_number = 0;
size_t i = 0;
while (i < num_characters) {
if (line_number == UINT16_MAX) {
fatal("file %s contains more than 65,535 lines", file_id);
}
line_number++;
size_t line_start = i;
jschar c;
bool done = false;
while (! done && i < num_characters) {
c = characters[i];
switch (c) {
case '\r':
case '\n':
case 0x2028:
case 0x2029:
done = true;
break;
default:
i++;
}
}
size_t line_end = i;
if (i < num_characters) {
i++;
if (c == '\r' && i < num_characters && characters[i] == '\n') {
i++;
}
}
if (characters_start_with(characters, line_start, line_end, "//#JSCOVERAGE_IF")) {
has_conditionals = true;
if (characters_are_white_space(characters, line_start + 16, line_end)) {
exclusive_directives[line_number - 1] = true;
}
else {
struct IfDirective * if_directive = xnew(struct IfDirective, 1);
if_directive->condition_start = characters + line_start + 16;
if_directive->condition_end = characters + line_end;
if_directive->start_line = line_number;
if_directive->end_line = 0;
if_directive->next = if_directives;
if_directives = if_directive;
}
}
else if (characters_start_with(characters, line_start, line_end, "//#JSCOVERAGE_ENDIF")) {
for (struct IfDirective * p = if_directives; p != NULL; p = p->next) {
if (p->end_line == 0) {
p->end_line = line_number;
break;
}
}
}
}
/*
An instrumented JavaScript file has 4 sections:
1. initialization
2. instrumented source code
3. conditionals
4. original source code
*/
Stream * instrumented = Stream_new(0);
instrument_statement(node, instrumented, 0, false);
js_FinishParseContext(context, &parse_context);
/* write line number info to the output */
Stream_write_string(output, "/* automatically generated by JSCoverage - do not edit */\n");
Stream_write_string(output, "if (typeof _$jscoverage === 'undefined') _$jscoverage = {};\n");
Stream_printf(output, "if (! _$jscoverage['%s']) {\n", file_id);
Stream_printf(output, " _$jscoverage['%s'] = [];\n", file_id);
for (int i = 0; i < num_lines; i++) {
if (lines[i]) {
Stream_printf(output, " _$jscoverage['%s'][%d] = 0;\n", file_id, i + 1);
}
}
Stream_write_string(output, "}\n");
free(lines);
lines = NULL;
free(exclusive_directives);
exclusive_directives = NULL;
/* conditionals */
if (has_conditionals) {
Stream_printf(output, "_$jscoverage['%s'].conditionals = [];\n", file_id);
}
/* copy the instrumented source code to the output */
Stream_write(output, instrumented->data, instrumented->length);
/* conditionals */
for (struct IfDirective * if_directive = if_directives; if_directive != NULL; if_directive = if_directive->next) {
Stream_write_string(output, "if (!(");
print_javascript(if_directive->condition_start, if_directive->condition_end - if_directive->condition_start, output);
Stream_write_string(output, ")) {\n");
Stream_printf(output, " _$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, if_directive->start_line, if_directive->end_line);
Stream_write_string(output, "}\n");
}
/* free */
while (if_directives != NULL) {
struct IfDirective * if_directive = if_directives;
if_directives = if_directives->next;
free(if_directive);
}
/* copy the original source to the output */
Stream_printf(output, "_$jscoverage['%s'].source = ", file_id);
jscoverage_write_source(id, characters, num_characters, output);
Stream_printf(output, ";\n");
Stream_delete(instrumented);
file_id = NULL;
}
void jscoverage_write_source(const char * id, const jschar * characters, size_t num_characters, Stream * output) {
Stream_write_string(output, "[");
if (jscoverage_highlight) {
Stream * highlighted_stream = Stream_new(num_characters);
jscoverage_highlight_js(context, id, characters, num_characters, highlighted_stream);
size_t i = 0;
while (i < highlighted_stream->length) {
if (i > 0) {
Stream_write_char(output, ',');
}
Stream_write_char(output, '"');
bool done = false;
while (! done) {
char c = highlighted_stream->data[i];
switch (c) {
case 0x8:
/* backspace */
Stream_write_string(output, "\\b");
break;
case 0x9:
/* horizontal tab */
Stream_write_string(output, "\\t");
break;
case 0xa:
/* line feed (new line) */
done = true;
break;
/* IE doesn't support this */
/*
case 0xb:
Stream_write_string(output, "\\v");
break;
*/
case 0xc:
/* form feed */
Stream_write_string(output, "\\f");
break;
case 0xd:
/* carriage return */
done = true;
if (i + 1 < highlighted_stream->length && highlighted_stream->data[i + 1] == '\n') {
i++;
}
break;
case '"':
Stream_write_string(output, "\\\"");
break;
case '\\':
Stream_write_string(output, "\\\\");
break;
default:
Stream_write_char(output, c);
break;
}
i++;
if (i >= highlighted_stream->length) {
done = true;
}
}
Stream_write_char(output, '"');
}
Stream_delete(highlighted_stream);
}
else {
size_t i = 0;
while (i < num_characters) {
if (i > 0) {
Stream_write_char(output, ',');
}
Stream_write_char(output, '"');
bool done = false;
while (! done) {
jschar c = characters[i];
switch (c) {
case 0x8:
/* backspace */
Stream_write_string(output, "\\b");
break;
case 0x9:
/* horizontal tab */
Stream_write_string(output, "\\t");
break;
case 0xa:
/* line feed (new line) */
done = true;
break;
/* IE doesn't support this */
/*
case 0xb:
Stream_write_string(output, "\\v");
break;
*/
case 0xc:
/* form feed */
Stream_write_string(output, "\\f");
break;
case 0xd:
/* carriage return */
done = true;
if (i + 1 < num_characters && characters[i + 1] == '\n') {
i++;
}
break;
case '"':
Stream_write_string(output, "\\\"");
break;
case '\\':
Stream_write_string(output, "\\\\");
break;
case '&':
Stream_write_string(output, "&");
break;
case '<':
Stream_write_string(output, "<");
break;
case '>':
Stream_write_string(output, ">");
break;
case 0x2028:
case 0x2029:
done = true;
break;
default:
if (32 <= c && c <= 126) {
Stream_write_char(output, c);
}
else {
Stream_printf(output, "&#%d;", c);
}
break;
}
i++;
if (i >= num_characters) {
done = true;
}
}
Stream_write_char(output, '"');
}
}
Stream_write_string(output, "]");
}
void jscoverage_copy_resources(const char * destination_directory) {
copy_resource("jscoverage.html", destination_directory);
copy_resource("jscoverage.css", destination_directory);
copy_resource("jscoverage.js", destination_directory);
copy_resource("jscoverage-ie.css", destination_directory);
copy_resource("jscoverage-throbber.gif", destination_directory);
copy_resource("jscoverage-highlight.css", destination_directory);
}
/*
coverage reports
*/
struct FileCoverageList {
FileCoverage * file_coverage;
struct FileCoverageList * next;
};
struct Coverage {
JSHashTable * coverage_table;
struct FileCoverageList * coverage_list;
};
static int compare_strings(const void * p1, const void * p2) {
return strcmp((const char *) p1, (const char *) p2) == 0;
}
Coverage * Coverage_new(void) {
Coverage * result = (Coverage *) xmalloc(sizeof(Coverage));
result->coverage_table = JS_NewHashTable(1024, JS_HashString, compare_strings, NULL, NULL, NULL);
if (result->coverage_table == NULL) {
fatal("cannot create hash table");
}
result->coverage_list = NULL;
return result;
}
void Coverage_delete(Coverage * coverage) {
JS_HashTableDestroy(coverage->coverage_table);
struct FileCoverageList * p = coverage->coverage_list;
while (p != NULL) {
free(p->file_coverage->coverage_lines);
if (p->file_coverage->source_lines != NULL) {
for (uint32 i = 0; i < p->file_coverage->num_source_lines; i++) {
free(p->file_coverage->source_lines[i]);
}
free(p->file_coverage->source_lines);
}
free(p->file_coverage->id);
free(p->file_coverage);
struct FileCoverageList * q = p;
p = p->next;
free(q);
}
free(coverage);
}
struct EnumeratorArg {
CoverageForeachFunction f;
void * p;
};
static intN enumerator(JSHashEntry * entry, intN i, void * arg) {
struct EnumeratorArg * enumerator_arg = (struct EnumeratorArg *) arg;
enumerator_arg->f((FileCoverage *) entry->value, i, enumerator_arg->p);
return 0;
}
void Coverage_foreach_file(Coverage * coverage, CoverageForeachFunction f, void * p) {
struct EnumeratorArg enumerator_arg;
enumerator_arg.f = f;
enumerator_arg.p = p;
JS_HashTableEnumerateEntries(coverage->coverage_table, enumerator, &enumerator_arg);
}
int jscoverage_parse_json(Coverage * coverage, const uint8_t * json, size_t length) {
int result = 0;
jschar * base = js_InflateString(context, (char *) json, &length);
if (base == NULL) {
fatal("out of memory");
}
jschar * parenthesized_json = xnew(jschar, addst(length, 2));
parenthesized_json[0] = '(';
memcpy(parenthesized_json + 1, base, mulst(length, sizeof(jschar)));
parenthesized_json[length + 1] = ')';
JS_free(context, base);
JSParseContext parse_context;
if (! js_InitParseContext(context, &parse_context, NULL, NULL, parenthesized_json, length + 2, NULL, NULL, 1)) {
free(parenthesized_json);
return -1;
}
JSParseNode * root = js_ParseScript(context, global, &parse_context);
free(parenthesized_json);
JSParseNode * semi = NULL;
JSParseNode * object = NULL;
if (root == NULL) {
result = -1;
goto done;
}
/* root node must be TOK_LC */
if (root->pn_type != TOK_LC) {
result = -1;
goto done;
}
semi = root->pn_u.list.head;
/* the list must be TOK_SEMI and it must contain only one element */
if (semi->pn_type != TOK_SEMI || semi->pn_next != NULL) {
result = -1;
goto done;
}
object = semi->pn_kid;
/* this must be an object literal */
if (object->pn_type != TOK_RC) {
result = -1;
goto done;
}
for (JSParseNode * p = object->pn_head; p != NULL; p = p->pn_next) {
/* every element of this list must be TOK_COLON */
if (p->pn_type != TOK_COLON) {
result = -1;
goto done;
}
/* the key must be a string representing the file */
JSParseNode * key = p->pn_left;
if (key->pn_type != TOK_STRING || ! ATOM_IS_STRING(key->pn_atom)) {
result = -1;
goto done;
}
char * id_bytes = JS_GetStringBytes(ATOM_TO_STRING(key->pn_atom));
/* the value must be an object literal OR an array */
JSParseNode * value = p->pn_right;
if (! (value->pn_type == TOK_RC || value->pn_type == TOK_RB)) {
result = -1;
goto done;
}
JSParseNode * array = NULL;
JSParseNode * source = NULL;
if (value->pn_type == TOK_RB) {
/* an array */
array = value;
}
else if (value->pn_type == TOK_RC) {
/* an object literal */
if (value->pn_count != 2) {
result = -1;
goto done;
}
for (JSParseNode * element = value->pn_head; element != NULL; element = element->pn_next) {
if (element->pn_type != TOK_COLON) {
result = -1;
goto done;
}
JSParseNode * left = element->pn_left;
if (left->pn_type != TOK_STRING || ! ATOM_IS_STRING(left->pn_atom)) {
result = -1;
goto done;
}
const char * s = JS_GetStringBytes(ATOM_TO_STRING(left->pn_atom));
if (strcmp(s, "coverage") == 0) {
array = element->pn_right;
if (array->pn_type != TOK_RB) {
result = -1;
goto done;
}
}
else if (strcmp(s, "source") == 0) {
source = element->pn_right;
if (source->pn_type != TOK_RB) {
result = -1;
goto done;
}
}
else {
result = -1;
goto done;
}
}
}
else {
result = -1;
goto done;
}
if (array == NULL) {
result = -1;
goto done;
}
/* look up the file in the coverage table */
FileCoverage * file_coverage = (FileCoverage *) JS_HashTableLookup(coverage->coverage_table, id_bytes);
if (file_coverage == NULL) {
/* not there: create a new one */
char * id = xstrdup(id_bytes);
file_coverage = (FileCoverage *) xmalloc(sizeof(FileCoverage));
file_coverage->id = id;
file_coverage->num_coverage_lines = array->pn_count;
file_coverage->coverage_lines = xnew(int, array->pn_count);
file_coverage->source_lines = NULL;
/* set coverage for all lines */
uint32 i = 0;
for (JSParseNode * element = array->pn_head; element != NULL; element = element->pn_next, i++) {
if (element->pn_type == TOK_NUMBER) {
file_coverage->coverage_lines[i] = (int) element->pn_dval;
}
else if (element->pn_type == TOK_PRIMARY && element->pn_op == JSOP_NULL) {
file_coverage->coverage_lines[i] = -1;
}
else {
result = -1;
goto done;
}
}
assert(i == array->pn_count);
/* add to the hash table */
JS_HashTableAdd(coverage->coverage_table, id, file_coverage);
struct FileCoverageList * coverage_list = (FileCoverageList *) xmalloc(sizeof(struct FileCoverageList));
coverage_list->file_coverage = file_coverage;
coverage_list->next = coverage->coverage_list;
coverage->coverage_list = coverage_list;
}
else {
/* sanity check */
assert(strcmp(file_coverage->id, id_bytes) == 0);
if (file_coverage->num_coverage_lines != array->pn_count) {
result = -2;
goto done;
}
/* merge the coverage */
uint32 i = 0;
for (JSParseNode * element = array->pn_head; element != NULL; element = element->pn_next, i++) {
if (element->pn_type == TOK_NUMBER) {
if (file_coverage->coverage_lines[i] == -1) {
result = -2;
goto done;
}
file_coverage->coverage_lines[i] += (int) element->pn_dval;
}
else if (element->pn_type == TOK_PRIMARY && element->pn_op == JSOP_NULL) {
if (file_coverage->coverage_lines[i] != -1) {
result = -2;
goto done;
}
}
else {
result = -1;
goto done;
}
}
assert(i == array->pn_count);
}
/* if this JSON file has source, use it */
if (file_coverage->source_lines == NULL && source != NULL) {
file_coverage->num_source_lines = source->pn_count;
file_coverage->source_lines = xnew(char *, source->pn_count);
uint32 i = 0;
for (JSParseNode * element = source->pn_head; element != NULL; element = element->pn_next, i++) {
if (element->pn_type != TOK_STRING) {
result = -1;
goto done;
}
file_coverage->source_lines[i] = xstrdup(JS_GetStringBytes(ATOM_TO_STRING(element->pn_atom)));
}
assert(i == source->pn_count);
}
}
done:
js_FinishParseContext(context, &parse_context);
return result;
}
| mit |
Dmitry-Me/coreclr | src/pal/tests/palsuite/locale_info/GetUserDefaultLangID/test1/test1.cpp | 112 | 1582 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================================
**
** Source: test1.c
**
** Purpose: Checks that GetUserDefaultLangID can be used to make a valid
** locale, and that it is consistent with LOCALE_USER_DEFAULT.
**
**
**==========================================================================*/
#include <palsuite.h>
int __cdecl main(int argc, char *argv[])
{
LCID lcid;
LANGID LangID;
if (PAL_Initialize(argc, argv))
{
return FAIL;
}
LangID = GetUserDefaultLangID();
if (LangID == 0)
{
Fail("GetUserDefaultLangID failed!\n");
}
/* Try using the langid (with default sort) as a locale */
if (!SetThreadLocale(MAKELCID(LangID, SORT_DEFAULT)))
{
Fail("Unable to use GetUserDefaultLangID as a locale!\n");
}
lcid = GetThreadLocale();
if (!IsValidLocale(lcid, LCID_INSTALLED))
{
Fail("Unable to use GetUserDefaultLangID as a locale!\n");
}
/* Make sure results consistent with using LOCALE_USER_DEFAULT */
if (!SetThreadLocale(LOCALE_USER_DEFAULT))
{
Fail("Unexpected error testing GetUserDefaultLangID!\n");
}
if (GetThreadLocale() != lcid)
{
Fail("Results from GetUserDefaultLangID inconsistent with "
"LOCALE_USER_DEFAULT!\n");
}
PAL_Terminate();
return PASS;
}
| mit |
coapp-packages/libffi | testsuite/libffi.call/va_struct2.c | 375 | 2296 | /* Area: ffi_call
Purpose: Test passing struct in variable argument lists.
Limitations: none.
PR: none.
Originator: ARM Ltd. */
/* { dg-do run } */
/* { dg-output "" { xfail avr32*-*-* } } */
#include "ffitest.h"
#include <stdarg.h>
struct small_tag
{
unsigned char a;
unsigned char b;
};
struct large_tag
{
unsigned a;
unsigned b;
unsigned c;
unsigned d;
unsigned e;
};
static struct small_tag
test_fn (int n, ...)
{
va_list ap;
struct small_tag s1;
struct small_tag s2;
struct large_tag l;
va_start (ap, n);
s1 = va_arg (ap, struct small_tag);
l = va_arg (ap, struct large_tag);
s2 = va_arg (ap, struct small_tag);
printf ("%u %u %u %u %u %u %u %u %u\n", s1.a, s1.b, l.a, l.b, l.c, l.d, l.e,
s2.a, s2.b);
va_end (ap);
s1.a += s2.a;
s1.b += s2.b;
return s1;
}
int
main (void)
{
ffi_cif cif;
void* args[5];
ffi_type* arg_types[5];
ffi_type s_type;
ffi_type *s_type_elements[3];
ffi_type l_type;
ffi_type *l_type_elements[6];
struct small_tag s1;
struct small_tag s2;
struct large_tag l1;
int n;
struct small_tag res;
s_type.size = 0;
s_type.alignment = 0;
s_type.type = FFI_TYPE_STRUCT;
s_type.elements = s_type_elements;
s_type_elements[0] = &ffi_type_uchar;
s_type_elements[1] = &ffi_type_uchar;
s_type_elements[2] = NULL;
l_type.size = 0;
l_type.alignment = 0;
l_type.type = FFI_TYPE_STRUCT;
l_type.elements = l_type_elements;
l_type_elements[0] = &ffi_type_uint;
l_type_elements[1] = &ffi_type_uint;
l_type_elements[2] = &ffi_type_uint;
l_type_elements[3] = &ffi_type_uint;
l_type_elements[4] = &ffi_type_uint;
l_type_elements[5] = NULL;
arg_types[0] = &ffi_type_sint;
arg_types[1] = &s_type;
arg_types[2] = &l_type;
arg_types[3] = &s_type;
arg_types[4] = NULL;
CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &s_type, arg_types) == FFI_OK);
s1.a = 5;
s1.b = 6;
l1.a = 10;
l1.b = 11;
l1.c = 12;
l1.d = 13;
l1.e = 14;
s2.a = 7;
s2.b = 8;
n = 41;
args[0] = &n;
args[1] = &s1;
args[2] = &l1;
args[3] = &s2;
args[4] = NULL;
ffi_call(&cif, FFI_FN(test_fn), &res, args);
/* { dg-output "5 6 10 11 12 13 14 7 8" } */
printf("res: %d %d\n", res.a, res.b);
/* { dg-output "\nres: 12 14" } */
return 0;
}
| mit |
cloudmonkeypeng/WinObjC | deps/3rdparty/icu/icu/source/samples/layout/gnomelayout.cpp | 385 | 8408 |
/*
****************************************************************************** *
*
* Copyright (C) 1999-2007, International Business Machines
* Corporation and others. All Rights Reserved.
*
****************************************************************************** *
* file name: gnomelayout.cpp
*
* created on: 09/04/2001
* created by: Eric R. Mader
*/
#include <gnome.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include "unicode/ustring.h"
#include "unicode/uscript.h"
#include "GnomeFontInstance.h"
#include "paragraph.h"
#include "GnomeGUISupport.h"
#include "GnomeFontMap.h"
#include "UnicodeReader.h"
#include "ScriptCompositeFontInstance.h"
#define ARRAY_LENGTH(array) (sizeof array / sizeof array[0])
struct Context
{
long width;
long height;
Paragraph *paragraph;
};
static FT_Library engine;
static GnomeGUISupport *guiSupport;
static GnomeFontMap *fontMap;
static ScriptCompositeFontInstance *font;
static GSList *appList = NULL;
GtkWidget *newSample(const gchar *fileName);
void closeSample(GtkWidget *sample);
void showabout(GtkWidget */*widget*/, gpointer /*data*/)
{
GtkWidget *aboutBox;
const gchar *documentedBy[] = {NULL};
const gchar *writtenBy[] = {
"Eric Mader",
NULL
};
aboutBox = gnome_about_new("Gnome Layout Sample",
"0.1",
"Copyright (C) 1998-2006 By International Business Machines Corporation and others. All Rights Reserved.",
"A simple demo of the ICU LayoutEngine.",
writtenBy,
documentedBy,
"",
NULL);
gtk_widget_show(aboutBox);
}
void notimpl(GtkObject */*object*/, gpointer /*data*/)
{
gnome_ok_dialog("Not implemented...");
}
gchar *prettyTitle(const gchar *path)
{
const gchar *name = g_basename(path);
gchar *title = g_strconcat("Gnome Layout Sample - ", name, NULL);
return title;
}
void openOK(GtkObject */*object*/, gpointer data)
{
GtkFileSelection *fileselection = GTK_FILE_SELECTION(data);
GtkWidget *app = GTK_WIDGET(gtk_object_get_data(GTK_OBJECT(fileselection), "app"));
Context *context = (Context *) gtk_object_get_data(GTK_OBJECT(app), "context");
gchar *fileName = g_strdup(gtk_file_selection_get_filename(fileselection));
Paragraph *newPara;
gtk_widget_destroy(GTK_WIDGET(fileselection));
newPara = Paragraph::paragraphFactory(fileName, font, guiSupport);
if (newPara != NULL) {
gchar *title = prettyTitle(fileName);
GtkWidget *area = GTK_WIDGET(gtk_object_get_data(GTK_OBJECT(app), "area"));
if (context->paragraph != NULL) {
delete context->paragraph;
}
context->paragraph = newPara;
gtk_window_set_title(GTK_WINDOW(app), title);
gtk_widget_hide(area);
context->paragraph->breakLines(context->width, context->height);
gtk_widget_show_all(area);
g_free(title);
}
g_free(fileName);
}
void openfile(GtkObject */*object*/, gpointer data)
{
GtkWidget *app = GTK_WIDGET(data);
GtkWidget *fileselection;
GtkWidget *okButton;
GtkWidget *cancelButton;
fileselection =
gtk_file_selection_new("Open File");
gtk_object_set_data(GTK_OBJECT(fileselection), "app", app);
okButton =
GTK_FILE_SELECTION(fileselection)->ok_button;
cancelButton =
GTK_FILE_SELECTION(fileselection)->cancel_button;
gtk_signal_connect(GTK_OBJECT(fileselection), "destroy",
GTK_SIGNAL_FUNC(gtk_main_quit), NULL);
gtk_signal_connect(GTK_OBJECT(okButton), "clicked",
GTK_SIGNAL_FUNC(openOK), fileselection);
gtk_signal_connect_object(GTK_OBJECT(cancelButton), "clicked",
GTK_SIGNAL_FUNC(gtk_widget_destroy), GTK_OBJECT(fileselection));
gtk_window_set_modal(GTK_WINDOW(fileselection), TRUE);
gtk_widget_show(fileselection);
gtk_main();
}
void newapp(GtkObject */*object*/, gpointer /*data*/)
{
GtkWidget *app = newSample("Sample.txt");
gtk_widget_show_all(app);
}
void closeapp(GtkWidget */*widget*/, gpointer data)
{
GtkWidget *app = GTK_WIDGET(data);
closeSample(app);
}
void shutdown(GtkObject */*object*/, gpointer /*data*/)
{
gtk_main_quit();
}
GnomeUIInfo fileMenu[] =
{
GNOMEUIINFO_MENU_NEW_ITEM((gchar *) "_New Sample",
(gchar *) "Create a new Gnome Layout Sample",
newapp, NULL),
GNOMEUIINFO_MENU_OPEN_ITEM(openfile, NULL),
GNOMEUIINFO_SEPARATOR,
GNOMEUIINFO_MENU_CLOSE_ITEM(closeapp, NULL),
GNOMEUIINFO_MENU_EXIT_ITEM(shutdown, NULL),
GNOMEUIINFO_END
};
GnomeUIInfo helpMenu[] =
{
// GNOMEUIINFO_HELP("gnomelayout"),
GNOMEUIINFO_MENU_ABOUT_ITEM(showabout, NULL),
GNOMEUIINFO_END
};
GnomeUIInfo mainMenu[] =
{
GNOMEUIINFO_SUBTREE(N_((gchar *) "File"), fileMenu),
GNOMEUIINFO_SUBTREE(N_((gchar *) "Help"), helpMenu),
GNOMEUIINFO_END
};
gint eventDelete(GtkWidget *widget, GdkEvent */*event*/, gpointer /*data*/)
{
closeSample(widget);
// indicate that closeapp already destroyed the window
return TRUE;
}
gint eventConfigure(GtkWidget */*widget*/, GdkEventConfigure *event, Context *context)
{
if (context->paragraph != NULL) {
context->width = event->width;
context->height = event->height;
if (context->width > 0 && context->height > 0) {
context->paragraph->breakLines(context->width, context->height);
}
}
return TRUE;
}
gint eventExpose(GtkWidget *widget, GdkEvent */*event*/, Context *context)
{
if (context->paragraph != NULL) {
gint maxLines = context->paragraph->getLineCount() - 1;
gint firstLine = 0, lastLine = context->height / context->paragraph->getLineHeight();
GnomeSurface surface(widget);
context->paragraph->draw(&surface, firstLine, (maxLines < lastLine)? maxLines : lastLine);
}
return TRUE;
}
GtkWidget *newSample(const gchar *fileName)
{
Context *context = new Context();
context->width = 600;
context->height = 400;
context->paragraph = Paragraph::paragraphFactory(fileName, font, guiSupport);
gchar *title = prettyTitle(fileName);
GtkWidget *app = gnome_app_new("gnomeLayout", title);
gtk_object_set_data(GTK_OBJECT(app), "context", context);
gtk_window_set_default_size(GTK_WINDOW(app), 600 - 24, 400);
gnome_app_create_menus_with_data(GNOME_APP(app), mainMenu, app);
gtk_signal_connect(GTK_OBJECT(app), "delete_event",
GTK_SIGNAL_FUNC(eventDelete), NULL);
GtkWidget *area = gtk_drawing_area_new();
gtk_object_set_data(GTK_OBJECT(app), "area", area);
GtkStyle *style = gtk_style_copy(gtk_widget_get_style(area));
for (int i = 0; i < 5; i += 1) {
style->fg[i] = style->white;
}
gtk_widget_set_style(area, style);
gnome_app_set_contents(GNOME_APP(app), area);
gtk_signal_connect(GTK_OBJECT(area),
"expose_event",
GTK_SIGNAL_FUNC(eventExpose),
context);
gtk_signal_connect(GTK_OBJECT(area),
"configure_event",
GTK_SIGNAL_FUNC(eventConfigure),
context);
appList = g_slist_prepend(appList, app);
g_free(title);
return app;
}
void closeSample(GtkWidget *app)
{
Context *context = (Context *) gtk_object_get_data(GTK_OBJECT(app), "context");
if (context->paragraph != NULL) {
delete context->paragraph;
}
delete context;
appList = g_slist_remove(appList, app);
gtk_widget_destroy(app);
if (appList == NULL) {
gtk_main_quit();
}
}
int main (int argc, char *argv[])
{
LEErrorCode fontStatus = LE_NO_ERROR;
poptContext ptctx;
GtkWidget *app;
FT_Init_FreeType(&engine);
gnome_init_with_popt_table("gnomelayout", "0.1", argc, argv, NULL, 0, &ptctx);
guiSupport = new GnomeGUISupport();
fontMap = new GnomeFontMap(engine, "FontMap.Gnome", 24, guiSupport, fontStatus);
font = new ScriptCompositeFontInstance(fontMap);
if (LE_FAILURE(fontStatus)) {
FT_Done_FreeType(engine);
return 1;
}
const char *defaultArgs[] = {"Sample.txt", NULL};
const char **args = poptGetArgs(ptctx);
if (args == NULL) {
args = defaultArgs;
}
for (int i = 0; args[i] != NULL; i += 1) {
app = newSample(args[i]);
gtk_widget_show_all(app);
}
poptFreeContext(ptctx);
gtk_main();
delete font;
delete guiSupport;
FT_Done_FreeType(engine);
exit(0);
}
| mit |
bqstony/Windows-universal-samples | Samples/StreamSocket/cpp/Scenario3.xaml.cpp | 135 | 3131 | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
//
// Scenario3.xaml.cpp
// Implementation of the Scenario3 class
//
#include "pch.h"
#include "Scenario3.xaml.h"
using namespace SDKTemplate::StreamSocketSample;
using namespace Concurrency;
using namespace Platform;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::Foundation;
using namespace Windows::Networking::Sockets;
using namespace Windows::Storage::Streams;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
Scenario3::Scenario3()
{
InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
rootPage = MainPage::Current;
}
void Scenario3::SendHello_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
if (!CoreApplication::Properties->HasKey("connected"))
{
rootPage->NotifyUser("Please run previous steps before doing this one.", NotifyType::ErrorMessage);
return;
}
StreamSocket^ socket = dynamic_cast<StreamSocket^>(CoreApplication::Properties->Lookup("clientSocket"));
DataWriter^ writer;
// If possible, use the DataWriter we created previously. If not, then create new one.
if (!CoreApplication::Properties->HasKey("clientDataWriter"))
{
writer = ref new DataWriter(socket->OutputStream);
CoreApplication::Properties->Insert("clientDataWriter", writer);
}
else
{
writer = dynamic_cast<DataWriter^>(CoreApplication::Properties->Lookup("clientDataWriter"));
}
// Write first the length of the string a UINT32 value followed up by the string. The operation will just store
// the data locally.
String^ stringToSend("Hello");
writer->WriteUInt32(writer->MeasureString(stringToSend));
writer->WriteString(stringToSend);
// Write the locally buffered data to the network.
create_task(writer->StoreAsync()).then([this, socket, stringToSend] (task<unsigned int> writeTask)
{
try
{
// Try getting an exception.
writeTask.get();
SendOutput->Text = "\"" + stringToSend + "\" sent successfully";
}
catch (Exception^ exception)
{
rootPage->NotifyUser("Send failed with error: " + exception->Message, NotifyType::ErrorMessage);
}
});
}
| mit |
utilite2/lk | lib/openssl/crypto/rc4/rc4test.c | 153 | 7613 | /* crypto/rc4/rc4test.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 <stdlib.h>
#include <string.h>
#include "../e_os.h"
#ifdef OPENSSL_NO_RC4
int main(int argc, char *argv[])
{
printf("No RC4 support\n");
return(0);
}
#else
#include <openssl/rc4.h>
#include <openssl/sha.h>
static unsigned char keys[7][30]={
{8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef},
{8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef},
{8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{4,0xef,0x01,0x23,0x45},
{8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef},
{4,0xef,0x01,0x23,0x45},
};
static unsigned char data_len[7]={8,8,8,20,28,10};
static unsigned char data[7][30]={
{0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xff},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xff},
{0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0,
0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0,
0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0,
0x12,0x34,0x56,0x78,0xff},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff},
{0},
};
static unsigned char output[7][30]={
{0x75,0xb7,0x87,0x80,0x99,0xe0,0xc5,0x96,0x00},
{0x74,0x94,0xc2,0xe7,0x10,0x4b,0x08,0x79,0x00},
{0xde,0x18,0x89,0x41,0xa3,0x37,0x5d,0x3a,0x00},
{0xd6,0xa1,0x41,0xa7,0xec,0x3c,0x38,0xdf,
0xbd,0x61,0x5a,0x11,0x62,0xe1,0xc7,0xba,
0x36,0xb6,0x78,0x58,0x00},
{0x66,0xa0,0x94,0x9f,0x8a,0xf7,0xd6,0x89,
0x1f,0x7f,0x83,0x2b,0xa8,0x33,0xc0,0x0c,
0x89,0x2e,0xbe,0x30,0x14,0x3c,0xe2,0x87,
0x40,0x01,0x1e,0xcf,0x00},
{0xd6,0xa1,0x41,0xa7,0xec,0x3c,0x38,0xdf,0xbd,0x61,0x00},
{0},
};
int main(int argc, char *argv[])
{
int i,err=0;
int j;
unsigned char *p;
RC4_KEY key;
unsigned char obuf[512];
for (i=0; i<6; i++)
{
RC4_set_key(&key,keys[i][0],&(keys[i][1]));
memset(obuf,0x00,sizeof(obuf));
RC4(&key,data_len[i],&(data[i][0]),obuf);
if (memcmp(obuf,output[i],data_len[i]+1) != 0)
{
printf("error calculating RC4\n");
printf("output:");
for (j=0; j<data_len[i]+1; j++)
printf(" %02x",obuf[j]);
printf("\n");
printf("expect:");
p= &(output[i][0]);
for (j=0; j<data_len[i]+1; j++)
printf(" %02x",*(p++));
printf("\n");
err++;
}
else
printf("test %d ok\n",i);
}
printf("test end processing ");
for (i=0; i<data_len[3]; i++)
{
RC4_set_key(&key,keys[3][0],&(keys[3][1]));
memset(obuf,0x00,sizeof(obuf));
RC4(&key,i,&(data[3][0]),obuf);
if ((memcmp(obuf,output[3],i) != 0) || (obuf[i] != 0))
{
printf("error in RC4 length processing\n");
printf("output:");
for (j=0; j<i+1; j++)
printf(" %02x",obuf[j]);
printf("\n");
printf("expect:");
p= &(output[3][0]);
for (j=0; j<i; j++)
printf(" %02x",*(p++));
printf(" 00\n");
err++;
}
else
{
printf(".");
fflush(stdout);
}
}
printf("done\n");
printf("test multi-call ");
for (i=0; i<data_len[3]; i++)
{
RC4_set_key(&key,keys[3][0],&(keys[3][1]));
memset(obuf,0x00,sizeof(obuf));
RC4(&key,i,&(data[3][0]),obuf);
RC4(&key,data_len[3]-i,&(data[3][i]),&(obuf[i]));
if (memcmp(obuf,output[3],data_len[3]+1) != 0)
{
printf("error in RC4 multi-call processing\n");
printf("output:");
for (j=0; j<data_len[3]+1; j++)
printf(" %02x",obuf[j]);
printf("\n");
printf("expect:");
p= &(output[3][0]);
for (j=0; j<data_len[3]+1; j++)
printf(" %02x",*(p++));
err++;
}
else
{
printf(".");
fflush(stdout);
}
}
printf("done\n");
printf("bulk test ");
{ unsigned char buf[513];
SHA_CTX c;
unsigned char md[SHA_DIGEST_LENGTH];
static unsigned char expected[]={
0xa4,0x7b,0xcc,0x00,0x3d,0xd0,0xbd,0xe1,0xac,0x5f,
0x12,0x1e,0x45,0xbc,0xfb,0x1a,0xa1,0xf2,0x7f,0xc5 };
RC4_set_key(&key,keys[0][0],&(keys[3][1]));
memset(buf,'\0',sizeof(buf));
SHA1_Init(&c);
for (i=0;i<2571;i++) {
RC4(&key,sizeof(buf),buf,buf);
SHA1_Update(&c,buf,sizeof(buf));
}
SHA1_Final(md,&c);
if (memcmp(md,expected,sizeof(md))) {
printf("error in RC4 bulk test\n");
printf("output:");
for (j=0; j<(int)sizeof(md); j++)
printf(" %02x",md[j]);
printf("\n");
printf("expect:");
for (j=0; j<(int)sizeof(md); j++)
printf(" %02x",expected[j]);
printf("\n");
err++;
}
else printf("ok\n");
}
#ifdef OPENSSL_SYS_NETWARE
if (err) printf("ERROR: %d\n", err);
#endif
EXIT(err);
return(0);
}
#endif
| mit |
DKrepsky/CC3200-Linux-SDK | examples/NWP Filter/startup_gcc.c | 154 | 13791 | //*****************************************************************************
// startup_gcc.c
//
// Startup code for use with GCC.
//
// Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
//
//
// 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 Texas Instruments Incorporated nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//*****************************************************************************
#include <stdint.h>
#include "hw_nvic.h"
#include "hw_types.h"
//*****************************************************************************
//
// Heap block pointers defined by linker script
//
//*****************************************************************************
static char *heap_end = 0;
extern unsigned long _heap;
extern unsigned long _eheap;
//*****************************************************************************
//
// Forward declaration of the default fault handlers.
//
//*****************************************************************************
void ResetISR(void);
static void NmiSR(void);
static void FaultISR(void);
static void IntDefaultHandler(void);
static void BusFaultHandler(void);
//*****************************************************************************
//
// External declaration for the reset handler that is to be called when the
// processor is started
//
//*****************************************************************************
extern void vPortSVCHandler(void);
extern void xPortPendSVHandler(void);
extern void xPortSysTickHandler(void);
//*****************************************************************************
//
// The entry point for the application.
//
//*****************************************************************************
extern int main(void);
//*****************************************************************************
//
// Reserve space for the system stack.
//
//*****************************************************************************
static uint32_t pui32Stack[1024];
//*****************************************************************************
//
// The vector table. Note that the proper constructs must be placed on this to
// ensure that it ends up at physical address 0x0000.0000.
//
//*****************************************************************************
__attribute__ ((section(".intvecs")))
void (* const g_pfnVectors[256])(void) =
{
(void (*)(void))((uint32_t)pui32Stack + sizeof(pui32Stack)),
// The initial stack pointer
ResetISR, // The reset handler
NmiSR, // The NMI handler
FaultISR, // The hard fault handler
IntDefaultHandler, // The MPU fault handler
BusFaultHandler, // The bus fault handler
IntDefaultHandler, // The usage fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
#ifdef USE_FREERTOS
vPortSVCHandler, // SVCall handler
#else
IntDefaultHandler, // SVCall handler
#endif
IntDefaultHandler, // Debug monitor handler
0, // Reserved
#ifdef USE_FREERTOS
xPortPendSVHandler, // The PendSV handler
xPortSysTickHandler, // The SysTick handler
#else
IntDefaultHandler, // The PendSV handler
IntDefaultHandler, // The SysTick handler
#endif
IntDefaultHandler, // GPIO Port A
IntDefaultHandler, // GPIO Port B
IntDefaultHandler, // GPIO Port C
IntDefaultHandler, // GPIO Port D
0, // Reserved
IntDefaultHandler, // UART0 Rx and Tx
IntDefaultHandler, // UART1 Rx and Tx
0, // Reserved
IntDefaultHandler, // I2C0 Master and Slave
0,0,0,0,0, // Reserved
IntDefaultHandler, // ADC Channel 0
IntDefaultHandler, // ADC Channel 1
IntDefaultHandler, // ADC Channel 2
IntDefaultHandler, // ADC Channel 3
IntDefaultHandler, // Watchdog Timer
IntDefaultHandler, // Timer 0 subtimer A
IntDefaultHandler, // Timer 0 subtimer B
IntDefaultHandler, // Timer 1 subtimer A
IntDefaultHandler, // Timer 1 subtimer B
IntDefaultHandler, // Timer 2 subtimer A
IntDefaultHandler, // Timer 2 subtimer B
0,0,0,0, // Reserved
IntDefaultHandler, // Flash
0,0,0,0,0, // Reserved
IntDefaultHandler, // Timer 3 subtimer A
IntDefaultHandler, // Timer 3 subtimer B
0,0,0,0,0,0,0,0,0, // Reserved
IntDefaultHandler, // uDMA Software Transfer
IntDefaultHandler, // uDMA Error
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
IntDefaultHandler, // SHA
0,0, // Reserved
IntDefaultHandler, // AES
0, // Reserved
IntDefaultHandler, // DES
0,0,0,0,0, // Reserved
IntDefaultHandler, // SDHost
0, // Reserved
IntDefaultHandler, // I2S
0, // Reserved
IntDefaultHandler, // Camera
0,0,0,0,0,0,0, // Reserved
IntDefaultHandler, // NWP to APPS Interrupt
IntDefaultHandler, // Power, Reset and Clock module
0,0, // Reserved
IntDefaultHandler, // Shared SPI
IntDefaultHandler, // Generic SPI
IntDefaultHandler, // Link SPI
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0,0,0,0,0,0,0,0,0, // Reserved
0,0 // Reserved
};
//*****************************************************************************
//
// The following are constructs created by the linker, indicating where the
// the "data" and "bss" segments reside in memory. The initializers for the
// for the "data" segment resides immediately following the "text" segment.
//
//*****************************************************************************
extern uint32_t _data;
extern uint32_t _edata;
extern uint32_t _bss;
extern uint32_t _ebss;
extern uint32_t __init_data;
//*****************************************************************************
//
// This is the code that gets called when the processor first starts execution
// following a reset event. Only the absolutely necessary set is performed,
// after which the application supplied entry() routine is called. Any fancy
// actions (such as making decisions based on the reset cause register, and
// resetting the bits in that register) are left solely in the hands of the
// application.
//
//*****************************************************************************
void
ResetISR(void)
{
uint32_t *pui32Src, *pui32Dest;
//
// Copy the data segment initializers
//
pui32Src = &__init_data;
for(pui32Dest = &_data; pui32Dest < &_edata; )
{
*pui32Dest++ = *pui32Src++;
}
//
// Zero fill the bss segment.
//
__asm(" ldr r0, =_bss\n"
" ldr r1, =_ebss\n"
" mov r2, #0\n"
" .thumb_func\n"
"zero_loop:\n"
" cmp r0, r1\n"
" it lt\n"
" strlt r2, [r0], #4\n"
" blt zero_loop");
//
// Call the application's entry point.
//
main();
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a NMI. This
// simply enters an infinite loop, preserving the system state for examination
// by a debugger.
//
//*****************************************************************************
static void
NmiSR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a fault
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
FaultISR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives an unexpected
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
BusFaultHandler(void)
{
//
// Go into an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives an unexpected
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
IntDefaultHandler(void)
{
//
// Go into an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This function is used by dynamic memory allocation API(s) in newlib
// library
//
//*****************************************************************************
void * _sbrk(unsigned int incr)
{
char *prev_heap_end;
//
// Check if this function is calld for the
// first time and the heap end pointer
//
if (heap_end == 0)
{
heap_end = (char *)&_heap;
}
//
// Check if we have enough heap memory available
//
prev_heap_end = heap_end;
if (heap_end + incr > (char *)&_eheap)
{
//
// Return error
//
return 0;
}
//
// Set the new heap end pointer
//
heap_end += incr;
//
// Return the pointer to the newly allocated memory
//
return prev_heap_end;
}
| mit |
segafan/wmelite_hcdaniel-dependencies-repo | dependencies/libfreetype-android/jni/src/pshinter/pshmod.c | 413 | 3521 | /***************************************************************************/
/* */
/* pshmod.c */
/* */
/* FreeType PostScript hinter module implementation (body). */
/* */
/* Copyright 2001, 2002, 2007, 2009, 2012 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_INTERNAL_OBJECTS_H
#include "pshrec.h"
#include "pshalgo.h"
#include "pshpic.h"
/* the Postscript Hinter module structure */
typedef struct PS_Hinter_Module_Rec_
{
FT_ModuleRec root;
PS_HintsRec ps_hints;
PSH_Globals_FuncsRec globals_funcs;
T1_Hints_FuncsRec t1_funcs;
T2_Hints_FuncsRec t2_funcs;
} PS_Hinter_ModuleRec, *PS_Hinter_Module;
/* finalize module */
FT_CALLBACK_DEF( void )
ps_hinter_done( PS_Hinter_Module module )
{
module->t1_funcs.hints = NULL;
module->t2_funcs.hints = NULL;
ps_hints_done( &module->ps_hints );
}
/* initialize module, create hints recorder and the interface */
FT_CALLBACK_DEF( FT_Error )
ps_hinter_init( PS_Hinter_Module module )
{
FT_Memory memory = module->root.memory;
void* ph = &module->ps_hints;
ps_hints_init( &module->ps_hints, memory );
psh_globals_funcs_init( &module->globals_funcs );
t1_hints_funcs_init( &module->t1_funcs );
module->t1_funcs.hints = (T1_Hints)ph;
t2_hints_funcs_init( &module->t2_funcs );
module->t2_funcs.hints = (T2_Hints)ph;
return 0;
}
/* returns global hints interface */
FT_CALLBACK_DEF( PSH_Globals_Funcs )
pshinter_get_globals_funcs( FT_Module module )
{
return &((PS_Hinter_Module)module)->globals_funcs;
}
/* return Type 1 hints interface */
FT_CALLBACK_DEF( T1_Hints_Funcs )
pshinter_get_t1_funcs( FT_Module module )
{
return &((PS_Hinter_Module)module)->t1_funcs;
}
/* return Type 2 hints interface */
FT_CALLBACK_DEF( T2_Hints_Funcs )
pshinter_get_t2_funcs( FT_Module module )
{
return &((PS_Hinter_Module)module)->t2_funcs;
}
FT_DEFINE_PSHINTER_INTERFACE(
pshinter_interface,
pshinter_get_globals_funcs,
pshinter_get_t1_funcs,
pshinter_get_t2_funcs )
FT_DEFINE_MODULE(
pshinter_module_class,
0,
sizeof ( PS_Hinter_ModuleRec ),
"pshinter",
0x10000L,
0x20000L,
&PSHINTER_INTERFACE_GET, /* module-specific interface */
(FT_Module_Constructor)ps_hinter_init,
(FT_Module_Destructor) ps_hinter_done,
(FT_Module_Requester) NULL ) /* no additional interface for now */
/* END */
| mit |
azureplus/WinObjC | deps/3rdparty/icu/icu/source/test/intltest/tufmtts.cpp | 166 | 21020 | /********************************************************************
* Copyright (c) 2008-2014, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/decimfmt.h"
#include "unicode/tmunit.h"
#include "unicode/tmutamt.h"
#include "unicode/tmutfmt.h"
#include "tufmtts.h"
#include "cmemory.h"
#include "unicode/ustring.h"
//TODO: put as compilation flag
//#define TUFMTTS_DEBUG 1
#ifdef TUFMTTS_DEBUG
#include <iostream>
#endif
void TimeUnitTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ ) {
if (exec) logln("TestSuite TimeUnitTest");
switch (index) {
TESTCASE(0, testBasic);
TESTCASE(1, testAPI);
TESTCASE(2, testGreekWithFallback);
TESTCASE(3, testGreekWithSanitization);
TESTCASE(4, test10219Plurals);
default: name = ""; break;
}
}
// This function is more lenient than equals operator as it considers integer 3 hours and
// double 3.0 hours to be equal
static UBool tmaEqual(const TimeUnitAmount& left, const TimeUnitAmount& right) {
if (left.getTimeUnitField() != right.getTimeUnitField()) {
return FALSE;
}
UErrorCode status = U_ZERO_ERROR;
if (!left.getNumber().isNumeric() || !right.getNumber().isNumeric()) {
return FALSE;
}
UBool result = left.getNumber().getDouble(status) == right.getNumber().getDouble(status);
if (U_FAILURE(status)) {
return FALSE;
}
return result;
}
/**
* Test basic
*/
void TimeUnitTest::testBasic() {
const char* locales[] = {"en", "sl", "fr", "zh", "ar", "ru", "zh_Hant", "pa"};
for ( unsigned int locIndex = 0;
locIndex < sizeof(locales)/sizeof(locales[0]);
++locIndex ) {
UErrorCode status = U_ZERO_ERROR;
Locale loc(locales[locIndex]);
TimeUnitFormat** formats = new TimeUnitFormat*[2];
formats[UTMUTFMT_FULL_STYLE] = new TimeUnitFormat(loc, status);
if (!assertSuccess("TimeUnitFormat(full)", status, TRUE)) return;
formats[UTMUTFMT_ABBREVIATED_STYLE] = new TimeUnitFormat(loc, UTMUTFMT_ABBREVIATED_STYLE, status);
if (!assertSuccess("TimeUnitFormat(short)", status)) return;
#ifdef TUFMTTS_DEBUG
std::cout << "locale: " << locales[locIndex] << "\n";
#endif
for (int style = UTMUTFMT_FULL_STYLE;
style <= UTMUTFMT_ABBREVIATED_STYLE;
++style) {
for (TimeUnit::UTimeUnitFields j = TimeUnit::UTIMEUNIT_YEAR;
j < TimeUnit::UTIMEUNIT_FIELD_COUNT;
j = (TimeUnit::UTimeUnitFields)(j+1)) {
#ifdef TUFMTTS_DEBUG
std::cout << "time unit: " << j << "\n";
#endif
double tests[] = {0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 5, 10, 100, 101.35};
for (unsigned int i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) {
#ifdef TUFMTTS_DEBUG
std::cout << "number: " << tests[i] << "\n";
#endif
TimeUnitAmount* source = new TimeUnitAmount(tests[i], j, status);
if (!assertSuccess("TimeUnitAmount()", status)) return;
UnicodeString formatted;
Formattable formattable;
formattable.adoptObject(source);
formatted = ((Format*)formats[style])->format(formattable, formatted, status);
if (!assertSuccess("format()", status)) return;
#ifdef TUFMTTS_DEBUG
char formatResult[1000];
formatted.extract(0, formatted.length(), formatResult, "UTF-8");
std::cout << "format result: " << formatResult << "\n";
#endif
Formattable result;
((Format*)formats[style])->parseObject(formatted, result, status);
if (!assertSuccess("parseObject()", status)) return;
if (!tmaEqual(*((TimeUnitAmount *)result.getObject()), *((TimeUnitAmount *) formattable.getObject()))) {
dataerrln("No round trip: ");
}
// other style parsing
Formattable result_1;
((Format*)formats[1-style])->parseObject(formatted, result_1, status);
if (!assertSuccess("parseObject()", status)) return;
if (!tmaEqual(*((TimeUnitAmount *)result_1.getObject()), *((TimeUnitAmount *) formattable.getObject()))) {
dataerrln("No round trip: ");
}
}
}
}
delete formats[UTMUTFMT_FULL_STYLE];
delete formats[UTMUTFMT_ABBREVIATED_STYLE];
delete[] formats;
}
}
void TimeUnitTest::testAPI() {
//================= TimeUnit =================
UErrorCode status = U_ZERO_ERROR;
TimeUnit* tmunit = TimeUnit::createInstance(TimeUnit::UTIMEUNIT_YEAR, status);
if (!assertSuccess("TimeUnit::createInstance", status)) return;
TimeUnit* another = (TimeUnit*)tmunit->clone();
TimeUnit third(*tmunit);
TimeUnit fourth = third;
assertTrue("orig and clone are equal", (*tmunit == *another));
assertTrue("copied and assigned are equal", (third == fourth));
TimeUnit* tmunit_m = TimeUnit::createInstance(TimeUnit::UTIMEUNIT_MONTH, status);
assertTrue("year != month", (*tmunit != *tmunit_m));
TimeUnit::UTimeUnitFields field = tmunit_m->getTimeUnitField();
assertTrue("field of month time unit is month", (field == TimeUnit::UTIMEUNIT_MONTH));
//===== Interoperability with MeasureUnit ======
MeasureUnit **ptrs = new MeasureUnit *[TimeUnit::UTIMEUNIT_FIELD_COUNT];
ptrs[TimeUnit::UTIMEUNIT_YEAR] = MeasureUnit::createYear(status);
ptrs[TimeUnit::UTIMEUNIT_MONTH] = MeasureUnit::createMonth(status);
ptrs[TimeUnit::UTIMEUNIT_DAY] = MeasureUnit::createDay(status);
ptrs[TimeUnit::UTIMEUNIT_WEEK] = MeasureUnit::createWeek(status);
ptrs[TimeUnit::UTIMEUNIT_HOUR] = MeasureUnit::createHour(status);
ptrs[TimeUnit::UTIMEUNIT_MINUTE] = MeasureUnit::createMinute(status);
ptrs[TimeUnit::UTIMEUNIT_SECOND] = MeasureUnit::createSecond(status);
if (!assertSuccess("TimeUnit::createInstance", status)) return;
for (TimeUnit::UTimeUnitFields j = TimeUnit::UTIMEUNIT_YEAR;
j < TimeUnit::UTIMEUNIT_FIELD_COUNT;
j = (TimeUnit::UTimeUnitFields)(j+1)) {
MeasureUnit *ptr = TimeUnit::createInstance(j, status);
if (!assertSuccess("TimeUnit::createInstance", status)) return;
// We have to convert *ptr to a MeasureUnit or else == will fail over
// differing types (TimeUnit vs. MeasureUnit).
assertTrue(
"Time unit should be equal to corresponding MeasureUnit",
MeasureUnit(*ptr) == *ptrs[j]);
delete ptr;
}
delete tmunit;
delete another;
delete tmunit_m;
for (int i = 0; i < TimeUnit::UTIMEUNIT_FIELD_COUNT; ++i) {
delete ptrs[i];
}
delete [] ptrs;
//
//================= TimeUnitAmount =================
Formattable formattable((int32_t)2);
TimeUnitAmount tma_long(formattable, TimeUnit::UTIMEUNIT_DAY, status);
if (!assertSuccess("TimeUnitAmount(formattable...)", status)) return;
formattable.setDouble(2);
TimeUnitAmount tma_double(formattable, TimeUnit::UTIMEUNIT_DAY, status);
if (!assertSuccess("TimeUnitAmount(formattable...)", status)) return;
formattable.setDouble(3);
TimeUnitAmount tma_double_3(formattable, TimeUnit::UTIMEUNIT_DAY, status);
if (!assertSuccess("TimeUnitAmount(formattable...)", status)) return;
TimeUnitAmount tma(2, TimeUnit::UTIMEUNIT_DAY, status);
if (!assertSuccess("TimeUnitAmount(number...)", status)) return;
TimeUnitAmount tma_h(2, TimeUnit::UTIMEUNIT_HOUR, status);
if (!assertSuccess("TimeUnitAmount(number...)", status)) return;
TimeUnitAmount second(tma);
TimeUnitAmount third_tma = tma;
TimeUnitAmount* fourth_tma = (TimeUnitAmount*)tma.clone();
assertTrue("orig and copy are equal", (second == tma));
assertTrue("clone and assigned are equal", (third_tma == *fourth_tma));
assertTrue("different if number diff", (tma_double != tma_double_3));
assertTrue("different if number type diff", (tma_double != tma_long));
assertTrue("different if time unit diff", (tma != tma_h));
assertTrue("same even different constructor", (tma_double == tma));
assertTrue("getTimeUnitField", (tma.getTimeUnitField() == TimeUnit::UTIMEUNIT_DAY));
delete fourth_tma;
//
//================= TimeUnitFormat =================
//
TimeUnitFormat* tmf_en = new TimeUnitFormat(Locale("en"), status);
if (!assertSuccess("TimeUnitFormat(en...)", status, TRUE)) return;
TimeUnitFormat tmf_fr(Locale("fr"), status);
if (!assertSuccess("TimeUnitFormat(fr...)", status)) return;
assertTrue("TimeUnitFormat: en and fr diff", (*tmf_en != tmf_fr));
TimeUnitFormat tmf_assign = *tmf_en;
assertTrue("TimeUnitFormat: orig and assign are equal", (*tmf_en == tmf_assign));
TimeUnitFormat tmf_copy(tmf_fr);
assertTrue("TimeUnitFormat: orig and copy are equal", (tmf_fr == tmf_copy));
TimeUnitFormat* tmf_clone = (TimeUnitFormat*)tmf_en->clone();
assertTrue("TimeUnitFormat: orig and clone are equal", (*tmf_en == *tmf_clone));
delete tmf_clone;
tmf_en->setLocale(Locale("fr"), status);
if (!assertSuccess("setLocale(fr...)", status)) return;
NumberFormat* numberFmt = NumberFormat::createInstance(
Locale("fr"), status);
if (!assertSuccess("NumberFormat::createInstance()", status)) return;
tmf_en->setNumberFormat(*numberFmt, status);
if (!assertSuccess("setNumberFormat(en...)", status)) return;
assertTrue("TimeUnitFormat: setLocale", (*tmf_en == tmf_fr));
delete tmf_en;
TimeUnitFormat* en_long = new TimeUnitFormat(Locale("en"), UTMUTFMT_FULL_STYLE, status);
if (!assertSuccess("TimeUnitFormat(en...)", status)) return;
delete en_long;
TimeUnitFormat* en_short = new TimeUnitFormat(Locale("en"), UTMUTFMT_ABBREVIATED_STYLE, status);
if (!assertSuccess("TimeUnitFormat(en...)", status)) return;
delete en_short;
TimeUnitFormat* format = new TimeUnitFormat(status);
format->setLocale(Locale("zh"), status);
format->setNumberFormat(*numberFmt, status);
if (!assertSuccess("TimeUnitFormat(en...)", status)) return;
delete numberFmt;
delete format;
}
/* @bug 7902
* Tests for Greek Language.
* This tests that requests for short unit names correctly fall back
* to long unit names for a locale where the locale data does not
* provide short unit names. As of CLDR 1.9, Greek is one such language.
*/
void TimeUnitTest::testGreekWithFallback() {
UErrorCode status = U_ZERO_ERROR;
const char* locales[] = {"el-GR", "el"};
TimeUnit::UTimeUnitFields tunits[] = {TimeUnit::UTIMEUNIT_SECOND, TimeUnit::UTIMEUNIT_MINUTE, TimeUnit::UTIMEUNIT_HOUR, TimeUnit::UTIMEUNIT_DAY, TimeUnit::UTIMEUNIT_MONTH, TimeUnit::UTIMEUNIT_YEAR};
UTimeUnitFormatStyle styles[] = {UTMUTFMT_FULL_STYLE, UTMUTFMT_ABBREVIATED_STYLE};
const int numbers[] = {1, 7};
const UChar oneSecond[] = {0x0031, 0x0020, 0x03b4, 0x03b5, 0x03c5, 0x03c4, 0x03b5, 0x03c1, 0x03cc, 0x03bb, 0x03b5, 0x03c0, 0x03c4, 0x03bf, 0};
const UChar oneSecondShort[] = {0x0031, 0x0020, 0x03b4, 0x03b5, 0x03c5, 0x03c4, 0x002e, 0};
const UChar oneMinute[] = {0x0031, 0x0020, 0x03bb, 0x03b5, 0x03c0, 0x03c4, 0x03cc, 0};
const UChar oneMinuteShort[] = {0x0031, 0x0020, 0x03bb, 0x03b5, 0x03c0, 0x002e, 0};
const UChar oneHour[] = {0x0031, 0x0020, 0x03ce, 0x03c1, 0x03b1, 0};
const UChar oneDay[] = {0x0031, 0x0020, 0x03b7, 0x03bc, 0x03ad, 0x03c1, 0x03b1, 0};
const UChar oneMonth[] = {0x0031, 0x0020, 0x03bc, 0x03ae, 0x03bd, 0x03b1, 0x03c2, 0};
const UChar oneMonthShort[] = {0x0031, 0x0020, 0x03bc, 0x03ae, 0x03bd, 0x002e, 0};
const UChar oneYear[] = {0x0031, 0x0020, 0x03ad, 0x03c4, 0x03bf, 0x03c2, 0};
const UChar oneYearShort[] = {0x0031, 0x0020, 0x03ad, 0x03c4, 0x002e, 0};
const UChar sevenSeconds[] = {0x0037, 0x0020, 0x03b4, 0x03b5, 0x03c5, 0x03c4, 0x03b5, 0x03c1, 0x03cc, 0x03bb, 0x03b5, 0x03c0, 0x03c4, 0x03b1, 0};
const UChar sevenSecondsShort[] = {0x0037, 0x0020, 0x03b4, 0x03b5, 0x03c5, 0x03c4, 0x002e, 0};
const UChar sevenMinutes[] = {0x0037, 0x0020, 0x03bb, 0x03b5, 0x03c0, 0x03c4, 0x03ac, 0};
const UChar sevenMinutesShort[] = {0x0037, 0x0020, 0x03bb, 0x03b5, 0x03c0, 0x002e, 0};
const UChar sevenHours[] = {0x0037, 0x0020, 0x03ce, 0x03c1, 0x03b5, 0x03c2, 0};
const UChar sevenHoursShort[] = {0x0037, 0x0020, 0x03ce, 0x03c1, 0x002e, 0};
const UChar sevenDays[] = {0x0037, 0x0020, 0x03b7, 0x03bc, 0x03ad, 0x03c1, 0x03b5, 0x03c2, 0};
const UChar sevenMonths[] = {0x0037, 0x0020, 0x03bc, 0x03ae, 0x03bd, 0x03b5, 0x3c2, 0};
const UChar sevenMonthsShort[] = {0x0037, 0x0020, 0x03bc, 0x03ae, 0x03bd, 0x002e, 0};
const UChar sevenYears[] = {0x0037, 0x0020, 0x03ad, 0x03c4, 0x03b7, 0};
const UChar sevenYearsShort[] = {0x0037, 0x0020, 0x03ad, 0x03c4, 0x002e, 0};
const UnicodeString oneSecondStr(oneSecond);
const UnicodeString oneSecondShortStr(oneSecondShort);
const UnicodeString oneMinuteStr(oneMinute);
const UnicodeString oneMinuteShortStr(oneMinuteShort);
const UnicodeString oneHourStr(oneHour);
const UnicodeString oneDayStr(oneDay);
const UnicodeString oneMonthStr(oneMonth);
const UnicodeString oneMonthShortStr(oneMonthShort);
const UnicodeString oneYearStr(oneYear);
const UnicodeString oneYearShortStr(oneYearShort);
const UnicodeString sevenSecondsStr(sevenSeconds);
const UnicodeString sevenSecondsShortStr(sevenSecondsShort);
const UnicodeString sevenMinutesStr(sevenMinutes);
const UnicodeString sevenMinutesShortStr(sevenMinutesShort);
const UnicodeString sevenHoursStr(sevenHours);
const UnicodeString sevenHoursShortStr(sevenHoursShort);
const UnicodeString sevenDaysStr(sevenDays);
const UnicodeString sevenMonthsStr(sevenMonths);
const UnicodeString sevenMonthsShortStr(sevenMonthsShort);
const UnicodeString sevenYearsStr(sevenYears);
const UnicodeString sevenYearsShortStr(sevenYearsShort);
const UnicodeString expected[] = {
oneSecondStr, oneMinuteStr, oneHourStr, oneDayStr, oneMonthStr, oneYearStr,
oneSecondShortStr, oneMinuteShortStr, oneHourStr, oneDayStr, oneMonthShortStr, oneYearShortStr,
sevenSecondsStr, sevenMinutesStr, sevenHoursStr, sevenDaysStr, sevenMonthsStr, sevenYearsStr,
sevenSecondsShortStr, sevenMinutesShortStr, sevenHoursShortStr, sevenDaysStr, sevenMonthsShortStr, sevenYearsShortStr,
oneSecondStr, oneMinuteStr, oneHourStr, oneDayStr, oneMonthStr, oneYearStr,
oneSecondShortStr, oneMinuteShortStr, oneHourStr, oneDayStr, oneMonthShortStr, oneYearShortStr,
sevenSecondsStr, sevenMinutesStr, sevenHoursStr, sevenDaysStr, sevenMonthsStr, sevenYearsStr,
sevenSecondsShortStr, sevenMinutesShortStr, sevenHoursShortStr, sevenDaysStr, sevenMonthsShortStr, sevenYearsShortStr};
int counter = 0;
for ( unsigned int locIndex = 0;
locIndex < sizeof(locales)/sizeof(locales[0]);
++locIndex ) {
Locale l = Locale::createFromName(locales[locIndex]);
for ( unsigned int numberIndex = 0;
numberIndex < sizeof(numbers)/sizeof(int);
++numberIndex ) {
for ( unsigned int styleIndex = 0;
styleIndex < sizeof(styles)/sizeof(styles[0]);
++styleIndex ) {
for ( unsigned int unitIndex = 0;
unitIndex < sizeof(tunits)/sizeof(tunits[0]);
++unitIndex ) {
TimeUnitAmount *tamt = new TimeUnitAmount(numbers[numberIndex], tunits[unitIndex], status);
if (U_FAILURE(status)) {
dataerrln("generating TimeUnitAmount Object failed.");
#ifdef TUFMTTS_DEBUG
std::cout << "Failed to get TimeUnitAmount for " << tunits[unitIndex] << "\n";
#endif
return;
}
TimeUnitFormat *tfmt = new TimeUnitFormat(l, styles[styleIndex], status);
if (U_FAILURE(status)) {
dataerrln("generating TimeUnitAmount Object failed.");
#ifdef TUFMTTS_DEBUG
std::cout << "Failed to get TimeUnitFormat for " << locales[locIndex] << "\n";
#endif
return;
}
Formattable fmt;
UnicodeString str;
fmt.adoptObject(tamt);
str = ((Format *)tfmt)->format(fmt, str, status);
if (!assertSuccess("formatting relative time failed", status)) {
delete tfmt;
#ifdef TUFMTTS_DEBUG
std::cout << "Failed to format" << "\n";
#endif
return;
}
#ifdef TUFMTTS_DEBUG
char tmp[128]; //output
char tmp1[128]; //expected
int len = 0;
u_strToUTF8(tmp, 128, &len, str.getTerminatedBuffer(), str.length(), &status);
u_strToUTF8(tmp1, 128, &len, expected[counter].unescape().getTerminatedBuffer(), expected[counter].unescape().length(), &status);
std::cout << "Formatted string : " << tmp << " expected : " << tmp1 << "\n";
#endif
if (!assertEquals("formatted time string is not expected, locale: " + UnicodeString(locales[locIndex]) + " style: " + (int)styles[styleIndex] + " units: " + (int)tunits[unitIndex], expected[counter], str)) {
delete tfmt;
str.remove();
return;
}
delete tfmt;
str.remove();
++counter;
}
}
}
}
}
// Test bug9042
void TimeUnitTest::testGreekWithSanitization() {
UErrorCode status = U_ZERO_ERROR;
Locale elLoc("el");
NumberFormat* numberFmt = NumberFormat::createInstance(Locale("el"), status);
if (!assertSuccess("NumberFormat::createInstance for el locale", status, TRUE)) return;
numberFmt->setMaximumFractionDigits(1);
TimeUnitFormat* timeUnitFormat = new TimeUnitFormat(elLoc, status);
if (!assertSuccess("TimeUnitFormat::TimeUnitFormat for el locale", status)) return;
timeUnitFormat->setNumberFormat(*numberFmt, status);
delete numberFmt;
delete timeUnitFormat;
}
void TimeUnitTest::test10219Plurals() {
Locale usLocale("en_US");
double values[2] = {1.588, 1.011};
UnicodeString expected[2][3] = {
{"1 minute", "1.5 minutes", "1.58 minutes"},
{"1 minute", "1.0 minutes", "1.01 minutes"}
};
UErrorCode status = U_ZERO_ERROR;
TimeUnitFormat tuf(usLocale, status);
if (U_FAILURE(status)) {
dataerrln("generating TimeUnitFormat Object failed: %s", u_errorName(status));
return;
}
LocalPointer<DecimalFormat> nf((DecimalFormat *) NumberFormat::createInstance(usLocale, status));
if (U_FAILURE(status)) {
dataerrln("generating NumberFormat Object failed: %s", u_errorName(status));
return;
}
for (int32_t j = 0; j < UPRV_LENGTHOF(values); ++j) {
for (int32_t i = 0; i < UPRV_LENGTHOF(expected[j]); ++i) {
nf->setMinimumFractionDigits(i);
nf->setMaximumFractionDigits(i);
nf->setRoundingMode(DecimalFormat::kRoundDown);
tuf.setNumberFormat(*nf, status);
if (U_FAILURE(status)) {
dataerrln("setting NumberFormat failed: %s", u_errorName(status));
return;
}
UnicodeString actual;
Formattable fmt;
LocalPointer<TimeUnitAmount> tamt(
new TimeUnitAmount(values[j], TimeUnit::UTIMEUNIT_MINUTE, status), status);
if (U_FAILURE(status)) {
dataerrln("generating TimeUnitAmount Object failed: %s", u_errorName(status));
return;
}
fmt.adoptObject(tamt.orphan());
tuf.format(fmt, actual, status);
if (U_FAILURE(status)) {
dataerrln("Actual formatting failed: %s", u_errorName(status));
return;
}
if (expected[j][i] != actual) {
errln("Expected " + expected[j][i] + ", got " + actual);
}
}
}
// test parsing
Formattable result;
ParsePosition pos;
UnicodeString formattedString = "1 minutes";
tuf.parseObject(formattedString, result, pos);
if (formattedString.length() != pos.getIndex()) {
errln("Expect parsing to go all the way to the end of the string.");
}
}
#endif
| mit |
OpenSocialGames/godot | drivers/builtin_openssl2/crypto/cms/cms_io.c | 181 | 4981 | /* crypto/cms/cms_io.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project.
*/
/* ====================================================================
* Copyright (c) 2008 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 <openssl/asn1t.h>
#include <openssl/x509.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include "cms.h"
#include "cms_lcl.h"
int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms)
{
ASN1_OCTET_STRING **pos;
pos = CMS_get0_content(cms);
if (!pos)
return 0;
if (!*pos)
*pos = ASN1_OCTET_STRING_new();
if (*pos) {
(*pos)->flags |= ASN1_STRING_FLAG_NDEF;
(*pos)->flags &= ~ASN1_STRING_FLAG_CONT;
*boundary = &(*pos)->data;
return 1;
}
CMSerr(CMS_F_CMS_STREAM, ERR_R_MALLOC_FAILURE);
return 0;
}
CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms)
{
return ASN1_item_d2i_bio(ASN1_ITEM_rptr(CMS_ContentInfo), bp, cms);
}
int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms)
{
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(CMS_ContentInfo), bp, cms);
}
IMPLEMENT_PEM_rw_const(CMS, CMS_ContentInfo, PEM_STRING_CMS, CMS_ContentInfo)
BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms)
{
return BIO_new_NDEF(out, (ASN1_VALUE *)cms,
ASN1_ITEM_rptr(CMS_ContentInfo));
}
/* CMS wrappers round generalised stream and MIME routines */
int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags)
{
return i2d_ASN1_bio_stream(out, (ASN1_VALUE *)cms, in, flags,
ASN1_ITEM_rptr(CMS_ContentInfo));
}
int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in,
int flags)
{
return PEM_write_bio_ASN1_stream(out, (ASN1_VALUE *)cms, in, flags,
"CMS", ASN1_ITEM_rptr(CMS_ContentInfo));
}
int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags)
{
STACK_OF(X509_ALGOR) *mdalgs;
int ctype_nid = OBJ_obj2nid(cms->contentType);
int econt_nid = OBJ_obj2nid(CMS_get0_eContentType(cms));
if (ctype_nid == NID_pkcs7_signed)
mdalgs = cms->d.signedData->digestAlgorithms;
else
mdalgs = NULL;
return SMIME_write_ASN1(bio, (ASN1_VALUE *)cms, data, flags,
ctype_nid, econt_nid, mdalgs,
ASN1_ITEM_rptr(CMS_ContentInfo));
}
CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont)
{
return (CMS_ContentInfo *)SMIME_read_ASN1(bio, bcont,
ASN1_ITEM_rptr
(CMS_ContentInfo));
}
| mit |
publicloudapp/csrutil | linux-4.3/drivers/staging/rdma/hfi1/pcie.c | 185 | 36351 | /*
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2015 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* BSD LICENSE
*
* Copyright(c) 2015 Intel Corporation.
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <linux/pci.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/vmalloc.h>
#include <linux/aer.h>
#include <linux/module.h>
#include "hfi.h"
#include "chip_registers.h"
/* link speed vector for Gen3 speed - not in Linux headers */
#define GEN1_SPEED_VECTOR 0x1
#define GEN2_SPEED_VECTOR 0x2
#define GEN3_SPEED_VECTOR 0x3
/*
* This file contains PCIe utility routines.
*/
/*
* Code to adjust PCIe capabilities.
*/
static void tune_pcie_caps(struct hfi1_devdata *);
/*
* Do all the common PCIe setup and initialization.
* devdata is not yet allocated, and is not allocated until after this
* routine returns success. Therefore dd_dev_err() can't be used for error
* printing.
*/
int hfi1_pcie_init(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int ret;
ret = pci_enable_device(pdev);
if (ret) {
/*
* This can happen (in theory) iff:
* We did a chip reset, and then failed to reprogram the
* BAR, or the chip reset due to an internal error. We then
* unloaded the driver and reloaded it.
*
* Both reset cases set the BAR back to initial state. For
* the latter case, the AER sticky error bit at offset 0x718
* should be set, but the Linux kernel doesn't yet know
* about that, it appears. If the original BAR was retained
* in the kernel data structures, this may be OK.
*/
hfi1_early_err(&pdev->dev, "pci enable failed: error %d\n",
-ret);
goto done;
}
ret = pci_request_regions(pdev, DRIVER_NAME);
if (ret) {
hfi1_early_err(&pdev->dev,
"pci_request_regions fails: err %d\n", -ret);
goto bail;
}
ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
if (ret) {
/*
* If the 64 bit setup fails, try 32 bit. Some systems
* do not setup 64 bit maps on systems with 2GB or less
* memory installed.
*/
ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret) {
hfi1_early_err(&pdev->dev,
"Unable to set DMA mask: %d\n", ret);
goto bail;
}
ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
} else
ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (ret) {
hfi1_early_err(&pdev->dev,
"Unable to set DMA consistent mask: %d\n", ret);
goto bail;
}
pci_set_master(pdev);
ret = pci_enable_pcie_error_reporting(pdev);
if (ret) {
hfi1_early_err(&pdev->dev,
"Unable to enable pcie error reporting: %d\n",
ret);
ret = 0;
}
goto done;
bail:
hfi1_pcie_cleanup(pdev);
done:
return ret;
}
/*
* Clean what was done in hfi1_pcie_init()
*/
void hfi1_pcie_cleanup(struct pci_dev *pdev)
{
pci_disable_device(pdev);
/*
* Release regions should be called after the disable. OK to
* call if request regions has not been called or failed.
*/
pci_release_regions(pdev);
}
/*
* Do remaining PCIe setup, once dd is allocated, and save away
* fields required to re-initialize after a chip reset, or for
* various other purposes
*/
int hfi1_pcie_ddinit(struct hfi1_devdata *dd, struct pci_dev *pdev,
const struct pci_device_id *ent)
{
unsigned long len;
resource_size_t addr;
dd->pcidev = pdev;
pci_set_drvdata(pdev, dd);
addr = pci_resource_start(pdev, 0);
len = pci_resource_len(pdev, 0);
/*
* The TXE PIO buffers are at the tail end of the chip space.
* Cut them off and map them separately.
*/
/* sanity check vs expectations */
if (len != TXE_PIO_SEND + TXE_PIO_SIZE) {
dd_dev_err(dd, "chip PIO range does not match\n");
return -EINVAL;
}
dd->kregbase = ioremap_nocache(addr, TXE_PIO_SEND);
if (!dd->kregbase)
return -ENOMEM;
dd->piobase = ioremap_wc(addr + TXE_PIO_SEND, TXE_PIO_SIZE);
if (!dd->piobase) {
iounmap(dd->kregbase);
return -ENOMEM;
}
dd->flags |= HFI1_PRESENT; /* now register routines work */
dd->kregend = dd->kregbase + TXE_PIO_SEND;
dd->physaddr = addr; /* used for io_remap, etc. */
/*
* Re-map the chip's RcvArray as write-combining to allow us
* to write an entire cacheline worth of entries in one shot.
* If this re-map fails, just continue - the RcvArray programming
* function will handle both cases.
*/
dd->chip_rcv_array_count = read_csr(dd, RCV_ARRAY_CNT);
dd->rcvarray_wc = ioremap_wc(addr + RCV_ARRAY,
dd->chip_rcv_array_count * 8);
dd_dev_info(dd, "WC Remapped RcvArray: %p\n", dd->rcvarray_wc);
/*
* Save BARs and command to rewrite after device reset.
*/
dd->pcibar0 = addr;
dd->pcibar1 = addr >> 32;
pci_read_config_dword(dd->pcidev, PCI_ROM_ADDRESS, &dd->pci_rom);
pci_read_config_word(dd->pcidev, PCI_COMMAND, &dd->pci_command);
pcie_capability_read_word(dd->pcidev, PCI_EXP_DEVCTL, &dd->pcie_devctl);
pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKCTL, &dd->pcie_lnkctl);
pcie_capability_read_word(dd->pcidev, PCI_EXP_DEVCTL2,
&dd->pcie_devctl2);
pci_read_config_dword(dd->pcidev, PCI_CFG_MSIX0, &dd->pci_msix0);
pci_read_config_dword(dd->pcidev, PCIE_CFG_SPCIE1,
&dd->pci_lnkctl3);
pci_read_config_dword(dd->pcidev, PCIE_CFG_TPH2, &dd->pci_tph2);
return 0;
}
/*
* Do PCIe cleanup related to dd, after chip-specific cleanup, etc. Just prior
* to releasing the dd memory.
* Void because all of the core pcie cleanup functions are void.
*/
void hfi1_pcie_ddcleanup(struct hfi1_devdata *dd)
{
u64 __iomem *base = (void __iomem *) dd->kregbase;
dd->flags &= ~HFI1_PRESENT;
dd->kregbase = NULL;
iounmap(base);
if (dd->rcvarray_wc)
iounmap(dd->rcvarray_wc);
if (dd->piobase)
iounmap(dd->piobase);
pci_set_drvdata(dd->pcidev, NULL);
}
/*
* Do a Function Level Reset (FLR) on the device.
* Based on static function drivers/pci/pci.c:pcie_flr().
*/
void hfi1_pcie_flr(struct hfi1_devdata *dd)
{
int i;
u16 status;
/* no need to check for the capability - we know the device has it */
/* wait for Transaction Pending bit to clear, at most a few ms */
for (i = 0; i < 4; i++) {
if (i)
msleep((1 << (i - 1)) * 100);
pcie_capability_read_word(dd->pcidev, PCI_EXP_DEVSTA, &status);
if (!(status & PCI_EXP_DEVSTA_TRPND))
goto clear;
}
dd_dev_err(dd, "Transaction Pending bit is not clearing, proceeding with reset anyway\n");
clear:
pcie_capability_set_word(dd->pcidev, PCI_EXP_DEVCTL,
PCI_EXP_DEVCTL_BCR_FLR);
/* PCIe spec requires the function to be back within 100ms */
msleep(100);
}
static void msix_setup(struct hfi1_devdata *dd, int pos, u32 *msixcnt,
struct hfi1_msix_entry *hfi1_msix_entry)
{
int ret;
int nvec = *msixcnt;
struct msix_entry *msix_entry;
int i;
/* We can't pass hfi1_msix_entry array to msix_setup
* so use a dummy msix_entry array and copy the allocated
* irq back to the hfi1_msix_entry array. */
msix_entry = kmalloc_array(nvec, sizeof(*msix_entry), GFP_KERNEL);
if (!msix_entry) {
ret = -ENOMEM;
goto do_intx;
}
for (i = 0; i < nvec; i++)
msix_entry[i] = hfi1_msix_entry[i].msix;
ret = pci_enable_msix_range(dd->pcidev, msix_entry, 1, nvec);
if (ret < 0)
goto free_msix_entry;
nvec = ret;
for (i = 0; i < nvec; i++)
hfi1_msix_entry[i].msix = msix_entry[i];
kfree(msix_entry);
*msixcnt = nvec;
return;
free_msix_entry:
kfree(msix_entry);
do_intx:
dd_dev_err(dd, "pci_enable_msix_range %d vectors failed: %d, falling back to INTx\n",
nvec, ret);
*msixcnt = 0;
hfi1_enable_intx(dd->pcidev);
}
/* return the PCIe link speed from the given link status */
static u32 extract_speed(u16 linkstat)
{
u32 speed;
switch (linkstat & PCI_EXP_LNKSTA_CLS) {
default: /* not defined, assume Gen1 */
case PCI_EXP_LNKSTA_CLS_2_5GB:
speed = 2500; /* Gen 1, 2.5GHz */
break;
case PCI_EXP_LNKSTA_CLS_5_0GB:
speed = 5000; /* Gen 2, 5GHz */
break;
case GEN3_SPEED_VECTOR:
speed = 8000; /* Gen 3, 8GHz */
break;
}
return speed;
}
/* return the PCIe link speed from the given link status */
static u32 extract_width(u16 linkstat)
{
return (linkstat & PCI_EXP_LNKSTA_NLW) >> PCI_EXP_LNKSTA_NLW_SHIFT;
}
/* read the link status and set dd->{lbus_width,lbus_speed,lbus_info} */
static void update_lbus_info(struct hfi1_devdata *dd)
{
u16 linkstat;
pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKSTA, &linkstat);
dd->lbus_width = extract_width(linkstat);
dd->lbus_speed = extract_speed(linkstat);
snprintf(dd->lbus_info, sizeof(dd->lbus_info),
"PCIe,%uMHz,x%u", dd->lbus_speed, dd->lbus_width);
}
/*
* Read in the current PCIe link width and speed. Find if the link is
* Gen3 capable.
*/
int pcie_speeds(struct hfi1_devdata *dd)
{
u32 linkcap;
if (!pci_is_pcie(dd->pcidev)) {
dd_dev_err(dd, "Can't find PCI Express capability!\n");
return -EINVAL;
}
/* find if our max speed is Gen3 and parent supports Gen3 speeds */
dd->link_gen3_capable = 1;
pcie_capability_read_dword(dd->pcidev, PCI_EXP_LNKCAP, &linkcap);
if ((linkcap & PCI_EXP_LNKCAP_SLS) != GEN3_SPEED_VECTOR) {
dd_dev_info(dd,
"This HFI is not Gen3 capable, max speed 0x%x, need 0x3\n",
linkcap & PCI_EXP_LNKCAP_SLS);
dd->link_gen3_capable = 0;
}
/*
* bus->max_bus_speed is set from the bridge's linkcap Max Link Speed
*/
if (dd->pcidev->bus->max_bus_speed != PCIE_SPEED_8_0GT) {
dd_dev_info(dd, "Parent PCIe bridge does not support Gen3\n");
dd->link_gen3_capable = 0;
}
/* obtain the link width and current speed */
update_lbus_info(dd);
/* check against expected pcie width and complain if "wrong" */
if (dd->lbus_width < 16)
dd_dev_err(dd, "PCIe width %u (x16 HFI)\n", dd->lbus_width);
return 0;
}
/*
* Returns in *nent:
* - actual number of interrupts allocated
* - 0 if fell back to INTx.
*/
void request_msix(struct hfi1_devdata *dd, u32 *nent,
struct hfi1_msix_entry *entry)
{
int pos;
pos = dd->pcidev->msix_cap;
if (*nent && pos) {
msix_setup(dd, pos, nent, entry);
/* did it, either MSI-X or INTx */
} else {
*nent = 0;
hfi1_enable_intx(dd->pcidev);
}
tune_pcie_caps(dd);
}
/*
* Disable MSI-X.
*/
void hfi1_nomsix(struct hfi1_devdata *dd)
{
pci_disable_msix(dd->pcidev);
}
void hfi1_enable_intx(struct pci_dev *pdev)
{
/* first, turn on INTx */
pci_intx(pdev, 1);
/* then turn off MSI-X */
pci_disable_msix(pdev);
}
/* restore command and BARs after a reset has wiped them out */
void restore_pci_variables(struct hfi1_devdata *dd)
{
pci_write_config_word(dd->pcidev, PCI_COMMAND, dd->pci_command);
pci_write_config_dword(dd->pcidev,
PCI_BASE_ADDRESS_0, dd->pcibar0);
pci_write_config_dword(dd->pcidev,
PCI_BASE_ADDRESS_1, dd->pcibar1);
pci_write_config_dword(dd->pcidev,
PCI_ROM_ADDRESS, dd->pci_rom);
pcie_capability_write_word(dd->pcidev, PCI_EXP_DEVCTL, dd->pcie_devctl);
pcie_capability_write_word(dd->pcidev, PCI_EXP_LNKCTL, dd->pcie_lnkctl);
pcie_capability_write_word(dd->pcidev, PCI_EXP_DEVCTL2,
dd->pcie_devctl2);
pci_write_config_dword(dd->pcidev, PCI_CFG_MSIX0, dd->pci_msix0);
pci_write_config_dword(dd->pcidev, PCIE_CFG_SPCIE1,
dd->pci_lnkctl3);
pci_write_config_dword(dd->pcidev, PCIE_CFG_TPH2, dd->pci_tph2);
}
/*
* BIOS may not set PCIe bus-utilization parameters for best performance.
* Check and optionally adjust them to maximize our throughput.
*/
static int hfi1_pcie_caps;
module_param_named(pcie_caps, hfi1_pcie_caps, int, S_IRUGO);
MODULE_PARM_DESC(pcie_caps, "Max PCIe tuning: Payload (0..3), ReadReq (4..7)");
static void tune_pcie_caps(struct hfi1_devdata *dd)
{
struct pci_dev *parent;
u16 rc_mpss, rc_mps, ep_mpss, ep_mps;
u16 rc_mrrs, ep_mrrs, max_mrrs;
/* Find out supported and configured values for parent (root) */
parent = dd->pcidev->bus->self;
if (!pci_is_root_bus(parent->bus)) {
dd_dev_info(dd, "Parent not root\n");
return;
}
if (!pci_is_pcie(parent) || !pci_is_pcie(dd->pcidev))
return;
rc_mpss = parent->pcie_mpss;
rc_mps = ffs(pcie_get_mps(parent)) - 8;
/* Find out supported and configured values for endpoint (us) */
ep_mpss = dd->pcidev->pcie_mpss;
ep_mps = ffs(pcie_get_mps(dd->pcidev)) - 8;
/* Find max payload supported by root, endpoint */
if (rc_mpss > ep_mpss)
rc_mpss = ep_mpss;
/* If Supported greater than limit in module param, limit it */
if (rc_mpss > (hfi1_pcie_caps & 7))
rc_mpss = hfi1_pcie_caps & 7;
/* If less than (allowed, supported), bump root payload */
if (rc_mpss > rc_mps) {
rc_mps = rc_mpss;
pcie_set_mps(parent, 128 << rc_mps);
}
/* If less than (allowed, supported), bump endpoint payload */
if (rc_mpss > ep_mps) {
ep_mps = rc_mpss;
pcie_set_mps(dd->pcidev, 128 << ep_mps);
}
/*
* Now the Read Request size.
* No field for max supported, but PCIe spec limits it to 4096,
* which is code '5' (log2(4096) - 7)
*/
max_mrrs = 5;
if (max_mrrs > ((hfi1_pcie_caps >> 4) & 7))
max_mrrs = (hfi1_pcie_caps >> 4) & 7;
max_mrrs = 128 << max_mrrs;
rc_mrrs = pcie_get_readrq(parent);
ep_mrrs = pcie_get_readrq(dd->pcidev);
if (max_mrrs > rc_mrrs) {
rc_mrrs = max_mrrs;
pcie_set_readrq(parent, rc_mrrs);
}
if (max_mrrs > ep_mrrs) {
ep_mrrs = max_mrrs;
pcie_set_readrq(dd->pcidev, ep_mrrs);
}
}
/* End of PCIe capability tuning */
/*
* From here through hfi1_pci_err_handler definition is invoked via
* PCI error infrastructure, registered via pci
*/
static pci_ers_result_t
pci_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
{
struct hfi1_devdata *dd = pci_get_drvdata(pdev);
pci_ers_result_t ret = PCI_ERS_RESULT_RECOVERED;
switch (state) {
case pci_channel_io_normal:
dd_dev_info(dd, "State Normal, ignoring\n");
break;
case pci_channel_io_frozen:
dd_dev_info(dd, "State Frozen, requesting reset\n");
pci_disable_device(pdev);
ret = PCI_ERS_RESULT_NEED_RESET;
break;
case pci_channel_io_perm_failure:
if (dd) {
dd_dev_info(dd, "State Permanent Failure, disabling\n");
/* no more register accesses! */
dd->flags &= ~HFI1_PRESENT;
hfi1_disable_after_error(dd);
}
/* else early, or other problem */
ret = PCI_ERS_RESULT_DISCONNECT;
break;
default: /* shouldn't happen */
dd_dev_info(dd, "HFI1 PCI errors detected (state %d)\n",
state);
break;
}
return ret;
}
static pci_ers_result_t
pci_mmio_enabled(struct pci_dev *pdev)
{
u64 words = 0U;
struct hfi1_devdata *dd = pci_get_drvdata(pdev);
pci_ers_result_t ret = PCI_ERS_RESULT_RECOVERED;
if (dd && dd->pport) {
words = read_port_cntr(dd->pport, C_RX_WORDS, CNTR_INVALID_VL);
if (words == ~0ULL)
ret = PCI_ERS_RESULT_NEED_RESET;
dd_dev_info(dd,
"HFI1 mmio_enabled function called, read wordscntr %Lx, returning %d\n",
words, ret);
}
return ret;
}
static pci_ers_result_t
pci_slot_reset(struct pci_dev *pdev)
{
struct hfi1_devdata *dd = pci_get_drvdata(pdev);
dd_dev_info(dd, "HFI1 slot_reset function called, ignored\n");
return PCI_ERS_RESULT_CAN_RECOVER;
}
static pci_ers_result_t
pci_link_reset(struct pci_dev *pdev)
{
struct hfi1_devdata *dd = pci_get_drvdata(pdev);
dd_dev_info(dd, "HFI1 link_reset function called, ignored\n");
return PCI_ERS_RESULT_CAN_RECOVER;
}
static void
pci_resume(struct pci_dev *pdev)
{
struct hfi1_devdata *dd = pci_get_drvdata(pdev);
dd_dev_info(dd, "HFI1 resume function called\n");
pci_cleanup_aer_uncorrect_error_status(pdev);
/*
* Running jobs will fail, since it's asynchronous
* unlike sysfs-requested reset. Better than
* doing nothing.
*/
hfi1_init(dd, 1); /* same as re-init after reset */
}
const struct pci_error_handlers hfi1_pci_err_handler = {
.error_detected = pci_error_detected,
.mmio_enabled = pci_mmio_enabled,
.link_reset = pci_link_reset,
.slot_reset = pci_slot_reset,
.resume = pci_resume,
};
/*============================================================================*/
/* PCIe Gen3 support */
/*
* This code is separated out because it is expected to be removed in the
* final shipping product. If not, then it will be revisited and items
* will be moved to more standard locations.
*/
/* ASIC_PCI_SD_HOST_STATUS.FW_DNLD_STS field values */
#define DL_STATUS_HFI0 0x1 /* hfi0 firmware download complete */
#define DL_STATUS_HFI1 0x2 /* hfi1 firmware download complete */
#define DL_STATUS_BOTH 0x3 /* hfi0 and hfi1 firmware download complete */
/* ASIC_PCI_SD_HOST_STATUS.FW_DNLD_ERR field values */
#define DL_ERR_NONE 0x0 /* no error */
#define DL_ERR_SWAP_PARITY 0x1 /* parity error in SerDes interrupt */
/* or response data */
#define DL_ERR_DISABLED 0x2 /* hfi disabled */
#define DL_ERR_SECURITY 0x3 /* security check failed */
#define DL_ERR_SBUS 0x4 /* SBus status error */
#define DL_ERR_XFR_PARITY 0x5 /* parity error during ROM transfer*/
/* gasket block secondary bus reset delay */
#define SBR_DELAY_US 200000 /* 200ms */
/* mask for PCIe capability register lnkctl2 target link speed */
#define LNKCTL2_TARGET_LINK_SPEED_MASK 0xf
static uint pcie_target = 3;
module_param(pcie_target, uint, S_IRUGO);
MODULE_PARM_DESC(pcie_target, "PCIe target speed (0 skip, 1-3 Gen1-3)");
static uint pcie_force;
module_param(pcie_force, uint, S_IRUGO);
MODULE_PARM_DESC(pcie_force, "Force driver to do a PCIe firmware download even if already at target speed");
static uint pcie_retry = 5;
module_param(pcie_retry, uint, S_IRUGO);
MODULE_PARM_DESC(pcie_retry, "Driver will try this many times to reach requested speed");
#define UNSET_PSET 255
#define DEFAULT_DISCRETE_PSET 2 /* discrete HFI */
#define DEFAULT_MCP_PSET 4 /* MCP HFI */
static uint pcie_pset = UNSET_PSET;
module_param(pcie_pset, uint, S_IRUGO);
MODULE_PARM_DESC(pcie_pset, "PCIe Eq Pset value to use, range is 0-10");
/* equalization columns */
#define PREC 0
#define ATTN 1
#define POST 2
/* discrete silicon preliminary equalization values */
static const u8 discrete_preliminary_eq[11][3] = {
/* prec attn post */
{ 0x00, 0x00, 0x12 }, /* p0 */
{ 0x00, 0x00, 0x0c }, /* p1 */
{ 0x00, 0x00, 0x0f }, /* p2 */
{ 0x00, 0x00, 0x09 }, /* p3 */
{ 0x00, 0x00, 0x00 }, /* p4 */
{ 0x06, 0x00, 0x00 }, /* p5 */
{ 0x09, 0x00, 0x00 }, /* p6 */
{ 0x06, 0x00, 0x0f }, /* p7 */
{ 0x09, 0x00, 0x09 }, /* p8 */
{ 0x0c, 0x00, 0x00 }, /* p9 */
{ 0x00, 0x00, 0x18 }, /* p10 */
};
/* integrated silicon preliminary equalization values */
static const u8 integrated_preliminary_eq[11][3] = {
/* prec attn post */
{ 0x00, 0x1e, 0x07 }, /* p0 */
{ 0x00, 0x1e, 0x05 }, /* p1 */
{ 0x00, 0x1e, 0x06 }, /* p2 */
{ 0x00, 0x1e, 0x04 }, /* p3 */
{ 0x00, 0x1e, 0x00 }, /* p4 */
{ 0x03, 0x1e, 0x00 }, /* p5 */
{ 0x04, 0x1e, 0x00 }, /* p6 */
{ 0x03, 0x1e, 0x06 }, /* p7 */
{ 0x03, 0x1e, 0x04 }, /* p8 */
{ 0x05, 0x1e, 0x00 }, /* p9 */
{ 0x00, 0x1e, 0x0a }, /* p10 */
};
/* helper to format the value to write to hardware */
#define eq_value(pre, curr, post) \
((((u32)(pre)) << \
PCIE_CFG_REG_PL102_GEN3_EQ_PRE_CURSOR_PSET_SHIFT) \
| (((u32)(curr)) << PCIE_CFG_REG_PL102_GEN3_EQ_CURSOR_PSET_SHIFT) \
| (((u32)(post)) << \
PCIE_CFG_REG_PL102_GEN3_EQ_POST_CURSOR_PSET_SHIFT))
/*
* Load the given EQ preset table into the PCIe hardware.
*/
static int load_eq_table(struct hfi1_devdata *dd, const u8 eq[11][3], u8 fs,
u8 div)
{
struct pci_dev *pdev = dd->pcidev;
u32 hit_error = 0;
u32 violation;
u32 i;
u8 c_minus1, c0, c_plus1;
for (i = 0; i < 11; i++) {
/* set index */
pci_write_config_dword(pdev, PCIE_CFG_REG_PL103, i);
/* write the value */
c_minus1 = eq[i][PREC] / div;
c0 = fs - (eq[i][PREC] / div) - (eq[i][POST] / div);
c_plus1 = eq[i][POST] / div;
pci_write_config_dword(pdev, PCIE_CFG_REG_PL102,
eq_value(c_minus1, c0, c_plus1));
/* check if these coefficients violate EQ rules */
pci_read_config_dword(dd->pcidev, PCIE_CFG_REG_PL105,
&violation);
if (violation
& PCIE_CFG_REG_PL105_GEN3_EQ_VIOLATE_COEF_RULES_SMASK){
if (hit_error == 0) {
dd_dev_err(dd,
"Gen3 EQ Table Coefficient rule violations\n");
dd_dev_err(dd, " prec attn post\n");
}
dd_dev_err(dd, " p%02d: %02x %02x %02x\n",
i, (u32)eq[i][0], (u32)eq[i][1], (u32)eq[i][2]);
dd_dev_err(dd, " %02x %02x %02x\n",
(u32)c_minus1, (u32)c0, (u32)c_plus1);
hit_error = 1;
}
}
if (hit_error)
return -EINVAL;
return 0;
}
/*
* Steps to be done after the PCIe firmware is downloaded and
* before the SBR for the Pcie Gen3.
* The hardware mutex is already being held.
*/
static void pcie_post_steps(struct hfi1_devdata *dd)
{
int i;
set_sbus_fast_mode(dd);
/*
* Write to the PCIe PCSes to set the G3_LOCKED_NEXT bits to 1.
* This avoids a spurious framing error that can otherwise be
* generated by the MAC layer.
*
* Use individual addresses since no broadcast is set up.
*/
for (i = 0; i < NUM_PCIE_SERDES; i++) {
sbus_request(dd, pcie_pcs_addrs[dd->hfi1_id][i],
0x03, WRITE_SBUS_RECEIVER, 0x00022132);
}
clear_sbus_fast_mode(dd);
}
/*
* Trigger a secondary bus reset (SBR) on ourselves using our parent.
*
* Based on pci_parent_bus_reset() which is not exported by the
* kernel core.
*/
static int trigger_sbr(struct hfi1_devdata *dd)
{
struct pci_dev *dev = dd->pcidev;
struct pci_dev *pdev;
/* need a parent */
if (!dev->bus->self) {
dd_dev_err(dd, "%s: no parent device\n", __func__);
return -ENOTTY;
}
/* should not be anyone else on the bus */
list_for_each_entry(pdev, &dev->bus->devices, bus_list)
if (pdev != dev) {
dd_dev_err(dd,
"%s: another device is on the same bus\n",
__func__);
return -ENOTTY;
}
/*
* A secondary bus reset (SBR) issues a hot reset to our device.
* The following routine does a 1s wait after the reset is dropped
* per PCI Trhfa (recovery time). PCIe 3.0 section 6.6.1 -
* Conventional Reset, paragraph 3, line 35 also says that a 1s
* delay after a reset is required. Per spec requirements,
* the link is either working or not after that point.
*/
pci_reset_bridge_secondary_bus(dev->bus->self);
return 0;
}
/*
* Write the given gasket interrupt register.
*/
static void write_gasket_interrupt(struct hfi1_devdata *dd, int index,
u16 code, u16 data)
{
write_csr(dd, ASIC_PCIE_SD_INTRPT_LIST + (index * 8),
(((u64)code << ASIC_PCIE_SD_INTRPT_LIST_INTRPT_CODE_SHIFT)
|((u64)data << ASIC_PCIE_SD_INTRPT_LIST_INTRPT_DATA_SHIFT)));
}
/*
* Tell the gasket logic how to react to the reset.
*/
static void arm_gasket_logic(struct hfi1_devdata *dd)
{
u64 reg;
reg = (((u64)1 << dd->hfi1_id)
<< ASIC_PCIE_SD_HOST_CMD_INTRPT_CMD_SHIFT)
| ((u64)pcie_serdes_broadcast[dd->hfi1_id]
<< ASIC_PCIE_SD_HOST_CMD_SBUS_RCVR_ADDR_SHIFT
| ASIC_PCIE_SD_HOST_CMD_SBR_MODE_SMASK
| ((u64)SBR_DELAY_US & ASIC_PCIE_SD_HOST_CMD_TIMER_MASK)
<< ASIC_PCIE_SD_HOST_CMD_TIMER_SHIFT
);
write_csr(dd, ASIC_PCIE_SD_HOST_CMD, reg);
/* read back to push the write */
read_csr(dd, ASIC_PCIE_SD_HOST_CMD);
}
/*
* Do all the steps needed to transition the PCIe link to Gen3 speed.
*/
int do_pcie_gen3_transition(struct hfi1_devdata *dd)
{
struct pci_dev *parent;
u64 fw_ctrl;
u64 reg, therm;
u32 reg32, fs, lf;
u32 status, err;
int ret;
int do_retry, retry_count = 0;
uint default_pset;
u16 target_vector, target_speed;
u16 lnkctl, lnkctl2, vendor;
u8 nsbr = 1;
u8 div;
const u8 (*eq)[3];
int return_error = 0;
/* PCIe Gen3 is for the ASIC only */
if (dd->icode != ICODE_RTL_SILICON)
return 0;
if (pcie_target == 1) { /* target Gen1 */
target_vector = GEN1_SPEED_VECTOR;
target_speed = 2500;
} else if (pcie_target == 2) { /* target Gen2 */
target_vector = GEN2_SPEED_VECTOR;
target_speed = 5000;
} else if (pcie_target == 3) { /* target Gen3 */
target_vector = GEN3_SPEED_VECTOR;
target_speed = 8000;
} else {
/* off or invalid target - skip */
dd_dev_info(dd, "%s: Skipping PCIe transition\n", __func__);
return 0;
}
/* if already at target speed, done (unless forced) */
if (dd->lbus_speed == target_speed) {
dd_dev_info(dd, "%s: PCIe already at gen%d, %s\n", __func__,
pcie_target,
pcie_force ? "re-doing anyway" : "skipping");
if (!pcie_force)
return 0;
}
/*
* A0 needs an additional SBR
*/
if (is_a0(dd))
nsbr++;
/*
* Do the Gen3 transition. Steps are those of the PCIe Gen3
* recipe.
*/
/* step 1: pcie link working in gen1/gen2 */
/* step 2: if either side is not capable of Gen3, done */
if (pcie_target == 3 && !dd->link_gen3_capable) {
dd_dev_err(dd, "The PCIe link is not Gen3 capable\n");
ret = -ENOSYS;
goto done_no_mutex;
}
/* hold the HW mutex across the firmware download and SBR */
ret = acquire_hw_mutex(dd);
if (ret)
return ret;
/* make sure thermal polling is not causing interrupts */
therm = read_csr(dd, ASIC_CFG_THERM_POLL_EN);
if (therm) {
write_csr(dd, ASIC_CFG_THERM_POLL_EN, 0x0);
msleep(100);
dd_dev_info(dd, "%s: Disabled therm polling\n",
__func__);
}
/* step 3: download SBus Master firmware */
/* step 4: download PCIe Gen3 SerDes firmware */
retry:
dd_dev_info(dd, "%s: downloading firmware\n", __func__);
ret = load_pcie_firmware(dd);
if (ret)
goto done;
/* step 5: set up device parameter settings */
dd_dev_info(dd, "%s: setting PCIe registers\n", __func__);
/*
* PcieCfgSpcie1 - Link Control 3
* Leave at reset value. No need to set PerfEq - link equalization
* will be performed automatically after the SBR when the target
* speed is 8GT/s.
*/
/* clear all 16 per-lane error bits (PCIe: Lane Error Status) */
pci_write_config_dword(dd->pcidev, PCIE_CFG_SPCIE2, 0xffff);
/* step 5a: Set Synopsys Port Logic registers */
/*
* PcieCfgRegPl2 - Port Force Link
*
* Set the low power field to 0x10 to avoid unnecessary power
* management messages. All other fields are zero.
*/
reg32 = 0x10ul << PCIE_CFG_REG_PL2_LOW_PWR_ENT_CNT_SHIFT;
pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL2, reg32);
/*
* PcieCfgRegPl100 - Gen3 Control
*
* turn off PcieCfgRegPl100.Gen3ZRxDcNonCompl
* turn on PcieCfgRegPl100.EqEieosCnt (erratum)
* Everything else zero.
*/
reg32 = PCIE_CFG_REG_PL100_EQ_EIEOS_CNT_SMASK;
pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL100, reg32);
/*
* PcieCfgRegPl101 - Gen3 EQ FS and LF
* PcieCfgRegPl102 - Gen3 EQ Presets to Coefficients Mapping
* PcieCfgRegPl103 - Gen3 EQ Preset Index
* PcieCfgRegPl105 - Gen3 EQ Status
*
* Give initial EQ settings.
*/
if (dd->pcidev->device == PCI_DEVICE_ID_INTEL0) { /* discrete */
/* 1000mV, FS=24, LF = 8 */
fs = 24;
lf = 8;
div = 3;
eq = discrete_preliminary_eq;
default_pset = DEFAULT_DISCRETE_PSET;
} else {
/* 400mV, FS=29, LF = 9 */
fs = 29;
lf = 9;
div = 1;
eq = integrated_preliminary_eq;
default_pset = DEFAULT_MCP_PSET;
}
pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL101,
(fs << PCIE_CFG_REG_PL101_GEN3_EQ_LOCAL_FS_SHIFT)
| (lf << PCIE_CFG_REG_PL101_GEN3_EQ_LOCAL_LF_SHIFT));
ret = load_eq_table(dd, eq, fs, div);
if (ret)
goto done;
/*
* PcieCfgRegPl106 - Gen3 EQ Control
*
* Set Gen3EqPsetReqVec, leave other fields 0.
*/
if (pcie_pset == UNSET_PSET)
pcie_pset = default_pset;
if (pcie_pset > 10) { /* valid range is 0-10, inclusive */
dd_dev_err(dd, "%s: Invalid Eq Pset %u, setting to %d\n",
__func__, pcie_pset, default_pset);
pcie_pset = default_pset;
}
dd_dev_info(dd, "%s: using EQ Pset %u\n", __func__, pcie_pset);
pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL106,
((1 << pcie_pset)
<< PCIE_CFG_REG_PL106_GEN3_EQ_PSET_REQ_VEC_SHIFT)
| PCIE_CFG_REG_PL106_GEN3_EQ_EVAL2MS_DISABLE_SMASK
| PCIE_CFG_REG_PL106_GEN3_EQ_PHASE23_EXIT_MODE_SMASK);
/*
* step 5b: Do post firmware download steps via SBus
*/
dd_dev_info(dd, "%s: doing pcie post steps\n", __func__);
pcie_post_steps(dd);
/*
* step 5c: Program gasket interrupts
*/
/* set the Rx Bit Rate to REFCLK ratio */
write_gasket_interrupt(dd, 0, 0x0006, 0x0050);
/* disable pCal for PCIe Gen3 RX equalization */
write_gasket_interrupt(dd, 1, 0x0026, 0x5b01);
/*
* Enable iCal for PCIe Gen3 RX equalization, and set which
* evaluation of RX_EQ_EVAL will launch the iCal procedure.
*/
write_gasket_interrupt(dd, 2, 0x0026, 0x5202);
/* terminate list */
write_gasket_interrupt(dd, 3, 0x0000, 0x0000);
/*
* step 5d: program XMT margin
* Right now, leave the default alone. To change, do a
* read-modify-write of:
* CcePcieCtrl.XmtMargin
* CcePcieCtrl.XmitMarginOverwriteEnable
*/
/* step 5e: disable active state power management (ASPM) */
dd_dev_info(dd, "%s: clearing ASPM\n", __func__);
pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKCTL, &lnkctl);
lnkctl &= ~PCI_EXP_LNKCTL_ASPMC;
pcie_capability_write_word(dd->pcidev, PCI_EXP_LNKCTL, lnkctl);
/*
* step 5f: clear DirectSpeedChange
* PcieCfgRegPl67.DirectSpeedChange must be zero to prevent the
* change in the speed target from starting before we are ready.
* This field defaults to 0 and we are not changing it, so nothing
* needs to be done.
*/
/* step 5g: Set target link speed */
/*
* Set target link speed to be target on both device and parent.
* On setting the parent: Some system BIOSs "helpfully" set the
* parent target speed to Gen2 to match the ASIC's initial speed.
* We can set the target Gen3 because we have already checked
* that it is Gen3 capable earlier.
*/
dd_dev_info(dd, "%s: setting parent target link speed\n", __func__);
parent = dd->pcidev->bus->self;
pcie_capability_read_word(parent, PCI_EXP_LNKCTL2, &lnkctl2);
dd_dev_info(dd, "%s: ..old link control2: 0x%x\n", __func__,
(u32)lnkctl2);
/* only write to parent if target is not as high as ours */
if ((lnkctl2 & LNKCTL2_TARGET_LINK_SPEED_MASK) < target_vector) {
lnkctl2 &= ~LNKCTL2_TARGET_LINK_SPEED_MASK;
lnkctl2 |= target_vector;
dd_dev_info(dd, "%s: ..new link control2: 0x%x\n", __func__,
(u32)lnkctl2);
pcie_capability_write_word(parent, PCI_EXP_LNKCTL2, lnkctl2);
} else {
dd_dev_info(dd, "%s: ..target speed is OK\n", __func__);
}
dd_dev_info(dd, "%s: setting target link speed\n", __func__);
pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKCTL2, &lnkctl2);
dd_dev_info(dd, "%s: ..old link control2: 0x%x\n", __func__,
(u32)lnkctl2);
lnkctl2 &= ~LNKCTL2_TARGET_LINK_SPEED_MASK;
lnkctl2 |= target_vector;
dd_dev_info(dd, "%s: ..new link control2: 0x%x\n", __func__,
(u32)lnkctl2);
pcie_capability_write_word(dd->pcidev, PCI_EXP_LNKCTL2, lnkctl2);
/* step 5h: arm gasket logic */
/* hold DC in reset across the SBR */
write_csr(dd, CCE_DC_CTRL, CCE_DC_CTRL_DC_RESET_SMASK);
(void) read_csr(dd, CCE_DC_CTRL); /* DC reset hold */
/* save firmware control across the SBR */
fw_ctrl = read_csr(dd, MISC_CFG_FW_CTRL);
dd_dev_info(dd, "%s: arming gasket logic\n", __func__);
arm_gasket_logic(dd);
/*
* step 6: quiesce PCIe link
* The chip has already been reset, so there will be no traffic
* from the chip. Linux has no easy way to enforce that it will
* not try to access the device, so we just need to hope it doesn't
* do it while we are doing the reset.
*/
/*
* step 7: initiate the secondary bus reset (SBR)
* step 8: hardware brings the links back up
* step 9: wait for link speed transition to be complete
*/
dd_dev_info(dd, "%s: calling trigger_sbr\n", __func__);
ret = trigger_sbr(dd);
if (ret)
goto done;
/* step 10: decide what to do next */
/* check if we can read PCI space */
ret = pci_read_config_word(dd->pcidev, PCI_VENDOR_ID, &vendor);
if (ret) {
dd_dev_info(dd,
"%s: read of VendorID failed after SBR, err %d\n",
__func__, ret);
return_error = 1;
goto done;
}
if (vendor == 0xffff) {
dd_dev_info(dd, "%s: VendorID is all 1s after SBR\n", __func__);
return_error = 1;
ret = -EIO;
goto done;
}
/* restore PCI space registers we know were reset */
dd_dev_info(dd, "%s: calling restore_pci_variables\n", __func__);
restore_pci_variables(dd);
/* restore firmware control */
write_csr(dd, MISC_CFG_FW_CTRL, fw_ctrl);
/*
* Check the gasket block status.
*
* This is the first CSR read after the SBR. If the read returns
* all 1s (fails), the link did not make it back.
*
* Once we're sure we can read and write, clear the DC reset after
* the SBR. Then check for any per-lane errors. Then look over
* the status.
*/
reg = read_csr(dd, ASIC_PCIE_SD_HOST_STATUS);
dd_dev_info(dd, "%s: gasket block status: 0x%llx\n", __func__, reg);
if (reg == ~0ull) { /* PCIe read failed/timeout */
dd_dev_err(dd, "SBR failed - unable to read from device\n");
return_error = 1;
ret = -ENOSYS;
goto done;
}
/* clear the DC reset */
write_csr(dd, CCE_DC_CTRL, 0);
/* Set the LED off */
if (is_a0(dd))
setextled(dd, 0);
/* check for any per-lane errors */
pci_read_config_dword(dd->pcidev, PCIE_CFG_SPCIE2, ®32);
dd_dev_info(dd, "%s: per-lane errors: 0x%x\n", __func__, reg32);
/* extract status, look for our HFI */
status = (reg >> ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_STS_SHIFT)
& ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_STS_MASK;
if ((status & (1 << dd->hfi1_id)) == 0) {
dd_dev_err(dd,
"%s: gasket status 0x%x, expecting 0x%x\n",
__func__, status, 1 << dd->hfi1_id);
ret = -EIO;
goto done;
}
/* extract error */
err = (reg >> ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_ERR_SHIFT)
& ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_ERR_MASK;
if (err) {
dd_dev_err(dd, "%s: gasket error %d\n", __func__, err);
ret = -EIO;
goto done;
}
/* update our link information cache */
update_lbus_info(dd);
dd_dev_info(dd, "%s: new speed and width: %s\n", __func__,
dd->lbus_info);
if (dd->lbus_speed != target_speed) { /* not target */
/* maybe retry */
do_retry = retry_count < pcie_retry;
dd_dev_err(dd, "PCIe link speed did not switch to Gen%d%s\n",
pcie_target, do_retry ? ", retrying" : "");
retry_count++;
if (do_retry) {
msleep(100); /* allow time to settle */
goto retry;
}
ret = -EIO;
}
done:
if (therm) {
write_csr(dd, ASIC_CFG_THERM_POLL_EN, 0x1);
msleep(100);
dd_dev_info(dd, "%s: Re-enable therm polling\n",
__func__);
}
release_hw_mutex(dd);
done_no_mutex:
/* return no error if it is OK to be at current speed */
if (ret && !return_error) {
dd_dev_err(dd, "Proceeding at current speed PCIe speed\n");
ret = 0;
}
dd_dev_info(dd, "%s: done\n", __func__);
return ret;
}
| mit |
joenmarz/joenmarz-yii2-advanced-with-gulp-bootstrap-sass | node_modules/node-sass/src/libsass/src/functions.cpp | 452 | 71309 | #include "sass.hpp"
#include "functions.hpp"
#include "ast.hpp"
#include "context.hpp"
#include "backtrace.hpp"
#include "parser.hpp"
#include "constants.hpp"
#include "inspect.hpp"
#include "extend.hpp"
#include "eval.hpp"
#include "util.hpp"
#include "expand.hpp"
#include "utf8_string.hpp"
#include "sass/base.h"
#include "utf8.h"
#include <cstdint>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <sstream>
#include <string>
#include <iomanip>
#include <iostream>
#include <random>
#include <set>
#ifdef __MINGW32__
#include "windows.h"
#include "wincrypt.h"
#endif
#define ARG(argname, argtype) get_arg<argtype>(argname, env, sig, pstate, backtrace)
#define ARGR(argname, argtype, lo, hi) get_arg_r(argname, env, sig, pstate, lo, hi, backtrace)
#define ARGM(argname, argtype, ctx) get_arg_m(argname, env, sig, pstate, backtrace, ctx)
namespace Sass {
using std::stringstream;
using std::endl;
Definition* make_native_function(Signature sig, Native_Function func, Context& ctx)
{
Parser sig_parser = Parser::from_c_str(sig, ctx, ParserState("[built-in function]"));
sig_parser.lex<Prelexer::identifier>();
std::string name(Util::normalize_underscores(sig_parser.lexed));
Parameters* params = sig_parser.parse_parameters();
return SASS_MEMORY_NEW(ctx.mem, Definition,
ParserState("[built-in function]"),
sig,
name,
params,
func,
false);
}
Definition* make_c_function(Sass_Function_Entry c_func, Context& ctx)
{
using namespace Prelexer;
const char* sig = sass_function_get_signature(c_func);
Parser sig_parser = Parser::from_c_str(sig, ctx, ParserState("[c function]"));
// allow to overload generic callback plus @warn, @error and @debug with custom functions
sig_parser.lex < alternatives < identifier, exactly <'*'>,
exactly < Constants::warn_kwd >,
exactly < Constants::error_kwd >,
exactly < Constants::debug_kwd >
> >();
std::string name(Util::normalize_underscores(sig_parser.lexed));
Parameters* params = sig_parser.parse_parameters();
return SASS_MEMORY_NEW(ctx.mem, Definition,
ParserState("[c function]"),
sig,
name,
params,
c_func,
false, true);
}
std::string function_name(Signature sig)
{
std::string str(sig);
return str.substr(0, str.find('('));
}
namespace Functions {
inline void handle_utf8_error (const ParserState& pstate, Backtrace* backtrace)
{
try {
throw;
}
catch (utf8::invalid_code_point) {
std::string msg("utf8::invalid_code_point");
error(msg, pstate, backtrace);
}
catch (utf8::not_enough_room) {
std::string msg("utf8::not_enough_room");
error(msg, pstate, backtrace);
}
catch (utf8::invalid_utf8) {
std::string msg("utf8::invalid_utf8");
error(msg, pstate, backtrace);
}
catch (...) { throw; }
}
template <typename T>
T* get_arg(const std::string& argname, Env& env, Signature sig, ParserState pstate, Backtrace* backtrace)
{
// Minimal error handling -- the expectation is that built-ins will be written correctly!
T* val = dynamic_cast<T*>(env[argname]);
if (!val) {
std::string msg("argument `");
msg += argname;
msg += "` of `";
msg += sig;
msg += "` must be a ";
msg += T::type_name();
error(msg, pstate, backtrace);
}
return val;
}
Map* get_arg_m(const std::string& argname, Env& env, Signature sig, ParserState pstate, Backtrace* backtrace, Context& ctx)
{
// Minimal error handling -- the expectation is that built-ins will be written correctly!
Map* val = dynamic_cast<Map*>(env[argname]);
if (val) return val;
List* lval = dynamic_cast<List*>(env[argname]);
if (lval && lval->length() == 0) return SASS_MEMORY_NEW(ctx.mem, Map, pstate, 0);
// fallback on get_arg for error handling
val = get_arg<Map>(argname, env, sig, pstate, backtrace);
return val;
}
Number* get_arg_r(const std::string& argname, Env& env, Signature sig, ParserState pstate, double lo, double hi, Backtrace* backtrace)
{
// Minimal error handling -- the expectation is that built-ins will be written correctly!
Number* val = get_arg<Number>(argname, env, sig, pstate, backtrace);
double v = val->value();
if (!(lo <= v && v <= hi)) {
std::stringstream msg;
msg << "argument `" << argname << "` of `" << sig << "` must be between ";
msg << lo << " and " << hi;
error(msg.str(), pstate, backtrace);
}
return val;
}
#define ARGSEL(argname, seltype, contextualize) get_arg_sel<seltype>(argname, env, sig, pstate, backtrace, ctx)
template <typename T>
T* get_arg_sel(const std::string& argname, Env& env, Signature sig, ParserState pstate, Backtrace* backtrace, Context& ctx);
template <>
Selector_List* get_arg_sel(const std::string& argname, Env& env, Signature sig, ParserState pstate, Backtrace* backtrace, Context& ctx) {
Expression* exp = ARG(argname, Expression);
if (exp->concrete_type() == Expression::NULL_VAL) {
std::stringstream msg;
msg << argname << ": null is not a valid selector: it must be a string,\n";
msg << "a list of strings, or a list of lists of strings for `" << function_name(sig) << "'";
error(msg.str(), pstate);
}
if (String_Constant* str =dynamic_cast<String_Constant*>(exp)) {
str->quote_mark(0);
}
std::string exp_src = exp->to_string(ctx.c_options) + "{";
return Parser::parse_selector(exp_src.c_str(), ctx);
}
template <>
Complex_Selector* get_arg_sel(const std::string& argname, Env& env, Signature sig, ParserState pstate, Backtrace* backtrace, Context& ctx) {
Expression* exp = ARG(argname, Expression);
if (exp->concrete_type() == Expression::NULL_VAL) {
std::stringstream msg;
msg << argname << ": null is not a valid selector: it must be a string,\n";
msg << "a list of strings, or a list of lists of strings for `" << function_name(sig) << "'";
error(msg.str(), pstate);
}
if (String_Constant* str =dynamic_cast<String_Constant*>(exp)) {
str->quote_mark(0);
}
std::string exp_src = exp->to_string(ctx.c_options) + "{";
Selector_List* sel_list = Parser::parse_selector(exp_src.c_str(), ctx);
return (sel_list->length() > 0) ? sel_list->first() : 0;
}
template <>
Compound_Selector* get_arg_sel(const std::string& argname, Env& env, Signature sig, ParserState pstate, Backtrace* backtrace, Context& ctx) {
Expression* exp = ARG(argname, Expression);
if (exp->concrete_type() == Expression::NULL_VAL) {
std::stringstream msg;
msg << argname << ": null is not a string for `" << function_name(sig) << "'";
error(msg.str(), pstate);
}
if (String_Constant* str =dynamic_cast<String_Constant*>(exp)) {
str->quote_mark(0);
}
std::string exp_src = exp->to_string(ctx.c_options) + "{";
Selector_List* sel_list = Parser::parse_selector(exp_src.c_str(), ctx);
return (sel_list->length() > 0) ? sel_list->first()->tail()->head() : 0;
}
#ifdef __MINGW32__
uint64_t GetSeed()
{
HCRYPTPROV hp = 0;
BYTE rb[8];
CryptAcquireContext(&hp, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
CryptGenRandom(hp, sizeof(rb), rb);
CryptReleaseContext(hp, 0);
uint64_t seed;
memcpy(&seed, &rb[0], sizeof(seed));
return seed;
}
#else
uint64_t GetSeed()
{
std::random_device rd;
return rd();
}
#endif
// note: the performance of many implementations of
// random_device degrades sharply once the entropy pool
// is exhausted. For practical use, random_device is
// generally only used to seed a PRNG such as mt19937.
static std::mt19937 rand(static_cast<unsigned int>(GetSeed()));
// features
static std::set<std::string> features {
"global-variable-shadowing",
"extend-selector-pseudoclass",
"at-error",
"units-level-3"
};
////////////////
// RGB FUNCTIONS
////////////////
inline double color_num(Number* n) {
if (n->unit() == "%") {
return std::min(std::max(n->value() * 255 / 100.0, 0.0), 255.0);
} else {
return std::min(std::max(n->value(), 0.0), 255.0);
}
}
inline double alpha_num(Number* n) {
if (n->unit() == "%") {
return std::min(std::max(n->value(), 0.0), 100.0);
} else {
return std::min(std::max(n->value(), 0.0), 1.0);
}
}
Signature rgb_sig = "rgb($red, $green, $blue)";
BUILT_IN(rgb)
{
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
color_num(ARG("$red", Number)),
color_num(ARG("$green", Number)),
color_num(ARG("$blue", Number)));
}
Signature rgba_4_sig = "rgba($red, $green, $blue, $alpha)";
BUILT_IN(rgba_4)
{
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
color_num(ARG("$red", Number)),
color_num(ARG("$green", Number)),
color_num(ARG("$blue", Number)),
alpha_num(ARG("$alpha", Number)));
}
Signature rgba_2_sig = "rgba($color, $alpha)";
BUILT_IN(rgba_2)
{
Color* c_arg = ARG("$color", Color);
Color* new_c = SASS_MEMORY_NEW(ctx.mem, Color, *c_arg);
new_c->a(alpha_num(ARG("$alpha", Number)));
new_c->disp("");
return new_c;
}
Signature red_sig = "red($color)";
BUILT_IN(red)
{ return SASS_MEMORY_NEW(ctx.mem, Number, pstate, ARG("$color", Color)->r()); }
Signature green_sig = "green($color)";
BUILT_IN(green)
{ return SASS_MEMORY_NEW(ctx.mem, Number, pstate, ARG("$color", Color)->g()); }
Signature blue_sig = "blue($color)";
BUILT_IN(blue)
{ return SASS_MEMORY_NEW(ctx.mem, Number, pstate, ARG("$color", Color)->b()); }
Signature mix_sig = "mix($color-1, $color-2, $weight: 50%)";
BUILT_IN(mix)
{
Color* color1 = ARG("$color-1", Color);
Color* color2 = ARG("$color-2", Color);
Number* weight = ARGR("$weight", Number, 0, 100);
double p = weight->value()/100;
double w = 2*p - 1;
double a = color1->a() - color2->a();
double w1 = (((w * a == -1) ? w : (w + a)/(1 + w*a)) + 1)/2.0;
double w2 = 1 - w1;
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
Sass::round(w1*color1->r() + w2*color2->r(), ctx.c_options.precision),
Sass::round(w1*color1->g() + w2*color2->g(), ctx.c_options.precision),
Sass::round(w1*color1->b() + w2*color2->b(), ctx.c_options.precision),
color1->a()*p + color2->a()*(1-p));
}
////////////////
// HSL FUNCTIONS
////////////////
// RGB to HSL helper function
struct HSL { double h; double s; double l; };
HSL rgb_to_hsl(double r, double g, double b)
{
// Algorithm from http://en.wikipedia.org/wiki/wHSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
r /= 255.0; g /= 255.0; b /= 255.0;
double max = std::max(r, std::max(g, b));
double min = std::min(r, std::min(g, b));
double delta = max - min;
double h = 0, s = 0, l = (max + min) / 2.0;
if (max == min) {
h = s = 0; // achromatic
}
else {
if (l < 0.5) s = delta / (max + min);
else s = delta / (2.0 - max - min);
if (r == max) h = (g - b) / delta + (g < b ? 6 : 0);
else if (g == max) h = (b - r) / delta + 2;
else if (b == max) h = (r - g) / delta + 4;
}
HSL hsl_struct;
hsl_struct.h = h / 6 * 360;
hsl_struct.s = s * 100;
hsl_struct.l = l * 100;
return hsl_struct;
}
// hue to RGB helper function
double h_to_rgb(double m1, double m2, double h) {
while (h < 0) h += 1;
while (h > 1) h -= 1;
if (h*6.0 < 1) return m1 + (m2 - m1)*h*6;
if (h*2.0 < 1) return m2;
if (h*3.0 < 2) return m1 + (m2 - m1) * (2.0/3.0 - h)*6;
return m1;
}
Color* hsla_impl(double h, double s, double l, double a, Context& ctx, ParserState pstate)
{
h /= 360.0;
s /= 100.0;
l /= 100.0;
if (l < 0) l = 0;
if (s < 0) s = 0;
if (l > 1) l = 1;
if (s > 1) s = 1;
while (h < 0) h += 1;
while (h > 1) h -= 1;
// Algorithm from the CSS3 spec: http://www.w3.org/TR/css3-color/#hsl-color.
double m2;
if (l <= 0.5) m2 = l*(s+1.0);
else m2 = (l+s)-(l*s);
double m1 = (l*2.0)-m2;
// round the results -- consider moving this into the Color constructor
double r = (h_to_rgb(m1, m2, h + 1.0/3.0) * 255.0);
double g = (h_to_rgb(m1, m2, h) * 255.0);
double b = (h_to_rgb(m1, m2, h - 1.0/3.0) * 255.0);
return SASS_MEMORY_NEW(ctx.mem, Color, pstate, r, g, b, a);
}
Signature hsl_sig = "hsl($hue, $saturation, $lightness)";
BUILT_IN(hsl)
{
return hsla_impl(ARG("$hue", Number)->value(),
ARG("$saturation", Number)->value(),
ARG("$lightness", Number)->value(),
1.0,
ctx,
pstate);
}
Signature hsla_sig = "hsla($hue, $saturation, $lightness, $alpha)";
BUILT_IN(hsla)
{
return hsla_impl(ARG("$hue", Number)->value(),
ARG("$saturation", Number)->value(),
ARG("$lightness", Number)->value(),
ARG("$alpha", Number)->value(),
ctx,
pstate);
}
Signature hue_sig = "hue($color)";
BUILT_IN(hue)
{
Color* rgb_color = ARG("$color", Color);
HSL hsl_color = rgb_to_hsl(rgb_color->r(),
rgb_color->g(),
rgb_color->b());
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, hsl_color.h, "deg");
}
Signature saturation_sig = "saturation($color)";
BUILT_IN(saturation)
{
Color* rgb_color = ARG("$color", Color);
HSL hsl_color = rgb_to_hsl(rgb_color->r(),
rgb_color->g(),
rgb_color->b());
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, hsl_color.s, "%");
}
Signature lightness_sig = "lightness($color)";
BUILT_IN(lightness)
{
Color* rgb_color = ARG("$color", Color);
HSL hsl_color = rgb_to_hsl(rgb_color->r(),
rgb_color->g(),
rgb_color->b());
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, hsl_color.l, "%");
}
Signature adjust_hue_sig = "adjust-hue($color, $degrees)";
BUILT_IN(adjust_hue)
{
Color* rgb_color = ARG("$color", Color);
Number* degrees = ARG("$degrees", Number);
HSL hsl_color = rgb_to_hsl(rgb_color->r(),
rgb_color->g(),
rgb_color->b());
return hsla_impl(hsl_color.h + degrees->value(),
hsl_color.s,
hsl_color.l,
rgb_color->a(),
ctx,
pstate);
}
Signature lighten_sig = "lighten($color, $amount)";
BUILT_IN(lighten)
{
Color* rgb_color = ARG("$color", Color);
Number* amount = ARGR("$amount", Number, 0, 100);
HSL hsl_color = rgb_to_hsl(rgb_color->r(),
rgb_color->g(),
rgb_color->b());
//Check lightness is not negative before lighten it
double hslcolorL = hsl_color.l;
if (hslcolorL < 0) {
hslcolorL = 0;
}
return hsla_impl(hsl_color.h,
hsl_color.s,
hslcolorL + amount->value(),
rgb_color->a(),
ctx,
pstate);
}
Signature darken_sig = "darken($color, $amount)";
BUILT_IN(darken)
{
Color* rgb_color = ARG("$color", Color);
Number* amount = ARGR("$amount", Number, 0, 100);
HSL hsl_color = rgb_to_hsl(rgb_color->r(),
rgb_color->g(),
rgb_color->b());
//Check lightness if not over 100, before darken it
double hslcolorL = hsl_color.l;
if (hslcolorL > 100) {
hslcolorL = 100;
}
return hsla_impl(hsl_color.h,
hsl_color.s,
hslcolorL - amount->value(),
rgb_color->a(),
ctx,
pstate);
}
Signature saturate_sig = "saturate($color, $amount: false)";
BUILT_IN(saturate)
{
// CSS3 filter function overload: pass literal through directly
Number* amount = dynamic_cast<Number*>(env["$amount"]);
if (!amount) {
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, "saturate(" + env["$color"]->to_string(ctx.c_options) + ")");
}
ARGR("$amount", Number, 0, 100);
Color* rgb_color = ARG("$color", Color);
HSL hsl_color = rgb_to_hsl(rgb_color->r(),
rgb_color->g(),
rgb_color->b());
double hslcolorS = hsl_color.s + amount->value();
// Saturation cannot be below 0 or above 100
if (hslcolorS < 0) {
hslcolorS = 0;
}
if (hslcolorS > 100) {
hslcolorS = 100;
}
return hsla_impl(hsl_color.h,
hslcolorS,
hsl_color.l,
rgb_color->a(),
ctx,
pstate);
}
Signature desaturate_sig = "desaturate($color, $amount)";
BUILT_IN(desaturate)
{
Color* rgb_color = ARG("$color", Color);
Number* amount = ARGR("$amount", Number, 0, 100);
HSL hsl_color = rgb_to_hsl(rgb_color->r(),
rgb_color->g(),
rgb_color->b());
double hslcolorS = hsl_color.s - amount->value();
// Saturation cannot be below 0 or above 100
if (hslcolorS <= 0) {
hslcolorS = 0;
}
if (hslcolorS > 100) {
hslcolorS = 100;
}
return hsla_impl(hsl_color.h,
hslcolorS,
hsl_color.l,
rgb_color->a(),
ctx,
pstate);
}
Signature grayscale_sig = "grayscale($color)";
BUILT_IN(grayscale)
{
// CSS3 filter function overload: pass literal through directly
Number* amount = dynamic_cast<Number*>(env["$color"]);
if (amount) {
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, "grayscale(" + amount->to_string(ctx.c_options) + ")");
}
Color* rgb_color = ARG("$color", Color);
HSL hsl_color = rgb_to_hsl(rgb_color->r(),
rgb_color->g(),
rgb_color->b());
return hsla_impl(hsl_color.h,
0.0,
hsl_color.l,
rgb_color->a(),
ctx,
pstate);
}
Signature complement_sig = "complement($color)";
BUILT_IN(complement)
{
Color* rgb_color = ARG("$color", Color);
HSL hsl_color = rgb_to_hsl(rgb_color->r(),
rgb_color->g(),
rgb_color->b());
return hsla_impl(hsl_color.h - 180.0,
hsl_color.s,
hsl_color.l,
rgb_color->a(),
ctx,
pstate);
}
Signature invert_sig = "invert($color)";
BUILT_IN(invert)
{
// CSS3 filter function overload: pass literal through directly
Number* amount = dynamic_cast<Number*>(env["$color"]);
if (amount) {
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, "invert(" + amount->to_string(ctx.c_options) + ")");
}
Color* rgb_color = ARG("$color", Color);
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
255 - rgb_color->r(),
255 - rgb_color->g(),
255 - rgb_color->b(),
rgb_color->a());
}
////////////////////
// OPACITY FUNCTIONS
////////////////////
Signature alpha_sig = "alpha($color)";
Signature opacity_sig = "opacity($color)";
BUILT_IN(alpha)
{
String_Constant* ie_kwd = dynamic_cast<String_Constant*>(env["$color"]);
if (ie_kwd) {
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, "alpha(" + ie_kwd->value() + ")");
}
// CSS3 filter function overload: pass literal through directly
Number* amount = dynamic_cast<Number*>(env["$color"]);
if (amount) {
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, "opacity(" + amount->to_string(ctx.c_options) + ")");
}
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, ARG("$color", Color)->a());
}
Signature opacify_sig = "opacify($color, $amount)";
Signature fade_in_sig = "fade-in($color, $amount)";
BUILT_IN(opacify)
{
Color* color = ARG("$color", Color);
double amount = ARGR("$amount", Number, 0, 1)->value();
double alpha = std::min(color->a() + amount, 1.0);
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
color->r(),
color->g(),
color->b(),
alpha);
}
Signature transparentize_sig = "transparentize($color, $amount)";
Signature fade_out_sig = "fade-out($color, $amount)";
BUILT_IN(transparentize)
{
Color* color = ARG("$color", Color);
double amount = ARGR("$amount", Number, 0, 1)->value();
double alpha = std::max(color->a() - amount, 0.0);
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
color->r(),
color->g(),
color->b(),
alpha);
}
////////////////////////
// OTHER COLOR FUNCTIONS
////////////////////////
Signature adjust_color_sig = "adjust-color($color, $red: false, $green: false, $blue: false, $hue: false, $saturation: false, $lightness: false, $alpha: false)";
BUILT_IN(adjust_color)
{
Color* color = ARG("$color", Color);
Number* r = dynamic_cast<Number*>(env["$red"]);
Number* g = dynamic_cast<Number*>(env["$green"]);
Number* b = dynamic_cast<Number*>(env["$blue"]);
Number* h = dynamic_cast<Number*>(env["$hue"]);
Number* s = dynamic_cast<Number*>(env["$saturation"]);
Number* l = dynamic_cast<Number*>(env["$lightness"]);
Number* a = dynamic_cast<Number*>(env["$alpha"]);
bool rgb = r || g || b;
bool hsl = h || s || l;
if (rgb && hsl) {
error("cannot specify both RGB and HSL values for `adjust-color`", pstate);
}
if (rgb) {
double rr = r ? ARGR("$red", Number, -255, 255)->value() : 0;
double gg = g ? ARGR("$green", Number, -255, 255)->value() : 0;
double bb = b ? ARGR("$blue", Number, -255, 255)->value() : 0;
double aa = a ? ARGR("$alpha", Number, -1, 1)->value() : 0;
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
color->r() + rr,
color->g() + gg,
color->b() + bb,
color->a() + aa);
}
if (hsl) {
HSL hsl_struct = rgb_to_hsl(color->r(), color->g(), color->b());
double ss = s ? ARGR("$saturation", Number, -100, 100)->value() : 0;
double ll = l ? ARGR("$lightness", Number, -100, 100)->value() : 0;
double aa = a ? ARGR("$alpha", Number, -1, 1)->value() : 0;
return hsla_impl(hsl_struct.h + (h ? h->value() : 0),
hsl_struct.s + ss,
hsl_struct.l + ll,
color->a() + aa,
ctx,
pstate);
}
if (a) {
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
color->r(),
color->g(),
color->b(),
color->a() + (a ? a->value() : 0));
}
error("not enough arguments for `adjust-color`", pstate);
// unreachable
return color;
}
Signature scale_color_sig = "scale-color($color, $red: false, $green: false, $blue: false, $hue: false, $saturation: false, $lightness: false, $alpha: false)";
BUILT_IN(scale_color)
{
Color* color = ARG("$color", Color);
Number* r = dynamic_cast<Number*>(env["$red"]);
Number* g = dynamic_cast<Number*>(env["$green"]);
Number* b = dynamic_cast<Number*>(env["$blue"]);
Number* h = dynamic_cast<Number*>(env["$hue"]);
Number* s = dynamic_cast<Number*>(env["$saturation"]);
Number* l = dynamic_cast<Number*>(env["$lightness"]);
Number* a = dynamic_cast<Number*>(env["$alpha"]);
bool rgb = r || g || b;
bool hsl = h || s || l;
if (rgb && hsl) {
error("cannot specify both RGB and HSL values for `scale-color`", pstate);
}
if (rgb) {
double rscale = (r ? ARGR("$red", Number, -100.0, 100.0)->value() : 0.0) / 100.0;
double gscale = (g ? ARGR("$green", Number, -100.0, 100.0)->value() : 0.0) / 100.0;
double bscale = (b ? ARGR("$blue", Number, -100.0, 100.0)->value() : 0.0) / 100.0;
double ascale = (a ? ARGR("$alpha", Number, -100.0, 100.0)->value() : 0.0) / 100.0;
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
color->r() + rscale * (rscale > 0.0 ? 255 - color->r() : color->r()),
color->g() + gscale * (gscale > 0.0 ? 255 - color->g() : color->g()),
color->b() + bscale * (bscale > 0.0 ? 255 - color->b() : color->b()),
color->a() + ascale * (ascale > 0.0 ? 1.0 - color->a() : color->a()));
}
if (hsl) {
double hscale = (h ? ARGR("$hue", Number, -100.0, 100.0)->value() : 0.0) / 100.0;
double sscale = (s ? ARGR("$saturation", Number, -100.0, 100.0)->value() : 0.0) / 100.0;
double lscale = (l ? ARGR("$lightness", Number, -100.0, 100.0)->value() : 0.0) / 100.0;
double ascale = (a ? ARGR("$alpha", Number, -100.0, 100.0)->value() : 0.0) / 100.0;
HSL hsl_struct = rgb_to_hsl(color->r(), color->g(), color->b());
hsl_struct.h += hscale * (hscale > 0.0 ? 360.0 - hsl_struct.h : hsl_struct.h);
hsl_struct.s += sscale * (sscale > 0.0 ? 100.0 - hsl_struct.s : hsl_struct.s);
hsl_struct.l += lscale * (lscale > 0.0 ? 100.0 - hsl_struct.l : hsl_struct.l);
double alpha = color->a() + ascale * (ascale > 0.0 ? 1.0 - color->a() : color->a());
return hsla_impl(hsl_struct.h, hsl_struct.s, hsl_struct.l, alpha, ctx, pstate);
}
if (a) {
double ascale = (a ? ARGR("$alpha", Number, -100.0, 100.0)->value() : 0.0) / 100.0;
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
color->r(),
color->g(),
color->b(),
color->a() + ascale * (ascale > 0.0 ? 1.0 - color->a() : color->a()));
}
error("not enough arguments for `scale-color`", pstate);
// unreachable
return color;
}
Signature change_color_sig = "change-color($color, $red: false, $green: false, $blue: false, $hue: false, $saturation: false, $lightness: false, $alpha: false)";
BUILT_IN(change_color)
{
Color* color = ARG("$color", Color);
Number* r = dynamic_cast<Number*>(env["$red"]);
Number* g = dynamic_cast<Number*>(env["$green"]);
Number* b = dynamic_cast<Number*>(env["$blue"]);
Number* h = dynamic_cast<Number*>(env["$hue"]);
Number* s = dynamic_cast<Number*>(env["$saturation"]);
Number* l = dynamic_cast<Number*>(env["$lightness"]);
Number* a = dynamic_cast<Number*>(env["$alpha"]);
bool rgb = r || g || b;
bool hsl = h || s || l;
if (rgb && hsl) {
error("cannot specify both RGB and HSL values for `change-color`", pstate);
}
if (rgb) {
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
r ? ARGR("$red", Number, 0, 255)->value() : color->r(),
g ? ARGR("$green", Number, 0, 255)->value() : color->g(),
b ? ARGR("$blue", Number, 0, 255)->value() : color->b(),
a ? ARGR("$alpha", Number, 0, 255)->value() : color->a());
}
if (hsl) {
HSL hsl_struct = rgb_to_hsl(color->r(), color->g(), color->b());
if (h) hsl_struct.h = static_cast<double>(((static_cast<int>(h->value()) % 360) + 360) % 360) / 360.0;
if (s) hsl_struct.s = ARGR("$saturation", Number, 0, 100)->value();
if (l) hsl_struct.l = ARGR("$lightness", Number, 0, 100)->value();
double alpha = a ? ARGR("$alpha", Number, 0, 1.0)->value() : color->a();
return hsla_impl(hsl_struct.h, hsl_struct.s, hsl_struct.l, alpha, ctx, pstate);
}
if (a) {
double alpha = a ? ARGR("$alpha", Number, 0, 1.0)->value() : color->a();
return SASS_MEMORY_NEW(ctx.mem, Color,
pstate,
color->r(),
color->g(),
color->b(),
alpha);
}
error("not enough arguments for `change-color`", pstate);
// unreachable
return color;
}
template <size_t range>
static double cap_channel(double c) {
if (c > range) return range;
else if (c < 0) return 0;
else return c;
}
Signature ie_hex_str_sig = "ie-hex-str($color)";
BUILT_IN(ie_hex_str)
{
Color* c = ARG("$color", Color);
double r = cap_channel<0xff>(c->r());
double g = cap_channel<0xff>(c->g());
double b = cap_channel<0xff>(c->b());
double a = cap_channel<1> (c->a()) * 255;
std::stringstream ss;
ss << '#' << std::setw(2) << std::setfill('0');
ss << std::hex << std::setw(2) << static_cast<unsigned long>(Sass::round(a, ctx.c_options.precision));
ss << std::hex << std::setw(2) << static_cast<unsigned long>(Sass::round(r, ctx.c_options.precision));
ss << std::hex << std::setw(2) << static_cast<unsigned long>(Sass::round(g, ctx.c_options.precision));
ss << std::hex << std::setw(2) << static_cast<unsigned long>(Sass::round(b, ctx.c_options.precision));
std::string result(ss.str());
for (size_t i = 0, L = result.length(); i < L; ++i) {
result[i] = std::toupper(result[i]);
}
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, result);
}
///////////////////
// STRING FUNCTIONS
///////////////////
Signature unquote_sig = "unquote($string)";
BUILT_IN(sass_unquote)
{
AST_Node* arg = env["$string"];
if (String_Quoted* string_quoted = dynamic_cast<String_Quoted*>(arg)) {
String_Constant* result = SASS_MEMORY_NEW(ctx.mem, String_Constant, pstate, string_quoted->value());
// remember if the string was quoted (color tokens)
result->sass_fix_1291(string_quoted->quote_mark() != 0);
return result;
}
else if (dynamic_cast<String_Constant*>(arg)) {
return (Expression*) arg;
}
else {
Sass_Output_Style oldstyle = ctx.c_options.output_style;
ctx.c_options.output_style = SASS_STYLE_NESTED;
std::string val(arg->to_string(ctx.c_options));
val = dynamic_cast<Null*>(arg) ? "null" : val;
ctx.c_options.output_style = oldstyle;
deprecated_function("Passing " + val + ", a non-string value, to unquote()", pstate);
return (Expression*) arg;
}
}
Signature quote_sig = "quote($string)";
BUILT_IN(sass_quote)
{
AST_Node* arg = env["$string"];
// only set quote mark to true if already a string
if (String_Quoted* qstr = dynamic_cast<String_Quoted*>(arg)) {
qstr->quote_mark('*');
return qstr;
}
// all other nodes must be converted to a string node
std::string str(quote(arg->to_string(ctx.c_options), String_Constant::double_quote()));
String_Quoted* result = SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, str);
result->is_delayed(true);
result->quote_mark('*');
return result;
}
Signature str_length_sig = "str-length($string)";
BUILT_IN(str_length)
{
size_t len = std::string::npos;
try {
String_Constant* s = ARG("$string", String_Constant);
len = UTF_8::code_point_count(s->value(), 0, s->value().size());
}
// handle any invalid utf8 errors
// other errors will be re-thrown
catch (...) { handle_utf8_error(pstate, backtrace); }
// return something even if we had an error (-1)
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, (double)len);
}
Signature str_insert_sig = "str-insert($string, $insert, $index)";
BUILT_IN(str_insert)
{
std::string str;
try {
String_Constant* s = ARG("$string", String_Constant);
str = s->value();
str = unquote(str);
String_Constant* i = ARG("$insert", String_Constant);
std::string ins = i->value();
ins = unquote(ins);
Number* ind = ARG("$index", Number);
double index = ind->value();
size_t len = UTF_8::code_point_count(str, 0, str.size());
if (index > 0 && index <= len) {
// positive and within string length
str.insert(UTF_8::offset_at_position(str, static_cast<size_t>(index) - 1), ins);
}
else if (index > len) {
// positive and past string length
str += ins;
}
else if (index == 0) {
str = ins + str;
}
else if (std::abs(index) <= len) {
// negative and within string length
index += len + 1;
str.insert(UTF_8::offset_at_position(str, static_cast<size_t>(index)), ins);
}
else {
// negative and past string length
str = ins + str;
}
if (String_Quoted* ss = dynamic_cast<String_Quoted*>(s)) {
if (ss->quote_mark()) str = quote(str);
}
}
// handle any invalid utf8 errors
// other errors will be re-thrown
catch (...) { handle_utf8_error(pstate, backtrace); }
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, str);
}
Signature str_index_sig = "str-index($string, $substring)";
BUILT_IN(str_index)
{
size_t index = std::string::npos;
try {
String_Constant* s = ARG("$string", String_Constant);
String_Constant* t = ARG("$substring", String_Constant);
std::string str = s->value();
str = unquote(str);
std::string substr = t->value();
substr = unquote(substr);
size_t c_index = str.find(substr);
if(c_index == std::string::npos) {
return SASS_MEMORY_NEW(ctx.mem, Null, pstate);
}
index = UTF_8::code_point_count(str, 0, c_index) + 1;
}
// handle any invalid utf8 errors
// other errors will be re-thrown
catch (...) { handle_utf8_error(pstate, backtrace); }
// return something even if we had an error (-1)
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, (double)index);
}
Signature str_slice_sig = "str-slice($string, $start-at, $end-at:-1)";
BUILT_IN(str_slice)
{
std::string newstr;
try {
String_Constant* s = ARG("$string", String_Constant);
double start_at = ARG("$start-at", Number)->value();
double end_at = ARG("$end-at", Number)->value();
std::string str = unquote(s->value());
size_t size = utf8::distance(str.begin(), str.end());
if (end_at <= size * -1.0) { end_at += size; }
if (end_at < 0) { end_at += size + 1; }
if (end_at > size) { end_at = (double)size; }
if (start_at < 0) { start_at += size + 1; }
else if (start_at == 0) { ++ start_at; }
if (start_at <= end_at)
{
std::string::iterator start = str.begin();
utf8::advance(start, start_at - 1, str.end());
std::string::iterator end = start;
utf8::advance(end, end_at - start_at + 1, str.end());
newstr = std::string(start, end);
}
if (String_Quoted* ss = dynamic_cast<String_Quoted*>(s)) {
if(ss->quote_mark()) newstr = quote(newstr);
}
}
// handle any invalid utf8 errors
// other errors will be re-thrown
catch (...) { handle_utf8_error(pstate, backtrace); }
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, newstr);
}
Signature to_upper_case_sig = "to-upper-case($string)";
BUILT_IN(to_upper_case)
{
String_Constant* s = ARG("$string", String_Constant);
std::string str = s->value();
for (size_t i = 0, L = str.length(); i < L; ++i) {
if (Sass::Util::isAscii(str[i])) {
str[i] = std::toupper(str[i]);
}
}
if (String_Quoted* ss = dynamic_cast<String_Quoted*>(s)) {
String_Quoted* cpy = SASS_MEMORY_NEW(ctx.mem, String_Quoted, *ss);
cpy->value(str);
return cpy;
} else {
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, str);
}
}
Signature to_lower_case_sig = "to-lower-case($string)";
BUILT_IN(to_lower_case)
{
String_Constant* s = ARG("$string", String_Constant);
std::string str = s->value();
for (size_t i = 0, L = str.length(); i < L; ++i) {
if (Sass::Util::isAscii(str[i])) {
str[i] = std::tolower(str[i]);
}
}
if (String_Quoted* ss = dynamic_cast<String_Quoted*>(s)) {
String_Quoted* cpy = SASS_MEMORY_NEW(ctx.mem, String_Quoted, *ss);
cpy->value(str);
return cpy;
} else {
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, str);
}
}
///////////////////
// NUMBER FUNCTIONS
///////////////////
Signature percentage_sig = "percentage($number)";
BUILT_IN(percentage)
{
Number* n = ARG("$number", Number);
if (!n->is_unitless()) error("argument $number of `" + std::string(sig) + "` must be unitless", pstate);
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, n->value() * 100, "%");
}
Signature round_sig = "round($number)";
BUILT_IN(round)
{
Number* n = ARG("$number", Number);
Number* r = SASS_MEMORY_NEW(ctx.mem, Number, *n);
r->pstate(pstate);
r->value(Sass::round(r->value(), ctx.c_options.precision));
return r;
}
Signature ceil_sig = "ceil($number)";
BUILT_IN(ceil)
{
Number* n = ARG("$number", Number);
Number* r = SASS_MEMORY_NEW(ctx.mem, Number, *n);
r->pstate(pstate);
r->value(std::ceil(r->value()));
return r;
}
Signature floor_sig = "floor($number)";
BUILT_IN(floor)
{
Number* n = ARG("$number", Number);
Number* r = SASS_MEMORY_NEW(ctx.mem, Number, *n);
r->pstate(pstate);
r->value(std::floor(r->value()));
return r;
}
Signature abs_sig = "abs($number)";
BUILT_IN(abs)
{
Number* n = ARG("$number", Number);
Number* r = SASS_MEMORY_NEW(ctx.mem, Number, *n);
r->pstate(pstate);
r->value(std::abs(r->value()));
return r;
}
Signature min_sig = "min($numbers...)";
BUILT_IN(min)
{
List* arglist = ARG("$numbers", List);
Number* least = 0;
for (size_t i = 0, L = arglist->length(); i < L; ++i) {
Expression* val = arglist->value_at_index(i);
Number* xi = dynamic_cast<Number*>(val);
if (!xi) {
error("\"" + val->to_string(ctx.c_options) + "\" is not a number for `min'", pstate);
}
if (least) {
if (*xi < *least) least = xi;
} else least = xi;
}
return least;
}
Signature max_sig = "max($numbers...)";
BUILT_IN(max)
{
List* arglist = ARG("$numbers", List);
Number* greatest = 0;
for (size_t i = 0, L = arglist->length(); i < L; ++i) {
Expression* val = arglist->value_at_index(i);
Number* xi = dynamic_cast<Number*>(val);
if (!xi) {
error("\"" + val->to_string(ctx.c_options) + "\" is not a number for `max'", pstate);
}
if (greatest) {
if (*greatest < *xi) greatest = xi;
} else greatest = xi;
}
return greatest;
}
Signature random_sig = "random($limit:false)";
BUILT_IN(random)
{
AST_Node* arg = env["$limit"];
Value* v = dynamic_cast<Value*>(arg);
Number* l = dynamic_cast<Number*>(arg);
Boolean* b = dynamic_cast<Boolean*>(arg);
if (l) {
double v = l->value();
if (v < 1) {
stringstream err;
err << "$limit " << v << " must be greater than or equal to 1 for `random`";
error(err.str(), pstate);
}
bool eq_int = std::fabs(trunc(v) - v) < NUMBER_EPSILON;
if (!eq_int) {
stringstream err;
err << "Expected $limit to be an integer but got `" << v << "` for `random`";
error(err.str(), pstate);
}
std::uniform_real_distribution<> distributor(1, v + 1);
uint_fast32_t distributed = static_cast<uint_fast32_t>(distributor(rand));
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, (double)distributed);
}
else if (b) {
std::uniform_real_distribution<> distributor(0, 1);
double distributed = static_cast<double>(distributor(rand));
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, distributed);
} else if (v) {
throw Exception::InvalidArgumentType(pstate, "random", "$limit", "number", v);
} else {
throw Exception::InvalidArgumentType(pstate, "random", "$limit", "number");
}
return 0;
}
/////////////////
// LIST FUNCTIONS
/////////////////
Signature length_sig = "length($list)";
BUILT_IN(length)
{
if (Selector_List* sl = dynamic_cast<Selector_List*>(env["$list"])) {
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, (double)sl->length());
}
Expression* v = ARG("$list", Expression);
if (v->concrete_type() == Expression::MAP) {
Map* map = dynamic_cast<Map*>(env["$list"]);
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, (double)(map ? map->length() : 1));
}
if (v->concrete_type() == Expression::SELECTOR) {
if (Compound_Selector* h = dynamic_cast<Compound_Selector*>(v)) {
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, (double)h->length());
} else if (Selector_List* ls = dynamic_cast<Selector_List*>(v)) {
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, (double)ls->length());
} else {
return SASS_MEMORY_NEW(ctx.mem, Number, pstate, 1);
}
}
List* list = dynamic_cast<List*>(env["$list"]);
return SASS_MEMORY_NEW(ctx.mem, Number,
pstate,
(double)(list ? list->size() : 1));
}
Signature nth_sig = "nth($list, $n)";
BUILT_IN(nth)
{
Number* n = ARG("$n", Number);
Map* m = dynamic_cast<Map*>(env["$list"]);
if (Selector_List* sl = dynamic_cast<Selector_List*>(env["$list"])) {
size_t len = m ? m->length() : sl->length();
bool empty = m ? m->empty() : sl->empty();
if (empty) error("argument `$list` of `" + std::string(sig) + "` must not be empty", pstate);
double index = std::floor(n->value() < 0 ? len + n->value() : n->value() - 1);
if (index < 0 || index > len - 1) error("index out of bounds for `" + std::string(sig) + "`", pstate);
// return (*sl)[static_cast<int>(index)];
Listize listize(ctx.mem);
return (*sl)[static_cast<int>(index)]->perform(&listize);
}
List* l = dynamic_cast<List*>(env["$list"]);
if (n->value() == 0) error("argument `$n` of `" + std::string(sig) + "` must be non-zero", pstate);
// if the argument isn't a list, then wrap it in a singleton list
if (!m && !l) {
l = SASS_MEMORY_NEW(ctx.mem, List, pstate, 1);
*l << ARG("$list", Expression);
}
size_t len = m ? m->length() : l->length();
bool empty = m ? m->empty() : l->empty();
if (empty) error("argument `$list` of `" + std::string(sig) + "` must not be empty", pstate);
double index = std::floor(n->value() < 0 ? len + n->value() : n->value() - 1);
if (index < 0 || index > len - 1) error("index out of bounds for `" + std::string(sig) + "`", pstate);
if (m) {
l = SASS_MEMORY_NEW(ctx.mem, List, pstate, 1);
*l << m->keys()[static_cast<unsigned int>(index)];
*l << m->at(m->keys()[static_cast<unsigned int>(index)]);
return l;
}
else {
return l->value_at_index(static_cast<int>(index));
}
}
Signature set_nth_sig = "set-nth($list, $n, $value)";
BUILT_IN(set_nth)
{
List* l = dynamic_cast<List*>(env["$list"]);
Number* n = ARG("$n", Number);
Expression* v = ARG("$value", Expression);
if (!l) {
l = SASS_MEMORY_NEW(ctx.mem, List, pstate, 1);
*l << ARG("$list", Expression);
}
if (l->empty()) error("argument `$list` of `" + std::string(sig) + "` must not be empty", pstate);
double index = std::floor(n->value() < 0 ? l->length() + n->value() : n->value() - 1);
if (index < 0 || index > l->length() - 1) error("index out of bounds for `" + std::string(sig) + "`", pstate);
List* result = SASS_MEMORY_NEW(ctx.mem, List, pstate, l->length(), l->separator());
for (size_t i = 0, L = l->length(); i < L; ++i) {
*result << ((i == index) ? v : (*l)[i]);
}
return result;
}
Signature index_sig = "index($list, $value)";
BUILT_IN(index)
{
List* l = dynamic_cast<List*>(env["$list"]);
Expression* v = ARG("$value", Expression);
if (!l) {
l = SASS_MEMORY_NEW(ctx.mem, List, pstate, 1);
*l << ARG("$list", Expression);
}
for (size_t i = 0, L = l->length(); i < L; ++i) {
if (Eval::eq(l->value_at_index(i), v)) return SASS_MEMORY_NEW(ctx.mem, Number, pstate, (double)(i+1));
}
return SASS_MEMORY_NEW(ctx.mem, Null, pstate);
}
Signature join_sig = "join($list1, $list2, $separator: auto)";
BUILT_IN(join)
{
List* l1 = dynamic_cast<List*>(env["$list1"]);
List* l2 = dynamic_cast<List*>(env["$list2"]);
String_Constant* sep = ARG("$separator", String_Constant);
enum Sass_Separator sep_val = (l1 ? l1->separator() : SASS_SPACE);
if (!l1) {
l1 = SASS_MEMORY_NEW(ctx.mem, List, pstate, 1);
*l1 << ARG("$list1", Expression);
sep_val = (l2 ? l2->separator() : SASS_SPACE);
}
if (!l2) {
l2 = SASS_MEMORY_NEW(ctx.mem, List, pstate, 1);
*l2 << ARG("$list2", Expression);
}
size_t len = l1->length() + l2->length();
std::string sep_str = unquote(sep->value());
if (sep_str == "space") sep_val = SASS_SPACE;
else if (sep_str == "comma") sep_val = SASS_COMMA;
else if (sep_str != "auto") error("argument `$separator` of `" + std::string(sig) + "` must be `space`, `comma`, or `auto`", pstate);
List* result = SASS_MEMORY_NEW(ctx.mem, List, pstate, len, sep_val);
*result += l1;
*result += l2;
return result;
}
Signature append_sig = "append($list, $val, $separator: auto)";
BUILT_IN(append)
{
List* l = dynamic_cast<List*>(env["$list"]);
Expression* v = ARG("$val", Expression);
if (Selector_List* sl = dynamic_cast<Selector_List*>(env["$list"])) {
Listize listize(ctx.mem);
l = dynamic_cast<List*>(sl->perform(&listize));
}
String_Constant* sep = ARG("$separator", String_Constant);
if (!l) {
l = SASS_MEMORY_NEW(ctx.mem, List, pstate, 1);
*l << ARG("$list", Expression);
}
List* result = SASS_MEMORY_NEW(ctx.mem, List, pstate, l->length() + 1, l->separator());
std::string sep_str(unquote(sep->value()));
if (sep_str == "space") result->separator(SASS_SPACE);
else if (sep_str == "comma") result->separator(SASS_COMMA);
else if (sep_str != "auto") error("argument `$separator` of `" + std::string(sig) + "` must be `space`, `comma`, or `auto`", pstate);
*result += l;
bool is_arglist = l->is_arglist();
result->is_arglist(is_arglist);
if (is_arglist) {
*result << SASS_MEMORY_NEW(ctx.mem, Argument,
v->pstate(),
v,
"",
false,
false);
} else {
*result << v;
}
return result;
}
Signature zip_sig = "zip($lists...)";
BUILT_IN(zip)
{
List* arglist = SASS_MEMORY_NEW(ctx.mem, List, *ARG("$lists", List));
size_t shortest = 0;
for (size_t i = 0, L = arglist->length(); i < L; ++i) {
List* ith = dynamic_cast<List*>(arglist->value_at_index(i));
if (!ith) {
ith = SASS_MEMORY_NEW(ctx.mem, List, pstate, 1);
*ith << arglist->value_at_index(i);
if (arglist->is_arglist()) {
((Argument*)(*arglist)[i])->value(ith);
} else {
(*arglist)[i] = ith;
}
}
shortest = (i ? std::min(shortest, ith->length()) : ith->length());
}
List* zippers = SASS_MEMORY_NEW(ctx.mem, List, pstate, shortest, SASS_COMMA);
size_t L = arglist->length();
for (size_t i = 0; i < shortest; ++i) {
List* zipper = SASS_MEMORY_NEW(ctx.mem, List, pstate, L);
for (size_t j = 0; j < L; ++j) {
*zipper << (*static_cast<List*>(arglist->value_at_index(j)))[i];
}
*zippers << zipper;
}
return zippers;
}
Signature list_separator_sig = "list_separator($list)";
BUILT_IN(list_separator)
{
List* l = dynamic_cast<List*>(env["$list"]);
if (!l) {
l = SASS_MEMORY_NEW(ctx.mem, List, pstate, 1);
*l << ARG("$list", Expression);
}
return SASS_MEMORY_NEW(ctx.mem, String_Quoted,
pstate,
l->separator() == SASS_COMMA ? "comma" : "space");
}
/////////////////
// MAP FUNCTIONS
/////////////////
Signature map_get_sig = "map-get($map, $key)";
BUILT_IN(map_get)
{
Map* m = ARGM("$map", Map, ctx);
Expression* v = ARG("$key", Expression);
try {
return m->at(v);
} catch (const std::out_of_range&) {
return SASS_MEMORY_NEW(ctx.mem, Null, pstate);
}
catch (...) { throw; }
}
Signature map_has_key_sig = "map-has-key($map, $key)";
BUILT_IN(map_has_key)
{
Map* m = ARGM("$map", Map, ctx);
Expression* v = ARG("$key", Expression);
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, m->has(v));
}
Signature map_keys_sig = "map-keys($map)";
BUILT_IN(map_keys)
{
Map* m = ARGM("$map", Map, ctx);
List* result = SASS_MEMORY_NEW(ctx.mem, List, pstate, m->length(), SASS_COMMA);
for ( auto key : m->keys()) {
*result << key;
}
return result;
}
Signature map_values_sig = "map-values($map)";
BUILT_IN(map_values)
{
Map* m = ARGM("$map", Map, ctx);
List* result = SASS_MEMORY_NEW(ctx.mem, List, pstate, m->length(), SASS_COMMA);
for ( auto key : m->keys()) {
*result << m->at(key);
}
return result;
}
Signature map_merge_sig = "map-merge($map1, $map2)";
BUILT_IN(map_merge)
{
Map* m1 = ARGM("$map1", Map, ctx);
Map* m2 = ARGM("$map2", Map, ctx);
size_t len = m1->length() + m2->length();
Map* result = SASS_MEMORY_NEW(ctx.mem, Map, pstate, len);
*result += m1;
*result += m2;
return result;
}
Signature map_remove_sig = "map-remove($map, $keys...)";
BUILT_IN(map_remove)
{
bool remove;
Map* m = ARGM("$map", Map, ctx);
List* arglist = ARG("$keys", List);
Map* result = SASS_MEMORY_NEW(ctx.mem, Map, pstate, 1);
for (auto key : m->keys()) {
remove = false;
for (size_t j = 0, K = arglist->length(); j < K && !remove; ++j) {
remove = Eval::eq(key, arglist->value_at_index(j));
}
if (!remove) *result << std::make_pair(key, m->at(key));
}
return result;
}
Signature keywords_sig = "keywords($args)";
BUILT_IN(keywords)
{
List* arglist = SASS_MEMORY_NEW(ctx.mem, List, *ARG("$args", List));
Map* result = SASS_MEMORY_NEW(ctx.mem, Map, pstate, 1);
for (size_t i = arglist->size(), L = arglist->length(); i < L; ++i) {
std::string name = std::string(((Argument*)(*arglist)[i])->name());
name = name.erase(0, 1); // sanitize name (remove dollar sign)
*result << std::make_pair(SASS_MEMORY_NEW(ctx.mem, String_Quoted,
pstate, name),
((Argument*)(*arglist)[i])->value());
}
return result;
}
//////////////////////////
// INTROSPECTION FUNCTIONS
//////////////////////////
Signature type_of_sig = "type-of($value)";
BUILT_IN(type_of)
{
Expression* v = ARG("$value", Expression);
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, v->type());
}
Signature unit_sig = "unit($number)";
BUILT_IN(unit)
{ return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, quote(ARG("$number", Number)->unit(), '"')); }
Signature unitless_sig = "unitless($number)";
BUILT_IN(unitless)
{ return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, ARG("$number", Number)->is_unitless()); }
Signature comparable_sig = "comparable($number-1, $number-2)";
BUILT_IN(comparable)
{
Number* n1 = ARG("$number-1", Number);
Number* n2 = ARG("$number-2", Number);
if (n1->is_unitless() || n2->is_unitless()) {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, true);
}
Number tmp_n2(*n2);
tmp_n2.normalize(n1->find_convertible_unit());
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, n1->unit() == tmp_n2.unit());
}
Signature variable_exists_sig = "variable-exists($name)";
BUILT_IN(variable_exists)
{
std::string s = Util::normalize_underscores(unquote(ARG("$name", String_Constant)->value()));
if(d_env.has("$"+s)) {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, true);
}
else {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, false);
}
}
Signature global_variable_exists_sig = "global-variable-exists($name)";
BUILT_IN(global_variable_exists)
{
std::string s = Util::normalize_underscores(unquote(ARG("$name", String_Constant)->value()));
if(d_env.has_global("$"+s)) {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, true);
}
else {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, false);
}
}
Signature function_exists_sig = "function-exists($name)";
BUILT_IN(function_exists)
{
std::string s = Util::normalize_underscores(unquote(ARG("$name", String_Constant)->value()));
if(d_env.has_global(s+"[f]")) {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, true);
}
else {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, false);
}
}
Signature mixin_exists_sig = "mixin-exists($name)";
BUILT_IN(mixin_exists)
{
std::string s = Util::normalize_underscores(unquote(ARG("$name", String_Constant)->value()));
if(d_env.has_global(s+"[m]")) {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, true);
}
else {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, false);
}
}
Signature feature_exists_sig = "feature-exists($name)";
BUILT_IN(feature_exists)
{
std::string s = unquote(ARG("$name", String_Constant)->value());
if(features.find(s) == features.end()) {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, false);
}
else {
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, true);
}
}
Signature call_sig = "call($name, $args...)";
BUILT_IN(call)
{
std::string name = Util::normalize_underscores(unquote(ARG("$name", String_Constant)->value()));
List* arglist = SASS_MEMORY_NEW(ctx.mem, List, *ARG("$args", List));
Arguments* args = SASS_MEMORY_NEW(ctx.mem, Arguments, pstate);
// std::string full_name(name + "[f]");
// Definition* def = d_env.has(full_name) ? static_cast<Definition*>((d_env)[full_name]) : 0;
// Parameters* params = def ? def->parameters() : 0;
// size_t param_size = params ? params->length() : 0;
for (size_t i = 0, L = arglist->length(); i < L; ++i) {
Expression* expr = arglist->value_at_index(i);
// if (params && params->has_rest_parameter()) {
// Parameter* p = param_size > i ? (*params)[i] : 0;
// List* list = dynamic_cast<List*>(expr);
// if (list && p && !p->is_rest_parameter()) expr = (*list)[0];
// }
if (arglist->is_arglist()) {
Argument* arg = dynamic_cast<Argument*>((*arglist)[i]);
*args << SASS_MEMORY_NEW(ctx.mem, Argument,
pstate,
expr,
arg ? arg->name() : "",
arg ? arg->is_rest_argument() : false,
arg ? arg->is_keyword_argument() : false);
} else {
*args << SASS_MEMORY_NEW(ctx.mem, Argument, pstate, expr);
}
}
Function_Call* func = SASS_MEMORY_NEW(ctx.mem, Function_Call, pstate, name, args);
Expand expand(ctx, &d_env, backtrace);
return func->perform(&expand.eval);
}
////////////////////
// BOOLEAN FUNCTIONS
////////////////////
Signature not_sig = "not($value)";
BUILT_IN(sass_not)
{ return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, ARG("$value", Expression)->is_false()); }
Signature if_sig = "if($condition, $if-true, $if-false)";
// BUILT_IN(sass_if)
// { return ARG("$condition", Expression)->is_false() ? ARG("$if-false", Expression) : ARG("$if-true", Expression); }
BUILT_IN(sass_if)
{
Expand expand(ctx, &d_env, backtrace);
bool is_true = !ARG("$condition", Expression)->perform(&expand.eval)->is_false();
if (is_true) {
return ARG("$if-true", Expression)->perform(&expand.eval);
}
else {
return ARG("$if-false", Expression)->perform(&expand.eval);
}
}
////////////////
// URL FUNCTIONS
////////////////
Signature image_url_sig = "image-url($path, $only-path: false, $cache-buster: false)";
BUILT_IN(image_url)
{
error("`image_url` has been removed from libsass because it's not part of the Sass spec", pstate);
return 0; // suppress warning, error will exit anyway
}
//////////////////////////
// MISCELLANEOUS FUNCTIONS
//////////////////////////
// value.check_deprecated_interp if value.is_a?(Sass::Script::Value::String)
// unquoted_string(value.to_sass)
Signature inspect_sig = "inspect($value)";
BUILT_IN(inspect)
{
Expression* v = ARG("$value", Expression);
if (v->concrete_type() == Expression::NULL_VAL) {
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, "null");
} else if (v->concrete_type() == Expression::BOOLEAN && *v == 0) {
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, "false");
} else if (v->concrete_type() == Expression::STRING) {
return v;
} else {
// ToDo: fix to_sass for nested parentheses
Sass_Output_Style old_style;
old_style = ctx.c_options.output_style;
ctx.c_options.output_style = TO_SASS;
Emitter emitter(ctx.c_options);
Inspect i(emitter);
i.in_declaration = false;
v->perform(&i);
ctx.c_options.output_style = old_style;
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, i.get_buffer());
}
// return v;
}
Signature selector_nest_sig = "selector-nest($selectors...)";
BUILT_IN(selector_nest)
{
List* arglist = ARG("$selectors", List);
// Not enough parameters
if( arglist->length() == 0 )
error("$selectors: At least one selector must be passed", pstate);
// Parse args into vector of selectors
std::vector<Selector_List*> parsedSelectors;
for (size_t i = 0, L = arglist->length(); i < L; ++i) {
Expression* exp = dynamic_cast<Expression*>(arglist->value_at_index(i));
if (exp->concrete_type() == Expression::NULL_VAL) {
std::stringstream msg;
msg << "$selectors: null is not a valid selector: it must be a string,\n";
msg << "a list of strings, or a list of lists of strings for 'selector-nest'";
error(msg.str(), pstate);
}
if (String_Constant* str =dynamic_cast<String_Constant*>(exp)) {
str->quote_mark(0);
}
std::string exp_src = exp->to_string(ctx.c_options) + "{";
Selector_List* sel = Parser::parse_selector(exp_src.c_str(), ctx);
parsedSelectors.push_back(sel);
}
// Nothing to do
if( parsedSelectors.empty() ) {
return SASS_MEMORY_NEW(ctx.mem, Null, pstate);
}
// Set the first element as the `result`, keep appending to as we go down the parsedSelector vector.
std::vector<Selector_List*>::iterator itr = parsedSelectors.begin();
Selector_List* result = *itr;
++itr;
for(;itr != parsedSelectors.end(); ++itr) {
Selector_List* child = *itr;
std::vector<Complex_Selector*> exploded;
Selector_List* rv = child->parentize(result, ctx);
for (size_t m = 0, mLen = rv->length(); m < mLen; ++m) {
exploded.push_back((*rv)[m]);
}
result->elements(exploded);
}
Listize listize(ctx.mem);
return result->perform(&listize);
}
Signature selector_append_sig = "selector-append($selectors...)";
BUILT_IN(selector_append)
{
List* arglist = ARG("$selectors", List);
// Not enough parameters
if( arglist->length() == 0 )
error("$selectors: At least one selector must be passed", pstate);
// Parse args into vector of selectors
std::vector<Selector_List*> parsedSelectors;
for (size_t i = 0, L = arglist->length(); i < L; ++i) {
Expression* exp = dynamic_cast<Expression*>(arglist->value_at_index(i));
if (exp->concrete_type() == Expression::NULL_VAL) {
std::stringstream msg;
msg << "$selectors: null is not a valid selector: it must be a string,\n";
msg << "a list of strings, or a list of lists of strings for 'selector-append'";
error(msg.str(), pstate);
}
if (String_Constant* str =dynamic_cast<String_Constant*>(exp)) {
str->quote_mark(0);
}
std::string exp_src = exp->to_string() + "{";
Selector_List* sel = Parser::parse_selector(exp_src.c_str(), ctx);
parsedSelectors.push_back(sel);
}
// Nothing to do
if( parsedSelectors.empty() ) {
return SASS_MEMORY_NEW(ctx.mem, Null, pstate);
}
// Set the first element as the `result`, keep appending to as we go down the parsedSelector vector.
std::vector<Selector_List*>::iterator itr = parsedSelectors.begin();
Selector_List* result = *itr;
++itr;
for(;itr != parsedSelectors.end(); ++itr) {
Selector_List* child = *itr;
std::vector<Complex_Selector*> newElements;
// For every COMPLEX_SELECTOR in `result`
// For every COMPLEX_SELECTOR in `child`
// let parentSeqClone equal a copy of result->elements[i]
// let childSeq equal child->elements[j]
// Append all of childSeq head elements into parentSeqClone
// Set the innermost tail of parentSeqClone, to childSeq's tail
// Replace result->elements with newElements
for (size_t i = 0, resultLen = result->length(); i < resultLen; ++i) {
for (size_t j = 0, childLen = child->length(); j < childLen; ++j) {
Complex_Selector* parentSeqClone = (*result)[i]->cloneFully(ctx);
Complex_Selector* childSeq = (*child)[j];
Complex_Selector* base = childSeq->tail();
// Must be a simple sequence
if( childSeq->combinator() != Complex_Selector::Combinator::ANCESTOR_OF ) {
std::string msg("Can't append `");
msg += childSeq->to_string();
msg += "` to `";
msg += parentSeqClone->to_string();
msg += "`";
error(msg, pstate, backtrace);
}
// Cannot be a Universal selector
Type_Selector* pType = dynamic_cast<Type_Selector*>(childSeq->head()->first());
if(pType && pType->name() == "*") {
std::string msg("Can't append `");
msg += childSeq->to_string();
msg += "` to `";
msg += parentSeqClone->to_string();
msg += "`";
error(msg, pstate, backtrace);
}
// TODO: Add check for namespace stuff
// append any selectors in childSeq's head
*(parentSeqClone->innermost()->head()) += (base->head());
// Set parentSeqClone new tail
parentSeqClone->innermost()->tail( base->tail() );
newElements.push_back(parentSeqClone);
}
}
result->elements(newElements);
}
Listize listize(ctx.mem);
return result->perform(&listize);
}
Signature selector_unify_sig = "selector-unify($selector1, $selector2)";
BUILT_IN(selector_unify)
{
Selector_List* selector1 = ARGSEL("$selector1", Selector_List, p_contextualize);
Selector_List* selector2 = ARGSEL("$selector2", Selector_List, p_contextualize);
Selector_List* result = selector1->unify_with(selector2, ctx);
Listize listize(ctx.mem);
return result->perform(&listize);
}
Signature simple_selectors_sig = "simple-selectors($selector)";
BUILT_IN(simple_selectors)
{
Compound_Selector* sel = ARGSEL("$selector", Compound_Selector, p_contextualize);
List* l = SASS_MEMORY_NEW(ctx.mem, List, sel->pstate(), sel->length(), SASS_COMMA);
for (size_t i = 0, L = sel->length(); i < L; ++i) {
Simple_Selector* ss = (*sel)[i];
std::string ss_string = ss->to_string() ;
*l << SASS_MEMORY_NEW(ctx.mem, String_Quoted, ss->pstate(), ss_string);
}
return l;
}
Signature selector_extend_sig = "selector-extend($selector, $extendee, $extender)";
BUILT_IN(selector_extend)
{
Selector_List* selector = ARGSEL("$selector", Selector_List, p_contextualize);
Selector_List* extendee = ARGSEL("$extendee", Selector_List, p_contextualize);
Selector_List* extender = ARGSEL("$extender", Selector_List, p_contextualize);
ExtensionSubsetMap subset_map;
extender->populate_extends(extendee, ctx, subset_map);
Selector_List* result = Extend::extendSelectorList(selector, ctx, subset_map, false);
Listize listize(ctx.mem);
return result->perform(&listize);
}
Signature selector_replace_sig = "selector-replace($selector, $original, $replacement)";
BUILT_IN(selector_replace)
{
Selector_List* selector = ARGSEL("$selector", Selector_List, p_contextualize);
Selector_List* original = ARGSEL("$original", Selector_List, p_contextualize);
Selector_List* replacement = ARGSEL("$replacement", Selector_List, p_contextualize);
ExtensionSubsetMap subset_map;
replacement->populate_extends(original, ctx, subset_map);
Selector_List* result = Extend::extendSelectorList(selector, ctx, subset_map, true);
Listize listize(ctx.mem);
return result->perform(&listize);
}
Signature selector_parse_sig = "selector-parse($selector)";
BUILT_IN(selector_parse)
{
Selector_List* sel = ARGSEL("$selector", Selector_List, p_contextualize);
Listize listize(ctx.mem);
return sel->perform(&listize);
}
Signature is_superselector_sig = "is-superselector($super, $sub)";
BUILT_IN(is_superselector)
{
Selector_List* sel_sup = ARGSEL("$super", Selector_List, p_contextualize);
Selector_List* sel_sub = ARGSEL("$sub", Selector_List, p_contextualize);
bool result = sel_sup->is_superselector_of(sel_sub);
return SASS_MEMORY_NEW(ctx.mem, Boolean, pstate, result);
}
Signature unique_id_sig = "unique-id()";
BUILT_IN(unique_id)
{
std::stringstream ss;
std::uniform_real_distribution<> distributor(0, 4294967296); // 16^8
uint_fast32_t distributed = static_cast<uint_fast32_t>(distributor(rand));
ss << "u" << std::setfill('0') << std::setw(8) << std::hex << distributed;
return SASS_MEMORY_NEW(ctx.mem, String_Quoted, pstate, ss.str());
}
}
}
| mit |
sandy98/pgnparser | tests/js/node_modules/ffi/deps/libffi/testsuite/libffi.call/cls_7_1_byte.c | 469 | 3406 | /* Area: ffi_call, closure_call
Purpose: Check structure passing with different structure size.
Depending on the ABI. Check overlapping.
Limitations: none.
PR: none.
Originator: <andreast@gcc.gnu.org> 20050708 */
/* { dg-do run } */
#include "ffitest.h"
typedef struct cls_struct_7byte {
unsigned char a;
unsigned char b;
unsigned char c;
unsigned char d;
unsigned char e;
unsigned char f;
unsigned char g;
} cls_struct_7byte;
cls_struct_7byte cls_struct_7byte_fn(struct cls_struct_7byte a1,
struct cls_struct_7byte a2)
{
struct cls_struct_7byte result;
result.a = a1.a + a2.a;
result.b = a1.b + a2.b;
result.c = a1.c + a2.c;
result.d = a1.d + a2.d;
result.e = a1.e + a2.e;
result.f = a1.f + a2.f;
result.g = a1.g + a2.g;
printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d %d %d %d %d %d %d\n",
a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g,
a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, a2.g,
result.a, result.b, result.c, result.d, result.e, result.f, result.g);
return result;
}
static void
cls_struct_7byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
void* userdata __UNUSED__)
{
struct cls_struct_7byte a1, a2;
a1 = *(struct cls_struct_7byte*)(args[0]);
a2 = *(struct cls_struct_7byte*)(args[1]);
*(cls_struct_7byte*)resp = cls_struct_7byte_fn(a1, a2);
}
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[8];
ffi_type cls_struct_type;
ffi_type* dbl_arg_types[5];
struct cls_struct_7byte g_dbl = { 127, 120, 1, 3, 4, 5, 6 };
struct cls_struct_7byte f_dbl = { 12, 128, 9, 3, 4, 5, 6 };
struct cls_struct_7byte res_dbl = { 0, 0, 0, 0, 0, 0, 0 };
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_fields[0] = &ffi_type_uchar;
cls_struct_fields[1] = &ffi_type_uchar;
cls_struct_fields[2] = &ffi_type_uchar;
cls_struct_fields[3] = &ffi_type_uchar;
cls_struct_fields[4] = &ffi_type_uchar;
cls_struct_fields[5] = &ffi_type_uchar;
cls_struct_fields[6] = &ffi_type_uchar;
cls_struct_fields[7] = NULL;
dbl_arg_types[0] = &cls_struct_type;
dbl_arg_types[1] = &cls_struct_type;
dbl_arg_types[2] = NULL;
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
dbl_arg_types) == FFI_OK);
args_dbl[0] = &g_dbl;
args_dbl[1] = &f_dbl;
args_dbl[2] = NULL;
ffi_call(&cif, FFI_FN(cls_struct_7byte_fn), &res_dbl, args_dbl);
/* { dg-output "127 120 1 3 4 5 6 12 128 9 3 4 5 6: 139 248 10 6 8 10 12" } */
printf("res: %d %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
/* { dg-output "\nres: 139 248 10 6 8 10 12" } */
res_dbl.a = 0;
res_dbl.b = 0;
res_dbl.c = 0;
res_dbl.d = 0;
res_dbl.e = 0;
res_dbl.f = 0;
res_dbl.g = 0;
CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_7byte_gn, NULL, code) == FFI_OK);
res_dbl = ((cls_struct_7byte(*)(cls_struct_7byte, cls_struct_7byte))(code))(g_dbl, f_dbl);
/* { dg-output "\n127 120 1 3 4 5 6 12 128 9 3 4 5 6: 139 248 10 6 8 10 12" } */
printf("res: %d %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
/* { dg-output "\nres: 139 248 10 6 8 10 12" } */
exit(0);
}
| mit |
sigma-random/cert-tool | cert_tool/openssl-1.0.1i/crypto/des/destest.c | 982 | 29528 | /* crypto/des/destest.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 <stdlib.h>
#include <openssl/e_os2.h>
#if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16) || defined(OPENSSL_SYS_WINDOWS)
#ifndef OPENSSL_SYS_MSDOS
#define OPENSSL_SYS_MSDOS
#endif
#endif
#ifndef OPENSSL_SYS_MSDOS
#if !defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VMS_DECC)
#include OPENSSL_UNISTD
#endif
#else
#include <io.h>
#endif
#include <string.h>
#ifdef OPENSSL_NO_DES
int main(int argc, char *argv[])
{
printf("No DES support\n");
return(0);
}
#else
#include <openssl/des.h>
#define crypt(c,s) (DES_crypt((c),(s)))
/* tisk tisk - the test keys don't all have odd parity :-( */
/* test data */
#define NUM_TESTS 34
static unsigned char key_data[NUM_TESTS][8]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF},
{0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10},
{0x7C,0xA1,0x10,0x45,0x4A,0x1A,0x6E,0x57},
{0x01,0x31,0xD9,0x61,0x9D,0xC1,0x37,0x6E},
{0x07,0xA1,0x13,0x3E,0x4A,0x0B,0x26,0x86},
{0x38,0x49,0x67,0x4C,0x26,0x02,0x31,0x9E},
{0x04,0xB9,0x15,0xBA,0x43,0xFE,0xB5,0xB6},
{0x01,0x13,0xB9,0x70,0xFD,0x34,0xF2,0xCE},
{0x01,0x70,0xF1,0x75,0x46,0x8F,0xB5,0xE6},
{0x43,0x29,0x7F,0xAD,0x38,0xE3,0x73,0xFE},
{0x07,0xA7,0x13,0x70,0x45,0xDA,0x2A,0x16},
{0x04,0x68,0x91,0x04,0xC2,0xFD,0x3B,0x2F},
{0x37,0xD0,0x6B,0xB5,0x16,0xCB,0x75,0x46},
{0x1F,0x08,0x26,0x0D,0x1A,0xC2,0x46,0x5E},
{0x58,0x40,0x23,0x64,0x1A,0xBA,0x61,0x76},
{0x02,0x58,0x16,0x16,0x46,0x29,0xB0,0x07},
{0x49,0x79,0x3E,0xBC,0x79,0xB3,0x25,0x8F},
{0x4F,0xB0,0x5E,0x15,0x15,0xAB,0x73,0xA7},
{0x49,0xE9,0x5D,0x6D,0x4C,0xA2,0x29,0xBF},
{0x01,0x83,0x10,0xDC,0x40,0x9B,0x26,0xD6},
{0x1C,0x58,0x7F,0x1C,0x13,0x92,0x4F,0xEF},
{0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01},
{0x1F,0x1F,0x1F,0x1F,0x0E,0x0E,0x0E,0x0E},
{0xE0,0xFE,0xE0,0xFE,0xF1,0xFE,0xF1,0xFE},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10}};
static unsigned char plain_data[NUM_TESTS][8]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF},
{0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x01},
{0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11},
{0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0x01,0xA1,0xD6,0xD0,0x39,0x77,0x67,0x42},
{0x5C,0xD5,0x4C,0xA8,0x3D,0xEF,0x57,0xDA},
{0x02,0x48,0xD4,0x38,0x06,0xF6,0x71,0x72},
{0x51,0x45,0x4B,0x58,0x2D,0xDF,0x44,0x0A},
{0x42,0xFD,0x44,0x30,0x59,0x57,0x7F,0xA2},
{0x05,0x9B,0x5E,0x08,0x51,0xCF,0x14,0x3A},
{0x07,0x56,0xD8,0xE0,0x77,0x47,0x61,0xD2},
{0x76,0x25,0x14,0xB8,0x29,0xBF,0x48,0x6A},
{0x3B,0xDD,0x11,0x90,0x49,0x37,0x28,0x02},
{0x26,0x95,0x5F,0x68,0x35,0xAF,0x60,0x9A},
{0x16,0x4D,0x5E,0x40,0x4F,0x27,0x52,0x32},
{0x6B,0x05,0x6E,0x18,0x75,0x9F,0x5C,0xCA},
{0x00,0x4B,0xD6,0xEF,0x09,0x17,0x60,0x62},
{0x48,0x0D,0x39,0x00,0x6E,0xE7,0x62,0xF2},
{0x43,0x75,0x40,0xC8,0x69,0x8F,0x3C,0xFA},
{0x07,0x2D,0x43,0xA0,0x77,0x07,0x52,0x92},
{0x02,0xFE,0x55,0x77,0x81,0x17,0xF1,0x2A},
{0x1D,0x9D,0x5C,0x50,0x18,0xF7,0x28,0xC2},
{0x30,0x55,0x32,0x28,0x6D,0x6F,0x29,0x5A},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}};
static unsigned char cipher_data[NUM_TESTS][8]={
{0x8C,0xA6,0x4D,0xE9,0xC1,0xB1,0x23,0xA7},
{0x73,0x59,0xB2,0x16,0x3E,0x4E,0xDC,0x58},
{0x95,0x8E,0x6E,0x62,0x7A,0x05,0x55,0x7B},
{0xF4,0x03,0x79,0xAB,0x9E,0x0E,0xC5,0x33},
{0x17,0x66,0x8D,0xFC,0x72,0x92,0x53,0x2D},
{0x8A,0x5A,0xE1,0xF8,0x1A,0xB8,0xF2,0xDD},
{0x8C,0xA6,0x4D,0xE9,0xC1,0xB1,0x23,0xA7},
{0xED,0x39,0xD9,0x50,0xFA,0x74,0xBC,0xC4},
{0x69,0x0F,0x5B,0x0D,0x9A,0x26,0x93,0x9B},
{0x7A,0x38,0x9D,0x10,0x35,0x4B,0xD2,0x71},
{0x86,0x8E,0xBB,0x51,0xCA,0xB4,0x59,0x9A},
{0x71,0x78,0x87,0x6E,0x01,0xF1,0x9B,0x2A},
{0xAF,0x37,0xFB,0x42,0x1F,0x8C,0x40,0x95},
{0x86,0xA5,0x60,0xF1,0x0E,0xC6,0xD8,0x5B},
{0x0C,0xD3,0xDA,0x02,0x00,0x21,0xDC,0x09},
{0xEA,0x67,0x6B,0x2C,0xB7,0xDB,0x2B,0x7A},
{0xDF,0xD6,0x4A,0x81,0x5C,0xAF,0x1A,0x0F},
{0x5C,0x51,0x3C,0x9C,0x48,0x86,0xC0,0x88},
{0x0A,0x2A,0xEE,0xAE,0x3F,0xF4,0xAB,0x77},
{0xEF,0x1B,0xF0,0x3E,0x5D,0xFA,0x57,0x5A},
{0x88,0xBF,0x0D,0xB6,0xD7,0x0D,0xEE,0x56},
{0xA1,0xF9,0x91,0x55,0x41,0x02,0x0B,0x56},
{0x6F,0xBF,0x1C,0xAF,0xCF,0xFD,0x05,0x56},
{0x2F,0x22,0xE4,0x9B,0xAB,0x7C,0xA1,0xAC},
{0x5A,0x6B,0x61,0x2C,0xC2,0x6C,0xCE,0x4A},
{0x5F,0x4C,0x03,0x8E,0xD1,0x2B,0x2E,0x41},
{0x63,0xFA,0xC0,0xD0,0x34,0xD9,0xF7,0x93},
{0x61,0x7B,0x3A,0x0C,0xE8,0xF0,0x71,0x00},
{0xDB,0x95,0x86,0x05,0xF8,0xC8,0xC6,0x06},
{0xED,0xBF,0xD1,0xC6,0x6C,0x29,0xCC,0xC7},
{0x35,0x55,0x50,0xB2,0x15,0x0E,0x24,0x51},
{0xCA,0xAA,0xAF,0x4D,0xEA,0xF1,0xDB,0xAE},
{0xD5,0xD4,0x4F,0xF7,0x20,0x68,0x3D,0x0D},
{0x2A,0x2B,0xB0,0x08,0xDF,0x97,0xC2,0xF2}};
static unsigned char cipher_ecb2[NUM_TESTS-1][8]={
{0x92,0x95,0xB5,0x9B,0xB3,0x84,0x73,0x6E},
{0x19,0x9E,0x9D,0x6D,0xF3,0x9A,0xA8,0x16},
{0x2A,0x4B,0x4D,0x24,0x52,0x43,0x84,0x27},
{0x35,0x84,0x3C,0x01,0x9D,0x18,0xC5,0xB6},
{0x4A,0x5B,0x2F,0x42,0xAA,0x77,0x19,0x25},
{0xA0,0x6B,0xA9,0xB8,0xCA,0x5B,0x17,0x8A},
{0xAB,0x9D,0xB7,0xFB,0xED,0x95,0xF2,0x74},
{0x3D,0x25,0x6C,0x23,0xA7,0x25,0x2F,0xD6},
{0xB7,0x6F,0xAB,0x4F,0xBD,0xBD,0xB7,0x67},
{0x8F,0x68,0x27,0xD6,0x9C,0xF4,0x1A,0x10},
{0x82,0x57,0xA1,0xD6,0x50,0x5E,0x81,0x85},
{0xA2,0x0F,0x0A,0xCD,0x80,0x89,0x7D,0xFA},
{0xCD,0x2A,0x53,0x3A,0xDB,0x0D,0x7E,0xF3},
{0xD2,0xC2,0xBE,0x27,0xE8,0x1B,0x68,0xE3},
{0xE9,0x24,0xCF,0x4F,0x89,0x3C,0x5B,0x0A},
{0xA7,0x18,0xC3,0x9F,0xFA,0x9F,0xD7,0x69},
{0x77,0x2C,0x79,0xB1,0xD2,0x31,0x7E,0xB1},
{0x49,0xAB,0x92,0x7F,0xD0,0x22,0x00,0xB7},
{0xCE,0x1C,0x6C,0x7D,0x85,0xE3,0x4A,0x6F},
{0xBE,0x91,0xD6,0xE1,0x27,0xB2,0xE9,0x87},
{0x70,0x28,0xAE,0x8F,0xD1,0xF5,0x74,0x1A},
{0xAA,0x37,0x80,0xBB,0xF3,0x22,0x1D,0xDE},
{0xA6,0xC4,0xD2,0x5E,0x28,0x93,0xAC,0xB3},
{0x22,0x07,0x81,0x5A,0xE4,0xB7,0x1A,0xAD},
{0xDC,0xCE,0x05,0xE7,0x07,0xBD,0xF5,0x84},
{0x26,0x1D,0x39,0x2C,0xB3,0xBA,0xA5,0x85},
{0xB4,0xF7,0x0F,0x72,0xFB,0x04,0xF0,0xDC},
{0x95,0xBA,0xA9,0x4E,0x87,0x36,0xF2,0x89},
{0xD4,0x07,0x3A,0xF1,0x5A,0x17,0x82,0x0E},
{0xEF,0x6F,0xAF,0xA7,0x66,0x1A,0x7E,0x89},
{0xC1,0x97,0xF5,0x58,0x74,0x8A,0x20,0xE7},
{0x43,0x34,0xCF,0xDA,0x22,0xC4,0x86,0xC8},
{0x08,0xD7,0xB4,0xFB,0x62,0x9D,0x08,0x85}};
static unsigned char cbc_key [8]={0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};
static unsigned char cbc2_key[8]={0xf1,0xe0,0xd3,0xc2,0xb5,0xa4,0x97,0x86};
static unsigned char cbc3_key[8]={0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
static unsigned char cbc_iv [8]={0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
/* Changed the following text constant to binary so it will work on ebcdic
* machines :-) */
/* static char cbc_data[40]="7654321 Now is the time for \0001"; */
static unsigned char cbc_data[40]={
0x37,0x36,0x35,0x34,0x33,0x32,0x31,0x20,
0x4E,0x6F,0x77,0x20,0x69,0x73,0x20,0x74,
0x68,0x65,0x20,0x74,0x69,0x6D,0x65,0x20,
0x66,0x6F,0x72,0x20,0x00,0x31,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
static unsigned char cbc_ok[32]={
0xcc,0xd1,0x73,0xff,0xab,0x20,0x39,0xf4,
0xac,0xd8,0xae,0xfd,0xdf,0xd8,0xa1,0xeb,
0x46,0x8e,0x91,0x15,0x78,0x88,0xba,0x68,
0x1d,0x26,0x93,0x97,0xf7,0xfe,0x62,0xb4};
#ifdef SCREW_THE_PARITY
#error "SCREW_THE_PARITY is not ment to be defined."
#error "Original vectors are preserved for reference only."
static unsigned char cbc2_key[8]={0xf0,0xe1,0xd2,0xc3,0xb4,0xa5,0x96,0x87};
static unsigned char xcbc_ok[32]={
0x86,0x74,0x81,0x0D,0x61,0xA4,0xA5,0x48,
0xB9,0x93,0x03,0xE1,0xB8,0xBB,0xBD,0xBD,
0x64,0x30,0x0B,0xB9,0x06,0x65,0x81,0x76,
0x04,0x1D,0x77,0x62,0x17,0xCA,0x2B,0xD2,
};
#else
static unsigned char xcbc_ok[32]={
0x84,0x6B,0x29,0x14,0x85,0x1E,0x9A,0x29,
0x54,0x73,0x2F,0x8A,0xA0,0xA6,0x11,0xC1,
0x15,0xCD,0xC2,0xD7,0x95,0x1B,0x10,0x53,
0xA6,0x3C,0x5E,0x03,0xB2,0x1A,0xA3,0xC4,
};
#endif
static unsigned char cbc3_ok[32]={
0x3F,0xE3,0x01,0xC9,0x62,0xAC,0x01,0xD0,
0x22,0x13,0x76,0x3C,0x1C,0xBD,0x4C,0xDC,
0x79,0x96,0x57,0xC0,0x64,0xEC,0xF5,0xD4,
0x1C,0x67,0x38,0x12,0xCF,0xDE,0x96,0x75};
static unsigned char pcbc_ok[32]={
0xcc,0xd1,0x73,0xff,0xab,0x20,0x39,0xf4,
0x6d,0xec,0xb4,0x70,0xa0,0xe5,0x6b,0x15,
0xae,0xa6,0xbf,0x61,0xed,0x7d,0x9c,0x9f,
0xf7,0x17,0x46,0x3b,0x8a,0xb3,0xcc,0x88};
static unsigned char cfb_key[8]={0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};
static unsigned char cfb_iv[8]={0x12,0x34,0x56,0x78,0x90,0xab,0xcd,0xef};
static unsigned char cfb_buf1[40],cfb_buf2[40],cfb_tmp[8];
static unsigned char plain[24]=
{
0x4e,0x6f,0x77,0x20,0x69,0x73,
0x20,0x74,0x68,0x65,0x20,0x74,
0x69,0x6d,0x65,0x20,0x66,0x6f,
0x72,0x20,0x61,0x6c,0x6c,0x20
};
static unsigned char cfb_cipher8[24]= {
0xf3,0x1f,0xda,0x07,0x01,0x14, 0x62,0xee,0x18,0x7f,0x43,0xd8,
0x0a,0x7c,0xd9,0xb5,0xb0,0xd2, 0x90,0xda,0x6e,0x5b,0x9a,0x87 };
static unsigned char cfb_cipher16[24]={
0xF3,0x09,0x87,0x87,0x7F,0x57, 0xF7,0x3C,0x36,0xB6,0xDB,0x70,
0xD8,0xD5,0x34,0x19,0xD3,0x86, 0xB2,0x23,0xB7,0xB2,0xAD,0x1B };
static unsigned char cfb_cipher32[24]={
0xF3,0x09,0x62,0x49,0xA4,0xDF, 0xA4,0x9F,0x33,0xDC,0x7B,0xAD,
0x4C,0xC8,0x9F,0x64,0xE4,0x53, 0xE5,0xEC,0x67,0x20,0xDA,0xB6 };
static unsigned char cfb_cipher48[24]={
0xF3,0x09,0x62,0x49,0xC7,0xF4, 0x30,0xB5,0x15,0xEC,0xBB,0x85,
0x97,0x5A,0x13,0x8C,0x68,0x60, 0xE2,0x38,0x34,0x3C,0xDC,0x1F };
static unsigned char cfb_cipher64[24]={
0xF3,0x09,0x62,0x49,0xC7,0xF4, 0x6E,0x51,0xA6,0x9E,0x83,0x9B,
0x1A,0x92,0xF7,0x84,0x03,0x46, 0x71,0x33,0x89,0x8E,0xA6,0x22 };
static unsigned char ofb_key[8]={0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};
static unsigned char ofb_iv[8]={0x12,0x34,0x56,0x78,0x90,0xab,0xcd,0xef};
static unsigned char ofb_buf1[24],ofb_buf2[24],ofb_tmp[8];
static unsigned char ofb_cipher[24]=
{
0xf3,0x09,0x62,0x49,0xc7,0xf4,0x6e,0x51,
0x35,0xf2,0x4a,0x24,0x2e,0xeb,0x3d,0x3f,
0x3d,0x6d,0x5b,0xe3,0x25,0x5a,0xf8,0xc3
};
#if 0
static DES_LONG cbc_cksum_ret=0xB462FEF7L;
#else
static DES_LONG cbc_cksum_ret=0xF7FE62B4L;
#endif
static unsigned char cbc_cksum_data[8]={0x1D,0x26,0x93,0x97,0xf7,0xfe,0x62,0xb4};
static char *pt(unsigned char *p);
static int cfb_test(int bits, unsigned char *cfb_cipher);
static int cfb64_test(unsigned char *cfb_cipher);
static int ede_cfb64_test(unsigned char *cfb_cipher);
int main(int argc, char *argv[])
{
int j,err=0;
unsigned int i;
des_cblock in,out,outin,iv3,iv2;
des_key_schedule ks,ks2,ks3;
unsigned char cbc_in[40];
unsigned char cbc_out[40];
DES_LONG cs;
unsigned char cret[8];
#ifdef _CRAY
struct {
int a:32;
int b:32;
} lqret[2];
#else
DES_LONG lqret[4];
#endif
int num;
char *str;
#ifndef OPENSSL_NO_DESCBCM
printf("Doing cbcm\n");
if ((j=DES_set_key_checked(&cbc_key,&ks)) != 0)
{
printf("Key error %d\n",j);
err=1;
}
if ((j=DES_set_key_checked(&cbc2_key,&ks2)) != 0)
{
printf("Key error %d\n",j);
err=1;
}
if ((j=DES_set_key_checked(&cbc3_key,&ks3)) != 0)
{
printf("Key error %d\n",j);
err=1;
}
memset(cbc_out,0,40);
memset(cbc_in,0,40);
i=strlen((char *)cbc_data)+1;
/* i=((i+7)/8)*8; */
memcpy(iv3,cbc_iv,sizeof(cbc_iv));
memset(iv2,'\0',sizeof iv2);
DES_ede3_cbcm_encrypt(cbc_data,cbc_out,16L,&ks,&ks2,&ks3,&iv3,&iv2,
DES_ENCRYPT);
DES_ede3_cbcm_encrypt(&cbc_data[16],&cbc_out[16],i-16,&ks,&ks2,&ks3,
&iv3,&iv2,DES_ENCRYPT);
/* if (memcmp(cbc_out,cbc3_ok,
(unsigned int)(strlen((char *)cbc_data)+1+7)/8*8) != 0)
{
printf("des_ede3_cbc_encrypt encrypt error\n");
err=1;
}
*/
memcpy(iv3,cbc_iv,sizeof(cbc_iv));
memset(iv2,'\0',sizeof iv2);
DES_ede3_cbcm_encrypt(cbc_out,cbc_in,i,&ks,&ks2,&ks3,&iv3,&iv2,DES_DECRYPT);
if (memcmp(cbc_in,cbc_data,strlen((char *)cbc_data)+1) != 0)
{
unsigned int n;
printf("des_ede3_cbcm_encrypt decrypt error\n");
for(n=0 ; n < i ; ++n)
printf(" %02x",cbc_data[n]);
printf("\n");
for(n=0 ; n < i ; ++n)
printf(" %02x",cbc_in[n]);
printf("\n");
err=1;
}
#endif
printf("Doing ecb\n");
for (i=0; i<NUM_TESTS; i++)
{
DES_set_key_unchecked(&key_data[i],&ks);
memcpy(in,plain_data[i],8);
memset(out,0,8);
memset(outin,0,8);
des_ecb_encrypt(&in,&out,ks,DES_ENCRYPT);
des_ecb_encrypt(&out,&outin,ks,DES_DECRYPT);
if (memcmp(out,cipher_data[i],8) != 0)
{
printf("Encryption error %2d\nk=%s p=%s o=%s act=%s\n",
i+1,pt(key_data[i]),pt(in),pt(cipher_data[i]),
pt(out));
err=1;
}
if (memcmp(in,outin,8) != 0)
{
printf("Decryption error %2d\nk=%s p=%s o=%s act=%s\n",
i+1,pt(key_data[i]),pt(out),pt(in),pt(outin));
err=1;
}
}
#ifndef LIBDES_LIT
printf("Doing ede ecb\n");
for (i=0; i<(NUM_TESTS-2); i++)
{
DES_set_key_unchecked(&key_data[i],&ks);
DES_set_key_unchecked(&key_data[i+1],&ks2);
DES_set_key_unchecked(&key_data[i+2],&ks3);
memcpy(in,plain_data[i],8);
memset(out,0,8);
memset(outin,0,8);
des_ecb2_encrypt(&in,&out,ks,ks2,DES_ENCRYPT);
des_ecb2_encrypt(&out,&outin,ks,ks2,DES_DECRYPT);
if (memcmp(out,cipher_ecb2[i],8) != 0)
{
printf("Encryption error %2d\nk=%s p=%s o=%s act=%s\n",
i+1,pt(key_data[i]),pt(in),pt(cipher_ecb2[i]),
pt(out));
err=1;
}
if (memcmp(in,outin,8) != 0)
{
printf("Decryption error %2d\nk=%s p=%s o=%s act=%s\n",
i+1,pt(key_data[i]),pt(out),pt(in),pt(outin));
err=1;
}
}
#endif
printf("Doing cbc\n");
if ((j=DES_set_key_checked(&cbc_key,&ks)) != 0)
{
printf("Key error %d\n",j);
err=1;
}
memset(cbc_out,0,40);
memset(cbc_in,0,40);
memcpy(iv3,cbc_iv,sizeof(cbc_iv));
des_ncbc_encrypt(cbc_data,cbc_out,strlen((char *)cbc_data)+1,ks,
&iv3,DES_ENCRYPT);
if (memcmp(cbc_out,cbc_ok,32) != 0)
{
printf("cbc_encrypt encrypt error\n");
err=1;
}
memcpy(iv3,cbc_iv,sizeof(cbc_iv));
des_ncbc_encrypt(cbc_out,cbc_in,strlen((char *)cbc_data)+1,ks,
&iv3,DES_DECRYPT);
if (memcmp(cbc_in,cbc_data,strlen((char *)cbc_data)) != 0)
{
printf("cbc_encrypt decrypt error\n");
err=1;
}
#ifndef LIBDES_LIT
printf("Doing desx cbc\n");
if ((j=DES_set_key_checked(&cbc_key,&ks)) != 0)
{
printf("Key error %d\n",j);
err=1;
}
memset(cbc_out,0,40);
memset(cbc_in,0,40);
memcpy(iv3,cbc_iv,sizeof(cbc_iv));
des_xcbc_encrypt(cbc_data,cbc_out,strlen((char *)cbc_data)+1,ks,
&iv3,&cbc2_key,&cbc3_key, DES_ENCRYPT);
if (memcmp(cbc_out,xcbc_ok,32) != 0)
{
printf("des_xcbc_encrypt encrypt error\n");
err=1;
}
memcpy(iv3,cbc_iv,sizeof(cbc_iv));
des_xcbc_encrypt(cbc_out,cbc_in,strlen((char *)cbc_data)+1,ks,
&iv3,&cbc2_key,&cbc3_key, DES_DECRYPT);
if (memcmp(cbc_in,cbc_data,strlen((char *)cbc_data)+1) != 0)
{
printf("des_xcbc_encrypt decrypt error\n");
err=1;
}
#endif
printf("Doing ede cbc\n");
if ((j=DES_set_key_checked(&cbc_key,&ks)) != 0)
{
printf("Key error %d\n",j);
err=1;
}
if ((j=DES_set_key_checked(&cbc2_key,&ks2)) != 0)
{
printf("Key error %d\n",j);
err=1;
}
if ((j=DES_set_key_checked(&cbc3_key,&ks3)) != 0)
{
printf("Key error %d\n",j);
err=1;
}
memset(cbc_out,0,40);
memset(cbc_in,0,40);
i=strlen((char *)cbc_data)+1;
/* i=((i+7)/8)*8; */
memcpy(iv3,cbc_iv,sizeof(cbc_iv));
des_ede3_cbc_encrypt(cbc_data,cbc_out,16L,ks,ks2,ks3,&iv3,
DES_ENCRYPT);
des_ede3_cbc_encrypt(&(cbc_data[16]),&(cbc_out[16]),i-16,ks,ks2,ks3,
&iv3,DES_ENCRYPT);
if (memcmp(cbc_out,cbc3_ok,
(unsigned int)(strlen((char *)cbc_data)+1+7)/8*8) != 0)
{
unsigned int n;
printf("des_ede3_cbc_encrypt encrypt error\n");
for(n=0 ; n < i ; ++n)
printf(" %02x",cbc_out[n]);
printf("\n");
for(n=0 ; n < i ; ++n)
printf(" %02x",cbc3_ok[n]);
printf("\n");
err=1;
}
memcpy(iv3,cbc_iv,sizeof(cbc_iv));
des_ede3_cbc_encrypt(cbc_out,cbc_in,i,ks,ks2,ks3,&iv3,DES_DECRYPT);
if (memcmp(cbc_in,cbc_data,strlen((char *)cbc_data)+1) != 0)
{
unsigned int n;
printf("des_ede3_cbc_encrypt decrypt error\n");
for(n=0 ; n < i ; ++n)
printf(" %02x",cbc_data[n]);
printf("\n");
for(n=0 ; n < i ; ++n)
printf(" %02x",cbc_in[n]);
printf("\n");
err=1;
}
#ifndef LIBDES_LIT
printf("Doing pcbc\n");
if ((j=DES_set_key_checked(&cbc_key,&ks)) != 0)
{
printf("Key error %d\n",j);
err=1;
}
memset(cbc_out,0,40);
memset(cbc_in,0,40);
des_pcbc_encrypt(cbc_data,cbc_out,strlen((char *)cbc_data)+1,ks,
&cbc_iv,DES_ENCRYPT);
if (memcmp(cbc_out,pcbc_ok,32) != 0)
{
printf("pcbc_encrypt encrypt error\n");
err=1;
}
des_pcbc_encrypt(cbc_out,cbc_in,strlen((char *)cbc_data)+1,ks,&cbc_iv,
DES_DECRYPT);
if (memcmp(cbc_in,cbc_data,strlen((char *)cbc_data)+1) != 0)
{
printf("pcbc_encrypt decrypt error\n");
err=1;
}
printf("Doing ");
printf("cfb8 ");
err+=cfb_test(8,cfb_cipher8);
printf("cfb16 ");
err+=cfb_test(16,cfb_cipher16);
printf("cfb32 ");
err+=cfb_test(32,cfb_cipher32);
printf("cfb48 ");
err+=cfb_test(48,cfb_cipher48);
printf("cfb64 ");
err+=cfb_test(64,cfb_cipher64);
printf("cfb64() ");
err+=cfb64_test(cfb_cipher64);
memcpy(cfb_tmp,cfb_iv,sizeof(cfb_iv));
for (i=0; i<sizeof(plain); i++)
des_cfb_encrypt(&(plain[i]),&(cfb_buf1[i]),
8,1,ks,&cfb_tmp,DES_ENCRYPT);
if (memcmp(cfb_cipher8,cfb_buf1,sizeof(plain)) != 0)
{
printf("cfb_encrypt small encrypt error\n");
err=1;
}
memcpy(cfb_tmp,cfb_iv,sizeof(cfb_iv));
for (i=0; i<sizeof(plain); i++)
des_cfb_encrypt(&(cfb_buf1[i]),&(cfb_buf2[i]),
8,1,ks,&cfb_tmp,DES_DECRYPT);
if (memcmp(plain,cfb_buf2,sizeof(plain)) != 0)
{
printf("cfb_encrypt small decrypt error\n");
err=1;
}
printf("ede_cfb64() ");
err+=ede_cfb64_test(cfb_cipher64);
printf("done\n");
printf("Doing ofb\n");
DES_set_key_checked(&ofb_key,&ks);
memcpy(ofb_tmp,ofb_iv,sizeof(ofb_iv));
des_ofb_encrypt(plain,ofb_buf1,64,sizeof(plain)/8,ks,&ofb_tmp);
if (memcmp(ofb_cipher,ofb_buf1,sizeof(ofb_buf1)) != 0)
{
printf("ofb_encrypt encrypt error\n");
printf("%02X %02X %02X %02X %02X %02X %02X %02X\n",
ofb_buf1[8+0], ofb_buf1[8+1], ofb_buf1[8+2], ofb_buf1[8+3],
ofb_buf1[8+4], ofb_buf1[8+5], ofb_buf1[8+6], ofb_buf1[8+7]);
printf("%02X %02X %02X %02X %02X %02X %02X %02X\n",
ofb_buf1[8+0], ofb_cipher[8+1], ofb_cipher[8+2], ofb_cipher[8+3],
ofb_buf1[8+4], ofb_cipher[8+5], ofb_cipher[8+6], ofb_cipher[8+7]);
err=1;
}
memcpy(ofb_tmp,ofb_iv,sizeof(ofb_iv));
des_ofb_encrypt(ofb_buf1,ofb_buf2,64,sizeof(ofb_buf1)/8,ks,&ofb_tmp);
if (memcmp(plain,ofb_buf2,sizeof(ofb_buf2)) != 0)
{
printf("ofb_encrypt decrypt error\n");
printf("%02X %02X %02X %02X %02X %02X %02X %02X\n",
ofb_buf2[8+0], ofb_buf2[8+1], ofb_buf2[8+2], ofb_buf2[8+3],
ofb_buf2[8+4], ofb_buf2[8+5], ofb_buf2[8+6], ofb_buf2[8+7]);
printf("%02X %02X %02X %02X %02X %02X %02X %02X\n",
plain[8+0], plain[8+1], plain[8+2], plain[8+3],
plain[8+4], plain[8+5], plain[8+6], plain[8+7]);
err=1;
}
printf("Doing ofb64\n");
DES_set_key_checked(&ofb_key,&ks);
memcpy(ofb_tmp,ofb_iv,sizeof(ofb_iv));
memset(ofb_buf1,0,sizeof(ofb_buf1));
memset(ofb_buf2,0,sizeof(ofb_buf1));
num=0;
for (i=0; i<sizeof(plain); i++)
{
des_ofb64_encrypt(&(plain[i]),&(ofb_buf1[i]),1,ks,&ofb_tmp,
&num);
}
if (memcmp(ofb_cipher,ofb_buf1,sizeof(ofb_buf1)) != 0)
{
printf("ofb64_encrypt encrypt error\n");
err=1;
}
memcpy(ofb_tmp,ofb_iv,sizeof(ofb_iv));
num=0;
des_ofb64_encrypt(ofb_buf1,ofb_buf2,sizeof(ofb_buf1),ks,&ofb_tmp,
&num);
if (memcmp(plain,ofb_buf2,sizeof(ofb_buf2)) != 0)
{
printf("ofb64_encrypt decrypt error\n");
err=1;
}
printf("Doing ede_ofb64\n");
DES_set_key_checked(&ofb_key,&ks);
memcpy(ofb_tmp,ofb_iv,sizeof(ofb_iv));
memset(ofb_buf1,0,sizeof(ofb_buf1));
memset(ofb_buf2,0,sizeof(ofb_buf1));
num=0;
for (i=0; i<sizeof(plain); i++)
{
des_ede3_ofb64_encrypt(&(plain[i]),&(ofb_buf1[i]),1,ks,ks,
ks,&ofb_tmp,&num);
}
if (memcmp(ofb_cipher,ofb_buf1,sizeof(ofb_buf1)) != 0)
{
printf("ede_ofb64_encrypt encrypt error\n");
err=1;
}
memcpy(ofb_tmp,ofb_iv,sizeof(ofb_iv));
num=0;
des_ede3_ofb64_encrypt(ofb_buf1,ofb_buf2,sizeof(ofb_buf1),ks,ks,ks,
&ofb_tmp,&num);
if (memcmp(plain,ofb_buf2,sizeof(ofb_buf2)) != 0)
{
printf("ede_ofb64_encrypt decrypt error\n");
err=1;
}
printf("Doing cbc_cksum\n");
DES_set_key_checked(&cbc_key,&ks);
cs=des_cbc_cksum(cbc_data,&cret,strlen((char *)cbc_data),ks,&cbc_iv);
if (cs != cbc_cksum_ret)
{
printf("bad return value (%08lX), should be %08lX\n",
(unsigned long)cs,(unsigned long)cbc_cksum_ret);
err=1;
}
if (memcmp(cret,cbc_cksum_data,8) != 0)
{
printf("bad cbc_cksum block returned\n");
err=1;
}
printf("Doing quad_cksum\n");
cs=des_quad_cksum(cbc_data,(des_cblock *)lqret,
(long)strlen((char *)cbc_data),2,(des_cblock *)cbc_iv);
if (cs != 0x70d7a63aL)
{
printf("quad_cksum error, ret %08lx should be 70d7a63a\n",
(unsigned long)cs);
err=1;
}
#ifdef _CRAY
if (lqret[0].a != 0x327eba8dL)
{
printf("quad_cksum error, out[0] %08lx is not %08lx\n",
(unsigned long)lqret[0].a,0x327eba8dUL);
err=1;
}
if (lqret[0].b != 0x201a49ccL)
{
printf("quad_cksum error, out[1] %08lx is not %08lx\n",
(unsigned long)lqret[0].b,0x201a49ccUL);
err=1;
}
if (lqret[1].a != 0x70d7a63aL)
{
printf("quad_cksum error, out[2] %08lx is not %08lx\n",
(unsigned long)lqret[1].a,0x70d7a63aUL);
err=1;
}
if (lqret[1].b != 0x501c2c26L)
{
printf("quad_cksum error, out[3] %08lx is not %08lx\n",
(unsigned long)lqret[1].b,0x501c2c26UL);
err=1;
}
#else
if (lqret[0] != 0x327eba8dL)
{
printf("quad_cksum error, out[0] %08lx is not %08lx\n",
(unsigned long)lqret[0],0x327eba8dUL);
err=1;
}
if (lqret[1] != 0x201a49ccL)
{
printf("quad_cksum error, out[1] %08lx is not %08lx\n",
(unsigned long)lqret[1],0x201a49ccUL);
err=1;
}
if (lqret[2] != 0x70d7a63aL)
{
printf("quad_cksum error, out[2] %08lx is not %08lx\n",
(unsigned long)lqret[2],0x70d7a63aUL);
err=1;
}
if (lqret[3] != 0x501c2c26L)
{
printf("quad_cksum error, out[3] %08lx is not %08lx\n",
(unsigned long)lqret[3],0x501c2c26UL);
err=1;
}
#endif
#endif
printf("input word alignment test");
for (i=0; i<4; i++)
{
printf(" %d",i);
des_ncbc_encrypt(&(cbc_out[i]),cbc_in,
strlen((char *)cbc_data)+1,ks,
&cbc_iv,DES_ENCRYPT);
}
printf("\noutput word alignment test");
for (i=0; i<4; i++)
{
printf(" %d",i);
des_ncbc_encrypt(cbc_out,&(cbc_in[i]),
strlen((char *)cbc_data)+1,ks,
&cbc_iv,DES_ENCRYPT);
}
printf("\n");
printf("fast crypt test ");
str=crypt("testing","ef");
if (strcmp("efGnQx2725bI2",str) != 0)
{
printf("fast crypt error, %s should be efGnQx2725bI2\n",str);
err=1;
}
str=crypt("bca76;23","yA");
if (strcmp("yA1Rp/1hZXIJk",str) != 0)
{
printf("fast crypt error, %s should be yA1Rp/1hZXIJk\n",str);
err=1;
}
#ifdef OPENSSL_SYS_NETWARE
if (err) printf("ERROR: %d\n", err);
#endif
printf("\n");
return(err);
}
static char *pt(unsigned char *p)
{
static char bufs[10][20];
static int bnum=0;
char *ret;
int i;
static char *f="0123456789ABCDEF";
ret= &(bufs[bnum++][0]);
bnum%=10;
for (i=0; i<8; i++)
{
ret[i*2]=f[(p[i]>>4)&0xf];
ret[i*2+1]=f[p[i]&0xf];
}
ret[16]='\0';
return(ret);
}
#ifndef LIBDES_LIT
static int cfb_test(int bits, unsigned char *cfb_cipher)
{
des_key_schedule ks;
int i,err=0;
DES_set_key_checked(&cfb_key,&ks);
memcpy(cfb_tmp,cfb_iv,sizeof(cfb_iv));
des_cfb_encrypt(plain,cfb_buf1,bits,sizeof(plain),ks,&cfb_tmp,
DES_ENCRYPT);
if (memcmp(cfb_cipher,cfb_buf1,sizeof(plain)) != 0)
{
err=1;
printf("cfb_encrypt encrypt error\n");
for (i=0; i<24; i+=8)
printf("%s\n",pt(&(cfb_buf1[i])));
}
memcpy(cfb_tmp,cfb_iv,sizeof(cfb_iv));
des_cfb_encrypt(cfb_buf1,cfb_buf2,bits,sizeof(plain),ks,&cfb_tmp,
DES_DECRYPT);
if (memcmp(plain,cfb_buf2,sizeof(plain)) != 0)
{
err=1;
printf("cfb_encrypt decrypt error\n");
for (i=0; i<24; i+=8)
printf("%s\n",pt(&(cfb_buf1[i])));
}
return(err);
}
static int cfb64_test(unsigned char *cfb_cipher)
{
des_key_schedule ks;
int err=0,i,n;
DES_set_key_checked(&cfb_key,&ks);
memcpy(cfb_tmp,cfb_iv,sizeof(cfb_iv));
n=0;
des_cfb64_encrypt(plain,cfb_buf1,12,ks,&cfb_tmp,&n,DES_ENCRYPT);
des_cfb64_encrypt(&(plain[12]),&(cfb_buf1[12]),sizeof(plain)-12,ks,
&cfb_tmp,&n,DES_ENCRYPT);
if (memcmp(cfb_cipher,cfb_buf1,sizeof(plain)) != 0)
{
err=1;
printf("cfb_encrypt encrypt error\n");
for (i=0; i<24; i+=8)
printf("%s\n",pt(&(cfb_buf1[i])));
}
memcpy(cfb_tmp,cfb_iv,sizeof(cfb_iv));
n=0;
des_cfb64_encrypt(cfb_buf1,cfb_buf2,17,ks,&cfb_tmp,&n,DES_DECRYPT);
des_cfb64_encrypt(&(cfb_buf1[17]),&(cfb_buf2[17]),
sizeof(plain)-17,ks,&cfb_tmp,&n,DES_DECRYPT);
if (memcmp(plain,cfb_buf2,sizeof(plain)) != 0)
{
err=1;
printf("cfb_encrypt decrypt error\n");
for (i=0; i<24; i+=8)
printf("%s\n",pt(&(cfb_buf2[i])));
}
return(err);
}
static int ede_cfb64_test(unsigned char *cfb_cipher)
{
des_key_schedule ks;
int err=0,i,n;
DES_set_key_checked(&cfb_key,&ks);
memcpy(cfb_tmp,cfb_iv,sizeof(cfb_iv));
n=0;
des_ede3_cfb64_encrypt(plain,cfb_buf1,12,ks,ks,ks,&cfb_tmp,&n,
DES_ENCRYPT);
des_ede3_cfb64_encrypt(&(plain[12]),&(cfb_buf1[12]),
sizeof(plain)-12,ks,ks,ks,
&cfb_tmp,&n,DES_ENCRYPT);
if (memcmp(cfb_cipher,cfb_buf1,sizeof(plain)) != 0)
{
err=1;
printf("ede_cfb_encrypt encrypt error\n");
for (i=0; i<24; i+=8)
printf("%s\n",pt(&(cfb_buf1[i])));
}
memcpy(cfb_tmp,cfb_iv,sizeof(cfb_iv));
n=0;
des_ede3_cfb64_encrypt(cfb_buf1,cfb_buf2,(long)17,ks,ks,ks,
&cfb_tmp,&n,DES_DECRYPT);
des_ede3_cfb64_encrypt(&(cfb_buf1[17]),&(cfb_buf2[17]),
sizeof(plain)-17,ks,ks,ks,
&cfb_tmp,&n,DES_DECRYPT);
if (memcmp(plain,cfb_buf2,sizeof(plain)) != 0)
{
err=1;
printf("ede_cfb_encrypt decrypt error\n");
for (i=0; i<24; i+=8)
printf("%s\n",pt(&(cfb_buf2[i])));
}
return(err);
}
#endif
#endif
| mit |
M1cha/mi2_lk | lib/openssl/crypto/evp/e_xcbc_d.c | 727 | 4920 | /* crypto/evp/e_xcbc_d.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"
#ifndef OPENSSL_NO_DES
#include <openssl/evp.h>
#include <openssl/objects.h>
#include "evp_locl.h"
#include <openssl/des.h>
static int desx_cbc_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv,int enc);
static int desx_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl);
typedef struct
{
DES_key_schedule ks;/* key schedule */
DES_cblock inw;
DES_cblock outw;
} DESX_CBC_KEY;
#define data(ctx) ((DESX_CBC_KEY *)(ctx)->cipher_data)
static const EVP_CIPHER d_xcbc_cipher=
{
NID_desx_cbc,
8,24,8,
EVP_CIPH_CBC_MODE,
desx_cbc_init_key,
desx_cbc_cipher,
NULL,
sizeof(DESX_CBC_KEY),
EVP_CIPHER_set_asn1_iv,
EVP_CIPHER_get_asn1_iv,
NULL,
NULL
};
const EVP_CIPHER *EVP_desx_cbc(void)
{
return(&d_xcbc_cipher);
}
static int desx_cbc_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc)
{
DES_cblock *deskey = (DES_cblock *)key;
DES_set_key_unchecked(deskey,&data(ctx)->ks);
memcpy(&data(ctx)->inw[0],&key[8],8);
memcpy(&data(ctx)->outw[0],&key[16],8);
return 1;
}
static int desx_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl)
{
while (inl>=EVP_MAXCHUNK)
{
DES_xcbc_encrypt(in,out,(long)EVP_MAXCHUNK,&data(ctx)->ks,
(DES_cblock *)&(ctx->iv[0]),
&data(ctx)->inw,
&data(ctx)->outw,
ctx->encrypt);
inl-=EVP_MAXCHUNK;
in +=EVP_MAXCHUNK;
out+=EVP_MAXCHUNK;
}
if (inl)
DES_xcbc_encrypt(in,out,(long)inl,&data(ctx)->ks,
(DES_cblock *)&(ctx->iv[0]),
&data(ctx)->inw,
&data(ctx)->outw,
ctx->encrypt);
return 1;
}
#endif
| mit |
JayKickliter/WinObjC | deps/3rdparty/icu/icu/source/i18n/collationroot.cpp | 221 | 3048 | /*
*******************************************************************************
* Copyright (C) 2012-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* collationroot.cpp
*
* created on: 2012dec17
* created by: Markus W. Scherer
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/coll.h"
#include "unicode/udata.h"
#include "collation.h"
#include "collationdata.h"
#include "collationdatareader.h"
#include "collationroot.h"
#include "collationsettings.h"
#include "collationtailoring.h"
#include "normalizer2impl.h"
#include "ucln_in.h"
#include "udatamem.h"
#include "umutex.h"
U_NAMESPACE_BEGIN
namespace {
static const CollationCacheEntry *rootSingleton = NULL;
static UInitOnce initOnce = U_INITONCE_INITIALIZER;
} // namespace
U_CDECL_BEGIN
static UBool U_CALLCONV uprv_collation_root_cleanup() {
SharedObject::clearPtr(rootSingleton);
initOnce.reset();
return TRUE;
}
U_CDECL_END
void
CollationRoot::load(UErrorCode &errorCode) {
if(U_FAILURE(errorCode)) { return; }
LocalPointer<CollationTailoring> t(new CollationTailoring(NULL));
if(t.isNull() || t->isBogus()) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
t->memory = udata_openChoice(U_ICUDATA_NAME U_TREE_SEPARATOR_STRING "coll",
"icu", "ucadata",
CollationDataReader::isAcceptable, t->version, &errorCode);
if(U_FAILURE(errorCode)) { return; }
const uint8_t *inBytes = static_cast<const uint8_t *>(udata_getMemory(t->memory));
CollationDataReader::read(NULL, inBytes, udata_getLength(t->memory), *t, errorCode);
if(U_FAILURE(errorCode)) { return; }
ucln_i18n_registerCleanup(UCLN_I18N_COLLATION_ROOT, uprv_collation_root_cleanup);
CollationCacheEntry *entry = new CollationCacheEntry(Locale::getRoot(), t.getAlias());
if(entry != NULL) {
t.orphan(); // The rootSingleton took ownership of the tailoring.
entry->addRef();
rootSingleton = entry;
}
}
const CollationCacheEntry *
CollationRoot::getRootCacheEntry(UErrorCode &errorCode) {
umtx_initOnce(initOnce, CollationRoot::load, errorCode);
if(U_FAILURE(errorCode)) { return NULL; }
return rootSingleton;
}
const CollationTailoring *
CollationRoot::getRoot(UErrorCode &errorCode) {
umtx_initOnce(initOnce, CollationRoot::load, errorCode);
if(U_FAILURE(errorCode)) { return NULL; }
return rootSingleton->tailoring;
}
const CollationData *
CollationRoot::getData(UErrorCode &errorCode) {
const CollationTailoring *root = getRoot(errorCode);
if(U_FAILURE(errorCode)) { return NULL; }
return root->data;
}
const CollationSettings *
CollationRoot::getSettings(UErrorCode &errorCode) {
const CollationTailoring *root = getRoot(errorCode);
if(U_FAILURE(errorCode)) { return NULL; }
return root->settings;
}
U_NAMESPACE_END
#endif // !UCONFIG_NO_COLLATION
| mit |
BlackFrog1/WinObjC | deps/3rdparty/icu/icu/source/i18n/bocsu.cpp | 226 | 4756 | /*
*******************************************************************************
* Copyright (C) 2001-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* file name: bocsu.cpp
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* Author: Markus W. Scherer
*
* Modification history:
* 05/18/2001 weiv Made into separate module
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/bytestream.h"
#include "unicode/utf16.h"
#include "bocsu.h"
/*
* encode one difference value -0x10ffff..+0x10ffff in 1..4 bytes,
* preserving lexical order
*/
static uint8_t *
u_writeDiff(int32_t diff, uint8_t *p) {
if(diff>=SLOPE_REACH_NEG_1) {
if(diff<=SLOPE_REACH_POS_1) {
*p++=(uint8_t)(SLOPE_MIDDLE+diff);
} else if(diff<=SLOPE_REACH_POS_2) {
*p++=(uint8_t)(SLOPE_START_POS_2+(diff/SLOPE_TAIL_COUNT));
*p++=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT);
} else if(diff<=SLOPE_REACH_POS_3) {
p[2]=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT);
diff/=SLOPE_TAIL_COUNT;
p[1]=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT);
*p=(uint8_t)(SLOPE_START_POS_3+(diff/SLOPE_TAIL_COUNT));
p+=3;
} else {
p[3]=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT);
diff/=SLOPE_TAIL_COUNT;
p[2]=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT);
diff/=SLOPE_TAIL_COUNT;
p[1]=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT);
*p=SLOPE_MAX;
p+=4;
}
} else {
int32_t m;
if(diff>=SLOPE_REACH_NEG_2) {
NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m);
*p++=(uint8_t)(SLOPE_START_NEG_2+diff);
*p++=(uint8_t)(SLOPE_MIN+m);
} else if(diff>=SLOPE_REACH_NEG_3) {
NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m);
p[2]=(uint8_t)(SLOPE_MIN+m);
NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m);
p[1]=(uint8_t)(SLOPE_MIN+m);
*p=(uint8_t)(SLOPE_START_NEG_3+diff);
p+=3;
} else {
NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m);
p[3]=(uint8_t)(SLOPE_MIN+m);
NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m);
p[2]=(uint8_t)(SLOPE_MIN+m);
NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m);
p[1]=(uint8_t)(SLOPE_MIN+m);
*p=SLOPE_MIN;
p+=4;
}
}
return p;
}
/*
* Encode the code points of a string as
* a sequence of byte-encoded differences (slope detection),
* preserving lexical order.
*
* Optimize the difference-taking for runs of Unicode text within
* small scripts:
*
* Most small scripts are allocated within aligned 128-blocks of Unicode
* code points. Lexical order is preserved if "prev" is always moved
* into the middle of such a block.
*
* Additionally, "prev" is moved from anywhere in the Unihan
* area into the middle of that area.
* Note that the identical-level run in a sort key is generated from
* NFD text - there are never Hangul characters included.
*/
U_CFUNC UChar32
u_writeIdenticalLevelRun(UChar32 prev, const UChar *s, int32_t length, icu::ByteSink &sink) {
char scratch[64];
int32_t capacity;
int32_t i=0;
while(i<length) {
char *buffer=sink.GetAppendBuffer(1, length*2, scratch, (int32_t)sizeof(scratch), &capacity);
uint8_t *p;
// We must have capacity>=SLOPE_MAX_BYTES in case u_writeDiff() writes that much,
// but we do not want to force the sink.GetAppendBuffer() to allocate
// for a large min_capacity because we might actually only write one byte.
if(capacity<16) {
buffer=scratch;
capacity=(int32_t)sizeof(scratch);
}
p=reinterpret_cast<uint8_t *>(buffer);
uint8_t *lastSafe=p+capacity-SLOPE_MAX_BYTES;
while(i<length && p<=lastSafe) {
if(prev<0x4e00 || prev>=0xa000) {
prev=(prev&~0x7f)-SLOPE_REACH_NEG_1;
} else {
/*
* Unihan U+4e00..U+9fa5:
* double-bytes down from the upper end
*/
prev=0x9fff-SLOPE_REACH_POS_2;
}
UChar32 c;
U16_NEXT(s, i, length, c);
if(c==0xfffe) {
*p++=2; // merge separator
prev=0;
} else {
p=u_writeDiff(c-prev, p);
prev=c;
}
}
sink.Append(buffer, (int32_t)(p-reinterpret_cast<uint8_t *>(buffer)));
}
return prev;
}
#endif /* #if !UCONFIG_NO_COLLATION */
| mit |
PKRoma/poedit | deps/icu4c/source/i18n/utf8collationiterator.cpp | 226 | 17041 | /*
*******************************************************************************
* Copyright (C) 2012-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* utf8collationiterator.cpp
*
* created on: 2012nov12 (from utf16collationiterator.cpp & uitercollationiterator.cpp)
* created by: Markus W. Scherer
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/utf8.h"
#include "charstr.h"
#include "cmemory.h"
#include "collation.h"
#include "collationdata.h"
#include "collationfcd.h"
#include "collationiterator.h"
#include "normalizer2impl.h"
#include "uassert.h"
#include "utf8collationiterator.h"
U_NAMESPACE_BEGIN
UTF8CollationIterator::~UTF8CollationIterator() {}
void
UTF8CollationIterator::resetToOffset(int32_t newOffset) {
reset();
pos = newOffset;
}
int32_t
UTF8CollationIterator::getOffset() const {
return pos;
}
uint32_t
UTF8CollationIterator::handleNextCE32(UChar32 &c, UErrorCode & /*errorCode*/) {
if(pos == length) {
c = U_SENTINEL;
return Collation::FALLBACK_CE32;
}
// Optimized combination of U8_NEXT_OR_FFFD() and UTRIE2_U8_NEXT32().
c = u8[pos++];
if(c < 0xc0) {
// ASCII 00..7F; trail bytes 80..BF map to error values.
return trie->data32[c];
}
uint8_t t1, t2;
if(c < 0xe0 && pos != length && (t1 = (u8[pos] - 0x80)) <= 0x3f) {
// U+0080..U+07FF; 00..7F map to error values.
uint32_t ce32 = trie->data32[trie->index[(UTRIE2_UTF8_2B_INDEX_2_OFFSET - 0xc0) + c] + t1];
c = ((c & 0x1f) << 6) | t1;
++pos;
return ce32;
} else if(c <= 0xef &&
((pos + 1) < length || length < 0) &&
(t1 = (u8[pos] - 0x80)) <= 0x3f && (c != 0xe0 || t1 >= 0x20) &&
(t2 = (u8[pos + 1] - 0x80)) <= 0x3f
) {
// U+0800..U+FFFF; caller maps surrogates to error values.
c = (UChar)((c << 12) | (t1 << 6) | t2);
pos += 2;
return UTRIE2_GET32_FROM_U16_SINGLE_LEAD(trie, c);
} else {
// Function call for supplementary code points and error cases.
// Illegal byte sequences yield U+FFFD.
c = utf8_nextCharSafeBody(u8, &pos, length, c, -3);
return data->getCE32(c);
}
}
UBool
UTF8CollationIterator::foundNULTerminator() {
if(length < 0) {
length = --pos;
return TRUE;
} else {
return FALSE;
}
}
UBool
UTF8CollationIterator::forbidSurrogateCodePoints() const {
return TRUE;
}
UChar32
UTF8CollationIterator::nextCodePoint(UErrorCode & /*errorCode*/) {
if(pos == length) {
return U_SENTINEL;
}
if(u8[pos] == 0 && length < 0) {
length = pos;
return U_SENTINEL;
}
UChar32 c;
U8_NEXT_OR_FFFD(u8, pos, length, c);
return c;
}
UChar32
UTF8CollationIterator::previousCodePoint(UErrorCode & /*errorCode*/) {
if(pos == 0) {
return U_SENTINEL;
}
UChar32 c;
U8_PREV_OR_FFFD(u8, 0, pos, c);
return c;
}
void
UTF8CollationIterator::forwardNumCodePoints(int32_t num, UErrorCode & /*errorCode*/) {
U8_FWD_N(u8, pos, length, num);
}
void
UTF8CollationIterator::backwardNumCodePoints(int32_t num, UErrorCode & /*errorCode*/) {
U8_BACK_N(u8, 0, pos, num);
}
// FCDUTF8CollationIterator ------------------------------------------------ ***
FCDUTF8CollationIterator::~FCDUTF8CollationIterator() {}
void
FCDUTF8CollationIterator::resetToOffset(int32_t newOffset) {
reset();
start = pos = newOffset;
state = CHECK_FWD;
}
int32_t
FCDUTF8CollationIterator::getOffset() const {
if(state != IN_NORMALIZED) {
return pos;
} else if(pos == 0) {
return start;
} else {
return limit;
}
}
uint32_t
FCDUTF8CollationIterator::handleNextCE32(UChar32 &c, UErrorCode &errorCode) {
for(;;) {
if(state == CHECK_FWD) {
// Combination of UTF8CollationIterator::handleNextCE32() with FCD check fastpath.
if(pos == length) {
c = U_SENTINEL;
return Collation::FALLBACK_CE32;
}
c = u8[pos++];
if(c < 0xc0) {
// ASCII 00..7F; trail bytes 80..BF map to error values.
return trie->data32[c];
}
uint8_t t1, t2;
if(c < 0xe0 && pos != length && (t1 = (u8[pos] - 0x80)) <= 0x3f) {
// U+0080..U+07FF; 00..7F map to error values.
uint32_t ce32 = trie->data32[trie->index[(UTRIE2_UTF8_2B_INDEX_2_OFFSET - 0xc0) + c] + t1];
c = ((c & 0x1f) << 6) | t1;
++pos;
if(CollationFCD::hasTccc(c) && pos != length && nextHasLccc()) {
pos -= 2;
} else {
return ce32;
}
} else if(c <= 0xef &&
((pos + 1) < length || length < 0) &&
(t1 = (u8[pos] - 0x80)) <= 0x3f && (c != 0xe0 || t1 >= 0x20) &&
(t2 = (u8[pos + 1] - 0x80)) <= 0x3f
) {
// U+0800..U+FFFF; caller maps surrogates to error values.
c = (UChar)((c << 12) | (t1 << 6) | t2);
pos += 2;
if(CollationFCD::hasTccc(c) &&
(CollationFCD::maybeTibetanCompositeVowel(c) ||
(pos != length && nextHasLccc()))) {
pos -= 3;
} else {
break; // return CE32(BMP)
}
} else {
// Function call for supplementary code points and error cases.
// Illegal byte sequences yield U+FFFD.
c = utf8_nextCharSafeBody(u8, &pos, length, c, -3);
if(c == 0xfffd) {
return Collation::FFFD_CE32;
} else {
U_ASSERT(c > 0xffff);
if(CollationFCD::hasTccc(U16_LEAD(c)) && pos != length && nextHasLccc()) {
pos -= 4;
} else {
return data->getCE32FromSupplementary(c);
}
}
}
if(!nextSegment(errorCode)) {
c = U_SENTINEL;
return Collation::FALLBACK_CE32;
}
continue;
} else if(state == IN_FCD_SEGMENT && pos != limit) {
return UTF8CollationIterator::handleNextCE32(c, errorCode);
} else if(state == IN_NORMALIZED && pos != normalized.length()) {
c = normalized[pos++];
break;
} else {
switchToForward();
}
}
return UTRIE2_GET32_FROM_U16_SINGLE_LEAD(trie, c);
}
UBool
FCDUTF8CollationIterator::nextHasLccc() const {
U_ASSERT(state == CHECK_FWD && pos != length);
// The lowest code point with ccc!=0 is U+0300 which is CC 80 in UTF-8.
// CJK U+4000..U+DFFF except U+Axxx are also FCD-inert. (Lead bytes E4..ED except EA.)
UChar32 c = u8[pos];
if(c < 0xcc || (0xe4 <= c && c <= 0xed && c != 0xea)) { return FALSE; }
int32_t i = pos;
U8_NEXT_OR_FFFD(u8, i, length, c);
if(c > 0xffff) { c = U16_LEAD(c); }
return CollationFCD::hasLccc(c);
}
UBool
FCDUTF8CollationIterator::previousHasTccc() const {
U_ASSERT(state == CHECK_BWD && pos != 0);
UChar32 c = u8[pos - 1];
if(c < 0x80) { return FALSE; }
int32_t i = pos;
U8_PREV_OR_FFFD(u8, 0, i, c);
if(c > 0xffff) { c = U16_LEAD(c); }
return CollationFCD::hasTccc(c);
}
UChar
FCDUTF8CollationIterator::handleGetTrailSurrogate() {
if(state != IN_NORMALIZED) { return 0; }
U_ASSERT(pos < normalized.length());
UChar trail;
if(U16_IS_TRAIL(trail = normalized[pos])) { ++pos; }
return trail;
}
UBool
FCDUTF8CollationIterator::foundNULTerminator() {
if(state == CHECK_FWD && length < 0) {
length = --pos;
return TRUE;
} else {
return FALSE;
}
}
UChar32
FCDUTF8CollationIterator::nextCodePoint(UErrorCode &errorCode) {
UChar32 c;
for(;;) {
if(state == CHECK_FWD) {
if(pos == length || ((c = u8[pos]) == 0 && length < 0)) {
return U_SENTINEL;
}
if(c < 0x80) {
++pos;
return c;
}
U8_NEXT_OR_FFFD(u8, pos, length, c);
if(CollationFCD::hasTccc(c <= 0xffff ? c : U16_LEAD(c)) &&
(CollationFCD::maybeTibetanCompositeVowel(c) ||
(pos != length && nextHasLccc()))) {
// c is not FCD-inert, therefore it is not U+FFFD and it has a valid byte sequence
// and we can use U8_LENGTH() rather than a previous-position variable.
pos -= U8_LENGTH(c);
if(!nextSegment(errorCode)) {
return U_SENTINEL;
}
continue;
}
return c;
} else if(state == IN_FCD_SEGMENT && pos != limit) {
U8_NEXT_OR_FFFD(u8, pos, length, c);
return c;
} else if(state == IN_NORMALIZED && pos != normalized.length()) {
c = normalized.char32At(pos);
pos += U16_LENGTH(c);
return c;
} else {
switchToForward();
}
}
}
UChar32
FCDUTF8CollationIterator::previousCodePoint(UErrorCode &errorCode) {
UChar32 c;
for(;;) {
if(state == CHECK_BWD) {
if(pos == 0) {
return U_SENTINEL;
}
if((c = u8[pos - 1]) < 0x80) {
--pos;
return c;
}
U8_PREV_OR_FFFD(u8, 0, pos, c);
if(CollationFCD::hasLccc(c <= 0xffff ? c : U16_LEAD(c)) &&
(CollationFCD::maybeTibetanCompositeVowel(c) ||
(pos != 0 && previousHasTccc()))) {
// c is not FCD-inert, therefore it is not U+FFFD and it has a valid byte sequence
// and we can use U8_LENGTH() rather than a previous-position variable.
pos += U8_LENGTH(c);
if(!previousSegment(errorCode)) {
return U_SENTINEL;
}
continue;
}
return c;
} else if(state == IN_FCD_SEGMENT && pos != start) {
U8_PREV_OR_FFFD(u8, 0, pos, c);
return c;
} else if(state >= IN_NORMALIZED && pos != 0) {
c = normalized.char32At(pos - 1);
pos -= U16_LENGTH(c);
return c;
} else {
switchToBackward();
}
}
}
void
FCDUTF8CollationIterator::forwardNumCodePoints(int32_t num, UErrorCode &errorCode) {
// Specify the class to avoid a virtual-function indirection.
// In Java, we would declare this class final.
while(num > 0 && FCDUTF8CollationIterator::nextCodePoint(errorCode) >= 0) {
--num;
}
}
void
FCDUTF8CollationIterator::backwardNumCodePoints(int32_t num, UErrorCode &errorCode) {
// Specify the class to avoid a virtual-function indirection.
// In Java, we would declare this class final.
while(num > 0 && FCDUTF8CollationIterator::previousCodePoint(errorCode) >= 0) {
--num;
}
}
void
FCDUTF8CollationIterator::switchToForward() {
U_ASSERT(state == CHECK_BWD ||
(state == IN_FCD_SEGMENT && pos == limit) ||
(state == IN_NORMALIZED && pos == normalized.length()));
if(state == CHECK_BWD) {
// Turn around from backward checking.
start = pos;
if(pos == limit) {
state = CHECK_FWD; // Check forward.
} else { // pos < limit
state = IN_FCD_SEGMENT; // Stay in FCD segment.
}
} else {
// Reached the end of the FCD segment.
if(state == IN_FCD_SEGMENT) {
// The input text segment is FCD, extend it forward.
} else {
// The input text segment needed to be normalized.
// Switch to checking forward from it.
start = pos = limit;
}
state = CHECK_FWD;
}
}
UBool
FCDUTF8CollationIterator::nextSegment(UErrorCode &errorCode) {
if(U_FAILURE(errorCode)) { return FALSE; }
U_ASSERT(state == CHECK_FWD && pos != length);
// The input text [start..pos[ passes the FCD check.
int32_t segmentStart = pos;
// Collect the characters being checked, in case they need to be normalized.
UnicodeString s;
uint8_t prevCC = 0;
for(;;) {
// Fetch the next character and its fcd16 value.
int32_t cpStart = pos;
UChar32 c;
U8_NEXT_OR_FFFD(u8, pos, length, c);
uint16_t fcd16 = nfcImpl.getFCD16(c);
uint8_t leadCC = (uint8_t)(fcd16 >> 8);
if(leadCC == 0 && cpStart != segmentStart) {
// FCD boundary before this character.
pos = cpStart;
break;
}
s.append(c);
if(leadCC != 0 && (prevCC > leadCC || CollationFCD::isFCD16OfTibetanCompositeVowel(fcd16))) {
// Fails FCD check. Find the next FCD boundary and normalize.
while(pos != length) {
cpStart = pos;
U8_NEXT_OR_FFFD(u8, pos, length, c);
if(nfcImpl.getFCD16(c) <= 0xff) {
pos = cpStart;
break;
}
s.append(c);
}
if(!normalize(s, errorCode)) { return FALSE; }
start = segmentStart;
limit = pos;
state = IN_NORMALIZED;
pos = 0;
return TRUE;
}
prevCC = (uint8_t)fcd16;
if(pos == length || prevCC == 0) {
// FCD boundary after the last character.
break;
}
}
limit = pos;
pos = segmentStart;
U_ASSERT(pos != limit);
state = IN_FCD_SEGMENT;
return TRUE;
}
void
FCDUTF8CollationIterator::switchToBackward() {
U_ASSERT(state == CHECK_FWD ||
(state == IN_FCD_SEGMENT && pos == start) ||
(state >= IN_NORMALIZED && pos == 0));
if(state == CHECK_FWD) {
// Turn around from forward checking.
limit = pos;
if(pos == start) {
state = CHECK_BWD; // Check backward.
} else { // pos > start
state = IN_FCD_SEGMENT; // Stay in FCD segment.
}
} else {
// Reached the start of the FCD segment.
if(state == IN_FCD_SEGMENT) {
// The input text segment is FCD, extend it backward.
} else {
// The input text segment needed to be normalized.
// Switch to checking backward from it.
limit = pos = start;
}
state = CHECK_BWD;
}
}
UBool
FCDUTF8CollationIterator::previousSegment(UErrorCode &errorCode) {
if(U_FAILURE(errorCode)) { return FALSE; }
U_ASSERT(state == CHECK_BWD && pos != 0);
// The input text [pos..limit[ passes the FCD check.
int32_t segmentLimit = pos;
// Collect the characters being checked, in case they need to be normalized.
UnicodeString s;
uint8_t nextCC = 0;
for(;;) {
// Fetch the previous character and its fcd16 value.
int32_t cpLimit = pos;
UChar32 c;
U8_PREV_OR_FFFD(u8, 0, pos, c);
uint16_t fcd16 = nfcImpl.getFCD16(c);
uint8_t trailCC = (uint8_t)fcd16;
if(trailCC == 0 && cpLimit != segmentLimit) {
// FCD boundary after this character.
pos = cpLimit;
break;
}
s.append(c);
if(trailCC != 0 && ((nextCC != 0 && trailCC > nextCC) ||
CollationFCD::isFCD16OfTibetanCompositeVowel(fcd16))) {
// Fails FCD check. Find the previous FCD boundary and normalize.
while(fcd16 > 0xff && pos != 0) {
cpLimit = pos;
U8_PREV_OR_FFFD(u8, 0, pos, c);
fcd16 = nfcImpl.getFCD16(c);
if(fcd16 == 0) {
pos = cpLimit;
break;
}
s.append(c);
}
s.reverse();
if(!normalize(s, errorCode)) { return FALSE; }
limit = segmentLimit;
start = pos;
state = IN_NORMALIZED;
pos = normalized.length();
return TRUE;
}
nextCC = (uint8_t)(fcd16 >> 8);
if(pos == 0 || nextCC == 0) {
// FCD boundary before the following character.
break;
}
}
start = pos;
pos = segmentLimit;
U_ASSERT(pos != start);
state = IN_FCD_SEGMENT;
return TRUE;
}
UBool
FCDUTF8CollationIterator::normalize(const UnicodeString &s, UErrorCode &errorCode) {
// NFD without argument checking.
U_ASSERT(U_SUCCESS(errorCode));
nfcImpl.decompose(s, normalized, errorCode);
return U_SUCCESS(errorCode);
}
U_NAMESPACE_END
#endif // !UCONFIG_NO_COLLATION
| mit |
rayrog/TLI | vendor/twig/twig/ext/twig/twig.c | 246 | 35536 | /*
+----------------------------------------------------------------------+
| Twig Extension |
+----------------------------------------------------------------------+
| Copyright (c) 2011 Derick Rethans |
+----------------------------------------------------------------------+
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the conditions mentioned |
| in the accompanying LICENSE file are met (BSD-3-Clause). |
+----------------------------------------------------------------------+
| Author: Derick Rethans <derick@derickrethans.nl> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_twig.h"
#include "ext/standard/php_var.h"
#include "ext/standard/php_string.h"
#include "ext/standard/php_smart_str.h"
#include "ext/spl/spl_exceptions.h"
#include "Zend/zend_object_handlers.h"
#include "Zend/zend_interfaces.h"
#include "Zend/zend_exceptions.h"
#ifndef Z_ADDREF_P
#define Z_ADDREF_P(pz) (pz)->refcount++
#endif
#ifndef E_USER_DEPRECATED
#define E_USER_DEPRECATED (1<<14L)
#endif
#define FREE_DTOR(z) \
zval_dtor(z); \
efree(z);
#if PHP_VERSION_ID >= 50300
#define APPLY_TSRMLS_DC TSRMLS_DC
#define APPLY_TSRMLS_CC TSRMLS_CC
#define APPLY_TSRMLS_FETCH()
#else
#define APPLY_TSRMLS_DC
#define APPLY_TSRMLS_CC
#define APPLY_TSRMLS_FETCH() TSRMLS_FETCH()
#endif
ZEND_BEGIN_ARG_INFO_EX(twig_template_get_attribute_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 6)
ZEND_ARG_INFO(0, template)
ZEND_ARG_INFO(0, object)
ZEND_ARG_INFO(0, item)
ZEND_ARG_INFO(0, arguments)
ZEND_ARG_INFO(0, type)
ZEND_ARG_INFO(0, isDefinedTest)
ZEND_END_ARG_INFO()
#ifndef PHP_FE_END
#define PHP_FE_END { NULL, NULL, NULL}
#endif
static const zend_function_entry twig_functions[] = {
PHP_FE(twig_template_get_attributes, twig_template_get_attribute_args)
PHP_FE_END
};
PHP_RSHUTDOWN_FUNCTION(twig)
{
#if ZEND_DEBUG
CG(unclean_shutdown) = 0; /* get rid of PHPUnit's exit() and report memleaks */
#endif
return SUCCESS;
}
zend_module_entry twig_module_entry = {
STANDARD_MODULE_HEADER,
"twig",
twig_functions,
NULL,
NULL,
NULL,
PHP_RSHUTDOWN(twig),
NULL,
PHP_TWIG_VERSION,
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_TWIG
ZEND_GET_MODULE(twig)
#endif
static int TWIG_ARRAY_KEY_EXISTS(zval *array, zval *key)
{
if (Z_TYPE_P(array) != IS_ARRAY) {
return 0;
}
switch (Z_TYPE_P(key)) {
case IS_NULL:
return zend_hash_exists(Z_ARRVAL_P(array), "", 1);
case IS_BOOL:
case IS_DOUBLE:
convert_to_long(key);
case IS_LONG:
return zend_hash_index_exists(Z_ARRVAL_P(array), Z_LVAL_P(key));
default:
convert_to_string(key);
return zend_symtable_exists(Z_ARRVAL_P(array), Z_STRVAL_P(key), Z_STRLEN_P(key) + 1);
}
}
static int TWIG_INSTANCE_OF(zval *object, zend_class_entry *interface TSRMLS_DC)
{
if (Z_TYPE_P(object) != IS_OBJECT) {
return 0;
}
return instanceof_function(Z_OBJCE_P(object), interface TSRMLS_CC);
}
static int TWIG_INSTANCE_OF_USERLAND(zval *object, char *interface TSRMLS_DC)
{
zend_class_entry **pce;
if (Z_TYPE_P(object) != IS_OBJECT) {
return 0;
}
if (zend_lookup_class(interface, strlen(interface), &pce TSRMLS_CC) == FAILURE) {
return 0;
}
return instanceof_function(Z_OBJCE_P(object), *pce TSRMLS_CC);
}
static zval *TWIG_GET_ARRAYOBJECT_ELEMENT(zval *object, zval *offset TSRMLS_DC)
{
zend_class_entry *ce = Z_OBJCE_P(object);
zval *retval;
if (Z_TYPE_P(object) == IS_OBJECT) {
SEPARATE_ARG_IF_REF(offset);
zend_call_method_with_1_params(&object, ce, NULL, "offsetget", &retval, offset);
zval_ptr_dtor(&offset);
if (!retval) {
if (!EG(exception)) {
zend_error(E_ERROR, "Undefined offset for object of type %s used as array.", ce->name);
}
return NULL;
}
return retval;
}
return NULL;
}
static int TWIG_ISSET_ARRAYOBJECT_ELEMENT(zval *object, zval *offset TSRMLS_DC)
{
zend_class_entry *ce = Z_OBJCE_P(object);
zval *retval;
if (Z_TYPE_P(object) == IS_OBJECT) {
SEPARATE_ARG_IF_REF(offset);
zend_call_method_with_1_params(&object, ce, NULL, "offsetexists", &retval, offset);
zval_ptr_dtor(&offset);
if (!retval) {
if (!EG(exception)) {
zend_error(E_ERROR, "Undefined offset for object of type %s used as array.", ce->name);
}
return 0;
}
return (retval && Z_TYPE_P(retval) == IS_BOOL && Z_LVAL_P(retval));
}
return 0;
}
static char *TWIG_STRTOLOWER(const char *str, int str_len)
{
char *item_dup;
item_dup = estrndup(str, str_len);
php_strtolower(item_dup, str_len);
return item_dup;
}
static zval *TWIG_CALL_USER_FUNC_ARRAY(zval *object, char *function, zval *arguments TSRMLS_DC)
{
zend_fcall_info fci;
zval ***args = NULL;
int arg_count = 0;
HashTable *table;
HashPosition pos;
int i = 0;
zval *retval_ptr;
zval *zfunction;
if (arguments) {
table = HASH_OF(arguments);
args = safe_emalloc(sizeof(zval **), table->nNumOfElements, 0);
zend_hash_internal_pointer_reset_ex(table, &pos);
while (zend_hash_get_current_data_ex(table, (void **)&args[i], &pos) == SUCCESS) {
i++;
zend_hash_move_forward_ex(table, &pos);
}
arg_count = table->nNumOfElements;
}
MAKE_STD_ZVAL(zfunction);
ZVAL_STRING(zfunction, function, 1);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
fci.function_name = zfunction;
fci.symbol_table = NULL;
#if PHP_VERSION_ID >= 50300
fci.object_ptr = object;
#else
fci.object_pp = &object;
#endif
fci.retval_ptr_ptr = &retval_ptr;
fci.param_count = arg_count;
fci.params = args;
fci.no_separation = 0;
if (zend_call_function(&fci, NULL TSRMLS_CC) == FAILURE) {
ALLOC_INIT_ZVAL(retval_ptr);
ZVAL_BOOL(retval_ptr, 0);
}
if (args) {
efree(fci.params);
}
FREE_DTOR(zfunction);
return retval_ptr;
}
static int TWIG_CALL_BOOLEAN(zval *object, char *functionName TSRMLS_DC)
{
zval *ret;
int res;
ret = TWIG_CALL_USER_FUNC_ARRAY(object, functionName, NULL TSRMLS_CC);
res = Z_LVAL_P(ret);
zval_ptr_dtor(&ret);
return res;
}
static zval *TWIG_GET_STATIC_PROPERTY(zval *class, char *prop_name TSRMLS_DC)
{
zval **tmp_zval;
zend_class_entry *ce;
if (class == NULL || Z_TYPE_P(class) != IS_OBJECT) {
return NULL;
}
ce = zend_get_class_entry(class TSRMLS_CC);
#if PHP_VERSION_ID >= 50400
tmp_zval = zend_std_get_static_property(ce, prop_name, strlen(prop_name), 0, NULL TSRMLS_CC);
#else
tmp_zval = zend_std_get_static_property(ce, prop_name, strlen(prop_name), 0 TSRMLS_CC);
#endif
return *tmp_zval;
}
static zval *TWIG_GET_ARRAY_ELEMENT_ZVAL(zval *class, zval *prop_name TSRMLS_DC)
{
zval **tmp_zval;
if (class == NULL || Z_TYPE_P(class) != IS_ARRAY) {
if (class != NULL && Z_TYPE_P(class) == IS_OBJECT && TWIG_INSTANCE_OF(class, zend_ce_arrayaccess TSRMLS_CC)) {
// array access object
return TWIG_GET_ARRAYOBJECT_ELEMENT(class, prop_name TSRMLS_CC);
}
return NULL;
}
switch(Z_TYPE_P(prop_name)) {
case IS_NULL:
zend_hash_find(HASH_OF(class), "", 1, (void**) &tmp_zval);
return *tmp_zval;
case IS_BOOL:
case IS_DOUBLE:
convert_to_long(prop_name);
case IS_LONG:
zend_hash_index_find(HASH_OF(class), Z_LVAL_P(prop_name), (void **) &tmp_zval);
return *tmp_zval;
case IS_STRING:
zend_symtable_find(HASH_OF(class), Z_STRVAL_P(prop_name), Z_STRLEN_P(prop_name) + 1, (void**) &tmp_zval);
return *tmp_zval;
}
return NULL;
}
static zval *TWIG_GET_ARRAY_ELEMENT(zval *class, char *prop_name, int prop_name_length TSRMLS_DC)
{
zval **tmp_zval;
if (class == NULL/* || Z_TYPE_P(class) != IS_ARRAY*/) {
return NULL;
}
if (class != NULL && Z_TYPE_P(class) == IS_OBJECT && TWIG_INSTANCE_OF(class, zend_ce_arrayaccess TSRMLS_CC)) {
// array access object
zval *tmp_name_zval;
zval *tmp_ret_zval;
ALLOC_INIT_ZVAL(tmp_name_zval);
ZVAL_STRING(tmp_name_zval, prop_name, 1);
tmp_ret_zval = TWIG_GET_ARRAYOBJECT_ELEMENT(class, tmp_name_zval TSRMLS_CC);
FREE_DTOR(tmp_name_zval);
return tmp_ret_zval;
}
if (zend_symtable_find(HASH_OF(class), prop_name, prop_name_length+1, (void**)&tmp_zval) == SUCCESS) {
return *tmp_zval;
}
return NULL;
}
static zval *TWIG_PROPERTY(zval *object, zval *propname TSRMLS_DC)
{
zval *tmp = NULL;
if (Z_OBJ_HT_P(object)->read_property) {
#if PHP_VERSION_ID >= 50400
tmp = Z_OBJ_HT_P(object)->read_property(object, propname, BP_VAR_IS, NULL TSRMLS_CC);
#else
tmp = Z_OBJ_HT_P(object)->read_property(object, propname, BP_VAR_IS TSRMLS_CC);
#endif
if (tmp == EG(uninitialized_zval_ptr)) {
ZVAL_NULL(tmp);
}
}
return tmp;
}
static int TWIG_HAS_PROPERTY(zval *object, zval *propname TSRMLS_DC)
{
if (Z_OBJ_HT_P(object)->has_property) {
#if PHP_VERSION_ID >= 50400
return Z_OBJ_HT_P(object)->has_property(object, propname, 0, NULL TSRMLS_CC);
#else
return Z_OBJ_HT_P(object)->has_property(object, propname, 0 TSRMLS_CC);
#endif
}
return 0;
}
static int TWIG_HAS_DYNAMIC_PROPERTY(zval *object, char *prop, int prop_len TSRMLS_DC)
{
if (Z_OBJ_HT_P(object)->get_properties) {
return zend_hash_quick_exists(
Z_OBJ_HT_P(object)->get_properties(object TSRMLS_CC), // the properties hash
prop, // property name
prop_len + 1, // property length
zend_get_hash_value(prop, prop_len + 1) // hash value
);
}
return 0;
}
static zval *TWIG_PROPERTY_CHAR(zval *object, char *propname TSRMLS_DC)
{
zval *tmp_name_zval, *tmp;
ALLOC_INIT_ZVAL(tmp_name_zval);
ZVAL_STRING(tmp_name_zval, propname, 1);
tmp = TWIG_PROPERTY(object, tmp_name_zval TSRMLS_CC);
FREE_DTOR(tmp_name_zval);
return tmp;
}
static zval *TWIG_CALL_S(zval *object, char *method, char *arg0 TSRMLS_DC)
{
zend_fcall_info fci;
zval **args[1];
zval *argument;
zval *zfunction;
zval *retval_ptr;
MAKE_STD_ZVAL(argument);
ZVAL_STRING(argument, arg0, 1);
args[0] = &argument;
MAKE_STD_ZVAL(zfunction);
ZVAL_STRING(zfunction, method, 1);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
fci.function_name = zfunction;
fci.symbol_table = NULL;
#if PHP_VERSION_ID >= 50300
fci.object_ptr = object;
#else
fci.object_pp = &object;
#endif
fci.retval_ptr_ptr = &retval_ptr;
fci.param_count = 1;
fci.params = args;
fci.no_separation = 0;
if (zend_call_function(&fci, NULL TSRMLS_CC) == FAILURE) {
FREE_DTOR(zfunction);
zval_ptr_dtor(&argument);
return 0;
}
FREE_DTOR(zfunction);
zval_ptr_dtor(&argument);
return retval_ptr;
}
static int TWIG_CALL_SB(zval *object, char *method, char *arg0 TSRMLS_DC)
{
zval *retval_ptr;
int success;
retval_ptr = TWIG_CALL_S(object, method, arg0 TSRMLS_CC);
success = (retval_ptr && (Z_TYPE_P(retval_ptr) == IS_BOOL) && Z_LVAL_P(retval_ptr));
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
return success;
}
static int TWIG_CALL_ZZ(zval *object, char *method, zval *arg1, zval *arg2 TSRMLS_DC)
{
zend_fcall_info fci;
zval **args[2];
zval *zfunction;
zval *retval_ptr;
int success;
args[0] = &arg1;
args[1] = &arg2;
MAKE_STD_ZVAL(zfunction);
ZVAL_STRING(zfunction, method, 1);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
fci.function_name = zfunction;
fci.symbol_table = NULL;
#if PHP_VERSION_ID >= 50300
fci.object_ptr = object;
#else
fci.object_pp = &object;
#endif
fci.retval_ptr_ptr = &retval_ptr;
fci.param_count = 2;
fci.params = args;
fci.no_separation = 0;
if (zend_call_function(&fci, NULL TSRMLS_CC) == FAILURE) {
FREE_DTOR(zfunction);
return 0;
}
FREE_DTOR(zfunction);
success = (retval_ptr && (Z_TYPE_P(retval_ptr) == IS_BOOL) && Z_LVAL_P(retval_ptr));
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
return success;
}
#ifndef Z_SET_REFCOUNT_P
# define Z_SET_REFCOUNT_P(pz, rc) pz->refcount = rc
# define Z_UNSET_ISREF_P(pz) pz->is_ref = 0
#endif
static void TWIG_NEW(zval *object, char *class, zval *arg0, zval *arg1 TSRMLS_DC)
{
zend_class_entry **pce;
if (zend_lookup_class(class, strlen(class), &pce TSRMLS_CC) == FAILURE) {
return;
}
Z_TYPE_P(object) = IS_OBJECT;
object_init_ex(object, *pce);
Z_SET_REFCOUNT_P(object, 1);
Z_UNSET_ISREF_P(object);
TWIG_CALL_ZZ(object, "__construct", arg0, arg1 TSRMLS_CC);
}
static int twig_add_array_key_to_string(void *pDest APPLY_TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key)
{
smart_str *buf;
char *joiner;
APPLY_TSRMLS_FETCH();
buf = va_arg(args, smart_str*);
joiner = va_arg(args, char*);
if (buf->len != 0) {
smart_str_appends(buf, joiner);
}
if (hash_key->nKeyLength == 0) {
smart_str_append_long(buf, (long) hash_key->h);
} else {
char *key, *tmp_str;
int key_len, tmp_len;
key = php_addcslashes(hash_key->arKey, hash_key->nKeyLength - 1, &key_len, 0, "'\\", 2 TSRMLS_CC);
tmp_str = php_str_to_str_ex(key, key_len, "\0", 1, "' . \"\\0\" . '", 12, &tmp_len, 0, NULL);
smart_str_appendl(buf, tmp_str, tmp_len);
efree(key);
efree(tmp_str);
}
return 0;
}
static char *TWIG_IMPLODE_ARRAY_KEYS(char *joiner, zval *array TSRMLS_DC)
{
smart_str collector = { 0, 0, 0 };
smart_str_appendl(&collector, "", 0);
zend_hash_apply_with_arguments(HASH_OF(array) APPLY_TSRMLS_CC, twig_add_array_key_to_string, 2, &collector, joiner);
smart_str_0(&collector);
return collector.c;
}
static void TWIG_RUNTIME_ERROR(zval *template TSRMLS_DC, char *message, ...)
{
char *buffer;
va_list args;
zend_class_entry **pce;
zval *ex;
zval *constructor;
zval *zmessage;
zval *lineno;
zval *filename_func;
zval *filename;
zval *constructor_args[3];
zval *constructor_retval;
if (zend_lookup_class("Twig_Error_Runtime", strlen("Twig_Error_Runtime"), &pce TSRMLS_CC) == FAILURE) {
return;
}
va_start(args, message);
vspprintf(&buffer, 0, message, args);
va_end(args);
MAKE_STD_ZVAL(ex);
object_init_ex(ex, *pce);
// Call Twig_Error constructor
MAKE_STD_ZVAL(constructor);
MAKE_STD_ZVAL(zmessage);
MAKE_STD_ZVAL(lineno);
MAKE_STD_ZVAL(filename);
MAKE_STD_ZVAL(filename_func);
MAKE_STD_ZVAL(constructor_retval);
ZVAL_STRINGL(constructor, "__construct", sizeof("__construct")-1, 1);
ZVAL_STRING(zmessage, buffer, 1);
ZVAL_LONG(lineno, -1);
// Get template filename
ZVAL_STRINGL(filename_func, "getTemplateName", sizeof("getTemplateName")-1, 1);
call_user_function(EG(function_table), &template, filename_func, filename, 0, 0 TSRMLS_CC);
constructor_args[0] = zmessage;
constructor_args[1] = lineno;
constructor_args[2] = filename;
call_user_function(EG(function_table), &ex, constructor, constructor_retval, 3, constructor_args TSRMLS_CC);
zval_ptr_dtor(&constructor_retval);
zval_ptr_dtor(&zmessage);
zval_ptr_dtor(&lineno);
zval_ptr_dtor(&filename);
FREE_DTOR(constructor);
FREE_DTOR(filename_func);
efree(buffer);
zend_throw_exception_object(ex TSRMLS_CC);
}
static char *TWIG_GET_CLASS_NAME(zval *object TSRMLS_DC)
{
char *class_name;
zend_uint class_name_len;
if (Z_TYPE_P(object) != IS_OBJECT) {
return "";
}
#if PHP_API_VERSION >= 20100412
zend_get_object_classname(object, (const char **) &class_name, &class_name_len TSRMLS_CC);
#else
zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC);
#endif
return class_name;
}
static int twig_add_method_to_class(void *pDest APPLY_TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key)
{
zend_class_entry *ce;
zval *retval;
char *item;
size_t item_len;
zend_function *mptr = (zend_function *) pDest;
APPLY_TSRMLS_FETCH();
if (!(mptr->common.fn_flags & ZEND_ACC_PUBLIC)) {
return 0;
}
ce = *va_arg(args, zend_class_entry**);
retval = va_arg(args, zval*);
item_len = strlen(mptr->common.function_name);
item = estrndup(mptr->common.function_name, item_len);
php_strtolower(item, item_len);
if (strcmp("getenvironment", item) == 0) {
zend_class_entry **twig_template_ce;
if (zend_lookup_class("Twig_Template", strlen("Twig_Template"), &twig_template_ce TSRMLS_CC) == FAILURE) {
return 0;
}
if (instanceof_function(ce, *twig_template_ce TSRMLS_CC)) {
return 0;
}
}
add_assoc_stringl_ex(retval, item, item_len+1, item, item_len, 0);
return 0;
}
static int twig_add_property_to_class(void *pDest APPLY_TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key)
{
zend_class_entry *ce;
zval *retval;
char *class_name, *prop_name;
zend_property_info *pptr = (zend_property_info *) pDest;
APPLY_TSRMLS_FETCH();
if (!(pptr->flags & ZEND_ACC_PUBLIC) || (pptr->flags & ZEND_ACC_STATIC)) {
return 0;
}
ce = *va_arg(args, zend_class_entry**);
retval = va_arg(args, zval*);
#if PHP_API_VERSION >= 20100412
zend_unmangle_property_name(pptr->name, pptr->name_length, (const char **) &class_name, (const char **) &prop_name);
#else
zend_unmangle_property_name(pptr->name, pptr->name_length, &class_name, &prop_name);
#endif
add_assoc_string(retval, prop_name, prop_name, 1);
return 0;
}
static void twig_add_class_to_cache(zval *cache, zval *object, char *class_name TSRMLS_DC)
{
zval *class_info, *class_methods, *class_properties;
zend_class_entry *class_ce;
class_ce = zend_get_class_entry(object TSRMLS_CC);
ALLOC_INIT_ZVAL(class_info);
ALLOC_INIT_ZVAL(class_methods);
ALLOC_INIT_ZVAL(class_properties);
array_init(class_info);
array_init(class_methods);
array_init(class_properties);
// add all methods to self::cache[$class]['methods']
zend_hash_apply_with_arguments(&class_ce->function_table APPLY_TSRMLS_CC, twig_add_method_to_class, 2, &class_ce, class_methods);
zend_hash_apply_with_arguments(&class_ce->properties_info APPLY_TSRMLS_CC, twig_add_property_to_class, 2, &class_ce, class_properties);
add_assoc_zval(class_info, "methods", class_methods);
add_assoc_zval(class_info, "properties", class_properties);
add_assoc_zval(cache, class_name, class_info);
}
/* {{{ proto mixed twig_template_get_attributes(TwigTemplate template, mixed object, mixed item, array arguments, string type, boolean isDefinedTest, boolean ignoreStrictCheck)
A C implementation of TwigTemplate::getAttribute() */
PHP_FUNCTION(twig_template_get_attributes)
{
zval *template;
zval *object;
char *item;
int item_len;
zval *zitem, ztmpitem;
zval *arguments = NULL;
zval *ret = NULL;
char *type = NULL;
int type_len = 0;
zend_bool isDefinedTest = 0;
zend_bool ignoreStrictCheck = 0;
int free_ret = 0;
zval *tmp_self_cache;
char *class_name = NULL;
zval *tmp_class;
char *type_name;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ozz|asbb", &template, &object, &zitem, &arguments, &type, &type_len, &isDefinedTest, &ignoreStrictCheck) == FAILURE) {
return;
}
// convert the item to a string
ztmpitem = *zitem;
zval_copy_ctor(&ztmpitem);
convert_to_string(&ztmpitem);
item_len = Z_STRLEN(ztmpitem);
item = estrndup(Z_STRVAL(ztmpitem), item_len);
zval_dtor(&ztmpitem);
if (!type) {
type = "any";
}
/*
// array
if (Twig_Template::METHOD_CALL !== $type) {
$arrayItem = is_bool($item) || is_float($item) ? (int) $item : $item;
if ((is_array($object) && array_key_exists($arrayItem, $object))
|| ($object instanceof ArrayAccess && isset($object[$arrayItem]))
) {
if ($isDefinedTest) {
return true;
}
return $object[$arrayItem];
}
*/
if (strcmp("method", type) != 0) {
if ((TWIG_ARRAY_KEY_EXISTS(object, zitem))
|| (TWIG_INSTANCE_OF(object, zend_ce_arrayaccess TSRMLS_CC) && TWIG_ISSET_ARRAYOBJECT_ELEMENT(object, zitem TSRMLS_CC))
) {
if (isDefinedTest) {
efree(item);
RETURN_TRUE;
}
ret = TWIG_GET_ARRAY_ELEMENT_ZVAL(object, zitem TSRMLS_CC);
if (!ret) {
ret = &EG(uninitialized_zval);
}
RETVAL_ZVAL(ret, 1, 0);
if (free_ret) {
zval_ptr_dtor(&ret);
}
efree(item);
return;
}
/*
if (Twig_Template::ARRAY_CALL === $type) {
if ($isDefinedTest) {
return false;
}
if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
return null;
}
*/
if (strcmp("array", type) == 0 || Z_TYPE_P(object) != IS_OBJECT) {
if (isDefinedTest) {
efree(item);
RETURN_FALSE;
}
if (ignoreStrictCheck || !TWIG_CALL_BOOLEAN(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "isStrictVariables" TSRMLS_CC)) {
efree(item);
return;
}
/*
if ($object instanceof ArrayAccess) {
$message = sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist', $arrayItem, get_class($object));
} elseif (is_object($object)) {
$message = sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface', $item, get_class($object));
} elseif (is_array($object)) {
if (empty($object)) {
$message = sprintf('Key "%s" does not exist as the array is empty', $arrayItem);
} else {
$message = sprintf('Key "%s" for array with keys "%s" does not exist', $arrayItem, implode(', ', array_keys($object)));
}
} elseif (Twig_Template::ARRAY_CALL === $type) {
if (null === $object) {
$message = sprintf('Impossible to access a key ("%s") on a null variable', $item);
} else {
$message = sprintf('Impossible to access a key ("%s") on a %s variable ("%s")', $item, gettype($object), $object);
}
} elseif (null === $object) {
$message = sprintf('Impossible to access an attribute ("%s") on a null variable', $item);
} else {
$message = sprintf('Impossible to access an attribute ("%s") on a %s variable ("%s")', $item, gettype($object), $object);
}
throw new Twig_Error_Runtime($message, -1, $this->getTemplateName());
}
}
*/
if (TWIG_INSTANCE_OF(object, zend_ce_arrayaccess TSRMLS_CC)) {
TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Key \"%s\" in object with ArrayAccess of class \"%s\" does not exist.", item, TWIG_GET_CLASS_NAME(object TSRMLS_CC));
} else if (Z_TYPE_P(object) == IS_OBJECT) {
TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Impossible to access a key \"%s\" on an object of class \"%s\" that does not implement ArrayAccess interface.", item, TWIG_GET_CLASS_NAME(object TSRMLS_CC));
} else if (Z_TYPE_P(object) == IS_ARRAY) {
if (0 == zend_hash_num_elements(Z_ARRVAL_P(object))) {
TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Key \"%s\" does not exist as the array is empty.", item);
} else {
char *array_keys = TWIG_IMPLODE_ARRAY_KEYS(", ", object TSRMLS_CC);
TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Key \"%s\" for array with keys \"%s\" does not exist.", item, array_keys);
efree(array_keys);
}
} else {
char *type_name = zend_zval_type_name(object);
Z_ADDREF_P(object);
if (Z_TYPE_P(object) == IS_NULL) {
convert_to_string(object);
TWIG_RUNTIME_ERROR(template TSRMLS_CC,
(strcmp("array", type) == 0)
? "Impossible to access a key (\"%s\") on a %s variable."
: "Impossible to access an attribute (\"%s\") on a %s variable.",
item, type_name);
} else {
convert_to_string(object);
TWIG_RUNTIME_ERROR(template TSRMLS_CC,
(strcmp("array", type) == 0)
? "Impossible to access a key (\"%s\") on a %s variable (\"%s\")."
: "Impossible to access an attribute (\"%s\") on a %s variable (\"%s\").",
item, type_name, Z_STRVAL_P(object));
}
zval_ptr_dtor(&object);
}
efree(item);
return;
}
}
/*
if (!is_object($object)) {
if ($isDefinedTest) {
return false;
}
*/
if (Z_TYPE_P(object) != IS_OBJECT) {
if (isDefinedTest) {
efree(item);
RETURN_FALSE;
}
/*
if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
return null;
}
if (null === $object) {
$message = sprintf('Impossible to invoke a method ("%s") on a null variable', $item);
} else {
$message = sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s")', $item, gettype($object), $object);
}
throw new Twig_Error_Runtime($message, -1, $this->getTemplateName());
}
*/
if (ignoreStrictCheck || !TWIG_CALL_BOOLEAN(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "isStrictVariables" TSRMLS_CC)) {
efree(item);
return;
}
type_name = zend_zval_type_name(object);
Z_ADDREF_P(object);
if (Z_TYPE_P(object) == IS_NULL) {
convert_to_string_ex(&object);
TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Impossible to invoke a method (\"%s\") on a %s variable.", item, type_name);
} else {
convert_to_string_ex(&object);
TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Impossible to invoke a method (\"%s\") on a %s variable (\"%s\").", item, type_name, Z_STRVAL_P(object));
}
zval_ptr_dtor(&object);
efree(item);
return;
}
/*
$class = get_class($object);
*/
class_name = TWIG_GET_CLASS_NAME(object TSRMLS_CC);
tmp_self_cache = TWIG_GET_STATIC_PROPERTY(template, "cache" TSRMLS_CC);
tmp_class = TWIG_GET_ARRAY_ELEMENT(tmp_self_cache, class_name, strlen(class_name) TSRMLS_CC);
if (!tmp_class) {
twig_add_class_to_cache(tmp_self_cache, object, class_name TSRMLS_CC);
tmp_class = TWIG_GET_ARRAY_ELEMENT(tmp_self_cache, class_name, strlen(class_name) TSRMLS_CC);
}
efree(class_name);
/*
// object property
if (Twig_Template::METHOD_CALL !== $type && !$object instanceof Twig_Template) {
if (isset($object->$item) || array_key_exists((string) $item, $object)) {
if ($isDefinedTest) {
return true;
}
if ($this->env->hasExtension('Twig_Extension_Sandbox')) {
$this->env->getExtension('Twig_Extension_Sandbox')->checkPropertyAllowed($object, $item);
}
return $object->$item;
}
}
*/
if (strcmp("method", type) != 0 && !TWIG_INSTANCE_OF_USERLAND(object, "Twig_Template" TSRMLS_CC)) {
zval *tmp_properties, *tmp_item;
tmp_properties = TWIG_GET_ARRAY_ELEMENT(tmp_class, "properties", strlen("properties") TSRMLS_CC);
tmp_item = TWIG_GET_ARRAY_ELEMENT(tmp_properties, item, item_len TSRMLS_CC);
if (tmp_item || TWIG_HAS_PROPERTY(object, zitem TSRMLS_CC) || TWIG_HAS_DYNAMIC_PROPERTY(object, item, item_len TSRMLS_CC)) {
if (isDefinedTest) {
efree(item);
RETURN_TRUE;
}
if (TWIG_CALL_SB(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "hasExtension", "Twig_Extension_Sandbox" TSRMLS_CC)) {
TWIG_CALL_ZZ(TWIG_CALL_S(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "getExtension", "Twig_Extension_Sandbox" TSRMLS_CC), "checkPropertyAllowed", object, zitem TSRMLS_CC);
}
if (EG(exception)) {
efree(item);
return;
}
ret = TWIG_PROPERTY(object, zitem TSRMLS_CC);
efree(item);
RETURN_ZVAL(ret, 1, 0);
}
}
/*
// object method
if (!isset(self::$cache[$class]['methods'])) {
if ($object instanceof self) {
$ref = new ReflectionClass($class);
$methods = array();
foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $refMethod) {
$methodName = strtolower($refMethod->name);
// Accessing the environment from templates is forbidden to prevent untrusted changes to the environment
if ('getenvironment' !== $methodName) {
$methods[$methodName] = true;
}
}
self::$cache[$class]['methods'] = $methods;
} else {
self::$cache[$class]['methods'] = array_change_key_case(array_flip(get_class_methods($object)));
}
}
$call = false;
$lcItem = strtolower($item);
if (isset(self::$cache[$class]['methods'][$lcItem])) {
$method = (string) $item;
} elseif (isset(self::$cache[$class]['methods']['get'.$lcItem])) {
$method = 'get'.$item;
} elseif (isset(self::$cache[$class]['methods']['is'.$lcItem])) {
$method = 'is'.$item;
} elseif (isset(self::$cache[$class]['methods']['__call'])) {
$method = (string) $item;
$call = true;
*/
{
int call = 0;
char *lcItem = TWIG_STRTOLOWER(item, item_len);
int lcItem_length;
char *method = NULL;
char *methodForDeprecation = NULL;
char *tmp_method_name_get;
char *tmp_method_name_is;
zval *zmethod;
zval *tmp_methods;
lcItem_length = strlen(lcItem);
tmp_method_name_get = emalloc(4 + lcItem_length);
tmp_method_name_is = emalloc(3 + lcItem_length);
sprintf(tmp_method_name_get, "get%s", lcItem);
sprintf(tmp_method_name_is, "is%s", lcItem);
tmp_methods = TWIG_GET_ARRAY_ELEMENT(tmp_class, "methods", strlen("methods") TSRMLS_CC);
methodForDeprecation = emalloc(item_len + 1);
sprintf(methodForDeprecation, "%s", item);
if (TWIG_GET_ARRAY_ELEMENT(tmp_methods, lcItem, lcItem_length TSRMLS_CC)) {
method = item;
} else if (TWIG_GET_ARRAY_ELEMENT(tmp_methods, tmp_method_name_get, lcItem_length + 3 TSRMLS_CC)) {
method = tmp_method_name_get;
} else if (TWIG_GET_ARRAY_ELEMENT(tmp_methods, tmp_method_name_is, lcItem_length + 2 TSRMLS_CC)) {
method = tmp_method_name_is;
} else if (TWIG_GET_ARRAY_ELEMENT(tmp_methods, "__call", 6 TSRMLS_CC)) {
method = item;
call = 1;
/*
} else {
if ($isDefinedTest) {
return false;
}
if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
return null;
}
throw new Twig_Error_Runtime(sprintf('Method "%s" for object "%s" does not exist.', $item, get_class($object)), -1, $this->getTemplateName());
}
if ($isDefinedTest) {
return true;
}
*/
} else {
efree(tmp_method_name_get);
efree(tmp_method_name_is);
efree(lcItem);
if (isDefinedTest) {
efree(item);
RETURN_FALSE;
}
if (ignoreStrictCheck || !TWIG_CALL_BOOLEAN(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "isStrictVariables" TSRMLS_CC)) {
efree(item);
return;
}
TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Neither the property \"%s\" nor one of the methods \"%s()\", \"get%s()\"/\"is%s()\" or \"__call()\" exist and have public access in class \"%s\".", item, item, item, item, TWIG_GET_CLASS_NAME(object TSRMLS_CC));
efree(item);
return;
}
if (isDefinedTest) {
efree(tmp_method_name_get);
efree(tmp_method_name_is);
efree(lcItem);efree(item);
RETURN_TRUE;
}
/*
if ($this->env->hasExtension('Twig_Extension_Sandbox')) {
$this->env->getExtension('Twig_Extension_Sandbox')->checkMethodAllowed($object, $method);
}
*/
MAKE_STD_ZVAL(zmethod);
ZVAL_STRING(zmethod, method, 1);
if (TWIG_CALL_SB(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "hasExtension", "Twig_Extension_Sandbox" TSRMLS_CC)) {
TWIG_CALL_ZZ(TWIG_CALL_S(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "getExtension", "Twig_Extension_Sandbox" TSRMLS_CC), "checkMethodAllowed", object, zmethod TSRMLS_CC);
}
zval_ptr_dtor(&zmethod);
if (EG(exception)) {
efree(tmp_method_name_get);
efree(tmp_method_name_is);
efree(lcItem);efree(item);
return;
}
/*
// Some objects throw exceptions when they have __call, and the method we try
// to call is not supported. If ignoreStrictCheck is true, we should return null.
try {
$ret = call_user_func_array(array($object, $method), $arguments);
} catch (BadMethodCallException $e) {
if ($call && ($ignoreStrictCheck || !$this->env->isStrictVariables())) {
return null;
}
throw $e;
}
*/
ret = TWIG_CALL_USER_FUNC_ARRAY(object, method, arguments TSRMLS_CC);
if (EG(exception) && TWIG_INSTANCE_OF(EG(exception), spl_ce_BadMethodCallException TSRMLS_CC)) {
if (ignoreStrictCheck || !TWIG_CALL_BOOLEAN(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "isStrictVariables" TSRMLS_CC)) {
efree(tmp_method_name_get);
efree(tmp_method_name_is);
efree(lcItem);efree(item);
zend_clear_exception(TSRMLS_C);
return;
}
}
free_ret = 1;
efree(tmp_method_name_get);
efree(tmp_method_name_is);
efree(lcItem);
/*
// @deprecated in 1.28
if ($object instanceof Twig_TemplateInterface) {
$self = $object->getTemplateName() === $this->getTemplateName();
$message = sprintf('Calling "%s" on template "%s" from template "%s" is deprecated since version 1.28 and won\'t be supported anymore in 2.0.', $item, $object->getTemplateName(), $this->getTemplateName());
if ('renderBlock' === $method || 'displayBlock' === $method) {
$message .= sprintf(' Use block("%s"%s) instead).', $arguments[0], $self ? '' : ', template');
} elseif ('hasBlock' === $method) {
$message .= sprintf(' Use "block("%s"%s) is defined" instead).', $arguments[0], $self ? '' : ', template');
} elseif ('render' === $method || 'display' === $method) {
$message .= sprintf(' Use include("%s") instead).', $object->getTemplateName());
}
@trigger_error($message, E_USER_DEPRECATED);
return $ret === '' ? '' : new Twig_Markup($ret, $this->env->getCharset());
}
return $ret;
*/
efree(item);
// ret can be null, if e.g. the called method throws an exception
if (ret) {
if (TWIG_INSTANCE_OF_USERLAND(object, "Twig_TemplateInterface" TSRMLS_CC)) {
int self;
int old_error_reporting;
zval *object_filename;
zval *this_filename;
zval *filename_func;
char *deprecation_message_complement = NULL;
char *deprecation_message = NULL;
MAKE_STD_ZVAL(object_filename);
MAKE_STD_ZVAL(this_filename);
MAKE_STD_ZVAL(filename_func);
// Get templates names
ZVAL_STRINGL(filename_func, "getTemplateName", sizeof("getTemplateName")-1, 1);
call_user_function(EG(function_table), &object, filename_func, object_filename, 0, 0 TSRMLS_CC);
ZVAL_STRINGL(filename_func, "getTemplateName", sizeof("getTemplateName")-1, 1);
call_user_function(EG(function_table), &template, filename_func, this_filename, 0, 0 TSRMLS_CC);
self = (strcmp(Z_STRVAL_P(object_filename), Z_STRVAL_P(this_filename)) == 0);
if (strcmp(methodForDeprecation, "renderBlock") == 0 || strcmp(methodForDeprecation, "displayBlock") == 0) {
zval **arg0;
zend_hash_index_find(HASH_OF(arguments), 0, (void **) &arg0);
asprintf(
&deprecation_message_complement,
" Use block(\"%s\"%s) instead).",
Z_STRVAL_PP(arg0),
self ? "" : ", template"
);
} else if (strcmp(methodForDeprecation, "hasBlock") == 0) {
zval **arg0;
zend_hash_index_find(HASH_OF(arguments), 0, (void **) &arg0);
asprintf(
&deprecation_message_complement,
" Use \"block(\"%s\"%s) is defined\" instead).",
Z_STRVAL_PP(arg0),
self ? "" : ", template"
);
} else if (strcmp(methodForDeprecation, "render") == 0 || strcmp(methodForDeprecation, "display") == 0) {
asprintf(
&deprecation_message_complement,
" Use include(\"%s\") instead).",
Z_STRVAL_P(object_filename)
);
} else {
deprecation_message_complement = (char*)calloc(0, sizeof(char));
}
asprintf(
&deprecation_message,
"Calling \"%s\" on template \"%s\" from template \"%s\" is deprecated since version 1.28 and won't be supported anymore in 2.0.%s",
methodForDeprecation,
Z_STRVAL_P(object_filename),
Z_STRVAL_P(this_filename),
deprecation_message_complement
);
old_error_reporting = EG(error_reporting);
EG(error_reporting) = 0;
zend_error(E_USER_DEPRECATED, "%s", deprecation_message);
EG(error_reporting) = old_error_reporting;
FREE_DTOR(filename_func)
FREE_DTOR(object_filename)
FREE_DTOR(this_filename)
free(deprecation_message);
free(deprecation_message_complement);
if (Z_STRLEN_P(ret) != 0) {
zval *charset = TWIG_CALL_USER_FUNC_ARRAY(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "getCharset", NULL TSRMLS_CC);
TWIG_NEW(return_value, "Twig_Markup", ret, charset TSRMLS_CC);
zval_ptr_dtor(&charset);
if (ret) {
zval_ptr_dtor(&ret);
}
efree(methodForDeprecation);
return;
}
}
RETVAL_ZVAL(ret, 1, 0);
if (free_ret) {
zval_ptr_dtor(&ret);
}
}
efree(methodForDeprecation);
}
}
| mit |
niker/elitekernel_oxp_42 | net/ipv6/af_inet6.c | 256 | 31589 | /*
* PF_INET6 socket protocol family
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Adapted from linux/net/ipv4/af_inet.c
*
* Fixes:
* piggy, Karl Knutson : Socket protocol table
* Hideaki YOSHIFUJI : sin6_scope_id support
* Arnaldo Melo : check proc_net_create return, cleanups
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/proc_fs.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/icmpv6.h>
#include <linux/netfilter_ipv6.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/udp.h>
#include <net/udplite.h>
#include <net/tcp.h>
#include <net/ipip.h>
#include <net/protocol.h>
#include <net/inet_common.h>
#include <net/route.h>
#include <net/transp_v6.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#ifdef CONFIG_IPV6_TUNNEL
#include <net/ip6_tunnel.h>
#endif
#include <asm/uaccess.h>
#include <asm/system.h>
#include <linux/mroute6.h>
#ifdef CONFIG_ANDROID_PARANOID_NETWORK
#include <linux/android_aid.h>
static inline int current_has_network(void)
{
return in_egroup_p(AID_INET) || capable(CAP_NET_RAW);
}
#else
static inline int current_has_network(void)
{
return 1;
}
#endif
MODULE_AUTHOR("Cast of dozens");
MODULE_DESCRIPTION("IPv6 protocol stack for Linux");
MODULE_LICENSE("GPL");
/* The inetsw6 table contains everything that inet6_create needs to
* build a new socket.
*/
static struct list_head inetsw6[SOCK_MAX];
static DEFINE_SPINLOCK(inetsw6_lock);
struct ipv6_params ipv6_defaults = {
.disable_ipv6 = 0,
.autoconf = 1,
};
static int disable_ipv6_mod = 0;
module_param_named(disable, disable_ipv6_mod, int, 0444);
MODULE_PARM_DESC(disable, "Disable IPv6 module such that it is non-functional");
module_param_named(disable_ipv6, ipv6_defaults.disable_ipv6, int, 0444);
MODULE_PARM_DESC(disable_ipv6, "Disable IPv6 on all interfaces");
module_param_named(autoconf, ipv6_defaults.autoconf, int, 0444);
MODULE_PARM_DESC(autoconf, "Enable IPv6 address autoconfiguration on all interfaces");
static __inline__ struct ipv6_pinfo *inet6_sk_generic(struct sock *sk)
{
const int offset = sk->sk_prot->obj_size - sizeof(struct ipv6_pinfo);
return (struct ipv6_pinfo *)(((u8 *)sk) + offset);
}
static int inet6_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct inet_sock *inet;
struct ipv6_pinfo *np;
struct sock *sk;
struct inet_protosw *answer;
struct proto *answer_prot;
unsigned char answer_flags;
char answer_no_check;
int try_loading_module = 0;
int err;
if (!current_has_network())
return -EACCES;
if (sock->type != SOCK_RAW &&
sock->type != SOCK_DGRAM &&
!inet_ehash_secret)
build_ehash_secret();
/* Look for the requested type/protocol pair. */
lookup_protocol:
err = -ESOCKTNOSUPPORT;
rcu_read_lock();
list_for_each_entry_rcu(answer, &inetsw6[sock->type], list) {
err = 0;
/* Check the non-wild match. */
if (protocol == answer->protocol) {
if (protocol != IPPROTO_IP)
break;
} else {
/* Check for the two wild cases. */
if (IPPROTO_IP == protocol) {
protocol = answer->protocol;
break;
}
if (IPPROTO_IP == answer->protocol)
break;
}
err = -EPROTONOSUPPORT;
}
if (err) {
if (try_loading_module < 2) {
rcu_read_unlock();
/*
* Be more specific, e.g. net-pf-10-proto-132-type-1
* (net-pf-PF_INET6-proto-IPPROTO_SCTP-type-SOCK_STREAM)
*/
if (++try_loading_module == 1)
request_module("net-pf-%d-proto-%d-type-%d",
PF_INET6, protocol, sock->type);
/*
* Fall back to generic, e.g. net-pf-10-proto-132
* (net-pf-PF_INET6-proto-IPPROTO_SCTP)
*/
else
request_module("net-pf-%d-proto-%d",
PF_INET6, protocol);
goto lookup_protocol;
} else
goto out_rcu_unlock;
}
err = -EPERM;
if (sock->type == SOCK_RAW && !kern && !capable(CAP_NET_RAW))
goto out_rcu_unlock;
sock->ops = answer->ops;
answer_prot = answer->prot;
answer_no_check = answer->no_check;
answer_flags = answer->flags;
rcu_read_unlock();
WARN_ON(answer_prot->slab == NULL);
err = -ENOBUFS;
sk = sk_alloc(net, PF_INET6, GFP_KERNEL, answer_prot);
if (sk == NULL)
goto out;
sock_init_data(sock, sk);
err = 0;
sk->sk_no_check = answer_no_check;
if (INET_PROTOSW_REUSE & answer_flags)
sk->sk_reuse = 1;
inet = inet_sk(sk);
inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0;
if (SOCK_RAW == sock->type) {
inet->inet_num = protocol;
if (IPPROTO_RAW == protocol)
inet->hdrincl = 1;
}
sk->sk_destruct = inet_sock_destruct;
sk->sk_family = PF_INET6;
sk->sk_protocol = protocol;
sk->sk_backlog_rcv = answer->prot->backlog_rcv;
inet_sk(sk)->pinet6 = np = inet6_sk_generic(sk);
np->hop_limit = -1;
np->mcast_hops = IPV6_DEFAULT_MCASTHOPS;
np->mc_loop = 1;
np->pmtudisc = IPV6_PMTUDISC_WANT;
np->ipv6only = net->ipv6.sysctl.bindv6only;
/* Init the ipv4 part of the socket since we can have sockets
* using v6 API for ipv4.
*/
inet->uc_ttl = -1;
inet->mc_loop = 1;
inet->mc_ttl = 1;
inet->mc_index = 0;
inet->mc_list = NULL;
if (ipv4_config.no_pmtu_disc)
inet->pmtudisc = IP_PMTUDISC_DONT;
else
inet->pmtudisc = IP_PMTUDISC_WANT;
/*
* Increment only the relevant sk_prot->socks debug field, this changes
* the previous behaviour of incrementing both the equivalent to
* answer->prot->socks (inet6_sock_nr) and inet_sock_nr.
*
* This allows better debug granularity as we'll know exactly how many
* UDPv6, TCPv6, etc socks were allocated, not the sum of all IPv6
* transport protocol socks. -acme
*/
sk_refcnt_debug_inc(sk);
if (inet->inet_num) {
/* It assumes that any protocol which allows
* the user to assign a number at socket
* creation time automatically shares.
*/
inet->inet_sport = htons(inet->inet_num);
sk->sk_prot->hash(sk);
}
if (sk->sk_prot->init) {
err = sk->sk_prot->init(sk);
if (err) {
sk_common_release(sk);
goto out;
}
}
out:
return err;
out_rcu_unlock:
rcu_read_unlock();
goto out;
}
/* bind for INET6 API */
int inet6_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_in6 *addr=(struct sockaddr_in6 *)uaddr;
struct sock *sk = sock->sk;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct net *net = sock_net(sk);
__be32 v4addr = 0;
unsigned short snum;
int addr_type = 0;
int err = 0;
/* If the socket has its own bind function then use it. */
if (sk->sk_prot->bind)
return sk->sk_prot->bind(sk, uaddr, addr_len);
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (addr->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
addr_type = ipv6_addr_type(&addr->sin6_addr);
if ((addr_type & IPV6_ADDR_MULTICAST) && sock->type == SOCK_STREAM)
return -EINVAL;
snum = ntohs(addr->sin6_port);
if (snum && snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE))
return -EACCES;
lock_sock(sk);
/* Check these errors (active socket, double bind). */
if (sk->sk_state != TCP_CLOSE || inet->inet_num) {
err = -EINVAL;
goto out;
}
/* Check if the address belongs to the host. */
if (addr_type == IPV6_ADDR_MAPPED) {
int chk_addr_ret;
/* Binding to v4-mapped address on a v6-only socket
* makes no sense
*/
if (np->ipv6only) {
err = -EINVAL;
goto out;
}
/* Reproduce AF_INET checks to make the bindings consistent */
v4addr = addr->sin6_addr.s6_addr32[3];
chk_addr_ret = inet_addr_type(net, v4addr);
if (!sysctl_ip_nonlocal_bind &&
!(inet->freebind || inet->transparent) &&
v4addr != htonl(INADDR_ANY) &&
chk_addr_ret != RTN_LOCAL &&
chk_addr_ret != RTN_MULTICAST &&
chk_addr_ret != RTN_BROADCAST) {
err = -EADDRNOTAVAIL;
goto out;
}
} else {
if (addr_type != IPV6_ADDR_ANY) {
struct net_device *dev = NULL;
rcu_read_lock();
if (addr_type & IPV6_ADDR_LINKLOCAL) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
addr->sin6_scope_id) {
/* Override any existing binding, if another one
* is supplied by user.
*/
sk->sk_bound_dev_if = addr->sin6_scope_id;
}
/* Binding to link-local address requires an interface */
if (!sk->sk_bound_dev_if) {
err = -EINVAL;
goto out_unlock;
}
dev = dev_get_by_index_rcu(net, sk->sk_bound_dev_if);
if (!dev) {
err = -ENODEV;
goto out_unlock;
}
}
/* ipv4 addr of the socket is invalid. Only the
* unspecified and mapped address have a v4 equivalent.
*/
v4addr = LOOPBACK4_IPV6;
if (!(addr_type & IPV6_ADDR_MULTICAST)) {
if (!inet->transparent &&
!ipv6_chk_addr(net, &addr->sin6_addr,
dev, 0)) {
err = -EADDRNOTAVAIL;
goto out_unlock;
}
}
rcu_read_unlock();
}
}
inet->inet_rcv_saddr = v4addr;
inet->inet_saddr = v4addr;
ipv6_addr_copy(&np->rcv_saddr, &addr->sin6_addr);
if (!(addr_type & IPV6_ADDR_MULTICAST))
ipv6_addr_copy(&np->saddr, &addr->sin6_addr);
/* Make sure we are allowed to bind here. */
if (sk->sk_prot->get_port(sk, snum)) {
inet_reset_saddr(sk);
err = -EADDRINUSE;
goto out;
}
if (addr_type != IPV6_ADDR_ANY) {
sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
if (addr_type != IPV6_ADDR_MAPPED)
np->ipv6only = 1;
}
if (snum)
sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
inet->inet_sport = htons(inet->inet_num);
inet->inet_dport = 0;
inet->inet_daddr = 0;
out:
release_sock(sk);
return err;
out_unlock:
rcu_read_unlock();
goto out;
}
EXPORT_SYMBOL(inet6_bind);
int inet6_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (sk == NULL)
return -EINVAL;
/* Free mc lists */
ipv6_sock_mc_close(sk);
/* Free ac lists */
ipv6_sock_ac_close(sk);
return inet_release(sock);
}
EXPORT_SYMBOL(inet6_release);
void inet6_destroy_sock(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct sk_buff *skb;
struct ipv6_txoptions *opt;
/* Release rx options */
if ((skb = xchg(&np->pktoptions, NULL)) != NULL)
kfree_skb(skb);
if ((skb = xchg(&np->rxpmtu, NULL)) != NULL)
kfree_skb(skb);
/* Free flowlabels */
fl6_free_socklist(sk);
/* Free tx options */
if ((opt = xchg(&np->opt, NULL)) != NULL)
sock_kfree_s(sk, opt, opt->tot_len);
}
EXPORT_SYMBOL_GPL(inet6_destroy_sock);
/*
* This does both peername and sockname.
*/
int inet6_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sockaddr_in6 *sin=(struct sockaddr_in6 *)uaddr;
struct sock *sk = sock->sk;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
sin->sin6_family = AF_INET6;
sin->sin6_flowinfo = 0;
sin->sin6_scope_id = 0;
if (peer) {
if (!inet->inet_dport)
return -ENOTCONN;
if (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)) &&
peer == 1)
return -ENOTCONN;
sin->sin6_port = inet->inet_dport;
ipv6_addr_copy(&sin->sin6_addr, &np->daddr);
if (np->sndflow)
sin->sin6_flowinfo = np->flow_label;
} else {
if (ipv6_addr_any(&np->rcv_saddr))
ipv6_addr_copy(&sin->sin6_addr, &np->saddr);
else
ipv6_addr_copy(&sin->sin6_addr, &np->rcv_saddr);
sin->sin6_port = inet->inet_sport;
}
if (ipv6_addr_type(&sin->sin6_addr) & IPV6_ADDR_LINKLOCAL)
sin->sin6_scope_id = sk->sk_bound_dev_if;
*uaddr_len = sizeof(*sin);
return 0;
}
EXPORT_SYMBOL(inet6_getname);
int inet6_killaddr_ioctl(struct net *net, void __user *arg) {
struct in6_ifreq ireq;
struct sockaddr_in6 sin6;
if (!capable(CAP_NET_ADMIN))
return -EACCES;
if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
return -EFAULT;
sin6.sin6_family = AF_INET6;
ipv6_addr_copy(&sin6.sin6_addr, &ireq.ifr6_addr);
return tcp_nuke_addr(net, (struct sockaddr *) &sin6);
}
int inet6_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
switch(cmd)
{
case SIOCGSTAMP:
return sock_get_timestamp(sk, (struct timeval __user *)arg);
case SIOCGSTAMPNS:
return sock_get_timestampns(sk, (struct timespec __user *)arg);
case SIOCADDRT:
case SIOCDELRT:
return ipv6_route_ioctl(net, cmd, (void __user *)arg);
case SIOCSIFADDR:
return addrconf_add_ifaddr(net, (void __user *) arg);
case SIOCDIFADDR:
return addrconf_del_ifaddr(net, (void __user *) arg);
case SIOCSIFDSTADDR:
return addrconf_set_dstaddr(net, (void __user *) arg);
case SIOCKILLADDR:
return inet6_killaddr_ioctl(net, (void __user *) arg);
default:
if (!sk->sk_prot->ioctl)
return -ENOIOCTLCMD;
return sk->sk_prot->ioctl(sk, cmd, arg);
}
/*NOTREACHED*/
return 0;
}
EXPORT_SYMBOL(inet6_ioctl);
const struct proto_ops inet6_stream_ops = {
.family = PF_INET6,
.owner = THIS_MODULE,
.release = inet6_release,
.bind = inet6_bind,
.connect = inet_stream_connect, /* ok */
.socketpair = sock_no_socketpair, /* a do nothing */
.accept = inet_accept, /* ok */
.getname = inet6_getname,
.poll = tcp_poll, /* ok */
.ioctl = inet6_ioctl, /* must change */
.listen = inet_listen, /* ok */
.shutdown = inet_shutdown, /* ok */
.setsockopt = sock_common_setsockopt, /* ok */
.getsockopt = sock_common_getsockopt, /* ok */
.sendmsg = inet_sendmsg, /* ok */
.recvmsg = inet_recvmsg, /* ok */
.mmap = sock_no_mmap,
.sendpage = inet_sendpage,
.splice_read = tcp_splice_read,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_sock_common_setsockopt,
.compat_getsockopt = compat_sock_common_getsockopt,
#endif
};
const struct proto_ops inet6_dgram_ops = {
.family = PF_INET6,
.owner = THIS_MODULE,
.release = inet6_release,
.bind = inet6_bind,
.connect = inet_dgram_connect, /* ok */
.socketpair = sock_no_socketpair, /* a do nothing */
.accept = sock_no_accept, /* a do nothing */
.getname = inet6_getname,
.poll = udp_poll, /* ok */
.ioctl = inet6_ioctl, /* must change */
.listen = sock_no_listen, /* ok */
.shutdown = inet_shutdown, /* ok */
.setsockopt = sock_common_setsockopt, /* ok */
.getsockopt = sock_common_getsockopt, /* ok */
.sendmsg = inet_sendmsg, /* ok */
.recvmsg = inet_recvmsg, /* ok */
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_sock_common_setsockopt,
.compat_getsockopt = compat_sock_common_getsockopt,
#endif
};
static const struct net_proto_family inet6_family_ops = {
.family = PF_INET6,
.create = inet6_create,
.owner = THIS_MODULE,
};
int inet6_register_protosw(struct inet_protosw *p)
{
struct list_head *lh;
struct inet_protosw *answer;
struct list_head *last_perm;
int protocol = p->protocol;
int ret;
spin_lock_bh(&inetsw6_lock);
ret = -EINVAL;
if (p->type >= SOCK_MAX)
goto out_illegal;
/* If we are trying to override a permanent protocol, bail. */
answer = NULL;
ret = -EPERM;
last_perm = &inetsw6[p->type];
list_for_each(lh, &inetsw6[p->type]) {
answer = list_entry(lh, struct inet_protosw, list);
/* Check only the non-wild match. */
if (INET_PROTOSW_PERMANENT & answer->flags) {
if (protocol == answer->protocol)
break;
last_perm = lh;
}
answer = NULL;
}
if (answer)
goto out_permanent;
/* Add the new entry after the last permanent entry if any, so that
* the new entry does not override a permanent entry when matched with
* a wild-card protocol. But it is allowed to override any existing
* non-permanent entry. This means that when we remove this entry, the
* system automatically returns to the old behavior.
*/
list_add_rcu(&p->list, last_perm);
ret = 0;
out:
spin_unlock_bh(&inetsw6_lock);
return ret;
out_permanent:
printk(KERN_ERR "Attempt to override permanent protocol %d.\n",
protocol);
goto out;
out_illegal:
printk(KERN_ERR
"Ignoring attempt to register invalid socket type %d.\n",
p->type);
goto out;
}
EXPORT_SYMBOL(inet6_register_protosw);
void
inet6_unregister_protosw(struct inet_protosw *p)
{
if (INET_PROTOSW_PERMANENT & p->flags) {
printk(KERN_ERR
"Attempt to unregister permanent protocol %d.\n",
p->protocol);
} else {
spin_lock_bh(&inetsw6_lock);
list_del_rcu(&p->list);
spin_unlock_bh(&inetsw6_lock);
synchronize_net();
}
}
EXPORT_SYMBOL(inet6_unregister_protosw);
int inet6_sk_rebuild_header(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct dst_entry *dst;
dst = __sk_dst_check(sk, np->dst_cookie);
if (dst == NULL) {
struct inet_sock *inet = inet_sk(sk);
struct in6_addr *final_p, final;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = sk->sk_protocol;
ipv6_addr_copy(&fl6.daddr, &np->daddr);
ipv6_addr_copy(&fl6.saddr, &np->saddr);
fl6.flowlabel = np->flow_label;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = inet->inet_dport;
fl6.fl6_sport = inet->inet_sport;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
final_p = fl6_update_dst(&fl6, np->opt, &final);
dst = ip6_dst_lookup_flow(sk, &fl6, final_p, false);
if (IS_ERR(dst)) {
sk->sk_route_caps = 0;
sk->sk_err_soft = -PTR_ERR(dst);
return PTR_ERR(dst);
}
__ip6_dst_store(sk, dst, NULL, NULL);
}
return 0;
}
EXPORT_SYMBOL_GPL(inet6_sk_rebuild_header);
int ipv6_opt_accepted(struct sock *sk, struct sk_buff *skb)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet6_skb_parm *opt = IP6CB(skb);
if (np->rxopt.all) {
if ((opt->hop && (np->rxopt.bits.hopopts ||
np->rxopt.bits.ohopopts)) ||
((IPV6_FLOWINFO_MASK &
*(__be32 *)skb_network_header(skb)) &&
np->rxopt.bits.rxflow) ||
(opt->srcrt && (np->rxopt.bits.srcrt ||
np->rxopt.bits.osrcrt)) ||
((opt->dst1 || opt->dst0) &&
(np->rxopt.bits.dstopts || np->rxopt.bits.odstopts)))
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(ipv6_opt_accepted);
static int ipv6_gso_pull_exthdrs(struct sk_buff *skb, int proto)
{
const struct inet6_protocol *ops = NULL;
for (;;) {
struct ipv6_opt_hdr *opth;
int len;
if (proto != NEXTHDR_HOP) {
ops = rcu_dereference(inet6_protos[proto]);
if (unlikely(!ops))
break;
if (!(ops->flags & INET6_PROTO_GSO_EXTHDR))
break;
}
if (unlikely(!pskb_may_pull(skb, 8)))
break;
opth = (void *)skb->data;
len = ipv6_optlen(opth);
if (unlikely(!pskb_may_pull(skb, len)))
break;
proto = opth->nexthdr;
__skb_pull(skb, len);
}
return proto;
}
static int ipv6_gso_send_check(struct sk_buff *skb)
{
const struct ipv6hdr *ipv6h;
const struct inet6_protocol *ops;
int err = -EINVAL;
if (unlikely(!pskb_may_pull(skb, sizeof(*ipv6h))))
goto out;
ipv6h = ipv6_hdr(skb);
__skb_pull(skb, sizeof(*ipv6h));
err = -EPROTONOSUPPORT;
rcu_read_lock();
ops = rcu_dereference(inet6_protos[
ipv6_gso_pull_exthdrs(skb, ipv6h->nexthdr)]);
if (likely(ops && ops->gso_send_check)) {
skb_reset_transport_header(skb);
err = ops->gso_send_check(skb);
}
rcu_read_unlock();
out:
return err;
}
static struct sk_buff *ipv6_gso_segment(struct sk_buff *skb, u32 features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
struct ipv6hdr *ipv6h;
const struct inet6_protocol *ops;
int proto;
struct frag_hdr *fptr;
unsigned int unfrag_ip6hlen;
u8 *prevhdr;
int offset = 0;
if (!(features & NETIF_F_V6_CSUM))
features &= ~NETIF_F_SG;
if (unlikely(skb_shinfo(skb)->gso_type &
~(SKB_GSO_UDP |
SKB_GSO_DODGY |
SKB_GSO_TCP_ECN |
SKB_GSO_TCPV6 |
0)))
goto out;
if (unlikely(!pskb_may_pull(skb, sizeof(*ipv6h))))
goto out;
ipv6h = ipv6_hdr(skb);
__skb_pull(skb, sizeof(*ipv6h));
segs = ERR_PTR(-EPROTONOSUPPORT);
proto = ipv6_gso_pull_exthdrs(skb, ipv6h->nexthdr);
rcu_read_lock();
ops = rcu_dereference(inet6_protos[proto]);
if (likely(ops && ops->gso_segment)) {
skb_reset_transport_header(skb);
segs = ops->gso_segment(skb, features);
}
rcu_read_unlock();
if (IS_ERR(segs))
goto out;
for (skb = segs; skb; skb = skb->next) {
ipv6h = ipv6_hdr(skb);
ipv6h->payload_len = htons(skb->len - skb->mac_len -
sizeof(*ipv6h));
if (proto == IPPROTO_UDP) {
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
fptr = (struct frag_hdr *)(skb_network_header(skb) +
unfrag_ip6hlen);
fptr->frag_off = htons(offset);
if (skb->next != NULL)
fptr->frag_off |= htons(IP6_MF);
offset += (ntohs(ipv6h->payload_len) -
sizeof(struct frag_hdr));
}
}
out:
return segs;
}
struct ipv6_gro_cb {
struct napi_gro_cb napi;
int proto;
};
#define IPV6_GRO_CB(skb) ((struct ipv6_gro_cb *)(skb)->cb)
static struct sk_buff **ipv6_gro_receive(struct sk_buff **head,
struct sk_buff *skb)
{
const struct inet6_protocol *ops;
struct sk_buff **pp = NULL;
struct sk_buff *p;
struct ipv6hdr *iph;
unsigned int nlen;
unsigned int hlen;
unsigned int off;
int flush = 1;
int proto;
__wsum csum;
off = skb_gro_offset(skb);
hlen = off + sizeof(*iph);
iph = skb_gro_header_fast(skb, off);
if (skb_gro_header_hard(skb, hlen)) {
iph = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!iph))
goto out;
}
skb_gro_pull(skb, sizeof(*iph));
skb_set_transport_header(skb, skb_gro_offset(skb));
flush += ntohs(iph->payload_len) != skb_gro_len(skb);
rcu_read_lock();
proto = iph->nexthdr;
ops = rcu_dereference(inet6_protos[proto]);
if (!ops || !ops->gro_receive) {
__pskb_pull(skb, skb_gro_offset(skb));
proto = ipv6_gso_pull_exthdrs(skb, proto);
skb_gro_pull(skb, -skb_transport_offset(skb));
skb_reset_transport_header(skb);
__skb_push(skb, skb_gro_offset(skb));
ops = rcu_dereference(inet6_protos[proto]);
if (!ops || !ops->gro_receive)
goto out_unlock;
iph = ipv6_hdr(skb);
}
IPV6_GRO_CB(skb)->proto = proto;
flush--;
nlen = skb_network_header_len(skb);
for (p = *head; p; p = p->next) {
struct ipv6hdr *iph2;
if (!NAPI_GRO_CB(p)->same_flow)
continue;
iph2 = ipv6_hdr(p);
/* All fields must match except length. */
if (nlen != skb_network_header_len(p) ||
memcmp(iph, iph2, offsetof(struct ipv6hdr, payload_len)) ||
memcmp(&iph->nexthdr, &iph2->nexthdr,
nlen - offsetof(struct ipv6hdr, nexthdr))) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
NAPI_GRO_CB(p)->flush |= flush;
}
NAPI_GRO_CB(skb)->flush |= flush;
csum = skb->csum;
skb_postpull_rcsum(skb, iph, skb_network_header_len(skb));
pp = ops->gro_receive(head, skb);
skb->csum = csum;
out_unlock:
rcu_read_unlock();
out:
NAPI_GRO_CB(skb)->flush |= flush;
return pp;
}
static int ipv6_gro_complete(struct sk_buff *skb)
{
const struct inet6_protocol *ops;
struct ipv6hdr *iph = ipv6_hdr(skb);
int err = -ENOSYS;
iph->payload_len = htons(skb->len - skb_network_offset(skb) -
sizeof(*iph));
rcu_read_lock();
ops = rcu_dereference(inet6_protos[IPV6_GRO_CB(skb)->proto]);
if (WARN_ON(!ops || !ops->gro_complete))
goto out_unlock;
err = ops->gro_complete(skb);
out_unlock:
rcu_read_unlock();
return err;
}
static struct packet_type ipv6_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_IPV6),
.func = ipv6_rcv,
.gso_send_check = ipv6_gso_send_check,
.gso_segment = ipv6_gso_segment,
.gro_receive = ipv6_gro_receive,
.gro_complete = ipv6_gro_complete,
};
static int __init ipv6_packet_init(void)
{
dev_add_pack(&ipv6_packet_type);
return 0;
}
static void ipv6_packet_cleanup(void)
{
dev_remove_pack(&ipv6_packet_type);
}
static int __net_init ipv6_init_mibs(struct net *net)
{
if (snmp_mib_init((void __percpu **)net->mib.udp_stats_in6,
sizeof(struct udp_mib),
__alignof__(struct udp_mib)) < 0)
return -ENOMEM;
if (snmp_mib_init((void __percpu **)net->mib.udplite_stats_in6,
sizeof(struct udp_mib),
__alignof__(struct udp_mib)) < 0)
goto err_udplite_mib;
if (snmp_mib_init((void __percpu **)net->mib.ipv6_statistics,
sizeof(struct ipstats_mib),
__alignof__(struct ipstats_mib)) < 0)
goto err_ip_mib;
if (snmp_mib_init((void __percpu **)net->mib.icmpv6_statistics,
sizeof(struct icmpv6_mib),
__alignof__(struct icmpv6_mib)) < 0)
goto err_icmp_mib;
if (snmp_mib_init((void __percpu **)net->mib.icmpv6msg_statistics,
sizeof(struct icmpv6msg_mib),
__alignof__(struct icmpv6msg_mib)) < 0)
goto err_icmpmsg_mib;
return 0;
err_icmpmsg_mib:
snmp_mib_free((void __percpu **)net->mib.icmpv6_statistics);
err_icmp_mib:
snmp_mib_free((void __percpu **)net->mib.ipv6_statistics);
err_ip_mib:
snmp_mib_free((void __percpu **)net->mib.udplite_stats_in6);
err_udplite_mib:
snmp_mib_free((void __percpu **)net->mib.udp_stats_in6);
return -ENOMEM;
}
static void ipv6_cleanup_mibs(struct net *net)
{
snmp_mib_free((void __percpu **)net->mib.udp_stats_in6);
snmp_mib_free((void __percpu **)net->mib.udplite_stats_in6);
snmp_mib_free((void __percpu **)net->mib.ipv6_statistics);
snmp_mib_free((void __percpu **)net->mib.icmpv6_statistics);
snmp_mib_free((void __percpu **)net->mib.icmpv6msg_statistics);
}
static int __net_init inet6_net_init(struct net *net)
{
int err = 0;
net->ipv6.sysctl.bindv6only = 0;
net->ipv6.sysctl.icmpv6_time = 1*HZ;
err = ipv6_init_mibs(net);
if (err)
return err;
#ifdef CONFIG_PROC_FS
err = udp6_proc_init(net);
if (err)
goto out;
err = tcp6_proc_init(net);
if (err)
goto proc_tcp6_fail;
err = ac6_proc_init(net);
if (err)
goto proc_ac6_fail;
#endif
return err;
#ifdef CONFIG_PROC_FS
proc_ac6_fail:
tcp6_proc_exit(net);
proc_tcp6_fail:
udp6_proc_exit(net);
out:
ipv6_cleanup_mibs(net);
return err;
#endif
}
static void __net_exit inet6_net_exit(struct net *net)
{
#ifdef CONFIG_PROC_FS
udp6_proc_exit(net);
tcp6_proc_exit(net);
ac6_proc_exit(net);
#endif
ipv6_cleanup_mibs(net);
}
static struct pernet_operations inet6_net_ops = {
.init = inet6_net_init,
.exit = inet6_net_exit,
};
static int __init inet6_init(void)
{
struct sk_buff *dummy_skb;
struct list_head *r;
int err = 0;
BUILD_BUG_ON(sizeof(struct inet6_skb_parm) > sizeof(dummy_skb->cb));
/* Register the socket-side information for inet6_create. */
for(r = &inetsw6[0]; r < &inetsw6[SOCK_MAX]; ++r)
INIT_LIST_HEAD(r);
if (disable_ipv6_mod) {
printk(KERN_INFO
"IPv6: Loaded, but administratively disabled, "
"reboot required to enable\n");
goto out;
}
err = proto_register(&tcpv6_prot, 1);
if (err)
goto out;
err = proto_register(&udpv6_prot, 1);
if (err)
goto out_unregister_tcp_proto;
err = proto_register(&udplitev6_prot, 1);
if (err)
goto out_unregister_udp_proto;
err = proto_register(&rawv6_prot, 1);
if (err)
goto out_unregister_udplite_proto;
/* We MUST register RAW sockets before we create the ICMP6,
* IGMP6, or NDISC control sockets.
*/
err = rawv6_init();
if (err)
goto out_unregister_raw_proto;
/* Register the family here so that the init calls below will
* be able to create sockets. (?? is this dangerous ??)
*/
err = sock_register(&inet6_family_ops);
if (err)
goto out_sock_register_fail;
#ifdef CONFIG_SYSCTL
err = ipv6_static_sysctl_register();
if (err)
goto static_sysctl_fail;
#endif
/*
* ipngwg API draft makes clear that the correct semantics
* for TCP and UDP is to consider one TCP and UDP instance
* in a host available by both INET and INET6 APIs and
* able to communicate via both network protocols.
*/
err = register_pernet_subsys(&inet6_net_ops);
if (err)
goto register_pernet_fail;
err = icmpv6_init();
if (err)
goto icmp_fail;
err = ip6_mr_init();
if (err)
goto ipmr_fail;
err = ndisc_init();
if (err)
goto ndisc_fail;
err = igmp6_init();
if (err)
goto igmp_fail;
err = ipv6_netfilter_init();
if (err)
goto netfilter_fail;
/* Create /proc/foo6 entries. */
#ifdef CONFIG_PROC_FS
err = -ENOMEM;
if (raw6_proc_init())
goto proc_raw6_fail;
if (udplite6_proc_init())
goto proc_udplite6_fail;
if (ipv6_misc_proc_init())
goto proc_misc6_fail;
if (if6_proc_init())
goto proc_if6_fail;
#endif
err = ip6_route_init();
if (err)
goto ip6_route_fail;
err = ip6_flowlabel_init();
if (err)
goto ip6_flowlabel_fail;
err = addrconf_init();
if (err)
goto addrconf_fail;
/* Init v6 extension headers. */
err = ipv6_exthdrs_init();
if (err)
goto ipv6_exthdrs_fail;
err = ipv6_frag_init();
if (err)
goto ipv6_frag_fail;
/* Init v6 transport protocols. */
err = udpv6_init();
if (err)
goto udpv6_fail;
err = udplitev6_init();
if (err)
goto udplitev6_fail;
err = tcpv6_init();
if (err)
goto tcpv6_fail;
err = ipv6_packet_init();
if (err)
goto ipv6_packet_fail;
#ifdef CONFIG_SYSCTL
err = ipv6_sysctl_register();
if (err)
goto sysctl_fail;
#endif
out:
return err;
#ifdef CONFIG_SYSCTL
sysctl_fail:
ipv6_packet_cleanup();
#endif
ipv6_packet_fail:
tcpv6_exit();
tcpv6_fail:
udplitev6_exit();
udplitev6_fail:
udpv6_exit();
udpv6_fail:
ipv6_frag_exit();
ipv6_frag_fail:
ipv6_exthdrs_exit();
ipv6_exthdrs_fail:
addrconf_cleanup();
addrconf_fail:
ip6_flowlabel_cleanup();
ip6_flowlabel_fail:
ip6_route_cleanup();
ip6_route_fail:
#ifdef CONFIG_PROC_FS
if6_proc_exit();
proc_if6_fail:
ipv6_misc_proc_exit();
proc_misc6_fail:
udplite6_proc_exit();
proc_udplite6_fail:
raw6_proc_exit();
proc_raw6_fail:
#endif
ipv6_netfilter_fini();
netfilter_fail:
igmp6_cleanup();
igmp_fail:
ndisc_cleanup();
ndisc_fail:
ip6_mr_cleanup();
ipmr_fail:
icmpv6_cleanup();
icmp_fail:
unregister_pernet_subsys(&inet6_net_ops);
register_pernet_fail:
#ifdef CONFIG_SYSCTL
ipv6_static_sysctl_unregister();
static_sysctl_fail:
#endif
sock_unregister(PF_INET6);
rtnl_unregister_all(PF_INET6);
out_sock_register_fail:
rawv6_exit();
out_unregister_raw_proto:
proto_unregister(&rawv6_prot);
out_unregister_udplite_proto:
proto_unregister(&udplitev6_prot);
out_unregister_udp_proto:
proto_unregister(&udpv6_prot);
out_unregister_tcp_proto:
proto_unregister(&tcpv6_prot);
goto out;
}
module_init(inet6_init);
static void __exit inet6_exit(void)
{
if (disable_ipv6_mod)
return;
/* First of all disallow new sockets creation. */
sock_unregister(PF_INET6);
/* Disallow any further netlink messages */
rtnl_unregister_all(PF_INET6);
#ifdef CONFIG_SYSCTL
ipv6_sysctl_unregister();
#endif
udpv6_exit();
udplitev6_exit();
tcpv6_exit();
/* Cleanup code parts. */
ipv6_packet_cleanup();
ipv6_frag_exit();
ipv6_exthdrs_exit();
addrconf_cleanup();
ip6_flowlabel_cleanup();
ip6_route_cleanup();
#ifdef CONFIG_PROC_FS
/* Cleanup code parts. */
if6_proc_exit();
ipv6_misc_proc_exit();
udplite6_proc_exit();
raw6_proc_exit();
#endif
ipv6_netfilter_fini();
igmp6_cleanup();
ndisc_cleanup();
ip6_mr_cleanup();
icmpv6_cleanup();
rawv6_exit();
unregister_pernet_subsys(&inet6_net_ops);
#ifdef CONFIG_SYSCTL
ipv6_static_sysctl_unregister();
#endif
proto_unregister(&rawv6_prot);
proto_unregister(&udplitev6_prot);
proto_unregister(&udpv6_prot);
proto_unregister(&tcpv6_prot);
rcu_barrier(); /* Wait for completion of call_rcu()'s */
}
module_exit(inet6_exit);
MODULE_ALIAS_NETPROTO(PF_INET6);
| gpl-2.0 |
haiphamspkt/haiphamkernel | arch/hexagon/kernel/time.c | 256 | 6593 | /*
* Time related functions for Hexagon architecture
*
* Copyright (c) 2010-2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/init.h>
#include <linux/clockchips.h>
#include <linux/clocksource.h>
#include <linux/interrupt.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/ioport.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <asm/timer-regs.h>
#include <asm/hexagon_vm.h>
/*
* For the clocksource we need:
* pcycle frequency (600MHz)
* For the loops_per_jiffy we need:
* thread/cpu frequency (100MHz)
* And for the timer, we need:
* sleep clock rate
*/
cycles_t pcycle_freq_mhz;
cycles_t thread_freq_mhz;
cycles_t sleep_clk_freq;
static struct resource rtos_timer_resources[] = {
{
.start = RTOS_TIMER_REGS_ADDR,
.end = RTOS_TIMER_REGS_ADDR+PAGE_SIZE-1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device rtos_timer_device = {
.name = "rtos_timer",
.id = -1,
.num_resources = ARRAY_SIZE(rtos_timer_resources),
.resource = rtos_timer_resources,
};
/* A lot of this stuff should move into a platform specific section. */
struct adsp_hw_timer_struct {
u32 match; /* Match value */
u32 count;
u32 enable; /* [1] - CLR_ON_MATCH_EN, [0] - EN */
u32 clear; /* one-shot register that clears the count */
};
/* Look for "TCX0" for related constants. */
static __iomem struct adsp_hw_timer_struct *rtos_timer;
static cycle_t timer_get_cycles(struct clocksource *cs)
{
return (cycle_t) __vmgettime();
}
static struct clocksource hexagon_clocksource = {
.name = "pcycles",
.rating = 250,
.read = timer_get_cycles,
.mask = CLOCKSOURCE_MASK(64),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
static int set_next_event(unsigned long delta, struct clock_event_device *evt)
{
/* Assuming the timer will be disabled when we enter here. */
iowrite32(1, &rtos_timer->clear);
iowrite32(0, &rtos_timer->clear);
iowrite32(delta, &rtos_timer->match);
iowrite32(1 << TIMER_ENABLE, &rtos_timer->enable);
return 0;
}
/*
* Sets the mode (periodic, shutdown, oneshot, etc) of a timer.
*/
static void set_mode(enum clock_event_mode mode,
struct clock_event_device *evt)
{
switch (mode) {
case CLOCK_EVT_MODE_SHUTDOWN:
/* XXX implement me */
default:
break;
}
}
#ifdef CONFIG_SMP
/* Broadcast mechanism */
static void broadcast(const struct cpumask *mask)
{
send_ipi(mask, IPI_TIMER);
}
#endif
static struct clock_event_device hexagon_clockevent_dev = {
.name = "clockevent",
.features = CLOCK_EVT_FEAT_ONESHOT,
.rating = 400,
.irq = RTOS_TIMER_INT,
.set_next_event = set_next_event,
.set_mode = set_mode,
#ifdef CONFIG_SMP
.broadcast = broadcast,
#endif
};
#ifdef CONFIG_SMP
static DEFINE_PER_CPU(struct clock_event_device, clock_events);
void setup_percpu_clockdev(void)
{
int cpu = smp_processor_id();
struct clock_event_device *ce_dev = &hexagon_clockevent_dev;
struct clock_event_device *dummy_clock_dev =
&per_cpu(clock_events, cpu);
memcpy(dummy_clock_dev, ce_dev, sizeof(*dummy_clock_dev));
INIT_LIST_HEAD(&dummy_clock_dev->list);
dummy_clock_dev->features = CLOCK_EVT_FEAT_DUMMY;
dummy_clock_dev->cpumask = cpumask_of(cpu);
dummy_clock_dev->mode = CLOCK_EVT_MODE_UNUSED;
clockevents_register_device(dummy_clock_dev);
}
/* Called from smp.c for each CPU's timer ipi call */
void ipi_timer(void)
{
int cpu = smp_processor_id();
struct clock_event_device *ce_dev = &per_cpu(clock_events, cpu);
ce_dev->event_handler(ce_dev);
}
#endif /* CONFIG_SMP */
static irqreturn_t timer_interrupt(int irq, void *devid)
{
struct clock_event_device *ce_dev = &hexagon_clockevent_dev;
iowrite32(0, &rtos_timer->enable);
ce_dev->event_handler(ce_dev);
return IRQ_HANDLED;
}
/* This should also be pulled from devtree */
static struct irqaction rtos_timer_intdesc = {
.handler = timer_interrupt,
.flags = IRQF_TIMER | IRQF_TRIGGER_RISING,
.name = "rtos_timer"
};
/*
* time_init_deferred - called by start_kernel to set up timer/clock source
*
* Install the IRQ handler for the clock, setup timers.
* This is done late, as that way, we can use ioremap().
*
* This runs just before the delay loop is calibrated, and
* is used for delay calibration.
*/
void __init time_init_deferred(void)
{
struct resource *resource = NULL;
struct clock_event_device *ce_dev = &hexagon_clockevent_dev;
struct device_node *dn;
struct resource r;
int err;
ce_dev->cpumask = cpu_all_mask;
if (!resource)
resource = rtos_timer_device.resource;
/* ioremap here means this has to run later, after paging init */
rtos_timer = ioremap(resource->start, resource->end
- resource->start + 1);
if (!rtos_timer) {
release_mem_region(resource->start, resource->end
- resource->start + 1);
}
clocksource_register_khz(&hexagon_clocksource, pcycle_freq_mhz * 1000);
/* Note: the sim generic RTOS clock is apparently really 18750Hz */
/*
* Last arg is some guaranteed seconds for which the conversion will
* work without overflow.
*/
clockevents_calc_mult_shift(ce_dev, sleep_clk_freq, 4);
ce_dev->max_delta_ns = clockevent_delta2ns(0x7fffffff, ce_dev);
ce_dev->min_delta_ns = clockevent_delta2ns(0xf, ce_dev);
#ifdef CONFIG_SMP
setup_percpu_clockdev();
#endif
clockevents_register_device(ce_dev);
setup_irq(ce_dev->irq, &rtos_timer_intdesc);
}
void __init time_init(void)
{
late_time_init = time_init_deferred;
}
/*
* This could become parametric or perhaps even computed at run-time,
* but for now we take the observed simulator jitter.
*/
static long long fudgefactor = 350; /* Maybe lower if kernel optimized. */
void __udelay(unsigned long usecs)
{
unsigned long long start = __vmgettime();
unsigned long long finish = (pcycle_freq_mhz * usecs) - fudgefactor;
while ((__vmgettime() - start) < finish)
cpu_relax(); /* not sure how this improves readability */
}
EXPORT_SYMBOL(__udelay);
| gpl-2.0 |
gengzh0016/kernel_BBxM | drivers/video/bfin-lq035q1-fb.c | 256 | 21457 | /*
* Blackfin LCD Framebuffer driver SHARP LQ035Q1DH02
*
* Copyright 2008-2009 Analog Devices Inc.
* Licensed under the GPL-2 or later.
*/
#define DRIVER_NAME "bfin-lq035q1"
#define pr_fmt(fmt) DRIVER_NAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/fb.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/backlight.h>
#include <linux/lcd.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <asm/blackfin.h>
#include <asm/irq.h>
#include <asm/dma.h>
#include <asm/portmux.h>
#include <asm/gptimers.h>
#include <asm/bfin-lq035q1.h>
#if defined(BF533_FAMILY) || defined(BF538_FAMILY)
#define TIMER_HSYNC_id TIMER1_id
#define TIMER_HSYNCbit TIMER1bit
#define TIMER_HSYNC_STATUS_TRUN TIMER_STATUS_TRUN1
#define TIMER_HSYNC_STATUS_TIMIL TIMER_STATUS_TIMIL1
#define TIMER_HSYNC_STATUS_TOVF TIMER_STATUS_TOVF1
#define TIMER_VSYNC_id TIMER2_id
#define TIMER_VSYNCbit TIMER2bit
#define TIMER_VSYNC_STATUS_TRUN TIMER_STATUS_TRUN2
#define TIMER_VSYNC_STATUS_TIMIL TIMER_STATUS_TIMIL2
#define TIMER_VSYNC_STATUS_TOVF TIMER_STATUS_TOVF2
#else
#define TIMER_HSYNC_id TIMER0_id
#define TIMER_HSYNCbit TIMER0bit
#define TIMER_HSYNC_STATUS_TRUN TIMER_STATUS_TRUN0
#define TIMER_HSYNC_STATUS_TIMIL TIMER_STATUS_TIMIL0
#define TIMER_HSYNC_STATUS_TOVF TIMER_STATUS_TOVF0
#define TIMER_VSYNC_id TIMER1_id
#define TIMER_VSYNCbit TIMER1bit
#define TIMER_VSYNC_STATUS_TRUN TIMER_STATUS_TRUN1
#define TIMER_VSYNC_STATUS_TIMIL TIMER_STATUS_TIMIL1
#define TIMER_VSYNC_STATUS_TOVF TIMER_STATUS_TOVF1
#endif
#define LCD_X_RES 320 /* Horizontal Resolution */
#define LCD_Y_RES 240 /* Vertical Resolution */
#define DMA_BUS_SIZE 16
#define U_LINE 4 /* Blanking Lines */
/* Interface 16/18-bit TFT over an 8-bit wide PPI using a small Programmable Logic Device (CPLD)
* http://blackfin.uclinux.org/gf/project/stamp/frs/?action=FrsReleaseBrowse&frs_package_id=165
*/
#define BFIN_LCD_NBR_PALETTE_ENTRIES 256
#define PPI_TX_MODE 0x2
#define PPI_XFER_TYPE_11 0xC
#define PPI_PORT_CFG_01 0x10
#define PPI_POLS_1 0x8000
#define LQ035_INDEX 0x74
#define LQ035_DATA 0x76
#define LQ035_DRIVER_OUTPUT_CTL 0x1
#define LQ035_SHUT_CTL 0x11
#define LQ035_DRIVER_OUTPUT_MASK (LQ035_LR | LQ035_TB | LQ035_BGR | LQ035_REV)
#define LQ035_DRIVER_OUTPUT_DEFAULT (0x2AEF & ~LQ035_DRIVER_OUTPUT_MASK)
#define LQ035_SHUT (1 << 0) /* Shutdown */
#define LQ035_ON (0 << 0) /* Shutdown */
struct bfin_lq035q1fb_info {
struct fb_info *fb;
struct device *dev;
struct spi_driver spidrv;
struct bfin_lq035q1fb_disp_info *disp_info;
unsigned char *fb_buffer; /* RGB Buffer */
dma_addr_t dma_handle;
int lq035_open_cnt;
int irq;
spinlock_t lock; /* lock */
u32 pseudo_pal[16];
u32 lcd_bpp;
u32 h_actpix;
u32 h_period;
u32 h_pulse;
u32 h_start;
u32 v_lines;
u32 v_pulse;
u32 v_period;
};
static int nocursor;
module_param(nocursor, int, 0644);
MODULE_PARM_DESC(nocursor, "cursor enable/disable");
struct spi_control {
unsigned short mode;
};
static int lq035q1_control(struct spi_device *spi, unsigned char reg, unsigned short value)
{
int ret;
u8 regs[3] = { LQ035_INDEX, 0, 0 };
u8 dat[3] = { LQ035_DATA, 0, 0 };
if (!spi)
return -ENODEV;
regs[2] = reg;
dat[1] = value >> 8;
dat[2] = value & 0xFF;
ret = spi_write(spi, regs, ARRAY_SIZE(regs));
ret |= spi_write(spi, dat, ARRAY_SIZE(dat));
return ret;
}
static int __devinit lq035q1_spidev_probe(struct spi_device *spi)
{
int ret;
struct spi_control *ctl;
struct bfin_lq035q1fb_info *info = container_of(spi->dev.driver,
struct bfin_lq035q1fb_info,
spidrv.driver);
ctl = kzalloc(sizeof(*ctl), GFP_KERNEL);
if (!ctl)
return -ENOMEM;
ctl->mode = (info->disp_info->mode &
LQ035_DRIVER_OUTPUT_MASK) | LQ035_DRIVER_OUTPUT_DEFAULT;
ret = lq035q1_control(spi, LQ035_SHUT_CTL, LQ035_ON);
ret |= lq035q1_control(spi, LQ035_DRIVER_OUTPUT_CTL, ctl->mode);
if (ret) {
kfree(ctl);
return ret;
}
spi_set_drvdata(spi, ctl);
return 0;
}
static int lq035q1_spidev_remove(struct spi_device *spi)
{
return lq035q1_control(spi, LQ035_SHUT_CTL, LQ035_SHUT);
}
#ifdef CONFIG_PM
static int lq035q1_spidev_suspend(struct spi_device *spi, pm_message_t state)
{
return lq035q1_control(spi, LQ035_SHUT_CTL, LQ035_SHUT);
}
static int lq035q1_spidev_resume(struct spi_device *spi)
{
int ret;
struct spi_control *ctl = spi_get_drvdata(spi);
ret = lq035q1_control(spi, LQ035_DRIVER_OUTPUT_CTL, ctl->mode);
if (ret)
return ret;
return lq035q1_control(spi, LQ035_SHUT_CTL, LQ035_ON);
}
#else
# define lq035q1_spidev_suspend NULL
# define lq035q1_spidev_resume NULL
#endif
/* Power down all displays on reboot, poweroff or halt */
static void lq035q1_spidev_shutdown(struct spi_device *spi)
{
lq035q1_control(spi, LQ035_SHUT_CTL, LQ035_SHUT);
}
static int lq035q1_backlight(struct bfin_lq035q1fb_info *info, unsigned arg)
{
if (info->disp_info->use_bl)
gpio_set_value(info->disp_info->gpio_bl, arg);
return 0;
}
static int bfin_lq035q1_calc_timing(struct bfin_lq035q1fb_info *fbi)
{
unsigned long clocks_per_pix, cpld_pipeline_delay_cor;
/*
* Interface 16/18-bit TFT over an 8-bit wide PPI using a small
* Programmable Logic Device (CPLD)
* http://blackfin.uclinux.org/gf/project/stamp/frs/?action=FrsReleaseBrowse&frs_package_id=165
*/
switch (fbi->disp_info->ppi_mode) {
case USE_RGB565_16_BIT_PPI:
fbi->lcd_bpp = 16;
clocks_per_pix = 1;
cpld_pipeline_delay_cor = 0;
break;
case USE_RGB565_8_BIT_PPI:
fbi->lcd_bpp = 16;
clocks_per_pix = 2;
cpld_pipeline_delay_cor = 3;
break;
case USE_RGB888_8_BIT_PPI:
fbi->lcd_bpp = 24;
clocks_per_pix = 3;
cpld_pipeline_delay_cor = 5;
break;
default:
return -EINVAL;
}
/*
* HS and VS timing parameters (all in number of PPI clk ticks)
*/
fbi->h_actpix = (LCD_X_RES * clocks_per_pix); /* active horizontal pixel */
fbi->h_period = (336 * clocks_per_pix); /* HS period */
fbi->h_pulse = (2 * clocks_per_pix); /* HS pulse width */
fbi->h_start = (7 * clocks_per_pix + cpld_pipeline_delay_cor); /* first valid pixel */
fbi->v_lines = (LCD_Y_RES + U_LINE); /* total vertical lines */
fbi->v_pulse = (2 * clocks_per_pix); /* VS pulse width (1-5 H_PERIODs) */
fbi->v_period = (fbi->h_period * fbi->v_lines); /* VS period */
return 0;
}
static void bfin_lq035q1_config_ppi(struct bfin_lq035q1fb_info *fbi)
{
unsigned ppi_pmode;
if (fbi->disp_info->ppi_mode == USE_RGB565_16_BIT_PPI)
ppi_pmode = DLEN_16;
else
ppi_pmode = (DLEN_8 | PACK_EN);
bfin_write_PPI_DELAY(fbi->h_start);
bfin_write_PPI_COUNT(fbi->h_actpix - 1);
bfin_write_PPI_FRAME(fbi->v_lines);
bfin_write_PPI_CONTROL(PPI_TX_MODE | /* output mode , PORT_DIR */
PPI_XFER_TYPE_11 | /* sync mode XFR_TYPE */
PPI_PORT_CFG_01 | /* two frame sync PORT_CFG */
ppi_pmode | /* 8/16 bit data length / PACK_EN? */
PPI_POLS_1); /* faling edge syncs POLS */
}
static inline void bfin_lq035q1_disable_ppi(void)
{
bfin_write_PPI_CONTROL(bfin_read_PPI_CONTROL() & ~PORT_EN);
}
static inline void bfin_lq035q1_enable_ppi(void)
{
bfin_write_PPI_CONTROL(bfin_read_PPI_CONTROL() | PORT_EN);
}
static void bfin_lq035q1_start_timers(void)
{
enable_gptimers(TIMER_VSYNCbit | TIMER_HSYNCbit);
}
static void bfin_lq035q1_stop_timers(void)
{
disable_gptimers(TIMER_HSYNCbit | TIMER_VSYNCbit);
set_gptimer_status(0, TIMER_HSYNC_STATUS_TRUN | TIMER_VSYNC_STATUS_TRUN |
TIMER_HSYNC_STATUS_TIMIL | TIMER_VSYNC_STATUS_TIMIL |
TIMER_HSYNC_STATUS_TOVF | TIMER_VSYNC_STATUS_TOVF);
}
static void bfin_lq035q1_init_timers(struct bfin_lq035q1fb_info *fbi)
{
bfin_lq035q1_stop_timers();
set_gptimer_period(TIMER_HSYNC_id, fbi->h_period);
set_gptimer_pwidth(TIMER_HSYNC_id, fbi->h_pulse);
set_gptimer_config(TIMER_HSYNC_id, TIMER_MODE_PWM | TIMER_PERIOD_CNT |
TIMER_TIN_SEL | TIMER_CLK_SEL|
TIMER_EMU_RUN);
set_gptimer_period(TIMER_VSYNC_id, fbi->v_period);
set_gptimer_pwidth(TIMER_VSYNC_id, fbi->v_pulse);
set_gptimer_config(TIMER_VSYNC_id, TIMER_MODE_PWM | TIMER_PERIOD_CNT |
TIMER_TIN_SEL | TIMER_CLK_SEL |
TIMER_EMU_RUN);
}
static void bfin_lq035q1_config_dma(struct bfin_lq035q1fb_info *fbi)
{
set_dma_config(CH_PPI,
set_bfin_dma_config(DIR_READ, DMA_FLOW_AUTO,
INTR_DISABLE, DIMENSION_2D,
DATA_SIZE_16,
DMA_NOSYNC_KEEP_DMA_BUF));
set_dma_x_count(CH_PPI, (LCD_X_RES * fbi->lcd_bpp) / DMA_BUS_SIZE);
set_dma_x_modify(CH_PPI, DMA_BUS_SIZE / 8);
set_dma_y_count(CH_PPI, fbi->v_lines);
set_dma_y_modify(CH_PPI, DMA_BUS_SIZE / 8);
set_dma_start_addr(CH_PPI, (unsigned long)fbi->fb_buffer);
}
static const u16 ppi0_req_16[] = {P_PPI0_CLK, P_PPI0_FS1, P_PPI0_FS2,
P_PPI0_D0, P_PPI0_D1, P_PPI0_D2,
P_PPI0_D3, P_PPI0_D4, P_PPI0_D5,
P_PPI0_D6, P_PPI0_D7, P_PPI0_D8,
P_PPI0_D9, P_PPI0_D10, P_PPI0_D11,
P_PPI0_D12, P_PPI0_D13, P_PPI0_D14,
P_PPI0_D15, 0};
static const u16 ppi0_req_8[] = {P_PPI0_CLK, P_PPI0_FS1, P_PPI0_FS2,
P_PPI0_D0, P_PPI0_D1, P_PPI0_D2,
P_PPI0_D3, P_PPI0_D4, P_PPI0_D5,
P_PPI0_D6, P_PPI0_D7, 0};
static inline void bfin_lq035q1_free_ports(unsigned ppi16)
{
if (ppi16)
peripheral_free_list(ppi0_req_16);
else
peripheral_free_list(ppi0_req_8);
if (ANOMALY_05000400)
gpio_free(P_IDENT(P_PPI0_FS3));
}
static int __devinit bfin_lq035q1_request_ports(struct platform_device *pdev,
unsigned ppi16)
{
int ret;
/* ANOMALY_05000400 - PPI Does Not Start Properly In Specific Mode:
* Drive PPI_FS3 Low
*/
if (ANOMALY_05000400) {
int ret = gpio_request(P_IDENT(P_PPI0_FS3), "PPI_FS3");
if (ret)
return ret;
gpio_direction_output(P_IDENT(P_PPI0_FS3), 0);
}
if (ppi16)
ret = peripheral_request_list(ppi0_req_16, DRIVER_NAME);
else
ret = peripheral_request_list(ppi0_req_8, DRIVER_NAME);
if (ret) {
dev_err(&pdev->dev, "requesting peripherals failed\n");
return -EFAULT;
}
return 0;
}
static int bfin_lq035q1_fb_open(struct fb_info *info, int user)
{
struct bfin_lq035q1fb_info *fbi = info->par;
spin_lock(&fbi->lock);
fbi->lq035_open_cnt++;
if (fbi->lq035_open_cnt <= 1) {
bfin_lq035q1_disable_ppi();
SSYNC();
bfin_lq035q1_config_dma(fbi);
bfin_lq035q1_config_ppi(fbi);
bfin_lq035q1_init_timers(fbi);
/* start dma */
enable_dma(CH_PPI);
bfin_lq035q1_enable_ppi();
bfin_lq035q1_start_timers();
lq035q1_backlight(fbi, 1);
}
spin_unlock(&fbi->lock);
return 0;
}
static int bfin_lq035q1_fb_release(struct fb_info *info, int user)
{
struct bfin_lq035q1fb_info *fbi = info->par;
spin_lock(&fbi->lock);
fbi->lq035_open_cnt--;
if (fbi->lq035_open_cnt <= 0) {
lq035q1_backlight(fbi, 0);
bfin_lq035q1_disable_ppi();
SSYNC();
disable_dma(CH_PPI);
bfin_lq035q1_stop_timers();
}
spin_unlock(&fbi->lock);
return 0;
}
static int bfin_lq035q1_fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct bfin_lq035q1fb_info *fbi = info->par;
if (var->bits_per_pixel == fbi->lcd_bpp) {
var->red.offset = info->var.red.offset;
var->green.offset = info->var.green.offset;
var->blue.offset = info->var.blue.offset;
var->red.length = info->var.red.length;
var->green.length = info->var.green.length;
var->blue.length = info->var.blue.length;
var->transp.offset = 0;
var->transp.length = 0;
var->transp.msb_right = 0;
var->red.msb_right = 0;
var->green.msb_right = 0;
var->blue.msb_right = 0;
} else {
pr_debug("%s: depth not supported: %u BPP\n", __func__,
var->bits_per_pixel);
return -EINVAL;
}
if (info->var.xres != var->xres || info->var.yres != var->yres ||
info->var.xres_virtual != var->xres_virtual ||
info->var.yres_virtual != var->yres_virtual) {
pr_debug("%s: Resolution not supported: X%u x Y%u \n",
__func__, var->xres, var->yres);
return -EINVAL;
}
/*
* Memory limit
*/
if ((info->fix.line_length * var->yres_virtual) > info->fix.smem_len) {
pr_debug("%s: Memory Limit requested yres_virtual = %u\n",
__func__, var->yres_virtual);
return -ENOMEM;
}
return 0;
}
int bfin_lq035q1_fb_cursor(struct fb_info *info, struct fb_cursor *cursor)
{
if (nocursor)
return 0;
else
return -EINVAL; /* just to force soft_cursor() call */
}
static int bfin_lq035q1_fb_setcolreg(u_int regno, u_int red, u_int green,
u_int blue, u_int transp,
struct fb_info *info)
{
if (regno >= BFIN_LCD_NBR_PALETTE_ENTRIES)
return -EINVAL;
if (info->var.grayscale) {
/* grayscale = 0.30*R + 0.59*G + 0.11*B */
red = green = blue = (red * 77 + green * 151 + blue * 28) >> 8;
}
if (info->fix.visual == FB_VISUAL_TRUECOLOR) {
u32 value;
/* Place color in the pseudopalette */
if (regno > 16)
return -EINVAL;
red >>= (16 - info->var.red.length);
green >>= (16 - info->var.green.length);
blue >>= (16 - info->var.blue.length);
value = (red << info->var.red.offset) |
(green << info->var.green.offset) |
(blue << info->var.blue.offset);
value &= 0xFFFFFF;
((u32 *) (info->pseudo_palette))[regno] = value;
}
return 0;
}
static struct fb_ops bfin_lq035q1_fb_ops = {
.owner = THIS_MODULE,
.fb_open = bfin_lq035q1_fb_open,
.fb_release = bfin_lq035q1_fb_release,
.fb_check_var = bfin_lq035q1_fb_check_var,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_cursor = bfin_lq035q1_fb_cursor,
.fb_setcolreg = bfin_lq035q1_fb_setcolreg,
};
static irqreturn_t bfin_lq035q1_irq_error(int irq, void *dev_id)
{
/*struct bfin_lq035q1fb_info *info = (struct bfin_lq035q1fb_info *)dev_id;*/
u16 status = bfin_read_PPI_STATUS();
bfin_write_PPI_STATUS(-1);
if (status) {
bfin_lq035q1_disable_ppi();
disable_dma(CH_PPI);
/* start dma */
enable_dma(CH_PPI);
bfin_lq035q1_enable_ppi();
bfin_write_PPI_STATUS(-1);
}
return IRQ_HANDLED;
}
static int __devinit bfin_lq035q1_probe(struct platform_device *pdev)
{
struct bfin_lq035q1fb_info *info;
struct fb_info *fbinfo;
u32 active_video_mem_offset;
int ret;
ret = request_dma(CH_PPI, DRIVER_NAME"_CH_PPI");
if (ret < 0) {
dev_err(&pdev->dev, "PPI DMA unavailable\n");
goto out1;
}
fbinfo = framebuffer_alloc(sizeof(*info), &pdev->dev);
if (!fbinfo) {
ret = -ENOMEM;
goto out2;
}
info = fbinfo->par;
info->fb = fbinfo;
info->dev = &pdev->dev;
info->disp_info = pdev->dev.platform_data;
platform_set_drvdata(pdev, fbinfo);
ret = bfin_lq035q1_calc_timing(info);
if (ret < 0) {
dev_err(&pdev->dev, "Failed PPI Mode\n");
goto out3;
}
strcpy(fbinfo->fix.id, DRIVER_NAME);
fbinfo->fix.type = FB_TYPE_PACKED_PIXELS;
fbinfo->fix.type_aux = 0;
fbinfo->fix.xpanstep = 0;
fbinfo->fix.ypanstep = 0;
fbinfo->fix.ywrapstep = 0;
fbinfo->fix.accel = FB_ACCEL_NONE;
fbinfo->fix.visual = FB_VISUAL_TRUECOLOR;
fbinfo->var.nonstd = 0;
fbinfo->var.activate = FB_ACTIVATE_NOW;
fbinfo->var.height = -1;
fbinfo->var.width = -1;
fbinfo->var.accel_flags = 0;
fbinfo->var.vmode = FB_VMODE_NONINTERLACED;
fbinfo->var.xres = LCD_X_RES;
fbinfo->var.xres_virtual = LCD_X_RES;
fbinfo->var.yres = LCD_Y_RES;
fbinfo->var.yres_virtual = LCD_Y_RES;
fbinfo->var.bits_per_pixel = info->lcd_bpp;
if (info->disp_info->mode & LQ035_BGR) {
if (info->lcd_bpp == 24) {
fbinfo->var.red.offset = 0;
fbinfo->var.green.offset = 8;
fbinfo->var.blue.offset = 16;
} else {
fbinfo->var.red.offset = 0;
fbinfo->var.green.offset = 5;
fbinfo->var.blue.offset = 11;
}
} else {
if (info->lcd_bpp == 24) {
fbinfo->var.red.offset = 16;
fbinfo->var.green.offset = 8;
fbinfo->var.blue.offset = 0;
} else {
fbinfo->var.red.offset = 11;
fbinfo->var.green.offset = 5;
fbinfo->var.blue.offset = 0;
}
}
fbinfo->var.transp.offset = 0;
if (info->lcd_bpp == 24) {
fbinfo->var.red.length = 8;
fbinfo->var.green.length = 8;
fbinfo->var.blue.length = 8;
} else {
fbinfo->var.red.length = 5;
fbinfo->var.green.length = 6;
fbinfo->var.blue.length = 5;
}
fbinfo->var.transp.length = 0;
active_video_mem_offset = ((U_LINE / 2) * LCD_X_RES * (info->lcd_bpp / 8));
fbinfo->fix.smem_len = LCD_X_RES * LCD_Y_RES * info->lcd_bpp / 8
+ active_video_mem_offset;
fbinfo->fix.line_length = fbinfo->var.xres_virtual *
fbinfo->var.bits_per_pixel / 8;
fbinfo->fbops = &bfin_lq035q1_fb_ops;
fbinfo->flags = FBINFO_FLAG_DEFAULT;
info->fb_buffer =
dma_alloc_coherent(NULL, fbinfo->fix.smem_len, &info->dma_handle,
GFP_KERNEL);
if (NULL == info->fb_buffer) {
dev_err(&pdev->dev, "couldn't allocate dma buffer\n");
ret = -ENOMEM;
goto out3;
}
fbinfo->screen_base = (void *)info->fb_buffer + active_video_mem_offset;
fbinfo->fix.smem_start = (int)info->fb_buffer + active_video_mem_offset;
fbinfo->fbops = &bfin_lq035q1_fb_ops;
fbinfo->pseudo_palette = &info->pseudo_pal;
ret = fb_alloc_cmap(&fbinfo->cmap, BFIN_LCD_NBR_PALETTE_ENTRIES, 0);
if (ret < 0) {
dev_err(&pdev->dev, "failed to allocate colormap (%d entries)\n",
BFIN_LCD_NBR_PALETTE_ENTRIES);
goto out4;
}
ret = bfin_lq035q1_request_ports(pdev,
info->disp_info->ppi_mode == USE_RGB565_16_BIT_PPI);
if (ret) {
dev_err(&pdev->dev, "couldn't request gpio port\n");
goto out6;
}
info->irq = platform_get_irq(pdev, 0);
if (info->irq < 0) {
ret = -EINVAL;
goto out7;
}
ret = request_irq(info->irq, bfin_lq035q1_irq_error, 0,
DRIVER_NAME" PPI ERROR", info);
if (ret < 0) {
dev_err(&pdev->dev, "unable to request PPI ERROR IRQ\n");
goto out7;
}
info->spidrv.driver.name = DRIVER_NAME"-spi";
info->spidrv.probe = lq035q1_spidev_probe;
info->spidrv.remove = __devexit_p(lq035q1_spidev_remove);
info->spidrv.shutdown = lq035q1_spidev_shutdown;
info->spidrv.suspend = lq035q1_spidev_suspend;
info->spidrv.resume = lq035q1_spidev_resume;
ret = spi_register_driver(&info->spidrv);
if (ret < 0) {
dev_err(&pdev->dev, "couldn't register SPI Interface\n");
goto out8;
}
if (info->disp_info->use_bl) {
ret = gpio_request(info->disp_info->gpio_bl, "LQ035 Backlight");
if (ret) {
dev_err(&pdev->dev, "failed to request GPIO %d\n",
info->disp_info->gpio_bl);
goto out9;
}
gpio_direction_output(info->disp_info->gpio_bl, 0);
}
ret = register_framebuffer(fbinfo);
if (ret < 0) {
dev_err(&pdev->dev, "unable to register framebuffer\n");
goto out10;
}
dev_info(&pdev->dev, "%dx%d %d-bit RGB FrameBuffer initialized\n",
LCD_X_RES, LCD_Y_RES, info->lcd_bpp);
return 0;
out10:
if (info->disp_info->use_bl)
gpio_free(info->disp_info->gpio_bl);
out9:
spi_unregister_driver(&info->spidrv);
out8:
free_irq(info->irq, info);
out7:
bfin_lq035q1_free_ports(info->disp_info->ppi_mode ==
USE_RGB565_16_BIT_PPI);
out6:
fb_dealloc_cmap(&fbinfo->cmap);
out4:
dma_free_coherent(NULL, fbinfo->fix.smem_len, info->fb_buffer,
info->dma_handle);
out3:
framebuffer_release(fbinfo);
out2:
free_dma(CH_PPI);
out1:
platform_set_drvdata(pdev, NULL);
return ret;
}
static int __devexit bfin_lq035q1_remove(struct platform_device *pdev)
{
struct fb_info *fbinfo = platform_get_drvdata(pdev);
struct bfin_lq035q1fb_info *info = fbinfo->par;
if (info->disp_info->use_bl)
gpio_free(info->disp_info->gpio_bl);
spi_unregister_driver(&info->spidrv);
unregister_framebuffer(fbinfo);
free_dma(CH_PPI);
free_irq(info->irq, info);
if (info->fb_buffer != NULL)
dma_free_coherent(NULL, fbinfo->fix.smem_len, info->fb_buffer,
info->dma_handle);
fb_dealloc_cmap(&fbinfo->cmap);
bfin_lq035q1_free_ports(info->disp_info->ppi_mode ==
USE_RGB565_16_BIT_PPI);
platform_set_drvdata(pdev, NULL);
framebuffer_release(fbinfo);
dev_info(&pdev->dev, "unregistered LCD driver\n");
return 0;
}
#ifdef CONFIG_PM
static int bfin_lq035q1_suspend(struct device *dev)
{
struct fb_info *fbinfo = dev_get_drvdata(dev);
struct bfin_lq035q1fb_info *info = fbinfo->par;
if (info->lq035_open_cnt) {
lq035q1_backlight(info, 0);
bfin_lq035q1_disable_ppi();
SSYNC();
disable_dma(CH_PPI);
bfin_lq035q1_stop_timers();
bfin_write_PPI_STATUS(-1);
}
return 0;
}
static int bfin_lq035q1_resume(struct device *dev)
{
struct fb_info *fbinfo = dev_get_drvdata(dev);
struct bfin_lq035q1fb_info *info = fbinfo->par;
if (info->lq035_open_cnt) {
bfin_lq035q1_disable_ppi();
SSYNC();
bfin_lq035q1_config_dma(info);
bfin_lq035q1_config_ppi(info);
bfin_lq035q1_init_timers(info);
/* start dma */
enable_dma(CH_PPI);
bfin_lq035q1_enable_ppi();
bfin_lq035q1_start_timers();
lq035q1_backlight(info, 1);
}
return 0;
}
static struct dev_pm_ops bfin_lq035q1_dev_pm_ops = {
.suspend = bfin_lq035q1_suspend,
.resume = bfin_lq035q1_resume,
};
#endif
static struct platform_driver bfin_lq035q1_driver = {
.probe = bfin_lq035q1_probe,
.remove = __devexit_p(bfin_lq035q1_remove),
.driver = {
.name = DRIVER_NAME,
#ifdef CONFIG_PM
.pm = &bfin_lq035q1_dev_pm_ops,
#endif
},
};
static int __init bfin_lq035q1_driver_init(void)
{
return platform_driver_register(&bfin_lq035q1_driver);
}
module_init(bfin_lq035q1_driver_init);
static void __exit bfin_lq035q1_driver_cleanup(void)
{
platform_driver_unregister(&bfin_lq035q1_driver);
}
module_exit(bfin_lq035q1_driver_cleanup);
MODULE_DESCRIPTION("Blackfin TFT LCD Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
kbc-developers/kernel_samsung_exynos4412 | arch/arm/mach-s5pv210/reserve_mem-s5pv210.c | 512 | 2308 | /* linux/arch/arm/mach-s5pv210/reserve_mem-s5pv210.c
*
* Copyright (c) 2011 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* reserve_mem helper functions for S5PV210
*
* 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/mm.h>
#include <linux/swap.h>
#include <asm/setup.h>
#include <linux/io.h>
#include <mach/memory.h>
#include <plat/media.h>
#include <mach/media.h>
struct s5p_media_device media_devs[] = {
#ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_MFC0
{
.id = S5P_MDEV_MFC,
.name = "mfc",
.bank = 0,
.memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_MFC0 * SZ_1K,
.paddr = 0,
},
#endif
#ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_MFC1
{
.id = S5P_MDEV_MFC,
.name = "mfc",
.bank = 1,
.memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_MFC1 * SZ_1K,
.paddr = 0,
},
#endif
#ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMD
{
.id = S5P_MDEV_FIMD,
.name = "fimd",
.bank = 1,
.memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMD * SZ_1K,
.paddr = 0,
},
#endif
#ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC0
{
.id = S5P_MDEV_FIMC0,
.name = "fimc0",
.bank = 1,
.memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC0 * SZ_1K,
.paddr = 0,
},
#endif
#ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC1
{
.id = S5P_MDEV_FIMC1,
.name = "fimc1",
.bank = 1,
.memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC1 * SZ_1K,
.paddr = 0,
},
#endif
#ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC2
{
.id = S5P_MDEV_FIMC2,
.name = "fimc2",
.bank = 1,
.memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC2 * SZ_1K,
.paddr = 0,
},
#endif
#ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMG2D
{
.id = S5P_MDEV_FIMG2D,
.name = "fimg2d",
.bank = 0,
.memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMG2D * SZ_1K,
.paddr = 0,
},
#endif
#ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_JPEG
{
.id = S5P_MDEV_JPEG,
.name = "jpeg",
.bank = 0,
.memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_JPEG * SZ_1K,
.paddr = 0,
},
#endif
#ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_TEXSTREAM
{
.id = S5P_MDEV_TEXSTREAM,
.name = "texstream",
.bank = 1,
.memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_TEXSTREAM * SZ_1K,
.paddr = 0,
},
#endif
};
int nr_media_devs = (sizeof(media_devs) / sizeof(media_devs[0]));
| gpl-2.0 |
xc-racer99/blastoff_kernel_samsung_galaxys4g | drivers/usb/host/fhci-hcd.c | 768 | 19716 | /*
* Freescale QUICC Engine USB Host Controller Driver
*
* Copyright (c) Freescale Semicondutor, Inc. 2006.
* Shlomi Gridish <gridish@freescale.com>
* Jerry Huang <Chang-Ming.Huang@freescale.com>
* Copyright (c) Logic Product Development, Inc. 2007
* Peter Barada <peterb@logicpd.com>
* Copyright (c) MontaVista Software, Inc. 2008.
* Anton Vorontsov <avorontsov@ru.mvista.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include <linux/of_platform.h>
#include <linux/of_gpio.h>
#include <linux/slab.h>
#include <asm/qe.h>
#include <asm/fsl_gtm.h>
#include "fhci.h"
void fhci_start_sof_timer(struct fhci_hcd *fhci)
{
fhci_dbg(fhci, "-> %s\n", __func__);
/* clear frame_n */
out_be16(&fhci->pram->frame_num, 0);
out_be16(&fhci->regs->usb_sof_tmr, 0);
setbits8(&fhci->regs->usb_mod, USB_MODE_SFTE);
fhci_dbg(fhci, "<- %s\n", __func__);
}
void fhci_stop_sof_timer(struct fhci_hcd *fhci)
{
fhci_dbg(fhci, "-> %s\n", __func__);
clrbits8(&fhci->regs->usb_mod, USB_MODE_SFTE);
gtm_stop_timer16(fhci->timer);
fhci_dbg(fhci, "<- %s\n", __func__);
}
u16 fhci_get_sof_timer_count(struct fhci_usb *usb)
{
return be16_to_cpu(in_be16(&usb->fhci->regs->usb_sof_tmr) / 12);
}
/* initialize the endpoint zero */
static u32 endpoint_zero_init(struct fhci_usb *usb,
enum fhci_mem_alloc data_mem,
u32 ring_len)
{
u32 rc;
rc = fhci_create_ep(usb, data_mem, ring_len);
if (rc)
return rc;
/* inilialize endpoint registers */
fhci_init_ep_registers(usb, usb->ep0, data_mem);
return 0;
}
/* enable the USB interrupts */
void fhci_usb_enable_interrupt(struct fhci_usb *usb)
{
struct fhci_hcd *fhci = usb->fhci;
if (usb->intr_nesting_cnt == 1) {
/* initialize the USB interrupt */
enable_irq(fhci_to_hcd(fhci)->irq);
/* initialize the event register and mask register */
out_be16(&usb->fhci->regs->usb_event, 0xffff);
out_be16(&usb->fhci->regs->usb_mask, usb->saved_msk);
/* enable the timer interrupts */
enable_irq(fhci->timer->irq);
} else if (usb->intr_nesting_cnt > 1)
fhci_info(fhci, "unbalanced USB interrupts nesting\n");
usb->intr_nesting_cnt--;
}
/* diable the usb interrupt */
void fhci_usb_disable_interrupt(struct fhci_usb *usb)
{
struct fhci_hcd *fhci = usb->fhci;
if (usb->intr_nesting_cnt == 0) {
/* diable the timer interrupt */
disable_irq_nosync(fhci->timer->irq);
/* disable the usb interrupt */
disable_irq_nosync(fhci_to_hcd(fhci)->irq);
out_be16(&usb->fhci->regs->usb_mask, 0);
}
usb->intr_nesting_cnt++;
}
/* enable the USB controller */
static u32 fhci_usb_enable(struct fhci_hcd *fhci)
{
struct fhci_usb *usb = fhci->usb_lld;
out_be16(&usb->fhci->regs->usb_event, 0xffff);
out_be16(&usb->fhci->regs->usb_mask, usb->saved_msk);
setbits8(&usb->fhci->regs->usb_mod, USB_MODE_EN);
mdelay(100);
return 0;
}
/* disable the USB controller */
static u32 fhci_usb_disable(struct fhci_hcd *fhci)
{
struct fhci_usb *usb = fhci->usb_lld;
fhci_usb_disable_interrupt(usb);
fhci_port_disable(fhci);
/* disable the usb controller */
if (usb->port_status == FHCI_PORT_FULL ||
usb->port_status == FHCI_PORT_LOW)
fhci_device_disconnected_interrupt(fhci);
clrbits8(&usb->fhci->regs->usb_mod, USB_MODE_EN);
return 0;
}
/* check the bus state by polling the QE bit on the IO ports */
int fhci_ioports_check_bus_state(struct fhci_hcd *fhci)
{
u8 bits = 0;
/* check USBOE,if transmitting,exit */
if (!gpio_get_value(fhci->gpios[GPIO_USBOE]))
return -1;
/* check USBRP */
if (gpio_get_value(fhci->gpios[GPIO_USBRP]))
bits |= 0x2;
/* check USBRN */
if (gpio_get_value(fhci->gpios[GPIO_USBRN]))
bits |= 0x1;
return bits;
}
static void fhci_mem_free(struct fhci_hcd *fhci)
{
struct ed *ed;
struct ed *next_ed;
struct td *td;
struct td *next_td;
list_for_each_entry_safe(ed, next_ed, &fhci->empty_eds, node) {
list_del(&ed->node);
kfree(ed);
}
list_for_each_entry_safe(td, next_td, &fhci->empty_tds, node) {
list_del(&td->node);
kfree(td);
}
kfree(fhci->vroot_hub);
fhci->vroot_hub = NULL;
kfree(fhci->hc_list);
fhci->hc_list = NULL;
}
static int fhci_mem_init(struct fhci_hcd *fhci)
{
int i;
fhci->hc_list = kzalloc(sizeof(*fhci->hc_list), GFP_KERNEL);
if (!fhci->hc_list)
goto err;
INIT_LIST_HEAD(&fhci->hc_list->ctrl_list);
INIT_LIST_HEAD(&fhci->hc_list->bulk_list);
INIT_LIST_HEAD(&fhci->hc_list->iso_list);
INIT_LIST_HEAD(&fhci->hc_list->intr_list);
INIT_LIST_HEAD(&fhci->hc_list->done_list);
fhci->vroot_hub = kzalloc(sizeof(*fhci->vroot_hub), GFP_KERNEL);
if (!fhci->vroot_hub)
goto err;
INIT_LIST_HEAD(&fhci->empty_eds);
INIT_LIST_HEAD(&fhci->empty_tds);
/* initialize work queue to handle done list */
fhci_tasklet.data = (unsigned long)fhci;
fhci->process_done_task = &fhci_tasklet;
for (i = 0; i < MAX_TDS; i++) {
struct td *td;
td = kmalloc(sizeof(*td), GFP_KERNEL);
if (!td)
goto err;
fhci_recycle_empty_td(fhci, td);
}
for (i = 0; i < MAX_EDS; i++) {
struct ed *ed;
ed = kmalloc(sizeof(*ed), GFP_KERNEL);
if (!ed)
goto err;
fhci_recycle_empty_ed(fhci, ed);
}
fhci->active_urbs = 0;
return 0;
err:
fhci_mem_free(fhci);
return -ENOMEM;
}
/* destroy the fhci_usb structure */
static void fhci_usb_free(void *lld)
{
struct fhci_usb *usb = lld;
struct fhci_hcd *fhci;
if (usb) {
fhci = usb->fhci;
fhci_config_transceiver(fhci, FHCI_PORT_POWER_OFF);
fhci_ep0_free(usb);
kfree(usb->actual_frame);
kfree(usb);
}
}
/* initialize the USB */
static int fhci_usb_init(struct fhci_hcd *fhci)
{
struct fhci_usb *usb = fhci->usb_lld;
memset_io(usb->fhci->pram, 0, FHCI_PRAM_SIZE);
usb->port_status = FHCI_PORT_DISABLED;
usb->max_frame_usage = FRAME_TIME_USAGE;
usb->sw_transaction_time = SW_FIX_TIME_BETWEEN_TRANSACTION;
usb->actual_frame = kzalloc(sizeof(*usb->actual_frame), GFP_KERNEL);
if (!usb->actual_frame) {
fhci_usb_free(usb);
return -ENOMEM;
}
INIT_LIST_HEAD(&usb->actual_frame->tds_list);
/* initializing registers on chip, clear frame number */
out_be16(&fhci->pram->frame_num, 0);
/* clear rx state */
out_be32(&fhci->pram->rx_state, 0);
/* set mask register */
usb->saved_msk = (USB_E_TXB_MASK |
USB_E_TXE1_MASK |
USB_E_IDLE_MASK |
USB_E_RESET_MASK | USB_E_SFT_MASK | USB_E_MSF_MASK);
out_8(&usb->fhci->regs->usb_mod, USB_MODE_HOST | USB_MODE_EN);
/* clearing the mask register */
out_be16(&usb->fhci->regs->usb_mask, 0);
/* initialing the event register */
out_be16(&usb->fhci->regs->usb_event, 0xffff);
if (endpoint_zero_init(usb, DEFAULT_DATA_MEM, DEFAULT_RING_LEN) != 0) {
fhci_usb_free(usb);
return -EINVAL;
}
return 0;
}
/* initialize the fhci_usb struct and the corresponding data staruct */
static struct fhci_usb *fhci_create_lld(struct fhci_hcd *fhci)
{
struct fhci_usb *usb;
/* allocate memory for SCC data structure */
usb = kzalloc(sizeof(*usb), GFP_KERNEL);
if (!usb) {
fhci_err(fhci, "no memory for SCC data struct\n");
return NULL;
}
usb->fhci = fhci;
usb->hc_list = fhci->hc_list;
usb->vroot_hub = fhci->vroot_hub;
usb->transfer_confirm = fhci_transfer_confirm_callback;
return usb;
}
static int fhci_start(struct usb_hcd *hcd)
{
int ret;
struct fhci_hcd *fhci = hcd_to_fhci(hcd);
ret = fhci_mem_init(fhci);
if (ret) {
fhci_err(fhci, "failed to allocate memory\n");
goto err;
}
fhci->usb_lld = fhci_create_lld(fhci);
if (!fhci->usb_lld) {
fhci_err(fhci, "low level driver config failed\n");
ret = -ENOMEM;
goto err;
}
ret = fhci_usb_init(fhci);
if (ret) {
fhci_err(fhci, "low level driver initialize failed\n");
goto err;
}
spin_lock_init(&fhci->lock);
/* connect the virtual root hub */
fhci->vroot_hub->dev_num = 1; /* this field may be needed to fix */
fhci->vroot_hub->hub.wHubStatus = 0;
fhci->vroot_hub->hub.wHubChange = 0;
fhci->vroot_hub->port.wPortStatus = 0;
fhci->vroot_hub->port.wPortChange = 0;
hcd->state = HC_STATE_RUNNING;
/*
* From here on, khubd concurrently accesses the root
* hub; drivers will be talking to enumerated devices.
* (On restart paths, khubd already knows about the root
* hub and could find work as soon as we wrote FLAG_CF.)
*
* Before this point the HC was idle/ready. After, khubd
* and device drivers may start it running.
*/
fhci_usb_enable(fhci);
return 0;
err:
fhci_mem_free(fhci);
return ret;
}
static void fhci_stop(struct usb_hcd *hcd)
{
struct fhci_hcd *fhci = hcd_to_fhci(hcd);
fhci_usb_disable_interrupt(fhci->usb_lld);
fhci_usb_disable(fhci);
fhci_usb_free(fhci->usb_lld);
fhci->usb_lld = NULL;
fhci_mem_free(fhci);
}
static int fhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb,
gfp_t mem_flags)
{
struct fhci_hcd *fhci = hcd_to_fhci(hcd);
u32 pipe = urb->pipe;
int ret;
int i;
int size = 0;
struct urb_priv *urb_priv;
unsigned long flags;
switch (usb_pipetype(pipe)) {
case PIPE_CONTROL:
/* 1 td fro setup,1 for ack */
size = 2;
case PIPE_BULK:
/* one td for every 4096 bytes(can be upto 8k) */
size += urb->transfer_buffer_length / 4096;
/* ...add for any remaining bytes... */
if ((urb->transfer_buffer_length % 4096) != 0)
size++;
/* ..and maybe a zero length packet to wrap it up */
if (size == 0)
size++;
else if ((urb->transfer_flags & URB_ZERO_PACKET) != 0
&& (urb->transfer_buffer_length
% usb_maxpacket(urb->dev, pipe,
usb_pipeout(pipe))) != 0)
size++;
break;
case PIPE_ISOCHRONOUS:
size = urb->number_of_packets;
if (size <= 0)
return -EINVAL;
for (i = 0; i < urb->number_of_packets; i++) {
urb->iso_frame_desc[i].actual_length = 0;
urb->iso_frame_desc[i].status = (u32) (-EXDEV);
}
break;
case PIPE_INTERRUPT:
size = 1;
}
/* allocate the private part of the URB */
urb_priv = kzalloc(sizeof(*urb_priv), mem_flags);
if (!urb_priv)
return -ENOMEM;
/* allocate the private part of the URB */
urb_priv->tds = kcalloc(size, sizeof(*urb_priv->tds), mem_flags);
if (!urb_priv->tds) {
kfree(urb_priv);
return -ENOMEM;
}
spin_lock_irqsave(&fhci->lock, flags);
ret = usb_hcd_link_urb_to_ep(hcd, urb);
if (ret)
goto err;
/* fill the private part of the URB */
urb_priv->num_of_tds = size;
urb->status = -EINPROGRESS;
urb->actual_length = 0;
urb->error_count = 0;
urb->hcpriv = urb_priv;
fhci_queue_urb(fhci, urb);
err:
if (ret) {
kfree(urb_priv->tds);
kfree(urb_priv);
}
spin_unlock_irqrestore(&fhci->lock, flags);
return ret;
}
/* dequeue FHCI URB */
static int fhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
{
struct fhci_hcd *fhci = hcd_to_fhci(hcd);
struct fhci_usb *usb = fhci->usb_lld;
int ret = -EINVAL;
unsigned long flags;
if (!urb || !urb->dev || !urb->dev->bus)
goto out;
spin_lock_irqsave(&fhci->lock, flags);
ret = usb_hcd_check_unlink_urb(hcd, urb, status);
if (ret)
goto out2;
if (usb->port_status != FHCI_PORT_DISABLED) {
struct urb_priv *urb_priv;
/*
* flag the urb's data for deletion in some upcoming
* SF interrupt's delete list processing
*/
urb_priv = urb->hcpriv;
if (!urb_priv || (urb_priv->state == URB_DEL))
goto out2;
urb_priv->state = URB_DEL;
/* already pending? */
urb_priv->ed->state = FHCI_ED_URB_DEL;
} else {
fhci_urb_complete_free(fhci, urb);
}
out2:
spin_unlock_irqrestore(&fhci->lock, flags);
out:
return ret;
}
static void fhci_endpoint_disable(struct usb_hcd *hcd,
struct usb_host_endpoint *ep)
{
struct fhci_hcd *fhci;
struct ed *ed;
unsigned long flags;
fhci = hcd_to_fhci(hcd);
spin_lock_irqsave(&fhci->lock, flags);
ed = ep->hcpriv;
if (ed) {
while (ed->td_head != NULL) {
struct td *td = fhci_remove_td_from_ed(ed);
fhci_urb_complete_free(fhci, td->urb);
}
fhci_recycle_empty_ed(fhci, ed);
ep->hcpriv = NULL;
}
spin_unlock_irqrestore(&fhci->lock, flags);
}
static int fhci_get_frame_number(struct usb_hcd *hcd)
{
struct fhci_hcd *fhci = hcd_to_fhci(hcd);
return get_frame_num(fhci);
}
static const struct hc_driver fhci_driver = {
.description = "fsl,usb-fhci",
.product_desc = "FHCI HOST Controller",
.hcd_priv_size = sizeof(struct fhci_hcd),
/* generic hardware linkage */
.irq = fhci_irq,
.flags = HCD_USB11 | HCD_MEMORY,
/* basic lifecycle operation */
.start = fhci_start,
.stop = fhci_stop,
/* managing i/o requests and associated device resources */
.urb_enqueue = fhci_urb_enqueue,
.urb_dequeue = fhci_urb_dequeue,
.endpoint_disable = fhci_endpoint_disable,
/* scheduling support */
.get_frame_number = fhci_get_frame_number,
/* root hub support */
.hub_status_data = fhci_hub_status_data,
.hub_control = fhci_hub_control,
};
static int __devinit of_fhci_probe(struct of_device *ofdev,
const struct of_device_id *ofid)
{
struct device *dev = &ofdev->dev;
struct device_node *node = dev->of_node;
struct usb_hcd *hcd;
struct fhci_hcd *fhci;
struct resource usb_regs;
unsigned long pram_addr;
unsigned int usb_irq;
const char *sprop;
const u32 *iprop;
int size;
int ret;
int i;
int j;
if (usb_disabled())
return -ENODEV;
sprop = of_get_property(node, "mode", NULL);
if (sprop && strcmp(sprop, "host"))
return -ENODEV;
hcd = usb_create_hcd(&fhci_driver, dev, dev_name(dev));
if (!hcd) {
dev_err(dev, "could not create hcd\n");
return -ENOMEM;
}
fhci = hcd_to_fhci(hcd);
hcd->self.controller = dev;
dev_set_drvdata(dev, hcd);
iprop = of_get_property(node, "hub-power-budget", &size);
if (iprop && size == sizeof(*iprop))
hcd->power_budget = *iprop;
/* FHCI registers. */
ret = of_address_to_resource(node, 0, &usb_regs);
if (ret) {
dev_err(dev, "could not get regs\n");
goto err_regs;
}
hcd->regs = ioremap(usb_regs.start, usb_regs.end - usb_regs.start + 1);
if (!hcd->regs) {
dev_err(dev, "could not ioremap regs\n");
ret = -ENOMEM;
goto err_regs;
}
fhci->regs = hcd->regs;
/* Parameter RAM. */
iprop = of_get_property(node, "reg", &size);
if (!iprop || size < sizeof(*iprop) * 4) {
dev_err(dev, "can't get pram offset\n");
ret = -EINVAL;
goto err_pram;
}
pram_addr = cpm_muram_alloc_fixed(iprop[2], FHCI_PRAM_SIZE);
if (IS_ERR_VALUE(pram_addr)) {
dev_err(dev, "failed to allocate usb pram\n");
ret = -ENOMEM;
goto err_pram;
}
fhci->pram = cpm_muram_addr(pram_addr);
/* GPIOs and pins */
for (i = 0; i < NUM_GPIOS; i++) {
int gpio;
enum of_gpio_flags flags;
gpio = of_get_gpio_flags(node, i, &flags);
fhci->gpios[i] = gpio;
fhci->alow_gpios[i] = flags & OF_GPIO_ACTIVE_LOW;
if (!gpio_is_valid(gpio)) {
if (i < GPIO_SPEED) {
dev_err(dev, "incorrect GPIO%d: %d\n",
i, gpio);
goto err_gpios;
} else {
dev_info(dev, "assuming board doesn't have "
"%s gpio\n", i == GPIO_SPEED ?
"speed" : "power");
continue;
}
}
ret = gpio_request(gpio, dev_name(dev));
if (ret) {
dev_err(dev, "failed to request gpio %d", i);
goto err_gpios;
}
if (i >= GPIO_SPEED) {
ret = gpio_direction_output(gpio, 0);
if (ret) {
dev_err(dev, "failed to set gpio %d as "
"an output\n", i);
i++;
goto err_gpios;
}
}
}
for (j = 0; j < NUM_PINS; j++) {
fhci->pins[j] = qe_pin_request(node, j);
if (IS_ERR(fhci->pins[j])) {
ret = PTR_ERR(fhci->pins[j]);
dev_err(dev, "can't get pin %d: %d\n", j, ret);
goto err_pins;
}
}
/* Frame limit timer and its interrupt. */
fhci->timer = gtm_get_timer16();
if (IS_ERR(fhci->timer)) {
ret = PTR_ERR(fhci->timer);
dev_err(dev, "failed to request qe timer: %i", ret);
goto err_get_timer;
}
ret = request_irq(fhci->timer->irq, fhci_frame_limit_timer_irq,
IRQF_DISABLED, "qe timer (usb)", hcd);
if (ret) {
dev_err(dev, "failed to request timer irq");
goto err_timer_irq;
}
/* USB Host interrupt. */
usb_irq = irq_of_parse_and_map(node, 0);
if (usb_irq == NO_IRQ) {
dev_err(dev, "could not get usb irq\n");
ret = -EINVAL;
goto err_usb_irq;
}
/* Clocks. */
sprop = of_get_property(node, "fsl,fullspeed-clock", NULL);
if (sprop) {
fhci->fullspeed_clk = qe_clock_source(sprop);
if (fhci->fullspeed_clk == QE_CLK_DUMMY) {
dev_err(dev, "wrong fullspeed-clock\n");
ret = -EINVAL;
goto err_clocks;
}
}
sprop = of_get_property(node, "fsl,lowspeed-clock", NULL);
if (sprop) {
fhci->lowspeed_clk = qe_clock_source(sprop);
if (fhci->lowspeed_clk == QE_CLK_DUMMY) {
dev_err(dev, "wrong lowspeed-clock\n");
ret = -EINVAL;
goto err_clocks;
}
}
if (fhci->fullspeed_clk == QE_CLK_NONE &&
fhci->lowspeed_clk == QE_CLK_NONE) {
dev_err(dev, "no clocks specified\n");
ret = -EINVAL;
goto err_clocks;
}
dev_info(dev, "at 0x%p, irq %d\n", hcd->regs, usb_irq);
fhci_config_transceiver(fhci, FHCI_PORT_POWER_OFF);
/* Start with full-speed, if possible. */
if (fhci->fullspeed_clk != QE_CLK_NONE) {
fhci_config_transceiver(fhci, FHCI_PORT_FULL);
qe_usb_clock_set(fhci->fullspeed_clk, USB_CLOCK);
} else {
fhci_config_transceiver(fhci, FHCI_PORT_LOW);
qe_usb_clock_set(fhci->lowspeed_clk, USB_CLOCK >> 3);
}
/* Clear and disable any pending interrupts. */
out_be16(&fhci->regs->usb_event, 0xffff);
out_be16(&fhci->regs->usb_mask, 0);
ret = usb_add_hcd(hcd, usb_irq, IRQF_DISABLED);
if (ret < 0)
goto err_add_hcd;
fhci_dfs_create(fhci);
return 0;
err_add_hcd:
err_clocks:
irq_dispose_mapping(usb_irq);
err_usb_irq:
free_irq(fhci->timer->irq, hcd);
err_timer_irq:
gtm_put_timer16(fhci->timer);
err_get_timer:
err_pins:
while (--j >= 0)
qe_pin_free(fhci->pins[j]);
err_gpios:
while (--i >= 0) {
if (gpio_is_valid(fhci->gpios[i]))
gpio_free(fhci->gpios[i]);
}
cpm_muram_free(pram_addr);
err_pram:
iounmap(hcd->regs);
err_regs:
usb_put_hcd(hcd);
return ret;
}
static int __devexit fhci_remove(struct device *dev)
{
struct usb_hcd *hcd = dev_get_drvdata(dev);
struct fhci_hcd *fhci = hcd_to_fhci(hcd);
int i;
int j;
usb_remove_hcd(hcd);
free_irq(fhci->timer->irq, hcd);
gtm_put_timer16(fhci->timer);
cpm_muram_free(cpm_muram_offset(fhci->pram));
for (i = 0; i < NUM_GPIOS; i++) {
if (!gpio_is_valid(fhci->gpios[i]))
continue;
gpio_free(fhci->gpios[i]);
}
for (j = 0; j < NUM_PINS; j++)
qe_pin_free(fhci->pins[j]);
fhci_dfs_destroy(fhci);
usb_put_hcd(hcd);
return 0;
}
static int __devexit of_fhci_remove(struct of_device *ofdev)
{
return fhci_remove(&ofdev->dev);
}
static const struct of_device_id of_fhci_match[] = {
{ .compatible = "fsl,mpc8323-qe-usb", },
{},
};
MODULE_DEVICE_TABLE(of, of_fhci_match);
static struct of_platform_driver of_fhci_driver = {
.driver = {
.name = "fsl,usb-fhci",
.owner = THIS_MODULE,
.of_match_table = of_fhci_match,
},
.probe = of_fhci_probe,
.remove = __devexit_p(of_fhci_remove),
};
static int __init fhci_module_init(void)
{
return of_register_platform_driver(&of_fhci_driver);
}
module_init(fhci_module_init);
static void __exit fhci_module_exit(void)
{
of_unregister_platform_driver(&of_fhci_driver);
}
module_exit(fhci_module_exit);
MODULE_DESCRIPTION("USB Freescale Host Controller Interface Driver");
MODULE_AUTHOR("Shlomi Gridish <gridish@freescale.com>, "
"Jerry Huang <Chang-Ming.Huang@freescale.com>, "
"Anton Vorontsov <avorontsov@ru.mvista.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Cardinal97/android_kernel_msm8939 | sound/soc/msm/apq8074.c | 768 | 71259 | /* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/of_gpio.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/mfd/pm8xxx/pm8921.h>
#include <linux/qpnp/clkdiv.h>
#include <linux/regulator/consumer.h>
#include <linux/io.h>
#include <soc/qcom/subsystem_notif.h>
#include <soc/qcom/socinfo.h>
#include <sound/core.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/pcm.h>
#include <sound/jack.h>
#include <sound/q6afe-v2.h>
#include <sound/q6core.h>
#include <sound/pcm_params.h>
#include "qdsp6v2/msm-pcm-routing-v2.h"
#include "../codecs/wcd9xxx-common.h"
#include "../codecs/wcd9320.h"
#define DRV_NAME "apq8074-asoc-taiko"
#define APQ8074_SPK_ON 1
#define APQ8074_SPK_OFF 0
#define MSM_SLIM_0_RX_MAX_CHANNELS 2
#define MSM_SLIM_0_TX_MAX_CHANNELS 4
#define BTSCO_RATE_8KHZ 8000
#define BTSCO_RATE_16KHZ 16000
static int slim0_rx_bit_format = SNDRV_PCM_FORMAT_S16_LE;
static int hdmi_rx_bit_format = SNDRV_PCM_FORMAT_S16_LE;
#define SAMPLING_RATE_48KHZ 48000
#define SAMPLING_RATE_96KHZ 96000
#define SAMPLING_RATE_192KHZ 192000
static int apq8074_auxpcm_rate = 8000;
#define LO_1_SPK_AMP 0x1
#define LO_3_SPK_AMP 0x2
#define LO_2_SPK_AMP 0x4
#define LO_4_SPK_AMP 0x8
#define LPAIF_OFFSET 0xFE000000
#define LPAIF_PRI_MODE_MUXSEL (LPAIF_OFFSET + 0x2B000)
#define LPAIF_SEC_MODE_MUXSEL (LPAIF_OFFSET + 0x2C000)
#define LPAIF_TER_MODE_MUXSEL (LPAIF_OFFSET + 0x2D000)
#define LPAIF_QUAD_MODE_MUXSEL (LPAIF_OFFSET + 0x2E000)
#define I2S_PCM_SEL 1
#define I2S_PCM_SEL_OFFSET 1
#define WCD9XXX_MBHC_DEF_BUTTONS 8
#define WCD9XXX_MBHC_DEF_RLOADS 5
#define TAIKO_EXT_CLK_RATE 9600000
/* It takes about 13ms for Class-D PAs to ramp-up */
#define EXT_CLASS_D_EN_DELAY 13000
#define EXT_CLASS_D_DIS_DELAY 3000
#define EXT_CLASS_D_DELAY_DELTA 2000
/* It takes about 13ms for Class-AB PAs to ramp-up */
#define EXT_CLASS_AB_EN_DELAY 10000
#define EXT_CLASS_AB_DIS_DELAY 1000
#define EXT_CLASS_AB_DELAY_DELTA 1000
#define NUM_OF_AUXPCM_GPIOS 4
static void *adsp_state_notifier;
#define ADSP_STATE_READY_TIMEOUT_MS 3000
static inline int param_is_mask(int p)
{
return ((p >= SNDRV_PCM_HW_PARAM_FIRST_MASK) &&
(p <= SNDRV_PCM_HW_PARAM_LAST_MASK));
}
static inline struct snd_mask *param_to_mask(struct snd_pcm_hw_params *p, int n)
{
return &(p->masks[n - SNDRV_PCM_HW_PARAM_FIRST_MASK]);
}
static void param_set_mask(struct snd_pcm_hw_params *p, int n, unsigned bit)
{
if (bit >= SNDRV_MASK_MAX)
return;
if (param_is_mask(n)) {
struct snd_mask *m = param_to_mask(p, n);
m->bits[0] = 0;
m->bits[1] = 0;
m->bits[bit >> 5] |= (1 << (bit & 31));
}
}
static const char *const auxpcm_rate_text[] = {"rate_8000", "rate_16000"};
static const struct soc_enum apq8074_auxpcm_enum[] = {
SOC_ENUM_SINGLE_EXT(2, auxpcm_rate_text),
};
static void *def_taiko_mbhc_cal(void);
static int msm_snd_enable_codec_ext_clk(struct snd_soc_codec *codec, int enable,
bool dapm);
static struct wcd9xxx_mbhc_config mbhc_cfg = {
.read_fw_bin = false,
.calibration = NULL,
.micbias = MBHC_MICBIAS2,
.mclk_cb_fn = msm_snd_enable_codec_ext_clk,
.mclk_rate = TAIKO_EXT_CLK_RATE,
.gpio = 0,
.gpio_irq = 0,
.gpio_level_insert = 1,
.detect_extn_cable = false,
.insert_detect = true,
.swap_gnd_mic = NULL,
};
struct msm_auxpcm_gpio {
unsigned gpio_no;
const char *gpio_name;
};
struct msm_auxpcm_ctrl {
struct msm_auxpcm_gpio *pin_data;
u32 cnt;
};
struct apq8074_asoc_mach_data {
int mclk_gpio;
u32 mclk_freq;
int us_euro_gpio;
struct msm_auxpcm_ctrl *pri_auxpcm_ctrl;
};
#define GPIO_NAME_INDEX 0
#define DT_PARSE_INDEX 1
static char *msm_prim_auxpcm_gpio_name[][2] = {
{"PRIM_AUXPCM_CLK", "qcom,prim-auxpcm-gpio-clk"},
{"PRIM_AUXPCM_SYNC", "qcom,prim-auxpcm-gpio-sync"},
{"PRIM_AUXPCM_DIN", "qcom,prim-auxpcm-gpio-din"},
{"PRIM_AUXPCM_DOUT", "qcom,prim-auxpcm-gpio-dout"},
};
static void *lpaif_pri_muxsel_virt_addr;
struct apq8074_liquid_dock_dev {
int dock_plug_gpio;
int dock_plug_irq;
struct snd_soc_dapm_context *dapm;
struct work_struct irq_work;
};
static struct apq8074_liquid_dock_dev *apq8074_liquid_dock_dev;
static int dock_plug_det = -1;
/* Shared channel numbers for Slimbus ports that connect APQ to MDM. */
enum {
SLIM_1_RX_1 = 145, /* BT-SCO and USB TX */
SLIM_1_TX_1 = 146, /* BT-SCO and USB RX */
SLIM_2_RX_1 = 147, /* HDMI RX */
SLIM_3_RX_1 = 148, /* In-call recording RX */
SLIM_3_RX_2 = 149, /* In-call recording RX */
SLIM_4_TX_1 = 150, /* In-call musid delivery TX */
};
static struct platform_device *spdev;
static struct regulator *ext_spk_amp_regulator;
static int ext_spk_amp_gpio = -1;
static int ext_ult_spk_amp_gpio = -1;
static int apq8074_spk_control = 1;
static int apq8074_ext_spk_pamp;
static int msm_slim_0_rx_ch = 1;
static int msm_slim_0_tx_ch = 1;
static int msm_btsco_rate = BTSCO_RATE_8KHZ;
static int msm_btsco_ch = 1;
static int msm_hdmi_rx_ch = 2;
static int slim0_rx_sample_rate = SAMPLING_RATE_48KHZ;
static int msm_proxy_rx_ch = 2;
static struct mutex cdc_mclk_mutex;
static struct clk *codec_clk;
static int clk_users;
static atomic_t prim_auxpcm_rsc_ref;
static int apq8074_liquid_ext_spk_power_amp_init(void)
{
int ret = 0;
ext_spk_amp_gpio = of_get_named_gpio(spdev->dev.of_node,
"qcom,ext-spk-amp-gpio", 0);
if (ext_spk_amp_gpio >= 0) {
ret = gpio_request(ext_spk_amp_gpio, "ext_spk_amp_gpio");
if (ret) {
pr_err("%s: gpio_request failed for ext_spk_amp_gpio.\n",
__func__);
return -EINVAL;
}
gpio_direction_output(ext_spk_amp_gpio, 0);
if (ext_spk_amp_regulator == NULL) {
ext_spk_amp_regulator = regulator_get(&spdev->dev,
"qcom,ext-spk-amp");
if (IS_ERR(ext_spk_amp_regulator)) {
pr_err("%s: Cannot get regulator %s.\n",
__func__, "qcom,ext-spk-amp");
gpio_free(ext_spk_amp_gpio);
return PTR_ERR(ext_spk_amp_regulator);
}
}
}
ext_ult_spk_amp_gpio = of_get_named_gpio(spdev->dev.of_node,
"qcom,ext-ult-spk-amp-gpio", 0);
if (ext_ult_spk_amp_gpio >= 0) {
ret = gpio_request(ext_ult_spk_amp_gpio,
"ext_ult_spk_amp_gpio");
if (ret) {
pr_err("%s: gpio_request failed for ext-ult_spk-amp-gpio.\n",
__func__);
return -EINVAL;
}
gpio_direction_output(ext_ult_spk_amp_gpio, 0);
}
return 0;
}
static void apq8074_liquid_ext_ult_spk_power_amp_enable(u32 on)
{
int ret;
if (on) {
ret = regulator_enable(ext_spk_amp_regulator);
if (ret)
pr_err("%s: regulator enable failed\n", __func__);
gpio_direction_output(ext_ult_spk_amp_gpio, 1);
/* time takes enable the external power class AB amplifier */
usleep_range(EXT_CLASS_AB_EN_DELAY,
EXT_CLASS_AB_EN_DELAY + EXT_CLASS_AB_DELAY_DELTA);
} else {
gpio_direction_output(ext_ult_spk_amp_gpio, 0);
regulator_disable(ext_spk_amp_regulator);
/* time takes disable the external power class AB amplifier */
usleep_range(EXT_CLASS_AB_DIS_DELAY,
EXT_CLASS_AB_DIS_DELAY + EXT_CLASS_AB_DELAY_DELTA);
}
pr_debug("%s: %s external ultrasound SPKR_DRV PAs.\n", __func__,
on ? "Enable" : "Disable");
}
static void apq8074_liquid_ext_spk_power_amp_enable(u32 on)
{
int ret;
if (on) {
ret = regulator_enable(ext_spk_amp_regulator);
if (ret)
pr_err("%s: regulator enable failed\n", __func__);
gpio_direction_output(ext_spk_amp_gpio, on);
/*time takes enable the external power amplifier*/
usleep_range(EXT_CLASS_D_EN_DELAY,
EXT_CLASS_D_EN_DELAY + EXT_CLASS_D_DELAY_DELTA);
} else {
gpio_direction_output(ext_spk_amp_gpio, on);
regulator_disable(ext_spk_amp_regulator);
/*time takes disable the external power amplifier*/
usleep_range(EXT_CLASS_D_DIS_DELAY,
EXT_CLASS_D_DIS_DELAY + EXT_CLASS_D_DELAY_DELTA);
}
pr_debug("%s: %s external speaker PAs.\n", __func__,
on ? "Enable" : "Disable");
}
static void apq8074_liquid_docking_irq_work(struct work_struct *work)
{
struct apq8074_liquid_dock_dev *dock_dev =
container_of(work,
struct apq8074_liquid_dock_dev,
irq_work);
struct snd_soc_dapm_context *dapm = dock_dev->dapm;
mutex_lock(&dapm->codec->mutex);
dock_plug_det =
gpio_get_value(dock_dev->dock_plug_gpio);
if (0 == dock_plug_det) {
if ((apq8074_ext_spk_pamp & LO_1_SPK_AMP) &&
(apq8074_ext_spk_pamp & LO_3_SPK_AMP) &&
(apq8074_ext_spk_pamp & LO_2_SPK_AMP) &&
(apq8074_ext_spk_pamp & LO_4_SPK_AMP))
apq8074_liquid_ext_spk_power_amp_enable(1);
} else {
if ((apq8074_ext_spk_pamp & LO_1_SPK_AMP) &&
(apq8074_ext_spk_pamp & LO_3_SPK_AMP) &&
(apq8074_ext_spk_pamp & LO_2_SPK_AMP) &&
(apq8074_ext_spk_pamp & LO_4_SPK_AMP))
apq8074_liquid_ext_spk_power_amp_enable(0);
}
mutex_unlock(&dapm->codec->mutex);
}
static irqreturn_t apq8074_liquid_docking_irq_handler(int irq, void *dev)
{
struct apq8074_liquid_dock_dev *dock_dev = dev;
/* switch speakers should not run in interrupt context */
schedule_work(&dock_dev->irq_work);
return IRQ_HANDLED;
}
static int apq8074_liquid_init_docking(struct snd_soc_dapm_context *dapm)
{
int ret = 0;
int dock_plug_gpio = 0;
/* plug in docking speaker+plug in device OR unplug one of them */
u32 dock_plug_irq_flags = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING;
dock_plug_det = 0;
dock_plug_gpio = of_get_named_gpio(spdev->dev.of_node,
"qcom,dock-plug-det-irq", 0);
if (dock_plug_gpio >= 0) {
apq8074_liquid_dock_dev =
kzalloc(sizeof(*apq8074_liquid_dock_dev), GFP_KERNEL);
if (!apq8074_liquid_dock_dev) {
pr_err("apq8074_liquid_dock_dev alloc fail.\n");
return -ENOMEM;
}
apq8074_liquid_dock_dev->dock_plug_gpio = dock_plug_gpio;
ret = gpio_request(apq8074_liquid_dock_dev->dock_plug_gpio,
"dock-plug-det-irq");
if (ret) {
pr_err("%s:failed request apq8074_liquid_dock_plug_gpio.\n",
__func__);
return -EINVAL;
}
dock_plug_det =
gpio_get_value(apq8074_liquid_dock_dev->dock_plug_gpio);
apq8074_liquid_dock_dev->dock_plug_irq =
gpio_to_irq(apq8074_liquid_dock_dev->dock_plug_gpio);
apq8074_liquid_dock_dev->dapm = dapm;
ret = request_irq(apq8074_liquid_dock_dev->dock_plug_irq,
apq8074_liquid_docking_irq_handler,
dock_plug_irq_flags,
"liquid_dock_plug_irq",
apq8074_liquid_dock_dev);
INIT_WORK(
&apq8074_liquid_dock_dev->irq_work,
apq8074_liquid_docking_irq_work);
}
return 0;
}
static int apq8074_liquid_ext_spk_power_amp_on(u32 spk)
{
int rc;
if (spk & (LO_1_SPK_AMP | LO_3_SPK_AMP | LO_2_SPK_AMP | LO_4_SPK_AMP)) {
pr_debug("%s: External speakers are already on. spk = 0x%x\n",
__func__, spk);
apq8074_ext_spk_pamp |= spk;
if ((apq8074_ext_spk_pamp & LO_1_SPK_AMP) &&
(apq8074_ext_spk_pamp & LO_3_SPK_AMP) &&
(apq8074_ext_spk_pamp & LO_2_SPK_AMP) &&
(apq8074_ext_spk_pamp & LO_4_SPK_AMP))
if (ext_spk_amp_gpio >= 0 &&
dock_plug_det == 0)
apq8074_liquid_ext_spk_power_amp_enable(1);
rc = 0;
} else {
pr_err("%s: Invalid external speaker ampl. spk = 0x%x\n",
__func__, spk);
rc = -EINVAL;
}
return rc;
}
static void apq8074_ext_spk_power_amp_on(u32 spk)
{
if (gpio_is_valid(ext_spk_amp_gpio))
apq8074_liquid_ext_spk_power_amp_on(spk);
}
static void apq8074_liquid_ext_spk_power_amp_off(u32 spk)
{
if (spk & (LO_1_SPK_AMP |
LO_3_SPK_AMP |
LO_2_SPK_AMP |
LO_4_SPK_AMP)) {
pr_debug("%s Left and right speakers case spk = 0x%08x",
__func__, spk);
if (!apq8074_ext_spk_pamp) {
if (ext_spk_amp_gpio >= 0 &&
dock_plug_det == 0)
apq8074_liquid_ext_spk_power_amp_enable(0);
apq8074_ext_spk_pamp = 0;
}
} else {
pr_err("%s: ERROR : Invalid Ext Spk Ampl. spk = 0x%08x\n",
__func__, spk);
return;
}
}
static void apq8074_ext_spk_power_amp_off(u32 spk)
{
if (gpio_is_valid(ext_spk_amp_gpio))
apq8074_liquid_ext_spk_power_amp_off(spk);
}
static void apq8074_ext_control(struct snd_soc_codec *codec)
{
struct snd_soc_dapm_context *dapm = &codec->dapm;
mutex_lock(&dapm->codec->mutex);
pr_debug("%s: apq8074_spk_control = %d", __func__, apq8074_spk_control);
if (apq8074_spk_control == APQ8074_SPK_ON) {
snd_soc_dapm_enable_pin(dapm, "Lineout_1 amp");
snd_soc_dapm_enable_pin(dapm, "Lineout_3 amp");
snd_soc_dapm_enable_pin(dapm, "Lineout_2 amp");
snd_soc_dapm_enable_pin(dapm, "Lineout_4 amp");
} else {
snd_soc_dapm_disable_pin(dapm, "Lineout_1 amp");
snd_soc_dapm_disable_pin(dapm, "Lineout_3 amp");
snd_soc_dapm_disable_pin(dapm, "Lineout_2 amp");
snd_soc_dapm_disable_pin(dapm, "Lineout_4 amp");
}
snd_soc_dapm_sync(dapm);
mutex_unlock(&dapm->codec->mutex);
}
static int apq8074_get_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: apq8074_spk_control = %d", __func__, apq8074_spk_control);
ucontrol->value.integer.value[0] = apq8074_spk_control;
return 0;
}
static int apq8074_set_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
pr_debug("%s()\n", __func__);
if (apq8074_spk_control == ucontrol->value.integer.value[0])
return 0;
apq8074_spk_control = ucontrol->value.integer.value[0];
apq8074_ext_control(codec);
return 1;
}
static int msm_ext_spkramp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
pr_debug("%s()\n", __func__);
if (SND_SOC_DAPM_EVENT_ON(event)) {
if (!strncmp(w->name, "Lineout_1 amp", 14))
apq8074_ext_spk_power_amp_on(LO_1_SPK_AMP);
else if (!strncmp(w->name, "Lineout_3 amp", 14))
apq8074_ext_spk_power_amp_on(LO_3_SPK_AMP);
else if (!strncmp(w->name, "Lineout_2 amp", 14))
apq8074_ext_spk_power_amp_on(LO_2_SPK_AMP);
else if (!strncmp(w->name, "Lineout_4 amp", 14))
apq8074_ext_spk_power_amp_on(LO_4_SPK_AMP);
else {
pr_err("%s() Invalid Speaker Widget = %s\n",
__func__, w->name);
return -EINVAL;
}
} else {
if (!strncmp(w->name, "Lineout_1 amp", 14))
apq8074_ext_spk_power_amp_off(LO_1_SPK_AMP);
else if (!strncmp(w->name, "Lineout_3 amp", 14))
apq8074_ext_spk_power_amp_off(LO_3_SPK_AMP);
else if (!strncmp(w->name, "Lineout_2 amp", 14))
apq8074_ext_spk_power_amp_off(LO_2_SPK_AMP);
else if (!strncmp(w->name, "Lineout_4 amp", 14))
apq8074_ext_spk_power_amp_off(LO_4_SPK_AMP);
else {
pr_err("%s() Invalid Speaker Widget = %s\n",
__func__, w->name);
return -EINVAL;
}
}
return 0;
}
static int msm_ext_spkramp_ultrasound_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
pr_debug("%s()\n", __func__);
if (!strncmp(w->name, "SPK_ultrasound amp", 19)) {
if (!gpio_is_valid(ext_ult_spk_amp_gpio)) {
pr_err("%s: ext_ult_spk_amp_gpio isn't configured\n",
__func__);
return -EINVAL;
}
if (SND_SOC_DAPM_EVENT_ON(event))
apq8074_liquid_ext_ult_spk_power_amp_enable(1);
else
apq8074_liquid_ext_ult_spk_power_amp_enable(0);
} else {
pr_err("%s() Invalid Speaker Widget = %s\n",
__func__, w->name);
return -EINVAL;
}
return 0;
}
static int msm_snd_enable_codec_ext_clk(struct snd_soc_codec *codec, int enable,
bool dapm)
{
int ret = 0;
pr_debug("%s: enable = %d clk_users = %d\n",
__func__, enable, clk_users);
mutex_lock(&cdc_mclk_mutex);
if (enable) {
if (!codec_clk) {
dev_err(codec->dev, "%s: did not get Taiko MCLK\n",
__func__);
ret = -EINVAL;
goto exit;
}
clk_users++;
if (clk_users != 1)
goto exit;
if (codec_clk) {
clk_set_rate(codec_clk, TAIKO_EXT_CLK_RATE);
clk_prepare_enable(codec_clk);
taiko_mclk_enable(codec, 1, dapm);
} else {
pr_err("%s: Error setting Taiko MCLK\n", __func__);
clk_users--;
goto exit;
}
} else {
if (clk_users > 0) {
clk_users--;
if (clk_users == 0) {
taiko_mclk_enable(codec, 0, dapm);
clk_disable_unprepare(codec_clk);
}
} else {
pr_err("%s: Error releasing Taiko MCLK\n", __func__);
ret = -EINVAL;
goto exit;
}
}
exit:
mutex_unlock(&cdc_mclk_mutex);
return ret;
}
static int apq8074_mclk_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
pr_debug("%s: event = %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
return msm_snd_enable_codec_ext_clk(w->codec, 1, true);
case SND_SOC_DAPM_POST_PMD:
return msm_snd_enable_codec_ext_clk(w->codec, 0, true);
}
return 0;
}
static const struct snd_soc_dapm_widget apq8074_dapm_widgets[] = {
SND_SOC_DAPM_SUPPLY("MCLK", SND_SOC_NOPM, 0, 0,
apq8074_mclk_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SPK("Lineout_1 amp", msm_ext_spkramp_event),
SND_SOC_DAPM_SPK("Lineout_3 amp", msm_ext_spkramp_event),
SND_SOC_DAPM_SPK("Lineout_2 amp", msm_ext_spkramp_event),
SND_SOC_DAPM_SPK("Lineout_4 amp", msm_ext_spkramp_event),
SND_SOC_DAPM_SPK("SPK_ultrasound amp",
msm_ext_spkramp_ultrasound_event),
SND_SOC_DAPM_MIC("Handset Mic", NULL),
SND_SOC_DAPM_MIC("Headset Mic", NULL),
SND_SOC_DAPM_MIC("ANCRight Headset Mic", NULL),
SND_SOC_DAPM_MIC("ANCLeft Headset Mic", NULL),
SND_SOC_DAPM_MIC("Analog Mic4", NULL),
SND_SOC_DAPM_MIC("Analog Mic6", NULL),
SND_SOC_DAPM_MIC("Analog Mic7", NULL),
SND_SOC_DAPM_MIC("Digital Mic1", NULL),
SND_SOC_DAPM_MIC("Digital Mic2", NULL),
SND_SOC_DAPM_MIC("Digital Mic3", NULL),
SND_SOC_DAPM_MIC("Digital Mic4", NULL),
SND_SOC_DAPM_MIC("Digital Mic5", NULL),
SND_SOC_DAPM_MIC("Digital Mic6", NULL),
};
static const char *const spk_function[] = {"Off", "On"};
static const char *const slim0_rx_ch_text[] = {"One", "Two"};
static const char *const slim0_tx_ch_text[] = {"One", "Two", "Three", "Four",
"Five", "Six", "Seven",
"Eight"};
static char const *hdmi_rx_ch_text[] = {"Two", "Three", "Four", "Five",
"Six", "Seven", "Eight"};
static char const *rx_bit_format_text[] = {"S16_LE", "S24_LE"};
static char const *slim0_rx_sample_rate_text[] = {"KHZ_48", "KHZ_96",
"KHZ_192"};
static const char *const proxy_rx_ch_text[] = {"One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight"};
static const char *const btsco_rate_text[] = {"8000", "16000"};
static const struct soc_enum msm_btsco_enum[] = {
SOC_ENUM_SINGLE_EXT(2, btsco_rate_text),
};
static int slim0_rx_sample_rate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int sample_rate_val = 0;
switch (slim0_rx_sample_rate) {
case SAMPLING_RATE_192KHZ:
sample_rate_val = 2;
break;
case SAMPLING_RATE_96KHZ:
sample_rate_val = 1;
break;
case SAMPLING_RATE_48KHZ:
default:
sample_rate_val = 0;
break;
}
ucontrol->value.integer.value[0] = sample_rate_val;
pr_debug("%s: slim0_rx_sample_rate = %d\n", __func__,
slim0_rx_sample_rate);
return 0;
}
static int slim0_rx_sample_rate_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: ucontrol value = %ld\n", __func__,
ucontrol->value.integer.value[0]);
switch (ucontrol->value.integer.value[0]) {
case 2:
slim0_rx_sample_rate = SAMPLING_RATE_192KHZ;
break;
case 1:
slim0_rx_sample_rate = SAMPLING_RATE_96KHZ;
break;
case 0:
default:
slim0_rx_sample_rate = SAMPLING_RATE_48KHZ;
}
pr_debug("%s: slim0_rx_sample_rate = %d\n", __func__,
slim0_rx_sample_rate);
return 0;
}
static int slim0_rx_bit_format_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (slim0_rx_bit_format) {
case SNDRV_PCM_FORMAT_S24_LE:
ucontrol->value.integer.value[0] = 1;
break;
case SNDRV_PCM_FORMAT_S16_LE:
default:
ucontrol->value.integer.value[0] = 0;
break;
}
pr_debug("%s: slim0_rx_bit_format = %d, ucontrol value = %ld\n",
__func__, slim0_rx_bit_format,
ucontrol->value.integer.value[0]);
return 0;
}
static int slim0_rx_bit_format_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (ucontrol->value.integer.value[0]) {
case 1:
slim0_rx_bit_format = SNDRV_PCM_FORMAT_S24_LE;
break;
case 0:
default:
slim0_rx_bit_format = SNDRV_PCM_FORMAT_S16_LE;
break;
}
return 0;
}
static int msm_slim_0_rx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_slim_0_rx_ch = %d\n", __func__,
msm_slim_0_rx_ch);
ucontrol->value.integer.value[0] = msm_slim_0_rx_ch - 1;
return 0;
}
static int msm_slim_0_rx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_slim_0_rx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_slim_0_rx_ch = %d\n", __func__,
msm_slim_0_rx_ch);
return 1;
}
static int msm_slim_0_tx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_slim_0_tx_ch = %d\n", __func__,
msm_slim_0_tx_ch);
ucontrol->value.integer.value[0] = msm_slim_0_tx_ch - 1;
return 0;
}
static int msm_slim_0_tx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_slim_0_tx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_slim_0_tx_ch = %d\n", __func__, msm_slim_0_tx_ch);
return 1;
}
static int msm_btsco_rate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_btsco_rate = %d", __func__, msm_btsco_rate);
ucontrol->value.integer.value[0] = msm_btsco_rate;
return 0;
}
static int msm_btsco_rate_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (ucontrol->value.integer.value[0]) {
case 0:
msm_btsco_rate = BTSCO_RATE_8KHZ;
break;
case 1:
msm_btsco_rate = BTSCO_RATE_16KHZ;
break;
default:
msm_btsco_rate = BTSCO_RATE_8KHZ;
break;
}
pr_debug("%s: msm_btsco_rate = %d\n", __func__, msm_btsco_rate);
return 0;
}
static int hdmi_rx_bit_format_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (hdmi_rx_bit_format) {
case SNDRV_PCM_FORMAT_S24_LE:
ucontrol->value.integer.value[0] = 1;
break;
case SNDRV_PCM_FORMAT_S16_LE:
default:
ucontrol->value.integer.value[0] = 0;
break;
}
pr_debug("%s: hdmi_rx_bit_format = %d, ucontrol value = %ld\n",
__func__, hdmi_rx_bit_format,
ucontrol->value.integer.value[0]);
return 0;
}
static int hdmi_rx_bit_format_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (ucontrol->value.integer.value[0]) {
case 1:
hdmi_rx_bit_format = SNDRV_PCM_FORMAT_S24_LE;
break;
case 0:
default:
hdmi_rx_bit_format = SNDRV_PCM_FORMAT_S16_LE;
break;
}
pr_debug("%s: hdmi_rx_bit_format = %d, ucontrol value = %ld\n",
__func__, hdmi_rx_bit_format,
ucontrol->value.integer.value[0]);
return 0;
}
static int msm_hdmi_rx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_hdmi_rx_ch = %d\n", __func__,
msm_hdmi_rx_ch);
ucontrol->value.integer.value[0] = msm_hdmi_rx_ch - 2;
return 0;
}
static int msm_hdmi_rx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_hdmi_rx_ch = ucontrol->value.integer.value[0] + 2;
if (msm_hdmi_rx_ch > 8) {
pr_err("%s: channels exceeded 8.Limiting to max channels-8\n",
__func__);
msm_hdmi_rx_ch = 8;
}
pr_debug("%s: msm_hdmi_rx_ch = %d\n", __func__, msm_hdmi_rx_ch);
return 1;
}
static const struct snd_kcontrol_new int_btsco_rate_mixer_controls[] = {
SOC_ENUM_EXT("Internal BTSCO SampleRate", msm_btsco_enum[0],
msm_btsco_rate_get, msm_btsco_rate_put),
};
static int msm_btsco_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
rate->min = rate->max = msm_btsco_rate;
channels->min = channels->max = msm_btsco_ch;
return 0;
}
static int apq8074_auxpcm_rate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = apq8074_auxpcm_rate;
return 0;
}
static int apq8074_auxpcm_rate_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (ucontrol->value.integer.value[0]) {
case 0:
apq8074_auxpcm_rate = 8000;
break;
case 1:
apq8074_auxpcm_rate = 16000;
break;
default:
apq8074_auxpcm_rate = 8000;
break;
}
return 0;
}
static int msm_proxy_rx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_proxy_rx_ch = %d\n", __func__,
msm_proxy_rx_ch);
ucontrol->value.integer.value[0] = msm_proxy_rx_ch - 1;
return 0;
}
static int msm_proxy_rx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_proxy_rx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_proxy_rx_ch = %d\n", __func__,
msm_proxy_rx_ch);
return 1;
}
static int msm_auxpcm_be_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate =
hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels =
hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
rate->min = rate->max = apq8074_auxpcm_rate;
channels->min = channels->max = 1;
return 0;
}
static int msm_proxy_rx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s: msm_proxy_rx_ch =%d\n", __func__, msm_proxy_rx_ch);
if (channels->max < 2)
channels->min = channels->max = 2;
channels->min = channels->max = msm_proxy_rx_ch;
rate->min = rate->max = 48000;
return 0;
}
static int msm_proxy_tx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
rate->min = rate->max = 48000;
return 0;
}
static int apq8074_hdmi_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s channels->min %u channels->max %u ()\n", __func__,
channels->min, channels->max);
param_set_mask(params, SNDRV_PCM_HW_PARAM_FORMAT,
hdmi_rx_bit_format);
if (channels->max < 2)
channels->min = channels->max = 2;
rate->min = rate->max = 48000;
channels->min = channels->max = msm_hdmi_rx_ch;
return 0;
}
static int msm_aux_pcm_get_gpios(struct msm_auxpcm_ctrl *auxpcm_ctrl)
{
struct msm_auxpcm_gpio *pin_data = NULL;
int ret = 0;
int i;
int j;
pin_data = auxpcm_ctrl->pin_data;
for (i = 0; i < auxpcm_ctrl->cnt; i++, pin_data++) {
ret = gpio_request(pin_data->gpio_no,
pin_data->gpio_name);
pr_debug("%s: gpio = %d, gpio name = %s\n"
"ret = %d\n", __func__,
pin_data->gpio_no,
pin_data->gpio_name,
ret);
if (ret) {
pr_err("%s: Failed to request gpio %d\n",
__func__, pin_data->gpio_no);
/* Release all GPIOs on failure */
for (j = i; j >= 0; j--)
gpio_free(pin_data->gpio_no);
return ret;
}
}
return 0;
}
static int msm_aux_pcm_free_gpios(struct msm_auxpcm_ctrl *auxpcm_ctrl)
{
struct msm_auxpcm_gpio *pin_data = NULL;
int i;
int ret = 0;
if (auxpcm_ctrl == NULL || auxpcm_ctrl->pin_data == NULL) {
pr_err("%s: Ctrl pointers are NULL\n", __func__);
ret = -EINVAL;
goto err;
}
pin_data = auxpcm_ctrl->pin_data;
for (i = 0; i < auxpcm_ctrl->cnt; i++, pin_data++) {
gpio_free(pin_data->gpio_no);
pr_debug("%s: gpio = %d, gpio_name = %s\n",
__func__, pin_data->gpio_no,
pin_data->gpio_name);
}
err:
return ret;
}
static int msm_prim_auxpcm_startup(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_card *card = rtd->card;
struct apq8074_asoc_mach_data *pdata = snd_soc_card_get_drvdata(card);
struct msm_auxpcm_ctrl *auxpcm_ctrl = NULL;
int ret = 0;
pr_debug("%s(): substream = %s, prim_auxpcm_rsc_ref counter = %d\n",
__func__, substream->name, atomic_read(&prim_auxpcm_rsc_ref));
auxpcm_ctrl = pdata->pri_auxpcm_ctrl;
if (auxpcm_ctrl == NULL || auxpcm_ctrl->pin_data == NULL) {
pr_err("%s: Ctrl pointers are NULL\n", __func__);
ret = -EINVAL;
goto err;
}
if (atomic_inc_return(&prim_auxpcm_rsc_ref) == 1) {
if (lpaif_pri_muxsel_virt_addr != NULL)
iowrite32(I2S_PCM_SEL << I2S_PCM_SEL_OFFSET,
lpaif_pri_muxsel_virt_addr);
else
pr_err("%s lpaif_pri_muxsel_virt_addr is NULL\n",
__func__);
ret = msm_aux_pcm_get_gpios(auxpcm_ctrl);
}
if (ret < 0) {
pr_err("%s: Aux PCM GPIO request failed\n", __func__);
return -EINVAL;
}
err:
return ret;
}
static void msm_prim_auxpcm_shutdown(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_card *card = rtd->card;
struct apq8074_asoc_mach_data *pdata = snd_soc_card_get_drvdata(card);
struct msm_auxpcm_ctrl *auxpcm_ctrl = NULL;
pr_debug("%s(): substream = %s, prim_auxpcm_rsc_ref counter = %d\n",
__func__, substream->name, atomic_read(&prim_auxpcm_rsc_ref));
auxpcm_ctrl = pdata->pri_auxpcm_ctrl;
if (atomic_dec_return(&prim_auxpcm_rsc_ref) == 0)
msm_aux_pcm_free_gpios(auxpcm_ctrl);
}
static struct snd_soc_ops msm_auxpcm_be_ops = {
.startup = msm_prim_auxpcm_startup,
.shutdown = msm_prim_auxpcm_shutdown,
};
static int msm_slim_0_rx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels =
hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
param_set_mask(params, SNDRV_PCM_HW_PARAM_FORMAT,
slim0_rx_bit_format);
rate->min = rate->max = slim0_rx_sample_rate;
channels->min = channels->max = msm_slim_0_rx_ch;
pr_debug("%s: format = %d, rate = %d, channels = %d\n",
__func__, params_format(params), params_rate(params),
msm_slim_0_rx_ch);
return 0;
}
static int msm_slim_0_tx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_slim_0_tx_ch;
return 0;
}
static int msm_slim_5_tx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
int rc;
void *config;
struct snd_soc_codec *codec = rtd->codec;
struct snd_interval *rate =
hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels =
hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s enter\n", __func__);
rate->min = rate->max = 16000;
channels->min = channels->max = 1;
config = taiko_get_afe_config(codec, AFE_SLIMBUS_SLAVE_PORT_CONFIG);
rc = afe_set_config(AFE_SLIMBUS_SLAVE_PORT_CONFIG, config,
SLIMBUS_5_TX);
if (rc) {
pr_err("%s: Failed to set slimbus slave port config %d\n",
__func__, rc);
return rc;
}
return 0;
}
static int msm_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
return 0;
}
static const struct soc_enum msm_snd_enum[] = {
SOC_ENUM_SINGLE_EXT(2, spk_function),
SOC_ENUM_SINGLE_EXT(2, slim0_rx_ch_text),
SOC_ENUM_SINGLE_EXT(8, slim0_tx_ch_text),
SOC_ENUM_SINGLE_EXT(7, hdmi_rx_ch_text),
SOC_ENUM_SINGLE_EXT(2, rx_bit_format_text),
SOC_ENUM_SINGLE_EXT(3, slim0_rx_sample_rate_text),
SOC_ENUM_SINGLE_EXT(8, proxy_rx_ch_text),
};
static const struct snd_kcontrol_new msm_snd_controls[] = {
SOC_ENUM_EXT("Speaker Function", msm_snd_enum[0], apq8074_get_spk,
apq8074_set_spk),
SOC_ENUM_EXT("SLIM_0_RX Channels", msm_snd_enum[1],
msm_slim_0_rx_ch_get, msm_slim_0_rx_ch_put),
SOC_ENUM_EXT("SLIM_0_TX Channels", msm_snd_enum[2],
msm_slim_0_tx_ch_get, msm_slim_0_tx_ch_put),
SOC_ENUM_EXT("AUX PCM SampleRate", apq8074_auxpcm_enum[0],
apq8074_auxpcm_rate_get, apq8074_auxpcm_rate_put),
SOC_ENUM_EXT("HDMI_RX Channels", msm_snd_enum[3],
msm_hdmi_rx_ch_get, msm_hdmi_rx_ch_put),
SOC_ENUM_EXT("SLIM_0_RX Format", msm_snd_enum[4],
slim0_rx_bit_format_get, slim0_rx_bit_format_put),
SOC_ENUM_EXT("SLIM_0_RX SampleRate", msm_snd_enum[5],
slim0_rx_sample_rate_get, slim0_rx_sample_rate_put),
SOC_ENUM_EXT("HDMI_RX Bit Format", msm_snd_enum[4],
hdmi_rx_bit_format_get, hdmi_rx_bit_format_put),
SOC_ENUM_EXT("PROXY_RX Channels", msm_snd_enum[6],
msm_proxy_rx_ch_get, msm_proxy_rx_ch_put),
};
static bool apq8074_swap_gnd_mic(struct snd_soc_codec *codec)
{
struct snd_soc_card *card = codec->card;
struct apq8074_asoc_mach_data *pdata = snd_soc_card_get_drvdata(card);
int value = gpio_get_value_cansleep(pdata->us_euro_gpio);
pr_debug("%s: swap select switch %d to %d\n", __func__, value, !value);
gpio_set_value_cansleep(pdata->us_euro_gpio, !value);
return true;
}
static int msm_afe_set_config(struct snd_soc_codec *codec)
{
int rc;
void *config_data;
pr_debug("%s: enter\n", __func__);
config_data = taiko_get_afe_config(codec, AFE_CDC_REGISTERS_CONFIG);
rc = afe_set_config(AFE_CDC_REGISTERS_CONFIG, config_data, 0);
if (rc) {
pr_err("%s: Failed to set codec registers config %d\n",
__func__, rc);
return rc;
}
config_data = taiko_get_afe_config(codec, AFE_SLIMBUS_SLAVE_CONFIG);
rc = afe_set_config(AFE_SLIMBUS_SLAVE_CONFIG, config_data, 0);
if (rc) {
pr_err("%s: Failed to set slimbus slave config %d\n", __func__,
rc);
return rc;
}
return 0;
}
static void msm_afe_clear_config(void)
{
afe_clear_config(AFE_CDC_REGISTERS_CONFIG);
afe_clear_config(AFE_SLIMBUS_SLAVE_CONFIG);
}
static int msm8974_adsp_state_callback(struct notifier_block *nb,
unsigned long value, void *priv)
{
if (value == SUBSYS_BEFORE_SHUTDOWN) {
pr_debug("%s: ADSP is about to shutdown. Clearing AFE config\n",
__func__);
msm_afe_clear_config();
} else if (value == SUBSYS_AFTER_POWERUP) {
pr_debug("%s: ADSP is up\n", __func__);
}
return NOTIFY_OK;
}
static struct notifier_block adsp_state_notifier_block = {
.notifier_call = msm8974_adsp_state_callback,
.priority = -INT_MAX,
};
static int msm8974_taiko_codec_up(struct snd_soc_codec *codec)
{
int err;
unsigned long timeout;
int adsp_ready = 0;
timeout = jiffies +
msecs_to_jiffies(ADSP_STATE_READY_TIMEOUT_MS);
do {
if (!q6core_is_adsp_ready()) {
pr_err("%s: ADSP Audio isn't ready\n", __func__);
} else {
pr_debug("%s: ADSP Audio is ready\n", __func__);
adsp_ready = 1;
break;
}
} while (time_after(timeout, jiffies));
if (!adsp_ready) {
pr_err("%s: timed out waiting for ADSP Audio\n", __func__);
return -ETIMEDOUT;
}
err = msm_afe_set_config(codec);
if (err)
pr_err("%s: Failed to set AFE config. err %d\n",
__func__, err);
return err;
}
static int apq8074_taiko_event_cb(struct snd_soc_codec *codec,
enum wcd9xxx_codec_event codec_event)
{
switch (codec_event) {
case WCD9XXX_CODEC_EVENT_CODEC_UP:
return msm8974_taiko_codec_up(codec);
break;
default:
pr_err("%s: UnSupported codec event %d\n",
__func__, codec_event);
return -EINVAL;
}
}
static int msm_audrx_init(struct snd_soc_pcm_runtime *rtd)
{
int err;
void *config_data;
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
/* Taiko SLIMBUS configuration
* RX1, RX2, RX3, RX4, RX5, RX6, RX7, RX8, RX9, RX10, RX11, RX12, RX13
* TX1, TX2, TX3, TX4, TX5, TX6, TX7, TX8, TX9, TX10, TX11, TX12, TX13
* TX14, TX15, TX16
*/
unsigned int rx_ch[TAIKO_RX_MAX] = {144, 145, 146, 147, 148, 149, 150,
151, 152, 153, 154, 155, 156};
unsigned int tx_ch[TAIKO_TX_MAX] = {128, 129, 130, 131, 132, 133,
134, 135, 136, 137, 138, 139,
140, 141, 142, 143};
pr_info("%s(), dev_name%s\n", __func__, dev_name(cpu_dai->dev));
rtd->pmdown_time = 0;
err = snd_soc_add_codec_controls(codec, msm_snd_controls,
ARRAY_SIZE(msm_snd_controls));
if (err < 0)
return err;
err = apq8074_liquid_ext_spk_power_amp_init();
if (err) {
pr_err("%s: LiQUID 8974 CLASS_D PAs init failed (%d)\n",
__func__, err);
return err;
}
err = apq8074_liquid_init_docking(dapm);
if (err) {
pr_err("%s: LiQUID 8974 init Docking stat IRQ failed (%d)\n",
__func__, err);
return err;
}
snd_soc_dapm_new_controls(dapm, apq8074_dapm_widgets,
ARRAY_SIZE(apq8074_dapm_widgets));
snd_soc_dapm_enable_pin(dapm, "Lineout_1 amp");
snd_soc_dapm_enable_pin(dapm, "Lineout_3 amp");
snd_soc_dapm_enable_pin(dapm, "Lineout_2 amp");
snd_soc_dapm_enable_pin(dapm, "Lineout_4 amp");
snd_soc_dapm_sync(dapm);
codec_clk = clk_get(cpu_dai->dev, "osr_clk");
snd_soc_dai_set_channel_map(codec_dai, ARRAY_SIZE(tx_ch),
tx_ch, ARRAY_SIZE(rx_ch), rx_ch);
err = msm_afe_set_config(codec);
if (err) {
pr_err("%s: Failed to set AFE config %d\n", __func__, err);
goto out;
}
config_data = taiko_get_afe_config(codec, AFE_AANC_VERSION);
err = afe_set_config(AFE_AANC_VERSION, config_data, 0);
if (err) {
pr_err("%s: Failed to set aanc version %d\n",
__func__, err);
goto out;
}
config_data = taiko_get_afe_config(codec,
AFE_CDC_CLIP_REGISTERS_CONFIG);
if (config_data) {
err = afe_set_config(AFE_CDC_CLIP_REGISTERS_CONFIG,
config_data, 0);
if (err) {
pr_err("%s: Failed to set clip registers %d\n",
__func__, err);
return err;
}
}
config_data = taiko_get_afe_config(codec, AFE_CLIP_BANK_SEL);
if (config_data) {
err = afe_set_config(AFE_CLIP_BANK_SEL, config_data, 0);
if (err) {
pr_err("%s: Failed to set AFE bank selection %d\n",
__func__, err);
return err;
}
}
/* start mbhc */
mbhc_cfg.calibration = def_taiko_mbhc_cal();
if (mbhc_cfg.calibration) {
err = taiko_hs_detect(codec, &mbhc_cfg);
if (err)
goto out;
} else {
err = -ENOMEM;
goto out;
}
adsp_state_notifier =
subsys_notif_register_notifier("adsp",
&adsp_state_notifier_block);
if (!adsp_state_notifier) {
pr_err("%s: Failed to register adsp state notifier\n",
__func__);
err = -EFAULT;
taiko_hs_detect_exit(codec);
goto out;
}
taiko_event_register(apq8074_taiko_event_cb, rtd->codec);
return 0;
out:
clk_put(codec_clk);
return err;
}
static int apq8074_snd_startup(struct snd_pcm_substream *substream)
{
pr_debug("%s(): substream = %s stream = %d\n", __func__,
substream->name, substream->stream);
return 0;
}
static void *def_taiko_mbhc_cal(void)
{
void *taiko_cal;
struct wcd9xxx_mbhc_btn_detect_cfg *btn_cfg;
u16 *btn_low, *btn_high;
u8 *n_ready, *n_cic, *gain;
taiko_cal = kzalloc(WCD9XXX_MBHC_CAL_SIZE(WCD9XXX_MBHC_DEF_BUTTONS,
WCD9XXX_MBHC_DEF_RLOADS),
GFP_KERNEL);
if (!taiko_cal) {
pr_err("%s: out of memory\n", __func__);
return NULL;
}
#define S(X, Y) ((WCD9XXX_MBHC_CAL_GENERAL_PTR(taiko_cal)->X) = (Y))
S(t_ldoh, 100);
S(t_bg_fast_settle, 100);
S(t_shutdown_plug_rem, 255);
S(mbhc_nsa, 4);
S(mbhc_navg, 4);
#undef S
#define S(X, Y) ((WCD9XXX_MBHC_CAL_PLUG_DET_PTR(taiko_cal)->X) = (Y))
S(mic_current, TAIKO_PID_MIC_5_UA);
S(hph_current, TAIKO_PID_MIC_5_UA);
S(t_mic_pid, 100);
S(t_ins_complete, 250);
S(t_ins_retry, 200);
#undef S
#define S(X, Y) ((WCD9XXX_MBHC_CAL_PLUG_TYPE_PTR(taiko_cal)->X) = (Y))
S(v_no_mic, 30);
S(v_hs_max, 2400);
#undef S
#define S(X, Y) ((WCD9XXX_MBHC_CAL_BTN_DET_PTR(taiko_cal)->X) = (Y))
S(c[0], 62);
S(c[1], 124);
S(nc, 1);
S(n_meas, 3);
S(mbhc_nsc, 11);
S(n_btn_meas, 1);
S(n_btn_con, 2);
S(num_btn, WCD9XXX_MBHC_DEF_BUTTONS);
S(v_btn_press_delta_sta, 100);
S(v_btn_press_delta_cic, 50);
#undef S
btn_cfg = WCD9XXX_MBHC_CAL_BTN_DET_PTR(taiko_cal);
btn_low = wcd9xxx_mbhc_cal_btn_det_mp(btn_cfg, MBHC_BTN_DET_V_BTN_LOW);
btn_high = wcd9xxx_mbhc_cal_btn_det_mp(btn_cfg,
MBHC_BTN_DET_V_BTN_HIGH);
btn_low[0] = -50;
btn_high[0] = 20;
btn_low[1] = 21;
btn_high[1] = 61;
btn_low[2] = 62;
btn_high[2] = 104;
btn_low[3] = 105;
btn_high[3] = 148;
btn_low[4] = 149;
btn_high[4] = 189;
btn_low[5] = 190;
btn_high[5] = 228;
btn_low[6] = 229;
btn_high[6] = 269;
btn_low[7] = 270;
btn_high[7] = 500;
n_ready = wcd9xxx_mbhc_cal_btn_det_mp(btn_cfg, MBHC_BTN_DET_N_READY);
n_ready[0] = 80;
n_ready[1] = 68;
n_cic = wcd9xxx_mbhc_cal_btn_det_mp(btn_cfg, MBHC_BTN_DET_N_CIC);
n_cic[0] = 60;
n_cic[1] = 47;
gain = wcd9xxx_mbhc_cal_btn_det_mp(btn_cfg, MBHC_BTN_DET_GAIN);
gain[0] = 11;
gain[1] = 9;
return taiko_cal;
}
static int msm_snd_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS];
unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0;
unsigned int user_set_tx_ch = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
pr_debug("%s: rx_0_ch=%d\n", __func__, msm_slim_0_rx_ch);
ret = snd_soc_dai_get_channel_map(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0,
msm_slim_0_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
} else {
pr_debug("%s: %s_tx_dai_id_%d_ch=%d\n", __func__,
codec_dai->name, codec_dai->id, user_set_tx_ch);
ret = snd_soc_dai_get_channel_map(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
/* For tabla_tx1 case */
if (codec_dai->id == 1)
user_set_tx_ch = msm_slim_0_tx_ch;
/* For tabla_tx2 case */
else if (codec_dai->id == 3)
user_set_tx_ch = params_channels(params);
else
user_set_tx_ch = tx_ch_cnt;
pr_debug("%s: msm_slim_0_tx_ch(%d)user_set_tx_ch(%d)tx_ch_cnt(%d)\n",
__func__, msm_slim_0_tx_ch, user_set_tx_ch, tx_ch_cnt);
ret = snd_soc_dai_set_channel_map(cpu_dai,
user_set_tx_ch, tx_ch, 0 , 0);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
}
end:
return ret;
}
static void apq8074_snd_shudown(struct snd_pcm_substream *substream)
{
pr_debug("%s(): substream = %s stream = %d\n", __func__,
substream->name, substream->stream);
}
static struct snd_soc_ops apq8074_be_ops = {
.startup = apq8074_snd_startup,
.hw_params = msm_snd_hw_params,
.shutdown = apq8074_snd_shudown,
};
static int apq8074_slimbus_2_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS];
unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0;
unsigned int num_tx_ch = 0;
unsigned int num_rx_ch = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
num_rx_ch = params_channels(params);
pr_debug("%s: %s rx_dai_id = %d num_ch = %d\n", __func__,
codec_dai->name, codec_dai->id, num_rx_ch);
ret = snd_soc_dai_get_channel_map(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0,
num_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
} else {
num_tx_ch = params_channels(params);
pr_debug("%s: %s tx_dai_id = %d num_ch = %d\n", __func__,
codec_dai->name, codec_dai->id, num_tx_ch);
ret = snd_soc_dai_get_channel_map(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(cpu_dai,
num_tx_ch, tx_ch, 0 , 0);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
}
end:
return ret;
}
static struct snd_soc_ops apq8074_slimbus_2_be_ops = {
.startup = apq8074_snd_startup,
.hw_params = apq8074_slimbus_2_hw_params,
.shutdown = apq8074_snd_shudown,
};
/* Digital audio interface glue - connects codec <---> CPU */
static struct snd_soc_dai_link apq8074_common_dai_links[] = {
/* FrontEnd DAI Links */
{
.name = "MSM8974 Media1",
.stream_name = "MultiMedia1",
.cpu_dai_name = "MultiMedia1",
.platform_name = "msm-pcm-dsp.0",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA1
},
{
.name = "MSM8974 Media2",
.stream_name = "MultiMedia2",
.cpu_dai_name = "MultiMedia2",
.platform_name = "msm-pcm-dsp.0",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA2,
},
{
.name = "Circuit-Switch Voice",
.stream_name = "CS-Voice",
.cpu_dai_name = "CS-VOICE",
.platform_name = "msm-pcm-voice",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.be_id = MSM_FRONTEND_DAI_CS_VOICE,
},
{
.name = "MSM VoIP",
.stream_name = "VoIP",
.cpu_dai_name = "VoIP",
.platform_name = "msm-voip-dsp",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.be_id = MSM_FRONTEND_DAI_VOIP,
},
{
.name = "MSM8974 LPA",
.stream_name = "LPA",
.cpu_dai_name = "MultiMedia3",
.platform_name = "msm-pcm-lpa",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA3,
},
/* Hostless PCM purpose */
{
.name = "SLIMBUS_0 Hostless",
.stream_name = "SLIMBUS_0 Hostless",
.cpu_dai_name = "SLIMBUS0_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* dai link has playback support */
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = "INT_FM Hostless",
.stream_name = "INT_FM Hostless",
.cpu_dai_name = "INT_FM_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = "MSM AFE-PCM RX",
.stream_name = "AFE-PROXY RX",
.cpu_dai_name = "msm-dai-q6-dev.241",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.platform_name = "msm-pcm-afe",
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
},
{
.name = "MSM AFE-PCM TX",
.stream_name = "AFE-PROXY TX",
.cpu_dai_name = "msm-dai-q6-dev.240",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.platform_name = "msm-pcm-afe",
.ignore_suspend = 1,
},
{
.name = "MSM8974 Compr",
.stream_name = "COMPR",
.cpu_dai_name = "MultiMedia4",
.platform_name = "msm-compress-dsp",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
/* this dainlink has playback support */
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA4,
},
{
.name = "AUXPCM Hostless",
.stream_name = "AUXPCM Hostless",
.cpu_dai_name = "AUXPCM_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = "SLIMBUS_1 Hostless",
.stream_name = "SLIMBUS_1 Hostless",
.cpu_dai_name = "SLIMBUS1_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* dai link has playback support */
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = "SLIMBUS_3 Hostless",
.stream_name = "SLIMBUS_3 Hostless",
.cpu_dai_name = "SLIMBUS3_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* dai link has playback support */
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = "SLIMBUS_4 Hostless",
.stream_name = "SLIMBUS_4 Hostless",
.cpu_dai_name = "SLIMBUS4_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* dai link has playback support */
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = "VoLTE",
.stream_name = "VoLTE",
.cpu_dai_name = "VoLTE",
.platform_name = "msm-pcm-voice",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.be_id = MSM_FRONTEND_DAI_VOLTE,
},
{
.name = "MSM8974 LowLatency",
.stream_name = "MultiMedia5",
.cpu_dai_name = "MultiMedia5",
.platform_name = "msm-pcm-dsp.1",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA5,
},
/* LSM FE */
{
.name = "Listen Audio Service",
.stream_name = "Listen Audio Service",
.cpu_dai_name = "LSM",
.platform_name = "msm-lsm-client",
.dynamic = 1,
.trigger = { SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST },
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.be_id = MSM_FRONTEND_DAI_LSM1,
},
/* Backend BT/FM DAI Links */
{
.name = LPASS_BE_INT_BT_SCO_RX,
.stream_name = "Internal BT-SCO Playback",
.cpu_dai_name = "msm-dai-q6-dev.12288",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_BT_SCO_RX,
.be_hw_params_fixup = msm_btsco_be_hw_params_fixup,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.ignore_suspend = 1,
},
{
.name = LPASS_BE_INT_BT_SCO_TX,
.stream_name = "Internal BT-SCO Capture",
.cpu_dai_name = "msm-dai-q6-dev.12289",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_BT_SCO_TX,
.be_hw_params_fixup = msm_btsco_be_hw_params_fixup,
.ignore_suspend = 1,
},
{
.name = LPASS_BE_INT_FM_RX,
.stream_name = "Internal FM Playback",
.cpu_dai_name = "msm-dai-q6-dev.12292",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_FM_RX,
.be_hw_params_fixup = msm_be_hw_params_fixup,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.ignore_suspend = 1,
},
{
.name = LPASS_BE_INT_FM_TX,
.stream_name = "Internal FM Capture",
.cpu_dai_name = "msm-dai-q6-dev.12293",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_FM_TX,
.be_hw_params_fixup = msm_be_hw_params_fixup,
.ignore_suspend = 1,
},
/* Backend AFE DAI Links */
{
.name = LPASS_BE_AFE_PCM_RX,
.stream_name = "AFE Playback",
.cpu_dai_name = "msm-dai-q6-dev.224",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AFE_PCM_RX,
.be_hw_params_fixup = msm_proxy_rx_be_hw_params_fixup,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.ignore_suspend = 1,
},
{
.name = LPASS_BE_AFE_PCM_TX,
.stream_name = "AFE Capture",
.cpu_dai_name = "msm-dai-q6-dev.225",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AFE_PCM_TX,
.be_hw_params_fixup = msm_proxy_tx_be_hw_params_fixup,
.ignore_suspend = 1,
},
/* HDMI Hostless */
{
.name = "HDMI_RX_HOSTLESS",
.stream_name = "HDMI_RX_HOSTLESS",
.cpu_dai_name = "HDMI_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
/* AUX PCM Backend DAI Links */
{
.name = LPASS_BE_AUXPCM_RX,
.stream_name = "AUX PCM Playback",
.cpu_dai_name = "msm-dai-q6-auxpcm.1",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AUXPCM_RX,
.be_hw_params_fixup = msm_auxpcm_be_params_fixup,
.ops = &msm_auxpcm_be_ops,
.ignore_pmdown_time = 1,
.ignore_suspend = 1,
/* this dainlink has playback support */
},
{
.name = LPASS_BE_AUXPCM_TX,
.stream_name = "AUX PCM Capture",
.cpu_dai_name = "msm-dai-q6-auxpcm.1",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AUXPCM_TX,
.be_hw_params_fixup = msm_auxpcm_be_params_fixup,
.ops = &msm_auxpcm_be_ops,
.ignore_suspend = 1,
},
/* Backend DAI Links */
{
.name = LPASS_BE_SLIMBUS_0_RX,
.stream_name = "Slimbus Playback",
.cpu_dai_name = "msm-dai-q6-dev.16384",
.platform_name = "msm-pcm-routing",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_rx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_0_RX,
.init = &msm_audrx_init,
.be_hw_params_fixup = msm_slim_0_rx_be_hw_params_fixup,
.ops = &apq8074_be_ops,
.ignore_pmdown_time = 1, /* dai link has playback support */
.ignore_suspend = 1,
},
{
.name = LPASS_BE_SLIMBUS_0_TX,
.stream_name = "Slimbus Capture",
.cpu_dai_name = "msm-dai-q6-dev.16385",
.platform_name = "msm-pcm-routing",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_tx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_0_TX,
.be_hw_params_fixup = msm_slim_0_tx_be_hw_params_fixup,
.ops = &apq8074_be_ops,
.ignore_suspend = 1,
},
{
.name = LPASS_BE_SLIMBUS_1_RX,
.stream_name = "Slimbus1 Playback",
.cpu_dai_name = "msm-dai-q6-dev.16386",
.platform_name = "msm-pcm-routing",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_rx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_1_RX,
.be_hw_params_fixup = msm_slim_0_rx_be_hw_params_fixup,
.ops = &apq8074_be_ops,
/* dai link has playback support */
.ignore_pmdown_time = 1,
.ignore_suspend = 1,
},
{
.name = LPASS_BE_SLIMBUS_1_TX,
.stream_name = "Slimbus1 Capture",
.cpu_dai_name = "msm-dai-q6-dev.16387",
.platform_name = "msm-pcm-routing",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_tx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_1_TX,
.be_hw_params_fixup = msm_slim_0_tx_be_hw_params_fixup,
.ops = &apq8074_be_ops,
.ignore_suspend = 1,
},
{
.name = LPASS_BE_SLIMBUS_3_RX,
.stream_name = "Slimbus3 Playback",
.cpu_dai_name = "msm-dai-q6-dev.16390",
.platform_name = "msm-pcm-routing",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_rx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_3_RX,
.be_hw_params_fixup = msm_slim_0_rx_be_hw_params_fixup,
.ops = &apq8074_be_ops,
/* dai link has playback support */
.ignore_pmdown_time = 1,
.ignore_suspend = 1,
},
{
.name = LPASS_BE_SLIMBUS_3_TX,
.stream_name = "Slimbus3 Capture",
.cpu_dai_name = "msm-dai-q6-dev.16391",
.platform_name = "msm-pcm-routing",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_tx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_3_TX,
.be_hw_params_fixup = msm_slim_0_tx_be_hw_params_fixup,
.ops = &apq8074_be_ops,
.ignore_suspend = 1,
},
{
.name = LPASS_BE_SLIMBUS_4_RX,
.stream_name = "Slimbus4 Playback",
.cpu_dai_name = "msm-dai-q6-dev.16392",
.platform_name = "msm-pcm-routing",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_rx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_4_RX,
.be_hw_params_fixup = msm_slim_0_rx_be_hw_params_fixup,
.ops = &apq8074_be_ops,
/* dai link has playback support */
.ignore_pmdown_time = 1,
.ignore_suspend = 1,
},
{
.name = LPASS_BE_SLIMBUS_4_TX,
.stream_name = "Slimbus4 Capture",
.cpu_dai_name = "msm-dai-q6-dev.16393",
.platform_name = "msm-pcm-hostless",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_vifeedback",
.be_id = MSM_BACKEND_DAI_SLIMBUS_4_TX,
.be_hw_params_fixup = msm_slim_0_tx_be_hw_params_fixup,
.ops = &apq8074_be_ops,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
},
/* Incall Record Uplink BACK END DAI Link */
{
.name = LPASS_BE_INCALL_RECORD_TX,
.stream_name = "Voice Uplink Capture",
.cpu_dai_name = "msm-dai-q6-dev.32772",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INCALL_RECORD_TX,
.be_hw_params_fixup = msm_be_hw_params_fixup,
.ignore_suspend = 1,
},
/* Incall Record Downlink BACK END DAI Link */
{
.name = LPASS_BE_INCALL_RECORD_RX,
.stream_name = "Voice Downlink Capture",
.cpu_dai_name = "msm-dai-q6-dev.32771",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INCALL_RECORD_RX,
.be_hw_params_fixup = msm_be_hw_params_fixup,
.ignore_suspend = 1,
},
/* MAD BE */
{
.name = LPASS_BE_SLIMBUS_5_TX,
.stream_name = "Slimbus5 Capture",
.cpu_dai_name = "msm-dai-q6-dev.16395",
.platform_name = "msm-pcm-routing",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_mad1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_5_TX,
.be_hw_params_fixup = msm_slim_5_tx_be_hw_params_fixup,
.ops = &apq8074_be_ops,
},
/* Incall Music BACK END DAI Link */
{
.name = LPASS_BE_VOICE_PLAYBACK_TX,
.stream_name = "Voice Farend Playback",
.cpu_dai_name = "msm-dai-q6-dev.32773",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_VOICE_PLAYBACK_TX,
.be_hw_params_fixup = msm_be_hw_params_fixup,
.ignore_suspend = 1,
},
/* Ultrasound RX Back End DAI Link */
{
.name = "SLIMBUS_2 Hostless Playback",
.stream_name = "SLIMBUS_2 Hostless Playback",
.cpu_dai_name = "msm-dai-q6-dev.16388",
.platform_name = "msm-pcm-hostless",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_rx2",
.ignore_suspend = 1,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ops = &apq8074_slimbus_2_be_ops,
},
/* Ultrasound TX Back End DAI Link */
{
.name = "SLIMBUS_2 Hostless Capture",
.stream_name = "SLIMBUS_2 Hostless Capture",
.cpu_dai_name = "msm-dai-q6-dev.16389",
.platform_name = "msm-pcm-hostless",
.codec_name = "taiko_codec",
.codec_dai_name = "taiko_tx2",
.ignore_suspend = 1,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ops = &apq8074_slimbus_2_be_ops,
},
};
static struct snd_soc_dai_link apq8074_hdmi_dai_link[] = {
/* HDMI BACK END DAI Link */
{
.name = LPASS_BE_HDMI,
.stream_name = "HDMI Playback",
.cpu_dai_name = "msm-dai-q6-hdmi.8",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-hdmi-audio-codec-rx",
.codec_dai_name = "msm_hdmi_audio_codec_rx_dai",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_HDMI_RX,
.be_hw_params_fixup = apq8074_hdmi_be_hw_params_fixup,
.ignore_pmdown_time = 1,
.ignore_suspend = 1,
},
};
static struct snd_soc_dai_link apq8074_dai_links[
ARRAY_SIZE(apq8074_common_dai_links) +
ARRAY_SIZE(apq8074_hdmi_dai_link)];
struct snd_soc_card snd_soc_card_apq8074 = {
.name = "apq8074-taiko-snd-card",
};
static int apq8074_dtparse_auxpcm(struct platform_device *pdev,
struct msm_auxpcm_ctrl **auxpcm_ctrl,
char *msm_auxpcm_gpio_name[][2])
{
int ret = 0;
int i = 0;
struct msm_auxpcm_gpio *pin_data = NULL;
struct msm_auxpcm_ctrl *ctrl;
unsigned int gpio_no[NUM_OF_AUXPCM_GPIOS];
enum of_gpio_flags flags = OF_GPIO_ACTIVE_LOW;
int auxpcm_cnt = 0;
pin_data = devm_kzalloc(&pdev->dev, (ARRAY_SIZE(gpio_no) *
sizeof(struct msm_auxpcm_gpio)),
GFP_KERNEL);
if (!pin_data) {
dev_err(&pdev->dev, "No memory for gpio\n");
ret = -ENOMEM;
goto err;
}
for (i = 0; i < ARRAY_SIZE(gpio_no); i++) {
gpio_no[i] = of_get_named_gpio_flags(pdev->dev.of_node,
msm_auxpcm_gpio_name[i][DT_PARSE_INDEX],
0, &flags);
if (gpio_no[i] > 0) {
pin_data[i].gpio_name =
msm_auxpcm_gpio_name[auxpcm_cnt][GPIO_NAME_INDEX];
pin_data[i].gpio_no = gpio_no[i];
dev_dbg(&pdev->dev, "%s:GPIO gpio[%s] =\n"
"0x%x\n", __func__,
pin_data[i].gpio_name,
pin_data[i].gpio_no);
auxpcm_cnt++;
} else {
dev_err(&pdev->dev, "%s:Invalid AUXPCM GPIO[%s]= %x\n",
__func__,
msm_auxpcm_gpio_name[i][GPIO_NAME_INDEX],
gpio_no[i]);
ret = -ENODEV;
goto err;
}
}
ctrl = devm_kzalloc(&pdev->dev,
sizeof(struct msm_auxpcm_ctrl), GFP_KERNEL);
if (!ctrl) {
dev_err(&pdev->dev, "No memory for gpio\n");
ret = -ENOMEM;
goto err;
}
ctrl->pin_data = pin_data;
ctrl->cnt = auxpcm_cnt;
*auxpcm_ctrl = ctrl;
return ret;
err:
if (pin_data)
devm_kfree(&pdev->dev, pin_data);
return ret;
}
static int apq8074_prepare_codec_mclk(struct snd_soc_card *card)
{
struct apq8074_asoc_mach_data *pdata = snd_soc_card_get_drvdata(card);
int ret;
if (pdata->mclk_gpio) {
ret = gpio_request(pdata->mclk_gpio, "TAIKO_CODEC_PMIC_MCLK");
if (ret) {
dev_err(card->dev,
"%s: Failed to request taiko mclk gpio %d\n",
__func__, pdata->mclk_gpio);
return ret;
}
}
return 0;
}
static int apq8074_prepare_us_euro(struct snd_soc_card *card)
{
struct apq8074_asoc_mach_data *pdata = snd_soc_card_get_drvdata(card);
int ret;
if (pdata->us_euro_gpio) {
dev_dbg(card->dev, "%s : us_euro gpio request %d", __func__,
pdata->us_euro_gpio);
ret = gpio_request(pdata->us_euro_gpio, "TAIKO_CODEC_US_EURO");
if (ret) {
dev_err(card->dev,
"%s: Failed to request taiko US/EURO gpio %d error %d\n",
__func__, pdata->us_euro_gpio, ret);
return ret;
}
}
return 0;
}
static int apq8074_asoc_machine_probe(struct platform_device *pdev)
{
struct snd_soc_card *card = &snd_soc_card_apq8074;
struct apq8074_asoc_mach_data *pdata;
int ret;
const char *auxpcm_pri_gpio_set = NULL;
if (!pdev->dev.of_node) {
dev_err(&pdev->dev, "No platform supplied from device tree\n");
return -EINVAL;
}
pdata = devm_kzalloc(&pdev->dev,
sizeof(struct apq8074_asoc_mach_data), GFP_KERNEL);
if (!pdata) {
dev_err(&pdev->dev, "Can't allocate apq8074_asoc_mach_data\n");
return -ENOMEM;
}
/* Parse AUXPCM info from DT */
ret = apq8074_dtparse_auxpcm(pdev, &pdata->pri_auxpcm_ctrl,
msm_prim_auxpcm_gpio_name);
if (ret) {
dev_err(&pdev->dev,
"%s: Auxpcm pin data parse failed\n", __func__);
goto err;
}
card->dev = &pdev->dev;
platform_set_drvdata(pdev, card);
snd_soc_card_set_drvdata(card, pdata);
ret = snd_soc_of_parse_card_name(card, "qcom,model");
if (ret)
goto err;
ret = snd_soc_of_parse_audio_routing(card,
"qcom,audio-routing");
if (ret)
goto err;
ret = of_property_read_u32(pdev->dev.of_node,
"qcom,taiko-mclk-clk-freq", &pdata->mclk_freq);
if (ret) {
dev_err(&pdev->dev, "Looking up %s property in node %s failed",
"qcom,taiko-mclk-clk-freq",
pdev->dev.of_node->full_name);
goto err;
}
if (pdata->mclk_freq != 9600000) {
dev_err(&pdev->dev, "unsupported taiko mclk freq %u\n",
pdata->mclk_freq);
ret = -EINVAL;
goto err;
}
pdata->mclk_gpio = of_get_named_gpio(pdev->dev.of_node,
"qcom,cdc-mclk-gpios", 0);
if (pdata->mclk_gpio < 0) {
dev_err(&pdev->dev,
"Looking up %s property in node %s failed %d\n",
"qcom, cdc-mclk-gpios", pdev->dev.of_node->full_name,
pdata->mclk_gpio);
ret = -ENODEV;
goto err;
}
ret = apq8074_prepare_codec_mclk(card);
if (ret)
goto err;
if (of_property_read_bool(pdev->dev.of_node, "qcom,hdmi-audio-rx")) {
dev_info(&pdev->dev, "%s(): hdmi audio support present\n",
__func__);
memcpy(apq8074_dai_links, apq8074_common_dai_links,
sizeof(apq8074_common_dai_links));
memcpy(apq8074_dai_links + ARRAY_SIZE(apq8074_common_dai_links),
apq8074_hdmi_dai_link, sizeof(apq8074_hdmi_dai_link));
card->dai_link = apq8074_dai_links;
card->num_links = ARRAY_SIZE(apq8074_dai_links);
} else {
dev_info(&pdev->dev, "%s(): No hdmi audio support\n", __func__);
card->dai_link = apq8074_common_dai_links;
card->num_links = ARRAY_SIZE(apq8074_common_dai_links);
}
pdata->us_euro_gpio = of_get_named_gpio(pdev->dev.of_node,
"qcom,us-euro-gpios", 0);
if (pdata->us_euro_gpio < 0) {
dev_err(&pdev->dev, "Looking up %s property in node %s failed",
"qcom,us-euro-gpios",
pdev->dev.of_node->full_name);
} else {
dev_dbg(&pdev->dev, "%s detected %d",
"qcom,us-euro-gpios", pdata->us_euro_gpio);
mbhc_cfg.swap_gnd_mic = apq8074_swap_gnd_mic;
}
ret = apq8074_prepare_us_euro(card);
if (ret)
dev_err(&pdev->dev, "apq8074_prepare_us_euro failed (%d)\n",
ret);
mutex_init(&cdc_mclk_mutex);
atomic_set(&prim_auxpcm_rsc_ref, 0);
spdev = pdev;
ext_spk_amp_regulator = NULL;
apq8074_liquid_dock_dev = NULL;
ret = snd_soc_register_card(card);
if (ret) {
dev_err(&pdev->dev, "snd_soc_register_card failed (%d)\n",
ret);
goto err;
}
ret = of_property_read_string(pdev->dev.of_node,
"qcom,prim-auxpcm-gpio-set", &auxpcm_pri_gpio_set);
if (ret) {
dev_err(&pdev->dev, "Looking up %s property in node %s failed",
"qcom,prim-auxpcm-gpio-set",
pdev->dev.of_node->full_name);
goto err;
}
if (!strcmp(auxpcm_pri_gpio_set, "prim-gpio-prim")) {
lpaif_pri_muxsel_virt_addr =
ioremap(LPAIF_PRI_MODE_MUXSEL, 4);
} else if (!strcmp(auxpcm_pri_gpio_set, "prim-gpio-tert")) {
lpaif_pri_muxsel_virt_addr =
ioremap(LPAIF_TER_MODE_MUXSEL, 4);
} else {
dev_err(&pdev->dev, "Invalid value %s for AUXPCM GPIO set\n",
auxpcm_pri_gpio_set);
ret = -EINVAL;
goto err;
}
if (lpaif_pri_muxsel_virt_addr == NULL) {
pr_err("%s Pri muxsel virt addr is null\n", __func__);
ret = -EINVAL;
goto err;
}
return 0;
err:
if (pdata->mclk_gpio > 0) {
dev_dbg(&pdev->dev, "%s free gpio %d\n",
__func__, pdata->mclk_gpio);
gpio_free(pdata->mclk_gpio);
pdata->mclk_gpio = 0;
}
if (pdata->us_euro_gpio > 0) {
dev_dbg(&pdev->dev, "%s free us_euro gpio %d\n",
__func__, pdata->us_euro_gpio);
gpio_free(pdata->us_euro_gpio);
pdata->us_euro_gpio = 0;
}
devm_kfree(&pdev->dev, pdata);
return ret;
}
static int apq8074_asoc_machine_remove(struct platform_device *pdev)
{
struct snd_soc_card *card = platform_get_drvdata(pdev);
struct apq8074_asoc_mach_data *pdata = snd_soc_card_get_drvdata(card);
if (ext_spk_amp_regulator)
regulator_put(ext_spk_amp_regulator);
if (gpio_is_valid(ext_ult_spk_amp_gpio))
gpio_free(ext_ult_spk_amp_gpio);
gpio_free(pdata->mclk_gpio);
gpio_free(pdata->us_euro_gpio);
if (gpio_is_valid(ext_spk_amp_gpio))
gpio_free(ext_spk_amp_gpio);
if (apq8074_liquid_dock_dev != NULL) {
if (apq8074_liquid_dock_dev->dock_plug_gpio)
gpio_free(apq8074_liquid_dock_dev->dock_plug_gpio);
if (apq8074_liquid_dock_dev->dock_plug_irq)
free_irq(apq8074_liquid_dock_dev->dock_plug_irq,
apq8074_liquid_dock_dev);
kfree(apq8074_liquid_dock_dev);
apq8074_liquid_dock_dev = NULL;
}
iounmap(lpaif_pri_muxsel_virt_addr);
snd_soc_unregister_card(card);
return 0;
}
static const struct of_device_id apq8074_asoc_machine_of_match[] = {
{ .compatible = "qcom,apq8074-audio-taiko", },
{},
};
static struct platform_driver apq8074_asoc_machine_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
.pm = &snd_soc_pm_ops,
.of_match_table = apq8074_asoc_machine_of_match,
},
.probe = apq8074_asoc_machine_probe,
.remove = apq8074_asoc_machine_remove,
};
module_platform_driver(apq8074_asoc_machine_driver);
MODULE_DESCRIPTION("ALSA SoC msm");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:" DRV_NAME);
MODULE_DEVICE_TABLE(of, apq8074_asoc_machine_of_match);
| gpl-2.0 |
dirtyredmi2/kernel | drivers/video/console/fbcon_cw.c | 1792 | 10761 | /*
* linux/drivers/video/console/fbcon_ud.c -- Software Rotation - 90 degrees
*
* Copyright (C) 2005 Antonino Daplas <adaplas @pol.net>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/fb.h>
#include <linux/vt_kern.h>
#include <linux/console.h>
#include <asm/types.h>
#include "fbcon.h"
#include "fbcon_rotate.h"
/*
* Rotation 90 degrees
*/
static void cw_update_attr(u8 *dst, u8 *src, int attribute,
struct vc_data *vc)
{
int i, j, offset = (vc->vc_font.height < 10) ? 1 : 2;
int width = (vc->vc_font.height + 7) >> 3;
u8 c, msk = ~(0xff >> offset);
for (i = 0; i < vc->vc_font.width; i++) {
for (j = 0; j < width; j++) {
c = *src;
if (attribute & FBCON_ATTRIBUTE_UNDERLINE && !j)
c |= msk;
if (attribute & FBCON_ATTRIBUTE_BOLD && i)
c |= *(src-width);
if (attribute & FBCON_ATTRIBUTE_REVERSE)
c = ~c;
src++;
*dst++ = c;
}
}
}
static void cw_bmove(struct vc_data *vc, struct fb_info *info, int sy,
int sx, int dy, int dx, int height, int width)
{
struct fbcon_ops *ops = info->fbcon_par;
struct fb_copyarea area;
u32 vxres = GETVXRES(ops->p->scrollmode, info);
area.sx = vxres - ((sy + height) * vc->vc_font.height);
area.sy = sx * vc->vc_font.width;
area.dx = vxres - ((dy + height) * vc->vc_font.height);
area.dy = dx * vc->vc_font.width;
area.width = height * vc->vc_font.height;
area.height = width * vc->vc_font.width;
info->fbops->fb_copyarea(info, &area);
}
static void cw_clear(struct vc_data *vc, struct fb_info *info, int sy,
int sx, int height, int width)
{
struct fbcon_ops *ops = info->fbcon_par;
struct fb_fillrect region;
int bgshift = (vc->vc_hi_font_mask) ? 13 : 12;
u32 vxres = GETVXRES(ops->p->scrollmode, info);
region.color = attr_bgcol_ec(bgshift,vc,info);
region.dx = vxres - ((sy + height) * vc->vc_font.height);
region.dy = sx * vc->vc_font.width;
region.height = width * vc->vc_font.width;
region.width = height * vc->vc_font.height;
region.rop = ROP_COPY;
info->fbops->fb_fillrect(info, ®ion);
}
static inline void cw_putcs_aligned(struct vc_data *vc, struct fb_info *info,
const u16 *s, u32 attr, u32 cnt,
u32 d_pitch, u32 s_pitch, u32 cellsize,
struct fb_image *image, u8 *buf, u8 *dst)
{
struct fbcon_ops *ops = info->fbcon_par;
u16 charmask = vc->vc_hi_font_mask ? 0x1ff : 0xff;
u32 idx = (vc->vc_font.height + 7) >> 3;
u8 *src;
while (cnt--) {
src = ops->fontbuffer + (scr_readw(s++) & charmask)*cellsize;
if (attr) {
cw_update_attr(buf, src, attr, vc);
src = buf;
}
if (likely(idx == 1))
__fb_pad_aligned_buffer(dst, d_pitch, src, idx,
vc->vc_font.width);
else
fb_pad_aligned_buffer(dst, d_pitch, src, idx,
vc->vc_font.width);
dst += d_pitch * vc->vc_font.width;
}
info->fbops->fb_imageblit(info, image);
}
static void cw_putcs(struct vc_data *vc, struct fb_info *info,
const unsigned short *s, int count, int yy, int xx,
int fg, int bg)
{
struct fb_image image;
struct fbcon_ops *ops = info->fbcon_par;
u32 width = (vc->vc_font.height + 7)/8;
u32 cellsize = width * vc->vc_font.width;
u32 maxcnt = info->pixmap.size/cellsize;
u32 scan_align = info->pixmap.scan_align - 1;
u32 buf_align = info->pixmap.buf_align - 1;
u32 cnt, pitch, size;
u32 attribute = get_attribute(info, scr_readw(s));
u8 *dst, *buf = NULL;
u32 vxres = GETVXRES(ops->p->scrollmode, info);
if (!ops->fontbuffer)
return;
image.fg_color = fg;
image.bg_color = bg;
image.dx = vxres - ((yy + 1) * vc->vc_font.height);
image.dy = xx * vc->vc_font.width;
image.width = vc->vc_font.height;
image.depth = 1;
if (attribute) {
buf = kmalloc(cellsize, GFP_KERNEL);
if (!buf)
return;
}
while (count) {
if (count > maxcnt)
cnt = maxcnt;
else
cnt = count;
image.height = vc->vc_font.width * cnt;
pitch = ((image.width + 7) >> 3) + scan_align;
pitch &= ~scan_align;
size = pitch * image.height + buf_align;
size &= ~buf_align;
dst = fb_get_buffer_offset(info, &info->pixmap, size);
image.data = dst;
cw_putcs_aligned(vc, info, s, attribute, cnt, pitch,
width, cellsize, &image, buf, dst);
image.dy += image.height;
count -= cnt;
s += cnt;
}
/* buf is always NULL except when in monochrome mode, so in this case
it's a gain to check buf against NULL even though kfree() handles
NULL pointers just fine */
if (unlikely(buf))
kfree(buf);
}
static void cw_clear_margins(struct vc_data *vc, struct fb_info *info,
int bottom_only)
{
unsigned int cw = vc->vc_font.width;
unsigned int ch = vc->vc_font.height;
unsigned int rw = info->var.yres - (vc->vc_cols*cw);
unsigned int bh = info->var.xres - (vc->vc_rows*ch);
unsigned int rs = info->var.yres - rw;
struct fb_fillrect region;
int bgshift = (vc->vc_hi_font_mask) ? 13 : 12;
region.color = attr_bgcol_ec(bgshift,vc,info);
region.rop = ROP_COPY;
if (rw && !bottom_only) {
region.dx = 0;
region.dy = info->var.yoffset + rs;
region.height = rw;
region.width = info->var.xres_virtual;
info->fbops->fb_fillrect(info, ®ion);
}
if (bh) {
region.dx = info->var.xoffset;
region.dy = info->var.yoffset;
region.height = info->var.yres;
region.width = bh;
info->fbops->fb_fillrect(info, ®ion);
}
}
static void cw_cursor(struct vc_data *vc, struct fb_info *info, int mode,
int softback_lines, int fg, int bg)
{
struct fb_cursor cursor;
struct fbcon_ops *ops = info->fbcon_par;
unsigned short charmask = vc->vc_hi_font_mask ? 0x1ff : 0xff;
int w = (vc->vc_font.height + 7) >> 3, c;
int y = real_y(ops->p, vc->vc_y);
int attribute, use_sw = (vc->vc_cursor_type & 0x10);
int err = 1, dx, dy;
char *src;
u32 vxres = GETVXRES(ops->p->scrollmode, info);
if (!ops->fontbuffer)
return;
cursor.set = 0;
if (softback_lines) {
if (y + softback_lines >= vc->vc_rows) {
mode = CM_ERASE;
ops->cursor_flash = 0;
return;
} else
y += softback_lines;
}
c = scr_readw((u16 *) vc->vc_pos);
attribute = get_attribute(info, c);
src = ops->fontbuffer + ((c & charmask) * (w * vc->vc_font.width));
if (ops->cursor_state.image.data != src ||
ops->cursor_reset) {
ops->cursor_state.image.data = src;
cursor.set |= FB_CUR_SETIMAGE;
}
if (attribute) {
u8 *dst;
dst = kmalloc(w * vc->vc_font.width, GFP_ATOMIC);
if (!dst)
return;
kfree(ops->cursor_data);
ops->cursor_data = dst;
cw_update_attr(dst, src, attribute, vc);
src = dst;
}
if (ops->cursor_state.image.fg_color != fg ||
ops->cursor_state.image.bg_color != bg ||
ops->cursor_reset) {
ops->cursor_state.image.fg_color = fg;
ops->cursor_state.image.bg_color = bg;
cursor.set |= FB_CUR_SETCMAP;
}
if (ops->cursor_state.image.height != vc->vc_font.width ||
ops->cursor_state.image.width != vc->vc_font.height ||
ops->cursor_reset) {
ops->cursor_state.image.height = vc->vc_font.width;
ops->cursor_state.image.width = vc->vc_font.height;
cursor.set |= FB_CUR_SETSIZE;
}
dx = vxres - ((y * vc->vc_font.height) + vc->vc_font.height);
dy = vc->vc_x * vc->vc_font.width;
if (ops->cursor_state.image.dx != dx ||
ops->cursor_state.image.dy != dy ||
ops->cursor_reset) {
ops->cursor_state.image.dx = dx;
ops->cursor_state.image.dy = dy;
cursor.set |= FB_CUR_SETPOS;
}
if (ops->cursor_state.hot.x || ops->cursor_state.hot.y ||
ops->cursor_reset) {
ops->cursor_state.hot.x = cursor.hot.y = 0;
cursor.set |= FB_CUR_SETHOT;
}
if (cursor.set & FB_CUR_SETSIZE ||
vc->vc_cursor_type != ops->p->cursor_shape ||
ops->cursor_state.mask == NULL ||
ops->cursor_reset) {
char *tmp, *mask = kmalloc(w*vc->vc_font.width, GFP_ATOMIC);
int cur_height, size, i = 0;
int width = (vc->vc_font.width + 7)/8;
if (!mask)
return;
tmp = kmalloc(width * vc->vc_font.height, GFP_ATOMIC);
if (!tmp) {
kfree(mask);
return;
}
kfree(ops->cursor_state.mask);
ops->cursor_state.mask = mask;
ops->p->cursor_shape = vc->vc_cursor_type;
cursor.set |= FB_CUR_SETSHAPE;
switch (ops->p->cursor_shape & CUR_HWMASK) {
case CUR_NONE:
cur_height = 0;
break;
case CUR_UNDERLINE:
cur_height = (vc->vc_font.height < 10) ? 1 : 2;
break;
case CUR_LOWER_THIRD:
cur_height = vc->vc_font.height/3;
break;
case CUR_LOWER_HALF:
cur_height = vc->vc_font.height >> 1;
break;
case CUR_TWO_THIRDS:
cur_height = (vc->vc_font.height << 1)/3;
break;
case CUR_BLOCK:
default:
cur_height = vc->vc_font.height;
break;
}
size = (vc->vc_font.height - cur_height) * width;
while (size--)
tmp[i++] = 0;
size = cur_height * width;
while (size--)
tmp[i++] = 0xff;
memset(mask, 0, w * vc->vc_font.width);
rotate_cw(tmp, mask, vc->vc_font.width, vc->vc_font.height);
kfree(tmp);
}
switch (mode) {
case CM_ERASE:
ops->cursor_state.enable = 0;
break;
case CM_DRAW:
case CM_MOVE:
default:
ops->cursor_state.enable = (use_sw) ? 0 : 1;
break;
}
cursor.image.data = src;
cursor.image.fg_color = ops->cursor_state.image.fg_color;
cursor.image.bg_color = ops->cursor_state.image.bg_color;
cursor.image.dx = ops->cursor_state.image.dx;
cursor.image.dy = ops->cursor_state.image.dy;
cursor.image.height = ops->cursor_state.image.height;
cursor.image.width = ops->cursor_state.image.width;
cursor.hot.x = ops->cursor_state.hot.x;
cursor.hot.y = ops->cursor_state.hot.y;
cursor.mask = ops->cursor_state.mask;
cursor.enable = ops->cursor_state.enable;
cursor.image.depth = 1;
cursor.rop = ROP_XOR;
if (info->fbops->fb_cursor)
err = info->fbops->fb_cursor(info, &cursor);
if (err)
soft_cursor(info, &cursor);
ops->cursor_reset = 0;
}
static int cw_update_start(struct fb_info *info)
{
struct fbcon_ops *ops = info->fbcon_par;
u32 vxres = GETVXRES(ops->p->scrollmode, info);
u32 xoffset;
int err;
xoffset = vxres - (info->var.xres + ops->var.yoffset);
ops->var.yoffset = ops->var.xoffset;
ops->var.xoffset = xoffset;
err = fb_pan_display(info, &ops->var);
ops->var.xoffset = info->var.xoffset;
ops->var.yoffset = info->var.yoffset;
ops->var.vmode = info->var.vmode;
return err;
}
void fbcon_rotate_cw(struct fbcon_ops *ops)
{
ops->bmove = cw_bmove;
ops->clear = cw_clear;
ops->putcs = cw_putcs;
ops->clear_margins = cw_clear_margins;
ops->cursor = cw_cursor;
ops->update_start = cw_update_start;
}
EXPORT_SYMBOL(fbcon_rotate_cw);
MODULE_AUTHOR("Antonino Daplas <adaplas@pol.net>");
MODULE_DESCRIPTION("Console Rotation (90 degrees) Support");
MODULE_LICENSE("GPL");
| gpl-2.0 |
dferg/samsung_hercskynote_kernels | kernel/stop_machine.c | 2304 | 13267 | /*
* kernel/stop_machine.c
*
* Copyright (C) 2008, 2005 IBM Corporation.
* Copyright (C) 2008, 2005 Rusty Russell rusty@rustcorp.com.au
* Copyright (C) 2010 SUSE Linux Products GmbH
* Copyright (C) 2010 Tejun Heo <tj@kernel.org>
*
* This file is released under the GPLv2 and any later version.
*/
#include <linux/completion.h>
#include <linux/cpu.h>
#include <linux/init.h>
#include <linux/kthread.h>
#include <linux/module.h>
#include <linux/percpu.h>
#include <linux/sched.h>
#include <linux/stop_machine.h>
#include <linux/interrupt.h>
#include <linux/kallsyms.h>
#include <asm/atomic.h>
/*
* Structure to determine completion condition and record errors. May
* be shared by works on different cpus.
*/
struct cpu_stop_done {
atomic_t nr_todo; /* nr left to execute */
bool executed; /* actually executed? */
int ret; /* collected return value */
struct completion completion; /* fired if nr_todo reaches 0 */
};
/* the actual stopper, one per every possible cpu, enabled on online cpus */
struct cpu_stopper {
spinlock_t lock;
bool enabled; /* is this stopper enabled? */
struct list_head works; /* list of pending works */
struct task_struct *thread; /* stopper thread */
};
static DEFINE_PER_CPU(struct cpu_stopper, cpu_stopper);
static void cpu_stop_init_done(struct cpu_stop_done *done, unsigned int nr_todo)
{
memset(done, 0, sizeof(*done));
atomic_set(&done->nr_todo, nr_todo);
init_completion(&done->completion);
}
/* signal completion unless @done is NULL */
static void cpu_stop_signal_done(struct cpu_stop_done *done, bool executed)
{
if (done) {
if (executed)
done->executed = true;
if (atomic_dec_and_test(&done->nr_todo))
complete(&done->completion);
}
}
/* queue @work to @stopper. if offline, @work is completed immediately */
static void cpu_stop_queue_work(struct cpu_stopper *stopper,
struct cpu_stop_work *work)
{
unsigned long flags;
spin_lock_irqsave(&stopper->lock, flags);
if (stopper->enabled) {
list_add_tail(&work->list, &stopper->works);
wake_up_process(stopper->thread);
} else
cpu_stop_signal_done(work->done, false);
spin_unlock_irqrestore(&stopper->lock, flags);
}
/**
* stop_one_cpu - stop a cpu
* @cpu: cpu to stop
* @fn: function to execute
* @arg: argument to @fn
*
* Execute @fn(@arg) on @cpu. @fn is run in a process context with
* the highest priority preempting any task on the cpu and
* monopolizing it. This function returns after the execution is
* complete.
*
* This function doesn't guarantee @cpu stays online till @fn
* completes. If @cpu goes down in the middle, execution may happen
* partially or fully on different cpus. @fn should either be ready
* for that or the caller should ensure that @cpu stays online until
* this function completes.
*
* CONTEXT:
* Might sleep.
*
* RETURNS:
* -ENOENT if @fn(@arg) was not executed because @cpu was offline;
* otherwise, the return value of @fn.
*/
int stop_one_cpu(unsigned int cpu, cpu_stop_fn_t fn, void *arg)
{
struct cpu_stop_done done;
struct cpu_stop_work work = { .fn = fn, .arg = arg, .done = &done };
cpu_stop_init_done(&done, 1);
cpu_stop_queue_work(&per_cpu(cpu_stopper, cpu), &work);
wait_for_completion(&done.completion);
return done.executed ? done.ret : -ENOENT;
}
/**
* stop_one_cpu_nowait - stop a cpu but don't wait for completion
* @cpu: cpu to stop
* @fn: function to execute
* @arg: argument to @fn
*
* Similar to stop_one_cpu() but doesn't wait for completion. The
* caller is responsible for ensuring @work_buf is currently unused
* and will remain untouched until stopper starts executing @fn.
*
* CONTEXT:
* Don't care.
*/
void stop_one_cpu_nowait(unsigned int cpu, cpu_stop_fn_t fn, void *arg,
struct cpu_stop_work *work_buf)
{
*work_buf = (struct cpu_stop_work){ .fn = fn, .arg = arg, };
cpu_stop_queue_work(&per_cpu(cpu_stopper, cpu), work_buf);
}
DEFINE_MUTEX(stop_cpus_mutex);
/* static data for stop_cpus */
static DEFINE_PER_CPU(struct cpu_stop_work, stop_cpus_work);
int __stop_cpus(const struct cpumask *cpumask, cpu_stop_fn_t fn, void *arg)
{
struct cpu_stop_work *work;
struct cpu_stop_done done;
unsigned int cpu;
/* initialize works and done */
for_each_cpu(cpu, cpumask) {
work = &per_cpu(stop_cpus_work, cpu);
work->fn = fn;
work->arg = arg;
work->done = &done;
}
cpu_stop_init_done(&done, cpumask_weight(cpumask));
/*
* Disable preemption while queueing to avoid getting
* preempted by a stopper which might wait for other stoppers
* to enter @fn which can lead to deadlock.
*/
preempt_disable();
for_each_cpu(cpu, cpumask)
cpu_stop_queue_work(&per_cpu(cpu_stopper, cpu),
&per_cpu(stop_cpus_work, cpu));
preempt_enable();
wait_for_completion(&done.completion);
return done.executed ? done.ret : -ENOENT;
}
/**
* stop_cpus - stop multiple cpus
* @cpumask: cpus to stop
* @fn: function to execute
* @arg: argument to @fn
*
* Execute @fn(@arg) on online cpus in @cpumask. On each target cpu,
* @fn is run in a process context with the highest priority
* preempting any task on the cpu and monopolizing it. This function
* returns after all executions are complete.
*
* This function doesn't guarantee the cpus in @cpumask stay online
* till @fn completes. If some cpus go down in the middle, execution
* on the cpu may happen partially or fully on different cpus. @fn
* should either be ready for that or the caller should ensure that
* the cpus stay online until this function completes.
*
* All stop_cpus() calls are serialized making it safe for @fn to wait
* for all cpus to start executing it.
*
* CONTEXT:
* Might sleep.
*
* RETURNS:
* -ENOENT if @fn(@arg) was not executed at all because all cpus in
* @cpumask were offline; otherwise, 0 if all executions of @fn
* returned 0, any non zero return value if any returned non zero.
*/
int stop_cpus(const struct cpumask *cpumask, cpu_stop_fn_t fn, void *arg)
{
int ret;
/* static works are used, process one request at a time */
mutex_lock(&stop_cpus_mutex);
ret = __stop_cpus(cpumask, fn, arg);
mutex_unlock(&stop_cpus_mutex);
return ret;
}
/**
* try_stop_cpus - try to stop multiple cpus
* @cpumask: cpus to stop
* @fn: function to execute
* @arg: argument to @fn
*
* Identical to stop_cpus() except that it fails with -EAGAIN if
* someone else is already using the facility.
*
* CONTEXT:
* Might sleep.
*
* RETURNS:
* -EAGAIN if someone else is already stopping cpus, -ENOENT if
* @fn(@arg) was not executed at all because all cpus in @cpumask were
* offline; otherwise, 0 if all executions of @fn returned 0, any non
* zero return value if any returned non zero.
*/
int try_stop_cpus(const struct cpumask *cpumask, cpu_stop_fn_t fn, void *arg)
{
int ret;
/* static works are used, process one request at a time */
if (!mutex_trylock(&stop_cpus_mutex))
return -EAGAIN;
ret = __stop_cpus(cpumask, fn, arg);
mutex_unlock(&stop_cpus_mutex);
return ret;
}
static int cpu_stopper_thread(void *data)
{
struct cpu_stopper *stopper = data;
struct cpu_stop_work *work;
int ret;
repeat:
set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
if (kthread_should_stop()) {
__set_current_state(TASK_RUNNING);
return 0;
}
work = NULL;
spin_lock_irq(&stopper->lock);
if (!list_empty(&stopper->works)) {
work = list_first_entry(&stopper->works,
struct cpu_stop_work, list);
list_del_init(&work->list);
}
spin_unlock_irq(&stopper->lock);
if (work) {
cpu_stop_fn_t fn = work->fn;
void *arg = work->arg;
struct cpu_stop_done *done = work->done;
char ksym_buf[KSYM_NAME_LEN] __maybe_unused;
__set_current_state(TASK_RUNNING);
/* cpu stop callbacks are not allowed to sleep */
preempt_disable();
ret = fn(arg);
if (ret)
done->ret = ret;
/* restore preemption and check it's still balanced */
preempt_enable();
WARN_ONCE(preempt_count(),
"cpu_stop: %s(%p) leaked preempt count\n",
kallsyms_lookup((unsigned long)fn, NULL, NULL, NULL,
ksym_buf), arg);
cpu_stop_signal_done(done, true);
} else
schedule();
goto repeat;
}
extern void sched_set_stop_task(int cpu, struct task_struct *stop);
/* manage stopper for a cpu, mostly lifted from sched migration thread mgmt */
static int __cpuinit cpu_stop_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
struct cpu_stopper *stopper = &per_cpu(cpu_stopper, cpu);
struct task_struct *p;
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_UP_PREPARE:
BUG_ON(stopper->thread || stopper->enabled ||
!list_empty(&stopper->works));
p = kthread_create_on_node(cpu_stopper_thread,
stopper,
cpu_to_node(cpu),
"migration/%d", cpu);
if (IS_ERR(p))
return notifier_from_errno(PTR_ERR(p));
get_task_struct(p);
kthread_bind(p, cpu);
sched_set_stop_task(cpu, p);
stopper->thread = p;
break;
case CPU_ONLINE:
/* strictly unnecessary, as first user will wake it */
wake_up_process(stopper->thread);
/* mark enabled */
spin_lock_irq(&stopper->lock);
stopper->enabled = true;
spin_unlock_irq(&stopper->lock);
break;
#ifdef CONFIG_HOTPLUG_CPU
case CPU_UP_CANCELED:
case CPU_POST_DEAD:
{
struct cpu_stop_work *work;
sched_set_stop_task(cpu, NULL);
/* kill the stopper */
kthread_stop(stopper->thread);
/* drain remaining works */
spin_lock_irq(&stopper->lock);
list_for_each_entry(work, &stopper->works, list)
cpu_stop_signal_done(work->done, false);
stopper->enabled = false;
spin_unlock_irq(&stopper->lock);
/* release the stopper */
put_task_struct(stopper->thread);
stopper->thread = NULL;
break;
}
#endif
}
return NOTIFY_OK;
}
/*
* Give it a higher priority so that cpu stopper is available to other
* cpu notifiers. It currently shares the same priority as sched
* migration_notifier.
*/
static struct notifier_block __cpuinitdata cpu_stop_cpu_notifier = {
.notifier_call = cpu_stop_cpu_callback,
.priority = 10,
};
static int __init cpu_stop_init(void)
{
void *bcpu = (void *)(long)smp_processor_id();
unsigned int cpu;
int err;
for_each_possible_cpu(cpu) {
struct cpu_stopper *stopper = &per_cpu(cpu_stopper, cpu);
spin_lock_init(&stopper->lock);
INIT_LIST_HEAD(&stopper->works);
}
/* start one for the boot cpu */
err = cpu_stop_cpu_callback(&cpu_stop_cpu_notifier, CPU_UP_PREPARE,
bcpu);
BUG_ON(err != NOTIFY_OK);
cpu_stop_cpu_callback(&cpu_stop_cpu_notifier, CPU_ONLINE, bcpu);
register_cpu_notifier(&cpu_stop_cpu_notifier);
return 0;
}
early_initcall(cpu_stop_init);
#ifdef CONFIG_STOP_MACHINE
/* This controls the threads on each CPU. */
enum stopmachine_state {
/* Dummy starting state for thread. */
STOPMACHINE_NONE,
/* Awaiting everyone to be scheduled. */
STOPMACHINE_PREPARE,
/* Disable interrupts. */
STOPMACHINE_DISABLE_IRQ,
/* Run the function */
STOPMACHINE_RUN,
/* Exit */
STOPMACHINE_EXIT,
};
struct stop_machine_data {
int (*fn)(void *);
void *data;
/* Like num_online_cpus(), but hotplug cpu uses us, so we need this. */
unsigned int num_threads;
const struct cpumask *active_cpus;
enum stopmachine_state state;
atomic_t thread_ack;
};
static void set_state(struct stop_machine_data *smdata,
enum stopmachine_state newstate)
{
/* Reset ack counter. */
atomic_set(&smdata->thread_ack, smdata->num_threads);
smp_wmb();
smdata->state = newstate;
}
/* Last one to ack a state moves to the next state. */
static void ack_state(struct stop_machine_data *smdata)
{
if (atomic_dec_and_test(&smdata->thread_ack))
set_state(smdata, smdata->state + 1);
}
/* This is the cpu_stop function which stops the CPU. */
static int stop_machine_cpu_stop(void *data)
{
struct stop_machine_data *smdata = data;
enum stopmachine_state curstate = STOPMACHINE_NONE;
int cpu = smp_processor_id(), err = 0;
bool is_active;
if (!smdata->active_cpus)
is_active = cpu == cpumask_first(cpu_online_mask);
else
is_active = cpumask_test_cpu(cpu, smdata->active_cpus);
/* Simple state machine */
do {
/* Chill out and ensure we re-read stopmachine_state. */
cpu_relax();
if (smdata->state != curstate) {
curstate = smdata->state;
switch (curstate) {
case STOPMACHINE_DISABLE_IRQ:
local_irq_disable();
hard_irq_disable();
break;
case STOPMACHINE_RUN:
if (is_active)
err = smdata->fn(smdata->data);
break;
default:
break;
}
ack_state(smdata);
}
} while (curstate != STOPMACHINE_EXIT);
local_irq_enable();
return err;
}
int __stop_machine(int (*fn)(void *), void *data, const struct cpumask *cpus)
{
struct stop_machine_data smdata = { .fn = fn, .data = data,
.num_threads = num_online_cpus(),
.active_cpus = cpus };
/* Set the initial state and stop all online cpus. */
set_state(&smdata, STOPMACHINE_PREPARE);
return stop_cpus(cpu_online_mask, stop_machine_cpu_stop, &smdata);
}
int stop_machine(int (*fn)(void *), void *data, const struct cpumask *cpus)
{
int ret;
/* No CPUs can come up or down during this. */
get_online_cpus();
ret = __stop_machine(fn, data, cpus);
put_online_cpus();
return ret;
}
EXPORT_SYMBOL_GPL(stop_machine);
#endif /* CONFIG_STOP_MACHINE */
| gpl-2.0 |
jdkoreclipse/cloaked-cyril | drivers/net/sfc/mcdi.c | 2304 | 31629 | /****************************************************************************
* Driver for Solarflare Solarstorm network controllers and boards
* Copyright 2008-2011 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/delay.h>
#include "net_driver.h"
#include "nic.h"
#include "io.h"
#include "regs.h"
#include "mcdi_pcol.h"
#include "phy.h"
/**************************************************************************
*
* Management-Controller-to-Driver Interface
*
**************************************************************************
*/
/* Software-defined structure to the shared-memory */
#define CMD_NOTIFY_PORT0 0
#define CMD_NOTIFY_PORT1 4
#define CMD_PDU_PORT0 0x008
#define CMD_PDU_PORT1 0x108
#define REBOOT_FLAG_PORT0 0x3f8
#define REBOOT_FLAG_PORT1 0x3fc
#define MCDI_RPC_TIMEOUT 10 /*seconds */
#define MCDI_PDU(efx) \
(efx_port_num(efx) ? CMD_PDU_PORT1 : CMD_PDU_PORT0)
#define MCDI_DOORBELL(efx) \
(efx_port_num(efx) ? CMD_NOTIFY_PORT1 : CMD_NOTIFY_PORT0)
#define MCDI_REBOOT_FLAG(efx) \
(efx_port_num(efx) ? REBOOT_FLAG_PORT1 : REBOOT_FLAG_PORT0)
#define SEQ_MASK \
EFX_MASK32(EFX_WIDTH(MCDI_HEADER_SEQ))
static inline struct efx_mcdi_iface *efx_mcdi(struct efx_nic *efx)
{
struct siena_nic_data *nic_data;
EFX_BUG_ON_PARANOID(efx_nic_rev(efx) < EFX_REV_SIENA_A0);
nic_data = efx->nic_data;
return &nic_data->mcdi;
}
void efx_mcdi_init(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (efx_nic_rev(efx) < EFX_REV_SIENA_A0)
return;
mcdi = efx_mcdi(efx);
init_waitqueue_head(&mcdi->wq);
spin_lock_init(&mcdi->iface_lock);
atomic_set(&mcdi->state, MCDI_STATE_QUIESCENT);
mcdi->mode = MCDI_MODE_POLL;
(void) efx_mcdi_poll_reboot(efx);
}
static void efx_mcdi_copyin(struct efx_nic *efx, unsigned cmd,
const u8 *inbuf, size_t inlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned pdu = FR_CZ_MC_TREG_SMEM + MCDI_PDU(efx);
unsigned doorbell = FR_CZ_MC_TREG_SMEM + MCDI_DOORBELL(efx);
unsigned int i;
efx_dword_t hdr;
u32 xflags, seqno;
BUG_ON(atomic_read(&mcdi->state) == MCDI_STATE_QUIESCENT);
BUG_ON(inlen & 3 || inlen >= 0x100);
seqno = mcdi->seqno & SEQ_MASK;
xflags = 0;
if (mcdi->mode == MCDI_MODE_EVENTS)
xflags |= MCDI_HEADER_XFLAGS_EVREQ;
EFX_POPULATE_DWORD_6(hdr,
MCDI_HEADER_RESPONSE, 0,
MCDI_HEADER_RESYNC, 1,
MCDI_HEADER_CODE, cmd,
MCDI_HEADER_DATALEN, inlen,
MCDI_HEADER_SEQ, seqno,
MCDI_HEADER_XFLAGS, xflags);
efx_writed(efx, &hdr, pdu);
for (i = 0; i < inlen; i += 4)
_efx_writed(efx, *((__le32 *)(inbuf + i)), pdu + 4 + i);
/* Ensure the payload is written out before the header */
wmb();
/* ring the doorbell with a distinctive value */
_efx_writed(efx, (__force __le32) 0x45789abc, doorbell);
}
static void efx_mcdi_copyout(struct efx_nic *efx, u8 *outbuf, size_t outlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned int pdu = FR_CZ_MC_TREG_SMEM + MCDI_PDU(efx);
int i;
BUG_ON(atomic_read(&mcdi->state) == MCDI_STATE_QUIESCENT);
BUG_ON(outlen & 3 || outlen >= 0x100);
for (i = 0; i < outlen; i += 4)
*((__le32 *)(outbuf + i)) = _efx_readd(efx, pdu + 4 + i);
}
static int efx_mcdi_poll(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned int time, finish;
unsigned int respseq, respcmd, error;
unsigned int pdu = FR_CZ_MC_TREG_SMEM + MCDI_PDU(efx);
unsigned int rc, spins;
efx_dword_t reg;
/* Check for a reboot atomically with respect to efx_mcdi_copyout() */
rc = -efx_mcdi_poll_reboot(efx);
if (rc)
goto out;
/* Poll for completion. Poll quickly (once a us) for the 1st jiffy,
* because generally mcdi responses are fast. After that, back off
* and poll once a jiffy (approximately)
*/
spins = TICK_USEC;
finish = get_seconds() + MCDI_RPC_TIMEOUT;
while (1) {
if (spins != 0) {
--spins;
udelay(1);
} else {
schedule_timeout_uninterruptible(1);
}
time = get_seconds();
rmb();
efx_readd(efx, ®, pdu);
/* All 1's indicates that shared memory is in reset (and is
* not a valid header). Wait for it to come out reset before
* completing the command */
if (EFX_DWORD_FIELD(reg, EFX_DWORD_0) != 0xffffffff &&
EFX_DWORD_FIELD(reg, MCDI_HEADER_RESPONSE))
break;
if (time >= finish)
return -ETIMEDOUT;
}
mcdi->resplen = EFX_DWORD_FIELD(reg, MCDI_HEADER_DATALEN);
respseq = EFX_DWORD_FIELD(reg, MCDI_HEADER_SEQ);
respcmd = EFX_DWORD_FIELD(reg, MCDI_HEADER_CODE);
error = EFX_DWORD_FIELD(reg, MCDI_HEADER_ERROR);
if (error && mcdi->resplen == 0) {
netif_err(efx, hw, efx->net_dev, "MC rebooted\n");
rc = EIO;
} else if ((respseq ^ mcdi->seqno) & SEQ_MASK) {
netif_err(efx, hw, efx->net_dev,
"MC response mismatch tx seq 0x%x rx seq 0x%x\n",
respseq, mcdi->seqno);
rc = EIO;
} else if (error) {
efx_readd(efx, ®, pdu + 4);
switch (EFX_DWORD_FIELD(reg, EFX_DWORD_0)) {
#define TRANSLATE_ERROR(name) \
case MC_CMD_ERR_ ## name: \
rc = name; \
break
TRANSLATE_ERROR(ENOENT);
TRANSLATE_ERROR(EINTR);
TRANSLATE_ERROR(EACCES);
TRANSLATE_ERROR(EBUSY);
TRANSLATE_ERROR(EINVAL);
TRANSLATE_ERROR(EDEADLK);
TRANSLATE_ERROR(ENOSYS);
TRANSLATE_ERROR(ETIME);
#undef TRANSLATE_ERROR
default:
rc = EIO;
break;
}
} else
rc = 0;
out:
mcdi->resprc = rc;
if (rc)
mcdi->resplen = 0;
/* Return rc=0 like wait_event_timeout() */
return 0;
}
/* Test and clear MC-rebooted flag for this port/function */
int efx_mcdi_poll_reboot(struct efx_nic *efx)
{
unsigned int addr = FR_CZ_MC_TREG_SMEM + MCDI_REBOOT_FLAG(efx);
efx_dword_t reg;
uint32_t value;
if (efx_nic_rev(efx) < EFX_REV_SIENA_A0)
return false;
efx_readd(efx, ®, addr);
value = EFX_DWORD_FIELD(reg, EFX_DWORD_0);
if (value == 0)
return 0;
EFX_ZERO_DWORD(reg);
efx_writed(efx, ®, addr);
if (value == MC_STATUS_DWORD_ASSERT)
return -EINTR;
else
return -EIO;
}
static void efx_mcdi_acquire(struct efx_mcdi_iface *mcdi)
{
/* Wait until the interface becomes QUIESCENT and we win the race
* to mark it RUNNING. */
wait_event(mcdi->wq,
atomic_cmpxchg(&mcdi->state,
MCDI_STATE_QUIESCENT,
MCDI_STATE_RUNNING)
== MCDI_STATE_QUIESCENT);
}
static int efx_mcdi_await_completion(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
if (wait_event_timeout(
mcdi->wq,
atomic_read(&mcdi->state) == MCDI_STATE_COMPLETED,
msecs_to_jiffies(MCDI_RPC_TIMEOUT * 1000)) == 0)
return -ETIMEDOUT;
/* Check if efx_mcdi_set_mode() switched us back to polled completions.
* In which case, poll for completions directly. If efx_mcdi_ev_cpl()
* completed the request first, then we'll just end up completing the
* request again, which is safe.
*
* We need an smp_rmb() to synchronise with efx_mcdi_mode_poll(), which
* wait_event_timeout() implicitly provides.
*/
if (mcdi->mode == MCDI_MODE_POLL)
return efx_mcdi_poll(efx);
return 0;
}
static bool efx_mcdi_complete(struct efx_mcdi_iface *mcdi)
{
/* If the interface is RUNNING, then move to COMPLETED and wake any
* waiters. If the interface isn't in RUNNING then we've received a
* duplicate completion after we've already transitioned back to
* QUIESCENT. [A subsequent invocation would increment seqno, so would
* have failed the seqno check].
*/
if (atomic_cmpxchg(&mcdi->state,
MCDI_STATE_RUNNING,
MCDI_STATE_COMPLETED) == MCDI_STATE_RUNNING) {
wake_up(&mcdi->wq);
return true;
}
return false;
}
static void efx_mcdi_release(struct efx_mcdi_iface *mcdi)
{
atomic_set(&mcdi->state, MCDI_STATE_QUIESCENT);
wake_up(&mcdi->wq);
}
static void efx_mcdi_ev_cpl(struct efx_nic *efx, unsigned int seqno,
unsigned int datalen, unsigned int errno)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
bool wake = false;
spin_lock(&mcdi->iface_lock);
if ((seqno ^ mcdi->seqno) & SEQ_MASK) {
if (mcdi->credits)
/* The request has been cancelled */
--mcdi->credits;
else
netif_err(efx, hw, efx->net_dev,
"MC response mismatch tx seq 0x%x rx "
"seq 0x%x\n", seqno, mcdi->seqno);
} else {
mcdi->resprc = errno;
mcdi->resplen = datalen;
wake = true;
}
spin_unlock(&mcdi->iface_lock);
if (wake)
efx_mcdi_complete(mcdi);
}
/* Issue the given command by writing the data into the shared memory PDU,
* ring the doorbell and wait for completion. Copyout the result. */
int efx_mcdi_rpc(struct efx_nic *efx, unsigned cmd,
const u8 *inbuf, size_t inlen, u8 *outbuf, size_t outlen,
size_t *outlen_actual)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
int rc;
BUG_ON(efx_nic_rev(efx) < EFX_REV_SIENA_A0);
efx_mcdi_acquire(mcdi);
/* Serialise with efx_mcdi_ev_cpl() and efx_mcdi_ev_death() */
spin_lock_bh(&mcdi->iface_lock);
++mcdi->seqno;
spin_unlock_bh(&mcdi->iface_lock);
efx_mcdi_copyin(efx, cmd, inbuf, inlen);
if (mcdi->mode == MCDI_MODE_POLL)
rc = efx_mcdi_poll(efx);
else
rc = efx_mcdi_await_completion(efx);
if (rc != 0) {
/* Close the race with efx_mcdi_ev_cpl() executing just too late
* and completing a request we've just cancelled, by ensuring
* that the seqno check therein fails.
*/
spin_lock_bh(&mcdi->iface_lock);
++mcdi->seqno;
++mcdi->credits;
spin_unlock_bh(&mcdi->iface_lock);
netif_err(efx, hw, efx->net_dev,
"MC command 0x%x inlen %d mode %d timed out\n",
cmd, (int)inlen, mcdi->mode);
} else {
size_t resplen;
/* At the very least we need a memory barrier here to ensure
* we pick up changes from efx_mcdi_ev_cpl(). Protect against
* a spurious efx_mcdi_ev_cpl() running concurrently by
* acquiring the iface_lock. */
spin_lock_bh(&mcdi->iface_lock);
rc = -mcdi->resprc;
resplen = mcdi->resplen;
spin_unlock_bh(&mcdi->iface_lock);
if (rc == 0) {
efx_mcdi_copyout(efx, outbuf,
min(outlen, mcdi->resplen + 3) & ~0x3);
if (outlen_actual != NULL)
*outlen_actual = resplen;
} else if (cmd == MC_CMD_REBOOT && rc == -EIO)
; /* Don't reset if MC_CMD_REBOOT returns EIO */
else if (rc == -EIO || rc == -EINTR) {
netif_err(efx, hw, efx->net_dev, "MC fatal error %d\n",
-rc);
efx_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
} else
netif_dbg(efx, hw, efx->net_dev,
"MC command 0x%x inlen %d failed rc=%d\n",
cmd, (int)inlen, -rc);
}
efx_mcdi_release(mcdi);
return rc;
}
void efx_mcdi_mode_poll(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (efx_nic_rev(efx) < EFX_REV_SIENA_A0)
return;
mcdi = efx_mcdi(efx);
if (mcdi->mode == MCDI_MODE_POLL)
return;
/* We can switch from event completion to polled completion, because
* mcdi requests are always completed in shared memory. We do this by
* switching the mode to POLL'd then completing the request.
* efx_mcdi_await_completion() will then call efx_mcdi_poll().
*
* We need an smp_wmb() to synchronise with efx_mcdi_await_completion(),
* which efx_mcdi_complete() provides for us.
*/
mcdi->mode = MCDI_MODE_POLL;
efx_mcdi_complete(mcdi);
}
void efx_mcdi_mode_event(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (efx_nic_rev(efx) < EFX_REV_SIENA_A0)
return;
mcdi = efx_mcdi(efx);
if (mcdi->mode == MCDI_MODE_EVENTS)
return;
/* We can't switch from polled to event completion in the middle of a
* request, because the completion method is specified in the request.
* So acquire the interface to serialise the requestors. We don't need
* to acquire the iface_lock to change the mode here, but we do need a
* write memory barrier ensure that efx_mcdi_rpc() sees it, which
* efx_mcdi_acquire() provides.
*/
efx_mcdi_acquire(mcdi);
mcdi->mode = MCDI_MODE_EVENTS;
efx_mcdi_release(mcdi);
}
static void efx_mcdi_ev_death(struct efx_nic *efx, int rc)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
/* If there is an outstanding MCDI request, it has been terminated
* either by a BADASSERT or REBOOT event. If the mcdi interface is
* in polled mode, then do nothing because the MC reboot handler will
* set the header correctly. However, if the mcdi interface is waiting
* for a CMDDONE event it won't receive it [and since all MCDI events
* are sent to the same queue, we can't be racing with
* efx_mcdi_ev_cpl()]
*
* There's a race here with efx_mcdi_rpc(), because we might receive
* a REBOOT event *before* the request has been copied out. In polled
* mode (during startup) this is irrelevant, because efx_mcdi_complete()
* is ignored. In event mode, this condition is just an edge-case of
* receiving a REBOOT event after posting the MCDI request. Did the mc
* reboot before or after the copyout? The best we can do always is
* just return failure.
*/
spin_lock(&mcdi->iface_lock);
if (efx_mcdi_complete(mcdi)) {
if (mcdi->mode == MCDI_MODE_EVENTS) {
mcdi->resprc = rc;
mcdi->resplen = 0;
++mcdi->credits;
}
} else
/* Nobody was waiting for an MCDI request, so trigger a reset */
efx_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
spin_unlock(&mcdi->iface_lock);
}
static unsigned int efx_mcdi_event_link_speed[] = {
[MCDI_EVENT_LINKCHANGE_SPEED_100M] = 100,
[MCDI_EVENT_LINKCHANGE_SPEED_1G] = 1000,
[MCDI_EVENT_LINKCHANGE_SPEED_10G] = 10000,
};
static void efx_mcdi_process_link_change(struct efx_nic *efx, efx_qword_t *ev)
{
u32 flags, fcntl, speed, lpa;
speed = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_SPEED);
EFX_BUG_ON_PARANOID(speed >= ARRAY_SIZE(efx_mcdi_event_link_speed));
speed = efx_mcdi_event_link_speed[speed];
flags = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_LINK_FLAGS);
fcntl = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_FCNTL);
lpa = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_LP_CAP);
/* efx->link_state is only modified by efx_mcdi_phy_get_link(),
* which is only run after flushing the event queues. Therefore, it
* is safe to modify the link state outside of the mac_lock here.
*/
efx_mcdi_phy_decode_link(efx, &efx->link_state, speed, flags, fcntl);
efx_mcdi_phy_check_fcntl(efx, lpa);
efx_link_status_changed(efx);
}
static const char *sensor_names[] = {
[MC_CMD_SENSOR_CONTROLLER_TEMP] = "Controller temp. sensor",
[MC_CMD_SENSOR_PHY_COMMON_TEMP] = "PHY shared temp. sensor",
[MC_CMD_SENSOR_CONTROLLER_COOLING] = "Controller cooling",
[MC_CMD_SENSOR_PHY0_TEMP] = "PHY 0 temp. sensor",
[MC_CMD_SENSOR_PHY0_COOLING] = "PHY 0 cooling",
[MC_CMD_SENSOR_PHY1_TEMP] = "PHY 1 temp. sensor",
[MC_CMD_SENSOR_PHY1_COOLING] = "PHY 1 cooling",
[MC_CMD_SENSOR_IN_1V0] = "1.0V supply sensor",
[MC_CMD_SENSOR_IN_1V2] = "1.2V supply sensor",
[MC_CMD_SENSOR_IN_1V8] = "1.8V supply sensor",
[MC_CMD_SENSOR_IN_2V5] = "2.5V supply sensor",
[MC_CMD_SENSOR_IN_3V3] = "3.3V supply sensor",
[MC_CMD_SENSOR_IN_12V0] = "12V supply sensor"
};
static const char *sensor_status_names[] = {
[MC_CMD_SENSOR_STATE_OK] = "OK",
[MC_CMD_SENSOR_STATE_WARNING] = "Warning",
[MC_CMD_SENSOR_STATE_FATAL] = "Fatal",
[MC_CMD_SENSOR_STATE_BROKEN] = "Device failure",
};
static void efx_mcdi_sensor_event(struct efx_nic *efx, efx_qword_t *ev)
{
unsigned int monitor, state, value;
const char *name, *state_txt;
monitor = EFX_QWORD_FIELD(*ev, MCDI_EVENT_SENSOREVT_MONITOR);
state = EFX_QWORD_FIELD(*ev, MCDI_EVENT_SENSOREVT_STATE);
value = EFX_QWORD_FIELD(*ev, MCDI_EVENT_SENSOREVT_VALUE);
/* Deal gracefully with the board having more drivers than we
* know about, but do not expect new sensor states. */
name = (monitor >= ARRAY_SIZE(sensor_names))
? "No sensor name available" :
sensor_names[monitor];
EFX_BUG_ON_PARANOID(state >= ARRAY_SIZE(sensor_status_names));
state_txt = sensor_status_names[state];
netif_err(efx, hw, efx->net_dev,
"Sensor %d (%s) reports condition '%s' for raw value %d\n",
monitor, name, state_txt, value);
}
/* Called from falcon_process_eventq for MCDI events */
void efx_mcdi_process_event(struct efx_channel *channel,
efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
int code = EFX_QWORD_FIELD(*event, MCDI_EVENT_CODE);
u32 data = EFX_QWORD_FIELD(*event, MCDI_EVENT_DATA);
switch (code) {
case MCDI_EVENT_CODE_BADSSERT:
netif_err(efx, hw, efx->net_dev,
"MC watchdog or assertion failure at 0x%x\n", data);
efx_mcdi_ev_death(efx, EINTR);
break;
case MCDI_EVENT_CODE_PMNOTICE:
netif_info(efx, wol, efx->net_dev, "MCDI PM event.\n");
break;
case MCDI_EVENT_CODE_CMDDONE:
efx_mcdi_ev_cpl(efx,
MCDI_EVENT_FIELD(*event, CMDDONE_SEQ),
MCDI_EVENT_FIELD(*event, CMDDONE_DATALEN),
MCDI_EVENT_FIELD(*event, CMDDONE_ERRNO));
break;
case MCDI_EVENT_CODE_LINKCHANGE:
efx_mcdi_process_link_change(efx, event);
break;
case MCDI_EVENT_CODE_SENSOREVT:
efx_mcdi_sensor_event(efx, event);
break;
case MCDI_EVENT_CODE_SCHEDERR:
netif_info(efx, hw, efx->net_dev,
"MC Scheduler error address=0x%x\n", data);
break;
case MCDI_EVENT_CODE_REBOOT:
netif_info(efx, hw, efx->net_dev, "MC Reboot\n");
efx_mcdi_ev_death(efx, EIO);
break;
case MCDI_EVENT_CODE_MAC_STATS_DMA:
/* MAC stats are gather lazily. We can ignore this. */
break;
default:
netif_err(efx, hw, efx->net_dev, "Unknown MCDI event 0x%x\n",
code);
}
}
/**************************************************************************
*
* Specific request functions
*
**************************************************************************
*/
void efx_mcdi_print_fwver(struct efx_nic *efx, char *buf, size_t len)
{
u8 outbuf[ALIGN(MC_CMD_GET_VERSION_V1_OUT_LEN, 4)];
size_t outlength;
const __le16 *ver_words;
int rc;
BUILD_BUG_ON(MC_CMD_GET_VERSION_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_VERSION, NULL, 0,
outbuf, sizeof(outbuf), &outlength);
if (rc)
goto fail;
if (outlength < MC_CMD_GET_VERSION_V1_OUT_LEN) {
rc = -EIO;
goto fail;
}
ver_words = (__le16 *)MCDI_PTR(outbuf, GET_VERSION_OUT_VERSION);
snprintf(buf, len, "%u.%u.%u.%u",
le16_to_cpu(ver_words[0]), le16_to_cpu(ver_words[1]),
le16_to_cpu(ver_words[2]), le16_to_cpu(ver_words[3]));
return;
fail:
netif_err(efx, probe, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
buf[0] = 0;
}
int efx_mcdi_drv_attach(struct efx_nic *efx, bool driver_operating,
bool *was_attached)
{
u8 inbuf[MC_CMD_DRV_ATTACH_IN_LEN];
u8 outbuf[MC_CMD_DRV_ATTACH_OUT_LEN];
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_NEW_STATE,
driver_operating ? 1 : 0);
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_UPDATE, 1);
rc = efx_mcdi_rpc(efx, MC_CMD_DRV_ATTACH, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_DRV_ATTACH_OUT_LEN) {
rc = -EIO;
goto fail;
}
if (was_attached != NULL)
*was_attached = MCDI_DWORD(outbuf, DRV_ATTACH_OUT_OLD_STATE);
return 0;
fail:
netif_err(efx, probe, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_get_board_cfg(struct efx_nic *efx, u8 *mac_address,
u16 *fw_subtype_list)
{
uint8_t outbuf[MC_CMD_GET_BOARD_CFG_OUT_LEN];
size_t outlen;
int port_num = efx_port_num(efx);
int offset;
int rc;
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_BOARD_CFG, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_GET_BOARD_CFG_OUT_LEN) {
rc = -EIO;
goto fail;
}
offset = (port_num)
? MC_CMD_GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT1_OFST
: MC_CMD_GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT0_OFST;
if (mac_address)
memcpy(mac_address, outbuf + offset, ETH_ALEN);
if (fw_subtype_list)
memcpy(fw_subtype_list,
outbuf + MC_CMD_GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST_OFST,
MC_CMD_GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST_LEN);
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d len=%d\n",
__func__, rc, (int)outlen);
return rc;
}
int efx_mcdi_log_ctrl(struct efx_nic *efx, bool evq, bool uart, u32 dest_evq)
{
u8 inbuf[MC_CMD_LOG_CTRL_IN_LEN];
u32 dest = 0;
int rc;
if (uart)
dest |= MC_CMD_LOG_CTRL_IN_LOG_DEST_UART;
if (evq)
dest |= MC_CMD_LOG_CTRL_IN_LOG_DEST_EVQ;
MCDI_SET_DWORD(inbuf, LOG_CTRL_IN_LOG_DEST, dest);
MCDI_SET_DWORD(inbuf, LOG_CTRL_IN_LOG_DEST_EVQ, dest_evq);
BUILD_BUG_ON(MC_CMD_LOG_CTRL_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_LOG_CTRL, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_types(struct efx_nic *efx, u32 *nvram_types_out)
{
u8 outbuf[MC_CMD_NVRAM_TYPES_OUT_LEN];
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_NVRAM_TYPES_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_TYPES, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_NVRAM_TYPES_OUT_LEN) {
rc = -EIO;
goto fail;
}
*nvram_types_out = MCDI_DWORD(outbuf, NVRAM_TYPES_OUT_TYPES);
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n",
__func__, rc);
return rc;
}
int efx_mcdi_nvram_info(struct efx_nic *efx, unsigned int type,
size_t *size_out, size_t *erase_size_out,
bool *protected_out)
{
u8 inbuf[MC_CMD_NVRAM_INFO_IN_LEN];
u8 outbuf[MC_CMD_NVRAM_INFO_OUT_LEN];
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_INFO_IN_TYPE, type);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_INFO, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_NVRAM_INFO_OUT_LEN) {
rc = -EIO;
goto fail;
}
*size_out = MCDI_DWORD(outbuf, NVRAM_INFO_OUT_SIZE);
*erase_size_out = MCDI_DWORD(outbuf, NVRAM_INFO_OUT_ERASESIZE);
*protected_out = !!(MCDI_DWORD(outbuf, NVRAM_INFO_OUT_FLAGS) &
(1 << MC_CMD_NVRAM_PROTECTED_LBN));
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_update_start(struct efx_nic *efx, unsigned int type)
{
u8 inbuf[MC_CMD_NVRAM_UPDATE_START_IN_LEN];
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_UPDATE_START_IN_TYPE, type);
BUILD_BUG_ON(MC_CMD_NVRAM_UPDATE_START_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_UPDATE_START, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_read(struct efx_nic *efx, unsigned int type,
loff_t offset, u8 *buffer, size_t length)
{
u8 inbuf[MC_CMD_NVRAM_READ_IN_LEN];
u8 outbuf[MC_CMD_NVRAM_READ_OUT_LEN(EFX_MCDI_NVRAM_LEN_MAX)];
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_LENGTH, length);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_READ, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
memcpy(buffer, MCDI_PTR(outbuf, NVRAM_READ_OUT_READ_BUFFER), length);
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_write(struct efx_nic *efx, unsigned int type,
loff_t offset, const u8 *buffer, size_t length)
{
u8 inbuf[MC_CMD_NVRAM_WRITE_IN_LEN(EFX_MCDI_NVRAM_LEN_MAX)];
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_LENGTH, length);
memcpy(MCDI_PTR(inbuf, NVRAM_WRITE_IN_WRITE_BUFFER), buffer, length);
BUILD_BUG_ON(MC_CMD_NVRAM_WRITE_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_WRITE, inbuf,
ALIGN(MC_CMD_NVRAM_WRITE_IN_LEN(length), 4),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_erase(struct efx_nic *efx, unsigned int type,
loff_t offset, size_t length)
{
u8 inbuf[MC_CMD_NVRAM_ERASE_IN_LEN];
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_LENGTH, length);
BUILD_BUG_ON(MC_CMD_NVRAM_ERASE_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_ERASE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_update_finish(struct efx_nic *efx, unsigned int type)
{
u8 inbuf[MC_CMD_NVRAM_UPDATE_FINISH_IN_LEN];
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_UPDATE_FINISH_IN_TYPE, type);
BUILD_BUG_ON(MC_CMD_NVRAM_UPDATE_FINISH_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_UPDATE_FINISH, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
static int efx_mcdi_nvram_test(struct efx_nic *efx, unsigned int type)
{
u8 inbuf[MC_CMD_NVRAM_TEST_IN_LEN];
u8 outbuf[MC_CMD_NVRAM_TEST_OUT_LEN];
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_TEST_IN_TYPE, type);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_TEST, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), NULL);
if (rc)
return rc;
switch (MCDI_DWORD(outbuf, NVRAM_TEST_OUT_RESULT)) {
case MC_CMD_NVRAM_TEST_PASS:
case MC_CMD_NVRAM_TEST_NOTSUPP:
return 0;
default:
return -EIO;
}
}
int efx_mcdi_nvram_test_all(struct efx_nic *efx)
{
u32 nvram_types;
unsigned int type;
int rc;
rc = efx_mcdi_nvram_types(efx, &nvram_types);
if (rc)
goto fail1;
type = 0;
while (nvram_types != 0) {
if (nvram_types & 1) {
rc = efx_mcdi_nvram_test(efx, type);
if (rc)
goto fail2;
}
type++;
nvram_types >>= 1;
}
return 0;
fail2:
netif_err(efx, hw, efx->net_dev, "%s: failed type=%u\n",
__func__, type);
fail1:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
static int efx_mcdi_read_assertion(struct efx_nic *efx)
{
u8 inbuf[MC_CMD_GET_ASSERTS_IN_LEN];
u8 outbuf[MC_CMD_GET_ASSERTS_OUT_LEN];
unsigned int flags, index, ofst;
const char *reason;
size_t outlen;
int retry;
int rc;
/* Attempt to read any stored assertion state before we reboot
* the mcfw out of the assertion handler. Retry twice, once
* because a boot-time assertion might cause this command to fail
* with EINTR. And once again because GET_ASSERTS can race with
* MC_CMD_REBOOT running on the other port. */
retry = 2;
do {
MCDI_SET_DWORD(inbuf, GET_ASSERTS_IN_CLEAR, 1);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_ASSERTS,
inbuf, MC_CMD_GET_ASSERTS_IN_LEN,
outbuf, sizeof(outbuf), &outlen);
} while ((rc == -EINTR || rc == -EIO) && retry-- > 0);
if (rc)
return rc;
if (outlen < MC_CMD_GET_ASSERTS_OUT_LEN)
return -EIO;
/* Print out any recorded assertion state */
flags = MCDI_DWORD(outbuf, GET_ASSERTS_OUT_GLOBAL_FLAGS);
if (flags == MC_CMD_GET_ASSERTS_FLAGS_NO_FAILS)
return 0;
reason = (flags == MC_CMD_GET_ASSERTS_FLAGS_SYS_FAIL)
? "system-level assertion"
: (flags == MC_CMD_GET_ASSERTS_FLAGS_THR_FAIL)
? "thread-level assertion"
: (flags == MC_CMD_GET_ASSERTS_FLAGS_WDOG_FIRED)
? "watchdog reset"
: "unknown assertion";
netif_err(efx, hw, efx->net_dev,
"MCPU %s at PC = 0x%.8x in thread 0x%.8x\n", reason,
MCDI_DWORD(outbuf, GET_ASSERTS_OUT_SAVED_PC_OFFS),
MCDI_DWORD(outbuf, GET_ASSERTS_OUT_THREAD_OFFS));
/* Print out the registers */
ofst = MC_CMD_GET_ASSERTS_OUT_GP_REGS_OFFS_OFST;
for (index = 1; index < 32; index++) {
netif_err(efx, hw, efx->net_dev, "R%.2d (?): 0x%.8x\n", index,
MCDI_DWORD2(outbuf, ofst));
ofst += sizeof(efx_dword_t);
}
return 0;
}
static void efx_mcdi_exit_assertion(struct efx_nic *efx)
{
u8 inbuf[MC_CMD_REBOOT_IN_LEN];
/* Atomically reboot the mcfw out of the assertion handler */
BUILD_BUG_ON(MC_CMD_REBOOT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, REBOOT_IN_FLAGS,
MC_CMD_REBOOT_FLAGS_AFTER_ASSERTION);
efx_mcdi_rpc(efx, MC_CMD_REBOOT, inbuf, MC_CMD_REBOOT_IN_LEN,
NULL, 0, NULL);
}
int efx_mcdi_handle_assertion(struct efx_nic *efx)
{
int rc;
rc = efx_mcdi_read_assertion(efx);
if (rc)
return rc;
efx_mcdi_exit_assertion(efx);
return 0;
}
void efx_mcdi_set_id_led(struct efx_nic *efx, enum efx_led_mode mode)
{
u8 inbuf[MC_CMD_SET_ID_LED_IN_LEN];
int rc;
BUILD_BUG_ON(EFX_LED_OFF != MC_CMD_LED_OFF);
BUILD_BUG_ON(EFX_LED_ON != MC_CMD_LED_ON);
BUILD_BUG_ON(EFX_LED_DEFAULT != MC_CMD_LED_DEFAULT);
BUILD_BUG_ON(MC_CMD_SET_ID_LED_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, SET_ID_LED_IN_STATE, mode);
rc = efx_mcdi_rpc(efx, MC_CMD_SET_ID_LED, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n",
__func__, rc);
}
int efx_mcdi_reset_port(struct efx_nic *efx)
{
int rc = efx_mcdi_rpc(efx, MC_CMD_PORT_RESET, NULL, 0, NULL, 0, NULL);
if (rc)
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n",
__func__, rc);
return rc;
}
int efx_mcdi_reset_mc(struct efx_nic *efx)
{
u8 inbuf[MC_CMD_REBOOT_IN_LEN];
int rc;
BUILD_BUG_ON(MC_CMD_REBOOT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, REBOOT_IN_FLAGS, 0);
rc = efx_mcdi_rpc(efx, MC_CMD_REBOOT, inbuf, sizeof(inbuf),
NULL, 0, NULL);
/* White is black, and up is down */
if (rc == -EIO)
return 0;
if (rc == 0)
rc = -EIO;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
static int efx_mcdi_wol_filter_set(struct efx_nic *efx, u32 type,
const u8 *mac, int *id_out)
{
u8 inbuf[MC_CMD_WOL_FILTER_SET_IN_LEN];
u8 outbuf[MC_CMD_WOL_FILTER_SET_OUT_LEN];
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, WOL_FILTER_SET_IN_WOL_TYPE, type);
MCDI_SET_DWORD(inbuf, WOL_FILTER_SET_IN_FILTER_MODE,
MC_CMD_FILTER_MODE_SIMPLE);
memcpy(MCDI_PTR(inbuf, WOL_FILTER_SET_IN_MAGIC_MAC), mac, ETH_ALEN);
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_SET, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_WOL_FILTER_SET_OUT_LEN) {
rc = -EIO;
goto fail;
}
*id_out = (int)MCDI_DWORD(outbuf, WOL_FILTER_SET_OUT_FILTER_ID);
return 0;
fail:
*id_out = -1;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int
efx_mcdi_wol_filter_set_magic(struct efx_nic *efx, const u8 *mac, int *id_out)
{
return efx_mcdi_wol_filter_set(efx, MC_CMD_WOL_TYPE_MAGIC, mac, id_out);
}
int efx_mcdi_wol_filter_get_magic(struct efx_nic *efx, int *id_out)
{
u8 outbuf[MC_CMD_WOL_FILTER_GET_OUT_LEN];
size_t outlen;
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_GET, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_WOL_FILTER_GET_OUT_LEN) {
rc = -EIO;
goto fail;
}
*id_out = (int)MCDI_DWORD(outbuf, WOL_FILTER_GET_OUT_FILTER_ID);
return 0;
fail:
*id_out = -1;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_wol_filter_remove(struct efx_nic *efx, int id)
{
u8 inbuf[MC_CMD_WOL_FILTER_REMOVE_IN_LEN];
int rc;
MCDI_SET_DWORD(inbuf, WOL_FILTER_REMOVE_IN_FILTER_ID, (u32)id);
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_REMOVE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_wol_filter_reset(struct efx_nic *efx)
{
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_RESET, NULL, 0, NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
| gpl-2.0 |
jpabferreira/linux-pcsws | drivers/scsi/bnx2i/bnx2i_init.c | 2304 | 16138 | /* bnx2i.c: Broadcom NetXtreme II iSCSI driver.
*
* Copyright (c) 2006 - 2012 Broadcom Corporation
* Copyright (c) 2007, 2008 Red Hat, Inc. All rights reserved.
* Copyright (c) 2007, 2008 Mike Christie
*
* 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.
*
* Written by: Anil Veerabhadrappa (anilgv@broadcom.com)
* Maintained by: Eddie Wai (eddie.wai@broadcom.com)
*/
#include "bnx2i.h"
static struct list_head adapter_list = LIST_HEAD_INIT(adapter_list);
static u32 adapter_count;
#define DRV_MODULE_NAME "bnx2i"
#define DRV_MODULE_VERSION "2.7.2.2"
#define DRV_MODULE_RELDATE "Apr 25, 2012"
static char version[] =
"Broadcom NetXtreme II iSCSI Driver " DRV_MODULE_NAME \
" v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")\n";
MODULE_AUTHOR("Anil Veerabhadrappa <anilgv@broadcom.com> and "
"Eddie Wai <eddie.wai@broadcom.com>");
MODULE_DESCRIPTION("Broadcom NetXtreme II BCM5706/5708/5709/57710/57711/57712"
"/57800/57810/57840 iSCSI Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_MODULE_VERSION);
static DEFINE_MUTEX(bnx2i_dev_lock);
unsigned int event_coal_min = 24;
module_param(event_coal_min, int, 0664);
MODULE_PARM_DESC(event_coal_min, "Event Coalescing Minimum Commands");
unsigned int event_coal_div = 2;
module_param(event_coal_div, int, 0664);
MODULE_PARM_DESC(event_coal_div, "Event Coalescing Divide Factor");
unsigned int en_tcp_dack = 1;
module_param(en_tcp_dack, int, 0664);
MODULE_PARM_DESC(en_tcp_dack, "Enable TCP Delayed ACK");
unsigned int error_mask1 = 0x00;
module_param(error_mask1, uint, 0664);
MODULE_PARM_DESC(error_mask1, "Config FW iSCSI Error Mask #1");
unsigned int error_mask2 = 0x00;
module_param(error_mask2, uint, 0664);
MODULE_PARM_DESC(error_mask2, "Config FW iSCSI Error Mask #2");
unsigned int sq_size;
module_param(sq_size, int, 0664);
MODULE_PARM_DESC(sq_size, "Configure SQ size");
unsigned int rq_size = BNX2I_RQ_WQES_DEFAULT;
module_param(rq_size, int, 0664);
MODULE_PARM_DESC(rq_size, "Configure RQ size");
u64 iscsi_error_mask = 0x00;
DEFINE_PER_CPU(struct bnx2i_percpu_s, bnx2i_percpu);
static int bnx2i_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu);
/* notification function for CPU hotplug events */
static struct notifier_block bnx2i_cpu_notifier = {
.notifier_call = bnx2i_cpu_callback,
};
/**
* bnx2i_identify_device - identifies NetXtreme II device type
* @hba: Adapter structure pointer
* @cnic: Corresponding cnic device
*
* This function identifies the NX2 device type and sets appropriate
* queue mailbox register access method, 5709 requires driver to
* access MBOX regs using *bin* mode
*/
void bnx2i_identify_device(struct bnx2i_hba *hba, struct cnic_dev *dev)
{
hba->cnic_dev_type = 0;
if (test_bit(CNIC_F_BNX2_CLASS, &dev->flags)) {
if (hba->pci_did == PCI_DEVICE_ID_NX2_5706 ||
hba->pci_did == PCI_DEVICE_ID_NX2_5706S) {
set_bit(BNX2I_NX2_DEV_5706, &hba->cnic_dev_type);
} else if (hba->pci_did == PCI_DEVICE_ID_NX2_5708 ||
hba->pci_did == PCI_DEVICE_ID_NX2_5708S) {
set_bit(BNX2I_NX2_DEV_5708, &hba->cnic_dev_type);
} else if (hba->pci_did == PCI_DEVICE_ID_NX2_5709 ||
hba->pci_did == PCI_DEVICE_ID_NX2_5709S) {
set_bit(BNX2I_NX2_DEV_5709, &hba->cnic_dev_type);
hba->mail_queue_access = BNX2I_MQ_BIN_MODE;
}
} else if (test_bit(CNIC_F_BNX2X_CLASS, &dev->flags)) {
set_bit(BNX2I_NX2_DEV_57710, &hba->cnic_dev_type);
} else {
printk(KERN_ALERT "bnx2i: unknown device, 0x%x\n",
hba->pci_did);
}
}
/**
* get_adapter_list_head - returns head of adapter list
*/
struct bnx2i_hba *get_adapter_list_head(void)
{
struct bnx2i_hba *hba = NULL;
struct bnx2i_hba *tmp_hba;
if (!adapter_count)
goto hba_not_found;
mutex_lock(&bnx2i_dev_lock);
list_for_each_entry(tmp_hba, &adapter_list, link) {
if (tmp_hba->cnic && tmp_hba->cnic->cm_select_dev) {
hba = tmp_hba;
break;
}
}
mutex_unlock(&bnx2i_dev_lock);
hba_not_found:
return hba;
}
/**
* bnx2i_find_hba_for_cnic - maps cnic device instance to bnx2i adapter instance
* @cnic: pointer to cnic device instance
*
*/
struct bnx2i_hba *bnx2i_find_hba_for_cnic(struct cnic_dev *cnic)
{
struct bnx2i_hba *hba, *temp;
mutex_lock(&bnx2i_dev_lock);
list_for_each_entry_safe(hba, temp, &adapter_list, link) {
if (hba->cnic == cnic) {
mutex_unlock(&bnx2i_dev_lock);
return hba;
}
}
mutex_unlock(&bnx2i_dev_lock);
return NULL;
}
/**
* bnx2i_start - cnic callback to initialize & start adapter instance
* @handle: transparent handle pointing to adapter structure
*
* This function maps adapter structure to pcidev structure and initiates
* firmware handshake to enable/initialize on chip iscsi components
* This bnx2i - cnic interface api callback is issued after following
* 2 conditions are met -
* a) underlying network interface is up (marked by event 'NETDEV_UP'
* from netdev
* b) bnx2i adapter instance is registered
*/
void bnx2i_start(void *handle)
{
#define BNX2I_INIT_POLL_TIME (1000 / HZ)
struct bnx2i_hba *hba = handle;
int i = HZ;
/*
* We should never register devices that don't support iSCSI
* (see bnx2i_init_one), so something is wrong if we try to
* start a iSCSI adapter on hardware with 0 supported iSCSI
* connections
*/
BUG_ON(!hba->cnic->max_iscsi_conn);
bnx2i_send_fw_iscsi_init_msg(hba);
while (!test_bit(ADAPTER_STATE_UP, &hba->adapter_state) && i--)
msleep(BNX2I_INIT_POLL_TIME);
}
/**
* bnx2i_chip_cleanup - local routine to handle chip cleanup
* @hba: Adapter instance to register
*
* Driver checks if adapter still has any active connections before
* executing the cleanup process
*/
static void bnx2i_chip_cleanup(struct bnx2i_hba *hba)
{
struct bnx2i_endpoint *bnx2i_ep;
struct list_head *pos, *tmp;
if (hba->ofld_conns_active) {
/* Stage to force the disconnection
* This is the case where the daemon is either slow or
* not present
*/
printk(KERN_ALERT "bnx2i: (%s) chip cleanup for %d active "
"connections\n", hba->netdev->name,
hba->ofld_conns_active);
mutex_lock(&hba->net_dev_lock);
list_for_each_safe(pos, tmp, &hba->ep_active_list) {
bnx2i_ep = list_entry(pos, struct bnx2i_endpoint, link);
/* Clean up the chip only */
bnx2i_hw_ep_disconnect(bnx2i_ep);
bnx2i_ep->cm_sk = NULL;
}
mutex_unlock(&hba->net_dev_lock);
}
}
/**
* bnx2i_stop - cnic callback to shutdown adapter instance
* @handle: transparent handle pointing to adapter structure
*
* driver checks if adapter is already in shutdown mode, if not start
* the shutdown process
*/
void bnx2i_stop(void *handle)
{
struct bnx2i_hba *hba = handle;
int conns_active;
int wait_delay = 1 * HZ;
/* check if cleanup happened in GOING_DOWN context */
if (!test_and_set_bit(ADAPTER_STATE_GOING_DOWN,
&hba->adapter_state)) {
iscsi_host_for_each_session(hba->shost,
bnx2i_drop_session);
wait_delay = hba->hba_shutdown_tmo;
}
/* Wait for inflight offload connection tasks to complete before
* proceeding. Forcefully terminate all connection recovery in
* progress at the earliest, either in bind(), send_pdu(LOGIN),
* or conn_start()
*/
wait_event_interruptible_timeout(hba->eh_wait,
(list_empty(&hba->ep_ofld_list) &&
list_empty(&hba->ep_destroy_list)),
2 * HZ);
/* Wait for all endpoints to be torn down, Chip will be reset once
* control returns to network driver. So it is required to cleanup and
* release all connection resources before returning from this routine.
*/
while (hba->ofld_conns_active) {
conns_active = hba->ofld_conns_active;
wait_event_interruptible_timeout(hba->eh_wait,
(hba->ofld_conns_active != conns_active),
wait_delay);
if (hba->ofld_conns_active == conns_active)
break;
}
bnx2i_chip_cleanup(hba);
/* This flag should be cleared last so that ep_disconnect() gracefully
* cleans up connection context
*/
clear_bit(ADAPTER_STATE_GOING_DOWN, &hba->adapter_state);
clear_bit(ADAPTER_STATE_UP, &hba->adapter_state);
}
/**
* bnx2i_init_one - initialize an adapter instance and allocate memory resources
* @hba: bnx2i adapter instance
* @cnic: cnic device handle
*
* Global resource lock is held during critical sections below. This routine is
* called from either cnic_register_driver() or device hot plug context and
* and does majority of device specific initialization
*/
static int bnx2i_init_one(struct bnx2i_hba *hba, struct cnic_dev *cnic)
{
int rc;
mutex_lock(&bnx2i_dev_lock);
if (!cnic->max_iscsi_conn) {
printk(KERN_ALERT "bnx2i: dev %s does not support "
"iSCSI\n", hba->netdev->name);
rc = -EOPNOTSUPP;
goto out;
}
hba->cnic = cnic;
rc = cnic->register_device(cnic, CNIC_ULP_ISCSI, hba);
if (!rc) {
hba->age++;
set_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic);
list_add_tail(&hba->link, &adapter_list);
adapter_count++;
} else if (rc == -EBUSY) /* duplicate registration */
printk(KERN_ALERT "bnx2i, duplicate registration"
"hba=%p, cnic=%p\n", hba, cnic);
else if (rc == -EAGAIN)
printk(KERN_ERR "bnx2i, driver not registered\n");
else if (rc == -EINVAL)
printk(KERN_ERR "bnx2i, invalid type %d\n", CNIC_ULP_ISCSI);
else
printk(KERN_ERR "bnx2i dev reg, unknown error, %d\n", rc);
out:
mutex_unlock(&bnx2i_dev_lock);
return rc;
}
/**
* bnx2i_ulp_init - initialize an adapter instance
* @dev: cnic device handle
*
* Called from cnic_register_driver() context to initialize all enumerated
* cnic devices. This routine allocate adapter structure and other
* device specific resources.
*/
void bnx2i_ulp_init(struct cnic_dev *dev)
{
struct bnx2i_hba *hba;
/* Allocate a HBA structure for this device */
hba = bnx2i_alloc_hba(dev);
if (!hba) {
printk(KERN_ERR "bnx2i init: hba initialization failed\n");
return;
}
/* Get PCI related information and update hba struct members */
clear_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic);
if (bnx2i_init_one(hba, dev)) {
printk(KERN_ERR "bnx2i - hba %p init failed\n", hba);
bnx2i_free_hba(hba);
}
}
/**
* bnx2i_ulp_exit - shuts down adapter instance and frees all resources
* @dev: cnic device handle
*
*/
void bnx2i_ulp_exit(struct cnic_dev *dev)
{
struct bnx2i_hba *hba;
hba = bnx2i_find_hba_for_cnic(dev);
if (!hba) {
printk(KERN_INFO "bnx2i_ulp_exit: hba not "
"found, dev 0x%p\n", dev);
return;
}
mutex_lock(&bnx2i_dev_lock);
list_del_init(&hba->link);
adapter_count--;
if (test_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic)) {
hba->cnic->unregister_device(hba->cnic, CNIC_ULP_ISCSI);
clear_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic);
}
mutex_unlock(&bnx2i_dev_lock);
bnx2i_free_hba(hba);
}
/**
* bnx2i_get_stats - Retrieve various statistic from iSCSI offload
* @handle: bnx2i_hba
*
* function callback exported via bnx2i - cnic driver interface to
* retrieve various iSCSI offload related statistics.
*/
int bnx2i_get_stats(void *handle)
{
struct bnx2i_hba *hba = handle;
struct iscsi_stats_info *stats;
if (!hba)
return -EINVAL;
stats = (struct iscsi_stats_info *)hba->cnic->stats_addr;
if (!stats)
return -ENOMEM;
strlcpy(stats->version, DRV_MODULE_VERSION, sizeof(stats->version));
memcpy(stats->mac_add1 + 2, hba->cnic->mac_addr, ETH_ALEN);
stats->max_frame_size = hba->netdev->mtu;
stats->txq_size = hba->max_sqes;
stats->rxq_size = hba->max_cqes;
stats->txq_avg_depth = 0;
stats->rxq_avg_depth = 0;
GET_STATS_64(hba, stats, rx_pdus);
GET_STATS_64(hba, stats, rx_bytes);
GET_STATS_64(hba, stats, tx_pdus);
GET_STATS_64(hba, stats, tx_bytes);
return 0;
}
/**
* bnx2i_percpu_thread_create - Create a receive thread for an
* online CPU
*
* @cpu: cpu index for the online cpu
*/
static void bnx2i_percpu_thread_create(unsigned int cpu)
{
struct bnx2i_percpu_s *p;
struct task_struct *thread;
p = &per_cpu(bnx2i_percpu, cpu);
thread = kthread_create_on_node(bnx2i_percpu_io_thread, (void *)p,
cpu_to_node(cpu),
"bnx2i_thread/%d", cpu);
/* bind thread to the cpu */
if (likely(!IS_ERR(thread))) {
kthread_bind(thread, cpu);
p->iothread = thread;
wake_up_process(thread);
}
}
static void bnx2i_percpu_thread_destroy(unsigned int cpu)
{
struct bnx2i_percpu_s *p;
struct task_struct *thread;
struct bnx2i_work *work, *tmp;
/* Prevent any new work from being queued for this CPU */
p = &per_cpu(bnx2i_percpu, cpu);
spin_lock_bh(&p->p_work_lock);
thread = p->iothread;
p->iothread = NULL;
/* Free all work in the list */
list_for_each_entry_safe(work, tmp, &p->work_list, list) {
list_del_init(&work->list);
bnx2i_process_scsi_cmd_resp(work->session,
work->bnx2i_conn, &work->cqe);
kfree(work);
}
spin_unlock_bh(&p->p_work_lock);
if (thread)
kthread_stop(thread);
}
/**
* bnx2i_cpu_callback - Handler for CPU hotplug events
*
* @nfb: The callback data block
* @action: The event triggering the callback
* @hcpu: The index of the CPU that the event is for
*
* This creates or destroys per-CPU data for iSCSI
*
* Returns NOTIFY_OK always.
*/
static int bnx2i_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned cpu = (unsigned long)hcpu;
switch (action) {
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
printk(KERN_INFO "bnx2i: CPU %x online: Create Rx thread\n",
cpu);
bnx2i_percpu_thread_create(cpu);
break;
case CPU_DEAD:
case CPU_DEAD_FROZEN:
printk(KERN_INFO "CPU %x offline: Remove Rx thread\n", cpu);
bnx2i_percpu_thread_destroy(cpu);
break;
default:
break;
}
return NOTIFY_OK;
}
/**
* bnx2i_mod_init - module init entry point
*
* initialize any driver wide global data structures such as endpoint pool,
* tcp port manager/queue, sysfs. finally driver will register itself
* with the cnic module
*/
static int __init bnx2i_mod_init(void)
{
int err;
unsigned cpu = 0;
struct bnx2i_percpu_s *p;
printk(KERN_INFO "%s", version);
if (sq_size && !is_power_of_2(sq_size))
sq_size = roundup_pow_of_two(sq_size);
mutex_init(&bnx2i_dev_lock);
bnx2i_scsi_xport_template =
iscsi_register_transport(&bnx2i_iscsi_transport);
if (!bnx2i_scsi_xport_template) {
printk(KERN_ERR "Could not register bnx2i transport.\n");
err = -ENOMEM;
goto out;
}
err = cnic_register_driver(CNIC_ULP_ISCSI, &bnx2i_cnic_cb);
if (err) {
printk(KERN_ERR "Could not register bnx2i cnic driver.\n");
goto unreg_xport;
}
/* Create percpu kernel threads to handle iSCSI I/O completions */
for_each_possible_cpu(cpu) {
p = &per_cpu(bnx2i_percpu, cpu);
INIT_LIST_HEAD(&p->work_list);
spin_lock_init(&p->p_work_lock);
p->iothread = NULL;
}
for_each_online_cpu(cpu)
bnx2i_percpu_thread_create(cpu);
/* Initialize per CPU interrupt thread */
register_hotcpu_notifier(&bnx2i_cpu_notifier);
return 0;
unreg_xport:
iscsi_unregister_transport(&bnx2i_iscsi_transport);
out:
return err;
}
/**
* bnx2i_mod_exit - module cleanup/exit entry point
*
* Global resource lock and host adapter lock is held during critical sections
* in this function. Driver will browse through the adapter list, cleans-up
* each instance, unregisters iscsi transport name and finally driver will
* unregister itself with the cnic module
*/
static void __exit bnx2i_mod_exit(void)
{
struct bnx2i_hba *hba;
unsigned cpu = 0;
mutex_lock(&bnx2i_dev_lock);
while (!list_empty(&adapter_list)) {
hba = list_entry(adapter_list.next, struct bnx2i_hba, link);
list_del(&hba->link);
adapter_count--;
if (test_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic)) {
bnx2i_chip_cleanup(hba);
hba->cnic->unregister_device(hba->cnic, CNIC_ULP_ISCSI);
clear_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic);
}
bnx2i_free_hba(hba);
}
mutex_unlock(&bnx2i_dev_lock);
unregister_hotcpu_notifier(&bnx2i_cpu_notifier);
for_each_online_cpu(cpu)
bnx2i_percpu_thread_destroy(cpu);
iscsi_unregister_transport(&bnx2i_iscsi_transport);
cnic_unregister_driver(CNIC_ULP_ISCSI);
}
module_init(bnx2i_mod_init);
module_exit(bnx2i_mod_exit);
| gpl-2.0 |
Elite-Kernels/Elite_angler | kernel/modsign_pubkey.c | 2304 | 2634 | /* Public keys for module signature verification
*
* Copyright (C) 2012 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 Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/cred.h>
#include <linux/err.h>
#include <keys/asymmetric-type.h>
#include "module-internal.h"
struct key *modsign_keyring;
extern __initdata const u8 modsign_certificate_list[];
extern __initdata const u8 modsign_certificate_list_end[];
/*
* We need to make sure ccache doesn't cache the .o file as it doesn't notice
* if modsign.pub changes.
*/
static __initdata const char annoy_ccache[] = __TIME__ "foo";
/*
* Load the compiled-in keys
*/
static __init int module_verify_init(void)
{
pr_notice("Initialise module verification\n");
modsign_keyring = keyring_alloc(".module_sign",
KUIDT_INIT(0), KGIDT_INIT(0),
current_cred(),
((KEY_POS_ALL & ~KEY_POS_SETATTR) |
KEY_USR_VIEW | KEY_USR_READ),
KEY_ALLOC_NOT_IN_QUOTA, NULL);
if (IS_ERR(modsign_keyring))
panic("Can't allocate module signing keyring\n");
return 0;
}
/*
* Must be initialised before we try and load the keys into the keyring.
*/
device_initcall(module_verify_init);
/*
* Load the compiled-in keys
*/
static __init int load_module_signing_keys(void)
{
key_ref_t key;
const u8 *p, *end;
size_t plen;
pr_notice("Loading module verification certificates\n");
end = modsign_certificate_list_end;
p = modsign_certificate_list;
while (p < end) {
/* Each cert begins with an ASN.1 SEQUENCE tag and must be more
* than 256 bytes in size.
*/
if (end - p < 4)
goto dodgy_cert;
if (p[0] != 0x30 &&
p[1] != 0x82)
goto dodgy_cert;
plen = (p[2] << 8) | p[3];
plen += 4;
if (plen > end - p)
goto dodgy_cert;
key = key_create_or_update(make_key_ref(modsign_keyring, 1),
"asymmetric",
NULL,
p,
plen,
(KEY_POS_ALL & ~KEY_POS_SETATTR) |
KEY_USR_VIEW,
KEY_ALLOC_NOT_IN_QUOTA);
if (IS_ERR(key))
pr_err("MODSIGN: Problem loading in-kernel X.509 certificate (%ld)\n",
PTR_ERR(key));
else
pr_notice("MODSIGN: Loaded cert '%s'\n",
key_ref_to_ptr(key)->description);
p += plen;
}
return 0;
dodgy_cert:
pr_err("MODSIGN: Problem parsing in-kernel X.509 certificate list\n");
return 0;
}
late_initcall(load_module_signing_keys);
| gpl-2.0 |
Driim/crypt_ubifs | arch/mips/bcm63xx/dev-flash.c | 2560 | 3320 | /*
* Broadcom BCM63xx flash registration
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2008 Maxime Bizon <mbizon@freebox.fr>
* Copyright (C) 2008 Florian Fainelli <florian@openwrt.org>
* Copyright (C) 2012 Jonas Gorski <jonas.gorski@gmail.com>
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <bcm63xx_cpu.h>
#include <bcm63xx_dev_flash.h>
#include <bcm63xx_regs.h>
#include <bcm63xx_io.h>
static struct mtd_partition mtd_partitions[] = {
{
.name = "cfe",
.offset = 0x0,
.size = 0x40000,
}
};
static const char *bcm63xx_part_types[] = { "bcm63xxpart", NULL };
static struct physmap_flash_data flash_data = {
.width = 2,
.parts = mtd_partitions,
.part_probe_types = bcm63xx_part_types,
};
static struct resource mtd_resources[] = {
{
.start = 0, /* filled at runtime */
.end = 0, /* filled at runtime */
.flags = IORESOURCE_MEM,
}
};
static struct platform_device mtd_dev = {
.name = "physmap-flash",
.resource = mtd_resources,
.num_resources = ARRAY_SIZE(mtd_resources),
.dev = {
.platform_data = &flash_data,
},
};
static int __init bcm63xx_detect_flash_type(void)
{
u32 val;
switch (bcm63xx_get_cpu_id()) {
case BCM6328_CPU_ID:
val = bcm_misc_readl(MISC_STRAPBUS_6328_REG);
if (val & STRAPBUS_6328_BOOT_SEL_SERIAL)
return BCM63XX_FLASH_TYPE_SERIAL;
else
return BCM63XX_FLASH_TYPE_NAND;
case BCM6338_CPU_ID:
case BCM6345_CPU_ID:
case BCM6348_CPU_ID:
/* no way to auto detect so assume parallel */
return BCM63XX_FLASH_TYPE_PARALLEL;
case BCM3368_CPU_ID:
case BCM6358_CPU_ID:
val = bcm_gpio_readl(GPIO_STRAPBUS_REG);
if (val & STRAPBUS_6358_BOOT_SEL_PARALLEL)
return BCM63XX_FLASH_TYPE_PARALLEL;
else
return BCM63XX_FLASH_TYPE_SERIAL;
case BCM6362_CPU_ID:
val = bcm_misc_readl(MISC_STRAPBUS_6362_REG);
if (val & STRAPBUS_6362_BOOT_SEL_SERIAL)
return BCM63XX_FLASH_TYPE_SERIAL;
else
return BCM63XX_FLASH_TYPE_NAND;
case BCM6368_CPU_ID:
val = bcm_gpio_readl(GPIO_STRAPBUS_REG);
switch (val & STRAPBUS_6368_BOOT_SEL_MASK) {
case STRAPBUS_6368_BOOT_SEL_NAND:
return BCM63XX_FLASH_TYPE_NAND;
case STRAPBUS_6368_BOOT_SEL_SERIAL:
return BCM63XX_FLASH_TYPE_SERIAL;
case STRAPBUS_6368_BOOT_SEL_PARALLEL:
return BCM63XX_FLASH_TYPE_PARALLEL;
}
default:
return -EINVAL;
}
}
int __init bcm63xx_flash_register(void)
{
int flash_type;
u32 val;
flash_type = bcm63xx_detect_flash_type();
switch (flash_type) {
case BCM63XX_FLASH_TYPE_PARALLEL:
/* read base address of boot chip select (0) */
val = bcm_mpi_readl(MPI_CSBASE_REG(0));
val &= MPI_CSBASE_BASE_MASK;
mtd_resources[0].start = val;
mtd_resources[0].end = 0x1FFFFFFF;
return platform_device_register(&mtd_dev);
case BCM63XX_FLASH_TYPE_SERIAL:
pr_warn("unsupported serial flash detected\n");
return -ENODEV;
case BCM63XX_FLASH_TYPE_NAND:
pr_warn("unsupported NAND flash detected\n");
return -ENODEV;
default:
pr_err("flash detection failed for BCM%x: %d\n",
bcm63xx_get_cpu_id(), flash_type);
return -ENODEV;
}
}
| gpl-2.0 |
vakkov/linux-n900-android | drivers/media/dvb-frontends/ix2505v.c | 4352 | 7866 | /**
* Driver for Sharp IX2505V (marked B0017) DVB-S silicon tuner
*
* Copyright (C) 2010 Malcolm Priestley
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License Version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <linux/module.h>
#include <linux/dvb/frontend.h>
#include <linux/slab.h>
#include <linux/types.h>
#include "ix2505v.h"
static int ix2505v_debug;
#define dprintk(level, args...) do { \
if (ix2505v_debug & level) \
printk(KERN_DEBUG "ix2505v: " args); \
} while (0)
#define deb_info(args...) dprintk(0x01, args)
#define deb_i2c(args...) dprintk(0x02, args)
struct ix2505v_state {
struct i2c_adapter *i2c;
const struct ix2505v_config *config;
u32 frequency;
};
/**
* Data read format of the Sharp IX2505V B0017
*
* byte1: 1 | 1 | 0 | 0 | 0 | MA1 | MA0 | 1
* byte2: POR | FL | RD2 | RD1 | RD0 | X | X | X
*
* byte1 = address
* byte2;
* POR = Power on Reset (VCC H=<2.2v L=>2.2v)
* FL = Phase Lock (H=lock L=unlock)
* RD0-2 = Reserved internal operations
*
* Only POR can be used to check the tuner is present
*
* Caution: after byte2 the I2C reverts to write mode continuing to read
* may corrupt tuning data.
*
*/
static int ix2505v_read_status_reg(struct ix2505v_state *state)
{
u8 addr = state->config->tuner_address;
u8 b2[] = {0};
int ret;
struct i2c_msg msg[1] = {
{ .addr = addr, .flags = I2C_M_RD, .buf = b2, .len = 1 }
};
ret = i2c_transfer(state->i2c, msg, 1);
deb_i2c("Read %s ", __func__);
return (ret == 1) ? (int) b2[0] : -1;
}
static int ix2505v_write(struct ix2505v_state *state, u8 buf[], u8 count)
{
struct i2c_msg msg[1] = {
{ .addr = state->config->tuner_address, .flags = 0,
.buf = buf, .len = count },
};
int ret;
ret = i2c_transfer(state->i2c, msg, 1);
if (ret != 1) {
deb_i2c("%s: i2c error, ret=%d\n", __func__, ret);
return -EIO;
}
return 0;
}
static int ix2505v_release(struct dvb_frontend *fe)
{
struct ix2505v_state *state = fe->tuner_priv;
fe->tuner_priv = NULL;
kfree(state);
return 0;
}
/**
* Data write format of the Sharp IX2505V B0017
*
* byte1: 1 | 1 | 0 | 0 | 0 | 0(MA1)| 0(MA0)| 0
* byte2: 0 | BG1 | BG2 | N8 | N7 | N6 | N5 | N4
* byte3: N3 | N2 | N1 | A5 | A4 | A3 | A2 | A1
* byte4: 1 | 1(C1) | 1(C0) | PD5 | PD4 | TM | 0(RTS)| 1(REF)
* byte5: BA2 | BA1 | BA0 | PSC | PD3 |PD2/TS2|DIV/TS1|PD0/TS0
*
* byte1 = address
*
* Write order
* 1) byte1 -> byte2 -> byte3 -> byte4 -> byte5
* 2) byte1 -> byte4 -> byte5 -> byte2 -> byte3
* 3) byte1 -> byte2 -> byte3 -> byte4
* 4) byte1 -> byte4 -> byte5 -> byte2
* 5) byte1 -> byte2 -> byte3
* 6) byte1 -> byte4 -> byte5
* 7) byte1 -> byte2
* 8) byte1 -> byte4
*
* Recommended Setup
* 1 -> 8 -> 6
*/
static int ix2505v_set_params(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
struct ix2505v_state *state = fe->tuner_priv;
u32 frequency = c->frequency;
u32 b_w = (c->symbol_rate * 27) / 32000;
u32 div_factor, N , A, x;
int ret = 0, len;
u8 gain, cc, ref, psc, local_osc, lpf;
u8 data[4] = {0};
if ((frequency < fe->ops.info.frequency_min)
|| (frequency > fe->ops.info.frequency_max))
return -EINVAL;
if (state->config->tuner_gain)
gain = (state->config->tuner_gain < 4)
? state->config->tuner_gain : 0;
else
gain = 0x0;
if (state->config->tuner_chargepump)
cc = state->config->tuner_chargepump;
else
cc = 0x3;
ref = 8; /* REF =1 */
psc = 32; /* PSC = 0 */
div_factor = (frequency * ref) / 40; /* local osc = 4Mhz */
x = div_factor / psc;
N = x/100;
A = ((x - (N * 100)) * psc) / 100;
data[0] = ((gain & 0x3) << 5) | (N >> 3);
data[1] = (N << 5) | (A & 0x1f);
data[2] = 0x81 | ((cc & 0x3) << 5) ; /*PD5,PD4 & TM = 0|C1,C0|REF=1*/
deb_info("Frq=%d x=%d N=%d A=%d\n", frequency, x, N, A);
if (frequency <= 1065000)
local_osc = (6 << 5) | 2;
else if (frequency <= 1170000)
local_osc = (7 << 5) | 2;
else if (frequency <= 1300000)
local_osc = (1 << 5);
else if (frequency <= 1445000)
local_osc = (2 << 5);
else if (frequency <= 1607000)
local_osc = (3 << 5);
else if (frequency <= 1778000)
local_osc = (4 << 5);
else if (frequency <= 1942000)
local_osc = (5 << 5);
else /*frequency up to 2150000*/
local_osc = (6 << 5);
data[3] = local_osc; /* all other bits set 0 */
if (b_w <= 10000)
lpf = 0xc;
else if (b_w <= 12000)
lpf = 0x2;
else if (b_w <= 14000)
lpf = 0xa;
else if (b_w <= 16000)
lpf = 0x6;
else if (b_w <= 18000)
lpf = 0xe;
else if (b_w <= 20000)
lpf = 0x1;
else if (b_w <= 22000)
lpf = 0x9;
else if (b_w <= 24000)
lpf = 0x5;
else if (b_w <= 26000)
lpf = 0xd;
else if (b_w <= 28000)
lpf = 0x3;
else
lpf = 0xb;
deb_info("Osc=%x b_w=%x lpf=%x\n", local_osc, b_w, lpf);
deb_info("Data 0=[%4phN]\n", data);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
len = sizeof(data);
ret |= ix2505v_write(state, data, len);
data[2] |= 0x4; /* set TM = 1 other bits same */
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
len = 1;
ret |= ix2505v_write(state, &data[2], len); /* write byte 4 only */
msleep(10);
data[2] |= ((lpf >> 2) & 0x3) << 3; /* lpf */
data[3] |= (lpf & 0x3) << 2;
deb_info("Data 2=[%x%x]\n", data[2], data[3]);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
len = 2;
ret |= ix2505v_write(state, &data[2], len); /* write byte 4 & 5 */
if (state->config->min_delay_ms)
msleep(state->config->min_delay_ms);
state->frequency = frequency;
return ret;
}
static int ix2505v_get_frequency(struct dvb_frontend *fe, u32 *frequency)
{
struct ix2505v_state *state = fe->tuner_priv;
*frequency = state->frequency;
return 0;
}
static struct dvb_tuner_ops ix2505v_tuner_ops = {
.info = {
.name = "Sharp IX2505V (B0017)",
.frequency_min = 950000,
.frequency_max = 2175000
},
.release = ix2505v_release,
.set_params = ix2505v_set_params,
.get_frequency = ix2505v_get_frequency,
};
struct dvb_frontend *ix2505v_attach(struct dvb_frontend *fe,
const struct ix2505v_config *config,
struct i2c_adapter *i2c)
{
struct ix2505v_state *state = NULL;
int ret;
if (NULL == config) {
deb_i2c("%s: no config ", __func__);
goto error;
}
state = kzalloc(sizeof(struct ix2505v_state), GFP_KERNEL);
if (NULL == state)
return NULL;
state->config = config;
state->i2c = i2c;
if (state->config->tuner_write_only) {
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
ret = ix2505v_read_status_reg(state);
if (ret & 0x80) {
deb_i2c("%s: No IX2505V found\n", __func__);
goto error;
}
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
}
fe->tuner_priv = state;
memcpy(&fe->ops.tuner_ops, &ix2505v_tuner_ops,
sizeof(struct dvb_tuner_ops));
deb_i2c("%s: initialization (%s addr=0x%02x) ok\n",
__func__, fe->ops.tuner_ops.info.name, config->tuner_address);
return fe;
error:
kfree(state);
return NULL;
}
EXPORT_SYMBOL(ix2505v_attach);
module_param_named(debug, ix2505v_debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off frontend debugging (default:off).");
MODULE_DESCRIPTION("DVB IX2505V tuner driver");
MODULE_AUTHOR("Malcolm Priestley");
MODULE_LICENSE("GPL");
| gpl-2.0 |
hiikezoe/android_kernel_fujitsu_f12nad | drivers/bluetooth/btmrvl_debugfs.c | 4608 | 11670 | /**
* Marvell Bluetooth driver: debugfs related functions
*
* Copyright (C) 2009, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
**/
#include <linux/debugfs.h>
#include <linux/slab.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include "btmrvl_drv.h"
struct btmrvl_debugfs_data {
struct dentry *config_dir;
struct dentry *status_dir;
/* config */
struct dentry *psmode;
struct dentry *pscmd;
struct dentry *hsmode;
struct dentry *hscmd;
struct dentry *gpiogap;
struct dentry *hscfgcmd;
/* status */
struct dentry *curpsmode;
struct dentry *hsstate;
struct dentry *psstate;
struct dentry *txdnldready;
};
static int btmrvl_open_generic(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static ssize_t btmrvl_hscfgcmd_write(struct file *file,
const char __user *ubuf, size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
long result, ret;
memset(buf, 0, sizeof(buf));
if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
return -EFAULT;
ret = strict_strtol(buf, 10, &result);
priv->btmrvl_dev.hscfgcmd = result;
if (priv->btmrvl_dev.hscfgcmd) {
btmrvl_prepare_command(priv);
wake_up_interruptible(&priv->main_thread.wait_q);
}
return count;
}
static ssize_t btmrvl_hscfgcmd_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
int ret;
ret = snprintf(buf, sizeof(buf) - 1, "%d\n",
priv->btmrvl_dev.hscfgcmd);
return simple_read_from_buffer(userbuf, count, ppos, buf, ret);
}
static const struct file_operations btmrvl_hscfgcmd_fops = {
.read = btmrvl_hscfgcmd_read,
.write = btmrvl_hscfgcmd_write,
.open = btmrvl_open_generic,
.llseek = default_llseek,
};
static ssize_t btmrvl_psmode_write(struct file *file, const char __user *ubuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
long result, ret;
memset(buf, 0, sizeof(buf));
if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
return -EFAULT;
ret = strict_strtol(buf, 10, &result);
priv->btmrvl_dev.psmode = result;
return count;
}
static ssize_t btmrvl_psmode_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
int ret;
ret = snprintf(buf, sizeof(buf) - 1, "%d\n",
priv->btmrvl_dev.psmode);
return simple_read_from_buffer(userbuf, count, ppos, buf, ret);
}
static const struct file_operations btmrvl_psmode_fops = {
.read = btmrvl_psmode_read,
.write = btmrvl_psmode_write,
.open = btmrvl_open_generic,
.llseek = default_llseek,
};
static ssize_t btmrvl_pscmd_write(struct file *file, const char __user *ubuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
long result, ret;
memset(buf, 0, sizeof(buf));
if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
return -EFAULT;
ret = strict_strtol(buf, 10, &result);
priv->btmrvl_dev.pscmd = result;
if (priv->btmrvl_dev.pscmd) {
btmrvl_prepare_command(priv);
wake_up_interruptible(&priv->main_thread.wait_q);
}
return count;
}
static ssize_t btmrvl_pscmd_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
int ret;
ret = snprintf(buf, sizeof(buf) - 1, "%d\n", priv->btmrvl_dev.pscmd);
return simple_read_from_buffer(userbuf, count, ppos, buf, ret);
}
static const struct file_operations btmrvl_pscmd_fops = {
.read = btmrvl_pscmd_read,
.write = btmrvl_pscmd_write,
.open = btmrvl_open_generic,
.llseek = default_llseek,
};
static ssize_t btmrvl_gpiogap_write(struct file *file, const char __user *ubuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
long result, ret;
memset(buf, 0, sizeof(buf));
if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
return -EFAULT;
ret = strict_strtol(buf, 16, &result);
priv->btmrvl_dev.gpio_gap = result;
return count;
}
static ssize_t btmrvl_gpiogap_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
int ret;
ret = snprintf(buf, sizeof(buf) - 1, "0x%x\n",
priv->btmrvl_dev.gpio_gap);
return simple_read_from_buffer(userbuf, count, ppos, buf, ret);
}
static const struct file_operations btmrvl_gpiogap_fops = {
.read = btmrvl_gpiogap_read,
.write = btmrvl_gpiogap_write,
.open = btmrvl_open_generic,
.llseek = default_llseek,
};
static ssize_t btmrvl_hscmd_write(struct file *file, const char __user *ubuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
long result, ret;
memset(buf, 0, sizeof(buf));
if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
return -EFAULT;
ret = strict_strtol(buf, 10, &result);
priv->btmrvl_dev.hscmd = result;
if (priv->btmrvl_dev.hscmd) {
btmrvl_prepare_command(priv);
wake_up_interruptible(&priv->main_thread.wait_q);
}
return count;
}
static ssize_t btmrvl_hscmd_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
int ret;
ret = snprintf(buf, sizeof(buf) - 1, "%d\n", priv->btmrvl_dev.hscmd);
return simple_read_from_buffer(userbuf, count, ppos, buf, ret);
}
static const struct file_operations btmrvl_hscmd_fops = {
.read = btmrvl_hscmd_read,
.write = btmrvl_hscmd_write,
.open = btmrvl_open_generic,
.llseek = default_llseek,
};
static ssize_t btmrvl_hsmode_write(struct file *file, const char __user *ubuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
long result, ret;
memset(buf, 0, sizeof(buf));
if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
return -EFAULT;
ret = strict_strtol(buf, 10, &result);
priv->btmrvl_dev.hsmode = result;
return count;
}
static ssize_t btmrvl_hsmode_read(struct file *file, char __user * userbuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
int ret;
ret = snprintf(buf, sizeof(buf) - 1, "%d\n", priv->btmrvl_dev.hsmode);
return simple_read_from_buffer(userbuf, count, ppos, buf, ret);
}
static const struct file_operations btmrvl_hsmode_fops = {
.read = btmrvl_hsmode_read,
.write = btmrvl_hsmode_write,
.open = btmrvl_open_generic,
.llseek = default_llseek,
};
static ssize_t btmrvl_curpsmode_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
int ret;
ret = snprintf(buf, sizeof(buf) - 1, "%d\n", priv->adapter->psmode);
return simple_read_from_buffer(userbuf, count, ppos, buf, ret);
}
static const struct file_operations btmrvl_curpsmode_fops = {
.read = btmrvl_curpsmode_read,
.open = btmrvl_open_generic,
.llseek = default_llseek,
};
static ssize_t btmrvl_psstate_read(struct file *file, char __user * userbuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
int ret;
ret = snprintf(buf, sizeof(buf) - 1, "%d\n", priv->adapter->ps_state);
return simple_read_from_buffer(userbuf, count, ppos, buf, ret);
}
static const struct file_operations btmrvl_psstate_fops = {
.read = btmrvl_psstate_read,
.open = btmrvl_open_generic,
.llseek = default_llseek,
};
static ssize_t btmrvl_hsstate_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
int ret;
ret = snprintf(buf, sizeof(buf) - 1, "%d\n", priv->adapter->hs_state);
return simple_read_from_buffer(userbuf, count, ppos, buf, ret);
}
static const struct file_operations btmrvl_hsstate_fops = {
.read = btmrvl_hsstate_read,
.open = btmrvl_open_generic,
.llseek = default_llseek,
};
static ssize_t btmrvl_txdnldready_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct btmrvl_private *priv = file->private_data;
char buf[16];
int ret;
ret = snprintf(buf, sizeof(buf) - 1, "%d\n",
priv->btmrvl_dev.tx_dnld_rdy);
return simple_read_from_buffer(userbuf, count, ppos, buf, ret);
}
static const struct file_operations btmrvl_txdnldready_fops = {
.read = btmrvl_txdnldready_read,
.open = btmrvl_open_generic,
.llseek = default_llseek,
};
void btmrvl_debugfs_init(struct hci_dev *hdev)
{
struct btmrvl_private *priv = hdev->driver_data;
struct btmrvl_debugfs_data *dbg;
if (!hdev->debugfs)
return;
dbg = kzalloc(sizeof(*dbg), GFP_KERNEL);
priv->debugfs_data = dbg;
if (!dbg) {
BT_ERR("Can not allocate memory for btmrvl_debugfs_data.");
return;
}
dbg->config_dir = debugfs_create_dir("config", hdev->debugfs);
dbg->psmode = debugfs_create_file("psmode", 0644, dbg->config_dir,
hdev->driver_data, &btmrvl_psmode_fops);
dbg->pscmd = debugfs_create_file("pscmd", 0644, dbg->config_dir,
hdev->driver_data, &btmrvl_pscmd_fops);
dbg->gpiogap = debugfs_create_file("gpiogap", 0644, dbg->config_dir,
hdev->driver_data, &btmrvl_gpiogap_fops);
dbg->hsmode = debugfs_create_file("hsmode", 0644, dbg->config_dir,
hdev->driver_data, &btmrvl_hsmode_fops);
dbg->hscmd = debugfs_create_file("hscmd", 0644, dbg->config_dir,
hdev->driver_data, &btmrvl_hscmd_fops);
dbg->hscfgcmd = debugfs_create_file("hscfgcmd", 0644, dbg->config_dir,
hdev->driver_data, &btmrvl_hscfgcmd_fops);
dbg->status_dir = debugfs_create_dir("status", hdev->debugfs);
dbg->curpsmode = debugfs_create_file("curpsmode", 0444,
dbg->status_dir,
hdev->driver_data,
&btmrvl_curpsmode_fops);
dbg->psstate = debugfs_create_file("psstate", 0444, dbg->status_dir,
hdev->driver_data, &btmrvl_psstate_fops);
dbg->hsstate = debugfs_create_file("hsstate", 0444, dbg->status_dir,
hdev->driver_data, &btmrvl_hsstate_fops);
dbg->txdnldready = debugfs_create_file("txdnldready", 0444,
dbg->status_dir,
hdev->driver_data,
&btmrvl_txdnldready_fops);
}
void btmrvl_debugfs_remove(struct hci_dev *hdev)
{
struct btmrvl_private *priv = hdev->driver_data;
struct btmrvl_debugfs_data *dbg = priv->debugfs_data;
if (!dbg)
return;
debugfs_remove(dbg->psmode);
debugfs_remove(dbg->pscmd);
debugfs_remove(dbg->gpiogap);
debugfs_remove(dbg->hsmode);
debugfs_remove(dbg->hscmd);
debugfs_remove(dbg->hscfgcmd);
debugfs_remove(dbg->config_dir);
debugfs_remove(dbg->curpsmode);
debugfs_remove(dbg->psstate);
debugfs_remove(dbg->hsstate);
debugfs_remove(dbg->txdnldready);
debugfs_remove(dbg->status_dir);
kfree(dbg);
}
| gpl-2.0 |
Solitarily/LGF180-Optimus-G-_Android_KK_v30b_Kernel | arch/arm/mach-omap2/board-zoom-peripherals.c | 4864 | 7802 | /*
* Copyright (C) 2009 Texas Instruments Inc.
*
* Modified from mach-omap2/board-zoom2.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#include <linux/gpio.h>
#include <linux/i2c/twl.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/fixed.h>
#include <linux/wl12xx.h>
#include <linux/mmc/host.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include "common.h"
#include <plat/usb.h>
#include <mach/board-zoom.h>
#include "mux.h"
#include "hsmmc.h"
#include "common-board-devices.h"
#define OMAP_ZOOM_WLAN_PMENA_GPIO (101)
#define OMAP_ZOOM_WLAN_IRQ_GPIO (162)
#define LCD_PANEL_ENABLE_GPIO (7 + OMAP_MAX_GPIO_LINES)
/* Zoom2 has Qwerty keyboard*/
static uint32_t board_keymap[] = {
KEY(0, 0, KEY_E),
KEY(0, 1, KEY_R),
KEY(0, 2, KEY_T),
KEY(0, 3, KEY_HOME),
KEY(0, 6, KEY_I),
KEY(0, 7, KEY_LEFTSHIFT),
KEY(1, 0, KEY_D),
KEY(1, 1, KEY_F),
KEY(1, 2, KEY_G),
KEY(1, 3, KEY_SEND),
KEY(1, 6, KEY_K),
KEY(1, 7, KEY_ENTER),
KEY(2, 0, KEY_X),
KEY(2, 1, KEY_C),
KEY(2, 2, KEY_V),
KEY(2, 3, KEY_END),
KEY(2, 6, KEY_DOT),
KEY(2, 7, KEY_CAPSLOCK),
KEY(3, 0, KEY_Z),
KEY(3, 1, KEY_KPPLUS),
KEY(3, 2, KEY_B),
KEY(3, 3, KEY_F1),
KEY(3, 6, KEY_O),
KEY(3, 7, KEY_SPACE),
KEY(4, 0, KEY_W),
KEY(4, 1, KEY_Y),
KEY(4, 2, KEY_U),
KEY(4, 3, KEY_F2),
KEY(4, 4, KEY_VOLUMEUP),
KEY(4, 6, KEY_L),
KEY(4, 7, KEY_LEFT),
KEY(5, 0, KEY_S),
KEY(5, 1, KEY_H),
KEY(5, 2, KEY_J),
KEY(5, 3, KEY_F3),
KEY(5, 4, KEY_UNKNOWN),
KEY(5, 5, KEY_VOLUMEDOWN),
KEY(5, 6, KEY_M),
KEY(5, 7, KEY_RIGHT),
KEY(6, 0, KEY_Q),
KEY(6, 1, KEY_A),
KEY(6, 2, KEY_N),
KEY(6, 3, KEY_BACKSPACE),
KEY(6, 6, KEY_P),
KEY(6, 7, KEY_UP),
KEY(7, 0, KEY_PROG1), /*MACRO 1 <User defined> */
KEY(7, 1, KEY_PROG2), /*MACRO 2 <User defined> */
KEY(7, 2, KEY_PROG3), /*MACRO 3 <User defined> */
KEY(7, 3, KEY_PROG4), /*MACRO 4 <User defined> */
KEY(7, 6, KEY_SELECT),
KEY(7, 7, KEY_DOWN)
};
static struct matrix_keymap_data board_map_data = {
.keymap = board_keymap,
.keymap_size = ARRAY_SIZE(board_keymap),
};
static struct twl4030_keypad_data zoom_kp_twl4030_data = {
.keymap_data = &board_map_data,
.rows = 8,
.cols = 8,
.rep = 1,
};
static struct regulator_consumer_supply zoom_vmmc1_supply[] = {
REGULATOR_SUPPLY("vmmc", "omap_hsmmc.0"),
};
static struct regulator_consumer_supply zoom_vsim_supply[] = {
REGULATOR_SUPPLY("vmmc_aux", "omap_hsmmc.0"),
};
static struct regulator_consumer_supply zoom_vmmc2_supply[] = {
REGULATOR_SUPPLY("vmmc", "omap_hsmmc.1"),
};
static struct regulator_consumer_supply zoom_vmmc3_supply[] = {
REGULATOR_SUPPLY("vmmc", "omap_hsmmc.2"),
};
/* VMMC1 for OMAP VDD_MMC1 (i/o) and MMC1 card */
static struct regulator_init_data zoom_vmmc1 = {
.constraints = {
.min_uV = 1850000,
.max_uV = 3150000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(zoom_vmmc1_supply),
.consumer_supplies = zoom_vmmc1_supply,
};
/* VMMC2 for MMC2 card */
static struct regulator_init_data zoom_vmmc2 = {
.constraints = {
.min_uV = 1850000,
.max_uV = 1850000,
.apply_uV = true,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(zoom_vmmc2_supply),
.consumer_supplies = zoom_vmmc2_supply,
};
/* VSIM for OMAP VDD_MMC1A (i/o for DAT4..DAT7) */
static struct regulator_init_data zoom_vsim = {
.constraints = {
.min_uV = 1800000,
.max_uV = 3000000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(zoom_vsim_supply),
.consumer_supplies = zoom_vsim_supply,
};
static struct regulator_init_data zoom_vmmc3 = {
.constraints = {
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(zoom_vmmc3_supply),
.consumer_supplies = zoom_vmmc3_supply,
};
static struct fixed_voltage_config zoom_vwlan = {
.supply_name = "vwl1271",
.microvolts = 1800000, /* 1.8V */
.gpio = OMAP_ZOOM_WLAN_PMENA_GPIO,
.startup_delay = 70000, /* 70msec */
.enable_high = 1,
.enabled_at_boot = 0,
.init_data = &zoom_vmmc3,
};
static struct platform_device omap_vwlan_device = {
.name = "reg-fixed-voltage",
.id = 1,
.dev = {
.platform_data = &zoom_vwlan,
},
};
static struct wl12xx_platform_data omap_zoom_wlan_data __initdata = {
/* ZOOM ref clock is 26 MHz */
.board_ref_clock = 1,
};
static struct omap2_hsmmc_info mmc[] = {
{
.name = "external",
.mmc = 1,
.caps = MMC_CAP_4_BIT_DATA,
.gpio_wp = -EINVAL,
.power_saving = true,
.deferred = true,
},
{
.name = "internal",
.mmc = 2,
.caps = MMC_CAP_4_BIT_DATA | MMC_CAP_8_BIT_DATA,
.gpio_cd = -EINVAL,
.gpio_wp = -EINVAL,
.nonremovable = true,
.power_saving = true,
},
{
.name = "wl1271",
.mmc = 3,
.caps = MMC_CAP_4_BIT_DATA | MMC_CAP_POWER_OFF_CARD,
.gpio_wp = -EINVAL,
.gpio_cd = -EINVAL,
.nonremovable = true,
},
{} /* Terminator */
};
static int zoom_twl_gpio_setup(struct device *dev,
unsigned gpio, unsigned ngpio)
{
int ret;
/* gpio + 0 is "mmc0_cd" (input/IRQ) */
mmc[0].gpio_cd = gpio + 0;
omap_hsmmc_late_init(mmc);
ret = gpio_request_one(LCD_PANEL_ENABLE_GPIO, GPIOF_OUT_INIT_LOW,
"lcd enable");
if (ret)
pr_err("Failed to get LCD_PANEL_ENABLE_GPIO (gpio%d).\n",
LCD_PANEL_ENABLE_GPIO);
return ret;
}
/* EXTMUTE callback function */
static void zoom2_set_hs_extmute(int mute)
{
gpio_set_value(ZOOM2_HEADSET_EXTMUTE_GPIO, mute);
}
static struct twl4030_gpio_platform_data zoom_gpio_data = {
.gpio_base = OMAP_MAX_GPIO_LINES,
.irq_base = TWL4030_GPIO_IRQ_BASE,
.irq_end = TWL4030_GPIO_IRQ_END,
.setup = zoom_twl_gpio_setup,
};
static struct twl4030_platform_data zoom_twldata = {
/* platform_data for children goes here */
.gpio = &zoom_gpio_data,
.keypad = &zoom_kp_twl4030_data,
.vmmc1 = &zoom_vmmc1,
.vmmc2 = &zoom_vmmc2,
.vsim = &zoom_vsim,
};
static int __init omap_i2c_init(void)
{
omap3_pmic_get_config(&zoom_twldata,
TWL_COMMON_PDATA_USB | TWL_COMMON_PDATA_BCI |
TWL_COMMON_PDATA_MADC | TWL_COMMON_PDATA_AUDIO,
TWL_COMMON_REGULATOR_VDAC | TWL_COMMON_REGULATOR_VPLL2);
if (machine_is_omap_zoom2()) {
struct twl4030_codec_data *codec_data;
codec_data = zoom_twldata.audio->codec;
codec_data->ramp_delay_value = 3; /* 161 ms */
codec_data->hs_extmute = 1;
codec_data->set_hs_extmute = zoom2_set_hs_extmute;
}
omap_pmic_init(1, 2400, "twl5030", INT_34XX_SYS_NIRQ, &zoom_twldata);
omap_register_i2c_bus(2, 400, NULL, 0);
omap_register_i2c_bus(3, 400, NULL, 0);
return 0;
}
static void enable_board_wakeup_source(void)
{
/* T2 interrupt line (keypad) */
omap_mux_init_signal("sys_nirq",
OMAP_WAKEUP_EN | OMAP_PIN_INPUT_PULLUP);
}
void __init zoom_peripherals_init(void)
{
int ret;
omap_zoom_wlan_data.irq = gpio_to_irq(OMAP_ZOOM_WLAN_IRQ_GPIO);
ret = wl12xx_set_platform_data(&omap_zoom_wlan_data);
if (ret)
pr_err("error setting wl12xx data: %d\n", ret);
omap_hsmmc_init(mmc);
omap_i2c_init();
platform_device_register(&omap_vwlan_device);
usb_musb_init(NULL);
enable_board_wakeup_source();
omap_serial_init();
}
| gpl-2.0 |
Octo-Kat/platform_kernel_asus_flo | arch/arm/plat-s3c24xx/s3c2412-iotiming.c | 5120 | 7783 | /* linux/arch/arm/plat-s3c24xx/s3c2412-iotiming.c
*
* Copyright (c) 2006-2008 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* S3C2412/S3C2443 (PL093 based) IO timing support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/cpufreq.h>
#include <linux/seq_file.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/amba/pl093.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/regs-s3c2412-mem.h>
#include <plat/cpu.h>
#include <plat/cpu-freq-core.h>
#include <plat/clock.h>
#define print_ns(x) ((x) / 10), ((x) % 10)
/**
* s3c2412_print_timing - print timing infromation via printk.
* @pfx: The prefix to print each line with.
* @iot: The IO timing information
*/
static void s3c2412_print_timing(const char *pfx, struct s3c_iotimings *iot)
{
struct s3c2412_iobank_timing *bt;
unsigned int bank;
for (bank = 0; bank < MAX_BANKS; bank++) {
bt = iot->bank[bank].io_2412;
if (!bt)
continue;
printk(KERN_DEBUG "%s: %d: idcy=%d.%d wstrd=%d.%d wstwr=%d,%d"
"wstoen=%d.%d wstwen=%d.%d wstbrd=%d.%d\n", pfx, bank,
print_ns(bt->idcy),
print_ns(bt->wstrd),
print_ns(bt->wstwr),
print_ns(bt->wstoen),
print_ns(bt->wstwen),
print_ns(bt->wstbrd));
}
}
/**
* to_div - turn a cycle length into a divisor setting.
* @cyc_tns: The cycle time in 10ths of nanoseconds.
* @clk_tns: The clock period in 10ths of nanoseconds.
*/
static inline unsigned int to_div(unsigned int cyc_tns, unsigned int clk_tns)
{
return cyc_tns ? DIV_ROUND_UP(cyc_tns, clk_tns) : 0;
}
/**
* calc_timing - calculate timing divisor value and check in range.
* @hwtm: The hardware timing in 10ths of nanoseconds.
* @clk_tns: The clock period in 10ths of nanoseconds.
* @err: Pointer to err variable to update in event of failure.
*/
static unsigned int calc_timing(unsigned int hwtm, unsigned int clk_tns,
unsigned int *err)
{
unsigned int ret = to_div(hwtm, clk_tns);
if (ret > 0xf)
*err = -EINVAL;
return ret;
}
/**
* s3c2412_calc_bank - calculate the bank divisor settings.
* @cfg: The current frequency configuration.
* @bt: The bank timing.
*/
static int s3c2412_calc_bank(struct s3c_cpufreq_config *cfg,
struct s3c2412_iobank_timing *bt)
{
unsigned int hclk = cfg->freq.hclk_tns;
int err = 0;
bt->smbidcyr = calc_timing(bt->idcy, hclk, &err);
bt->smbwstrd = calc_timing(bt->wstrd, hclk, &err);
bt->smbwstwr = calc_timing(bt->wstwr, hclk, &err);
bt->smbwstoen = calc_timing(bt->wstoen, hclk, &err);
bt->smbwstwen = calc_timing(bt->wstwen, hclk, &err);
bt->smbwstbrd = calc_timing(bt->wstbrd, hclk, &err);
return err;
}
/**
* s3c2412_iotiming_debugfs - debugfs show io bank timing information
* @seq: The seq_file to write output to using seq_printf().
* @cfg: The current configuration.
* @iob: The IO bank information to decode.
*/
void s3c2412_iotiming_debugfs(struct seq_file *seq,
struct s3c_cpufreq_config *cfg,
union s3c_iobank *iob)
{
struct s3c2412_iobank_timing *bt = iob->io_2412;
seq_printf(seq,
"\tRead: idcy=%d.%d wstrd=%d.%d wstwr=%d,%d"
"wstoen=%d.%d wstwen=%d.%d wstbrd=%d.%d\n",
print_ns(bt->idcy),
print_ns(bt->wstrd),
print_ns(bt->wstwr),
print_ns(bt->wstoen),
print_ns(bt->wstwen),
print_ns(bt->wstbrd));
}
/**
* s3c2412_iotiming_calc - calculate all the bank divisor settings.
* @cfg: The current frequency configuration.
* @iot: The bank timing information.
*
* Calculate the timing information for all the banks that are
* configured as IO, using s3c2412_calc_bank().
*/
int s3c2412_iotiming_calc(struct s3c_cpufreq_config *cfg,
struct s3c_iotimings *iot)
{
struct s3c2412_iobank_timing *bt;
int bank;
int ret;
for (bank = 0; bank < MAX_BANKS; bank++) {
bt = iot->bank[bank].io_2412;
if (!bt)
continue;
ret = s3c2412_calc_bank(cfg, bt);
if (ret) {
printk(KERN_ERR "%s: cannot calculate bank %d io\n",
__func__, bank);
goto err;
}
}
return 0;
err:
return ret;
}
/**
* s3c2412_iotiming_set - set the timing information
* @cfg: The current frequency configuration.
* @iot: The bank timing information.
*
* Set the IO bank information from the details calculated earlier from
* calling s3c2412_iotiming_calc().
*/
void s3c2412_iotiming_set(struct s3c_cpufreq_config *cfg,
struct s3c_iotimings *iot)
{
struct s3c2412_iobank_timing *bt;
void __iomem *regs;
int bank;
/* set the io timings from the specifier */
for (bank = 0; bank < MAX_BANKS; bank++) {
bt = iot->bank[bank].io_2412;
if (!bt)
continue;
regs = S3C2412_SSMC_BANK(bank);
__raw_writel(bt->smbidcyr, regs + SMBIDCYR);
__raw_writel(bt->smbwstrd, regs + SMBWSTRDR);
__raw_writel(bt->smbwstwr, regs + SMBWSTWRR);
__raw_writel(bt->smbwstoen, regs + SMBWSTOENR);
__raw_writel(bt->smbwstwen, regs + SMBWSTWENR);
__raw_writel(bt->smbwstbrd, regs + SMBWSTBRDR);
}
}
static inline unsigned int s3c2412_decode_timing(unsigned int clock, u32 reg)
{
return (reg & 0xf) * clock;
}
static void s3c2412_iotiming_getbank(struct s3c_cpufreq_config *cfg,
struct s3c2412_iobank_timing *bt,
unsigned int bank)
{
unsigned long clk = cfg->freq.hclk_tns; /* ssmc clock??? */
void __iomem *regs = S3C2412_SSMC_BANK(bank);
bt->idcy = s3c2412_decode_timing(clk, __raw_readl(regs + SMBIDCYR));
bt->wstrd = s3c2412_decode_timing(clk, __raw_readl(regs + SMBWSTRDR));
bt->wstoen = s3c2412_decode_timing(clk, __raw_readl(regs + SMBWSTOENR));
bt->wstwen = s3c2412_decode_timing(clk, __raw_readl(regs + SMBWSTWENR));
bt->wstbrd = s3c2412_decode_timing(clk, __raw_readl(regs + SMBWSTBRDR));
}
/**
* bank_is_io - return true if bank is (possibly) IO.
* @bank: The bank number.
* @bankcfg: The value of S3C2412_EBI_BANKCFG.
*/
static inline bool bank_is_io(unsigned int bank, u32 bankcfg)
{
if (bank < 2)
return true;
return !(bankcfg & (1 << bank));
}
int s3c2412_iotiming_get(struct s3c_cpufreq_config *cfg,
struct s3c_iotimings *timings)
{
struct s3c2412_iobank_timing *bt;
u32 bankcfg = __raw_readl(S3C2412_EBI_BANKCFG);
unsigned int bank;
/* look through all banks to see what is currently set. */
for (bank = 0; bank < MAX_BANKS; bank++) {
if (!bank_is_io(bank, bankcfg))
continue;
bt = kzalloc(sizeof(struct s3c2412_iobank_timing), GFP_KERNEL);
if (!bt) {
printk(KERN_ERR "%s: no memory for bank\n", __func__);
return -ENOMEM;
}
timings->bank[bank].io_2412 = bt;
s3c2412_iotiming_getbank(cfg, bt, bank);
}
s3c2412_print_timing("get", timings);
return 0;
}
/* this is in here as it is so small, it doesn't currently warrant a file
* to itself. We expect that any s3c24xx needing this is going to also
* need the iotiming support.
*/
void s3c2412_cpufreq_setrefresh(struct s3c_cpufreq_config *cfg)
{
struct s3c_cpufreq_board *board = cfg->board;
u32 refresh;
WARN_ON(board == NULL);
/* Reduce both the refresh time (in ns) and the frequency (in MHz)
* down to ensure that we do not overflow 32 bit numbers.
*
* This should work for HCLK up to 133MHz and refresh period up
* to 30usec.
*/
refresh = (cfg->freq.hclk / 100) * (board->refresh / 10);
refresh = DIV_ROUND_UP(refresh, (1000 * 1000)); /* apply scale */
refresh &= ((1 << 16) - 1);
s3c_freq_dbg("%s: refresh value %u\n", __func__, (unsigned int)refresh);
__raw_writel(refresh, S3C2412_REFRESH);
}
| gpl-2.0 |
jeboo/kernel_JB_ZSLS6_i777 | drivers/media/dvb/mantis/mantis_dvb.c | 6400 | 7701 | /*
Mantis PCI bridge driver
Copyright (C) Manu Abraham (abraham.manu@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/bitops.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/i2c.h>
#include "dmxdev.h"
#include "dvbdev.h"
#include "dvb_demux.h"
#include "dvb_frontend.h"
#include "dvb_net.h"
#include "mantis_common.h"
#include "mantis_dma.h"
#include "mantis_ca.h"
#include "mantis_ioc.h"
#include "mantis_dvb.h"
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
int mantis_frontend_power(struct mantis_pci *mantis, enum mantis_power power)
{
struct mantis_hwconfig *config = mantis->hwconfig;
switch (power) {
case POWER_ON:
dprintk(MANTIS_DEBUG, 1, "Power ON");
mantis_gpio_set_bits(mantis, config->power, POWER_ON);
msleep(100);
mantis_gpio_set_bits(mantis, config->power, POWER_ON);
msleep(100);
break;
case POWER_OFF:
dprintk(MANTIS_DEBUG, 1, "Power OFF");
mantis_gpio_set_bits(mantis, config->power, POWER_OFF);
msleep(100);
break;
default:
dprintk(MANTIS_DEBUG, 1, "Unknown state <%02x>", power);
return -1;
}
return 0;
}
EXPORT_SYMBOL_GPL(mantis_frontend_power);
void mantis_frontend_soft_reset(struct mantis_pci *mantis)
{
struct mantis_hwconfig *config = mantis->hwconfig;
dprintk(MANTIS_DEBUG, 1, "Frontend RESET");
mantis_gpio_set_bits(mantis, config->reset, 0);
msleep(100);
mantis_gpio_set_bits(mantis, config->reset, 0);
msleep(100);
mantis_gpio_set_bits(mantis, config->reset, 1);
msleep(100);
mantis_gpio_set_bits(mantis, config->reset, 1);
msleep(100);
return;
}
EXPORT_SYMBOL_GPL(mantis_frontend_soft_reset);
static int mantis_frontend_shutdown(struct mantis_pci *mantis)
{
int err;
mantis_frontend_soft_reset(mantis);
err = mantis_frontend_power(mantis, POWER_OFF);
if (err != 0) {
dprintk(MANTIS_ERROR, 1, "Frontend POWER OFF failed! <%d>", err);
return 1;
}
return 0;
}
static int mantis_dvb_start_feed(struct dvb_demux_feed *dvbdmxfeed)
{
struct dvb_demux *dvbdmx = dvbdmxfeed->demux;
struct mantis_pci *mantis = dvbdmx->priv;
dprintk(MANTIS_DEBUG, 1, "Mantis DVB Start feed");
if (!dvbdmx->dmx.frontend) {
dprintk(MANTIS_DEBUG, 1, "no frontend ?");
return -EINVAL;
}
mantis->feeds++;
dprintk(MANTIS_DEBUG, 1, "mantis start feed, feeds=%d", mantis->feeds);
if (mantis->feeds == 1) {
dprintk(MANTIS_DEBUG, 1, "mantis start feed & dma");
mantis_dma_start(mantis);
tasklet_enable(&mantis->tasklet);
}
return mantis->feeds;
}
static int mantis_dvb_stop_feed(struct dvb_demux_feed *dvbdmxfeed)
{
struct dvb_demux *dvbdmx = dvbdmxfeed->demux;
struct mantis_pci *mantis = dvbdmx->priv;
dprintk(MANTIS_DEBUG, 1, "Mantis DVB Stop feed");
if (!dvbdmx->dmx.frontend) {
dprintk(MANTIS_DEBUG, 1, "no frontend ?");
return -EINVAL;
}
mantis->feeds--;
if (mantis->feeds == 0) {
dprintk(MANTIS_DEBUG, 1, "mantis stop feed and dma");
tasklet_disable(&mantis->tasklet);
mantis_dma_stop(mantis);
}
return 0;
}
int __devinit mantis_dvb_init(struct mantis_pci *mantis)
{
struct mantis_hwconfig *config = mantis->hwconfig;
int result = -1;
dprintk(MANTIS_DEBUG, 1, "dvb_register_adapter");
result = dvb_register_adapter(&mantis->dvb_adapter,
"Mantis DVB adapter",
THIS_MODULE,
&mantis->pdev->dev,
adapter_nr);
if (result < 0) {
dprintk(MANTIS_ERROR, 1, "Error registering adapter");
return -ENODEV;
}
mantis->dvb_adapter.priv = mantis;
mantis->demux.dmx.capabilities = DMX_TS_FILTERING |
DMX_SECTION_FILTERING |
DMX_MEMORY_BASED_FILTERING;
mantis->demux.priv = mantis;
mantis->demux.filternum = 256;
mantis->demux.feednum = 256;
mantis->demux.start_feed = mantis_dvb_start_feed;
mantis->demux.stop_feed = mantis_dvb_stop_feed;
mantis->demux.write_to_decoder = NULL;
dprintk(MANTIS_DEBUG, 1, "dvb_dmx_init");
result = dvb_dmx_init(&mantis->demux);
if (result < 0) {
dprintk(MANTIS_ERROR, 1, "dvb_dmx_init failed, ERROR=%d", result);
goto err0;
}
mantis->dmxdev.filternum = 256;
mantis->dmxdev.demux = &mantis->demux.dmx;
mantis->dmxdev.capabilities = 0;
dprintk(MANTIS_DEBUG, 1, "dvb_dmxdev_init");
result = dvb_dmxdev_init(&mantis->dmxdev, &mantis->dvb_adapter);
if (result < 0) {
dprintk(MANTIS_ERROR, 1, "dvb_dmxdev_init failed, ERROR=%d", result);
goto err1;
}
mantis->fe_hw.source = DMX_FRONTEND_0;
result = mantis->demux.dmx.add_frontend(&mantis->demux.dmx, &mantis->fe_hw);
if (result < 0) {
dprintk(MANTIS_ERROR, 1, "dvb_dmx_init failed, ERROR=%d", result);
goto err2;
}
mantis->fe_mem.source = DMX_MEMORY_FE;
result = mantis->demux.dmx.add_frontend(&mantis->demux.dmx, &mantis->fe_mem);
if (result < 0) {
dprintk(MANTIS_ERROR, 1, "dvb_dmx_init failed, ERROR=%d", result);
goto err3;
}
result = mantis->demux.dmx.connect_frontend(&mantis->demux.dmx, &mantis->fe_hw);
if (result < 0) {
dprintk(MANTIS_ERROR, 1, "dvb_dmx_init failed, ERROR=%d", result);
goto err4;
}
dvb_net_init(&mantis->dvb_adapter, &mantis->dvbnet, &mantis->demux.dmx);
tasklet_init(&mantis->tasklet, mantis_dma_xfer, (unsigned long) mantis);
tasklet_disable(&mantis->tasklet);
if (mantis->hwconfig) {
result = config->frontend_init(mantis, mantis->fe);
if (result < 0) {
dprintk(MANTIS_ERROR, 1, "!!! NO Frontends found !!!");
goto err5;
} else {
if (mantis->fe == NULL) {
dprintk(MANTIS_ERROR, 1, "FE <NULL>");
goto err5;
}
if (dvb_register_frontend(&mantis->dvb_adapter, mantis->fe)) {
dprintk(MANTIS_ERROR, 1, "ERROR: Frontend registration failed");
if (mantis->fe->ops.release)
mantis->fe->ops.release(mantis->fe);
mantis->fe = NULL;
goto err5;
}
}
}
return 0;
/* Error conditions .. */
err5:
tasklet_kill(&mantis->tasklet);
dvb_net_release(&mantis->dvbnet);
dvb_unregister_frontend(mantis->fe);
dvb_frontend_detach(mantis->fe);
err4:
mantis->demux.dmx.remove_frontend(&mantis->demux.dmx, &mantis->fe_mem);
err3:
mantis->demux.dmx.remove_frontend(&mantis->demux.dmx, &mantis->fe_hw);
err2:
dvb_dmxdev_release(&mantis->dmxdev);
err1:
dvb_dmx_release(&mantis->demux);
err0:
dvb_unregister_adapter(&mantis->dvb_adapter);
return result;
}
EXPORT_SYMBOL_GPL(mantis_dvb_init);
int __devexit mantis_dvb_exit(struct mantis_pci *mantis)
{
int err;
if (mantis->fe) {
/* mantis_ca_exit(mantis); */
err = mantis_frontend_shutdown(mantis);
if (err != 0)
dprintk(MANTIS_ERROR, 1, "Frontend exit while POWER ON! <%d>", err);
dvb_unregister_frontend(mantis->fe);
dvb_frontend_detach(mantis->fe);
}
tasklet_kill(&mantis->tasklet);
dvb_net_release(&mantis->dvbnet);
mantis->demux.dmx.remove_frontend(&mantis->demux.dmx, &mantis->fe_mem);
mantis->demux.dmx.remove_frontend(&mantis->demux.dmx, &mantis->fe_hw);
dvb_dmxdev_release(&mantis->dmxdev);
dvb_dmx_release(&mantis->demux);
dprintk(MANTIS_DEBUG, 1, "dvb_unregister_adapter");
dvb_unregister_adapter(&mantis->dvb_adapter);
return 0;
}
EXPORT_SYMBOL_GPL(mantis_dvb_exit);
| gpl-2.0 |
bangprovn/android_kernel_lge_v400_10c | arch/ia64/hp/common/sba_iommu.c | 6656 | 60275 | /*
** IA64 System Bus Adapter (SBA) I/O MMU manager
**
** (c) Copyright 2002-2005 Alex Williamson
** (c) Copyright 2002-2003 Grant Grundler
** (c) Copyright 2002-2005 Hewlett-Packard Company
**
** Portions (c) 2000 Grant Grundler (from parisc I/O MMU code)
** Portions (c) 1999 Dave S. Miller (from sparc64 I/O MMU code)
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
**
** This module initializes the IOC (I/O Controller) found on HP
** McKinley machines and their successors.
**
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/pci.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/acpi.h>
#include <linux/efi.h>
#include <linux/nodemask.h>
#include <linux/bitops.h> /* hweight64() */
#include <linux/crash_dump.h>
#include <linux/iommu-helper.h>
#include <linux/dma-mapping.h>
#include <linux/prefetch.h>
#include <asm/delay.h> /* ia64_get_itc() */
#include <asm/io.h>
#include <asm/page.h> /* PAGE_OFFSET */
#include <asm/dma.h>
#include <asm/acpi-ext.h>
extern int swiotlb_late_init_with_default_size (size_t size);
#define PFX "IOC: "
/*
** Enabling timing search of the pdir resource map. Output in /proc.
** Disabled by default to optimize performance.
*/
#undef PDIR_SEARCH_TIMING
/*
** This option allows cards capable of 64bit DMA to bypass the IOMMU. If
** not defined, all DMA will be 32bit and go through the TLB.
** There's potentially a conflict in the bio merge code with us
** advertising an iommu, but then bypassing it. Since I/O MMU bypassing
** appears to give more performance than bio-level virtual merging, we'll
** do the former for now. NOTE: BYPASS_SG also needs to be undef'd to
** completely restrict DMA to the IOMMU.
*/
#define ALLOW_IOV_BYPASS
/*
** This option specifically allows/disallows bypassing scatterlists with
** multiple entries. Coalescing these entries can allow better DMA streaming
** and in some cases shows better performance than entirely bypassing the
** IOMMU. Performance increase on the order of 1-2% sequential output/input
** using bonnie++ on a RAID0 MD device (sym2 & mpt).
*/
#undef ALLOW_IOV_BYPASS_SG
/*
** If a device prefetches beyond the end of a valid pdir entry, it will cause
** a hard failure, ie. MCA. Version 3.0 and later of the zx1 LBA should
** disconnect on 4k boundaries and prevent such issues. If the device is
** particularly aggressive, this option will keep the entire pdir valid such
** that prefetching will hit a valid address. This could severely impact
** error containment, and is therefore off by default. The page that is
** used for spill-over is poisoned, so that should help debugging somewhat.
*/
#undef FULL_VALID_PDIR
#define ENABLE_MARK_CLEAN
/*
** The number of debug flags is a clue - this code is fragile. NOTE: since
** tightening the use of res_lock the resource bitmap and actual pdir are no
** longer guaranteed to stay in sync. The sanity checking code isn't going to
** like that.
*/
#undef DEBUG_SBA_INIT
#undef DEBUG_SBA_RUN
#undef DEBUG_SBA_RUN_SG
#undef DEBUG_SBA_RESOURCE
#undef ASSERT_PDIR_SANITY
#undef DEBUG_LARGE_SG_ENTRIES
#undef DEBUG_BYPASS
#if defined(FULL_VALID_PDIR) && defined(ASSERT_PDIR_SANITY)
#error FULL_VALID_PDIR and ASSERT_PDIR_SANITY are mutually exclusive
#endif
#define SBA_INLINE __inline__
/* #define SBA_INLINE */
#ifdef DEBUG_SBA_INIT
#define DBG_INIT(x...) printk(x)
#else
#define DBG_INIT(x...)
#endif
#ifdef DEBUG_SBA_RUN
#define DBG_RUN(x...) printk(x)
#else
#define DBG_RUN(x...)
#endif
#ifdef DEBUG_SBA_RUN_SG
#define DBG_RUN_SG(x...) printk(x)
#else
#define DBG_RUN_SG(x...)
#endif
#ifdef DEBUG_SBA_RESOURCE
#define DBG_RES(x...) printk(x)
#else
#define DBG_RES(x...)
#endif
#ifdef DEBUG_BYPASS
#define DBG_BYPASS(x...) printk(x)
#else
#define DBG_BYPASS(x...)
#endif
#ifdef ASSERT_PDIR_SANITY
#define ASSERT(expr) \
if(!(expr)) { \
printk( "\n" __FILE__ ":%d: Assertion " #expr " failed!\n",__LINE__); \
panic(#expr); \
}
#else
#define ASSERT(expr)
#endif
/*
** The number of pdir entries to "free" before issuing
** a read to PCOM register to flush out PCOM writes.
** Interacts with allocation granularity (ie 4 or 8 entries
** allocated and free'd/purged at a time might make this
** less interesting).
*/
#define DELAYED_RESOURCE_CNT 64
#define PCI_DEVICE_ID_HP_SX2000_IOC 0x12ec
#define ZX1_IOC_ID ((PCI_DEVICE_ID_HP_ZX1_IOC << 16) | PCI_VENDOR_ID_HP)
#define ZX2_IOC_ID ((PCI_DEVICE_ID_HP_ZX2_IOC << 16) | PCI_VENDOR_ID_HP)
#define REO_IOC_ID ((PCI_DEVICE_ID_HP_REO_IOC << 16) | PCI_VENDOR_ID_HP)
#define SX1000_IOC_ID ((PCI_DEVICE_ID_HP_SX1000_IOC << 16) | PCI_VENDOR_ID_HP)
#define SX2000_IOC_ID ((PCI_DEVICE_ID_HP_SX2000_IOC << 16) | PCI_VENDOR_ID_HP)
#define ZX1_IOC_OFFSET 0x1000 /* ACPI reports SBA, we want IOC */
#define IOC_FUNC_ID 0x000
#define IOC_FCLASS 0x008 /* function class, bist, header, rev... */
#define IOC_IBASE 0x300 /* IO TLB */
#define IOC_IMASK 0x308
#define IOC_PCOM 0x310
#define IOC_TCNFG 0x318
#define IOC_PDIR_BASE 0x320
#define IOC_ROPE0_CFG 0x500
#define IOC_ROPE_AO 0x10 /* Allow "Relaxed Ordering" */
/* AGP GART driver looks for this */
#define ZX1_SBA_IOMMU_COOKIE 0x0000badbadc0ffeeUL
/*
** The zx1 IOC supports 4/8/16/64KB page sizes (see TCNFG register)
**
** Some IOCs (sx1000) can run at the above pages sizes, but are
** really only supported using the IOC at a 4k page size.
**
** iovp_size could only be greater than PAGE_SIZE if we are
** confident the drivers really only touch the next physical
** page iff that driver instance owns it.
*/
static unsigned long iovp_size;
static unsigned long iovp_shift;
static unsigned long iovp_mask;
struct ioc {
void __iomem *ioc_hpa; /* I/O MMU base address */
char *res_map; /* resource map, bit == pdir entry */
u64 *pdir_base; /* physical base address */
unsigned long ibase; /* pdir IOV Space base */
unsigned long imask; /* pdir IOV Space mask */
unsigned long *res_hint; /* next avail IOVP - circular search */
unsigned long dma_mask;
spinlock_t res_lock; /* protects the resource bitmap, but must be held when */
/* clearing pdir to prevent races with allocations. */
unsigned int res_bitshift; /* from the RIGHT! */
unsigned int res_size; /* size of resource map in bytes */
#ifdef CONFIG_NUMA
unsigned int node; /* node where this IOC lives */
#endif
#if DELAYED_RESOURCE_CNT > 0
spinlock_t saved_lock; /* may want to try to get this on a separate cacheline */
/* than res_lock for bigger systems. */
int saved_cnt;
struct sba_dma_pair {
dma_addr_t iova;
size_t size;
} saved[DELAYED_RESOURCE_CNT];
#endif
#ifdef PDIR_SEARCH_TIMING
#define SBA_SEARCH_SAMPLE 0x100
unsigned long avg_search[SBA_SEARCH_SAMPLE];
unsigned long avg_idx; /* current index into avg_search */
#endif
/* Stuff we don't need in performance path */
struct ioc *next; /* list of IOC's in system */
acpi_handle handle; /* for multiple IOC's */
const char *name;
unsigned int func_id;
unsigned int rev; /* HW revision of chip */
u32 iov_size;
unsigned int pdir_size; /* in bytes, determined by IOV Space size */
struct pci_dev *sac_only_dev;
};
static struct ioc *ioc_list;
static int reserve_sba_gart = 1;
static SBA_INLINE void sba_mark_invalid(struct ioc *, dma_addr_t, size_t);
static SBA_INLINE void sba_free_range(struct ioc *, dma_addr_t, size_t);
#define sba_sg_address(sg) sg_virt((sg))
#ifdef FULL_VALID_PDIR
static u64 prefetch_spill_page;
#endif
#ifdef CONFIG_PCI
# define GET_IOC(dev) (((dev)->bus == &pci_bus_type) \
? ((struct ioc *) PCI_CONTROLLER(to_pci_dev(dev))->iommu) : NULL)
#else
# define GET_IOC(dev) NULL
#endif
/*
** DMA_CHUNK_SIZE is used by the SCSI mid-layer to break up
** (or rather not merge) DMAs into manageable chunks.
** On parisc, this is more of the software/tuning constraint
** rather than the HW. I/O MMU allocation algorithms can be
** faster with smaller sizes (to some degree).
*/
#define DMA_CHUNK_SIZE (BITS_PER_LONG*iovp_size)
#define ROUNDUP(x,y) ((x + ((y)-1)) & ~((y)-1))
/************************************
** SBA register read and write support
**
** BE WARNED: register writes are posted.
** (ie follow writes which must reach HW with a read)
**
*/
#define READ_REG(addr) __raw_readq(addr)
#define WRITE_REG(val, addr) __raw_writeq(val, addr)
#ifdef DEBUG_SBA_INIT
/**
* sba_dump_tlb - debugging only - print IOMMU operating parameters
* @hpa: base address of the IOMMU
*
* Print the size/location of the IO MMU PDIR.
*/
static void
sba_dump_tlb(char *hpa)
{
DBG_INIT("IO TLB at 0x%p\n", (void *)hpa);
DBG_INIT("IOC_IBASE : %016lx\n", READ_REG(hpa+IOC_IBASE));
DBG_INIT("IOC_IMASK : %016lx\n", READ_REG(hpa+IOC_IMASK));
DBG_INIT("IOC_TCNFG : %016lx\n", READ_REG(hpa+IOC_TCNFG));
DBG_INIT("IOC_PDIR_BASE: %016lx\n", READ_REG(hpa+IOC_PDIR_BASE));
DBG_INIT("\n");
}
#endif
#ifdef ASSERT_PDIR_SANITY
/**
* sba_dump_pdir_entry - debugging only - print one IOMMU PDIR entry
* @ioc: IO MMU structure which owns the pdir we are interested in.
* @msg: text to print ont the output line.
* @pide: pdir index.
*
* Print one entry of the IO MMU PDIR in human readable form.
*/
static void
sba_dump_pdir_entry(struct ioc *ioc, char *msg, uint pide)
{
/* start printing from lowest pde in rval */
u64 *ptr = &ioc->pdir_base[pide & ~(BITS_PER_LONG - 1)];
unsigned long *rptr = (unsigned long *) &ioc->res_map[(pide >>3) & -sizeof(unsigned long)];
uint rcnt;
printk(KERN_DEBUG "SBA: %s rp %p bit %d rval 0x%lx\n",
msg, rptr, pide & (BITS_PER_LONG - 1), *rptr);
rcnt = 0;
while (rcnt < BITS_PER_LONG) {
printk(KERN_DEBUG "%s %2d %p %016Lx\n",
(rcnt == (pide & (BITS_PER_LONG - 1)))
? " -->" : " ",
rcnt, ptr, (unsigned long long) *ptr );
rcnt++;
ptr++;
}
printk(KERN_DEBUG "%s", msg);
}
/**
* sba_check_pdir - debugging only - consistency checker
* @ioc: IO MMU structure which owns the pdir we are interested in.
* @msg: text to print ont the output line.
*
* Verify the resource map and pdir state is consistent
*/
static int
sba_check_pdir(struct ioc *ioc, char *msg)
{
u64 *rptr_end = (u64 *) &(ioc->res_map[ioc->res_size]);
u64 *rptr = (u64 *) ioc->res_map; /* resource map ptr */
u64 *pptr = ioc->pdir_base; /* pdir ptr */
uint pide = 0;
while (rptr < rptr_end) {
u64 rval;
int rcnt; /* number of bits we might check */
rval = *rptr;
rcnt = 64;
while (rcnt) {
/* Get last byte and highest bit from that */
u32 pde = ((u32)((*pptr >> (63)) & 0x1));
if ((rval & 0x1) ^ pde)
{
/*
** BUMMER! -- res_map != pdir --
** Dump rval and matching pdir entries
*/
sba_dump_pdir_entry(ioc, msg, pide);
return(1);
}
rcnt--;
rval >>= 1; /* try the next bit */
pptr++;
pide++;
}
rptr++; /* look at next word of res_map */
}
/* It'd be nice if we always got here :^) */
return 0;
}
/**
* sba_dump_sg - debugging only - print Scatter-Gather list
* @ioc: IO MMU structure which owns the pdir we are interested in.
* @startsg: head of the SG list
* @nents: number of entries in SG list
*
* print the SG list so we can verify it's correct by hand.
*/
static void
sba_dump_sg( struct ioc *ioc, struct scatterlist *startsg, int nents)
{
while (nents-- > 0) {
printk(KERN_DEBUG " %d : DMA %08lx/%05x CPU %p\n", nents,
startsg->dma_address, startsg->dma_length,
sba_sg_address(startsg));
startsg = sg_next(startsg);
}
}
static void
sba_check_sg( struct ioc *ioc, struct scatterlist *startsg, int nents)
{
struct scatterlist *the_sg = startsg;
int the_nents = nents;
while (the_nents-- > 0) {
if (sba_sg_address(the_sg) == 0x0UL)
sba_dump_sg(NULL, startsg, nents);
the_sg = sg_next(the_sg);
}
}
#endif /* ASSERT_PDIR_SANITY */
/**************************************************************
*
* I/O Pdir Resource Management
*
* Bits set in the resource map are in use.
* Each bit can represent a number of pages.
* LSbs represent lower addresses (IOVA's).
*
***************************************************************/
#define PAGES_PER_RANGE 1 /* could increase this to 4 or 8 if needed */
/* Convert from IOVP to IOVA and vice versa. */
#define SBA_IOVA(ioc,iovp,offset) ((ioc->ibase) | (iovp) | (offset))
#define SBA_IOVP(ioc,iova) ((iova) & ~(ioc->ibase))
#define PDIR_ENTRY_SIZE sizeof(u64)
#define PDIR_INDEX(iovp) ((iovp)>>iovp_shift)
#define RESMAP_MASK(n) ~(~0UL << (n))
#define RESMAP_IDX_MASK (sizeof(unsigned long) - 1)
/**
* For most cases the normal get_order is sufficient, however it limits us
* to PAGE_SIZE being the minimum mapping alignment and TC flush granularity.
* It only incurs about 1 clock cycle to use this one with the static variable
* and makes the code more intuitive.
*/
static SBA_INLINE int
get_iovp_order (unsigned long size)
{
long double d = size - 1;
long order;
order = ia64_getf_exp(d);
order = order - iovp_shift - 0xffff + 1;
if (order < 0)
order = 0;
return order;
}
static unsigned long ptr_to_pide(struct ioc *ioc, unsigned long *res_ptr,
unsigned int bitshiftcnt)
{
return (((unsigned long)res_ptr - (unsigned long)ioc->res_map) << 3)
+ bitshiftcnt;
}
/**
* sba_search_bitmap - find free space in IO PDIR resource bitmap
* @ioc: IO MMU structure which owns the pdir we are interested in.
* @bits_wanted: number of entries we need.
* @use_hint: use res_hint to indicate where to start looking
*
* Find consecutive free bits in resource bitmap.
* Each bit represents one entry in the IO Pdir.
* Cool perf optimization: search for log2(size) bits at a time.
*/
static SBA_INLINE unsigned long
sba_search_bitmap(struct ioc *ioc, struct device *dev,
unsigned long bits_wanted, int use_hint)
{
unsigned long *res_ptr;
unsigned long *res_end = (unsigned long *) &(ioc->res_map[ioc->res_size]);
unsigned long flags, pide = ~0UL, tpide;
unsigned long boundary_size;
unsigned long shift;
int ret;
ASSERT(((unsigned long) ioc->res_hint & (sizeof(unsigned long) - 1UL)) == 0);
ASSERT(res_ptr < res_end);
boundary_size = (unsigned long long)dma_get_seg_boundary(dev) + 1;
boundary_size = ALIGN(boundary_size, 1ULL << iovp_shift) >> iovp_shift;
BUG_ON(ioc->ibase & ~iovp_mask);
shift = ioc->ibase >> iovp_shift;
spin_lock_irqsave(&ioc->res_lock, flags);
/* Allow caller to force a search through the entire resource space */
if (likely(use_hint)) {
res_ptr = ioc->res_hint;
} else {
res_ptr = (ulong *)ioc->res_map;
ioc->res_bitshift = 0;
}
/*
* N.B. REO/Grande defect AR2305 can cause TLB fetch timeouts
* if a TLB entry is purged while in use. sba_mark_invalid()
* purges IOTLB entries in power-of-two sizes, so we also
* allocate IOVA space in power-of-two sizes.
*/
bits_wanted = 1UL << get_iovp_order(bits_wanted << iovp_shift);
if (likely(bits_wanted == 1)) {
unsigned int bitshiftcnt;
for(; res_ptr < res_end ; res_ptr++) {
if (likely(*res_ptr != ~0UL)) {
bitshiftcnt = ffz(*res_ptr);
*res_ptr |= (1UL << bitshiftcnt);
pide = ptr_to_pide(ioc, res_ptr, bitshiftcnt);
ioc->res_bitshift = bitshiftcnt + bits_wanted;
goto found_it;
}
}
goto not_found;
}
if (likely(bits_wanted <= BITS_PER_LONG/2)) {
/*
** Search the resource bit map on well-aligned values.
** "o" is the alignment.
** We need the alignment to invalidate I/O TLB using
** SBA HW features in the unmap path.
*/
unsigned long o = 1 << get_iovp_order(bits_wanted << iovp_shift);
uint bitshiftcnt = ROUNDUP(ioc->res_bitshift, o);
unsigned long mask, base_mask;
base_mask = RESMAP_MASK(bits_wanted);
mask = base_mask << bitshiftcnt;
DBG_RES("%s() o %ld %p", __func__, o, res_ptr);
for(; res_ptr < res_end ; res_ptr++)
{
DBG_RES(" %p %lx %lx\n", res_ptr, mask, *res_ptr);
ASSERT(0 != mask);
for (; mask ; mask <<= o, bitshiftcnt += o) {
tpide = ptr_to_pide(ioc, res_ptr, bitshiftcnt);
ret = iommu_is_span_boundary(tpide, bits_wanted,
shift,
boundary_size);
if ((0 == ((*res_ptr) & mask)) && !ret) {
*res_ptr |= mask; /* mark resources busy! */
pide = tpide;
ioc->res_bitshift = bitshiftcnt + bits_wanted;
goto found_it;
}
}
bitshiftcnt = 0;
mask = base_mask;
}
} else {
int qwords, bits, i;
unsigned long *end;
qwords = bits_wanted >> 6; /* /64 */
bits = bits_wanted - (qwords * BITS_PER_LONG);
end = res_end - qwords;
for (; res_ptr < end; res_ptr++) {
tpide = ptr_to_pide(ioc, res_ptr, 0);
ret = iommu_is_span_boundary(tpide, bits_wanted,
shift, boundary_size);
if (ret)
goto next_ptr;
for (i = 0 ; i < qwords ; i++) {
if (res_ptr[i] != 0)
goto next_ptr;
}
if (bits && res_ptr[i] && (__ffs(res_ptr[i]) < bits))
continue;
/* Found it, mark it */
for (i = 0 ; i < qwords ; i++)
res_ptr[i] = ~0UL;
res_ptr[i] |= RESMAP_MASK(bits);
pide = tpide;
res_ptr += qwords;
ioc->res_bitshift = bits;
goto found_it;
next_ptr:
;
}
}
not_found:
prefetch(ioc->res_map);
ioc->res_hint = (unsigned long *) ioc->res_map;
ioc->res_bitshift = 0;
spin_unlock_irqrestore(&ioc->res_lock, flags);
return (pide);
found_it:
ioc->res_hint = res_ptr;
spin_unlock_irqrestore(&ioc->res_lock, flags);
return (pide);
}
/**
* sba_alloc_range - find free bits and mark them in IO PDIR resource bitmap
* @ioc: IO MMU structure which owns the pdir we are interested in.
* @size: number of bytes to create a mapping for
*
* Given a size, find consecutive unmarked and then mark those bits in the
* resource bit map.
*/
static int
sba_alloc_range(struct ioc *ioc, struct device *dev, size_t size)
{
unsigned int pages_needed = size >> iovp_shift;
#ifdef PDIR_SEARCH_TIMING
unsigned long itc_start;
#endif
unsigned long pide;
ASSERT(pages_needed);
ASSERT(0 == (size & ~iovp_mask));
#ifdef PDIR_SEARCH_TIMING
itc_start = ia64_get_itc();
#endif
/*
** "seek and ye shall find"...praying never hurts either...
*/
pide = sba_search_bitmap(ioc, dev, pages_needed, 1);
if (unlikely(pide >= (ioc->res_size << 3))) {
pide = sba_search_bitmap(ioc, dev, pages_needed, 0);
if (unlikely(pide >= (ioc->res_size << 3))) {
#if DELAYED_RESOURCE_CNT > 0
unsigned long flags;
/*
** With delayed resource freeing, we can give this one more shot. We're
** getting close to being in trouble here, so do what we can to make this
** one count.
*/
spin_lock_irqsave(&ioc->saved_lock, flags);
if (ioc->saved_cnt > 0) {
struct sba_dma_pair *d;
int cnt = ioc->saved_cnt;
d = &(ioc->saved[ioc->saved_cnt - 1]);
spin_lock(&ioc->res_lock);
while (cnt--) {
sba_mark_invalid(ioc, d->iova, d->size);
sba_free_range(ioc, d->iova, d->size);
d--;
}
ioc->saved_cnt = 0;
READ_REG(ioc->ioc_hpa+IOC_PCOM); /* flush purges */
spin_unlock(&ioc->res_lock);
}
spin_unlock_irqrestore(&ioc->saved_lock, flags);
pide = sba_search_bitmap(ioc, dev, pages_needed, 0);
if (unlikely(pide >= (ioc->res_size << 3))) {
printk(KERN_WARNING "%s: I/O MMU @ %p is"
"out of mapping resources, %u %u %lx\n",
__func__, ioc->ioc_hpa, ioc->res_size,
pages_needed, dma_get_seg_boundary(dev));
return -1;
}
#else
printk(KERN_WARNING "%s: I/O MMU @ %p is"
"out of mapping resources, %u %u %lx\n",
__func__, ioc->ioc_hpa, ioc->res_size,
pages_needed, dma_get_seg_boundary(dev));
return -1;
#endif
}
}
#ifdef PDIR_SEARCH_TIMING
ioc->avg_search[ioc->avg_idx++] = (ia64_get_itc() - itc_start) / pages_needed;
ioc->avg_idx &= SBA_SEARCH_SAMPLE - 1;
#endif
prefetchw(&(ioc->pdir_base[pide]));
#ifdef ASSERT_PDIR_SANITY
/* verify the first enable bit is clear */
if(0x00 != ((u8 *) ioc->pdir_base)[pide*PDIR_ENTRY_SIZE + 7]) {
sba_dump_pdir_entry(ioc, "sba_search_bitmap() botched it?", pide);
}
#endif
DBG_RES("%s(%x) %d -> %lx hint %x/%x\n",
__func__, size, pages_needed, pide,
(uint) ((unsigned long) ioc->res_hint - (unsigned long) ioc->res_map),
ioc->res_bitshift );
return (pide);
}
/**
* sba_free_range - unmark bits in IO PDIR resource bitmap
* @ioc: IO MMU structure which owns the pdir we are interested in.
* @iova: IO virtual address which was previously allocated.
* @size: number of bytes to create a mapping for
*
* clear bits in the ioc's resource map
*/
static SBA_INLINE void
sba_free_range(struct ioc *ioc, dma_addr_t iova, size_t size)
{
unsigned long iovp = SBA_IOVP(ioc, iova);
unsigned int pide = PDIR_INDEX(iovp);
unsigned int ridx = pide >> 3; /* convert bit to byte address */
unsigned long *res_ptr = (unsigned long *) &((ioc)->res_map[ridx & ~RESMAP_IDX_MASK]);
int bits_not_wanted = size >> iovp_shift;
unsigned long m;
/* Round up to power-of-two size: see AR2305 note above */
bits_not_wanted = 1UL << get_iovp_order(bits_not_wanted << iovp_shift);
for (; bits_not_wanted > 0 ; res_ptr++) {
if (unlikely(bits_not_wanted > BITS_PER_LONG)) {
/* these mappings start 64bit aligned */
*res_ptr = 0UL;
bits_not_wanted -= BITS_PER_LONG;
pide += BITS_PER_LONG;
} else {
/* 3-bits "bit" address plus 2 (or 3) bits for "byte" == bit in word */
m = RESMAP_MASK(bits_not_wanted) << (pide & (BITS_PER_LONG - 1));
bits_not_wanted = 0;
DBG_RES("%s( ,%x,%x) %x/%lx %x %p %lx\n", __func__, (uint) iova, size,
bits_not_wanted, m, pide, res_ptr, *res_ptr);
ASSERT(m != 0);
ASSERT(bits_not_wanted);
ASSERT((*res_ptr & m) == m); /* verify same bits are set */
*res_ptr &= ~m;
}
}
}
/**************************************************************
*
* "Dynamic DMA Mapping" support (aka "Coherent I/O")
*
***************************************************************/
/**
* sba_io_pdir_entry - fill in one IO PDIR entry
* @pdir_ptr: pointer to IO PDIR entry
* @vba: Virtual CPU address of buffer to map
*
* SBA Mapping Routine
*
* Given a virtual address (vba, arg1) sba_io_pdir_entry()
* loads the I/O PDIR entry pointed to by pdir_ptr (arg0).
* Each IO Pdir entry consists of 8 bytes as shown below
* (LSB == bit 0):
*
* 63 40 11 7 0
* +-+---------------------+----------------------------------+----+--------+
* |V| U | PPN[39:12] | U | FF |
* +-+---------------------+----------------------------------+----+--------+
*
* V == Valid Bit
* U == Unused
* PPN == Physical Page Number
*
* The physical address fields are filled with the results of virt_to_phys()
* on the vba.
*/
#if 1
#define sba_io_pdir_entry(pdir_ptr, vba) *pdir_ptr = ((vba & ~0xE000000000000FFFULL) \
| 0x8000000000000000ULL)
#else
void SBA_INLINE
sba_io_pdir_entry(u64 *pdir_ptr, unsigned long vba)
{
*pdir_ptr = ((vba & ~0xE000000000000FFFULL) | 0x80000000000000FFULL);
}
#endif
#ifdef ENABLE_MARK_CLEAN
/**
* Since DMA is i-cache coherent, any (complete) pages that were written via
* DMA can be marked as "clean" so that lazy_mmu_prot_update() doesn't have to
* flush them when they get mapped into an executable vm-area.
*/
static void
mark_clean (void *addr, size_t size)
{
unsigned long pg_addr, end;
pg_addr = PAGE_ALIGN((unsigned long) addr);
end = (unsigned long) addr + size;
while (pg_addr + PAGE_SIZE <= end) {
struct page *page = virt_to_page((void *)pg_addr);
set_bit(PG_arch_1, &page->flags);
pg_addr += PAGE_SIZE;
}
}
#endif
/**
* sba_mark_invalid - invalidate one or more IO PDIR entries
* @ioc: IO MMU structure which owns the pdir we are interested in.
* @iova: IO Virtual Address mapped earlier
* @byte_cnt: number of bytes this mapping covers.
*
* Marking the IO PDIR entry(ies) as Invalid and invalidate
* corresponding IO TLB entry. The PCOM (Purge Command Register)
* is to purge stale entries in the IO TLB when unmapping entries.
*
* The PCOM register supports purging of multiple pages, with a minium
* of 1 page and a maximum of 2GB. Hardware requires the address be
* aligned to the size of the range being purged. The size of the range
* must be a power of 2. The "Cool perf optimization" in the
* allocation routine helps keep that true.
*/
static SBA_INLINE void
sba_mark_invalid(struct ioc *ioc, dma_addr_t iova, size_t byte_cnt)
{
u32 iovp = (u32) SBA_IOVP(ioc,iova);
int off = PDIR_INDEX(iovp);
/* Must be non-zero and rounded up */
ASSERT(byte_cnt > 0);
ASSERT(0 == (byte_cnt & ~iovp_mask));
#ifdef ASSERT_PDIR_SANITY
/* Assert first pdir entry is set */
if (!(ioc->pdir_base[off] >> 60)) {
sba_dump_pdir_entry(ioc,"sba_mark_invalid()", PDIR_INDEX(iovp));
}
#endif
if (byte_cnt <= iovp_size)
{
ASSERT(off < ioc->pdir_size);
iovp |= iovp_shift; /* set "size" field for PCOM */
#ifndef FULL_VALID_PDIR
/*
** clear I/O PDIR entry "valid" bit
** Do NOT clear the rest - save it for debugging.
** We should only clear bits that have previously
** been enabled.
*/
ioc->pdir_base[off] &= ~(0x80000000000000FFULL);
#else
/*
** If we want to maintain the PDIR as valid, put in
** the spill page so devices prefetching won't
** cause a hard fail.
*/
ioc->pdir_base[off] = (0x80000000000000FFULL | prefetch_spill_page);
#endif
} else {
u32 t = get_iovp_order(byte_cnt) + iovp_shift;
iovp |= t;
ASSERT(t <= 31); /* 2GB! Max value of "size" field */
do {
/* verify this pdir entry is enabled */
ASSERT(ioc->pdir_base[off] >> 63);
#ifndef FULL_VALID_PDIR
/* clear I/O Pdir entry "valid" bit first */
ioc->pdir_base[off] &= ~(0x80000000000000FFULL);
#else
ioc->pdir_base[off] = (0x80000000000000FFULL | prefetch_spill_page);
#endif
off++;
byte_cnt -= iovp_size;
} while (byte_cnt > 0);
}
WRITE_REG(iovp | ioc->ibase, ioc->ioc_hpa+IOC_PCOM);
}
/**
* sba_map_single_attrs - map one buffer and return IOVA for DMA
* @dev: instance of PCI owned by the driver that's asking.
* @addr: driver buffer to map.
* @size: number of bytes to map in driver buffer.
* @dir: R/W or both.
* @attrs: optional dma attributes
*
* See Documentation/DMA-API-HOWTO.txt
*/
static dma_addr_t sba_map_page(struct device *dev, struct page *page,
unsigned long poff, size_t size,
enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct ioc *ioc;
void *addr = page_address(page) + poff;
dma_addr_t iovp;
dma_addr_t offset;
u64 *pdir_start;
int pide;
#ifdef ASSERT_PDIR_SANITY
unsigned long flags;
#endif
#ifdef ALLOW_IOV_BYPASS
unsigned long pci_addr = virt_to_phys(addr);
#endif
#ifdef ALLOW_IOV_BYPASS
ASSERT(to_pci_dev(dev)->dma_mask);
/*
** Check if the PCI device can DMA to ptr... if so, just return ptr
*/
if (likely((pci_addr & ~to_pci_dev(dev)->dma_mask) == 0)) {
/*
** Device is bit capable of DMA'ing to the buffer...
** just return the PCI address of ptr
*/
DBG_BYPASS("sba_map_single_attrs() bypass mask/addr: "
"0x%lx/0x%lx\n",
to_pci_dev(dev)->dma_mask, pci_addr);
return pci_addr;
}
#endif
ioc = GET_IOC(dev);
ASSERT(ioc);
prefetch(ioc->res_hint);
ASSERT(size > 0);
ASSERT(size <= DMA_CHUNK_SIZE);
/* save offset bits */
offset = ((dma_addr_t) (long) addr) & ~iovp_mask;
/* round up to nearest iovp_size */
size = (size + offset + ~iovp_mask) & iovp_mask;
#ifdef ASSERT_PDIR_SANITY
spin_lock_irqsave(&ioc->res_lock, flags);
if (sba_check_pdir(ioc,"Check before sba_map_single_attrs()"))
panic("Sanity check failed");
spin_unlock_irqrestore(&ioc->res_lock, flags);
#endif
pide = sba_alloc_range(ioc, dev, size);
if (pide < 0)
return 0;
iovp = (dma_addr_t) pide << iovp_shift;
DBG_RUN("%s() 0x%p -> 0x%lx\n", __func__, addr, (long) iovp | offset);
pdir_start = &(ioc->pdir_base[pide]);
while (size > 0) {
ASSERT(((u8 *)pdir_start)[7] == 0); /* verify availability */
sba_io_pdir_entry(pdir_start, (unsigned long) addr);
DBG_RUN(" pdir 0x%p %lx\n", pdir_start, *pdir_start);
addr += iovp_size;
size -= iovp_size;
pdir_start++;
}
/* force pdir update */
wmb();
/* form complete address */
#ifdef ASSERT_PDIR_SANITY
spin_lock_irqsave(&ioc->res_lock, flags);
sba_check_pdir(ioc,"Check after sba_map_single_attrs()");
spin_unlock_irqrestore(&ioc->res_lock, flags);
#endif
return SBA_IOVA(ioc, iovp, offset);
}
static dma_addr_t sba_map_single_attrs(struct device *dev, void *addr,
size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
return sba_map_page(dev, virt_to_page(addr),
(unsigned long)addr & ~PAGE_MASK, size, dir, attrs);
}
#ifdef ENABLE_MARK_CLEAN
static SBA_INLINE void
sba_mark_clean(struct ioc *ioc, dma_addr_t iova, size_t size)
{
u32 iovp = (u32) SBA_IOVP(ioc,iova);
int off = PDIR_INDEX(iovp);
void *addr;
if (size <= iovp_size) {
addr = phys_to_virt(ioc->pdir_base[off] &
~0xE000000000000FFFULL);
mark_clean(addr, size);
} else {
do {
addr = phys_to_virt(ioc->pdir_base[off] &
~0xE000000000000FFFULL);
mark_clean(addr, min(size, iovp_size));
off++;
size -= iovp_size;
} while (size > 0);
}
}
#endif
/**
* sba_unmap_single_attrs - unmap one IOVA and free resources
* @dev: instance of PCI owned by the driver that's asking.
* @iova: IOVA of driver buffer previously mapped.
* @size: number of bytes mapped in driver buffer.
* @dir: R/W or both.
* @attrs: optional dma attributes
*
* See Documentation/DMA-API-HOWTO.txt
*/
static void sba_unmap_page(struct device *dev, dma_addr_t iova, size_t size,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct ioc *ioc;
#if DELAYED_RESOURCE_CNT > 0
struct sba_dma_pair *d;
#endif
unsigned long flags;
dma_addr_t offset;
ioc = GET_IOC(dev);
ASSERT(ioc);
#ifdef ALLOW_IOV_BYPASS
if (likely((iova & ioc->imask) != ioc->ibase)) {
/*
** Address does not fall w/in IOVA, must be bypassing
*/
DBG_BYPASS("sba_unmap_single_attrs() bypass addr: 0x%lx\n",
iova);
#ifdef ENABLE_MARK_CLEAN
if (dir == DMA_FROM_DEVICE) {
mark_clean(phys_to_virt(iova), size);
}
#endif
return;
}
#endif
offset = iova & ~iovp_mask;
DBG_RUN("%s() iovp 0x%lx/%x\n", __func__, (long) iova, size);
iova ^= offset; /* clear offset bits */
size += offset;
size = ROUNDUP(size, iovp_size);
#ifdef ENABLE_MARK_CLEAN
if (dir == DMA_FROM_DEVICE)
sba_mark_clean(ioc, iova, size);
#endif
#if DELAYED_RESOURCE_CNT > 0
spin_lock_irqsave(&ioc->saved_lock, flags);
d = &(ioc->saved[ioc->saved_cnt]);
d->iova = iova;
d->size = size;
if (unlikely(++(ioc->saved_cnt) >= DELAYED_RESOURCE_CNT)) {
int cnt = ioc->saved_cnt;
spin_lock(&ioc->res_lock);
while (cnt--) {
sba_mark_invalid(ioc, d->iova, d->size);
sba_free_range(ioc, d->iova, d->size);
d--;
}
ioc->saved_cnt = 0;
READ_REG(ioc->ioc_hpa+IOC_PCOM); /* flush purges */
spin_unlock(&ioc->res_lock);
}
spin_unlock_irqrestore(&ioc->saved_lock, flags);
#else /* DELAYED_RESOURCE_CNT == 0 */
spin_lock_irqsave(&ioc->res_lock, flags);
sba_mark_invalid(ioc, iova, size);
sba_free_range(ioc, iova, size);
READ_REG(ioc->ioc_hpa+IOC_PCOM); /* flush purges */
spin_unlock_irqrestore(&ioc->res_lock, flags);
#endif /* DELAYED_RESOURCE_CNT == 0 */
}
void sba_unmap_single_attrs(struct device *dev, dma_addr_t iova, size_t size,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
sba_unmap_page(dev, iova, size, dir, attrs);
}
/**
* sba_alloc_coherent - allocate/map shared mem for DMA
* @dev: instance of PCI owned by the driver that's asking.
* @size: number of bytes mapped in driver buffer.
* @dma_handle: IOVA of new buffer.
*
* See Documentation/DMA-API-HOWTO.txt
*/
static void *
sba_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_handle,
gfp_t flags, struct dma_attrs *attrs)
{
struct ioc *ioc;
void *addr;
ioc = GET_IOC(dev);
ASSERT(ioc);
#ifdef CONFIG_NUMA
{
struct page *page;
page = alloc_pages_exact_node(ioc->node == MAX_NUMNODES ?
numa_node_id() : ioc->node, flags,
get_order(size));
if (unlikely(!page))
return NULL;
addr = page_address(page);
}
#else
addr = (void *) __get_free_pages(flags, get_order(size));
#endif
if (unlikely(!addr))
return NULL;
memset(addr, 0, size);
*dma_handle = virt_to_phys(addr);
#ifdef ALLOW_IOV_BYPASS
ASSERT(dev->coherent_dma_mask);
/*
** Check if the PCI device can DMA to ptr... if so, just return ptr
*/
if (likely((*dma_handle & ~dev->coherent_dma_mask) == 0)) {
DBG_BYPASS("sba_alloc_coherent() bypass mask/addr: 0x%lx/0x%lx\n",
dev->coherent_dma_mask, *dma_handle);
return addr;
}
#endif
/*
* If device can't bypass or bypass is disabled, pass the 32bit fake
* device to map single to get an iova mapping.
*/
*dma_handle = sba_map_single_attrs(&ioc->sac_only_dev->dev, addr,
size, 0, NULL);
return addr;
}
/**
* sba_free_coherent - free/unmap shared mem for DMA
* @dev: instance of PCI owned by the driver that's asking.
* @size: number of bytes mapped in driver buffer.
* @vaddr: virtual address IOVA of "consistent" buffer.
* @dma_handler: IO virtual address of "consistent" buffer.
*
* See Documentation/DMA-API-HOWTO.txt
*/
static void sba_free_coherent(struct device *dev, size_t size, void *vaddr,
dma_addr_t dma_handle, struct dma_attrs *attrs)
{
sba_unmap_single_attrs(dev, dma_handle, size, 0, NULL);
free_pages((unsigned long) vaddr, get_order(size));
}
/*
** Since 0 is a valid pdir_base index value, can't use that
** to determine if a value is valid or not. Use a flag to indicate
** the SG list entry contains a valid pdir index.
*/
#define PIDE_FLAG 0x1UL
#ifdef DEBUG_LARGE_SG_ENTRIES
int dump_run_sg = 0;
#endif
/**
* sba_fill_pdir - write allocated SG entries into IO PDIR
* @ioc: IO MMU structure which owns the pdir we are interested in.
* @startsg: list of IOVA/size pairs
* @nents: number of entries in startsg list
*
* Take preprocessed SG list and write corresponding entries
* in the IO PDIR.
*/
static SBA_INLINE int
sba_fill_pdir(
struct ioc *ioc,
struct scatterlist *startsg,
int nents)
{
struct scatterlist *dma_sg = startsg; /* pointer to current DMA */
int n_mappings = 0;
u64 *pdirp = NULL;
unsigned long dma_offset = 0;
while (nents-- > 0) {
int cnt = startsg->dma_length;
startsg->dma_length = 0;
#ifdef DEBUG_LARGE_SG_ENTRIES
if (dump_run_sg)
printk(" %2d : %08lx/%05x %p\n",
nents, startsg->dma_address, cnt,
sba_sg_address(startsg));
#else
DBG_RUN_SG(" %d : %08lx/%05x %p\n",
nents, startsg->dma_address, cnt,
sba_sg_address(startsg));
#endif
/*
** Look for the start of a new DMA stream
*/
if (startsg->dma_address & PIDE_FLAG) {
u32 pide = startsg->dma_address & ~PIDE_FLAG;
dma_offset = (unsigned long) pide & ~iovp_mask;
startsg->dma_address = 0;
if (n_mappings)
dma_sg = sg_next(dma_sg);
dma_sg->dma_address = pide | ioc->ibase;
pdirp = &(ioc->pdir_base[pide >> iovp_shift]);
n_mappings++;
}
/*
** Look for a VCONTIG chunk
*/
if (cnt) {
unsigned long vaddr = (unsigned long) sba_sg_address(startsg);
ASSERT(pdirp);
/* Since multiple Vcontig blocks could make up
** one DMA stream, *add* cnt to dma_len.
*/
dma_sg->dma_length += cnt;
cnt += dma_offset;
dma_offset=0; /* only want offset on first chunk */
cnt = ROUNDUP(cnt, iovp_size);
do {
sba_io_pdir_entry(pdirp, vaddr);
vaddr += iovp_size;
cnt -= iovp_size;
pdirp++;
} while (cnt > 0);
}
startsg = sg_next(startsg);
}
/* force pdir update */
wmb();
#ifdef DEBUG_LARGE_SG_ENTRIES
dump_run_sg = 0;
#endif
return(n_mappings);
}
/*
** Two address ranges are DMA contiguous *iff* "end of prev" and
** "start of next" are both on an IOV page boundary.
**
** (shift left is a quick trick to mask off upper bits)
*/
#define DMA_CONTIG(__X, __Y) \
(((((unsigned long) __X) | ((unsigned long) __Y)) << (BITS_PER_LONG - iovp_shift)) == 0UL)
/**
* sba_coalesce_chunks - preprocess the SG list
* @ioc: IO MMU structure which owns the pdir we are interested in.
* @startsg: list of IOVA/size pairs
* @nents: number of entries in startsg list
*
* First pass is to walk the SG list and determine where the breaks are
* in the DMA stream. Allocates PDIR entries but does not fill them.
* Returns the number of DMA chunks.
*
* Doing the fill separate from the coalescing/allocation keeps the
* code simpler. Future enhancement could make one pass through
* the sglist do both.
*/
static SBA_INLINE int
sba_coalesce_chunks(struct ioc *ioc, struct device *dev,
struct scatterlist *startsg,
int nents)
{
struct scatterlist *vcontig_sg; /* VCONTIG chunk head */
unsigned long vcontig_len; /* len of VCONTIG chunk */
unsigned long vcontig_end;
struct scatterlist *dma_sg; /* next DMA stream head */
unsigned long dma_offset, dma_len; /* start/len of DMA stream */
int n_mappings = 0;
unsigned int max_seg_size = dma_get_max_seg_size(dev);
int idx;
while (nents > 0) {
unsigned long vaddr = (unsigned long) sba_sg_address(startsg);
/*
** Prepare for first/next DMA stream
*/
dma_sg = vcontig_sg = startsg;
dma_len = vcontig_len = vcontig_end = startsg->length;
vcontig_end += vaddr;
dma_offset = vaddr & ~iovp_mask;
/* PARANOID: clear entries */
startsg->dma_address = startsg->dma_length = 0;
/*
** This loop terminates one iteration "early" since
** it's always looking one "ahead".
*/
while (--nents > 0) {
unsigned long vaddr; /* tmp */
startsg = sg_next(startsg);
/* PARANOID */
startsg->dma_address = startsg->dma_length = 0;
/* catch brokenness in SCSI layer */
ASSERT(startsg->length <= DMA_CHUNK_SIZE);
/*
** First make sure current dma stream won't
** exceed DMA_CHUNK_SIZE if we coalesce the
** next entry.
*/
if (((dma_len + dma_offset + startsg->length + ~iovp_mask) & iovp_mask)
> DMA_CHUNK_SIZE)
break;
if (dma_len + startsg->length > max_seg_size)
break;
/*
** Then look for virtually contiguous blocks.
**
** append the next transaction?
*/
vaddr = (unsigned long) sba_sg_address(startsg);
if (vcontig_end == vaddr)
{
vcontig_len += startsg->length;
vcontig_end += startsg->length;
dma_len += startsg->length;
continue;
}
#ifdef DEBUG_LARGE_SG_ENTRIES
dump_run_sg = (vcontig_len > iovp_size);
#endif
/*
** Not virtually contiguous.
** Terminate prev chunk.
** Start a new chunk.
**
** Once we start a new VCONTIG chunk, dma_offset
** can't change. And we need the offset from the first
** chunk - not the last one. Ergo Successive chunks
** must start on page boundaries and dove tail
** with it's predecessor.
*/
vcontig_sg->dma_length = vcontig_len;
vcontig_sg = startsg;
vcontig_len = startsg->length;
/*
** 3) do the entries end/start on page boundaries?
** Don't update vcontig_end until we've checked.
*/
if (DMA_CONTIG(vcontig_end, vaddr))
{
vcontig_end = vcontig_len + vaddr;
dma_len += vcontig_len;
continue;
} else {
break;
}
}
/*
** End of DMA Stream
** Terminate last VCONTIG block.
** Allocate space for DMA stream.
*/
vcontig_sg->dma_length = vcontig_len;
dma_len = (dma_len + dma_offset + ~iovp_mask) & iovp_mask;
ASSERT(dma_len <= DMA_CHUNK_SIZE);
idx = sba_alloc_range(ioc, dev, dma_len);
if (idx < 0) {
dma_sg->dma_length = 0;
return -1;
}
dma_sg->dma_address = (dma_addr_t)(PIDE_FLAG | (idx << iovp_shift)
| dma_offset);
n_mappings++;
}
return n_mappings;
}
static void sba_unmap_sg_attrs(struct device *dev, struct scatterlist *sglist,
int nents, enum dma_data_direction dir,
struct dma_attrs *attrs);
/**
* sba_map_sg - map Scatter/Gather list
* @dev: instance of PCI owned by the driver that's asking.
* @sglist: array of buffer/length pairs
* @nents: number of entries in list
* @dir: R/W or both.
* @attrs: optional dma attributes
*
* See Documentation/DMA-API-HOWTO.txt
*/
static int sba_map_sg_attrs(struct device *dev, struct scatterlist *sglist,
int nents, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct ioc *ioc;
int coalesced, filled = 0;
#ifdef ASSERT_PDIR_SANITY
unsigned long flags;
#endif
#ifdef ALLOW_IOV_BYPASS_SG
struct scatterlist *sg;
#endif
DBG_RUN_SG("%s() START %d entries\n", __func__, nents);
ioc = GET_IOC(dev);
ASSERT(ioc);
#ifdef ALLOW_IOV_BYPASS_SG
ASSERT(to_pci_dev(dev)->dma_mask);
if (likely((ioc->dma_mask & ~to_pci_dev(dev)->dma_mask) == 0)) {
for_each_sg(sglist, sg, nents, filled) {
sg->dma_length = sg->length;
sg->dma_address = virt_to_phys(sba_sg_address(sg));
}
return filled;
}
#endif
/* Fast path single entry scatterlists. */
if (nents == 1) {
sglist->dma_length = sglist->length;
sglist->dma_address = sba_map_single_attrs(dev, sba_sg_address(sglist), sglist->length, dir, attrs);
return 1;
}
#ifdef ASSERT_PDIR_SANITY
spin_lock_irqsave(&ioc->res_lock, flags);
if (sba_check_pdir(ioc,"Check before sba_map_sg_attrs()"))
{
sba_dump_sg(ioc, sglist, nents);
panic("Check before sba_map_sg_attrs()");
}
spin_unlock_irqrestore(&ioc->res_lock, flags);
#endif
prefetch(ioc->res_hint);
/*
** First coalesce the chunks and allocate I/O pdir space
**
** If this is one DMA stream, we can properly map using the
** correct virtual address associated with each DMA page.
** w/o this association, we wouldn't have coherent DMA!
** Access to the virtual address is what forces a two pass algorithm.
*/
coalesced = sba_coalesce_chunks(ioc, dev, sglist, nents);
if (coalesced < 0) {
sba_unmap_sg_attrs(dev, sglist, nents, dir, attrs);
return 0;
}
/*
** Program the I/O Pdir
**
** map the virtual addresses to the I/O Pdir
** o dma_address will contain the pdir index
** o dma_len will contain the number of bytes to map
** o address contains the virtual address.
*/
filled = sba_fill_pdir(ioc, sglist, nents);
#ifdef ASSERT_PDIR_SANITY
spin_lock_irqsave(&ioc->res_lock, flags);
if (sba_check_pdir(ioc,"Check after sba_map_sg_attrs()"))
{
sba_dump_sg(ioc, sglist, nents);
panic("Check after sba_map_sg_attrs()\n");
}
spin_unlock_irqrestore(&ioc->res_lock, flags);
#endif
ASSERT(coalesced == filled);
DBG_RUN_SG("%s() DONE %d mappings\n", __func__, filled);
return filled;
}
/**
* sba_unmap_sg_attrs - unmap Scatter/Gather list
* @dev: instance of PCI owned by the driver that's asking.
* @sglist: array of buffer/length pairs
* @nents: number of entries in list
* @dir: R/W or both.
* @attrs: optional dma attributes
*
* See Documentation/DMA-API-HOWTO.txt
*/
static void sba_unmap_sg_attrs(struct device *dev, struct scatterlist *sglist,
int nents, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
#ifdef ASSERT_PDIR_SANITY
struct ioc *ioc;
unsigned long flags;
#endif
DBG_RUN_SG("%s() START %d entries, %p,%x\n",
__func__, nents, sba_sg_address(sglist), sglist->length);
#ifdef ASSERT_PDIR_SANITY
ioc = GET_IOC(dev);
ASSERT(ioc);
spin_lock_irqsave(&ioc->res_lock, flags);
sba_check_pdir(ioc,"Check before sba_unmap_sg_attrs()");
spin_unlock_irqrestore(&ioc->res_lock, flags);
#endif
while (nents && sglist->dma_length) {
sba_unmap_single_attrs(dev, sglist->dma_address,
sglist->dma_length, dir, attrs);
sglist = sg_next(sglist);
nents--;
}
DBG_RUN_SG("%s() DONE (nents %d)\n", __func__, nents);
#ifdef ASSERT_PDIR_SANITY
spin_lock_irqsave(&ioc->res_lock, flags);
sba_check_pdir(ioc,"Check after sba_unmap_sg_attrs()");
spin_unlock_irqrestore(&ioc->res_lock, flags);
#endif
}
/**************************************************************
*
* Initialization and claim
*
***************************************************************/
static void __init
ioc_iova_init(struct ioc *ioc)
{
int tcnfg;
int agp_found = 0;
struct pci_dev *device = NULL;
#ifdef FULL_VALID_PDIR
unsigned long index;
#endif
/*
** Firmware programs the base and size of a "safe IOVA space"
** (one that doesn't overlap memory or LMMIO space) in the
** IBASE and IMASK registers.
*/
ioc->ibase = READ_REG(ioc->ioc_hpa + IOC_IBASE) & ~0x1UL;
ioc->imask = READ_REG(ioc->ioc_hpa + IOC_IMASK) | 0xFFFFFFFF00000000UL;
ioc->iov_size = ~ioc->imask + 1;
DBG_INIT("%s() hpa %p IOV base 0x%lx mask 0x%lx (%dMB)\n",
__func__, ioc->ioc_hpa, ioc->ibase, ioc->imask,
ioc->iov_size >> 20);
switch (iovp_size) {
case 4*1024: tcnfg = 0; break;
case 8*1024: tcnfg = 1; break;
case 16*1024: tcnfg = 2; break;
case 64*1024: tcnfg = 3; break;
default:
panic(PFX "Unsupported IOTLB page size %ldK",
iovp_size >> 10);
break;
}
WRITE_REG(tcnfg, ioc->ioc_hpa + IOC_TCNFG);
ioc->pdir_size = (ioc->iov_size / iovp_size) * PDIR_ENTRY_SIZE;
ioc->pdir_base = (void *) __get_free_pages(GFP_KERNEL,
get_order(ioc->pdir_size));
if (!ioc->pdir_base)
panic(PFX "Couldn't allocate I/O Page Table\n");
memset(ioc->pdir_base, 0, ioc->pdir_size);
DBG_INIT("%s() IOV page size %ldK pdir %p size %x\n", __func__,
iovp_size >> 10, ioc->pdir_base, ioc->pdir_size);
ASSERT(ALIGN((unsigned long) ioc->pdir_base, 4*1024) == (unsigned long) ioc->pdir_base);
WRITE_REG(virt_to_phys(ioc->pdir_base), ioc->ioc_hpa + IOC_PDIR_BASE);
/*
** If an AGP device is present, only use half of the IOV space
** for PCI DMA. Unfortunately we can't know ahead of time
** whether GART support will actually be used, for now we
** can just key on an AGP device found in the system.
** We program the next pdir index after we stop w/ a key for
** the GART code to handshake on.
*/
for_each_pci_dev(device)
agp_found |= pci_find_capability(device, PCI_CAP_ID_AGP);
if (agp_found && reserve_sba_gart) {
printk(KERN_INFO PFX "reserving %dMb of IOVA space at 0x%lx for agpgart\n",
ioc->iov_size/2 >> 20, ioc->ibase + ioc->iov_size/2);
ioc->pdir_size /= 2;
((u64 *)ioc->pdir_base)[PDIR_INDEX(ioc->iov_size/2)] = ZX1_SBA_IOMMU_COOKIE;
}
#ifdef FULL_VALID_PDIR
/*
** Check to see if the spill page has been allocated, we don't need more than
** one across multiple SBAs.
*/
if (!prefetch_spill_page) {
char *spill_poison = "SBAIOMMU POISON";
int poison_size = 16;
void *poison_addr, *addr;
addr = (void *)__get_free_pages(GFP_KERNEL, get_order(iovp_size));
if (!addr)
panic(PFX "Couldn't allocate PDIR spill page\n");
poison_addr = addr;
for ( ; (u64) poison_addr < addr + iovp_size; poison_addr += poison_size)
memcpy(poison_addr, spill_poison, poison_size);
prefetch_spill_page = virt_to_phys(addr);
DBG_INIT("%s() prefetch spill addr: 0x%lx\n", __func__, prefetch_spill_page);
}
/*
** Set all the PDIR entries valid w/ the spill page as the target
*/
for (index = 0 ; index < (ioc->pdir_size / PDIR_ENTRY_SIZE) ; index++)
((u64 *)ioc->pdir_base)[index] = (0x80000000000000FF | prefetch_spill_page);
#endif
/* Clear I/O TLB of any possible entries */
WRITE_REG(ioc->ibase | (get_iovp_order(ioc->iov_size) + iovp_shift), ioc->ioc_hpa + IOC_PCOM);
READ_REG(ioc->ioc_hpa + IOC_PCOM);
/* Enable IOVA translation */
WRITE_REG(ioc->ibase | 1, ioc->ioc_hpa + IOC_IBASE);
READ_REG(ioc->ioc_hpa + IOC_IBASE);
}
static void __init
ioc_resource_init(struct ioc *ioc)
{
spin_lock_init(&ioc->res_lock);
#if DELAYED_RESOURCE_CNT > 0
spin_lock_init(&ioc->saved_lock);
#endif
/* resource map size dictated by pdir_size */
ioc->res_size = ioc->pdir_size / PDIR_ENTRY_SIZE; /* entries */
ioc->res_size >>= 3; /* convert bit count to byte count */
DBG_INIT("%s() res_size 0x%x\n", __func__, ioc->res_size);
ioc->res_map = (char *) __get_free_pages(GFP_KERNEL,
get_order(ioc->res_size));
if (!ioc->res_map)
panic(PFX "Couldn't allocate resource map\n");
memset(ioc->res_map, 0, ioc->res_size);
/* next available IOVP - circular search */
ioc->res_hint = (unsigned long *) ioc->res_map;
#ifdef ASSERT_PDIR_SANITY
/* Mark first bit busy - ie no IOVA 0 */
ioc->res_map[0] = 0x1;
ioc->pdir_base[0] = 0x8000000000000000ULL | ZX1_SBA_IOMMU_COOKIE;
#endif
#ifdef FULL_VALID_PDIR
/* Mark the last resource used so we don't prefetch beyond IOVA space */
ioc->res_map[ioc->res_size - 1] |= 0x80UL; /* res_map is chars */
ioc->pdir_base[(ioc->pdir_size / PDIR_ENTRY_SIZE) - 1] = (0x80000000000000FF
| prefetch_spill_page);
#endif
DBG_INIT("%s() res_map %x %p\n", __func__,
ioc->res_size, (void *) ioc->res_map);
}
static void __init
ioc_sac_init(struct ioc *ioc)
{
struct pci_dev *sac = NULL;
struct pci_controller *controller = NULL;
/*
* pci_alloc_coherent() must return a DMA address which is
* SAC (single address cycle) addressable, so allocate a
* pseudo-device to enforce that.
*/
sac = kzalloc(sizeof(*sac), GFP_KERNEL);
if (!sac)
panic(PFX "Couldn't allocate struct pci_dev");
controller = kzalloc(sizeof(*controller), GFP_KERNEL);
if (!controller)
panic(PFX "Couldn't allocate struct pci_controller");
controller->iommu = ioc;
sac->sysdata = controller;
sac->dma_mask = 0xFFFFFFFFUL;
#ifdef CONFIG_PCI
sac->dev.bus = &pci_bus_type;
#endif
ioc->sac_only_dev = sac;
}
static void __init
ioc_zx1_init(struct ioc *ioc)
{
unsigned long rope_config;
unsigned int i;
if (ioc->rev < 0x20)
panic(PFX "IOC 2.0 or later required for IOMMU support\n");
/* 38 bit memory controller + extra bit for range displaced by MMIO */
ioc->dma_mask = (0x1UL << 39) - 1;
/*
** Clear ROPE(N)_CONFIG AO bit.
** Disables "NT Ordering" (~= !"Relaxed Ordering")
** Overrides bit 1 in DMA Hint Sets.
** Improves netperf UDP_STREAM by ~10% for tg3 on bcm5701.
*/
for (i=0; i<(8*8); i+=8) {
rope_config = READ_REG(ioc->ioc_hpa + IOC_ROPE0_CFG + i);
rope_config &= ~IOC_ROPE_AO;
WRITE_REG(rope_config, ioc->ioc_hpa + IOC_ROPE0_CFG + i);
}
}
typedef void (initfunc)(struct ioc *);
struct ioc_iommu {
u32 func_id;
char *name;
initfunc *init;
};
static struct ioc_iommu ioc_iommu_info[] __initdata = {
{ ZX1_IOC_ID, "zx1", ioc_zx1_init },
{ ZX2_IOC_ID, "zx2", NULL },
{ SX1000_IOC_ID, "sx1000", NULL },
{ SX2000_IOC_ID, "sx2000", NULL },
};
static struct ioc * __init
ioc_init(unsigned long hpa, void *handle)
{
struct ioc *ioc;
struct ioc_iommu *info;
ioc = kzalloc(sizeof(*ioc), GFP_KERNEL);
if (!ioc)
return NULL;
ioc->next = ioc_list;
ioc_list = ioc;
ioc->handle = handle;
ioc->ioc_hpa = ioremap(hpa, 0x1000);
ioc->func_id = READ_REG(ioc->ioc_hpa + IOC_FUNC_ID);
ioc->rev = READ_REG(ioc->ioc_hpa + IOC_FCLASS) & 0xFFUL;
ioc->dma_mask = 0xFFFFFFFFFFFFFFFFUL; /* conservative */
for (info = ioc_iommu_info; info < ioc_iommu_info + ARRAY_SIZE(ioc_iommu_info); info++) {
if (ioc->func_id == info->func_id) {
ioc->name = info->name;
if (info->init)
(info->init)(ioc);
}
}
iovp_size = (1 << iovp_shift);
iovp_mask = ~(iovp_size - 1);
DBG_INIT("%s: PAGE_SIZE %ldK, iovp_size %ldK\n", __func__,
PAGE_SIZE >> 10, iovp_size >> 10);
if (!ioc->name) {
ioc->name = kmalloc(24, GFP_KERNEL);
if (ioc->name)
sprintf((char *) ioc->name, "Unknown (%04x:%04x)",
ioc->func_id & 0xFFFF, (ioc->func_id >> 16) & 0xFFFF);
else
ioc->name = "Unknown";
}
ioc_iova_init(ioc);
ioc_resource_init(ioc);
ioc_sac_init(ioc);
if ((long) ~iovp_mask > (long) ia64_max_iommu_merge_mask)
ia64_max_iommu_merge_mask = ~iovp_mask;
printk(KERN_INFO PFX
"%s %d.%d HPA 0x%lx IOVA space %dMb at 0x%lx\n",
ioc->name, (ioc->rev >> 4) & 0xF, ioc->rev & 0xF,
hpa, ioc->iov_size >> 20, ioc->ibase);
return ioc;
}
/**************************************************************************
**
** SBA initialization code (HW and SW)
**
** o identify SBA chip itself
** o FIXME: initialize DMA hints for reasonable defaults
**
**************************************************************************/
#ifdef CONFIG_PROC_FS
static void *
ioc_start(struct seq_file *s, loff_t *pos)
{
struct ioc *ioc;
loff_t n = *pos;
for (ioc = ioc_list; ioc; ioc = ioc->next)
if (!n--)
return ioc;
return NULL;
}
static void *
ioc_next(struct seq_file *s, void *v, loff_t *pos)
{
struct ioc *ioc = v;
++*pos;
return ioc->next;
}
static void
ioc_stop(struct seq_file *s, void *v)
{
}
static int
ioc_show(struct seq_file *s, void *v)
{
struct ioc *ioc = v;
unsigned long *res_ptr = (unsigned long *)ioc->res_map;
int i, used = 0;
seq_printf(s, "Hewlett Packard %s IOC rev %d.%d\n",
ioc->name, ((ioc->rev >> 4) & 0xF), (ioc->rev & 0xF));
#ifdef CONFIG_NUMA
if (ioc->node != MAX_NUMNODES)
seq_printf(s, "NUMA node : %d\n", ioc->node);
#endif
seq_printf(s, "IOVA size : %ld MB\n", ((ioc->pdir_size >> 3) * iovp_size)/(1024*1024));
seq_printf(s, "IOVA page size : %ld kb\n", iovp_size/1024);
for (i = 0; i < (ioc->res_size / sizeof(unsigned long)); ++i, ++res_ptr)
used += hweight64(*res_ptr);
seq_printf(s, "PDIR size : %d entries\n", ioc->pdir_size >> 3);
seq_printf(s, "PDIR used : %d entries\n", used);
#ifdef PDIR_SEARCH_TIMING
{
unsigned long i = 0, avg = 0, min, max;
min = max = ioc->avg_search[0];
for (i = 0; i < SBA_SEARCH_SAMPLE; i++) {
avg += ioc->avg_search[i];
if (ioc->avg_search[i] > max) max = ioc->avg_search[i];
if (ioc->avg_search[i] < min) min = ioc->avg_search[i];
}
avg /= SBA_SEARCH_SAMPLE;
seq_printf(s, "Bitmap search : %ld/%ld/%ld (min/avg/max CPU Cycles/IOVA page)\n",
min, avg, max);
}
#endif
#ifndef ALLOW_IOV_BYPASS
seq_printf(s, "IOVA bypass disabled\n");
#endif
return 0;
}
static const struct seq_operations ioc_seq_ops = {
.start = ioc_start,
.next = ioc_next,
.stop = ioc_stop,
.show = ioc_show
};
static int
ioc_open(struct inode *inode, struct file *file)
{
return seq_open(file, &ioc_seq_ops);
}
static const struct file_operations ioc_fops = {
.open = ioc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release
};
static void __init
ioc_proc_init(void)
{
struct proc_dir_entry *dir;
dir = proc_mkdir("bus/mckinley", NULL);
if (!dir)
return;
proc_create(ioc_list->name, 0, dir, &ioc_fops);
}
#endif
static void
sba_connect_bus(struct pci_bus *bus)
{
acpi_handle handle, parent;
acpi_status status;
struct ioc *ioc;
if (!PCI_CONTROLLER(bus))
panic(PFX "no sysdata on bus %d!\n", bus->number);
if (PCI_CONTROLLER(bus)->iommu)
return;
handle = PCI_CONTROLLER(bus)->acpi_handle;
if (!handle)
return;
/*
* The IOC scope encloses PCI root bridges in the ACPI
* namespace, so work our way out until we find an IOC we
* claimed previously.
*/
do {
for (ioc = ioc_list; ioc; ioc = ioc->next)
if (ioc->handle == handle) {
PCI_CONTROLLER(bus)->iommu = ioc;
return;
}
status = acpi_get_parent(handle, &parent);
handle = parent;
} while (ACPI_SUCCESS(status));
printk(KERN_WARNING "No IOC for PCI Bus %04x:%02x in ACPI\n", pci_domain_nr(bus), bus->number);
}
#ifdef CONFIG_NUMA
static void __init
sba_map_ioc_to_node(struct ioc *ioc, acpi_handle handle)
{
unsigned int node;
int pxm;
ioc->node = MAX_NUMNODES;
pxm = acpi_get_pxm(handle);
if (pxm < 0)
return;
node = pxm_to_node(pxm);
if (node >= MAX_NUMNODES || !node_online(node))
return;
ioc->node = node;
return;
}
#else
#define sba_map_ioc_to_node(ioc, handle)
#endif
static int __init
acpi_sba_ioc_add(struct acpi_device *device)
{
struct ioc *ioc;
acpi_status status;
u64 hpa, length;
struct acpi_device_info *adi;
status = hp_acpi_csr_space(device->handle, &hpa, &length);
if (ACPI_FAILURE(status))
return 1;
status = acpi_get_object_info(device->handle, &adi);
if (ACPI_FAILURE(status))
return 1;
/*
* For HWP0001, only SBA appears in ACPI namespace. It encloses the PCI
* root bridges, and its CSR space includes the IOC function.
*/
if (strncmp("HWP0001", adi->hardware_id.string, 7) == 0) {
hpa += ZX1_IOC_OFFSET;
/* zx1 based systems default to kernel page size iommu pages */
if (!iovp_shift)
iovp_shift = min(PAGE_SHIFT, 16);
}
kfree(adi);
/*
* default anything not caught above or specified on cmdline to 4k
* iommu page size
*/
if (!iovp_shift)
iovp_shift = 12;
ioc = ioc_init(hpa, device->handle);
if (!ioc)
return 1;
/* setup NUMA node association */
sba_map_ioc_to_node(ioc, device->handle);
return 0;
}
static const struct acpi_device_id hp_ioc_iommu_device_ids[] = {
{"HWP0001", 0},
{"HWP0004", 0},
{"", 0},
};
static struct acpi_driver acpi_sba_ioc_driver = {
.name = "IOC IOMMU Driver",
.ids = hp_ioc_iommu_device_ids,
.ops = {
.add = acpi_sba_ioc_add,
},
};
extern struct dma_map_ops swiotlb_dma_ops;
static int __init
sba_init(void)
{
if (!ia64_platform_is("hpzx1") && !ia64_platform_is("hpzx1_swiotlb"))
return 0;
#if defined(CONFIG_IA64_GENERIC)
/* If we are booting a kdump kernel, the sba_iommu will
* cause devices that were not shutdown properly to MCA
* as soon as they are turned back on. Our only option for
* a successful kdump kernel boot is to use the swiotlb.
*/
if (is_kdump_kernel()) {
dma_ops = &swiotlb_dma_ops;
if (swiotlb_late_init_with_default_size(64 * (1<<20)) != 0)
panic("Unable to initialize software I/O TLB:"
" Try machvec=dig boot option");
machvec_init("dig");
return 0;
}
#endif
acpi_bus_register_driver(&acpi_sba_ioc_driver);
if (!ioc_list) {
#ifdef CONFIG_IA64_GENERIC
/*
* If we didn't find something sba_iommu can claim, we
* need to setup the swiotlb and switch to the dig machvec.
*/
dma_ops = &swiotlb_dma_ops;
if (swiotlb_late_init_with_default_size(64 * (1<<20)) != 0)
panic("Unable to find SBA IOMMU or initialize "
"software I/O TLB: Try machvec=dig boot option");
machvec_init("dig");
#else
panic("Unable to find SBA IOMMU: Try a generic or DIG kernel");
#endif
return 0;
}
#if defined(CONFIG_IA64_GENERIC) || defined(CONFIG_IA64_HP_ZX1_SWIOTLB)
/*
* hpzx1_swiotlb needs to have a fairly small swiotlb bounce
* buffer setup to support devices with smaller DMA masks than
* sba_iommu can handle.
*/
if (ia64_platform_is("hpzx1_swiotlb")) {
extern void hwsw_init(void);
hwsw_init();
}
#endif
#ifdef CONFIG_PCI
{
struct pci_bus *b = NULL;
while ((b = pci_find_next_bus(b)) != NULL)
sba_connect_bus(b);
}
#endif
#ifdef CONFIG_PROC_FS
ioc_proc_init();
#endif
return 0;
}
subsys_initcall(sba_init); /* must be initialized after ACPI etc., but before any drivers... */
static int __init
nosbagart(char *str)
{
reserve_sba_gart = 0;
return 1;
}
static int sba_dma_supported (struct device *dev, u64 mask)
{
/* make sure it's at least 32bit capable */
return ((mask & 0xFFFFFFFFUL) == 0xFFFFFFFFUL);
}
static int sba_dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
{
return 0;
}
__setup("nosbagart", nosbagart);
static int __init
sba_page_override(char *str)
{
unsigned long page_size;
page_size = memparse(str, &str);
switch (page_size) {
case 4096:
case 8192:
case 16384:
case 65536:
iovp_shift = ffs(page_size) - 1;
break;
default:
printk("%s: unknown/unsupported iommu page size %ld\n",
__func__, page_size);
}
return 1;
}
__setup("sbapagesize=",sba_page_override);
struct dma_map_ops sba_dma_ops = {
.alloc = sba_alloc_coherent,
.free = sba_free_coherent,
.map_page = sba_map_page,
.unmap_page = sba_unmap_page,
.map_sg = sba_map_sg_attrs,
.unmap_sg = sba_unmap_sg_attrs,
.sync_single_for_cpu = machvec_dma_sync_single,
.sync_sg_for_cpu = machvec_dma_sync_sg,
.sync_single_for_device = machvec_dma_sync_single,
.sync_sg_for_device = machvec_dma_sync_sg,
.dma_supported = sba_dma_supported,
.mapping_error = sba_dma_mapping_error,
};
void sba_dma_init(void)
{
dma_ops = &sba_dma_ops;
}
| gpl-2.0 |
kallaballa/linux-sunxi | drivers/isdn/pcbit/callbacks.c | 9472 | 6852 | /*
* Callbacks for the FSM
*
* Copyright (C) 1996 Universidade de Lisboa
*
* Written by Pedro Roque Marques (roque@di.fc.ul.pt)
*
* This software may be used and distributed according to the terms of
* the GNU General Public License, incorporated herein by reference.
*/
/*
* Fix: 19981230 - Carlos Morgado <chbm@techie.com>
* Port of Nelson Escravana's <nelson.escravana@usa.net> fix to CalledPN
* NULL pointer dereference in cb_in_1 (originally fixed in 2.0)
*/
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/skbuff.h>
#include <asm/io.h>
#include <linux/isdnif.h>
#include "pcbit.h"
#include "layer2.h"
#include "edss1.h"
#include "callbacks.h"
#include "capi.h"
ushort last_ref_num = 1;
/*
* send_conn_req
*
*/
void cb_out_1(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *cbdata)
{
struct sk_buff *skb;
int len;
ushort refnum;
#ifdef DEBUG
printk(KERN_DEBUG "Called Party Number: %s\n",
cbdata->data.setup.CalledPN);
#endif
/*
* hdr - kmalloc in capi_conn_req
* - kfree when msg has been sent
*/
if ((len = capi_conn_req(cbdata->data.setup.CalledPN, &skb,
chan->proto)) < 0)
{
printk("capi_conn_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->callref = 0;
chan->layer2link = 0;
chan->snum = 0;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_CONN_REQ, refnum, skb, len);
}
/*
* rcv CONNECT
* will go into ACTIVE state
* send CONN_ACTIVE_RESP
* send Select protocol request
*/
void cb_out_2(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
isdn_ctrl ictl;
struct sk_buff *skb;
int len;
ushort refnum;
if ((len = capi_conn_active_resp(chan, &skb)) < 0)
{
printk("capi_conn_active_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_CONN_ACTV_RESP, refnum, skb, len);
ictl.command = ISDN_STAT_DCONN;
ictl.driver = dev->id;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
/* ACTIVE D-channel */
/* Select protocol */
if ((len = capi_select_proto_req(chan, &skb, 1 /*outgoing*/)) < 0) {
printk("capi_select_proto_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_SELP_REQ, refnum, skb, len);
}
/*
* Incoming call received
* inform user
*/
void cb_in_1(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *cbdata)
{
isdn_ctrl ictl;
unsigned short refnum;
struct sk_buff *skb;
int len;
ictl.command = ISDN_STAT_ICALL;
ictl.driver = dev->id;
ictl.arg = chan->id;
/*
* ictl.num >= strlen() + strlen() + 5
*/
if (cbdata->data.setup.CallingPN == NULL) {
printk(KERN_DEBUG "NULL CallingPN to phone; using 0\n");
strcpy(ictl.parm.setup.phone, "0");
}
else {
strcpy(ictl.parm.setup.phone, cbdata->data.setup.CallingPN);
}
if (cbdata->data.setup.CalledPN == NULL) {
printk(KERN_DEBUG "NULL CalledPN to eazmsn; using 0\n");
strcpy(ictl.parm.setup.eazmsn, "0");
}
else {
strcpy(ictl.parm.setup.eazmsn, cbdata->data.setup.CalledPN);
}
ictl.parm.setup.si1 = 7;
ictl.parm.setup.si2 = 0;
ictl.parm.setup.plan = 0;
ictl.parm.setup.screen = 0;
#ifdef DEBUG
printk(KERN_DEBUG "statstr: %s\n", ictl.num);
#endif
dev->dev_if->statcallb(&ictl);
if ((len = capi_conn_resp(chan, &skb)) < 0) {
printk(KERN_DEBUG "capi_conn_resp failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_CONN_RESP, refnum, skb, len);
}
/*
* user has replied
* open the channel
* send CONNECT message CONNECT_ACTIVE_REQ in CAPI
*/
void cb_in_2(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
unsigned short refnum;
struct sk_buff *skb;
int len;
if ((len = capi_conn_active_req(chan, &skb)) < 0) {
printk(KERN_DEBUG "capi_conn_active_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
printk(KERN_DEBUG "sending MSG_CONN_ACTV_REQ\n");
pcbit_l2_write(dev, MSG_CONN_ACTV_REQ, refnum, skb, len);
}
/*
* CONN_ACK arrived
* start b-proto selection
*
*/
void cb_in_3(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
unsigned short refnum;
struct sk_buff *skb;
int len;
if ((len = capi_select_proto_req(chan, &skb, 0 /*incoming*/)) < 0)
{
printk("capi_select_proto_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_SELP_REQ, refnum, skb, len);
}
/*
* Received disconnect ind on active state
* send disconnect resp
* send msg to user
*/
void cb_disc_1(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
struct sk_buff *skb;
int len;
ushort refnum;
isdn_ctrl ictl;
if ((len = capi_disc_resp(chan, &skb)) < 0) {
printk("capi_disc_resp failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_DISC_RESP, refnum, skb, len);
ictl.command = ISDN_STAT_BHUP;
ictl.driver = dev->id;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
}
/*
* User HANGUP on active/call proceeding state
* send disc.req
*/
void cb_disc_2(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
struct sk_buff *skb;
int len;
ushort refnum;
if ((len = capi_disc_req(chan->callref, &skb, CAUSE_NORMAL)) < 0)
{
printk("capi_disc_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_DISC_REQ, refnum, skb, len);
}
/*
* Disc confirm received send BHUP
* Problem: when the HL driver sends the disc req itself
* LL receives BHUP
*/
void cb_disc_3(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
isdn_ctrl ictl;
ictl.command = ISDN_STAT_BHUP;
ictl.driver = dev->id;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
}
void cb_notdone(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
}
/*
* send activate b-chan protocol
*/
void cb_selp_1(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
struct sk_buff *skb;
int len;
ushort refnum;
if ((len = capi_activate_transp_req(chan, &skb)) < 0)
{
printk("capi_conn_activate_transp_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_ACT_TRANSP_REQ, refnum, skb, len);
}
/*
* Inform User that the B-channel is available
*/
void cb_open(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
isdn_ctrl ictl;
ictl.command = ISDN_STAT_BCONN;
ictl.driver = dev->id;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
}
| gpl-2.0 |
LiquidSmooth-Devices/kernel_oneplus_msm8974 | drivers/isdn/pcbit/callbacks.c | 9472 | 6852 | /*
* Callbacks for the FSM
*
* Copyright (C) 1996 Universidade de Lisboa
*
* Written by Pedro Roque Marques (roque@di.fc.ul.pt)
*
* This software may be used and distributed according to the terms of
* the GNU General Public License, incorporated herein by reference.
*/
/*
* Fix: 19981230 - Carlos Morgado <chbm@techie.com>
* Port of Nelson Escravana's <nelson.escravana@usa.net> fix to CalledPN
* NULL pointer dereference in cb_in_1 (originally fixed in 2.0)
*/
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/skbuff.h>
#include <asm/io.h>
#include <linux/isdnif.h>
#include "pcbit.h"
#include "layer2.h"
#include "edss1.h"
#include "callbacks.h"
#include "capi.h"
ushort last_ref_num = 1;
/*
* send_conn_req
*
*/
void cb_out_1(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *cbdata)
{
struct sk_buff *skb;
int len;
ushort refnum;
#ifdef DEBUG
printk(KERN_DEBUG "Called Party Number: %s\n",
cbdata->data.setup.CalledPN);
#endif
/*
* hdr - kmalloc in capi_conn_req
* - kfree when msg has been sent
*/
if ((len = capi_conn_req(cbdata->data.setup.CalledPN, &skb,
chan->proto)) < 0)
{
printk("capi_conn_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->callref = 0;
chan->layer2link = 0;
chan->snum = 0;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_CONN_REQ, refnum, skb, len);
}
/*
* rcv CONNECT
* will go into ACTIVE state
* send CONN_ACTIVE_RESP
* send Select protocol request
*/
void cb_out_2(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
isdn_ctrl ictl;
struct sk_buff *skb;
int len;
ushort refnum;
if ((len = capi_conn_active_resp(chan, &skb)) < 0)
{
printk("capi_conn_active_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_CONN_ACTV_RESP, refnum, skb, len);
ictl.command = ISDN_STAT_DCONN;
ictl.driver = dev->id;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
/* ACTIVE D-channel */
/* Select protocol */
if ((len = capi_select_proto_req(chan, &skb, 1 /*outgoing*/)) < 0) {
printk("capi_select_proto_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_SELP_REQ, refnum, skb, len);
}
/*
* Incoming call received
* inform user
*/
void cb_in_1(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *cbdata)
{
isdn_ctrl ictl;
unsigned short refnum;
struct sk_buff *skb;
int len;
ictl.command = ISDN_STAT_ICALL;
ictl.driver = dev->id;
ictl.arg = chan->id;
/*
* ictl.num >= strlen() + strlen() + 5
*/
if (cbdata->data.setup.CallingPN == NULL) {
printk(KERN_DEBUG "NULL CallingPN to phone; using 0\n");
strcpy(ictl.parm.setup.phone, "0");
}
else {
strcpy(ictl.parm.setup.phone, cbdata->data.setup.CallingPN);
}
if (cbdata->data.setup.CalledPN == NULL) {
printk(KERN_DEBUG "NULL CalledPN to eazmsn; using 0\n");
strcpy(ictl.parm.setup.eazmsn, "0");
}
else {
strcpy(ictl.parm.setup.eazmsn, cbdata->data.setup.CalledPN);
}
ictl.parm.setup.si1 = 7;
ictl.parm.setup.si2 = 0;
ictl.parm.setup.plan = 0;
ictl.parm.setup.screen = 0;
#ifdef DEBUG
printk(KERN_DEBUG "statstr: %s\n", ictl.num);
#endif
dev->dev_if->statcallb(&ictl);
if ((len = capi_conn_resp(chan, &skb)) < 0) {
printk(KERN_DEBUG "capi_conn_resp failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_CONN_RESP, refnum, skb, len);
}
/*
* user has replied
* open the channel
* send CONNECT message CONNECT_ACTIVE_REQ in CAPI
*/
void cb_in_2(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
unsigned short refnum;
struct sk_buff *skb;
int len;
if ((len = capi_conn_active_req(chan, &skb)) < 0) {
printk(KERN_DEBUG "capi_conn_active_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
printk(KERN_DEBUG "sending MSG_CONN_ACTV_REQ\n");
pcbit_l2_write(dev, MSG_CONN_ACTV_REQ, refnum, skb, len);
}
/*
* CONN_ACK arrived
* start b-proto selection
*
*/
void cb_in_3(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
unsigned short refnum;
struct sk_buff *skb;
int len;
if ((len = capi_select_proto_req(chan, &skb, 0 /*incoming*/)) < 0)
{
printk("capi_select_proto_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_SELP_REQ, refnum, skb, len);
}
/*
* Received disconnect ind on active state
* send disconnect resp
* send msg to user
*/
void cb_disc_1(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
struct sk_buff *skb;
int len;
ushort refnum;
isdn_ctrl ictl;
if ((len = capi_disc_resp(chan, &skb)) < 0) {
printk("capi_disc_resp failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_DISC_RESP, refnum, skb, len);
ictl.command = ISDN_STAT_BHUP;
ictl.driver = dev->id;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
}
/*
* User HANGUP on active/call proceeding state
* send disc.req
*/
void cb_disc_2(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
struct sk_buff *skb;
int len;
ushort refnum;
if ((len = capi_disc_req(chan->callref, &skb, CAUSE_NORMAL)) < 0)
{
printk("capi_disc_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_DISC_REQ, refnum, skb, len);
}
/*
* Disc confirm received send BHUP
* Problem: when the HL driver sends the disc req itself
* LL receives BHUP
*/
void cb_disc_3(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
isdn_ctrl ictl;
ictl.command = ISDN_STAT_BHUP;
ictl.driver = dev->id;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
}
void cb_notdone(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
}
/*
* send activate b-chan protocol
*/
void cb_selp_1(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
struct sk_buff *skb;
int len;
ushort refnum;
if ((len = capi_activate_transp_req(chan, &skb)) < 0)
{
printk("capi_conn_activate_transp_req failed\n");
return;
}
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_ACT_TRANSP_REQ, refnum, skb, len);
}
/*
* Inform User that the B-channel is available
*/
void cb_open(struct pcbit_dev *dev, struct pcbit_chan *chan,
struct callb_data *data)
{
isdn_ctrl ictl;
ictl.command = ISDN_STAT_BCONN;
ictl.driver = dev->id;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
}
| gpl-2.0 |
pershoot/android_kernel_samsung_p4 | arch/cris/arch-v32/mach-fs/cpufreq.c | 9472 | 3546 | #include <linux/init.h>
#include <linux/module.h>
#include <linux/cpufreq.h>
#include <hwregs/reg_map.h>
#include <arch/hwregs/reg_rdwr.h>
#include <arch/hwregs/config_defs.h>
#include <arch/hwregs/bif_core_defs.h>
static int
cris_sdram_freq_notifier(struct notifier_block *nb, unsigned long val,
void *data);
static struct notifier_block cris_sdram_freq_notifier_block = {
.notifier_call = cris_sdram_freq_notifier
};
static struct cpufreq_frequency_table cris_freq_table[] = {
{0x01, 6000},
{0x02, 200000},
{0, CPUFREQ_TABLE_END},
};
static unsigned int cris_freq_get_cpu_frequency(unsigned int cpu)
{
reg_config_rw_clk_ctrl clk_ctrl;
clk_ctrl = REG_RD(config, regi_config, rw_clk_ctrl);
return clk_ctrl.pll ? 200000 : 6000;
}
static void cris_freq_set_cpu_state(unsigned int state)
{
int i;
struct cpufreq_freqs freqs;
reg_config_rw_clk_ctrl clk_ctrl;
clk_ctrl = REG_RD(config, regi_config, rw_clk_ctrl);
for_each_possible_cpu(i) {
freqs.old = cris_freq_get_cpu_frequency(i);
freqs.new = cris_freq_table[state].frequency;
freqs.cpu = i;
}
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
local_irq_disable();
/* Even though we may be SMP they will share the same clock
* so all settings are made on CPU0. */
if (cris_freq_table[state].frequency == 200000)
clk_ctrl.pll = 1;
else
clk_ctrl.pll = 0;
REG_WR(config, regi_config, rw_clk_ctrl, clk_ctrl);
local_irq_enable();
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
};
static int cris_freq_verify(struct cpufreq_policy *policy)
{
return cpufreq_frequency_table_verify(policy, &cris_freq_table[0]);
}
static int cris_freq_target(struct cpufreq_policy *policy,
unsigned int target_freq, unsigned int relation)
{
unsigned int newstate = 0;
if (cpufreq_frequency_table_target
(policy, cris_freq_table, target_freq, relation, &newstate))
return -EINVAL;
cris_freq_set_cpu_state(newstate);
return 0;
}
static int cris_freq_cpu_init(struct cpufreq_policy *policy)
{
int result;
/* cpuinfo and default policy values */
policy->cpuinfo.transition_latency = 1000000; /* 1ms */
policy->cur = cris_freq_get_cpu_frequency(0);
result = cpufreq_frequency_table_cpuinfo(policy, cris_freq_table);
if (result)
return (result);
cpufreq_frequency_table_get_attr(cris_freq_table, policy->cpu);
return 0;
}
static int cris_freq_cpu_exit(struct cpufreq_policy *policy)
{
cpufreq_frequency_table_put_attr(policy->cpu);
return 0;
}
static struct freq_attr *cris_freq_attr[] = {
&cpufreq_freq_attr_scaling_available_freqs,
NULL,
};
static struct cpufreq_driver cris_freq_driver = {
.get = cris_freq_get_cpu_frequency,
.verify = cris_freq_verify,
.target = cris_freq_target,
.init = cris_freq_cpu_init,
.exit = cris_freq_cpu_exit,
.name = "cris_freq",
.owner = THIS_MODULE,
.attr = cris_freq_attr,
};
static int __init cris_freq_init(void)
{
int ret;
ret = cpufreq_register_driver(&cris_freq_driver);
cpufreq_register_notifier(&cris_sdram_freq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
return ret;
}
static int
cris_sdram_freq_notifier(struct notifier_block *nb, unsigned long val,
void *data)
{
int i;
struct cpufreq_freqs *freqs = data;
if (val == CPUFREQ_PRECHANGE) {
reg_bif_core_rw_sdram_timing timing =
REG_RD(bif_core, regi_bif_core, rw_sdram_timing);
timing.cpd = (freqs->new == 200000 ? 0 : 1);
if (freqs->new == 200000)
for (i = 0; i < 50000; i++) ;
REG_WR(bif_core, regi_bif_core, rw_sdram_timing, timing);
}
return 0;
}
module_init(cris_freq_init);
| gpl-2.0 |
alexforsale/android_kernel_xiaomi_armani | net/ceph/crush/hash.c | 12032 | 3181 |
#include <linux/types.h>
#include <linux/crush/hash.h>
/*
* Robert Jenkins' function for mixing 32-bit values
* http://burtleburtle.net/bob/hash/evahash.html
* a, b = random bits, c = input and output
*/
#define crush_hashmix(a, b, c) do { \
a = a-b; a = a-c; a = a^(c>>13); \
b = b-c; b = b-a; b = b^(a<<8); \
c = c-a; c = c-b; c = c^(b>>13); \
a = a-b; a = a-c; a = a^(c>>12); \
b = b-c; b = b-a; b = b^(a<<16); \
c = c-a; c = c-b; c = c^(b>>5); \
a = a-b; a = a-c; a = a^(c>>3); \
b = b-c; b = b-a; b = b^(a<<10); \
c = c-a; c = c-b; c = c^(b>>15); \
} while (0)
#define crush_hash_seed 1315423911
static __u32 crush_hash32_rjenkins1(__u32 a)
{
__u32 hash = crush_hash_seed ^ a;
__u32 b = a;
__u32 x = 231232;
__u32 y = 1232;
crush_hashmix(b, x, hash);
crush_hashmix(y, a, hash);
return hash;
}
static __u32 crush_hash32_rjenkins1_2(__u32 a, __u32 b)
{
__u32 hash = crush_hash_seed ^ a ^ b;
__u32 x = 231232;
__u32 y = 1232;
crush_hashmix(a, b, hash);
crush_hashmix(x, a, hash);
crush_hashmix(b, y, hash);
return hash;
}
static __u32 crush_hash32_rjenkins1_3(__u32 a, __u32 b, __u32 c)
{
__u32 hash = crush_hash_seed ^ a ^ b ^ c;
__u32 x = 231232;
__u32 y = 1232;
crush_hashmix(a, b, hash);
crush_hashmix(c, x, hash);
crush_hashmix(y, a, hash);
crush_hashmix(b, x, hash);
crush_hashmix(y, c, hash);
return hash;
}
static __u32 crush_hash32_rjenkins1_4(__u32 a, __u32 b, __u32 c, __u32 d)
{
__u32 hash = crush_hash_seed ^ a ^ b ^ c ^ d;
__u32 x = 231232;
__u32 y = 1232;
crush_hashmix(a, b, hash);
crush_hashmix(c, d, hash);
crush_hashmix(a, x, hash);
crush_hashmix(y, b, hash);
crush_hashmix(c, x, hash);
crush_hashmix(y, d, hash);
return hash;
}
static __u32 crush_hash32_rjenkins1_5(__u32 a, __u32 b, __u32 c, __u32 d,
__u32 e)
{
__u32 hash = crush_hash_seed ^ a ^ b ^ c ^ d ^ e;
__u32 x = 231232;
__u32 y = 1232;
crush_hashmix(a, b, hash);
crush_hashmix(c, d, hash);
crush_hashmix(e, x, hash);
crush_hashmix(y, a, hash);
crush_hashmix(b, x, hash);
crush_hashmix(y, c, hash);
crush_hashmix(d, x, hash);
crush_hashmix(y, e, hash);
return hash;
}
__u32 crush_hash32(int type, __u32 a)
{
switch (type) {
case CRUSH_HASH_RJENKINS1:
return crush_hash32_rjenkins1(a);
default:
return 0;
}
}
__u32 crush_hash32_2(int type, __u32 a, __u32 b)
{
switch (type) {
case CRUSH_HASH_RJENKINS1:
return crush_hash32_rjenkins1_2(a, b);
default:
return 0;
}
}
__u32 crush_hash32_3(int type, __u32 a, __u32 b, __u32 c)
{
switch (type) {
case CRUSH_HASH_RJENKINS1:
return crush_hash32_rjenkins1_3(a, b, c);
default:
return 0;
}
}
__u32 crush_hash32_4(int type, __u32 a, __u32 b, __u32 c, __u32 d)
{
switch (type) {
case CRUSH_HASH_RJENKINS1:
return crush_hash32_rjenkins1_4(a, b, c, d);
default:
return 0;
}
}
__u32 crush_hash32_5(int type, __u32 a, __u32 b, __u32 c, __u32 d, __u32 e)
{
switch (type) {
case CRUSH_HASH_RJENKINS1:
return crush_hash32_rjenkins1_5(a, b, c, d, e);
default:
return 0;
}
}
const char *crush_hash_name(int type)
{
switch (type) {
case CRUSH_HASH_RJENKINS1:
return "rjenkins1";
default:
return "unknown";
}
}
| gpl-2.0 |
MinimalOS/android_kernel_xiaomi_armani | arch/ia64/kernel/esi.c | 13312 | 4576 | /*
* Extensible SAL Interface (ESI) support routines.
*
* Copyright (C) 2006 Hewlett-Packard Co
* Alex Williamson <alex.williamson@hp.com>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/string.h>
#include <asm/esi.h>
#include <asm/sal.h>
MODULE_AUTHOR("Alex Williamson <alex.williamson@hp.com>");
MODULE_DESCRIPTION("Extensible SAL Interface (ESI) support");
MODULE_LICENSE("GPL");
#define MODULE_NAME "esi"
#define ESI_TABLE_GUID \
EFI_GUID(0x43EA58DC, 0xCF28, 0x4b06, 0xB3, \
0x91, 0xB7, 0x50, 0x59, 0x34, 0x2B, 0xD4)
enum esi_systab_entry_type {
ESI_DESC_ENTRY_POINT = 0
};
/*
* Entry type: Size:
* 0 48
*/
#define ESI_DESC_SIZE(type) "\060"[(unsigned) (type)]
typedef struct ia64_esi_desc_entry_point {
u8 type;
u8 reserved1[15];
u64 esi_proc;
u64 gp;
efi_guid_t guid;
} ia64_esi_desc_entry_point_t;
struct pdesc {
void *addr;
void *gp;
};
static struct ia64_sal_systab *esi_systab;
static int __init esi_init (void)
{
efi_config_table_t *config_tables;
struct ia64_sal_systab *systab;
unsigned long esi = 0;
char *p;
int i;
config_tables = __va(efi.systab->tables);
for (i = 0; i < (int) efi.systab->nr_tables; ++i) {
if (efi_guidcmp(config_tables[i].guid, ESI_TABLE_GUID) == 0) {
esi = config_tables[i].table;
break;
}
}
if (!esi)
return -ENODEV;
systab = __va(esi);
if (strncmp(systab->signature, "ESIT", 4) != 0) {
printk(KERN_ERR "bad signature in ESI system table!");
return -ENODEV;
}
p = (char *) (systab + 1);
for (i = 0; i < systab->entry_count; i++) {
/*
* The first byte of each entry type contains the type
* descriptor.
*/
switch (*p) {
case ESI_DESC_ENTRY_POINT:
break;
default:
printk(KERN_WARNING "Unknown table type %d found in "
"ESI table, ignoring rest of table\n", *p);
return -ENODEV;
}
p += ESI_DESC_SIZE(*p);
}
esi_systab = systab;
return 0;
}
int ia64_esi_call (efi_guid_t guid, struct ia64_sal_retval *isrvp,
enum esi_proc_type proc_type, u64 func,
u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5, u64 arg6,
u64 arg7)
{
struct ia64_fpreg fr[6];
unsigned long flags = 0;
int i;
char *p;
if (!esi_systab)
return -1;
p = (char *) (esi_systab + 1);
for (i = 0; i < esi_systab->entry_count; i++) {
if (*p == ESI_DESC_ENTRY_POINT) {
ia64_esi_desc_entry_point_t *esi = (void *)p;
if (!efi_guidcmp(guid, esi->guid)) {
ia64_sal_handler esi_proc;
struct pdesc pdesc;
pdesc.addr = __va(esi->esi_proc);
pdesc.gp = __va(esi->gp);
esi_proc = (ia64_sal_handler) &pdesc;
ia64_save_scratch_fpregs(fr);
if (proc_type == ESI_PROC_SERIALIZED)
spin_lock_irqsave(&sal_lock, flags);
else if (proc_type == ESI_PROC_MP_SAFE)
local_irq_save(flags);
else
preempt_disable();
*isrvp = (*esi_proc)(func, arg1, arg2, arg3,
arg4, arg5, arg6, arg7);
if (proc_type == ESI_PROC_SERIALIZED)
spin_unlock_irqrestore(&sal_lock,
flags);
else if (proc_type == ESI_PROC_MP_SAFE)
local_irq_restore(flags);
else
preempt_enable();
ia64_load_scratch_fpregs(fr);
return 0;
}
}
p += ESI_DESC_SIZE(*p);
}
return -1;
}
EXPORT_SYMBOL_GPL(ia64_esi_call);
int ia64_esi_call_phys (efi_guid_t guid, struct ia64_sal_retval *isrvp,
u64 func, u64 arg1, u64 arg2, u64 arg3, u64 arg4,
u64 arg5, u64 arg6, u64 arg7)
{
struct ia64_fpreg fr[6];
unsigned long flags;
u64 esi_params[8];
char *p;
int i;
if (!esi_systab)
return -1;
p = (char *) (esi_systab + 1);
for (i = 0; i < esi_systab->entry_count; i++) {
if (*p == ESI_DESC_ENTRY_POINT) {
ia64_esi_desc_entry_point_t *esi = (void *)p;
if (!efi_guidcmp(guid, esi->guid)) {
ia64_sal_handler esi_proc;
struct pdesc pdesc;
pdesc.addr = (void *)esi->esi_proc;
pdesc.gp = (void *)esi->gp;
esi_proc = (ia64_sal_handler) &pdesc;
esi_params[0] = func;
esi_params[1] = arg1;
esi_params[2] = arg2;
esi_params[3] = arg3;
esi_params[4] = arg4;
esi_params[5] = arg5;
esi_params[6] = arg6;
esi_params[7] = arg7;
ia64_save_scratch_fpregs(fr);
spin_lock_irqsave(&sal_lock, flags);
*isrvp = esi_call_phys(esi_proc, esi_params);
spin_unlock_irqrestore(&sal_lock, flags);
ia64_load_scratch_fpregs(fr);
return 0;
}
}
p += ESI_DESC_SIZE(*p);
}
return -1;
}
EXPORT_SYMBOL_GPL(ia64_esi_call_phys);
static void __exit esi_exit (void)
{
}
module_init(esi_init);
module_exit(esi_exit); /* makes module removable... */
| gpl-2.0 |
ARPA-SIMC/libsim | examples/example_vg6d_3.f90 | 1 | 2903 | ! Copyright (C) 2010 ARPA-SIM <urpsim@smr.arpa.emr.it>
! authors:
! Davide Cesari <dcesari@arpa.emr.it>
! Paolo Patruno <ppatruno@arpa.emr.it>
! This program is free software; you can redistribute it and/or
! modify it under the terms of the GNU General Public License as
! published by the Free Software Foundation; either version 2 of
! the License, or (at your option) any later version.
! This program is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
! GNU General Public License for more details.
! You should have received a copy of the GNU General Public License
! along with this program. If not, see <http://www.gnu.org/licenses/>.
program demo3
use gridinfo_class
use missing_values
use log4fortran
use grid_id_class
use volgrid6d_class
use char_utilities
implicit none
integer :: category,ier
character(len=512):: a_name
type(arrayof_gridinfo) :: gridinfoin, gridinfoout
type(volgrid6d),pointer :: volgrid(:)
TYPE(grid_file_id) :: ifile
TYPE(grid_id) :: gaid, gaid_template
INTEGER :: ngrib
!questa chiamata prende dal launcher il nome univoco
call l4f_launcher(a_name,a_name_force="demo3")
!init di log4fortran
ier=l4f_init()
!imposta a_name
category=l4f_category_get(a_name//".main")
ngrib=0
ifile = grid_file_id_new('../data/in.grb','r')
ngrib = grid_file_id_count(ifile)
call l4f_category_log(category,L4F_INFO,&
"Numero totale di grib: "//to_char(ngrib))
! aggiungo ngrib elementi vuoti
CALL insert(gridinfoin, nelem=ngrib)
ngrib=0
! Loop on all the messages in a file.
DO WHILE (.TRUE.)
gaid = grid_id_new(ifile)
IF (.NOT.c_e(gaid)) EXIT
CALL l4f_category_log(category,L4F_INFO,"import gridinfoin")
ngrib = ngrib + 1
CALL init (gridinfoin%array(ngrib), gaid=gaid, categoryappend=TRIM(to_char(ngrib)))
CALL import(gridinfoin%array(ngrib))
ENDDO
call delete(ifile)
call display(gridinfoin)
call l4f_category_log(category,L4F_INFO,"import")
call import(volgrid, gridinfoin, categoryappend="volume di test")
call l4f_category_log(category,L4F_INFO,"delete gridinfoin")
CALL delete(gridinfoin)
! qui posso fare tutti i conti possibili
gaid_template = grid_id_new(grib_api_template="regular_ll_sfc_grib1")
call l4f_category_log(category,L4F_INFO,"export a un grib fatto come voglio io")
call export(volgrid, gridinfoout, gaid_template=gaid_template)
ifile = grid_file_id_new('out.grb','w')
do ngrib=1,gridinfoout%arraysize
! write the new message to a file
if(c_e(gridinfoout%array(ngrib)%gaid)) then
call export(gridinfoout%array(ngrib))
call export(gridinfoout%array(ngrib)%gaid,ifile)
end if
end do
call delete(ifile)
call l4f_category_log(category,L4F_INFO,"terminato")
call delete(gridinfoout)
!chiudo il logger
call l4f_category_delete(category)
ier=l4f_fini()
end program demo3
| gpl-2.0 |
rluu/superlooper | looper/MediaInfo.cpp | 1 | 5023 |
#include "MediaInfo.h"
MediaInfo::MediaInfo( const QString& mediaFilename,
const QString& ffmpegLocation )
:
mediaFilename_( mediaFilename ),
ffmpegLocation_( ffmpegLocation )
{
process_ = new QProcess( this );
}
MediaInfo::~MediaInfo()
{
if( process_->state() != QProcess::NotRunning )
{
// process__->tryTerminate();
process_->kill();
}
delete process_;
}
void MediaInfo::setMediaFilename( const QString& mediaFilename )
{
mediaFilename_ = mediaFilename;
}
void MediaInfo::setFFMPEGLocation( const QString& ffmpegLocation )
{
ffmpegLocation_ = ffmpegLocation;
}
QTime MediaInfo::getDuration()
{
// Make sure we have the required ffmpeg file location, so we can
// use it to determine the duration.
if( ffmpegLocation_ == QString( "" ) ||
ffmpegLocation_.isNull() == true )
{
return QTime();
}
// Make sure we have a media filename set, so we can know what to
// check the duration of.
if( mediaFilename_ == QString( "" ) ||
mediaFilename_.isNull() == true )
{
return QTime();
}
process_->setReadChannel( QProcess::StandardError );
// qDebug( QString( QString("ffmpegLocation_ is: ") + QString( ffmpegLocation_ ) ).toAscii() );
// qDebug( QString( QString("Media filename is: ") + QString( mediaFilename_ ) ).toAscii() );
// Start the process
QString toExec( QString( "/usr/bin/" ) + ffmpegLocation_ + " -i \"" + mediaFilename_ + "\"" );
// qDebug( QString( QString("Str to exec is: ") + toExec ).toAscii() );
process_->start( toExec );
// process_->waitForReadyRead( -1 );
process_->waitForFinished( 5000 );
// process_->terminate();
QByteArray byteArray;
byteArray = process_->readAllStandardError();
while( byteArray.size() != 0 )
{
QString line( byteArray );
// qDebug(QString( QString( "Line recieved is: " ) + line ).toAscii());
QString durationStr( " Duration: " );
QString commaStr( "," );
QString periodStr( "." );
int locationOfDuration = line.indexOf( durationStr );
line.remove( 0, locationOfDuration );
locationOfDuration = 0;
// qDebug(QString( QString( "Revised line is: " ) + line ).toAscii() );
int locationOfComma = line.indexOf( commaStr );
int locationOfPeriod = line.indexOf( periodStr );
// qDebug( "locationOfDuration == %d", locationOfDuration );
// qDebug( "locationOfComma == %d", locationOfComma );
// qDebug( "locationOfPeriod == %d", locationOfPeriod );
if( locationOfDuration != -1 )
{
QString durationTimeStr;
if( locationOfComma != -1 )
{
line.truncate( locationOfComma );
durationTimeStr = line;
}
if( locationOfPeriod != -1 )
{
durationTimeStr.truncate( locationOfPeriod );
}
durationTimeStr = durationTimeStr.remove( 0,
locationOfDuration +
durationStr.size() );
qDebug( QString( QString("Duration: ") +
durationTimeStr ).toAscii() );
QString hoursStr = durationTimeStr.section( ':', 0, 0 );
QString minutesStr = durationTimeStr.section( ':', 1, 1 );
QString secondsStr =
durationTimeStr.section( ':', 2, 2 ).section( '.', 0, 0 );
QString millisecondsStr =
durationTimeStr.section( ':', 2, 2 ).section( '.', 1, 1 );
if( millisecondsStr.size() == 0 )
{
millisecondsStr = "0";
}
else if( millisecondsStr.size() == 1 )
{
millisecondsStr += "000";
}
else if( millisecondsStr.size() == 2 )
{
millisecondsStr += "00" ;
}
else if( millisecondsStr.size() == 3 )
{
millisecondsStr += "0";
}
int hours = hoursStr.toInt();
int minutes = minutesStr.toInt();
int seconds = secondsStr.toInt();
int milliseconds = millisecondsStr.toInt();
// qDebug( "Hours == %d", hours );
// qDebug( "Minutes == %d", minutes );
// qDebug( "Seconds == %d", seconds );
// qDebug( "Milliseconds == %d", milliseconds );
QTime duration( hours, minutes, seconds, milliseconds );
return duration;
}
process_->waitForReadyRead( 2000 );
byteArray = process_->readAllStandardError();
}
qDebug( "DEBUG: Ran out of lines to parse while "
"looking for the duration." );
return QTime();
}
| gpl-2.0 |
pastewka/lammps | lib/atc/GhostManager.cpp | 1 | 30493 | // ATC transfer headers
#include "GhostManager.h"
#include "ATC_Method.h"
#include "LammpsInterface.h"
#include "ATC_Error.h"
using std::vector;
using std::set;
using std::pair;
using std::map;
using std::stringstream;
using ATC_Utility::to_string;
namespace ATC {
//--------------------------------------------------------
//--------------------------------------------------------
// Class GhostManager
//--------------------------------------------------------
//--------------------------------------------------------
//--------------------------------------------------------
// Constructor
//--------------------------------------------------------
GhostManager::GhostManager(ATC_Method * atc) :
ghostModifier_(NULL),
atc_(atc),
boundaryDynamics_(NO_BOUNDARY_DYNAMICS),
needReset_(true)
{
// do nothing
}
//--------------------------------------------------------
// Destructor
//--------------------------------------------------------
GhostManager::~GhostManager()
{
if (ghostModifier_) delete ghostModifier_;
}
//--------------------------------------------------------
// modify
// parses inputs and modifies state of the integrator
//--------------------------------------------------------
bool GhostManager::modify(int narg, char **arg)
{
int argIndex = 0;
/*! \page man_boundary_dynamics fix_modify AtC boundary_dynamics
\section syntax
fix_modify AtC boundary_dynamics < on | damped_harmonic | prescribed | coupled | none > [args] \n
\section description
Sets different schemes for controlling boundary atoms. On will integrate the boundary atoms using the velocity-verlet algorithm. Damped harmonic uses a mass/spring/dashpot for the boundary atoms with added arguments of the damping and spring constants followed by the ratio of the boundary type mass to the desired mass. Prescribed forces the boundary atoms to follow the finite element displacement. Coupled does the same.
\section restrictions
Boundary atoms must be specified. When using swaps between internal and boundary atoms, the initial configuration must have already correctly partitioned the two.
\section related
\man_boundary
\section default
prescribed
on
*/
if (strcmp(arg[argIndex],"none")==0) {
boundaryDynamics_ = NO_BOUNDARY_DYNAMICS;
needReset_ = true;
return true;
}
else if (strcmp(arg[argIndex],"on")==0) {
boundaryDynamics_ = VERLET;
needReset_ = true;
return true;
}
else if (strcmp(arg[argIndex],"prescribed")==0) {
boundaryDynamics_ = PRESCRIBED;
needReset_ = true;
return true;
}
else if (strcmp(arg[argIndex],"damped_harmonic")==0) {
argIndex++;
kappa_.push_back(atof(arg[argIndex++]));
gamma_.push_back(atof(arg[argIndex++]));
mu_.push_back(atof(arg[argIndex]));
boundaryDynamics_ = DAMPED_HARMONIC;
needReset_ = true;
return true;
}
else if (strcmp(arg[argIndex],"damped_layers")==0) {
argIndex++;
while (argIndex < narg) {
kappa_.push_back(atof(arg[argIndex++]));
gamma_.push_back(atof(arg[argIndex++]));
mu_.push_back(atof(arg[argIndex++]));
}
boundaryDynamics_ = DAMPED_LAYERS;
needReset_ = true;
return true;
}
else if (strcmp(arg[argIndex],"coupled")==0) {
boundaryDynamics_ = COUPLED;
kappa_.push_back(0.);
gamma_.push_back(0.);
mu_.push_back(0.);
needReset_ = true;
return true;
}
return false;
}
//--------------------------------------------------------
// construct_methods
// constructs the specific method to modify the ghosts
//--------------------------------------------------------
void GhostManager::construct_methods()
{
if (ghostModifier_) {
delete ghostModifier_;
ghostModifier_ = NULL;
}
if (!atc_->groupbit_ghost()) {
ghostModifier_ = new GhostModifier(this);
return;
}
switch (boundaryDynamics_) {
case VERLET: {
ghostModifier_ = new GhostModifier(this);
ghostModifier_->set_integrate_atoms(true);
break;
}
case PRESCRIBED: {
ghostModifier_ = new GhostModifierPrescribed(this);
break;
}
case COUPLED:
case DAMPED_HARMONIC: {
ghostModifier_ = new GhostModifierDampedHarmonic(this,kappa_,gamma_,mu_);
ghostModifier_->set_integrate_atoms(true);
break;
}
case DAMPED_LAYERS: {
ghostModifier_ = new GhostModifierDampedHarmonicLayers(this,kappa_,gamma_,mu_);
ghostModifier_->set_integrate_atoms(true);
break;
}
case SWAP: {
// if regions based on element sets, use verlet on ghosts and swap ghosts and internal when they move between regions
const std::string & internalElementSet(atc_->internal_element_set());
if (internalElementSet.size() && (atc_->atom_to_element_map_type()==EULERIAN)) {
LammpsInterface * lammpsInterface = LammpsInterface::instance();
if (atc_->atom_to_element_map_frequency() % lammpsInterface->reneighbor_frequency() != 0) {
throw ATC_Error("GhostManager::construct_methods - eulerian frequency and lammsp reneighbor frequency must be consistent to swap boundary and internal atoms");
}
ghostModifier_ = new GhostIntegratorSwap(this);
}
break;
}
case SWAP_VERLET: {
// if regions based on element sets, use verlet on ghosts and swap ghosts and internal when they move between regions
const std::string & internalElementSet(atc_->internal_element_set());
if (internalElementSet.size() && (atc_->atom_to_element_map_type()==EULERIAN)) {
LammpsInterface * lammpsInterface = LammpsInterface::instance();
if (atc_->atom_to_element_map_frequency() % lammpsInterface->reneighbor_frequency() != 0) {
throw ATC_Error("GhostManager::construct_methods - eulerian frequency and lammsp reneighbor frequency must be consistent to swap boundary and internal atoms");
}
ghostModifier_ = new GhostIntegratorSwap(this);
ghostModifier_->set_integrate_atoms(true);
}
break;
}
default: {
ghostModifier_ = new GhostModifier(this);
}
}
}
//--------------------------------------------------------
// construct_transfers
// sets/constructs all required dependency managed data
//--------------------------------------------------------
void GhostManager::construct_transfers()
{
ghostModifier_->construct_transfers();
}
//--------------------------------------------------------
// initialize
// initialize all data and variables before a run
//--------------------------------------------------------
void GhostManager::initialize()
{
ghostModifier_->initialize();
needReset_ = false;
}
//--------------------------------------------------------
// pre_exchange
// makes any updates required before lammps exchanges
// atoms
//--------------------------------------------------------
void GhostManager::pre_exchange()
{
ghostModifier_->pre_exchange();
}
//--------------------------------------------------------
// initial_integrate_velocity
// velocity update in first part of velocity-verlet
//--------------------------------------------------------
void GhostManager::init_integrate_velocity(double dt)
{
ghostModifier_->init_integrate_velocity(dt);
}
//--------------------------------------------------------
// initial_integrate_position
// position update in first part of velocity-verlet
//--------------------------------------------------------
void GhostManager::init_integrate_position(double dt)
{
ghostModifier_->init_integrate_position(dt);
}
//--------------------------------------------------------
// post_init_integrate
// makes any updates required after first integration
//--------------------------------------------------------
void GhostManager::post_init_integrate()
{
ghostModifier_->post_init_integrate();
}
//--------------------------------------------------------
// final_integrate
// velocity update in second part of velocity-verlet
//--------------------------------------------------------
void GhostManager::final_integrate(double dt)
{
ghostModifier_->final_integrate(dt);
}
//--------------------------------------------------------
//--------------------------------------------------------
// Class GhostModifier
//--------------------------------------------------------
//--------------------------------------------------------
//--------------------------------------------------------
// Constructor
//--------------------------------------------------------
GhostModifier::GhostModifier(GhostManager * ghostManager) :
ghostManager_(ghostManager),
atomTimeIntegrator_(NULL),
integrateAtoms_(false)
{
// do nothing
}
//--------------------------------------------------------
// Destructor
//--------------------------------------------------------
GhostModifier::~GhostModifier()
{
if (atomTimeIntegrator_) delete atomTimeIntegrator_;
}
//--------------------------------------------------------
// construct_transfers
// sets/constructs all required dependency managed data
//--------------------------------------------------------
void GhostModifier::construct_transfers()
{
if (atomTimeIntegrator_) delete atomTimeIntegrator_;
if (integrateAtoms_) {
atomTimeIntegrator_ = new AtomTimeIntegratorType(ghostManager_->atc(),GHOST);
atomTimeIntegrator_->construct_transfers();
}
else {
atomTimeIntegrator_ = new AtomTimeIntegrator();
}
}
//--------------------------------------------------------
// initial_integrate_velocity
// velocity update in first part of velocity-verlet
//--------------------------------------------------------
void GhostModifier::init_integrate_velocity(double dt)
{
atomTimeIntegrator_->init_integrate_velocity(dt);
}
//--------------------------------------------------------
// initial_integrate_position
// position update in first part of velocity-verlet
//--------------------------------------------------------
void GhostModifier::init_integrate_position(double dt)
{
atomTimeIntegrator_->init_integrate_position(dt);
}
//--------------------------------------------------------
// final_integrate
// velocity update in second part of velocity-verlet
//--------------------------------------------------------
void GhostModifier::final_integrate(double dt)
{
atomTimeIntegrator_->final_integrate(dt);
}
//--------------------------------------------------------
//--------------------------------------------------------
// Class GhostModifierPrescribed
//--------------------------------------------------------
//--------------------------------------------------------
//--------------------------------------------------------
// Constructor
//--------------------------------------------------------
GhostModifierPrescribed::GhostModifierPrescribed(GhostManager * ghostManager) :
GhostModifier(ghostManager),
atomPositions_(NULL),
atomFeDisplacement_(NULL),
atomRefPositions_(NULL)
{
// do nothing
}
//--------------------------------------------------------
// construct_transfers
// sets/constructs all required dependency managed data
//--------------------------------------------------------
void GhostModifierPrescribed::construct_transfers()
{
GhostModifier::construct_transfers();
InterscaleManager & interscaleManager((ghostManager_->atc())->interscale_manager());
atomPositions_ = interscaleManager.fundamental_atom_quantity(LammpsInterface::ATOM_POSITION,GHOST);
// prolongation from displacement field to atoms
PerAtomSparseMatrix<double> * atomShapeFunctions = interscaleManager.per_atom_sparse_matrix("InterpolantGhost");
if (!atomShapeFunctions) {
atomShapeFunctions = new PerAtomShapeFunction(ghostManager_->atc(),
interscaleManager.per_atom_quantity("AtomicGhostCoarseGrainingPositions"),
interscaleManager.per_atom_int_quantity("AtomGhostElement"),
GHOST);
interscaleManager.add_per_atom_sparse_matrix(atomShapeFunctions,"InterpolantGhost");
}
atomFeDisplacement_ = new FtaShapeFunctionProlongation(ghostManager_->atc(),
&(ghostManager_->atc())->field(DISPLACEMENT),
atomShapeFunctions,
GHOST);
interscaleManager.add_per_atom_quantity(atomFeDisplacement_,field_to_prolongation_name(DISPLACEMENT)+"Ghost");
atomRefPositions_ = interscaleManager.per_atom_quantity("AtomicGhostCoarseGrainingPositions");
}
//--------------------------------------------------------
// post_init_integrate
// after integration, fix ghost atoms' positions
//--------------------------------------------------------
void GhostModifierPrescribed::post_init_integrate()
{
const DENS_MAT & atomFeDisplacement(atomFeDisplacement_->quantity());
const DENS_MAT & atomRefPositions(atomRefPositions_->quantity());
*atomPositions_ = atomFeDisplacement + atomRefPositions;
}
//--------------------------------------------------------
//--------------------------------------------------------
// Class GhostModifierDampedHarmonic
//--------------------------------------------------------
//--------------------------------------------------------
//--------------------------------------------------------
// Constructor
//--------------------------------------------------------
GhostModifierDampedHarmonic::GhostModifierDampedHarmonic(GhostManager * ghostManager,
const vector<double> & kappa,
const vector<double> & gamma,
const vector<double> & mu) :
GhostModifierPrescribed(ghostManager),
atomVelocities_(NULL),
atomFeVelocity_(NULL),
atomForces_(NULL),
kappa_(kappa),
gamma_(gamma),
mu_(mu)
{
// do nothing
}
//--------------------------------------------------------
// construct_transfers
// sets/constructs all required dependency managed data
//--------------------------------------------------------
void GhostModifierDampedHarmonic::construct_transfers()
{
GhostModifierPrescribed::construct_transfers();
InterscaleManager & interscaleManager((ghostManager_->atc())->interscale_manager());
atomVelocities_ = interscaleManager.fundamental_atom_quantity(LammpsInterface::ATOM_VELOCITY,GHOST);
atomForces_ = interscaleManager.fundamental_atom_quantity(LammpsInterface::ATOM_FORCE,GHOST);
// prolongation from displacement field to atoms
PerAtomSparseMatrix<double> * atomShapeFunctions = interscaleManager.per_atom_sparse_matrix("InterpolantGhost");
atomFeVelocity_ = new FtaShapeFunctionProlongation(ghostManager_->atc(),
&(ghostManager_->atc())->field(VELOCITY),
atomShapeFunctions,
GHOST);
interscaleManager.add_per_atom_quantity(atomFeVelocity_,field_to_prolongation_name(VELOCITY)+"Ghost");
// calculate nominal bond stiffness
int i = 0, j = 1;// HACk should be an atom and its neighbor in the boundary
double rsq = 0.0;
//k0_ = LammpsInterface_->bond_stiffness(i,j,rsq);
k0_ = LammpsInterface::instance()->bond_stiffness(i,j,rsq);
}
#if true
//--------------------------------------------------------
// initial_integrate_velocity
// velocity update in first part of velocity-verlet
//--------------------------------------------------------
void GhostModifierDampedHarmonic::init_integrate_velocity(double dt)
{
#if true
atomTimeIntegrator_->init_integrate_velocity(mu_[0]*dt);
#else
atomTimeIntegrator_->init_integrate_velocity(dt);
#endif
}
//--------------------------------------------------------
// initial_integrate_position
// position update in first part of velocity-verlet
//--------------------------------------------------------
void GhostModifierDampedHarmonic::init_integrate_position(double dt)
{
atomTimeIntegrator_->init_integrate_position(dt);
}
#endif
//--------------------------------------------------------
// final_integrate
// velocity update in second part of velocity-verlet
//--------------------------------------------------------
void GhostModifierDampedHarmonic::final_integrate(double dt)
{
const DENS_MAT & atomPositions(atomPositions_->quantity());
const DENS_MAT & atomVelocities(atomVelocities_->quantity());
const DENS_MAT & atomFeDisplacement(atomFeDisplacement_->quantity());
const DENS_MAT & atomFeVelocity(atomFeVelocity_->quantity());
const DENS_MAT & atomRefPositions(atomRefPositions_->quantity());
_forces_ = atomFeDisplacement;
_forces_ += atomRefPositions;
_forces_ -= atomPositions;
_forces_ *= kappa_[0];
_forces_ += gamma_[0]*(atomFeVelocity - atomVelocities);
#if true
#else
_forces_ *= 1./mu_[0];
#endif
*atomForces_ = _forces_;
#if true
atomTimeIntegrator_->final_integrate(mu_[0]*dt);
#else
atomTimeIntegrator_->final_integrate(dt);
#endif
}
//--------------------------------------------------------
//--------------------------------------------------------
// Class GhostModifierDampedHarmonicLayers
//--------------------------------------------------------
//--------------------------------------------------------
//--------------------------------------------------------
// Constructor
//--------------------------------------------------------
GhostModifierDampedHarmonicLayers::GhostModifierDampedHarmonicLayers(GhostManager * ghostManager,
const vector<double> & kappa,
const vector<double> & gamma,
const vector<double> & mu) :
GhostModifierDampedHarmonic(ghostManager,kappa,gamma,mu),
ghostToBoundaryDistance_(NULL),
layerId_(NULL)
{
// do nothing
}
//--------------------------------------------------------
// construct_transfers
// sets/constructs all required dependency managed data
//--------------------------------------------------------
void GhostModifierDampedHarmonicLayers::construct_transfers()
{
GhostModifierDampedHarmonic::construct_transfers();
InterscaleManager & interscaleManager((ghostManager_->atc())->interscale_manager());
// transfer for distance to boundary
ghostToBoundaryDistance_ = new AtcAtomQuantity<double>(ghostManager_->atc(),
1,GHOST);
interscaleManager.add_per_atom_quantity(ghostToBoundaryDistance_,
"GhostToBoundaryDistance");
// transfer from ghost atom to its layer id
layerId_ = new AtcAtomQuantity<int>(ghostManager_->atc(),
1,GHOST);
interscaleManager.add_per_atom_int_quantity(layerId_,"GhostLayerId");
}
//--------------------------------------------------------
// initialize
// initialize all data and variables before a run
//--------------------------------------------------------
void GhostModifierDampedHarmonicLayers::initialize()
{
compute_distances();
int nlayers = find_layers();
if (nlayers > ((int)gamma_.size())) throw ATC_Error("GhostModifierDampedHarmonicLayers::initialize not enough damping factors specified " + to_string(gamma_.size()));
}
//--------------------------------------------------------
// find atomic mononlayers
//--------------------------------------------------------
bool compare( pair<int,double> a, pair<int,double> b) {
return (a.second < b.second);
}
int GhostModifierDampedHarmonicLayers::find_layers()
{
DENS_MAT & d(ghostToBoundaryDistance_->set_quantity());
DenseMatrix<int> & ids = layerId_->set_quantity();
// get distances for every ghost atom for sorting
// size arrays of length number of processors
int commSize = LammpsInterface::instance()->comm_size();
int * procCounts = new int[commSize];
int * procOffsets = new int[commSize];
// get size information from all processors
int localGhosts = d.nRows();
LammpsInterface::instance()->int_allgather(localGhosts,procCounts);
procOffsets[0] = 0;
int totalGhosts = 0;
for (int i = 0; i < commSize-1; ++i) {
totalGhosts += procCounts[i];
procOffsets[i+1] = totalGhosts;
}
totalGhosts += procCounts[commSize-1];
double * globalDistances = new double[totalGhosts];
// allgather distances
LammpsInterface::instance()->allgatherv(d.ptr(), localGhosts,
globalDistances, procCounts, procOffsets);
// add to distances vector with -1 ids
// convert to STL for sort
vector< pair <int,double> > distances;
distances.resize(totalGhosts);
int myRank = LammpsInterface::instance()->comm_rank();
int j = 0;
for (int i = 0; i < totalGhosts; ++i) {
if (i >= procOffsets[myRank] && i < procOffsets[myRank] + procCounts[myRank]) {
distances[i] = pair <int,double> (j++,globalDistances[i]);
}
else {
distances[i] = pair <int,double> (-1,globalDistances[i]);
}
}
delete [] globalDistances;
delete [] procCounts;
delete [] procOffsets;
std::sort(distances.begin(),distances.end(),compare);
double min = (distances[0]).second;
double a = LammpsInterface::instance()->max_lattice_constant();
double tol = a/4;
double xlayer = min; // nominal position of layer
int ilayer =0;
vector<int> counts(1);
counts[0] = 0;
for (vector<pair<int,double> >::const_iterator itr = distances.begin();
itr != distances.end(); itr++) {
int id = (*itr).first;
double d = (*itr).second;
if (fabs(d-xlayer) > tol) {
counts.push_back(0);
ilayer++;
xlayer = d;
}
if (id > -1) {
ids(id,0) = ilayer;
}
counts[ilayer]++;
}
int nlayers = ilayer;
stringstream msg;
msg << nlayers << " boundary layers:\n";
for (int i = 0; i < nlayers; ++i) {
msg << i+1 << ": " << counts[i] << "\n";
}
ATC::LammpsInterface::instance()->print_msg_once(msg.str());
return nlayers;
}
//--------------------------------------------------------
// compute distances to boundary faces
//--------------------------------------------------------
void GhostModifierDampedHarmonicLayers::compute_distances()
{
// get fe mesh
const FE_Mesh * feMesh = ((ghostManager_->atc())->fe_engine())->fe_mesh();
InterscaleManager & interscaleManager((ghostManager_->atc())->interscale_manager());
// get elements in which ghosts reside
const DenseMatrix<int> & elementHasGhost((interscaleManager.dense_matrix_int("ElementHasGhost"))->quantity());
// get type of each node
const DenseMatrix<int> & nodeType((interscaleManager.dense_matrix_int("NodalGeometryType"))->quantity());
// create map from those elements to pair<DENS_VEC,DENS_VEC> (centroid, normal)
map<int, pair<DENS_VEC,DENS_VEC> > elementToFace;
int nsd = (ghostManager_->atc())->nsd();
int nfe = feMesh->num_faces_per_element();
DENS_MAT nodalCoords(nsd,nfe);
DENS_VEC centroid(nsd), normal(nsd);
Array<int> faceNodes;
bool isBoundaryFace;
for (int elt = 0; elt < elementHasGhost.nRows(); ++elt) {
if (elementHasGhost(elt,0)) {
// loop over all faces
int face;
for (face = 0; face < nfe; ++face) {
// get the nodes in a face
feMesh->face_connectivity_unique(PAIR(elt,face),faceNodes);
// identify the boundary face by the face which contains only boundary nodes
isBoundaryFace = true;
for (int i = 0; i < faceNodes.size(); ++i) {
if (nodeType(faceNodes(i),0) != BOUNDARY) {
isBoundaryFace = false;
break;
}
}
if (isBoundaryFace) {
break;
}
}
if (face == nfe) {
throw ATC_Error("GhostModifierDampedHarmonicLayers::initialize - Could not find boundary face for element " + to_string(elt));
}
// for each boundary face get the centroid by the average position of the nodes comprising it
feMesh->face_coordinates(PAIR(elt,face),nodalCoords);
centroid = 0.;
for (int i = 0; i < nodalCoords.nRows(); ++i) {
for (int j = 0; j < nodalCoords.nCols(); ++j) {
centroid(i) += nodalCoords(i,j);
}
}
centroid *= -1./double(nfe); // -1 gets outward normal from ATC region => all distances should be > 0
// for each boundary face get the normal
// ASSUMES all faces are planar
feMesh->face_normal(PAIR(elt,face),0,normal);
elementToFace[elt] = pair<DENS_VEC,DENS_VEC>(centroid,normal);
}
}
// for each atom compute (atom_pos - element->face_centroid) dot element_->face_normal
// get atom to element map for ghosts
PerAtomQuantity<int> * ghostToElementMap = interscaleManager.per_atom_int_quantity("AtomGhostElement");
const DenseMatrix<int> & ghostToElement(ghostToElementMap->quantity());
DENS_MAT & distance(ghostToBoundaryDistance_->set_quantity());
const DENS_MAT & atomPositions(atomPositions_->quantity());
DENS_VEC diff(nsd);
for (int i = 0; i < distance.nRows(); ++i) {
int elt = ghostToElement(i,0);
const DENS_VEC & c(elementToFace[elt].first);
const DENS_VEC & n(elementToFace[elt].second);
for (int j = 0; j < nsd; ++j) {
diff(j) = atomPositions(i,j) - c(j);
}
distance(i,0) = diff.dot(n); // should always be positive
}
}
//--------------------------------------------------------
// final_integrate
// velocity update in second part of velocity-verlet
//--------------------------------------------------------
void GhostModifierDampedHarmonicLayers::final_integrate(double dt)
{
const DENS_MAT & atomPositions(atomPositions_->quantity());
const DENS_MAT & atomVelocities(atomVelocities_->quantity());
const DENS_MAT & atomFeDisplacement(atomFeDisplacement_->quantity());
const DENS_MAT & atomFeVelocity(atomFeVelocity_->quantity());
const DENS_MAT & atomRefPositions(atomRefPositions_->quantity());
_forces_ = atomFeDisplacement;
_forces_ += atomRefPositions;
_forces_ -= atomPositions;
_forces_ *= kappa_[0];
_forces_ += gamma_[0]*(atomFeVelocity - atomVelocities);
_forces_ *= 1./mu_[0];
*atomForces_ = _forces_;
atomTimeIntegrator_->final_integrate(dt);
}
//--------------------------------------------------------
//--------------------------------------------------------
// Class GhostIntegratorVerletSwap
//--------------------------------------------------------
//--------------------------------------------------------
//--------------------------------------------------------
// Constructor
//--------------------------------------------------------
GhostIntegratorSwap::GhostIntegratorSwap(GhostManager * ghostManager) :
GhostModifier(ghostManager),
lammpsInterface_(LammpsInterface::instance()),
elementSet_((((ghostManager_->atc())->fe_engine())->fe_mesh())->elementset((ghostManager_->atc())->internal_element_set())),
atomElement_(NULL),
atomGhostElement_(NULL),
internalToAtom_((ghostManager_->atc())->internal_to_atom_map()),
ghostToAtom_((ghostManager_->atc())->ghost_to_atom_map()),
groupbit_((ghostManager_->atc())->groupbit()),
groupbitGhost_((ghostManager_->atc())->groupbit_ghost())
{
// do nothing
}
//--------------------------------------------------------
// construct_transfers
// sets/constructs all required dependency managed data
//--------------------------------------------------------
void GhostIntegratorSwap::construct_transfers()
{
GhostModifier::construct_transfers();
InterscaleManager & interscaleManager((ghostManager_->atc())->interscale_manager());
atomElement_ = interscaleManager.per_atom_int_quantity("AtomElement");
atomGhostElement_ = interscaleManager.per_atom_int_quantity("AtomGhostElement");
}
//--------------------------------------------------------
// initialize
// initialize all data and variables before a run
//--------------------------------------------------------
void GhostIntegratorSwap::initialize()
{
if ((ghostManager_->atc())->atom_to_element_map_frequency() % lammpsInterface_->reneighbor_frequency() != 0) {
throw ATC_Error("GhostIntegratorSwap::initialize - AtC Eulerian reset frequency must be a multiple of the Lammps reneighbor frequency when using internal/boundary atom swapping");
}
}
//--------------------------------------------------------
// pre_exchange
// swaps atoms between types depending on region
//--------------------------------------------------------
void GhostIntegratorSwap::pre_exchange()
{
// lammps mask to change type
int * mask = lammpsInterface_->atom_mask();
const DenseMatrix<int> & atomElement(atomElement_->quantity());
for (int i = 0; i < atomElement.nRows(); ++i) {
if (elementSet_.find(atomElement(i,0)) == elementSet_.end()) {
mask[internalToAtom_(i)] |= groupbitGhost_;
// remove from internal
}
}
}
};
| gpl-2.0 |
blackav/ejudge | lib/testing_report_xml.c | 1 | 52140 | /* -*- c -*- */
/* Copyright (C) 2005-2022 Alexander Chernov <cher@ejudge.ru> */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "ejudge/config.h"
#include "ejudge/ej_limits.h"
#include "ejudge/testing_report_xml.h"
#include "ejudge/expat_iface.h"
#include "ejudge/xml_utils.h"
#include "ejudge/protocol.h"
#include "ejudge/runlog.h"
#include "ejudge/digest_io.h"
#include "ejudge/misctext.h"
#include "ejudge/ej_uuid.h"
#include "ejudge/xalloc.h"
#include "ejudge/logger.h"
#include <string.h>
#ifndef EJUDGE_CHARSET
#define EJUDGE_CHARSET EJ_INTERNAL_CHARSET
#endif /* EJUDGE_CHARSET */
/*
<testing-report run-id="N" judge-id="N" judge-uuid="U" status="O" scoring="R" archive-available="B" [correct-available="B"] [info-available="B"] run-tests="N" [variant="N"] [accepting-mode="B"] [failed-test="N"] [tests-passed="N"] [score="N"] [time_limit_ms="T" real_time_limit_ms="T" [real-time-available="B"] [max-memory-used-available="T"] [marked-flag="B"] [tests-mode="B"] [tt-row-count="N"] [tt-column-count="N"] [user-status="O"] [user-tests-passed="N"] [user-score="N"] [user-max-score="N"] [user-run-tests="N"] >
<comment>T</comment>
<valuer_comment>T</valuer_comment>
<valuer_judge_comment>T</valuer_judge_comment>
<valuer_errors>T</valuer_errors>
<host>T</host>
<cpu_model>T</cpu_model>
<cpu_mhz>T</cpu_mhz>
<errors>T</errors>
[<compiler_output>T</compiler_output>]
<tests>
<test num="N" status="O" [exit-code="N"] [term-signal="N"] time="N" real-time="N" [max-memory-used="N"] [nominal-score="N" score="N"] [comment="S"] [team-comment="S"] [checker-comment="S"] [exit-comment="S"] output-available="B" stderr-available="B" checker-output-available="B" args-too-long="B" [input-digest="X"] [correct-digest="X"] [visibility="O"]>
[<args>T</args>]
[<input>T</input>]
[<output>T</output>]
[<correct>T</correct>]
[<stderr>T</stderr>]
[<checker>T</checker>]
</test>
</tests>
<ttrows>
<ttrow id="N" name="S" must-fail="B" />
</ttrows>
<ttcells>
<ttcell row="N" column="N" status="O" time="N" real-time="N" />
</ttcells>
</testing-report>
*/
/* elements */
enum
{
TR_T_TESTING_REPORT = 1,
TR_T_TESTS,
TR_T_TEST,
TR_T_ARGS,
TR_T_INPUT,
TR_T_OUTPUT,
TR_T_CORRECT,
TR_T_STDERR,
TR_T_CHECKER,
TR_T_COMMENT,
TR_T_VALUER_COMMENT,
TR_T_VALUER_JUDGE_COMMENT,
TR_T_VALUER_ERRORS,
TR_T_HOST,
TR_T_CPU_MODEL,
TR_T_CPU_MHZ,
TR_T_ERRORS,
TR_T_TTROWS,
TR_T_TTROW,
TR_T_TTCELLS,
TR_T_TTCELL,
TR_T_COMPILER_OUTPUT,
TR_T_UUID,
TR_T_PROGRAM_STATS_STR,
TR_T_INTERACTOR_STATS_STR,
TR_T_CHECKER_STATS_STR,
TR_T_TEST_CHECKER,
TR_T_LAST_TAG,
};
enum
{
TR_A_RUN_ID = 1,
TR_A_JUDGE_ID,
TR_A_STATUS,
TR_A_SCORING,
TR_A_ARCHIVE_AVAILABLE,
TR_A_CORRECT_AVAILABLE,
TR_A_INFO_AVAILABLE,
TR_A_RUN_TESTS,
TR_A_VARIANT,
TR_A_ACCEPTING_MODE,
TR_A_FAILED_TEST,
TR_A_TESTS_PASSED,
TR_A_MAX_SCORE,
TR_A_SCORE,
TR_A_NUM,
TR_A_EXIT_CODE,
TR_A_TERM_SIGNAL,
TR_A_TIME,
TR_A_REAL_TIME,
TR_A_NOMINAL_SCORE,
TR_A_COMMENT,
TR_A_TEAM_COMMENT,
TR_A_CHECKER_COMMENT,
TR_A_OUTPUT_AVAILABLE,
TR_A_STDERR_AVAILABLE,
TR_A_CHECKER_OUTPUT_AVAILABLE,
TR_A_ARGS_TOO_LONG,
TR_A_INPUT_DIGEST,
TR_A_CORRECT_DIGEST,
TR_A_INFO_DIGEST,
TR_A_TIME_LIMIT_MS,
TR_A_REAL_TIME_LIMIT_MS,
TR_A_EXIT_COMMENT,
TR_A_MAX_MEMORY_USED,
TR_A_REAL_TIME_AVAILABLE,
TR_A_MAX_MEMORY_USED_AVAILABLE,
TR_A_MARKED_FLAG,
TR_A_TESTS_MODE,
TR_A_TT_ROW_COUNT,
TR_A_TT_COLUMN_COUNT,
TR_A_NAME,
TR_A_MUST_FAIL,
TR_A_ROW,
TR_A_COLUMN,
TR_A_VISIBILITY,
TR_A_USER_STATUS,
TR_A_USER_TESTS_PASSED,
TR_A_USER_SCORE,
TR_A_USER_MAX_SCORE,
TR_A_USER_RUN_TESTS,
TR_A_COMPILE_ERROR,
TR_A_CONTEST_ID,
TR_A_SIZE,
TR_A_TOO_BIG,
TR_A_ORIGINAL_SIZE,
TR_A_BASE64,
TR_A_HAS_USER,
TR_A_USER_NOMINAL_SCORE,
TR_A_CHECKER_TOKEN,
TR_A_JUDGE_UUID,
TR_A_MAX_RSS_AVAILABLE,
TR_A_SEPARATE_USER_SCORE,
TR_A_MAX_RSS,
TR_A_SUBMIT_ID,
TR_A_LAST_ATTR,
};
static const char * const elem_map[] =
{
[TR_T_TESTING_REPORT] = "testing-report",
[TR_T_TESTS] = "tests",
[TR_T_TEST] = "test",
[TR_T_ARGS] = "args",
[TR_T_INPUT] = "input",
[TR_T_OUTPUT] = "output",
[TR_T_CORRECT] = "correct",
[TR_T_STDERR] = "stderr",
[TR_T_CHECKER] = "checker",
[TR_T_COMMENT] = "comment",
[TR_T_VALUER_COMMENT] = "valuer-comment",
[TR_T_VALUER_JUDGE_COMMENT] = "valuer-judge-comment",
[TR_T_VALUER_ERRORS] = "valuer-errors",
[TR_T_HOST] = "host",
[TR_T_CPU_MODEL] = "cpu-model",
[TR_T_CPU_MHZ] = "cpu-mhz",
[TR_T_ERRORS] = "errors",
[TR_T_TTROWS] = "ttrows",
[TR_T_TTROW] = "ttrow",
[TR_T_TTCELLS] = "ttcells",
[TR_T_TTCELL] = "ttcell",
[TR_T_COMPILER_OUTPUT] = "compiler_output",
[TR_T_UUID] = "uuid",
[TR_T_PROGRAM_STATS_STR] = "program-stats-str",
[TR_T_INTERACTOR_STATS_STR] = "interactor-stats-str",
[TR_T_CHECKER_STATS_STR] = "checker-stats-str",
[TR_T_TEST_CHECKER] = "test-checker",
[TR_T_LAST_TAG] = 0,
};
static const char * const attr_map[] =
{
[TR_A_RUN_ID] = "run-id",
[TR_A_JUDGE_ID] = "judge-id",
[TR_A_STATUS] = "status",
[TR_A_SCORING] = "scoring",
[TR_A_ARCHIVE_AVAILABLE] = "archive-available",
[TR_A_CORRECT_AVAILABLE] = "correct-available",
[TR_A_INFO_AVAILABLE] = "info-available",
[TR_A_RUN_TESTS] = "run-tests",
[TR_A_VARIANT] = "variant",
[TR_A_ACCEPTING_MODE] = "accepting-mode",
[TR_A_FAILED_TEST] = "failed-test",
[TR_A_TESTS_PASSED] = "tests-passed",
[TR_A_SCORE] = "score",
[TR_A_MAX_SCORE] = "max-score",
[TR_A_NUM] = "num",
[TR_A_EXIT_CODE] = "exit-code",
[TR_A_TERM_SIGNAL] = "term-signal",
[TR_A_TIME] = "time",
[TR_A_REAL_TIME] = "real-time",
[TR_A_NOMINAL_SCORE] = "nominal-score",
[TR_A_COMMENT] = "comment",
[TR_A_TEAM_COMMENT] = "team-comment",
[TR_A_CHECKER_COMMENT] = "checker-comment",
[TR_A_OUTPUT_AVAILABLE] = "output-available",
[TR_A_STDERR_AVAILABLE] = "stderr-available",
[TR_A_CHECKER_OUTPUT_AVAILABLE] = "checker-output-available",
[TR_A_ARGS_TOO_LONG] = "args-too-long",
[TR_A_INPUT_DIGEST] = "input-digest",
[TR_A_CORRECT_DIGEST] = "correct-digest",
[TR_A_INFO_DIGEST] = "info-digest",
[TR_A_TIME_LIMIT_MS] = "time-limit-ms",
[TR_A_REAL_TIME_LIMIT_MS] = "real-time-limit-ms",
[TR_A_EXIT_COMMENT] = "exit-comment",
[TR_A_MAX_MEMORY_USED] = "max-memory-used",
[TR_A_REAL_TIME_AVAILABLE] = "real-time-available",
[TR_A_MAX_MEMORY_USED_AVAILABLE] = "max-memory-used-available",
[TR_A_MARKED_FLAG] = "marked-flag",
[TR_A_TESTS_MODE] = "tests-mode",
[TR_A_TT_ROW_COUNT] = "tt-row-count",
[TR_A_TT_COLUMN_COUNT] = "tt-column-count",
[TR_A_NAME] = "name",
[TR_A_MUST_FAIL] = "must-fail",
[TR_A_ROW] = "row",
[TR_A_COLUMN] = "column",
[TR_A_VISIBILITY] = "visibility",
[TR_A_USER_STATUS] = "user-status",
[TR_A_USER_TESTS_PASSED] = "user-tests-passed",
[TR_A_USER_SCORE] = "user-score",
[TR_A_USER_MAX_SCORE] = "user-max-score",
[TR_A_USER_RUN_TESTS] = "user-run-tests",
[TR_A_COMPILE_ERROR] = "compile-error",
[TR_A_CONTEST_ID] = "contest-id",
[TR_A_SIZE] = "size",
[TR_A_TOO_BIG] = "too-big",
[TR_A_ORIGINAL_SIZE] = "original-size",
[TR_A_BASE64] = "base64",
[TR_A_HAS_USER] = "has-user",
[TR_A_USER_NOMINAL_SCORE] = "user-nominal-score",
[TR_A_CHECKER_TOKEN] = "checker-token",
[TR_A_JUDGE_UUID] = "judge-uuid",
[TR_A_MAX_RSS_AVAILABLE] = "max-rss-available",
[TR_A_SEPARATE_USER_SCORE] = "separate-user-score",
[TR_A_MAX_RSS] = "max-rss",
[TR_A_SUBMIT_ID] = "submit-id",
[TR_A_LAST_ATTR] = 0,
};
static struct xml_parse_spec testing_report_parse_spec =
{
.elem_map = elem_map,
.attr_map = attr_map,
.elem_sizes = NULL,
.attr_sizes = NULL,
.default_elem = 0,
.default_attr = 0,
.elem_alloc = NULL,
.attr_alloc = NULL,
.elem_free = NULL,
.attr_free = NULL,
};
static int
parse_scoring(const unsigned char *str, int *px)
{
if (!str) return -1;
if (!strcasecmp(str, "ACM")) {
*px = SCORE_ACM;
} else if (!strcasecmp(str, "KIROV")) {
*px = SCORE_KIROV;
} else if (!strcasecmp(str, "OLYMPIAD")) {
*px = SCORE_OLYMPIAD;
} else if (!strcasecmp(str, "MOSCOW")) {
*px = SCORE_MOSCOW;
} else {
return -1;
}
return 0;
}
struct testing_report_test * testing_report_test_free(struct testing_report_test *p);
static int
parse_file(
struct xml_tree *t,
struct testing_report_file_content *fc)
{
long long size = -1;
int oversized = 0;
long long orig_size = -1;
int base64 = 0;
for (struct xml_attr *a = t->first; a; a = a->next) {
switch (a->tag) {
case TR_A_SIZE:
{
long long x = -1;
if (xml_attr_long_long(a, &x) < 0) goto failure;
if (x < 0) {
xml_err_attr_invalid(a);
goto failure;
}
size = x;
}
break;
case TR_A_TOO_BIG:
{
int x;
if (xml_attr_bool(a, &x) < 0) goto failure;
oversized = x;
}
break;
case TR_A_ORIGINAL_SIZE:
{
long long x = -1;
if (xml_attr_long_long(a, &x) < 0) goto failure;
if (x < 0) {
xml_err_attr_invalid(a);
goto failure;
}
orig_size = x;
}
break;
case TR_A_BASE64:
{
int x;
if (xml_attr_bool(a, &x) < 0) goto failure;
base64 = x;
}
break;
default:
xml_err_attr_not_allowed(t, a);
goto failure;
}
}
if (t->first_down) {
xml_err_nested_elems(t);
goto failure;
}
if (oversized) {
if (orig_size < 0) {
orig_size = 0;
}
fc->data = NULL;
fc->size = 0;
fc->is_too_big = oversized;
fc->orig_size = orig_size;
fc->is_base64 = 0;
} else {
if (size < 0) size = strlen(t->text);
fc->data = t->text; t->text = 0;
fc->size = size;
fc->is_too_big = 0;
fc->orig_size = -1;
fc->is_base64 = base64;
}
return 0;
failure:
return -1;
}
static int
parse_test(struct xml_tree *t, testing_report_xml_t r)
{
struct testing_report_test *p = 0, *q = 0;
struct xml_attr *a;
struct xml_tree *t2;
int x;
unsigned long ulx;
if (t->tag != TR_T_TEST) {
xml_err_elem_not_allowed(t);
return -1;
}
if (xml_empty_text(t) < 0) goto failure;
p = testing_report_test_alloc(-1, -1);
p->num = -1;
p->status = -1;
p->time = -1;
p->real_time = -1;
p->exit_code = -1;
p->term_signal = -1;
p->nominal_score = -1;
p->score = -1;
p->user_status = -1;
p->user_score = -1;
p->user_nominal_score = -1;
for (a = t->first; a; a = a->next) {
switch (a->tag) {
case TR_A_NUM:
if (xml_attr_int(a, &x) < 0) goto failure;
if (x <= 0 || x > r->run_tests) {
xml_err_attr_invalid(a);
goto failure;
}
p->num = x;
break;
case TR_A_STATUS:
if (!a->text || run_str_short_to_status(a->text, &x) < 0
|| !run_is_valid_test_status(x)) {
xml_err_attr_invalid(a);
goto failure;
}
p->status = x;
break;
case TR_A_USER_STATUS:
if (!a->text || run_str_short_to_status(a->text, &x) < 0) {
xml_err_attr_invalid(a);
goto failure;
}
p->user_status = x;
break;
case TR_A_TIME:
if (xml_attr_int(a, &x) < 0) goto failure;
if (x < 0) {
xml_err_attr_invalid(a);
goto failure;
}
p->time = x;
break;
case TR_A_REAL_TIME:
if (xml_attr_int(a, &x) < 0) goto failure;
if (x < 0) {
xml_err_attr_invalid(a);
goto failure;
}
p->real_time = x;
break;
case TR_A_MAX_MEMORY_USED:
ulx = 0;
if (xml_attr_ulong(a, &ulx) < 0) goto failure;
p->max_memory_used = ulx;
break;
case TR_A_MAX_RSS:
ulx = 0;
if (xml_attr_ulong(a, &ulx) < 0) goto failure;
p->max_rss = ulx;
break;
case TR_A_EXIT_CODE:
if (xml_attr_int(a, &x) < 0) goto failure;
if (x < 0) x = 255;
if (x < 0 || x > 255) {
xml_err_attr_invalid(a);
goto failure;
}
p->exit_code = x;
break;
case TR_A_TERM_SIGNAL:
if (xml_attr_int(a, &x) < 0) goto failure;
if (x <= 0 || x > 255) {
xml_err_attr_invalid(a);
goto failure;
}
p->term_signal = x;
break;
case TR_A_NOMINAL_SCORE:
if (xml_attr_int(a, &x) < 0) goto failure;
if (x < 0 || x > EJ_MAX_SCORE) {
xml_err_attr_invalid(a);
goto failure;
}
p->nominal_score = x;
break;
case TR_A_SCORE:
if (xml_attr_int(a, &x) < 0) goto failure;
if (x < 0 || x > EJ_MAX_SCORE) {
xml_err_attr_invalid(a);
goto failure;
}
p->score = x;
break;
case TR_A_USER_SCORE:
if (xml_attr_int(a, &x) < 0) goto failure;
if (x < 0 || x > EJ_MAX_SCORE) {
xml_err_attr_invalid(a);
goto failure;
}
p->user_score = x;
break;
case TR_A_USER_NOMINAL_SCORE:
if (xml_attr_int(a, &x) < 0) goto failure;
if (x < 0 || x > EJ_MAX_SCORE) {
xml_err_attr_invalid(a);
goto failure;
}
p->user_nominal_score = x;
break;
case TR_A_VISIBILITY:
x = test_visibility_parse(a->text);
if (x < 0 || x >= TV_LAST) {
xml_err_attr_invalid(a);
goto failure;
}
p->visibility = x;
break;
case TR_A_COMMENT:
p->comment = a->text;
a->text = 0;
break;
case TR_A_TEAM_COMMENT:
p->team_comment = a->text;
a->text = 0;
break;
case TR_A_CHECKER_COMMENT:
p->checker_comment = a->text;
a->text = 0;
break;
case TR_A_EXIT_COMMENT:
p->exit_comment = a->text;
a->text = 0;
break;
case TR_A_CHECKER_TOKEN:
p->checker_token = a->text;
a->text = NULL;
break;
case TR_A_OUTPUT_AVAILABLE:
if (xml_attr_bool(a, &x) < 0) goto failure;
p->output_available = x;
break;
case TR_A_STDERR_AVAILABLE:
if (xml_attr_bool(a, &x) < 0) goto failure;
p->stderr_available = x;
break;
case TR_A_CHECKER_OUTPUT_AVAILABLE:
if (xml_attr_bool(a, &x) < 0) goto failure;
p->checker_output_available = x;
break;
case TR_A_HAS_USER:
if (xml_attr_bool(a, &x) < 0) goto failure;
p->has_user = x;
break;
case TR_A_ARGS_TOO_LONG:
if (xml_attr_bool(a, &x) < 0) goto failure;
p->args_too_long = x;
break;
case TR_A_INPUT_DIGEST:
if (digest_from_ascii(DIGEST_SHA1, a->text, p->input_digest) < 0) {
xml_err_attr_invalid(a);
goto failure;
}
p->has_input_digest = 1;
break;
case TR_A_CORRECT_DIGEST:
if (digest_from_ascii(DIGEST_SHA1, a->text, p->correct_digest) < 0) {
xml_err_attr_invalid(a);
goto failure;
}
p->has_correct_digest = 1;
break;
case TR_A_INFO_DIGEST:
if (digest_from_ascii(DIGEST_SHA1, a->text, p->info_digest) < 0) {
xml_err_attr_invalid(a);
goto failure;
}
p->has_info_digest = 1;
break;
default:
xml_err_attr_not_allowed(t, a);
goto failure;
}
}
if (p->num < 0) {
xml_err_attr_undefined(t, TR_A_NUM);
goto failure;
}
if (p->status < 0) {
xml_err_attr_undefined(t, TR_A_STATUS);
goto failure;
}
if (r->tests[p->num - 1]) {
xml_err(t, "duplicated test %d", p->num);
goto failure;
}
q = r->tests[p->num - 1] = p;
p = 0;
for (t2 = t->first_down; t2; t2 = t2->right) {
switch (t2->tag) {
case TR_T_ARGS:
if (xml_leaf_elem(t2, &q->args, 1, 1) < 0) goto failure;
break;
case TR_T_PROGRAM_STATS_STR:
if (xml_leaf_elem(t2, &q->program_stats_str, 1, 1) < 0) goto failure;
break;
case TR_T_INTERACTOR_STATS_STR:
if (xml_leaf_elem(t2, &q->interactor_stats_str, 1, 1) < 0) goto failure;
break;
case TR_T_CHECKER_STATS_STR:
if (xml_leaf_elem(t2, &q->checker_stats_str, 1, 1) < 0) goto failure;
break;
case TR_T_INPUT:
if (parse_file(t2, &q->input) < 0) goto failure;
break;
case TR_T_OUTPUT:
if (parse_file(t2, &q->output) < 0) goto failure;
break;
case TR_T_CORRECT:
if (parse_file(t2, &q->correct) < 0) goto failure;
break;
case TR_T_STDERR:
if (parse_file(t2, &q->error) < 0) goto failure;
break;
case TR_T_CHECKER:
if (parse_file(t2, &q->checker) < 0) goto failure;
break;
case TR_T_TEST_CHECKER:
if (parse_file(t2, &q->test_checker) < 0) goto failure;
break;
default:
xml_err_elem_not_allowed(t2);
goto failure;
}
}
return 0;
failure:
testing_report_test_free(p);
return -1;
}
static int
parse_tests(struct xml_tree *t, testing_report_xml_t r)
{
struct xml_tree *p;
if (t->tag != TR_T_TESTS) {
xml_err_elem_not_allowed(t);
return -1;
}
if (t->first) {
xml_err_attrs(t);
return -1;
}
if (xml_empty_text(t) < 0) return -1;
for (p = t->first_down; p; p = p->right) {
if (parse_test(p, r) < 0) return -1;
}
return 0;
}
static int
parse_ttrow(struct xml_tree *t, testing_report_xml_t r)
{
struct xml_attr *a;
int x, row = -1, status = RUN_CHECK_FAILED, must_fail = 0;
int nominal_score = -1, score = -1;
unsigned char *name = 0;
if (t->tag != TR_T_TTROW) {
return xml_err_elem_not_allowed(t);
}
if (xml_empty_text(t) < 0) return -1;
if (t->first_down) {
return xml_err_nested_elems(t);
}
for (a = t->first; a; a = a->next) {
switch (a->tag) {
case TR_A_ROW:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x >= r->tt_row_count) return xml_err_attr_invalid(a);
row = x;
break;
case TR_A_NAME:
name = a->text;
a->text = 0;
break;
case TR_A_MUST_FAIL:
if (xml_attr_bool(a, &x) < 0) return -1;
must_fail = x;
break;
case TR_A_STATUS:
if (!a->text || run_str_short_to_status(a->text, &x) < 0)
return xml_err_attr_invalid(a);
status = x;
break;
case TR_A_NOMINAL_SCORE:
if (xml_attr_int(a, &x) < 0) return xml_err_attr_invalid(a);
if (x < 0 || x > EJ_MAX_SCORE) return xml_err_attr_invalid(a);
nominal_score = x;
break;
case TR_A_SCORE:
if (xml_attr_int(a, &x) < 0) return xml_err_attr_invalid(a);
if (x < 0 || x > EJ_MAX_SCORE) return xml_err_attr_invalid(a);
score = x;
break;
default:
return xml_err_attr_not_allowed(t, a);
}
}
if (row < 0) return xml_err_attr_undefined(t, TR_A_ROW);
if (!name) return xml_err_attr_undefined(t, TR_A_NAME);
r->tt_rows[row]->row = row;
r->tt_rows[row]->name = name;
r->tt_rows[row]->status = status;
r->tt_rows[row]->must_fail = must_fail;
r->tt_rows[row]->nominal_score = nominal_score;
r->tt_rows[row]->score = score;
return 0;
}
static int
parse_ttrows(struct xml_tree *t, testing_report_xml_t r)
{
struct xml_tree *p;
if (t->tag != TR_T_TTROWS) {
xml_err_elem_not_allowed(t);
return -1;
}
if (t->first) {
xml_err_attrs(t);
return -1;
}
if (xml_empty_text(t) < 0) return -1;
for (p = t->first_down; p; p = p->right) {
if (parse_ttrow(p, r) < 0) return -1;
}
return 0;
}
static int
parse_ttcell(struct xml_tree *t, testing_report_xml_t r)
{
struct xml_attr *a;
int row = -1, column = -1;
int status = RUN_CHECK_FAILED;
int time = -1, real_time = -1, x;
struct testing_report_cell *ttc = 0;
if (t->tag != TR_T_TTCELL) {
return xml_err_elem_not_allowed(t);
}
if (xml_empty_text(t) < 0) return -1;
if (t->first_down) {
return xml_err_nested_elems(t);
}
for (a = t->first; a; a = a->next) {
switch (a->tag) {
case TR_A_ROW:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x >= r->tt_row_count) return xml_err_attr_invalid(a);
row = x;
break;
case TR_A_COLUMN:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x >= r->tt_column_count) return xml_err_attr_invalid(a);
column = x;
break;
case TR_A_STATUS:
if (!a->text || run_str_short_to_status(a->text, &x) < 0)
return xml_err_attr_invalid(a);
status = x;
break;
case TR_A_TIME:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < -1) return xml_err_attr_invalid(a);
time = x;
break;
case TR_A_REAL_TIME:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < -1) return xml_err_attr_invalid(a);
real_time = x;
break;
default:
return xml_err_attr_not_allowed(t, a);
}
}
ttc = r->tt_cells[row][column];
ttc->row = row;
ttc->column = column;
ttc->status = status;
ttc->time = time;
ttc->real_time = real_time;
return 0;
}
static int
parse_ttcells(struct xml_tree *t, testing_report_xml_t r)
{
struct xml_tree *p;
if (t->tag != TR_T_TTCELLS) {
xml_err_elem_not_allowed(t);
return -1;
}
if (t->first) {
xml_err_attrs(t);
return -1;
}
if (xml_empty_text(t) < 0) return -1;
for (p = t->first_down; p; p = p->right) {
if (parse_ttcell(p, r) < 0) return -1;
}
return 0;
}
static int
parse_testing_report(struct xml_tree *t, testing_report_xml_t r)
{
struct xml_attr *a;
int x, was_tests = 0, was_ttrows = 0, was_ttcells = 0;
struct xml_attr *a_failed_test = 0, *a_score = 0;
struct xml_attr *a_max_score = 0;
struct xml_tree *t2;
int i, j;
if (t->tag != TR_T_TESTING_REPORT) {
xml_err_top_level(t, TR_T_TESTING_REPORT);
return -1;
}
if (xml_empty_text(t) < 0) return -1;
r->run_id = -1;
r->judge_id = -1;
r->status = -1;
r->scoring_system = -1;
r->archive_available = 0;
r->run_tests = -1;
r->variant = 0;
r->accepting_mode = 0;
r->failed_test = -1;
r->tests_passed = -1;
r->score = -1;
r->max_score = -1;
r->time_limit_ms = -1;
r->real_time_limit_ms = -1;
r->marked_flag = -1;
r->user_status = -1;
r->user_tests_passed = -1;
r->user_score = -1;
r->user_max_score = -1;
r->user_run_tests = -1;
for (a = t->first; a; a = a->next) {
switch (a->tag) {
case TR_A_CONTEST_ID:
if (xml_attr_int(a, &x) < 0) return -1;
if (x <= 0) {
xml_err_attr_invalid(a);
return -1;
}
r->contest_id = x;
break;
case TR_A_RUN_ID:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x > EJ_MAX_RUN_ID) {
xml_err_attr_invalid(a);
return -1;
}
r->run_id = x;
break;
case TR_A_SUBMIT_ID: {
long long v;
if (xml_attr_long_long(a, &v) < 0) return -1;
r->submit_id = v;
break;
}
case TR_A_JUDGE_ID:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x > EJ_MAX_JUDGE_ID) {
xml_err_attr_invalid(a);
return -1;
}
r->judge_id = x;
break;
case TR_A_STATUS:
if (!a->text || run_str_short_to_status(a->text, &x) < 0) {
xml_err_attr_invalid(a);
return -1;
}
r->status = x;
break;
case TR_A_USER_STATUS:
if (!a->text || run_str_short_to_status(a->text, &x) < 0) {
xml_err_attr_invalid(a);
return -1;
}
r->user_status = x;
break;
case TR_A_SCORING:
if (parse_scoring(a->text, &x) < 0) {
xml_err_attr_invalid(a);
return -1;
}
r->scoring_system = x;
break;
case TR_A_ARCHIVE_AVAILABLE:
if (xml_attr_bool(a, &x) < 0) return -1;
r->archive_available = x;
break;
case TR_A_CORRECT_AVAILABLE:
if (xml_attr_bool(a, &x) < 0) return -1;
r->correct_available = x;
break;
case TR_A_INFO_AVAILABLE:
if (xml_attr_bool(a, &x) < 0) return -1;
r->info_available = x;
break;
case TR_A_REAL_TIME_AVAILABLE:
if (xml_attr_bool(a, &x) < 0) return -1;
r->real_time_available = x;
break;
case TR_A_MAX_MEMORY_USED_AVAILABLE:
if (xml_attr_bool(a, &x) < 0) return -1;
r->max_memory_used_available = x;
break;
case TR_A_MAX_RSS_AVAILABLE:
if (xml_attr_bool(a, &x) < 0) return -1;
r->max_rss_available = x;
break;
case TR_A_SEPARATE_USER_SCORE:
if (xml_attr_bool(a, &x) < 0) return -1;
r->separate_user_score = x;
break;
case TR_A_COMPILE_ERROR:
if (xml_attr_bool(a, &x) < 0) return -1;
r->compile_error = x;
break;
/*
The total number of tests is allowed to be 0.
*/
case TR_A_RUN_TESTS:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x > EJ_MAX_TEST_NUM) {
xml_err_attr_invalid(a);
return -1;
}
r->run_tests = x;
break;
case TR_A_USER_RUN_TESTS:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x > EJ_MAX_TEST_NUM) {
xml_err_attr_invalid(a);
return -1;
}
r->user_run_tests = x;
break;
case TR_A_VARIANT:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x > EJ_MAX_VARIANT) {
xml_err_attr_invalid(a);
return -1;
}
r->variant = x;
break;
case TR_A_ACCEPTING_MODE:
if (xml_attr_bool(a, &x) < 0) return -1;
r->accepting_mode = x;
break;
/*
Tests are counted from 1.
*/
case TR_A_FAILED_TEST:
if (xml_attr_int(a, &x) < 0) return -1;
if (x <= 0 || x >= EJ_MAX_TEST_NUM) {
xml_err_attr_invalid(a);
return -1;
}
r->failed_test = x;
a_failed_test = a;
break;
case TR_A_TESTS_PASSED:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < -1 || x > EJ_MAX_TEST_NUM) {
xml_err_attr_invalid(a);
return -1;
}
if (x < 0) x = 0;
r->tests_passed = x;
break;
case TR_A_USER_TESTS_PASSED:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x > EJ_MAX_TEST_NUM) {
xml_err_attr_invalid(a);
return -1;
}
r->user_tests_passed = x;
break;
case TR_A_SCORE:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x > EJ_MAX_SCORE) {
xml_err_attr_invalid(a);
return -1;
}
r->score = x;
a_score = a;
break;
case TR_A_USER_SCORE:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x > EJ_MAX_SCORE) {
xml_err_attr_invalid(a);
return -1;
}
r->user_score = x;
break;
case TR_A_MAX_SCORE:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x > EJ_MAX_SCORE) {
xml_err_attr_invalid(a);
return -1;
}
r->max_score = x;
a_max_score = a;
break;
case TR_A_USER_MAX_SCORE:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0 || x > EJ_MAX_SCORE) {
xml_err_attr_invalid(a);
return -1;
}
r->user_max_score = x;
break;
case TR_A_TIME_LIMIT_MS:
if (xml_attr_int(a, &x) < 0) return -1;
r->time_limit_ms = x;
break;
case TR_A_REAL_TIME_LIMIT_MS:
if (xml_attr_int(a, &x) < 0) return -1;
r->real_time_limit_ms = x;
break;
case TR_A_MARKED_FLAG:
if (xml_attr_bool(a, &x) < 0) return -1;
r->marked_flag = x;
break;
case TR_A_TESTS_MODE:
if (xml_attr_bool(a, &x) < 0) return -1;
r->tests_mode = x;
break;
case TR_A_TT_ROW_COUNT:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0) {
xml_err_attr_invalid(a);
return -1;
}
r->tt_row_count = x;
break;
case TR_A_TT_COLUMN_COUNT:
if (xml_attr_int(a, &x) < 0) return -1;
if (x < 0) {
xml_err_attr_invalid(a);
return -1;
}
r->tt_column_count = x;
break;
case TR_A_JUDGE_UUID:
if (a->text && a->text[0]) {
if (ej_uuid_parse(a->text, &r->judge_uuid) < 0) {
xml_err_attr_invalid(a);
return -1;
}
}
break;
default:
xml_err_attr_not_allowed(t, a);
return -1;
}
}
if (r->tt_row_count < 0 || r->tt_column_count < 0) {
/* FIXME: report an error */
return -1;
}
if (r->tests_mode > 0) {
if (!r->tt_row_count || !r->tt_column_count) {
/* FIXME: report an error */
}
} else {
if (r->tt_row_count > 0 || r->tt_column_count > 0) {
/* FIXME: report an error */
return -1;
}
}
if (r->run_id < 0 && r->submit_id <= 0) {
xml_err_attr_undefined(t, TR_A_RUN_ID);
return -1;
}
if (r->judge_id < 0) {
xml_err_attr_undefined(t, TR_A_JUDGE_ID);
return -1;
}
if (r->status < 0) {
xml_err_attr_undefined(t, TR_A_STATUS);
return -1;
}
if (r->scoring_system < 0) {
xml_err_attr_undefined(t, TR_A_SCORING);
return -1;
}
if (r->run_tests < 0) {
xml_err_attr_undefined(t, TR_A_RUN_TESTS);
return -1;
}
if ((r->scoring_system == SCORE_ACM && r->status != RUN_OK)
|| (r->scoring_system == SCORE_OLYMPIAD && r->accepting_mode
&& r->status != RUN_ACCEPTED)) {
/*
if (r->failed_test < 0) {
xml_err_attr_undefined(t, TR_A_FAILED_TEST);
return -1;
}
*/
/*
if (r->tests_passed >= 0) {
xml_err_attr_not_allowed(t, a_tests_passed);
return -1;
}
*/
if (r->score >= 0) {
xml_err_attr_not_allowed(t, a_score);
return -1;
}
if (r->max_score >= 0) {
xml_err_attr_not_allowed(t, a_max_score);
return -1;
}
} else if ((r->scoring_system == SCORE_OLYMPIAD && !r->accepting_mode
&& r->status != RUN_OK)
|| (r->scoring_system == SCORE_KIROV && r->status != RUN_OK)) {
if (r->failed_test >= 0) {
xml_err_attr_not_allowed(t, a_failed_test);
return -1;
}
if (r->tests_passed < 0) {
xml_err_attr_undefined(t, TR_A_TESTS_PASSED);
return -1;
}
if (r->score < 0) {
xml_err_attr_undefined(t, TR_A_SCORE);
return -1;
}
if (r->max_score < 0) {
xml_err_attr_undefined(t, TR_A_MAX_SCORE);
return -1;
}
}
if (!t->first_down) {
xml_err_elem_undefined(t, TR_T_TESTS);
return -1;
}
/*
if (t->first_down->right) {
xml_err_elem_not_allowed(t->first_down->right);
return -1;
}
*/
if (r->run_tests > 0) {
XCALLOC(r->tests, r->run_tests);
}
if (r->tests_mode > 0) {
if (r->tt_row_count > 0 && r->tt_column_count > 0) {
XCALLOC(r->tt_rows, r->tt_row_count);
XCALLOC(r->tt_cells, r->tt_row_count);
for (i = 0; i < r->tt_row_count; ++i) {
struct testing_report_row *ttr = 0;
XCALLOC(ttr, 1);
r->tt_rows[i] = ttr;
ttr->row = i;
ttr->status = RUN_CHECK_FAILED;
ttr->nominal_score = -1;
ttr->score = -1;
XCALLOC(r->tt_cells[i], r->tt_column_count);
for (j = 0; j < r->tt_column_count; ++j) {
struct testing_report_cell *ttc = 0;
XCALLOC(ttc, 1);
r->tt_cells[i][j] = ttc;
ttc->row = i;
ttc->column = j;
ttc->status = RUN_CHECK_FAILED;
ttc->time = -1;
ttc->real_time = -1;
}
}
}
}
for (t2 = t->first_down; t2; t2 = t2->right) {
switch (t2->tag) {
case TR_T_COMMENT:
if (xml_leaf_elem(t2, &r->comment, 1, 1) < 0) return -1;
break;
case TR_T_VALUER_COMMENT:
if (xml_leaf_elem(t2, &r->valuer_comment, 1, 1) < 0) return -1;
break;
case TR_T_VALUER_JUDGE_COMMENT:
if (xml_leaf_elem(t2, &r->valuer_judge_comment, 1, 1) < 0) return -1;
break;
case TR_T_VALUER_ERRORS:
if (xml_leaf_elem(t2, &r->valuer_errors, 1, 1) < 0) return -1;
break;
case TR_T_HOST:
if (xml_leaf_elem(t2, &r->host, 1, 1) < 0) return -1;
break;
case TR_T_CPU_MODEL:
if (xml_leaf_elem(t2, &r->cpu_model, 1, 1) < 0) return -1;
break;
case TR_T_CPU_MHZ:
if (xml_leaf_elem(t2, &r->cpu_mhz, 1, 1) < 0) return -1;
break;
case TR_T_ERRORS:
if (xml_leaf_elem(t2, &r->errors, 1, 1) < 0) return -1;
break;
case TR_T_COMPILER_OUTPUT:
if (xml_leaf_elem(t2, &r->compiler_output, 1, 1) < 0) return -1;
break;
case TR_T_UUID:
{
unsigned char *uuid = NULL;
if (xml_leaf_elem(t2, &uuid, 1, 1) < 0) {
xfree(uuid);
return -1;
}
if (ej_uuid_parse(uuid, &r->uuid) < 0) {
xml_err(t2, "invalid value of <uuid>");
xfree(uuid);
return -1;
}
xfree(uuid);
}
break;
case TR_T_TESTS:
if (was_tests) {
xml_err(t2, "duplicated element <tests>");
return -1;
}
was_tests = 1;
if (parse_tests(t2, r) < 0) return -1;
break;
case TR_T_TTROWS:
if (was_ttrows) {
xml_err(t2, "duplicated element <ttrows>");
return -1;
}
was_ttrows = 1;
if (parse_ttrows(t2, r) < 0) return -1;
break;
case TR_T_TTCELLS:
if (was_ttcells) {
xml_err(t2, "duplicated element <ttcells>");
return -1;
}
was_ttcells = 1;
if (parse_ttcells(t2, r) < 0) return -1;
break;
default:
xml_err_elem_not_allowed(t2);
return -1;
}
}
return 0;
}
testing_report_xml_t
testing_report_parse_xml(const unsigned char *str)
{
struct xml_tree *t = 0;
testing_report_xml_t r = 0;
t = xml_build_tree_str(NULL, str, &testing_report_parse_spec);
if (!t) goto failure;
xml_err_path = "<string>";
xml_err_spec = &testing_report_parse_spec;
XCALLOC(r, 1);
if (parse_testing_report(t, r) < 0) goto failure;
xml_tree_free(t, &testing_report_parse_spec);
return r;
failure:
testing_report_free(r);
if (t) xml_tree_free(t, &testing_report_parse_spec);
return 0;
}
struct testing_report_test *
testing_report_test_free(struct testing_report_test *p)
{
if (!p) return 0;
xfree(p->comment); p->comment = 0;
xfree(p->team_comment); p->team_comment = 0;
xfree(p->checker_comment); p->checker_comment = 0;
xfree(p->exit_comment); p->exit_comment = 0;
xfree(p->checker_token); p->checker_token = NULL;
xfree(p->args); p->args = 0;
xfree(p->program_stats_str); p->program_stats_str = 0;
xfree(p->interactor_stats_str); p->interactor_stats_str = 0;
xfree(p->checker_stats_str); p->checker_stats_str = 0;
xfree(p->input.data); p->input.data = 0;
xfree(p->output.data); p->output.data = 0;
xfree(p->correct.data); p->correct.data = 0;
xfree(p->error.data); p->error.data = 0;
xfree(p->checker.data); p->checker.data = 0;
xfree(p->test_checker.data); p->test_checker.data = 0;
xfree(p);
return 0;
}
testing_report_xml_t
testing_report_free(testing_report_xml_t r)
{
int i, j;
if (!r) return 0;
if (r->tests) {
for (i = 0; i < r->run_tests; i++) {
r->tests[i] = testing_report_test_free(r->tests[i]);
}
xfree(r->tests);
r->run_tests = 0;
}
xfree(r->comment); r->comment = 0;
xfree(r->valuer_comment); r->valuer_comment = 0;
xfree(r->valuer_judge_comment); r->valuer_judge_comment = 0;
xfree(r->valuer_errors); r->valuer_errors = 0;
xfree(r->host); r->host = 0;
xfree(r->cpu_model); r->cpu_model = 0;
xfree(r->cpu_mhz); r->cpu_mhz = 0;
xfree(r->errors); r->errors = 0;
xfree(r->compiler_output); r->compiler_output = 0;
if (r->tt_rows) {
for (i = 0; i < r->tt_row_count; ++i) {
if (r->tt_rows[i]) {
xfree(r->tt_rows[i]->name);
xfree(r->tt_rows[i]);
}
}
xfree(r->tt_rows); r->tt_rows = 0;
}
if (r->tt_cells) {
for (i = 0; i < r->tt_row_count; ++i) {
if (r->tt_cells[i]) {
for (j = 0; j < r->tt_column_count; ++j) {
if (r->tt_cells[i][j]) {
// free the cell
xfree(r->tt_cells[i][j]);
}
}
xfree(r->tt_cells[i]);
}
}
xfree(r->tt_cells); r->tt_cells = 0;
}
xfree(r);
return 0;
}
struct testing_report_test *
testing_report_test_alloc(int num, int status)
{
struct testing_report_test *trt = calloc(1, sizeof(*trt));
trt->num = num;
trt->status = status;
trt->input.size = -1;
trt->input.orig_size = -1;
trt->output.size = -1;
trt->output.orig_size = -1;
trt->correct.size = -1;
trt->correct.orig_size = -1;
trt->error.size = -1;
trt->error.orig_size = -1;
trt->checker.size = -1;
trt->checker.orig_size = -1;
trt->test_checker.size = -1;
trt->test_checker.orig_size = -1;
return trt;
}
testing_report_xml_t
testing_report_alloc(int contest_id, int run_id, int judge_id, const ej_uuid_t *judge_uuid)
{
testing_report_xml_t r = 0;
XCALLOC(r, 1);
r->contest_id = contest_id;
r->run_id = run_id;
r->judge_id = judge_id;
r->status = RUN_CHECK_FAILED;
r->scoring_system = -1;
r->marked_flag = -1;
r->user_status = -1;
r->user_tests_passed = -1;
r->user_score = -1;
r->user_max_score = -1;
r->user_run_tests = -1;
if (judge_uuid) {
r->judge_uuid = *judge_uuid;
}
return r;
}
static const char * const scoring_system_strs[] =
{
[SCORE_ACM] = "ACM",
[SCORE_KIROV] = "KIROV",
[SCORE_OLYMPIAD] = "OLYMPIAD",
[SCORE_MOSCOW] = "MOSCOW",
};
static const unsigned char *
unparse_scoring_system(unsigned char *buf, size_t size, int val)
{
if (val >= SCORE_ACM && val < SCORE_TOTAL) return scoring_system_strs[val];
snprintf(buf, size, "scoring_%d", val);
return buf;
}
#define ARMOR(s) html_armor_buf(&ab, s)
static void
unparse_bool_attr(FILE *out, int attr_index, int value)
{
if (value > 0) {
fprintf(out, " %s=\"%s\"", attr_map[attr_index], xml_unparse_bool(value));
}
}
static void
unparse_bool_attr2(FILE *out, int attr_index, int value)
{
if (value >= 0) {
fprintf(out, " %s=\"%s\"", attr_map[attr_index], xml_unparse_bool(value));
}
}
static void
unparse_string_elem(
FILE *out,
struct html_armor_buffer *pab,
int elem_index,
const unsigned char *value)
{
if (value) {
fprintf(out, " <%s>%s</%s>\n", elem_map[elem_index],
html_armor_buf(pab, value), elem_map[elem_index]);
}
}
static void
unparse_string_attr(
FILE *out,
struct html_armor_buffer *pab,
int attr_index,
const unsigned char *value)
{
if (value && value[0]) {
fprintf(out, " %s=\"%s\"", attr_map[attr_index],
html_armor_buf(pab, value));
}
}
static void
unparse_digest_attr(
FILE *out,
int attr_index,
const void *raw)
{
const unsigned int *v = raw;
if (v[0] || v[1] || v[2] || v[3] || v[4]) {
fprintf(out, " %s=\"", attr_map[attr_index]);
digest_to_file(out, DIGEST_SHA1, raw);
fprintf(out, "\"");
}
}
static void
unparse_file_content(
FILE *out,
struct html_armor_buffer *pab,
int elem_index,
struct testing_report_file_content *fc)
{
if (fc->size >= 0) {
fprintf(out, " <%s", elem_map[elem_index]);
if (fc->is_too_big) {
unparse_bool_attr(out, TR_A_TOO_BIG, 1);
fprintf(out, " %s=\"%lld\"", attr_map[TR_A_ORIGINAL_SIZE], fc->orig_size);
fprintf(out, " />\n");
return;
}
fprintf(out, " %s=\"%lld\"", attr_map[TR_A_SIZE], fc->size);
unparse_bool_attr(out, TR_A_BASE64, fc->is_base64);
fprintf(out, ">");
if (fc->data) {
fprintf(out, "%s", html_armor_buf(pab, fc->data));
}
fprintf(out, "</%s>\n", elem_map[elem_index]);
}
}
void
testing_report_unparse_xml(
FILE *out,
int utf8_mode,
testing_report_xml_t r)
{
struct html_armor_buffer ab = HTML_ARMOR_INITIALIZER;
unsigned char buf1[128], buf2[128];
struct testing_report_test *t;
int i, j;
struct testing_report_row *ttr;
struct testing_report_cell *ttc;
const unsigned char *scoring = 0;
run_status_to_str_short(buf1, sizeof(buf1), r->status);
scoring = unparse_scoring_system(buf2, sizeof(buf2), r->scoring_system);
fprintf(out, "<%s %s=\"%d\" %s=\"%d\" %s=\"%s\" %s=\"%s\" %s=\"%d\"",
elem_map[TR_T_TESTING_REPORT],
attr_map[TR_A_RUN_ID], r->run_id,
attr_map[TR_A_JUDGE_ID], r->judge_id,
attr_map[TR_A_STATUS], buf1,
attr_map[TR_A_SCORING], scoring,
attr_map[TR_A_RUN_TESTS], r->run_tests);
if (r->submit_id > 0) {
fprintf(out, " %s=\"%lld\"", attr_map[TR_A_SUBMIT_ID],
(long long) r->submit_id);
}
if (ej_uuid_is_nonempty(r->judge_uuid)) {
fprintf(out, " %s=\"%s\"", attr_map[TR_A_JUDGE_UUID],
ej_uuid_unparse(&r->judge_uuid, NULL));
}
if (r->contest_id > 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_CONTEST_ID], r->contest_id);
}
unparse_bool_attr(out, TR_A_ARCHIVE_AVAILABLE, r->archive_available);
unparse_bool_attr(out, TR_A_REAL_TIME_AVAILABLE, r->real_time_available);
unparse_bool_attr(out, TR_A_MAX_MEMORY_USED_AVAILABLE,
r->max_memory_used_available);
unparse_bool_attr(out, TR_A_MAX_RSS_AVAILABLE, r->max_rss_available);
unparse_bool_attr(out, TR_A_CORRECT_AVAILABLE, r->correct_available);
unparse_bool_attr(out, TR_A_SEPARATE_USER_SCORE, r->separate_user_score);
unparse_bool_attr(out, TR_A_INFO_AVAILABLE, r->info_available);
unparse_bool_attr(out, TR_A_COMPILE_ERROR, r->compile_error);
if (r->variant > 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_VARIANT], r->variant);
}
unparse_bool_attr(out, TR_A_ACCEPTING_MODE, r->accepting_mode);
if (r->scoring_system == SCORE_OLYMPIAD && r->accepting_mode > 0
&& r->status != RUN_ACCEPTED) {
if (r->failed_test > 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_FAILED_TEST], r->failed_test);
}
} else if (r->scoring_system == SCORE_ACM && r->status != RUN_OK) {
if (r->failed_test > 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_FAILED_TEST], r->failed_test);
}
} else if (r->scoring_system == SCORE_OLYMPIAD && r->accepting_mode <= 0) {
fprintf(out, " %s=\"%d\" %s=\"%d\" %s=\"%d\"",
attr_map[TR_A_TESTS_PASSED], r->tests_passed,
attr_map[TR_A_SCORE], r->score,
attr_map[TR_A_MAX_SCORE], r->max_score);
} else if (r->scoring_system == SCORE_KIROV) {
fprintf(out, " %s=\"%d\" %s=\"%d\" %s=\"%d\"",
attr_map[TR_A_TESTS_PASSED], r->tests_passed,
attr_map[TR_A_SCORE], r->score,
attr_map[TR_A_MAX_SCORE], r->max_score);
} else if (r->scoring_system == SCORE_MOSCOW) {
if (r->status != RUN_OK) {
if (r->failed_test > 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_FAILED_TEST], r->failed_test);
}
}
fprintf(out, " %s=\"%d\" %s=\"%d\"",
attr_map[TR_A_SCORE], r->score,
attr_map[TR_A_MAX_SCORE], r->max_score);
}
if (r->time_limit_ms > 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_TIME_LIMIT_MS], r->time_limit_ms);
}
if (r->real_time_limit_ms > 0) {
fprintf(out, " %s=\"%d\"",
attr_map[TR_A_REAL_TIME_LIMIT_MS], r->real_time_limit_ms);
}
unparse_bool_attr2(out, TR_A_MARKED_FLAG, r->marked_flag);
unparse_bool_attr(out, TR_A_TESTS_MODE, r->tests_mode);
if (r->tests_mode > 0 && r->tt_row_count > 0 && r->tt_column_count > 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_TT_ROW_COUNT], r->tt_row_count);
fprintf(out, " %s=\"%d\"", attr_map[TR_A_TT_COLUMN_COUNT],
r->tt_column_count);
}
if (r->user_status >= 0) {
run_status_to_str_short(buf1, sizeof(buf1), r->user_status);
fprintf(out, " %s=\"%s\"", attr_map[TR_A_USER_STATUS], buf1);
}
if (r->user_tests_passed >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_USER_TESTS_PASSED], r->user_tests_passed);
}
if (r->user_score >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_USER_SCORE], r->user_score);
}
if (r->user_max_score >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_USER_MAX_SCORE],
r->user_max_score);
}
if (r->user_run_tests >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_USER_RUN_TESTS],
r->user_run_tests);
}
fprintf(out, " >\n");
if (r->uuid.v[0] || r->uuid.v[1] || r->uuid.v[2] || r->uuid.v[3]) {
fprintf(out, " <%s>%s</%s>\n", elem_map[TR_T_UUID], ej_uuid_unparse(&r->uuid, NULL), elem_map[TR_T_UUID]);
}
unparse_string_elem(out, &ab, TR_T_COMMENT, r->comment);
unparse_string_elem(out, &ab, TR_T_VALUER_COMMENT, r->valuer_comment);
unparse_string_elem(out, &ab, TR_T_VALUER_JUDGE_COMMENT,
r->valuer_judge_comment);
unparse_string_elem(out, &ab, TR_T_VALUER_ERRORS, r->valuer_errors);
unparse_string_elem(out, &ab, TR_T_HOST, r->host);
unparse_string_elem(out, &ab, TR_T_CPU_MODEL, r->cpu_model);
unparse_string_elem(out, &ab, TR_T_CPU_MHZ, r->cpu_mhz);
unparse_string_elem(out, &ab, TR_T_ERRORS, r->errors);
unparse_string_elem(out, &ab, TR_T_COMPILER_OUTPUT, r->compiler_output);
if (r->run_tests > 0 && r->tests) {
fprintf(out, " <%s>\n", elem_map[TR_T_TESTS]);
for (i = 0; i < r->run_tests; ++i) {
if (!(t = r->tests[i])) continue;
run_status_to_str_short(buf1, sizeof(buf1), t->status);
fprintf(out, " <%s %s=\"%d\" %s=\"%s\"",
elem_map[TR_T_TEST], attr_map[TR_A_NUM], i + 1,
attr_map[TR_A_STATUS], buf1);
if (t->term_signal > 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_TERM_SIGNAL], t->term_signal);
}
if (t->exit_code > 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_EXIT_CODE], t->exit_code);
}
if (t->time >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_TIME], t->time);
}
if (r->real_time_available > 0 && t->real_time >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_REAL_TIME], t->real_time);
}
if (r->max_memory_used_available > 0 && t->max_memory_used > 0) {
fprintf(out, " %s=\"%lu\"", attr_map[TR_A_MAX_MEMORY_USED],
t->max_memory_used);
}
if (r->max_rss_available > 0 && t->max_rss > 0) {
fprintf(out, " %s=\"%lld\"", attr_map[TR_A_MAX_RSS], t->max_rss);
}
if (r->scoring_system == SCORE_OLYMPIAD && r->accepting_mode <= 0) {
fprintf(out, " %s=\"%d\" %s=\"%d\"",
attr_map[TR_A_NOMINAL_SCORE], t->nominal_score,
attr_map[TR_A_SCORE], t->score);
} else if (r->scoring_system == SCORE_KIROV) {
fprintf(out, " %s=\"%d\" %s=\"%d\"",
attr_map[TR_A_NOMINAL_SCORE], t->nominal_score,
attr_map[TR_A_SCORE], t->score);
}
unparse_string_attr(out, &ab, TR_A_COMMENT, t->comment);
unparse_string_attr(out, &ab, TR_A_TEAM_COMMENT, t->team_comment);
unparse_string_attr(out, &ab, TR_A_EXIT_COMMENT, t->exit_comment);
unparse_string_attr(out, &ab, TR_A_CHECKER_COMMENT, t->checker_comment);
unparse_string_attr(out, &ab, TR_A_CHECKER_TOKEN, t->checker_token);
unparse_digest_attr(out, TR_A_INPUT_DIGEST, t->input_digest);
unparse_digest_attr(out, TR_A_CORRECT_DIGEST, t->correct_digest);
unparse_digest_attr(out, TR_A_INFO_DIGEST, t->info_digest);
unparse_bool_attr(out, TR_A_OUTPUT_AVAILABLE, t->output_available);
unparse_bool_attr(out, TR_A_STDERR_AVAILABLE, t->stderr_available);
unparse_bool_attr(out, TR_A_CHECKER_OUTPUT_AVAILABLE,
t->checker_output_available);
unparse_bool_attr(out, TR_A_ARGS_TOO_LONG, t->args_too_long);
if (t->visibility > 0) {
fprintf(out, " %s=\"%s\"", attr_map[TR_A_VISIBILITY], test_visibility_unparse(t->visibility));
}
if (t->has_user > 0) {
unparse_bool_attr(out, TR_A_HAS_USER, t->has_user);
if (t->user_status >= 0) {
run_status_to_str_short(buf1, sizeof(buf1), t->user_status);
fprintf(out, " %s=\"%s\"", attr_map[TR_A_USER_STATUS], buf1);
}
if (t->user_score >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_USER_SCORE], t->user_score);
}
if (t->user_nominal_score >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_USER_NOMINAL_SCORE], t->user_nominal_score);
}
}
fprintf(out, " >\n");
unparse_string_elem(out, &ab, TR_T_ARGS, t->args);
unparse_string_elem(out, &ab, TR_T_PROGRAM_STATS_STR, t->program_stats_str);
unparse_string_elem(out, &ab, TR_T_INTERACTOR_STATS_STR, t->interactor_stats_str);
unparse_string_elem(out, &ab, TR_T_CHECKER_STATS_STR, t->checker_stats_str);
unparse_file_content(out, &ab, TR_T_INPUT, &t->input);
unparse_file_content(out, &ab, TR_T_OUTPUT, &t->output);
unparse_file_content(out, &ab, TR_T_CORRECT, &t->correct);
unparse_file_content(out, &ab, TR_T_STDERR, &t->error);
unparse_file_content(out, &ab, TR_T_CHECKER, &t->checker);
unparse_file_content(out, &ab, TR_T_TEST_CHECKER, &t->test_checker);
fprintf(out, " </%s>\n", elem_map[TR_T_TEST]);
}
fprintf(out, " </%s>\n", elem_map[TR_T_TESTS]);
}
if (r->tt_row_count > 0 && r->tt_rows) {
fprintf(out, " <%s>\n", elem_map[TR_T_TTROWS]);
for (i = 0; i < r->tt_row_count; ++i) {
run_status_to_str_short(buf1, sizeof(buf1), r->tt_rows[i]->status);
if (!(ttr = r->tt_rows[i])) continue;
fprintf(out, " <%s %s=\"%d\" %s=\"%s\" %s=\"%s\" %s=\"%s\"",
elem_map[TR_T_TTROW], attr_map[TR_A_ROW], ttr->row,
attr_map[TR_A_NAME], ARMOR(ttr->name),
attr_map[TR_A_MUST_FAIL], xml_unparse_bool(ttr->must_fail),
attr_map[TR_A_STATUS], buf1);
if (ttr->nominal_score >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_NOMINAL_SCORE],
ttr->nominal_score);
}
if (ttr->score >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_SCORE], ttr->score);
}
fprintf(out, "/>\n");
}
fprintf(out, " </%s>\n", elem_map[TR_T_TTROWS]);
}
if (r->tt_row_count > 0 && r->tt_column_count > 0 && r->tt_cells) {
fprintf(out, " <%s>\n", elem_map[TR_T_TTCELLS]);
for (i = 0; i < r->tt_row_count; ++i) {
if (!r->tt_cells[i]) continue;
for (j = 0; j < r->tt_column_count; ++j) {
if (!(ttc = r->tt_cells[i][j])) continue;
run_status_to_str_short(buf1, sizeof(buf1), ttc->status);
fprintf(out, " <%s %s=\"%d\" %s=\"%d\" %s=\"%s\"",
elem_map[TR_T_TTCELL], attr_map[TR_A_ROW], i,
attr_map[TR_A_COLUMN], j,
attr_map[TR_A_STATUS], buf1);
if (ttc->time >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_TIME], ttc->time);
}
if (ttc->real_time >= 0) {
fprintf(out, " %s=\"%d\"", attr_map[TR_A_REAL_TIME], ttc->real_time);
}
fprintf (out, " />\n");
}
}
fprintf(out, " </%s>\n", elem_map[TR_T_TTCELLS]);
}
fprintf(out, "</%s>\n", elem_map[TR_T_TESTING_REPORT]);
html_armor_free(&ab);
}
void
testing_report_to_str(
char **pstr,
size_t *psize,
int utf8_mode,
testing_report_xml_t r)
{
FILE *f = open_memstream(pstr, psize);
fprintf(f, "Content-type: text/xml\n\n");
fprintf(f, "<?xml version=\"1.0\" encoding=\"%s\"?>\n", EJUDGE_CHARSET);
testing_report_unparse_xml(f, utf8_mode, r);
fclose(f); f = NULL;
}
int
testing_report_to_file(
const unsigned char *path,
int utf8_mode,
testing_report_xml_t r)
{
FILE *f = fopen(path, "w");
if (!f) {
return -1;
}
fprintf(f, "Content-type: text/xml\n\n");
fprintf(f, "<?xml version=\"1.0\" encoding=\"%s\"?>\n", EJUDGE_CHARSET);
testing_report_unparse_xml(f, utf8_mode, r);
if (ferror(f)) {
fclose(f);
return -1;
}
if (fflush(f) < 0) {
fclose(f);
return -1;
}
fclose(f); f = NULL;
return 0;
}
| gpl-2.0 |
reduz/chibitracker | gui/drivers/file_system_dirent.cpp | 1 | 3286 | //
// C++ Implementation: file_system_dirent
//
// Description:
//
//
// Author: Juan Linietsky <reduzio@gmail.com>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "file_system_dirent.h"
#ifdef POSIX_ENABLED
namespace GUI {
FileSystem *FileSystemDirent::create_fs() {
return GUI_NEW( FileSystemDirent );
}
bool FileSystemDirent::list_dir_begin() {
list_dir_end(); //close any previous dir opening!
// char real_current_dir_name[2048]; //is this enough?!
//getcwd(real_current_dir_name,2048);
//chdir(curent_path.utf8().get_data());
dir_stream = opendir(current_dir.utf8().get_data());
//chdir(real_current_dir_name);
if (!dir_stream)
return true; //error!
return false;
}
bool FileSystemDirent::file_exists(String p_file) {
struct stat flags;
if ((stat(p_file.utf8().get_data(),&flags)!=0))
return false;
if (S_ISDIR(flags.st_mode))
return false;
return true;
}
String FileSystemDirent::get_next(bool* p_is_dir) {
if (!dir_stream)
return "";
dirent *entry;
entry=readdir(dir_stream);
if (entry==NULL) {
list_dir_end();
return "";
}
//typedef struct stat Stat;
struct stat flags;
String fname;
if (fname.parse_utf8(entry->d_name))
fname=entry->d_name; //no utf8, maybe latin?
String f=current_dir+"/"+fname;
if (p_is_dir) {
if (stat(f.utf8().get_data(),&flags)==0) {
if (S_ISDIR(flags.st_mode)) {
*p_is_dir=true;
} else {
*p_is_dir=false;
}
} else {
*p_is_dir=false;
}
}
return fname;
}
void FileSystemDirent::list_dir_end() {
if (dir_stream)
closedir(dir_stream);
dir_stream=0;
}
int FileSystemDirent::get_drive_count() {
return 0;
}
String FileSystemDirent::get_drive(int p_drive) {
return "";
}
bool FileSystemDirent::make_dir(String p_dir) {
char real_current_dir_name[2048];
getcwd(real_current_dir_name,2048);
chdir(current_dir.utf8().get_data()); //ascii since this may be unicode or wathever the host os wants
bool success=(mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)==0);
chdir(real_current_dir_name);
return !success;
}
bool FileSystemDirent::change_dir(String p_dir) {
char real_current_dir_name[2048];
getcwd(real_current_dir_name,2048);
String prev_dir;
if (prev_dir.parse_utf8(real_current_dir_name))
prev_dir=real_current_dir_name; //no utf8, maybe latin?
chdir(current_dir.utf8().get_data()); //ascii since this may be unicode or wathever the host os wants
bool worked=(chdir(p_dir.utf8().get_data())==0); // we can only give this utf8
if (worked) {
getcwd(real_current_dir_name,2048);
if (current_dir.parse_utf8(real_current_dir_name))
current_dir=real_current_dir_name; //no utf8, maybe latin?
}
chdir(prev_dir.utf8().get_data());
return !worked;
}
String FileSystemDirent::get_current_dir() {
return current_dir;
}
void FileSystemDirent::set_default_filesystem() {
FileSystem::instance_func=&FileSystemDirent::create_fs;
}
FileSystemDirent::FileSystemDirent() {
dir_stream=0;
current_dir=".";
/* determine drive count */
change_dir(current_dir);
}
FileSystemDirent::~FileSystemDirent() {
list_dir_end();
}
}
#endif //posix_enabled
| gpl-2.0 |
KDE/kmuddy | kmuddy/main.cpp | 1 | 5308 | /***************************************************************************
main.cpp - main file for KMuddy
This file is a part of KMuddy distribution.
-------------------
begin : Fri Jun 14 12:37:51 CEST 2002
copyright : (C) 2002 by Tomas Mecir
email : kmuddy@kmuddy.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <KAboutData>
#include <klocale.h>
#include <QApplication>
#include <Kdelibs4ConfigMigrator>
#include <signal.h>
#include "kmuddy-version.h"
#include "kmuddy.h"
#include "cglobalsettings.h"
#define DESCRIPTION i18n("KMuddy is a MUD (Multi-User Dungeon) client by KDE with a variety of features.")
int main(int argc, char *argv[])
{
QApplication a (argc, argv);
KLocalizedString::setApplicationDomain("kmuddy");
QApplication::setApplicationDisplayName(i18n("KMuddy"));
KAboutData aboutData ("kmuddy", i18n("KMuddy"),
VERSION, DESCRIPTION, KAboutLicense::GPL,
i18n("(c) 2002-2018, Tomas Mecir"), QString(), "http://www.kmuddy.com/", "mecirt@gmail.com");
aboutData.addAuthor(i18n ("Tomas Mecir"),
i18n("Main developer and maintainer"), "mecirt@gmail.com");
aboutData.addCredit(i18n("Alex Bache"),
i18n("Many improvements in external scripting, internal script parser, output view and aliases/triggers, bugfixes"), "alex.bache@ntlworld.com");
aboutData.addCredit(i18n("Alsherok staff"),
i18n("for releasing AFKMud codebase, used to test MCCP/MSP"));
aboutData.addCredit(i18n("Andrea Cascio"),
i18n("SuSE RPMs, speed-walking improvements"), "hacksaw@triangolo.it");
aboutData.addCredit(i18n("Orion Elder"),
i18n("KMuddy forum, many ideas"), "orion@mudplanet.org");
aboutData.addCredit(i18n("Scott Monachello"),
i18n("Improvements in scripting, bugfixes"), "smonachello@yahoo.com");
aboutData.addCredit(i18n("Tyler Montbriand"),
i18n("Help with SDL support"), "tsm@accesscomm.ca");
aboutData.addCredit(i18n("Marco Mastroddi"),
i18n("Tick timers"), "marco.mastroddi@libero.it");
aboutData.addCredit (i18n("Henrikki Almusa"),
i18n("Commands to enable/disable groups"), "hena@iki.fi");
aboutData.addCredit(i18n("Drossos Stamboulakis"),
i18n("Selection improvements, full screen mode, cross-tab commands"), "adsluard@tpg.com.au");
aboutData.addCredit (i18n("Antonio J. Soler Sanchez"),
i18n("Spanish translation"), "redtony@telefonica.net");
aboutData.addCredit(i18n("lontau"),
i18n("Code to access KMuddy variables in Ruby"));
aboutData.addCredit (i18n("Magnus Lundborg"), i18n("Tab-expansion improvements"), "lundborg.magnus@gmail.com");
aboutData.addCredit(i18n("Vladimir Lazarenko"),
i18n("Many improvements. Hosting KMuddy CVS."), "vlad@lazarenko.net");
aboutData.addCredit(i18n("Stuart Henshall"),
i18n("Speed improvements."), "shenshall@blueyonder.co.uk");
aboutData.addCredit(i18n("Vadim Peretokin"),
i18n("Many improvements, website"), "vadimuses@gmail.com");
aboutData.addCredit(i18n("Heiko Koehn"),
i18n("Scripting improvements"), "koehnheiko@googlemail.com");
aboutData.addCredit(i18n("Robert Marmorstein"),
i18n("Systray icon support"), "robertandbeth@gmail.com");
KAboutData::setApplicationData (aboutData);
QApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("kmuddy")));
//alarm signal is sometimes causing KMuddy to terminate incorrectly
//when switching tabs using Alt+number - ignoring the signal, hoping
//for the best...
signal (SIGALRM, SIG_IGN);
// migrate settings from kde4
Kdelibs4ConfigMigrator migrator(QStringLiteral("kmuddy")); // the same name defined in the aboutData
// all the config files of your application
migrator.setConfigFiles(QStringList() << QStringLiteral("kmuddyrc"));
// list of KXMLGUI files used by your application
migrator.setUiFiles(QStringList() << QStringLiteral("kmuddymapperpart.rc"));
migrator.migrate();
KMuddy *kmuddy = nullptr;
/*
if (a.isSessionRestored ()) //session management
RESTORE(KMuddy); //DOES NOT WORK - we need kmuddy object in the program
//and I couldn't find a way to get to it after RESTORE (mainWidget
//didn't work (?))
else
{
*/
//normal startup
kmuddy = KMuddy::self();
/*
}
*/
//event handler for macro keys
a.installEventFilter (kmuddy);
kmuddy->show();
int retCode = a.exec ();
//Looks like KApplication deletes the widget using deleteLater, resulting
//in double deleting and problems. We therefore keep the object alive,
//hoping for the best
//delete kmuddy;
return retCode;
}
| gpl-2.0 |
modulexcite/frei0r | src/filter/cartoon/cartoon.cpp | 1 | 5319 | /* Cartoon filter
* main algorithm: (c) Copyright 2003 Dries Pruimboom <dries@irssystems.nl>
* further optimizations and frei0r port by Denis Rojo <jaromil@dyne.org>
*
* This source code is free software; you can redistribute it and/or
* modify it under the terms of the GNU Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* Please refer to the GNU Public License for more details.
*
* You should have received a copy of the GNU Public License along with
* this source code; if not, write to:
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* "$Id: cartoon.c 193 2004-06-01 11:00:25Z jaromil $"
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <frei0r.hpp>
#define RED(n) ((n>>16) & 0x000000FF)
#define GREEN(n) ((n>>8) & 0x000000FF)
#define BLUE(n) (n & 0x000000FF)
#define RGB(r,g,b) ((r<<16) + (g <<8) + (b))
#define BOOST(n) { \
if((*p = *p<<4)<0)>>n; \
*(p+1) = (*(p+1)<<4)>>n; \
*(p+2) = (*(p+2)<<4)>>n; }
/* setup some data to identify the plugin */
typedef struct {
int16_t w;
int16_t h;
uint8_t bpp;
uint32_t size;
} ScreenGeometry;
#define PIXELAT(x1,y1,s) ((s)+(x1)+ yprecal[y1])// (y1)*(geo->w)))
#define GMERROR(cc1,cc2) ((((RED(cc1)-RED(cc2))*(RED(cc1)-RED(cc2))) + \
((GREEN(cc1)-GREEN(cc2)) *(GREEN(cc1)-GREEN(cc2))) + \
((BLUE(cc1)-BLUE(cc2))*(BLUE(cc1)-BLUE(cc2)))))
class Cartoon: public frei0r::filter {
public:
f0r_param_double triplevel;
f0r_param_double diffspace;
Cartoon(unsigned int width, unsigned int height) {
int c;
register_param(triplevel, "triplevel", "level of trip: mapped to [0,1] asymptotical");
register_param(diffspace, "diffspace", "difference space: a value from 0 to 256 (mapped to [0,1])");
geo = new ScreenGeometry();
geo->w = width;
geo->h = height;
geo->size = width*height*sizeof(uint32_t);
if ( geo->size > 0 ) {
prePixBuffer = (int32_t*)malloc(geo->size);
conBuffer = (int32_t*)malloc(geo->size);
yprecal = (int*)malloc(geo->h*2*sizeof(int));
}
for(c=0;c<geo->h*2;c++)
yprecal[c] = geo->w*c;
for(c=0;c<256;c++)
powprecal[c] = c*c;
black = 0xFF000000;
triplevel = 1 - 1 / (1000 + 1);
diffspace = 1 / 256.;
}
~Cartoon() {
if ( geo->size > 0 ) {
free(prePixBuffer);
free(conBuffer);
free(yprecal);
}
delete geo;
}
virtual void update(double time,
uint32_t* out,
const uint32_t* in,
const uint32_t* in2,
const uint32_t* in3) {
// Cartoonify picture, do a form of edge detect
int x, y, t;
m_diffspace = diffspace * 256;
for (x=m_diffspace;x<geo->w-(1+m_diffspace);x++) {
for (y=m_diffspace;y<geo->h-(1+m_diffspace);y++) {
t = GetMaxContrast((int32_t*)in,x,y);
if (t > 1 / (1 - triplevel) - 1) {
// Make a border pixel
*(out+x+yprecal[y]) = black;
} else {
// Copy original color
*(out+x+yprecal[y]) = *(in+x+yprecal[y]);
FlattenColor((int32_t*)out+x+yprecal[y]);
}
}
}
}
private:
ScreenGeometry *geo;
/* buffer where to copy the screen
a pointer to it is being given back by process() */
int32_t *prePixBuffer;
int32_t *conBuffer;
int *yprecal;
uint16_t powprecal[256];
int32_t black;
int m_diffspace;
void FlattenColor(int32_t *c);
long GetMaxContrast(int32_t *src,int x,int y);
inline uint16_t gmerror(int32_t a, int32_t b);
};
/* the following should be faster on older CPUs
but runs slower than the GMERROR define on SSE units*/
inline uint16_t Cartoon::gmerror(int32_t a, int32_t b) {
register int dr, dg, db;
if((dr = RED(a) - RED(b)) < 0) dr = -dr;
if((dg = GREEN(a) - GREEN(b)) < 0) dg = -dg;
if((db = BLUE(a) - BLUE(b)) < 0) db = -db;
return(powprecal[dr]+powprecal[dg]+powprecal[db]);
}
void Cartoon::FlattenColor(int32_t *c) {
// (*c) = RGB(40*(RED(*c)/40),40*(GREEN(*c)/40),40*(BLUE(*c)/40)); */
uint8_t *p;
p = (uint8_t*)c;
(*p) = ((*p)>>5)<<5; p++;
(*p) = ((*p)>>5)<<5; p++;
(*p) = ((*p)>>5)<<5;
}
long Cartoon::GetMaxContrast(int32_t *src,int x,int y) {
int32_t c1,c2;
long error,max=0;
/* Assumes PrePixelModify has been run */
c1 = *PIXELAT(x-m_diffspace,y,src);
c2 = *PIXELAT(x+m_diffspace,y,src);
error = GMERROR(c1,c2);
if (error>max) max = error;
c1 = *PIXELAT(x,y-m_diffspace,src);
c2 = *PIXELAT(x,y+m_diffspace,src);
error = GMERROR(c1,c2);
if (error>max) max = error;
c1 = *PIXELAT(x-m_diffspace,y-m_diffspace,src);
c2 = *PIXELAT(x+m_diffspace,y+m_diffspace,src);
error = GMERROR(c1,c2);
if (error>max) max = error;
c1 = *PIXELAT(x+m_diffspace,y-m_diffspace,src);
c2 = *PIXELAT(x-m_diffspace,y+m_diffspace,src);
error = GMERROR(c1,c2);
if (error>max) max = error;
return(max);
}
frei0r::construct<Cartoon> plugin("Cartoon",
"Cartoonify video, do a form of edge detect",
"Dries Pruimboom, Jaromil",
2,2);
| gpl-2.0 |
tojo9900/vice | src/vdrive/vdrive-bam.c | 1 | 30513 | /*
* vdrive-bam.c - Virtual disk-drive implementation. BAM specific functions.
*
* Written by
* Andreas Boose <viceteam@t-online.de>
* Ingo Korb <ingo@akana.de>
*
* Based on old code by
* Teemu Rantanen <tvr@cs.hut.fi>
* Jarkko Sonninen <sonninen@lut.fi>
* Jouko Valta <jopi@stekt.oulu.fi>
* Olaf Seibert <rhialto@mbfys.kun.nl>
* Andre Fachat <a.fachat@physik.tu-chemnitz.de>
* Ettore Perazzoli <ettore@comm2000.it>
* pottendo <pottendo@gmx.net>
*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* 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 "vice.h"
#include <stdio.h>
#include <string.h>
#include "attach.h"
#include "cbmdos.h"
#include "diskconstants.h"
#include "diskimage.h"
#include "log.h"
#include "types.h"
#include "vdrive-bam.h"
#include "vdrive-command.h"
#include "vdrive.h"
/*
return Maximum distance from dir track to start/end of disk.
FIXME: partition support
*/
static int vdrive_calculate_disk_half(vdrive_t *vdrive)
{
switch (vdrive->image_format) {
case VDRIVE_IMAGE_FORMAT_1541:
case VDRIVE_IMAGE_FORMAT_2040:
return 17 + 5;
case VDRIVE_IMAGE_FORMAT_1571:
return 17 + 35;
case VDRIVE_IMAGE_FORMAT_1581:
return 40;
case VDRIVE_IMAGE_FORMAT_8050:
case VDRIVE_IMAGE_FORMAT_8250:
return 39;
case VDRIVE_IMAGE_FORMAT_4000:
return vdrive->num_tracks - 1;
default:
log_error(LOG_ERR,
"Unknown disk type %i. Cannot calculate disk half.", vdrive->image_format);
}
return -1;
}
/*
FIXME: partition support
*/
int vdrive_bam_alloc_first_free_sector(vdrive_t *vdrive,
unsigned int *track,
unsigned int *sector)
{
unsigned int s, d, max_tracks;
int t;
max_tracks = vdrive_calculate_disk_half(vdrive);
for (d = 0; d <= max_tracks; d++) {
int max_sector;
t = vdrive->Bam_Track - d;
#ifdef DEBUG_DRIVE
log_error(LOG_ERR, "Allocate first free sector on track %d.", t);
#endif
if (d && t >= 1) {
max_sector = vdrive_get_max_sectors(vdrive, t);
for (s = 0; s < (unsigned int)max_sector; s++) {
if (vdrive_bam_allocate_sector(vdrive, t, s)) {
*track = t;
*sector = s;
#ifdef DEBUG_DRIVE
log_error(LOG_ERR,
"Allocate first free sector: %d,%d.", t, s);
#endif
return 0;
}
}
}
t = vdrive->Bam_Track + d;
#ifdef DEBUG_DRIVE
log_error(LOG_ERR, "Allocate first free sector on track %d.", t);
#endif
if (t <= (int)(vdrive->num_tracks)) {
max_sector = vdrive_get_max_sectors(vdrive, t);
if (d) {
s = 0;
} else if (vdrive->image_format == VDRIVE_IMAGE_FORMAT_4000) {
s = 64; /* after root directory */
} else {
s = max_sector; /* skip bam track */
}
for (; s < (unsigned int)max_sector; s++) {
if (vdrive_bam_allocate_sector(vdrive, t, s)) {
*track = t;
*sector = s;
#ifdef DEBUG_DRIVE
log_error(LOG_ERR,
"Allocate first free sector: %d,%d.", t, s);
#endif
return 0;
}
}
}
}
return -1;
}
static int vdrive_bam_alloc_down(vdrive_t *vdrive,
unsigned int *track, unsigned int *sector)
{
unsigned int max_sector, t, s;
for (t = *track; t >= 1; t--) {
max_sector = vdrive_get_max_sectors(vdrive, t);
for (s = 0; s < max_sector; s++) {
if (vdrive_bam_allocate_sector(vdrive, t, s)) {
*track = t;
*sector = s;
return 0;
}
}
}
return -1;
}
static int vdrive_bam_alloc_up(vdrive_t *vdrive,
unsigned int *track, unsigned int *sector)
{
unsigned int max_sector, t, s;
for (t = *track; t <= vdrive->num_tracks; t++) {
max_sector = vdrive_get_max_sectors(vdrive, t);
for (s = 0; s < max_sector; s++) {
if (vdrive_bam_allocate_sector(vdrive, t, s)) {
*track = t;
*sector = s;
return 0;
}
}
}
return -1;
}
/*
FIXME: partition support
*/
int vdrive_bam_alloc_next_free_sector(vdrive_t *vdrive,
unsigned int *track,
unsigned int *sector)
{
unsigned int max_sector, i, t, s;
if (*track == vdrive->Bam_Track) {
if (vdrive->image_format != VDRIVE_IMAGE_FORMAT_4000 || *sector < 64) {
return -1;
}
}
/* Calculate the next sector for the current interleave */
s = *sector + vdrive_bam_get_interleave(vdrive->image_format);
t = *track;
max_sector = vdrive_get_max_sectors(vdrive, t);
if (s >= max_sector) {
s -= max_sector;
if (s != 0) {
s--;
}
}
/* Look for a sector on the same track */
for (i = 0; i < max_sector; i++) {
if (vdrive->image_format == VDRIVE_IMAGE_FORMAT_4000 && *track == vdrive->Bam_Track && s < 64) {
s = 64;
}
if (vdrive_bam_allocate_sector(vdrive, t, s)) {
*track = t;
*sector = s;
return 0;
}
s++;
if (s >= max_sector) {
s = 0;
}
}
if (vdrive->image_format == VDRIVE_IMAGE_FORMAT_4000 && *track == vdrive->Bam_Track) {
(*track)++;
}
/* Look for a sector on a close track */
*sector = 0;
if (*track < vdrive->Dir_Track) {
if (vdrive_bam_alloc_down(vdrive, track, sector) == 0) {
return 0;
}
*track = vdrive->Dir_Track - 1;
if (vdrive_bam_alloc_down(vdrive, track, sector) == 0) {
return 0;
}
*track = vdrive->Dir_Track + 1;
if (vdrive_bam_alloc_up(vdrive, track, sector) == 0) {
return 0;
}
} else {
if (vdrive_bam_alloc_up(vdrive, track, sector) == 0) {
return 0;
}
*track = vdrive->Dir_Track + 1;
if (vdrive_bam_alloc_up(vdrive, track, sector) == 0) {
return 0;
}
*track = vdrive->Dir_Track - 1;
if (vdrive_bam_alloc_down(vdrive, track, sector) == 0) {
return 0;
}
}
return -1;
}
static void vdrive_bam_set(uint8_t *bamp, unsigned int sector)
{
bamp[1 + sector / 8] |= (1 << (sector % 8));
return;
}
static void vdrive_bam_clr(uint8_t *bamp, unsigned int sector)
{
bamp[1 + sector / 8] &= ~(1 << (sector % 8));
return;
}
int vdrive_bam_isset(uint8_t *bamp, unsigned int sector)
{
return bamp[1 + sector / 8] & (1 << (sector % 8));
}
int vdrive_bam_allocate_chain(vdrive_t *vdrive, unsigned int t, unsigned int s)
{
uint8_t tmp[256];
int rc;
while (t) {
/* Check for illegal track or sector. */
if (disk_image_check_sector(vdrive->image, t, s) < 0) {
vdrive_command_set_error(vdrive, CBMDOS_IPE_ILLEGAL_TRACK_OR_SECTOR,
s, t);
return CBMDOS_IPE_ILLEGAL_TRACK_OR_SECTOR;
}
if (!vdrive_bam_allocate_sector(vdrive, t, s)) {
/* The real drive does not seem to catch this error. */
vdrive_command_set_error(vdrive, CBMDOS_IPE_NO_BLOCK, s, t);
return CBMDOS_IPE_NO_BLOCK;
}
rc = vdrive_read_sector(vdrive, tmp, t, s);
if (rc > 0) {
return rc;
}
if (rc < 0) {
return CBMDOS_IPE_NOT_READY;
}
t = (int)tmp[0];
s = (int)tmp[1];
}
return CBMDOS_IPE_OK;
}
/** \brief Get pointer to the BAM entry for \a track in \a vdrive's image
*
* A CBMDOS BAM entry consists of a single byte indication the number of free
* sectors (unreliable since there's a lot of disks out there which set this
* to 0 to get a "0 blocks free."), followed by a bitmap of free/used sectors.
* The size of the bitmap depends on the image type, 1541 and 1571 have three
* bytes (enough for 21 sectors), while 1581 has 5 bytes (40 sectors).
*
* \param[in] vdrive vdrive object
* \param[in] track track number
*
* \return pointer to BAM entry
*
*( FIXME: partition support
*/
uint8_t *vdrive_bam_get_track_entry(vdrive_t *vdrive, unsigned int track)
{
uint8_t *bamp = NULL;
uint8_t *bam = vdrive->bam;
if (track == 0) {
log_error(LOG_ERR, "invalid track number: 0");
return NULL;
}
switch (vdrive->image_format) {
case VDRIVE_IMAGE_FORMAT_1541:
case VDRIVE_IMAGE_FORMAT_2040:
bamp = (track <= NUM_TRACKS_1541) ?
&bam[BAM_BIT_MAP + 4 * (track - 1)] :
&bam[BAM_EXT_BIT_MAP_1541 + 4 * (track - NUM_TRACKS_1541 - 1)];
break;
case VDRIVE_IMAGE_FORMAT_1571:
bamp = (track <= NUM_TRACKS_1571 / 2) ?
&bam[BAM_BIT_MAP + 4 * (track - 1)] :
&bam[0x100 + 3 * (track - NUM_TRACKS_1571 / 2 - 1) - 1];
break;
case VDRIVE_IMAGE_FORMAT_1581:
bamp = (track <= BAM_TRACK_1581) ?
&bam[0x100 + BAM_BIT_MAP_1581 + 6 * (track - 1)] :
&bam[0x200 + BAM_BIT_MAP_1581 + 6 *
(track - BAM_TRACK_1581 - 1)];
break;
case VDRIVE_IMAGE_FORMAT_8050:
{
int i;
for (i = 1; i < 3; i++) {
if (track >= bam[(i * 0x100) + 4] && track < bam[(i * 0x100) + 5]) {
bamp = &bam[(i * 0x100) + BAM_BIT_MAP_8050 + 5 * (track - bam[(i * 0x100) + 4])];
break;
}
}
}
break;
case VDRIVE_IMAGE_FORMAT_8250:
{
int i;
for (i = 1; i < 5; i++) {
if (track >= bam[(i * 0x100) + 4] && track < bam[(i * 0x100) + 5]) {
bamp = &bam[(i * 0x100) + BAM_BIT_MAP_8050 + 5 * (track - bam[(i * 0x100) + 4])];
break;
}
}
}
break;
case VDRIVE_IMAGE_FORMAT_4000:
bamp = &bam[0x100 + BAM_BIT_MAP_4000 + 32 * (track - 1) - 1];
break;
default:
log_error(LOG_ERR, "Unknown disk type %i. Cannot calculate BAM track.", vdrive->image_format);
}
return bamp;
}
static void vdrive_bam_sector_free(vdrive_t *vdrive, uint8_t *bamp,
unsigned int track, int add)
{
switch (vdrive->image_format) {
case VDRIVE_IMAGE_FORMAT_1541:
case VDRIVE_IMAGE_FORMAT_2040:
case VDRIVE_IMAGE_FORMAT_1581:
case VDRIVE_IMAGE_FORMAT_8050:
case VDRIVE_IMAGE_FORMAT_8250:
*bamp += add;
break;
case VDRIVE_IMAGE_FORMAT_1571:
if (track <= NUM_TRACKS_1571 / 2) {
*bamp += add;
} else {
vdrive->bam[BAM_EXT_BIT_MAP_1571 + track - NUM_TRACKS_1571 / 2 - 1] += add;
}
break;
case VDRIVE_IMAGE_FORMAT_4000:
break;
default:
log_error(LOG_ERR, "Unknown disk type %i. Cannot find free sector.", vdrive->image_format);
}
}
int vdrive_bam_allocate_sector(vdrive_t *vdrive,
unsigned int track, unsigned int sector)
{
uint8_t *bamp;
/* Tracks > 70 don't go into the (regular) BAM on 1571 */
if ((track > NUM_TRACKS_1571) && (vdrive->image_format == VDRIVE_IMAGE_FORMAT_1571)) {
return 0;
}
if (vdrive->image_format == VDRIVE_IMAGE_FORMAT_4000) {
sector ^= 7;
}
bamp = vdrive_bam_get_track_entry(vdrive, track);
if (vdrive_bam_isset(bamp, sector)) {
vdrive_bam_sector_free(vdrive, bamp, track, -1);
vdrive_bam_clr(bamp, sector);
return 1;
}
return 0;
}
int vdrive_bam_free_sector(vdrive_t *vdrive, unsigned int track,
unsigned int sector)
{
uint8_t *bamp;
/* Tracks > 70 don't go into the (regular) BAM on 1571 */
if ((track > NUM_TRACKS_1571) && (vdrive->image_format == VDRIVE_IMAGE_FORMAT_1571)) {
return 0;
}
if (vdrive->image_format == VDRIVE_IMAGE_FORMAT_4000) {
sector ^= 7;
}
bamp = vdrive_bam_get_track_entry(vdrive, track);
if (!(vdrive_bam_isset(bamp, sector))) {
vdrive_bam_set(bamp, sector);
vdrive_bam_sector_free(vdrive, bamp, track, 1);
return 1;
}
return 0;
}
void vdrive_bam_clear_all(vdrive_t *vdrive)
{
uint8_t *bam = vdrive->bam;
switch (vdrive->image_format) {
case VDRIVE_IMAGE_FORMAT_1541:
memset(bam + BAM_EXT_BIT_MAP_1541, 0, 4 * 5);
/* fallthrough */
case VDRIVE_IMAGE_FORMAT_2040:
memset(bam + BAM_BIT_MAP, 0, 4 * NUM_TRACKS_1541);
break;
case VDRIVE_IMAGE_FORMAT_1571:
memset(bam + BAM_BIT_MAP, 0, 4 * NUM_TRACKS_1571 / 2);
memset(bam + BAM_EXT_BIT_MAP_1571, 0, NUM_TRACKS_1571 / 2);
memset(bam + 0x100, 0, 3 * NUM_TRACKS_1571 / 2);
break;
case VDRIVE_IMAGE_FORMAT_1581:
memset(bam + 0x100 + BAM_BIT_MAP_1581, 0, 6 * NUM_TRACKS_1581 / 2);
memset(bam + 0x200 + BAM_BIT_MAP_1581, 0, 6 * NUM_TRACKS_1581 / 2);
break;
case VDRIVE_IMAGE_FORMAT_8050:
memset(bam + 0x100 + BAM_BIT_MAP_8050, 0, 0x100 - BAM_BIT_MAP_8050);
memset(bam + 0x200 + BAM_BIT_MAP_8050, 0, 0x100 - BAM_BIT_MAP_8050);
break;
case VDRIVE_IMAGE_FORMAT_8250:
memset(bam + 0x100 + BAM_BIT_MAP_8250, 0, 0x100 - BAM_BIT_MAP_8250);
memset(bam + 0x200 + BAM_BIT_MAP_8250, 0, 0x100 - BAM_BIT_MAP_8250);
memset(bam + 0x300 + BAM_BIT_MAP_8250, 0, 0x100 - BAM_BIT_MAP_8250);
memset(bam + 0x400 + BAM_BIT_MAP_8250, 0, 0x100 - BAM_BIT_MAP_8250);
break;
case VDRIVE_IMAGE_FORMAT_4000:
memset(bam + 0x100 + BAM_BIT_MAP_4000, 255, 255 * 32);
break;
default:
log_error(LOG_ERR,
"Unknown disk type %i. Cannot clear BAM.", vdrive->image_format);
}
}
/* Should be removed some day. */
static int mystrncpy(uint8_t *d, uint8_t *s, int n)
{
while (n-- && *s) {
*d++ = *s++;
}
return (n);
}
void vdrive_bam_create_empty_bam(vdrive_t *vdrive, const char *name, uint8_t *id)
{
/* Create Disk Format for 1541/1571/1581/2040/4000 disks. */
memset(vdrive->bam, 0, vdrive->bam_size);
if (vdrive->image_format != VDRIVE_IMAGE_FORMAT_8050
&& vdrive->image_format != VDRIVE_IMAGE_FORMAT_8250) {
vdrive->bam[0] = vdrive->Dir_Track;
vdrive->bam[1] = vdrive->Dir_Sector;
/* position 2 will be overwritten later for 2040/1581/4000 */
vdrive->bam[2] = 65;
if (vdrive->image_format == VDRIVE_IMAGE_FORMAT_1571) {
vdrive->bam[3] = 0x80;
}
memset(vdrive->bam + vdrive->bam_name, 0xa0,
(vdrive->image_format == VDRIVE_IMAGE_FORMAT_1581
|| vdrive->image_format == VDRIVE_IMAGE_FORMAT_4000) ? 25 : 27);
mystrncpy(vdrive->bam + vdrive->bam_name, (uint8_t *)name, 16);
mystrncpy(vdrive->bam + vdrive->bam_id, id, 2);
}
switch (vdrive->image_format) {
case VDRIVE_IMAGE_FORMAT_2040:
vdrive->bam[0x02] = 0x01;
vdrive->bam[0xa4] = 0x20;
vdrive->bam[0xa5] = 0x20;
break;
case VDRIVE_IMAGE_FORMAT_1541:
case VDRIVE_IMAGE_FORMAT_1571:
vdrive->bam[BAM_VERSION_1541] = 50;
vdrive->bam[BAM_VERSION_1541 + 1] = 65;
break;
case VDRIVE_IMAGE_FORMAT_1581:
vdrive->bam[0x02] = 68;
/* Setup BAM linker. */
vdrive->bam[0x100] = vdrive->Bam_Track;
vdrive->bam[0x100 + 1] = 2;
vdrive->bam[0x200] = 0;
vdrive->bam[0x200 + 1] = 0xff;
/* Setup BAM version. */
vdrive->bam[BAM_VERSION_1581] = 51;
vdrive->bam[BAM_VERSION_1581 + 1] = 68;
vdrive->bam[0x100 + 2] = 68;
vdrive->bam[0x100 + 3] = 0xbb;
vdrive->bam[0x100 + 4] = id[0];
vdrive->bam[0x100 + 5] = id[1];
vdrive->bam[0x100 + 6] = 0xc0;
vdrive->bam[0x200 + 2] = 68;
vdrive->bam[0x200 + 3] = 0xbb;
vdrive->bam[0x200 + 4] = id[0];
vdrive->bam[0x200 + 5] = id[1];
vdrive->bam[0x200 + 6] = 0xc0;
break;
case VDRIVE_IMAGE_FORMAT_8050:
case VDRIVE_IMAGE_FORMAT_8250:
/* the first BAM block with the disk name is at 39/0, but it
points to the first bitmap BAM block at 38/0 ...
Only the last BAM block at 38/3 resp. 38/9 points to the
first dir block at 39/1 */
vdrive->bam[0] = 38;
vdrive->bam[1] = 0;
vdrive->bam[2] = 67;
/* byte 3-5 unused */
/* bytes 6- disk name + id + version */
memset(vdrive->bam + vdrive->bam_name, 0xa0, 27);
mystrncpy(vdrive->bam + vdrive->bam_name, (uint8_t *)name, 16);
mystrncpy(vdrive->bam + vdrive->bam_id, id, 2);
vdrive->bam[BAM_VERSION_8050] = 50;
vdrive->bam[BAM_VERSION_8050 + 1] = 67;
/* rest of first block unused */
/* first bitmap block at 38/0 */
vdrive->bam[0x100] = 38;
vdrive->bam[0x100 + 1] = 3;
vdrive->bam[0x100 + 2] = 67;
vdrive->bam[0x100 + 4] = 1; /* In this block from track ... */
vdrive->bam[0x100 + 5] = 51; /* till excluding track ... */
if (vdrive->image_format == VDRIVE_IMAGE_FORMAT_8050) {
/* second bitmap block at 38/3 */
vdrive->bam[0x200] = 39;
vdrive->bam[0x200 + 1] = 1;
vdrive->bam[0x200 + 2] = 67;
vdrive->bam[0x200 + 4] = 51; /* In this block from track ... */
vdrive->bam[0x200 + 5] = 78; /* till excluding track ... */
} else
if (vdrive->image_format == VDRIVE_IMAGE_FORMAT_8250) {
/* second bitmap block at 38/3 */
vdrive->bam[0x200] = 38;
vdrive->bam[0x200 + 1] = 6;
vdrive->bam[0x200 + 2] = 67;
vdrive->bam[0x200 + 4] = 51; /* In this block from track ... */
vdrive->bam[0x200 + 5] = 101; /* till excluding track ... */
/* third bitmap block at 38/6 */
vdrive->bam[0x300] = 38;
vdrive->bam[0x300 + 1] = 9;
vdrive->bam[0x300 + 2] = 67;
vdrive->bam[0x300 + 4] = 101; /* In this block from track ... */
vdrive->bam[0x300 + 5] = 151; /* till excluding track ... */
/* fourth bitmap block at 38/9 */
vdrive->bam[0x400] = 39;
vdrive->bam[0x400 + 1] = 1;
vdrive->bam[0x400 + 2] = 67;
vdrive->bam[0x400 + 4] = 151; /* In this block from track ... */
vdrive->bam[0x400 + 5] = 155; /* till excluding track ... */
}
break;
case VDRIVE_IMAGE_FORMAT_4000:
vdrive->bam[0x02] = 72;
/* Setup BAM version. */
vdrive->bam[BAM_VERSION_4000] = 49;
vdrive->bam[BAM_VERSION_4000 + 1] = 72;
vdrive->bam[0x20] = vdrive->Bam_Track;
vdrive->bam[0x21] = vdrive->Bam_Sector;
vdrive->bam[0x100 + 2] = 72;
vdrive->bam[0x100 + 3] = ~72;
vdrive->bam[0x100 + 4] = id[0];
vdrive->bam[0x100 + 5] = id[1];
vdrive->bam[0x100 + 6] = 0xc0;
vdrive->bam[0x100 + 8] = vdrive->num_tracks;
break;
default:
log_error(LOG_ERR,
"Unknown disk type %i. Cannot create BAM.",
vdrive->image_format);
}
return;
}
int vdrive_bam_get_disk_id(unsigned int unit, uint8_t *id)
{
vdrive_t *vdrive;
vdrive = file_system_get_vdrive(unit);
if (vdrive == NULL || id == NULL || vdrive->bam == NULL) {
return -1;
}
memcpy(id, vdrive->bam + vdrive->bam_id, 2);
return 0;
}
int vdrive_bam_set_disk_id(unsigned int unit, uint8_t *id)
{
vdrive_t *vdrive;
vdrive = file_system_get_vdrive(unit);
if (vdrive == NULL || id == NULL || vdrive->bam == NULL) {
return -1;
}
memcpy(vdrive->bam + vdrive->bam_id, id, 2);
return 0;
}
int vdrive_bam_get_interleave(unsigned int type)
{
/* Note: Values for 2040/8050/8250 determined empirically */
switch (type) {
case VDRIVE_IMAGE_FORMAT_1541:
case VDRIVE_IMAGE_FORMAT_2040:
return 10;
case VDRIVE_IMAGE_FORMAT_1571:
return 6;
case VDRIVE_IMAGE_FORMAT_1581:
return 1;
case VDRIVE_IMAGE_FORMAT_8050:
return 6;
case VDRIVE_IMAGE_FORMAT_8250:
return 7;
case VDRIVE_IMAGE_FORMAT_4000:
return 1;
default:
log_error(LOG_ERR, "Unknown disk type %i. Using interleave 10.", type);
return 10;
}
}
/* ------------------------------------------------------------------------- */
/*
* Load/Store BAM Image.
*/
/*
FIXME: partition support
*/
/* probably we should make a list with BAM blocks for each drive type... (AF)*/
int vdrive_bam_read_bam(vdrive_t *vdrive)
{
int err = -1, i;
switch (vdrive->image_format) {
case VDRIVE_IMAGE_FORMAT_2040:
case VDRIVE_IMAGE_FORMAT_1541:
err = vdrive_read_sector(vdrive, vdrive->bam, BAM_TRACK_1541, BAM_SECTOR_1541);
break;
case VDRIVE_IMAGE_FORMAT_1571:
err = vdrive_read_sector(vdrive, vdrive->bam, BAM_TRACK_1571, BAM_SECTOR_1571);
if (err != 0) {
break;
}
err = vdrive_read_sector(vdrive, vdrive->bam + 256, BAM_TRACK_1571 + 35, BAM_SECTOR_1571);
break;
case VDRIVE_IMAGE_FORMAT_1581:
err = vdrive_read_sector(vdrive, vdrive->bam, BAM_TRACK_1581, BAM_SECTOR_1581);
if (err != 0) {
break;
}
err = vdrive_read_sector(vdrive, vdrive->bam + 256, BAM_TRACK_1581, BAM_SECTOR_1581 + 1);
if (err != 0) {
break;
}
err = vdrive_read_sector(vdrive, vdrive->bam + 512, BAM_TRACK_1581, BAM_SECTOR_1581 + 2);
break;
case VDRIVE_IMAGE_FORMAT_8050:
case VDRIVE_IMAGE_FORMAT_8250:
err = vdrive_read_sector(vdrive, vdrive->bam, BAM_TRACK_8050, BAM_SECTOR_8050);
if (err != 0) {
break;
}
err = vdrive_read_sector(vdrive, vdrive->bam + 256, BAM_TRACK_8050 - 1, BAM_SECTOR_8050);
if (err != 0) {
break;
}
err = vdrive_read_sector(vdrive, vdrive->bam + 512, BAM_TRACK_8050 - 1, BAM_SECTOR_8050 + 3);
if (err != 0) {
break;
}
if (vdrive->image_format == VDRIVE_IMAGE_FORMAT_8050) {
break;
}
err = vdrive_read_sector(vdrive, vdrive->bam + 768, BAM_TRACK_8050 - 1, BAM_SECTOR_8050 + 6);
if (err != 0) {
break;
}
err = vdrive_read_sector(vdrive, vdrive->bam + 1024, BAM_TRACK_8050 - 1, BAM_SECTOR_8050 + 9);
break;
case VDRIVE_IMAGE_FORMAT_4000:
for (i = 0; i < 33; i++) {
err = vdrive_read_sector(vdrive, vdrive->bam + i * 256, BAM_TRACK_4000, BAM_SECTOR_4000 + i);
if (err != 0) {
break;
}
}
break;
default:
log_error(LOG_ERR, "Unknown disk type %i. Cannot read BAM.", vdrive->image_format);
}
if (err < 0) {
return CBMDOS_IPE_NOT_READY;
}
return err;
}
/* Temporary hack. */
int vdrive_bam_reread_bam(unsigned int unit)
{
return vdrive_bam_read_bam(file_system_get_vdrive(unit));
}
/*
FIXME: partition support
*/
int vdrive_bam_write_bam(vdrive_t *vdrive)
{
int err = -1, i;
switch (vdrive->image_format) {
case VDRIVE_IMAGE_FORMAT_1541:
case VDRIVE_IMAGE_FORMAT_2040:
err = vdrive_write_sector(vdrive, vdrive->bam, BAM_TRACK_1541, BAM_SECTOR_1541);
break;
case VDRIVE_IMAGE_FORMAT_1571:
err = vdrive_write_sector(vdrive, vdrive->bam, BAM_TRACK_1571, BAM_SECTOR_1571);
err |= vdrive_write_sector(vdrive, vdrive->bam + 256, BAM_TRACK_1571 + (vdrive->num_tracks / 2), BAM_SECTOR_1571);
break;
case VDRIVE_IMAGE_FORMAT_1581:
err = vdrive_write_sector(vdrive, vdrive->bam, BAM_TRACK_1581, BAM_SECTOR_1581);
err |= vdrive_write_sector(vdrive, vdrive->bam + 256, BAM_TRACK_1581, BAM_SECTOR_1581 + 1);
err |= vdrive_write_sector(vdrive, vdrive->bam + 512, BAM_TRACK_1581, BAM_SECTOR_1581 + 2);
break;
case VDRIVE_IMAGE_FORMAT_8050:
case VDRIVE_IMAGE_FORMAT_8250:
err = vdrive_write_sector(vdrive, vdrive->bam, BAM_TRACK_8050, BAM_SECTOR_8050);
err |= vdrive_write_sector(vdrive, vdrive->bam + 256, BAM_TRACK_8050 - 1, BAM_SECTOR_8050);
err |= vdrive_write_sector(vdrive, vdrive->bam + 512, BAM_TRACK_8050 - 1, BAM_SECTOR_8050 + 3);
if (vdrive->image_format == 8050) {
break;
}
err |= vdrive_write_sector(vdrive, vdrive->bam + 768, BAM_TRACK_8050 - 1, BAM_SECTOR_8050 + 6);
err |= vdrive_write_sector(vdrive, vdrive->bam + 1024, BAM_TRACK_8050 - 1, BAM_SECTOR_8050 + 9);
break;
case VDRIVE_IMAGE_FORMAT_4000:
err = 0;
for (i = 0; i < 33; i++) {
err |= vdrive_write_sector(vdrive, vdrive->bam + i * 256, BAM_TRACK_4000, BAM_SECTOR_4000 + i);
}
break;
default:
log_error(LOG_ERR, "Unknown disk type %i. Cannot read BAM.", vdrive->image_format);
}
return err;
}
/* ------------------------------------------------------------------------- */
/*
* Return the number of free blocks on disk.
*/
unsigned int vdrive_bam_free_block_count(vdrive_t *vdrive)
{
unsigned int blocks, i, j;
for (blocks = 0, i = 1; i <= vdrive->num_tracks; i++) {
switch (vdrive->image_format) {
case VDRIVE_IMAGE_FORMAT_2040:
case VDRIVE_IMAGE_FORMAT_1541:
if (i != vdrive->Dir_Track) {
blocks += (i <= NUM_TRACKS_1541) ?
vdrive->bam[BAM_BIT_MAP + 4 * (i - 1)] :
vdrive->bam[BAM_EXT_BIT_MAP_1541 + 4 * (i - NUM_TRACKS_1541 - 1)];
}
break;
case VDRIVE_IMAGE_FORMAT_1571:
if (i != vdrive->Dir_Track && i != vdrive->Dir_Track + 35) {
blocks += (i <= NUM_TRACKS_1571 / 2) ?
vdrive->bam[BAM_BIT_MAP + 4 * (i - 1)] :
vdrive->bam[BAM_EXT_BIT_MAP_1571 + i - 1 - NUM_TRACKS_1571 / 2];
}
break;
case VDRIVE_IMAGE_FORMAT_1581:
if (i != vdrive->Dir_Track) {
blocks += (i <= NUM_TRACKS_1581 / 2) ?
vdrive->bam[BAM_BIT_MAP_1581 + 256 + 6 * (i - 1)] :
vdrive->bam[BAM_BIT_MAP_1581 + 512 + 6 * (i - 1 - NUM_TRACKS_1581 / 2)];
}
break;
case VDRIVE_IMAGE_FORMAT_8050:
if (i != vdrive->Dir_Track) {
int j;
for (j = 1; j < 3; j++) {
if (i >= vdrive->bam[(j * 0x100) + 4] && i < vdrive->bam[(j * 0x100) + 5]) {
blocks += vdrive->bam[(j * 0x100) + BAM_BIT_MAP_8050 + 5 * (i - vdrive->bam[(j * 0x100) + 4])];
break;
}
}
}
break;
case VDRIVE_IMAGE_FORMAT_8250:
if (i != vdrive->Dir_Track) {
int j;
for (j = 1; j < 5; j++) {
if (i >= vdrive->bam[(j * 0x100) + 4] && i < vdrive->bam[(j * 0x100) + 5]) {
blocks += vdrive->bam[(j * 0x100) + BAM_BIT_MAP_8050 + 5 * (i - vdrive->bam[(j * 0x100) + 4])];
break;
}
}
}
break;
case VDRIVE_IMAGE_FORMAT_4000:
for (j = ((i == vdrive->Bam_Track) ? 64 : 0); j < 256; j++) {
blocks += (vdrive->bam[BAM_BIT_MAP_4000 + 256 + 32 * (i - 1) + j / 8] >> (j % 8)) & 1;
}
break;
default:
log_error(LOG_ERR,
"Unknown disk type %i. Cannot calculate free sectors.",
vdrive->image_format);
}
}
return blocks;
}
| gpl-2.0 |
worldforge/cyphesis | src/pythonbase/PythonDebug.cpp | 1 | 1069 | /*
Copyright (C) 2021 Erik Ogenvik
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "PythonDebug.h"
#include "pycxx/CXX/Objects.hxx"
void pythonStackTrace() {
Py::Module sys("sys");
Py::Module traceback("traceback");
auto currentFrames = Py::Dict(sys.callMemberFunction("_current_frames"));
for (auto entry : currentFrames) {
traceback.callMemberFunction("print_stack", Py::TupleN(entry.second));
}
}
| gpl-2.0 |
koksneo/MangosBack | src/game/Vehicle.cpp | 1 | 2567 | /*
* Copyright (C) 2005-2010 MaNGOS <http://getmangos.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 "Common.h"
#include "Log.h"
#include "ObjectMgr.h"
#include "Vehicle.h"
#include "Unit.h"
#include "Util.h"
Vehicle::Vehicle() : Creature(CREATURE_SUBTYPE_VEHICLE), m_vehicleId(0)
{
m_updateFlag = (UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION | UPDATEFLAG_VEHICLE);
}
Vehicle::~Vehicle()
{
}
void Vehicle::AddToWorld()
{
///- Register the vehicle for guid lookup
if(!IsInWorld())
GetMap()->GetObjectsStore().insert<Vehicle>(GetGUID(), (Vehicle*)this);
Unit::AddToWorld();
}
void Vehicle::RemoveFromWorld()
{
///- Remove the vehicle from the accessor
if(IsInWorld())
GetMap()->GetObjectsStore().erase<Vehicle>(GetGUID(), (Vehicle*)NULL);
///- Don't call the function for Creature, normal mobs + totems go in a different storage
Unit::RemoveFromWorld();
}
void Vehicle::SetDeathState(DeathState s) // overwrite virtual Creature::SetDeathState and Unit::SetDeathState
{
Creature::SetDeathState(s);
}
void Vehicle::Update( uint32 update_diff, uint32 diff)
{
Creature::Update(update_diff, diff);
}
bool Vehicle::Create(uint32 guidlow, Map *map, uint32 Entry, uint32 vehicleId, Team team)
{
SetMap(map);
Object::_Create(guidlow, Entry, HIGHGUID_VEHICLE);
if(!InitEntry(Entry))
return false;
m_defaultMovementType = IDLE_MOTION_TYPE;
AIM_Initialize();
SetVehicleId(vehicleId);
SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f);
CreatureInfo const *ci = GetCreatureInfo();
setFaction(team == ALLIANCE ? ci->faction_A : ci->faction_H);
SelectLevel(ci);
return true;
}
void Vehicle::Dismiss()
{
SendObjectDeSpawnAnim(GetGUID());
CombatStop();
AddObjectToRemoveList();
}
| gpl-2.0 |
koying/xbmc-vidonme | xbmc/video/dialogs/GUIDialogVideoOSD.cpp | 1 | 4854 | /*
* Copyright (C) 2005-2013 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "GUIDialogVideoOSD.h"
#include "Application.h"
#include "FileItem.h"
#include "GUIUserMessages.h"
#include "guilib/GUIWindowManager.h"
#include "input/MouseStat.h"
#include "pvr/PVRManager.h"
#include "pvr/channels/PVRChannelGroupsContainer.h"
using namespace PVR;
CGUIDialogVideoOSD::CGUIDialogVideoOSD(void)
: CGUIDialog(WINDOW_DIALOG_VIDEO_OSD, "VideoOSD.xml")
{
m_loadType = KEEP_IN_MEMORY;
}
CGUIDialogVideoOSD::~CGUIDialogVideoOSD(void)
{
}
void CGUIDialogVideoOSD::FrameMove()
{
if (m_autoClosing)
{
// check for movement of mouse or a submenu open
if (g_Mouse.IsActive() || g_windowManager.IsWindowActive(WINDOW_DIALOG_AUDIO_OSD_SETTINGS)
|| g_windowManager.IsWindowActive(WINDOW_DIALOG_VIDEO_OSD_SETTINGS)
|| g_windowManager.IsWindowActive(WINDOW_DIALOG_VIDEO_BOOKMARKS)
|| g_windowManager.IsWindowActive(WINDOW_DIALOG_PVR_OSD_CHANNELS)
|| g_windowManager.IsWindowActive(WINDOW_DIALOG_PVR_OSD_GUIDE)
|| g_windowManager.IsWindowActive(WINDOW_DIALOG_PVR_OSD_DIRECTOR)
|| g_windowManager.IsWindowActive(WINDOW_DIALOG_PVR_OSD_CUTTER)
|| g_windowManager.IsWindowActive(WINDOW_DIALOG_OSD_TELETEXT))
SetAutoClose(100); // enough for 10fps
}
CGUIDialog::FrameMove();
}
bool CGUIDialogVideoOSD::OnAction(const CAction &action)
{
if (action.GetID() == ACTION_NEXT_ITEM || action.GetID() == ACTION_PREV_ITEM || action.GetID() == ACTION_CHANNEL_UP || action.GetID() == ACTION_CHANNEL_DOWN)
{
// these could indicate next chapter if video supports it
if (g_application.m_pPlayer != NULL && g_application.m_pPlayer->OnAction(action))
return true;
}
if (action.GetID() == ACTION_SHOW_OSD)
{
Close();
return true;
}
return CGUIDialog::OnAction(action);
}
EVENT_RESULT CGUIDialogVideoOSD::OnMouseEvent(const CPoint &point, const CMouseEvent &event)
{
if (event.m_id == ACTION_MOUSE_WHEEL_UP)
{
return g_application.OnAction(CAction(ACTION_ANALOG_SEEK_FORWARD, 0.5f)) ? EVENT_RESULT_HANDLED : EVENT_RESULT_UNHANDLED;
}
if (event.m_id == ACTION_MOUSE_WHEEL_DOWN)
{
return g_application.OnAction(CAction(ACTION_ANALOG_SEEK_BACK, 0.5f)) ? EVENT_RESULT_HANDLED : EVENT_RESULT_UNHANDLED;
}
return CGUIDialog::OnMouseEvent(point, event);
}
bool CGUIDialogVideoOSD::OnMessage(CGUIMessage& message)
{
switch ( message.GetMessage() )
{
case GUI_MSG_VIDEO_MENU_STARTED:
{
// We have gone to the DVD menu, so close the OSD.
Close();
}
break;
case GUI_MSG_WINDOW_DEINIT: // fired when OSD is hidden
{
// Remove our subdialogs if visible
CGUIDialog *pDialog = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_OSD_SETTINGS);
if (pDialog && pDialog->IsDialogRunning())
pDialog->Close(true);
pDialog = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_AUDIO_OSD_SETTINGS);
if (pDialog && pDialog->IsDialogRunning()) pDialog->Close(true);
pDialog = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_BOOKMARKS);
if (pDialog && pDialog->IsDialogRunning()) pDialog->Close(true);
pDialog = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_PVR_OSD_CHANNELS);
if (pDialog && pDialog->IsDialogRunning()) pDialog->Close(true);
pDialog = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_PVR_OSD_GUIDE);
if (pDialog && pDialog->IsDialogRunning()) pDialog->Close(true);
pDialog = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_PVR_OSD_DIRECTOR);
if (pDialog && pDialog->IsDialogRunning()) pDialog->Close(true);
pDialog = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_PVR_OSD_CUTTER);
if (pDialog && pDialog->IsDialogRunning()) pDialog->Close(true);
pDialog = (CGUIDialog *)g_windowManager.GetWindow(WINDOW_DIALOG_OSD_TELETEXT);
if (pDialog && pDialog->IsDialogRunning()) pDialog->Close(true);
}
break;
}
return CGUIDialog::OnMessage(message);
}
| gpl-2.0 |
GreenteaOS/Kernel | third-party/reactos/dll/directx/dsound_new/capture.c | 1 | 8906 | /*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: Configuration of network devices
* FILE: dll/directx/dsound_new/capture.c
* PURPOSE: Implement IDirectSoundCapture
*
* PROGRAMMERS: Johannes Anderwald (johannes.anderwald@reactos.org)
*/
#include "precomp.h"
typedef struct
{
IDirectSoundCaptureVtbl *lpVtbl;
LONG ref;
GUID DeviceGUID;
BOOL bInitialized;
LPFILTERINFO Filter;
}CDirectSoundCaptureImpl, *LPCDirectSoundCaptureImpl;
HRESULT
WINAPI
CDirectSoundCapture_fnQueryInterface(
LPDIRECTSOUNDCAPTURE8 iface,
REFIID riid,
LPVOID * ppobj)
{
LPOLESTR pStr;
LPCDirectSoundCaptureImpl This = (LPCDirectSoundCaptureImpl)CONTAINING_RECORD(iface, CDirectSoundCaptureImpl, lpVtbl);
/* check if the interface is supported */
if (IsEqualIID(riid, &IID_IUnknown) ||
IsEqualIID(riid, &IID_IDirectSoundCapture))
{
*ppobj = (LPVOID)&This->lpVtbl;
InterlockedIncrement(&This->ref);
return S_OK;
}
/* unsupported interface */
if (SUCCEEDED(StringFromIID(riid, &pStr)))
{
DPRINT("No Interface for class %s\n", pStr);
CoTaskMemFree(pStr);
}
return E_NOINTERFACE;
}
ULONG
WINAPI
CDirectSoundCapture_fnAddRef(
LPDIRECTSOUNDCAPTURE8 iface)
{
ULONG ref;
LPCDirectSoundCaptureImpl This = (LPCDirectSoundCaptureImpl)CONTAINING_RECORD(iface, CDirectSoundCaptureImpl, lpVtbl);
/* increment reference count */
ref = InterlockedIncrement(&This->ref);
return ref;
}
ULONG
WINAPI
CDirectSoundCapture_fnRelease(
LPDIRECTSOUNDCAPTURE8 iface)
{
ULONG ref;
LPCDirectSoundCaptureImpl This = (LPCDirectSoundCaptureImpl)CONTAINING_RECORD(iface, CDirectSoundCaptureImpl, lpVtbl);
/* release reference count */
ref = InterlockedDecrement(&(This->ref));
if (!ref)
{
HeapFree(GetProcessHeap(), 0, This);
}
return ref;
}
HRESULT
WINAPI
CDirectSoundCapture_fnCreateCaptureBuffer(
LPDIRECTSOUNDCAPTURE8 iface,
LPCDSCBUFFERDESC lpcDSBufferDesc,
LPDIRECTSOUNDCAPTUREBUFFER *ppDSCBuffer,
LPUNKNOWN pUnkOuter)
{
HRESULT hResult;
LPCDirectSoundCaptureImpl This = (LPCDirectSoundCaptureImpl)CONTAINING_RECORD(iface, CDirectSoundCaptureImpl, lpVtbl);
if (!This->bInitialized)
{
/* object not yet initialized */
return DSERR_UNINITIALIZED;
}
if (!lpcDSBufferDesc || !ppDSCBuffer || pUnkOuter != NULL)
{
/* invalid param */
return DSERR_INVALIDPARAM;
}
/* check buffer description */
if ((lpcDSBufferDesc->dwSize != sizeof(DSCBUFFERDESC) && lpcDSBufferDesc->dwSize != sizeof(DSCBUFFERDESC1)) ||
lpcDSBufferDesc->dwReserved != 0 || lpcDSBufferDesc->dwBufferBytes == 0 || lpcDSBufferDesc->lpwfxFormat == NULL)
{
/* invalid buffer description */
return DSERR_INVALIDPARAM;
}
DPRINT("This %p wFormatTag %x nChannels %u nSamplesPerSec %u nAvgBytesPerSec %u NBlockAlign %u wBitsPerSample %u cbSize %u\n",
This, lpcDSBufferDesc->lpwfxFormat->wFormatTag, lpcDSBufferDesc->lpwfxFormat->nChannels, lpcDSBufferDesc->lpwfxFormat->nSamplesPerSec, lpcDSBufferDesc->lpwfxFormat->nAvgBytesPerSec, lpcDSBufferDesc->lpwfxFormat->nBlockAlign, lpcDSBufferDesc->lpwfxFormat->wBitsPerSample, lpcDSBufferDesc->lpwfxFormat->cbSize);
hResult = NewDirectSoundCaptureBuffer((LPDIRECTSOUNDCAPTUREBUFFER8*)ppDSCBuffer, This->Filter, lpcDSBufferDesc);
return hResult;
}
HRESULT
WINAPI
CDirectSoundCapture_fnGetCaps(
LPDIRECTSOUNDCAPTURE8 iface,
LPDSCCAPS pDSCCaps)
{
WAVEINCAPSW Caps;
MMRESULT Result;
LPCDirectSoundCaptureImpl This = (LPCDirectSoundCaptureImpl)CONTAINING_RECORD(iface, CDirectSoundCaptureImpl, lpVtbl);
if (!This->bInitialized)
{
/* object not yet initialized */
return DSERR_UNINITIALIZED;
}
if (!pDSCCaps)
{
/* invalid param */
return DSERR_INVALIDPARAM;
}
if (pDSCCaps->dwSize != sizeof(DSCCAPS))
{
/* invalid param */
return DSERR_INVALIDPARAM;
}
/* We are certified ;) */
pDSCCaps->dwFlags = DSCCAPS_CERTIFIED;
ASSERT(This->Filter);
Result = waveInGetDevCapsW(This->Filter->MappedId[0], &Caps, sizeof(WAVEINCAPSW));
if (Result != MMSYSERR_NOERROR)
{
/* failed */
DPRINT("waveInGetDevCapsW for device %u failed with %x\n", This->Filter->MappedId[0], Result);
return DSERR_UNSUPPORTED;
}
pDSCCaps->dwFormats = Caps.dwFormats;
pDSCCaps->dwChannels = Caps.wChannels;
return DS_OK;
}
HRESULT
WINAPI
CDirectSoundCapture_fnInitialize(
LPDIRECTSOUNDCAPTURE8 iface,
LPCGUID pcGuidDevice)
{
GUID DeviceGuid;
LPOLESTR pGuidStr;
LPCDirectSoundCaptureImpl This = (LPCDirectSoundCaptureImpl)CONTAINING_RECORD(iface, CDirectSoundCaptureImpl, lpVtbl);
/* sanity check */
ASSERT(RootInfo);
if (This->bInitialized)
{
/* object has already been initialized */
return DSERR_ALREADYINITIALIZED;
}
/* fixme mutual exlucsion */
if (pcGuidDevice == NULL || IsEqualGUID(pcGuidDevice, &GUID_NULL))
{
/* use default playback device id */
pcGuidDevice = &DSDEVID_DefaultCapture;
}
if (IsEqualIID(pcGuidDevice, &DSDEVID_DefaultVoicePlayback) || IsEqualIID(pcGuidDevice, &DSDEVID_DefaultPlayback))
{
/* this has to be a winetest */
return DSERR_NODRIVER;
}
/* now verify the guid */
if (GetDeviceID(pcGuidDevice, &DeviceGuid) != DS_OK)
{
if (SUCCEEDED(StringFromIID(pcGuidDevice, &pGuidStr)))
{
DPRINT("IDirectSound8_fnInitialize: Unknown GUID %ws\n", pGuidStr);
CoTaskMemFree(pGuidStr);
}
return DSERR_INVALIDPARAM;
}
if (FindDeviceByGuid(&DeviceGuid, &This->Filter))
{
This->bInitialized = TRUE;
return DS_OK;
}
DPRINT("Failed to find device\n");
return DSERR_INVALIDPARAM;
}
static IDirectSoundCaptureVtbl vt_DirectSoundCapture =
{
/* IUnknown methods */
CDirectSoundCapture_fnQueryInterface,
CDirectSoundCapture_fnAddRef,
CDirectSoundCapture_fnRelease,
CDirectSoundCapture_fnCreateCaptureBuffer,
CDirectSoundCapture_fnGetCaps,
CDirectSoundCapture_fnInitialize
};
HRESULT
InternalDirectSoundCaptureCreate(
LPCGUID lpcGUID,
LPDIRECTSOUNDCAPTURE8 *ppDS,
IUnknown *pUnkOuter)
{
LPCDirectSoundCaptureImpl This;
HRESULT hr;
if (!ppDS || pUnkOuter != NULL)
{
/* invalid parameter passed */
return DSERR_INVALIDPARAM;
}
/* allocate CDirectSoundCaptureImpl struct */
This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CDirectSoundCaptureImpl));
if (!This)
{
/* not enough memory */
return DSERR_OUTOFMEMORY;
}
/* initialize IDirectSoundCapture object */
This->ref = 1;
This->lpVtbl = &vt_DirectSoundCapture;
/* initialize direct sound interface */
hr = IDirectSoundCapture_Initialize((LPDIRECTSOUNDCAPTURE8)&This->lpVtbl, lpcGUID);
/* check for success */
if (!SUCCEEDED(hr))
{
/* failed */
DPRINT("Failed to initialize DirectSoundCapture object with %x\n", hr);
IDirectSoundCapture_Release((LPDIRECTSOUND8)&This->lpVtbl);
return hr;
}
/* store result */
*ppDS = (LPDIRECTSOUNDCAPTURE8)&This->lpVtbl;
DPRINT("DirectSoundCapture object %p\n", *ppDS);
return DS_OK;
}
HRESULT
CALLBACK
NewDirectSoundCapture(
IUnknown* pUnkOuter,
REFIID riid,
LPVOID* ppvObject)
{
LPOLESTR pStr;
LPCDirectSoundCaptureImpl This;
/* check requested interface */
if (!IsEqualIID(riid, &IID_IUnknown) && !IsEqualIID(riid, &IID_IDirectSoundCapture) && !IsEqualIID(riid, &IID_IDirectSoundCapture8))
{
*ppvObject = 0;
StringFromIID(riid, &pStr);
DPRINT("NewDirectSoundCapture does not support Interface %ws\n", pStr);
CoTaskMemFree(pStr);
return E_NOINTERFACE;
}
/* allocate CDirectSoundCaptureImpl struct */
This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CDirectSoundCaptureImpl));
if (!This)
{
/* not enough memory */
return DSERR_OUTOFMEMORY;
}
/* initialize object */
This->ref = 1;
This->lpVtbl = &vt_DirectSoundCapture;
This->bInitialized = FALSE;
*ppvObject = (LPVOID)&This->lpVtbl;
return S_OK;
}
HRESULT
WINAPI
DirectSoundCaptureCreate(
LPCGUID lpcGUID,
LPDIRECTSOUNDCAPTURE *ppDSC,
LPUNKNOWN pUnkOuter)
{
return InternalDirectSoundCaptureCreate(lpcGUID, (LPDIRECTSOUNDCAPTURE8*)ppDSC, pUnkOuter);
}
HRESULT
WINAPI
DirectSoundCaptureCreate8(
LPCGUID lpcGUID,
LPDIRECTSOUNDCAPTURE8 *ppDSC8,
LPUNKNOWN pUnkOuter)
{
return InternalDirectSoundCaptureCreate(lpcGUID, ppDSC8, pUnkOuter);
}
| gpl-2.0 |
ioangogo/space-nerds-in-space | snis_ship_type.c | 1 | 4553 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include "snis_ship_type.h"
struct ship_type_entry *snis_read_ship_types(char *filename, int *count)
{
FILE *f;
char line[255], class[255], model_file[PATH_MAX], thrust_attach[PATH_MAX];
double toughness, max_speed;
int warpchance;
int crew_max;
char *x;
int i, scancount;
int integer;
int linecount = 0, n = 0;
int nalloced = 0;
struct ship_type_entry *st;
int nrots;
char axis[4];
float rot[4];
int expected_count;
nalloced = 30;
st = malloc(sizeof(*st) * nalloced);
if (!st)
return NULL;
f = fopen(filename, "r");
if (!f)
return NULL;
while (!feof(f)) {
x = fgets(line, sizeof(line) - 1, f);
line[strlen(line) - 1] = '\0'; /* cut off trailing \n */
if (!x) {
if (feof(f))
break;
}
linecount++;
if (line[0] == '#') /* skip comment lines */
continue;
scancount = sscanf(line, "%s %s %s %lf %d %d %d %[xyzs] %f %[xyzs] %f %[xyzs] %f %[xyzs] %f\n",
class, model_file, thrust_attach,
&toughness, &integer, &warpchance, &crew_max,
&axis[0], &rot[0],
&axis[1], &rot[1],
&axis[2], &rot[2],
&axis[3], &rot[3]);
expected_count = 15;
if (scancount == expected_count) {
nrots = 4;
goto done_scanfing_line;
}
expected_count -= 2;
scancount = sscanf(line, "%s %s %s %lf %d %d %d %[xyzs] %f %[xyzs] %f %[xyzs] %f\n",
class, model_file, thrust_attach,
&toughness, &integer, &warpchance, &crew_max,
&axis[0], &rot[0],
&axis[1], &rot[1],
&axis[2], &rot[2]);
if (scancount == expected_count) {
nrots = 3;
goto done_scanfing_line;
}
expected_count -= 2;
scancount = sscanf(line, "%s %s %s %lf %d %d %d %[xyzs] %f %[xyzs] %f\n",
class, model_file, thrust_attach,
&toughness, &integer, &warpchance, &crew_max,
&axis[0], &rot[0], &axis[1], &rot[1]);
if (scancount == expected_count) {
nrots = 2;
goto done_scanfing_line;
}
expected_count -= 2;
scancount = sscanf(line, "%s %s %s %lf %d %d %d %[xyzs] %f\n",
class, model_file, thrust_attach,
&toughness, &integer, &warpchance, &crew_max,
&axis[0], &rot[0]);
if (scancount == expected_count) {
nrots = 1;
goto done_scanfing_line;
}
expected_count -= 2;
scancount = sscanf(line, "%s %s %s %lf %d %d %d\n", class, model_file,
thrust_attach, &toughness, &integer, &warpchance, &crew_max);
if (scancount != expected_count) {
fprintf(stderr, "Error at line %d in %s: '%s'\n",
linecount, filename, line);
if (scancount > 0)
fprintf(stderr, "converted %d items\n", scancount);
continue;
}
nrots = 0;
done_scanfing_line:
for (i = 0; i < nrots; i++) {
if (axis[i] != 'x' && axis[i] != 'y' && axis[i] != 'z' && axis[i] != 's') {
fprintf(stderr, "Bad axis '%c' at line %d in %s: '%s'\n",
axis[i], linecount, filename, line);
axis[i] = 'x';
rot[i] = 0.0;
}
if (axis[i] != 's')
rot[i] = rot[i] * M_PI / 180.0;
}
max_speed = (double) integer / 100.0;
if (toughness < 0.05) {
fprintf(stderr, "%s:%d: toughness %lf for class %s out of range\n",
filename, linecount, toughness, class);
toughness = 0.05;
}
if (toughness > 1.0) {
fprintf(stderr, "%s:%d: toughness %lf for class %s out of range\n",
filename, linecount, toughness, class);
toughness = 1.0;
}
/* exceeded allocated capacity */
if (n >= nalloced) {
struct ship_type_entry *newst;
nalloced += 100;
newst = realloc(st, nalloced * sizeof(*st));
if (!newst) {
fprintf(stderr, "out of memory at %s:%d\n", __FILE__, __LINE__);
*count = n;
return st;
}
}
st[n].thrust_attachment_file = strdup(thrust_attach);
st[n].class = strdup(class);
if (!st[n].class) {
fprintf(stderr, "out of memory at %s:%d\n", __FILE__, __LINE__);
*count = n;
return st;
}
st[n].model_file = strdup(model_file);
if (!st[n].class) {
fprintf(stderr, "out of memory at %s:%d\n", __FILE__, __LINE__);
*count = n;
return st;
}
st[n].toughness = toughness;
st[n].max_shield_strength =
(uint8_t) (255.0f * ((st[n].toughness * 0.8f) + 0.2f));
st[n].max_speed = max_speed;
st[n].warpchance = warpchance;
st[n].crew_max = crew_max;
st[n].nrotations = nrots;
for (i = 0; i < nrots; i++) {
st[n].axis[i] = axis[i];
st[n].angle[i] = rot[i];
}
n++;
}
*count = n;
return st;
}
void snis_free_ship_type(struct ship_type_entry *st, int count)
{
int i;
for (i = 0; i < count; i++)
free(st[i].class);
free(st);
}
| gpl-2.0 |
rbberger/lammps | src/USER-MISC/pair_coul_slater_cut.cpp | 1 | 5801 | /* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
https://lammps.sandia.gov/, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
* Contributing author: Evangelos Voyiatzis (Royal DSM)
* ------------------------------------------------------------------------- */
#include "pair_coul_slater_cut.h"
#include "atom.h"
#include "comm.h"
#include "error.h"
#include "force.h"
#include "neigh_list.h"
#include <cmath>
using namespace LAMMPS_NS;
/* ---------------------------------------------------------------------- */
PairCoulSlaterCut::PairCoulSlaterCut(LAMMPS *lmp) : PairCoulCut(lmp) {}
/* ---------------------------------------------------------------------- */
void PairCoulSlaterCut::compute(int eflag, int vflag)
{
int i,j,ii,jj,inum,jnum,itype,jtype;
double qtmp,xtmp,ytmp,ztmp,delx,dely,delz,ecoul,fpair;
double rsq,r2inv,r,rinv,forcecoul,factor_coul,bracket_term;
int *ilist,*jlist,*numneigh,**firstneigh;
ev_init(eflag,vflag);
ecoul = 0.0;
double **x = atom->x;
double **f = atom->f;
double *q = atom->q;
int *type = atom->type;
int nlocal = atom->nlocal;
double *special_coul = force->special_coul;
int newton_pair = force->newton_pair;
double qqrd2e = force->qqrd2e;
inum = list->inum;
ilist = list->ilist;
numneigh = list->numneigh;
firstneigh = list->firstneigh;
// loop over neighbors of my atoms
for (ii = 0; ii < inum; ii++) {
i = ilist[ii];
qtmp = q[i];
xtmp = x[i][0];
ytmp = x[i][1];
ztmp = x[i][2];
itype = type[i];
jlist = firstneigh[i];
jnum = numneigh[i];
for (jj = 0; jj < jnum; jj++) {
j = jlist[jj];
factor_coul = special_coul[sbmask(j)];
j &= NEIGHMASK;
delx = xtmp - x[j][0];
dely = ytmp - x[j][1];
delz = ztmp - x[j][2];
rsq = delx*delx + dely*dely + delz*delz;
jtype = type[j];
if (rsq < cutsq[itype][jtype]) {
r2inv = 1.0/rsq;
r = sqrt(rsq);
rinv = 1.0/r;
bracket_term = 1 - exp(-2*r/lamda)*(1 + (2*r/lamda*(1+r/lamda)));
forcecoul = qqrd2e * scale[itype][jtype] *
qtmp*q[j] * bracket_term * rinv;
fpair = factor_coul*forcecoul * r2inv;
f[i][0] += delx*fpair;
f[i][1] += dely*fpair;
f[i][2] += delz*fpair;
if (newton_pair || j < nlocal) {
f[j][0] -= delx*fpair;
f[j][1] -= dely*fpair;
f[j][2] -= delz*fpair;
}
if (eflag) ecoul = factor_coul * qqrd2e *
scale[itype][jtype] * qtmp*q[j] * rinv *
(1 - (1 + r/lamda)*exp(-2*r/lamda));
if (evflag) ev_tally(i,j,nlocal,newton_pair,
0.0,ecoul,fpair,delx,dely,delz);
}
}
}
if (vflag_fdotr) virial_fdotr_compute();
}
/* ----------------------------------------------------------------------
global settings
------------------------------------------------------------------------- */
void PairCoulSlaterCut::settings(int narg, char **arg)
{
if (narg != 2) error->all(FLERR,"Illegal pair_style command");
lamda = utils::numeric(FLERR,arg[0],false,lmp);
cut_global = utils::numeric(FLERR,arg[1],false,lmp);
// reset cutoffs that have been explicitly set
if (allocated) {
int i,j;
for (i = 1; i <= atom->ntypes; i++)
for (j = i; j <= atom->ntypes; j++)
if (setflag[i][j]) cut[i][j] = cut_global;
}
}
/* ----------------------------------------------------------------------
proc 0 writes to restart file
------------------------------------------------------------------------- */
void PairCoulSlaterCut::write_restart_settings(FILE *fp)
{
fwrite(&cut_global,sizeof(double),1,fp);
fwrite(&lamda,sizeof(double),1,fp);
fwrite(&offset_flag,sizeof(int),1,fp);
fwrite(&mix_flag,sizeof(int),1,fp);
}
/* ----------------------------------------------------------------------
proc 0 reads from restart file, bcasts
------------------------------------------------------------------------- */
void PairCoulSlaterCut::read_restart_settings(FILE *fp)
{
if (comm->me == 0) {
utils::sfread(FLERR,&cut_global,sizeof(double),1,fp,nullptr,error);
utils::sfread(FLERR,&lamda,sizeof(double),1,fp,nullptr,error);
utils::sfread(FLERR,&offset_flag,sizeof(int),1,fp,nullptr,error);
utils::sfread(FLERR,&mix_flag,sizeof(int),1,fp,nullptr,error);
}
MPI_Bcast(&cut_global,1,MPI_DOUBLE,0,world);
MPI_Bcast(&lamda,1,MPI_DOUBLE,0,world);
MPI_Bcast(&offset_flag,1,MPI_INT,0,world);
MPI_Bcast(&mix_flag,1,MPI_INT,0,world);
}
/* ---------------------------------------------------------------------- */
double PairCoulSlaterCut::single(int i, int j, int /*itype*/, int /*jtype*/,
double rsq, double factor_coul, double /*factor_lj*/,
double &fforce)
{
double r2inv,r,rinv,forcecoul,phicoul,bracket_term;
r2inv = 1.0/rsq;
r = sqrt(rsq);
rinv = 1.0/r;
bracket_term = 1 - exp(-2*r/lamda)*(1 + (2*r/lamda*(1+r/lamda)));
forcecoul = force->qqrd2e * atom->q[i]*atom->q[j] *
bracket_term * rinv;
fforce = factor_coul*forcecoul * r2inv;
phicoul = force->qqrd2e * atom->q[i]*atom->q[j] * rinv * (1 - (1 + r/lamda)*exp(-2*r/lamda));
return factor_coul*phicoul;
}
| gpl-2.0 |
vvdeng/MinerLampDerbySystem | cfiles/stc15_terminal_v01/lcd12864.c | 1 | 14496 | /*
×¢Ò⣡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡11
½¯×ܵįÁCS1¡¢CS2ÊÇ¸ßµçÆ½ÓÐЧ£¬ÇÒÑÓʱʱ¼ä¾Êµ¼ùÐèѡΪ200us
Êг¡ÉÏµÄÆÁCS1¡¢CS2ÊÇµÍµçÆ½ÓÐЧ£¬ÇÒÑÓʱʱ¼ä¾Êµ¼ùÐèѡΪ100us
*/
#include "lcd12864.h"
#include "hanzi.h"
#include "vvspi.h"
#define ENABLE 0
#define DISENABLE 1
bit infoChanged=1;
unsigned char xdata null16x16[]={
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
unsigned char xdata underline16x16[]={
0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
unsigned char xdata full16x16[]={
0x00,0x00,0x00,0x00,0xfc,0xfc,0xff,0xff,0xff,0xff,0xfc,0xfc,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,
};
unsigned char xdata half16x16[]={
0x00,0x00,0x00,0x00,0xfc,0x04,0x07,0x07,0x07,0x07,0x04,0xfc,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,
};
/*unsigned char xdata half16x16[]={
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, };*/
unsigned char xdata empty16x16[]={
0x00,0x00,0x00,0x00,0xfc,0x04,0x07,0x07,0x07,0x07,0x04,0xfc,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xff,0x80,0x80,0x80,0x80,0x80,0x80,0xff,0x00,0x00,0x00,0x00,
};
unsigned char xdata error16x16[]={
0x00,0x00,0x00,0x00,0xfc,0x24,0x47,0x87,0x87,0x47,0x24,0xfc,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xff,0x84,0x82,0x81,0x81,0x82,0x84,0xff,0x00,0x00,0x00,0x00,
};
unsigned char xdata arrow16x16[]={
0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x90,0xA0,0xC0,0x80,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x02,0x01,0x00,
};
void LCD_WrCmd(uchar port,uchar cmd)
{
delayUs(DISPLAY_DELAY_TIME);
EN=0;
if(port==1){
CS1=ENABLE;
delayUs(DISPLAY_DELAY_TIME);
CS2=DISENABLE;
delayUs(DISPLAY_DELAY_TIME);
}
else
{
CS1=DISENABLE;
delayUs(DISPLAY_DELAY_TIME);
CS2=ENABLE;
delayUs(DISPLAY_DELAY_TIME);
}
DI=0;
RW=0;
EN=1;
LCD=cmd;
EN=0;
}
void LCD_WrDat(uchar port ,uchar wrdata)
{
delayUs(DISPLAY_DELAY_TIME);
EN=0;
if(port==1){
CS1=ENABLE;
delayUs(DISPLAY_DELAY_TIME);
CS2=DISENABLE;
delayUs(DISPLAY_DELAY_TIME);
}else{
CS1=DISENABLE;
delayUs(DISPLAY_DELAY_TIME);
CS2=ENABLE;
delayUs(DISPLAY_DELAY_TIME);
}
DI=1;
RW=0;
EN=1;
LCD=wrdata;
EN=0;
}
void LCD_DispFill(uchar filldata)
{ uchar x, y;
LCD_WrCmd(1,LCD_STARTROW);
LCD_WrCmd(2,LCD_STARTROW);
for(y=0; y<8; y++)
{ LCD_WrCmd(1,LCD_ADDRSTRY+y);
LCD_WrCmd(1,LCD_ADDRSTRX);
LCD_WrCmd(2,LCD_ADDRSTRY+y);
LCD_WrCmd(2,LCD_ADDRSTRX);
for(x=0; x<64; x++)
{ LCD_WrDat(1,filldata);
LCD_WrDat(2,filldata);
}
}
}
void LCD_DispIni(void)
{
LCD_RST = 0;
delayUs(1000);
LCD_RST = 1;
delayUs(1000);
LCD_WrCmd(1,LCD_DISPON);
LCD_WrCmd(1,LCD_STARTROW);
delayUs(1000);
LCD_WrCmd(2,LCD_DISPON);
LCD_WrCmd(2,LCD_STARTROW);
LCD_DispFill(0x00);
LCD_WrCmd(1,LCD_ADDRSTRY+0);
LCD_WrCmd(1,LCD_ADDRSTRX+0);
LCD_WrCmd(2,LCD_ADDRSTRY+0);
LCD_WrCmd(2,LCD_ADDRSTRX+0);
}
uchar xdata chrBuf[32];
void getBytesFormGB2312s(char* chr){
uchar i=0, charSize=0,offsetLen=32;
unsigned long temp_addr;
//ÓÃ12x12×ÖÌå
temp_addr = GB_ADDR(chr,16);
charSize = GB_HZZF_len(chr);
CS=0;
// WriteByte(0x0b);
// WriteByte((temp_addr>>16)&0xff);
// WriteByte((temp_addr>>8)&0xff);
// WriteByte((temp_addr>>0)&0xff);
// WriteByte(0xFF);
WriteByte(0x03);
WriteByte((temp_addr>>16)&0xff);
WriteByte((temp_addr>>8)&0xff);
WriteByte((temp_addr>>0)&0xff);
if(charSize==2){
for(i=0;i<offsetLen;i++){
chrBuf[i]=ReadByte();
}
} else if(charSize==1){
for(i=0;i<(offsetLen/2);i++){
chrBuf[2*i]=ReadByte(); //todo´Ë´¦Ëã·¨Ðè¸ü¸Ä
chrBuf[2*i+1]=0x00;
}
}
CS=1;
}
void lcd_disp_sz_char(uchar cx,uchar cy,uchar* chr)
{
uchar *p,i,s,page;
uchar port;
getBytesFormGB2312s(chr);
p=chrBuf;
if(cx<4)
{
port=1;
s=cx<<4;
}
else
{
port=2;
s=((cx-4)<<4);
}
for(page=0;page<2;page++)
{
LCD_WrCmd(port,0xb8+cy*2+page);
delayUs(100);
LCD_WrCmd(port,0x40+s);
delayUs(100);
for(i=0;i<16;i++)
{
LCD_WrDat(port,*p);
delayUs(10);
p++;
}
}
}
void LCD_PutString(unsigned char cx,unsigned char cy,unsigned char *s)
{
uchar wordCount=0,charSize=0;
// lcd_disp_sz_char(0,0,s);
// lcd_disp_sz_char(4,1,s+2);
while(*s!='\0'&&wordCount<10)
{
charSize = GB_HZZF_len(s);
lcd_disp_sz_char(cx,cy,s);
wordCount++;
s++;
if(charSize==2)
{
s++;
}
cx++;
if(cx>7) {cx=0;cy++;}
}
}
uchar xdata chrBuf_24[72];
void get24x24BytesFormGB2312s(char* chr,uchar * buf){
uchar i=0, charSize=0,offsetLen=72;
unsigned long temp_addr;
temp_addr = GB_ADDR(chr,24);
charSize = GB_HZZF_len(chr);
CS=0;
// WriteByte(0x0b);
// WriteByte((temp_addr>>16)&0xff);
// WriteByte((temp_addr>>8)&0xff);
// WriteByte((temp_addr>>0)&0xff);
// WriteByte(0xFF);
WriteByte(0x03);
WriteByte((temp_addr>>16)&0xff);
WriteByte((temp_addr>>8)&0xff);
WriteByte((temp_addr>>0)&0xff);
if(charSize==2){
for(i=0;i<offsetLen;i++){
buf[i]=ReadByte();
}
} else if(charSize==1){
for(i=0;i<(offsetLen/2);i++){
buf[2*i]=ReadByte(); //todo´Ë´¦Ëã·¨Ðè¸ü¸Ä
buf[2*i+1]=0x00;
}
}
CS=1;
}
void lcd_disp_sz_char_24(uchar cx,uchar cy,uchar* chr,uchar* buf)
{
uchar *p,i,s,page;
uchar port;
if(chr!=0)
{
get24x24BytesFormGB2312s(chr,buf);
}
p=chrBuf_24;
if(cx<2)
{
port=1;
s=cx*24;
}
else
{
port=2;
s=((cx-2)*24);
}
for(page=0;page<3;page++)
{
LCD_WrCmd(port,0xb8+cy*3+page);
delayUs(100);
LCD_WrCmd(port,0x40+s);
delayUs(100);
for(i=0;i<24;i++)
{
LCD_WrDat(port,*p);
delayUs(10);
p++;
}
}
}
void LCD_PutString_24(unsigned char cx,unsigned char cy,unsigned char *s)
{
uchar wordCount=0,charSize=0;
// lcd_disp_sz_char(0,0,s);
// lcd_disp_sz_char(4,1,s+2);
while(*s!='\0'&&wordCount<10)
{
charSize = GB_HZZF_len(s);
lcd_disp_sz_char_24(cx,cy,s,chrBuf_24);
wordCount++;
s++;
if(charSize==2)
{
s++;
}
cx++;
if(cx>4) {cx=0;cy++;}
}
}
void lcd_disp_sz_char_24_original_x(uchar x,uchar cy,uchar* chr,uchar* buf)
{
uchar *p,i,s,page;
uchar port;
if(chr!=0)
{
get24x24BytesFormGB2312s(chr,buf);
}
p=buf;
if(x<64)
{
port=1;
s=x;
}
else
{
port=2;
s=x-64;
}
for(page=0;page<3;page++)
{
LCD_WrCmd(port,0xb8+cy*3+page);
delayUs(100);
LCD_WrCmd(port,0x40+s);
delayUs(100);
for(i=0;i<24;i++)
{
LCD_WrDat(port,*p);
delayUs(10);
p++;
}
}
}
void LCD_PutString_24_cy(unsigned char cy,unsigned char *s)
{
uchar wordCount=0,charSize=0, *p=s;
uchar x[4];
//¼ÆËã×Ü×ÖÊý£¬È·¶¨ÅÅÁз½Ê½
while(*p!='\0'){
charSize= GB_HZZF_len(p);
wordCount++;
p++;
if(charSize==2){
p++;
}
}
switch (wordCount){
case 1:
x[0]=39;
break;
case 2:
x[0]=29;
x[1]=74;
break;
case 3:
x[0]=38;
x[1]=64;
x[2]=86;
break;
default:
x[0]=0;
x[1]=34;
x[2]=69;
x[3]=103;
}
wordCount=0;
// lcd_disp_sz_char(0,0,s);
// lcd_disp_sz_char(4,1,s+2);
while(*s!='\0'&&wordCount<4)
{
charSize = GB_HZZF_len(s);
lcd_disp_sz_char_24_original_x(x[wordCount],cy,s,chrBuf_24);
wordCount++;
s++;
if(charSize==2)
{
s++;
}
}
}
uchar xdata nameCharBuf[288];
void get24x24NameBytesFormGB2312s(char* chr,uint startIndex){
uchar i=0, charSize=0,offsetLen=72;
unsigned long temp_addr;
temp_addr = GB_ADDR(chr,24);
charSize = GB_HZZF_len(chr);
CS=0;
// WriteByte(0x0b);
// WriteByte((temp_addr>>16)&0xff);
// WriteByte((temp_addr>>8)&0xff);
// WriteByte((temp_addr>>0)&0xff);
// WriteByte(0xFF);
WriteByte(0x03);
WriteByte((temp_addr>>16)&0xff);
WriteByte((temp_addr>>8)&0xff);
WriteByte((temp_addr>>0)&0xff);
if(charSize==2){
for(i=0;i<offsetLen;i++){
nameCharBuf[i+startIndex]=ReadByte();
}
} else if(charSize==1){
for(i=0;i<(offsetLen/2);i++){
nameCharBuf[2*i+startIndex]=ReadByte(); //todo´Ë´¦Ëã·¨Ðè¸ü¸Ä
nameCharBuf[2*i+1+startIndex]=0x00;
}
}
CS=1;
}
void arrangeNameArr(uchar wordCount){
uint m;
//ÔÝÇÒÈ«²¿Ó²±àÂë
switch(wordCount){
case 1:
for (m=72;m<288;m++){
nameCharBuf[m]=0;
}
for (m=72;m<144;m++){
if(m%24>11){
nameCharBuf[m]=nameCharBuf[m-72-12];
}
}
for (m=144;m<216;m++){
if(m%24<11){
nameCharBuf[m]=nameCharBuf[m-144+12];
}
}
for (m=0;m<72;m++){
nameCharBuf[m]=0;
}
break;
case 2:
for (m=287;m>215;m--){
nameCharBuf[m]=nameCharBuf[m-144];
}
for (m=72;m<216;m++){
nameCharBuf[m]=0;
}
break;
case 3:
for (m=216;m<288;m++){
nameCharBuf[m]=nameCharBuf[m-72];
}
for (m=215;m>143;m--){
if(m%24<11){
nameCharBuf[m]=nameCharBuf[m-72+12];
}
else{
nameCharBuf[m]=0;
}
}
for (m=143;m>71;m--){
if(m%24>11){
nameCharBuf[m]=nameCharBuf[m-0-12];
}
else{
nameCharBuf[m]=0;
}
}
break;
}
}
void LCD_PutName_24_cy(unsigned char cy,unsigned char *s){
uchar m,wordCount=0,charSize=0, *p=s,offsetLen=72;
if(infoChanged)
{
infoChanged=0;
while(*s!='\0'&&wordCount<4)
{
charSize = GB_HZZF_len(s);
get24x24NameBytesFormGB2312s(s,72*wordCount);
wordCount++;
s++;
if(charSize==2)
{
s++;
}
}
arrangeNameArr(wordCount);
}
for(m=0;m<4;m++){
lcd_disp_sz_char_24_original_x(16+m*24,cy,0,nameCharBuf+offsetLen*m);
}
}
void getBytesFormASCIIs(char* chr){
uchar i=0, charSize=0,offsetLen=32;
unsigned long temp_addr;
temp_addr = GB_ADDR(chr,16);
charSize = GB_HZZF_len(chr);
CS=0;
// WriteByte(0x0b);
// WriteByte((temp_addr>>16)&0xff);
// WriteByte((temp_addr>>8)&0xff);
// WriteByte((temp_addr>>0)&0xff);
// WriteByte(0xFF);
WriteByte(0x03);
WriteByte((temp_addr>>16)&0xff);
WriteByte((temp_addr>>8)&0xff);
WriteByte((temp_addr>>0)&0xff);
if(charSize==2){
for(i=0;i<offsetLen;i++){
chrBuf[i]=ReadByte();
}
} else if(charSize==1){
for(i=0;i<(offsetLen/2);i++){
chrBuf[i]=ReadByte();
chrBuf[16+i]=0x00;
}
}
CS=1;
}
void lcd_disp_sz_SingleBytechar(uchar cy,uchar cx,uchar* chr)
{
uchar *p,i,s,page;
uchar port;
getBytesFormASCIIs(chr);
p=chrBuf;
if(cx<8)
{
port=1;
s=cx<<3;
}
else
{
port=2;
s=((cx-8)<<3);
}
for(page=0;page<2;page++)
{
LCD_WrCmd(port,0xb8+cy*2+page);
delayUs(100);
LCD_WrCmd(port,0x40+s);
delayUs(100);
for(i=0;i<8;i++)
{
LCD_WrDat(port,*p);
delayUs(10);
p++;
}
}
}
void LCD_PutSingleByteString(unsigned char cx,unsigned char cy,unsigned char *s)
{
uchar wordCount=0,charSize=0;
// lcd_disp_sz_char(0,0,s);
// lcd_disp_sz_char(4,1,s+2);
while(*s!='\0'&&wordCount<10)
{
charSize = GB_HZZF_len(s); //charsizeÖ»¿ÉÄÜΪһ
lcd_disp_sz_SingleBytechar(cy,cx,s);
wordCount++;
s++;
if(charSize==2)
{
s++;
}
cx++;
if(cx>15) {cx=0;cy++;}
}
}
uchar charArr[2];
void LCD_PutChar(unsigned char cx,unsigned char cy,unsigned char chr){
uchar *p,i,s,page;
uchar port;
chr=0;//Ïû³ýwarning ¸Ã±äÁ¿ÎÞÓ㬽öΪ¼æÈÝ֮ǰ½Ó¿Ú
cy--;
p=arrow16x16;
if(cx<4)
{
port=1;
s=cx<<4;
}
else
{
port=2;
s=((cx-4)<<4);
}
for(page=0;page<2;page++)
{
LCD_WrCmd(port,0xb8+cy*2+page);
delayUs(100);
LCD_WrCmd(port,0x40+s);
delayUs(100);
for(i=0;i<16;i++)
{
LCD_WrDat(port,*p);
delayUs(10);
p++;
}
}
}
uchar *lbatStateGraph=0;
void FullCGRAM()
{
lbatStateGraph=full16x16;
}
void HalfCGRAM()
{
lbatStateGraph=half16x16;
}
void EmptyCGRAM()
{
lbatStateGraph=empty16x16;
}
void ErrorCGRAM()
{
lbatStateGraph=error16x16;
}
void NullCGRAM()
{
lbatStateGraph=null16x16;
}
void DisplayCGRAM(unsigned char cx,unsigned char cy)
{
uchar *p,i,s,page;
uchar port;
cy--;
p=lbatStateGraph;
if(cx<4)
{
port=1;
s=cx<<4;
}
else
{
port=2;
s=((cx-4)<<4);
}
for(page=0;page<2;page++)
{
LCD_WrCmd(port,0xb8+cy*2+page);
delayUs(100);
LCD_WrCmd(port,0x40+s);
delayUs(100);
for(i=0;i<16;i++)
{
LCD_WrDat(port,*p);
delayUs(10);
p++;
}
}
}
uchar oldUnderlineX=0,oldUnderlineY=0;
void resetUnderline(){
oldUnderlineX=0;
oldUnderlineY=0;
}
void DisplayUnderline(unsigned char cx,unsigned char cy,bit display)
{
uchar *p,i,s,page;
uchar port;
cy--;
if(display==0){
//²Áȥϻ®Ïß
}
if(oldUnderlineX!=0||oldUnderlineY!=0){
p=null16x16;
if(oldUnderlineX<4)
{
port=1;
s=oldUnderlineX<<4;
}
else
{
port=2;
s=((oldUnderlineX-4)<<4);
}
for(page=0;page<2;page++)
{
LCD_WrCmd(port,0xb8+oldUnderlineY*2+page);
delayUs(100);
LCD_WrCmd(port,0x40+s);
delayUs(100);
for(i=0;i<16;i++)
{
LCD_WrDat(port,*p);
delayUs(10);
p++;
}
}
}
oldUnderlineX=cx;
oldUnderlineY=cy;
p=underline16x16;
if(cx<4)
{
port=1;
s=cx<<4;
}
else
{
port=2;
s=((cx-4)<<4);
}
for(page=0;page<2;page++)
{
LCD_WrCmd(port,0xb8+cy*2+page);
delayUs(100);
LCD_WrCmd(port,0x40+s);
delayUs(100);
for(i=0;i<16;i++)
{
LCD_WrDat(port,*p);
delayUs(10);
p++;
}
}
}
void LCD_PutPosition(unsigned char x,unsigned char y)
{
DisplayUnderline(x,y+1,1);
}
void ClrScreen()
{
LCD_DispFill(0x00);
}
| gpl-2.0 |
ztemt/X6_NX601_kernel | arch/arm/mach-msm/acpuclock-krait.c | 1 | 32822 | /*
* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/cpufreq.h>
#include <linux/cpu.h>
#include <linux/regulator/consumer.h>
#include <linux/iopoll.h>
#include <asm/mach-types.h>
#include <asm/cpu.h>
#include <mach/board.h>
#include <mach/msm_iomap.h>
#include <mach/socinfo.h>
#include <mach/msm-krait-l2-accessors.h>
#include <mach/rpm-regulator.h>
#include <mach/rpm-regulator-smd.h>
#include <mach/msm_bus.h>
#include <mach/msm_dcvs.h>
#include "acpuclock.h"
#include "acpuclock-krait.h"
#include "avs.h"
/* MUX source selects. */
#define PRI_SRC_SEL_SEC_SRC 0
#define PRI_SRC_SEL_HFPLL 1
#define PRI_SRC_SEL_HFPLL_DIV2 2
static DEFINE_MUTEX(driver_lock);
static DEFINE_SPINLOCK(l2_lock);
static struct drv_data drv;
/* ZTEMT Added by LiuYongfeng, 2013/12/19 */
static int speed_bin = 0;
static int pvs_bin = 0;
/* ZTEMT END */
static unsigned long acpuclk_krait_get_rate(int cpu)
{
return drv.scalable[cpu].cur_speed->khz;
}
struct set_clk_src_args {
struct scalable *sc;
u32 src_sel;
};
static void __set_pri_clk_src(struct scalable *sc, u32 pri_src_sel)
{
u32 regval;
regval = get_l2_indirect_reg(sc->l2cpmr_iaddr);
regval &= ~0x3;
regval |= pri_src_sel;
if (sc != &drv.scalable[L2]) {
regval &= ~(0x3 << 8);
regval |= pri_src_sel << 8;
}
set_l2_indirect_reg(sc->l2cpmr_iaddr, regval);
/* Wait for switch to complete. */
mb();
udelay(1);
}
static void __set_cpu_pri_clk_src(void *data)
{
struct set_clk_src_args *args = data;
__set_pri_clk_src(args->sc, args->src_sel);
}
/* Select a source on the primary MUX. */
static void set_pri_clk_src(struct scalable *sc, u32 pri_src_sel)
{
int cpu = sc - drv.scalable;
if (sc != &drv.scalable[L2] && cpu_online(cpu)) {
struct set_clk_src_args args = {
.sc = sc,
.src_sel = pri_src_sel,
};
smp_call_function_single(cpu, __set_cpu_pri_clk_src, &args, 1);
} else {
__set_pri_clk_src(sc, pri_src_sel);
}
}
/* Select a source on the secondary MUX. */
static void __cpuinit set_sec_clk_src(struct scalable *sc, u32 sec_src_sel)
{
u32 regval;
regval = get_l2_indirect_reg(sc->l2cpmr_iaddr);
regval &= ~(0x3 << 2);
regval |= sec_src_sel << 2;
if (sc != &drv.scalable[L2]) {
regval &= ~(0x3 << 10);
regval |= sec_src_sel << 10;
}
set_l2_indirect_reg(sc->l2cpmr_iaddr, regval);
/* Wait for switch to complete. */
mb();
udelay(1);
}
static int enable_rpm_vreg(struct vreg *vreg)
{
int ret = 0;
if (vreg->rpm_reg) {
ret = rpm_regulator_enable(vreg->rpm_reg);
if (ret)
dev_err(drv.dev, "%s regulator enable failed (%d)\n",
vreg->name, ret);
}
return ret;
}
static void disable_rpm_vreg(struct vreg *vreg)
{
int rc;
if (vreg->rpm_reg) {
rc = rpm_regulator_disable(vreg->rpm_reg);
if (rc)
dev_err(drv.dev, "%s regulator disable failed (%d)\n",
vreg->name, rc);
}
}
/* Enable an already-configured HFPLL. */
static void hfpll_enable(struct scalable *sc, bool skip_regulators)
{
if (!skip_regulators) {
/* Enable regulators required by the HFPLL. */
enable_rpm_vreg(&sc->vreg[VREG_HFPLL_A]);
enable_rpm_vreg(&sc->vreg[VREG_HFPLL_B]);
}
/* Disable PLL bypass mode. */
writel_relaxed(0x2, sc->hfpll_base + drv.hfpll_data->mode_offset);
/*
* H/W requires a 5us delay between disabling the bypass and
* de-asserting the reset. Delay 10us just to be safe.
*/
mb();
udelay(10);
/* De-assert active-low PLL reset. */
writel_relaxed(0x6, sc->hfpll_base + drv.hfpll_data->mode_offset);
/* Wait for PLL to lock. */
if (drv.hfpll_data->has_lock_status) {
u32 regval;
readl_tight_poll(sc->hfpll_base + drv.hfpll_data->status_offset,
regval, regval & BIT(16));
} else {
mb();
udelay(60);
}
/* Enable PLL output. */
writel_relaxed(0x7, sc->hfpll_base + drv.hfpll_data->mode_offset);
}
/* Disable a HFPLL for power-savings or while it's being reprogrammed. */
static void hfpll_disable(struct scalable *sc, bool skip_regulators)
{
/*
* Disable the PLL output, disable test mode, enable the bypass mode,
* and assert the reset.
*/
writel_relaxed(0, sc->hfpll_base + drv.hfpll_data->mode_offset);
if (!skip_regulators) {
/* Remove voltage votes required by the HFPLL. */
disable_rpm_vreg(&sc->vreg[VREG_HFPLL_B]);
disable_rpm_vreg(&sc->vreg[VREG_HFPLL_A]);
}
}
/* Program the HFPLL rate. Assumes HFPLL is already disabled. */
static void hfpll_set_rate(struct scalable *sc, const struct core_speed *tgt_s)
{
void __iomem *base = sc->hfpll_base;
u32 regval;
writel_relaxed(tgt_s->pll_l_val, base + drv.hfpll_data->l_offset);
if (drv.hfpll_data->has_user_reg) {
regval = readl_relaxed(base + drv.hfpll_data->user_offset);
if (tgt_s->pll_l_val <= drv.hfpll_data->low_vco_l_max)
regval &= ~drv.hfpll_data->user_vco_mask;
else
regval |= drv.hfpll_data->user_vco_mask;
writel_relaxed(regval, base + drv.hfpll_data->user_offset);
}
}
/* Return the L2 speed that should be applied. */
static unsigned int compute_l2_level(struct scalable *sc, unsigned int vote_l)
{
unsigned int new_l = 0;
int cpu;
/* Find max L2 speed vote. */
sc->l2_vote = vote_l;
for_each_present_cpu(cpu)
new_l = max(new_l, drv.scalable[cpu].l2_vote);
return new_l;
}
/* Update the bus bandwidth request. */
static void set_bus_bw(unsigned int bw)
{
int ret;
/* Update bandwidth if request has changed. This may sleep. */
ret = msm_bus_scale_client_update_request(drv.bus_perf_client, bw);
if (ret)
dev_err(drv.dev, "bandwidth request failed (%d)\n", ret);
}
/* Set the CPU or L2 clock speed. */
static void set_speed(struct scalable *sc, const struct core_speed *tgt_s,
bool skip_regulators)
{
const struct core_speed *strt_s = sc->cur_speed;
if (strt_s == tgt_s)
return;
if (strt_s->src == HFPLL && tgt_s->src == HFPLL) {
/*
* Move to an always-on source running at a frequency
* that does not require an elevated CPU voltage.
*/
set_pri_clk_src(sc, PRI_SRC_SEL_SEC_SRC);
/* Re-program HFPLL. */
hfpll_disable(sc, true);
hfpll_set_rate(sc, tgt_s);
hfpll_enable(sc, true);
/* Move to HFPLL. */
set_pri_clk_src(sc, tgt_s->pri_src_sel);
} else if (strt_s->src == HFPLL && tgt_s->src != HFPLL) {
set_pri_clk_src(sc, tgt_s->pri_src_sel);
hfpll_disable(sc, skip_regulators);
} else if (strt_s->src != HFPLL && tgt_s->src == HFPLL) {
hfpll_set_rate(sc, tgt_s);
hfpll_enable(sc, skip_regulators);
set_pri_clk_src(sc, tgt_s->pri_src_sel);
}
sc->cur_speed = tgt_s;
}
struct vdd_data {
int vdd_mem;
int vdd_dig;
int vdd_core;
int ua_core;
};
/* Apply any per-cpu voltage increases. */
static int increase_vdd(int cpu, struct vdd_data *data,
enum setrate_reason reason)
{
struct scalable *sc = &drv.scalable[cpu];
int rc;
/*
* Increase vdd_mem active-set before vdd_dig.
* vdd_mem should be >= vdd_dig.
*/
if (data->vdd_mem > sc->vreg[VREG_MEM].cur_vdd) {
rc = rpm_regulator_set_voltage(sc->vreg[VREG_MEM].rpm_reg,
data->vdd_mem, sc->vreg[VREG_MEM].max_vdd);
if (rc) {
dev_err(drv.dev,
"vdd_mem (cpu%d) increase failed (%d)\n",
cpu, rc);
return rc;
}
sc->vreg[VREG_MEM].cur_vdd = data->vdd_mem;
}
/* Increase vdd_dig active-set vote. */
if (data->vdd_dig > sc->vreg[VREG_DIG].cur_vdd) {
rc = rpm_regulator_set_voltage(sc->vreg[VREG_DIG].rpm_reg,
data->vdd_dig, sc->vreg[VREG_DIG].max_vdd);
if (rc) {
dev_err(drv.dev,
"vdd_dig (cpu%d) increase failed (%d)\n",
cpu, rc);
return rc;
}
sc->vreg[VREG_DIG].cur_vdd = data->vdd_dig;
}
/* Increase current request. */
if (data->ua_core > sc->vreg[VREG_CORE].cur_ua) {
rc = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg,
data->ua_core);
if (rc < 0) {
dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n",
sc->vreg[VREG_CORE].name, rc);
return rc;
}
sc->vreg[VREG_CORE].cur_ua = data->ua_core;
}
/*
* Update per-CPU core voltage. Don't do this for the hotplug path for
* which it should already be correct. Attempting to set it is bad
* because we don't know what CPU we are running on at this point, but
* the CPU regulator API requires we call it from the affected CPU.
*/
if (data->vdd_core > sc->vreg[VREG_CORE].cur_vdd
&& reason != SETRATE_HOTPLUG) {
rc = regulator_set_voltage(sc->vreg[VREG_CORE].reg,
data->vdd_core, sc->vreg[VREG_CORE].max_vdd);
if (rc) {
dev_err(drv.dev,
"vdd_core (cpu%d) increase failed (%d)\n",
cpu, rc);
return rc;
}
sc->vreg[VREG_CORE].cur_vdd = data->vdd_core;
}
return 0;
}
/* Apply any per-cpu voltage decreases. */
static void decrease_vdd(int cpu, struct vdd_data *data,
enum setrate_reason reason)
{
struct scalable *sc = &drv.scalable[cpu];
int ret;
/*
* Update per-CPU core voltage. This must be called on the CPU
* that's being affected. Don't do this in the hotplug remove path,
* where the rail is off and we're executing on the other CPU.
*/
if (data->vdd_core < sc->vreg[VREG_CORE].cur_vdd
&& reason != SETRATE_HOTPLUG) {
ret = regulator_set_voltage(sc->vreg[VREG_CORE].reg,
data->vdd_core, sc->vreg[VREG_CORE].max_vdd);
if (ret) {
dev_err(drv.dev,
"vdd_core (cpu%d) decrease failed (%d)\n",
cpu, ret);
return;
}
sc->vreg[VREG_CORE].cur_vdd = data->vdd_core;
}
/* Decrease current request. */
if (data->ua_core < sc->vreg[VREG_CORE].cur_ua) {
ret = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg,
data->ua_core);
if (ret < 0) {
dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n",
sc->vreg[VREG_CORE].name, ret);
return;
}
sc->vreg[VREG_CORE].cur_ua = data->ua_core;
}
/* Decrease vdd_dig active-set vote. */
if (data->vdd_dig < sc->vreg[VREG_DIG].cur_vdd) {
ret = rpm_regulator_set_voltage(sc->vreg[VREG_DIG].rpm_reg,
data->vdd_dig, sc->vreg[VREG_DIG].max_vdd);
if (ret) {
dev_err(drv.dev,
"vdd_dig (cpu%d) decrease failed (%d)\n",
cpu, ret);
return;
}
sc->vreg[VREG_DIG].cur_vdd = data->vdd_dig;
}
/*
* Decrease vdd_mem active-set after vdd_dig.
* vdd_mem should be >= vdd_dig.
*/
if (data->vdd_mem < sc->vreg[VREG_MEM].cur_vdd) {
ret = rpm_regulator_set_voltage(sc->vreg[VREG_MEM].rpm_reg,
data->vdd_mem, sc->vreg[VREG_MEM].max_vdd);
if (ret) {
dev_err(drv.dev,
"vdd_mem (cpu%d) decrease failed (%d)\n",
cpu, ret);
return;
}
sc->vreg[VREG_MEM].cur_vdd = data->vdd_mem;
}
}
static int calculate_vdd_mem(const struct acpu_level *tgt)
{
return drv.l2_freq_tbl[tgt->l2_level].vdd_mem;
}
static int get_src_dig(const struct core_speed *s)
{
const int *hfpll_vdd = drv.hfpll_data->vdd;
const u32 low_vdd_l_max = drv.hfpll_data->low_vdd_l_max;
const u32 nom_vdd_l_max = drv.hfpll_data->nom_vdd_l_max;
if (s->src != HFPLL)
return hfpll_vdd[HFPLL_VDD_NONE];
else if (s->pll_l_val > nom_vdd_l_max)
return hfpll_vdd[HFPLL_VDD_HIGH];
else if (s->pll_l_val > low_vdd_l_max)
return hfpll_vdd[HFPLL_VDD_NOM];
else
return hfpll_vdd[HFPLL_VDD_LOW];
}
static int calculate_vdd_dig(const struct acpu_level *tgt)
{
int l2_pll_vdd_dig, cpu_pll_vdd_dig;
l2_pll_vdd_dig = get_src_dig(&drv.l2_freq_tbl[tgt->l2_level].speed);
cpu_pll_vdd_dig = get_src_dig(&tgt->speed);
return max(drv.l2_freq_tbl[tgt->l2_level].vdd_dig,
max(l2_pll_vdd_dig, cpu_pll_vdd_dig));
}
static bool enable_boost = true;
module_param_named(boost, enable_boost, bool, S_IRUGO | S_IWUSR);
static int calculate_vdd_core(const struct acpu_level *tgt)
{
return tgt->vdd_core + (enable_boost ? drv.boost_uv : 0);
}
static DEFINE_MUTEX(l2_regulator_lock);
static int l2_vreg_count;
static int enable_l2_regulators(void)
{
int ret = 0;
mutex_lock(&l2_regulator_lock);
if (l2_vreg_count == 0) {
ret = enable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]);
if (ret)
goto out;
ret = enable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_B]);
if (ret) {
disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]);
goto out;
}
}
l2_vreg_count++;
out:
mutex_unlock(&l2_regulator_lock);
return ret;
}
static void disable_l2_regulators(void)
{
mutex_lock(&l2_regulator_lock);
if (WARN(!l2_vreg_count, "L2 regulator votes are unbalanced!"))
goto out;
if (l2_vreg_count == 1) {
disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_B]);
disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]);
}
l2_vreg_count--;
out:
mutex_unlock(&l2_regulator_lock);
}
/* Set the CPU's clock rate and adjust the L2 rate, voltage and BW requests. */
static int acpuclk_krait_set_rate(int cpu, unsigned long rate,
enum setrate_reason reason)
{
const struct core_speed *strt_acpu_s, *tgt_acpu_s;
const struct acpu_level *tgt;
int tgt_l2_l;
enum src_id prev_l2_src = NUM_SRC_ID;
struct vdd_data vdd_data;
bool skip_regulators;
int rc = 0;
if (cpu > num_possible_cpus())
return -EINVAL;
if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG)
mutex_lock(&driver_lock);
strt_acpu_s = drv.scalable[cpu].cur_speed;
/* Return early if rate didn't change. */
if (rate == strt_acpu_s->khz)
goto out;
/* Find target frequency. */
for (tgt = drv.acpu_freq_tbl; tgt->speed.khz != 0; tgt++) {
if (tgt->speed.khz == rate) {
tgt_acpu_s = &tgt->speed;
break;
}
}
if (tgt->speed.khz == 0) {
rc = -EINVAL;
goto out;
}
/* Calculate voltage requirements for the current CPU. */
vdd_data.vdd_mem = calculate_vdd_mem(tgt);
vdd_data.vdd_dig = calculate_vdd_dig(tgt);
vdd_data.vdd_core = calculate_vdd_core(tgt);
vdd_data.ua_core = tgt->ua_core;
/* Disable AVS before voltage switch */
if (reason == SETRATE_CPUFREQ && drv.scalable[cpu].avs_enabled) {
AVS_DISABLE(cpu);
drv.scalable[cpu].avs_enabled = false;
}
/* Increase VDD levels if needed. */
if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG) {
rc = increase_vdd(cpu, &vdd_data, reason);
if (rc)
goto out;
prev_l2_src =
drv.l2_freq_tbl[drv.scalable[cpu].l2_vote].speed.src;
/* Vote for the L2 regulators here if necessary. */
if (drv.l2_freq_tbl[tgt->l2_level].speed.src == HFPLL) {
rc = enable_l2_regulators();
if (rc)
goto out;
}
}
dev_dbg(drv.dev, "Switching from ACPU%d rate %lu KHz -> %lu KHz\n",
cpu, strt_acpu_s->khz, tgt_acpu_s->khz);
/*
* If we are setting the rate as part of power collapse or in the resume
* path after power collapse, skip the vote for the HFPLL regulators,
* which are active-set-only votes that will be removed when apps enters
* its sleep set. This is needed to avoid voting for regulators with
* sleeping APIs from an atomic context.
*/
skip_regulators = (reason == SETRATE_PC);
/* Set the new CPU speed. */
set_speed(&drv.scalable[cpu], tgt_acpu_s, skip_regulators);
/*
* Update the L2 vote and apply the rate change. A spinlock is
* necessary to ensure L2 rate is calculated and set atomically
* with the CPU frequency, even if acpuclk_krait_set_rate() is
* called from an atomic context and the driver_lock mutex is not
* acquired.
*/
spin_lock(&l2_lock);
tgt_l2_l = compute_l2_level(&drv.scalable[cpu], tgt->l2_level);
set_speed(&drv.scalable[L2],
&drv.l2_freq_tbl[tgt_l2_l].speed, true);
spin_unlock(&l2_lock);
/* Nothing else to do for power collapse or SWFI. */
if (reason == SETRATE_PC || reason == SETRATE_SWFI)
goto out;
/*
* Remove the vote for the L2 HFPLL regulators only if the L2
* was already on an HFPLL source.
*/
if (prev_l2_src == HFPLL)
disable_l2_regulators();
/* Update bus bandwith request. */
set_bus_bw(drv.l2_freq_tbl[tgt_l2_l].bw_level);
/* Drop VDD levels if we can. */
decrease_vdd(cpu, &vdd_data, reason);
/* Re-enable AVS */
if (reason == SETRATE_CPUFREQ && tgt->avsdscr_setting) {
AVS_ENABLE(cpu, tgt->avsdscr_setting);
drv.scalable[cpu].avs_enabled = true;
}
dev_dbg(drv.dev, "ACPU%d speed change complete\n", cpu);
out:
if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG)
mutex_unlock(&driver_lock);
return rc;
}
static struct acpuclk_data acpuclk_krait_data = {
.set_rate = acpuclk_krait_set_rate,
.get_rate = acpuclk_krait_get_rate,
};
/* Initialize a HFPLL at a given rate and enable it. */
static void __cpuinit hfpll_init(struct scalable *sc,
const struct core_speed *tgt_s)
{
dev_dbg(drv.dev, "Initializing HFPLL%d\n", sc - drv.scalable);
/* Disable the PLL for re-programming. */
hfpll_disable(sc, true);
/* Configure PLL parameters for integer mode. */
writel_relaxed(drv.hfpll_data->config_val,
sc->hfpll_base + drv.hfpll_data->config_offset);
writel_relaxed(0, sc->hfpll_base + drv.hfpll_data->m_offset);
writel_relaxed(1, sc->hfpll_base + drv.hfpll_data->n_offset);
if (drv.hfpll_data->has_user_reg)
writel_relaxed(drv.hfpll_data->user_val,
sc->hfpll_base + drv.hfpll_data->user_offset);
/* Program droop controller, if supported */
if (drv.hfpll_data->has_droop_ctl)
writel_relaxed(drv.hfpll_data->droop_val,
sc->hfpll_base + drv.hfpll_data->droop_offset);
/* Set an initial PLL rate. */
hfpll_set_rate(sc, tgt_s);
}
static int __cpuinit rpm_regulator_init(struct scalable *sc, enum vregs vreg,
int vdd, bool enable)
{
int ret;
if (!sc->vreg[vreg].name)
return 0;
sc->vreg[vreg].rpm_reg = rpm_regulator_get(drv.dev,
sc->vreg[vreg].name);
if (IS_ERR(sc->vreg[vreg].rpm_reg)) {
ret = PTR_ERR(sc->vreg[vreg].rpm_reg);
dev_err(drv.dev, "rpm_regulator_get(%s) failed (%d)\n",
sc->vreg[vreg].name, ret);
goto err_get;
}
ret = rpm_regulator_set_voltage(sc->vreg[vreg].rpm_reg, vdd,
sc->vreg[vreg].max_vdd);
if (ret) {
dev_err(drv.dev, "%s initialization failed (%d)\n",
sc->vreg[vreg].name, ret);
goto err_conf;
}
sc->vreg[vreg].cur_vdd = vdd;
if (enable) {
ret = enable_rpm_vreg(&sc->vreg[vreg]);
if (ret)
goto err_conf;
}
return 0;
err_conf:
rpm_regulator_put(sc->vreg[vreg].rpm_reg);
err_get:
return ret;
}
static void __cpuinit rpm_regulator_cleanup(struct scalable *sc,
enum vregs vreg)
{
if (!sc->vreg[vreg].rpm_reg)
return;
disable_rpm_vreg(&sc->vreg[vreg]);
rpm_regulator_put(sc->vreg[vreg].rpm_reg);
}
/* Voltage regulator initialization. */
static int __cpuinit regulator_init(struct scalable *sc,
const struct acpu_level *acpu_level)
{
int ret, vdd_mem, vdd_dig, vdd_core;
vdd_mem = calculate_vdd_mem(acpu_level);
ret = rpm_regulator_init(sc, VREG_MEM, vdd_mem, true);
if (ret)
goto err_mem;
vdd_dig = calculate_vdd_dig(acpu_level);
ret = rpm_regulator_init(sc, VREG_DIG, vdd_dig, true);
if (ret)
goto err_dig;
ret = rpm_regulator_init(sc, VREG_HFPLL_A,
sc->vreg[VREG_HFPLL_A].max_vdd, false);
if (ret)
goto err_hfpll_a;
ret = rpm_regulator_init(sc, VREG_HFPLL_B,
sc->vreg[VREG_HFPLL_B].max_vdd, false);
if (ret)
goto err_hfpll_b;
/* Setup Krait CPU regulators and initial core voltage. */
sc->vreg[VREG_CORE].reg = regulator_get(drv.dev,
sc->vreg[VREG_CORE].name);
if (IS_ERR(sc->vreg[VREG_CORE].reg)) {
ret = PTR_ERR(sc->vreg[VREG_CORE].reg);
dev_err(drv.dev, "regulator_get(%s) failed (%d)\n",
sc->vreg[VREG_CORE].name, ret);
goto err_core_get;
}
ret = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg,
acpu_level->ua_core);
if (ret < 0) {
dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n",
sc->vreg[VREG_CORE].name, ret);
goto err_core_conf;
}
sc->vreg[VREG_CORE].cur_ua = acpu_level->ua_core;
vdd_core = calculate_vdd_core(acpu_level);
ret = regulator_set_voltage(sc->vreg[VREG_CORE].reg, vdd_core,
sc->vreg[VREG_CORE].max_vdd);
if (ret) {
dev_err(drv.dev, "regulator_set_voltage(%s) (%d)\n",
sc->vreg[VREG_CORE].name, ret);
goto err_core_conf;
}
sc->vreg[VREG_CORE].cur_vdd = vdd_core;
ret = regulator_enable(sc->vreg[VREG_CORE].reg);
if (ret) {
dev_err(drv.dev, "regulator_enable(%s) failed (%d)\n",
sc->vreg[VREG_CORE].name, ret);
goto err_core_conf;
}
/*
* Vote for the L2 HFPLL regulators if _this_ CPU's frequency requires
* a corresponding target L2 frequency that needs the L2 an HFPLL.
*/
if (drv.l2_freq_tbl[acpu_level->l2_level].speed.src == HFPLL) {
ret = enable_l2_regulators();
if (ret) {
dev_err(drv.dev, "enable_l2_regulators() failed (%d)\n",
ret);
goto err_l2_regs;
}
}
return 0;
err_l2_regs:
regulator_disable(sc->vreg[VREG_CORE].reg);
err_core_conf:
regulator_put(sc->vreg[VREG_CORE].reg);
err_core_get:
rpm_regulator_cleanup(sc, VREG_HFPLL_B);
err_hfpll_b:
rpm_regulator_cleanup(sc, VREG_HFPLL_A);
err_hfpll_a:
rpm_regulator_cleanup(sc, VREG_DIG);
err_dig:
rpm_regulator_cleanup(sc, VREG_MEM);
err_mem:
return ret;
}
static void __cpuinit regulator_cleanup(struct scalable *sc)
{
regulator_disable(sc->vreg[VREG_CORE].reg);
regulator_put(sc->vreg[VREG_CORE].reg);
rpm_regulator_cleanup(sc, VREG_HFPLL_B);
rpm_regulator_cleanup(sc, VREG_HFPLL_A);
rpm_regulator_cleanup(sc, VREG_DIG);
rpm_regulator_cleanup(sc, VREG_MEM);
}
/* Set initial rate for a given core. */
static int __cpuinit init_clock_sources(struct scalable *sc,
const struct core_speed *tgt_s)
{
u32 regval;
void __iomem *aux_reg;
/* Program AUX source input to the secondary MUX. */
if (sc->aux_clk_sel_phys) {
aux_reg = ioremap(sc->aux_clk_sel_phys, 4);
if (!aux_reg)
return -ENOMEM;
writel_relaxed(sc->aux_clk_sel, aux_reg);
iounmap(aux_reg);
}
/* Switch away from the HFPLL while it's re-initialized. */
set_sec_clk_src(sc, sc->sec_clk_sel);
set_pri_clk_src(sc, PRI_SRC_SEL_SEC_SRC);
hfpll_init(sc, tgt_s);
/* Set PRI_SRC_SEL_HFPLL_DIV2 divider to div-2. */
regval = get_l2_indirect_reg(sc->l2cpmr_iaddr);
regval &= ~(0x3 << 6);
if (sc != &drv.scalable[L2])
regval &= ~(0x3 << 14);
set_l2_indirect_reg(sc->l2cpmr_iaddr, regval);
/* Enable and switch to the target clock source. */
if (tgt_s->src == HFPLL)
hfpll_enable(sc, false);
set_pri_clk_src(sc, tgt_s->pri_src_sel);
sc->cur_speed = tgt_s;
return 0;
}
static void __cpuinit fill_cur_core_speed(struct core_speed *s,
struct scalable *sc)
{
s->pri_src_sel = get_l2_indirect_reg(sc->l2cpmr_iaddr) & 0x3;
s->pll_l_val = readl_relaxed(sc->hfpll_base + drv.hfpll_data->l_offset);
}
static bool __cpuinit speed_equal(const struct core_speed *s1,
const struct core_speed *s2)
{
return (s1->pri_src_sel == s2->pri_src_sel &&
s1->pll_l_val == s2->pll_l_val);
}
static const struct acpu_level __cpuinit *find_cur_acpu_level(int cpu)
{
struct scalable *sc = &drv.scalable[cpu];
const struct acpu_level *l;
struct core_speed cur_speed;
fill_cur_core_speed(&cur_speed, sc);
for (l = drv.acpu_freq_tbl; l->speed.khz != 0; l++)
if (speed_equal(&l->speed, &cur_speed))
return l;
return NULL;
}
static const struct l2_level __init *find_cur_l2_level(void)
{
struct scalable *sc = &drv.scalable[L2];
const struct l2_level *l;
struct core_speed cur_speed;
fill_cur_core_speed(&cur_speed, sc);
for (l = drv.l2_freq_tbl; l->speed.khz != 0; l++)
if (speed_equal(&l->speed, &cur_speed))
return l;
return NULL;
}
static const struct acpu_level __cpuinit *find_min_acpu_level(void)
{
struct acpu_level *l;
for (l = drv.acpu_freq_tbl; l->speed.khz != 0; l++)
if (l->use_for_scaling)
return l;
return NULL;
}
static int __cpuinit per_cpu_init(int cpu)
{
struct scalable *sc = &drv.scalable[cpu];
const struct acpu_level *acpu_level;
int ret;
sc->hfpll_base = ioremap(sc->hfpll_phys_base, SZ_32);
if (!sc->hfpll_base) {
ret = -ENOMEM;
goto err_ioremap;
}
acpu_level = find_cur_acpu_level(cpu);
if (!acpu_level) {
acpu_level = find_min_acpu_level();
if (!acpu_level) {
ret = -ENODEV;
goto err_table;
}
dev_warn(drv.dev, "CPU%d is running at an unknown rate. Defaulting to %lu KHz.\n",
cpu, acpu_level->speed.khz);
} else {
dev_dbg(drv.dev, "CPU%d is running at %lu KHz\n", cpu,
acpu_level->speed.khz);
}
ret = regulator_init(sc, acpu_level);
if (ret)
goto err_regulators;
ret = init_clock_sources(sc, &acpu_level->speed);
if (ret)
goto err_clocks;
sc->l2_vote = acpu_level->l2_level;
sc->initialized = true;
return 0;
err_clocks:
regulator_cleanup(sc);
err_regulators:
err_table:
iounmap(sc->hfpll_base);
err_ioremap:
return ret;
}
/* Register with bus driver. */
static void __init bus_init(const struct l2_level *l2_level)
{
int ret;
drv.bus_perf_client = msm_bus_scale_register_client(drv.bus_scale);
if (!drv.bus_perf_client) {
dev_err(drv.dev, "unable to register bus client\n");
BUG();
}
ret = msm_bus_scale_client_update_request(drv.bus_perf_client,
l2_level->bw_level);
if (ret)
dev_err(drv.dev, "initial bandwidth req failed (%d)\n", ret);
}
#ifdef CONFIG_CPU_FREQ_MSM
static struct cpufreq_frequency_table freq_table[NR_CPUS][35];
static void __init cpufreq_table_init(void)
{
int cpu;
int freq_cnt = 0;
for_each_possible_cpu(cpu) {
int i;
/* Construct the freq_table tables from acpu_freq_tbl. */
for (i = 0, freq_cnt = 0; drv.acpu_freq_tbl[i].speed.khz != 0
&& freq_cnt < ARRAY_SIZE(*freq_table); i++) {
if (drv.acpu_freq_tbl[i].use_for_scaling) {
freq_table[cpu][freq_cnt].index = freq_cnt;
freq_table[cpu][freq_cnt].frequency
= drv.acpu_freq_tbl[i].speed.khz;
freq_cnt++;
}
}
/* freq_table not big enough to store all usable freqs. */
BUG_ON(drv.acpu_freq_tbl[i].speed.khz != 0);
freq_table[cpu][freq_cnt].index = freq_cnt;
freq_table[cpu][freq_cnt].frequency = CPUFREQ_TABLE_END;
/* Register table with CPUFreq. */
cpufreq_frequency_table_get_attr(freq_table[cpu], cpu);
}
dev_info(drv.dev, "CPU Frequencies Supported: %d\n", freq_cnt);
}
#else
static void __init cpufreq_table_init(void) {}
#endif
static void __init dcvs_freq_init(void)
{
int i;
for (i = 0; drv.acpu_freq_tbl[i].speed.khz != 0; i++)
if (drv.acpu_freq_tbl[i].use_for_scaling)
msm_dcvs_register_cpu_freq(
drv.acpu_freq_tbl[i].speed.khz,
drv.acpu_freq_tbl[i].vdd_core / 1000);
}
static int __cpuinit acpuclk_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
static int prev_khz[NR_CPUS];
int rc, cpu = (int)hcpu;
struct scalable *sc = &drv.scalable[cpu];
unsigned long hot_unplug_khz = acpuclk_krait_data.power_collapse_khz;
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_DEAD:
prev_khz[cpu] = acpuclk_krait_get_rate(cpu);
/* Fall through. */
case CPU_UP_CANCELED:
acpuclk_krait_set_rate(cpu, hot_unplug_khz, SETRATE_HOTPLUG);
regulator_disable(sc->vreg[VREG_CORE].reg);
regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, 0);
regulator_set_voltage(sc->vreg[VREG_CORE].reg, 0,
sc->vreg[VREG_CORE].max_vdd);
break;
case CPU_UP_PREPARE:
if (!sc->initialized) {
rc = per_cpu_init(cpu);
if (rc)
return NOTIFY_BAD;
break;
}
if (WARN_ON(!prev_khz[cpu]))
return NOTIFY_BAD;
rc = regulator_set_voltage(sc->vreg[VREG_CORE].reg,
sc->vreg[VREG_CORE].cur_vdd,
sc->vreg[VREG_CORE].max_vdd);
if (rc < 0)
return NOTIFY_BAD;
rc = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg,
sc->vreg[VREG_CORE].cur_ua);
if (rc < 0)
return NOTIFY_BAD;
rc = regulator_enable(sc->vreg[VREG_CORE].reg);
if (rc < 0)
return NOTIFY_BAD;
acpuclk_krait_set_rate(cpu, prev_khz[cpu], SETRATE_HOTPLUG);
break;
default:
break;
}
return NOTIFY_OK;
}
static struct notifier_block __cpuinitdata acpuclk_cpu_notifier = {
.notifier_call = acpuclk_cpu_callback,
};
static const int __init krait_needs_vmin(void)
{
switch (read_cpuid_id()) {
case 0x511F04D0: /* KR28M2A20 */
case 0x511F04D1: /* KR28M2A21 */
case 0x510F06F0: /* KR28M4A10 */
return 1;
default:
return 0;
};
}
static void __init krait_apply_vmin(struct acpu_level *tbl)
{
for (; tbl->speed.khz != 0; tbl++) {
if (tbl->vdd_core < 1150000)
tbl->vdd_core = 1150000;
tbl->avsdscr_setting = 0;
}
}
void __init get_krait_bin_format_a(void __iomem *base, struct bin_info *bin)
{
u32 pte_efuse = readl_relaxed(base);
bin->speed = pte_efuse & 0xF;
if (bin->speed == 0xF)
bin->speed = (pte_efuse >> 4) & 0xF;
bin->speed_valid = bin->speed != 0xF;
bin->pvs = (pte_efuse >> 10) & 0x7;
if (bin->pvs == 0x7)
bin->pvs = (pte_efuse >> 13) & 0x7;
bin->pvs_valid = bin->pvs != 0x7;
}
void __init get_krait_bin_format_b(void __iomem *base, struct bin_info *bin)
{
u32 pte_efuse, redundant_sel;
pte_efuse = readl_relaxed(base);
redundant_sel = (pte_efuse >> 24) & 0x7;
bin->pvs_rev = (pte_efuse >> 4) & 0x3;
bin->speed = pte_efuse & 0x7;
/* PVS number is in bits 31, 8, 7, 6 */
bin->pvs = ((pte_efuse >> 28) & 0x8) | ((pte_efuse >> 6) & 0x7);
switch (redundant_sel) {
case 1:
bin->speed = (pte_efuse >> 27) & 0xF;
break;
case 2:
bin->pvs = (pte_efuse >> 27) & 0xF;
break;
}
bin->speed_valid = true;
/* Check PVS_BLOW_STATUS */
pte_efuse = readl_relaxed(base + 0x4);
bin->pvs_valid = !!(pte_efuse & BIT(21));
}
static struct pvs_table * __init select_freq_plan(
const struct acpuclk_krait_params *params)
{
void __iomem *pte_efuse_base;
struct bin_info bin;
pte_efuse_base = ioremap(params->pte_efuse_phys, 8);
if (!pte_efuse_base) {
dev_err(drv.dev, "Unable to map PTE eFuse base\n");
return NULL;
}
params->get_bin_info(pte_efuse_base, &bin);
iounmap(pte_efuse_base);
if (bin.speed_valid) {
drv.speed_bin = bin.speed;
dev_info(drv.dev, "SPEED BIN: %d\n", drv.speed_bin);
} else {
drv.speed_bin = 0;
dev_info(drv.dev, "SPEED BIN: Defaulting to %d\n",
drv.speed_bin);
}
if (bin.pvs_valid) {
drv.pvs_bin = bin.pvs;
dev_info(drv.dev, "ACPU PVS: %d\n", drv.pvs_bin);
drv.pvs_rev = bin.pvs_rev;
dev_info(drv.dev, "ACPU PVS REVISION: %d\n", drv.pvs_rev);
} else {
drv.pvs_bin = 0;
dev_info(drv.dev, "ACPU PVS: Defaulting to %d\n",
drv.pvs_bin);
}
//L1 error debug code, add by yfliu, case:01393461
// return ¶ms->pvs_tables[drv.pvs_rev][drv.speed_bin][drv.pvs_bin];
speed_bin = drv.speed_bin;
pvs_bin = drv.pvs_bin;
return ¶ms->pvs_tables[drv.pvs_rev][drv.speed_bin][0];
}
static void __init drv_data_init(struct device *dev,
const struct acpuclk_krait_params *params)
{
struct pvs_table *pvs;
drv.dev = dev;
drv.scalable = kmemdup(params->scalable, params->scalable_size,
GFP_KERNEL);
BUG_ON(!drv.scalable);
drv.hfpll_data = kmemdup(params->hfpll_data, sizeof(*drv.hfpll_data),
GFP_KERNEL);
BUG_ON(!drv.hfpll_data);
drv.l2_freq_tbl = kmemdup(params->l2_freq_tbl, params->l2_freq_tbl_size,
GFP_KERNEL);
BUG_ON(!drv.l2_freq_tbl);
drv.bus_scale = kmemdup(params->bus_scale, sizeof(*drv.bus_scale),
GFP_KERNEL);
BUG_ON(!drv.bus_scale);
drv.bus_scale->usecase = kmemdup(drv.bus_scale->usecase,
drv.bus_scale->num_usecases * sizeof(*drv.bus_scale->usecase),
GFP_KERNEL);
BUG_ON(!drv.bus_scale->usecase);
pvs = select_freq_plan(params);
BUG_ON(!pvs->table);
drv.acpu_freq_tbl = kmemdup(pvs->table, pvs->size, GFP_KERNEL);
BUG_ON(!drv.acpu_freq_tbl);
drv.boost_uv = pvs->boost_uv;
acpuclk_krait_data.power_collapse_khz = params->stby_khz;
acpuclk_krait_data.wait_for_irq_khz = params->stby_khz;
}
static void __init hw_init(void)
{
struct scalable *l2 = &drv.scalable[L2];
const struct l2_level *l2_level;
int cpu, rc;
if (krait_needs_vmin())
krait_apply_vmin(drv.acpu_freq_tbl);
l2->hfpll_base = ioremap(l2->hfpll_phys_base, SZ_32);
BUG_ON(!l2->hfpll_base);
rc = rpm_regulator_init(l2, VREG_HFPLL_A,
l2->vreg[VREG_HFPLL_A].max_vdd, false);
BUG_ON(rc);
rc = rpm_regulator_init(l2, VREG_HFPLL_B,
l2->vreg[VREG_HFPLL_B].max_vdd, false);
BUG_ON(rc);
l2_level = find_cur_l2_level();
if (!l2_level) {
l2_level = drv.l2_freq_tbl;
dev_warn(drv.dev, "L2 is running at an unknown rate. Defaulting to %lu KHz.\n",
l2_level->speed.khz);
} else {
dev_dbg(drv.dev, "L2 is running at %lu KHz\n",
l2_level->speed.khz);
}
rc = init_clock_sources(l2, &l2_level->speed);
BUG_ON(rc);
for_each_online_cpu(cpu) {
rc = per_cpu_init(cpu);
BUG_ON(rc);
}
bus_init(l2_level);
}
int __init acpuclk_krait_init(struct device *dev,
const struct acpuclk_krait_params *params)
{
drv_data_init(dev, params);
hw_init();
cpufreq_table_init();
dcvs_freq_init();
acpuclk_register(&acpuclk_krait_data);
register_hotcpu_notifier(&acpuclk_cpu_notifier);
acpuclk_krait_debug_init(&drv);
return 0;
}
| gpl-2.0 |
evolver56k/xpenology | arch/arm/mach-sa1100/simpad.c | 1 | 8669 | /*
* linux/arch/arm/mach-sa1100/simpad.c
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/tty.h>
#include <linux/proc_fs.h>
#include <linux/string.h>
#include <linux/pm.h>
#include <linux/platform_data/sa11x0-serial.h>
#include <linux/platform_device.h>
#include <linux/mfd/ucb1x00.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <mach/hardware.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/flash.h>
#include <asm/mach/map.h>
#include <linux/platform_data/mfd-mcp-sa11x0.h>
#include <mach/simpad.h>
#include <mach/irqs.h>
#include <linux/serial_core.h>
#include <linux/ioport.h>
#include <linux/input.h>
#include <linux/gpio_keys.h>
#include <linux/leds.h>
#include <linux/i2c-gpio.h>
#include "generic.h"
/*
* CS3 support
*/
static long cs3_shadow;
static spinlock_t cs3_lock;
static struct gpio_chip cs3_gpio;
long simpad_get_cs3_ro(void)
{
return readl(CS3_BASE);
}
EXPORT_SYMBOL(simpad_get_cs3_ro);
long simpad_get_cs3_shadow(void)
{
return cs3_shadow;
}
EXPORT_SYMBOL(simpad_get_cs3_shadow);
static void __simpad_write_cs3(void)
{
writel(cs3_shadow, CS3_BASE);
}
void simpad_set_cs3_bit(int value)
{
unsigned long flags;
spin_lock_irqsave(&cs3_lock, flags);
cs3_shadow |= value;
__simpad_write_cs3();
spin_unlock_irqrestore(&cs3_lock, flags);
}
EXPORT_SYMBOL(simpad_set_cs3_bit);
void simpad_clear_cs3_bit(int value)
{
unsigned long flags;
spin_lock_irqsave(&cs3_lock, flags);
cs3_shadow &= ~value;
__simpad_write_cs3();
spin_unlock_irqrestore(&cs3_lock, flags);
}
EXPORT_SYMBOL(simpad_clear_cs3_bit);
static void cs3_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
if (offset > 15)
return;
if (value)
simpad_set_cs3_bit(1 << offset);
else
simpad_clear_cs3_bit(1 << offset);
};
static int cs3_gpio_get(struct gpio_chip *chip, unsigned offset)
{
if (offset > 15)
return simpad_get_cs3_ro() & (1 << (offset - 16));
return simpad_get_cs3_shadow() & (1 << offset);
};
static int cs3_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
if (offset > 15)
return 0;
return -EINVAL;
};
static int cs3_gpio_direction_output(struct gpio_chip *chip, unsigned offset,
int value)
{
if (offset > 15)
return -EINVAL;
cs3_gpio_set(chip, offset, value);
return 0;
};
static struct map_desc simpad_io_desc[] __initdata = {
{ /* MQ200 */
.virtual = 0xf2800000,
.pfn = __phys_to_pfn(0x4b800000),
.length = 0x00800000,
.type = MT_DEVICE
}, { /* Simpad CS3 */
.virtual = (unsigned long)CS3_BASE,
.pfn = __phys_to_pfn(SA1100_CS3_PHYS),
.length = 0x00100000,
.type = MT_DEVICE
},
};
static void simpad_uart_pm(struct uart_port *port, u_int state, u_int oldstate)
{
if (port->mapbase == (u_int)&Ser1UTCR0) {
if (state)
{
simpad_clear_cs3_bit(RS232_ON);
simpad_clear_cs3_bit(DECT_POWER_ON);
}else
{
simpad_set_cs3_bit(RS232_ON);
simpad_set_cs3_bit(DECT_POWER_ON);
}
}
}
static struct sa1100_port_fns simpad_port_fns __initdata = {
.pm = simpad_uart_pm,
};
static struct mtd_partition simpad_partitions[] = {
{
.name = "SIMpad boot firmware",
.size = 0x00080000,
.offset = 0,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "SIMpad kernel",
.size = 0x0010000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "SIMpad root jffs2",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND,
}
};
static struct flash_platform_data simpad_flash_data = {
.map_name = "cfi_probe",
.parts = simpad_partitions,
.nr_parts = ARRAY_SIZE(simpad_partitions),
};
static struct resource simpad_flash_resources [] = {
DEFINE_RES_MEM(SA1100_CS0_PHYS, SZ_16M),
DEFINE_RES_MEM(SA1100_CS1_PHYS, SZ_16M),
};
static struct ucb1x00_plat_data simpad_ucb1x00_data = {
.gpio_base = SIMPAD_UCB1X00_GPIO_BASE,
};
static struct mcp_plat_data simpad_mcp_data = {
.mccr0 = MCCR0_ADM,
.sclk_rate = 11981000,
.codec_pdata = &simpad_ucb1x00_data,
};
static void __init simpad_map_io(void)
{
sa1100_map_io();
iotable_init(simpad_io_desc, ARRAY_SIZE(simpad_io_desc));
/* Initialize CS3 */
cs3_shadow = (EN1 | EN0 | LED2_ON | DISPLAY_ON |
RS232_ON | ENABLE_5V | RESET_SIMCARD | DECT_POWER_ON);
__simpad_write_cs3(); /* Spinlocks not yet initialized */
sa1100_register_uart_fns(&simpad_port_fns);
sa1100_register_uart(0, 3); /* serial interface */
sa1100_register_uart(1, 1); /* DECT */
// Reassign UART 1 pins
GAFR |= GPIO_UART_TXD | GPIO_UART_RXD;
GPDR |= GPIO_UART_TXD | GPIO_LDD13 | GPIO_LDD15;
GPDR &= ~GPIO_UART_RXD;
PPAR |= PPAR_UPR;
/*
* Set up registers for sleep mode.
*/
PWER = PWER_GPIO0| PWER_RTC;
PGSR = 0x818;
PCFR = 0;
PSDR = 0;
}
static void simpad_power_off(void)
{
local_irq_disable();
cs3_shadow = SD_MEDIAQ;
__simpad_write_cs3(); /* Bypass spinlock here */
/* disable internal oscillator, float CS lines */
PCFR = (PCFR_OPDE | PCFR_FP | PCFR_FS);
/* enable wake-up on GPIO0 */
PWER = GFER = GRER = PWER_GPIO0;
/*
* set scratchpad to zero, just in case it is used as a
* restart address by the bootloader.
*/
PSPR = 0;
PGSR = 0;
/* enter sleep mode */
PMCR = PMCR_SF;
while(1);
local_irq_enable(); /* we won't ever call it */
}
/*
* gpio_keys
*/
static struct gpio_keys_button simpad_button_table[] = {
{ KEY_POWER, IRQ_GPIO_POWER_BUTTON, 1, "power button" },
};
static struct gpio_keys_platform_data simpad_keys_data = {
.buttons = simpad_button_table,
.nbuttons = ARRAY_SIZE(simpad_button_table),
};
static struct platform_device simpad_keys = {
.name = "gpio-keys",
.dev = {
.platform_data = &simpad_keys_data,
},
};
static struct gpio_keys_button simpad_polled_button_table[] = {
{ KEY_PROG1, SIMPAD_UCB1X00_GPIO_PROG1, 1, "prog1 button" },
{ KEY_PROG2, SIMPAD_UCB1X00_GPIO_PROG2, 1, "prog2 button" },
{ KEY_UP, SIMPAD_UCB1X00_GPIO_UP, 1, "up button" },
{ KEY_DOWN, SIMPAD_UCB1X00_GPIO_DOWN, 1, "down button" },
{ KEY_LEFT, SIMPAD_UCB1X00_GPIO_LEFT, 1, "left button" },
{ KEY_RIGHT, SIMPAD_UCB1X00_GPIO_RIGHT, 1, "right button" },
};
static struct gpio_keys_platform_data simpad_polled_keys_data = {
.buttons = simpad_polled_button_table,
.nbuttons = ARRAY_SIZE(simpad_polled_button_table),
.poll_interval = 50,
};
static struct platform_device simpad_polled_keys = {
.name = "gpio-keys-polled",
.dev = {
.platform_data = &simpad_polled_keys_data,
},
};
/*
* GPIO LEDs
*/
static struct gpio_led simpad_leds[] = {
{
.name = "simpad:power",
.gpio = SIMPAD_CS3_LED2_ON,
.active_low = 0,
.default_trigger = "default-on",
},
};
static struct gpio_led_platform_data simpad_led_data = {
.num_leds = ARRAY_SIZE(simpad_leds),
.leds = simpad_leds,
};
static struct platform_device simpad_gpio_leds = {
.name = "leds-gpio",
.id = 0,
.dev = {
.platform_data = &simpad_led_data,
},
};
/*
* i2c
*/
static struct i2c_gpio_platform_data simpad_i2c_data = {
.sda_pin = GPIO_GPIO21,
.scl_pin = GPIO_GPIO25,
.udelay = 10,
.timeout = HZ,
};
static struct platform_device simpad_i2c = {
.name = "i2c-gpio",
.id = 0,
.dev = {
.platform_data = &simpad_i2c_data,
},
};
/*
* MediaQ Video Device
*/
static struct platform_device simpad_mq200fb = {
.name = "simpad-mq200",
.id = 0,
};
static struct platform_device *devices[] __initdata = {
&simpad_keys,
&simpad_polled_keys,
&simpad_mq200fb,
&simpad_gpio_leds,
&simpad_i2c,
};
static int __init simpad_init(void)
{
int ret;
spin_lock_init(&cs3_lock);
cs3_gpio.label = "simpad_cs3";
cs3_gpio.base = SIMPAD_CS3_GPIO_BASE;
cs3_gpio.ngpio = 24;
cs3_gpio.set = cs3_gpio_set;
cs3_gpio.get = cs3_gpio_get;
cs3_gpio.direction_input = cs3_gpio_direction_input;
cs3_gpio.direction_output = cs3_gpio_direction_output;
ret = gpiochip_add(&cs3_gpio);
if (ret)
printk(KERN_WARNING "simpad: Unable to register cs3 GPIO device");
pm_power_off = simpad_power_off;
sa11x0_ppc_configure_mcp();
sa11x0_register_mtd(&simpad_flash_data, simpad_flash_resources,
ARRAY_SIZE(simpad_flash_resources));
sa11x0_register_mcp(&simpad_mcp_data);
ret = platform_add_devices(devices, ARRAY_SIZE(devices));
if(ret)
printk(KERN_WARNING "simpad: Unable to register mq200 framebuffer device");
return 0;
}
arch_initcall(simpad_init);
MACHINE_START(SIMPAD, "Simpad")
/* Maintainer: Holger Freyther */
.atag_offset = 0x100,
.map_io = simpad_map_io,
.nr_irqs = SA1100_NR_IRQS,
.init_irq = sa1100_init_irq,
.init_late = sa11x0_init_late,
.init_time = sa1100_timer_init,
.restart = sa11x0_restart,
MACHINE_END
| gpl-2.0 |
chetan/cherokee | cherokee/handler_render_rrd.c | 1 | 24020 | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/* Cherokee
*
* Authors:
* Alvaro Lopez Ortega <alvaro@alobbs.com>
*
* Copyright (C) 2001-2010 Alvaro Lopez Ortega
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "common-internal.h"
#include "handler_render_rrd.h"
#include "server-protected.h"
#include "connection-protected.h"
#include "thread.h"
#include "rrd_tools.h"
#include "util.h"
#define ENTRIES "rrd,render,render_rrd,handler"
#define DISABLED_MSG "Graphs generation is disabled because RRDtool was not found." CRLF
PLUGIN_INFO_HANDLER_EASY_INIT (render_rrd, http_get | http_head);
/* Functions
*/
static ret_t
find_interval (const char *txt,
cherokee_collector_rrd_interval_t **interval)
{
cherokee_collector_rrd_interval_t *i;
for (i = cherokee_rrd_intervals; i->interval != NULL; i++) {
if (strncmp (i->interval, txt, 2) == 0) {
*interval = i;
return ret_ok;
}
}
return ret_error;
}
static cherokee_boolean_t
check_image_freshness (cherokee_buffer_t *buf,
cherokee_collector_rrd_interval_t *interval)
{
int re;
struct stat info;
/* cache_img_dir + "/" + buf + "_" + interval + ".png"
*/
cherokee_buffer_prepend_str (buf, "/");
cherokee_buffer_prepend_buf (buf, &rrd_connection->path_img_cache);
cherokee_buffer_add_char (buf, '_');
cherokee_buffer_add (buf, interval->interval, strlen(interval->interval));
cherokee_buffer_add_str (buf, ".png");
re = cherokee_stat (buf->buf, &info);
if (re != 0) {
TRACE(ENTRIES, "Image does not exist: '%s'\n", buf->buf);
return false;
}
if (cherokee_bogonow_now >= info.st_mtime + interval->secs_per_pixel) {
TRACE(ENTRIES, "Image is too old: '%s'. It was valid for %d secs, but it's %d secs old.\n",
buf->buf, interval->secs_per_pixel, (cherokee_bogonow_now - info.st_mtime));
return false;
}
TRACE(ENTRIES, "Image is fresh enough: '%s'\n", buf->buf);
return true;
}
static ret_t
command_rrdtool (cherokee_handler_render_rrd_t *hdl,
cherokee_buffer_t *buf)
{
ret_t ret;
/* Execute
*/
ret = cherokee_rrd_connection_execute (rrd_connection, buf);
if (ret != ret_ok) {
LOG_ERROR (CHEROKEE_ERROR_HANDLER_RENDER_RRD_EXEC, buf->buf);
cherokee_rrd_connection_kill (rrd_connection, false);
return ret_error;
}
/* Check everything was alright
*/
if (cherokee_buffer_is_empty (buf)) {
LOG_ERROR_S (CHEROKEE_ERROR_HANDLER_RENDER_RRD_EMPTY_REPLY);
return ret_error;
} else if (strncmp (buf->buf, "ERROR", 5) == 0) {
cherokee_buffer_add_buffer (&hdl->rrd_error, buf);
LOG_ERROR (CHEROKEE_ERROR_HANDLER_RENDER_RRD_MSG, buf->buf);
return ret_error;
}
TRACE(ENTRIES, "Command execute. Everything is fine.\n");
return ret_ok;
}
static ret_t
render_srv_accepts (cherokee_handler_render_rrd_t *hdl,
cherokee_collector_rrd_interval_t *interval)
{
cherokee_buffer_t *tmp = &rrd_connection->tmp;
cherokee_buffer_add_str (tmp, "graph ");
cherokee_buffer_add_buffer (tmp, &rrd_connection->path_img_cache);
cherokee_buffer_add_va (tmp, "/server_accepts_%s.png ", interval->interval);
cherokee_buffer_add_va (tmp, "--imgformat PNG --width 580 --height 340 --start -%s ", interval->interval);
cherokee_buffer_add_va (tmp, "--title \"Accepted Connections: %s\" ", interval->interval);
cherokee_buffer_add_str (tmp, "--vertical-label \"conn/s\" -c BACK#FFFFFF -c SHADEA#FFFFFF -c SHADEB#FFFFFF -c SHADEA#FFFFFF -c SHADEB#FFFFFF ");
cherokee_buffer_add_va (tmp, "DEF:accepts=%s/server.rrd:Accepts:AVERAGE ", rrd_connection->path_databases.buf);
cherokee_buffer_add_va (tmp, "DEF:accepts_min=%s/server.rrd:Accepts:MIN ", rrd_connection->path_databases.buf);
cherokee_buffer_add_va (tmp, "DEF:accepts_max=%s/server.rrd:Accepts:MAX ", rrd_connection->path_databases.buf);
cherokee_buffer_add_str (tmp, "VDEF:accepts_total=accepts,TOTAL ");
cherokee_buffer_add_str (tmp, "CDEF:accepts_minmax=accepts_max,accepts_min,- ");
cherokee_buffer_add_va (tmp, "DEF:requests=%s/server.rrd:Requests:AVERAGE ", rrd_connection->path_databases.buf);
cherokee_buffer_add_va (tmp, "DEF:requests_min=%s/server.rrd:Requests:MIN ", rrd_connection->path_databases.buf);
cherokee_buffer_add_va (tmp, "DEF:requests_max=%s/server.rrd:Requests:MAX ", rrd_connection->path_databases.buf);
cherokee_buffer_add_str (tmp, "VDEF:requests_total=requests,TOTAL ");
cherokee_buffer_add_str (tmp, "CDEF:requests_minmax=requests_max,requests_min,- ");
cherokee_buffer_add_str (tmp, "LINE1.5:requests#900:\"HTTP reqs\" ");
cherokee_buffer_add_str (tmp, "GPRINT:requests:LAST:\"Current\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:requests:AVERAGE:\" Average\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:requests_max:MAX:\" Maximum\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:requests_total:\" Total\\:%8.2lf%s\\n\" ");
cherokee_buffer_add_str (tmp, "AREA:accepts_min#ffffff: ");
cherokee_buffer_add_str (tmp, "STACK:accepts_minmax#4477BB: ");
cherokee_buffer_add_str (tmp, "LINE1.5:accepts#224499:\"TCP conns\" ");
cherokee_buffer_add_str (tmp, "GPRINT:accepts:LAST:\"Current\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:accepts:AVERAGE:\" Average\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:accepts_max:MAX:\" Maximum\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:accepts_total:\" Total\\:%8.2lf%s\\n\" ");
cherokee_buffer_add_str (tmp, "\n");
command_rrdtool (hdl, tmp);
cherokee_buffer_clean (tmp);
return ret_ok;
}
static ret_t
render_srv_timeouts (cherokee_handler_render_rrd_t *hdl,
cherokee_collector_rrd_interval_t *interval)
{
cherokee_buffer_t *tmp = &rrd_connection->tmp;
cherokee_buffer_add_str (tmp, "graph ");
cherokee_buffer_add_buffer (tmp, &rrd_connection->path_img_cache);
cherokee_buffer_add_va (tmp, "/server_timeouts_%s.png ", interval->interval);
cherokee_buffer_add_va (tmp, "--imgformat PNG --width 580 --height 340 --start -%s ", interval->interval);
cherokee_buffer_add_va (tmp, "--title \"Timeouts: %s\" ", interval->interval);
cherokee_buffer_add_str (tmp, "--vertical-label \"timeouts/s\" -c BACK#FFFFFF -c SHADEA#FFFFFF -c SHADEB#FFFFFF ");
cherokee_buffer_add_va (tmp, "DEF:timeouts=%s/server.rrd:Timeouts:AVERAGE ", rrd_connection->path_databases.buf);
cherokee_buffer_add_va (tmp, "DEF:timeouts_min=%s/server.rrd:Timeouts:MIN ", rrd_connection->path_databases.buf);
cherokee_buffer_add_va (tmp, "DEF:timeouts_max=%s/server.rrd:Timeouts:MAX ", rrd_connection->path_databases.buf);
cherokee_buffer_add_str (tmp, "VDEF:timeouts_total=timeouts,TOTAL ");
cherokee_buffer_add_str (tmp, "CDEF:timeouts_minmax=timeouts_max,timeouts_min,- ");
cherokee_buffer_add_str (tmp, "COMMENT:\"\\n\" ");
cherokee_buffer_add_str (tmp, "COMMENT:\" Current Average Maximum Total\\n\" ");
cherokee_buffer_add_str (tmp, "GPRINT:timeouts:LAST:\"%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:timeouts:AVERAGE:\"%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:timeouts_max:MAX:\"%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:timeouts_total:\"%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "AREA:timeouts_min#ffffff: ");
cherokee_buffer_add_str (tmp, "STACK:timeouts_minmax#C007:Timeouts ");
cherokee_buffer_add_str (tmp, "LINE1.5:timeouts#900:Average ");
cherokee_buffer_add_str (tmp, "\n");
command_rrdtool (hdl, tmp);
cherokee_buffer_clean (tmp);
return ret_ok;
}
static ret_t
render_srv_traffic (cherokee_handler_render_rrd_t *hdl,
cherokee_collector_rrd_interval_t *interval)
{
cherokee_buffer_t *tmp = &rrd_connection->tmp;
cherokee_buffer_add_str (tmp, "graph ");
cherokee_buffer_add_buffer (tmp, &rrd_connection->path_img_cache);
cherokee_buffer_add_va (tmp, "/server_traffic_%s.png ", interval->interval);
cherokee_buffer_add_va (tmp, "--imgformat PNG --width 580 --height 340 --start -%s ", interval->interval);
cherokee_buffer_add_va (tmp, "--title \"Traffic: %s\" ", interval->interval);
cherokee_buffer_add_str (tmp, "--vertical-label \"bytes/s\" -c BACK#FFFFFF -c SHADEA#FFFFFF -c SHADEB#FFFFFF ");
cherokee_buffer_add_va (tmp, "DEF:rx=%s/server.rrd:RX:AVERAGE ", rrd_connection->path_databases.buf);
cherokee_buffer_add_va (tmp, "DEF:rx_max=%s/server.rrd:RX:MAX ", rrd_connection->path_databases.buf);
cherokee_buffer_add_va (tmp, "DEF:tx=%s/server.rrd:TX:AVERAGE ", rrd_connection->path_databases.buf);
cherokee_buffer_add_va (tmp, "DEF:tx_max=%s/server.rrd:TX:MAX ", rrd_connection->path_databases.buf);
cherokee_buffer_add_str (tmp, "VDEF:tx_total=tx,TOTAL ");
cherokee_buffer_add_str (tmp, "VDEF:rx_total=rx,TOTAL ");
cherokee_buffer_add_str (tmp, "CDEF:rx_r=rx,-1,* ");
cherokee_buffer_add_str (tmp, "AREA:tx#4477BB:Out ");
cherokee_buffer_add_str (tmp, "LINE1:tx#224499 ");
cherokee_buffer_add_str (tmp, "GPRINT:tx:LAST:\" Current\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:tx:AVERAGE:\" Average\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:tx_max:MAX:\" Maximum\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:tx_total:\" Total\\:%8.2lf%s\\n\" ");
cherokee_buffer_add_str (tmp, "AREA:rx_r#C007 ");
cherokee_buffer_add_str (tmp, "LINE1:rx_r#990000:In ");
cherokee_buffer_add_str (tmp, "GPRINT:rx:LAST:\" Current\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:rx:AVERAGE:\" Average\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:rx_max:MAX:\" Maximum\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:rx_total:\" Total\\:%8.2lf%s\\n\" ");
cherokee_buffer_add_str (tmp, "\n");
command_rrdtool (hdl, tmp);
cherokee_buffer_clean (tmp);
return ret_ok;
}
static ret_t
render_vsrv_traffic (cherokee_handler_render_rrd_t *hdl,
cherokee_collector_rrd_interval_t *interval,
cherokee_buffer_t *vserver_name)
{
cherokee_buffer_t *tmp = &rrd_connection->tmp;
cherokee_buffer_add_str (tmp, "graph ");
cherokee_buffer_add_buffer (tmp, &rrd_connection->path_img_cache);
cherokee_buffer_add_va (tmp, "'/vserver_traffic_%s_%s.png' ", vserver_name->buf, interval->interval);
cherokee_buffer_add_va (tmp, "--imgformat PNG --width 580 --height 340 --start -%s ", interval->interval);
cherokee_buffer_add_va (tmp, "--title \"Traffic, %s: %s\" ", vserver_name->buf, interval->interval);
cherokee_buffer_add_str (tmp, "--vertical-label \"bytes/s\" -c BACK#FFFFFF -c SHADEA#FFFFFF -c SHADEB#FFFFFF ");
cherokee_buffer_add_va (tmp, "'DEF:rx=%s/vserver_%s.rrd:RX:AVERAGE' ", rrd_connection->path_databases.buf, vserver_name->buf);
cherokee_buffer_add_va (tmp, "'DEF:rx_max=%s/vserver_%s.rrd:RX:MAX' ", rrd_connection->path_databases.buf, vserver_name->buf);
cherokee_buffer_add_va (tmp, "'DEF:tx=%s/vserver_%s.rrd:TX:AVERAGE' ", rrd_connection->path_databases.buf, vserver_name->buf);
cherokee_buffer_add_va (tmp, "'DEF:tx_max=%s/vserver_%s.rrd:TX:MAX' ", rrd_connection->path_databases.buf, vserver_name->buf);
cherokee_buffer_add_str (tmp, "VDEF:tx_total=tx,TOTAL ");
cherokee_buffer_add_str (tmp, "VDEF:rx_total=rx,TOTAL ");
cherokee_buffer_add_str (tmp, "CDEF:rx_r=rx,-1,* ");
cherokee_buffer_add_str (tmp, "AREA:tx#4477BB:Out ");
cherokee_buffer_add_str (tmp, "LINE1:tx#224499 ");
cherokee_buffer_add_str (tmp, "GPRINT:tx:LAST:\" Current\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:tx:AVERAGE:\" Average\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:tx_max:MAX:\" Maximum\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:tx_total:\" Total\\:%8.2lf%s\\n\" ");
cherokee_buffer_add_str (tmp, "AREA:rx_r#C007 ");
cherokee_buffer_add_str (tmp, "LINE1:rx_r#990000:In ");
cherokee_buffer_add_str (tmp, "GPRINT:rx:LAST:\" Current\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:rx:AVERAGE:\" Average\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:rx_max:MAX:\" Maximum\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:rx_total:\" Total\\:%8.2lf%s\\n\" ");
/* Total server traffic */
cherokee_buffer_add_va (tmp, "DEF:srv_tx=%s/server.rrd:TX:AVERAGE ", rrd_connection->path_databases.buf);
cherokee_buffer_add_str (tmp, "VDEF:srv_tx_total=srv_tx,TOTAL ");
cherokee_buffer_add_str (tmp, "LINE1:srv_tx#ADE:\"Global\" ");
cherokee_buffer_add_str (tmp, "GPRINT:srv_tx:LAST:\" Current\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:srv_tx:AVERAGE:\" Average\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:srv_tx:MAX:\" Maximum\\:%8.2lf%s\" ");
cherokee_buffer_add_str (tmp, "GPRINT:srv_tx_total:\" Total\\:%8.2lf%s\\n\" ");
cherokee_buffer_add_str (tmp, "\n");
command_rrdtool (hdl, tmp);
cherokee_buffer_clean (tmp);
return ret_ok;
}
ret_t
cherokee_handler_render_rrd_init (cherokee_handler_render_rrd_t *hdl)
{
ret_t ret;
int unlocked;
const char *begin;
const char *dash;
cherokee_collector_rrd_interval_t *interval;
cherokee_boolean_t fresh;
cherokee_connection_t *conn = HANDLER_CONN(hdl);
cherokee_buffer_t tmp = CHEROKEE_BUF_INIT;
/* The handler might be disabled
*/
if (HANDLER_RENDER_RRD_PROPS(hdl)->disabled) {
return ret_ok;
}
/* Sanity checks
*/
if (strncmp (conn->request.buf + conn->request.len - 4, ".png", 4) != 0) {
TRACE (ENTRIES, "Malformed RRD image request\n");
conn->error_code = http_service_unavailable;
return ret_error;
}
/* Parse the interval
*/
dash = conn->request.buf + conn->request.len - (3 + 4);
ret = find_interval (dash+1, &interval);
if (ret != ret_ok) {
TRACE (ENTRIES, "No interval detected: %s\n", dash+1);
conn->error_code = http_service_unavailable;
return ret_error;
}
begin = strrchr (conn->request.buf, '/');
if (begin == NULL) {
TRACE (ENTRIES, "Malformed RRD image request. No slash.\n");
conn->error_code = http_service_unavailable;
return ret_error;
}
/* Launch the task
*/
if (! strncmp (begin, "/server_accepts_", 16)) {
if (strlen(begin) != 18 + 4) {
TRACE (ENTRIES, "Bad length: %d. Expected 18+4\n", conn->request.len);
conn->error_code = http_service_unavailable;
return ret_error;
}
cherokee_buffer_add_str (&tmp, "server_accepts");
fresh = check_image_freshness (&tmp, interval);
cherokee_buffer_mrproper (&tmp);
if (! fresh) {
unlocked = CHEROKEE_MUTEX_TRY_LOCK (&rrd_connection->mutex);
if (unlocked) {
cherokee_connection_sleep (conn, 200);
return ret_eagain;
}
ret = render_srv_accepts (hdl, interval);
if (ret != ret_ok) {
TRACE (ENTRIES, "Couldn't render image: %s\n", conn->request.buf);
CHEROKEE_MUTEX_UNLOCK (&rrd_connection->mutex);
conn->error_code = http_service_unavailable;
return ret_error;
}
CHEROKEE_MUTEX_UNLOCK (&rrd_connection->mutex);
}
} else if (! strncmp (begin, "/server_timeouts_", 17)) {
if (strlen(begin) != 19 + 4) {
TRACE (ENTRIES, "Bad length: %d. Expected 19+4.\n", conn->request.len);
conn->error_code = http_service_unavailable;
return ret_error;
}
cherokee_buffer_add_str (&tmp, "server_timeouts");
fresh = check_image_freshness (&tmp, interval);
cherokee_buffer_mrproper (&tmp);
if (! fresh) {
unlocked = CHEROKEE_MUTEX_TRY_LOCK (&rrd_connection->mutex);
if (unlocked) {
cherokee_connection_sleep (conn, 200);
return ret_eagain;
}
ret = render_srv_timeouts (hdl, interval);
if (ret != ret_ok) {
TRACE (ENTRIES, "Couldn't render image: %s\n", conn->request.buf);
CHEROKEE_MUTEX_UNLOCK (&rrd_connection->mutex);
conn->error_code = http_service_unavailable;
return ret_error;
}
CHEROKEE_MUTEX_UNLOCK (&rrd_connection->mutex);
}
} else if (! strncmp (begin, "/server_traffic_", 16)) {
if (strlen(begin) != 18 + 4) {
TRACE (ENTRIES, "Bad length: %d. Expected 18+4.\n", conn->request.len);
conn->error_code = http_service_unavailable;
return ret_error;
}
cherokee_buffer_add_str (&tmp, "server_traffic");
fresh = check_image_freshness (&tmp, interval);
cherokee_buffer_mrproper (&tmp);
if (! fresh) {
unlocked = CHEROKEE_MUTEX_TRY_LOCK (&rrd_connection->mutex);
if (unlocked) {
cherokee_connection_sleep (conn, 200);
return ret_eagain;
}
ret = render_srv_traffic (hdl, interval);
if (ret != ret_ok) {
TRACE (ENTRIES, "Couldn't render image: %s\n", conn->request.buf);
CHEROKEE_MUTEX_UNLOCK (&rrd_connection->mutex);
conn->error_code = http_service_unavailable;
return ret_error;
}
CHEROKEE_MUTEX_UNLOCK (&rrd_connection->mutex);
}
} else if (! strncmp (begin, "/vserver_traffic_", 17)) {
const char *vserver_name;
int vserver_len;
cherokee_buffer_t vserver_buf = CHEROKEE_BUF_INIT;
/* Virtual server name
*/
vserver_name = begin + 17;
vserver_len = dash - vserver_name;
if (vserver_len <= 0) {
TRACE (ENTRIES, "Bad virtual server name. Length: %d\n", vserver_len);
conn->error_code = http_service_unavailable;
return ret_error;
}
cherokee_buffer_add (&vserver_buf, vserver_name, vserver_len);
cherokee_buffer_replace_string (&vserver_buf, " ", 1, "_", 1);
/* Is it fresh enough?
*/
cherokee_buffer_add_str (&tmp, "vserver_traffic_");
cherokee_buffer_add_buffer (&tmp, &vserver_buf);
fresh = check_image_freshness (&tmp, interval);
cherokee_buffer_mrproper (&tmp);
if (! fresh) {
unlocked = CHEROKEE_MUTEX_TRY_LOCK (&rrd_connection->mutex);
if (unlocked) {
cherokee_connection_sleep (conn, 200);
return ret_eagain;
}
/* Render
*/
ret = render_vsrv_traffic (hdl, interval, &vserver_buf);
cherokee_buffer_mrproper (&vserver_buf);
if (ret != ret_ok) {
TRACE (ENTRIES, "Couldn't render image: %s\n", conn->request.buf);
CHEROKEE_MUTEX_UNLOCK (&rrd_connection->mutex);
conn->error_code = http_service_unavailable;
return ret_error;
}
CHEROKEE_MUTEX_UNLOCK (&rrd_connection->mutex);
}
} else {
LOG_ERROR (CHEROKEE_ERROR_HANDLER_RENDER_RRD_INVALID_REQ, conn->request.buf);
conn->error_code = http_service_unavailable;
return ret_error;
}
/* Has everything gone alright?
*/
if (! cherokee_buffer_is_empty (&hdl->rrd_error)) {
cherokee_connection_t *conn = HANDLER_CONN(hdl);
conn->error_code = http_service_unavailable;
BIT_SET (HANDLER(hdl)->support, hsupport_error);
return ret_ok;
}
/* Rewrite the request
*/
if (cherokee_buffer_is_empty (&conn->request_original)) {
cherokee_buffer_add_buffer (&conn->request_original, &conn->request);
}
cherokee_buffer_replace_string (&conn->request, " ", 1, "_", 1);
/* Handler file init
*/
return cherokee_handler_file_init (hdl->file_hdl);
}
static ret_t
handler_add_headers (cherokee_handler_render_rrd_t *hdl,
cherokee_buffer_t *buffer)
{
if (! cherokee_buffer_is_empty (&hdl->rrd_error)) {
cherokee_buffer_add_str (buffer, "Content-Type: text/html" CRLF);
cherokee_buffer_add_va (buffer, "Content-Length: %d" CRLF, hdl->rrd_error.len);
return ret_ok;
}
if (HANDLER_RENDER_RRD_PROPS(hdl)->disabled) {
cherokee_buffer_add_str (buffer, "Content-Type: text/html" CRLF);
cherokee_buffer_add_va (buffer, "Content-Length: %d" CRLF, strlen(DISABLED_MSG));
return ret_ok;
}
return cherokee_handler_file_add_headers (hdl->file_hdl, buffer);
}
static ret_t
handler_step (cherokee_handler_render_rrd_t *hdl,
cherokee_buffer_t *buffer)
{
if (! cherokee_buffer_is_empty (&hdl->rrd_error)) {
cherokee_buffer_add_buffer (buffer, &hdl->rrd_error);
return ret_eof_have_data;
}
if (HANDLER_RENDER_RRD_PROPS(hdl)->disabled) {
cherokee_buffer_add_str (buffer, DISABLED_MSG);
return ret_eof_have_data;
}
return cherokee_handler_file_step (hdl->file_hdl, buffer);
}
static ret_t
handler_free (cherokee_handler_render_rrd_t *hdl)
{
cherokee_buffer_mrproper (&hdl->rrd_error);
if (hdl->file_hdl != NULL) {
cherokee_handler_file_free (hdl->file_hdl);
}
return ret_ok;
}
ret_t
cherokee_handler_render_rrd_new (cherokee_handler_t **hdl,
void *cnt,
cherokee_module_props_t *props)
{
ret_t ret;
CHEROKEE_NEW_STRUCT (n, handler_render_rrd);
/* Init the base class object
*/
cherokee_handler_init_base (HANDLER(n), cnt, HANDLER_PROPS(props), PLUGIN_INFO_HANDLER_PTR(render_rrd));
MODULE(n)->init = (handler_func_init_t) cherokee_handler_render_rrd_init;
MODULE(n)->free = (module_func_free_t) handler_free;
HANDLER(n)->step = (handler_func_step_t) handler_step;
HANDLER(n)->add_headers = (handler_func_add_headers_t) handler_add_headers;
/* Supported features
*/
HANDLER(n)->support = hsupport_nothing;
/* Properties
*/
n->file_hdl = NULL;
cherokee_buffer_init (&n->rrd_error);
/* Instance file sub-handler
*/
if (PROP_RENDER_RRD(props)->disabled) {
HANDLER(n)->support |= hsupport_length;
} else {
ret = cherokee_handler_file_new ((cherokee_handler_t **)&n->file_hdl, cnt, MODULE_PROPS(PROP_RENDER_RRD(props)->file_props));
if (ret != ret_ok) {
return ret_ok;
}
HANDLER(n)->support = HANDLER(n->file_hdl)->support;
}
*hdl = HANDLER(n);
return ret_ok;
}
static ret_t
props_free (cherokee_handler_render_rrd_props_t *props)
{
if (props->file_props != NULL) {
cherokee_handler_file_props_free (props->file_props);
}
return cherokee_handler_props_free_base (HANDLER_PROPS(props));
}
ret_t
cherokee_handler_render_rrd_configure (cherokee_config_node_t *conf,
cherokee_server_t *srv,
cherokee_module_props_t **_props)
{
ret_t ret;
if (*_props == NULL) {
CHEROKEE_NEW_STRUCT (n, handler_render_rrd_props);
cherokee_handler_props_init_base (HANDLER_PROPS(n),
MODULE_PROPS_FREE(props_free));
/* Sub-handler properties */
n->disabled = false;
n->file_props = NULL;
cherokee_handler_file_configure (conf, srv,
(cherokee_module_props_t **) &n->file_props);
/* Force IO-cache off */
n->file_props->use_cache = false;
*_props = MODULE_PROPS(n);
}
/* Ensure the global RRD connection obj is ready
*/
cherokee_rrd_connection_get (NULL);
/* Parse the configuration tree
*/
ret = cherokee_rrd_connection_configure (rrd_connection, conf);
if (ret != ret_ok) {
PROP_RENDER_RRD(*_props)->disabled = true;
return ret_ok;
}
/* Ensure the image cache directory exists
*/
ret = cherokee_mkdir_p_perm (&rrd_connection->path_img_cache, 0775, W_OK);
if (ret != ret_ok) {
LOG_CRITICAL (CHEROKEE_ERROR_RRD_MKDIR_WRITE, rrd_connection->path_img_cache.buf);
return ret_error;
}
TRACE(ENTRIES, "RRD cache image directory ready: %s\n", rrd_connection->path_img_cache.buf);
return ret_ok;
}
/* Library init function
*/
static cherokee_boolean_t _render_rrd_is_init = false;
void
PLUGIN_INIT_NAME(render_rrd) (cherokee_plugin_loader_t *loader)
{
if (_render_rrd_is_init) return;
_render_rrd_is_init = true;
/* Load the dependences
*/
cherokee_plugin_loader_load (loader, "file");
}
| gpl-2.0 |
donniexyz/calligra | krita/crashreporter/mainwindow.cpp | 1 | 11629 | /*
* Copyright (c) 2008-2009 Hyves (Startphone Ltd.)
* Copyright (c) 2014 Boudewijn Rempt <boud@valdyas.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
*/
#include "mainwindow.h"
#include <QtCore>
#include <QtGui>
#include <QtNetwork>
#include <kglobal.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <calligraversion.h>
#include <calligragitversion.h>
#include <cstdlib>
#include <KoConfig.h>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
//#ifdef Q_WS_WIN
//#include <cstring>
//#include <windows.h>
//#include <shellapi.h>
///**
// * Native Win32 method for starting a process. This is required in order to
// * launch the installer with User Account Control enabled.
// *
// * @param path Path to the process to start.
// * @param parameters Parameters for the process.
// * @return @c true if the process is started successfully, @c false otherwise.
// */
//bool startProcess(LPCWSTR path, char *parameters = 0) {
// Q_ASSERT(path != 0);
// SHELLEXECUTEINFO info;
// memset(&info, '\0', sizeof(info));
// info.cbSize = sizeof(info);
// info.fMask = 0;
// info.hwnd = 0;
// info.lpVerb = TEXT("open");
// info.lpFile = path;
// info.lpParameters = (LPCWSTR)parameters;
// info.lpDirectory = 0;
// info.nShow = SW_SHOWNORMAL;
// return ShellExecuteEx(&info);
//}
//void doRestart(bool resetConfig)
//{
// if (!startProcess(QString("krita").toStdWString().data())) {
// QMessageBox::warning(0, i18nc("@title:window", "Krita"),
// i18n("Could not restart %1. Please try to restart %1 manually.").arg("krita"));
// }
//}
//#else // Q_WS_WIN
void doRestart(MainWindow* mainWindow, bool resetConfig)
{
if (resetConfig) {
{
QString appdata = qgetenv("APPDATA");
QDir inputDir(appdata + "/krita/share/apps/krita/input/");
foreach(QString entry, inputDir.entryList(QStringList("*.profile"))) {
inputDir.remove(entry);
}
QDir configDir(appdata + "/krita/share/config/");
configDir.remove("kritarc");
}
{
QString appdata = qgetenv("LOCALAPPDATA");
QDir inputDir(appdata + "/krita/share/apps/krita/input/");
foreach(QString entry, inputDir.entryList(QStringList("*.profile"))) {
inputDir.remove(entry);
}
QDir configDir(appdata + "/krita/share/config/");
configDir.remove("kritarc");
}
{
QDir inputDir(KGlobal::dirs()->saveLocation("data", "krita/input/"));
foreach(QString entry, inputDir.entryList(QStringList("*.profile"))) {
inputDir.remove(entry);
}
QDir configDir(KGlobal::dirs()->saveLocation("config"));
configDir.remove("kritarc");
}
}
QString restartCommand;
#ifdef Q_WS_MAC
QDir bundleDir(qApp->applicationDirPath());
bundleDir.cdUp();
bundleDir.cdUp();
bundleDir.cdUp();
restartCommand = QString("open \"") + QString(bundleDir.absolutePath() + "/krita.app\"");
#endif
#ifdef Q_WS_WIN
restartCommand = qApp->applicationDirPath().replace(' ', "\\ ") + "/krita.exe \"";
#endif
#ifdef Q_WS_X11
restartCommand = "sh -c \"" + qApp->applicationDirPath().replace(' ', "\\ ") + "/krita \"";
#endif
qDebug() << "restartCommand" << restartCommand;
QProcess restartProcess;
if (!restartProcess.startDetached(restartCommand)) {
QMessageBox::warning(mainWindow, i18nc("@title:window", "Krita"),
i18n("Could not restart Krita. Please try to restart manually."));
}
}
//#endif // Q_WS_WIN
#ifdef Q_WS_MAC
QString platformToStringMac(QSysInfo::MacVersion version)
{
switch(version) {
case QSysInfo::MV_9:
return "MacOS 9";
case QSysInfo::MV_10_0:
return "OSX 10.0 (cheetah)";
case QSysInfo::MV_10_1:
return "OSX 10.1 (puma)";
case QSysInfo::MV_10_2:
return "OSX 10.2 (jaguar)";
case QSysInfo::MV_10_3:
return "OSX 10.3 (panther)";
case QSysInfo::MV_10_4:
return "OSX 10.4 (tiger)";
case QSysInfo::MV_10_5:
return "OSX 10.5 (leopard)";
case QSysInfo::MV_10_6:
return "OSX 10.6 (snow leopard)";
case QSysInfo::MV_10_7:
return "OSX 10.6 (Lion)";
case QSysInfo::MV_10_8:
return "OSX 10.6 (Mountain Lion)";
case QSysInfo::MV_Unknown:
default:
return "Unknown OSX version";
};
}
#endif
#ifdef Q_WS_WIN
QString platformToStringWin(QSysInfo::WinVersion version)
{
switch(version) {
case QSysInfo::WV_32s:
return "Windows 3.1 with win32s";
case QSysInfo::WV_95:
return "Windows 95";
case QSysInfo::WV_98:
return "Windows 98";
case QSysInfo::WV_Me:
return "Windows Me";
case QSysInfo::WV_NT:
return "Windows NT";
case QSysInfo::WV_2000:
return "Windows 2000";
case QSysInfo::WV_XP:
return "Windows XP";
case QSysInfo::WV_2003:
return "Windows 2003";
case QSysInfo::WV_VISTA:
return "Windows Vista";
case QSysInfo::WV_WINDOWS7:
return "Windows 7";
case QSysInfo::WV_WINDOWS8:
return "Windows 8";
#if QT_VERSION >= 0x040806
case QSysInfo::WV_WINDOWS8_1:
return "Windows 8.1";
#endif
default:
return "Unknown Windows version";
};
}
#endif
struct MainWindow::Private {
QString dumpPath;
QString id;
QNetworkAccessManager *networkAccessManager;
bool doRestart;
bool uploadStarted;
Private() :
doRestart(true),
uploadStarted(false) {
}
};
MainWindow::MainWindow(const QString &dumpPath, const QString &id, QWidget *parent)
: QWidget(parent)
, m_d(new Private())
{
setupUi(this);
progressBar->hide();
lblKiki->setPixmap(QPixmap(KGlobal::dirs()->findResource("data", "krita/pics/KikiNurse_sm.png")));
setWindowFlags(Qt::WindowStaysOnTopHint | windowFlags());
m_d->networkAccessManager = new QNetworkAccessManager(this);
connect(m_d->networkAccessManager, SIGNAL(finished(QNetworkReply *)), SLOT(uploadDone(QNetworkReply *)));
connect(bnRestart, SIGNAL(clicked()), this, SLOT(restart()));
connect(bnClose, SIGNAL(clicked()), this, SLOT(close()));
m_d->dumpPath = dumpPath;
m_d->id = id;
}
MainWindow::~MainWindow()
{
delete m_d;
}
void MainWindow::restart()
{
m_d->doRestart = true;
if (chkAllowUpload->isChecked()) {
startUpload();
}
else {
doRestart(this, chkRemoveSettings->isChecked());
qApp->quit();
}
}
void MainWindow::close()
{
m_d->doRestart = false;
if (!m_d->uploadStarted && chkAllowUpload->isChecked()) {
startUpload();
}
else {
qApp->quit();
}
}
void MainWindow::startUpload()
{
bnRestart->setEnabled(false);
bnClose->setEnabled(false);
progressBar->show();
m_d->uploadStarted = true;
// Upload minidump
QNetworkRequest request(QUrl("http://krita-breakpad.kogmbh.net:1127/post"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=9876543210");
QString boundary = "--9876543210";
typedef QPair<QByteArray, QByteArray> Field;
QList<Field> fields;
QString calligraVersion(CALLIGRA_VERSION_STRING);
QString version;
#ifdef CALLIGRA_GIT_SHA1_STRING
QString gitVersion(CALLIGRA_GIT_SHA1_STRING);
version = QString("%1-%2").arg(calligraVersion).arg(gitVersion).toLatin1();
#else
version = calligraVersion;
#endif
fields << Field("BuildID", CALLIGRA_GIT_SHA1_STRING)
<< Field("ProductName", "krita")
<< Field("Version", version.toLatin1())
<< Field("Vendor", "KO GmbH")
<< Field("Email", txtEmail->text().toLatin1())
<< Field("timestamp", QByteArray::number(QDateTime::currentDateTime().toTime_t()));
#ifdef Q_WS_WIN
QString platform = platformToStringWin(QSysInfo::WindowsVersion);
#ifdef ENV32BIT
platform += "_x86";
#else
platform += "_x64";
#endif
fields << Field("Platform", platform.toLatin1());
#endif
#ifdef Q_WS_X11
fields << Field("Platform", "Linux/X11");
#endif
#ifdef Q_WS_MAC
fields << Field("Platform", platformToStringMac(QSysInfo::MacintoshVersion).toLatin1());
#endif
QFile f(QDesktopServices::storageLocation(QDesktopServices::TempLocation) + "/krita-opengl.txt");
qDebug() << KGlobal::dirs()->saveLocation("config") + "/krita-opengl.txt" << f.exists();
if (f.exists()) {
f.open(QFile::ReadOnly);
fields << Field("OpenGL", f.readAll());
}
QString body;
foreach(Field const field, fields) {
body += boundary + "\r\n";
body += "Content-Disposition: form-data; name=\"" + field.first + "\"\r\n\r\n";
body += field.second + "\r\n";
}
body += boundary + "\r\n";
// add minidump file
QString dumpfile = m_d->dumpPath + "/" + m_d->id + ".dmp";
qDebug() << "dumpfile" << dumpfile;
body += "Content-Disposition: form-data; name=\"upload_file_minidump\"; filename=\""
+ QFileInfo(dumpfile).fileName().toLatin1() + "\"\r\n";
body += "Content-Type: application/octet-stream\r\n\r\n";
QFile file(dumpfile);
if (file.exists()) {
file.open(QFile::ReadOnly);
QByteArray ba = file.readAll();
body += ba.toBase64();
file.remove();
}
body += "\r\n";
// add description
body += boundary + "\r\n";
body += "Content-Disposition: form-data; name=\"description\"\r\n";
body += "\r\n";
body += txtDescription->toPlainText();
body += "\r\n";
body += boundary + "--" + "\r\n";
QFile report(QDir::homePath() + "/krita-" + m_d->id + ".report");
report.open(QFile::WriteOnly);
report.write(body.toLatin1());
report.close();
QNetworkReply *reply = m_d->networkAccessManager->post(request, body.toLatin1());
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(uploadError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress(qint64,qint64)));
}
void MainWindow::uploadDone(QNetworkReply *reply)
{
qDebug() << "updloadDone";
if (reply && reply->error() != QNetworkReply::NoError) {
qCritical() << "uploadDone: Error uploading crash report: " << reply->errorString();
}
if (m_d->doRestart) {
doRestart(this, chkRemoveSettings->isChecked());
}
qApp->quit();
}
void MainWindow::uploadProgress(qint64 received, qint64 total)
{
qDebug() << "updloadProgress";
progressBar->setMaximum(total);
progressBar->setValue(received);
}
void MainWindow::uploadError(QNetworkReply::NetworkError error)
{
qDebug() << "updloadError" << error;
// Fake success...
progressBar->setRange(0, 100);
progressBar->setValue(100);
qCritical() << "UploadError: Error uploading crash report: " << error;
uploadDone(0);
}
| gpl-2.0 |
NamanG/coreboot2.0 | src/southbridge/intel/i3100/smbus.c | 1 | 2550 | /*
* This file is part of the coreboot project.
*
* Copyright (C) 2008 Arastra, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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.
*
*/
#include <device/device.h>
#include <device/path.h>
#include <device/pci.h>
#include <device/pci_ids.h>
#include <device/pci_ops.h>
#include <device/smbus.h>
#include <arch/io.h>
#include "i3100.h"
#include "smbus.h"
static int lsmbus_read_byte(device_t dev, u8 address)
{
u16 device;
struct resource *res;
struct bus *pbus;
device = dev->path.i2c.device;
pbus = get_pbus_smbus(dev);
res = find_resource(pbus->dev, 0x20);
return do_smbus_read_byte(res->base, device, address);
}
static int lsmbus_write_byte(device_t dev, u8 address, u8 byte)
{
u16 device;
struct resource *res;
struct bus *pbus;
device = dev->path.i2c.device;
pbus = get_pbus_smbus(dev);
res = find_resource(pbus->dev, 0x20);
return do_smbus_write_byte(res->base, device, address, byte);
}
static struct smbus_bus_operations lops_smbus_bus = {
.read_byte = lsmbus_read_byte,
.write_byte = lsmbus_write_byte,
};
static void smbus_set_subsystem(device_t dev, unsigned vendor, unsigned device)
{
pci_write_config32(dev, PCI_SUBSYSTEM_VENDOR_ID,
((device & 0xffff) << 16) | (vendor & 0xffff));
}
static struct pci_operations lops_pci = {
.set_subsystem = &smbus_set_subsystem,
};
static struct device_operations smbus_ops = {
.read_resources = pci_dev_read_resources,
.set_resources = pci_dev_set_resources,
.enable_resources = pci_dev_enable_resources,
.init = 0,
.scan_bus = scan_static_bus,
.enable = i3100_enable,
.ops_pci = &lops_pci,
.ops_smbus_bus = &lops_smbus_bus,
};
static const struct pci_driver smbus_driver __pci_driver = {
.ops = &smbus_ops,
.vendor = PCI_VENDOR_ID_INTEL,
.device = PCI_DEVICE_ID_INTEL_3100_SMB,
};
static const struct pci_driver smbus_driver_ep80579 __pci_driver = {
.ops = &smbus_ops,
.vendor = PCI_VENDOR_ID_INTEL,
.device = PCI_DEVICE_ID_INTEL_EP80579_SMB,
};
| gpl-2.0 |
mur47x111/JDK8-concurrent-tagging | src/share/vm/oops/constantPool.cpp | 1 | 73955 | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/classLoaderData.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/metadataOnStackMark.hpp"
#include "classfile/symbolTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "interpreter/linkResolver.hpp"
#include "memory/heapInspection.hpp"
#include "memory/metadataFactory.hpp"
#include "memory/oopFactory.hpp"
#include "oops/constantPool.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/objArrayKlass.hpp"
#include "runtime/fieldType.hpp"
#include "runtime/init.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/signature.hpp"
#include "runtime/vframe.hpp"
ConstantPool* ConstantPool::allocate(ClassLoaderData* loader_data, int length, TRAPS) {
// Tags are RW but comment below applies to tags also.
Array<u1>* tags = MetadataFactory::new_writeable_array<u1>(loader_data, length, 0, CHECK_NULL);
int size = ConstantPool::size(length);
// CDS considerations:
// Allocate read-write but may be able to move to read-only at dumping time
// if all the klasses are resolved. The only other field that is writable is
// the resolved_references array, which is recreated at startup time.
// But that could be moved to InstanceKlass (although a pain to access from
// assembly code). Maybe it could be moved to the cpCache which is RW.
return new (loader_data, size, false, MetaspaceObj::ConstantPoolType, THREAD) ConstantPool(tags);
}
ConstantPool::ConstantPool(Array<u1>* tags) {
set_length(tags->length());
set_tags(NULL);
set_cache(NULL);
set_reference_map(NULL);
set_resolved_references(NULL);
set_operands(NULL);
set_pool_holder(NULL);
set_flags(0);
// only set to non-zero if constant pool is merged by RedefineClasses
set_version(0);
set_lock(new Monitor(Monitor::nonleaf + 2, "A constant pool lock"));
// initialize tag array
int length = tags->length();
for (int index = 0; index < length; index++) {
tags->at_put(index, JVM_CONSTANT_Invalid);
}
set_tags(tags);
}
void ConstantPool::deallocate_contents(ClassLoaderData* loader_data) {
MetadataFactory::free_metadata(loader_data, cache());
set_cache(NULL);
MetadataFactory::free_array<u2>(loader_data, reference_map());
set_reference_map(NULL);
MetadataFactory::free_array<jushort>(loader_data, operands());
set_operands(NULL);
release_C_heap_structures();
// free tag array
MetadataFactory::free_array<u1>(loader_data, tags());
set_tags(NULL);
}
void ConstantPool::release_C_heap_structures() {
// walk constant pool and decrement symbol reference counts
unreference_symbols();
delete _lock;
set_lock(NULL);
}
objArrayOop ConstantPool::resolved_references() const {
return (objArrayOop)JNIHandles::resolve(_resolved_references);
}
// Create resolved_references array and mapping array for original cp indexes
// The ldc bytecode was rewritten to have the resolved reference array index so need a way
// to map it back for resolving and some unlikely miscellaneous uses.
// The objects created by invokedynamic are appended to this list.
void ConstantPool::initialize_resolved_references(ClassLoaderData* loader_data,
intStack reference_map,
int constant_pool_map_length,
TRAPS) {
// Initialized the resolved object cache.
int map_length = reference_map.length();
if (map_length > 0) {
// Only need mapping back to constant pool entries. The map isn't used for
// invokedynamic resolved_reference entries. For invokedynamic entries,
// the constant pool cache index has the mapping back to both the constant
// pool and to the resolved reference index.
if (constant_pool_map_length > 0) {
Array<u2>* om = MetadataFactory::new_array<u2>(loader_data, constant_pool_map_length, CHECK);
for (int i = 0; i < constant_pool_map_length; i++) {
int x = reference_map.at(i);
assert(x == (int)(jushort) x, "klass index is too big");
om->at_put(i, (jushort)x);
}
set_reference_map(om);
}
// Create Java array for holding resolved strings, methodHandles,
// methodTypes, invokedynamic and invokehandle appendix objects, etc.
objArrayOop stom = oopFactory::new_objArray(SystemDictionary::Object_klass(), map_length, CHECK);
Handle refs_handle (THREAD, (oop)stom); // must handleize.
set_resolved_references(loader_data->add_handle(refs_handle));
}
}
// CDS support. Create a new resolved_references array.
void ConstantPool::restore_unshareable_info(TRAPS) {
// Only create the new resolved references array and lock if it hasn't been
// attempted before
if (resolved_references() != NULL) return;
// restore the C++ vtable from the shared archive
restore_vtable();
if (SystemDictionary::Object_klass_loaded()) {
// Recreate the object array and add to ClassLoaderData.
int map_length = resolved_reference_length();
if (map_length > 0) {
objArrayOop stom = oopFactory::new_objArray(SystemDictionary::Object_klass(), map_length, CHECK);
Handle refs_handle (THREAD, (oop)stom); // must handleize.
ClassLoaderData* loader_data = pool_holder()->class_loader_data();
set_resolved_references(loader_data->add_handle(refs_handle));
}
// Also need to recreate the mutex. Make sure this matches the constructor
set_lock(new Monitor(Monitor::nonleaf + 2, "A constant pool lock"));
}
}
void ConstantPool::remove_unshareable_info() {
// Resolved references are not in the shared archive.
// Save the length for restoration. It is not necessarily the same length
// as reference_map.length() if invokedynamic is saved.
set_resolved_reference_length(
resolved_references() != NULL ? resolved_references()->length() : 0);
set_resolved_references(NULL);
set_lock(NULL);
}
int ConstantPool::cp_to_object_index(int cp_index) {
// this is harder don't do this so much.
int i = reference_map()->find(cp_index);
// We might not find the index for jsr292 call.
return (i < 0) ? _no_index_sentinel : i;
}
Klass* ConstantPool::klass_at_impl(constantPoolHandle this_oop, int which, TRAPS) {
// A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
// It is not safe to rely on the tag bit's here, since we don't have a lock, and the entry and
// tag is not updated atomicly.
CPSlot entry = this_oop->slot_at(which);
if (entry.is_resolved()) {
assert(entry.get_klass()->is_klass(), "must be");
// Already resolved - return entry.
return entry.get_klass();
}
// Acquire lock on constant oop while doing update. After we get the lock, we check if another object
// already has updated the object
assert(THREAD->is_Java_thread(), "must be a Java thread");
bool do_resolve = false;
bool in_error = false;
// Create a handle for the mirror. This will preserve the resolved class
// until the loader_data is registered.
Handle mirror_handle;
Symbol* name = NULL;
Handle loader;
{ MonitorLockerEx ml(this_oop->lock());
if (this_oop->tag_at(which).is_unresolved_klass()) {
if (this_oop->tag_at(which).is_unresolved_klass_in_error()) {
in_error = true;
} else {
do_resolve = true;
name = this_oop->unresolved_klass_at(which);
loader = Handle(THREAD, this_oop->pool_holder()->class_loader());
}
}
} // unlocking constantPool
// The original attempt to resolve this constant pool entry failed so find the
// original error and throw it again (JVMS 5.4.3).
if (in_error) {
Symbol* error = SystemDictionary::find_resolution_error(this_oop, which);
guarantee(error != (Symbol*)NULL, "tag mismatch with resolution error table");
ResourceMark rm;
// exception text will be the class name
const char* className = this_oop->unresolved_klass_at(which)->as_C_string();
THROW_MSG_0(error, className);
}
if (do_resolve) {
// this_oop must be unlocked during resolve_or_fail
oop protection_domain = this_oop->pool_holder()->protection_domain();
Handle h_prot (THREAD, protection_domain);
Klass* k_oop = SystemDictionary::resolve_or_fail(name, loader, h_prot, true, THREAD);
KlassHandle k;
if (!HAS_PENDING_EXCEPTION) {
k = KlassHandle(THREAD, k_oop);
// preserve the resolved klass.
mirror_handle = Handle(THREAD, k_oop->java_mirror());
// Do access check for klasses
verify_constant_pool_resolve(this_oop, k, THREAD);
}
// Failed to resolve class. We must record the errors so that subsequent attempts
// to resolve this constant pool entry fail with the same error (JVMS 5.4.3).
if (HAS_PENDING_EXCEPTION) {
ResourceMark rm;
Symbol* error = PENDING_EXCEPTION->klass()->name();
bool throw_orig_error = false;
{
MonitorLockerEx ml(this_oop->lock());
// some other thread has beaten us and has resolved the class.
if (this_oop->tag_at(which).is_klass()) {
CLEAR_PENDING_EXCEPTION;
entry = this_oop->resolved_klass_at(which);
return entry.get_klass();
}
if (!PENDING_EXCEPTION->
is_a(SystemDictionary::LinkageError_klass())) {
// Just throw the exception and don't prevent these classes from
// being loaded due to virtual machine errors like StackOverflow
// and OutOfMemoryError, etc, or if the thread was hit by stop()
// Needs clarification to section 5.4.3 of the VM spec (see 6308271)
}
else if (!this_oop->tag_at(which).is_unresolved_klass_in_error()) {
SystemDictionary::add_resolution_error(this_oop, which, error);
this_oop->tag_at_put(which, JVM_CONSTANT_UnresolvedClassInError);
} else {
// some other thread has put the class in error state.
error = SystemDictionary::find_resolution_error(this_oop, which);
assert(error != NULL, "checking");
throw_orig_error = true;
}
} // unlocked
if (throw_orig_error) {
CLEAR_PENDING_EXCEPTION;
ResourceMark rm;
const char* className = this_oop->unresolved_klass_at(which)->as_C_string();
THROW_MSG_0(error, className);
}
return 0;
}
if (TraceClassResolution && !k()->oop_is_array()) {
// skip resolving the constant pool so that this code get's
// called the next time some bytecodes refer to this class.
ResourceMark rm;
int line_number = -1;
const char * source_file = NULL;
if (JavaThread::current()->has_last_Java_frame()) {
// try to identify the method which called this function.
vframeStream vfst(JavaThread::current());
if (!vfst.at_end()) {
line_number = vfst.method()->line_number_from_bci(vfst.bci());
Symbol* s = vfst.method()->method_holder()->source_file_name();
if (s != NULL) {
source_file = s->as_C_string();
}
}
}
if (k() != this_oop->pool_holder()) {
// only print something if the classes are different
if (source_file != NULL) {
tty->print("RESOLVE %s %s %s:%d\n",
this_oop->pool_holder()->external_name(),
InstanceKlass::cast(k())->external_name(), source_file, line_number);
} else {
tty->print("RESOLVE %s %s\n",
this_oop->pool_holder()->external_name(),
InstanceKlass::cast(k())->external_name());
}
}
return k();
} else {
MonitorLockerEx ml(this_oop->lock());
// Only updated constant pool - if it is resolved.
do_resolve = this_oop->tag_at(which).is_unresolved_klass();
if (do_resolve) {
ClassLoaderData* this_key = this_oop->pool_holder()->class_loader_data();
this_key->record_dependency(k(), CHECK_NULL); // Can throw OOM
this_oop->klass_at_put(which, k());
}
}
}
entry = this_oop->resolved_klass_at(which);
assert(entry.is_resolved() && entry.get_klass()->is_klass(), "must be resolved at this point");
return entry.get_klass();
}
// Does not update ConstantPool* - to avoid any exception throwing. Used
// by compiler and exception handling. Also used to avoid classloads for
// instanceof operations. Returns NULL if the class has not been loaded or
// if the verification of constant pool failed
Klass* ConstantPool::klass_at_if_loaded(constantPoolHandle this_oop, int which) {
CPSlot entry = this_oop->slot_at(which);
if (entry.is_resolved()) {
assert(entry.get_klass()->is_klass(), "must be");
return entry.get_klass();
} else {
assert(entry.is_unresolved(), "must be either symbol or klass");
Thread *thread = Thread::current();
Symbol* name = entry.get_symbol();
oop loader = this_oop->pool_holder()->class_loader();
oop protection_domain = this_oop->pool_holder()->protection_domain();
Handle h_prot (thread, protection_domain);
Handle h_loader (thread, loader);
Klass* k = SystemDictionary::find(name, h_loader, h_prot, thread);
if (k != NULL) {
// Make sure that resolving is legal
EXCEPTION_MARK;
KlassHandle klass(THREAD, k);
// return NULL if verification fails
verify_constant_pool_resolve(this_oop, klass, THREAD);
if (HAS_PENDING_EXCEPTION) {
CLEAR_PENDING_EXCEPTION;
return NULL;
}
return klass();
} else {
return k;
}
}
}
Klass* ConstantPool::klass_ref_at_if_loaded(constantPoolHandle this_oop, int which) {
return klass_at_if_loaded(this_oop, this_oop->klass_ref_index_at(which));
}
Method* ConstantPool::method_at_if_loaded(constantPoolHandle cpool,
int which) {
if (cpool->cache() == NULL) return NULL; // nothing to load yet
int cache_index = decode_cpcache_index(which, true);
if (!(cache_index >= 0 && cache_index < cpool->cache()->length())) {
// FIXME: should be an assert
if (PrintMiscellaneous && (Verbose||WizardMode)) {
tty->print_cr("bad operand %d in:", which); cpool->print();
}
return NULL;
}
ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
return e->method_if_resolved(cpool);
}
bool ConstantPool::has_appendix_at_if_loaded(constantPoolHandle cpool, int which) {
if (cpool->cache() == NULL) return false; // nothing to load yet
int cache_index = decode_cpcache_index(which, true);
ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
return e->has_appendix();
}
oop ConstantPool::appendix_at_if_loaded(constantPoolHandle cpool, int which) {
if (cpool->cache() == NULL) return NULL; // nothing to load yet
int cache_index = decode_cpcache_index(which, true);
ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
return e->appendix_if_resolved(cpool);
}
bool ConstantPool::has_method_type_at_if_loaded(constantPoolHandle cpool, int which) {
if (cpool->cache() == NULL) return false; // nothing to load yet
int cache_index = decode_cpcache_index(which, true);
ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
return e->has_method_type();
}
oop ConstantPool::method_type_at_if_loaded(constantPoolHandle cpool, int which) {
if (cpool->cache() == NULL) return NULL; // nothing to load yet
int cache_index = decode_cpcache_index(which, true);
ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
return e->method_type_if_resolved(cpool);
}
Symbol* ConstantPool::impl_name_ref_at(int which, bool uncached) {
int name_index = name_ref_index_at(impl_name_and_type_ref_index_at(which, uncached));
return symbol_at(name_index);
}
Symbol* ConstantPool::impl_signature_ref_at(int which, bool uncached) {
int signature_index = signature_ref_index_at(impl_name_and_type_ref_index_at(which, uncached));
return symbol_at(signature_index);
}
int ConstantPool::impl_name_and_type_ref_index_at(int which, bool uncached) {
int i = which;
if (!uncached && cache() != NULL) {
if (ConstantPool::is_invokedynamic_index(which)) {
// Invokedynamic index is index into resolved_references
int pool_index = invokedynamic_cp_cache_entry_at(which)->constant_pool_index();
pool_index = invoke_dynamic_name_and_type_ref_index_at(pool_index);
assert(tag_at(pool_index).is_name_and_type(), "");
return pool_index;
}
// change byte-ordering and go via cache
i = remap_instruction_operand_from_cache(which);
} else {
if (tag_at(which).is_invoke_dynamic()) {
int pool_index = invoke_dynamic_name_and_type_ref_index_at(which);
assert(tag_at(pool_index).is_name_and_type(), "");
return pool_index;
}
}
assert(tag_at(i).is_field_or_method(), "Corrupted constant pool");
assert(!tag_at(i).is_invoke_dynamic(), "Must be handled above");
jint ref_index = *int_at_addr(i);
return extract_high_short_from_int(ref_index);
}
int ConstantPool::impl_klass_ref_index_at(int which, bool uncached) {
guarantee(!ConstantPool::is_invokedynamic_index(which),
"an invokedynamic instruction does not have a klass");
int i = which;
if (!uncached && cache() != NULL) {
// change byte-ordering and go via cache
i = remap_instruction_operand_from_cache(which);
}
assert(tag_at(i).is_field_or_method(), "Corrupted constant pool");
jint ref_index = *int_at_addr(i);
return extract_low_short_from_int(ref_index);
}
int ConstantPool::remap_instruction_operand_from_cache(int operand) {
int cpc_index = operand;
DEBUG_ONLY(cpc_index -= CPCACHE_INDEX_TAG);
assert((int)(u2)cpc_index == cpc_index, "clean u2");
int member_index = cache()->entry_at(cpc_index)->constant_pool_index();
return member_index;
}
void ConstantPool::verify_constant_pool_resolve(constantPoolHandle this_oop, KlassHandle k, TRAPS) {
if (k->oop_is_instance() || k->oop_is_objArray()) {
instanceKlassHandle holder (THREAD, this_oop->pool_holder());
Klass* elem_oop = k->oop_is_instance() ? k() : ObjArrayKlass::cast(k())->bottom_klass();
KlassHandle element (THREAD, elem_oop);
// The element type could be a typeArray - we only need the access check if it is
// an reference to another class
if (element->oop_is_instance()) {
LinkResolver::check_klass_accessability(holder, element, CHECK);
}
}
}
int ConstantPool::name_ref_index_at(int which_nt) {
jint ref_index = name_and_type_at(which_nt);
return extract_low_short_from_int(ref_index);
}
int ConstantPool::signature_ref_index_at(int which_nt) {
jint ref_index = name_and_type_at(which_nt);
return extract_high_short_from_int(ref_index);
}
Klass* ConstantPool::klass_ref_at(int which, TRAPS) {
return klass_at(klass_ref_index_at(which), CHECK_NULL);
}
Symbol* ConstantPool::klass_name_at(int which) {
assert(tag_at(which).is_unresolved_klass() || tag_at(which).is_klass(),
"Corrupted constant pool");
// A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
// It is not safe to rely on the tag bit's here, since we don't have a lock, and the entry and
// tag is not updated atomicly.
CPSlot entry = slot_at(which);
if (entry.is_resolved()) {
// Already resolved - return entry's name.
assert(entry.get_klass()->is_klass(), "must be");
return entry.get_klass()->name();
} else {
assert(entry.is_unresolved(), "must be either symbol or klass");
return entry.get_symbol();
}
}
Symbol* ConstantPool::klass_ref_at_noresolve(int which) {
jint ref_index = klass_ref_index_at(which);
return klass_at_noresolve(ref_index);
}
Symbol* ConstantPool::uncached_klass_ref_at_noresolve(int which) {
jint ref_index = uncached_klass_ref_index_at(which);
return klass_at_noresolve(ref_index);
}
char* ConstantPool::string_at_noresolve(int which) {
Symbol* s = unresolved_string_at(which);
if (s == NULL) {
return (char*)"<pseudo-string>";
} else {
return unresolved_string_at(which)->as_C_string();
}
}
BasicType ConstantPool::basic_type_for_signature_at(int which) {
return FieldType::basic_type(symbol_at(which));
}
void ConstantPool::resolve_string_constants_impl(constantPoolHandle this_oop, TRAPS) {
for (int index = 1; index < this_oop->length(); index++) { // Index 0 is unused
if (this_oop->tag_at(index).is_string()) {
this_oop->string_at(index, CHECK);
}
}
}
// Resolve all the classes in the constant pool. If they are all resolved,
// the constant pool is read-only. Enhancement: allocate cp entries to
// another metaspace, and copy to read-only or read-write space if this
// bit is set.
bool ConstantPool::resolve_class_constants(TRAPS) {
constantPoolHandle cp(THREAD, this);
for (int index = 1; index < length(); index++) { // Index 0 is unused
if (tag_at(index).is_unresolved_klass() &&
klass_at_if_loaded(cp, index) == NULL) {
return false;
}
}
// set_preresolution(); or some bit for future use
return true;
}
// If resolution for MethodHandle or MethodType fails, save the exception
// in the resolution error table, so that the same exception is thrown again.
void ConstantPool::save_and_throw_exception(constantPoolHandle this_oop, int which,
int tag, TRAPS) {
ResourceMark rm;
Symbol* error = PENDING_EXCEPTION->klass()->name();
MonitorLockerEx ml(this_oop->lock()); // lock cpool to change tag.
int error_tag = (tag == JVM_CONSTANT_MethodHandle) ?
JVM_CONSTANT_MethodHandleInError : JVM_CONSTANT_MethodTypeInError;
if (!PENDING_EXCEPTION->
is_a(SystemDictionary::LinkageError_klass())) {
// Just throw the exception and don't prevent these classes from
// being loaded due to virtual machine errors like StackOverflow
// and OutOfMemoryError, etc, or if the thread was hit by stop()
// Needs clarification to section 5.4.3 of the VM spec (see 6308271)
} else if (this_oop->tag_at(which).value() != error_tag) {
SystemDictionary::add_resolution_error(this_oop, which, error);
this_oop->tag_at_put(which, error_tag);
} else {
// some other thread has put the class in error state.
error = SystemDictionary::find_resolution_error(this_oop, which);
assert(error != NULL, "checking");
CLEAR_PENDING_EXCEPTION;
THROW_MSG(error, "");
}
}
// Called to resolve constants in the constant pool and return an oop.
// Some constant pool entries cache their resolved oop. This is also
// called to create oops from constants to use in arguments for invokedynamic
oop ConstantPool::resolve_constant_at_impl(constantPoolHandle this_oop, int index, int cache_index, TRAPS) {
oop result_oop = NULL;
Handle throw_exception;
if (cache_index == _possible_index_sentinel) {
// It is possible that this constant is one which is cached in the objects.
// We'll do a linear search. This should be OK because this usage is rare.
assert(index > 0, "valid index");
cache_index = this_oop->cp_to_object_index(index);
}
assert(cache_index == _no_index_sentinel || cache_index >= 0, "");
assert(index == _no_index_sentinel || index >= 0, "");
if (cache_index >= 0) {
result_oop = this_oop->resolved_references()->obj_at(cache_index);
if (result_oop != NULL) {
return result_oop;
// That was easy...
}
index = this_oop->object_to_cp_index(cache_index);
}
jvalue prim_value; // temp used only in a few cases below
int tag_value = this_oop->tag_at(index).value();
switch (tag_value) {
case JVM_CONSTANT_UnresolvedClass:
case JVM_CONSTANT_UnresolvedClassInError:
case JVM_CONSTANT_Class:
{
assert(cache_index == _no_index_sentinel, "should not have been set");
Klass* resolved = klass_at_impl(this_oop, index, CHECK_NULL);
// ldc wants the java mirror.
result_oop = resolved->java_mirror();
break;
}
case JVM_CONSTANT_String:
assert(cache_index != _no_index_sentinel, "should have been set");
if (this_oop->is_pseudo_string_at(index)) {
result_oop = this_oop->pseudo_string_at(index, cache_index);
break;
}
result_oop = string_at_impl(this_oop, index, cache_index, CHECK_NULL);
break;
case JVM_CONSTANT_MethodHandleInError:
case JVM_CONSTANT_MethodTypeInError:
{
Symbol* error = SystemDictionary::find_resolution_error(this_oop, index);
guarantee(error != (Symbol*)NULL, "tag mismatch with resolution error table");
ResourceMark rm;
THROW_MSG_0(error, "");
break;
}
case JVM_CONSTANT_MethodHandle:
{
int ref_kind = this_oop->method_handle_ref_kind_at(index);
int callee_index = this_oop->method_handle_klass_index_at(index);
Symbol* name = this_oop->method_handle_name_ref_at(index);
Symbol* signature = this_oop->method_handle_signature_ref_at(index);
if (PrintMiscellaneous)
tty->print_cr("resolve JVM_CONSTANT_MethodHandle:%d [%d/%d/%d] %s.%s",
ref_kind, index, this_oop->method_handle_index_at(index),
callee_index, name->as_C_string(), signature->as_C_string());
KlassHandle callee;
{ Klass* k = klass_at_impl(this_oop, callee_index, CHECK_NULL);
callee = KlassHandle(THREAD, k);
}
KlassHandle klass(THREAD, this_oop->pool_holder());
Handle value = SystemDictionary::link_method_handle_constant(klass, ref_kind,
callee, name, signature,
THREAD);
result_oop = value();
if (HAS_PENDING_EXCEPTION) {
save_and_throw_exception(this_oop, index, tag_value, CHECK_NULL);
}
break;
}
case JVM_CONSTANT_MethodType:
{
Symbol* signature = this_oop->method_type_signature_at(index);
if (PrintMiscellaneous)
tty->print_cr("resolve JVM_CONSTANT_MethodType [%d/%d] %s",
index, this_oop->method_type_index_at(index),
signature->as_C_string());
KlassHandle klass(THREAD, this_oop->pool_holder());
Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);
result_oop = value();
if (HAS_PENDING_EXCEPTION) {
save_and_throw_exception(this_oop, index, tag_value, CHECK_NULL);
}
break;
}
case JVM_CONSTANT_Integer:
assert(cache_index == _no_index_sentinel, "should not have been set");
prim_value.i = this_oop->int_at(index);
result_oop = java_lang_boxing_object::create(T_INT, &prim_value, CHECK_NULL);
break;
case JVM_CONSTANT_Float:
assert(cache_index == _no_index_sentinel, "should not have been set");
prim_value.f = this_oop->float_at(index);
result_oop = java_lang_boxing_object::create(T_FLOAT, &prim_value, CHECK_NULL);
break;
case JVM_CONSTANT_Long:
assert(cache_index == _no_index_sentinel, "should not have been set");
prim_value.j = this_oop->long_at(index);
result_oop = java_lang_boxing_object::create(T_LONG, &prim_value, CHECK_NULL);
break;
case JVM_CONSTANT_Double:
assert(cache_index == _no_index_sentinel, "should not have been set");
prim_value.d = this_oop->double_at(index);
result_oop = java_lang_boxing_object::create(T_DOUBLE, &prim_value, CHECK_NULL);
break;
default:
DEBUG_ONLY( tty->print_cr("*** %p: tag at CP[%d/%d] = %d",
this_oop(), index, cache_index, tag_value) );
assert(false, "unexpected constant tag");
break;
}
if (cache_index >= 0) {
// Cache the oop here also.
Handle result_handle(THREAD, result_oop);
MonitorLockerEx ml(this_oop->lock()); // don't know if we really need this
oop result = this_oop->resolved_references()->obj_at(cache_index);
// Benign race condition: resolved_references may already be filled in while we were trying to lock.
// The important thing here is that all threads pick up the same result.
// It doesn't matter which racing thread wins, as long as only one
// result is used by all threads, and all future queries.
// That result may be either a resolved constant or a failure exception.
if (result == NULL) {
this_oop->resolved_references()->obj_at_put(cache_index, result_handle());
return result_handle();
} else {
// Return the winning thread's result. This can be different than
// result_handle() for MethodHandles.
return result;
}
} else {
return result_oop;
}
}
oop ConstantPool::uncached_string_at(int which, TRAPS) {
Symbol* sym = unresolved_string_at(which);
oop str = StringTable::intern(sym, CHECK_(NULL));
assert(java_lang_String::is_instance(str), "must be string");
return str;
}
oop ConstantPool::resolve_bootstrap_specifier_at_impl(constantPoolHandle this_oop, int index, TRAPS) {
assert(this_oop->tag_at(index).is_invoke_dynamic(), "Corrupted constant pool");
Handle bsm;
int argc;
{
// JVM_CONSTANT_InvokeDynamic is an ordered pair of [bootm, name&type], plus optional arguments
// The bootm, being a JVM_CONSTANT_MethodHandle, has its own cache entry.
// It is accompanied by the optional arguments.
int bsm_index = this_oop->invoke_dynamic_bootstrap_method_ref_index_at(index);
oop bsm_oop = this_oop->resolve_possibly_cached_constant_at(bsm_index, CHECK_NULL);
if (!java_lang_invoke_MethodHandle::is_instance(bsm_oop)) {
THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "BSM not an MethodHandle");
}
// Extract the optional static arguments.
argc = this_oop->invoke_dynamic_argument_count_at(index);
if (argc == 0) return bsm_oop;
bsm = Handle(THREAD, bsm_oop);
}
objArrayHandle info;
{
objArrayOop info_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1+argc, CHECK_NULL);
info = objArrayHandle(THREAD, info_oop);
}
info->obj_at_put(0, bsm());
for (int i = 0; i < argc; i++) {
int arg_index = this_oop->invoke_dynamic_argument_index_at(index, i);
oop arg_oop = this_oop->resolve_possibly_cached_constant_at(arg_index, CHECK_NULL);
info->obj_at_put(1+i, arg_oop);
}
return info();
}
oop ConstantPool::string_at_impl(constantPoolHandle this_oop, int which, int obj_index, TRAPS) {
// If the string has already been interned, this entry will be non-null
oop str = this_oop->resolved_references()->obj_at(obj_index);
if (str != NULL) return str;
Symbol* sym = this_oop->unresolved_string_at(which);
str = StringTable::intern(sym, CHECK_(NULL));
this_oop->string_at_put(which, obj_index, str);
assert(java_lang_String::is_instance(str), "must be string");
return str;
}
bool ConstantPool::klass_name_at_matches(instanceKlassHandle k,
int which) {
// Names are interned, so we can compare Symbol*s directly
Symbol* cp_name = klass_name_at(which);
return (cp_name == k->name());
}
// Iterate over symbols and decrement ones which are Symbol*s.
// This is done during GC so do not need to lock constantPool unless we
// have per-thread safepoints.
// Only decrement the UTF8 symbols. Unresolved classes and strings point to
// these symbols but didn't increment the reference count.
void ConstantPool::unreference_symbols() {
for (int index = 1; index < length(); index++) { // Index 0 is unused
constantTag tag = tag_at(index);
if (tag.is_symbol()) {
symbol_at(index)->decrement_refcount();
}
}
}
// Compare this constant pool's entry at index1 to the constant pool
// cp2's entry at index2.
bool ConstantPool::compare_entry_to(int index1, constantPoolHandle cp2,
int index2, TRAPS) {
// The error tags are equivalent to non-error tags when comparing
jbyte t1 = tag_at(index1).non_error_value();
jbyte t2 = cp2->tag_at(index2).non_error_value();
if (t1 != t2) {
// Not the same entry type so there is nothing else to check. Note
// that this style of checking will consider resolved/unresolved
// class pairs as different.
// From the ConstantPool* API point of view, this is correct
// behavior. See VM_RedefineClasses::merge_constant_pools() to see how this
// plays out in the context of ConstantPool* merging.
return false;
}
switch (t1) {
case JVM_CONSTANT_Class:
{
Klass* k1 = klass_at(index1, CHECK_false);
Klass* k2 = cp2->klass_at(index2, CHECK_false);
if (k1 == k2) {
return true;
}
} break;
case JVM_CONSTANT_ClassIndex:
{
int recur1 = klass_index_at(index1);
int recur2 = cp2->klass_index_at(index2);
bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
if (match) {
return true;
}
} break;
case JVM_CONSTANT_Double:
{
jdouble d1 = double_at(index1);
jdouble d2 = cp2->double_at(index2);
if (d1 == d2) {
return true;
}
} break;
case JVM_CONSTANT_Fieldref:
case JVM_CONSTANT_InterfaceMethodref:
case JVM_CONSTANT_Methodref:
{
int recur1 = uncached_klass_ref_index_at(index1);
int recur2 = cp2->uncached_klass_ref_index_at(index2);
bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
if (match) {
recur1 = uncached_name_and_type_ref_index_at(index1);
recur2 = cp2->uncached_name_and_type_ref_index_at(index2);
match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
if (match) {
return true;
}
}
} break;
case JVM_CONSTANT_Float:
{
jfloat f1 = float_at(index1);
jfloat f2 = cp2->float_at(index2);
if (f1 == f2) {
return true;
}
} break;
case JVM_CONSTANT_Integer:
{
jint i1 = int_at(index1);
jint i2 = cp2->int_at(index2);
if (i1 == i2) {
return true;
}
} break;
case JVM_CONSTANT_Long:
{
jlong l1 = long_at(index1);
jlong l2 = cp2->long_at(index2);
if (l1 == l2) {
return true;
}
} break;
case JVM_CONSTANT_NameAndType:
{
int recur1 = name_ref_index_at(index1);
int recur2 = cp2->name_ref_index_at(index2);
bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
if (match) {
recur1 = signature_ref_index_at(index1);
recur2 = cp2->signature_ref_index_at(index2);
match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
if (match) {
return true;
}
}
} break;
case JVM_CONSTANT_StringIndex:
{
int recur1 = string_index_at(index1);
int recur2 = cp2->string_index_at(index2);
bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
if (match) {
return true;
}
} break;
case JVM_CONSTANT_UnresolvedClass:
{
Symbol* k1 = unresolved_klass_at(index1);
Symbol* k2 = cp2->unresolved_klass_at(index2);
if (k1 == k2) {
return true;
}
} break;
case JVM_CONSTANT_MethodType:
{
int k1 = method_type_index_at_error_ok(index1);
int k2 = cp2->method_type_index_at_error_ok(index2);
bool match = compare_entry_to(k1, cp2, k2, CHECK_false);
if (match) {
return true;
}
} break;
case JVM_CONSTANT_MethodHandle:
{
int k1 = method_handle_ref_kind_at_error_ok(index1);
int k2 = cp2->method_handle_ref_kind_at_error_ok(index2);
if (k1 == k2) {
int i1 = method_handle_index_at_error_ok(index1);
int i2 = cp2->method_handle_index_at_error_ok(index2);
bool match = compare_entry_to(i1, cp2, i2, CHECK_false);
if (match) {
return true;
}
}
} break;
case JVM_CONSTANT_InvokeDynamic:
{
int k1 = invoke_dynamic_name_and_type_ref_index_at(index1);
int k2 = cp2->invoke_dynamic_name_and_type_ref_index_at(index2);
int i1 = invoke_dynamic_bootstrap_specifier_index(index1);
int i2 = cp2->invoke_dynamic_bootstrap_specifier_index(index2);
// separate statements and variables because CHECK_false is used
bool match_entry = compare_entry_to(k1, cp2, k2, CHECK_false);
bool match_operand = compare_operand_to(i1, cp2, i2, CHECK_false);
return (match_entry && match_operand);
} break;
case JVM_CONSTANT_String:
{
Symbol* s1 = unresolved_string_at(index1);
Symbol* s2 = cp2->unresolved_string_at(index2);
if (s1 == s2) {
return true;
}
} break;
case JVM_CONSTANT_Utf8:
{
Symbol* s1 = symbol_at(index1);
Symbol* s2 = cp2->symbol_at(index2);
if (s1 == s2) {
return true;
}
} break;
// Invalid is used as the tag for the second constant pool entry
// occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
// not be seen by itself.
case JVM_CONSTANT_Invalid: // fall through
default:
ShouldNotReachHere();
break;
}
return false;
} // end compare_entry_to()
// Resize the operands array with delta_len and delta_size.
// Used in RedefineClasses for CP merge.
void ConstantPool::resize_operands(int delta_len, int delta_size, TRAPS) {
int old_len = operand_array_length(operands());
int new_len = old_len + delta_len;
int min_len = (delta_len > 0) ? old_len : new_len;
int old_size = operands()->length();
int new_size = old_size + delta_size;
int min_size = (delta_size > 0) ? old_size : new_size;
ClassLoaderData* loader_data = pool_holder()->class_loader_data();
Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, new_size, CHECK);
// Set index in the resized array for existing elements only
for (int idx = 0; idx < min_len; idx++) {
int offset = operand_offset_at(idx); // offset in original array
operand_offset_at_put(new_ops, idx, offset + 2*delta_len); // offset in resized array
}
// Copy the bootstrap specifiers only
Copy::conjoint_memory_atomic(operands()->adr_at(2*old_len),
new_ops->adr_at(2*new_len),
(min_size - 2*min_len) * sizeof(u2));
// Explicitly deallocate old operands array.
// Note, it is not needed for 7u backport.
if ( operands() != NULL) { // the safety check
MetadataFactory::free_array<u2>(loader_data, operands());
}
set_operands(new_ops);
} // end resize_operands()
// Extend the operands array with the length and size of the ext_cp operands.
// Used in RedefineClasses for CP merge.
void ConstantPool::extend_operands(constantPoolHandle ext_cp, TRAPS) {
int delta_len = operand_array_length(ext_cp->operands());
if (delta_len == 0) {
return; // nothing to do
}
int delta_size = ext_cp->operands()->length();
assert(delta_len > 0 && delta_size > 0, "extended operands array must be bigger");
if (operand_array_length(operands()) == 0) {
ClassLoaderData* loader_data = pool_holder()->class_loader_data();
Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, delta_size, CHECK);
// The first element index defines the offset of second part
operand_offset_at_put(new_ops, 0, 2*delta_len); // offset in new array
set_operands(new_ops);
} else {
resize_operands(delta_len, delta_size, CHECK);
}
} // end extend_operands()
// Shrink the operands array to a smaller array with new_len length.
// Used in RedefineClasses for CP merge.
void ConstantPool::shrink_operands(int new_len, TRAPS) {
int old_len = operand_array_length(operands());
if (new_len == old_len) {
return; // nothing to do
}
assert(new_len < old_len, "shrunken operands array must be smaller");
int free_base = operand_next_offset_at(new_len - 1);
int delta_len = new_len - old_len;
int delta_size = 2*delta_len + free_base - operands()->length();
resize_operands(delta_len, delta_size, CHECK);
} // end shrink_operands()
void ConstantPool::copy_operands(constantPoolHandle from_cp,
constantPoolHandle to_cp,
TRAPS) {
int from_oplen = operand_array_length(from_cp->operands());
int old_oplen = operand_array_length(to_cp->operands());
if (from_oplen != 0) {
ClassLoaderData* loader_data = to_cp->pool_holder()->class_loader_data();
// append my operands to the target's operands array
if (old_oplen == 0) {
// Can't just reuse from_cp's operand list because of deallocation issues
int len = from_cp->operands()->length();
Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, len, CHECK);
Copy::conjoint_memory_atomic(
from_cp->operands()->adr_at(0), new_ops->adr_at(0), len * sizeof(u2));
to_cp->set_operands(new_ops);
} else {
int old_len = to_cp->operands()->length();
int from_len = from_cp->operands()->length();
int old_off = old_oplen * sizeof(u2);
int from_off = from_oplen * sizeof(u2);
// Use the metaspace for the destination constant pool
Array<u2>* new_operands = MetadataFactory::new_array<u2>(loader_data, old_len + from_len, CHECK);
int fillp = 0, len = 0;
// first part of dest
Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(0),
new_operands->adr_at(fillp),
(len = old_off) * sizeof(u2));
fillp += len;
// first part of src
Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(0),
new_operands->adr_at(fillp),
(len = from_off) * sizeof(u2));
fillp += len;
// second part of dest
Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(old_off),
new_operands->adr_at(fillp),
(len = old_len - old_off) * sizeof(u2));
fillp += len;
// second part of src
Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(from_off),
new_operands->adr_at(fillp),
(len = from_len - from_off) * sizeof(u2));
fillp += len;
assert(fillp == new_operands->length(), "");
// Adjust indexes in the first part of the copied operands array.
for (int j = 0; j < from_oplen; j++) {
int offset = operand_offset_at(new_operands, old_oplen + j);
assert(offset == operand_offset_at(from_cp->operands(), j), "correct copy");
offset += old_len; // every new tuple is preceded by old_len extra u2's
operand_offset_at_put(new_operands, old_oplen + j, offset);
}
// replace target operands array with combined array
to_cp->set_operands(new_operands);
}
}
} // end copy_operands()
// Copy this constant pool's entries at start_i to end_i (inclusive)
// to the constant pool to_cp's entries starting at to_i. A total of
// (end_i - start_i) + 1 entries are copied.
void ConstantPool::copy_cp_to_impl(constantPoolHandle from_cp, int start_i, int end_i,
constantPoolHandle to_cp, int to_i, TRAPS) {
int dest_i = to_i; // leave original alone for debug purposes
for (int src_i = start_i; src_i <= end_i; /* see loop bottom */ ) {
copy_entry_to(from_cp, src_i, to_cp, dest_i, CHECK);
switch (from_cp->tag_at(src_i).value()) {
case JVM_CONSTANT_Double:
case JVM_CONSTANT_Long:
// double and long take two constant pool entries
src_i += 2;
dest_i += 2;
break;
default:
// all others take one constant pool entry
src_i++;
dest_i++;
break;
}
}
copy_operands(from_cp, to_cp, CHECK);
} // end copy_cp_to_impl()
// Copy this constant pool's entry at from_i to the constant pool
// to_cp's entry at to_i.
void ConstantPool::copy_entry_to(constantPoolHandle from_cp, int from_i,
constantPoolHandle to_cp, int to_i,
TRAPS) {
int tag = from_cp->tag_at(from_i).value();
switch (tag) {
case JVM_CONSTANT_Class:
{
Klass* k = from_cp->klass_at(from_i, CHECK);
to_cp->klass_at_put(to_i, k);
} break;
case JVM_CONSTANT_ClassIndex:
{
jint ki = from_cp->klass_index_at(from_i);
to_cp->klass_index_at_put(to_i, ki);
} break;
case JVM_CONSTANT_Double:
{
jdouble d = from_cp->double_at(from_i);
to_cp->double_at_put(to_i, d);
// double takes two constant pool entries so init second entry's tag
to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
} break;
case JVM_CONSTANT_Fieldref:
{
int class_index = from_cp->uncached_klass_ref_index_at(from_i);
int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
to_cp->field_at_put(to_i, class_index, name_and_type_index);
} break;
case JVM_CONSTANT_Float:
{
jfloat f = from_cp->float_at(from_i);
to_cp->float_at_put(to_i, f);
} break;
case JVM_CONSTANT_Integer:
{
jint i = from_cp->int_at(from_i);
to_cp->int_at_put(to_i, i);
} break;
case JVM_CONSTANT_InterfaceMethodref:
{
int class_index = from_cp->uncached_klass_ref_index_at(from_i);
int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);
} break;
case JVM_CONSTANT_Long:
{
jlong l = from_cp->long_at(from_i);
to_cp->long_at_put(to_i, l);
// long takes two constant pool entries so init second entry's tag
to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
} break;
case JVM_CONSTANT_Methodref:
{
int class_index = from_cp->uncached_klass_ref_index_at(from_i);
int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
to_cp->method_at_put(to_i, class_index, name_and_type_index);
} break;
case JVM_CONSTANT_NameAndType:
{
int name_ref_index = from_cp->name_ref_index_at(from_i);
int signature_ref_index = from_cp->signature_ref_index_at(from_i);
to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);
} break;
case JVM_CONSTANT_StringIndex:
{
jint si = from_cp->string_index_at(from_i);
to_cp->string_index_at_put(to_i, si);
} break;
case JVM_CONSTANT_UnresolvedClass:
case JVM_CONSTANT_UnresolvedClassInError:
{
// Can be resolved after checking tag, so check the slot first.
CPSlot entry = from_cp->slot_at(from_i);
if (entry.is_resolved()) {
assert(entry.get_klass()->is_klass(), "must be");
// Already resolved
to_cp->klass_at_put(to_i, entry.get_klass());
} else {
to_cp->unresolved_klass_at_put(to_i, entry.get_symbol());
}
} break;
case JVM_CONSTANT_String:
{
Symbol* s = from_cp->unresolved_string_at(from_i);
to_cp->unresolved_string_at_put(to_i, s);
} break;
case JVM_CONSTANT_Utf8:
{
Symbol* s = from_cp->symbol_at(from_i);
// Need to increase refcount, the old one will be thrown away and deferenced
s->increment_refcount();
to_cp->symbol_at_put(to_i, s);
} break;
case JVM_CONSTANT_MethodType:
case JVM_CONSTANT_MethodTypeInError:
{
jint k = from_cp->method_type_index_at_error_ok(from_i);
to_cp->method_type_index_at_put(to_i, k);
} break;
case JVM_CONSTANT_MethodHandle:
case JVM_CONSTANT_MethodHandleInError:
{
int k1 = from_cp->method_handle_ref_kind_at_error_ok(from_i);
int k2 = from_cp->method_handle_index_at_error_ok(from_i);
to_cp->method_handle_index_at_put(to_i, k1, k2);
} break;
case JVM_CONSTANT_InvokeDynamic:
{
int k1 = from_cp->invoke_dynamic_bootstrap_specifier_index(from_i);
int k2 = from_cp->invoke_dynamic_name_and_type_ref_index_at(from_i);
k1 += operand_array_length(to_cp->operands()); // to_cp might already have operands
to_cp->invoke_dynamic_at_put(to_i, k1, k2);
} break;
// Invalid is used as the tag for the second constant pool entry
// occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
// not be seen by itself.
case JVM_CONSTANT_Invalid: // fall through
default:
{
ShouldNotReachHere();
} break;
}
} // end copy_entry_to()
// Search constant pool search_cp for an entry that matches this
// constant pool's entry at pattern_i. Returns the index of a
// matching entry or zero (0) if there is no matching entry.
int ConstantPool::find_matching_entry(int pattern_i,
constantPoolHandle search_cp, TRAPS) {
// index zero (0) is not used
for (int i = 1; i < search_cp->length(); i++) {
bool found = compare_entry_to(pattern_i, search_cp, i, CHECK_0);
if (found) {
return i;
}
}
return 0; // entry not found; return unused index zero (0)
} // end find_matching_entry()
// Compare this constant pool's bootstrap specifier at idx1 to the constant pool
// cp2's bootstrap specifier at idx2.
bool ConstantPool::compare_operand_to(int idx1, constantPoolHandle cp2, int idx2, TRAPS) {
int k1 = operand_bootstrap_method_ref_index_at(idx1);
int k2 = cp2->operand_bootstrap_method_ref_index_at(idx2);
bool match = compare_entry_to(k1, cp2, k2, CHECK_false);
if (!match) {
return false;
}
int argc = operand_argument_count_at(idx1);
if (argc == cp2->operand_argument_count_at(idx2)) {
for (int j = 0; j < argc; j++) {
k1 = operand_argument_index_at(idx1, j);
k2 = cp2->operand_argument_index_at(idx2, j);
match = compare_entry_to(k1, cp2, k2, CHECK_false);
if (!match) {
return false;
}
}
return true; // got through loop; all elements equal
}
return false;
} // end compare_operand_to()
// Search constant pool search_cp for a bootstrap specifier that matches
// this constant pool's bootstrap specifier at pattern_i index.
// Return the index of a matching bootstrap specifier or (-1) if there is no match.
int ConstantPool::find_matching_operand(int pattern_i,
constantPoolHandle search_cp, int search_len, TRAPS) {
for (int i = 0; i < search_len; i++) {
bool found = compare_operand_to(pattern_i, search_cp, i, CHECK_(-1));
if (found) {
return i;
}
}
return -1; // bootstrap specifier not found; return unused index (-1)
} // end find_matching_operand()
#ifndef PRODUCT
const char* ConstantPool::printable_name_at(int which) {
constantTag tag = tag_at(which);
if (tag.is_string()) {
return string_at_noresolve(which);
} else if (tag.is_klass() || tag.is_unresolved_klass()) {
return klass_name_at(which)->as_C_string();
} else if (tag.is_symbol()) {
return symbol_at(which)->as_C_string();
}
return "";
}
#endif // PRODUCT
// JVMTI GetConstantPool support
// For debugging of constant pool
const bool debug_cpool = false;
#define DBG(code) do { if (debug_cpool) { (code); } } while(0)
static void print_cpool_bytes(jint cnt, u1 *bytes) {
const char* WARN_MSG = "Must not be such entry!";
jint size = 0;
u2 idx1, idx2;
for (jint idx = 1; idx < cnt; idx++) {
jint ent_size = 0;
u1 tag = *bytes++;
size++; // count tag
printf("const #%03d, tag: %02d ", idx, tag);
switch(tag) {
case JVM_CONSTANT_Invalid: {
printf("Invalid");
break;
}
case JVM_CONSTANT_Unicode: {
printf("Unicode %s", WARN_MSG);
break;
}
case JVM_CONSTANT_Utf8: {
u2 len = Bytes::get_Java_u2(bytes);
char str[128];
if (len > 127) {
len = 127;
}
strncpy(str, (char *) (bytes+2), len);
str[len] = '\0';
printf("Utf8 \"%s\"", str);
ent_size = 2 + len;
break;
}
case JVM_CONSTANT_Integer: {
u4 val = Bytes::get_Java_u4(bytes);
printf("int %d", *(int *) &val);
ent_size = 4;
break;
}
case JVM_CONSTANT_Float: {
u4 val = Bytes::get_Java_u4(bytes);
printf("float %5.3ff", *(float *) &val);
ent_size = 4;
break;
}
case JVM_CONSTANT_Long: {
u8 val = Bytes::get_Java_u8(bytes);
printf("long "INT64_FORMAT, (int64_t) *(jlong *) &val);
ent_size = 8;
idx++; // Long takes two cpool slots
break;
}
case JVM_CONSTANT_Double: {
u8 val = Bytes::get_Java_u8(bytes);
printf("double %5.3fd", *(jdouble *)&val);
ent_size = 8;
idx++; // Double takes two cpool slots
break;
}
case JVM_CONSTANT_Class: {
idx1 = Bytes::get_Java_u2(bytes);
printf("class #%03d", idx1);
ent_size = 2;
break;
}
case JVM_CONSTANT_String: {
idx1 = Bytes::get_Java_u2(bytes);
printf("String #%03d", idx1);
ent_size = 2;
break;
}
case JVM_CONSTANT_Fieldref: {
idx1 = Bytes::get_Java_u2(bytes);
idx2 = Bytes::get_Java_u2(bytes+2);
printf("Field #%03d, #%03d", (int) idx1, (int) idx2);
ent_size = 4;
break;
}
case JVM_CONSTANT_Methodref: {
idx1 = Bytes::get_Java_u2(bytes);
idx2 = Bytes::get_Java_u2(bytes+2);
printf("Method #%03d, #%03d", idx1, idx2);
ent_size = 4;
break;
}
case JVM_CONSTANT_InterfaceMethodref: {
idx1 = Bytes::get_Java_u2(bytes);
idx2 = Bytes::get_Java_u2(bytes+2);
printf("InterfMethod #%03d, #%03d", idx1, idx2);
ent_size = 4;
break;
}
case JVM_CONSTANT_NameAndType: {
idx1 = Bytes::get_Java_u2(bytes);
idx2 = Bytes::get_Java_u2(bytes+2);
printf("NameAndType #%03d, #%03d", idx1, idx2);
ent_size = 4;
break;
}
case JVM_CONSTANT_ClassIndex: {
printf("ClassIndex %s", WARN_MSG);
break;
}
case JVM_CONSTANT_UnresolvedClass: {
printf("UnresolvedClass: %s", WARN_MSG);
break;
}
case JVM_CONSTANT_UnresolvedClassInError: {
printf("UnresolvedClassInErr: %s", WARN_MSG);
break;
}
case JVM_CONSTANT_StringIndex: {
printf("StringIndex: %s", WARN_MSG);
break;
}
}
printf(";\n");
bytes += ent_size;
size += ent_size;
}
printf("Cpool size: %d\n", size);
fflush(0);
return;
} /* end print_cpool_bytes */
// Returns size of constant pool entry.
jint ConstantPool::cpool_entry_size(jint idx) {
switch(tag_at(idx).value()) {
case JVM_CONSTANT_Invalid:
case JVM_CONSTANT_Unicode:
return 1;
case JVM_CONSTANT_Utf8:
return 3 + symbol_at(idx)->utf8_length();
case JVM_CONSTANT_Class:
case JVM_CONSTANT_String:
case JVM_CONSTANT_ClassIndex:
case JVM_CONSTANT_UnresolvedClass:
case JVM_CONSTANT_UnresolvedClassInError:
case JVM_CONSTANT_StringIndex:
case JVM_CONSTANT_MethodType:
case JVM_CONSTANT_MethodTypeInError:
return 3;
case JVM_CONSTANT_MethodHandle:
case JVM_CONSTANT_MethodHandleInError:
return 4; //tag, ref_kind, ref_index
case JVM_CONSTANT_Integer:
case JVM_CONSTANT_Float:
case JVM_CONSTANT_Fieldref:
case JVM_CONSTANT_Methodref:
case JVM_CONSTANT_InterfaceMethodref:
case JVM_CONSTANT_NameAndType:
return 5;
case JVM_CONSTANT_InvokeDynamic:
// u1 tag, u2 bsm, u2 nt
return 5;
case JVM_CONSTANT_Long:
case JVM_CONSTANT_Double:
return 9;
}
assert(false, "cpool_entry_size: Invalid constant pool entry tag");
return 1;
} /* end cpool_entry_size */
// SymbolHashMap is used to find a constant pool index from a string.
// This function fills in SymbolHashMaps, one for utf8s and one for
// class names, returns size of the cpool raw bytes.
jint ConstantPool::hash_entries_to(SymbolHashMap *symmap,
SymbolHashMap *classmap) {
jint size = 0;
for (u2 idx = 1; idx < length(); idx++) {
u2 tag = tag_at(idx).value();
size += cpool_entry_size(idx);
switch(tag) {
case JVM_CONSTANT_Utf8: {
Symbol* sym = symbol_at(idx);
symmap->add_entry(sym, idx);
DBG(printf("adding symbol entry %s = %d\n", sym->as_utf8(), idx));
break;
}
case JVM_CONSTANT_Class:
case JVM_CONSTANT_UnresolvedClass:
case JVM_CONSTANT_UnresolvedClassInError: {
Symbol* sym = klass_name_at(idx);
classmap->add_entry(sym, idx);
DBG(printf("adding class entry %s = %d\n", sym->as_utf8(), idx));
break;
}
case JVM_CONSTANT_Long:
case JVM_CONSTANT_Double: {
idx++; // Both Long and Double take two cpool slots
break;
}
}
}
return size;
} /* end hash_utf8_entries_to */
// Copy cpool bytes.
// Returns:
// 0, in case of OutOfMemoryError
// -1, in case of internal error
// > 0, count of the raw cpool bytes that have been copied
int ConstantPool::copy_cpool_bytes(int cpool_size,
SymbolHashMap* tbl,
unsigned char *bytes) {
u2 idx1, idx2;
jint size = 0;
jint cnt = length();
unsigned char *start_bytes = bytes;
for (jint idx = 1; idx < cnt; idx++) {
u1 tag = tag_at(idx).value();
jint ent_size = cpool_entry_size(idx);
assert(size + ent_size <= cpool_size, "Size mismatch");
*bytes = tag;
DBG(printf("#%03hd tag=%03hd, ", idx, tag));
switch(tag) {
case JVM_CONSTANT_Invalid: {
DBG(printf("JVM_CONSTANT_Invalid"));
break;
}
case JVM_CONSTANT_Unicode: {
assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");
DBG(printf("JVM_CONSTANT_Unicode"));
break;
}
case JVM_CONSTANT_Utf8: {
Symbol* sym = symbol_at(idx);
char* str = sym->as_utf8();
// Warning! It's crashing on x86 with len = sym->utf8_length()
int len = (int) strlen(str);
Bytes::put_Java_u2((address) (bytes+1), (u2) len);
for (int i = 0; i < len; i++) {
bytes[3+i] = (u1) str[i];
}
DBG(printf("JVM_CONSTANT_Utf8: %s ", str));
break;
}
case JVM_CONSTANT_Integer: {
jint val = int_at(idx);
Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
break;
}
case JVM_CONSTANT_Float: {
jfloat val = float_at(idx);
Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
break;
}
case JVM_CONSTANT_Long: {
jlong val = long_at(idx);
Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
idx++; // Long takes two cpool slots
break;
}
case JVM_CONSTANT_Double: {
jdouble val = double_at(idx);
Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
idx++; // Double takes two cpool slots
break;
}
case JVM_CONSTANT_Class:
case JVM_CONSTANT_UnresolvedClass:
case JVM_CONSTANT_UnresolvedClassInError: {
*bytes = JVM_CONSTANT_Class;
Symbol* sym = klass_name_at(idx);
idx1 = tbl->symbol_to_value(sym);
assert(idx1 != 0, "Have not found a hashtable entry");
Bytes::put_Java_u2((address) (bytes+1), idx1);
DBG(printf("JVM_CONSTANT_Class: idx=#%03hd, %s", idx1, sym->as_utf8()));
break;
}
case JVM_CONSTANT_String: {
*bytes = JVM_CONSTANT_String;
Symbol* sym = unresolved_string_at(idx);
idx1 = tbl->symbol_to_value(sym);
assert(idx1 != 0, "Have not found a hashtable entry");
Bytes::put_Java_u2((address) (bytes+1), idx1);
DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, sym->as_utf8()));
break;
}
case JVM_CONSTANT_Fieldref:
case JVM_CONSTANT_Methodref:
case JVM_CONSTANT_InterfaceMethodref: {
idx1 = uncached_klass_ref_index_at(idx);
idx2 = uncached_name_and_type_ref_index_at(idx);
Bytes::put_Java_u2((address) (bytes+1), idx1);
Bytes::put_Java_u2((address) (bytes+3), idx2);
DBG(printf("JVM_CONSTANT_Methodref: %hd %hd", idx1, idx2));
break;
}
case JVM_CONSTANT_NameAndType: {
idx1 = name_ref_index_at(idx);
idx2 = signature_ref_index_at(idx);
Bytes::put_Java_u2((address) (bytes+1), idx1);
Bytes::put_Java_u2((address) (bytes+3), idx2);
DBG(printf("JVM_CONSTANT_NameAndType: %hd %hd", idx1, idx2));
break;
}
case JVM_CONSTANT_ClassIndex: {
*bytes = JVM_CONSTANT_Class;
idx1 = klass_index_at(idx);
Bytes::put_Java_u2((address) (bytes+1), idx1);
DBG(printf("JVM_CONSTANT_ClassIndex: %hd", idx1));
break;
}
case JVM_CONSTANT_StringIndex: {
*bytes = JVM_CONSTANT_String;
idx1 = string_index_at(idx);
Bytes::put_Java_u2((address) (bytes+1), idx1);
DBG(printf("JVM_CONSTANT_StringIndex: %hd", idx1));
break;
}
case JVM_CONSTANT_MethodHandle:
case JVM_CONSTANT_MethodHandleInError: {
*bytes = JVM_CONSTANT_MethodHandle;
int kind = method_handle_ref_kind_at_error_ok(idx);
idx1 = method_handle_index_at_error_ok(idx);
*(bytes+1) = (unsigned char) kind;
Bytes::put_Java_u2((address) (bytes+2), idx1);
DBG(printf("JVM_CONSTANT_MethodHandle: %d %hd", kind, idx1));
break;
}
case JVM_CONSTANT_MethodType:
case JVM_CONSTANT_MethodTypeInError: {
*bytes = JVM_CONSTANT_MethodType;
idx1 = method_type_index_at_error_ok(idx);
Bytes::put_Java_u2((address) (bytes+1), idx1);
DBG(printf("JVM_CONSTANT_MethodType: %hd", idx1));
break;
}
case JVM_CONSTANT_InvokeDynamic: {
*bytes = tag;
idx1 = extract_low_short_from_int(*int_at_addr(idx));
idx2 = extract_high_short_from_int(*int_at_addr(idx));
assert(idx2 == invoke_dynamic_name_and_type_ref_index_at(idx), "correct half of u4");
Bytes::put_Java_u2((address) (bytes+1), idx1);
Bytes::put_Java_u2((address) (bytes+3), idx2);
DBG(printf("JVM_CONSTANT_InvokeDynamic: %hd %hd", idx1, idx2));
break;
}
}
DBG(printf("\n"));
bytes += ent_size;
size += ent_size;
}
assert(size == cpool_size, "Size mismatch");
// Keep temorarily for debugging until it's stable.
DBG(print_cpool_bytes(cnt, start_bytes));
return (int)(bytes - start_bytes);
} /* end copy_cpool_bytes */
#undef DBG
void ConstantPool::set_on_stack(const bool value) {
if (value) {
_flags |= _on_stack;
} else {
_flags &= ~_on_stack;
}
if (value) MetadataOnStackMark::record(this);
}
// JSR 292 support for patching constant pool oops after the class is linked and
// the oop array for resolved references are created.
// We can't do this during classfile parsing, which is how the other indexes are
// patched. The other patches are applied early for some error checking
// so only defer the pseudo_strings.
void ConstantPool::patch_resolved_references(
GrowableArray<Handle>* cp_patches) {
assert(EnableInvokeDynamic, "");
for (int index = 1; index < cp_patches->length(); index++) { // Index 0 is unused
Handle patch = cp_patches->at(index);
if (patch.not_null()) {
assert (tag_at(index).is_string(), "should only be string left");
// Patching a string means pre-resolving it.
// The spelling in the constant pool is ignored.
// The constant reference may be any object whatever.
// If it is not a real interned string, the constant is referred
// to as a "pseudo-string", and must be presented to the CP
// explicitly, because it may require scavenging.
int obj_index = cp_to_object_index(index);
pseudo_string_at_put(index, obj_index, patch());
DEBUG_ONLY(cp_patches->at_put(index, Handle());)
}
}
#ifdef ASSERT
// Ensure that all the patches have been used.
for (int index = 0; index < cp_patches->length(); index++) {
assert(cp_patches->at(index).is_null(),
err_msg("Unused constant pool patch at %d in class file %s",
index,
pool_holder()->external_name()));
}
#endif // ASSERT
}
#ifndef PRODUCT
// CompileTheWorld support. Preload all classes loaded references in the passed in constantpool
void ConstantPool::preload_and_initialize_all_classes(ConstantPool* obj, TRAPS) {
guarantee(obj->is_constantPool(), "object must be constant pool");
constantPoolHandle cp(THREAD, (ConstantPool*)obj);
guarantee(cp->pool_holder() != NULL, "must be fully loaded");
for (int i = 0; i< cp->length(); i++) {
if (cp->tag_at(i).is_unresolved_klass()) {
// This will force loading of the class
Klass* klass = cp->klass_at(i, CHECK);
if (klass->oop_is_instance()) {
// Force initialization of class
InstanceKlass::cast(klass)->initialize(CHECK);
}
}
}
}
#endif
// Printing
void ConstantPool::print_on(outputStream* st) const {
EXCEPTION_MARK;
assert(is_constantPool(), "must be constantPool");
st->print_cr(internal_name());
if (flags() != 0) {
st->print(" - flags: 0x%x", flags());
if (has_preresolution()) st->print(" has_preresolution");
if (on_stack()) st->print(" on_stack");
st->cr();
}
if (pool_holder() != NULL) {
st->print_cr(" - holder: " INTPTR_FORMAT, pool_holder());
}
st->print_cr(" - cache: " INTPTR_FORMAT, cache());
st->print_cr(" - resolved_references: " INTPTR_FORMAT, (void *)resolved_references());
st->print_cr(" - reference_map: " INTPTR_FORMAT, reference_map());
for (int index = 1; index < length(); index++) { // Index 0 is unused
((ConstantPool*)this)->print_entry_on(index, st);
switch (tag_at(index).value()) {
case JVM_CONSTANT_Long :
case JVM_CONSTANT_Double :
index++; // Skip entry following eigth-byte constant
}
}
st->cr();
}
// Print one constant pool entry
void ConstantPool::print_entry_on(const int index, outputStream* st) {
EXCEPTION_MARK;
st->print(" - %3d : ", index);
tag_at(index).print_on(st);
st->print(" : ");
switch (tag_at(index).value()) {
case JVM_CONSTANT_Class :
{ Klass* k = klass_at(index, CATCH);
guarantee(k != NULL, "need klass");
k->print_value_on(st);
st->print(" {0x%lx}", (address)k);
}
break;
case JVM_CONSTANT_Fieldref :
case JVM_CONSTANT_Methodref :
case JVM_CONSTANT_InterfaceMethodref :
st->print("klass_index=%d", uncached_klass_ref_index_at(index));
st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(index));
break;
case JVM_CONSTANT_String :
if (is_pseudo_string_at(index)) {
oop anObj = pseudo_string_at(index);
anObj->print_value_on(st);
st->print(" {0x%lx}", (address)anObj);
} else {
unresolved_string_at(index)->print_value_on(st);
}
break;
case JVM_CONSTANT_Integer :
st->print("%d", int_at(index));
break;
case JVM_CONSTANT_Float :
st->print("%f", float_at(index));
break;
case JVM_CONSTANT_Long :
st->print_jlong(long_at(index));
break;
case JVM_CONSTANT_Double :
st->print("%lf", double_at(index));
break;
case JVM_CONSTANT_NameAndType :
st->print("name_index=%d", name_ref_index_at(index));
st->print(" signature_index=%d", signature_ref_index_at(index));
break;
case JVM_CONSTANT_Utf8 :
symbol_at(index)->print_value_on(st);
break;
case JVM_CONSTANT_UnresolvedClass : // fall-through
case JVM_CONSTANT_UnresolvedClassInError: {
// unresolved_klass_at requires lock or safe world.
CPSlot entry = slot_at(index);
if (entry.is_resolved()) {
entry.get_klass()->print_value_on(st);
} else {
entry.get_symbol()->print_value_on(st);
}
}
break;
case JVM_CONSTANT_MethodHandle :
case JVM_CONSTANT_MethodHandleInError :
st->print("ref_kind=%d", method_handle_ref_kind_at_error_ok(index));
st->print(" ref_index=%d", method_handle_index_at_error_ok(index));
break;
case JVM_CONSTANT_MethodType :
case JVM_CONSTANT_MethodTypeInError :
st->print("signature_index=%d", method_type_index_at_error_ok(index));
break;
case JVM_CONSTANT_InvokeDynamic :
{
st->print("bootstrap_method_index=%d", invoke_dynamic_bootstrap_method_ref_index_at(index));
st->print(" name_and_type_index=%d", invoke_dynamic_name_and_type_ref_index_at(index));
int argc = invoke_dynamic_argument_count_at(index);
if (argc > 0) {
for (int arg_i = 0; arg_i < argc; arg_i++) {
int arg = invoke_dynamic_argument_index_at(index, arg_i);
st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
}
st->print("}");
}
}
break;
default:
ShouldNotReachHere();
break;
}
st->cr();
}
void ConstantPool::print_value_on(outputStream* st) const {
assert(is_constantPool(), "must be constantPool");
st->print("constant pool [%d]", length());
if (has_preresolution()) st->print("/preresolution");
if (operands() != NULL) st->print("/operands[%d]", operands()->length());
print_address_on(st);
st->print(" for ");
pool_holder()->print_value_on(st);
if (pool_holder() != NULL) {
bool extra = (pool_holder()->constants() != this);
if (extra) st->print(" (extra)");
}
if (cache() != NULL) {
st->print(" cache=" PTR_FORMAT, cache());
}
}
#if INCLUDE_SERVICES
// Size Statistics
void ConstantPool::collect_statistics(KlassSizeStats *sz) const {
sz->_cp_all_bytes += (sz->_cp_bytes = sz->count(this));
sz->_cp_all_bytes += (sz->_cp_tags_bytes = sz->count_array(tags()));
sz->_cp_all_bytes += (sz->_cp_cache_bytes = sz->count(cache()));
sz->_cp_all_bytes += (sz->_cp_operands_bytes = sz->count_array(operands()));
sz->_cp_all_bytes += (sz->_cp_refmap_bytes = sz->count_array(reference_map()));
sz->_ro_bytes += sz->_cp_operands_bytes + sz->_cp_tags_bytes +
sz->_cp_refmap_bytes;
sz->_rw_bytes += sz->_cp_bytes + sz->_cp_cache_bytes;
}
#endif // INCLUDE_SERVICES
// Verification
void ConstantPool::verify_on(outputStream* st) {
guarantee(is_constantPool(), "object must be constant pool");
for (int i = 0; i< length(); i++) {
constantTag tag = tag_at(i);
CPSlot entry = slot_at(i);
if (tag.is_klass()) {
if (entry.is_resolved()) {
guarantee(entry.get_klass()->is_klass(), "should be klass");
}
} else if (tag.is_unresolved_klass()) {
if (entry.is_resolved()) {
guarantee(entry.get_klass()->is_klass(), "should be klass");
}
} else if (tag.is_symbol()) {
guarantee(entry.get_symbol()->refcount() != 0, "should have nonzero reference count");
} else if (tag.is_string()) {
guarantee(entry.get_symbol()->refcount() != 0, "should have nonzero reference count");
}
}
if (cache() != NULL) {
// Note: cache() can be NULL before a class is completely setup or
// in temporary constant pools used during constant pool merging
guarantee(cache()->is_constantPoolCache(), "should be constant pool cache");
}
if (pool_holder() != NULL) {
// Note: pool_holder() can be NULL in temporary constant pools
// used during constant pool merging
guarantee(pool_holder()->is_klass(), "should be klass");
}
}
void SymbolHashMap::add_entry(Symbol* sym, u2 value) {
char *str = sym->as_utf8();
unsigned int hash = compute_hash(str, sym->utf8_length());
unsigned int index = hash % table_size();
// check if already in map
// we prefer the first entry since it is more likely to be what was used in
// the class file
for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {
assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
if (en->hash() == hash && en->symbol() == sym) {
return; // already there
}
}
SymbolHashMapEntry* entry = new SymbolHashMapEntry(hash, sym, value);
entry->set_next(bucket(index));
_buckets[index].set_entry(entry);
assert(entry->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
}
SymbolHashMapEntry* SymbolHashMap::find_entry(Symbol* sym) {
assert(sym != NULL, "SymbolHashMap::find_entry - symbol is NULL");
char *str = sym->as_utf8();
int len = sym->utf8_length();
unsigned int hash = SymbolHashMap::compute_hash(str, len);
unsigned int index = hash % table_size();
for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {
assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
if (en->hash() == hash && en->symbol() == sym) {
return en;
}
}
return NULL;
}
| gpl-2.0 |
NooNameR/NMK | arch/arm/mach-msm/acpuclock-qsd8x502.c | 1 | 17364 | /*
* Copyright (c) 2009 Google, Inc.
* Copyright (c) 2008 QUALCOMM Incorporated.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/errno.h>
#include <linux/cpufreq.h>
#include <linux/regulator/consumer.h>
#include <linux/regulator/driver.h>
#include <mach/board.h>
#include <mach/msm_iomap.h>
#include "acpuclock.h"
#include "avs.h"
#include "proc_comm.h"
#if 0
#define DEBUG(x...) pr_info(x)
#else
#define DEBUG(x...) do {} while (0)
#endif
#define SHOT_SWITCH 4
#define HOP_SWITCH 5
#define SIMPLE_SLEW 6
#define COMPLEX_SLEW 7
#define SPSS_CLK_CNTL_ADDR (MSM_CSR_BASE + 0x100)
#define SPSS_CLK_SEL_ADDR (MSM_CSR_BASE + 0x104)
/* Scorpion PLL registers */
#define SCPLL_CTL_ADDR (MSM_SCPLL_BASE + 0x4)
#define SCPLL_STATUS_ADDR (MSM_SCPLL_BASE + 0x18)
#define SCPLL_FSM_CTL_EXT_ADDR (MSM_SCPLL_BASE + 0x10)
struct clkctl_acpu_speed {
unsigned acpu_khz;
unsigned clk_cfg;
unsigned clk_sel;
unsigned sc_l_value;
unsigned lpj;
int vdd;
unsigned axiclk_khz;
};
static unsigned long max_axi_rate;
struct regulator {
struct device *dev;
struct list_head list;
int uA_load;
int min_uV;
int max_uV;
char *supply_name;
struct device_attribute dev_attr;
struct regulator_dev *rdev;
};
/* clock sources */
#define CLK_TCXO 0 /* 19.2 MHz */
#define CLK_GLOBAL_PLL 1 /* 768 MHz */
#define CLK_MODEM_PLL 4 /* 245 MHz (UMTS) or 235.93 MHz (CDMA) */
#define CCTL(src, div) (((src) << 4) | (div - 1))
/* core sources */
#define SRC_RAW 0 /* clock from SPSS_CLK_CNTL */
#define SRC_SCPLL 1 /* output of scpll 128-1113 MHZ */
#define SRC_AXI 2 /* 128 MHz */
#define SRC_PLL1 3 /* 768 MHz */
struct clkctl_acpu_speed acpu_freq_tbl[] = {
{ 19200, CCTL(CLK_TCXO, 1), SRC_RAW, 0, 0, 975, 14000 },
{ 128000, CCTL(CLK_TCXO, 1), SRC_AXI, 0, 0, 975, 14000 },
{ 245000, CCTL(CLK_MODEM_PLL, 1), SRC_RAW, 0, 0, 1000, 29000 },
{ 384000, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x0A, 0, 1025, 58000 },
{ 422400, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x0B, 0, 1050, 117000 },
{ 460800, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x0C, 0, 1050, 117000 },
{ 499200, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x0D, 0, 1075, 117000 },
{ 537600, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x0E, 0, 1075, 117000 },
{ 576000, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x0F, 0, 1100, 117000 },
{ 614400, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x10, 0, 1100, 117000 },
{ 652800, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x11, 0, 1125, 117000 },
{ 691200, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x12, 0, 1150, 117000 },
{ 729600, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x13, 0, 1175, 117000 },
{ 768000, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x14, 0, 1200, 128000 },
{ 806400, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x15, 0, 1225, 128000 },
{ 844800, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x16, 0, 1250, 128000 },
{ 883200, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x17, 0, 1275, 128000 },
{ 921600, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x18, 0, 1275, 128000 },
{ 960000, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x19, 0, 1275, 128000 },
{ 998400, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x1A, 0, 1275, 128000 },
{ 1036800, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x1B, 0, 1275, 128000 },
{ 1075200, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x1C, 0, 1275, 128000 },
{ 1113600, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x1D, 0, 1275, 128000 },
{ 1152000, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x1E, 0, 1300, 128000 },
{ 1190400, CCTL(CLK_TCXO, 1), SRC_SCPLL, 0x1F, 0, 1325, 128000 },
{ 0 },
};
/* select the standby clock that is used when switching scpll
* frequencies
*
* Currently: MPLL
*/
struct clkctl_acpu_speed *acpu_stby = &acpu_freq_tbl[1];
#define IS_ACPU_STANDBY(x) (((x)->clk_cfg == acpu_stby->clk_cfg) && \
((x)->clk_sel == acpu_stby->clk_sel))
struct clkctl_acpu_speed *acpu_mpll = &acpu_freq_tbl[1];
#ifdef CONFIG_CPU_FREQ_TABLE
static struct cpufreq_frequency_table freq_table[ARRAY_SIZE(acpu_freq_tbl)];
static void __init acpuclk_init_cpufreq_table(void)
{
int i;
int vdd;
for (i = 0; acpu_freq_tbl[i].acpu_khz; i++) {
freq_table[i].index = i;
freq_table[i].frequency = CPUFREQ_ENTRY_INVALID;
/* Define speeds that we want to skip */
if (acpu_freq_tbl[i].acpu_khz == 19200 ||
acpu_freq_tbl[i].acpu_khz == 256000)
continue;
vdd = acpu_freq_tbl[i].vdd;
/* Allow mpll and the first scpll speeds */
if (acpu_freq_tbl[i].acpu_khz == acpu_mpll->acpu_khz ||
acpu_freq_tbl[i].acpu_khz == 384000) {
freq_table[i].frequency = acpu_freq_tbl[i].acpu_khz;
continue;
}
/* Add to the table */
freq_table[i].frequency = acpu_freq_tbl[i].acpu_khz;
}
freq_table[i].index = i;
freq_table[i].frequency = CPUFREQ_TABLE_END;
cpufreq_frequency_table_get_attr(freq_table, smp_processor_id());
}
#else
#define acpuclk_init_cpufreq_table() do {} while (0);
#endif
struct clock_state {
struct clkctl_acpu_speed *current_speed;
struct mutex lock;
uint32_t acpu_switch_time_us;
uint32_t max_speed_delta_khz;
uint32_t vdd_switch_time_us;
unsigned long power_collapse_khz;
unsigned long wait_for_irq_khz;
struct clk* clk_ebi1;
struct regulator *regulator;
int (*acpu_set_vdd) (int mvolts);
};
static struct clock_state drv_state = { 0 };
struct clk *clk_get(struct device *dev, const char *id);
unsigned long clk_get_rate(struct clk *clk);
int clk_set_rate(struct clk *clk, unsigned long rate);
static DEFINE_SPINLOCK(acpu_lock);
#define PLLMODE_POWERDOWN 0
#define PLLMODE_BYPASS 1
#define PLLMODE_STANDBY 2
#define PLLMODE_FULL_CAL 4
#define PLLMODE_HALF_CAL 5
#define PLLMODE_STEP_CAL 6
#define PLLMODE_NORMAL 7
#define PLLMODE_MASK 7
static void scpll_power_down(void)
{
uint32_t val;
/* Wait for any frequency switches to finish. */
while (readl(SCPLL_STATUS_ADDR) & 0x1)
;
/* put the pll in standby mode */
val = readl(SCPLL_CTL_ADDR);
val = (val & (~PLLMODE_MASK)) | PLLMODE_STANDBY;
writel(val, SCPLL_CTL_ADDR);
dmb();
/* wait to stabilize in standby mode */
udelay(10);
val = (val & (~PLLMODE_MASK)) | PLLMODE_POWERDOWN;
writel(val, SCPLL_CTL_ADDR);
dmb();
}
static void scpll_set_freq(uint32_t lval)
{
uint32_t val, ctl;
if (lval > 33)
lval = 33;
if (lval < 10)
lval = 10;
/* wait for any calibrations or frequency switches to finish */
while (readl(SCPLL_STATUS_ADDR) & 0x3)
;
ctl = readl(SCPLL_CTL_ADDR);
if ((ctl & PLLMODE_MASK) != PLLMODE_NORMAL) {
/* put the pll in standby mode */
writel((ctl & (~PLLMODE_MASK)) | PLLMODE_STANDBY, SCPLL_CTL_ADDR);
dmb();
/* wait to stabilize in standby mode */
udelay(10);
/* switch to 384 MHz */
val = readl(SCPLL_FSM_CTL_EXT_ADDR);
val = (val & (~0x1FF)) | (0x0A << 3) | SHOT_SWITCH;
writel(val, SCPLL_FSM_CTL_EXT_ADDR);
dmb();
ctl = readl(SCPLL_CTL_ADDR);
writel(ctl | PLLMODE_NORMAL, SCPLL_CTL_ADDR);
dmb();
/* wait for frequency switch to finish */
while (readl(SCPLL_STATUS_ADDR) & 0x1)
;
/* completion bit is not reliable for SHOT switch */
udelay(25);
}
/* write the new L val and switch mode */
val = readl(SCPLL_FSM_CTL_EXT_ADDR);
val = (val & (~0x1FF)) | (lval << 3) | HOP_SWITCH;
writel(val, SCPLL_FSM_CTL_EXT_ADDR);
dmb();
ctl = readl(SCPLL_CTL_ADDR);
writel(ctl | PLLMODE_NORMAL, SCPLL_CTL_ADDR);
dmb();
/* wait for frequency switch to finish */
while (readl(SCPLL_STATUS_ADDR) & 0x1)
;
}
/* this is still a bit weird... */
static void select_clock(unsigned src, unsigned config)
{
uint32_t val;
if (src == SRC_RAW) {
uint32_t sel = readl(SPSS_CLK_SEL_ADDR);
unsigned shift = (sel & 1) ? 8 : 0;
/* set other clock source to the new configuration */
val = readl(SPSS_CLK_CNTL_ADDR);
val = (val & (~(0x7F << shift))) | (config << shift);
writel(val, SPSS_CLK_CNTL_ADDR);
/* switch to other clock source */
writel(sel ^ 1, SPSS_CLK_SEL_ADDR);
dmb(); /* necessary? */
}
/* switch to new source */
val = readl(SPSS_CLK_SEL_ADDR) & (~6);
writel(val | ((src & 3) << 1), SPSS_CLK_SEL_ADDR);
}
static int acpu_set_vdd(int vdd)
{
int rc = 0;
if (!drv_state.regulator || IS_ERR(drv_state.regulator)) {
drv_state.regulator = regulator_get(NULL, "acpu_vcore");
if (IS_ERR(drv_state.regulator)) {
pr_info("acpu_set_vdd %d no regulator\n", vdd);
/* Assume that the PMIC supports scaling the processor
* to its maximum frequency at its default voltage.
*/
return -ENODEV;
}
pr_info("acpu_set_vdd got regulator\n");
}
rc = tps65023_set_dcdc1_level(drv_state.regulator->rdev, vdd);
if (rc == -ENODEV && vdd <= CONFIG_QSD_PMIC_DEFAULT_DCDC1)
return 0;
return rc;
}
static int acpuclk_set_vdd_level(int vdd)
{
if (drv_state.acpu_set_vdd)
return drv_state.acpu_set_vdd(vdd);
else {
/* Assume that the PMIC supports scaling the processor
* to its maximum frequency at its default voltage.
*/
return 0;
}
}
int acpuclk_set_rate(unsigned long rate, enum setrate_reason reason)
{
struct clkctl_acpu_speed *cur, *next;
unsigned long flags;
int rc = 0;
int freq_index = 0;
cur = drv_state.current_speed;
/* convert to KHz */
rate /= 1000;
DEBUG("acpuclk_set_rate(%d,%d)\n", (int) rate, reason);
if (rate == 0 || rate == cur->acpu_khz)
return 0;
next = acpu_freq_tbl;
for (;;) {
if (next->acpu_khz == rate)
break;
if (next->acpu_khz == 0)
return -EINVAL;
next++;
freq_index++;
}
if (reason == SETRATE_CPUFREQ) {
mutex_lock(&drv_state.lock);
#ifdef CONFIG_MSM_CPU_AVS
/* Notify avs before changing frequency */
rc = avs_adjust_freq(freq_index, 1);
if (rc) {
printk(KERN_ERR
"acpuclock: Unable to increase ACPU "
"vdd: %d.\n", (int) rate);
mutex_unlock(&drv_state.lock);
return rc;
}
#endif
/* Increase VDD if needed. */
if (next->vdd > cur->vdd) {
rc = acpuclk_set_vdd_level(next->vdd);
if (rc) {
pr_err("acpuclock: Unable to increase ACPU VDD from %d to %d setting rate to %d.\n", cur->vdd, next->vdd, (int) rate);
mutex_unlock(&drv_state.lock);
return rc;
}
}
}
spin_lock_irqsave(&acpu_lock, flags);
DEBUG("sel=%d cfg=%02x lv=%02x -> sel=%d, cfg=%02x lv=%02x\n",
cur->clk_sel, cur->clk_cfg, cur->sc_l_value,
next->clk_sel, next->clk_cfg, next->sc_l_value);
if (next->clk_sel == SRC_SCPLL) {
if (!IS_ACPU_STANDBY(cur))
select_clock(acpu_stby->clk_sel, acpu_stby->clk_cfg);
loops_per_jiffy = next->lpj;
scpll_set_freq(next->sc_l_value);
select_clock(SRC_SCPLL, 0);
} else {
loops_per_jiffy = next->lpj;
if (cur->clk_sel == SRC_SCPLL) {
select_clock(acpu_stby->clk_sel, acpu_stby->clk_cfg);
select_clock(next->clk_sel, next->clk_cfg);
scpll_power_down();
} else {
select_clock(next->clk_sel, next->clk_cfg);
}
}
drv_state.current_speed = next;
spin_unlock_irqrestore(&acpu_lock, flags);
#ifndef CONFIG_AXI_SCREEN_POLICY
if (reason == SETRATE_CPUFREQ || reason == SETRATE_PC) {
if (cur->axiclk_khz != next->axiclk_khz)
clk_set_rate(drv_state.clk_ebi1, next->axiclk_khz * 1000);
DEBUG("acpuclk_set_rate switch axi to %d\n",
clk_get_rate(drv_state.clk_ebi1));
}
#endif
if (reason == SETRATE_CPUFREQ) {
#ifdef CONFIG_MSM_CPU_AVS
/* notify avs after changing frequency */
rc = avs_adjust_freq(freq_index, 0);
if (rc)
printk(KERN_ERR
"acpuclock: Unable to drop ACPU vdd: %d.\n", (int) rate);
#endif
/* Drop VDD level if we can. */
if (next->vdd < cur->vdd) {
rc = acpuclk_set_vdd_level(next->vdd);
if (rc)
pr_err("acpuclock: Unable to drop ACPU VDD from%d to %d setting rate to %d.\n", cur->vdd, next->vdd, (int) rate);
}
mutex_unlock(&drv_state.lock);
}
return 0;
}
static unsigned __init acpuclk_find_speed(void)
{
uint32_t sel, val;
sel = readl(SPSS_CLK_SEL_ADDR);
switch ((sel & 6) >> 1) {
case 1:
val = readl(SCPLL_FSM_CTL_EXT_ADDR);
val = (val >> 3) & 0x3f;
return val * 38400;
case 2:
return 128000;
default:
pr_err("acpu_find_speed: failed\n");
BUG();
return 0;
}
}
#define PCOM_MODEM_PLL 0
static int pll_request(unsigned id, unsigned on)
{
on = !!on;
return msm_proc_comm(PCOM_CLKCTL_RPC_PLL_REQUEST, &id, &on);
}
static void __init acpuclk_init(void)
{
struct clkctl_acpu_speed *speed, *max_s;
unsigned init_khz;
init_khz = acpuclk_find_speed();
/* request the modem pll, and then drop it. We don't want to keep a
* ref to it, but we do want to make sure that it is initialized at
* this point. The ARM9 will ensure that the MPLL is always on
* once it is fully booted, but it may not be up by the time we get
* to here. So, our pll_request for it will block until the mpll is
* actually up. We want it up because we will want to use it as a
* temporary step during frequency scaling. */
pll_request(PCOM_MODEM_PLL, 1);
pll_request(PCOM_MODEM_PLL, 0);
if (!(readl(MSM_CLK_CTL_BASE + 0x300) & 1)) {
pr_err("%s: MPLL IS NOT ON!!! RUN AWAY!!\n", __func__);
BUG();
}
/* Move to 768MHz for boot, which is a safe frequency
* for all versions of Scorpion at the moment.
*/
speed = acpu_freq_tbl;
for (;;) {
if (speed->acpu_khz == 806400)
break;
if (speed->acpu_khz == 0) {
pr_err("acpuclk_init: cannot find 806MHz\n");
BUG();
}
speed++;
}
if (init_khz != speed->acpu_khz) {
/* Bootloader needs to have SCPLL operating, but we're
* going to step over to the standby clock and make sure
* we select the right frequency on SCPLL and then
* step back to it, to make sure we're sane here.
*/
select_clock(acpu_stby->clk_sel, acpu_stby->clk_cfg);
scpll_power_down();
scpll_set_freq(speed->sc_l_value);
select_clock(SRC_SCPLL, 0);
}
drv_state.current_speed = speed;
for (speed = acpu_freq_tbl; speed->acpu_khz; speed++)
speed->lpj = cpufreq_scale(loops_per_jiffy,
init_khz, speed->acpu_khz);
loops_per_jiffy = drv_state.current_speed->lpj;
for (speed = acpu_freq_tbl; speed->acpu_khz != 0; speed++)
;
max_s = speed - 1;
max_axi_rate = max_s->axiclk_khz * 1000;
}
unsigned long acpuclk_get_max_axi_rate(void)
{
return max_axi_rate;
}
EXPORT_SYMBOL(acpuclk_get_max_axi_rate);
unsigned long acpuclk_get_rate(void)
{
return drv_state.current_speed->acpu_khz;
}
uint32_t acpuclk_get_switch_time(void)
{
return drv_state.acpu_switch_time_us;
}
unsigned long acpuclk_power_collapse(int from_idle)
{
int ret = acpuclk_get_rate();
enum setrate_reason reason = (from_idle) ? SETRATE_PC_IDLE : SETRATE_PC;
if (ret > drv_state.power_collapse_khz)
acpuclk_set_rate(drv_state.power_collapse_khz * 1000, reason);
return ret * 1000;
}
unsigned long acpuclk_get_wfi_rate(void)
{
return drv_state.wait_for_irq_khz * 1000;
}
unsigned long acpuclk_wait_for_irq(void)
{
int ret = acpuclk_get_rate();
if (ret > drv_state.wait_for_irq_khz)
acpuclk_set_rate(drv_state.wait_for_irq_khz * 1000, 1);
return ret * 1000;
}
#ifdef CONFIG_MSM_CPU_AVS
static int __init acpu_avs_init(int (*set_vdd) (int), int khz)
{
int i;
int freq_count = 0;
int freq_index = -1;
for (i = 0; acpu_freq_tbl[i].acpu_khz; i++) {
freq_count++;
if (acpu_freq_tbl[i].acpu_khz == khz)
freq_index = i;
}
return avs_init(set_vdd, freq_count, freq_index);
}
#endif
void __init msm_acpu_clock_init(struct msm_acpu_clock_platform_data *clkdata)
{
spin_lock_init(&acpu_lock);
mutex_init(&drv_state.lock);
drv_state.acpu_switch_time_us = clkdata->acpu_switch_time_us;
drv_state.max_speed_delta_khz = clkdata->max_speed_delta_khz;
drv_state.vdd_switch_time_us = clkdata->vdd_switch_time_us;
drv_state.power_collapse_khz = clkdata->power_collapse_khz;
drv_state.wait_for_irq_khz = clkdata->wait_for_irq_khz;
drv_state.acpu_set_vdd = acpu_set_vdd;
if (clkdata->mpll_khz)
acpu_mpll->acpu_khz = clkdata->mpll_khz;
acpuclk_init();
acpuclk_init_cpufreq_table();
drv_state.clk_ebi1 = clk_get(NULL,"ebi1_clk");
#ifndef CONFIG_AXI_SCREEN_POLICY
clk_set_rate(drv_state.clk_ebi1, drv_state.current_speed->axiclk_khz * 1000);
#endif
#ifdef CONFIG_MSM_CPU_AVS
if (!acpu_avs_init(drv_state.acpu_set_vdd,
drv_state.current_speed->acpu_khz)) {
/* avs init successful. avs will handle voltage changes */
drv_state.acpu_set_vdd = NULL;
}
#endif
}
#ifndef CONFIG_MSM_CPU_AVS
ssize_t acpuclk_get_vdd_levels_str(char *buf)
{
int i, len = 0;
if (buf) {
mutex_lock(&drv_state.lock);
for (i = 0; acpu_freq_tbl[i].acpu_khz; i++) {
if (freq_table[i].frequency != CPUFREQ_ENTRY_INVALID)
len += sprintf(buf + len, "%8u: %4d\n", acpu_freq_tbl[i].acpu_khz, acpu_freq_tbl[i].vdd);
}
mutex_unlock(&drv_state.lock);
}
return len;
}
void acpuclk_set_vdd(unsigned acpu_khz, int vdd)
{
int i;
vdd = vdd / 25 * 25;
mutex_lock(&drv_state.lock);
for (i = 0; acpu_freq_tbl[i].acpu_khz; i++) {
if (freq_table[i].frequency != CPUFREQ_ENTRY_INVALID) {
if (acpu_khz == 0)
acpu_freq_tbl[i].vdd = min(max((acpu_freq_tbl[i].vdd + vdd), VOLTAGE_MIN), VOLTAGE_MAX);
else if (acpu_freq_tbl[i].acpu_khz == acpu_khz)
acpu_freq_tbl[i].vdd = min(max(vdd, VOLTAGE_MIN), VOLTAGE_MAX);
}
}
mutex_unlock(&drv_state.lock);
}
#endif
| gpl-2.0 |
ojwb/survex | src/matrix.c | 1 | 12805 | /* matrix.c
* Matrix building and solving routines
* Copyright (C) 1993-2003,2010,2013 Olly Betts
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*#define SOR 1*/
#if 0
# define DEBUG_INVALID 1
#endif
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "debug.h"
#include "cavern.h"
#include "filename.h"
#include "message.h"
#include "netbits.h"
#include "matrix.h"
#include "out.h"
#undef PRINT_MATRICES
#define PRINT_MATRICES 0
#undef DEBUG_MATRIX_BUILD
#define DEBUG_MATRIX_BUILD 0
#undef DEBUG_MATRIX
#define DEBUG_MATRIX 0
#if PRINT_MATRICES
static void print_matrix(real *M, real *B, long n);
#endif
static void choleski(real *M, real *B, long n);
#ifdef SOR
static void sor(real *M, real *B, long n);
#endif
/* for M(row, col) col must be <= row, so Y <= X */
# define M(X, Y) ((real *)M)[((((OSSIZE_T)(X)) * ((X) + 1)) >> 1) + (Y)]
/* +(Y>X?0*printf("row<col (line %d)\n",__LINE__):0) */
/*#define M_(X, Y) ((real *)M)[((((OSSIZE_T)(Y)) * ((Y) + 1)) >> 1) + (X)]*/
static int find_stn_in_tab(node *stn);
static int add_stn_to_tab(node *stn);
static void build_matrix(node *list);
static long n_stn_tab;
static pos **stn_tab;
extern void
solve_matrix(node *list)
{
node *stn;
long n = 0;
FOR_EACH_STN(stn, list) {
if (!fixed(stn)) n++;
}
if (n == 0) return;
/* we just need n to be a reasonable estimate >= the number
* of stations left after reduction. If memory is
* plentiful, we can be crass.
*/
stn_tab = osmalloc((OSSIZE_T)(n * ossizeof(pos*)));
n_stn_tab = 0;
FOR_EACH_STN(stn, list) {
if (!fixed(stn)) add_stn_to_tab(stn);
}
if (n_stn_tab < n) {
/* release unused entries in stn_tab */
stn_tab = osrealloc(stn_tab, n_stn_tab * ossizeof(pos*));
}
build_matrix(list);
#if DEBUG_MATRIX
FOR_EACH_STN(stn, list) {
printf("(%8.2f, %8.2f, %8.2f ) ", POS(stn, 0), POS(stn, 1), POS(stn, 2));
print_prefix(stn->name);
putnl();
}
#endif
osfree(stn_tab);
}
#ifdef NO_COVARIANCES
# define FACTOR 1
#else
# define FACTOR 3
#endif
static void
build_matrix(node *list)
{
real *M;
real *B;
int dim;
if (n_stn_tab == 0) {
if (!fQuiet)
puts(msg(/*Network solved by reduction - no simultaneous equations to solve.*/74));
return;
}
/* (OSSIZE_T) cast may be needed if n_stn_tab>=181 */
M = osmalloc((OSSIZE_T)((((OSSIZE_T)n_stn_tab * FACTOR * (n_stn_tab * FACTOR + 1)) >> 1)) * ossizeof(real));
B = osmalloc((OSSIZE_T)(n_stn_tab * FACTOR * ossizeof(real)));
if (!fQuiet) {
if (n_stn_tab == 1)
out_current_action(msg(/*Solving one equation*/78));
else
out_current_action1(msg(/*Solving %d simultaneous equations*/75), n_stn_tab);
}
#ifdef NO_COVARIANCES
dim = 2;
#else
dim = 0; /* fudge next loop for now */
#endif
for ( ; dim >= 0; dim--) {
node *stn;
int row;
/* Initialise M and B to zero - zeroing "linearly" will minimise
* paging when the matrix is large */
{
int end = n_stn_tab * FACTOR;
for (row = 0; row < end; row++) B[row] = (real)0.0;
end = ((OSSIZE_T)n_stn_tab * FACTOR * (n_stn_tab * FACTOR + 1)) >> 1;
for (row = 0; row < end; row++) M[row] = (real)0.0;
}
/* Construct matrix - Go thru' stn list & add all forward legs between
* two unfixed stations to M (so each leg goes on exactly once).
*
* All legs between two fixed stations can be ignored here.
*
* All legs between a fixed and an unfixed station are then considered
* from the unfixed end (if we consider them from the fixed end we'd
* need to somehow detect when we're at a fixed point cut line and work
* out which side we're dealing with at this time. */
FOR_EACH_STN(stn, list) {
#ifdef NO_COVARIANCES
real e;
#else
svar e;
delta a;
#endif
int f, t;
int dirn;
#if DEBUG_MATRIX_BUILD
print_prefix(stn->name);
printf(" used: %d colour %ld\n",
(!!stn->leg[2]) << 2 | (!!stn -> leg[1]) << 1 | (!!stn->leg[0]),
stn->colour);
for (dirn = 0; dirn <= 2 && stn->leg[dirn]; dirn++) {
#ifdef NO_COVARIANCES
printf("Leg %d, vx=%f, reverse=%d, to ", dirn,
stn->leg[dirn]->v[0], stn->leg[dirn]->l.reverse);
#else
printf("Leg %d, vx=%f, reverse=%d, to ", dirn,
stn->leg[dirn]->v[0][0], stn->leg[dirn]->l.reverse);
#endif
print_prefix(stn->leg[dirn]->l.to->name);
putnl();
}
putnl();
#endif /* DEBUG_MATRIX_BUILD */
if (!fixed(stn)) {
f = find_stn_in_tab(stn);
for (dirn = 0; dirn <= 2 && stn->leg[dirn]; dirn++) {
linkfor *leg = stn->leg[dirn];
node *to = leg->l.to;
if (fixed(to)) {
bool fRev = !data_here(leg);
if (fRev) leg = reverse_leg(leg);
/* Ignore equated nodes */
#ifdef NO_COVARIANCES
e = leg->v[dim];
if (e != (real)0.0) {
e = ((real)1.0) / e;
M(f,f) += e;
B[f] += e * POS(to, dim);
if (fRev) {
B[f] += leg->d[dim];
} else {
B[f] -= leg->d[dim];
}
}
#else
if (invert_svar(&e, &leg->v)) {
delta b;
int i;
if (fRev) {
adddd(&a, &POSD(to), &leg->d);
} else {
subdd(&a, &POSD(to), &leg->d);
}
mulsd(&b, &e, &a);
for (i = 0; i < 3; i++) {
M(f * FACTOR + i, f * FACTOR + i) += e[i];
B[f * FACTOR + i] += b[i];
}
M(f * FACTOR + 1, f * FACTOR) += e[3];
M(f * FACTOR + 2, f * FACTOR) += e[4];
M(f * FACTOR + 2, f * FACTOR + 1) += e[5];
}
#endif
} else if (data_here(leg)) {
/* forward leg, unfixed -> unfixed */
t = find_stn_in_tab(to);
#if DEBUG_MATRIX
printf("Leg %d to %d, var %f, delta %f\n", f, t, e,
leg->d[dim]);
#endif
/* Ignore equated nodes & lollipops */
#ifdef NO_COVARIANCES
e = leg->v[dim];
if (t != f && e != (real)0.0) {
real a;
e = ((real)1.0) / e;
M(f,f) += e;
M(t,t) += e;
if (f < t) M(t,f) -= e; else M(f,t) -= e;
a = e * leg->d[dim];
B[f] -= a;
B[t] += a;
}
#else
if (t != f && invert_svar(&e, &leg->v)) {
int i;
mulsd(&a, &e, &leg->d);
for (i = 0; i < 3; i++) {
M(f * FACTOR + i, f * FACTOR + i) += e[i];
M(t * FACTOR + i, t * FACTOR + i) += e[i];
if (f < t)
M(t * FACTOR + i, f * FACTOR + i) -= e[i];
else
M(f * FACTOR + i, t * FACTOR + i) -= e[i];
B[f * FACTOR + i] -= a[i];
B[t * FACTOR + i] += a[i];
}
M(f * FACTOR + 1, f * FACTOR) += e[3];
M(t * FACTOR + 1, t * FACTOR) += e[3];
M(f * FACTOR + 2, f * FACTOR) += e[4];
M(t * FACTOR + 2, t * FACTOR) += e[4];
M(f * FACTOR + 2, f * FACTOR + 1) += e[5];
M(t * FACTOR + 2, t * FACTOR + 1) += e[5];
if (f < t) {
M(t * FACTOR + 1, f * FACTOR) -= e[3];
M(t * FACTOR, f * FACTOR + 1) -= e[3];
M(t * FACTOR + 2, f * FACTOR) -= e[4];
M(t * FACTOR, f * FACTOR + 2) -= e[4];
M(t * FACTOR + 2, f * FACTOR + 1) -= e[5];
M(t * FACTOR + 1, f * FACTOR + 2) -= e[5];
} else {
M(f * FACTOR + 1, t * FACTOR) -= e[3];
M(f * FACTOR, t * FACTOR + 1) -= e[3];
M(f * FACTOR + 2, t * FACTOR) -= e[4];
M(f * FACTOR, t * FACTOR + 2) -= e[4];
M(f * FACTOR + 2, t * FACTOR + 1) -= e[5];
M(f * FACTOR + 1, t * FACTOR + 2) -= e[5];
}
}
#endif
}
}
}
}
#if PRINT_MATRICES
print_matrix(M, B, n_stn_tab * FACTOR); /* 'ave a look! */
#endif
#ifdef SOR
/* defined in network.c, may be altered by -z<letters> on command line */
if (optimize & BITA('i'))
sor(M, B, n_stn_tab * FACTOR);
else
#endif
choleski(M, B, n_stn_tab * FACTOR);
{
int m;
for (m = (int)(n_stn_tab - 1); m >= 0; m--) {
#ifdef NO_COVARIANCES
stn_tab[m]->p[dim] = B[m];
if (dim == 0) {
SVX_ASSERT2(pos_fixed(stn_tab[m]),
"setting station coordinates didn't mark pos as fixed");
}
#else
int i;
for (i = 0; i < 3; i++) {
stn_tab[m]->p[i] = B[m * FACTOR + i];
}
SVX_ASSERT2(pos_fixed(stn_tab[m]),
"setting station coordinates didn't mark pos as fixed");
#endif
}
#if EXPLICIT_FIXED_FLAG
for (m = n_stn_tab - 1; m >= 0; m--) fixpos(stn_tab[m]);
#endif
}
}
osfree(B);
osfree(M);
}
static int
find_stn_in_tab(node *stn)
{
int i = 0;
pos *p = stn->name->pos;
while (stn_tab[i] != p)
if (++i == n_stn_tab) {
#if DEBUG_INVALID
fputs("Station ", stderr);
fprint_prefix(stderr, stn->name);
fputs(" not in table\n\n", stderr);
#endif
#if 0
print_prefix(stn->name);
printf(" used: %d colour %d\n",
(!!stn->leg[2])<<2 | (!!stn->leg[1])<<1 | (!!stn->leg[0]),
stn->colour);
#endif
fatalerror(/*Bug in program detected! Please report this to the authors*/11);
}
return i;
}
static int
add_stn_to_tab(node *stn)
{
int i;
pos *p = stn->name->pos;
for (i = 0; i < n_stn_tab; i++) {
if (stn_tab[i] == p) return i;
}
stn_tab[n_stn_tab++] = p;
return i;
}
/* Solve MX=B for X by Choleski factorisation - modified Choleski actually
* since we factor into LDL' while Choleski is just LL'
*/
/* Note M must be symmetric positive definite */
/* routine is entitled to scribble on M and B if it wishes */
static void
choleski(real *M, real *B, long n)
{
int i, j, k;
for (j = 1; j < n; j++) {
real V;
for (i = 0; i < j; i++) {
V = (real)0.0;
for (k = 0; k < i; k++) V += M(i,k) * M(j,k) * M(k,k);
M(j,i) = (M(j,i) - V) / M(i,i);
}
V = (real)0.0;
for (k = 0; k < j; k++) V += M(j,k) * M(j,k) * M(k,k);
M(j,j) -= V; /* may be best to add M() last for numerical reasons too */
}
/* Multiply x by L inverse */
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
B[j] -= M(j,i) * B[i];
}
}
/* Multiply x by D inverse */
for (i = 0; i < n; i++) {
B[i] /= M(i,i);
}
/* Multiply x by (L transpose) inverse */
for (i = (int)(n - 1); i > 0; i--) {
for (j = i - 1; j >= 0; j--) {
B[j] -= M(i,j) * B[i];
}
}
/* printf("\n%ld/%ld\n\n",flops,flopsTot); */
}
#ifdef SOR
/* factor to use for SOR (must have 1 <= SOR_factor < 2) */
#define SOR_factor 1.93 /* 1.95 */
/* Solve MX=B for X by SOR of Gauss-Siedel */
/* routine is entitled to scribble on M and B if it wishes */
static void
sor(real *M, real *B, long n)
{
real t, x, delta, threshold, t2;
int row, col;
real *X;
long it = 0;
X = osmalloc(n * ossizeof(real));
threshold = 0.00001;
printf("reciprocating diagonal\n"); /* TRANSLATE */
/* munge diagonal so we can multiply rather than divide */
for (row = n - 1; row >= 0; row--) {
M(row,row) = 1 / M(row,row);
X[row] = 0;
}
printf("starting iteration\n"); /* TRANSLATE */
do {
/*printf("*");*/
it++;
t = 0.0;
for (row = 0; row < n; row++) {
x = B[row];
for (col = 0; col < row; col++) x -= M(row,col) * X[col];
for (col++; col < n; col++) x -= M(col,row) * X[col];
x *= M(row,row);
delta = (x - X[row]) * SOR_factor;
X[row] += delta;
t2 = fabs(delta);
if (t2 > t) t = t2;
}
printf("% 6d: %8.6f\n", it, t);
} while (t >= threshold && it < 100000);
if (t >= threshold) {
fprintf(stderr, "*not* converged after %ld iterations\n", it);
BUG("iteration stinks");
}
printf("%ld iterations\n", it); /* TRANSLATE */
#if 0
putnl();
for (row = n - 1; row >= 0; row--) {
t = 0.0;
for (col = 0; col < row; col++) t += M(row, col) * X[col];
t += X[row] / M(row, row);
for (col = row + 1; col < n; col++)
t += M(col, row) * X[col];
printf("[ %f %f ]\n", t, B[row]);
}
#endif
for (row = n - 1; row >= 0; row--) B[row] = X[row];
osfree(X);
printf("\ndone\n"); /* TRANSLATE */
}
#endif
#if PRINT_MATRICES
static void
print_matrix(real *M, real *B, long n)
{
long row, col;
printf("Matrix, M and vector, B:\n");
for (row = 0; row < n; row++) {
for (col = 0; col <= row; col++) printf("%6.2f\t", M(row, col));
for (; col <= n; col++) printf(" \t");
printf("\t%6.2f\n", B[row]);
}
putnl();
return;
}
#endif
| gpl-2.0 |
rex-xxx/mt6572_x201 | system/core/libcorkscrew/map_info.c | 1 | 5657 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* 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.
*/
#define LOG_TAG "Corkscrew"
//#define LOG_NDEBUG 0
#include <corkscrew/map_info.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <pthread.h>
#include <unistd.h>
#include <cutils/log.h>
#include <sys/time.h>
// 6f000000-6f01e000 rwxp 00000000 00:0c 16389419 /system/lib/libcomposer.so\n
// 012345678901234567890123456789012345678901234567890123456789
// 0 1 2 3 4 5
static map_info_t* parse_maps_line(const char* line)
{
unsigned long int start;
unsigned long int end;
char permissions[5];
int name_pos;
if (sscanf(line, "%lx-%lx %4s %*x %*x:%*x %*d%n", &start, &end,
permissions, &name_pos) != 3) {
return NULL;
}
while (isspace(line[name_pos])) {
name_pos += 1;
}
const char* name = line + name_pos;
size_t name_len = strlen(name);
if (name_len && name[name_len - 1] == '\n') {
name_len -= 1;
}
map_info_t* mi = calloc(1, sizeof(map_info_t) + name_len + 1);
if (mi) {
mi->start = start;
mi->end = end;
mi->is_readable = strlen(permissions) == 4 && permissions[0] == 'r';
mi->is_executable = strlen(permissions) == 4 && permissions[2] == 'x';
mi->data = NULL;
memcpy(mi->name, name, name_len);
mi->name[name_len] = '\0';
ALOGV("Parsed map: start=0x%08x, end=0x%08x, "
"is_readable=%d, is_executable=%d, name=%s",
mi->start, mi->end, mi->is_readable, mi->is_executable, mi->name);
}
return mi;
}
map_info_t* load_map_info_list(pid_t tid) {
char path[PATH_MAX];
char line[1024];
FILE* fp;
map_info_t* milist = NULL;
snprintf(path, PATH_MAX, "/proc/%d/maps", tid);
fp = fopen(path, "r");
if (fp) {
while(fgets(line, sizeof(line), fp)) {
map_info_t* mi = parse_maps_line(line);
if (mi) {
mi->next = milist;
milist = mi;
}
}
fclose(fp);
}
return milist;
}
void free_map_info_list(map_info_t* milist) {
while (milist) {
map_info_t* next = milist->next;
free(milist);
milist = next;
}
}
const map_info_t* find_map_info(const map_info_t* milist, uintptr_t addr) {
const map_info_t* mi = milist;
while (mi && !(addr >= mi->start && addr < mi->end)) {
mi = mi->next;
}
return mi;
}
bool is_readable_map(const map_info_t* milist, uintptr_t addr) {
const map_info_t* mi = find_map_info(milist, addr);
return mi && mi->is_readable;
}
bool is_executable_map(const map_info_t* milist, uintptr_t addr) {
const map_info_t* mi = find_map_info(milist, addr);
return mi && mi->is_executable;
}
static pthread_mutex_t g_my_map_info_list_mutex = PTHREAD_MUTEX_INITIALIZER;
static map_info_t* g_my_map_info_list = NULL;
static const int64_t MAX_CACHE_AGE = 5 * 1000 * 1000000LL;
typedef struct {
uint32_t refs;
int64_t timestamp;
} my_map_info_data_t;
static int64_t now() {
struct timespec t;
t.tv_sec = t.tv_nsec = 0;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec * 1000000000LL + t.tv_nsec;
}
static void dec_ref(map_info_t* milist, my_map_info_data_t* data) {
if (!--data->refs) {
ALOGV("Freed my_map_info_list %p.", milist);
free(data);
free_map_info_list(milist);
}
}
map_info_t* acquire_my_map_info_list() {
pthread_mutex_lock(&g_my_map_info_list_mutex);
int64_t time = now();
if (g_my_map_info_list) {
my_map_info_data_t* data = (my_map_info_data_t*)g_my_map_info_list->data;
int64_t age = time - data->timestamp;
if (age >= MAX_CACHE_AGE) {
ALOGV("Invalidated my_map_info_list %p, age=%lld.", g_my_map_info_list, age);
dec_ref(g_my_map_info_list, data);
g_my_map_info_list = NULL;
} else {
ALOGV("Reusing my_map_info_list %p, age=%lld.", g_my_map_info_list, age);
}
}
if (!g_my_map_info_list) {
my_map_info_data_t* data = (my_map_info_data_t*)malloc(sizeof(my_map_info_data_t));
g_my_map_info_list = load_map_info_list(getpid());
if (g_my_map_info_list) {
ALOGV("Loaded my_map_info_list %p.", g_my_map_info_list);
g_my_map_info_list->data = data;
data->refs = 1;
data->timestamp = time;
} else {
free(data);
}
}
map_info_t* milist = g_my_map_info_list;
if (milist) {
my_map_info_data_t* data = (my_map_info_data_t*)g_my_map_info_list->data;
data->refs += 1;
}
pthread_mutex_unlock(&g_my_map_info_list_mutex);
return milist;
}
void release_my_map_info_list(map_info_t* milist) {
if (milist) {
pthread_mutex_lock(&g_my_map_info_list_mutex);
my_map_info_data_t* data = (my_map_info_data_t*)milist->data;
dec_ref(milist, data);
pthread_mutex_unlock(&g_my_map_info_list_mutex);
}
}
| gpl-2.0 |
Akagi201/learning-lua | lua-all/lua-4.0/lvm.c | 1 | 19482 | /*
** $Id: lvm.c,v 1.146 2000/10/26 12:47:05 roberto Exp $
** Lua virtual machine
** See Copyright Notice in lua.h
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lapi.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#include "lvm.h"
#ifdef OLD_ANSI
#define strcoll(a,b) strcmp(a,b)
#endif
/*
** Extra stack size to run a function:
** TAG_LINE(1), NAME(1), TM calls(3) (plus some extra...)
*/
#define EXTRA_STACK 8
int luaV_tonumber (TObject *obj) {
if (ttype(obj) != LUA_TSTRING)
return 1;
else {
if (!luaO_str2d(svalue(obj), &nvalue(obj)))
return 2;
ttype(obj) = LUA_TNUMBER;
return 0;
}
}
int luaV_tostring (lua_State *L, TObject *obj) { /* LUA_NUMBER */
if (ttype(obj) != LUA_TNUMBER)
return 1;
else {
char s[32]; /* 16 digits, sign, point and \0 (+ some extra...) */
lua_number2str(s, nvalue(obj)); /* convert `s' to number */
tsvalue(obj) = luaS_new(L, s);
ttype(obj) = LUA_TSTRING;
return 0;
}
}
static void traceexec (lua_State *L, StkId base, StkId top, lua_Hook linehook) {
CallInfo *ci = infovalue(base-1);
int *lineinfo = ci->func->f.l->lineinfo;
int pc = (*ci->pc - ci->func->f.l->code) - 1;
int newline;
if (pc == 0) { /* may be first time? */
ci->line = 1;
ci->refi = 0;
ci->lastpc = pc+1; /* make sure it will call linehook */
}
newline = luaG_getline(lineinfo, pc, ci->line, &ci->refi);
/* calls linehook when enters a new line or jumps back (loop) */
if (newline != ci->line || pc <= ci->lastpc) {
ci->line = newline;
L->top = top;
luaD_lineHook(L, base-2, newline, linehook);
}
ci->lastpc = pc;
}
static Closure *luaV_closure (lua_State *L, int nelems) {
Closure *c = luaF_newclosure(L, nelems);
L->top -= nelems;
while (nelems--)
c->upvalue[nelems] = *(L->top+nelems);
clvalue(L->top) = c;
ttype(L->top) = LUA_TFUNCTION;
incr_top;
return c;
}
void luaV_Cclosure (lua_State *L, lua_CFunction c, int nelems) {
Closure *cl = luaV_closure(L, nelems);
cl->f.c = c;
cl->isC = 1;
}
void luaV_Lclosure (lua_State *L, Proto *l, int nelems) {
Closure *cl = luaV_closure(L, nelems);
cl->f.l = l;
cl->isC = 0;
}
/*
** Function to index a table.
** Receives the table at `t' and the key at top.
*/
const TObject *luaV_gettable (lua_State *L, StkId t) {
Closure *tm;
int tg;
if (ttype(t) == LUA_TTABLE && /* `t' is a table? */
((tg = hvalue(t)->htag) == LUA_TTABLE || /* with default tag? */
luaT_gettm(L, tg, TM_GETTABLE) == NULL)) { /* or no TM? */
/* do a primitive get */
const TObject *h = luaH_get(L, hvalue(t), L->top-1);
/* result is no nil or there is no `index' tag method? */
if (ttype(h) != LUA_TNIL || ((tm=luaT_gettm(L, tg, TM_INDEX)) == NULL))
return h; /* return result */
/* else call `index' tag method */
}
else { /* try a `gettable' tag method */
tm = luaT_gettmbyObj(L, t, TM_GETTABLE);
}
if (tm != NULL) { /* is there a tag method? */
luaD_checkstack(L, 2);
*(L->top+1) = *(L->top-1); /* key */
*L->top = *t; /* table */
clvalue(L->top-1) = tm; /* tag method */
ttype(L->top-1) = LUA_TFUNCTION;
L->top += 2;
luaD_call(L, L->top - 3, 1);
return L->top - 1; /* call result */
}
else { /* no tag method */
luaG_typeerror(L, t, "index");
return NULL; /* to avoid warnings */
}
}
/*
** Receives table at `t', key at `key' and value at top.
*/
void luaV_settable (lua_State *L, StkId t, StkId key) {
int tg;
if (ttype(t) == LUA_TTABLE && /* `t' is a table? */
((tg = hvalue(t)->htag) == LUA_TTABLE || /* with default tag? */
luaT_gettm(L, tg, TM_SETTABLE) == NULL)) /* or no TM? */
*luaH_set(L, hvalue(t), key) = *(L->top-1); /* do a primitive set */
else { /* try a `settable' tag method */
Closure *tm = luaT_gettmbyObj(L, t, TM_SETTABLE);
if (tm != NULL) {
luaD_checkstack(L, 3);
*(L->top+2) = *(L->top-1);
*(L->top+1) = *key;
*(L->top) = *t;
clvalue(L->top-1) = tm;
ttype(L->top-1) = LUA_TFUNCTION;
L->top += 3;
luaD_call(L, L->top - 4, 0); /* call `settable' tag method */
}
else /* no tag method... */
luaG_typeerror(L, t, "index");
}
}
const TObject *luaV_getglobal (lua_State *L, TString *s) {
const TObject *value = luaH_getstr(L->gt, s);
Closure *tm = luaT_gettmbyObj(L, value, TM_GETGLOBAL);
if (tm == NULL) /* is there a tag method? */
return value; /* default behavior */
else { /* tag method */
luaD_checkstack(L, 3);
clvalue(L->top) = tm;
ttype(L->top) = LUA_TFUNCTION;
tsvalue(L->top+1) = s; /* global name */
ttype(L->top+1) = LUA_TSTRING;
*(L->top+2) = *value;
L->top += 3;
luaD_call(L, L->top - 3, 1);
return L->top - 1;
}
}
void luaV_setglobal (lua_State *L, TString *s) {
const TObject *oldvalue = luaH_getstr(L->gt, s);
Closure *tm = luaT_gettmbyObj(L, oldvalue, TM_SETGLOBAL);
if (tm == NULL) { /* is there a tag method? */
if (oldvalue != &luaO_nilobject) {
/* cast to remove `const' is OK, because `oldvalue' != luaO_nilobject */
*(TObject *)oldvalue = *(L->top - 1);
}
else {
TObject key;
ttype(&key) = LUA_TSTRING;
tsvalue(&key) = s;
*luaH_set(L, L->gt, &key) = *(L->top - 1);
}
}
else {
luaD_checkstack(L, 3);
*(L->top+2) = *(L->top-1); /* new value */
*(L->top+1) = *oldvalue;
ttype(L->top) = LUA_TSTRING;
tsvalue(L->top) = s;
clvalue(L->top-1) = tm;
ttype(L->top-1) = LUA_TFUNCTION;
L->top += 3;
luaD_call(L, L->top - 4, 0);
}
}
static int call_binTM (lua_State *L, StkId top, TMS event) {
/* try first operand */
Closure *tm = luaT_gettmbyObj(L, top-2, event);
L->top = top;
if (tm == NULL) {
tm = luaT_gettmbyObj(L, top-1, event); /* try second operand */
if (tm == NULL) {
tm = luaT_gettm(L, 0, event); /* try a `global' method */
if (tm == NULL)
return 0; /* error */
}
}
lua_pushstring(L, luaT_eventname[event]);
luaD_callTM(L, tm, 3, 1);
return 1;
}
static void call_arith (lua_State *L, StkId top, TMS event) {
if (!call_binTM(L, top, event))
luaG_binerror(L, top-2, LUA_TNUMBER, "perform arithmetic on");
}
static int luaV_strcomp (const TString *ls, const TString *rs) {
const char *l = ls->str;
size_t ll = ls->len;
const char *r = rs->str;
size_t lr = rs->len;
for (;;) {
int temp = strcoll(l, r);
if (temp != 0) return temp;
else { /* strings are equal up to a '\0' */
size_t len = strlen(l); /* index of first '\0' in both strings */
if (len == ll) /* l is finished? */
return (len == lr) ? 0 : -1; /* l is equal or smaller than r */
else if (len == lr) /* r is finished? */
return 1; /* l is greater than r (because l is not finished) */
/* both strings longer than `len'; go on comparing (after the '\0') */
len++;
l += len; ll -= len; r += len; lr -= len;
}
}
}
int luaV_lessthan (lua_State *L, const TObject *l, const TObject *r, StkId top) {
if (ttype(l) == LUA_TNUMBER && ttype(r) == LUA_TNUMBER)
return (nvalue(l) < nvalue(r));
else if (ttype(l) == LUA_TSTRING && ttype(r) == LUA_TSTRING)
return (luaV_strcomp(tsvalue(l), tsvalue(r)) < 0);
else { /* call TM */
luaD_checkstack(L, 2);
*top++ = *l;
*top++ = *r;
if (!call_binTM(L, top, TM_LT))
luaG_ordererror(L, top-2);
L->top--;
return (ttype(L->top) != LUA_TNIL);
}
}
void luaV_strconc (lua_State *L, int total, StkId top) {
do {
int n = 2; /* number of elements handled in this pass (at least 2) */
if (tostring(L, top-2) || tostring(L, top-1)) {
if (!call_binTM(L, top, TM_CONCAT))
luaG_binerror(L, top-2, LUA_TSTRING, "concat");
}
else if (tsvalue(top-1)->len > 0) { /* if len=0, do nothing */
/* at least two string values; get as many as possible */
lint32 tl = (lint32)tsvalue(top-1)->len +
(lint32)tsvalue(top-2)->len;
char *buffer;
int i;
while (n < total && !tostring(L, top-n-1)) { /* collect total length */
tl += tsvalue(top-n-1)->len;
n++;
}
if (tl > MAX_SIZET) lua_error(L, "string size overflow");
buffer = luaO_openspace(L, tl);
tl = 0;
for (i=n; i>0; i--) { /* concat all strings */
size_t l = tsvalue(top-i)->len;
memcpy(buffer+tl, tsvalue(top-i)->str, l);
tl += l;
}
tsvalue(top-n) = luaS_newlstr(L, buffer, tl);
}
total -= n-1; /* got `n' strings to create 1 new */
top -= n-1;
} while (total > 1); /* repeat until only 1 result left */
}
static void luaV_pack (lua_State *L, StkId firstelem) {
int i;
Hash *htab = luaH_new(L, 0);
for (i=0; firstelem+i<L->top; i++)
*luaH_setint(L, htab, i+1) = *(firstelem+i);
/* store counter in field `n' */
luaH_setstrnum(L, htab, luaS_new(L, "n"), i);
L->top = firstelem; /* remove elements from the stack */
ttype(L->top) = LUA_TTABLE;
hvalue(L->top) = htab;
incr_top;
}
static void adjust_varargs (lua_State *L, StkId base, int nfixargs) {
int nvararg = (L->top-base) - nfixargs;
if (nvararg < 0)
luaD_adjusttop(L, base, nfixargs);
luaV_pack(L, base+nfixargs);
}
#define dojump(pc, i) { int d = GETARG_S(i); pc += d; }
/*
** Executes the given Lua function. Parameters are between [base,top).
** Returns n such that the the results are between [n,top).
*/
StkId luaV_execute (lua_State *L, const Closure *cl, StkId base) {
const Proto *const tf = cl->f.l;
StkId top; /* keep top local, for performance */
const Instruction *pc = tf->code;
TString **const kstr = tf->kstr;
const lua_Hook linehook = L->linehook;
infovalue(base-1)->pc = &pc;
luaD_checkstack(L, tf->maxstacksize+EXTRA_STACK);
if (tf->is_vararg) /* varargs? */
adjust_varargs(L, base, tf->numparams);
else
luaD_adjusttop(L, base, tf->numparams);
top = L->top;
/* main loop of interpreter */
for (;;) {
const Instruction i = *pc++;
if (linehook)
traceexec(L, base, top, linehook);
switch (GET_OPCODE(i)) {
case OP_END: {
L->top = top;
return top;
}
case OP_RETURN: {
L->top = top;
return base+GETARG_U(i);
}
case OP_CALL: {
int nres = GETARG_B(i);
if (nres == MULT_RET) nres = LUA_MULTRET;
L->top = top;
luaD_call(L, base+GETARG_A(i), nres);
top = L->top;
break;
}
case OP_TAILCALL: {
L->top = top;
luaD_call(L, base+GETARG_A(i), LUA_MULTRET);
return base+GETARG_B(i);
}
case OP_PUSHNIL: {
int n = GETARG_U(i);
LUA_ASSERT(n>0, "invalid argument");
do {
ttype(top++) = LUA_TNIL;
} while (--n > 0);
break;
}
case OP_POP: {
top -= GETARG_U(i);
break;
}
case OP_PUSHINT: {
ttype(top) = LUA_TNUMBER;
nvalue(top) = (Number)GETARG_S(i);
top++;
break;
}
case OP_PUSHSTRING: {
ttype(top) = LUA_TSTRING;
tsvalue(top) = kstr[GETARG_U(i)];
top++;
break;
}
case OP_PUSHNUM: {
ttype(top) = LUA_TNUMBER;
nvalue(top) = tf->knum[GETARG_U(i)];
top++;
break;
}
case OP_PUSHNEGNUM: {
ttype(top) = LUA_TNUMBER;
nvalue(top) = -tf->knum[GETARG_U(i)];
top++;
break;
}
case OP_PUSHUPVALUE: {
*top++ = cl->upvalue[GETARG_U(i)];
break;
}
case OP_GETLOCAL: {
*top++ = *(base+GETARG_U(i));
break;
}
case OP_GETGLOBAL: {
L->top = top;
*top = *luaV_getglobal(L, kstr[GETARG_U(i)]);
top++;
break;
}
case OP_GETTABLE: {
L->top = top;
top--;
*(top-1) = *luaV_gettable(L, top-1);
break;
}
case OP_GETDOTTED: {
ttype(top) = LUA_TSTRING;
tsvalue(top) = kstr[GETARG_U(i)];
L->top = top+1;
*(top-1) = *luaV_gettable(L, top-1);
break;
}
case OP_GETINDEXED: {
*top = *(base+GETARG_U(i));
L->top = top+1;
*(top-1) = *luaV_gettable(L, top-1);
break;
}
case OP_PUSHSELF: {
TObject receiver;
receiver = *(top-1);
ttype(top) = LUA_TSTRING;
tsvalue(top++) = kstr[GETARG_U(i)];
L->top = top;
*(top-2) = *luaV_gettable(L, top-2);
*(top-1) = receiver;
break;
}
case OP_CREATETABLE: {
L->top = top;
luaC_checkGC(L);
hvalue(top) = luaH_new(L, GETARG_U(i));
ttype(top) = LUA_TTABLE;
top++;
break;
}
case OP_SETLOCAL: {
*(base+GETARG_U(i)) = *(--top);
break;
}
case OP_SETGLOBAL: {
L->top = top;
luaV_setglobal(L, kstr[GETARG_U(i)]);
top--;
break;
}
case OP_SETTABLE: {
StkId t = top-GETARG_A(i);
L->top = top;
luaV_settable(L, t, t+1);
top -= GETARG_B(i); /* pop values */
break;
}
case OP_SETLIST: {
int aux = GETARG_A(i) * LFIELDS_PER_FLUSH;
int n = GETARG_B(i);
Hash *arr = hvalue(top-n-1);
L->top = top-n; /* final value of `top' (in case of errors) */
for (; n; n--)
*luaH_setint(L, arr, n+aux) = *(--top);
break;
}
case OP_SETMAP: {
int n = GETARG_U(i);
StkId finaltop = top-2*n;
Hash *arr = hvalue(finaltop-1);
L->top = finaltop; /* final value of `top' (in case of errors) */
for (; n; n--) {
top-=2;
*luaH_set(L, arr, top) = *(top+1);
}
break;
}
case OP_ADD: {
if (tonumber(top-2) || tonumber(top-1))
call_arith(L, top, TM_ADD);
else
nvalue(top-2) += nvalue(top-1);
top--;
break;
}
case OP_ADDI: {
if (tonumber(top-1)) {
ttype(top) = LUA_TNUMBER;
nvalue(top) = (Number)GETARG_S(i);
call_arith(L, top+1, TM_ADD);
}
else
nvalue(top-1) += (Number)GETARG_S(i);
break;
}
case OP_SUB: {
if (tonumber(top-2) || tonumber(top-1))
call_arith(L, top, TM_SUB);
else
nvalue(top-2) -= nvalue(top-1);
top--;
break;
}
case OP_MULT: {
if (tonumber(top-2) || tonumber(top-1))
call_arith(L, top, TM_MUL);
else
nvalue(top-2) *= nvalue(top-1);
top--;
break;
}
case OP_DIV: {
if (tonumber(top-2) || tonumber(top-1))
call_arith(L, top, TM_DIV);
else
nvalue(top-2) /= nvalue(top-1);
top--;
break;
}
case OP_POW: {
if (!call_binTM(L, top, TM_POW))
lua_error(L, "undefined operation");
top--;
break;
}
case OP_CONCAT: {
int n = GETARG_U(i);
luaV_strconc(L, n, top);
top -= n-1;
L->top = top;
luaC_checkGC(L);
break;
}
case OP_MINUS: {
if (tonumber(top-1)) {
ttype(top) = LUA_TNIL;
call_arith(L, top+1, TM_UNM);
}
else
nvalue(top-1) = -nvalue(top-1);
break;
}
case OP_NOT: {
ttype(top-1) =
(ttype(top-1) == LUA_TNIL) ? LUA_TNUMBER : LUA_TNIL;
nvalue(top-1) = 1;
break;
}
case OP_JMPNE: {
top -= 2;
if (!luaO_equalObj(top, top+1)) dojump(pc, i);
break;
}
case OP_JMPEQ: {
top -= 2;
if (luaO_equalObj(top, top+1)) dojump(pc, i);
break;
}
case OP_JMPLT: {
top -= 2;
if (luaV_lessthan(L, top, top+1, top+2)) dojump(pc, i);
break;
}
case OP_JMPLE: { /* a <= b === !(b<a) */
top -= 2;
if (!luaV_lessthan(L, top+1, top, top+2)) dojump(pc, i);
break;
}
case OP_JMPGT: { /* a > b === (b<a) */
top -= 2;
if (luaV_lessthan(L, top+1, top, top+2)) dojump(pc, i);
break;
}
case OP_JMPGE: { /* a >= b === !(a<b) */
top -= 2;
if (!luaV_lessthan(L, top, top+1, top+2)) dojump(pc, i);
break;
}
case OP_JMPT: {
if (ttype(--top) != LUA_TNIL) dojump(pc, i);
break;
}
case OP_JMPF: {
if (ttype(--top) == LUA_TNIL) dojump(pc, i);
break;
}
case OP_JMPONT: {
if (ttype(top-1) == LUA_TNIL) top--;
else dojump(pc, i);
break;
}
case OP_JMPONF: {
if (ttype(top-1) != LUA_TNIL) top--;
else dojump(pc, i);
break;
}
case OP_JMP: {
dojump(pc, i);
break;
}
case OP_PUSHNILJMP: {
ttype(top++) = LUA_TNIL;
pc++;
break;
}
case OP_FORPREP: {
if (tonumber(top-1))
lua_error(L, "`for' step must be a number");
if (tonumber(top-2))
lua_error(L, "`for' limit must be a number");
if (tonumber(top-3))
lua_error(L, "`for' initial value must be a number");
if (nvalue(top-1) > 0 ?
nvalue(top-3) > nvalue(top-2) :
nvalue(top-3) < nvalue(top-2)) { /* `empty' loop? */
top -= 3; /* remove control variables */
dojump(pc, i); /* jump to loop end */
}
break;
}
case OP_FORLOOP: {
LUA_ASSERT(ttype(top-1) == LUA_TNUMBER, "invalid step");
LUA_ASSERT(ttype(top-2) == LUA_TNUMBER, "invalid limit");
if (ttype(top-3) != LUA_TNUMBER)
lua_error(L, "`for' index must be a number");
nvalue(top-3) += nvalue(top-1); /* increment index */
if (nvalue(top-1) > 0 ?
nvalue(top-3) > nvalue(top-2) :
nvalue(top-3) < nvalue(top-2))
top -= 3; /* end loop: remove control variables */
else
dojump(pc, i); /* repeat loop */
break;
}
case OP_LFORPREP: {
Node *node;
if (ttype(top-1) != LUA_TTABLE)
lua_error(L, "`for' table must be a table");
node = luaH_next(L, hvalue(top-1), &luaO_nilobject);
if (node == NULL) { /* `empty' loop? */
top--; /* remove table */
dojump(pc, i); /* jump to loop end */
}
else {
top += 2; /* index,value */
*(top-2) = *key(node);
*(top-1) = *val(node);
}
break;
}
case OP_LFORLOOP: {
Node *node;
LUA_ASSERT(ttype(top-3) == LUA_TTABLE, "invalid table");
node = luaH_next(L, hvalue(top-3), top-2);
if (node == NULL) /* end loop? */
top -= 3; /* remove table, key, and value */
else {
*(top-2) = *key(node);
*(top-1) = *val(node);
dojump(pc, i); /* repeat loop */
}
break;
}
case OP_CLOSURE: {
L->top = top;
luaV_Lclosure(L, tf->kproto[GETARG_A(i)], GETARG_B(i));
top = L->top;
luaC_checkGC(L);
break;
}
}
}
}
| gpl-2.0 |
morphis/ofono | src/gprs.c | 1 | 87326 | /*
*
* oFono - Open Source Telephony
*
* Copyright (C) 2008-2011 Intel Corporation. All rights reserved.
* Copyright (C) 2014 Canonical Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <net/route.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <resolv.h>
#include <netdb.h>
#include <glib.h>
#include <gdbus.h>
#include "ofono.h"
#include "common.h"
#include "storage.h"
#include "idmap.h"
#include "simutil.h"
#include "util.h"
#include "dns-client.h"
#define GPRS_FLAG_ATTACHING 0x1
#define GPRS_FLAG_RECHECK 0x2
#define GPRS_FLAG_ATTACHED_UPDATE 0x4
#define SETTINGS_STORE "gprs"
#define SETTINGS_GROUP "Settings"
#define MAX_CONTEXT_NAME_LENGTH 127
#define MAX_MESSAGE_PROXY_LENGTH 255
#define MAX_MESSAGE_CENTER_LENGTH 255
#define MAX_CONTEXTS 256
#define SUSPEND_TIMEOUT 8
#define DNS_LOOKUP_TOUT_MS 15000
struct ofono_gprs {
GSList *contexts;
ofono_bool_t attached;
ofono_bool_t driver_attached;
ofono_bool_t roaming_allowed;
ofono_bool_t powered;
ofono_bool_t suspended;
int status;
int flags;
int bearer;
guint suspend_timeout;
struct idmap *pid_map;
unsigned int last_context_id;
struct idmap *cid_map;
int netreg_status;
struct ofono_netreg *netreg;
unsigned int netreg_watch;
unsigned int status_watch;
GKeyFile *settings;
char *imsi;
DBusMessage *pending;
GSList *context_drivers;
const struct ofono_gprs_driver *driver;
void *driver_data;
struct ofono_atom *atom;
unsigned int spn_watch;
struct ofono_sim *sim;
struct ofono_sim_context *sim_context;
char *gid1;
};
struct ipv4_settings {
ofono_bool_t static_ip;
char *ip;
char *netmask;
char *gateway;
char **dns;
char *proxy;
uint16_t proxy_port;
};
struct ipv6_settings {
char *ip;
unsigned char prefix_len;
char *gateway;
char **dns;
};
struct context_settings {
char *interface;
struct ipv4_settings *ipv4;
struct ipv6_settings *ipv6;
};
struct ofono_gprs_context {
struct ofono_gprs *gprs;
enum ofono_gprs_context_type type;
ofono_bool_t inuse;
const struct ofono_gprs_context_driver *driver;
void *driver_data;
struct context_settings *settings;
struct ofono_atom *atom;
};
struct pri_context {
ofono_bool_t active;
enum ofono_gprs_context_type type;
gboolean preferred;
char name[MAX_CONTEXT_NAME_LENGTH + 1];
char message_proxy[MAX_MESSAGE_PROXY_LENGTH + 1];
char message_center[MAX_MESSAGE_CENTER_LENGTH + 1];
unsigned int id;
char *path;
char *key;
char *proxy_host;
uint16_t proxy_port;
DBusMessage *pending;
struct ofono_gprs_primary_context context;
struct ofono_gprs_context *context_driver;
struct ofono_gprs *gprs;
ofono_dns_client_request_t lookup_req;
};
static void gprs_netreg_update(struct ofono_gprs *gprs);
static void gprs_deactivate_next(struct ofono_gprs *gprs);
static GSList *g_drivers = NULL;
static GSList *g_context_drivers = NULL;
static const char *gprs_context_default_name(enum ofono_gprs_context_type type)
{
switch (type) {
case OFONO_GPRS_CONTEXT_TYPE_ANY:
return NULL;
case OFONO_GPRS_CONTEXT_TYPE_INTERNET:
return "Internet";
case OFONO_GPRS_CONTEXT_TYPE_MMS:
return "MMS";
case OFONO_GPRS_CONTEXT_TYPE_WAP:
return "WAP";
case OFONO_GPRS_CONTEXT_TYPE_IMS:
return "IMS";
case OFONO_GPRS_CONTEXT_TYPE_IA:
return "IA";
}
return NULL;
}
static const char *gprs_context_type_to_string(
enum ofono_gprs_context_type type)
{
switch (type) {
case OFONO_GPRS_CONTEXT_TYPE_ANY:
return NULL;
case OFONO_GPRS_CONTEXT_TYPE_INTERNET:
return "internet";
case OFONO_GPRS_CONTEXT_TYPE_MMS:
return "mms";
case OFONO_GPRS_CONTEXT_TYPE_WAP:
return "wap";
case OFONO_GPRS_CONTEXT_TYPE_IMS:
return "ims";
case OFONO_GPRS_CONTEXT_TYPE_IA:
return "ia";
}
return NULL;
}
static gboolean gprs_context_string_to_type(const char *str,
enum ofono_gprs_context_type *out)
{
if (g_str_equal(str, "internet")) {
*out = OFONO_GPRS_CONTEXT_TYPE_INTERNET;
return TRUE;
} else if (g_str_equal(str, "wap")) {
*out = OFONO_GPRS_CONTEXT_TYPE_WAP;
return TRUE;
} else if (g_str_equal(str, "mms")) {
*out = OFONO_GPRS_CONTEXT_TYPE_MMS;
return TRUE;
} else if (g_str_equal(str, "ims")) {
*out = OFONO_GPRS_CONTEXT_TYPE_IMS;
return TRUE;
} else if (g_str_equal(str, "ia")) {
*out = OFONO_GPRS_CONTEXT_TYPE_IA;
return TRUE;
}
return FALSE;
}
static const char *gprs_proto_to_string(enum ofono_gprs_proto proto)
{
switch (proto) {
case OFONO_GPRS_PROTO_IP:
return "ip";
case OFONO_GPRS_PROTO_IPV6:
return "ipv6";
case OFONO_GPRS_PROTO_IPV4V6:
return "dual";
};
return NULL;
}
static gboolean gprs_proto_from_string(const char *str,
enum ofono_gprs_proto *proto)
{
if (g_str_equal(str, "ip")) {
*proto = OFONO_GPRS_PROTO_IP;
return TRUE;
} else if (g_str_equal(str, "ipv6")) {
*proto = OFONO_GPRS_PROTO_IPV6;
return TRUE;
} else if (g_str_equal(str, "dual")) {
*proto = OFONO_GPRS_PROTO_IPV4V6;
return TRUE;
}
return FALSE;
}
static const char *gprs_auth_method_to_string(enum ofono_gprs_auth_method auth)
{
switch (auth) {
case OFONO_GPRS_AUTH_METHOD_CHAP:
return "chap";
case OFONO_GPRS_AUTH_METHOD_PAP:
return "pap";
};
return NULL;
}
static gboolean gprs_auth_method_from_string(const char *str,
enum ofono_gprs_auth_method *auth)
{
if (g_str_equal(str, "chap")) {
*auth = OFONO_GPRS_AUTH_METHOD_CHAP;
return TRUE;
} else if (g_str_equal(str, "pap")) {
*auth = OFONO_GPRS_AUTH_METHOD_PAP;
return TRUE;
}
return FALSE;
}
static unsigned int gprs_cid_alloc(struct ofono_gprs *gprs)
{
return idmap_alloc(gprs->cid_map);
}
static void gprs_cid_release(struct ofono_gprs *gprs, unsigned int id)
{
idmap_put(gprs->cid_map, id);
}
static gboolean assign_context(struct pri_context *ctx)
{
struct idmap *cidmap = ctx->gprs->cid_map;
GSList *l;
if (cidmap == NULL)
return FALSE;
ctx->context.cid = gprs_cid_alloc(ctx->gprs);
if (ctx->context.cid == 0)
return FALSE;
for (l = ctx->gprs->context_drivers; l; l = l->next) {
struct ofono_gprs_context *gc = l->data;
if (gc->inuse == TRUE)
continue;
if (gc->driver == NULL)
continue;
if (gc->driver->activate_primary == NULL ||
gc->driver->deactivate_primary == NULL)
continue;
if (gc->type != OFONO_GPRS_CONTEXT_TYPE_ANY &&
gc->type != ctx->type)
continue;
ctx->context_driver = gc;
ctx->context_driver->inuse = TRUE;
if (ctx->context.proto == OFONO_GPRS_PROTO_IPV4V6 ||
ctx->context.proto == OFONO_GPRS_PROTO_IP)
gc->settings->ipv4 = g_new0(struct ipv4_settings, 1);
if (ctx->context.proto == OFONO_GPRS_PROTO_IPV4V6 ||
ctx->context.proto == OFONO_GPRS_PROTO_IPV6)
gc->settings->ipv6 = g_new0(struct ipv6_settings, 1);
return TRUE;
}
return FALSE;
}
static void release_context(struct pri_context *ctx)
{
if (ctx == NULL || ctx->gprs == NULL || ctx->context_driver == NULL)
return;
gprs_cid_release(ctx->gprs, ctx->context.cid);
ctx->context.cid = 0;
ctx->context_driver->inuse = FALSE;
ctx->context_driver = NULL;
ctx->active = FALSE;
}
static struct pri_context *gprs_context_by_path(struct ofono_gprs *gprs,
const char *ctx_path)
{
GSList *l;
for (l = gprs->contexts; l; l = l->next) {
struct pri_context *ctx = l->data;
if (g_str_equal(ctx_path, ctx->path))
return ctx;
}
return NULL;
}
static void context_settings_free(struct context_settings *settings)
{
if (settings->ipv4) {
g_free(settings->ipv4->ip);
g_free(settings->ipv4->netmask);
g_free(settings->ipv4->gateway);
g_strfreev(settings->ipv4->dns);
g_free(settings->ipv4->proxy);
g_free(settings->ipv4);
settings->ipv4 = NULL;
}
if (settings->ipv6) {
g_free(settings->ipv6->ip);
g_free(settings->ipv6->gateway);
g_strfreev(settings->ipv6->dns);
g_free(settings->ipv6);
settings->ipv6 = NULL;
}
g_free(settings->interface);
settings->interface = NULL;
}
static void context_settings_append_ipv4(struct context_settings *settings,
DBusMessageIter *iter)
{
DBusMessageIter variant;
DBusMessageIter array;
char typesig[5];
char arraysig[6];
const char *method;
arraysig[0] = DBUS_TYPE_ARRAY;
arraysig[1] = typesig[0] = DBUS_DICT_ENTRY_BEGIN_CHAR;
arraysig[2] = typesig[1] = DBUS_TYPE_STRING;
arraysig[3] = typesig[2] = DBUS_TYPE_VARIANT;
arraysig[4] = typesig[3] = DBUS_DICT_ENTRY_END_CHAR;
arraysig[5] = typesig[4] = '\0';
dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT,
arraysig, &variant);
dbus_message_iter_open_container(&variant, DBUS_TYPE_ARRAY,
typesig, &array);
if (settings == NULL || settings->ipv4 == NULL)
goto done;
ofono_dbus_dict_append(&array, "Interface",
DBUS_TYPE_STRING, &settings->interface);
if (settings->ipv4->proxy) {
ofono_dbus_dict_append(&array, "Proxy", DBUS_TYPE_STRING,
&settings->ipv4->proxy);
ofono_dbus_dict_append(&array, "ProxyPort", DBUS_TYPE_UINT16,
&settings->ipv4->proxy_port);
}
if (settings->ipv4->static_ip == TRUE)
method = "static";
else
method = "dhcp";
ofono_dbus_dict_append(&array, "Method", DBUS_TYPE_STRING, &method);
if (settings->ipv4->ip)
ofono_dbus_dict_append(&array, "Address", DBUS_TYPE_STRING,
&settings->ipv4->ip);
if (settings->ipv4->netmask)
ofono_dbus_dict_append(&array, "Netmask", DBUS_TYPE_STRING,
&settings->ipv4->netmask);
if (settings->ipv4->gateway)
ofono_dbus_dict_append(&array, "Gateway", DBUS_TYPE_STRING,
&settings->ipv4->gateway);
if (settings->ipv4->dns)
ofono_dbus_dict_append_array(&array, "DomainNameServers",
DBUS_TYPE_STRING,
&settings->ipv4->dns);
done:
dbus_message_iter_close_container(&variant, &array);
dbus_message_iter_close_container(iter, &variant);
}
static void context_settings_append_ipv4_dict(struct context_settings *settings,
DBusMessageIter *dict)
{
DBusMessageIter entry;
const char *key = "Settings";
dbus_message_iter_open_container(dict, DBUS_TYPE_DICT_ENTRY,
NULL, &entry);
dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &key);
context_settings_append_ipv4(settings, &entry);
dbus_message_iter_close_container(dict, &entry);
}
static void context_settings_append_ipv6(struct context_settings *settings,
DBusMessageIter *iter)
{
DBusMessageIter variant;
DBusMessageIter array;
char typesig[5];
char arraysig[6];
arraysig[0] = DBUS_TYPE_ARRAY;
arraysig[1] = typesig[0] = DBUS_DICT_ENTRY_BEGIN_CHAR;
arraysig[2] = typesig[1] = DBUS_TYPE_STRING;
arraysig[3] = typesig[2] = DBUS_TYPE_VARIANT;
arraysig[4] = typesig[3] = DBUS_DICT_ENTRY_END_CHAR;
arraysig[5] = typesig[4] = '\0';
dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT,
arraysig, &variant);
dbus_message_iter_open_container(&variant, DBUS_TYPE_ARRAY,
typesig, &array);
if (settings == NULL || settings->ipv6 == NULL)
goto done;
ofono_dbus_dict_append(&array, "Interface",
DBUS_TYPE_STRING, &settings->interface);
if (settings->ipv6->ip)
ofono_dbus_dict_append(&array, "Address", DBUS_TYPE_STRING,
&settings->ipv6->ip);
if (settings->ipv6->prefix_len)
ofono_dbus_dict_append(&array, "PrefixLength", DBUS_TYPE_BYTE,
&settings->ipv6->prefix_len);
if (settings->ipv6->gateway)
ofono_dbus_dict_append(&array, "Gateway", DBUS_TYPE_STRING,
&settings->ipv6->gateway);
if (settings->ipv6->dns)
ofono_dbus_dict_append_array(&array, "DomainNameServers",
DBUS_TYPE_STRING,
&settings->ipv6->dns);
done:
dbus_message_iter_close_container(&variant, &array);
dbus_message_iter_close_container(iter, &variant);
}
static void context_settings_append_ipv6_dict(struct context_settings *settings,
DBusMessageIter *dict)
{
DBusMessageIter entry;
const char *key = "IPv6.Settings";
dbus_message_iter_open_container(dict, DBUS_TYPE_DICT_ENTRY,
NULL, &entry);
dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &key);
context_settings_append_ipv6(settings, &entry);
dbus_message_iter_close_container(dict, &entry);
}
static void signal_settings(struct pri_context *ctx, const char *prop,
void (*append)(struct context_settings *, DBusMessageIter *))
{
DBusConnection *conn = ofono_dbus_get_connection();
const char *path = ctx->path;
DBusMessage *signal;
DBusMessageIter iter;
struct context_settings *settings;
signal = dbus_message_new_signal(path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"PropertyChanged");
if (signal == NULL)
return;
dbus_message_iter_init_append(signal, &iter);
dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &prop);
if (ctx->context_driver)
settings = ctx->context_driver->settings;
else
settings = NULL;
append(settings, &iter);
g_dbus_send_message(conn, signal);
}
static void pri_context_signal_settings(struct pri_context *ctx,
gboolean ipv4, gboolean ipv6)
{
if (ipv4)
signal_settings(ctx, "Settings",
context_settings_append_ipv4);
if (ipv6)
signal_settings(ctx, "IPv6.Settings",
context_settings_append_ipv6);
}
static void set_route(const struct context_settings *settings,
const char *ipstr, gboolean create)
{
struct rtentry rt;
struct sockaddr_in addr;
int sk;
const char *debug_str = create ? "create" : "remove";
/* TODO Handle IPv6 case */
DBG("%s for %s", ipstr, debug_str);
if (settings->interface == NULL)
return;
sk = socket(PF_INET, SOCK_DGRAM, 0);
if (sk < 0)
return;
memset(&rt, 0, sizeof(rt));
rt.rt_dev = (char *) settings->interface;
rt.rt_flags = RTF_HOST;
if (create)
rt.rt_flags |= RTF_UP;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ipstr);
if (addr.sin_addr.s_addr == INADDR_NONE) {
ofono_error("Cannot %s route for invalid IP %s",
debug_str, ipstr);
return;
}
memcpy(&rt.rt_dst, &addr, sizeof(rt.rt_dst));
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
memcpy(&rt.rt_gateway, &addr, sizeof(rt.rt_gateway));
memcpy(&rt.rt_genmask, &addr, sizeof(rt.rt_genmask));
if (ioctl(sk, create ? SIOCADDRT : SIOCDELRT, &rt) < 0)
ofono_error("Failed to %s proxy host route: %s (%d)",
debug_str, strerror(errno), errno);
close(sk);
}
static void pri_activate_finish(struct pri_context *ctx)
{
struct ofono_gprs_context *gc = ctx->context_driver;
struct context_settings *settings = gc->settings;
DBusConnection *conn = ofono_dbus_get_connection();
dbus_bool_t value;
DBG("proxy %s port %u", ctx->proxy_host ? ctx->proxy_host : "NULL",
ctx->proxy_port);
if (ctx->proxy_host) {
settings->ipv4->proxy = g_strdup(ctx->proxy_host);
settings->ipv4->proxy_port = ctx->proxy_port;
if (ctx->type == OFONO_GPRS_CONTEXT_TYPE_MMS)
set_route(settings, ctx->proxy_host, TRUE);
}
ctx->active = TRUE;
__ofono_dbus_pending_reply(&ctx->pending,
dbus_message_new_method_return(ctx->pending));
if (gc->settings->interface != NULL)
pri_context_signal_settings(ctx, settings->ipv4 != NULL,
settings->ipv6 != NULL);
value = ctx->active;
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Active", DBUS_TYPE_BOOLEAN, &value);
}
static void lookup_address_cb(void *data, ofono_dns_client_status_t status,
struct sockaddr *ip_addr)
{
struct pri_context *ctx = data;
char str[INET_ADDRSTRLEN];
if (status == OFONO_DNS_CLIENT_SUCCESS) {
void *addr;
if (ip_addr->sa_family == AF_INET) {
struct sockaddr_in *ip4 = (void *) ip_addr;
addr = &ip4->sin_addr;
} else {
/* Assume ipv6 */
struct sockaddr_in6 *ip6 = (void *) ip_addr;
addr = &ip6->sin6_addr;
}
if (inet_ntop(ip_addr->sa_family, addr, str, sizeof(str)))
ctx->proxy_host = g_strdup(str);
else
ofono_error("%s: Cannot convert type %d to address",
__func__, ip_addr->sa_family);
} else {
ofono_error("DNS error %s",
__ofono_dns_client_strerror(status));
}
ctx->lookup_req = NULL;
pri_activate_finish(ctx);
}
static void lookup_address(struct pri_context *ctx, const char *proxy)
{
struct context_settings *settings = ctx->context_driver->settings;
DBG("hostname is %s", proxy);
ctx->lookup_req = __ofono_dns_client_submit_request(
proxy, settings->interface,
(const char **) settings->ipv4->dns,
DNS_LOOKUP_TOUT_MS,
lookup_address_cb, ctx);
}
static void get_proxy_ip(struct pri_context *ctx, const char *host)
{
struct context_settings *settings = ctx->context_driver->settings;
struct in_addr addr;
if (inet_pton(AF_INET, host, &addr) == 1) {
ctx->proxy_host = g_strdup(host);
return;
}
/* Not an IP -> use DNS if possible */
if (settings->ipv4 == NULL || settings->ipv4->dns == NULL ||
settings->ipv4->dns[0] == NULL) {
ofono_error("No DNS to find IP for MMS proxy/MMSC %s", host);
return;
}
lookup_address(ctx, host);
}
static void pri_parse_proxy(struct pri_context *ctx)
{
char *proxy, *scheme, *host, *port, *path;
g_free(ctx->proxy_host);
ctx->proxy_host = NULL;
if (ctx->message_proxy[0] != '\0')
proxy = ctx->message_proxy;
else if (ctx->message_center[0] != '\0')
proxy = ctx->message_center;
else
return;
scheme = g_strdup(proxy);
if (scheme == NULL)
return;
host = strstr(scheme, "://");
if (host != NULL) {
*host = '\0';
host += 3;
if (strcasecmp(scheme, "https") == 0)
ctx->proxy_port = 443;
else if (strcasecmp(scheme, "http") == 0)
ctx->proxy_port = 80;
else {
g_free(scheme);
return;
}
} else {
host = scheme;
ctx->proxy_port = 80;
}
path = strchr(host, '/');
if (path != NULL)
*(path++) = '\0';
port = strrchr(host, ':');
if (port != NULL) {
char *end;
int tmp = strtol(port + 1, &end, 10);
if (*end == '\0') {
*port = '\0';
ctx->proxy_port = tmp;
}
}
get_proxy_ip(ctx, host);
g_free(scheme);
}
static void pri_ifupdown(const char *interface, ofono_bool_t active)
{
struct ifreq ifr;
int sk;
if (interface == NULL)
return;
sk = socket(PF_INET, SOCK_DGRAM, 0);
if (sk < 0)
return;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, interface, IFNAMSIZ);
if (ioctl(sk, SIOCGIFFLAGS, &ifr) < 0)
goto done;
if (active == TRUE) {
if (ifr.ifr_flags & IFF_UP)
goto done;
ifr.ifr_flags |= IFF_UP;
} else {
if (!(ifr.ifr_flags & IFF_UP))
goto done;
ifr.ifr_flags &= ~IFF_UP;
}
if (ioctl(sk, SIOCSIFFLAGS, &ifr) < 0)
ofono_error("Failed to change interface flags");
done:
close(sk);
}
static void pri_set_ipv4_addr(const char *interface, const char *address)
{
struct ifreq ifr;
struct sockaddr_in addr;
int sk;
if (interface == NULL)
return;
sk = socket(PF_INET, SOCK_DGRAM, 0);
if (sk < 0)
return;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, interface, IFNAMSIZ);
if (ioctl(sk, SIOCGIFFLAGS, &ifr) < 0)
goto done;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = address ? inet_addr(address) : INADDR_ANY;
memcpy(&ifr.ifr_addr, &addr, sizeof(ifr.ifr_addr));
if (ioctl(sk, SIOCSIFADDR, &ifr) < 0) {
ofono_error("Failed to set interface address");
goto done;
}
if (address == NULL)
goto done;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("255.255.255.255");
memcpy(&ifr.ifr_netmask, &addr, sizeof(ifr.ifr_netmask));
if (ioctl(sk, SIOCSIFNETMASK, &ifr) < 0)
ofono_error("Failed to set interface netmask");
done:
close(sk);
}
static void pri_reset_context_settings(struct pri_context *ctx)
{
struct context_settings *settings;
char *interface;
gboolean signal_ipv4;
gboolean signal_ipv6;
if (ctx->context_driver == NULL)
return;
settings = ctx->context_driver->settings;
interface = settings->interface;
settings->interface = NULL;
signal_ipv4 = settings->ipv4 != NULL;
signal_ipv6 = settings->ipv6 != NULL;
context_settings_free(settings);
pri_context_signal_settings(ctx, signal_ipv4, signal_ipv6);
if (ctx->type == OFONO_GPRS_CONTEXT_TYPE_MMS)
pri_set_ipv4_addr(interface, NULL);
if (ctx->proxy_host != NULL) {
g_free(ctx->proxy_host);
ctx->proxy_host = NULL;
ctx->proxy_port = 0;
}
pri_ifupdown(interface, FALSE);
g_free(interface);
}
static void append_context_properties(struct pri_context *ctx,
DBusMessageIter *dict)
{
const char *type = gprs_context_type_to_string(ctx->type);
const char *proto = gprs_proto_to_string(ctx->context.proto);
const char *name = ctx->name;
dbus_bool_t value, preferred;
const char *strvalue;
struct context_settings *settings;
ofono_dbus_dict_append(dict, "Name", DBUS_TYPE_STRING, &name);
value = ctx->active;
ofono_dbus_dict_append(dict, "Active", DBUS_TYPE_BOOLEAN, &value);
preferred = ctx->preferred;
ofono_dbus_dict_append(dict, "Preferred", DBUS_TYPE_BOOLEAN, &preferred);
ofono_dbus_dict_append(dict, "Type", DBUS_TYPE_STRING, &type);
ofono_dbus_dict_append(dict, "Protocol", DBUS_TYPE_STRING, &proto);
strvalue = ctx->context.apn;
ofono_dbus_dict_append(dict, "AccessPointName", DBUS_TYPE_STRING,
&strvalue);
strvalue = ctx->context.username;
ofono_dbus_dict_append(dict, "Username", DBUS_TYPE_STRING,
&strvalue);
strvalue = ctx->context.password;
ofono_dbus_dict_append(dict, "Password", DBUS_TYPE_STRING,
&strvalue);
strvalue = gprs_auth_method_to_string(ctx->context.auth_method);
ofono_dbus_dict_append(dict, "AuthenticationMethod", DBUS_TYPE_STRING,
&strvalue);
if (ctx->type == OFONO_GPRS_CONTEXT_TYPE_MMS ||
(ctx->message_center && strlen(ctx->message_center) > 0)) {
strvalue = ctx->message_proxy;
ofono_dbus_dict_append(dict, "MessageProxy",
DBUS_TYPE_STRING, &strvalue);
strvalue = ctx->message_center;
ofono_dbus_dict_append(dict, "MessageCenter",
DBUS_TYPE_STRING, &strvalue);
}
if (ctx->context_driver)
settings = ctx->context_driver->settings;
else
settings = NULL;
context_settings_append_ipv4_dict(settings, dict);
context_settings_append_ipv6_dict(settings, dict);
}
static DBusMessage *pri_get_properties(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct pri_context *ctx = data;
DBusMessage *reply;
DBusMessageIter iter;
DBusMessageIter dict;
reply = dbus_message_new_method_return(msg);
if (reply == NULL)
return NULL;
dbus_message_iter_init_append(reply, &iter);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
OFONO_PROPERTIES_ARRAY_SIGNATURE,
&dict);
append_context_properties(ctx, &dict);
dbus_message_iter_close_container(&iter, &dict);
return reply;
}
static void pri_activate_callback(const struct ofono_error *error, void *data)
{
struct pri_context *ctx = data;
struct ofono_gprs_context *gc = ctx->context_driver;
DBG("%p", ctx);
if (error->type != OFONO_ERROR_TYPE_NO_ERROR) {
DBG("Activating context failed with error: %s",
telephony_error_to_str(error));
__ofono_dbus_pending_reply(&ctx->pending,
__ofono_error_failed(ctx->pending));
context_settings_free(ctx->context_driver->settings);
release_context(ctx);
return;
}
if (gc->settings->interface != NULL) {
pri_ifupdown(gc->settings->interface, TRUE);
if (gc->settings->ipv4) {
if (ctx->type == OFONO_GPRS_CONTEXT_TYPE_MMS)
pri_set_ipv4_addr(gc->settings->interface,
gc->settings->ipv4->ip);
pri_parse_proxy(ctx);
/* Not answer yet if waiting for DNS lookup */
if (ctx->lookup_req != NULL)
return;
}
}
pri_activate_finish(ctx);
}
static void pri_deactivate_callback(const struct ofono_error *error, void *data)
{
struct pri_context *ctx = data;
DBusConnection *conn = ofono_dbus_get_connection();
dbus_bool_t value;
if (error->type != OFONO_ERROR_TYPE_NO_ERROR) {
DBG("Deactivating context failed with error: %s",
telephony_error_to_str(error));
__ofono_dbus_pending_reply(&ctx->pending,
__ofono_error_failed(ctx->pending));
return;
}
__ofono_dbus_pending_reply(&ctx->pending,
dbus_message_new_method_return(ctx->pending));
pri_reset_context_settings(ctx);
release_context(ctx);
value = ctx->active;
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Active", DBUS_TYPE_BOOLEAN, &value);
}
static void set_preferred(struct pri_context *ctx, DBusConnection *conn,
gboolean preferred)
{
GKeyFile *settings = ctx->gprs->settings;
ctx->preferred = preferred;
if (settings) {
g_key_file_set_boolean(settings, ctx->key, "Preferred",
preferred);
storage_sync(ctx->gprs->imsi, SETTINGS_STORE, settings);
}
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Preferred", DBUS_TYPE_BOOLEAN,
&preferred);
}
static DBusMessage *pri_set_preferred(struct pri_context *ctx,
DBusConnection *conn,
DBusMessage *msg, gboolean preferred)
{
if (ctx->preferred == preferred)
return dbus_message_new_method_return(msg);
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
set_preferred(ctx, conn, preferred);
return NULL;
}
static DBusMessage *pri_set_apn(struct pri_context *ctx, DBusConnection *conn,
DBusMessage *msg, const char *apn)
{
GKeyFile *settings = ctx->gprs->settings;
if (strlen(apn) > OFONO_GPRS_MAX_APN_LENGTH)
return __ofono_error_invalid_format(msg);
if (g_str_equal(apn, ctx->context.apn))
return dbus_message_new_method_return(msg);
if (is_valid_apn(apn) == FALSE)
return __ofono_error_invalid_format(msg);
strcpy(ctx->context.apn, apn);
if (settings) {
g_key_file_set_string(settings, ctx->key,
"AccessPointName", apn);
storage_sync(ctx->gprs->imsi, SETTINGS_STORE, settings);
}
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"AccessPointName",
DBUS_TYPE_STRING, &apn);
return NULL;
}
static DBusMessage *pri_set_username(struct pri_context *ctx,
DBusConnection *conn, DBusMessage *msg,
const char *username)
{
GKeyFile *settings = ctx->gprs->settings;
if (strlen(username) > OFONO_GPRS_MAX_USERNAME_LENGTH)
return __ofono_error_invalid_format(msg);
if (g_str_equal(username, ctx->context.username))
return dbus_message_new_method_return(msg);
strcpy(ctx->context.username, username);
if (settings) {
g_key_file_set_string(settings, ctx->key,
"Username", username);
storage_sync(ctx->gprs->imsi, SETTINGS_STORE, settings);
}
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Username",
DBUS_TYPE_STRING, &username);
return NULL;
}
static DBusMessage *pri_set_password(struct pri_context *ctx,
DBusConnection *conn, DBusMessage *msg,
const char *password)
{
GKeyFile *settings = ctx->gprs->settings;
if (strlen(password) > OFONO_GPRS_MAX_PASSWORD_LENGTH)
return __ofono_error_invalid_format(msg);
if (g_str_equal(password, ctx->context.password))
return dbus_message_new_method_return(msg);
strcpy(ctx->context.password, password);
if (settings) {
g_key_file_set_string(settings, ctx->key,
"Password", password);
storage_sync(ctx->gprs->imsi, SETTINGS_STORE, settings);
}
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Password",
DBUS_TYPE_STRING, &password);
return NULL;
}
static DBusMessage *pri_set_type(struct pri_context *ctx, DBusConnection *conn,
DBusMessage *msg, const char *type)
{
GKeyFile *settings = ctx->gprs->settings;
enum ofono_gprs_context_type context_type;
if (gprs_context_string_to_type(type, &context_type) == FALSE)
return __ofono_error_invalid_format(msg);
if (ctx->type == context_type)
return dbus_message_new_method_return(msg);
ctx->type = context_type;
if (settings) {
g_key_file_set_string(settings, ctx->key, "Type", type);
storage_sync(ctx->gprs->imsi, SETTINGS_STORE, settings);
}
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Type", DBUS_TYPE_STRING, &type);
return NULL;
}
static DBusMessage *pri_set_proto(struct pri_context *ctx,
DBusConnection *conn,
DBusMessage *msg, const char *str)
{
GKeyFile *settings = ctx->gprs->settings;
enum ofono_gprs_proto proto;
if (gprs_proto_from_string(str, &proto) == FALSE)
return __ofono_error_invalid_format(msg);
if (ctx->context.proto == proto)
return dbus_message_new_method_return(msg);
ctx->context.proto = proto;
if (settings) {
g_key_file_set_string(settings, ctx->key, "Protocol", str);
storage_sync(ctx->gprs->imsi, SETTINGS_STORE, settings);
}
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Protocol", DBUS_TYPE_STRING, &str);
return NULL;
}
static DBusMessage *pri_set_name(struct pri_context *ctx, DBusConnection *conn,
DBusMessage *msg, const char *name)
{
GKeyFile *settings = ctx->gprs->settings;
if (strlen(name) > MAX_CONTEXT_NAME_LENGTH)
return __ofono_error_invalid_format(msg);
if (ctx->name && g_str_equal(ctx->name, name))
return dbus_message_new_method_return(msg);
strcpy(ctx->name, name);
if (settings) {
g_key_file_set_string(settings, ctx->key, "Name", ctx->name);
storage_sync(ctx->gprs->imsi, SETTINGS_STORE, settings);
}
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Name", DBUS_TYPE_STRING, &name);
return NULL;
}
static DBusMessage *pri_set_message_proxy(struct pri_context *ctx,
DBusConnection *conn,
DBusMessage *msg, const char *proxy)
{
GKeyFile *settings = ctx->gprs->settings;
if (strlen(proxy) > MAX_MESSAGE_PROXY_LENGTH)
return __ofono_error_invalid_format(msg);
if (ctx->message_proxy && g_str_equal(ctx->message_proxy, proxy))
return dbus_message_new_method_return(msg);
strcpy(ctx->message_proxy, proxy);
if (settings) {
g_key_file_set_string(settings, ctx->key, "MessageProxy",
ctx->message_proxy);
storage_sync(ctx->gprs->imsi, SETTINGS_STORE, settings);
}
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"MessageProxy", DBUS_TYPE_STRING, &proxy);
return NULL;
}
static DBusMessage *pri_set_message_center(struct pri_context *ctx,
DBusConnection *conn,
DBusMessage *msg, const char *center)
{
GKeyFile *settings = ctx->gprs->settings;
if (strlen(center) > MAX_MESSAGE_CENTER_LENGTH)
return __ofono_error_invalid_format(msg);
if (ctx->message_center && g_str_equal(ctx->message_center, center))
return dbus_message_new_method_return(msg);
strcpy(ctx->message_center, center);
if (settings) {
g_key_file_set_string(settings, ctx->key, "MessageCenter",
ctx->message_center);
storage_sync(ctx->gprs->imsi, SETTINGS_STORE, settings);
}
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"MessageCenter", DBUS_TYPE_STRING, ¢er);
return NULL;
}
static DBusMessage *pri_set_auth_method(struct pri_context *ctx,
DBusConnection *conn,
DBusMessage *msg, const char *str)
{
GKeyFile *settings = ctx->gprs->settings;
enum ofono_gprs_auth_method auth;
if (gprs_auth_method_from_string(str, &auth) == FALSE)
return __ofono_error_invalid_format(msg);
if (ctx->context.auth_method == auth)
return dbus_message_new_method_return(msg);
ctx->context.auth_method = auth;
if (settings) {
g_key_file_set_string(settings, ctx->key,
"AuthenticationMethod", str);
storage_sync(ctx->gprs->imsi, SETTINGS_STORE, settings);
}
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"AuthenticationMethod",
DBUS_TYPE_STRING, &str);
return NULL;
}
static DBusMessage *pri_set_property(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct pri_context *ctx = data;
DBusMessageIter iter;
DBusMessageIter var;
const char *property;
dbus_bool_t value;
const char *str;
if (!dbus_message_iter_init(msg, &iter))
return __ofono_error_invalid_args(msg);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&iter, &property);
dbus_message_iter_next(&iter);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
return __ofono_error_invalid_args(msg);
dbus_message_iter_recurse(&iter, &var);
if (g_str_equal(property, "Active")) {
struct ofono_gprs_context *gc;
if (ctx->gprs->pending)
return __ofono_error_busy(msg);
if (ctx->pending)
return __ofono_error_busy(msg);
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_BOOLEAN)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &value);
if (ctx->active == (ofono_bool_t) value)
return dbus_message_new_method_return(msg);
if (value && !ctx->gprs->attached)
return __ofono_error_not_attached(msg);
if (ctx->gprs->flags & GPRS_FLAG_ATTACHING)
return __ofono_error_attach_in_progress(msg);
if (value && assign_context(ctx) == FALSE)
return __ofono_error_not_implemented(msg);
gc = ctx->context_driver;
ctx->pending = dbus_message_ref(msg);
if (value)
gc->driver->activate_primary(gc, &ctx->context,
pri_activate_callback, ctx);
else
gc->driver->deactivate_primary(gc, ctx->context.cid,
pri_deactivate_callback, ctx);
return NULL;
}
if (!strcmp(property, "Preferred")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_BOOLEAN)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &value);
return pri_set_preferred(ctx, conn, msg, value);
}
/* All other properties are read-only when context is active */
if (ctx->active == TRUE)
return __ofono_error_in_use(msg);
if (!strcmp(property, "AccessPointName")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &str);
return pri_set_apn(ctx, conn, msg, str);
} else if (!strcmp(property, "Type")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &str);
return pri_set_type(ctx, conn, msg, str);
} else if (!strcmp(property, "Protocol")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &str);
return pri_set_proto(ctx, conn, msg, str);
} else if (!strcmp(property, "Username")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &str);
return pri_set_username(ctx, conn, msg, str);
} else if (!strcmp(property, "Password")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &str);
return pri_set_password(ctx, conn, msg, str);
} else if (!strcmp(property, "Name")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &str);
return pri_set_name(ctx, conn, msg, str);
} else if (!strcmp(property, "AuthenticationMethod")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &str);
return pri_set_auth_method(ctx, conn, msg, str);
}
if (ctx->type == OFONO_GPRS_CONTEXT_TYPE_ANY ||
ctx->type == OFONO_GPRS_CONTEXT_TYPE_WAP ||
ctx->type == OFONO_GPRS_CONTEXT_TYPE_IMS ||
ctx->type == OFONO_GPRS_CONTEXT_TYPE_IA)
return __ofono_error_invalid_args(msg);
if (!strcmp(property, "MessageProxy")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &str);
return pri_set_message_proxy(ctx, conn, msg, str);
} else if (!strcmp(property, "MessageCenter")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &str);
return pri_set_message_center(ctx, conn, msg, str);
}
return __ofono_error_invalid_args(msg);
}
static const GDBusMethodTable context_methods[] = {
{ GDBUS_METHOD("GetProperties",
NULL, GDBUS_ARGS({ "properties", "a{sv}" }),
pri_get_properties) },
{ GDBUS_ASYNC_METHOD("SetProperty",
GDBUS_ARGS({ "property", "s" }, { "value", "v" }),
NULL, pri_set_property) },
{ }
};
static const GDBusSignalTable context_signals[] = {
{ GDBUS_SIGNAL("PropertyChanged",
GDBUS_ARGS({ "name", "s" }, { "value", "v" })) },
{ }
};
static struct pri_context *pri_context_create(struct ofono_gprs *gprs,
const char *name,
enum ofono_gprs_context_type type)
{
struct pri_context *context = g_try_new0(struct pri_context, 1);
if (context == NULL)
return NULL;
if (name == NULL) {
name = gprs_context_default_name(type);
if (name == NULL) {
g_free(context);
return NULL;
}
}
context->gprs = gprs;
strcpy(context->name, name);
context->type = type;
return context;
}
static void pri_context_destroy(gpointer userdata)
{
struct pri_context *ctx = userdata;
g_free(ctx->proxy_host);
g_free(ctx->path);
g_free(ctx);
}
static gboolean context_dbus_register(struct pri_context *ctx)
{
DBusConnection *conn = ofono_dbus_get_connection();
char path[256];
const char *basepath;
basepath = __ofono_atom_get_path(ctx->gprs->atom);
snprintf(path, sizeof(path), "%s/context%u", basepath, ctx->id);
if (!g_dbus_register_interface(conn, path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
context_methods, context_signals,
NULL, ctx, pri_context_destroy)) {
ofono_error("Could not register PrimaryContext %s", path);
idmap_put(ctx->gprs->pid_map, ctx->id);
pri_context_destroy(ctx);
return FALSE;
}
ctx->path = g_strdup(path);
ctx->key = ctx->path + strlen(basepath) + 1;
return TRUE;
}
static gboolean context_dbus_unregister(struct pri_context *ctx)
{
DBusConnection *conn = ofono_dbus_get_connection();
char path[256];
if (ctx->active == TRUE) {
const char *interface =
ctx->context_driver->settings->interface;
if (ctx->type == OFONO_GPRS_CONTEXT_TYPE_MMS)
pri_set_ipv4_addr(interface, NULL);
pri_ifupdown(interface, FALSE);
}
strcpy(path, ctx->path);
idmap_put(ctx->gprs->pid_map, ctx->id);
return g_dbus_unregister_interface(conn, path,
OFONO_CONNECTION_CONTEXT_INTERFACE);
}
static void update_suspended_property(struct ofono_gprs *gprs,
ofono_bool_t suspended)
{
DBusConnection *conn = ofono_dbus_get_connection();
const char *path = __ofono_atom_get_path(gprs->atom);
dbus_bool_t value = suspended;
if (gprs->suspend_timeout) {
g_source_remove(gprs->suspend_timeout);
gprs->suspend_timeout = 0;
}
if (gprs->suspended == suspended)
return;
DBG("%s GPRS service %s", __ofono_atom_get_path(gprs->atom),
suspended ? "suspended" : "resumed");
gprs->suspended = suspended;
if (gprs->attached)
ofono_dbus_signal_property_changed(conn, path,
OFONO_CONNECTION_MANAGER_INTERFACE,
"Suspended", DBUS_TYPE_BOOLEAN, &value);
}
static gboolean suspend_timeout(gpointer data)
{
struct ofono_gprs *gprs = data;
gprs->suspend_timeout = 0;
update_suspended_property(gprs, TRUE);
return FALSE;
}
void ofono_gprs_suspend_notify(struct ofono_gprs *gprs, int cause)
{
switch (cause) {
case GPRS_SUSPENDED_DETACHED:
case GPRS_SUSPENDED_CALL:
case GPRS_SUSPENDED_NO_COVERAGE:
update_suspended_property(gprs, TRUE);
break;
case GPRS_SUSPENDED_SIGNALLING:
case GPRS_SUSPENDED_UNKNOWN_CAUSE:
if (gprs->suspend_timeout)
g_source_remove(gprs->suspend_timeout);
gprs->suspend_timeout = g_timeout_add_seconds(SUSPEND_TIMEOUT,
suspend_timeout,
gprs);
break;
}
}
void ofono_gprs_resume_notify(struct ofono_gprs *gprs)
{
update_suspended_property(gprs, FALSE);
}
static gboolean have_active_contexts(struct ofono_gprs *gprs)
{
GSList *l;
struct pri_context *ctx;
for (l = gprs->contexts; l; l = l->next) {
ctx = l->data;
if (ctx->active == TRUE)
return TRUE;
}
return FALSE;
}
static void release_active_contexts(struct ofono_gprs *gprs)
{
GSList *l;
struct pri_context *ctx;
for (l = gprs->contexts; l; l = l->next) {
struct ofono_gprs_context *gc;
ctx = l->data;
if (ctx->active == FALSE)
continue;
/* This context is already being messed with */
if (ctx->pending)
continue;
gc = ctx->context_driver;
if (gc->driver->detach_shutdown != NULL)
gc->driver->detach_shutdown(gc, ctx->context.cid);
}
}
static void gprs_attached_update(struct ofono_gprs *gprs)
{
DBusConnection *conn = ofono_dbus_get_connection();
const char *path;
ofono_bool_t attached;
dbus_bool_t value;
attached = gprs->driver_attached &&
(gprs->status == NETWORK_REGISTRATION_STATUS_REGISTERED ||
gprs->status == NETWORK_REGISTRATION_STATUS_ROAMING);
if (attached == gprs->attached)
return;
/*
* If an active context is found, a PPP session might be still active
* at driver level. "Attached" = TRUE property can't be signalled to
* the applications registered on GPRS properties.
* Active contexts have to be release at driver level.
*/
if (attached == FALSE) {
release_active_contexts(gprs);
gprs->bearer = -1;
} else if (have_active_contexts(gprs) == TRUE) {
gprs->flags |= GPRS_FLAG_ATTACHED_UPDATE;
return;
}
gprs->attached = attached;
path = __ofono_atom_get_path(gprs->atom);
value = attached;
ofono_dbus_signal_property_changed(conn, path,
OFONO_CONNECTION_MANAGER_INTERFACE,
"Attached", DBUS_TYPE_BOOLEAN, &value);
}
static void registration_status_cb(const struct ofono_error *error,
int status, void *data)
{
struct ofono_gprs *gprs = data;
DBG("%s error %d status %d", __ofono_atom_get_path(gprs->atom),
error->type, status);
gprs->flags &= ~GPRS_FLAG_ATTACHING;
if (error->type == OFONO_ERROR_TYPE_NO_ERROR)
ofono_gprs_status_notify(gprs, status);
else
gprs_attached_update(gprs);
if (gprs->flags & GPRS_FLAG_RECHECK) {
gprs->flags &= ~GPRS_FLAG_RECHECK;
gprs_netreg_update(gprs);
}
}
static void gprs_attach_callback(const struct ofono_error *error, void *data)
{
struct ofono_gprs *gprs = data;
DBG("%s error = %d", __ofono_atom_get_path(gprs->atom), error->type);
if (error->type != OFONO_ERROR_TYPE_NO_ERROR)
gprs->driver_attached = !gprs->driver_attached;
if (gprs->driver->attached_status == NULL) {
struct ofono_error status_error;
status_error.type = OFONO_ERROR_TYPE_FAILURE;
status_error.error = 0;
registration_status_cb(&status_error, -1, gprs);
return;
}
gprs->driver->attached_status(gprs, registration_status_cb, gprs);
}
static void gprs_netreg_removed(struct ofono_gprs *gprs)
{
gprs->netreg = NULL;
gprs->flags &= ~(GPRS_FLAG_RECHECK | GPRS_FLAG_ATTACHING);
gprs->status_watch = 0;
gprs->netreg_status = NETWORK_REGISTRATION_STATUS_NOT_REGISTERED;
gprs->driver_attached = FALSE;
gprs_attached_update(gprs);
}
static void gprs_netreg_update(struct ofono_gprs *gprs)
{
ofono_bool_t attach;
attach = gprs->netreg_status == NETWORK_REGISTRATION_STATUS_REGISTERED;
attach = attach || (gprs->roaming_allowed &&
gprs->netreg_status == NETWORK_REGISTRATION_STATUS_ROAMING);
attach = attach && gprs->powered;
DBG("attach: %u, driver_attached: %u", attach, gprs->driver_attached);
if (gprs->driver_attached == attach)
return;
if (gprs->flags & GPRS_FLAG_ATTACHING) {
gprs->flags |= GPRS_FLAG_RECHECK;
return;
}
gprs->flags |= GPRS_FLAG_ATTACHING;
gprs->driver->set_attached(gprs, attach, gprs_attach_callback, gprs);
gprs->driver_attached = attach;
}
static void netreg_status_changed(int status, int lac, int ci, int tech,
const char *mcc, const char *mnc,
void *data)
{
struct ofono_gprs *gprs = data;
DBG("%d", status);
gprs->netreg_status = status;
gprs_netreg_update(gprs);
}
static void notify_connection_powered(struct ofono_modem *modem, void *data)
{
struct ofono_atom *atom;
struct ofono_gprs *gprs;
struct ofono_modem *modem_notif = data;
DBusConnection *conn;
const char *path = ofono_modem_get_path(modem);
if (strcmp(path, ofono_modem_get_path(modem_notif)) == 0)
return;
if (!ofono_modem_is_standby(modem))
return;
atom = __ofono_modem_find_atom(modem, OFONO_ATOM_TYPE_GPRS);
if (atom == NULL)
return;
gprs = __ofono_atom_get_data(atom);
if (gprs->driver->set_attached == NULL)
return;
if (gprs->powered == FALSE)
return;
gprs->powered = FALSE;
if (gprs->settings) {
g_key_file_set_integer(gprs->settings, SETTINGS_GROUP,
"Powered", gprs->powered);
storage_sync(gprs->imsi, SETTINGS_STORE, gprs->settings);
}
gprs_netreg_update(gprs);
conn = ofono_dbus_get_connection();
ofono_dbus_signal_property_changed(conn, path,
OFONO_CONNECTION_MANAGER_INTERFACE,
"Powered", DBUS_TYPE_BOOLEAN,
&gprs->powered);
}
static void notify_powered_change(struct ofono_gprs *gprs)
{
if (gprs->powered) {
struct ofono_modem *modem = __ofono_atom_get_modem(gprs->atom);
__ofono_modem_foreach(notify_connection_powered, modem);
}
}
static DBusMessage *gprs_get_properties(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct ofono_gprs *gprs = data;
DBusMessage *reply;
DBusMessageIter iter;
DBusMessageIter dict;
dbus_bool_t value;
reply = dbus_message_new_method_return(msg);
if (reply == NULL)
return NULL;
dbus_message_iter_init_append(reply, &iter);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
OFONO_PROPERTIES_ARRAY_SIGNATURE,
&dict);
value = gprs->attached;
ofono_dbus_dict_append(&dict, "Attached", DBUS_TYPE_BOOLEAN, &value);
if (gprs->bearer != -1) {
const char *bearer = packet_bearer_to_string(gprs->bearer);
ofono_dbus_dict_append(&dict, "Bearer",
DBUS_TYPE_STRING, &bearer);
}
value = gprs->roaming_allowed;
ofono_dbus_dict_append(&dict, "RoamingAllowed",
DBUS_TYPE_BOOLEAN, &value);
value = gprs->powered;
ofono_dbus_dict_append(&dict, "Powered", DBUS_TYPE_BOOLEAN, &value);
if (gprs->attached) {
value = gprs->suspended;
ofono_dbus_dict_append(&dict, "Suspended",
DBUS_TYPE_BOOLEAN, &value);
}
dbus_message_iter_close_container(&iter, &dict);
return reply;
}
static DBusMessage *gprs_set_property(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct ofono_gprs *gprs = data;
DBusMessageIter iter;
DBusMessageIter var;
const char *property;
dbus_bool_t value;
const char *path;
if (gprs->pending)
return __ofono_error_busy(msg);
if (!dbus_message_iter_init(msg, &iter))
return __ofono_error_invalid_args(msg);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&iter, &property);
dbus_message_iter_next(&iter);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
return __ofono_error_invalid_args(msg);
dbus_message_iter_recurse(&iter, &var);
if (!strcmp(property, "RoamingAllowed")) {
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_BOOLEAN)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &value);
if (gprs->roaming_allowed == (ofono_bool_t) value)
return dbus_message_new_method_return(msg);
gprs->roaming_allowed = value;
if (gprs->settings) {
g_key_file_set_integer(gprs->settings, SETTINGS_GROUP,
"RoamingAllowed",
gprs->roaming_allowed);
storage_sync(gprs->imsi, SETTINGS_STORE,
gprs->settings);
}
gprs_netreg_update(gprs);
} else if (!strcmp(property, "Powered")) {
if (gprs->driver->set_attached == NULL)
return __ofono_error_not_implemented(msg);
if (dbus_message_iter_get_arg_type(&var) != DBUS_TYPE_BOOLEAN)
return __ofono_error_invalid_args(msg);
dbus_message_iter_get_basic(&var, &value);
if (gprs->powered == (ofono_bool_t) value)
return dbus_message_new_method_return(msg);
gprs->powered = value;
if (gprs->settings) {
g_key_file_set_integer(gprs->settings, SETTINGS_GROUP,
"Powered", gprs->powered);
storage_sync(gprs->imsi, SETTINGS_STORE,
gprs->settings);
}
gprs_netreg_update(gprs);
notify_powered_change(gprs);
} else {
return __ofono_error_invalid_args(msg);
}
path = __ofono_atom_get_path(gprs->atom);
ofono_dbus_signal_property_changed(conn, path,
OFONO_CONNECTION_MANAGER_INTERFACE,
property, DBUS_TYPE_BOOLEAN, &value);
return dbus_message_new_method_return(msg);
}
static void write_context_settings(struct ofono_gprs *gprs,
struct pri_context *context)
{
const char *auth_method;
g_key_file_set_string(gprs->settings, context->key,
"Name", context->name);
g_key_file_set_string(gprs->settings, context->key,
"AccessPointName", context->context.apn);
g_key_file_set_string(gprs->settings, context->key,
"Username", context->context.username);
g_key_file_set_string(gprs->settings, context->key,
"Password", context->context.password);
auth_method = gprs_auth_method_to_string(context->context.auth_method);
g_key_file_set_string(gprs->settings, context->key,
"AuthenticationMethod", auth_method);
g_key_file_set_string(gprs->settings, context->key, "Type",
gprs_context_type_to_string(context->type));
g_key_file_set_string(gprs->settings, context->key, "Protocol",
gprs_proto_to_string(context->context.proto));
g_key_file_set_boolean(gprs->settings, context->key, "Preferred",
context->preferred);
if (context->type == OFONO_GPRS_CONTEXT_TYPE_MMS ||
(context->message_center && strlen(context->message_center) > 0)) {
g_key_file_set_string(gprs->settings, context->key,
"MessageProxy",
context->message_proxy);
g_key_file_set_string(gprs->settings, context->key,
"MessageCenter",
context->message_center);
}
}
static struct pri_context *add_context(struct ofono_gprs *gprs,
const char *name,
enum ofono_gprs_context_type type)
{
unsigned int id;
struct pri_context *context;
if (gprs->last_context_id)
id = idmap_alloc_next(gprs->pid_map, gprs->last_context_id);
else
id = idmap_alloc(gprs->pid_map);
if (id > idmap_get_max(gprs->pid_map))
return NULL;
context = pri_context_create(gprs, name, type);
if (context == NULL) {
idmap_put(gprs->pid_map, id);
ofono_error("Unable to allocate context struct");
return NULL;
}
context->id = id;
DBG("Registering new context");
if (!context_dbus_register(context)) {
ofono_error("Unable to register primary context");
return NULL;
}
gprs->last_context_id = id;
if (gprs->settings) {
write_context_settings(gprs, context);
storage_sync(gprs->imsi, SETTINGS_STORE, gprs->settings);
}
gprs->contexts = g_slist_append(gprs->contexts, context);
return context;
}
static void send_context_added_signal(struct ofono_gprs *gprs,
struct pri_context *context,
DBusConnection *conn)
{
const char *path;
DBusMessage *signal;
DBusMessageIter iter;
DBusMessageIter dict;
path = __ofono_atom_get_path(gprs->atom);
signal = dbus_message_new_signal(path,
OFONO_CONNECTION_MANAGER_INTERFACE,
"ContextAdded");
if (!signal)
return;
dbus_message_iter_init_append(signal, &iter);
path = context->path;
dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &path);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
OFONO_PROPERTIES_ARRAY_SIGNATURE,
&dict);
append_context_properties(context, &dict);
dbus_message_iter_close_container(&iter, &dict);
g_dbus_send_message(conn, signal);
}
static DBusMessage *gprs_add_context(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct ofono_gprs *gprs = data;
struct pri_context *context;
const char *typestr;
const char *name;
const char *path;
enum ofono_gprs_context_type type;
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &typestr,
DBUS_TYPE_INVALID))
return __ofono_error_invalid_args(msg);
if (gprs_context_string_to_type(typestr, &type) == FALSE)
return __ofono_error_invalid_format(msg);
name = gprs_context_default_name(type);
if (name == NULL)
name = typestr;
context = add_context(gprs, name, type);
if (context == NULL)
return __ofono_error_failed(msg);
path = context->path;
g_dbus_send_reply(conn, msg, DBUS_TYPE_OBJECT_PATH, &path,
DBUS_TYPE_INVALID);
send_context_added_signal(gprs, context, conn);
return NULL;
}
static void gprs_deactivate_for_remove(const struct ofono_error *error,
void *data)
{
struct pri_context *ctx = data;
struct ofono_gprs *gprs = ctx->gprs;
DBusConnection *conn = ofono_dbus_get_connection();
char *path;
const char *atompath;
dbus_bool_t value;
if (error->type != OFONO_ERROR_TYPE_NO_ERROR) {
DBG("Removing context failed with error: %s",
telephony_error_to_str(error));
__ofono_dbus_pending_reply(&gprs->pending,
__ofono_error_failed(gprs->pending));
return;
}
pri_reset_context_settings(ctx);
release_context(ctx);
value = FALSE;
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Active", DBUS_TYPE_BOOLEAN, &value);
if (gprs->settings) {
g_key_file_remove_group(gprs->settings, ctx->key, NULL);
storage_sync(gprs->imsi, SETTINGS_STORE, gprs->settings);
}
/* Make a backup copy of path for signal emission below */
path = g_strdup(ctx->path);
context_dbus_unregister(ctx);
gprs->contexts = g_slist_remove(gprs->contexts, ctx);
__ofono_dbus_pending_reply(&gprs->pending,
dbus_message_new_method_return(gprs->pending));
atompath = __ofono_atom_get_path(gprs->atom);
g_dbus_emit_signal(conn, atompath, OFONO_CONNECTION_MANAGER_INTERFACE,
"ContextRemoved", DBUS_TYPE_OBJECT_PATH, &path,
DBUS_TYPE_INVALID);
g_free(path);
}
static DBusMessage *gprs_remove_context(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct ofono_gprs *gprs = data;
struct pri_context *ctx;
const char *path;
const char *atompath;
if (gprs->pending)
return __ofono_error_busy(msg);
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
DBUS_TYPE_INVALID))
return __ofono_error_invalid_args(msg);
if (path[0] == '\0')
return __ofono_error_invalid_format(msg);
ctx = gprs_context_by_path(gprs, path);
if (ctx == NULL)
return __ofono_error_not_found(msg);
if (ctx->active) {
struct ofono_gprs_context *gc = ctx->context_driver;
/* This context is already being messed with */
if (ctx->pending)
return __ofono_error_busy(msg);
gprs->pending = dbus_message_ref(msg);
gc->driver->deactivate_primary(gc, ctx->context.cid,
gprs_deactivate_for_remove, ctx);
return NULL;
}
if (gprs->settings) {
g_key_file_remove_group(gprs->settings, ctx->key, NULL);
storage_sync(gprs->imsi, SETTINGS_STORE, gprs->settings);
}
DBG("Unregistering context: %s", ctx->path);
context_dbus_unregister(ctx);
gprs->contexts = g_slist_remove(gprs->contexts, ctx);
g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
atompath = __ofono_atom_get_path(gprs->atom);
g_dbus_emit_signal(conn, atompath, OFONO_CONNECTION_MANAGER_INTERFACE,
"ContextRemoved", DBUS_TYPE_OBJECT_PATH, &path,
DBUS_TYPE_INVALID);
return NULL;
}
static void gprs_deactivate_for_all(const struct ofono_error *error,
void *data)
{
struct pri_context *ctx = data;
struct ofono_gprs *gprs = ctx->gprs;
DBusConnection *conn;
dbus_bool_t value;
if (error->type != OFONO_ERROR_TYPE_NO_ERROR) {
__ofono_dbus_pending_reply(&gprs->pending,
__ofono_error_failed(gprs->pending));
return;
}
pri_reset_context_settings(ctx);
release_context(ctx);
value = ctx->active;
conn = ofono_dbus_get_connection();
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Active", DBUS_TYPE_BOOLEAN, &value);
gprs_deactivate_next(gprs);
}
static void gprs_deactivate_next(struct ofono_gprs *gprs)
{
GSList *l;
struct pri_context *ctx;
struct ofono_gprs_context *gc;
for (l = gprs->contexts; l; l = l->next) {
ctx = l->data;
if (ctx->active == FALSE)
continue;
gc = ctx->context_driver;
gc->driver->deactivate_primary(gc, ctx->context.cid,
gprs_deactivate_for_all, ctx);
return;
}
__ofono_dbus_pending_reply(&gprs->pending,
dbus_message_new_method_return(gprs->pending));
}
static DBusMessage *gprs_deactivate_all(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct ofono_gprs *gprs = data;
GSList *l;
struct pri_context *ctx;
if (gprs->pending)
return __ofono_error_busy(msg);
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_INVALID))
return __ofono_error_invalid_args(msg);
for (l = gprs->contexts; l; l = l->next) {
ctx = l->data;
if (ctx->pending)
return __ofono_error_busy(msg);
}
gprs->pending = dbus_message_ref(msg);
gprs_deactivate_next(gprs);
return NULL;
}
static DBusMessage *gprs_get_contexts(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct ofono_gprs *gprs = data;
DBusMessage *reply;
DBusMessageIter iter;
DBusMessageIter array;
DBusMessageIter entry, dict;
const char *path;
GSList *l;
struct pri_context *ctx;
reply = dbus_message_new_method_return(msg);
if (reply == NULL)
return NULL;
dbus_message_iter_init_append(reply, &iter);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
DBUS_STRUCT_BEGIN_CHAR_AS_STRING
DBUS_TYPE_OBJECT_PATH_AS_STRING
DBUS_TYPE_ARRAY_AS_STRING
DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
DBUS_TYPE_STRING_AS_STRING
DBUS_TYPE_VARIANT_AS_STRING
DBUS_DICT_ENTRY_END_CHAR_AS_STRING
DBUS_STRUCT_END_CHAR_AS_STRING,
&array);
for (l = gprs->contexts; l; l = l->next) {
ctx = l->data;
path = ctx->path;
dbus_message_iter_open_container(&array, DBUS_TYPE_STRUCT,
NULL, &entry);
dbus_message_iter_append_basic(&entry, DBUS_TYPE_OBJECT_PATH,
&path);
dbus_message_iter_open_container(&entry, DBUS_TYPE_ARRAY,
OFONO_PROPERTIES_ARRAY_SIGNATURE,
&dict);
append_context_properties(ctx, &dict);
dbus_message_iter_close_container(&entry, &dict);
dbus_message_iter_close_container(&array, &entry);
}
dbus_message_iter_close_container(&iter, &array);
return reply;
}
static void provision_context(const struct ofono_gprs_provision_data *ap,
struct ofono_gprs *gprs)
{
unsigned int id;
struct pri_context *context = NULL;
/* Sanity check */
if (ap == NULL)
return;
if (ap->name && strlen(ap->name) > MAX_CONTEXT_NAME_LENGTH)
return;
if (ap->apn == NULL || strlen(ap->apn) > OFONO_GPRS_MAX_APN_LENGTH)
return;
if (is_valid_apn(ap->apn) == FALSE)
return;
if (ap->username &&
strlen(ap->username) > OFONO_GPRS_MAX_USERNAME_LENGTH)
return;
if (ap->password &&
strlen(ap->password) > OFONO_GPRS_MAX_PASSWORD_LENGTH)
return;
if (ap->message_proxy &&
strlen(ap->message_proxy) > MAX_MESSAGE_PROXY_LENGTH)
return;
if (ap->message_center &&
strlen(ap->message_center) > MAX_MESSAGE_CENTER_LENGTH)
return;
if (gprs->last_context_id)
id = idmap_alloc_next(gprs->pid_map, gprs->last_context_id);
else
id = idmap_alloc(gprs->pid_map);
if (id > idmap_get_max(gprs->pid_map))
return;
context = pri_context_create(gprs, ap->name, ap->type);
if (context == NULL) {
idmap_put(gprs->pid_map, id);
return;
}
context->id = id;
if (ap->username != NULL)
strcpy(context->context.username, ap->username);
if (ap->password != NULL)
strcpy(context->context.password, ap->password);
context->context.auth_method = ap->auth_method;
strcpy(context->context.apn, ap->apn);
context->context.proto = ap->proto;
if (ap->type == OFONO_GPRS_CONTEXT_TYPE_MMS ||
ap->type == OFONO_GPRS_CONTEXT_TYPE_INTERNET) {
if (ap->message_proxy != NULL)
strcpy(context->message_proxy, ap->message_proxy);
if (ap->message_center != NULL)
strcpy(context->message_center, ap->message_center);
}
if (context_dbus_register(context) == FALSE)
return;
gprs->last_context_id = id;
if (gprs->settings) {
write_context_settings(gprs, context);
storage_sync(gprs->imsi, SETTINGS_STORE, gprs->settings);
}
gprs->contexts = g_slist_append(gprs->contexts, context);
}
static void provision_contexts(struct ofono_gprs *gprs, const char *mcc,
const char *mnc, const char *spn,
const char *gid1)
{
struct ofono_gprs_provision_data *settings;
int count;
int i;
if (__ofono_gprs_provision_get_settings(mcc, mnc, spn, gprs->imsi, gid1,
&settings, &count) == FALSE) {
ofono_warn("Provisioning failed");
return;
}
for (i = 0; i < count; i++)
provision_context(&settings[i], gprs);
__ofono_gprs_provision_free_settings(settings, count);
}
static void remove_non_active_context(struct ofono_gprs *gprs,
struct pri_context *ctx, DBusConnection *conn)
{
char *path;
const char *atompath;
if (gprs->settings) {
g_key_file_remove_group(gprs->settings, ctx->key, NULL);
storage_sync(gprs->imsi, SETTINGS_STORE, gprs->settings);
}
/* Make a backup copy of path for signal emission below */
path = g_strdup(ctx->path);
context_dbus_unregister(ctx);
gprs->contexts = g_slist_remove(gprs->contexts, ctx);
atompath = __ofono_atom_get_path(gprs->atom);
g_dbus_emit_signal(conn, atompath, OFONO_CONNECTION_MANAGER_INTERFACE,
"ContextRemoved", DBUS_TYPE_OBJECT_PATH, &path,
DBUS_TYPE_INVALID);
g_free(path);
}
static DBusMessage *gprs_reset_contexts(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct ofono_gprs *gprs = data;
DBusMessage *reply;
GSList *l;
if (gprs->pending)
return __ofono_error_busy(msg);
/*
* We want __ofono_error_busy to take precedence over
* __ofono_error_not_allowed errors, so we check it first.
*/
for (l = gprs->contexts; l; l = l->next) {
struct pri_context *ctx = l->data;
if (ctx->pending)
return __ofono_error_busy(msg);
}
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_INVALID))
return __ofono_error_invalid_args(msg);
if (gprs->powered)
return __ofono_error_not_allowed(msg);
for (l = gprs->contexts; l; l = l->next) {
struct pri_context *ctx = l->data;
if (ctx->active)
return __ofono_error_not_allowed(msg);
}
reply = dbus_message_new_method_return(msg);
if (reply == NULL)
return NULL;
/* Remove first the current contexts, re-provision after */
while (gprs->contexts != NULL) {
struct pri_context *ctx = gprs->contexts->data;
remove_non_active_context(gprs, ctx, conn);
}
gprs->last_context_id = 0;
provision_contexts(gprs, ofono_sim_get_mcc(gprs->sim),
ofono_sim_get_mnc(gprs->sim),
ofono_sim_get_spn(gprs->sim), gprs->gid1);
if (gprs->contexts == NULL) /* Automatic provisioning failed */
add_context(gprs, NULL, OFONO_GPRS_CONTEXT_TYPE_INTERNET);
for (l = gprs->contexts; l; l = l->next) {
struct pri_context *ctx = l->data;
send_context_added_signal(gprs, ctx, conn);
}
return reply;
}
static const GDBusMethodTable manager_methods[] = {
{ GDBUS_METHOD("GetProperties",
NULL, GDBUS_ARGS({ "properties", "a{sv}" }),
gprs_get_properties) },
{ GDBUS_METHOD("SetProperty",
GDBUS_ARGS({ "property", "s" }, { "value", "v" }),
NULL, gprs_set_property) },
{ GDBUS_ASYNC_METHOD("AddContext",
GDBUS_ARGS({ "type", "s" }),
GDBUS_ARGS({ "path", "o" }),
gprs_add_context) },
{ GDBUS_ASYNC_METHOD("RemoveContext",
GDBUS_ARGS({ "path", "o" }), NULL,
gprs_remove_context) },
{ GDBUS_ASYNC_METHOD("DeactivateAll", NULL, NULL,
gprs_deactivate_all) },
{ GDBUS_METHOD("GetContexts", NULL,
GDBUS_ARGS({ "contexts_with_properties", "a(oa{sv})" }),
gprs_get_contexts) },
{ GDBUS_ASYNC_METHOD("ResetContexts", NULL, NULL,
gprs_reset_contexts) },
{ }
};
static const GDBusSignalTable manager_signals[] = {
{ GDBUS_SIGNAL("PropertyChanged",
GDBUS_ARGS({ "name", "s" }, { "value", "v" })) },
{ GDBUS_SIGNAL("ContextAdded",
GDBUS_ARGS({ "path", "o" }, { "properties", "v" })) },
{ GDBUS_SIGNAL("ContextRemoved", GDBUS_ARGS({ "path", "o" })) },
{ }
};
void ofono_gprs_detached_notify(struct ofono_gprs *gprs)
{
DBG("%s", __ofono_atom_get_path(gprs->atom));
gprs->driver_attached = FALSE;
gprs_attached_update(gprs);
/*
* TODO: The network forced a detach, we should wait for some time
* and try to re-attach. This might also be related to a suspend
* event while voicecall is active.
*/
}
void ofono_gprs_status_notify(struct ofono_gprs *gprs, int status)
{
DBG("%s status %d", __ofono_atom_get_path(gprs->atom), status);
if (status == NETWORK_REGISTRATION_STATUS_ROAMING &&
ofono_netreg_get_status(gprs->netreg) ==
NETWORK_REGISTRATION_STATUS_REGISTERED) {
DBG("MVNO: roaming -> registered");
status = NETWORK_REGISTRATION_STATUS_REGISTERED;
}
gprs->status = status;
if (status != NETWORK_REGISTRATION_STATUS_REGISTERED &&
status != NETWORK_REGISTRATION_STATUS_ROAMING) {
gprs_attached_update(gprs);
return;
}
/*
* If we're already taking action, e.g. attaching or detaching, then
* ignore this notification for now, we will take appropriate action
* after the set_attach operation has completed
*/
if (gprs->flags & GPRS_FLAG_ATTACHING)
return;
/* We registered without being powered */
if (gprs->powered == FALSE)
goto detach;
if (gprs->roaming_allowed == FALSE &&
status == NETWORK_REGISTRATION_STATUS_ROAMING)
goto detach;
gprs->driver_attached = TRUE;
gprs_attached_update(gprs);
return;
detach:
gprs->flags |= GPRS_FLAG_ATTACHING;
gprs->driver->set_attached(gprs, FALSE, gprs_attach_callback, gprs);
}
void ofono_gprs_set_cid_range(struct ofono_gprs *gprs,
unsigned int min, unsigned int max)
{
if (gprs == NULL)
return;
if (gprs->cid_map)
idmap_free(gprs->cid_map);
gprs->cid_map = idmap_new_from_range(min, max);
}
static void gprs_context_unregister(struct ofono_atom *atom)
{
struct ofono_gprs_context *gc = __ofono_atom_get_data(atom);
DBusConnection *conn = ofono_dbus_get_connection();
GSList *l;
struct pri_context *ctx;
dbus_bool_t value;
DBG("%p, %p", gc, gc->gprs);
if (gc->gprs == NULL)
goto done;
for (l = gc->gprs->contexts; l; l = l->next) {
ctx = l->data;
if (ctx->context_driver != gc)
continue;
if (ctx->pending != NULL)
__ofono_dbus_pending_reply(&ctx->pending,
__ofono_error_failed(ctx->pending));
if (ctx->active == FALSE)
break;
pri_reset_context_settings(ctx);
release_context(ctx);
value = FALSE;
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Active", DBUS_TYPE_BOOLEAN, &value);
}
gc->gprs->context_drivers = g_slist_remove(gc->gprs->context_drivers,
gc);
gc->gprs = NULL;
done:
if (gc->settings) {
context_settings_free(gc->settings);
g_free(gc->settings);
gc->settings = NULL;
}
}
void ofono_gprs_add_context(struct ofono_gprs *gprs,
struct ofono_gprs_context *gc)
{
if (gc->driver == NULL)
return;
gc->gprs = gprs;
gc->settings = g_new0(struct context_settings, 1);
gprs->context_drivers = g_slist_append(gprs->context_drivers, gc);
__ofono_atom_register(gc->atom, gprs_context_unregister);
}
void ofono_gprs_bearer_notify(struct ofono_gprs *gprs, int bearer)
{
DBusConnection *conn = ofono_dbus_get_connection();
const char *path;
const char *value;
if (gprs->bearer == bearer)
return;
gprs->bearer = bearer;
path = __ofono_atom_get_path(gprs->atom);
value = packet_bearer_to_string(bearer);
ofono_dbus_signal_property_changed(conn, path,
OFONO_CONNECTION_MANAGER_INTERFACE,
"Bearer", DBUS_TYPE_STRING, &value);
}
void ofono_gprs_context_deactivated(struct ofono_gprs_context *gc,
unsigned int cid)
{
DBusConnection *conn = ofono_dbus_get_connection();
GSList *l;
struct pri_context *ctx;
dbus_bool_t value;
if (gc->gprs == NULL)
return;
for (l = gc->gprs->contexts; l; l = l->next) {
ctx = l->data;
if (ctx->context.cid != cid)
continue;
if (ctx->active == FALSE)
break;
pri_reset_context_settings(ctx);
release_context(ctx);
value = FALSE;
ofono_dbus_signal_property_changed(conn, ctx->path,
OFONO_CONNECTION_CONTEXT_INTERFACE,
"Active", DBUS_TYPE_BOOLEAN, &value);
}
/*
* If "Attached" property was about to be signalled as TRUE but there
* were still active contexts, try again to signal "Attached" property
* to registered applications after active contexts have been released.
*/
if (gc->gprs->flags & GPRS_FLAG_ATTACHED_UPDATE) {
gc->gprs->flags &= ~GPRS_FLAG_ATTACHED_UPDATE;
gprs_attached_update(gc->gprs);
}
}
int ofono_gprs_context_driver_register(
const struct ofono_gprs_context_driver *d)
{
DBG("driver: %p, name: %s", d, d->name);
if (d->probe == NULL)
return -EINVAL;
g_context_drivers = g_slist_prepend(g_context_drivers, (void *) d);
return 0;
}
void ofono_gprs_context_driver_unregister(
const struct ofono_gprs_context_driver *d)
{
DBG("driver: %p, name: %s", d, d->name);
g_context_drivers = g_slist_remove(g_context_drivers, (void *) d);
}
static void gprs_context_remove(struct ofono_atom *atom)
{
struct ofono_gprs_context *gc = __ofono_atom_get_data(atom);
DBG("atom: %p", atom);
if (gc == NULL)
return;
if (gc->driver && gc->driver->remove)
gc->driver->remove(gc);
g_free(gc);
}
struct ofono_gprs_context *ofono_gprs_context_create(struct ofono_modem *modem,
unsigned int vendor,
const char *driver, void *data)
{
struct ofono_gprs_context *gc;
GSList *l;
if (driver == NULL)
return NULL;
gc = g_try_new0(struct ofono_gprs_context, 1);
if (gc == NULL)
return NULL;
gc->type = OFONO_GPRS_CONTEXT_TYPE_ANY;
gc->atom = __ofono_modem_add_atom(modem, OFONO_ATOM_TYPE_GPRS_CONTEXT,
gprs_context_remove, gc);
for (l = g_context_drivers; l; l = l->next) {
const struct ofono_gprs_context_driver *drv = l->data;
if (g_strcmp0(drv->name, driver))
continue;
if (drv->probe(gc, vendor, data) < 0)
continue;
gc->driver = drv;
break;
}
return gc;
}
void ofono_gprs_context_remove(struct ofono_gprs_context *gc)
{
if (gc == NULL)
return;
__ofono_atom_free(gc->atom);
}
void ofono_gprs_context_set_data(struct ofono_gprs_context *gc, void *data)
{
gc->driver_data = data;
}
void *ofono_gprs_context_get_data(struct ofono_gprs_context *gc)
{
return gc->driver_data;
}
struct ofono_modem *ofono_gprs_context_get_modem(struct ofono_gprs_context *gc)
{
return __ofono_atom_get_modem(gc->atom);
}
void ofono_gprs_context_set_type(struct ofono_gprs_context *gc,
enum ofono_gprs_context_type type)
{
DBG("type %d", type);
gc->type = type;
}
void ofono_gprs_context_set_interface(struct ofono_gprs_context *gc,
const char *interface)
{
struct context_settings *settings = gc->settings;
g_free(settings->interface);
settings->interface = g_strdup(interface);
}
void ofono_gprs_context_set_ipv4_address(struct ofono_gprs_context *gc,
const char *address,
ofono_bool_t static_ip)
{
struct context_settings *settings = gc->settings;
if (settings->ipv4 == NULL)
return;
g_free(settings->ipv4->ip);
settings->ipv4->ip = g_strdup(address);
settings->ipv4->static_ip = static_ip;
}
void ofono_gprs_context_set_ipv4_netmask(struct ofono_gprs_context *gc,
const char *netmask)
{
struct context_settings *settings = gc->settings;
if (settings->ipv4 == NULL)
return;
g_free(settings->ipv4->netmask);
settings->ipv4->netmask = g_strdup(netmask);
}
void ofono_gprs_context_set_ipv4_gateway(struct ofono_gprs_context *gc,
const char *gateway)
{
struct context_settings *settings = gc->settings;
if (settings->ipv4 == NULL)
return;
g_free(settings->ipv4->gateway);
settings->ipv4->gateway = g_strdup(gateway);
}
void ofono_gprs_context_set_ipv4_dns_servers(struct ofono_gprs_context *gc,
const char **dns)
{
struct context_settings *settings = gc->settings;
if (settings->ipv4 == NULL)
return;
g_strfreev(settings->ipv4->dns);
settings->ipv4->dns = g_strdupv((char **) dns);
}
void ofono_gprs_context_set_ipv6_address(struct ofono_gprs_context *gc,
const char *address)
{
struct context_settings *settings = gc->settings;
if (settings->ipv6 == NULL)
return;
g_free(settings->ipv6->ip);
settings->ipv6->ip = g_strdup(address);
}
void ofono_gprs_context_set_ipv6_prefix_length(struct ofono_gprs_context *gc,
unsigned char length)
{
struct context_settings *settings = gc->settings;
if (settings->ipv6 == NULL)
return;
settings->ipv6->prefix_len = length;
}
void ofono_gprs_context_set_ipv6_gateway(struct ofono_gprs_context *gc,
const char *gateway)
{
struct context_settings *settings = gc->settings;
if (settings->ipv6 == NULL)
return;
g_free(settings->ipv6->gateway);
settings->ipv6->gateway = g_strdup(gateway);
}
void ofono_gprs_context_set_ipv6_dns_servers(struct ofono_gprs_context *gc,
const char **dns)
{
struct context_settings *settings = gc->settings;
if (settings->ipv6 == NULL)
return;
g_strfreev(settings->ipv6->dns);
settings->ipv6->dns = g_strdupv((char **) dns);
}
int ofono_gprs_driver_register(const struct ofono_gprs_driver *d)
{
DBG("driver: %p, name: %s", d, d->name);
if (d->probe == NULL)
return -EINVAL;
g_drivers = g_slist_prepend(g_drivers, (void *)d);
return 0;
}
void ofono_gprs_driver_unregister(const struct ofono_gprs_driver *d)
{
DBG("driver: %p, name: %s", d, d->name);
g_drivers = g_slist_remove(g_drivers, (void *)d);
}
static void free_contexts(struct ofono_gprs *gprs)
{
GSList *l;
if (gprs->settings) {
storage_close(gprs->imsi, SETTINGS_STORE,
gprs->settings, TRUE);
g_free(gprs->imsi);
gprs->imsi = NULL;
gprs->settings = NULL;
}
for (l = gprs->contexts; l; l = l->next) {
struct pri_context *context = l->data;
context_dbus_unregister(context);
}
g_slist_free(gprs->contexts);
}
static void gprs_unregister(struct ofono_atom *atom)
{
DBusConnection *conn = ofono_dbus_get_connection();
struct ofono_gprs *gprs = __ofono_atom_get_data(atom);
struct ofono_modem *modem = __ofono_atom_get_modem(atom);
const char *path = __ofono_atom_get_path(atom);
DBG("%p", gprs);
free_contexts(gprs);
if (gprs->cid_map) {
idmap_free(gprs->cid_map);
gprs->cid_map = NULL;
}
if (gprs->netreg_watch) {
if (gprs->status_watch) {
__ofono_netreg_remove_status_watch(gprs->netreg,
gprs->status_watch);
gprs->status_watch = 0;
}
__ofono_modem_remove_atom_watch(modem, gprs->netreg_watch);
gprs->netreg_watch = 0;
gprs->netreg = NULL;
}
if (gprs->spn_watch)
ofono_sim_remove_spn_watch(gprs->sim, &gprs->spn_watch);
if (gprs->sim_context) {
ofono_sim_context_free(gprs->sim_context);
gprs->sim_context = NULL;
}
ofono_modem_remove_interface(modem,
OFONO_CONNECTION_MANAGER_INTERFACE);
g_dbus_unregister_interface(conn, path,
OFONO_CONNECTION_MANAGER_INTERFACE);
}
static void gprs_remove(struct ofono_atom *atom)
{
struct ofono_gprs *gprs = __ofono_atom_get_data(atom);
GSList *l;
DBG("atom: %p", atom);
if (gprs == NULL)
return;
if (gprs->suspend_timeout)
g_source_remove(gprs->suspend_timeout);
if (gprs->pid_map) {
idmap_free(gprs->pid_map);
gprs->pid_map = NULL;
}
for (l = gprs->context_drivers; l; l = l->next) {
struct ofono_gprs_context *gc = l->data;
gc->gprs = NULL;
}
g_free(gprs->gid1);
g_slist_free(gprs->context_drivers);
if (gprs->driver && gprs->driver->remove)
gprs->driver->remove(gprs);
g_free(gprs);
}
struct ofono_gprs *ofono_gprs_create(struct ofono_modem *modem,
unsigned int vendor,
const char *driver, void *data)
{
struct ofono_gprs *gprs;
GSList *l;
if (driver == NULL)
return NULL;
gprs = g_try_new0(struct ofono_gprs, 1);
if (gprs == NULL)
return NULL;
gprs->atom = __ofono_modem_add_atom(modem, OFONO_ATOM_TYPE_GPRS,
gprs_remove, gprs);
for (l = g_drivers; l; l = l->next) {
const struct ofono_gprs_driver *drv = l->data;
if (g_strcmp0(drv->name, driver))
continue;
if (drv->probe(gprs, vendor, data) < 0)
continue;
gprs->driver = drv;
break;
}
gprs->status = NETWORK_REGISTRATION_STATUS_UNKNOWN;
gprs->netreg_status = NETWORK_REGISTRATION_STATUS_UNKNOWN;
gprs->pid_map = idmap_new(MAX_CONTEXTS);
return gprs;
}
static void netreg_watch(struct ofono_atom *atom,
enum ofono_atom_watch_condition cond,
void *data)
{
struct ofono_gprs *gprs = data;
if (cond == OFONO_ATOM_WATCH_CONDITION_UNREGISTERED) {
gprs_netreg_removed(gprs);
return;
}
gprs->netreg = __ofono_atom_get_data(atom);
gprs->netreg_status = ofono_netreg_get_status(gprs->netreg);
gprs->status_watch = __ofono_netreg_add_status_watch(gprs->netreg,
netreg_status_changed, gprs, NULL);
gprs_netreg_update(gprs);
}
static gboolean load_context(struct ofono_gprs *gprs, const char *group)
{
char *name = NULL;
char *typestr = NULL;
char *protostr = NULL;
char *username = NULL;
char *password = NULL;
char *apn = NULL;
char *msgproxy = NULL;
char *msgcenter = NULL;
char *authstr = NULL;
gboolean ret = FALSE;
gboolean legacy = FALSE;
gboolean preferred;
struct pri_context *context;
enum ofono_gprs_context_type type;
enum ofono_gprs_proto proto;
enum ofono_gprs_auth_method auth;
unsigned int id;
if (sscanf(group, "context%d", &id) != 1) {
if (sscanf(group, "primarycontext%d", &id) != 1)
goto error;
legacy = TRUE;
}
if (id < 1 || id > MAX_CONTEXTS)
goto error;
name = g_key_file_get_string(gprs->settings, group, "Name", NULL);
if (name == NULL)
goto error;
typestr = g_key_file_get_string(gprs->settings, group, "Type", NULL);
if (typestr == NULL)
goto error;
if (gprs_context_string_to_type(typestr, &type) == FALSE)
goto error;
protostr = g_key_file_get_string(gprs->settings, group,
"Protocol", NULL);
if (protostr == NULL)
protostr = g_strdup("ip");
if (gprs_proto_from_string(protostr, &proto) == FALSE)
goto error;
preferred = g_key_file_get_boolean(gprs->settings, group,
"Preferred", NULL);
username = g_key_file_get_string(gprs->settings, group,
"Username", NULL);
if (username == NULL)
goto error;
if (strlen(username) > OFONO_GPRS_MAX_USERNAME_LENGTH)
goto error;
password = g_key_file_get_string(gprs->settings, group,
"Password", NULL);
if (password == NULL)
goto error;
authstr = g_key_file_get_string(gprs->settings, group,
"AuthenticationMethod", NULL);
if (authstr == NULL)
authstr = g_strdup("chap");
if (gprs_auth_method_from_string(authstr, &auth) == FALSE)
goto error;
if (strlen(password) > OFONO_GPRS_MAX_PASSWORD_LENGTH)
goto error;
apn = g_key_file_get_string(gprs->settings, group,
"AccessPointName", NULL);
if (apn == NULL)
goto error;
if (strlen(apn) > OFONO_GPRS_MAX_APN_LENGTH)
goto error;
if (type == OFONO_GPRS_CONTEXT_TYPE_MMS ||
type == OFONO_GPRS_CONTEXT_TYPE_INTERNET) {
msgproxy = g_key_file_get_string(gprs->settings, group,
"MessageProxy", NULL);
msgcenter = g_key_file_get_string(gprs->settings, group,
"MessageCenter", NULL);
}
/*
* Accept empty (just created) APNs, but don't allow other
* invalid ones
*/
if (apn[0] != '\0' && is_valid_apn(apn) == FALSE)
goto error;
context = pri_context_create(gprs, name, type);
if (context == NULL)
goto error;
idmap_take(gprs->pid_map, id);
context->id = id;
strcpy(context->context.username, username);
strcpy(context->context.password, password);
strcpy(context->context.apn, apn);
context->context.proto = proto;
context->preferred = preferred;
context->context.auth_method = auth;
if (msgproxy != NULL)
strcpy(context->message_proxy, msgproxy);
if (msgcenter != NULL)
strcpy(context->message_center, msgcenter);
if (context_dbus_register(context) == FALSE)
goto error;
gprs->last_context_id = id;
gprs->contexts = g_slist_append(gprs->contexts, context);
ret = TRUE;
if (legacy) {
write_context_settings(gprs, context);
g_key_file_remove_group(gprs->settings, group, NULL);
}
error:
g_free(name);
g_free(typestr);
g_free(protostr);
g_free(username);
g_free(password);
g_free(apn);
g_free(msgproxy);
g_free(msgcenter);
g_free(authstr);
return ret;
}
static void gprs_load_settings(struct ofono_gprs *gprs, const char *imsi)
{
GError *error;
gboolean legacy = FALSE;
char **groups;
int i;
gprs->settings = storage_open(imsi, SETTINGS_STORE);
if (gprs->settings == NULL)
return;
gprs->imsi = g_strdup(imsi);
error = NULL;
gprs->powered = g_key_file_get_boolean(gprs->settings, SETTINGS_GROUP,
"Powered", &error);
/*
* If any error occurs, simply switch to defaults.
* Default to Powered = True
* and RoamingAllowed = False
*/
if (error) {
g_error_free(error);
gprs->powered = TRUE;
g_key_file_set_boolean(gprs->settings, SETTINGS_GROUP,
"Powered", gprs->powered);
}
notify_powered_change(gprs);
error = NULL;
gprs->roaming_allowed = g_key_file_get_boolean(gprs->settings,
SETTINGS_GROUP,
"RoamingAllowed",
&error);
if (error) {
g_error_free(error);
gprs->roaming_allowed = FALSE;
g_key_file_set_boolean(gprs->settings, SETTINGS_GROUP,
"RoamingAllowed",
gprs->roaming_allowed);
}
groups = g_key_file_get_groups(gprs->settings, NULL);
for (i = 0; groups[i]; i++) {
if (g_str_equal(groups[i], SETTINGS_GROUP))
continue;
if (!g_str_has_prefix(groups[i], "context")) {
if (!g_str_has_prefix(groups[i], "primarycontext"))
goto remove;
legacy = TRUE;
}
if (load_context(gprs, groups[i]) == TRUE)
continue;
remove:
g_key_file_remove_group(gprs->settings, groups[i], NULL);
}
g_strfreev(groups);
if (legacy)
storage_sync(imsi, SETTINGS_STORE, gprs->settings);
}
static struct pri_context *gprs_context_for_ia(struct ofono_gprs *gprs)
{
GSList *l;
struct pri_context *ctx_ia = NULL;
struct pri_context *ctx_inet_pref = NULL;
struct pri_context *ctx_inet = NULL;
struct pri_context *ctx_other_pref = NULL;
for (l = gprs->contexts; l; l = l->next) {
struct pri_context *ctx = l->data;
if (ctx->type == OFONO_GPRS_CONTEXT_TYPE_IA) {
if (ctx->preferred)
return ctx;
if (ctx_ia == NULL)
ctx_ia = ctx;
} else if (ctx->type == OFONO_GPRS_CONTEXT_TYPE_INTERNET) {
if (ctx->preferred && ctx_inet_pref == NULL)
ctx_inet_pref = ctx;
else if (ctx_inet == NULL)
ctx_inet = ctx;
} else if (ctx->preferred && ctx_other_pref == NULL) {
ctx_other_pref = ctx;
}
}
if (ctx_ia != NULL) {
set_preferred(ctx_ia, ofono_dbus_get_connection(), TRUE);
return ctx_ia;
}
if (ctx_inet_pref != NULL)
return ctx_inet_pref;
if (ctx_inet != NULL)
return ctx_inet;
if (ctx_other_pref != NULL)
return ctx_other_pref;
if (gprs->contexts == NULL)
return NULL;
return gprs->contexts->data;
}
static void set_ia_apn_cb(const struct ofono_error *error, void *data)
{
if (error->type != OFONO_ERROR_TYPE_NO_ERROR)
ofono_error("Could not set IA APN");
}
static void set_ia_apn(struct ofono_gprs *gprs)
{
struct pri_context *ctx = gprs_context_for_ia(gprs);
struct ofono_gprs_primary_context *ofono_ctx;
char mccmnc[OFONO_MAX_MCC_LENGTH + OFONO_MAX_MNC_LENGTH + 1];
const char *mcc = ofono_sim_get_mcc(gprs->sim);
const char *mnc = ofono_sim_get_mnc(gprs->sim);
if (ctx == NULL)
return;
ofono_ctx = &ctx->context;
strcpy(mccmnc, mcc);
strcpy(mccmnc + strlen(mcc), mnc);
gprs->driver->set_ia_apn(gprs, ofono_ctx->apn, ofono_ctx->proto,
ofono_ctx->username,
ofono_ctx->password, mccmnc,
set_ia_apn_cb, gprs);
}
static void ofono_gprs_finish_register(struct ofono_gprs *gprs)
{
DBusConnection *conn = ofono_dbus_get_connection();
struct ofono_modem *modem = __ofono_atom_get_modem(gprs->atom);
const char *path = __ofono_atom_get_path(gprs->atom);
if (gprs->contexts == NULL) /* Automatic provisioning failed */
add_context(gprs, NULL, OFONO_GPRS_CONTEXT_TYPE_INTERNET);
if (gprs->driver->set_ia_apn)
set_ia_apn(gprs);
if (!g_dbus_register_interface(conn, path,
OFONO_CONNECTION_MANAGER_INTERFACE,
manager_methods, manager_signals, NULL,
gprs, NULL)) {
ofono_error("Could not create %s interface",
OFONO_CONNECTION_MANAGER_INTERFACE);
free_contexts(gprs);
return;
}
ofono_modem_add_interface(modem,
OFONO_CONNECTION_MANAGER_INTERFACE);
gprs->netreg_watch = __ofono_modem_add_atom_watch(modem,
OFONO_ATOM_TYPE_NETREG,
netreg_watch, gprs, NULL);
__ofono_atom_register(gprs->atom, gprs_unregister);
}
static void sim_gid1_read_cb(int ok, int total_length, int record,
const unsigned char *data,
int record_length, void *userdata)
{
struct ofono_gprs *gprs = userdata;
if (ok) {
gprs->gid1 = encode_hex(data, record_length, '\0');
} else {
ofono_error("%s: error reading EF_GID1", __func__);
gprs->gid1 = NULL;
}
provision_contexts(gprs, ofono_sim_get_mcc(gprs->sim),
ofono_sim_get_mnc(gprs->sim),
ofono_sim_get_spn(gprs->sim), gprs->gid1);
ofono_gprs_finish_register(gprs);
}
static void spn_read_cb(const char *spn, const char *dc, void *data)
{
struct ofono_gprs *gprs = data;
ofono_sim_remove_spn_watch(gprs->sim, &gprs->spn_watch);
if (__ofono_sim_service_available(gprs->sim,
SIM_UST_SERVICE_GROUP_ID_LEVEL_1,
SIM_SST_SERVICE_GROUP_ID_LEVEL_1) == TRUE) {
DBG("GID1 file available");
ofono_sim_read(gprs->sim_context, SIM_EFGID1_FILEID,
OFONO_SIM_FILE_STRUCTURE_TRANSPARENT,
sim_gid1_read_cb, gprs);
} else {
provision_contexts(gprs, ofono_sim_get_mcc(gprs->sim),
ofono_sim_get_mnc(gprs->sim),
spn, NULL);
ofono_gprs_finish_register(gprs);
}
}
void ofono_gprs_register(struct ofono_gprs *gprs)
{
struct ofono_modem *modem = __ofono_atom_get_modem(gprs->atom);
gprs->sim = __ofono_atom_find(OFONO_ATOM_TYPE_SIM, modem);
if (gprs->sim == NULL)
goto finish;
gprs_load_settings(gprs, ofono_sim_get_imsi(gprs->sim));
if (gprs->contexts)
goto finish;
gprs->sim_context = ofono_sim_context_create(gprs->sim);
ofono_sim_add_spn_watch(gprs->sim, &gprs->spn_watch, spn_read_cb,
gprs, NULL);
return;
finish:
ofono_gprs_finish_register(gprs);
}
void ofono_gprs_remove(struct ofono_gprs *gprs)
{
__ofono_atom_free(gprs->atom);
}
void ofono_gprs_set_data(struct ofono_gprs *gprs, void *data)
{
gprs->driver_data = data;
}
void *ofono_gprs_get_data(struct ofono_gprs *gprs)
{
return gprs->driver_data;
}
| gpl-2.0 |
vSlipenchuk/ac100hd | drivers/usb/class/cdc-acm.c | 1 | 45103 | /*
* cdc-acm.c
*
* Copyright (c) 1999 Armin Fuerst <fuerst@in.tum.de>
* Copyright (c) 1999 Pavel Machek <pavel@ucw.cz>
* Copyright (c) 1999 Johannes Erdfelt <johannes@erdfelt.com>
* Copyright (c) 2000 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2004 Oliver Neukum <oliver@neukum.name>
* Copyright (c) 2005 David Kubicek <dave@awk.cz>
* Copyright (c) 2011 Johan Hovold <jhovold@gmail.com>
*
* USB Abstract Control Model driver for USB modems and ISDN adapters
*
* Sponsored by SuSE
*
* 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
*/
#undef DEBUG
#undef VERBOSE_DEBUG
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/serial.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/usb/cdc.h>
#include <asm/byteorder.h>
#include <asm/unaligned.h>
#include <linux/list.h>
#include "cdc-acm.h"
#define DRIVER_AUTHOR "Armin Fuerst, Pavel Machek, Johannes Erdfelt, Vojtech Pavlik, David Kubicek, Johan Hovold"
#define DRIVER_DESC "USB Abstract Control Model driver for USB modems and ISDN adapters"
static struct usb_driver acm_driver;
static struct tty_driver *acm_tty_driver;
static struct acm *acm_table[ACM_TTY_MINORS];
static DEFINE_MUTEX(open_mutex);
#define ACM_READY(acm) (acm && acm->dev && acm->port.count)
static const struct tty_port_operations acm_port_ops = {
};
/*
* Functions for ACM control messages.
*/
static int acm_ctrl_msg(struct acm *acm, int request, int value,
void *buf, int len)
{
int retval = usb_control_msg(acm->dev, usb_sndctrlpipe(acm->dev, 0),
request, USB_RT_ACM, value,
acm->control->altsetting[0].desc.bInterfaceNumber,
buf, len, 5000);
dev_dbg(&acm->control->dev,
"%s - rq 0x%02x, val %#x, len %#x, result %d\n",
__func__, request, value, len, retval);
return retval < 0 ? retval : 0;
}
/* devices aren't required to support these requests.
* the cdc acm descriptor tells whether they do...
*/
#define acm_set_control(acm, control) \
acm_ctrl_msg(acm, USB_CDC_REQ_SET_CONTROL_LINE_STATE, control, NULL, 0)
#define acm_set_line(acm, line) \
acm_ctrl_msg(acm, USB_CDC_REQ_SET_LINE_CODING, 0, line, sizeof *(line))
#define acm_send_break(acm, ms) \
acm_ctrl_msg(acm, USB_CDC_REQ_SEND_BREAK, ms, NULL, 0)
/*
* Write buffer management.
* All of these assume proper locks taken by the caller.
*/
static int acm_wb_alloc(struct acm *acm)
{
int i, wbn;
struct acm_wb *wb;
wbn = 0;
i = 0;
for (;;) {
wb = &acm->wb[wbn];
if (!wb->use) {
wb->use = 1;
return wbn;
}
wbn = (wbn + 1) % ACM_NW;
if (++i >= ACM_NW)
return -1;
}
}
static int acm_wb_is_avail(struct acm *acm)
{
int i, n;
unsigned long flags;
n = ACM_NW;
spin_lock_irqsave(&acm->write_lock, flags);
for (i = 0; i < ACM_NW; i++)
n -= acm->wb[i].use;
spin_unlock_irqrestore(&acm->write_lock, flags);
return n;
}
/*
* Finish write. Caller must hold acm->write_lock
*/
static void acm_write_done(struct acm *acm, struct acm_wb *wb)
{
wb->use = 0;
acm->transmitting--;
usb_autopm_put_interface_async(acm->control);
}
/*
* Poke write.
*
* the caller is responsible for locking
*/
static int acm_start_wb(struct acm *acm, struct acm_wb *wb)
{
int rc;
acm->transmitting++;
wb->urb->transfer_buffer = wb->buf;
wb->urb->transfer_dma = wb->dmah;
wb->urb->transfer_buffer_length = wb->len;
wb->urb->dev = acm->dev;
rc = usb_submit_urb(wb->urb, GFP_ATOMIC);
if (rc < 0) {
dev_err(&acm->data->dev,
"%s - usb_submit_urb(write bulk) failed: %d\n",
__func__, rc);
acm_write_done(acm, wb);
}
return rc;
}
static int acm_write_start(struct acm *acm, int wbn)
{
unsigned long flags;
struct acm_wb *wb = &acm->wb[wbn];
int rc;
spin_lock_irqsave(&acm->write_lock, flags);
if (!acm->dev) {
wb->use = 0;
spin_unlock_irqrestore(&acm->write_lock, flags);
return -ENODEV;
}
dev_vdbg(&acm->data->dev, "%s - susp_count %d\n", __func__,
acm->susp_count);
usb_autopm_get_interface_async(acm->control);
if (acm->susp_count) {
if (!acm->delayed_wb)
acm->delayed_wb = wb;
else
usb_autopm_put_interface_async(acm->control);
spin_unlock_irqrestore(&acm->write_lock, flags);
return 0; /* A white lie */
}
usb_mark_last_busy(acm->dev);
rc = acm_start_wb(acm, wb);
spin_unlock_irqrestore(&acm->write_lock, flags);
return rc;
}
/*
* attributes exported through sysfs
*/
static ssize_t show_caps
(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct acm *acm = usb_get_intfdata(intf);
return sprintf(buf, "%d", acm->ctrl_caps);
}
static DEVICE_ATTR(bmCapabilities, S_IRUGO, show_caps, NULL);
static ssize_t show_country_codes
(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct acm *acm = usb_get_intfdata(intf);
memcpy(buf, acm->country_codes, acm->country_code_size);
return acm->country_code_size;
}
static DEVICE_ATTR(wCountryCodes, S_IRUGO, show_country_codes, NULL);
static ssize_t show_country_rel_date
(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct acm *acm = usb_get_intfdata(intf);
return sprintf(buf, "%d", acm->country_rel_date);
}
static DEVICE_ATTR(iCountryCodeRelDate, S_IRUGO, show_country_rel_date, NULL);
/*
* Interrupt handlers for various ACM device responses
*/
/* control interface reports status changes with "interrupt" transfers */
static void acm_ctrl_irq(struct urb *urb)
{
struct acm *acm = urb->context;
struct usb_cdc_notification *dr = urb->transfer_buffer;
struct tty_struct *tty;
unsigned char *data;
int newctrl;
int retval;
int status = urb->status;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(&acm->control->dev,
"%s - urb shutting down with status: %d\n",
__func__, status);
return;
default:
dev_dbg(&acm->control->dev,
"%s - nonzero urb status received: %d\n",
__func__, status);
goto exit;
}
if (!ACM_READY(acm))
goto exit;
usb_mark_last_busy(acm->dev);
data = (unsigned char *)(dr + 1);
switch (dr->bNotificationType) {
case USB_CDC_NOTIFY_NETWORK_CONNECTION:
dev_dbg(&acm->control->dev, "%s - network connection: %d\n",
__func__, dr->wValue);
break;
case USB_CDC_NOTIFY_SERIAL_STATE:
tty = tty_port_tty_get(&acm->port);
newctrl = get_unaligned_le16(data);
if (tty) {
if (!acm->clocal &&
(acm->ctrlin & ~newctrl & ACM_CTRL_DCD)) {
dev_dbg(&acm->control->dev,
"%s - calling hangup\n", __func__);
tty_hangup(tty);
}
tty_kref_put(tty);
}
acm->ctrlin = newctrl;
dev_dbg(&acm->control->dev,
"%s - input control lines: dcd%c dsr%c break%c "
"ring%c framing%c parity%c overrun%c\n",
__func__,
acm->ctrlin & ACM_CTRL_DCD ? '+' : '-',
acm->ctrlin & ACM_CTRL_DSR ? '+' : '-',
acm->ctrlin & ACM_CTRL_BRK ? '+' : '-',
acm->ctrlin & ACM_CTRL_RI ? '+' : '-',
acm->ctrlin & ACM_CTRL_FRAMING ? '+' : '-',
acm->ctrlin & ACM_CTRL_PARITY ? '+' : '-',
acm->ctrlin & ACM_CTRL_OVERRUN ? '+' : '-');
break;
default:
dev_dbg(&acm->control->dev,
"%s - unknown notification %d received: index %d "
"len %d data0 %d data1 %d\n",
__func__,
dr->bNotificationType, dr->wIndex,
dr->wLength, data[0], data[1]);
break;
}
exit:
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
dev_err(&acm->control->dev, "%s - usb_submit_urb failed: %d\n",
__func__, retval);
}
static int acm_submit_read_urb(struct acm *acm, int index, gfp_t mem_flags)
{
int res;
if (!test_and_clear_bit(index, &acm->read_urbs_free))
return 0;
dev_vdbg(&acm->data->dev, "%s - urb %d\n", __func__, index);
res = usb_submit_urb(acm->read_urbs[index], mem_flags);
if (res) {
if (res != -EPERM) {
dev_err(&acm->data->dev,
"%s - usb_submit_urb failed: %d\n",
__func__, res);
}
set_bit(index, &acm->read_urbs_free);
return res;
}
return 0;
}
static int acm_submit_read_urbs(struct acm *acm, gfp_t mem_flags)
{
int res;
int i;
for (i = 0; i < acm->rx_buflimit; ++i) {
res = acm_submit_read_urb(acm, i, mem_flags);
if (res)
return res;
}
return 0;
}
static void acm_process_read_urb(struct acm *acm, struct urb *urb)
{
struct tty_struct *tty;
if (!urb->actual_length)
return;
tty = tty_port_tty_get(&acm->port);
if (!tty)
return;
tty_insert_flip_string(tty, urb->transfer_buffer, urb->actual_length);
tty_flip_buffer_push(tty);
tty_kref_put(tty);
}
static void acm_read_bulk_callback(struct urb *urb)
{
struct acm_rb *rb = urb->context;
struct acm *acm = rb->instance;
unsigned long flags;
dev_vdbg(&acm->data->dev, "%s - urb %d, len %d\n", __func__,
rb->index, urb->actual_length);
set_bit(rb->index, &acm->read_urbs_free);
if (!acm->dev) {
dev_dbg(&acm->data->dev, "%s - disconnected\n", __func__);
return;
}
usb_mark_last_busy(acm->dev);
if (urb->status) {
dev_dbg(&acm->data->dev, "%s - non-zero urb status: %d\n",
__func__, urb->status);
return;
}
acm_process_read_urb(acm, urb);
/* throttle device if requested by tty */
spin_lock_irqsave(&acm->read_lock, flags);
acm->throttled = acm->throttle_req;
if (!acm->throttled && !acm->susp_count) {
spin_unlock_irqrestore(&acm->read_lock, flags);
acm_submit_read_urb(acm, rb->index, GFP_ATOMIC);
} else {
spin_unlock_irqrestore(&acm->read_lock, flags);
}
}
/* data interface wrote those outgoing bytes */
static void acm_write_bulk(struct urb *urb)
{
struct acm_wb *wb = urb->context;
struct acm *acm = wb->instance;
unsigned long flags;
if (urb->status || (urb->actual_length != urb->transfer_buffer_length))
dev_vdbg(&acm->data->dev, "%s - len %d/%d, status %d\n",
__func__,
urb->actual_length,
urb->transfer_buffer_length,
urb->status);
spin_lock_irqsave(&acm->write_lock, flags);
acm_write_done(acm, wb);
spin_unlock_irqrestore(&acm->write_lock, flags);
if (ACM_READY(acm))
schedule_work(&acm->work);
}
static void acm_softint(struct work_struct *work)
{
struct acm *acm = container_of(work, struct acm, work);
struct tty_struct *tty;
dev_vdbg(&acm->data->dev, "%s\n", __func__);
if (!ACM_READY(acm))
return;
tty = tty_port_tty_get(&acm->port);
if (!tty)
return;
tty_wakeup(tty);
tty_kref_put(tty);
}
/*
* TTY handlers
*/
static int acm_tty_open(struct tty_struct *tty, struct file *filp)
{
struct acm *acm;
int rv = -ENODEV;
mutex_lock(&open_mutex);
acm = acm_table[tty->index];
if (!acm || !acm->dev)
goto out;
else
rv = 0;
dev_dbg(&acm->control->dev, "%s\n", __func__);
set_bit(TTY_NO_WRITE_SPLIT, &tty->flags);
tty->driver_data = acm;
tty_port_tty_set(&acm->port, tty);
if (usb_autopm_get_interface(acm->control) < 0)
goto early_bail;
else
acm->control->needs_remote_wakeup = 1;
mutex_lock(&acm->mutex);
if (acm->port.count++) {
mutex_unlock(&acm->mutex);
usb_autopm_put_interface(acm->control);
goto out;
}
acm->ctrlurb->dev = acm->dev;
if (usb_submit_urb(acm->ctrlurb, GFP_KERNEL)) {
dev_err(&acm->control->dev,
"%s - usb_submit_urb(ctrl irq) failed\n", __func__);
goto bail_out;
}
if (0 > acm_set_control(acm, acm->ctrlout = ACM_CTRL_DTR | ACM_CTRL_RTS) &&
(acm->ctrl_caps & USB_CDC_CAP_LINE))
goto bail_out;
usb_autopm_put_interface(acm->control);
if (acm_submit_read_urbs(acm, GFP_KERNEL))
goto bail_out;
set_bit(ASYNCB_INITIALIZED, &acm->port.flags);
rv = tty_port_block_til_ready(&acm->port, tty, filp);
mutex_unlock(&acm->mutex);
out:
mutex_unlock(&open_mutex);
return rv;
bail_out:
acm->port.count--;
mutex_unlock(&acm->mutex);
usb_autopm_put_interface(acm->control);
early_bail:
mutex_unlock(&open_mutex);
tty_port_tty_set(&acm->port, NULL);
return -EIO;
}
static void acm_tty_unregister(struct acm *acm)
{
int i;
tty_unregister_device(acm_tty_driver, acm->minor);
usb_put_intf(acm->control);
acm_table[acm->minor] = NULL;
usb_free_urb(acm->ctrlurb);
for (i = 0; i < ACM_NW; i++)
usb_free_urb(acm->wb[i].urb);
for (i = 0; i < acm->rx_buflimit; i++)
usb_free_urb(acm->read_urbs[i]);
kfree(acm->country_codes);
kfree(acm);
}
static void acm_port_down(struct acm *acm)
{
int i;
if (acm->dev) {
usb_autopm_get_interface(acm->control);
acm_set_control(acm, acm->ctrlout = 0);
usb_kill_urb(acm->ctrlurb);
for (i = 0; i < ACM_NW; i++)
usb_kill_urb(acm->wb[i].urb);
for (i = 0; i < acm->rx_buflimit; i++)
usb_kill_urb(acm->read_urbs[i]);
acm->control->needs_remote_wakeup = 0;
usb_autopm_put_interface(acm->control);
}
}
static void acm_tty_hangup(struct tty_struct *tty)
{
struct acm *acm;
mutex_lock(&open_mutex);
acm = tty->driver_data;
if (acm) {
tty_port_hangup(&acm->port);
acm_port_down(acm);
}
mutex_unlock(&open_mutex);
}
static void acm_tty_close(struct tty_struct *tty, struct file *filp)
{
struct acm *acm = tty->driver_data;
/* Perform the closing process and see if we need to do the hardware
shutdown */
if (!acm)
return;
if (tty_port_close_start(&acm->port, tty, filp) == 0) {
mutex_lock(&open_mutex);
if (!acm->dev) {
tty_port_tty_set(&acm->port, NULL);
acm_tty_unregister(acm);
tty->driver_data = NULL;
}
mutex_unlock(&open_mutex);
return;
}
mutex_lock(&open_mutex);
acm_port_down(acm);
mutex_unlock(&open_mutex);
tty_port_close_end(&acm->port, tty);
tty_port_tty_set(&acm->port, NULL);
}
static int acm_tty_write(struct tty_struct *tty,
const unsigned char *buf, int count)
{
struct acm *acm = tty->driver_data;
int stat;
unsigned long flags;
int wbn;
struct acm_wb *wb;
if (!ACM_READY(acm))
return -EINVAL;
if (!count)
return 0;
dev_vdbg(&acm->data->dev, "%s - count %d\n", __func__, count);
spin_lock_irqsave(&acm->write_lock, flags);
wbn = acm_wb_alloc(acm);
if (wbn < 0) {
spin_unlock_irqrestore(&acm->write_lock, flags);
return 0;
}
wb = &acm->wb[wbn];
count = (count > acm->writesize) ? acm->writesize : count;
dev_vdbg(&acm->data->dev, "%s - write %d\n", __func__, count);
memcpy(wb->buf, buf, count);
wb->len = count;
spin_unlock_irqrestore(&acm->write_lock, flags);
stat = acm_write_start(acm, wbn);
if (stat < 0)
return stat;
return count;
}
static int acm_tty_write_room(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
if (!ACM_READY(acm))
return -EINVAL;
/*
* Do not let the line discipline to know that we have a reserve,
* or it might get too enthusiastic.
*/
return acm_wb_is_avail(acm) ? acm->writesize : 0;
}
static int acm_tty_chars_in_buffer(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
if (!ACM_READY(acm))
return 0;
/*
* This is inaccurate (overcounts), but it works.
*/
return (ACM_NW - acm_wb_is_avail(acm)) * acm->writesize;
}
static void acm_tty_throttle(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
if (!ACM_READY(acm))
return;
spin_lock_irq(&acm->read_lock);
acm->throttle_req = 1;
spin_unlock_irq(&acm->read_lock);
}
static void acm_tty_unthrottle(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
unsigned int was_throttled;
if (!ACM_READY(acm))
return;
spin_lock_irq(&acm->read_lock);
was_throttled = acm->throttled;
acm->throttled = 0;
acm->throttle_req = 0;
spin_unlock_irq(&acm->read_lock);
if (was_throttled)
acm_submit_read_urbs(acm, GFP_KERNEL);
}
static int acm_tty_break_ctl(struct tty_struct *tty, int state)
{
struct acm *acm = tty->driver_data;
int retval;
if (!ACM_READY(acm))
return -EINVAL;
retval = acm_send_break(acm, state ? 0xffff : 0);
if (retval < 0)
dev_dbg(&acm->control->dev, "%s - send break failed\n",
__func__);
return retval;
}
static int acm_tty_tiocmget(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
if (!ACM_READY(acm))
return -EINVAL;
return (acm->ctrlout & ACM_CTRL_DTR ? TIOCM_DTR : 0) |
(acm->ctrlout & ACM_CTRL_RTS ? TIOCM_RTS : 0) |
(acm->ctrlin & ACM_CTRL_DSR ? TIOCM_DSR : 0) |
(acm->ctrlin & ACM_CTRL_RI ? TIOCM_RI : 0) |
(acm->ctrlin & ACM_CTRL_DCD ? TIOCM_CD : 0) |
TIOCM_CTS;
}
static int acm_tty_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct acm *acm = tty->driver_data;
unsigned int newctrl;
if (!ACM_READY(acm))
return -EINVAL;
newctrl = acm->ctrlout;
set = (set & TIOCM_DTR ? ACM_CTRL_DTR : 0) |
(set & TIOCM_RTS ? ACM_CTRL_RTS : 0);
clear = (clear & TIOCM_DTR ? ACM_CTRL_DTR : 0) |
(clear & TIOCM_RTS ? ACM_CTRL_RTS : 0);
newctrl = (newctrl & ~clear) | set;
if (acm->ctrlout == newctrl)
return 0;
return acm_set_control(acm, acm->ctrlout = newctrl);
}
static int acm_tty_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct acm *acm = tty->driver_data;
if (!ACM_READY(acm))
return -EINVAL;
return -ENOIOCTLCMD;
}
static const __u32 acm_tty_speed[] = {
0, 50, 75, 110, 134, 150, 200, 300, 600,
1200, 1800, 2400, 4800, 9600, 19200, 38400,
57600, 115200, 230400, 460800, 500000, 576000,
921600, 1000000, 1152000, 1500000, 2000000,
2500000, 3000000, 3500000, 4000000
};
static const __u8 acm_tty_size[] = {
5, 6, 7, 8
};
static void acm_tty_set_termios(struct tty_struct *tty,
struct ktermios *termios_old)
{
struct acm *acm = tty->driver_data;
struct ktermios *termios = tty->termios;
struct usb_cdc_line_coding newline;
int newctrl = acm->ctrlout;
if (!ACM_READY(acm))
return;
newline.dwDTERate = cpu_to_le32(tty_get_baud_rate(tty));
newline.bCharFormat = termios->c_cflag & CSTOPB ? 2 : 0;
newline.bParityType = termios->c_cflag & PARENB ?
(termios->c_cflag & PARODD ? 1 : 2) +
(termios->c_cflag & CMSPAR ? 2 : 0) : 0;
newline.bDataBits = acm_tty_size[(termios->c_cflag & CSIZE) >> 4];
/* FIXME: Needs to clear unsupported bits in the termios */
acm->clocal = ((termios->c_cflag & CLOCAL) != 0);
if (!newline.dwDTERate) {
newline.dwDTERate = acm->line.dwDTERate;
newctrl &= ~ACM_CTRL_DTR;
} else
newctrl |= ACM_CTRL_DTR;
if (newctrl != acm->ctrlout)
acm_set_control(acm, acm->ctrlout = newctrl);
if (memcmp(&acm->line, &newline, sizeof newline)) {
memcpy(&acm->line, &newline, sizeof newline);
dev_dbg(&acm->control->dev, "%s - set line: %d %d %d %d\n",
__func__,
le32_to_cpu(newline.dwDTERate),
newline.bCharFormat, newline.bParityType,
newline.bDataBits);
acm_set_line(acm, &acm->line);
}
}
/*
* USB probe and disconnect routines.
*/
/* Little helpers: write/read buffers free */
static void acm_write_buffers_free(struct acm *acm)
{
int i;
struct acm_wb *wb;
struct usb_device *usb_dev = interface_to_usbdev(acm->control);
for (wb = &acm->wb[0], i = 0; i < ACM_NW; i++, wb++)
usb_free_coherent(usb_dev, acm->writesize, wb->buf, wb->dmah);
}
static void acm_read_buffers_free(struct acm *acm)
{
struct usb_device *usb_dev = interface_to_usbdev(acm->control);
int i;
for (i = 0; i < acm->rx_buflimit; i++)
usb_free_coherent(usb_dev, acm->readsize,
acm->read_buffers[i].base, acm->read_buffers[i].dma);
}
/* Little helper: write buffers allocate */
static int acm_write_buffers_alloc(struct acm *acm)
{
int i;
struct acm_wb *wb;
for (wb = &acm->wb[0], i = 0; i < ACM_NW; i++, wb++) {
wb->buf = usb_alloc_coherent(acm->dev, acm->writesize, GFP_KERNEL,
&wb->dmah);
if (!wb->buf) {
while (i != 0) {
--i;
--wb;
usb_free_coherent(acm->dev, acm->writesize,
wb->buf, wb->dmah);
}
return -ENOMEM;
}
}
return 0;
}
static int acm_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_cdc_union_desc *union_header = NULL;
struct usb_cdc_country_functional_desc *cfd = NULL;
unsigned char *buffer = intf->altsetting->extra;
int buflen = intf->altsetting->extralen;
struct usb_interface *control_interface;
struct usb_interface *data_interface;
struct usb_endpoint_descriptor *epctrl = NULL;
struct usb_endpoint_descriptor *epread = NULL;
struct usb_endpoint_descriptor *epwrite = NULL;
struct usb_device *usb_dev = interface_to_usbdev(intf);
struct acm *acm;
int minor;
int ctrlsize, readsize;
u8 *buf;
u8 ac_management_function = 0;
u8 call_management_function = 0;
int call_interface_num = -1;
int data_interface_num = -1;
unsigned long quirks;
int num_rx_buf;
int i;
int combined_interfaces = 0;
/* normal quirks */
quirks = (unsigned long)id->driver_info;
num_rx_buf = (quirks == SINGLE_RX_URB) ? 1 : ACM_NR;
/* handle quirks deadly to normal probing*/
if (quirks == NO_UNION_NORMAL) {
data_interface = usb_ifnum_to_if(usb_dev, 1);
control_interface = usb_ifnum_to_if(usb_dev, 0);
goto skip_normal_probe;
}
/* normal probing*/
if (!buffer) {
dev_err(&intf->dev, "Weird descriptor references\n");
return -EINVAL;
}
if (!buflen) {
if (intf->cur_altsetting->endpoint &&
intf->cur_altsetting->endpoint->extralen &&
intf->cur_altsetting->endpoint->extra) {
dev_dbg(&intf->dev,
"Seeking extra descriptors on endpoint\n");
buflen = intf->cur_altsetting->endpoint->extralen;
buffer = intf->cur_altsetting->endpoint->extra;
} else {
dev_err(&intf->dev,
"Zero length descriptor references\n");
return -EINVAL;
}
}
while (buflen > 0) {
if (buffer[1] != USB_DT_CS_INTERFACE) {
dev_err(&intf->dev, "skipping garbage\n");
goto next_desc;
}
switch (buffer[2]) {
case USB_CDC_UNION_TYPE: /* we've found it */
if (union_header) {
dev_err(&intf->dev, "More than one "
"union descriptor, skipping ...\n");
goto next_desc;
}
union_header = (struct usb_cdc_union_desc *)buffer;
break;
case USB_CDC_COUNTRY_TYPE: /* export through sysfs*/
cfd = (struct usb_cdc_country_functional_desc *)buffer;
break;
case USB_CDC_HEADER_TYPE: /* maybe check version */
break; /* for now we ignore it */
case USB_CDC_ACM_TYPE:
ac_management_function = buffer[3];
break;
case USB_CDC_CALL_MANAGEMENT_TYPE:
call_management_function = buffer[3];
call_interface_num = buffer[4];
if ( (quirks & NOT_A_MODEM) == 0 && (call_management_function & 3) != 3)
dev_err(&intf->dev, "This device cannot do calls on its own. It is not a modem.\n");
break;
default:
/* there are LOTS more CDC descriptors that
* could legitimately be found here.
*/
dev_dbg(&intf->dev, "Ignoring descriptor: "
"type %02x, length %d\n",
buffer[2], buffer[0]);
break;
}
next_desc:
buflen -= buffer[0];
buffer += buffer[0];
}
if (!union_header) {
if (call_interface_num > 0) {
dev_dbg(&intf->dev, "No union descriptor, using call management descriptor\n");
/* quirks for Droids MuIn LCD */
if (quirks & NO_DATA_INTERFACE)
data_interface = usb_ifnum_to_if(usb_dev, 0);
else
data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = call_interface_num));
control_interface = intf;
} else {
if (intf->cur_altsetting->desc.bNumEndpoints != 3) {
dev_dbg(&intf->dev,"No union descriptor, giving up\n");
return -ENODEV;
} else {
dev_warn(&intf->dev,"No union descriptor, testing for castrated device\n");
combined_interfaces = 1;
control_interface = data_interface = intf;
goto look_for_collapsed_interface;
}
}
} else {
control_interface = usb_ifnum_to_if(usb_dev, union_header->bMasterInterface0);
data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = union_header->bSlaveInterface0));
if (!control_interface || !data_interface) {
dev_dbg(&intf->dev, "no interfaces\n");
return -ENODEV;
}
}
if (data_interface_num != call_interface_num)
dev_dbg(&intf->dev, "Separate call control interface. That is not fully supported.\n");
if (control_interface == data_interface) {
/* some broken devices designed for windows work this way */
dev_warn(&intf->dev,"Control and data interfaces are not separated!\n");
combined_interfaces = 1;
/* a popular other OS doesn't use it */
quirks |= NO_CAP_LINE;
if (data_interface->cur_altsetting->desc.bNumEndpoints != 3) {
dev_err(&intf->dev, "This needs exactly 3 endpoints\n");
return -EINVAL;
}
look_for_collapsed_interface:
for (i = 0; i < 3; i++) {
struct usb_endpoint_descriptor *ep;
ep = &data_interface->cur_altsetting->endpoint[i].desc;
if (usb_endpoint_is_int_in(ep))
epctrl = ep;
else if (usb_endpoint_is_bulk_out(ep))
epwrite = ep;
else if (usb_endpoint_is_bulk_in(ep))
epread = ep;
else
return -EINVAL;
}
if (!epctrl || !epread || !epwrite)
return -ENODEV;
else
goto made_compressed_probe;
}
skip_normal_probe:
/*workaround for switched interfaces */
if (data_interface->cur_altsetting->desc.bInterfaceClass
!= CDC_DATA_INTERFACE_TYPE) {
if (control_interface->cur_altsetting->desc.bInterfaceClass
== CDC_DATA_INTERFACE_TYPE) {
struct usb_interface *t;
dev_dbg(&intf->dev,
"Your device has switched interfaces.\n");
t = control_interface;
control_interface = data_interface;
data_interface = t;
} else {
return -EINVAL;
}
}
/* Accept probe requests only for the control interface */
if (!combined_interfaces && intf != control_interface)
return -ENODEV;
if (!combined_interfaces && usb_interface_claimed(data_interface)) {
/* valid in this context */
dev_dbg(&intf->dev, "The data interface isn't available\n");
return -EBUSY;
}
if (data_interface->cur_altsetting->desc.bNumEndpoints < 2)
return -EINVAL;
epctrl = &control_interface->cur_altsetting->endpoint[0].desc;
epread = &data_interface->cur_altsetting->endpoint[0].desc;
epwrite = &data_interface->cur_altsetting->endpoint[1].desc;
/* workaround for switched endpoints */
if (!usb_endpoint_dir_in(epread)) {
/* descriptors are swapped */
struct usb_endpoint_descriptor *t;
dev_dbg(&intf->dev,
"The data interface has switched endpoints\n");
t = epread;
epread = epwrite;
epwrite = t;
}
made_compressed_probe:
dev_dbg(&intf->dev, "interfaces are valid\n");
for (minor = 0; minor < ACM_TTY_MINORS && acm_table[minor]; minor++);
if (minor == ACM_TTY_MINORS) {
dev_err(&intf->dev, "no more free acm devices\n");
return -ENODEV;
}
acm = kzalloc(sizeof(struct acm), GFP_KERNEL);
if (acm == NULL) {
dev_err(&intf->dev, "out of memory (acm kzalloc)\n");
goto alloc_fail;
}
ctrlsize = le16_to_cpu(epctrl->wMaxPacketSize);
readsize = le16_to_cpu(epread->wMaxPacketSize) *
(quirks == SINGLE_RX_URB ? 1 : 2);
acm->combined_interfaces = combined_interfaces;
acm->writesize = le16_to_cpu(epwrite->wMaxPacketSize) * 20;
acm->control = control_interface;
acm->data = data_interface;
acm->minor = minor;
acm->dev = usb_dev;
acm->ctrl_caps = ac_management_function;
if (quirks & NO_CAP_LINE)
acm->ctrl_caps &= ~USB_CDC_CAP_LINE;
acm->ctrlsize = ctrlsize;
acm->readsize = readsize;
acm->rx_buflimit = num_rx_buf;
INIT_WORK(&acm->work, acm_softint);
spin_lock_init(&acm->write_lock);
spin_lock_init(&acm->read_lock);
mutex_init(&acm->mutex);
acm->rx_endpoint = usb_rcvbulkpipe(usb_dev, epread->bEndpointAddress);
acm->is_int_ep = usb_endpoint_xfer_int(epread);
if (acm->is_int_ep)
acm->bInterval = epread->bInterval;
tty_port_init(&acm->port);
acm->port.ops = &acm_port_ops;
buf = usb_alloc_coherent(usb_dev, ctrlsize, GFP_KERNEL, &acm->ctrl_dma);
if (!buf) {
dev_err(&intf->dev, "out of memory (ctrl buffer alloc)\n");
goto alloc_fail2;
}
acm->ctrl_buffer = buf;
if (acm_write_buffers_alloc(acm) < 0) {
dev_err(&intf->dev, "out of memory (write buffer alloc)\n");
goto alloc_fail4;
}
acm->ctrlurb = usb_alloc_urb(0, GFP_KERNEL);
if (!acm->ctrlurb) {
dev_err(&intf->dev, "out of memory (ctrlurb kmalloc)\n");
goto alloc_fail5;
}
for (i = 0; i < num_rx_buf; i++) {
struct acm_rb *rb = &(acm->read_buffers[i]);
struct urb *urb;
rb->base = usb_alloc_coherent(acm->dev, readsize, GFP_KERNEL,
&rb->dma);
if (!rb->base) {
dev_err(&intf->dev, "out of memory "
"(read bufs usb_alloc_coherent)\n");
goto alloc_fail6;
}
rb->index = i;
rb->instance = acm;
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb) {
dev_err(&intf->dev,
"out of memory (read urbs usb_alloc_urb)\n");
goto alloc_fail6;
}
urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
urb->transfer_dma = rb->dma;
if (acm->is_int_ep) {
usb_fill_int_urb(urb, acm->dev,
acm->rx_endpoint,
rb->base,
acm->readsize,
acm_read_bulk_callback, rb,
acm->bInterval);
} else {
usb_fill_bulk_urb(urb, acm->dev,
acm->rx_endpoint,
rb->base,
acm->readsize,
acm_read_bulk_callback, rb);
}
acm->read_urbs[i] = urb;
__set_bit(i, &acm->read_urbs_free);
}
for (i = 0; i < ACM_NW; i++) {
struct acm_wb *snd = &(acm->wb[i]);
snd->urb = usb_alloc_urb(0, GFP_KERNEL);
if (snd->urb == NULL) {
dev_err(&intf->dev,
"out of memory (write urbs usb_alloc_urb)\n");
goto alloc_fail7;
}
if (usb_endpoint_xfer_int(epwrite))
usb_fill_int_urb(snd->urb, usb_dev,
usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress),
NULL, acm->writesize, acm_write_bulk, snd, epwrite->bInterval);
else
usb_fill_bulk_urb(snd->urb, usb_dev,
usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress),
NULL, acm->writesize, acm_write_bulk, snd);
snd->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
snd->instance = acm;
}
usb_set_intfdata(intf, acm);
i = device_create_file(&intf->dev, &dev_attr_bmCapabilities);
if (i < 0)
goto alloc_fail7;
if (cfd) { /* export the country data */
acm->country_codes = kmalloc(cfd->bLength - 4, GFP_KERNEL);
if (!acm->country_codes)
goto skip_countries;
acm->country_code_size = cfd->bLength - 4;
memcpy(acm->country_codes, (u8 *)&cfd->wCountyCode0,
cfd->bLength - 4);
acm->country_rel_date = cfd->iCountryCodeRelDate;
i = device_create_file(&intf->dev, &dev_attr_wCountryCodes);
if (i < 0) {
kfree(acm->country_codes);
goto skip_countries;
}
i = device_create_file(&intf->dev,
&dev_attr_iCountryCodeRelDate);
if (i < 0) {
device_remove_file(&intf->dev, &dev_attr_wCountryCodes);
kfree(acm->country_codes);
goto skip_countries;
}
}
skip_countries:
usb_fill_int_urb(acm->ctrlurb, usb_dev,
usb_rcvintpipe(usb_dev, epctrl->bEndpointAddress),
acm->ctrl_buffer, ctrlsize, acm_ctrl_irq, acm,
/* works around buggy devices */
epctrl->bInterval ? epctrl->bInterval : 0xff);
acm->ctrlurb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
acm->ctrlurb->transfer_dma = acm->ctrl_dma;
dev_info(&intf->dev, "ttyACM%d: USB ACM device\n", minor);
acm_set_control(acm, acm->ctrlout);
acm->line.dwDTERate = cpu_to_le32(9600);
acm->line.bDataBits = 8;
acm_set_line(acm, &acm->line);
usb_driver_claim_interface(&acm_driver, data_interface, acm);
usb_set_intfdata(data_interface, acm);
usb_get_intf(control_interface);
tty_register_device(acm_tty_driver, minor, &control_interface->dev);
acm_table[minor] = acm;
return 0;
alloc_fail7:
for (i = 0; i < ACM_NW; i++)
usb_free_urb(acm->wb[i].urb);
alloc_fail6:
for (i = 0; i < num_rx_buf; i++)
usb_free_urb(acm->read_urbs[i]);
acm_read_buffers_free(acm);
usb_free_urb(acm->ctrlurb);
alloc_fail5:
acm_write_buffers_free(acm);
alloc_fail4:
usb_free_coherent(usb_dev, ctrlsize, acm->ctrl_buffer, acm->ctrl_dma);
alloc_fail2:
kfree(acm);
alloc_fail:
return -ENOMEM;
}
static void stop_data_traffic(struct acm *acm)
{
int i;
dev_dbg(&acm->control->dev, "%s\n", __func__);
usb_kill_urb(acm->ctrlurb);
for (i = 0; i < ACM_NW; i++)
usb_kill_urb(acm->wb[i].urb);
for (i = 0; i < acm->rx_buflimit; i++)
usb_kill_urb(acm->read_urbs[i]);
cancel_work_sync(&acm->work);
}
static void acm_disconnect(struct usb_interface *intf)
{
struct acm *acm = usb_get_intfdata(intf);
struct usb_device *usb_dev = interface_to_usbdev(intf);
struct tty_struct *tty;
/* sibling interface is already cleaning up */
if (!acm)
return;
mutex_lock(&open_mutex);
if (acm->country_codes) {
device_remove_file(&acm->control->dev,
&dev_attr_wCountryCodes);
device_remove_file(&acm->control->dev,
&dev_attr_iCountryCodeRelDate);
}
device_remove_file(&acm->control->dev, &dev_attr_bmCapabilities);
acm->dev = NULL;
usb_set_intfdata(acm->control, NULL);
usb_set_intfdata(acm->data, NULL);
stop_data_traffic(acm);
acm_write_buffers_free(acm);
usb_free_coherent(usb_dev, acm->ctrlsize, acm->ctrl_buffer,
acm->ctrl_dma);
acm_read_buffers_free(acm);
if (!acm->combined_interfaces)
usb_driver_release_interface(&acm_driver, intf == acm->control ?
acm->data : acm->control);
if (acm->port.count == 0) {
acm_tty_unregister(acm);
mutex_unlock(&open_mutex);
return;
}
mutex_unlock(&open_mutex);
tty = tty_port_tty_get(&acm->port);
if (tty) {
tty_hangup(tty);
tty_kref_put(tty);
}
}
#ifdef CONFIG_PM
static int acm_suspend(struct usb_interface *intf, pm_message_t message)
{
struct acm *acm = usb_get_intfdata(intf);
int cnt;
if (message.event & PM_EVENT_AUTO) {
int b;
spin_lock_irq(&acm->write_lock);
b = acm->transmitting;
spin_unlock_irq(&acm->write_lock);
if (b)
return -EBUSY;
}
spin_lock_irq(&acm->read_lock);
spin_lock(&acm->write_lock);
cnt = acm->susp_count++;
spin_unlock(&acm->write_lock);
spin_unlock_irq(&acm->read_lock);
if (cnt)
return 0;
/*
we treat opened interfaces differently,
we must guard against open
*/
mutex_lock(&acm->mutex);
if (acm->port.count)
stop_data_traffic(acm);
mutex_unlock(&acm->mutex);
return 0;
}
static int acm_resume(struct usb_interface *intf)
{
struct acm *acm = usb_get_intfdata(intf);
struct acm_wb *wb;
int rv = 0;
int cnt;
spin_lock_irq(&acm->read_lock);
acm->susp_count -= 1;
cnt = acm->susp_count;
spin_unlock_irq(&acm->read_lock);
if (cnt)
return 0;
mutex_lock(&acm->mutex);
if (acm->port.count) {
rv = usb_submit_urb(acm->ctrlurb, GFP_NOIO);
spin_lock_irq(&acm->write_lock);
if (acm->delayed_wb) {
wb = acm->delayed_wb;
acm->delayed_wb = NULL;
spin_unlock_irq(&acm->write_lock);
acm_start_wb(acm, wb);
} else {
spin_unlock_irq(&acm->write_lock);
}
/*
* delayed error checking because we must
* do the write path at all cost
*/
if (rv < 0)
goto err_out;
rv = acm_submit_read_urbs(acm, GFP_NOIO);
}
err_out:
mutex_unlock(&acm->mutex);
return rv;
}
static int acm_reset_resume(struct usb_interface *intf)
{
struct acm *acm = usb_get_intfdata(intf);
struct tty_struct *tty;
mutex_lock(&acm->mutex);
if (acm->port.count) {
tty = tty_port_tty_get(&acm->port);
if (tty) {
tty_hangup(tty);
tty_kref_put(tty);
}
}
mutex_unlock(&acm->mutex);
return acm_resume(intf);
}
#endif /* CONFIG_PM */
#define NOKIA_PCSUITE_ACM_INFO(x) \
USB_DEVICE_AND_INTERFACE_INFO(0x0421, x, \
USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, \
USB_CDC_ACM_PROTO_VENDOR)
#define SAMSUNG_PCSUITE_ACM_INFO(x) \
USB_DEVICE_AND_INTERFACE_INFO(0x04e7, x, \
USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, \
USB_CDC_ACM_PROTO_VENDOR)
/*
* USB driver structure.
*/
static const struct usb_device_id acm_ids[] = {
/* quirky and broken devices */
{ USB_DEVICE(0x0870, 0x0001), /* Metricom GS Modem */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0e8d, 0x0003), /* FIREFLY, MediaTek Inc; andrey.arapov@gmail.com */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0e8d, 0x3329), /* MediaTek Inc GPS */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0482, 0x0203), /* KYOCERA AH-K3001V */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x079b, 0x000f), /* BT On-Air USB MODEM */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0ace, 0x1602), /* ZyDAS 56K USB MODEM */
.driver_info = SINGLE_RX_URB,
},
{ USB_DEVICE(0x0ace, 0x1608), /* ZyDAS 56K USB MODEM */
.driver_info = SINGLE_RX_URB, /* firmware bug */
},
{ USB_DEVICE(0x0ace, 0x1611), /* ZyDAS 56K USB MODEM - new version */
.driver_info = SINGLE_RX_URB, /* firmware bug */
},
{ USB_DEVICE(0x22b8, 0x7000), /* Motorola Q Phone */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0803, 0x3095), /* Zoom Telephonics Model 3095F USB MODEM */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0572, 0x1321), /* Conexant USB MODEM CX93010 */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0572, 0x1324), /* Conexant USB MODEM RD02-D400 */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0572, 0x1328), /* Shiro / Aztech USB MODEM UM-3100 */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x22b8, 0x6425), /* Motorola MOTOMAGX phones */
},
{ USB_DEVICE(0x0572, 0x1329), /* Hummingbird huc56s (Conexant) */
.driver_info = NO_UNION_NORMAL, /* union descriptor misplaced on
data interface instead of
communications interface.
Maybe we should define a new
quirk for this. */
},
{ USB_DEVICE(0x1bbb, 0x0003), /* Alcatel OT-I650 */
.driver_info = NO_UNION_NORMAL, /* reports zero length descriptor */
},
{ USB_DEVICE(0x1576, 0x03b1), /* Maretron USB100 */
.driver_info = NO_UNION_NORMAL, /* reports zero length descriptor */
},
/* Nokia S60 phones expose two ACM channels. The first is
* a modem and is picked up by the standard AT-command
* information below. The second is 'vendor-specific' but
* is treated as a serial device at the S60 end, so we want
* to expose it on Linux too. */
{ NOKIA_PCSUITE_ACM_INFO(0x042D), }, /* Nokia 3250 */
{ NOKIA_PCSUITE_ACM_INFO(0x04D8), }, /* Nokia 5500 Sport */
{ NOKIA_PCSUITE_ACM_INFO(0x04C9), }, /* Nokia E50 */
{ NOKIA_PCSUITE_ACM_INFO(0x0419), }, /* Nokia E60 */
{ NOKIA_PCSUITE_ACM_INFO(0x044D), }, /* Nokia E61 */
{ NOKIA_PCSUITE_ACM_INFO(0x0001), }, /* Nokia E61i */
{ NOKIA_PCSUITE_ACM_INFO(0x0475), }, /* Nokia E62 */
{ NOKIA_PCSUITE_ACM_INFO(0x0508), }, /* Nokia E65 */
{ NOKIA_PCSUITE_ACM_INFO(0x0418), }, /* Nokia E70 */
{ NOKIA_PCSUITE_ACM_INFO(0x0425), }, /* Nokia N71 */
{ NOKIA_PCSUITE_ACM_INFO(0x0486), }, /* Nokia N73 */
{ NOKIA_PCSUITE_ACM_INFO(0x04DF), }, /* Nokia N75 */
{ NOKIA_PCSUITE_ACM_INFO(0x000e), }, /* Nokia N77 */
{ NOKIA_PCSUITE_ACM_INFO(0x0445), }, /* Nokia N80 */
{ NOKIA_PCSUITE_ACM_INFO(0x042F), }, /* Nokia N91 & N91 8GB */
{ NOKIA_PCSUITE_ACM_INFO(0x048E), }, /* Nokia N92 */
{ NOKIA_PCSUITE_ACM_INFO(0x0420), }, /* Nokia N93 */
{ NOKIA_PCSUITE_ACM_INFO(0x04E6), }, /* Nokia N93i */
{ NOKIA_PCSUITE_ACM_INFO(0x04B2), }, /* Nokia 5700 XpressMusic */
{ NOKIA_PCSUITE_ACM_INFO(0x0134), }, /* Nokia 6110 Navigator (China) */
{ NOKIA_PCSUITE_ACM_INFO(0x046E), }, /* Nokia 6110 Navigator */
{ NOKIA_PCSUITE_ACM_INFO(0x002f), }, /* Nokia 6120 classic & */
{ NOKIA_PCSUITE_ACM_INFO(0x0088), }, /* Nokia 6121 classic */
{ NOKIA_PCSUITE_ACM_INFO(0x00fc), }, /* Nokia 6124 classic */
{ NOKIA_PCSUITE_ACM_INFO(0x0042), }, /* Nokia E51 */
{ NOKIA_PCSUITE_ACM_INFO(0x00b0), }, /* Nokia E66 */
{ NOKIA_PCSUITE_ACM_INFO(0x00ab), }, /* Nokia E71 */
{ NOKIA_PCSUITE_ACM_INFO(0x0481), }, /* Nokia N76 */
{ NOKIA_PCSUITE_ACM_INFO(0x0007), }, /* Nokia N81 & N81 8GB */
{ NOKIA_PCSUITE_ACM_INFO(0x0071), }, /* Nokia N82 */
{ NOKIA_PCSUITE_ACM_INFO(0x04F0), }, /* Nokia N95 & N95-3 NAM */
{ NOKIA_PCSUITE_ACM_INFO(0x0070), }, /* Nokia N95 8GB */
{ NOKIA_PCSUITE_ACM_INFO(0x00e9), }, /* Nokia 5320 XpressMusic */
{ NOKIA_PCSUITE_ACM_INFO(0x0099), }, /* Nokia 6210 Navigator, RM-367 */
{ NOKIA_PCSUITE_ACM_INFO(0x0128), }, /* Nokia 6210 Navigator, RM-419 */
{ NOKIA_PCSUITE_ACM_INFO(0x008f), }, /* Nokia 6220 Classic */
{ NOKIA_PCSUITE_ACM_INFO(0x00a0), }, /* Nokia 6650 */
{ NOKIA_PCSUITE_ACM_INFO(0x007b), }, /* Nokia N78 */
{ NOKIA_PCSUITE_ACM_INFO(0x0094), }, /* Nokia N85 */
{ NOKIA_PCSUITE_ACM_INFO(0x003a), }, /* Nokia N96 & N96-3 */
{ NOKIA_PCSUITE_ACM_INFO(0x00e9), }, /* Nokia 5320 XpressMusic */
{ NOKIA_PCSUITE_ACM_INFO(0x0108), }, /* Nokia 5320 XpressMusic 2G */
{ NOKIA_PCSUITE_ACM_INFO(0x01f5), }, /* Nokia N97, RM-505 */
{ NOKIA_PCSUITE_ACM_INFO(0x02e3), }, /* Nokia 5230, RM-588 */
{ NOKIA_PCSUITE_ACM_INFO(0x0178), }, /* Nokia E63 */
{ NOKIA_PCSUITE_ACM_INFO(0x010e), }, /* Nokia E75 */
{ NOKIA_PCSUITE_ACM_INFO(0x02d9), }, /* Nokia 6760 Slide */
{ NOKIA_PCSUITE_ACM_INFO(0x01d0), }, /* Nokia E52 */
{ NOKIA_PCSUITE_ACM_INFO(0x0223), }, /* Nokia E72 */
{ NOKIA_PCSUITE_ACM_INFO(0x0275), }, /* Nokia X6 */
{ NOKIA_PCSUITE_ACM_INFO(0x026c), }, /* Nokia N97 Mini */
{ NOKIA_PCSUITE_ACM_INFO(0x0154), }, /* Nokia 5800 XpressMusic */
{ NOKIA_PCSUITE_ACM_INFO(0x04ce), }, /* Nokia E90 */
{ NOKIA_PCSUITE_ACM_INFO(0x01d4), }, /* Nokia E55 */
{ NOKIA_PCSUITE_ACM_INFO(0x0302), }, /* Nokia N8 */
{ NOKIA_PCSUITE_ACM_INFO(0x0335), }, /* Nokia E7 */
{ NOKIA_PCSUITE_ACM_INFO(0x03cd), }, /* Nokia C7 */
{ SAMSUNG_PCSUITE_ACM_INFO(0x6651), }, /* Samsung GTi8510 (INNOV8) */
/* NOTE: non-Nokia COMM/ACM/0xff is likely MSFT RNDIS... NOT a modem! */
/* Support Lego NXT using pbLua firmware */
{ USB_DEVICE(0x0694, 0xff00),
.driver_info = NOT_A_MODEM,
},
/* Support for Droids MuIn LCD */
{ USB_DEVICE(0x04d8, 0x000b),
.driver_info = NO_DATA_INTERFACE,
},
/* control interfaces without any protocol set */
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_PROTO_NONE) },
/* control interfaces with various AT-command sets */
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_V25TER) },
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_PCCA101) },
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_PCCA101_WAKE) },
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_GSM) },
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_3G) },
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_CDMA) },
{ }
};
MODULE_DEVICE_TABLE(usb, acm_ids);
static struct usb_driver acm_driver = {
.name = "cdc_acm",
.probe = acm_probe,
.disconnect = acm_disconnect,
#ifdef CONFIG_PM
.suspend = acm_suspend,
.resume = acm_resume,
.reset_resume = acm_reset_resume,
#endif
.id_table = acm_ids,
#ifdef CONFIG_PM
.supports_autosuspend = 1,
#endif
};
/*
* TTY driver structures.
*/
static const struct tty_operations acm_ops = {
.open = acm_tty_open,
.close = acm_tty_close,
.hangup = acm_tty_hangup,
.write = acm_tty_write,
.write_room = acm_tty_write_room,
.ioctl = acm_tty_ioctl,
.throttle = acm_tty_throttle,
.unthrottle = acm_tty_unthrottle,
.chars_in_buffer = acm_tty_chars_in_buffer,
.break_ctl = acm_tty_break_ctl,
.set_termios = acm_tty_set_termios,
.tiocmget = acm_tty_tiocmget,
.tiocmset = acm_tty_tiocmset,
};
/*
* Init / exit.
*/
static int __init acm_init(void)
{
int retval;
acm_tty_driver = alloc_tty_driver(ACM_TTY_MINORS);
if (!acm_tty_driver)
return -ENOMEM;
acm_tty_driver->owner = THIS_MODULE,
acm_tty_driver->driver_name = "acm",
acm_tty_driver->name = "ttyACM",
acm_tty_driver->major = ACM_TTY_MAJOR,
acm_tty_driver->minor_start = 0,
acm_tty_driver->type = TTY_DRIVER_TYPE_SERIAL,
acm_tty_driver->subtype = SERIAL_TYPE_NORMAL,
acm_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
acm_tty_driver->init_termios = tty_std_termios;
acm_tty_driver->init_termios.c_cflag = B9600 | CS8 | CREAD |
HUPCL | CLOCAL;
tty_set_operations(acm_tty_driver, &acm_ops);
retval = tty_register_driver(acm_tty_driver);
if (retval) {
put_tty_driver(acm_tty_driver);
return retval;
}
retval = usb_register(&acm_driver);
if (retval) {
tty_unregister_driver(acm_tty_driver);
put_tty_driver(acm_tty_driver);
return retval;
}
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_DESC "\n");
return 0;
}
static void __exit acm_exit(void)
{
usb_deregister(&acm_driver);
tty_unregister_driver(acm_tty_driver);
put_tty_driver(acm_tty_driver);
}
module_init(acm_init);
module_exit(acm_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV_MAJOR(ACM_TTY_MAJOR);
| gpl-2.0 |
dixon13/CBA_A3 | mod.cpp | 1 | 1095 | name = "Community Base Addons v3.6.1";
picture = "logo_cba_ca.paa";
actionName = "Website";
action = "https://github.com/CBATeam/CBA_A3/wiki";
description = "Bugtracker: https://github.com/CBATeam/CBA_A3/issues<br />Documentation: https://cbateam.github.io/CBA_A3/docs/files/overview-txt.html";
logo = "logo_cba_ca.paa";
logoOver = "logo_cba_ca.paa";
tooltip = "Community Base Addons";
tooltipOwned = "Community Base Addons Owned";
overview = "What does the name Community Base Addons mean? It is a system that offers a range of features for addon-makers and mission designers. This includes a collection of community-built functions, an integrated keybinding system, and extend event-handler support for compatibility with other 3rd-party addons; and much much more.";
author = "CBA Team";
overviewPicture = "logo_cba_ca.paa";
overviewText = "Community Base Addons overviewText";
overviewFootnote = "<br /><br /><t color='#999999'>This content is under GPLv2 License.<br />Press <t /><t color='#19d3ff'>Left Shift + P<t /><t color='#999999'> to open the store page for more information.<t />";
| gpl-2.0 |
feiliuesmf/mom | src/atmos_param/cosp/llnl/pf_to_mr.f | 1 | 5874 |
!---------------------------------------------------------------------
!------------ FMS version number and tagname for this file -----------
! $Id: pf_to_mr.f,v 19.0 2012/01/06 20:04:30 fms Exp $
! $Name: siena_201207 $
! (c) 2008, Lawrence Livermore National Security Limited Liability Corporation.
! All rights reserved.
!
! Redistribution and use in source and binary forms, with or without modification, are permitted
! provided that the following conditions are met:
!
! * Redistributions of source code must retain the above copyright notice, this list
! of conditions and the following disclaimer.
! * Redistributions in binary form must reproduce the above copyright notice, this list
! of conditions and the following disclaimer in the documentation and/or other materials
! provided with the distribution.
! * Neither the name of the Lawrence Livermore National Security Limited Liability Corporation
! nor the names of its contributors may be used to endorse or promote products derived from
! this software without specific prior written permission.
!
! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
! IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
! FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
! CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
! DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
! IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
! OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
subroutine pf_to_mr(me,npoints,nlev,ncol,rain_ls,snow_ls,grpl_ls,
& rain_cv,snow_cv,prec_frac,
& p,t,mx_rain_ls,mx_snow_ls,mx_grpl_ls,
& mx_rain_cv,mx_snow_cv)
implicit none
integer me
INTEGER npoints ! number of model points in the horizontal
INTEGER nlev ! number of model levels in column
INTEGER ncol ! number of subcolumns
INTEGER i,j,ilev,ibox
REAL rain_ls(npoints,nlev),snow_ls(npoints,nlev) ! large-scale precipitation flux
REAL grpl_ls(npoints,nlev)
REAL rain_cv(npoints,nlev),snow_cv(npoints,nlev) ! convective precipitation flux
REAL prec_frac(npoints,ncol,nlev) ! 0 -> clear sky
! 1 -> LS precipitation
! 2 -> CONV precipitation
! 3 -> both
REAL mx_rain_ls(npoints,ncol,nlev),mx_snow_ls(npoints,ncol,nlev)
REAL mx_grpl_ls(npoints,ncol,nlev)
REAL mx_rain_cv(npoints,ncol,nlev),mx_snow_cv(npoints,ncol,nlev)
REAL p(npoints,nlev),t(npoints,nlev)
REAL ar,as,ag,br,bs,bg,nr,ns,ng,rho0,rhor,rhos,rhog,rho
REAL term1r,term1s,term1g,term2r,term2s,term2g,term3
REAL term4r_ls,term4s_ls,term4g_ls,term4r_cv,term4s_cv
REAL term1x2r,term1x2s,term1x2g,t123r,t123s,t123g
! method from Khairoutdinov and Randall (2003 JAS)
! --- List of constants from Appendix B
! Constant in fall speed formula
ar=842.
as=4.84
ag=94.5
! Exponent in fall speed formula
br=0.8
bs=0.25
bg=0.5
! Intercept parameter
nr=8.*1000.*1000.
ns=3.*1000.*1000.
ng=4.*1000.*1000.
! Densities for air and hydrometeors
rho0=1.29
rhor=1000.
rhos=100.
rhog=400.
! Term 1 of Eq. (A19).
term1r=ar*17.8379/6.
term1s=as*8.28508/6.
term1g=ag*11.6317/6.
! Term 2 of Eq. (A19).
term2r=(3.14159265*rhor*nr)**(-br/4.)
term2s=(3.14159265*rhos*ns)**(-bs/4.)
term2g=(3.14159265*rhog*ng)**(-bg/4.)
term1x2r=term1r*term2r
term1x2s=term1s*term2s
term1x2g=term1g*term2g
do ilev=1,nlev
do j=1,npoints
rho=p(j,ilev)/(287.05*t(j,ilev))
term3=(rho0/rho)**0.5
! Term 4 of Eq. (A19).
t123r=term1x2r*term3
t123s=term1x2s*term3
t123g=term1x2g*term3
term4r_ls=rain_ls(j,ilev)/(t123r)
term4s_ls=snow_ls(j,ilev)/(t123s)
term4g_ls=grpl_ls(j,ilev)/(t123g)
term4r_cv=rain_cv(j,ilev)/(t123r)
term4s_cv=snow_cv(j,ilev)/(t123s)
do ibox=1,ncol
mx_rain_ls(j,ibox,ilev)=0.
mx_snow_ls(j,ibox,ilev)=0.
mx_grpl_ls(j,ibox,ilev)=0.
mx_rain_cv(j,ibox,ilev)=0.
mx_snow_cv(j,ibox,ilev)=0.
if ((prec_frac(j,ibox,ilev) .eq. 1.) .or.
& (prec_frac(j,ibox,ilev) .eq. 3.)) then
mx_rain_ls(j,ibox,ilev)=
& (term4r_ls**(1./(1.+br/4.)))/rho
mx_snow_ls(j,ibox,ilev)=
& (term4s_ls**(1./(1.+bs/4.)))/rho
mx_grpl_ls(j,ibox,ilev)=
& (term4g_ls**(1./(1.+bg/4.)))/rho
endif
if ((prec_frac(j,ibox,ilev) .eq. 2.) .or.
& (prec_frac(j,ibox,ilev) .eq. 3.)) then
mx_rain_cv(j,ibox,ilev)=
& (term4r_cv**(1./(1.+br/4.)))/rho
mx_snow_cv(j,ibox,ilev)=
& (term4s_cv**(1./(1.+bs/4.)))/rho
endif
enddo ! loop over ncol
enddo ! loop over npoints
enddo ! loop over nlev
end
| gpl-2.0 |
xdajog/kernel_fx3q_aosp | sound/soc/msm/msm8930.c | 1 | 60473 | /* Copyright (c) 2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
/* LGE_CHANGE */
#define DEBUG 1
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/mfd/pm8xxx/spk.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/pcm.h>
#include <sound/jack.h>
#include <asm/mach-types.h>
#include <mach/socinfo.h>
#include "msm-pcm-routing.h"
#include "../codecs/wcd9304.h"
#ifdef CONFIG_LGE_AUDIO_TPA2028D
#include <sound/tpa2028d.h>
#endif
/* 8930 machine driver */
#if defined(CONFIG_SWITCH_FSA8008)
#include "../../../arch/arm/mach-msm/include/mach/board_lge.h"
#endif
#if defined(CONFIG_MACH_MSM8930_LGPS9)
#include "../../../arch/arm/mach-msm/lge/lgps9/board-lgps9.h"
#endif
#if defined(CONFIG_MACH_MSM8930_FX3)
#include "../../../arch/arm/mach-msm/lge/fx3/board-fx3.h"
#endif
#define MSM8930_SPK_ON 1
#define MSM8930_SPK_OFF 0
#define BTSCO_RATE_8KHZ 8000
#define BTSCO_RATE_16KHZ 16000
#define SPK_AMP_POS 0x1
#define SPK_AMP_NEG 0x2
#define SPKR_BOOST_GPIO 15
#define LEFT_SPKR_AMPL_GPIO 15
#define DEFAULT_PMIC_SPK_GAIN 0x0D
#define SITAR_EXT_CLK_RATE 12288000
#define SITAR_MBHC_DEF_BUTTONS 8
#define SITAR_MBHC_DEF_RLOADS 5
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
#define GPIO_MI2S_WS 47
#define GPIO_MI2S_SCLK 48
#define GPIO_MI2S_DOUT3 49
#define GPIO_MI2S_DOUT2 50
#define GPIO_MI2S_DOUT1 51
#define GPIO_MI2S_DOUT0 52
#define GPIO_MI2S_MCLK 53
struct request_gpio {
unsigned gpio_no;
char *gpio_name;
};
static struct request_gpio mi2s_gpio[] = {
{
.gpio_no = GPIO_MI2S_WS,
.gpio_name = "MI2S_WS",
},
{
.gpio_no = GPIO_MI2S_SCLK,
.gpio_name = "MI2S_SCLK",
},
{
.gpio_no = GPIO_MI2S_DOUT0,
.gpio_name = "MI2S_DOUT0",
},
};
static struct clk *mi2s_osr_clk;
static struct clk *mi2s_bit_clk;
static atomic_t mi2s_rsc_ref;
#endif
#define GPIO_AUX_PCM_DOUT 63
#define GPIO_AUX_PCM_DIN 64
#define GPIO_AUX_PCM_SYNC 65
#define GPIO_AUX_PCM_CLK 66
#ifdef CONFIG_LGE_AUDIO_TPA2028D
#define MSM8960_SPK_ON 1
#define MSM8960_SPK_OFF 0
#endif
//LGE_CHANGE_S [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
#define GPIO_MIC_FM_SW 51
#define MIC_ON 0
#define FM_ON 1
//LGE_CHANGE_E [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
static int msm8930_spk_control;
static int msm8930_slim_0_rx_ch = 1;
static int msm8930_slim_0_tx_ch = 1;
static int msm8930_pmic_spk_gain = DEFAULT_PMIC_SPK_GAIN;
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
static int msm_slim_3_rx_ch = 1;
#endif
#ifdef CONFIG_LGE_AUDIO_TPA2028D
#else
static int msm8930_ext_spk_pamp;
#endif
static int msm8930_btsco_rate = BTSCO_RATE_8KHZ;
static int msm8930_btsco_ch = 1;
static int msm8930_auxpcm_rate = BTSCO_RATE_8KHZ;
static struct clk *codec_clk;
static int clk_users;
static int msm8930_headset_gpios_configured;
static struct snd_soc_jack hs_jack;
static struct snd_soc_jack button_jack;
static atomic_t auxpcm_rsc_ref;
#ifdef CONFIG_ANDROID_SW_IRRC
#define EXT_AMP_MUTE 0
#define EXT_AMP_UNMUTE 1
struct timer_list EXT_AMP_ON_Timer;
unsigned long pm8xxx_spk_mute_data=1; // 0 is unmute
int PM8xxx_EXT_SPK_Force_Mute=0; // 0 mute, 1 unmute
#endif
//LGE_CHANGE_S [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
static int msm8930_mic_fm_sw_set = MIC_ON;
//LGE_CHANGE_E [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
static int msm8930_enable_codec_ext_clk(
struct snd_soc_codec *codec, int enable,
bool dapm);
static struct sitar_mbhc_config mbhc_cfg = {
.headset_jack = &hs_jack,
.button_jack = &button_jack,
.read_fw_bin = false,
.calibration = NULL,
.micbias = SITAR_MICBIAS2,
.mclk_cb_fn = msm8930_enable_codec_ext_clk,
.mclk_rate = SITAR_EXT_CLK_RATE,
.gpio = 0,
.gpio_irq = 0,
.gpio_level_insert = 1,
};
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
/* Shared channel numbers for Slimbus ports that connect APQ to MDM. */
enum {
SLIM_1_RX_1 = 145, /* BT-SCO and USB TX */
SLIM_1_TX_1 = 146, /* BT-SCO, USB, and MI2S RX */
SLIM_3_RX_1 = 151, /* External echo-cancellation ref */
SLIM_3_RX_2 = 152, /* External echo-cancellation ref */
SLIM_3_TX_1 = 147, /* HDMI RX */
SLIM_4_TX_1 = 148, /* In-call recording RX */
SLIM_4_TX_2 = 149, /* In-call recording RX */
SLIM_4_RX_1 = 150, /* In-call music delivery TX */
};
#endif
static void msm8930_ext_control(struct snd_soc_codec *codec)
{
struct snd_soc_dapm_context *dapm = &codec->dapm;
pr_debug("%s: msm8930_spk_control = %d", __func__, msm8930_spk_control);
#if defined(CONFIG_LGE_AUDIO_TPA2028D)
if (msm8930_spk_control == MSM8960_SPK_ON)
snd_soc_dapm_enable_pin(dapm, "Ext Spk");
else
snd_soc_dapm_disable_pin(dapm, "Ext Spk");
#else
if (msm8930_spk_control == MSM8930_SPK_ON) {
snd_soc_dapm_enable_pin(dapm, "Ext Spk Left Pos");
snd_soc_dapm_enable_pin(dapm, "Ext Spk left Neg");
} else {
snd_soc_dapm_disable_pin(dapm, "Ext Spk Left Pos");
snd_soc_dapm_disable_pin(dapm, "Ext Spk Left Neg");
}
#endif
snd_soc_dapm_sync(dapm);
}
static int msm8930_get_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm8930_spk_control = %d", __func__, msm8930_spk_control);
ucontrol->value.integer.value[0] = msm8930_spk_control;
return 0;
}
static int msm8930_set_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
pr_debug("%s()\n", __func__);
if (msm8930_spk_control == ucontrol->value.integer.value[0])
return 0;
msm8930_spk_control = ucontrol->value.integer.value[0];
msm8930_ext_control(codec);
return 1;
}
#ifdef CONFIG_LGE_AUDIO_TPA2028D
#else
static int msm8930_cfg_spkr_gpio(int gpio,
int enable, const char *gpio_label)
{
int ret = 0;
pr_debug("%s: Configure %s GPIO %u",
__func__, gpio_label, gpio);
ret = gpio_request(gpio, gpio_label);
if (ret)
return ret;
pr_debug("%s: Enable %s gpio %u\n",
__func__, gpio_label, gpio);
gpio_direction_output(gpio, enable);
return ret;
}
static void msm8960_ext_spk_power_amp_on(u32 spk)
{
int ret = 0;
if (spk & (SPK_AMP_POS | SPK_AMP_NEG)) {
if ((msm8930_ext_spk_pamp & SPK_AMP_POS) &&
(msm8930_ext_spk_pamp & SPK_AMP_NEG)) {
pr_debug("%s() External Bottom Speaker Ampl already "
"turned on. spk = 0x%08x\n", __func__, spk);
return;
}
msm8930_ext_spk_pamp |= spk;
if ((msm8930_ext_spk_pamp & SPK_AMP_POS) &&
(msm8930_ext_spk_pamp & SPK_AMP_NEG)) {
if (socinfo_get_pmic_model() == PMIC_MODEL_PM8917) {
ret = msm8930_cfg_spkr_gpio(
LEFT_SPKR_AMPL_GPIO,
1, "LEFT_SPKR_AMPL");
if (ret) {
pr_err("%s: Failed to config ampl gpio %u\n",
__func__, LEFT_SPKR_AMPL_GPIO);
return;
}
} else {
/*
* 8930 CDP does not have a 5V speaker boost,
* hence the GPIO enable for speaker boost is
* only required for platforms other than CDP
*/
//LGE_START,myungwon.kim,Not Use BOOST_SPKR
#if 0
if (!machine_is_msm8930_cdp()) {
ret = msm8930_cfg_spkr_gpio(
SPKR_BOOST_GPIO, 1, "SPKR_BOOST");
if (ret) {
pr_err("%s: Failure: spkr boost gpio %u\n",
__func__, SPKR_BOOST_GPIO);
return;
}
}
#endif
#ifdef CONFIG_ANDROID_SW_IRRC
if(PM8xxx_EXT_SPK_Force_Mute==1){
printk("msm8960_ext_spk_power_amp_on Force_Mute, PM8xxx_EXT_SPK_Force_Mute = %d\n",PM8xxx_EXT_SPK_Force_Mute);
pm8xxx_spk_enable(MSM8930_SPK_OFF);
// pm8xxx_spk_mute(0);
}
else{
pm8xxx_spk_enable(MSM8930_SPK_ON);
}
#else
pm8xxx_spk_enable(MSM8930_SPK_ON);
#endif
}
pr_debug("%s: sleeping 10 ms after turning on external "
" Left Speaker Ampl\n", __func__);
usleep_range(10000, 10000);
}
} else {
pr_err("%s: ERROR : Invalid External Speaker Ampl. spk = 0x%08x\n",
__func__, spk);
return;
}
}
static void msm8960_ext_spk_power_amp_off(u32 spk)
{
if (spk & (SPK_AMP_POS | SPK_AMP_NEG)) {
if (!msm8930_ext_spk_pamp)
return;
if (socinfo_get_pmic_model() == PMIC_MODEL_PM8917) {
gpio_free(LEFT_SPKR_AMPL_GPIO);
msm8930_ext_spk_pamp = 0;
return;
}
//LGE_START,myungwon.kim,Not Use BOOST_SPKR
#if 0
if (!machine_is_msm8930_cdp()) {
pr_debug("%s: Free speaker boost gpio %u\n",
__func__, SPKR_BOOST_GPIO);
gpio_direction_output(SPKR_BOOST_GPIO, 0);
gpio_free(SPKR_BOOST_GPIO);
}
#endif
pm8xxx_spk_enable(MSM8930_SPK_OFF);
msm8930_ext_spk_pamp = 0;
pr_debug("%s: slepping 10 ms after turning on external "
" Left Speaker Ampl\n", __func__);
usleep_range(10000, 10000);
} else {
pr_err("%s: ERROR : Invalid External Speaker Ampl. spk = 0x%08x\n",
__func__, spk);
return;
}
}
#endif
static int msm8930_spkramp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
pr_debug("%s() %x\n", __func__, SND_SOC_DAPM_EVENT_ON(event));
#ifdef CONFIG_LGE_AUDIO_TPA2028D
printk(KERN_DEBUG "spk amp event\n");
if (SND_SOC_DAPM_EVENT_ON(event))
set_amp_gain(MSM8960_SPK_ON);
else
set_amp_gain(MSM8960_SPK_OFF);
return 0;
#else
if (SND_SOC_DAPM_EVENT_ON(event)) {
if (!strncmp(w->name, "Ext Spk Left Pos", 17))
msm8960_ext_spk_power_amp_on(SPK_AMP_POS);
else if (!strncmp(w->name, "Ext Spk Left Neg", 17))
msm8960_ext_spk_power_amp_on(SPK_AMP_NEG);
else {
pr_err("%s() Invalid Speaker Widget = %s\n",
__func__, w->name);
return -EINVAL;
}
} else {
if (!strncmp(w->name, "Ext Spk Left Pos", 17))
msm8960_ext_spk_power_amp_off(SPK_AMP_POS);
else if (!strncmp(w->name, "Ext Spk Left Neg", 17))
msm8960_ext_spk_power_amp_off(SPK_AMP_NEG);
else {
pr_err("%s() Invalid Speaker Widget = %s\n",
__func__, w->name);
return -EINVAL;
}
}
return 0;
#endif
}
static int msm8930_enable_codec_ext_clk(
struct snd_soc_codec *codec, int enable,
bool dapm)
{
pr_debug("%s: enable = %d\n", __func__, enable);
#ifdef CONFIG_SWITCH_FSA8008
if (enable == MCLK_ON_BANDGAP_ON) {
clk_users++;
pr_debug("%s: clk_users = %d\n", __func__, clk_users);
if (clk_users != 1)
return 0;
if (codec_clk) {
clk_set_rate(codec_clk, SITAR_EXT_CLK_RATE);
clk_prepare_enable(codec_clk);
sitar_mclk_enable(codec, enable, dapm);
} else {
pr_err("%s: Error setting Sitar MCLK\n", __func__);
clk_users--;
return -EINVAL;
}
} else if ((enable == MCLK_OFF_BANDGAP_OFF) ||
(enable == MCLK_OF_BANDGAP_ON)){
pr_debug("%s: clk_users = %d\n", __func__, clk_users);
if (clk_users == 0)
return 0;
clk_users--;
if (!clk_users) {
pr_debug("%s: disabling MCLK. clk_users = %d\n",
__func__, clk_users);
sitar_mclk_enable(codec, enable, dapm);
clk_disable_unprepare(codec_clk);
}
}
#else
if (enable) {
clk_users++;
pr_debug("%s: clk_users = %d\n", __func__, clk_users);
if (clk_users != 1)
return 0;
if (codec_clk) {
clk_set_rate(codec_clk, SITAR_EXT_CLK_RATE);
clk_prepare_enable(codec_clk);
sitar_mclk_enable(codec, 1, dapm);
} else {
pr_err("%s: Error setting Sitar MCLK\n", __func__);
clk_users--;
return -EINVAL;
}
} else {
pr_debug("%s: clk_users = %d\n", __func__, clk_users);
if (clk_users == 0)
return 0;
clk_users--;
if (!clk_users) {
pr_debug("%s: disabling MCLK. clk_users = %d\n",
__func__, clk_users);
sitar_mclk_enable(codec, 0, dapm);
clk_disable_unprepare(codec_clk);
}
}
#endif
return 0;
}
static int msm8930_mclk_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
pr_debug("%s: event = %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
return msm8930_enable_codec_ext_clk(w->codec, 1, true);
case SND_SOC_DAPM_POST_PMD:
return msm8930_enable_codec_ext_clk(w->codec, 0, true);
}
return 0;
}
static const struct snd_soc_dapm_widget msm8930_dapm_widgets[] = {
SND_SOC_DAPM_SUPPLY("MCLK", SND_SOC_NOPM, 0, 0,
msm8930_mclk_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
#ifdef CONFIG_LGE_AUDIO_TPA2028D
SND_SOC_DAPM_SPK("Ext Spk", msm8930_spkramp_event),
#else
SND_SOC_DAPM_SPK("Ext Spk Left Pos", msm8930_spkramp_event),
SND_SOC_DAPM_SPK("Ext Spk Left Neg", msm8930_spkramp_event),
#endif
SND_SOC_DAPM_MIC("Headset Mic", NULL),
SND_SOC_DAPM_MIC("Digital Mic1", NULL),
SND_SOC_DAPM_MIC("ANCRight Headset Mic", NULL),
SND_SOC_DAPM_MIC("ANCLeft Headset Mic", NULL),
SND_SOC_DAPM_MIC("Digital Mic1", NULL),
SND_SOC_DAPM_MIC("Digital Mic2", NULL),
SND_SOC_DAPM_MIC("Digital Mic3", NULL),
SND_SOC_DAPM_MIC("Digital Mic4", NULL),
};
static const struct snd_soc_dapm_route common_audio_map[] = {
{"RX_BIAS", NULL, "MCLK"},
{"LDO_H", NULL, "MCLK"},
{"MIC BIAS1 Internal1", NULL, "MCLK"},
{"MIC BIAS2 Internal1", NULL, "MCLK"},
/* Speaker path */
#if defined(CONFIG_LGE_AUDIO_TPA2028D)
{"Ext Spk", NULL, "LINEOUT1"},
#else
{"Ext Spk Left Pos", NULL, "LINEOUT1"},
{"Ext Spk Left Neg", NULL, "LINEOUT2"},
#endif
/* Headset Mic */
#ifdef CONFIG_SWITCH_FSA8008
{"AMIC2", NULL, "LDO_H"},
{"MIC BIAS2 External", NULL, "Headset Mic"},
#else
{"AMIC2", NULL, "MIC BIAS2 External"},
{"MIC BIAS2 External", NULL, "Headset Mic"},
#endif
/* Microphone path */
/*LGE_CHANGE_START, fixed to MIC BIAS for F3 */
{"AMIC1", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "ANCLeft Headset Mic"},
{"AMIC3", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "ANCRight Headset Mic"},
/*LGE_CHANGE_END */
{"HEADPHONE", NULL, "LDO_H"},
/**
* The digital Mic routes are setup considering
* fluid as default device.
*/
/**
* Digital Mic1. Front Bottom left Mic on Fluid and MTP.
* Digital Mic GM5 on CDP mainboard.
* Conncted to DMIC1 Input on Sitar codec.
*/
#if 0
{"DMIC1", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "Digital Mic1"},
/**
* Digital Mic2. Back top MIC on Fluid.
* Digital Mic GM6 on CDP mainboard.
* Conncted to DMIC2 Input on Sitar codec.
*/
{"DMIC2", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "Digital Mic2"},
/**
* Digital Mic3. Back Bottom Digital Mic on Fluid.
* Digital Mic GM1 on CDP mainboard.
* Conncted to DMIC4 Input on Sitar codec.
*/
{"DMIC3", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "Digital Mic3"},
/**
* Digital Mic4. Back top Digital Mic on Fluid.
* Digital Mic GM2 on CDP mainboard.
* Conncted to DMIC3 Input on Sitar codec.
*/
{"DMIC4", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "Digital Mic4"},
#endif
};
static const char *spk_function[] = {"Off", "On"};
static const char *slim0_rx_ch_text[] = {"One", "Two"};
static const char *slim0_tx_ch_text[] = {"One", "Two", "Three", "Four"};
static const struct soc_enum msm8930_enum[] = {
SOC_ENUM_SINGLE_EXT(2, spk_function),
SOC_ENUM_SINGLE_EXT(2, slim0_rx_ch_text),
SOC_ENUM_SINGLE_EXT(4, slim0_tx_ch_text),
};
static const char *btsco_rate_text[] = {"8000", "16000"};
static const struct soc_enum msm8930_btsco_enum[] = {
SOC_ENUM_SINGLE_EXT(2, btsco_rate_text),
};
//LGE_START, MYUNGWON.KIM
static const char *auxpcm_rate_text[] = {"rate_8000", "rate_16000"};
static const struct soc_enum msm8930_auxpcm_enum[] = {
SOC_ENUM_SINGLE_EXT(2, auxpcm_rate_text),
};
//LGE_END , MYUNGWON.KIM
#ifdef CONFIG_ANDROID_SW_IRRC
static const char *PMxxxx_SKP_Mute[] = {"Unmute","Mute"};
static const struct soc_enum PMxxxx_SPK_Mute_enum[] = {
SOC_ENUM_SINGLE_EXT(2, PMxxxx_SKP_Mute),
};
#endif
//LGE_CHANGE_S [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
static const char* mic_fm_sw_text[] = {"mic_on", "fm_on"};
static const struct soc_enum msm8930_mic_fm_sw_enum[] = {
SOC_ENUM_SINGLE_EXT(2, mic_fm_sw_text),
};
//LGE_CHANGE_E [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
static int msm8930_slim_0_rx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm8930_slim_0_rx_ch = %d\n", __func__,
msm8930_slim_0_rx_ch);
ucontrol->value.integer.value[0] = msm8930_slim_0_rx_ch - 1;
return 0;
}
static int msm8930_slim_0_rx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm8930_slim_0_rx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm8930_slim_0_rx_ch = %d\n", __func__,
msm8930_slim_0_rx_ch);
return 1;
}
static int msm8930_slim_0_tx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm8930_slim_0_tx_ch = %d\n", __func__,
msm8930_slim_0_tx_ch);
ucontrol->value.integer.value[0] = msm8930_slim_0_tx_ch - 1;
return 0;
}
static int msm8930_slim_0_tx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm8930_slim_0_tx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm8930_slim_0_tx_ch = %d\n", __func__,
msm8930_slim_0_tx_ch);
return 1;
}
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
static int msm_slim_3_rx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_slim_3_rx_ch = %d\n", __func__,
msm_slim_3_rx_ch);
ucontrol->value.integer.value[0] = msm_slim_3_rx_ch - 1;
return 0;
}
static int msm_slim_3_rx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_slim_3_rx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_slim_3_rx_ch = %d\n", __func__,
msm_slim_3_rx_ch);
return 1;
}
#endif
static int msm8930_btsco_rate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm8930_btsco_rate = %d", __func__, msm8930_btsco_rate);
ucontrol->value.integer.value[0] = msm8930_btsco_rate;
return 0;
}
static int msm8930_btsco_rate_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (ucontrol->value.integer.value[0]) {
case 8000:
msm8930_btsco_rate = BTSCO_RATE_8KHZ;
break;
case 16000:
msm8930_btsco_rate = BTSCO_RATE_16KHZ;
break;
default:
msm8930_btsco_rate = BTSCO_RATE_8KHZ;
break;
}
pr_debug("%s: msm8930_btsco_rate = %d\n", __func__, msm8930_btsco_rate);
return 0;
}
//LGE_START, MYUNGWON.KIM
static int msm8930_auxpcm_rate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm8930_auxpcm_rate = %d", __func__,
msm8930_auxpcm_rate);
ucontrol->value.integer.value[0] = msm8930_auxpcm_rate;
return 0;
}
static int msm8930_auxpcm_rate_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (ucontrol->value.integer.value[0]) {
case 0:
msm8930_auxpcm_rate = BTSCO_RATE_8KHZ;
break;
case 1:
msm8930_auxpcm_rate = BTSCO_RATE_16KHZ;
break;
default:
msm8930_auxpcm_rate = BTSCO_RATE_8KHZ;
break;
}
pr_debug("%s: msm8930_auxpcm_rate = %d"
"ucontrol->value.integer.value[0] = %d\n", __func__,
msm8930_auxpcm_rate,
(int)ucontrol->value.integer.value[0]);
return 0;
}
//LGE_END , MYUNGWON.KIM
//LGE_CHANGE_S [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
static int msm8930_mic_fm_sw_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm8930_mic_fm_sw_set = %d\n", __func__,
msm8930_mic_fm_sw_set);
//ucontrol->value.integer.value[0] = msm8930_mic_fm_sw_set;
return 0;
}
//LGE_CHANGE_E [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
//LGE_CHANGE_S [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
static int msm8930_mic_fm_sw_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
switch(ucontrol->value.integer.value[0]) {
case 0:
gpio_direction_output(GPIO_MIC_FM_SW, MIC_ON);
break;
case 1:
gpio_direction_output(GPIO_MIC_FM_SW, FM_ON);
break;
default:
gpio_direction_output(GPIO_MIC_FM_SW, MIC_ON);
}
pr_debug("%s: ms8930_mic_fm_set = %d"
"ucontrol->value.integer.value[0] = %d\n", __func__,
msm8930_mic_fm_sw_set,
(int)ucontrol->value.integer.value[0]);
return 0;
}
//LGE_CHANGE_E [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
static const char *pmic_spk_gain_text[] = {
"NEG_6_DB", "NEG_4_DB", "NEG_2_DB", "ZERO_DB", "POS_2_DB", "POS_4_DB",
"POS_6_DB", "POS_8_DB", "POS_10_DB", "POS_12_DB", "POS_14_DB",
"POS_16_DB", "POS_18_DB", "POS_20_DB", "POS_22_DB", "POS_24_DB"
};
static const struct soc_enum msm8960_pmic_spk_gain_enum[] = {
SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(pmic_spk_gain_text),
pmic_spk_gain_text),
};
static int msm8930_pmic_gain_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm8930_pmic_spk_gain = %d\n", __func__,
msm8930_pmic_spk_gain);
ucontrol->value.integer.value[0] = msm8930_pmic_spk_gain;
return 0;
}
static int msm8930_pmic_gain_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int ret = 0;
msm8930_pmic_spk_gain = ucontrol->value.integer.value[0];
/* LGE_CHANGE */
// MYUNGWON.KIM Block Duplicated Code 2012-11-22
// if (socinfo_get_pmic_model() != PMIC_MODEL_PM8917)
// ret = pm8xxx_spk_gain(msm8930_pmic_spk_gain);
ret = pm8xxx_spk_gain(msm8930_pmic_spk_gain);
pr_debug("%s: msm8930_pmic_spk_gain = %d"
" ucontrol->value.integer.value[0] = %d\n", __func__,
msm8930_pmic_spk_gain,
(int) ucontrol->value.integer.value[0]);
return ret;
}
#ifdef CONFIG_ANDROID_SW_IRRC
void pm8xxx_spk_unmute_timer_function(unsigned long data)
{
printk("pm8xxx_spk_unmute_timer_function data %d\n",(int)data);
// pm8xxx_spk_mute(data);
if((int)data==MSM8930_SPK_ON) //unmute case
{
printk("pm8xxx_spk_unmute_timer_function data %d Unmute\n",(int)data);
PM8xxx_EXT_SPK_Force_Mute=0;
pm8xxx_spk_enable((int)data);
// pm8xxx_spk_mute(1);
}
else{
printk("pm8xxx_spk_unmute_timer_function data %d mute Case\n",(int)data);
PM8xxx_EXT_SPK_Force_Mute=1;
pm8xxx_spk_enable((int)data);
// pm8xxx_spk_mute(0);
}
}
static int msm8930_pmic_mute_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int ret = 0;
int msm8930_pmic_mute_enable =0;
int temp_pp = (int)ucontrol->value.integer.value[0];
del_timer(&EXT_AMP_ON_Timer);
init_timer(&EXT_AMP_ON_Timer);
pm8xxx_spk_mute_data=MSM8930_SPK_ON;
PM8xxx_EXT_SPK_Force_Mute=1;
EXT_AMP_ON_Timer.expires = get_jiffies_64()+ (9*HZ/10); //(700ms)
EXT_AMP_ON_Timer.data= pm8xxx_spk_mute_data;
EXT_AMP_ON_Timer.function = pm8xxx_spk_unmute_timer_function;
add_timer(&EXT_AMP_ON_Timer);
printk("msm8930_pmic_mute_put msm8930_pmic_mute_enable %d \n",temp_pp);
if(ucontrol->value.integer.value[0]==1){
msm8930_pmic_mute_enable=MSM8930_SPK_OFF;
printk("msm8930_pmic_mute_put msm8930_pmic_mute_enable MUTE\n");
}
else{
msm8930_pmic_mute_enable=MSM8930_SPK_ON;
printk("msm8930_pmic_mute_put msm8930_pmic_mute_enable UNMUTE\n");
}
pm8xxx_spk_enable(msm8930_pmic_mute_enable);
// pm8xxx_spk_mute(0);
return ret;
}
static int msm8930_pmic_mute_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int ret = 0;
int msm8930_pmic_mute_enable = ucontrol->value.integer.value[0];
pr_debug("%s: msm8930_pmic_mute_enable = %d"
" ucontrol->value.integer.value[0] = %d\n", __func__,
msm8930_pmic_mute_enable,
(int) ucontrol->value.integer.value[0]);
return ret;
}
#endif
static const struct snd_kcontrol_new sitar_msm8930_controls[] = {
SOC_ENUM_EXT("Speaker Function", msm8930_enum[0], msm8930_get_spk,
msm8930_set_spk),
SOC_ENUM_EXT("SLIM_0_RX Channels", msm8930_enum[1],
msm8930_slim_0_rx_ch_get, msm8930_slim_0_rx_ch_put),
SOC_ENUM_EXT("SLIM_0_TX Channels", msm8930_enum[2],
msm8930_slim_0_tx_ch_get, msm8930_slim_0_tx_ch_put),
SOC_ENUM_EXT("PMIC SPK Gain", msm8960_pmic_spk_gain_enum[0],
msm8930_pmic_gain_get, msm8930_pmic_gain_put),
SOC_ENUM_EXT("Internal BTSCO SampleRate", msm8930_btsco_enum[0],
msm8930_btsco_rate_get, msm8930_btsco_rate_put),
/* LGE_CHANGE */
SOC_ENUM_EXT("AUX PCM SampleRate", msm8930_auxpcm_enum[0],
msm8930_auxpcm_rate_get, msm8930_auxpcm_rate_put),
#ifdef CONFIG_ANDROID_SW_IRRC
SOC_ENUM_EXT("SPK Force Mute", PMxxxx_SPK_Mute_enum[0],
msm8930_pmic_mute_get, msm8930_pmic_mute_put),
#endif
//LGE_CHANGE_S [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
SOC_ENUM_EXT("Mic FM Switch", msm8930_mic_fm_sw_enum[0],
msm8930_mic_fm_sw_get, msm8930_mic_fm_sw_put),
//LGE_CHANGE_E [kugchin.kang@lge.com] Audio for L9II, FM Radio Switch, 13-03-21
};
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
static const struct snd_kcontrol_new slim_3_mixer_controls[] = {
SOC_ENUM_EXT("SLIM_3_RX Channels", msm8930_enum[1],
msm_slim_3_rx_ch_get, msm_slim_3_rx_ch_put),
};
static int msm_slim_3_init(struct snd_soc_pcm_runtime *rtd)
{
int err = 0;
struct snd_soc_platform *platform = rtd->platform;
err = snd_soc_add_platform_controls(platform,
slim_3_mixer_controls,
ARRAY_SIZE(slim_3_mixer_controls));
if (err < 0)
return err;
return 0;
}
#endif
static void *def_sitar_mbhc_cal(void)
{
void *sitar_cal;
struct sitar_mbhc_btn_detect_cfg *btn_cfg;
u16 *btn_low, *btn_high;
u8 *n_ready, *n_cic, *gain;
sitar_cal = kzalloc(SITAR_MBHC_CAL_SIZE(SITAR_MBHC_DEF_BUTTONS,
SITAR_MBHC_DEF_RLOADS),
GFP_KERNEL);
if (!sitar_cal) {
pr_err("%s: out of memory\n", __func__);
return NULL;
}
#define S(X, Y) ((SITAR_MBHC_CAL_GENERAL_PTR(sitar_cal)->X) = (Y))
S(t_ldoh, 100);
S(t_bg_fast_settle, 100);
S(t_shutdown_plug_rem, 255);
S(mbhc_nsa, 4);
S(mbhc_navg, 4);
#undef S
#define S(X, Y) ((SITAR_MBHC_CAL_PLUG_DET_PTR(sitar_cal)->X) = (Y))
S(mic_current, SITAR_PID_MIC_5_UA);
S(hph_current, SITAR_PID_MIC_5_UA);
S(t_mic_pid, 100);
S(t_ins_complete, 250);
S(t_ins_retry, 200);
#undef S
#define S(X, Y) ((SITAR_MBHC_CAL_PLUG_TYPE_PTR(sitar_cal)->X) = (Y))
S(v_no_mic, 30);
S(v_hs_max, 1650);
#undef S
#define S(X, Y) ((SITAR_MBHC_CAL_BTN_DET_PTR(sitar_cal)->X) = (Y))
S(c[0], 62);
S(c[1], 124);
S(nc, 1);
S(n_meas, 3);
S(mbhc_nsc, 11);
S(n_btn_meas, 1);
S(n_btn_con, 2);
S(num_btn, SITAR_MBHC_DEF_BUTTONS);
S(v_btn_press_delta_sta, 100);
S(v_btn_press_delta_cic, 50);
#undef S
btn_cfg = SITAR_MBHC_CAL_BTN_DET_PTR(sitar_cal);
btn_low = sitar_mbhc_cal_btn_det_mp(btn_cfg, SITAR_BTN_DET_V_BTN_LOW);
btn_high = sitar_mbhc_cal_btn_det_mp(btn_cfg, SITAR_BTN_DET_V_BTN_HIGH);
btn_low[0] = -50;
btn_high[0] = 10;
btn_low[1] = 11;
btn_high[1] = 38;
btn_low[2] = 39;
btn_high[2] = 64;
btn_low[3] = 65;
btn_high[3] = 91;
btn_low[4] = 92;
btn_high[4] = 115;
btn_low[5] = 116;
btn_high[5] = 141;
btn_low[6] = 142;
btn_high[6] = 163;
btn_low[7] = 164;
btn_high[7] = 250;
n_ready = sitar_mbhc_cal_btn_det_mp(btn_cfg, SITAR_BTN_DET_N_READY);
n_ready[0] = 48;
n_ready[1] = 38;
n_cic = sitar_mbhc_cal_btn_det_mp(btn_cfg, SITAR_BTN_DET_N_CIC);
n_cic[0] = 60;
n_cic[1] = 47;
gain = sitar_mbhc_cal_btn_det_mp(btn_cfg, SITAR_BTN_DET_GAIN);
gain[0] = 11;
gain[1] = 9;
return sitar_cal;
}
static int msm8930_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS];
unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0;
pr_debug("%s: ch=%d\n", __func__,
msm8930_slim_0_rx_ch);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
ret = snd_soc_dai_get_channel_map(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0,
msm8930_slim_0_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(codec_dai, 0, 0,
msm8930_slim_0_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set codec channel map\n",
__func__);
goto end;
}
} else {
ret = snd_soc_dai_get_channel_map(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(cpu_dai,
msm8930_slim_0_tx_ch, tx_ch, 0 , 0);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(codec_dai,
msm8930_slim_0_tx_ch, tx_ch, 0, 0);
if (ret < 0) {
pr_err("%s: failed to set codec channel map\n",
__func__);
goto end;
}
}
end:
return ret;
}
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
static int msm_slimbus_1_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch = SLIM_1_RX_1, tx_ch = SLIM_1_TX_1;
pr_debug("%s: rx_ch=%d,tx_ch=%d\n",__func__, rx_ch,tx_ch);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
pr_debug("%s: APQ BT/USB TX -> SLIMBUS_1_RX -> MDM TX shared ch %d\n",
__func__, rx_ch);
ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0, 1, &rx_ch);
if (ret < 0) {
pr_err("%s: Erorr %d setting SLIM_1 RX channel map\n",
__func__, ret);
goto end;
}
} else {
pr_debug("%s: MDM RX -> SLIMBUS_1_TX -> APQ BT/USB/MI2S Rx shared ch %d\n",
__func__, tx_ch);
ret = snd_soc_dai_set_channel_map(cpu_dai, 1, &tx_ch, 0, 0);
if (ret < 0) {
pr_err("%s: Erorr %d setting SLIM_1 TX channel map\n",
__func__, ret);
goto end;
}
}
end:
return ret;
}
static int msm_slimbus_3_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch[2] = {SLIM_3_RX_1, SLIM_3_RX_2};
pr_debug("%s: slim_3_rx_ch %d, sch %d %d\n",__func__, msm_slim_3_rx_ch,
rx_ch[0], rx_ch[1]);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
pr_debug("%s: slim_3_rx_ch %d, sch %d %d\n",
__func__, msm_slim_3_rx_ch,
rx_ch[0], rx_ch[1]);
ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0,
msm_slim_3_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: Erorr %d setting SLIM_3 RX channel map\n",
__func__, ret);
goto end;
}
} else {
pr_err("%s: SLIMBUS_3_TX not defined for this DAI\n", __func__);
}
end:
return ret;
}
#endif
static int msm8930_audrx_init(struct snd_soc_pcm_runtime *rtd)
{
int err;
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
pr_debug("%s()\n", __func__);
snd_soc_dapm_new_controls(dapm, msm8930_dapm_widgets,
ARRAY_SIZE(msm8930_dapm_widgets));
snd_soc_dapm_add_routes(dapm, common_audio_map,
ARRAY_SIZE(common_audio_map));
#ifdef CONFIG_LGE_AUDIO_TPA2028D
snd_soc_dapm_enable_pin(dapm, "Ext Spk");
#else
snd_soc_dapm_enable_pin(dapm, "Ext Spk Left Pos");
snd_soc_dapm_enable_pin(dapm, "Ext Spk Left Neg");
#endif
snd_soc_dapm_sync(dapm);
err = snd_soc_jack_new(codec, "Headset Jack",
(SND_JACK_HEADSET | SND_JACK_OC_HPHL | SND_JACK_OC_HPHR),
&hs_jack);
if (err) {
pr_err("failed to create new jack\n");
return err;
}
err = snd_soc_jack_new(codec, "Button Jack",
SITAR_JACK_BUTTON_MASK, &button_jack);
if (err) {
pr_err("failed to create new jack\n");
return err;
}
codec_clk = clk_get(cpu_dai->dev, "osr_clk");
#ifdef CONFIG_SWITCH_FSA8008
if (lge_get_board_usembhc()) {
mbhc_cfg.gpio = 37;
mbhc_cfg.gpio_irq = gpio_to_irq(mbhc_cfg.gpio);
sitar_hs_detect(codec, &mbhc_cfg);
} else {
sitar_register_mclk_call_back(codec, msm8930_enable_codec_ext_clk);
}
#else
mbhc_cfg.gpio = 37;
mbhc_cfg.gpio_irq = gpio_to_irq(mbhc_cfg.gpio);
sitar_hs_detect(codec, &mbhc_cfg);
#endif
if (socinfo_get_pmic_model() != PMIC_MODEL_PM8917) {
/* Initialize default PMIC speaker gain */
pm8xxx_spk_gain(DEFAULT_PMIC_SPK_GAIN);
}
return 0;
}
/* LGE_CHANGE */
#if 0
static struct snd_soc_dsp_link lpa_fe_media = {
.playback = true,
.trigger = {
SND_SOC_DSP_TRIGGER_POST,
SND_SOC_DSP_TRIGGER_POST
},
};
static struct snd_soc_dsp_link fe_media = {
.playback = true,
.capture = true,
.trigger = {
SND_SOC_DSP_TRIGGER_POST,
SND_SOC_DSP_TRIGGER_POST
},
};
static struct snd_soc_dsp_link slimbus0_hl_media = {
.playback = true,
.capture = true,
.trigger = {
SND_SOC_DSP_TRIGGER_POST,
SND_SOC_DSP_TRIGGER_POST
},
};
#endif
/* LGE_CHANGE */
#if 0
static struct snd_soc_dsp_link int_fm_hl_media = {
.playback = true,
.capture = true,
.trigger = {
SND_SOC_DSP_TRIGGER_POST,
SND_SOC_DSP_TRIGGER_POST
},
};
/* bi-directional media definition for hostless PCM device */
static struct snd_soc_dsp_link bidir_hl_media = {
.playback = true,
.capture = true,
.trigger = {
SND_SOC_DSP_TRIGGER_POST,
SND_SOC_DSP_TRIGGER_POST
},
};
#endif
/* LGE_CHANGE */
#if 0
static struct snd_soc_dsp_link hdmi_rx_hl = {
.playback = true,
.trigger = {
SND_SOC_DSP_TRIGGER_POST,
SND_SOC_DSP_TRIGGER_POST
},
};
#endif
static int msm8930_slim_0_rx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm8930_slim_0_rx_ch;
return 0;
}
static int msm8930_slim_0_tx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm8930_slim_0_tx_ch;
return 0;
}
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
static int msm_slim_3_rx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_slim_3_rx_ch;
return 0;
}
#endif
static int msm8930_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
return 0;
}
/* LGE_CHANGE */
#if 0
static int msm8930_hdmi_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
rate->min = rate->max = 48000;
channels->min = channels->max = 2;
return 0;
}
#endif
static int msm8930_btsco_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()msm8930_btsco_rate=%d \n", __func__,msm8930_btsco_rate);
rate->min = rate->max = msm8930_btsco_rate;
channels->min = channels->max = msm8930_btsco_ch;
return 0;
}
static int msm8930_auxpcm_be_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
/* PCM only supports mono output with 8khz sample rate */
/* LGE_CHANGE */
pr_debug("%s()msm8930_auxpcm_rate=%d \n", __func__,msm8930_auxpcm_rate);
rate->min = rate->max = msm8930_auxpcm_rate;
//LGE_END , MYUNGWON.KIM
channels->min = channels->max = 1;
return 0;
}
static int msm8930_proxy_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
return 0;
}
static int msm8930_aux_pcm_get_gpios(void)
{
int ret = 0;
pr_debug("%s\n", __func__);
ret = gpio_request(GPIO_AUX_PCM_DOUT, "AUX PCM DOUT");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM DOUT",
__func__, GPIO_AUX_PCM_DOUT);
goto fail_dout;
}
ret = gpio_request(GPIO_AUX_PCM_DIN, "AUX PCM DIN");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM DIN",
__func__, GPIO_AUX_PCM_DIN);
goto fail_din;
}
ret = gpio_request(GPIO_AUX_PCM_SYNC, "AUX PCM SYNC");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM SYNC",
__func__, GPIO_AUX_PCM_SYNC);
goto fail_sync;
}
ret = gpio_request(GPIO_AUX_PCM_CLK, "AUX PCM CLK");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM CLK",
__func__, GPIO_AUX_PCM_CLK);
goto fail_clk;
}
return 0;
fail_clk:
gpio_free(GPIO_AUX_PCM_SYNC);
fail_sync:
gpio_free(GPIO_AUX_PCM_DIN);
fail_din:
gpio_free(GPIO_AUX_PCM_DOUT);
fail_dout:
return ret;
}
static int msm8930_aux_pcm_free_gpios(void)
{
gpio_free(GPIO_AUX_PCM_DIN);
gpio_free(GPIO_AUX_PCM_DOUT);
gpio_free(GPIO_AUX_PCM_SYNC);
gpio_free(GPIO_AUX_PCM_CLK);
return 0;
}
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
static int msm8960_mi2s_free_gpios(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(mi2s_gpio); i++)
gpio_free(mi2s_gpio[i].gpio_no);
return 0;
}
static int msm8960_mi2s_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
int rate = params_rate(params);
int bit_clk_set = 0;
bit_clk_set = 12288000/(rate * 2 * 16);
pr_debug("%s[chapman]: rate = %d, bit_clk_set = %d\n", __func__,rate,bit_clk_set);
clk_set_rate(mi2s_bit_clk, bit_clk_set);
return 1;
}
static void msm8960_mi2s_shutdown(struct snd_pcm_substream *substream)
{
pr_info("%s: free mi2s resources\n", __func__);
if (atomic_dec_return(&mi2s_rsc_ref) == 0) {
pr_info("%s: free mi2s resources\n", __func__);
if (mi2s_bit_clk) {
clk_disable_unprepare(mi2s_bit_clk);
clk_put(mi2s_bit_clk);
mi2s_bit_clk = NULL;
}
if (mi2s_osr_clk) {
clk_disable_unprepare(mi2s_osr_clk);
clk_put(mi2s_osr_clk);
mi2s_osr_clk = NULL;
}
msm8960_mi2s_free_gpios();
}
}
static int configure_mi2s_gpio(void)
{
int rtn;
int i;
int j;
for (i = 0; i < ARRAY_SIZE(mi2s_gpio); i++) {
rtn = gpio_request(mi2s_gpio[i].gpio_no,
mi2s_gpio[i].gpio_name);
pr_debug("%s: gpio = %d, gpio name = %s, rtn = %d\n",
__func__,
mi2s_gpio[i].gpio_no,
mi2s_gpio[i].gpio_name,
rtn);
if (rtn) {
pr_err("%s: Failed to request gpio %d\n",
__func__,
mi2s_gpio[i].gpio_no);
for (j = i; j >= 0; j--)
gpio_free(mi2s_gpio[j].gpio_no);
goto err;
}
}
err:
return rtn;
}
static int msm8960_mi2s_startup(struct snd_pcm_substream *substream)
{
int ret = 0;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
pr_debug("%s: dai name %s %p\n", __func__, cpu_dai->name, cpu_dai->dev);
if (atomic_inc_return(&mi2s_rsc_ref) == 1) {
pr_info("%s: acquire mi2s resources\n", __func__);
configure_mi2s_gpio();
mi2s_osr_clk = clk_get(cpu_dai->dev, "osr_clk");
if (!IS_ERR(mi2s_osr_clk)) {
clk_set_rate(mi2s_osr_clk, 12288000);
clk_prepare_enable(mi2s_osr_clk);
} else
pr_err("Failed to get mi2s_osr_clk\n");
mi2s_bit_clk = clk_get(cpu_dai->dev, "bit_clk");
if (IS_ERR(mi2s_bit_clk)) {
pr_err("Failed to get mi2s_bit_clk\n");
clk_disable_unprepare(mi2s_osr_clk);
clk_put(mi2s_osr_clk);
return PTR_ERR(mi2s_bit_clk);
}
clk_set_rate(mi2s_bit_clk, 8);
ret = clk_prepare_enable(mi2s_bit_clk);
if (ret != 0) {
pr_err("Unable to enable mi2s_rx_bit_clk\n");
clk_put(mi2s_bit_clk);
clk_disable_unprepare(mi2s_osr_clk);
clk_put(mi2s_osr_clk);
return ret;
}
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
ret = snd_soc_dai_set_fmt(codec_dai,
SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
pr_err("set format for codec dai failed\n");
}
return ret;
}
#endif
static int msm8930_startup(struct snd_pcm_substream *substream)
{
pr_debug("%s(): substream = %s stream = %d\n", __func__,
substream->name, substream->stream);
return 0;
}
static int msm8930_auxpcm_startup(struct snd_pcm_substream *substream)
{
int ret = 0;
pr_debug("%s(): substream = %s, auxpcm_rsc_ref counter = %d\n",
__func__, substream->name, atomic_read(&auxpcm_rsc_ref));
if (atomic_inc_return(&auxpcm_rsc_ref) == 1)
ret = msm8930_aux_pcm_get_gpios();
if (ret < 0) {
pr_err("%s: Aux PCM GPIO request failed\n", __func__);
return -EINVAL;
}
return 0;
}
static void msm8930_auxpcm_shutdown(struct snd_pcm_substream *substream)
{
pr_debug("%s(): substream = %s, auxpcm_rsc_ref counter = %d\n",
__func__, substream->name, atomic_read(&auxpcm_rsc_ref));
if (atomic_dec_return(&auxpcm_rsc_ref) == 0)
msm8930_aux_pcm_free_gpios();
}
static void msm8930_shutdown(struct snd_pcm_substream *substream)
{
pr_debug("%s(): substream = %s stream = %d\n", __func__,
substream->name, substream->stream);
}
static struct snd_soc_ops msm8930_be_ops = {
.startup = msm8930_startup,
.hw_params = msm8930_hw_params,
.shutdown = msm8930_shutdown,
};
static struct snd_soc_ops msm8930_auxpcm_be_ops = {
.startup = msm8930_auxpcm_startup,
.shutdown = msm8930_auxpcm_shutdown,
};
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
static struct snd_soc_ops msm8960_mi2s_be_ops = {
.startup = msm8960_mi2s_startup,
.shutdown = msm8960_mi2s_shutdown,
.hw_params = msm8960_mi2s_hw_params,
};
static struct snd_soc_ops msm_slimbus_1_be_ops = {
.hw_params = msm_slimbus_1_hw_params,
};
static struct snd_soc_ops msm_slimbus_3_be_ops = {
.hw_params = msm_slimbus_3_hw_params,
};
#endif
/* Digital audio interface glue - connects codec <---> CPU */
static struct snd_soc_dai_link msm8930_dai[] = {
/* FrontEnd DAI Links */
{
.name = "MSM8930 Media1",
.stream_name = "MultiMedia1",
.cpu_dai_name = "MultiMedia1",
.platform_name = "msm-pcm-dsp",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST},
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA1
},
{
.name = "MSM8930 Media2",
.stream_name = "MultiMedia2",
.cpu_dai_name = "MultiMedia2",
.platform_name = "msm-multi-ch-pcm-dsp",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST},
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA2,
},
{
.name = "Circuit-Switch Voice",
.stream_name = "CS-Voice",
.cpu_dai_name = "CS-VOICE",
.platform_name = "msm-pcm-voice",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST},
.be_id = MSM_FRONTEND_DAI_CS_VOICE,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
},
{
.name = "MSM VoIP",
.stream_name = "VoIP",
.cpu_dai_name = "VoIP",
.platform_name = "msm-voip-dsp",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST},
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
.be_id = MSM_FRONTEND_DAI_VOIP,
},
{
.name = "MSM8930 LPA",
.stream_name = "LPA",
.cpu_dai_name = "MultiMedia3",
.platform_name = "msm-pcm-lpa",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST},
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA3,
},
/* Hostless PMC purpose */
{
.name = "SLIMBUS_0 Hostless",
.stream_name = "SLIMBUS_0 Hostless",
.cpu_dai_name = "SLIMBUS0_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
/* .be_id = do not care */
},
{
.name = "INT_FM Hostless",
.stream_name = "INT_FM Hostless",
.cpu_dai_name = "INT_FM_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
/* .be_id = do not care */
},
{
.name = "MSM AFE-PCM RX",
.stream_name = "AFE-PROXY RX",
.cpu_dai_name = "msm-dai-q6.241",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.platform_name = "msm-pcm-afe",
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
},
{
.name = "MSM AFE-PCM TX",
.stream_name = "AFE-PROXY TX",
.cpu_dai_name = "msm-dai-q6.240",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.platform_name = "msm-pcm-afe",
.ignore_suspend = 1,
},
{
.name = "MSM8930 Compr",
.stream_name = "COMPR",
.cpu_dai_name = "MultiMedia4",
.platform_name = "msm-compr-dsp",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA4,
},
{
.name = "AUXPCM Hostless",
.stream_name = "AUXPCM Hostless",
.cpu_dai_name = "AUXPCM_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
/* LGE_CHANGE */
#if 0
/* HDMI Hostless */
{
.name = "HDMI_RX_HOSTLESS",
.stream_name = "HDMI_RX_HOSTLESS",
.cpu_dai_name = "HDMI_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
#endif
{
.name = "VoLTE",
.stream_name = "VoLTE",
.cpu_dai_name = "VoLTE",
.platform_name = "msm-pcm-voice",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.be_id = MSM_FRONTEND_DAI_VOLTE,
},
{
.name = "SGLTE",
.stream_name = "SGLTE",
.cpu_dai_name = "SGLTE",
.platform_name = "msm-pcm-voice",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.be_id = MSM_FRONTEND_DAI_SGLTE,
},
{
.name = "MSM8960 LowLatency",
.stream_name = "MultiMedia5",
.cpu_dai_name = "MultiMedia5",
.platform_name = "msm-lowlatency-pcm-dsp",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA5,
},
/* Backend DAI Links */
{
.name = LPASS_BE_SLIMBUS_0_RX,
.stream_name = "Slimbus Playback",
.cpu_dai_name = "msm-dai-q6.16384",
.platform_name = "msm-pcm-routing",
.codec_name = "sitar_codec",
.codec_dai_name = "sitar_rx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_0_RX,
.init = &msm8930_audrx_init,
.be_hw_params_fixup = msm8930_slim_0_rx_be_hw_params_fixup,
.ops = &msm8930_be_ops,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
},
{
.name = LPASS_BE_SLIMBUS_0_TX,
.stream_name = "Slimbus Capture",
.cpu_dai_name = "msm-dai-q6.16385",
.platform_name = "msm-pcm-routing",
.codec_name = "sitar_codec",
.codec_dai_name = "sitar_tx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_0_TX,
.be_hw_params_fixup = msm8930_slim_0_tx_be_hw_params_fixup,
.ops = &msm8930_be_ops,
},
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
{
.name = "Voice Stub",
.stream_name = "Voice Stub",
.cpu_dai_name = "VOICE_STUB",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* Playback support */
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.be_id = MSM_FRONTEND_DAI_VOICE_STUB,
},
#endif
/* Backend BT/FM DAI Links */
{
.name = LPASS_BE_INT_BT_SCO_RX,
.stream_name = "Internal BT-SCO Playback",
.cpu_dai_name = "msm-dai-q6.12288",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_BT_SCO_RX,
.be_hw_params_fixup = msm8930_btsco_be_hw_params_fixup,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
},
{
.name = LPASS_BE_INT_BT_SCO_TX,
.stream_name = "Internal BT-SCO Capture",
.cpu_dai_name = "msm-dai-q6.12289",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_BT_SCO_TX,
.be_hw_params_fixup = msm8930_btsco_be_hw_params_fixup,
},
{
.name = LPASS_BE_INT_FM_RX,
.stream_name = "Internal FM Playback",
.cpu_dai_name = "msm-dai-q6.12292",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_FM_RX,
.be_hw_params_fixup = msm8930_be_hw_params_fixup,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
},
{
.name = LPASS_BE_INT_FM_TX,
.stream_name = "Internal FM Capture",
.cpu_dai_name = "msm-dai-q6.12293",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_FM_TX,
.be_hw_params_fixup = msm8930_be_hw_params_fixup,
},
/* LGE_CHANGE */
#if 0
/* HDMI BACK END DAI Link */
{
.name = LPASS_BE_HDMI,
.stream_name = "HDMI Playback",
.cpu_dai_name = "msm-dai-q6-hdmi.8",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_HDMI_RX,
.be_hw_params_fixup = msm8930_hdmi_be_hw_params_fixup,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
},
#endif
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
{
.name = LPASS_BE_MI2S_RX,
.stream_name = "MI2S Playback",
.cpu_dai_name = "msm-dai-q6-mi2s",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_MI2S_RX,
.be_hw_params_fixup = msm8930_be_hw_params_fixup,
.ops = &msm8960_mi2s_be_ops,
.ignore_pmdown_time = 1, /* Playback support */
},
{
.name = "MI2S_TX Hostless",
.stream_name = "MI2S_TX Hostless",
.cpu_dai_name = "MI2S_TX_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {SND_SOC_DPCM_TRIGGER_POST,
SND_SOC_DPCM_TRIGGER_POST},
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = LPASS_BE_MI2S_TX,
.stream_name = "MI2S Capture",
.cpu_dai_name = "msm-dai-q6-mi2s",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_MI2S_TX,
.ops = &msm8960_mi2s_be_ops,
},
#endif
/* Backend AFE DAI Links */
{
.name = LPASS_BE_AFE_PCM_RX,
.stream_name = "AFE Playback",
.cpu_dai_name = "msm-dai-q6.224",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AFE_PCM_RX,
.be_hw_params_fixup = msm8930_proxy_be_hw_params_fixup,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
},
{
.name = LPASS_BE_AFE_PCM_TX,
.stream_name = "AFE Capture",
.cpu_dai_name = "msm-dai-q6.225",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AFE_PCM_TX,
.be_hw_params_fixup = msm8930_proxy_be_hw_params_fixup,
},
/* AUX PCM Backend DAI Links */
{
.name = LPASS_BE_AUXPCM_RX,
.stream_name = "AUX PCM Playback",
.cpu_dai_name = "msm-dai-q6.2",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AUXPCM_RX,
.be_hw_params_fixup = msm8930_auxpcm_be_params_fixup,
.ops = &msm8930_auxpcm_be_ops,
},
{
.name = LPASS_BE_AUXPCM_TX,
.stream_name = "AUX PCM Capture",
.cpu_dai_name = "msm-dai-q6.3",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AUXPCM_TX,
.be_hw_params_fixup = msm8930_auxpcm_be_params_fixup,
.ops = &msm8930_auxpcm_be_ops,
},
/* Incall Music BACK END DAI Link */
{
.name = LPASS_BE_VOICE_PLAYBACK_TX,
.stream_name = "Voice Farend Playback",
.cpu_dai_name = "msm-dai-q6.32773",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_VOICE_PLAYBACK_TX,
.be_hw_params_fixup = msm8930_be_hw_params_fixup,
},
/* Incall Record Uplink BACK END DAI Link */
{
.name = LPASS_BE_INCALL_RECORD_TX,
.stream_name = "Voice Uplink Capture",
.cpu_dai_name = "msm-dai-q6.32772",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INCALL_RECORD_TX,
.be_hw_params_fixup = msm8930_be_hw_params_fixup,
},
/* Incall Record Downlink BACK END DAI Link */
{
.name = LPASS_BE_INCALL_RECORD_RX,
.stream_name = "Voice Downlink Capture",
.cpu_dai_name = "msm-dai-q6.32771",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INCALL_RECORD_RX,
.be_hw_params_fixup = msm8930_be_hw_params_fixup,
.ignore_pmdown_time = 1, /* this dainlink has playback support */
},
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
{
.name = LPASS_BE_SLIMBUS_1_TX,
.stream_name = "Slimbus1 Capture",
.cpu_dai_name = "msm-dai-q6.16387",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_1_TX,
.be_hw_params_fixup = msm8930_btsco_be_hw_params_fixup,
.ops = &msm_slimbus_1_be_ops,
},
{
.name = LPASS_BE_SLIMBUS_3_RX,
.stream_name = "Slimbus3 Playback",
.cpu_dai_name = "msm-dai-q6.16390",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.init = &msm_slim_3_init,
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_3_RX,
.be_hw_params_fixup = msm_slim_3_rx_be_hw_params_fixup,
.ops = &msm_slimbus_3_be_ops,
},
#endif
};
struct snd_soc_card snd_soc_card_msm8930 = {
.name = "msm8930-sitar-snd-card",
.dai_link = msm8930_dai,
.num_links = ARRAY_SIZE(msm8930_dai),
.controls = sitar_msm8930_controls,
.num_controls = ARRAY_SIZE(sitar_msm8930_controls),
};
static struct platform_device *msm8930_snd_device;
static int msm8930_configure_headset_mic_gpios(void)
{
int ret;
ret = gpio_request(80, "US_EURO_SWITCH");
if (ret) {
pr_err("%s: Failed to request gpio 80\n", __func__);
return ret;
}
ret = gpio_direction_output(80, 0);
if (ret) {
pr_err("%s: Unable to set direction\n", __func__);
gpio_free(80);
}
msm8930_headset_gpios_configured = 0;
return 0;
}
static void msm8930_free_headset_mic_gpios(void)
{
if (msm8930_headset_gpios_configured){
#ifdef CONFIG_SWITCH_FSA8008
if(lge_get_board_usembhc()) {
gpio_free(80);
}
#else
gpio_free(80);
#endif
}
}
static int __init msm8930_audio_init(void)
{
int ret;
if (!cpu_is_msm8930() && !cpu_is_msm8930aa() && !cpu_is_msm8627()) {
pr_err("%s: Not the right machine type\n", __func__);
return -ENODEV ;
}
mbhc_cfg.calibration = def_sitar_mbhc_cal();
if (!mbhc_cfg.calibration) {
pr_err("Calibration data allocation failed\n");
return -ENOMEM;
}
msm8930_snd_device = platform_device_alloc("soc-audio", 0);
if (!msm8930_snd_device) {
pr_err("Platform device allocation failed\n");
kfree(mbhc_cfg.calibration);
return -ENOMEM;
}
#ifdef CONFIG_MACH_MSM8930_LGPS9
ret = gpio_request(GPIO_EXT_BOOST_EN, "ext_boost_en");
if (unlikely(ret < 0))
printk(KERN_INFO"%s not able to get gpio\n", __func__);
if (gpio_get_value(GPIO_EXT_BOOST_EN) != 1) {
gpio_set_value(GPIO_EXT_BOOST_EN, 1);
pr_info("The ext_bootst_en gpio value is =%d\n",
gpio_get_value(GPIO_EXT_BOOST_EN));
}
#endif
platform_set_drvdata(msm8930_snd_device, &snd_soc_card_msm8930);
ret = platform_device_add(msm8930_snd_device);
if (ret) {
platform_device_put(msm8930_snd_device);
kfree(mbhc_cfg.calibration);
return ret;
}
#ifdef CONFIG_SWITCH_FSA8008
if (lge_get_board_usembhc()) {
if (msm8930_configure_headset_mic_gpios()) {
pr_err("%s Fail to configure headset mic gpios\n", __func__);
msm8930_headset_gpios_configured = 0;
} else
msm8930_headset_gpios_configured = 1;
} else {
msm8930_headset_gpios_configured = 1;
}
#else
if (msm8930_configure_headset_mic_gpios()) {
pr_err("%s Fail to configure headset mic gpios\n", __func__);
msm8930_headset_gpios_configured = 0;
} else
msm8930_headset_gpios_configured = 1;
#endif
atomic_set(&auxpcm_rsc_ref, 0);
#ifdef CONFIG_FM_RADIO_MI2S_ENABLE
atomic_set(&mi2s_rsc_ref, 0);
#endif
return ret;
}
module_init(msm8930_audio_init);
static void __exit msm8930_audio_exit(void)
{
if (!cpu_is_msm8930() && !cpu_is_msm8930aa() && !cpu_is_msm8627()) {
pr_err("%s: Not the right machine type\n", __func__);
return ;
}
msm8930_free_headset_mic_gpios();
platform_device_unregister(msm8930_snd_device);
kfree(mbhc_cfg.calibration);
}
module_exit(msm8930_audio_exit);
MODULE_DESCRIPTION("ALSA SoC MSM8930");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
AMDmi3/Wyrmgus | src/action/action_research.cpp | 1 | 6157 | // _________ __ __
// / _____// |_____________ _/ |______ ____ __ __ ______
// \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/
// / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ |
// /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ >
// \/ \/ \//_____/ \/
// ______________________ ______________________
// T H E W A R B E G I N S
// Stratagus - A free fantasy real time strategy game engine
//
/**@name action_research.cpp - The research action. */
//
// (c) Copyright 1998-2020 by Lutz Sammer, Jimmy Salmon and Andrettin
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; only version 2 of the License.
//
// 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 "stratagus.h"
#include "action/action_research.h"
#include "ai.h"
#include "animation.h"
#include "civilization.h"
#include "iolib.h"
#include "map/map_layer.h"
#include "script.h"
#include "sound/sound.h"
#include "sound/unitsound.h"
#include "player.h"
#include "translate.h"
#include "unit/unit.h"
#include "unit/unit_type.h"
#include "upgrade/upgrade_structs.h"
#include "upgrade/upgrade.h"
/// How many resources the player gets back if canceling research
static constexpr int CancelResearchCostsFactor = 100;
std::unique_ptr<COrder> COrder::NewActionResearch(const CUpgrade &upgrade, CPlayer *player)
{
auto order = std::make_unique<COrder_Research>();
// FIXME: if you give quick an other order, the resources are lost!
//Wyrmgus start
order->Player = player;
// unit.Player->SubCosts(upgrade.Costs);
int upgrade_costs[MaxCosts];
player->GetUpgradeCosts(&upgrade, upgrade_costs);
player->SubCosts(upgrade_costs);
//Wyrmgus end
order->SetUpgrade(upgrade);
return order;
}
void COrder_Research::Save(CFile &file, const CUnit &unit) const
{
Q_UNUSED(unit)
file.printf("{\"action-research\",");
if (this->Finished) {
file.printf(" \"finished\", ");
}
//Wyrmgus start
file.printf("\"player\", %d,", this->Player->get_index());
//Wyrmgus end
if (this->Upgrade) {
file.printf(" \"upgrade\", \"%s\"", this->Upgrade->get_identifier().c_str());
}
file.printf("}");
}
bool COrder_Research::ParseSpecificData(lua_State *l, int &j, const char *value, const CUnit &unit)
{
Q_UNUSED(unit)
if (!strcmp(value, "upgrade")) {
++j;
this->Upgrade = CUpgrade::get(LuaToString(l, -1, j + 1));
//Wyrmgus start
} else if (!strcmp(value, "player")) {
++j;
this->Player = CPlayer::Players[LuaToNumber(l, -1, j + 1)];
//Wyrmgus end
} else {
return false;
}
return true;
}
/* virtual */ bool COrder_Research::IsValid() const
{
return true;
}
/* virtual */ PixelPos COrder_Research::Show(const CViewport &, const PixelPos &lastScreenPos) const
{
return lastScreenPos;
}
/* virtual */ void COrder_Research::UpdateUnitVariables(CUnit &unit) const
{
//Wyrmgus start
// unit.Variable[RESEARCH_INDEX].Value = unit.Player->UpgradeTimers.Upgrades[this->Upgrade->ID];
unit.Variable[RESEARCH_INDEX].Value = this->Player->UpgradeTimers.Upgrades[this->Upgrade->ID];
//Wyrmgus end
unit.Variable[RESEARCH_INDEX].Max = this->Upgrade->Costs[TimeCost];
}
/**
** Research upgrade.
**
** @return true when finished.
*/
/* virtual */ void COrder_Research::Execute(CUnit &unit)
{
const CUpgrade &upgrade = this->GetUpgrade();
const wyrmgus::unit_type &type = *unit.Type;
UnitShowAnimation(unit, unit.get_animation_set()->Research ? unit.get_animation_set()->Research.get() : unit.get_animation_set()->Still.get());
if (unit.Wait) {
unit.Wait--;
return ;
}
#if 0
if (unit.Anim.Unbreakable) {
return ;
}
#endif
//Wyrmgus start
// CPlayer &player = *unit.Player;
CPlayer &player = *this->Player;
// player.UpgradeTimers.Upgrades[upgrade.ID] += std::max(1, player.SpeedResearch / SPEEDUP_FACTOR);
player.UpgradeTimers.Upgrades[upgrade.ID] += std::max(1, (player.SpeedResearch + unit.Variable[TIMEEFFICIENCYBONUS_INDEX].Value + unit.Variable[RESEARCHSPEEDBONUS_INDEX].Value) / SPEEDUP_FACTOR);
//Wyrmgus end
if (player.UpgradeTimers.Upgrades[upgrade.ID] >= upgrade.Costs[TimeCost]) {
if (upgrade.get_name().empty()) {
//Wyrmgus start
// player.Notify(NotifyGreen, unit.tilePos, _("%s: research complete"), type.Name.c_str());
player.Notify(NotifyGreen, unit.tilePos, unit.MapLayer->ID, _("%s: research complete"), type.GetDefaultName(&player).c_str());
//Wyrmgus end
} else {
player.Notify(NotifyGreen, unit.tilePos, unit.MapLayer->ID, _("%s: research complete"), upgrade.get_name().c_str());
}
if (&player == CPlayer::GetThisPlayer()) {
const wyrmgus::civilization *civilization = unit.Player->get_civilization();
const wyrmgus::sound *sound = nullptr;
if (civilization != nullptr) {
sound = civilization->get_research_complete_sound();
}
if (sound != nullptr) {
PlayGameSound(sound, MaxSampleVolume);
}
}
if (player.AiEnabled) {
AiResearchComplete(unit, &upgrade);
}
UpgradeAcquire(player, &upgrade);
this->Finished = true;
return ;
}
unit.Wait = CYCLES_PER_SECOND / 6;
}
void COrder_Research::Cancel(CUnit &unit)
{
Q_UNUSED(unit)
const CUpgrade &upgrade = this->GetUpgrade();
//Wyrmgus start
// unit.Player->UpgradeTimers.Upgrades[upgrade.ID] = 0;
// unit.Player->AddCostsFactor(upgrade.Costs, CancelResearchCostsFactor);
this->Player->UpgradeTimers.Upgrades[upgrade.ID] = 0;
this->Player->AddCostsFactor(upgrade.Costs, CancelResearchCostsFactor);
//Wyrmgus end
}
| gpl-2.0 |
zeha/xrdp-suse-fork | sesman/libscp/libscp_connection.c | 1 | 1521 | /*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
xrdp: A Remote Desktop Protocol server.
Copyright (C) Jay Sorg 2005-2008
*/
/**
*
* @file libscp_connection.c
* @brief SCP_CONNECTION handling code
* @author Simone Fedele
*
*/
#include "libscp_connection.h"
extern struct log_config* s_log;
struct SCP_CONNECTION*
scp_connection_create(int sck)
{
struct SCP_CONNECTION* conn;
conn = g_malloc(sizeof(struct SCP_CONNECTION), 0);
if (0 == conn)
{
log_message(s_log, LOG_LEVEL_WARNING, "[connection:%d] connection create: malloc error", __LINE__);
return 0;
}
conn->in_sck=sck;
make_stream(conn->in_s);
init_stream(conn->in_s, 8196);
make_stream(conn->out_s);
init_stream(conn->out_s, 8196);
return conn;
}
void
scp_connection_destroy(struct SCP_CONNECTION* c)
{
free_stream(c->in_s);
free_stream(c->out_s);
g_free(c);
}
| gpl-2.0 |
bogdanov-d-a/Amlogic-reff16-uboot | board/amlogic/aml_aio_m2c_haier/firmware/lowlevel_init.c | 1 | 2056 | #include <asm/arch/firm/regs.h>
#include <asm/arch/firm/reg_addr.h>
#include <asm/arch/firm/timing.h>
#include <asm/arch/romboot.h>
#include <memtest.h>
#include <config.h>
#include <asm/arch/firm/io.h>
void lowlevel_init(void* cur,void * target)
{
int i;
#if 0
if(cur != target) //r0!=r1
{
//running from spi
// take me as a spi rom boot mode
romboot_info->por_cfg = POR_INTL_SPI |
(READ_CBUS_REG(ASSIST_POR_CONFIG)&(~POR_INTL_CFG_MASK));
romboot_info->boot_id = 0;//boot from spi
/// Release pull up registers .
}
#endif
//writel((1<<22)|100000,P_WATCHDOG_TC);//enable Watchdog 1 seconds
//Adjust 1us timer base
//clrbits_le32(P_PREG_FGPIO_O, 1<<21);
//mute
// setbits_le32(P_PREG_GGPIO_O, 1<<5);
// clrbits_le32(P_PREG_GGPIO_EN_N, 1<<5);
// //vcc_12v/24v power down GPIOX_70
// setbits_le32(P_PREG_GGPIO_O, 1<<6);
// clrbits_le32(P_PREG_GGPIO_EN_N, 1<<6);
// bl
// setbits_le32(P_PREG_FGPIO_O, 1<<21);
// clrbits_le32(P_PREG_FGPIO_EN_N, 1<<21);
//Wr(REG_LVDS_PHY_CNTL4, 0);//LVDS_MDR_PU
//clrbits_le32(P_PREG_GGPIO_O, 1<<6);
//clrbits_le32(P_PREG_GGPIO_EN_N, 1<<6);
WRITE_CBUS_REG_BITS(PREG_CTLREG0_ADDR,CONFIG_CRYSTAL_MHZ,4,5);
/*
Select TimerE 1 us base
*/
clrsetbits_le32(P_ISA_TIMER_MUX,0x7<<8,0x1<<8);
if(1)
{
writel(0,P_WATCHDOG_TC);//disable Watchdog
//while(1)
{
__udelay(50000);
}
}
memory_pll_init(0,NULL);
//serial_put_dword(get_timer(0));
//serial_put_dword(readl(0xc1100000+0x200b*4));
#if CONFIG_ENABLE_SPL_DEBUG_ROM
__udelay(100000);//wait for a uart input
if(serial_tstc()){
writel(0,P_WATCHDOG_TC);//disable Watchdog
debug_rom(__FILE__,__LINE__);
}
#else
__udelay(1000);//delay 1 ms , wait pll ready
#endif
#if 1
#if CONFIG_ENABLE_SPL_DEBUG_ROM
if(ddr_init_test()){
writel(0,P_WATCHDOG_TC);//disable Watchdog
debug_rom(__FILE__,__LINE__);
}
#else
do{
}while(ddr_init_test(0x6));
#endif
#endif
writel(0,P_WATCHDOG_TC);//disable Watchdog
//serial_puts("\nM2C (Haier TV) Systemp Started\n");
}
| gpl-2.0 |
jameyboor/Antrix | src/game/Channel.cpp | 1 | 9248 | #include "StdAfx.h"
bool Channel::Join(Player *p, const char *pass)
{
m_Lock.Acquire();
bool ret = false;
WorldPacket data(100);
if(IsOn(p))
{
MakeAlreadyOn(&data,p);
SendToOne(&data,p);
}
else if(IsBanned(p->GetGUID()))
{
MakeYouAreBanned(&data);
SendToOne(&data,p);
}
else if((password.length() > 0 && strcmp(pass,password.c_str())) || (strcmp(name.c_str(), sWorld.getGmClientChannel().c_str()) == 0 && !p->GetSession()->CanUseCommand('c')))
{
MakeWrongPass(&data);
SendToOne(&data,p);
}
else
{
PlayerInfo pinfo;
pinfo.player = p;
pinfo.muted = false;
if(GetNumPlayers() == 0)
pinfo.owner = true;
else
pinfo.owner = false;
pinfo.moderator = false;
MakeJoined(&data,p);
p->JoinedChannel(this);
if(announce && !m_DefaultChannel)
SendToAll(&data);
data.clear();
players[p] = pinfo;
/*MakeYouJoined(&data,p);
SendToOne(&data,p);*/
if(owner == NULL)
{
if(!IsDefaultChannel())
{
SetOwner(p);
players[p].moderator = false;
}
else if(p->GetSession()->CanUseCommand('c'))
{
SetOwner(p);
players[p].moderator = true;
}
}
ret = true;
}
m_Lock.Release();
return ret;
}
void Channel::Leave(Player *p, bool send)
{
m_Lock.Acquire();
WorldPacket data(100);
if(!IsOn(p))
{
MakeNotOn(&data);
if(send) SendToOne(&data,p);
}
else
{
bool changeowner = (owner == p);
//MakeYouLeft(&data);
if(send)
{
//SendToOne(&data,p);
p->LeftChannel(this);
}
//data.clear();
players.erase(p);
MakeLeft(&data,p);
if(announce && !m_DefaultChannel)
SendToAll(&data);
if(changeowner)
{
Player *newowner = players.size() > 0 ? players.begin()->second.player : NULL;
SetOwner(newowner);
}
}
m_Lock.Release();
}
void Channel::KickOrBan(Player *good, const char *badname, bool ban)
{
m_Lock.Acquire();
WorldPacket data(100);
if(!IsOn(good))
{
MakeNotOn(&data);
SendToOne(&data,good);
}
else if(!players[good].moderator && !good->GetSession()->CanUseCommand('c'))
{
MakeNotModerator(&data);
SendToOne(&data,good);
}
else
{
Player *bad = objmgr.GetPlayer(badname);
if(bad == NULL || !IsOn(bad))
{
MakeNotOn(&data,badname);
SendToOne(&data,good);
}
else if(!good->GetSession()->CanUseCommand('c') && bad == owner && good != owner)
{
MakeNotOwner(&data);
SendToOne(&data,good);
}
else
{
bool changeowner = (owner == bad);
if(ban && !IsBanned(bad->GetGUID()))
{
banned.push_back(bad->GetGUID());
MakeBanned(&data,good,bad);
}
else
MakeKicked(&data,good,bad);
SendToAll(&data);
players.erase(bad);
if(changeowner)
{
Player *newowner = players.size() > 0 ? good : NULL;
SetOwner(newowner);
}
}
}
m_Lock.Release();
}
void Channel::UnBan(Player *good, const char *badname)
{
m_Lock.Acquire();
WorldPacket data(100);
if(!IsOn(good))
{
MakeNotOn(&data);
SendToOne(&data,good);
}
else if(!players[good].moderator && !good->GetSession()->CanUseCommand('c'))
{
MakeNotModerator(&data);
SendToOne(&data,good);
}
else
{
Player *bad = objmgr.GetPlayer(badname);
if(bad == NULL || !IsBanned(bad->GetGUID()))
{
MakeNotOn(&data,badname); // Change to <Not Banned> message. Not sure what it is.
SendToOne(&data,good);
}
else
{
banned.remove(bad->GetGUID());
MakeUnbanned(&data,good,bad);
SendToAll(&data);
}
}
m_Lock.Release();
}
void Channel::Password(Player *p, const char *pass)
{
m_Lock.Acquire();
WorldPacket data(100);
if(!IsOn(p))
{
MakeNotOn(&data);
SendToOne(&data,p);
}
else if(!players[p].moderator && !p->GetSession()->CanUseCommand('c'))
{
MakeNotModerator(&data);
SendToOne(&data,p);
}
else
{
password = pass;
MakeSetPassword(&data,p);
SendToAll(&data);
}
m_Lock.Release();
}
void Channel::SetMode(Player *p, const char *p2n, bool mod, bool set)
{
m_Lock.Acquire();
WorldPacket data(100);
if(!IsOn(p))
{
MakeNotOn(&data);
SendToOne(&data,p);
}
else if(!players[p].moderator && !p->GetSession()->CanUseCommand('c'))
{
MakeNotModerator(&data);
SendToOne(&data,p);
}
else
{
Player *newp = objmgr.GetPlayer(p2n);
// PlayerInfo inf = players[newp];
if(p == owner && newp == owner && mod)
{
m_Lock.Release();
return;
}
if(newp == NULL || !IsOn(newp))
{
MakeNotOn(&data,p2n);
SendToOne(&data,p);
}
else if(owner == newp && owner != p)
{
MakeNotOwner(&data);
SendToOne(&data,p);
}
else
{
if(mod)
SetModerator(newp,set);
else
SetMute(newp,set);
}
}
m_Lock.Release();
}
void Channel::SetOwner(Player *p, const char *newname)
{
m_Lock.Acquire();
WorldPacket data(100);
if(!IsOn(p))
{
MakeNotOn(&data);
SendToOne(&data,p);
}
else if(!p->GetSession()->CanUseCommand('c') && p != owner)
{
MakeNotOwner(&data);
SendToOne(&data,p);
}
else
{
Player *newp = objmgr.GetPlayer(newname);
if(newp == NULL || !IsOn(newp))
{
MakeNotOn(&data,newname);
SendToOne(&data,p);
}
else
{
MakeChangeOwner(&data,newp);
if(!m_DefaultChannel) SendToAll(&data);
SetModerator(newp,true);
owner = newp;
}
}
m_Lock.Release();
}
void Channel::GetOwner(Player *p)
{
WorldPacket data(100);
if(!IsOn(p))
{
MakeNotOn(&data);
SendToOne(&data,p);
}
else
{
MakeWhoOwner(&data);
SendToOne(&data,p);
}
}
void Channel::List(Player *p)
{
m_Lock.Acquire();
WorldPacket data(100);
if(!IsOn(p))
{
MakeNotOn(&data);
SendToOne(&data,p);
}
else
{
data.Initialize(SMSG_CHANNEL_LIST);
data << (uint8)3 << (uint32)players.size();
PlayerList::iterator i;
for(i = players.begin(); i!=players.end(); i++)
{
data << i->first->GetGUID();
uint8 mode = 0x00;
if(i->second.muted)
mode |= 0x04;
if(i->second.moderator)
mode |= 0x02;
data << mode;
}
SendToOne(&data,p);
}
m_Lock.Release();
}
void Channel::Announce(Player *p)
{
WorldPacket data(100);
if(!IsOn(p))
{
MakeNotOn(&data);
SendToOne(&data,p);
}
else if(!players[p].moderator && !p->GetSession()->CanUseCommand('c'))
{
MakeNotModerator(&data);
SendToOne(&data,p);
}
else
{
announce = !announce;
MakeAnnounce(&data,p,announce);
SendToAll(&data);
}
}
void Channel::Moderate(Player *p)
{
WorldPacket data(100);
if(!IsOn(p))
{
MakeNotOn(&data);
SendToOne(&data,p);
}
else if(!players[p].moderator && !p->GetSession()->CanUseCommand('c'))
{
MakeNotModerator(&data);
SendToOne(&data,p);
}
else
{
moderate = !moderate;
MakeModerate(&data,p,moderate);
SendToAll(&data);
}
}
void Channel::Say(Player *p, const char *what, Player *t)
{
WorldPacket data(100);
if(!IsOn(p))
{
MakeNotOn(&data);
SendToOne(&data,p);
}
else if(players[p].muted)
{
MakeYouCantSpeak(&data);
SendToOne(&data,p);
}
else if(moderate && !players[p].moderator && !p->GetSession()->CanUseCommand('c'))
{
MakeNotModerator(&data);
SendToOne(&data,p);
}
else
{
//Packet structure
//uint8 type;
//uint32 language;
//uint32 PVP rank
//uint64 guid;
//uint32 len_of_text;
//char text[];
//uint8 afk_state;
uint32 messageLength = strlen((char*)what) + 1;
// uint8 afk = 0;
data.Initialize(SMSG_MESSAGECHAT);
data << (uint8)14; // CHAT_MESSAGE_CHANNEL
data << (uint32)0; // Universal lang
data << p->GetGUID();
data << uint32(0); // pvp rank??
data << name;
data << p->GetGUID();
data << messageLength;
data << what;
data << (uint8)(p->bGMTagOn ? 4 : 0);
if(t == NULL)
SendToAll(&data);
else
SendToOne(&data, t);
// Send the actual talking stuff.
}
}
void Channel::SayFromIRC(const char* msg)
{
WorldPacket data;
//Packet structure
//uint8 type;
//uint32 language;
//uint32 PVP rank
//uint64 guid;
//uint32 len_of_text;
//char text[];
//uint8 afk_state;
uint32 messageLength = strlen((char*)msg) + 1;
// uint8 afk = 0;
data.Initialize(SMSG_MESSAGECHAT);
data << (uint8)14; // CHAT_MESSAGE_CHANNEL
data << (uint32)0; // Universal lang
data << name.c_str();
data << (uint32)0; // pvp ranks
data << (uint64)0; // was.. guid..
data << messageLength;
data << msg;
data << (uint8)0;
SendToAll(&data);
}
void Channel::Invite(Player *p, const char *newname)
{
WorldPacket data(100);
if(!IsOn(p))
{
MakeNotOn(&data);
SendToOne(&data,p);
}
else
{
Player *newp = objmgr.GetPlayer(newname);
if(newp == NULL)
{
MakeNotOn(&data,newname);
SendToOne(&data,p);
}
else if(IsOn(newp))
{
MakeAlreadyOn(&data,newp);
SendToOne(&data,p);
}
else
{
MakeInvited(&data,p);
SendToOne(&data,newp);
data.clear();
MakeYouInvited(&data,newp);
SendToOne(&data,p);
}
}
}
bool Channel::IsDefaultChannel()
{
const char* cName = name.c_str();
if( !memcmp (cName, "General", 7)
)
return true;
if( !memcmp(cName, "LookingForGroup", 15)
)
return true;
if( !strncmp(cName, "LocalDefense", 12)
)
return true;
if( !strncmp(cName, "Trade", 5)
)
return true;
if( !strncmp(cName, "Guild Recruitment", 17)
)
return true;
return false;
}
ChannelMgr::~ChannelMgr()
{
for(int i = 0; i < 2; ++i)
{
ChannelList::iterator itr = this->Channels[i].begin();
for(; itr != this->Channels[i].end(); ++itr)
{
delete itr->second;
}
Channels[i].clear();
}
}
| gpl-2.0 |
teamfx/openjfx-8u-dev-rt | modules/web/src/main/native/Source/JavaScriptCore/b3/air/AirLowerEntrySwitch.cpp | 1 | 4491 | /*
* Copyright (C) 2016 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h"
#include "AirLowerEntrySwitch.h"
#if ENABLE(B3_JIT)
#include "AirBlockWorklist.h"
#include "AirCode.h"
#include "AirInstInlines.h"
#include "AirPhaseScope.h"
#include "B3Procedure.h"
namespace JSC { namespace B3 { namespace Air {
void lowerEntrySwitch(Code& code)
{
PhaseScope phaseScope(code, "lowerEntrySwitch");
// Figure out the set of blocks that should be duplicated.
BlockWorklist worklist;
for (BasicBlock* block : code) {
if (block->last().kind.opcode == EntrySwitch)
worklist.push(block);
}
// It's possible that we don't have any EntrySwitches. That's fine.
if (worklist.seen().isEmpty()) {
Vector<FrequentedBlock> entrypoints(code.proc().numEntrypoints(), FrequentedBlock(code[0]));
code.setEntrypoints(WTFMove(entrypoints));
return;
}
while (BasicBlock* block = worklist.pop())
worklist.pushAll(block->predecessors());
RELEASE_ASSERT(worklist.saw(code[0]));
Vector<FrequencyClass> entrypointFrequencies(code.proc().numEntrypoints(), FrequencyClass::Rare);
for (BasicBlock* block : code) {
if (block->last().kind.opcode != EntrySwitch)
continue;
for (unsigned entrypointIndex = code.proc().numEntrypoints(); entrypointIndex--;) {
entrypointFrequencies[entrypointIndex] = maxFrequency(
entrypointFrequencies[entrypointIndex],
block->successor(entrypointIndex).frequency());
}
}
auto fixEntrySwitch = [&] (BasicBlock* block, unsigned entrypointIndex) {
if (block->last().kind.opcode != EntrySwitch)
return;
FrequentedBlock target = block->successor(entrypointIndex);
block->last().kind.opcode = Jump;
block->successors().resize(1);
block->successor(0) = target;
};
// Now duplicate them.
Vector<FrequentedBlock> entrypoints;
entrypoints.append(FrequentedBlock(code[0], entrypointFrequencies[0]));
IndexMap<BasicBlock*, BasicBlock*> map(code.size());
for (unsigned entrypointIndex = 1; entrypointIndex < code.proc().numEntrypoints(); ++entrypointIndex) {
map.clear();
for (BasicBlock* block : worklist.seen().values(code))
map[block] = code.addBlock(block->frequency());
entrypoints.append(FrequentedBlock(map[code[0]], entrypointFrequencies[entrypointIndex]));
for (BasicBlock* block : worklist.seen().values(code)) {
BasicBlock* newBlock = map[block];
for (const Inst& inst : *block)
newBlock->appendInst(inst);
newBlock->successors() = block->successors();
for (BasicBlock*& successor : newBlock->successorBlocks()) {
if (BasicBlock* replacement = map[successor])
successor = replacement;
}
fixEntrySwitch(newBlock, entrypointIndex);
}
}
for (BasicBlock* block : worklist.seen().values(code))
fixEntrySwitch(block, 0);
code.setEntrypoints(WTFMove(entrypoints));
code.resetReachability();
}
} } } // namespace JSC::B3::Air
#endif // ENABLE(B3_JIT)
| gpl-2.0 |
luohaha/Telegram | TMessagesProj/jni/opus/silk/fixed/warped_autocorrelation_FIX.c | 257 | 4600 | /***********************************************************************
Copyright (c) 2006-2011, Skype Limited. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Internet Society, IETF or IETF Trust, nor the
names of specific 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.
***********************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "main_FIX.h"
#define QC 10
#define QS 14
/* Autocorrelations for a warped frequency axis */
void silk_warped_autocorrelation_FIX(
opus_int32 *corr, /* O Result [order + 1] */
opus_int *scale, /* O Scaling of the correlation vector */
const opus_int16 *input, /* I Input data to correlate */
const opus_int warping_Q16, /* I Warping coefficient */
const opus_int length, /* I Length of input */
const opus_int order /* I Correlation order (even) */
)
{
opus_int n, i, lsh;
opus_int32 tmp1_QS, tmp2_QS;
opus_int32 state_QS[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };
opus_int64 corr_QC[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };
/* Order must be even */
silk_assert( ( order & 1 ) == 0 );
silk_assert( 2 * QS - QC >= 0 );
/* Loop over samples */
for( n = 0; n < length; n++ ) {
tmp1_QS = silk_LSHIFT32( (opus_int32)input[ n ], QS );
/* Loop over allpass sections */
for( i = 0; i < order; i += 2 ) {
/* Output of allpass section */
tmp2_QS = silk_SMLAWB( state_QS[ i ], state_QS[ i + 1 ] - tmp1_QS, warping_Q16 );
state_QS[ i ] = tmp1_QS;
corr_QC[ i ] += silk_RSHIFT64( silk_SMULL( tmp1_QS, state_QS[ 0 ] ), 2 * QS - QC );
/* Output of allpass section */
tmp1_QS = silk_SMLAWB( state_QS[ i + 1 ], state_QS[ i + 2 ] - tmp2_QS, warping_Q16 );
state_QS[ i + 1 ] = tmp2_QS;
corr_QC[ i + 1 ] += silk_RSHIFT64( silk_SMULL( tmp2_QS, state_QS[ 0 ] ), 2 * QS - QC );
}
state_QS[ order ] = tmp1_QS;
corr_QC[ order ] += silk_RSHIFT64( silk_SMULL( tmp1_QS, state_QS[ 0 ] ), 2 * QS - QC );
}
lsh = silk_CLZ64( corr_QC[ 0 ] ) - 35;
lsh = silk_LIMIT( lsh, -12 - QC, 30 - QC );
*scale = -( QC + lsh );
silk_assert( *scale >= -30 && *scale <= 12 );
if( lsh >= 0 ) {
for( i = 0; i < order + 1; i++ ) {
corr[ i ] = (opus_int32)silk_CHECK_FIT32( silk_LSHIFT64( corr_QC[ i ], lsh ) );
}
} else {
for( i = 0; i < order + 1; i++ ) {
corr[ i ] = (opus_int32)silk_CHECK_FIT32( silk_RSHIFT64( corr_QC[ i ], -lsh ) );
}
}
silk_assert( corr_QC[ 0 ] >= 0 ); /* If breaking, decrease QC*/
}
| gpl-2.0 |
genopublic/kernel_u8800 | drivers/scsi/bfa/rport.c | 513 | 66782 | /*
* Copyright (c) 2005-2009 Brocade Communications Systems, Inc.
* All rights reserved
* www.brocade.com
*
* Linux driver for Brocade Fibre Channel Host Bus Adapter.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (GPL) Version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
/**
* rport.c Remote port implementation.
*/
#include <bfa.h>
#include <bfa_svc.h>
#include "fcbuild.h"
#include "fcs_vport.h"
#include "fcs_lport.h"
#include "fcs_rport.h"
#include "fcs_fcpim.h"
#include "fcs_fcptm.h"
#include "fcs_trcmod.h"
#include "fcs_fcxp.h"
#include "fcs.h"
#include <fcb/bfa_fcb_rport.h>
#include <aen/bfa_aen_rport.h>
BFA_TRC_FILE(FCS, RPORT);
#define BFA_FCS_RPORT_MAX_RETRIES (5)
/* In millisecs */
static u32 bfa_fcs_rport_del_timeout =
BFA_FCS_RPORT_DEF_DEL_TIMEOUT * 1000;
/*
* forward declarations
*/
static struct bfa_fcs_rport_s *bfa_fcs_rport_alloc(struct bfa_fcs_port_s *port,
wwn_t pwwn, u32 rpid);
static void bfa_fcs_rport_free(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_hal_online(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_online_action(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_offline_action(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_update(struct bfa_fcs_rport_s *rport,
struct fc_logi_s *plogi);
static void bfa_fcs_rport_fc4_pause(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_fc4_resume(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_timeout(void *arg);
static void bfa_fcs_rport_send_plogi(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_send_plogiacc(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_plogi_response(void *fcsarg,
struct bfa_fcxp_s *fcxp,
void *cbarg,
bfa_status_t req_status,
u32 rsp_len,
u32 resid_len,
struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_send_adisc(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_adisc_response(void *fcsarg,
struct bfa_fcxp_s *fcxp,
void *cbarg,
bfa_status_t req_status,
u32 rsp_len,
u32 resid_len,
struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_send_gidpn(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_gidpn_response(void *fcsarg,
struct bfa_fcxp_s *fcxp,
void *cbarg,
bfa_status_t req_status,
u32 rsp_len,
u32 resid_len,
struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_send_logo(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_send_logo_acc(void *rport_cbarg);
static void bfa_fcs_rport_process_prli(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len);
static void bfa_fcs_rport_send_ls_rjt(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u8 reason_code,
u8 reason_code_expl);
static void bfa_fcs_rport_process_adisc(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len);
/**
* fcs_rport_sm FCS rport state machine events
*/
enum rport_event {
RPSM_EVENT_PLOGI_SEND = 1, /* new rport; start with PLOGI */
RPSM_EVENT_PLOGI_RCVD = 2, /* Inbound PLOGI from remote port */
RPSM_EVENT_PLOGI_COMP = 3, /* PLOGI completed to rport */
RPSM_EVENT_LOGO_RCVD = 4, /* LOGO from remote device */
RPSM_EVENT_LOGO_IMP = 5, /* implicit logo for SLER */
RPSM_EVENT_FCXP_SENT = 6, /* Frame from has been sent */
RPSM_EVENT_DELETE = 7, /* RPORT delete request */
RPSM_EVENT_SCN = 8, /* state change notification */
RPSM_EVENT_ACCEPTED = 9,/* Good response from remote device */
RPSM_EVENT_FAILED = 10, /* Request to rport failed. */
RPSM_EVENT_TIMEOUT = 11, /* Rport SM timeout event */
RPSM_EVENT_HCB_ONLINE = 12, /* BFA rport online callback */
RPSM_EVENT_HCB_OFFLINE = 13, /* BFA rport offline callback */
RPSM_EVENT_FC4_OFFLINE = 14, /* FC-4 offline complete */
RPSM_EVENT_ADDRESS_CHANGE = 15, /* Rport's PID has changed */
RPSM_EVENT_ADDRESS_DISC = 16 /* Need to Discover rport's PID */
};
static void bfa_fcs_rport_sm_uninit(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogi_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogiacc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogi_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogi(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hal_online(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_online(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsquery_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsquery(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_adisc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_adisc(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hcb_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hcb_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hcb_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_logo_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_sent(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_sent(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static struct bfa_sm_table_s rport_sm_table[] = {
{BFA_SM(bfa_fcs_rport_sm_uninit), BFA_RPORT_UNINIT},
{BFA_SM(bfa_fcs_rport_sm_plogi_sending), BFA_RPORT_PLOGI},
{BFA_SM(bfa_fcs_rport_sm_plogiacc_sending), BFA_RPORT_ONLINE},
{BFA_SM(bfa_fcs_rport_sm_plogi_retry), BFA_RPORT_PLOGI_RETRY},
{BFA_SM(bfa_fcs_rport_sm_plogi), BFA_RPORT_PLOGI},
{BFA_SM(bfa_fcs_rport_sm_hal_online), BFA_RPORT_ONLINE},
{BFA_SM(bfa_fcs_rport_sm_online), BFA_RPORT_ONLINE},
{BFA_SM(bfa_fcs_rport_sm_nsquery_sending), BFA_RPORT_NSQUERY},
{BFA_SM(bfa_fcs_rport_sm_nsquery), BFA_RPORT_NSQUERY},
{BFA_SM(bfa_fcs_rport_sm_adisc_sending), BFA_RPORT_ADISC},
{BFA_SM(bfa_fcs_rport_sm_adisc), BFA_RPORT_ADISC},
{BFA_SM(bfa_fcs_rport_sm_fc4_logorcv), BFA_RPORT_LOGORCV},
{BFA_SM(bfa_fcs_rport_sm_fc4_logosend), BFA_RPORT_LOGO},
{BFA_SM(bfa_fcs_rport_sm_fc4_offline), BFA_RPORT_OFFLINE},
{BFA_SM(bfa_fcs_rport_sm_hcb_offline), BFA_RPORT_OFFLINE},
{BFA_SM(bfa_fcs_rport_sm_hcb_logorcv), BFA_RPORT_LOGORCV},
{BFA_SM(bfa_fcs_rport_sm_hcb_logosend), BFA_RPORT_LOGO},
{BFA_SM(bfa_fcs_rport_sm_logo_sending), BFA_RPORT_LOGO},
{BFA_SM(bfa_fcs_rport_sm_offline), BFA_RPORT_OFFLINE},
{BFA_SM(bfa_fcs_rport_sm_nsdisc_sending), BFA_RPORT_NSDISC},
{BFA_SM(bfa_fcs_rport_sm_nsdisc_retry), BFA_RPORT_NSDISC},
{BFA_SM(bfa_fcs_rport_sm_nsdisc_sent), BFA_RPORT_NSDISC},
};
/**
* Beginning state.
*/
static void
bfa_fcs_rport_sm_uninit(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_PLOGI_SEND:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
rport->plogi_retries = 0;
bfa_fcs_rport_send_plogi(rport, NULL);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcs_rport_hal_online(rport);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_ADDRESS_DISC:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
break;
default:
bfa_assert(0);
}
}
/**
* PLOGI is being sent.
*/
static void
bfa_fcs_rport_sm_plogi_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_SCN:
break;
default:
bfa_assert(0);
}
}
/**
* PLOGI is being sent.
*/
static void
bfa_fcs_rport_sm_plogiacc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcs_rport_hal_online(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_SCN:
/**
* Ignore, SCN is possibly online notification.
*/
break;
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_HCB_OFFLINE:
/**
* Ignore BFA callback, on a PLOGI receive we call bfa offline.
*/
break;
default:
bfa_assert(0);
}
}
/**
* PLOGI is sent.
*/
static void
bfa_fcs_rport_sm_plogi_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_SCN:
bfa_timer_stop(&rport->timer);
/*
* !! fall through !!
*/
case RPSM_EVENT_TIMEOUT:
rport->plogi_retries++;
if (rport->plogi_retries < BFA_FCS_RPORT_MAX_RETRIES) {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
bfa_fcs_rport_send_plogi(rport, NULL);
} else {
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_timer_stop(&rport->timer);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_stop(&rport->timer);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_hal_online(rport);
break;
default:
bfa_assert(0);
}
}
/**
* PLOGI is sent.
*/
static void
bfa_fcs_rport_sm_plogi(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
rport->plogi_retries = 0;
bfa_fcs_rport_hal_online(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_fcs_rport_send_logo_acc(rport);
bfa_fcxp_discard(rport->fcxp);
/*
* !! fall through !!
*/
case RPSM_EVENT_FAILED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_retry);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
BFA_FCS_RETRY_TIMEOUT);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_fcxp_discard(rport->fcxp);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_SCN:
/**
* Ignore SCN - wait for PLOGI response.
*/
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_hal_online(rport);
break;
default:
bfa_assert(0);
}
}
/**
* PLOGI is complete. Awaiting BFA rport online callback. FC-4s
* are offline.
*/
static void
bfa_fcs_rport_sm_hal_online(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_ONLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_online);
bfa_fcs_rport_online_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logorcv);
bfa_rport_offline(rport->bfa_rport);
break;
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_offline);
bfa_rport_offline(rport->bfa_rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_rport_offline(rport->bfa_rport);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logosend);
bfa_rport_offline(rport->bfa_rport);
break;
case RPSM_EVENT_SCN:
/**
* @todo
* Ignore SCN - PLOGI just completed, FC-4 login should detect
* device failures.
*/
break;
default:
bfa_assert(0);
}
}
/**
* Rport is ONLINE. FC-4s active.
*/
static void
bfa_fcs_rport_sm_online(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_SCN:
/**
* Pause FC-4 activity till rport is authenticated.
* In switched fabrics, check presence of device in nameserver
* first.
*/
bfa_fcs_rport_fc4_pause(rport);
if (bfa_fcs_fabric_is_switched(rport->port->fabric)) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsquery_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
} else {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_adisc_sending);
bfa_fcs_rport_send_adisc(rport, NULL);
}
break;
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
break;
default:
bfa_assert(0);
}
}
/**
* An SCN event is received in ONLINE state. NS query is being sent
* prior to ADISC authentication with rport. FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_nsquery_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsquery);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_SCN:
/**
* ignore SCN, wait for response to query itself
*/
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
default:
bfa_assert(0);
}
}
/**
* An SCN event is received in ONLINE state. NS query is sent to rport.
* FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_nsquery(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_adisc_sending);
bfa_fcs_rport_send_adisc(rport, NULL);
break;
case RPSM_EVENT_FAILED:
rport->ns_retries++;
if (rport->ns_retries < BFA_FCS_RPORT_MAX_RETRIES) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsquery_sending);
bfa_fcs_rport_send_gidpn(rport, NULL);
} else {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_offline_action(rport);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_SCN:
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
default:
bfa_assert(0);
}
}
/**
* An SCN event is received in ONLINE state. ADISC is being sent for
* authenticating with rport. FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_adisc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_adisc);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_SCN:
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
default:
bfa_assert(0);
}
}
/**
* An SCN event is received in ONLINE state. ADISC is to rport.
* FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_adisc(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_online);
bfa_fcs_rport_fc4_resume(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
/**
* Too complex to cleanup FC-4 & rport and then acc to PLOGI.
* At least go offline when a PLOGI is received.
*/
bfa_fcxp_discard(rport->fcxp);
/*
* !!! fall through !!!
*/
case RPSM_EVENT_FAILED:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_SCN:
/**
* already processing RSCN
*/
break;
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
default:
bfa_assert(0);
}
}
/**
* Rport has sent LOGO. Awaiting FC-4 offline completion callback.
*/
static void
bfa_fcs_rport_sm_fc4_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logorcv);
bfa_rport_offline(rport->bfa_rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_ADDRESS_CHANGE:
break;
default:
bfa_assert(0);
}
}
/**
* LOGO needs to be sent to rport. Awaiting FC-4 offline completion
* callback.
*/
static void
bfa_fcs_rport_sm_fc4_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logosend);
bfa_rport_offline(rport->bfa_rport);
break;
default:
bfa_assert(0);
}
}
/**
* Rport is going offline. Awaiting FC-4 offline completion callback.
*/
static void
bfa_fcs_rport_sm_fc4_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_offline);
bfa_rport_offline(rport->bfa_rport);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_ADDRESS_CHANGE:
/**
* rport is already going offline.
* SCN - ignore and wait till transitioning to offline state
*/
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
break;
default:
bfa_assert(0);
}
}
/**
* Rport is offline. FC-4s are offline. Awaiting BFA rport offline
* callback.
*/
static void
bfa_fcs_rport_sm_hcb_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_OFFLINE:
case RPSM_EVENT_ADDRESS_CHANGE:
if (bfa_fcs_port_is_online(rport->port)) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
} else {
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_LOGO_RCVD:
/**
* Ignore, already offline.
*/
break;
default:
bfa_assert(0);
}
}
/**
* Rport is offline. FC-4s are offline. Awaiting BFA rport offline
* callback to send LOGO accept.
*/
static void
bfa_fcs_rport_sm_hcb_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_OFFLINE:
case RPSM_EVENT_ADDRESS_CHANGE:
if (rport->pid)
bfa_fcs_rport_send_logo_acc(rport);
/*
* If the lport is online and if the rport is not a well known
* address port, we try to re-discover the r-port.
*/
if (bfa_fcs_port_is_online(rport->port)
&& (!BFA_FCS_PID_IS_WKA(rport->pid))) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
} else {
/*
* if it is not a well known address, reset the pid to
*
*/
if (!BFA_FCS_PID_IS_WKA(rport->pid))
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logosend);
break;
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_offline);
break;
case RPSM_EVENT_LOGO_RCVD:
/**
* Ignore - already processing a LOGO.
*/
break;
default:
bfa_assert(0);
}
}
/**
* Rport is being deleted. FC-4s are offline. Awaiting BFA rport offline
* callback to send LOGO.
*/
static void
bfa_fcs_rport_sm_hcb_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_logo_sending);
bfa_fcs_rport_send_logo(rport, NULL);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_ADDRESS_CHANGE:
break;
default:
bfa_assert(0);
}
}
/**
* Rport is being deleted. FC-4s are offline. LOGO is being sent.
*/
static void
bfa_fcs_rport_sm_logo_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
/*
* Once LOGO is sent, we donot wait for the response
*/
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_ADDRESS_CHANGE:
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
default:
bfa_assert(0);
}
}
/**
* Rport is offline. FC-4s are offline. BFA rport is offline.
* Timer active to delete stale rport.
*/
static void
bfa_fcs_rport_sm_offline(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_TIMEOUT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
bfa_timer_stop(&rport->timer);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_LOGO_IMP:
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_hal_online(rport);
break;
case RPSM_EVENT_PLOGI_SEND:
bfa_timer_stop(&rport->timer);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
rport->plogi_retries = 0;
bfa_fcs_rport_send_plogi(rport, NULL);
break;
default:
bfa_assert(0);
}
}
/**
* Rport address has changed. Nameserver discovery request is being sent.
*/
static void
bfa_fcs_rport_sm_nsdisc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sent);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PLOGI_SEND:
break;
case RPSM_EVENT_ADDRESS_CHANGE:
rport->ns_retries = 0; /* reset the retry count */
break;
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_hal_online(rport);
break;
default:
bfa_assert(0);
}
}
/**
* Nameserver discovery failed. Waiting for timeout to retry.
*/
static void
bfa_fcs_rport_sm_nsdisc_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_TIMEOUT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
bfa_fcs_rport_send_gidpn(rport, NULL);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
bfa_timer_stop(&rport->timer);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_stop(&rport->timer);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_fcs_rport_send_logo_acc(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_hal_online(rport);
break;
default:
bfa_assert(0);
}
}
/**
* Rport address has changed. Nameserver discovery request is sent.
*/
static void
bfa_fcs_rport_sm_nsdisc_sent(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
case RPSM_EVENT_ADDRESS_CHANGE:
if (rport->pid) {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
bfa_fcs_rport_send_plogi(rport, NULL);
} else {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_gidpn(rport, NULL);
}
break;
case RPSM_EVENT_FAILED:
rport->ns_retries++;
if (rport->ns_retries < BFA_FCS_RPORT_MAX_RETRIES) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
bfa_fcs_rport_send_gidpn(rport, NULL);
} else {
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
};
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_SCN:
/**
* ignore, wait for NS query response
*/
break;
case RPSM_EVENT_LOGO_RCVD:
/**
* Not logged-in yet. Accept LOGO.
*/
bfa_fcs_rport_send_logo_acc(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_hal_online(rport);
break;
default:
bfa_assert(0);
}
}
/**
* fcs_rport_private FCS RPORT provate functions
*/
static void
bfa_fcs_rport_send_plogi(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_port_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_plogi, rport);
return;
}
rport->fcxp = fcxp;
len = fc_plogi_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_port_get_fcid(port), 0,
port->port_cfg.pwwn, port->port_cfg.nwwn,
bfa_pport_get_maxfrsize(port->fcs->bfa));
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, bfa_fcs_rport_plogi_response,
(void *)rport, FC_MAX_PDUSZ, FC_RA_TOV);
rport->stats.plogis++;
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_plogi_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *)cbarg;
struct fc_logi_s *plogi_rsp;
struct fc_ls_rjt_s *ls_rjt;
struct bfa_fcs_rport_s *twin;
struct list_head *qe;
bfa_trc(rport->fcs, rport->pwwn);
/*
* Sanity Checks
*/
if (req_status != BFA_STATUS_OK) {
bfa_trc(rport->fcs, req_status);
rport->stats.plogi_failed++;
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
return;
}
plogi_rsp = (struct fc_logi_s *) BFA_FCXP_RSP_PLD(fcxp);
/**
* Check for failure first.
*/
if (plogi_rsp->els_cmd.els_code != FC_ELS_ACC) {
ls_rjt = (struct fc_ls_rjt_s *) BFA_FCXP_RSP_PLD(fcxp);
bfa_trc(rport->fcs, ls_rjt->reason_code);
bfa_trc(rport->fcs, ls_rjt->reason_code_expl);
rport->stats.plogi_rejects++;
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
return;
}
/**
* PLOGI is complete. Make sure this device is not one of the known
* device with a new FC port address.
*/
list_for_each(qe, &rport->port->rport_q) {
twin = (struct bfa_fcs_rport_s *)qe;
if (twin == rport)
continue;
if (!rport->pwwn && (plogi_rsp->port_name == twin->pwwn)) {
bfa_trc(rport->fcs, twin->pid);
bfa_trc(rport->fcs, rport->pid);
/*
* Update plogi stats in twin
*/
twin->stats.plogis += rport->stats.plogis;
twin->stats.plogi_rejects += rport->stats.plogi_rejects;
twin->stats.plogi_timeouts +=
rport->stats.plogi_timeouts;
twin->stats.plogi_failed += rport->stats.plogi_failed;
twin->stats.plogi_rcvd += rport->stats.plogi_rcvd;
twin->stats.plogi_accs++;
bfa_fcs_rport_delete(rport);
bfa_fcs_rport_update(twin, plogi_rsp);
twin->pid = rsp_fchs->s_id;
bfa_sm_send_event(twin, RPSM_EVENT_PLOGI_COMP);
return;
}
}
/**
* Normal login path -- no evil twins.
*/
rport->stats.plogi_accs++;
bfa_fcs_rport_update(rport, plogi_rsp);
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
}
static void
bfa_fcs_rport_send_plogiacc(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_port_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->reply_oxid);
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_plogiacc, rport);
return;
}
rport->fcxp = fcxp;
len = fc_plogi_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_port_get_fcid(port), rport->reply_oxid,
port->port_cfg.pwwn, port->port_cfg.nwwn,
bfa_pport_get_maxfrsize(port->fcs->bfa));
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_send_adisc(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_port_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_adisc, rport);
return;
}
rport->fcxp = fcxp;
len = fc_adisc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_port_get_fcid(port), 0,
port->port_cfg.pwwn, port->port_cfg.nwwn);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, bfa_fcs_rport_adisc_response,
rport, FC_MAX_PDUSZ, FC_RA_TOV);
rport->stats.adisc_sent++;
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_adisc_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *)cbarg;
void *pld = bfa_fcxp_get_rspbuf(fcxp);
struct fc_ls_rjt_s *ls_rjt;
if (req_status != BFA_STATUS_OK) {
bfa_trc(rport->fcs, req_status);
rport->stats.adisc_failed++;
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
return;
}
if (fc_adisc_rsp_parse((struct fc_adisc_s *)pld, rsp_len, rport->pwwn,
rport->nwwn) == FC_PARSE_OK) {
rport->stats.adisc_accs++;
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
return;
}
rport->stats.adisc_rejects++;
ls_rjt = pld;
bfa_trc(rport->fcs, ls_rjt->els_cmd.els_code);
bfa_trc(rport->fcs, ls_rjt->reason_code);
bfa_trc(rport->fcs, ls_rjt->reason_code_expl);
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
}
static void
bfa_fcs_rport_send_gidpn(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_port_s *port = rport->port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
int len;
bfa_trc(rport->fcs, rport->pid);
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_gidpn, rport);
return;
}
rport->fcxp = fcxp;
len = fc_gidpn_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
bfa_fcs_port_get_fcid(port), 0, rport->pwwn);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, bfa_fcs_rport_gidpn_response,
(void *)rport, FC_MAX_PDUSZ, FC_RA_TOV);
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_gidpn_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *)cbarg;
struct bfa_fcs_rport_s *twin;
struct list_head *qe;
struct ct_hdr_s *cthdr;
struct fcgs_gidpn_resp_s *gidpn_rsp;
bfa_trc(rport->fcs, rport->pwwn);
cthdr = (struct ct_hdr_s *) BFA_FCXP_RSP_PLD(fcxp);
cthdr->cmd_rsp_code = bfa_os_ntohs(cthdr->cmd_rsp_code);
if (cthdr->cmd_rsp_code == CT_RSP_ACCEPT) {
/*
* Check if the pid is the same as before.
*/
gidpn_rsp = (struct fcgs_gidpn_resp_s *) (cthdr + 1);
if (gidpn_rsp->dap == rport->pid) {
/*
* Device is online
*/
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
} else {
/*
* Device's PID has changed. We need to cleanup and
* re-login. If there is another device with the the
* newly discovered pid, send an scn notice so that its
* new pid can be discovered.
*/
list_for_each(qe, &rport->port->rport_q) {
twin = (struct bfa_fcs_rport_s *)qe;
if (twin == rport)
continue;
if (gidpn_rsp->dap == twin->pid) {
bfa_trc(rport->fcs, twin->pid);
bfa_trc(rport->fcs, rport->pid);
twin->pid = 0;
bfa_sm_send_event(twin,
RPSM_EVENT_ADDRESS_CHANGE);
}
}
rport->pid = gidpn_rsp->dap;
bfa_sm_send_event(rport, RPSM_EVENT_ADDRESS_CHANGE);
}
return;
}
/*
* Reject Response
*/
switch (cthdr->reason_code) {
case CT_RSN_LOGICAL_BUSY:
/*
* Need to retry
*/
bfa_sm_send_event(rport, RPSM_EVENT_TIMEOUT);
break;
case CT_RSN_UNABLE_TO_PERF:
/*
* device doesn't exist : Start timer to cleanup this later.
*/
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
break;
default:
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
break;
}
}
/**
* Called to send a logout to the rport.
*/
static void
bfa_fcs_rport_send_logo(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_port_s *port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
u16 len;
bfa_trc(rport->fcs, rport->pid);
port = rport->port;
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_logo, rport);
return;
}
rport->fcxp = fcxp;
len = fc_logo_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_port_get_fcid(port), 0,
bfa_fcs_port_get_pwwn(port));
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, rport, FC_MAX_PDUSZ,
FC_ED_TOV);
rport->stats.logos++;
bfa_fcxp_discard(rport->fcxp);
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
/**
* Send ACC for a LOGO received.
*/
static void
bfa_fcs_rport_send_logo_acc(void *rport_cbarg)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_port_s *port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
u16 len;
bfa_trc(rport->fcs, rport->pid);
port = rport->port;
fcxp = bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp)
return;
rport->stats.logo_rcvd++;
len = fc_logo_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_port_get_fcid(port), rport->reply_oxid);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
}
/**
* This routine will be called by bfa_timer on timer timeouts.
*
* param[in] rport - pointer to bfa_fcs_port_ns_t.
* param[out] rport_status - pointer to return vport status in
*
* return
* void
*
* Special Considerations:
*
* note
*/
static void
bfa_fcs_rport_timeout(void *arg)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *)arg;
rport->stats.plogi_timeouts++;
bfa_sm_send_event(rport, RPSM_EVENT_TIMEOUT);
}
static void
bfa_fcs_rport_process_prli(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len)
{
struct bfa_fcxp_s *fcxp;
struct fchs_s fchs;
struct bfa_fcs_port_s *port = rport->port;
struct fc_prli_s *prli;
bfa_trc(port->fcs, rx_fchs->s_id);
bfa_trc(port->fcs, rx_fchs->d_id);
rport->stats.prli_rcvd++;
if (BFA_FCS_VPORT_IS_TARGET_MODE(port)) {
/*
* Target Mode : Let the fcptm handle it
*/
bfa_fcs_tin_rx_prli(rport->tin, rx_fchs, len);
return;
}
/*
* We are either in Initiator or ipfc Mode
*/
prli = (struct fc_prli_s *) (rx_fchs + 1);
if (prli->parampage.servparams.initiator) {
bfa_trc(rport->fcs, prli->parampage.type);
rport->scsi_function = BFA_RPORT_INITIATOR;
bfa_fcs_itnim_is_initiator(rport->itnim);
} else {
/*
* @todo: PRLI from a target ?
*/
bfa_trc(port->fcs, rx_fchs->s_id);
rport->scsi_function = BFA_RPORT_TARGET;
}
fcxp = bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp)
return;
len = fc_prli_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rx_fchs->s_id,
bfa_fcs_port_get_fcid(port), rx_fchs->ox_id,
port->port_cfg.roles);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
}
static void
bfa_fcs_rport_process_rpsc(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len)
{
struct bfa_fcxp_s *fcxp;
struct fchs_s fchs;
struct bfa_fcs_port_s *port = rport->port;
struct fc_rpsc_speed_info_s speeds;
struct bfa_pport_attr_s pport_attr;
bfa_trc(port->fcs, rx_fchs->s_id);
bfa_trc(port->fcs, rx_fchs->d_id);
rport->stats.rpsc_rcvd++;
speeds.port_speed_cap =
RPSC_SPEED_CAP_1G | RPSC_SPEED_CAP_2G | RPSC_SPEED_CAP_4G |
RPSC_SPEED_CAP_8G;
/*
* get curent speed from pport attributes from BFA
*/
bfa_pport_get_attr(port->fcs->bfa, &pport_attr);
speeds.port_op_speed = fc_bfa_speed_to_rpsc_operspeed(pport_attr.speed);
fcxp = bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp)
return;
len = fc_rpsc_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rx_fchs->s_id,
bfa_fcs_port_get_fcid(port), rx_fchs->ox_id,
&speeds);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
}
static void
bfa_fcs_rport_process_adisc(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len)
{
struct bfa_fcxp_s *fcxp;
struct fchs_s fchs;
struct bfa_fcs_port_s *port = rport->port;
struct fc_adisc_s *adisc;
bfa_trc(port->fcs, rx_fchs->s_id);
bfa_trc(port->fcs, rx_fchs->d_id);
rport->stats.adisc_rcvd++;
if (BFA_FCS_VPORT_IS_TARGET_MODE(port)) {
/*
* @todo : Target Mode handling
*/
bfa_trc(port->fcs, rx_fchs->d_id);
bfa_assert(0);
return;
}
adisc = (struct fc_adisc_s *) (rx_fchs + 1);
/*
* Accept if the itnim for this rport is online. Else reject the ADISC
*/
if (bfa_fcs_itnim_get_online_state(rport->itnim) == BFA_STATUS_OK) {
fcxp = bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp)
return;
len = fc_adisc_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rx_fchs->s_id,
bfa_fcs_port_get_fcid(port),
rx_fchs->ox_id, port->port_cfg.pwwn,
port->port_cfg.nwwn);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag,
BFA_FALSE, FC_CLASS_3, len, &fchs, NULL, NULL,
FC_MAX_PDUSZ, 0);
} else {
rport->stats.adisc_rejected++;
bfa_fcs_rport_send_ls_rjt(rport, rx_fchs,
FC_LS_RJT_RSN_UNABLE_TO_PERF_CMD,
FC_LS_RJT_EXP_LOGIN_REQUIRED);
}
}
static void
bfa_fcs_rport_hal_online(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_port_s *port = rport->port;
struct bfa_rport_info_s rport_info;
rport_info.pid = rport->pid;
rport_info.local_pid = port->pid;
rport_info.lp_tag = port->lp_tag;
rport_info.vf_id = port->fabric->vf_id;
rport_info.vf_en = port->fabric->is_vf;
rport_info.fc_class = rport->fc_cos;
rport_info.cisc = rport->cisc;
rport_info.max_frmsz = rport->maxfrsize;
bfa_rport_online(rport->bfa_rport, &rport_info);
}
static void
bfa_fcs_rport_fc4_pause(struct bfa_fcs_rport_s *rport)
{
if (bfa_fcs_port_is_initiator(rport->port))
bfa_fcs_itnim_pause(rport->itnim);
if (bfa_fcs_port_is_target(rport->port))
bfa_fcs_tin_pause(rport->tin);
}
static void
bfa_fcs_rport_fc4_resume(struct bfa_fcs_rport_s *rport)
{
if (bfa_fcs_port_is_initiator(rport->port))
bfa_fcs_itnim_resume(rport->itnim);
if (bfa_fcs_port_is_target(rport->port))
bfa_fcs_tin_resume(rport->tin);
}
static struct bfa_fcs_rport_s *
bfa_fcs_rport_alloc(struct bfa_fcs_port_s *port, wwn_t pwwn, u32 rpid)
{
struct bfa_fcs_s *fcs = port->fcs;
struct bfa_fcs_rport_s *rport;
struct bfad_rport_s *rport_drv;
/**
* allocate rport
*/
if (bfa_fcb_rport_alloc(fcs->bfad, &rport, &rport_drv)
!= BFA_STATUS_OK) {
bfa_trc(fcs, rpid);
return NULL;
}
/*
* Initialize r-port
*/
rport->port = port;
rport->fcs = fcs;
rport->rp_drv = rport_drv;
rport->pid = rpid;
rport->pwwn = pwwn;
/**
* allocate BFA rport
*/
rport->bfa_rport = bfa_rport_create(port->fcs->bfa, rport);
if (!rport->bfa_rport) {
bfa_trc(fcs, rpid);
kfree(rport_drv);
return NULL;
}
/**
* allocate FC-4s
*/
bfa_assert(bfa_fcs_port_is_initiator(port) ^
bfa_fcs_port_is_target(port));
if (bfa_fcs_port_is_initiator(port)) {
rport->itnim = bfa_fcs_itnim_create(rport);
if (!rport->itnim) {
bfa_trc(fcs, rpid);
bfa_rport_delete(rport->bfa_rport);
kfree(rport_drv);
return NULL;
}
}
if (bfa_fcs_port_is_target(port)) {
rport->tin = bfa_fcs_tin_create(rport);
if (!rport->tin) {
bfa_trc(fcs, rpid);
bfa_rport_delete(rport->bfa_rport);
kfree(rport_drv);
return NULL;
}
}
bfa_fcs_port_add_rport(port, rport);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
/*
* Initialize the Rport Features(RPF) Sub Module
*/
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_init(rport);
return rport;
}
static void
bfa_fcs_rport_free(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_port_s *port = rport->port;
/**
* - delete FC-4s
* - delete BFA rport
* - remove from queue of rports
*/
if (bfa_fcs_port_is_initiator(port))
bfa_fcs_itnim_delete(rport->itnim);
if (bfa_fcs_port_is_target(port))
bfa_fcs_tin_delete(rport->tin);
bfa_rport_delete(rport->bfa_rport);
bfa_fcs_port_del_rport(port, rport);
kfree(rport->rp_drv);
}
static void
bfa_fcs_rport_aen_post(struct bfa_fcs_rport_s *rport,
enum bfa_rport_aen_event event,
struct bfa_rport_aen_data_s *data)
{
union bfa_aen_data_u aen_data;
struct bfa_log_mod_s *logmod = rport->fcs->logm;
wwn_t lpwwn = bfa_fcs_port_get_pwwn(rport->port);
wwn_t rpwwn = rport->pwwn;
char lpwwn_ptr[BFA_STRING_32];
char rpwwn_ptr[BFA_STRING_32];
char *prio_str[] = { "unknown", "high", "medium", "low" };
wwn2str(lpwwn_ptr, lpwwn);
wwn2str(rpwwn_ptr, rpwwn);
switch (event) {
case BFA_RPORT_AEN_ONLINE:
bfa_log(logmod, BFA_AEN_RPORT_ONLINE, rpwwn_ptr, lpwwn_ptr);
break;
case BFA_RPORT_AEN_OFFLINE:
bfa_log(logmod, BFA_AEN_RPORT_OFFLINE, rpwwn_ptr, lpwwn_ptr);
break;
case BFA_RPORT_AEN_DISCONNECT:
bfa_log(logmod, BFA_AEN_RPORT_DISCONNECT, rpwwn_ptr, lpwwn_ptr);
break;
case BFA_RPORT_AEN_QOS_PRIO:
aen_data.rport.priv.qos = data->priv.qos;
bfa_log(logmod, BFA_AEN_RPORT_QOS_PRIO,
prio_str[aen_data.rport.priv.qos.qos_priority],
rpwwn_ptr, lpwwn_ptr);
break;
case BFA_RPORT_AEN_QOS_FLOWID:
aen_data.rport.priv.qos = data->priv.qos;
bfa_log(logmod, BFA_AEN_RPORT_QOS_FLOWID,
aen_data.rport.priv.qos.qos_flow_id, rpwwn_ptr,
lpwwn_ptr);
break;
default:
break;
}
aen_data.rport.vf_id = rport->port->fabric->vf_id;
aen_data.rport.ppwwn =
bfa_fcs_port_get_pwwn(bfa_fcs_get_base_port(rport->fcs));
aen_data.rport.lpwwn = lpwwn;
aen_data.rport.rpwwn = rpwwn;
}
static void
bfa_fcs_rport_online_action(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_port_s *port = rport->port;
rport->stats.onlines++;
if (bfa_fcs_port_is_initiator(port)) {
bfa_fcs_itnim_rport_online(rport->itnim);
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_rport_online(rport);
};
if (bfa_fcs_port_is_target(port))
bfa_fcs_tin_rport_online(rport->tin);
/*
* Don't post events for well known addresses
*/
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_ONLINE, NULL);
}
static void
bfa_fcs_rport_offline_action(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_port_s *port = rport->port;
rport->stats.offlines++;
/*
* Don't post events for well known addresses
*/
if (!BFA_FCS_PID_IS_WKA(rport->pid)) {
if (bfa_fcs_port_is_online(rport->port) == BFA_TRUE) {
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_DISCONNECT,
NULL);
} else {
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_OFFLINE,
NULL);
}
}
if (bfa_fcs_port_is_initiator(port)) {
bfa_fcs_itnim_rport_offline(rport->itnim);
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_rport_offline(rport);
}
if (bfa_fcs_port_is_target(port))
bfa_fcs_tin_rport_offline(rport->tin);
}
/**
* Update rport parameters from PLOGI or PLOGI accept.
*/
static void
bfa_fcs_rport_update(struct bfa_fcs_rport_s *rport, struct fc_logi_s *plogi)
{
struct bfa_fcs_port_s *port = rport->port;
/**
* - port name
* - node name
*/
rport->pwwn = plogi->port_name;
rport->nwwn = plogi->node_name;
/**
* - class of service
*/
rport->fc_cos = 0;
if (plogi->class3.class_valid)
rport->fc_cos = FC_CLASS_3;
if (plogi->class2.class_valid)
rport->fc_cos |= FC_CLASS_2;
/**
* - CISC
* - MAX receive frame size
*/
rport->cisc = plogi->csp.cisc;
rport->maxfrsize = bfa_os_ntohs(plogi->class3.rxsz);
bfa_trc(port->fcs, bfa_os_ntohs(plogi->csp.bbcred));
bfa_trc(port->fcs, port->fabric->bb_credit);
/**
* Direct Attach P2P mode :
* This is to handle a bug (233476) in IBM targets in Direct Attach
* Mode. Basically, in FLOGI Accept the target would have erroneously
* set the BB Credit to the value used in the FLOGI sent by the HBA.
* It uses the correct value (its own BB credit) in PLOGI.
*/
if ((!bfa_fcs_fabric_is_switched(port->fabric))
&& (bfa_os_ntohs(plogi->csp.bbcred) < port->fabric->bb_credit)) {
bfa_trc(port->fcs, bfa_os_ntohs(plogi->csp.bbcred));
bfa_trc(port->fcs, port->fabric->bb_credit);
port->fabric->bb_credit = bfa_os_ntohs(plogi->csp.bbcred);
bfa_pport_set_tx_bbcredit(port->fcs->bfa,
port->fabric->bb_credit);
}
}
/**
* Called to handle LOGO received from an existing remote port.
*/
static void
bfa_fcs_rport_process_logo(struct bfa_fcs_rport_s *rport, struct fchs_s *fchs)
{
rport->reply_oxid = fchs->ox_id;
bfa_trc(rport->fcs, rport->reply_oxid);
rport->stats.logo_rcvd++;
bfa_sm_send_event(rport, RPSM_EVENT_LOGO_RCVD);
}
/**
* fcs_rport_public FCS rport public interfaces
*/
/**
* Called by bport/vport to create a remote port instance for a discovered
* remote device.
*
* @param[in] port - base port or vport
* @param[in] rpid - remote port ID
*
* @return None
*/
struct bfa_fcs_rport_s *
bfa_fcs_rport_create(struct bfa_fcs_port_s *port, u32 rpid)
{
struct bfa_fcs_rport_s *rport;
bfa_trc(port->fcs, rpid);
rport = bfa_fcs_rport_alloc(port, WWN_NULL, rpid);
if (!rport)
return NULL;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_SEND);
return rport;
}
/**
* Called to create a rport for which only the wwn is known.
*
* @param[in] port - base port
* @param[in] rpwwn - remote port wwn
*
* @return None
*/
struct bfa_fcs_rport_s *
bfa_fcs_rport_create_by_wwn(struct bfa_fcs_port_s *port, wwn_t rpwwn)
{
struct bfa_fcs_rport_s *rport;
bfa_trc(port->fcs, rpwwn);
rport = bfa_fcs_rport_alloc(port, rpwwn, 0);
if (!rport)
return NULL;
bfa_sm_send_event(rport, RPSM_EVENT_ADDRESS_DISC);
return rport;
}
/**
* Called by bport in private loop topology to indicate that a
* rport has been discovered and plogi has been completed.
*
* @param[in] port - base port or vport
* @param[in] rpid - remote port ID
*/
void
bfa_fcs_rport_start(struct bfa_fcs_port_s *port, struct fchs_s *fchs,
struct fc_logi_s *plogi)
{
struct bfa_fcs_rport_s *rport;
rport = bfa_fcs_rport_alloc(port, WWN_NULL, fchs->s_id);
if (!rport)
return;
bfa_fcs_rport_update(rport, plogi);
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_COMP);
}
/**
* Called by bport/vport to handle PLOGI received from a new remote port.
* If an existing rport does a plogi, it will be handled separately.
*/
void
bfa_fcs_rport_plogi_create(struct bfa_fcs_port_s *port, struct fchs_s *fchs,
struct fc_logi_s *plogi)
{
struct bfa_fcs_rport_s *rport;
rport = bfa_fcs_rport_alloc(port, plogi->port_name, fchs->s_id);
if (!rport)
return;
bfa_fcs_rport_update(rport, plogi);
rport->reply_oxid = fchs->ox_id;
bfa_trc(rport->fcs, rport->reply_oxid);
rport->stats.plogi_rcvd++;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_RCVD);
}
static int
wwn_compare(wwn_t wwn1, wwn_t wwn2)
{
u8 *b1 = (u8 *) &wwn1;
u8 *b2 = (u8 *) &wwn2;
int i;
for (i = 0; i < sizeof(wwn_t); i++) {
if (b1[i] < b2[i])
return -1;
if (b1[i] > b2[i])
return 1;
}
return 0;
}
/**
* Called by bport/vport to handle PLOGI received from an existing
* remote port.
*/
void
bfa_fcs_rport_plogi(struct bfa_fcs_rport_s *rport, struct fchs_s *rx_fchs,
struct fc_logi_s *plogi)
{
/**
* @todo Handle P2P and initiator-initiator.
*/
bfa_fcs_rport_update(rport, plogi);
rport->reply_oxid = rx_fchs->ox_id;
bfa_trc(rport->fcs, rport->reply_oxid);
/**
* In Switched fabric topology,
* PLOGI to each other. If our pwwn is smaller, ignore it,
* if it is not a well known address.
* If the link topology is N2N,
* this Plogi should be accepted.
*/
if ((wwn_compare(rport->port->port_cfg.pwwn, rport->pwwn) == -1)
&& (bfa_fcs_fabric_is_switched(rport->port->fabric))
&& (!BFA_FCS_PID_IS_WKA(rport->pid))) {
bfa_trc(rport->fcs, rport->pid);
return;
}
rport->stats.plogi_rcvd++;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_RCVD);
}
/**
* Called by bport/vport to delete a remote port instance.
*
* Rport delete is called under the following conditions:
* - vport is deleted
* - vf is deleted
* - explicit request from OS to delete rport (vmware)
*/
void
bfa_fcs_rport_delete(struct bfa_fcs_rport_s *rport)
{
bfa_sm_send_event(rport, RPSM_EVENT_DELETE);
}
/**
* Called by bport/vport to when a target goes offline.
*
*/
void
bfa_fcs_rport_offline(struct bfa_fcs_rport_s *rport)
{
bfa_sm_send_event(rport, RPSM_EVENT_LOGO_IMP);
}
/**
* Called by bport in n2n when a target (attached port) becomes online.
*
*/
void
bfa_fcs_rport_online(struct bfa_fcs_rport_s *rport)
{
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_SEND);
}
/**
* Called by bport/vport to notify SCN for the remote port
*/
void
bfa_fcs_rport_scn(struct bfa_fcs_rport_s *rport)
{
rport->stats.rscns++;
bfa_sm_send_event(rport, RPSM_EVENT_SCN);
}
/**
* Called by fcpim to notify that the ITN cleanup is done.
*/
void
bfa_fcs_rport_itnim_ack(struct bfa_fcs_rport_s *rport)
{
bfa_sm_send_event(rport, RPSM_EVENT_FC4_OFFLINE);
}
/**
* Called by fcptm to notify that the ITN cleanup is done.
*/
void
bfa_fcs_rport_tin_ack(struct bfa_fcs_rport_s *rport)
{
bfa_sm_send_event(rport, RPSM_EVENT_FC4_OFFLINE);
}
/**
* This routine BFA callback for bfa_rport_online() call.
*
* param[in] cb_arg - rport struct.
*
* return
* void
*
* Special Considerations:
*
* note
*/
void
bfa_cb_rport_online(void *cbarg)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *)cbarg;
bfa_trc(rport->fcs, rport->pwwn);
bfa_sm_send_event(rport, RPSM_EVENT_HCB_ONLINE);
}
/**
* This routine BFA callback for bfa_rport_offline() call.
*
* param[in] rport -
*
* return
* void
*
* Special Considerations:
*
* note
*/
void
bfa_cb_rport_offline(void *cbarg)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *)cbarg;
bfa_trc(rport->fcs, rport->pwwn);
bfa_sm_send_event(rport, RPSM_EVENT_HCB_OFFLINE);
}
/**
* This routine is a static BFA callback when there is a QoS flow_id
* change notification
*
* @param[in] rport -
*
* @return void
*
* Special Considerations:
*
* @note
*/
void
bfa_cb_rport_qos_scn_flowid(void *cbarg,
struct bfa_rport_qos_attr_s old_qos_attr,
struct bfa_rport_qos_attr_s new_qos_attr)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *)cbarg;
struct bfa_rport_aen_data_s aen_data;
bfa_trc(rport->fcs, rport->pwwn);
aen_data.priv.qos = new_qos_attr;
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_QOS_FLOWID, &aen_data);
}
/**
* This routine is a static BFA callback when there is a QoS priority
* change notification
*
* @param[in] rport -
*
* @return void
*
* Special Considerations:
*
* @note
*/
void
bfa_cb_rport_qos_scn_prio(void *cbarg, struct bfa_rport_qos_attr_s old_qos_attr,
struct bfa_rport_qos_attr_s new_qos_attr)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *)cbarg;
struct bfa_rport_aen_data_s aen_data;
bfa_trc(rport->fcs, rport->pwwn);
aen_data.priv.qos = new_qos_attr;
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_QOS_PRIO, &aen_data);
}
/**
* Called to process any unsolicted frames from this remote port
*/
void
bfa_fcs_rport_logo_imp(struct bfa_fcs_rport_s *rport)
{
bfa_sm_send_event(rport, RPSM_EVENT_LOGO_IMP);
}
/**
* Called to process any unsolicted frames from this remote port
*/
void
bfa_fcs_rport_uf_recv(struct bfa_fcs_rport_s *rport, struct fchs_s *fchs,
u16 len)
{
struct bfa_fcs_port_s *port = rport->port;
struct fc_els_cmd_s *els_cmd;
bfa_trc(rport->fcs, fchs->s_id);
bfa_trc(rport->fcs, fchs->d_id);
bfa_trc(rport->fcs, fchs->type);
if (fchs->type != FC_TYPE_ELS)
return;
els_cmd = (struct fc_els_cmd_s *) (fchs + 1);
bfa_trc(rport->fcs, els_cmd->els_code);
switch (els_cmd->els_code) {
case FC_ELS_LOGO:
bfa_fcs_rport_process_logo(rport, fchs);
break;
case FC_ELS_ADISC:
bfa_fcs_rport_process_adisc(rport, fchs, len);
break;
case FC_ELS_PRLO:
if (bfa_fcs_port_is_initiator(port))
bfa_fcs_fcpim_uf_recv(rport->itnim, fchs, len);
if (bfa_fcs_port_is_target(port))
bfa_fcs_fcptm_uf_recv(rport->tin, fchs, len);
break;
case FC_ELS_PRLI:
bfa_fcs_rport_process_prli(rport, fchs, len);
break;
case FC_ELS_RPSC:
bfa_fcs_rport_process_rpsc(rport, fchs, len);
break;
default:
bfa_fcs_rport_send_ls_rjt(rport, fchs,
FC_LS_RJT_RSN_CMD_NOT_SUPP,
FC_LS_RJT_EXP_NO_ADDL_INFO);
break;
}
}
/*
* Send a LS reject
*/
static void
bfa_fcs_rport_send_ls_rjt(struct bfa_fcs_rport_s *rport, struct fchs_s *rx_fchs,
u8 reason_code, u8 reason_code_expl)
{
struct bfa_fcs_port_s *port = rport->port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
int len;
bfa_trc(rport->fcs, rx_fchs->s_id);
fcxp = bfa_fcs_fcxp_alloc(rport->fcs);
if (!fcxp)
return;
len = fc_ls_rjt_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rx_fchs->s_id,
bfa_fcs_port_get_fcid(port), rx_fchs->ox_id,
reason_code, reason_code_expl);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
}
/**
* Module initialization
*/
void
bfa_fcs_rport_modinit(struct bfa_fcs_s *fcs)
{
}
/**
* Module cleanup
*/
void
bfa_fcs_rport_modexit(struct bfa_fcs_s *fcs)
{
bfa_fcs_modexit_comp(fcs);
}
/**
* Return state of rport.
*/
int
bfa_fcs_rport_get_state(struct bfa_fcs_rport_s *rport)
{
return bfa_sm_to_state(rport_sm_table, rport->sm);
}
/**
* Called by the Driver to set rport delete/ageout timeout
*
* param[in] rport timeout value in seconds.
*
* return None
*/
void
bfa_fcs_rport_set_del_timeout(u8 rport_tmo)
{
/*
* convert to Millisecs
*/
if (rport_tmo > 0)
bfa_fcs_rport_del_timeout = rport_tmo * 1000;
}
| gpl-2.0 |
cwhuang/linux | drivers/clk/rockchip/softrst.c | 513 | 3213 | /*
* Copyright (c) 2014 MundoReader S.L.
* Author: Heiko Stuebner <heiko@sntech.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/reset-controller.h>
#include <linux/spinlock.h>
#include "clk.h"
struct rockchip_softrst {
struct reset_controller_dev rcdev;
void __iomem *reg_base;
int num_regs;
int num_per_reg;
u8 flags;
spinlock_t lock;
};
static int rockchip_softrst_assert(struct reset_controller_dev *rcdev,
unsigned long id)
{
struct rockchip_softrst *softrst = container_of(rcdev,
struct rockchip_softrst,
rcdev);
int bank = id / softrst->num_per_reg;
int offset = id % softrst->num_per_reg;
if (softrst->flags & ROCKCHIP_SOFTRST_HIWORD_MASK) {
writel(BIT(offset) | (BIT(offset) << 16),
softrst->reg_base + (bank * 4));
} else {
unsigned long flags;
u32 reg;
spin_lock_irqsave(&softrst->lock, flags);
reg = readl(softrst->reg_base + (bank * 4));
writel(reg | BIT(offset), softrst->reg_base + (bank * 4));
spin_unlock_irqrestore(&softrst->lock, flags);
}
return 0;
}
static int rockchip_softrst_deassert(struct reset_controller_dev *rcdev,
unsigned long id)
{
struct rockchip_softrst *softrst = container_of(rcdev,
struct rockchip_softrst,
rcdev);
int bank = id / softrst->num_per_reg;
int offset = id % softrst->num_per_reg;
if (softrst->flags & ROCKCHIP_SOFTRST_HIWORD_MASK) {
writel((BIT(offset) << 16), softrst->reg_base + (bank * 4));
} else {
unsigned long flags;
u32 reg;
spin_lock_irqsave(&softrst->lock, flags);
reg = readl(softrst->reg_base + (bank * 4));
writel(reg & ~BIT(offset), softrst->reg_base + (bank * 4));
spin_unlock_irqrestore(&softrst->lock, flags);
}
return 0;
}
static const struct reset_control_ops rockchip_softrst_ops = {
.assert = rockchip_softrst_assert,
.deassert = rockchip_softrst_deassert,
};
void __init rockchip_register_softrst(struct device_node *np,
unsigned int num_regs,
void __iomem *base, u8 flags)
{
struct rockchip_softrst *softrst;
int ret;
softrst = kzalloc(sizeof(*softrst), GFP_KERNEL);
if (!softrst)
return;
spin_lock_init(&softrst->lock);
softrst->reg_base = base;
softrst->flags = flags;
softrst->num_regs = num_regs;
softrst->num_per_reg = (flags & ROCKCHIP_SOFTRST_HIWORD_MASK) ? 16
: 32;
softrst->rcdev.owner = THIS_MODULE;
softrst->rcdev.nr_resets = num_regs * softrst->num_per_reg;
softrst->rcdev.ops = &rockchip_softrst_ops;
softrst->rcdev.of_node = np;
ret = reset_controller_register(&softrst->rcdev);
if (ret) {
pr_err("%s: could not register reset controller, %d\n",
__func__, ret);
kfree(softrst);
}
};
| gpl-2.0 |
simone201/Talon-SH-Vibrant | arch/mips/kernel/signal_n32.c | 769 | 6398 | /*
* Copyright (C) 2003 Broadcom Corporation
*
* 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/cache.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/ptrace.h>
#include <linux/unistd.h>
#include <linux/compat.h>
#include <linux/bitops.h>
#include <asm/abi.h>
#include <asm/asm.h>
#include <asm/cacheflush.h>
#include <asm/compat-signal.h>
#include <asm/sim.h>
#include <asm/uaccess.h>
#include <asm/ucontext.h>
#include <asm/system.h>
#include <asm/fpu.h>
#include <asm/cpu-features.h>
#include <asm/war.h>
#include <asm/vdso.h>
#include "signal-common.h"
/*
* Including <asm/unistd.h> would give use the 64-bit syscall numbers ...
*/
#define __NR_N32_restart_syscall 6214
extern int setup_sigcontext(struct pt_regs *, struct sigcontext __user *);
extern int restore_sigcontext(struct pt_regs *, struct sigcontext __user *);
/* IRIX compatible stack_t */
typedef struct sigaltstack32 {
s32 ss_sp;
compat_size_t ss_size;
int ss_flags;
} stack32_t;
struct ucontextn32 {
u32 uc_flags;
s32 uc_link;
stack32_t uc_stack;
struct sigcontext uc_mcontext;
compat_sigset_t uc_sigmask; /* mask last for extensibility */
};
struct rt_sigframe_n32 {
u32 rs_ass[4]; /* argument save space for o32 */
u32 rs_pad[2]; /* Was: signal trampoline */
struct compat_siginfo rs_info;
struct ucontextn32 rs_uc;
};
extern void sigset_from_compat(sigset_t *set, compat_sigset_t *compat);
asmlinkage int sysn32_rt_sigsuspend(nabi_no_regargs struct pt_regs regs)
{
compat_sigset_t __user *unewset;
compat_sigset_t uset;
size_t sigsetsize;
sigset_t newset;
/* XXX Don't preclude handling different sized sigset_t's. */
sigsetsize = regs.regs[5];
if (sigsetsize != sizeof(sigset_t))
return -EINVAL;
unewset = (compat_sigset_t __user *) regs.regs[4];
if (copy_from_user(&uset, unewset, sizeof(uset)))
return -EFAULT;
sigset_from_compat(&newset, &uset);
sigdelsetmask(&newset, ~_BLOCKABLE);
spin_lock_irq(¤t->sighand->siglock);
current->saved_sigmask = current->blocked;
current->blocked = newset;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
current->state = TASK_INTERRUPTIBLE;
schedule();
set_thread_flag(TIF_RESTORE_SIGMASK);
return -ERESTARTNOHAND;
}
asmlinkage void sysn32_rt_sigreturn(nabi_no_regargs struct pt_regs regs)
{
struct rt_sigframe_n32 __user *frame;
sigset_t set;
stack_t st;
s32 sp;
int sig;
frame = (struct rt_sigframe_n32 __user *) regs.regs[29];
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_conv_sigset_from_user(&set, &frame->rs_uc.uc_sigmask))
goto badframe;
sigdelsetmask(&set, ~_BLOCKABLE);
spin_lock_irq(¤t->sighand->siglock);
current->blocked = set;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
sig = restore_sigcontext(®s, &frame->rs_uc.uc_mcontext);
if (sig < 0)
goto badframe;
else if (sig)
force_sig(sig, current);
/* The ucontext contains a stack32_t, so we must convert! */
if (__get_user(sp, &frame->rs_uc.uc_stack.ss_sp))
goto badframe;
st.ss_sp = (void __user *)(long) sp;
if (__get_user(st.ss_size, &frame->rs_uc.uc_stack.ss_size))
goto badframe;
if (__get_user(st.ss_flags, &frame->rs_uc.uc_stack.ss_flags))
goto badframe;
/* It is more difficult to avoid calling this function than to
call it and ignore errors. */
do_sigaltstack((stack_t __user *)&st, NULL, regs.regs[29]);
/*
* Don't let your children do this ...
*/
__asm__ __volatile__(
"move\t$29, %0\n\t"
"j\tsyscall_exit"
:/* no outputs */
:"r" (®s));
/* Unreached */
badframe:
force_sig(SIGSEGV, current);
}
static int setup_rt_frame_n32(void *sig_return, struct k_sigaction *ka,
struct pt_regs *regs, int signr, sigset_t *set, siginfo_t *info)
{
struct rt_sigframe_n32 __user *frame;
int err = 0;
s32 sp;
frame = get_sigframe(ka, regs, sizeof(*frame));
if (!access_ok(VERIFY_WRITE, frame, sizeof (*frame)))
goto give_sigsegv;
/* Create siginfo. */
err |= copy_siginfo_to_user32(&frame->rs_info, info);
/* Create the ucontext. */
err |= __put_user(0, &frame->rs_uc.uc_flags);
err |= __put_user(0, &frame->rs_uc.uc_link);
sp = (int) (long) current->sas_ss_sp;
err |= __put_user(sp,
&frame->rs_uc.uc_stack.ss_sp);
err |= __put_user(sas_ss_flags(regs->regs[29]),
&frame->rs_uc.uc_stack.ss_flags);
err |= __put_user(current->sas_ss_size,
&frame->rs_uc.uc_stack.ss_size);
err |= setup_sigcontext(regs, &frame->rs_uc.uc_mcontext);
err |= __copy_conv_sigset_to_user(&frame->rs_uc.uc_sigmask, set);
if (err)
goto give_sigsegv;
/*
* Arguments to signal handler:
*
* a0 = signal number
* a1 = 0 (should be cause)
* a2 = pointer to ucontext
*
* $25 and c0_epc point to the signal handler, $29 points to
* the struct rt_sigframe.
*/
regs->regs[ 4] = signr;
regs->regs[ 5] = (unsigned long) &frame->rs_info;
regs->regs[ 6] = (unsigned long) &frame->rs_uc;
regs->regs[29] = (unsigned long) frame;
regs->regs[31] = (unsigned long) sig_return;
regs->cp0_epc = regs->regs[25] = (unsigned long) ka->sa.sa_handler;
DEBUGP("SIG deliver (%s:%d): sp=0x%p pc=0x%lx ra=0x%lx\n",
current->comm, current->pid,
frame, regs->cp0_epc, regs->regs[31]);
return 0;
give_sigsegv:
force_sigsegv(signr, current);
return -EFAULT;
}
struct mips_abi mips_abi_n32 = {
.setup_rt_frame = setup_rt_frame_n32,
.rt_signal_return_offset =
offsetof(struct mips_vdso, n32_rt_signal_trampoline),
.restart = __NR_N32_restart_syscall
};
| gpl-2.0 |
TSCLKS/linux | drivers/firmware/iscsi_ibft.c | 769 | 19737 | /*
* Copyright 2007-2010 Red Hat, Inc.
* by Peter Jones <pjones@redhat.com>
* Copyright 2008 IBM, Inc.
* by Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Copyright 2008
* by Konrad Rzeszutek <ketuzsezr@darnok.org>
*
* This code exposes the iSCSI Boot Format Table to userland via sysfs.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License v2.0 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.
*
* Changelog:
*
* 06 Jan 2010 - Peter Jones <pjones@redhat.com>
* New changelog entries are in the git log from now on. Not here.
*
* 14 Mar 2008 - Konrad Rzeszutek <ketuzsezr@darnok.org>
* Updated comments and copyrights. (v0.4.9)
*
* 11 Feb 2008 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Converted to using ibft_addr. (v0.4.8)
*
* 8 Feb 2008 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Combined two functions in one: reserve_ibft_region. (v0.4.7)
*
* 30 Jan 2008 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added logic to handle IPv6 addresses. (v0.4.6)
*
* 25 Jan 2008 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added logic to handle badly not-to-spec iBFT. (v0.4.5)
*
* 4 Jan 2008 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added __init to function declarations. (v0.4.4)
*
* 21 Dec 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Updated kobject registration, combined unregister functions in one
* and code and style cleanup. (v0.4.3)
*
* 5 Dec 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added end-markers to enums and re-organized kobject registration. (v0.4.2)
*
* 4 Dec 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Created 'device' sysfs link to the NIC and style cleanup. (v0.4.1)
*
* 28 Nov 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added sysfs-ibft documentation, moved 'find_ibft' function to
* in its own file and added text attributes for every struct field. (v0.4)
*
* 21 Nov 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added text attributes emulating OpenFirmware /proc/device-tree naming.
* Removed binary /sysfs interface (v0.3)
*
* 29 Aug 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added functionality in setup.c to reserve iBFT region. (v0.2)
*
* 27 Aug 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* First version exposing iBFT data via a binary /sysfs. (v0.1)
*
*/
#include <linux/blkdev.h>
#include <linux/capability.h>
#include <linux/ctype.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/iscsi_ibft.h>
#include <linux/limits.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/acpi.h>
#include <linux/iscsi_boot_sysfs.h>
#define IBFT_ISCSI_VERSION "0.5.0"
#define IBFT_ISCSI_DATE "2010-Feb-25"
MODULE_AUTHOR("Peter Jones <pjones@redhat.com> and "
"Konrad Rzeszutek <ketuzsezr@darnok.org>");
MODULE_DESCRIPTION("sysfs interface to BIOS iBFT information");
MODULE_LICENSE("GPL");
MODULE_VERSION(IBFT_ISCSI_VERSION);
struct ibft_hdr {
u8 id;
u8 version;
u16 length;
u8 index;
u8 flags;
} __attribute__((__packed__));
struct ibft_control {
struct ibft_hdr hdr;
u16 extensions;
u16 initiator_off;
u16 nic0_off;
u16 tgt0_off;
u16 nic1_off;
u16 tgt1_off;
} __attribute__((__packed__));
struct ibft_initiator {
struct ibft_hdr hdr;
char isns_server[16];
char slp_server[16];
char pri_radius_server[16];
char sec_radius_server[16];
u16 initiator_name_len;
u16 initiator_name_off;
} __attribute__((__packed__));
struct ibft_nic {
struct ibft_hdr hdr;
char ip_addr[16];
u8 subnet_mask_prefix;
u8 origin;
char gateway[16];
char primary_dns[16];
char secondary_dns[16];
char dhcp[16];
u16 vlan;
char mac[6];
u16 pci_bdf;
u16 hostname_len;
u16 hostname_off;
} __attribute__((__packed__));
struct ibft_tgt {
struct ibft_hdr hdr;
char ip_addr[16];
u16 port;
char lun[8];
u8 chap_type;
u8 nic_assoc;
u16 tgt_name_len;
u16 tgt_name_off;
u16 chap_name_len;
u16 chap_name_off;
u16 chap_secret_len;
u16 chap_secret_off;
u16 rev_chap_name_len;
u16 rev_chap_name_off;
u16 rev_chap_secret_len;
u16 rev_chap_secret_off;
} __attribute__((__packed__));
/*
* The kobject different types and its names.
*
*/
enum ibft_id {
id_reserved = 0, /* We don't support. */
id_control = 1, /* Should show up only once and is not exported. */
id_initiator = 2,
id_nic = 3,
id_target = 4,
id_extensions = 5, /* We don't support. */
id_end_marker,
};
/*
* The kobject and attribute structures.
*/
struct ibft_kobject {
struct acpi_table_ibft *header;
union {
struct ibft_initiator *initiator;
struct ibft_nic *nic;
struct ibft_tgt *tgt;
struct ibft_hdr *hdr;
};
};
static struct iscsi_boot_kset *boot_kset;
static const char nulls[16];
/*
* Helper functions to parse data properly.
*/
static ssize_t sprintf_ipaddr(char *buf, u8 *ip)
{
char *str = buf;
if (ip[0] == 0 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0 &&
ip[4] == 0 && ip[5] == 0 && ip[6] == 0 && ip[7] == 0 &&
ip[8] == 0 && ip[9] == 0 && ip[10] == 0xff && ip[11] == 0xff) {
/*
* IPV4
*/
str += sprintf(buf, "%pI4", ip + 12);
} else {
/*
* IPv6
*/
str += sprintf(str, "%pI6", ip);
}
str += sprintf(str, "\n");
return str - buf;
}
static ssize_t sprintf_string(char *str, int len, char *buf)
{
return sprintf(str, "%.*s\n", len, buf);
}
/*
* Helper function to verify the IBFT header.
*/
static int ibft_verify_hdr(char *t, struct ibft_hdr *hdr, int id, int length)
{
if (hdr->id != id) {
printk(KERN_ERR "iBFT error: We expected the %s " \
"field header.id to have %d but " \
"found %d instead!\n", t, id, hdr->id);
return -ENODEV;
}
if (hdr->length != length) {
printk(KERN_ERR "iBFT error: We expected the %s " \
"field header.length to have %d but " \
"found %d instead!\n", t, length, hdr->length);
return -ENODEV;
}
return 0;
}
/*
* Routines for parsing the iBFT data to be human readable.
*/
static ssize_t ibft_attr_show_initiator(void *data, int type, char *buf)
{
struct ibft_kobject *entry = data;
struct ibft_initiator *initiator = entry->initiator;
void *ibft_loc = entry->header;
char *str = buf;
if (!initiator)
return 0;
switch (type) {
case ISCSI_BOOT_INI_INDEX:
str += sprintf(str, "%d\n", initiator->hdr.index);
break;
case ISCSI_BOOT_INI_FLAGS:
str += sprintf(str, "%d\n", initiator->hdr.flags);
break;
case ISCSI_BOOT_INI_ISNS_SERVER:
str += sprintf_ipaddr(str, initiator->isns_server);
break;
case ISCSI_BOOT_INI_SLP_SERVER:
str += sprintf_ipaddr(str, initiator->slp_server);
break;
case ISCSI_BOOT_INI_PRI_RADIUS_SERVER:
str += sprintf_ipaddr(str, initiator->pri_radius_server);
break;
case ISCSI_BOOT_INI_SEC_RADIUS_SERVER:
str += sprintf_ipaddr(str, initiator->sec_radius_server);
break;
case ISCSI_BOOT_INI_INITIATOR_NAME:
str += sprintf_string(str, initiator->initiator_name_len,
(char *)ibft_loc +
initiator->initiator_name_off);
break;
default:
break;
}
return str - buf;
}
static ssize_t ibft_attr_show_nic(void *data, int type, char *buf)
{
struct ibft_kobject *entry = data;
struct ibft_nic *nic = entry->nic;
void *ibft_loc = entry->header;
char *str = buf;
__be32 val;
if (!nic)
return 0;
switch (type) {
case ISCSI_BOOT_ETH_INDEX:
str += sprintf(str, "%d\n", nic->hdr.index);
break;
case ISCSI_BOOT_ETH_FLAGS:
str += sprintf(str, "%d\n", nic->hdr.flags);
break;
case ISCSI_BOOT_ETH_IP_ADDR:
str += sprintf_ipaddr(str, nic->ip_addr);
break;
case ISCSI_BOOT_ETH_SUBNET_MASK:
val = cpu_to_be32(~((1 << (32-nic->subnet_mask_prefix))-1));
str += sprintf(str, "%pI4", &val);
break;
case ISCSI_BOOT_ETH_ORIGIN:
str += sprintf(str, "%d\n", nic->origin);
break;
case ISCSI_BOOT_ETH_GATEWAY:
str += sprintf_ipaddr(str, nic->gateway);
break;
case ISCSI_BOOT_ETH_PRIMARY_DNS:
str += sprintf_ipaddr(str, nic->primary_dns);
break;
case ISCSI_BOOT_ETH_SECONDARY_DNS:
str += sprintf_ipaddr(str, nic->secondary_dns);
break;
case ISCSI_BOOT_ETH_DHCP:
str += sprintf_ipaddr(str, nic->dhcp);
break;
case ISCSI_BOOT_ETH_VLAN:
str += sprintf(str, "%d\n", nic->vlan);
break;
case ISCSI_BOOT_ETH_MAC:
str += sprintf(str, "%pM\n", nic->mac);
break;
case ISCSI_BOOT_ETH_HOSTNAME:
str += sprintf_string(str, nic->hostname_len,
(char *)ibft_loc + nic->hostname_off);
break;
default:
break;
}
return str - buf;
};
static ssize_t ibft_attr_show_target(void *data, int type, char *buf)
{
struct ibft_kobject *entry = data;
struct ibft_tgt *tgt = entry->tgt;
void *ibft_loc = entry->header;
char *str = buf;
int i;
if (!tgt)
return 0;
switch (type) {
case ISCSI_BOOT_TGT_INDEX:
str += sprintf(str, "%d\n", tgt->hdr.index);
break;
case ISCSI_BOOT_TGT_FLAGS:
str += sprintf(str, "%d\n", tgt->hdr.flags);
break;
case ISCSI_BOOT_TGT_IP_ADDR:
str += sprintf_ipaddr(str, tgt->ip_addr);
break;
case ISCSI_BOOT_TGT_PORT:
str += sprintf(str, "%d\n", tgt->port);
break;
case ISCSI_BOOT_TGT_LUN:
for (i = 0; i < 8; i++)
str += sprintf(str, "%x", (u8)tgt->lun[i]);
str += sprintf(str, "\n");
break;
case ISCSI_BOOT_TGT_NIC_ASSOC:
str += sprintf(str, "%d\n", tgt->nic_assoc);
break;
case ISCSI_BOOT_TGT_CHAP_TYPE:
str += sprintf(str, "%d\n", tgt->chap_type);
break;
case ISCSI_BOOT_TGT_NAME:
str += sprintf_string(str, tgt->tgt_name_len,
(char *)ibft_loc + tgt->tgt_name_off);
break;
case ISCSI_BOOT_TGT_CHAP_NAME:
str += sprintf_string(str, tgt->chap_name_len,
(char *)ibft_loc + tgt->chap_name_off);
break;
case ISCSI_BOOT_TGT_CHAP_SECRET:
str += sprintf_string(str, tgt->chap_secret_len,
(char *)ibft_loc + tgt->chap_secret_off);
break;
case ISCSI_BOOT_TGT_REV_CHAP_NAME:
str += sprintf_string(str, tgt->rev_chap_name_len,
(char *)ibft_loc +
tgt->rev_chap_name_off);
break;
case ISCSI_BOOT_TGT_REV_CHAP_SECRET:
str += sprintf_string(str, tgt->rev_chap_secret_len,
(char *)ibft_loc +
tgt->rev_chap_secret_off);
break;
default:
break;
}
return str - buf;
}
static int __init ibft_check_device(void)
{
int len;
u8 *pos;
u8 csum = 0;
len = ibft_addr->header.length;
/* Sanity checking of iBFT. */
if (ibft_addr->header.revision != 1) {
printk(KERN_ERR "iBFT module supports only revision 1, " \
"while this is %d.\n",
ibft_addr->header.revision);
return -ENOENT;
}
for (pos = (u8 *)ibft_addr; pos < (u8 *)ibft_addr + len; pos++)
csum += *pos;
if (csum) {
printk(KERN_ERR "iBFT has incorrect checksum (0x%x)!\n", csum);
return -ENOENT;
}
return 0;
}
/*
* Helper routiners to check to determine if the entry is valid
* in the proper iBFT structure.
*/
static umode_t ibft_check_nic_for(void *data, int type)
{
struct ibft_kobject *entry = data;
struct ibft_nic *nic = entry->nic;
umode_t rc = 0;
switch (type) {
case ISCSI_BOOT_ETH_INDEX:
case ISCSI_BOOT_ETH_FLAGS:
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_IP_ADDR:
if (memcmp(nic->ip_addr, nulls, sizeof(nic->ip_addr)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_SUBNET_MASK:
if (nic->subnet_mask_prefix)
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_ORIGIN:
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_GATEWAY:
if (memcmp(nic->gateway, nulls, sizeof(nic->gateway)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_PRIMARY_DNS:
if (memcmp(nic->primary_dns, nulls,
sizeof(nic->primary_dns)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_SECONDARY_DNS:
if (memcmp(nic->secondary_dns, nulls,
sizeof(nic->secondary_dns)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_DHCP:
if (memcmp(nic->dhcp, nulls, sizeof(nic->dhcp)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_VLAN:
case ISCSI_BOOT_ETH_MAC:
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_HOSTNAME:
if (nic->hostname_off)
rc = S_IRUGO;
break;
default:
break;
}
return rc;
}
static umode_t __init ibft_check_tgt_for(void *data, int type)
{
struct ibft_kobject *entry = data;
struct ibft_tgt *tgt = entry->tgt;
umode_t rc = 0;
switch (type) {
case ISCSI_BOOT_TGT_INDEX:
case ISCSI_BOOT_TGT_FLAGS:
case ISCSI_BOOT_TGT_IP_ADDR:
case ISCSI_BOOT_TGT_PORT:
case ISCSI_BOOT_TGT_LUN:
case ISCSI_BOOT_TGT_NIC_ASSOC:
case ISCSI_BOOT_TGT_CHAP_TYPE:
rc = S_IRUGO;
case ISCSI_BOOT_TGT_NAME:
if (tgt->tgt_name_len)
rc = S_IRUGO;
break;
case ISCSI_BOOT_TGT_CHAP_NAME:
case ISCSI_BOOT_TGT_CHAP_SECRET:
if (tgt->chap_name_len)
rc = S_IRUGO;
break;
case ISCSI_BOOT_TGT_REV_CHAP_NAME:
case ISCSI_BOOT_TGT_REV_CHAP_SECRET:
if (tgt->rev_chap_name_len)
rc = S_IRUGO;
break;
default:
break;
}
return rc;
}
static umode_t __init ibft_check_initiator_for(void *data, int type)
{
struct ibft_kobject *entry = data;
struct ibft_initiator *init = entry->initiator;
umode_t rc = 0;
switch (type) {
case ISCSI_BOOT_INI_INDEX:
case ISCSI_BOOT_INI_FLAGS:
rc = S_IRUGO;
break;
case ISCSI_BOOT_INI_ISNS_SERVER:
if (memcmp(init->isns_server, nulls,
sizeof(init->isns_server)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_INI_SLP_SERVER:
if (memcmp(init->slp_server, nulls,
sizeof(init->slp_server)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_INI_PRI_RADIUS_SERVER:
if (memcmp(init->pri_radius_server, nulls,
sizeof(init->pri_radius_server)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_INI_SEC_RADIUS_SERVER:
if (memcmp(init->sec_radius_server, nulls,
sizeof(init->sec_radius_server)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_INI_INITIATOR_NAME:
if (init->initiator_name_len)
rc = S_IRUGO;
break;
default:
break;
}
return rc;
}
static void ibft_kobj_release(void *data)
{
kfree(data);
}
/*
* Helper function for ibft_register_kobjects.
*/
static int __init ibft_create_kobject(struct acpi_table_ibft *header,
struct ibft_hdr *hdr)
{
struct iscsi_boot_kobj *boot_kobj = NULL;
struct ibft_kobject *ibft_kobj = NULL;
struct ibft_nic *nic = (struct ibft_nic *)hdr;
struct pci_dev *pci_dev;
int rc = 0;
ibft_kobj = kzalloc(sizeof(*ibft_kobj), GFP_KERNEL);
if (!ibft_kobj)
return -ENOMEM;
ibft_kobj->header = header;
ibft_kobj->hdr = hdr;
switch (hdr->id) {
case id_initiator:
rc = ibft_verify_hdr("initiator", hdr, id_initiator,
sizeof(*ibft_kobj->initiator));
if (rc)
break;
boot_kobj = iscsi_boot_create_initiator(boot_kset, hdr->index,
ibft_kobj,
ibft_attr_show_initiator,
ibft_check_initiator_for,
ibft_kobj_release);
if (!boot_kobj) {
rc = -ENOMEM;
goto free_ibft_obj;
}
break;
case id_nic:
rc = ibft_verify_hdr("ethernet", hdr, id_nic,
sizeof(*ibft_kobj->nic));
if (rc)
break;
boot_kobj = iscsi_boot_create_ethernet(boot_kset, hdr->index,
ibft_kobj,
ibft_attr_show_nic,
ibft_check_nic_for,
ibft_kobj_release);
if (!boot_kobj) {
rc = -ENOMEM;
goto free_ibft_obj;
}
break;
case id_target:
rc = ibft_verify_hdr("target", hdr, id_target,
sizeof(*ibft_kobj->tgt));
if (rc)
break;
boot_kobj = iscsi_boot_create_target(boot_kset, hdr->index,
ibft_kobj,
ibft_attr_show_target,
ibft_check_tgt_for,
ibft_kobj_release);
if (!boot_kobj) {
rc = -ENOMEM;
goto free_ibft_obj;
}
break;
case id_reserved:
case id_control:
case id_extensions:
/* Fields which we don't support. Ignore them */
rc = 1;
break;
default:
printk(KERN_ERR "iBFT has unknown structure type (%d). " \
"Report this bug to %.6s!\n", hdr->id,
header->header.oem_id);
rc = 1;
break;
}
if (rc) {
/* Skip adding this kobject, but exit with non-fatal error. */
rc = 0;
goto free_ibft_obj;
}
if (hdr->id == id_nic) {
/*
* We don't search for the device in other domains than
* zero. This is because on x86 platforms the BIOS
* executes only devices which are in domain 0. Furthermore, the
* iBFT spec doesn't have a domain id field :-(
*/
pci_dev = pci_get_bus_and_slot((nic->pci_bdf & 0xff00) >> 8,
(nic->pci_bdf & 0xff));
if (pci_dev) {
rc = sysfs_create_link(&boot_kobj->kobj,
&pci_dev->dev.kobj, "device");
pci_dev_put(pci_dev);
}
}
return 0;
free_ibft_obj:
kfree(ibft_kobj);
return rc;
}
/*
* Scan the IBFT table structure for the NIC and Target fields. When
* found add them on the passed-in list. We do not support the other
* fields at this point, so they are skipped.
*/
static int __init ibft_register_kobjects(struct acpi_table_ibft *header)
{
struct ibft_control *control = NULL;
void *ptr, *end;
int rc = 0;
u16 offset;
u16 eot_offset;
control = (void *)header + sizeof(*header);
end = (void *)control + control->hdr.length;
eot_offset = (void *)header + header->header.length - (void *)control;
rc = ibft_verify_hdr("control", (struct ibft_hdr *)control, id_control,
sizeof(*control));
/* iBFT table safety checking */
rc |= ((control->hdr.index) ? -ENODEV : 0);
if (rc) {
printk(KERN_ERR "iBFT error: Control header is invalid!\n");
return rc;
}
for (ptr = &control->initiator_off; ptr < end; ptr += sizeof(u16)) {
offset = *(u16 *)ptr;
if (offset && offset < header->header.length &&
offset < eot_offset) {
rc = ibft_create_kobject(header,
(void *)header + offset);
if (rc)
break;
}
}
return rc;
}
static void ibft_unregister(void)
{
struct iscsi_boot_kobj *boot_kobj, *tmp_kobj;
struct ibft_kobject *ibft_kobj;
list_for_each_entry_safe(boot_kobj, tmp_kobj,
&boot_kset->kobj_list, list) {
ibft_kobj = boot_kobj->data;
if (ibft_kobj->hdr->id == id_nic)
sysfs_remove_link(&boot_kobj->kobj, "device");
};
}
static void ibft_cleanup(void)
{
if (boot_kset) {
ibft_unregister();
iscsi_boot_destroy_kset(boot_kset);
}
}
static void __exit ibft_exit(void)
{
ibft_cleanup();
}
#ifdef CONFIG_ACPI
static const struct {
char *sign;
} ibft_signs[] = {
/*
* One spec says "IBFT", the other says "iBFT". We have to check
* for both.
*/
{ ACPI_SIG_IBFT },
{ "iBFT" },
{ "BIFT" }, /* Broadcom iSCSI Offload */
};
static void __init acpi_find_ibft_region(void)
{
int i;
struct acpi_table_header *table = NULL;
if (acpi_disabled)
return;
for (i = 0; i < ARRAY_SIZE(ibft_signs) && !ibft_addr; i++) {
acpi_get_table(ibft_signs[i].sign, 0, &table);
ibft_addr = (struct acpi_table_ibft *)table;
}
}
#else
static void __init acpi_find_ibft_region(void)
{
}
#endif
/*
* ibft_init() - creates sysfs tree entries for the iBFT data.
*/
static int __init ibft_init(void)
{
int rc = 0;
/*
As on UEFI systems the setup_arch()/find_ibft_region()
is called before ACPI tables are parsed and it only does
legacy finding.
*/
if (!ibft_addr)
acpi_find_ibft_region();
if (ibft_addr) {
pr_info("iBFT detected.\n");
rc = ibft_check_device();
if (rc)
return rc;
boot_kset = iscsi_boot_create_kset("ibft");
if (!boot_kset)
return -ENOMEM;
/* Scan the IBFT for data and register the kobjects. */
rc = ibft_register_kobjects(ibft_addr);
if (rc)
goto out_free;
} else
printk(KERN_INFO "No iBFT detected.\n");
return 0;
out_free:
ibft_cleanup();
return rc;
}
module_init(ibft_init);
module_exit(ibft_exit);
| gpl-2.0 |
HTC-MSM8916/android_kernel_htc_msm8916 | net/phonet/pn_dev.c | 2049 | 10103 | /*
* File: pn_dev.c
*
* Phonet network device
*
* Copyright (C) 2008 Nokia Corporation.
*
* Authors: Sakari Ailus <sakari.ailus@nokia.com>
* Rémi Denis-Courmont
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/kernel.h>
#include <linux/net.h>
#include <linux/slab.h>
#include <linux/netdevice.h>
#include <linux/phonet.h>
#include <linux/proc_fs.h>
#include <linux/if_arp.h>
#include <net/sock.h>
#include <net/netns/generic.h>
#include <net/phonet/pn_dev.h>
struct phonet_routes {
struct mutex lock;
struct net_device *table[64];
};
struct phonet_net {
struct phonet_device_list pndevs;
struct phonet_routes routes;
};
static int phonet_net_id __read_mostly;
static struct phonet_net *phonet_pernet(struct net *net)
{
BUG_ON(!net);
return net_generic(net, phonet_net_id);
}
struct phonet_device_list *phonet_device_list(struct net *net)
{
struct phonet_net *pnn = phonet_pernet(net);
return &pnn->pndevs;
}
/* Allocate new Phonet device. */
static struct phonet_device *__phonet_device_alloc(struct net_device *dev)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd = kmalloc(sizeof(*pnd), GFP_ATOMIC);
if (pnd == NULL)
return NULL;
pnd->netdev = dev;
bitmap_zero(pnd->addrs, 64);
BUG_ON(!mutex_is_locked(&pndevs->lock));
list_add_rcu(&pnd->list, &pndevs->list);
return pnd;
}
static struct phonet_device *__phonet_get(struct net_device *dev)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd;
BUG_ON(!mutex_is_locked(&pndevs->lock));
list_for_each_entry(pnd, &pndevs->list, list) {
if (pnd->netdev == dev)
return pnd;
}
return NULL;
}
static struct phonet_device *__phonet_get_rcu(struct net_device *dev)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd;
list_for_each_entry_rcu(pnd, &pndevs->list, list) {
if (pnd->netdev == dev)
return pnd;
}
return NULL;
}
static void phonet_device_destroy(struct net_device *dev)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd;
ASSERT_RTNL();
mutex_lock(&pndevs->lock);
pnd = __phonet_get(dev);
if (pnd)
list_del_rcu(&pnd->list);
mutex_unlock(&pndevs->lock);
if (pnd) {
u8 addr;
for_each_set_bit(addr, pnd->addrs, 64)
phonet_address_notify(RTM_DELADDR, dev, addr);
kfree(pnd);
}
}
struct net_device *phonet_device_get(struct net *net)
{
struct phonet_device_list *pndevs = phonet_device_list(net);
struct phonet_device *pnd;
struct net_device *dev = NULL;
rcu_read_lock();
list_for_each_entry_rcu(pnd, &pndevs->list, list) {
dev = pnd->netdev;
BUG_ON(!dev);
if ((dev->reg_state == NETREG_REGISTERED) &&
((pnd->netdev->flags & IFF_UP)) == IFF_UP)
break;
dev = NULL;
}
if (dev)
dev_hold(dev);
rcu_read_unlock();
return dev;
}
int phonet_address_add(struct net_device *dev, u8 addr)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd;
int err = 0;
mutex_lock(&pndevs->lock);
/* Find or create Phonet-specific device data */
pnd = __phonet_get(dev);
if (pnd == NULL)
pnd = __phonet_device_alloc(dev);
if (unlikely(pnd == NULL))
err = -ENOMEM;
else if (test_and_set_bit(addr >> 2, pnd->addrs))
err = -EEXIST;
mutex_unlock(&pndevs->lock);
return err;
}
int phonet_address_del(struct net_device *dev, u8 addr)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd;
int err = 0;
mutex_lock(&pndevs->lock);
pnd = __phonet_get(dev);
if (!pnd || !test_and_clear_bit(addr >> 2, pnd->addrs)) {
err = -EADDRNOTAVAIL;
pnd = NULL;
} else if (bitmap_empty(pnd->addrs, 64))
list_del_rcu(&pnd->list);
else
pnd = NULL;
mutex_unlock(&pndevs->lock);
if (pnd)
kfree_rcu(pnd, rcu);
return err;
}
/* Gets a source address toward a destination, through a interface. */
u8 phonet_address_get(struct net_device *dev, u8 daddr)
{
struct phonet_device *pnd;
u8 saddr;
rcu_read_lock();
pnd = __phonet_get_rcu(dev);
if (pnd) {
BUG_ON(bitmap_empty(pnd->addrs, 64));
/* Use same source address as destination, if possible */
if (test_bit(daddr >> 2, pnd->addrs))
saddr = daddr;
else
saddr = find_first_bit(pnd->addrs, 64) << 2;
} else
saddr = PN_NO_ADDR;
rcu_read_unlock();
if (saddr == PN_NO_ADDR) {
/* Fallback to another device */
struct net_device *def_dev;
def_dev = phonet_device_get(dev_net(dev));
if (def_dev) {
if (def_dev != dev)
saddr = phonet_address_get(def_dev, daddr);
dev_put(def_dev);
}
}
return saddr;
}
int phonet_address_lookup(struct net *net, u8 addr)
{
struct phonet_device_list *pndevs = phonet_device_list(net);
struct phonet_device *pnd;
int err = -EADDRNOTAVAIL;
rcu_read_lock();
list_for_each_entry_rcu(pnd, &pndevs->list, list) {
/* Don't allow unregistering devices! */
if ((pnd->netdev->reg_state != NETREG_REGISTERED) ||
((pnd->netdev->flags & IFF_UP)) != IFF_UP)
continue;
if (test_bit(addr >> 2, pnd->addrs)) {
err = 0;
goto found;
}
}
found:
rcu_read_unlock();
return err;
}
/* automatically configure a Phonet device, if supported */
static int phonet_device_autoconf(struct net_device *dev)
{
struct if_phonet_req req;
int ret;
if (!dev->netdev_ops->ndo_do_ioctl)
return -EOPNOTSUPP;
ret = dev->netdev_ops->ndo_do_ioctl(dev, (struct ifreq *)&req,
SIOCPNGAUTOCONF);
if (ret < 0)
return ret;
ASSERT_RTNL();
ret = phonet_address_add(dev, req.ifr_phonet_autoconf.device);
if (ret)
return ret;
phonet_address_notify(RTM_NEWADDR, dev,
req.ifr_phonet_autoconf.device);
return 0;
}
static void phonet_route_autodel(struct net_device *dev)
{
struct phonet_net *pnn = phonet_pernet(dev_net(dev));
unsigned int i;
DECLARE_BITMAP(deleted, 64);
/* Remove left-over Phonet routes */
bitmap_zero(deleted, 64);
mutex_lock(&pnn->routes.lock);
for (i = 0; i < 64; i++)
if (dev == pnn->routes.table[i]) {
RCU_INIT_POINTER(pnn->routes.table[i], NULL);
set_bit(i, deleted);
}
mutex_unlock(&pnn->routes.lock);
if (bitmap_empty(deleted, 64))
return; /* short-circuit RCU */
synchronize_rcu();
for_each_set_bit(i, deleted, 64) {
rtm_phonet_notify(RTM_DELROUTE, dev, i);
dev_put(dev);
}
}
/* notify Phonet of device events */
static int phonet_device_notify(struct notifier_block *me, unsigned long what,
void *arg)
{
struct net_device *dev = arg;
switch (what) {
case NETDEV_REGISTER:
if (dev->type == ARPHRD_PHONET)
phonet_device_autoconf(dev);
break;
case NETDEV_UNREGISTER:
phonet_device_destroy(dev);
phonet_route_autodel(dev);
break;
}
return 0;
}
static struct notifier_block phonet_device_notifier = {
.notifier_call = phonet_device_notify,
.priority = 0,
};
/* Per-namespace Phonet devices handling */
static int __net_init phonet_init_net(struct net *net)
{
struct phonet_net *pnn = phonet_pernet(net);
if (!proc_create("phonet", 0, net->proc_net, &pn_sock_seq_fops))
return -ENOMEM;
INIT_LIST_HEAD(&pnn->pndevs.list);
mutex_init(&pnn->pndevs.lock);
mutex_init(&pnn->routes.lock);
return 0;
}
static void __net_exit phonet_exit_net(struct net *net)
{
remove_proc_entry("phonet", net->proc_net);
}
static struct pernet_operations phonet_net_ops = {
.init = phonet_init_net,
.exit = phonet_exit_net,
.id = &phonet_net_id,
.size = sizeof(struct phonet_net),
};
/* Initialize Phonet devices list */
int __init phonet_device_init(void)
{
int err = register_pernet_subsys(&phonet_net_ops);
if (err)
return err;
proc_create("pnresource", 0, init_net.proc_net, &pn_res_seq_fops);
register_netdevice_notifier(&phonet_device_notifier);
err = phonet_netlink_register();
if (err)
phonet_device_exit();
return err;
}
void phonet_device_exit(void)
{
rtnl_unregister_all(PF_PHONET);
unregister_netdevice_notifier(&phonet_device_notifier);
unregister_pernet_subsys(&phonet_net_ops);
remove_proc_entry("pnresource", init_net.proc_net);
}
int phonet_route_add(struct net_device *dev, u8 daddr)
{
struct phonet_net *pnn = phonet_pernet(dev_net(dev));
struct phonet_routes *routes = &pnn->routes;
int err = -EEXIST;
daddr = daddr >> 2;
mutex_lock(&routes->lock);
if (routes->table[daddr] == NULL) {
rcu_assign_pointer(routes->table[daddr], dev);
dev_hold(dev);
err = 0;
}
mutex_unlock(&routes->lock);
return err;
}
int phonet_route_del(struct net_device *dev, u8 daddr)
{
struct phonet_net *pnn = phonet_pernet(dev_net(dev));
struct phonet_routes *routes = &pnn->routes;
daddr = daddr >> 2;
mutex_lock(&routes->lock);
if (dev == routes->table[daddr])
RCU_INIT_POINTER(routes->table[daddr], NULL);
else
dev = NULL;
mutex_unlock(&routes->lock);
if (!dev)
return -ENOENT;
synchronize_rcu();
dev_put(dev);
return 0;
}
struct net_device *phonet_route_get_rcu(struct net *net, u8 daddr)
{
struct phonet_net *pnn = phonet_pernet(net);
struct phonet_routes *routes = &pnn->routes;
struct net_device *dev;
daddr >>= 2;
dev = rcu_dereference(routes->table[daddr]);
return dev;
}
struct net_device *phonet_route_output(struct net *net, u8 daddr)
{
struct phonet_net *pnn = phonet_pernet(net);
struct phonet_routes *routes = &pnn->routes;
struct net_device *dev;
daddr >>= 2;
rcu_read_lock();
dev = rcu_dereference(routes->table[daddr]);
if (dev)
dev_hold(dev);
rcu_read_unlock();
if (!dev)
dev = phonet_device_get(net); /* Default route */
return dev;
}
| gpl-2.0 |
skybosi/linux | drivers/ata/pata_cypress.c | 2049 | 4364 | /*
* pata_cypress.c - Cypress PATA for new ATA layer
* (C) 2006 Red Hat Inc
* Alan Cox
*
* Based heavily on
* linux/drivers/ide/pci/cy82c693.c Version 0.40 Sep. 10, 2002
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_cypress"
#define DRV_VERSION "0.1.5"
/* here are the offset definitions for the registers */
enum {
CY82_IDE_CMDREG = 0x04,
CY82_IDE_ADDRSETUP = 0x48,
CY82_IDE_MASTER_IOR = 0x4C,
CY82_IDE_MASTER_IOW = 0x4D,
CY82_IDE_SLAVE_IOR = 0x4E,
CY82_IDE_SLAVE_IOW = 0x4F,
CY82_IDE_MASTER_8BIT = 0x50,
CY82_IDE_SLAVE_8BIT = 0x51,
CY82_INDEX_PORT = 0x22,
CY82_DATA_PORT = 0x23,
CY82_INDEX_CTRLREG1 = 0x01,
CY82_INDEX_CHANNEL0 = 0x30,
CY82_INDEX_CHANNEL1 = 0x31,
CY82_INDEX_TIMEOUT = 0x32
};
/**
* cy82c693_set_piomode - set initial PIO mode data
* @ap: ATA interface
* @adev: ATA device
*
* Called to do the PIO mode setup.
*/
static void cy82c693_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
struct ata_timing t;
const unsigned long T = 1000000 / 33;
short time_16, time_8;
u32 addr;
if (ata_timing_compute(adev, adev->pio_mode, &t, T, 1) < 0) {
printk(KERN_ERR DRV_NAME ": mome computation failed.\n");
return;
}
time_16 = clamp_val(t.recover - 1, 0, 15) |
(clamp_val(t.active - 1, 0, 15) << 4);
time_8 = clamp_val(t.act8b - 1, 0, 15) |
(clamp_val(t.rec8b - 1, 0, 15) << 4);
if (adev->devno == 0) {
pci_read_config_dword(pdev, CY82_IDE_ADDRSETUP, &addr);
addr &= ~0x0F; /* Mask bits */
addr |= clamp_val(t.setup - 1, 0, 15);
pci_write_config_dword(pdev, CY82_IDE_ADDRSETUP, addr);
pci_write_config_byte(pdev, CY82_IDE_MASTER_IOR, time_16);
pci_write_config_byte(pdev, CY82_IDE_MASTER_IOW, time_16);
pci_write_config_byte(pdev, CY82_IDE_MASTER_8BIT, time_8);
} else {
pci_read_config_dword(pdev, CY82_IDE_ADDRSETUP, &addr);
addr &= ~0xF0; /* Mask bits */
addr |= (clamp_val(t.setup - 1, 0, 15) << 4);
pci_write_config_dword(pdev, CY82_IDE_ADDRSETUP, addr);
pci_write_config_byte(pdev, CY82_IDE_SLAVE_IOR, time_16);
pci_write_config_byte(pdev, CY82_IDE_SLAVE_IOW, time_16);
pci_write_config_byte(pdev, CY82_IDE_SLAVE_8BIT, time_8);
}
}
/**
* cy82c693_set_dmamode - set initial DMA mode data
* @ap: ATA interface
* @adev: ATA device
*
* Called to do the DMA mode setup.
*/
static void cy82c693_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
int reg = CY82_INDEX_CHANNEL0 + ap->port_no;
/* Be afraid, be very afraid. Magic registers in low I/O space */
outb(reg, 0x22);
outb(adev->dma_mode - XFER_MW_DMA_0, 0x23);
/* 0x50 gives the best behaviour on the Alpha's using this chip */
outb(CY82_INDEX_TIMEOUT, 0x22);
outb(0x50, 0x23);
}
static struct scsi_host_template cy82c693_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations cy82c693_port_ops = {
.inherits = &ata_bmdma_port_ops,
.cable_detect = ata_cable_40wire,
.set_piomode = cy82c693_set_piomode,
.set_dmamode = cy82c693_set_dmamode,
};
static int cy82c693_init_one(struct pci_dev *pdev, const struct pci_device_id *id)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.port_ops = &cy82c693_port_ops
};
const struct ata_port_info *ppi[] = { &info, &ata_dummy_port_info };
/* Devfn 1 is the ATA primary. The secondary is magic and on devfn2.
For the moment we don't handle the secondary. FIXME */
if (PCI_FUNC(pdev->devfn) != 1)
return -ENODEV;
return ata_pci_bmdma_init_one(pdev, ppi, &cy82c693_sht, NULL, 0);
}
static const struct pci_device_id cy82c693[] = {
{ PCI_VDEVICE(CONTAQ, PCI_DEVICE_ID_CONTAQ_82C693), },
{ },
};
static struct pci_driver cy82c693_pci_driver = {
.name = DRV_NAME,
.id_table = cy82c693,
.probe = cy82c693_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM_SLEEP
.suspend = ata_pci_device_suspend,
.resume = ata_pci_device_resume,
#endif
};
module_pci_driver(cy82c693_pci_driver);
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for the CY82C693 PATA controller");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, cy82c693);
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.