repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
vslavik/poedit | deps/boost/libs/ratio/test/typedefs_pass.cpp | 53 | 1991 | // Copyright 2010 Vicente J. Botet Escriba
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
// test ratio typedef's
#include <boost/ratio/ratio.hpp>
#if !defined(BOOST_NO_CXX11_STATIC_ASSERT)
#define NOTHING ""
#endif
BOOST_RATIO_STATIC_ASSERT(boost::atto::num == 1 && boost::atto::den == 1000000000000000000ULL, NOTHING, (boost::mpl::integral_c<boost::intmax_t,boost::atto::den>));
BOOST_RATIO_STATIC_ASSERT(boost::femto::num == 1 && boost::femto::den == 1000000000000000ULL, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::pico::num == 1 && boost::pico::den == 1000000000000ULL, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::nano::num == 1 && boost::nano::den == 1000000000ULL, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::micro::num == 1 && boost::micro::den == 1000000ULL, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::milli::num == 1 && boost::milli::den == 1000ULL, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::centi::num == 1 && boost::centi::den == 100ULL, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::deci::num == 1 && boost::deci::den == 10ULL, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::deca::num == 10ULL && boost::deca::den == 1, NOTHING, (boost::mpl::integral_c<boost::intmax_t,boost::deca::den>));
BOOST_RATIO_STATIC_ASSERT(boost::hecto::num == 100ULL && boost::hecto::den == 1, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::kilo::num == 1000ULL && boost::kilo::den == 1, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::mega::num == 1000000ULL && boost::mega::den == 1, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::giga::num == 1000000000ULL && boost::giga::den == 1, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::tera::num == 1000000000000ULL && boost::tera::den == 1, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::peta::num == 1000000000000000ULL && boost::peta::den == 1, NOTHING, ());
BOOST_RATIO_STATIC_ASSERT(boost::exa::num == 1000000000000000000ULL && boost::exa::den == 1, NOTHING, ());
| mit |
vslavik/poedit | deps/boost/libs/wave/test/testwave/testfiles/t_6_015.cpp | 55 | 2390 | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2012 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
The tests included in this file were initially taken from the mcpp V2.5
preprocessor validation suite and were modified to fit into the Boost.Wave
unit test requirements.
The original files of the mcpp preprocessor are distributed under the
license reproduced at the end of this file.
=============================================================================*/
// Tests error reporting: overflow of constant expression in #if directive.
// 14.10:
//E t_6_015.cpp(20): error: integer overflow in preprocessor expression: $E(__TESTWAVE_LONG_MAX__) - $E(__TESTWAVE_LONG_MIN__)
#if __TESTWAVE_LONG_MAX__ - __TESTWAVE_LONG_MIN__
#endif
/*-
* Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <kmatsui@t3.rim.or.jp>
* 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 THE AUTHOR ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
| mit |
redxdev/Wake-old | Dependencies/luajit/host/buildvm_asm.c | 55 | 8263 | /*
** LuaJIT VM builder: Assembler source code emitter.
** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
*/
#include "buildvm.h"
#include "lj_bc.h"
/* ------------------------------------------------------------------------ */
#if LJ_TARGET_X86ORX64
/* Emit bytes piecewise as assembler text. */
static void emit_asm_bytes(BuildCtx *ctx, uint8_t *p, int n)
{
int i;
for (i = 0; i < n; i++) {
if ((i & 15) == 0)
fprintf(ctx->fp, "\t.byte %d", p[i]);
else
fprintf(ctx->fp, ",%d", p[i]);
if ((i & 15) == 15) putc('\n', ctx->fp);
}
if ((n & 15) != 0) putc('\n', ctx->fp);
}
/* Emit relocation */
static void emit_asm_reloc(BuildCtx *ctx, int type, const char *sym)
{
switch (ctx->mode) {
case BUILD_elfasm:
if (type)
fprintf(ctx->fp, "\t.long %s-.-4\n", sym);
else
fprintf(ctx->fp, "\t.long %s\n", sym);
break;
case BUILD_coffasm:
fprintf(ctx->fp, "\t.def %s; .scl 3; .type 32; .endef\n", sym);
if (type)
fprintf(ctx->fp, "\t.long %s-.-4\n", sym);
else
fprintf(ctx->fp, "\t.long %s\n", sym);
break;
default: /* BUILD_machasm for relative relocations handled below. */
fprintf(ctx->fp, "\t.long %s\n", sym);
break;
}
}
static const char *const jccnames[] = {
"jo", "jno", "jb", "jnb", "jz", "jnz", "jbe", "ja",
"js", "jns", "jpe", "jpo", "jl", "jge", "jle", "jg"
};
/* Emit relocation for the incredibly stupid OSX assembler. */
static void emit_asm_reloc_mach(BuildCtx *ctx, uint8_t *cp, int n,
const char *sym)
{
const char *opname = NULL;
if (--n < 0) goto err;
if (cp[n] == 0xe8) {
opname = "call";
} else if (cp[n] == 0xe9) {
opname = "jmp";
} else if (cp[n] >= 0x80 && cp[n] <= 0x8f && n > 0 && cp[n-1] == 0x0f) {
opname = jccnames[cp[n]-0x80];
n--;
} else {
err:
fprintf(stderr, "Error: unsupported opcode for %s symbol relocation.\n",
sym);
exit(1);
}
emit_asm_bytes(ctx, cp, n);
fprintf(ctx->fp, "\t%s %s\n", opname, sym);
}
#else
/* Emit words piecewise as assembler text. */
static void emit_asm_words(BuildCtx *ctx, uint8_t *p, int n)
{
int i;
for (i = 0; i < n; i += 4) {
if ((i & 15) == 0)
fprintf(ctx->fp, "\t.long 0x%08x", *(uint32_t *)(p+i));
else
fprintf(ctx->fp, ",0x%08x", *(uint32_t *)(p+i));
if ((i & 15) == 12) putc('\n', ctx->fp);
}
if ((n & 15) != 0) putc('\n', ctx->fp);
}
/* Emit relocation as part of an instruction. */
static void emit_asm_wordreloc(BuildCtx *ctx, uint8_t *p, int n,
const char *sym)
{
uint32_t ins;
emit_asm_words(ctx, p, n-4);
ins = *(uint32_t *)(p+n-4);
#if LJ_TARGET_ARM
if ((ins & 0xff000000u) == 0xfa000000u) {
fprintf(ctx->fp, "\tblx %s\n", sym);
} else if ((ins & 0x0e000000u) == 0x0a000000u) {
fprintf(ctx->fp, "\t%s%.2s %s\n", (ins & 0x01000000u) ? "bl" : "b",
&"eqnecsccmiplvsvchilsgeltgtle"[2*(ins >> 28)], sym);
} else {
fprintf(stderr,
"Error: unsupported opcode %08x for %s symbol relocation.\n",
ins, sym);
exit(1);
}
#elif LJ_TARGET_PPC || LJ_TARGET_PPCSPE
#if LJ_TARGET_PS3
#define TOCPREFIX "."
#else
#define TOCPREFIX ""
#endif
if ((ins >> 26) == 16) {
fprintf(ctx->fp, "\t%s %d, %d, " TOCPREFIX "%s\n",
(ins & 1) ? "bcl" : "bc", (ins >> 21) & 31, (ins >> 16) & 31, sym);
} else if ((ins >> 26) == 18) {
fprintf(ctx->fp, "\t%s " TOCPREFIX "%s\n", (ins & 1) ? "bl" : "b", sym);
} else {
fprintf(stderr,
"Error: unsupported opcode %08x for %s symbol relocation.\n",
ins, sym);
exit(1);
}
#elif LJ_TARGET_MIPS
fprintf(stderr,
"Error: unsupported opcode %08x for %s symbol relocation.\n",
ins, sym);
exit(1);
#else
#error "missing relocation support for this architecture"
#endif
}
#endif
#if LJ_TARGET_ARM
#define ELFASM_PX "%%"
#else
#define ELFASM_PX "@"
#endif
/* Emit an assembler label. */
static void emit_asm_label(BuildCtx *ctx, const char *name, int size, int isfunc)
{
switch (ctx->mode) {
case BUILD_elfasm:
#if LJ_TARGET_PS3
if (!strncmp(name, "lj_vm_", 6) &&
strcmp(name, ctx->beginsym) &&
!strstr(name, "hook")) {
fprintf(ctx->fp,
"\n\t.globl %s\n"
"\t.section \".opd\",\"aw\"\n"
"%s:\n"
"\t.long .%s,.TOC.@tocbase32\n"
"\t.size %s,8\n"
"\t.previous\n"
"\t.globl .%s\n"
"\t.hidden .%s\n"
"\t.type .%s, " ELFASM_PX "function\n"
"\t.size .%s, %d\n"
".%s:\n",
name, name, name, name, name, name, name, name, size, name);
break;
}
#endif
fprintf(ctx->fp,
"\n\t.globl %s\n"
"\t.hidden %s\n"
"\t.type %s, " ELFASM_PX "%s\n"
"\t.size %s, %d\n"
"%s:\n",
name, name, name, isfunc ? "function" : "object", name, size, name);
break;
case BUILD_coffasm:
fprintf(ctx->fp, "\n\t.globl %s\n", name);
if (isfunc)
fprintf(ctx->fp, "\t.def %s; .scl 3; .type 32; .endef\n", name);
fprintf(ctx->fp, "%s:\n", name);
break;
case BUILD_machasm:
fprintf(ctx->fp,
"\n\t.private_extern %s\n"
"%s:\n", name, name);
break;
default:
break;
}
}
/* Emit alignment. */
static void emit_asm_align(BuildCtx *ctx, int bits)
{
switch (ctx->mode) {
case BUILD_elfasm:
case BUILD_coffasm:
fprintf(ctx->fp, "\t.p2align %d\n", bits);
break;
case BUILD_machasm:
fprintf(ctx->fp, "\t.align %d\n", bits);
break;
default:
break;
}
}
/* ------------------------------------------------------------------------ */
/* Emit assembler source code. */
void emit_asm(BuildCtx *ctx)
{
int i, rel;
fprintf(ctx->fp, "\t.file \"buildvm_%s.dasc\"\n", ctx->dasm_arch);
fprintf(ctx->fp, "\t.text\n");
emit_asm_align(ctx, 4);
#if LJ_TARGET_PS3
emit_asm_label(ctx, ctx->beginsym, ctx->codesz, 0);
#else
emit_asm_label(ctx, ctx->beginsym, 0, 0);
#endif
if (ctx->mode != BUILD_machasm)
fprintf(ctx->fp, ".Lbegin:\n");
#if LJ_TARGET_ARM && defined(__GNUC__) && !LJ_NO_UNWIND
/* This should really be moved into buildvm_arm.dasc. */
fprintf(ctx->fp,
".fnstart\n"
".save {r4, r5, r6, r7, r8, r9, r10, r11, lr}\n"
".pad #28\n");
#endif
#if LJ_TARGET_MIPS
fprintf(ctx->fp, ".set nomips16\n.abicalls\n.set noreorder\n.set nomacro\n");
#endif
for (i = rel = 0; i < ctx->nsym; i++) {
int32_t ofs = ctx->sym[i].ofs;
int32_t next = ctx->sym[i+1].ofs;
#if LJ_TARGET_ARM && defined(__GNUC__) && !LJ_NO_UNWIND && LJ_HASFFI
if (!strcmp(ctx->sym[i].name, "lj_vm_ffi_call"))
fprintf(ctx->fp,
".globl lj_err_unwind_arm\n"
".personality lj_err_unwind_arm\n"
".fnend\n"
".fnstart\n"
".save {r4, r5, r11, lr}\n"
".setfp r11, sp\n");
#endif
emit_asm_label(ctx, ctx->sym[i].name, next - ofs, 1);
while (rel < ctx->nreloc && ctx->reloc[rel].ofs <= next) {
BuildReloc *r = &ctx->reloc[rel];
int n = r->ofs - ofs;
#if LJ_TARGET_X86ORX64
if (ctx->mode == BUILD_machasm && r->type != 0) {
emit_asm_reloc_mach(ctx, ctx->code+ofs, n, ctx->relocsym[r->sym]);
} else {
emit_asm_bytes(ctx, ctx->code+ofs, n);
emit_asm_reloc(ctx, r->type, ctx->relocsym[r->sym]);
}
ofs += n+4;
#else
emit_asm_wordreloc(ctx, ctx->code+ofs, n, ctx->relocsym[r->sym]);
ofs += n;
#endif
rel++;
}
#if LJ_TARGET_X86ORX64
emit_asm_bytes(ctx, ctx->code+ofs, next-ofs);
#else
emit_asm_words(ctx, ctx->code+ofs, next-ofs);
#endif
}
#if LJ_TARGET_ARM && defined(__GNUC__) && !LJ_NO_UNWIND
fprintf(ctx->fp,
#if !LJ_HASFFI
".globl lj_err_unwind_arm\n"
".personality lj_err_unwind_arm\n"
#endif
".fnend\n");
#endif
fprintf(ctx->fp, "\n");
switch (ctx->mode) {
case BUILD_elfasm:
#if !LJ_TARGET_PS3
fprintf(ctx->fp, "\t.section .note.GNU-stack,\"\"," ELFASM_PX "progbits\n");
#endif
#if LJ_TARGET_PPCSPE
/* Soft-float ABI + SPE. */
fprintf(ctx->fp, "\t.gnu_attribute 4, 2\n\t.gnu_attribute 8, 3\n");
#elif LJ_TARGET_PPC && !LJ_TARGET_PS3
/* Hard-float ABI. */
fprintf(ctx->fp, "\t.gnu_attribute 4, 1\n");
#endif
/* fallthrough */
case BUILD_coffasm:
fprintf(ctx->fp, "\t.ident \"%s\"\n", ctx->dasm_ident);
break;
case BUILD_machasm:
fprintf(ctx->fp,
"\t.cstring\n"
"\t.ascii \"%s\\0\"\n", ctx->dasm_ident);
break;
default:
break;
}
fprintf(ctx->fp, "\n");
}
| mit |
aspectron/jsx | extern/boost/libs/local_function/example/n2529_this.cpp | 57 | 1332 |
// Copyright (C) 2009-2012 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE_1_0.txt or a copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Home at http://www.boost.org/libs/local_function
#include <boost/local_function.hpp>
#include <boost/typeof/typeof.hpp>
#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
#include <boost/detail/lightweight_test.hpp>
#include <vector>
#include <algorithm>
struct v;
BOOST_TYPEOF_REGISTER_TYPE(v) // Register before `bind this_` below.
struct v {
std::vector<int> nums;
v(const std::vector<int>& numbers): nums(numbers) {}
void change_sign_all(const std::vector<int>& indices) {
void BOOST_LOCAL_FUNCTION(bind this_, int i) { // Bind object `this`.
this_->nums.at(i) = -this_->nums.at(i);
} BOOST_LOCAL_FUNCTION_NAME(complement)
std::for_each(indices.begin(), indices.end(), complement);
}
};
int main(void) {
std::vector<int> n(3);
n[0] = 1; n[1] = 2; n[2] = 3;
std::vector<int> i(2);
i[0] = 0; i[1] = 2; // Will change n[0] and n[2] but not n[1].
v vn(n);
vn.change_sign_all(i);
BOOST_TEST(vn.nums.at(0) == -1);
BOOST_TEST(vn.nums.at(1) == 2);
BOOST_TEST(vn.nums.at(2) == -3);
return boost::report_errors();
}
| mit |
stonegithubs/micropython | stmhal/hal/f7/src/stm32f7xx_hal_dma.c | 57 | 30830 | /**
******************************************************************************
* @file stm32f7xx_hal_dma.c
* @author MCD Application Team
* @version V1.0.1
* @date 25-June-2015
* @brief DMA HAL module driver.
*
* This file provides firmware functions to manage the following
* functionalities of the Direct Memory Access (DMA) peripheral:
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral State and errors functions
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
(#) Enable and configure the peripheral to be connected to the DMA Stream
(except for internal SRAM/FLASH memories: no initialization is
necessary) please refer to Reference manual for connection between peripherals
and DMA requests .
(#) For a given Stream, program the required configuration through the following parameters:
Transfer Direction, Source and Destination data formats,
Circular, Normal or peripheral flow control mode, Stream Priority level,
Source and Destination Increment mode, FIFO mode and its Threshold (if needed),
Burst mode for Source and/or Destination (if needed) using HAL_DMA_Init() function.
*** Polling mode IO operation ***
=================================
[..]
(+) Use HAL_DMA_Start() to start DMA transfer after the configuration of Source
address and destination address and the Length of data to be transferred
(+) Use HAL_DMA_PollForTransfer() to poll for the end of current transfer, in this
case a fixed Timeout can be configured by User depending from his application.
*** Interrupt mode IO operation ***
===================================
[..]
(+) Configure the DMA interrupt priority using HAL_NVIC_SetPriority()
(+) Enable the DMA IRQ handler using HAL_NVIC_EnableIRQ()
(+) Use HAL_DMA_Start_IT() to start DMA transfer after the configuration of
Source address and destination address and the Length of data to be transferred. In this
case the DMA interrupt is configured
(+) Use HAL_DMA_IRQHandler() called under DMA_IRQHandler() Interrupt subroutine
(+) At the end of data transfer HAL_DMA_IRQHandler() function is executed and user can
add his own function by customization of function pointer XferCpltCallback and
XferErrorCallback (i.e a member of DMA handle structure).
[..]
(#) Use HAL_DMA_GetState() function to return the DMA state and HAL_DMA_GetError() in case of error
detection.
(#) Use HAL_DMA_Abort() function to abort the current transfer
-@- In Memory-to-Memory transfer mode, Circular mode is not allowed.
-@- The FIFO is used mainly to reduce bus usage and to allow data packing/unpacking: it is
possible to set different Data Sizes for the Peripheral and the Memory (ie. you can set
Half-Word data size for the peripheral to access its data register and set Word data size
for the Memory to gain in access time. Each two half words will be packed and written in
a single access to a Word in the Memory).
-@- When FIFO is disabled, it is not allowed to configure different Data Sizes for Source
and Destination. In this case the Peripheral Data Size will be applied to both Source
and Destination.
*** DMA HAL driver macros list ***
=============================================
[..]
Below the list of most used macros in DMA HAL driver.
(+) __HAL_DMA_ENABLE: Enable the specified DMA Stream.
(+) __HAL_DMA_DISABLE: Disable the specified DMA Stream.
(+) __HAL_DMA_GET_FS: Return the current DMA Stream FIFO filled level.
(+) __HAL_DMA_GET_FLAG: Get the DMA Stream pending flags.
(+) __HAL_DMA_CLEAR_FLAG: Clear the DMA Stream pending flags.
(+) __HAL_DMA_ENABLE_IT: Enable the specified DMA Stream interrupts.
(+) __HAL_DMA_DISABLE_IT: Disable the specified DMA Stream interrupts.
(+) __HAL_DMA_GET_IT_SOURCE: Check whether the specified DMA Stream interrupt has occurred or not.
[..]
(@) You can refer to the DMA HAL driver header file for more useful macros
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2015 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f7xx_hal.h"
/** @addtogroup STM32F7xx_HAL_Driver
* @{
*/
/** @defgroup DMA DMA
* @brief DMA HAL module driver
* @{
*/
#ifdef HAL_DMA_MODULE_ENABLED
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup DMA_Private_Constants
* @{
*/
#define HAL_TIMEOUT_DMA_ABORT ((uint32_t)1000) /* 1s */
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/** @addtogroup DMA_Private_Functions
* @{
*/
static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength);
/**
* @brief Sets the DMA Transfer parameter.
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @param SrcAddress: The source memory Buffer address
* @param DstAddress: The destination memory Buffer address
* @param DataLength: The length of data to be transferred from source to destination
* @retval HAL status
*/
static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
{
/* Clear DBM bit */
hdma->Instance->CR &= (uint32_t)(~DMA_SxCR_DBM);
/* Configure DMA Stream data length */
hdma->Instance->NDTR = DataLength;
/* Peripheral to Memory */
if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH)
{
/* Configure DMA Stream destination address */
hdma->Instance->PAR = DstAddress;
/* Configure DMA Stream source address */
hdma->Instance->M0AR = SrcAddress;
}
/* Memory to Peripheral */
else
{
/* Configure DMA Stream source address */
hdma->Instance->PAR = SrcAddress;
/* Configure DMA Stream destination address */
hdma->Instance->M0AR = DstAddress;
}
}
/**
* @}
*/
/* Exported functions ---------------------------------------------------------*/
/** @addtogroup DMA_Exported_Functions
* @{
*/
/** @addtogroup DMA_Exported_Functions_Group1
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..]
This section provides functions allowing to initialize the DMA Stream source
and destination addresses, incrementation and data sizes, transfer direction,
circular/normal mode selection, memory-to-memory mode selection and Stream priority value.
[..]
The HAL_DMA_Init() function follows the DMA configuration procedures as described in
reference manual.
@endverbatim
* @{
*/
/**
* @brief Initializes the DMA according to the specified
* parameters in the DMA_InitTypeDef and create the associated handle.
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma)
{
uint32_t tmp = 0;
/* Check the DMA peripheral state */
if(hdma == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_DMA_STREAM_ALL_INSTANCE(hdma->Instance));
assert_param(IS_DMA_CHANNEL(hdma->Init.Channel));
assert_param(IS_DMA_DIRECTION(hdma->Init.Direction));
assert_param(IS_DMA_PERIPHERAL_INC_STATE(hdma->Init.PeriphInc));
assert_param(IS_DMA_MEMORY_INC_STATE(hdma->Init.MemInc));
assert_param(IS_DMA_PERIPHERAL_DATA_SIZE(hdma->Init.PeriphDataAlignment));
assert_param(IS_DMA_MEMORY_DATA_SIZE(hdma->Init.MemDataAlignment));
assert_param(IS_DMA_MODE(hdma->Init.Mode));
assert_param(IS_DMA_PRIORITY(hdma->Init.Priority));
assert_param(IS_DMA_FIFO_MODE_STATE(hdma->Init.FIFOMode));
/* Check the memory burst, peripheral burst and FIFO threshold parameters only
when FIFO mode is enabled */
if(hdma->Init.FIFOMode != DMA_FIFOMODE_DISABLE)
{
assert_param(IS_DMA_FIFO_THRESHOLD(hdma->Init.FIFOThreshold));
assert_param(IS_DMA_MEMORY_BURST(hdma->Init.MemBurst));
assert_param(IS_DMA_PERIPHERAL_BURST(hdma->Init.PeriphBurst));
}
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_BUSY;
/* Get the CR register value */
tmp = hdma->Instance->CR;
/* Clear CHSEL, MBURST, PBURST, PL, MSIZE, PSIZE, MINC, PINC, CIRC, DIR, CT and DBM bits */
tmp &= ((uint32_t)~(DMA_SxCR_CHSEL | DMA_SxCR_MBURST | DMA_SxCR_PBURST | \
DMA_SxCR_PL | DMA_SxCR_MSIZE | DMA_SxCR_PSIZE | \
DMA_SxCR_MINC | DMA_SxCR_PINC | DMA_SxCR_CIRC | \
DMA_SxCR_DIR | DMA_SxCR_CT | DMA_SxCR_DBM));
/* Prepare the DMA Stream configuration */
tmp |= hdma->Init.Channel | hdma->Init.Direction |
hdma->Init.PeriphInc | hdma->Init.MemInc |
hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment |
hdma->Init.Mode | hdma->Init.Priority;
/* the Memory burst and peripheral burst are not used when the FIFO is disabled */
if(hdma->Init.FIFOMode == DMA_FIFOMODE_ENABLE)
{
/* Get memory burst and peripheral burst */
tmp |= hdma->Init.MemBurst | hdma->Init.PeriphBurst;
}
/* Write to DMA Stream CR register */
hdma->Instance->CR = tmp;
/* Get the FCR register value */
tmp = hdma->Instance->FCR;
/* Clear Direct mode and FIFO threshold bits */
tmp &= (uint32_t)~(DMA_SxFCR_DMDIS | DMA_SxFCR_FTH);
/* Prepare the DMA Stream FIFO configuration */
tmp |= hdma->Init.FIFOMode;
/* the FIFO threshold is not used when the FIFO mode is disabled */
if(hdma->Init.FIFOMode == DMA_FIFOMODE_ENABLE)
{
/* Get the FIFO threshold */
tmp |= hdma->Init.FIFOThreshold;
}
/* Write to DMA Stream FCR */
hdma->Instance->FCR = tmp;
/* Initialize the error code */
hdma->ErrorCode = HAL_DMA_ERROR_NONE;
/* Initialize the DMA state */
hdma->State = HAL_DMA_STATE_READY;
return HAL_OK;
}
/**
* @brief DeInitializes the DMA peripheral
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma)
{
/* Check the DMA peripheral state */
if(hdma == NULL)
{
return HAL_ERROR;
}
/* Check the DMA peripheral state */
if(hdma->State == HAL_DMA_STATE_BUSY)
{
return HAL_ERROR;
}
/* Disable the selected DMA Streamx */
__HAL_DMA_DISABLE(hdma);
/* Reset DMA Streamx control register */
hdma->Instance->CR = 0;
/* Reset DMA Streamx number of data to transfer register */
hdma->Instance->NDTR = 0;
/* Reset DMA Streamx peripheral address register */
hdma->Instance->PAR = 0;
/* Reset DMA Streamx memory 0 address register */
hdma->Instance->M0AR = 0;
/* Reset DMA Streamx memory 1 address register */
hdma->Instance->M1AR = 0;
/* Reset DMA Streamx FIFO control register */
hdma->Instance->FCR = (uint32_t)0x00000021;
/* Clear all flags */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma));
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma));
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma));
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
/* Initialize the error code */
hdma->ErrorCode = HAL_DMA_ERROR_NONE;
/* Initialize the DMA state */
hdma->State = HAL_DMA_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hdma);
return HAL_OK;
}
/**
* @}
*/
/** @addtogroup DMA_Exported_Functions_Group2
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure the source, destination address and data length and Start DMA transfer
(+) Configure the source, destination address and data length and
Start DMA transfer with interrupt
(+) Abort DMA transfer
(+) Poll for transfer complete
(+) Handle DMA interrupt request
@endverbatim
* @{
*/
/**
* @brief Starts the DMA Transfer.
* @param hdma : pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @param SrcAddress: The source memory Buffer address
* @param DstAddress: The destination memory Buffer address
* @param DataLength: The length of data to be transferred from source to destination
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
{
/* Process locked */
__HAL_LOCK(hdma);
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_BUSY;
/* Check the parameters */
assert_param(IS_DMA_BUFFER_SIZE(DataLength));
/* Disable the peripheral */
__HAL_DMA_DISABLE(hdma);
/* Configure the source, destination address and the data length */
DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength);
/* Enable the Peripheral */
__HAL_DMA_ENABLE(hdma);
return HAL_OK;
}
/**
* @brief Start the DMA Transfer with interrupt enabled.
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @param SrcAddress: The source memory Buffer address
* @param DstAddress: The destination memory Buffer address
* @param DataLength: The length of data to be transferred from source to destination
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
{
/* Process locked */
__HAL_LOCK(hdma);
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_BUSY;
/* Check the parameters */
assert_param(IS_DMA_BUFFER_SIZE(DataLength));
/* Disable the peripheral */
__HAL_DMA_DISABLE(hdma);
/* Configure the source, destination address and the data length */
DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength);
/* Enable the transfer complete interrupt */
__HAL_DMA_ENABLE_IT(hdma, DMA_IT_TC);
/* Enable the Half transfer complete interrupt */
__HAL_DMA_ENABLE_IT(hdma, DMA_IT_HT);
/* Enable the transfer Error interrupt */
__HAL_DMA_ENABLE_IT(hdma, DMA_IT_TE);
/* Enable the FIFO Error interrupt */
__HAL_DMA_ENABLE_IT(hdma, DMA_IT_FE);
/* Enable the direct mode Error interrupt */
__HAL_DMA_ENABLE_IT(hdma, DMA_IT_DME);
/* Enable the Peripheral */
__HAL_DMA_ENABLE(hdma);
return HAL_OK;
}
/**
* @brief Aborts the DMA Transfer.
* @param hdma : pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
*
* @note After disabling a DMA Stream, a check for wait until the DMA Stream is
* effectively disabled is added. If a Stream is disabled
* while a data transfer is ongoing, the current data will be transferred
* and the Stream will be effectively disabled only after the transfer of
* this single data is finished.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma)
{
uint32_t tickstart = 0;
/* Disable the stream */
__HAL_DMA_DISABLE(hdma);
/* Get tick */
tickstart = HAL_GetTick();
/* Check if the DMA Stream is effectively disabled */
while((hdma->Instance->CR & DMA_SxCR_EN) != 0)
{
/* Check for the Timeout */
if((HAL_GetTick() - tickstart ) > HAL_TIMEOUT_DMA_ABORT)
{
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hdma);
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
/* Process Unlocked */
__HAL_UNLOCK(hdma);
/* Change the DMA state*/
hdma->State = HAL_DMA_STATE_READY;
return HAL_OK;
}
/**
* @brief Polling for transfer complete.
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @param CompleteLevel: Specifies the DMA level complete.
* @param Timeout: Timeout duration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout)
{
uint32_t temp, tmp, tmp1, tmp2;
uint32_t tickstart = 0;
/* Get the level transfer complete flag */
if(CompleteLevel == HAL_DMA_FULL_TRANSFER)
{
/* Transfer Complete flag */
temp = __HAL_DMA_GET_TC_FLAG_INDEX(hdma);
}
else
{
/* Half Transfer Complete flag */
temp = __HAL_DMA_GET_HT_FLAG_INDEX(hdma);
}
/* Get tick */
tickstart = HAL_GetTick();
while(__HAL_DMA_GET_FLAG(hdma, temp) == RESET)
{
tmp = __HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma));
tmp1 = __HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma));
tmp2 = __HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma));
if((tmp != RESET) || (tmp1 != RESET) || (tmp2 != RESET))
{
if(tmp != RESET)
{
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_TE;
/* Clear the transfer error flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma));
}
if(tmp1 != RESET)
{
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_FE;
/* Clear the FIFO error flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma));
}
if(tmp2 != RESET)
{
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_DME;
/* Clear the Direct Mode error flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma));
}
/* Change the DMA state */
hdma->State= HAL_DMA_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hdma);
return HAL_ERROR;
}
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_TIMEOUT;
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hdma);
return HAL_TIMEOUT;
}
}
}
if(CompleteLevel == HAL_DMA_FULL_TRANSFER)
{
/* Multi_Buffering mode enabled */
if(((hdma->Instance->CR) & (uint32_t)(DMA_SxCR_DBM)) != 0)
{
/* Clear the half transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
/* Clear the transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
/* Current memory buffer used is Memory 0 */
if((hdma->Instance->CR & DMA_SxCR_CT) == 0)
{
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_READY_MEM0;
}
/* Current memory buffer used is Memory 1 */
else if((hdma->Instance->CR & DMA_SxCR_CT) != 0)
{
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_READY_MEM1;
}
}
else
{
/* Clear the half transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
/* Clear the transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
/* The selected Streamx EN bit is cleared (DMA is disabled and all transfers
are complete) */
hdma->State = HAL_DMA_STATE_READY_MEM0;
}
/* Process Unlocked */
__HAL_UNLOCK(hdma);
}
else
{
/* Multi_Buffering mode enabled */
if(((hdma->Instance->CR) & (uint32_t)(DMA_SxCR_DBM)) != 0)
{
/* Clear the half transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
/* Current memory buffer used is Memory 0 */
if((hdma->Instance->CR & DMA_SxCR_CT) == 0)
{
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_READY_HALF_MEM0;
}
/* Current memory buffer used is Memory 1 */
else if((hdma->Instance->CR & DMA_SxCR_CT) != 0)
{
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_READY_HALF_MEM1;
}
}
else
{
/* Clear the half transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_READY_HALF_MEM0;
}
}
return HAL_OK;
}
/**
* @brief Handles DMA interrupt request.
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @retval None
*/
void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma)
{
/* Transfer Error Interrupt management ***************************************/
if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET)
{
if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TE) != RESET)
{
/* Disable the transfer error interrupt */
__HAL_DMA_DISABLE_IT(hdma, DMA_IT_TE);
/* Clear the transfer error flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma));
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_TE;
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hdma);
if(hdma->XferErrorCallback != NULL)
{
/* Transfer error callback */
hdma->XferErrorCallback(hdma);
}
}
}
/* FIFO Error Interrupt management ******************************************/
if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma)) != RESET)
{
if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_FE) != RESET)
{
/* Disable the FIFO Error interrupt */
__HAL_DMA_DISABLE_IT(hdma, DMA_IT_FE);
/* Clear the FIFO error flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma));
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_FE;
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hdma);
if(hdma->XferErrorCallback != NULL)
{
/* Transfer error callback */
hdma->XferErrorCallback(hdma);
}
}
}
/* Direct Mode Error Interrupt management ***********************************/
if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma)) != RESET)
{
if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_DME) != RESET)
{
/* Disable the direct mode Error interrupt */
__HAL_DMA_DISABLE_IT(hdma, DMA_IT_DME);
/* Clear the direct mode error flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma));
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_DME;
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hdma);
if(hdma->XferErrorCallback != NULL)
{
/* Transfer error callback */
hdma->XferErrorCallback(hdma);
}
}
}
/* Half Transfer Complete Interrupt management ******************************/
if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)) != RESET)
{
if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_HT) != RESET)
{
/* Multi_Buffering mode enabled */
if(((hdma->Instance->CR) & (uint32_t)(DMA_SxCR_DBM)) != 0)
{
/* Clear the half transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
/* Current memory buffer used is Memory 0 */
if((hdma->Instance->CR & DMA_SxCR_CT) == 0)
{
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_READY_HALF_MEM0;
}
/* Current memory buffer used is Memory 1 */
else if((hdma->Instance->CR & DMA_SxCR_CT) != 0)
{
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_READY_HALF_MEM1;
}
}
else
{
/* Disable the half transfer interrupt if the DMA mode is not CIRCULAR */
if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
{
/* Disable the half transfer interrupt */
__HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT);
}
/* Clear the half transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_READY_HALF_MEM0;
}
if(hdma->XferHalfCpltCallback != NULL)
{
/* Half transfer callback */
hdma->XferHalfCpltCallback(hdma);
}
}
}
/* Transfer Complete Interrupt management ***********************************/
if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)) != RESET)
{
if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TC) != RESET)
{
if(((hdma->Instance->CR) & (uint32_t)(DMA_SxCR_DBM)) != 0)
{
/* Clear the transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
/* Current memory buffer used is Memory 1 */
if((hdma->Instance->CR & DMA_SxCR_CT) == 0)
{
if(hdma->XferM1CpltCallback != NULL)
{
/* Transfer complete Callback for memory1 */
hdma->XferM1CpltCallback(hdma);
}
}
/* Current memory buffer used is Memory 0 */
else if((hdma->Instance->CR & DMA_SxCR_CT) != 0)
{
if(hdma->XferCpltCallback != NULL)
{
/* Transfer complete Callback for memory0 */
hdma->XferCpltCallback(hdma);
}
}
}
/* Disable the transfer complete interrupt if the DMA mode is not CIRCULAR */
else
{
if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
{
/* Disable the transfer complete interrupt */
__HAL_DMA_DISABLE_IT(hdma, DMA_IT_TC);
}
/* Clear the transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_NONE;
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_READY_MEM0;
/* Process Unlocked */
__HAL_UNLOCK(hdma);
if(hdma->XferCpltCallback != NULL)
{
/* Transfer complete callback */
hdma->XferCpltCallback(hdma);
}
}
}
}
}
/**
* @}
*/
/** @addtogroup DMA_Exported_Functions_Group3
*
@verbatim
===============================================================================
##### State and Errors functions #####
===============================================================================
[..]
This subsection provides functions allowing to
(+) Check the DMA state
(+) Get error code
@endverbatim
* @{
*/
/**
* @brief Returns the DMA state.
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @retval HAL state
*/
HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma)
{
return hdma->State;
}
/**
* @brief Return the DMA error code
* @param hdma : pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @retval DMA Error Code
*/
uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma)
{
return hdma->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_DMA_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| mit |
yxcoin/yxcoin | src/boost_1_55_0/libs/spirit/test/karma/utree3.cpp | 59 | 4186 | // Copyright (c) 2001-2011 Hartmut Kaiser
// Copyright (c) 2001-2011 Joel de Guzman
// Copyright (c) 2010 Bryce Lelbach
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/config/warning_disable.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/mpl/print.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/support_utree.hpp>
#include <sstream>
#include "test.hpp"
int main()
{
using spirit_test::test;
using spirit_test::test_delimited;
using boost::spirit::utree;
using boost::spirit::utree_type;
using boost::spirit::utf8_string_range_type;
using boost::spirit::utf8_string_type;
using boost::spirit::utf8_symbol_type;
using boost::spirit::karma::char_;
using boost::spirit::karma::bool_;
using boost::spirit::karma::int_;
using boost::spirit::karma::double_;
using boost::spirit::karma::string;
using boost::spirit::karma::space;
using boost::spirit::karma::rule;
typedef spirit_test::output_iterator<char>::type output_iterator;
// as_string
{
using boost::spirit::karma::digit;
using boost::spirit::karma::as_string;
utree ut("xy");
BOOST_TEST(test("xy", string, ut));
BOOST_TEST(test("xy", as_string[*char_], ut));
BOOST_TEST(test("x,y", as_string[char_ << ',' << char_], ut));
ut.clear();
ut.push_back("ab");
ut.push_back(1.2);
BOOST_TEST(test("ab1.2", as_string[*~digit] << double_, ut));
BOOST_TEST(test("a,b1.2", as_string[~digit % ','] << double_, ut));
}
// as
{
using boost::spirit::karma::digit;
using boost::spirit::karma::as;
typedef as<std::string> as_string_type;
as_string_type const as_string = as_string_type();
typedef as<utf8_symbol_type> as_symbol_type;
as_symbol_type const as_symbol = as_symbol_type();
utree ut("xy");
BOOST_TEST(test("xy", string, ut));
BOOST_TEST(test("xy", as_string[*char_], ut));
BOOST_TEST(test("x,y", as_string[char_ << ',' << char_], ut));
ut.clear();
ut.push_back("ab");
ut.push_back(1.2);
BOOST_TEST(test("ab1.2", as_string[*~digit] << double_, ut));
BOOST_TEST(test("a,b1.2", as_string[~digit % ','] << double_, ut));
ut = utf8_symbol_type("xy");
BOOST_TEST(test("xy", string, ut));
BOOST_TEST(test("xy", as_symbol[*char_], ut));
BOOST_TEST(test("x,y", as_symbol[char_ << ',' << char_], ut));
ut.clear();
ut.push_back(utf8_symbol_type("ab"));
ut.push_back(1.2);
BOOST_TEST(test("ab1.2", as_symbol[*~digit] << double_, ut));
BOOST_TEST(test("a,b1.2", as_symbol[~digit % ','] << double_, ut));
}
// typed basic_string rules
{
utree ut("buzz");
rule<output_iterator, utf8_string_type()> r1 = string;
rule<output_iterator, utf8_symbol_type()> r2 = string;
BOOST_TEST(test("buzz", r1, ut));
ut = utf8_symbol_type("bar");
BOOST_TEST(test("bar", r2, ut));
}
// parameterized karma::string
{
utree ut("foo");
rule<output_iterator, utf8_string_type()> r1 = string("foo");
BOOST_TEST(test("foo", string("foo"), ut));
BOOST_TEST(test("foo", r1, ut));
}
{
using boost::spirit::karma::verbatim;
using boost::spirit::karma::repeat;
using boost::spirit::karma::space;
using boost::spirit::karma::digit;
utree ut;
ut.push_back('x');
ut.push_back('y');
ut.push_back('c');
BOOST_TEST(test_delimited("xy c ", verbatim[repeat(2)[char_]] << char_, ut, space));
BOOST_TEST(test_delimited("x yc ", char_ << verbatim[*char_], ut, space));
ut.clear();
ut.push_back('a');
ut.push_back('b');
ut.push_back(1.2);
BOOST_TEST(test_delimited("ab 1.2 ", verbatim[repeat(2)[~digit]] << double_, ut, space));
}
return boost::report_errors();
}
| mit |
chaos7theory/coreclr | src/pal/tests/palsuite/c_runtime/fwrite/test1/test1.c | 62 | 2736 | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*============================================================================
**
** Source: test1.c
**
** Purpose: Write a short string to a file and check that it was written
** properly.
**
**
**==========================================================================*/
#include <palsuite.h>
int __cdecl main(int argc, char **argv)
{
const char filename[] = "testfile.tmp";
const char outBuffer[] = "This is a test.";
char inBuffer[sizeof(outBuffer) + 10];
int itemsExpected;
int itemsWritten;
FILE * fp = NULL;
if (PAL_Initialize(argc, argv))
{
return FAIL;
}
if((fp = fopen(filename, "w")) == NULL)
{
Fail("Unable to open a file for write.\n");
}
itemsExpected = sizeof(outBuffer);
itemsWritten = fwrite(outBuffer,
sizeof(outBuffer[0]),
sizeof(outBuffer),
fp);
if (itemsWritten == 0)
{
if(fclose(fp) != 0)
{
Fail("fwrite: Error occurred during the closing of a file.\n");
}
Fail("fwrite() couldn't write to a stream at all\n");
}
else if (itemsWritten != itemsExpected)
{
if(fclose(fp) != 0)
{
Fail("fwrite: Error occurred during the closing of a file.\n");
}
Fail("fwrite() produced errors writing to a stream.\n");
}
if(fclose(fp) != 0)
{
Fail("fwrite: Error occurred during the closing of a file.\n");
}
/* open the file to verify what was written to the file */
if ((fp = fopen(filename, "r")) == NULL)
{
Fail("Couldn't open newly written file for read.\n");
}
if (fgets(inBuffer, sizeof(inBuffer), fp) == NULL)
{
if(fclose(fp) != 0)
{
Fail("fwrite: Error occurred during the closing of a file.\n");
}
Fail("We wrote something to a file using fwrite() and got errors"
" when we tried to read it back using fgets(). Either "
"fwrite() or fgets() is broken.\n");
}
if (strcmp(inBuffer, outBuffer) != 0)
{
if(fclose(fp) != 0)
{
Fail("fwrite: Error occurred during the closing of a file.\n");
}
Fail("fwrite() (or fgets()) is broken. The string read back from"
" the file does not match the string written.\n");
}
if(fclose(fp) != 0)
{
Fail("fwrite: Error occurred during the closing of a file.\n");
}
PAL_Terminate();
return PASS;
}
| mit |
Brit-Coin/britcoin | src/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 |
wilseypa/odroidNetworking | linux/drivers/net/fddi/skfp/hwt.c | 13125 | 5396 | /******************************************************************************
*
* (C)Copyright 1998,1999 SysKonnect,
* a business unit of Schneider & Koch & Co. Datensysteme GmbH.
*
* See the file "skfddi.c" for further information.
*
* 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.
*
* The information in this file is provided "AS IS" without warranty.
*
******************************************************************************/
/*
* Timer Driver for FBI board (timer chip 82C54)
*/
/*
* Modifications:
*
* 28-Jun-1994 sw Edit v1.6.
* MCA: Added support for the SK-NET FDDI-FM2 adapter. The
* following functions have been added(+) or modified(*):
* hwt_start(*), hwt_stop(*), hwt_restart(*), hwt_read(*)
*/
#include "h/types.h"
#include "h/fddi.h"
#include "h/smc.h"
#ifndef lint
static const char ID_sccs[] = "@(#)hwt.c 1.13 97/04/23 (C) SK " ;
#endif
/*
* Prototypes of local functions.
*/
/* 28-Jun-1994 sw - Note: hwt_restart() is also used in module 'drvfbi.c'. */
/*static void hwt_restart() ; */
/************************
*
* hwt_start
*
* Start hardware timer (clock ticks are 16us).
*
* void hwt_start(
* struct s_smc *smc,
* u_long time) ;
* In
* smc - A pointer to the SMT Context structure.
*
* time - The time in units of 16us to load the timer with.
* Out
* Nothing.
*
************************/
#define HWT_MAX (65000)
void hwt_start(struct s_smc *smc, u_long time)
{
u_short cnt ;
if (time > HWT_MAX)
time = HWT_MAX ;
smc->hw.t_start = time ;
smc->hw.t_stop = 0L ;
cnt = (u_short)time ;
/*
* if time < 16 us
* time = 16 us
*/
if (!cnt)
cnt++ ;
outpd(ADDR(B2_TI_INI), (u_long) cnt * 200) ; /* Load timer value. */
outpw(ADDR(B2_TI_CRTL), TIM_START) ; /* Start timer. */
smc->hw.timer_activ = TRUE ;
}
/************************
*
* hwt_stop
*
* Stop hardware timer.
*
* void hwt_stop(
* struct s_smc *smc) ;
* In
* smc - A pointer to the SMT Context structure.
* Out
* Nothing.
*
************************/
void hwt_stop(struct s_smc *smc)
{
outpw(ADDR(B2_TI_CRTL), TIM_STOP) ;
outpw(ADDR(B2_TI_CRTL), TIM_CL_IRQ) ;
smc->hw.timer_activ = FALSE ;
}
/************************
*
* hwt_init
*
* Initialize hardware timer.
*
* void hwt_init(
* struct s_smc *smc) ;
* In
* smc - A pointer to the SMT Context structure.
* Out
* Nothing.
*
************************/
void hwt_init(struct s_smc *smc)
{
smc->hw.t_start = 0 ;
smc->hw.t_stop = 0 ;
smc->hw.timer_activ = FALSE ;
hwt_restart(smc) ;
}
/************************
*
* hwt_restart
*
* Clear timer interrupt.
*
* void hwt_restart(
* struct s_smc *smc) ;
* In
* smc - A pointer to the SMT Context structure.
* Out
* Nothing.
*
************************/
void hwt_restart(struct s_smc *smc)
{
hwt_stop(smc) ;
}
/************************
*
* hwt_read
*
* Stop hardware timer and read time elapsed since last start.
*
* u_long hwt_read(smc) ;
* In
* smc - A pointer to the SMT Context structure.
* Out
* The elapsed time since last start in units of 16us.
*
************************/
u_long hwt_read(struct s_smc *smc)
{
u_short tr ;
u_long is ;
if (smc->hw.timer_activ) {
hwt_stop(smc) ;
tr = (u_short)((inpd(ADDR(B2_TI_VAL))/200) & 0xffff) ;
is = GET_ISR() ;
/* Check if timer expired (or wraparound). */
if ((tr > smc->hw.t_start) || (is & IS_TIMINT)) {
hwt_restart(smc) ;
smc->hw.t_stop = smc->hw.t_start ;
}
else
smc->hw.t_stop = smc->hw.t_start - tr ;
}
return smc->hw.t_stop;
}
#ifdef PCI
/************************
*
* hwt_quick_read
*
* Stop hardware timer and read timer value and start the timer again.
*
* u_long hwt_read(smc) ;
* In
* smc - A pointer to the SMT Context structure.
* Out
* current timer value in units of 80ns.
*
************************/
u_long hwt_quick_read(struct s_smc *smc)
{
u_long interval ;
u_long time ;
interval = inpd(ADDR(B2_TI_INI)) ;
outpw(ADDR(B2_TI_CRTL), TIM_STOP) ;
time = inpd(ADDR(B2_TI_VAL)) ;
outpd(ADDR(B2_TI_INI),time) ;
outpw(ADDR(B2_TI_CRTL), TIM_START) ;
outpd(ADDR(B2_TI_INI),interval) ;
return time;
}
/************************
*
* hwt_wait_time(smc,start,duration)
*
* This function returnes after the amount of time is elapsed
* since the start time.
*
* para start start time
* duration time to wait
*
* NOTE: The function will return immediately, if the timer is not
* started
************************/
void hwt_wait_time(struct s_smc *smc, u_long start, long int duration)
{
long diff ;
long interval ;
int wrapped ;
/*
* check if timer is running
*/
if (smc->hw.timer_activ == FALSE ||
hwt_quick_read(smc) == hwt_quick_read(smc)) {
return ;
}
interval = inpd(ADDR(B2_TI_INI)) ;
if (interval > duration) {
do {
diff = (long)(start - hwt_quick_read(smc)) ;
if (diff < 0) {
diff += interval ;
}
} while (diff <= duration) ;
}
else {
diff = interval ;
wrapped = 0 ;
do {
if (!wrapped) {
if (hwt_quick_read(smc) >= start) {
diff += interval ;
wrapped = 1 ;
}
}
else {
if (hwt_quick_read(smc) < start) {
wrapped = 0 ;
}
}
} while (diff <= duration) ;
}
}
#endif
| mit |
blueshaedow/Polarbear | firmware/tmk_core/tool/mbed/mbed-sdk/libraries/dsp/cmsis_dsp/FastMathFunctions/arm_cos_f32.c | 70 | 12143 | /* ----------------------------------------------------------------------
* Copyright (C) 2010-2013 ARM Limited. All rights reserved.
*
* $Date: 17. January 2013
* $Revision: V1.4.1
*
* Project: CMSIS DSP Library
* Title: arm_cos_f32.c
*
* Description: Fast cosine calculation for floating-point values.
*
* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0
*
* 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 ARM LIMITED 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 "arm_math.h"
/**
* @ingroup groupFastMath
*/
/**
* @defgroup cos Cosine
*
* Computes the trigonometric cosine function using a combination of table lookup
* and cubic interpolation. There are separate functions for
* Q15, Q31, and floating-point data types.
* The input to the floating-point version is in radians while the
* fixed-point Q15 and Q31 have a scaled input with the range
* [0 +0.9999] mapping to [0 2*pi). The fixed-point range is chosen so that a
* value of 2*pi wraps around to 0.
*
* The implementation is based on table lookup using 256 values together with cubic interpolation.
* The steps used are:
* -# Calculation of the nearest integer table index
* -# Fetch the four table values a, b, c, and d
* -# Compute the fractional portion (fract) of the table index.
* -# Calculation of wa, wb, wc, wd
* -# The final result equals <code>a*wa + b*wb + c*wc + d*wd</code>
*
* where
* <pre>
* a=Table[index-1];
* b=Table[index+0];
* c=Table[index+1];
* d=Table[index+2];
* </pre>
* and
* <pre>
* wa=-(1/6)*fract.^3 + (1/2)*fract.^2 - (1/3)*fract;
* wb=(1/2)*fract.^3 - fract.^2 - (1/2)*fract + 1;
* wc=-(1/2)*fract.^3+(1/2)*fract.^2+fract;
* wd=(1/6)*fract.^3 - (1/6)*fract;
* </pre>
*/
/**
* @addtogroup cos
* @{
*/
/**
* \par
* <b>Example code for Generation of Cos Table:</b>
* <pre>
* tableSize = 256;
* for(n = -1; n < (tableSize + 2); n++)
* {
* cosTable[n+1]= cos(2*pi*n/tableSize);
* } </pre>
* where pi value is 3.14159265358979
*/
static const float32_t cosTable[260] = {
0.999698817729949950f, 1.000000000000000000f, 0.999698817729949950f,
0.998795449733734130f, 0.997290432453155520f, 0.995184719562530520f,
0.992479562759399410f, 0.989176511764526370f,
0.985277652740478520f, 0.980785250663757320f, 0.975702106952667240f,
0.970031261444091800f, 0.963776051998138430f, 0.956940352916717530f,
0.949528157711029050f, 0.941544055938720700f,
0.932992815971374510f, 0.923879504203796390f, 0.914209783077239990f,
0.903989315032958980f, 0.893224298954010010f, 0.881921291351318360f,
0.870086967945098880f, 0.857728600502014160f,
0.844853579998016360f, 0.831469595432281490f, 0.817584812641143800f,
0.803207516670227050f, 0.788346409797668460f, 0.773010432720184330f,
0.757208824157714840f, 0.740951120853424070f,
0.724247097969055180f, 0.707106769084930420f, 0.689540565013885500f,
0.671558976173400880f, 0.653172850608825680f, 0.634393274784088130f,
0.615231573581695560f, 0.595699310302734380f,
0.575808167457580570f, 0.555570244789123540f, 0.534997642040252690f,
0.514102756977081300f, 0.492898195981979370f, 0.471396744251251220f,
0.449611335992813110f, 0.427555084228515630f,
0.405241310596466060f, 0.382683426141738890f, 0.359895050525665280f,
0.336889863014221190f, 0.313681751489639280f, 0.290284663438797000f,
0.266712754964828490f, 0.242980182170867920f,
0.219101235270500180f, 0.195090323686599730f, 0.170961886644363400f,
0.146730467677116390f, 0.122410677373409270f, 0.098017141222953796f,
0.073564566671848297f, 0.049067676067352295f,
0.024541229009628296f, 0.000000000000000061f, -0.024541229009628296f,
-0.049067676067352295f, -0.073564566671848297f, -0.098017141222953796f,
-0.122410677373409270f, -0.146730467677116390f,
-0.170961886644363400f, -0.195090323686599730f, -0.219101235270500180f,
-0.242980182170867920f, -0.266712754964828490f, -0.290284663438797000f,
-0.313681751489639280f, -0.336889863014221190f,
-0.359895050525665280f, -0.382683426141738890f, -0.405241310596466060f,
-0.427555084228515630f, -0.449611335992813110f, -0.471396744251251220f,
-0.492898195981979370f, -0.514102756977081300f,
-0.534997642040252690f, -0.555570244789123540f, -0.575808167457580570f,
-0.595699310302734380f, -0.615231573581695560f, -0.634393274784088130f,
-0.653172850608825680f, -0.671558976173400880f,
-0.689540565013885500f, -0.707106769084930420f, -0.724247097969055180f,
-0.740951120853424070f, -0.757208824157714840f, -0.773010432720184330f,
-0.788346409797668460f, -0.803207516670227050f,
-0.817584812641143800f, -0.831469595432281490f, -0.844853579998016360f,
-0.857728600502014160f, -0.870086967945098880f, -0.881921291351318360f,
-0.893224298954010010f, -0.903989315032958980f,
-0.914209783077239990f, -0.923879504203796390f, -0.932992815971374510f,
-0.941544055938720700f, -0.949528157711029050f, -0.956940352916717530f,
-0.963776051998138430f, -0.970031261444091800f,
-0.975702106952667240f, -0.980785250663757320f, -0.985277652740478520f,
-0.989176511764526370f, -0.992479562759399410f, -0.995184719562530520f,
-0.997290432453155520f, -0.998795449733734130f,
-0.999698817729949950f, -1.000000000000000000f, -0.999698817729949950f,
-0.998795449733734130f, -0.997290432453155520f, -0.995184719562530520f,
-0.992479562759399410f, -0.989176511764526370f,
-0.985277652740478520f, -0.980785250663757320f, -0.975702106952667240f,
-0.970031261444091800f, -0.963776051998138430f, -0.956940352916717530f,
-0.949528157711029050f, -0.941544055938720700f,
-0.932992815971374510f, -0.923879504203796390f, -0.914209783077239990f,
-0.903989315032958980f, -0.893224298954010010f, -0.881921291351318360f,
-0.870086967945098880f, -0.857728600502014160f,
-0.844853579998016360f, -0.831469595432281490f, -0.817584812641143800f,
-0.803207516670227050f, -0.788346409797668460f, -0.773010432720184330f,
-0.757208824157714840f, -0.740951120853424070f,
-0.724247097969055180f, -0.707106769084930420f, -0.689540565013885500f,
-0.671558976173400880f, -0.653172850608825680f, -0.634393274784088130f,
-0.615231573581695560f, -0.595699310302734380f,
-0.575808167457580570f, -0.555570244789123540f, -0.534997642040252690f,
-0.514102756977081300f, -0.492898195981979370f, -0.471396744251251220f,
-0.449611335992813110f, -0.427555084228515630f,
-0.405241310596466060f, -0.382683426141738890f, -0.359895050525665280f,
-0.336889863014221190f, -0.313681751489639280f, -0.290284663438797000f,
-0.266712754964828490f, -0.242980182170867920f,
-0.219101235270500180f, -0.195090323686599730f, -0.170961886644363400f,
-0.146730467677116390f, -0.122410677373409270f, -0.098017141222953796f,
-0.073564566671848297f, -0.049067676067352295f,
-0.024541229009628296f, -0.000000000000000184f, 0.024541229009628296f,
0.049067676067352295f, 0.073564566671848297f, 0.098017141222953796f,
0.122410677373409270f, 0.146730467677116390f,
0.170961886644363400f, 0.195090323686599730f, 0.219101235270500180f,
0.242980182170867920f, 0.266712754964828490f, 0.290284663438797000f,
0.313681751489639280f, 0.336889863014221190f,
0.359895050525665280f, 0.382683426141738890f, 0.405241310596466060f,
0.427555084228515630f, 0.449611335992813110f, 0.471396744251251220f,
0.492898195981979370f, 0.514102756977081300f,
0.534997642040252690f, 0.555570244789123540f, 0.575808167457580570f,
0.595699310302734380f, 0.615231573581695560f, 0.634393274784088130f,
0.653172850608825680f, 0.671558976173400880f,
0.689540565013885500f, 0.707106769084930420f, 0.724247097969055180f,
0.740951120853424070f, 0.757208824157714840f, 0.773010432720184330f,
0.788346409797668460f, 0.803207516670227050f,
0.817584812641143800f, 0.831469595432281490f, 0.844853579998016360f,
0.857728600502014160f, 0.870086967945098880f, 0.881921291351318360f,
0.893224298954010010f, 0.903989315032958980f,
0.914209783077239990f, 0.923879504203796390f, 0.932992815971374510f,
0.941544055938720700f, 0.949528157711029050f, 0.956940352916717530f,
0.963776051998138430f, 0.970031261444091800f,
0.975702106952667240f, 0.980785250663757320f, 0.985277652740478520f,
0.989176511764526370f, 0.992479562759399410f, 0.995184719562530520f,
0.997290432453155520f, 0.998795449733734130f,
0.999698817729949950f, 1.000000000000000000f, 0.999698817729949950f,
0.998795449733734130f
};
/**
* @brief Fast approximation to the trigonometric cosine function for floating-point data.
* @param[in] x input value in radians.
* @return cos(x).
*/
float32_t arm_cos_f32(
float32_t x)
{
float32_t cosVal, fract, in;
int32_t index;
uint32_t tableSize = (uint32_t) TABLE_SIZE;
float32_t wa, wb, wc, wd;
float32_t a, b, c, d;
float32_t *tablePtr;
int32_t n;
float32_t fractsq, fractby2, fractby6, fractby3, fractsqby2;
float32_t oneminusfractby2;
float32_t frby2xfrsq, frby6xfrsq;
/* input x is in radians */
/* Scale the input to [0 1] range from [0 2*PI] , divide input by 2*pi */
in = x * 0.159154943092f;
/* Calculation of floor value of input */
n = (int32_t) in;
/* Make negative values towards -infinity */
if(x < 0.0f)
{
n = n - 1;
}
/* Map input value to [0 1] */
in = in - (float32_t) n;
/* Calculation of index of the table */
index = (uint32_t) (tableSize * in);
/* fractional value calculation */
fract = ((float32_t) tableSize * in) - (float32_t) index;
/* Checking min and max index of table */
if(index < 0)
{
index = 0;
}
else if(index > 256)
{
index = 256;
}
/* Initialise table pointer */
tablePtr = (float32_t *) & cosTable[index];
/* Read four nearest values of input value from the cos table */
a = tablePtr[0];
b = tablePtr[1];
c = tablePtr[2];
d = tablePtr[3];
/* Cubic interpolation process */
fractsq = fract * fract;
fractby2 = fract * 0.5f;
fractby6 = fract * 0.166666667f;
fractby3 = fract * 0.3333333333333f;
fractsqby2 = fractsq * 0.5f;
frby2xfrsq = (fractby2) * fractsq;
frby6xfrsq = (fractby6) * fractsq;
oneminusfractby2 = 1.0f - fractby2;
wb = fractsqby2 - fractby3;
wc = (fractsqby2 + fract);
wa = wb - frby6xfrsq;
wb = frby2xfrsq - fractsq;
cosVal = wa * a;
wc = wc - frby2xfrsq;
wd = (frby6xfrsq) - fractby6;
wb = wb + oneminusfractby2;
/* Calculate cos value */
cosVal = (cosVal + (b * wb)) + ((c * wc) + (d * wd));
/* Return the output value */
return (cosVal);
}
/**
* @} end of cos group
*/
| mit |
masterofnix/securealumnicoin3 | src/qt/overviewpage.cpp | 328 | 7376 | // 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 "overviewpage.h"
#include "ui_overviewpage.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "transactiontablemodel.h"
#include "transactionfilterproxy.h"
#include "guiutil.h"
#include "guiconstants.h"
#include <QAbstractItemDelegate>
#include <QPainter>
#define DECORATION_SIZE 64
#define NUM_ITEMS 3
class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)
{
}
inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
painter->save();
QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
QRect mainRect = option.rect;
QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
int xspace = DECORATION_SIZE + 8;
int ypad = 6;
int halfheight = (mainRect.height() - 2*ypad)/2;
QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
icon.paint(painter, decorationRect);
QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(Qt::DisplayRole).toString();
qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
QVariant value = index.data(Qt::ForegroundRole);
QColor foreground = option.palette.color(QPalette::Text);
if(value.canConvert<QBrush>())
{
QBrush brush = qvariant_cast<QBrush>(value);
foreground = brush.color();
}
painter->setPen(foreground);
painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);
if(amount < 0)
{
foreground = COLOR_NEGATIVE;
}
else if(!confirmed)
{
foreground = COLOR_UNCONFIRMED;
}
else
{
foreground = option.palette.color(QPalette::Text);
}
painter->setPen(foreground);
QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);
if(!confirmed)
{
amountText = QString("[") + amountText + QString("]");
}
painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);
painter->setPen(option.palette.color(QPalette::Text));
painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));
painter->restore();
}
inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
return QSize(DECORATION_SIZE, DECORATION_SIZE);
}
int unit;
};
#include "overviewpage.moc"
OverviewPage::OverviewPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::OverviewPage),
clientModel(0),
walletModel(0),
currentBalance(-1),
currentUnconfirmedBalance(-1),
currentImmatureBalance(-1),
txdelegate(new TxViewDelegate()),
filter(0)
{
ui->setupUi(this);
// Recent transactions
ui->listTransactions->setItemDelegate(txdelegate);
ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));
// init "out of sync" warning labels
ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");
// start with displaying the "out of sync" warnings
showOutOfSyncWarning(true);
}
void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
if(filter)
emit transactionClicked(filter->mapToSource(index));
}
OverviewPage::~OverviewPage()
{
delete ui;
}
void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
int unit = walletModel->getOptionsModel()->getDisplayUnit();
currentBalance = balance;
currentUnconfirmedBalance = unconfirmedBalance;
currentImmatureBalance = immatureBalance;
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));
// only show immature (newly mined) balance if it's non-zero, so as not to complicate things
// for the non-mining users
bool showImmature = immatureBalance != 0;
ui->labelImmature->setVisible(showImmature);
ui->labelImmatureText->setVisible(showImmature);
}
void OverviewPage::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Show warning if this is a prerelease version
connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));
updateAlerts(model->getStatusBarWarnings());
}
}
void OverviewPage::setWalletModel(WalletModel *model)
{
this->walletModel = model;
if(model && model->getOptionsModel())
{
// Set up transaction list
filter = new TransactionFilterProxy();
filter->setSourceModel(model->getTransactionTableModel());
filter->setLimit(NUM_ITEMS);
filter->setDynamicSortFilter(true);
filter->setSortRole(Qt::EditRole);
filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);
ui->listTransactions->setModel(filter);
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
// Keep up to date with wallet
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()));
}
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void OverviewPage::updateDisplayUnit()
{
if(walletModel && walletModel->getOptionsModel())
{
if(currentBalance != -1)
setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance);
// Update txdelegate->unit with the current unit
txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();
ui->listTransactions->update();
}
}
void OverviewPage::updateAlerts(const QString &warnings)
{
this->ui->labelAlerts->setVisible(!warnings.isEmpty());
this->ui->labelAlerts->setText(warnings);
}
void OverviewPage::showOutOfSyncWarning(bool fShow)
{
ui->labelWalletStatus->setVisible(fShow);
ui->labelTransactionsStatus->setVisible(fShow);
}
| mit |
ErgoDox-EZ/reactor | lib/firmware/tmk_core/tool/mbed/mbed-sdk/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC408X/TARGET_LPC4088_DM/can_api.c | 77 | 10694 | /* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "can_api.h"
#include "cmsis.h"
#include "pinmap.h"
#include <math.h>
#include <string.h>
#define CAN_NUM 2
/* Acceptance filter mode in AFMR register */
#define ACCF_OFF 0x01
#define ACCF_BYPASS 0x02
#define ACCF_ON 0x00
#define ACCF_FULLCAN 0x04
/* There are several bit timing calculators on the internet.
http://www.port.de/engl/canprod/sv_req_form.html
http://www.kvaser.com/can/index.htm
*/
static const PinMap PinMap_CAN_RD[] = {
{P0_0 , CAN_1, 1},
{P0_4 , CAN_2, 2},
{P0_21, CAN_1, 4},
{NC , NC , 0}
};
static const PinMap PinMap_CAN_TD[] = {
{P0_1 , CAN_1, 1},
{P0_5 , CAN_2, 2},
{NC , NC , 0}
};
// Type definition to hold a CAN message
struct CANMsg {
unsigned int reserved1 : 16;
unsigned int dlc : 4; // Bits 16..19: DLC - Data Length Counter
unsigned int reserved0 : 10;
unsigned int rtr : 1; // Bit 30: Set if this is a RTR message
unsigned int type : 1; // Bit 31: Set if this is a 29-bit ID message
unsigned int id; // CAN Message ID (11-bit or 29-bit)
unsigned char data[8]; // CAN Message Data Bytes 0-7
};
typedef struct CANMsg CANMsg;
static uint32_t can_irq_ids[CAN_NUM] = {0};
static can_irq_handler irq_handler;
static uint32_t can_disable(can_t *obj) {
uint32_t sm = obj->dev->MOD;
obj->dev->MOD |= 1;
return sm;
}
static inline void can_enable(can_t *obj) {
if (obj->dev->MOD & 1) {
obj->dev->MOD &= ~(1);
}
}
int can_mode(can_t *obj, CanMode mode)
{
return 0; // not implemented
}
int can_filter(can_t *obj, uint32_t id, uint32_t mask, CANFormat format, int32_t handle) {
return 0; // not implemented
}
static inline void can_irq(uint32_t icr, uint32_t index) {
uint32_t i;
for(i = 0; i < 8; i++)
{
if((can_irq_ids[index] != 0) && (icr & (1 << i)))
{
switch (i) {
case 0: irq_handler(can_irq_ids[index], IRQ_RX); break;
case 1: irq_handler(can_irq_ids[index], IRQ_TX); break;
case 2: irq_handler(can_irq_ids[index], IRQ_ERROR); break;
case 3: irq_handler(can_irq_ids[index], IRQ_OVERRUN); break;
case 4: irq_handler(can_irq_ids[index], IRQ_WAKEUP); break;
case 5: irq_handler(can_irq_ids[index], IRQ_PASSIVE); break;
case 6: irq_handler(can_irq_ids[index], IRQ_ARB); break;
case 7: irq_handler(can_irq_ids[index], IRQ_BUS); break;
case 8: irq_handler(can_irq_ids[index], IRQ_READY); break;
}
}
}
}
// Have to check that the CAN block is active before reading the Interrupt
// Control Register, or the mbed hangs
void can_irq_n() {
uint32_t icr;
if(LPC_SC->PCONP & (1 << 13)) {
icr = LPC_CAN1->ICR & 0x1FF;
can_irq(icr, 0);
}
if(LPC_SC->PCONP & (1 << 14)) {
icr = LPC_CAN2->ICR & 0x1FF;
can_irq(icr, 1);
}
}
// Register CAN object's irq handler
void can_irq_init(can_t *obj, can_irq_handler handler, uint32_t id) {
irq_handler = handler;
can_irq_ids[obj->index] = id;
}
// Unregister CAN object's irq handler
void can_irq_free(can_t *obj) {
obj->dev->IER &= ~(1);
can_irq_ids[obj->index] = 0;
if ((can_irq_ids[0] == 0) && (can_irq_ids[1] == 0)) {
NVIC_DisableIRQ(CAN_IRQn);
}
}
// Clear or set a irq
void can_irq_set(can_t *obj, CanIrqType type, uint32_t enable) {
uint32_t ier;
switch (type) {
case IRQ_RX: ier = (1 << 0); break;
case IRQ_TX: ier = (1 << 1); break;
case IRQ_ERROR: ier = (1 << 2); break;
case IRQ_OVERRUN: ier = (1 << 3); break;
case IRQ_WAKEUP: ier = (1 << 4); break;
case IRQ_PASSIVE: ier = (1 << 5); break;
case IRQ_ARB: ier = (1 << 6); break;
case IRQ_BUS: ier = (1 << 7); break;
case IRQ_READY: ier = (1 << 8); break;
default: return;
}
obj->dev->MOD |= 1;
if(enable == 0) {
obj->dev->IER &= ~ier;
}
else {
obj->dev->IER |= ier;
}
obj->dev->MOD &= ~(1);
// Enable NVIC if at least 1 interrupt is active
if(((LPC_SC->PCONP & (1 << 13)) && LPC_CAN1->IER) || ((LPC_SC->PCONP & (1 << 14)) && LPC_CAN2->IER)) {
NVIC_SetVector(CAN_IRQn, (uint32_t) &can_irq_n);
NVIC_EnableIRQ(CAN_IRQn);
}
else {
NVIC_DisableIRQ(CAN_IRQn);
}
}
// This table has the sampling points as close to 75% as possible. The first
// value is TSEG1, the second TSEG2.
static const int timing_pts[23][2] = {
{0x0, 0x0}, // 2, 50%
{0x1, 0x0}, // 3, 67%
{0x2, 0x0}, // 4, 75%
{0x3, 0x0}, // 5, 80%
{0x3, 0x1}, // 6, 67%
{0x4, 0x1}, // 7, 71%
{0x5, 0x1}, // 8, 75%
{0x6, 0x1}, // 9, 78%
{0x6, 0x2}, // 10, 70%
{0x7, 0x2}, // 11, 73%
{0x8, 0x2}, // 12, 75%
{0x9, 0x2}, // 13, 77%
{0x9, 0x3}, // 14, 71%
{0xA, 0x3}, // 15, 73%
{0xB, 0x3}, // 16, 75%
{0xC, 0x3}, // 17, 76%
{0xD, 0x3}, // 18, 78%
{0xD, 0x4}, // 19, 74%
{0xE, 0x4}, // 20, 75%
{0xF, 0x4}, // 21, 76%
{0xF, 0x5}, // 22, 73%
{0xF, 0x6}, // 23, 70%
{0xF, 0x7}, // 24, 67%
};
static unsigned int can_speed(unsigned int pclk, unsigned int cclk, unsigned char psjw) {
uint32_t btr;
uint16_t brp = 0;
uint32_t calcbit;
uint32_t bitwidth;
int hit = 0;
int bits;
bitwidth = (pclk / cclk);
brp = bitwidth / 0x18;
while ((!hit) && (brp < bitwidth / 4)) {
brp++;
for (bits = 22; bits > 0; bits--) {
calcbit = (bits + 3) * (brp + 1);
if (calcbit == bitwidth) {
hit = 1;
break;
}
}
}
if (hit) {
btr = ((timing_pts[bits][1] << 20) & 0x00700000)
| ((timing_pts[bits][0] << 16) & 0x000F0000)
| ((psjw << 14) & 0x0000C000)
| ((brp << 0) & 0x000003FF);
} else {
btr = 0xFFFFFFFF;
}
return btr;
}
void can_init(can_t *obj, PinName rd, PinName td) {
CANName can_rd = (CANName)pinmap_peripheral(rd, PinMap_CAN_RD);
CANName can_td = (CANName)pinmap_peripheral(td, PinMap_CAN_TD);
obj->dev = (LPC_CAN_TypeDef *)pinmap_merge(can_rd, can_td);
MBED_ASSERT((int)obj->dev != NC);
switch ((int)obj->dev) {
case CAN_1: LPC_SC->PCONP |= 1 << 13; break;
case CAN_2: LPC_SC->PCONP |= 1 << 14; break;
}
pinmap_pinout(rd, PinMap_CAN_RD);
pinmap_pinout(td, PinMap_CAN_TD);
switch ((int)obj->dev) {
case CAN_1: obj->index = 0; break;
case CAN_2: obj->index = 1; break;
}
can_reset(obj);
obj->dev->IER = 0; // Disable Interrupts
can_frequency(obj, 100000);
LPC_CANAF->AFMR = ACCF_BYPASS; // Bypass Filter
}
void can_free(can_t *obj) {
switch ((int)obj->dev) {
case CAN_1: LPC_SC->PCONP &= ~(1 << 13); break;
case CAN_2: LPC_SC->PCONP &= ~(1 << 14); break;
}
}
int can_frequency(can_t *obj, int f) {
int pclk = PeripheralClock;
int btr = can_speed(pclk, (unsigned int)f, 1);
if (btr > 0) {
uint32_t modmask = can_disable(obj);
obj->dev->BTR = btr;
obj->dev->MOD = modmask;
return 1;
} else {
return 0;
}
}
int can_write(can_t *obj, CAN_Message msg, int cc) {
unsigned int CANStatus;
CANMsg m;
can_enable(obj);
m.id = msg.id ;
m.dlc = msg.len & 0xF;
m.rtr = msg.type;
m.type = msg.format;
memcpy(m.data, msg.data, msg.len);
const unsigned int *buf = (const unsigned int *)&m;
CANStatus = obj->dev->SR;
if (CANStatus & 0x00000004) {
obj->dev->TFI1 = buf[0] & 0xC00F0000;
obj->dev->TID1 = buf[1];
obj->dev->TDA1 = buf[2];
obj->dev->TDB1 = buf[3];
if(cc) {
obj->dev->CMR = 0x30;
} else {
obj->dev->CMR = 0x21;
}
return 1;
} else if (CANStatus & 0x00000400) {
obj->dev->TFI2 = buf[0] & 0xC00F0000;
obj->dev->TID2 = buf[1];
obj->dev->TDA2 = buf[2];
obj->dev->TDB2 = buf[3];
if (cc) {
obj->dev->CMR = 0x50;
} else {
obj->dev->CMR = 0x41;
}
return 1;
} else if (CANStatus & 0x00040000) {
obj->dev->TFI3 = buf[0] & 0xC00F0000;
obj->dev->TID3 = buf[1];
obj->dev->TDA3 = buf[2];
obj->dev->TDB3 = buf[3];
if (cc) {
obj->dev->CMR = 0x90;
} else {
obj->dev->CMR = 0x81;
}
return 1;
}
return 0;
}
int can_read(can_t *obj, CAN_Message *msg, int handle) {
CANMsg x;
unsigned int *i = (unsigned int *)&x;
can_enable(obj);
if (obj->dev->GSR & 0x1) {
*i++ = obj->dev->RFS; // Frame
*i++ = obj->dev->RID; // ID
*i++ = obj->dev->RDA; // Data A
*i++ = obj->dev->RDB; // Data B
obj->dev->CMR = 0x04; // release receive buffer
msg->id = x.id;
msg->len = x.dlc;
msg->format = (x.type)? CANExtended : CANStandard;
msg->type = (x.rtr)? CANRemote: CANData;
memcpy(msg->data,x.data,x.dlc);
return 1;
}
return 0;
}
void can_reset(can_t *obj) {
can_disable(obj);
obj->dev->GSR = 0; // Reset error counter when CAN1MOD is in reset
}
unsigned char can_rderror(can_t *obj) {
return (obj->dev->GSR >> 16) & 0xFF;
}
unsigned char can_tderror(can_t *obj) {
return (obj->dev->GSR >> 24) & 0xFF;
}
void can_monitor(can_t *obj, int silent) {
uint32_t mod_mask = can_disable(obj);
if (silent) {
obj->dev->MOD |= (1 << 1);
} else {
obj->dev->MOD &= ~(1 << 1);
}
if (!(mod_mask & 1)) {
can_enable(obj);
}
}
| mit |
ArcherSys/ArcherSys | arduino-1.6.8/libraries/WiFi/extras/wifiHD/src/printf-stdarg.c | 340 | 8673 | /* This source file is part of the ATMEL AVR32-SoftwareFramework-AT32UC3A-1.4.0 Release */
/*This file has been prepared for Doxygen automatic documentation generation.*/
/*! \file *********************************************************************
*
* \brief sprintf functions to replace newlib for AVR32 UC3.
*
* - Compiler: IAR EWAVR32 and GNU GCC for AVR32
* - Supported devices: All AVR32 devices can be used.
* - AppNote:
*
* \author Atmel Corporation: http://www.atmel.com \n
* Support and FAQ: http://support.atmel.no/
*
*****************************************************************************/
/* Copyright (C) 2006-2008, Atmel 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:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of ATMEL may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL ``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 EXPRESSLY AND
* SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*/
/*
Copyright 2001, 2002 Georges Menie (www.menie.org)
stdarg version contributed by Christian Ettinger
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
putchar is the only external dependency for this file,
if you have a working putchar, leave it commented out.
If not, uncomment the define below and
replace outbyte(c) by your own function call.
*/
#include <stdarg.h>
static void printchar(char **str, int c)
{
extern int board_putchar(char c);
if (str) {
**str = c;
++(*str);
}
else (void) board_putchar(c);
}
#define PAD_RIGHT 1
#define PAD_ZERO 2
static int prints(char **out, const char *string, int width, int pad)
{
register int pc = 0, padchar = ' ';
if (width > 0) {
register int len = 0;
register const char *ptr;
for (ptr = string; *ptr; ++ptr) ++len;
if (len >= width) width = 0;
else width -= len;
if (pad & PAD_ZERO) padchar = '0';
}
if (!(pad & PAD_RIGHT)) {
for ( ; width > 0; --width) {
printchar (out, padchar);
++pc;
}
}
for ( ; *string ; ++string) {
printchar (out, *string);
++pc;
}
for ( ; width > 0; --width) {
printchar (out, padchar);
++pc;
}
return pc;
}
/* the following should be enough for 32 bit int */
#define PRINT_BUF_LEN 12
static int printi(char **out, int i, int b, int sg, int width, int pad, int letbase)
{
char print_buf[PRINT_BUF_LEN];
register char *s;
register int t, neg = 0, pc = 0;
register unsigned int u = i;
if (i == 0) {
print_buf[0] = '0';
print_buf[1] = '\0';
return prints (out, print_buf, width, pad);
}
if (sg && b == 10 && i < 0) {
neg = 1;
u = -i;
}
s = print_buf + PRINT_BUF_LEN-1;
*s = '\0';
while (u) {
t = u % b;
if( t >= 10 )
t += letbase - '0' - 10;
*--s = t + '0';
u /= b;
}
if (neg) {
if( width && (pad & PAD_ZERO) ) {
printchar (out, '-');
++pc;
--width;
}
else {
*--s = '-';
}
}
return pc + prints (out, s, width, pad);
}
#if 0
int fprintf(__FILE *stream, const char *format, ...)
{
return 0;
}
#endif
int printk_va(char **out, const char *format, va_list args )
{
register int width, pad;
register int pc = 0;
char scr[2];
for (; *format != 0; ++format) {
if (*format == '%') {
++format;
width = pad = 0;
if (*format == '\0') break;
if (*format == '%') goto out;
if (*format == '-') {
++format;
pad = PAD_RIGHT;
}
while (*format == '0') {
++format;
pad |= PAD_ZERO;
}
for ( ; *format >= '0' && *format <= '9'; ++format) {
width *= 10;
width += *format - '0';
}
if( *format == 's' ) {
register char *s = (char *)va_arg( args, int );
pc += prints (out, s?s:"(null)", width, pad);
continue;
}
if( *format == 'd' ) {
pc += printi (out, va_arg( args, int ), 10, 1, width, pad, 'a');
continue;
}
if( *format == 'p' ) {
pad = 8;
pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'a');
continue;
}
if( *format == 'x' ) {
pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'a');
continue;
}
if( *format == 'X' ) {
pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'A');
continue;
}
if( *format == 'u' ) {
pc += printi (out, va_arg( args, int ), 10, 0, width, pad, 'a');
continue;
}
if( *format == 'c' ) {
/* char are converted to int then pushed on the stack */
scr[0] = (char)va_arg( args, int );
scr[1] = '\0';
pc += prints (out, scr, width, pad);
continue;
}
}
else {
out:
printchar (out, *format);
++pc;
}
}
if (out) **out = '\0';
va_end( args );
return pc;
}
int printk(const char *format, ...)
{
va_list args;
va_start( args, format );
return printk_va( 0, format, args );
}
#ifndef __ARM__
int sprintf(char *out, const char *format, ...)
{
va_list args;
va_start( args, format );
return printk_va( &out, format, args );
}
#endif
#ifdef TEST_PRINTF
int main(void)
{
char *ptr = "Hello world!";
char *np = 0;
int i = 5;
unsigned int bs = sizeof(int)*8;
int mi;
char buf[80];
mi = (1 << (bs-1)) + 1;
printf("%s\n", ptr);
printf("printf test\n");
printf("%s is null pointer\n", np);
printf("%d = 5\n", i);
printf("%d = - max int\n", mi);
printf("char %c = 'a'\n", 'a');
printf("hex %x = ff\n", 0xff);
printf("hex %02x = 00\n", 0);
printf("signed %d = unsigned %u = hex %x\n", -3, -3, -3);
printf("%d %s(s)%", 0, "message");
printf("\n");
printf("%d %s(s) with %%\n", 0, "message");
sprintf(buf, "justif: \"%-10s\"\n", "left"); printf("%s", buf);
sprintf(buf, "justif: \"%10s\"\n", "right"); printf("%s", buf);
sprintf(buf, " 3: %04d zero padded\n", 3); printf("%s", buf);
sprintf(buf, " 3: %-4d left justif.\n", 3); printf("%s", buf);
sprintf(buf, " 3: %4d right justif.\n", 3); printf("%s", buf);
sprintf(buf, "-3: %04d zero padded\n", -3); printf("%s", buf);
sprintf(buf, "-3: %-4d left justif.\n", -3); printf("%s", buf);
sprintf(buf, "-3: %4d right justif.\n", -3); printf("%s", buf);
return 0;
}
/*
* if you compile this file with
* gcc -Wall $(YOUR_C_OPTIONS) -DTEST_PRINTF -c printf.c
* you will get a normal warning:
* printf.c:214: warning: spurious trailing `%' in format
* this line is testing an invalid % at the end of the format string.
*
* this should display (on 32bit int machine) :
*
* Hello world!
* printf test
* (null) is null pointer
* 5 = 5
* -2147483647 = - max int
* char a = 'a'
* hex ff = ff
* hex 00 = 00
* signed -3 = unsigned 4294967293 = hex fffffffd
* 0 message(s)
* 0 message(s) with %
* justif: "left "
* justif: " right"
* 3: 0003 zero padded
* 3: 3 left justif.
* 3: 3 right justif.
* -3: -003 zero padded
* -3: -3 left justif.
* -3: -3 right justif.
*/
#endif
| mit |
agent010101/agent010101.github.io | vendor/bundle/ruby/2.0.0/gems/ffi-1.9.8/ext/ffi_c/AbstractMemory.c | 88 | 34507 | /*
* Copyright (c) 2008, 2009, Wayne Meissner
* Copyright (C) 2009 Jake Douglas <jake@shiftedlabs.com>
* Copyright (C) 2008 Luc Heinrich <luc@honk-honk.com>
*
* Copyright (c) 2008-2013, Ruby FFI project contributors
* 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 Ruby FFI project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#ifndef _MSC_VER
# include <sys/param.h>
# include <stdint.h>
# include <stdbool.h>
#else
# include "win32/stdbool.h"
# include "win32/stdint.h"
#endif
#include <limits.h>
#include <ruby.h>
#include "rbffi.h"
#include "compat.h"
#include "AbstractMemory.h"
#include "Pointer.h"
#include "Function.h"
#include "LongDouble.h"
static inline char* memory_address(VALUE self);
VALUE rbffi_AbstractMemoryClass = Qnil;
static VALUE NullPointerErrorClass = Qnil;
static ID id_to_ptr = 0, id_plus = 0, id_call = 0;
static VALUE
memory_allocate(VALUE klass)
{
AbstractMemory* memory;
VALUE obj;
obj = Data_Make_Struct(klass, AbstractMemory, NULL, -1, memory);
memory->flags = MEM_RD | MEM_WR;
return obj;
}
#define VAL(x, swap) (unlikely(((memory->flags & MEM_SWAP) != 0)) ? swap((x)) : (x))
#define NUM_OP(name, type, toNative, fromNative, swap) \
static void memory_op_put_##name(AbstractMemory* memory, long off, VALUE value); \
static void \
memory_op_put_##name(AbstractMemory* memory, long off, VALUE value) \
{ \
type tmp = (type) VAL(toNative(value), swap); \
checkWrite(memory); \
checkBounds(memory, off, sizeof(type)); \
memcpy(memory->address + off, &tmp, sizeof(tmp)); \
} \
static VALUE memory_put_##name(VALUE self, VALUE offset, VALUE value); \
static VALUE \
memory_put_##name(VALUE self, VALUE offset, VALUE value) \
{ \
AbstractMemory* memory; \
Data_Get_Struct(self, AbstractMemory, memory); \
memory_op_put_##name(memory, NUM2LONG(offset), value); \
return self; \
} \
static VALUE memory_write_##name(VALUE self, VALUE value); \
static VALUE \
memory_write_##name(VALUE self, VALUE value) \
{ \
AbstractMemory* memory; \
Data_Get_Struct(self, AbstractMemory, memory); \
memory_op_put_##name(memory, 0, value); \
return self; \
} \
static VALUE memory_op_get_##name(AbstractMemory* memory, long off); \
static VALUE \
memory_op_get_##name(AbstractMemory* memory, long off) \
{ \
type tmp; \
checkRead(memory); \
checkBounds(memory, off, sizeof(type)); \
memcpy(&tmp, memory->address + off, sizeof(tmp)); \
return fromNative(VAL(tmp, swap)); \
} \
static VALUE memory_get_##name(VALUE self, VALUE offset); \
static VALUE \
memory_get_##name(VALUE self, VALUE offset) \
{ \
AbstractMemory* memory; \
Data_Get_Struct(self, AbstractMemory, memory); \
return memory_op_get_##name(memory, NUM2LONG(offset)); \
} \
static VALUE memory_read_##name(VALUE self); \
static VALUE \
memory_read_##name(VALUE self) \
{ \
AbstractMemory* memory; \
Data_Get_Struct(self, AbstractMemory, memory); \
return memory_op_get_##name(memory, 0); \
} \
static MemoryOp memory_op_##name = { memory_op_get_##name, memory_op_put_##name }; \
\
static VALUE memory_put_array_of_##name(VALUE self, VALUE offset, VALUE ary); \
static VALUE \
memory_put_array_of_##name(VALUE self, VALUE offset, VALUE ary) \
{ \
long count = RARRAY_LEN(ary); \
long off = NUM2LONG(offset); \
AbstractMemory* memory = MEMORY(self); \
long i; \
checkWrite(memory); \
checkBounds(memory, off, count * sizeof(type)); \
for (i = 0; i < count; i++) { \
type tmp = (type) VAL(toNative(RARRAY_PTR(ary)[i]), swap); \
memcpy(memory->address + off + (i * sizeof(type)), &tmp, sizeof(tmp)); \
} \
return self; \
} \
static VALUE memory_write_array_of_##name(VALUE self, VALUE ary); \
static VALUE \
memory_write_array_of_##name(VALUE self, VALUE ary) \
{ \
return memory_put_array_of_##name(self, INT2FIX(0), ary); \
} \
static VALUE memory_get_array_of_##name(VALUE self, VALUE offset, VALUE length); \
static VALUE \
memory_get_array_of_##name(VALUE self, VALUE offset, VALUE length) \
{ \
long count = NUM2LONG(length); \
long off = NUM2LONG(offset); \
AbstractMemory* memory = MEMORY(self); \
VALUE retVal = rb_ary_new2(count); \
long i; \
checkRead(memory); \
checkBounds(memory, off, count * sizeof(type)); \
for (i = 0; i < count; ++i) { \
type tmp; \
memcpy(&tmp, memory->address + off + (i * sizeof(type)), sizeof(tmp)); \
rb_ary_push(retVal, fromNative(VAL(tmp, swap))); \
} \
return retVal; \
} \
static VALUE memory_read_array_of_##name(VALUE self, VALUE length); \
static VALUE \
memory_read_array_of_##name(VALUE self, VALUE length) \
{ \
return memory_get_array_of_##name(self, INT2FIX(0), length); \
}
#define NOSWAP(x) (x)
#define bswap16(x) (((x) >> 8) & 0xff) | (((x) << 8) & 0xff00);
static inline int16_t
SWAPS16(int16_t x)
{
return bswap16(x);
}
static inline uint16_t
SWAPU16(uint16_t x)
{
return bswap16(x);
}
#if !defined(__GNUC__) || (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 3)
#define bswap32(x) \
(((x << 24) & 0xff000000) | \
((x << 8) & 0x00ff0000) | \
((x >> 8) & 0x0000ff00) | \
((x >> 24) & 0x000000ff))
#define bswap64(x) \
(((x << 56) & 0xff00000000000000ULL) | \
((x << 40) & 0x00ff000000000000ULL) | \
((x << 24) & 0x0000ff0000000000ULL) | \
((x << 8) & 0x000000ff00000000ULL) | \
((x >> 8) & 0x00000000ff000000ULL) | \
((x >> 24) & 0x0000000000ff0000ULL) | \
((x >> 40) & 0x000000000000ff00ULL) | \
((x >> 56) & 0x00000000000000ffULL))
static inline int32_t
SWAPS32(int32_t x)
{
return bswap32(x);
}
static inline uint32_t
SWAPU32(uint32_t x)
{
return bswap32(x);
}
static inline int64_t
SWAPS64(int64_t x)
{
return bswap64(x);
}
static inline uint64_t
SWAPU64(uint64_t x)
{
return bswap64(x);
}
#else
# define SWAPS32(x) ((int32_t) __builtin_bswap32(x))
# define SWAPU32(x) ((uint32_t) __builtin_bswap32(x))
# define SWAPS64(x) ((int64_t) __builtin_bswap64(x))
# define SWAPU64(x) ((uint64_t) __builtin_bswap64(x))
#endif
#if LONG_MAX > INT_MAX
# define SWAPSLONG SWAPS64
# define SWAPULONG SWAPU64
#else
# define SWAPSLONG SWAPS32
# define SWAPULONG SWAPU32
#endif
NUM_OP(int8, int8_t, NUM2INT, INT2NUM, NOSWAP);
NUM_OP(uint8, uint8_t, NUM2UINT, UINT2NUM, NOSWAP);
NUM_OP(int16, int16_t, NUM2INT, INT2NUM, SWAPS16);
NUM_OP(uint16, uint16_t, NUM2UINT, UINT2NUM, SWAPU16);
NUM_OP(int32, int32_t, NUM2INT, INT2NUM, SWAPS32);
NUM_OP(uint32, uint32_t, NUM2UINT, UINT2NUM, SWAPU32);
NUM_OP(int64, int64_t, NUM2LL, LL2NUM, SWAPS64);
NUM_OP(uint64, uint64_t, NUM2ULL, ULL2NUM, SWAPU64);
NUM_OP(long, long, NUM2LONG, LONG2NUM, SWAPSLONG);
NUM_OP(ulong, unsigned long, NUM2ULONG, ULONG2NUM, SWAPULONG);
NUM_OP(float32, float, NUM2DBL, rb_float_new, NOSWAP);
NUM_OP(float64, double, NUM2DBL, rb_float_new, NOSWAP);
NUM_OP(longdouble, long double, rbffi_num2longdouble, rbffi_longdouble_new, NOSWAP);
static inline void*
get_pointer_value(VALUE value)
{
const int type = TYPE(value);
if (type == T_DATA && rb_obj_is_kind_of(value, rbffi_PointerClass)) {
return memory_address(value);
} else if (type == T_NIL) {
return NULL;
} else if (type == T_FIXNUM) {
return (void *) (uintptr_t) FIX2ULONG(value);
} else if (type == T_BIGNUM) {
return (void *) (uintptr_t) NUM2ULL(value);
} else if (rb_respond_to(value, id_to_ptr)) {
return MEMORY_PTR(rb_funcall2(value, id_to_ptr, 0, NULL));
} else {
rb_raise(rb_eArgError, "value is not a pointer");
return NULL;
}
}
NUM_OP(pointer, void *, get_pointer_value, rbffi_Pointer_NewInstance, NOSWAP);
static inline uint8_t
rbffi_bool_value(VALUE value)
{
return RTEST(value);
}
static inline VALUE
rbffi_bool_new(uint8_t value)
{
return (value & 1) != 0 ? Qtrue : Qfalse;
}
NUM_OP(bool, unsigned char, rbffi_bool_value, rbffi_bool_new, NOSWAP);
/*
* call-seq: memory.clear
* Set the memory to all-zero.
* @return [self]
*/
static VALUE
memory_clear(VALUE self)
{
AbstractMemory* ptr = MEMORY(self);
memset(ptr->address, 0, ptr->size);
return self;
}
/*
* call-seq: memory.size
* Return memory size in bytes (alias: #total)
* @return [Numeric]
*/
static VALUE
memory_size(VALUE self)
{
AbstractMemory* ptr;
Data_Get_Struct(self, AbstractMemory, ptr);
return LONG2NUM(ptr->size);
}
/*
* call-seq: memory.get_string(offset, length=nil)
* Return string contained in memory.
* @param [Numeric] offset point in buffer to start from
* @param [Numeric] length string's length in bytes. If nil, a (memory size - offset) length string is returned).
* @return [String]
* @raise {IndexError} if +length+ is too great
* @raise {NullPointerError} if memory not initialized
*/
static VALUE
memory_get_string(int argc, VALUE* argv, VALUE self)
{
VALUE length = Qnil, offset = Qnil;
AbstractMemory* ptr = MEMORY(self);
long off, len;
char* end;
int nargs = rb_scan_args(argc, argv, "11", &offset, &length);
off = NUM2LONG(offset);
len = nargs > 1 && length != Qnil ? NUM2LONG(length) : (ptr->size - off);
checkRead(ptr);
checkBounds(ptr, off, len);
end = memchr(ptr->address + off, 0, len);
return rb_tainted_str_new((char *) ptr->address + off,
(end != NULL ? end - ptr->address - off : len));
}
/*
* call-seq: memory.get_array_of_string(offset, count=nil)
* Return an array of strings contained in memory.
* @param [Numeric] offset point in memory to start from
* @param [Numeric] count number of strings to get. If nil, return all strings
* @return [Array<String>]
* @raise {IndexError} if +offset+ is too great
* @raise {NullPointerError} if memory not initialized
*/
static VALUE
memory_get_array_of_string(int argc, VALUE* argv, VALUE self)
{
VALUE offset = Qnil, countnum = Qnil, retVal = Qnil;
AbstractMemory* ptr;
long off;
int count;
rb_scan_args(argc, argv, "11", &offset, &countnum);
off = NUM2LONG(offset);
count = (countnum == Qnil ? 0 : NUM2INT(countnum));
retVal = rb_ary_new2(count);
Data_Get_Struct(self, AbstractMemory, ptr);
checkRead(ptr);
if (countnum != Qnil) {
int i;
checkBounds(ptr, off, count * sizeof (char*));
for (i = 0; i < count; ++i) {
const char* strptr = *((const char**) (ptr->address + off) + i);
rb_ary_push(retVal, (strptr == NULL ? Qnil : rb_tainted_str_new2(strptr)));
}
} else {
checkBounds(ptr, off, sizeof (char*));
for ( ; off < ptr->size - (long) sizeof (void *); off += (long) sizeof (void *)) {
const char* strptr = *(const char**) (ptr->address + off);
if (strptr == NULL) {
break;
}
rb_ary_push(retVal, rb_tainted_str_new2(strptr));
}
}
return retVal;
}
/*
* call-seq: memory.read_array_of_string(count=nil)
* Return an array of strings contained in memory. Same as:
* memory.get_array_of_string(0, count)
* @param [Numeric] count number of strings to get. If nil, return all strings
* @return [Array<String>]
*/
static VALUE
memory_read_array_of_string(int argc, VALUE* argv, VALUE self)
{
VALUE* rargv = ALLOCA_N(VALUE, argc + 1);
int i;
rargv[0] = INT2FIX(0);
for (i = 0; i < argc; i++) {
rargv[i + 1] = argv[i];
}
return memory_get_array_of_string(argc + 1, rargv, self);
}
/*
* call-seq: memory.put_string(offset, str)
* @param [Numeric] offset
* @param [String] str
* @return [self]
* @raise {SecurityError} when writing unsafe string to memory
* @raise {IndexError} if +offset+ is too great
* @raise {NullPointerError} if memory not initialized
* Put a string in memory.
*/
static VALUE
memory_put_string(VALUE self, VALUE offset, VALUE str)
{
AbstractMemory* ptr = MEMORY(self);
long off, len;
Check_Type(str, T_STRING);
off = NUM2LONG(offset);
len = RSTRING_LEN(str);
checkWrite(ptr);
checkBounds(ptr, off, len + 1);
memcpy(ptr->address + off, RSTRING_PTR(str), len);
*((char *) ptr->address + off + len) = '\0';
return self;
}
/*
* call-seq: memory.get_bytes(offset, length)
* Return string contained in memory.
* @param [Numeric] offset point in buffer to start from
* @param [Numeric] length string's length in bytes.
* @return [String]
* @raise {IndexError} if +length+ is too great
* @raise {NullPointerError} if memory not initialized
*/
static VALUE
memory_get_bytes(VALUE self, VALUE offset, VALUE length)
{
AbstractMemory* ptr = MEMORY(self);
long off, len;
off = NUM2LONG(offset);
len = NUM2LONG(length);
checkRead(ptr);
checkBounds(ptr, off, len);
return rb_tainted_str_new((char *) ptr->address + off, len);
}
/*
* call-seq: memory.put_bytes(offset, str, index=0, length=nil)
* Put a string in memory.
* @param [Numeric] offset point in buffer to start from
* @param [String] str string to put to memory
* @param [Numeric] index
* @param [Numeric] length string's length in bytes. If nil, a (memory size - offset) length string is returned).
* @return [self]
* @raise {IndexError} if +length+ is too great
* @raise {NullPointerError} if memory not initialized
* @raise {RangeError} if +index+ is negative, or if index+length is greater than size of string
* @raise {SecurityError} when writing unsafe string to memory
*/
static VALUE
memory_put_bytes(int argc, VALUE* argv, VALUE self)
{
AbstractMemory* ptr = MEMORY(self);
VALUE offset = Qnil, str = Qnil, rbIndex = Qnil, rbLength = Qnil;
long off, len, idx;
int nargs = rb_scan_args(argc, argv, "22", &offset, &str, &rbIndex, &rbLength);
Check_Type(str, T_STRING);
off = NUM2LONG(offset);
idx = nargs > 2 ? NUM2LONG(rbIndex) : 0;
if (idx < 0) {
rb_raise(rb_eRangeError, "index canot be less than zero");
return Qnil;
}
len = nargs > 3 ? NUM2LONG(rbLength) : (RSTRING_LEN(str) - idx);
if ((idx + len) > RSTRING_LEN(str)) {
rb_raise(rb_eRangeError, "index+length is greater than size of string");
return Qnil;
}
checkWrite(ptr);
checkBounds(ptr, off, len);
if (rb_safe_level() >= 1 && OBJ_TAINTED(str)) {
rb_raise(rb_eSecurityError, "Writing unsafe string to memory");
return Qnil;
}
memcpy(ptr->address + off, RSTRING_PTR(str) + idx, len);
return self;
}
/*
* call-seq: memory.read_bytes(length)
* @param [Numeric] length of string to return
* @return [String]
* equivalent to :
* memory.get_bytes(0, length)
*/
static VALUE
memory_read_bytes(VALUE self, VALUE length)
{
return memory_get_bytes(self, INT2FIX(0), length);
}
/*
* call-seq: memory.write_bytes(str, index=0, length=nil)
* @param [String] str string to put to memory
* @param [Numeric] index
* @param [Numeric] length string's length in bytes. If nil, a (memory size - offset) length string is returned).
* @return [self]
* equivalent to :
* memory.put_bytes(0, str, index, length)
*/
static VALUE
memory_write_bytes(int argc, VALUE* argv, VALUE self)
{
VALUE* wargv = ALLOCA_N(VALUE, argc + 1);
int i;
wargv[0] = INT2FIX(0);
for (i = 0; i < argc; i++) {
wargv[i + 1] = argv[i];
}
return memory_put_bytes(argc + 1, wargv, self);
}
/*
* call-seq: memory.type_size
* @return [Numeric] type size in bytes
* Get the memory's type size.
*/
static VALUE
memory_type_size(VALUE self)
{
AbstractMemory* ptr;
Data_Get_Struct(self, AbstractMemory, ptr);
return INT2NUM(ptr->typeSize);
}
/*
* Document-method: []
* call-seq: memory[idx]
* @param [Numeric] idx index to access in memory
* @return
* Memory read accessor.
*/
static VALUE
memory_aref(VALUE self, VALUE idx)
{
AbstractMemory* ptr;
VALUE rbOffset = Qnil;
Data_Get_Struct(self, AbstractMemory, ptr);
rbOffset = ULONG2NUM(NUM2ULONG(idx) * ptr->typeSize);
return rb_funcall2(self, id_plus, 1, &rbOffset);
}
static inline char*
memory_address(VALUE obj)
{
return ((AbstractMemory *) DATA_PTR(obj))->address;
}
static VALUE
memory_copy_from(VALUE self, VALUE rbsrc, VALUE rblen)
{
AbstractMemory* dst;
Data_Get_Struct(self, AbstractMemory, dst);
memcpy(dst->address, rbffi_AbstractMemory_Cast(rbsrc, rbffi_AbstractMemoryClass)->address, NUM2INT(rblen));
return self;
}
AbstractMemory*
rbffi_AbstractMemory_Cast(VALUE obj, VALUE klass)
{
if (rb_obj_is_kind_of(obj, klass)) {
AbstractMemory* memory;
Data_Get_Struct(obj, AbstractMemory, memory);
return memory;
}
rb_raise(rb_eArgError, "Invalid Memory object");
return NULL;
}
void
rbffi_AbstractMemory_Error(AbstractMemory *mem, int op)
{
VALUE rbErrorClass = mem->address == NULL ? NullPointerErrorClass : rb_eRuntimeError;
if (op == MEM_RD) {
rb_raise(rbErrorClass, "invalid memory read at address=%p", mem->address);
} else if (op == MEM_WR) {
rb_raise(rbErrorClass, "invalid memory write at address=%p", mem->address);
} else {
rb_raise(rbErrorClass, "invalid memory access at address=%p", mem->address);
}
}
static VALUE
memory_op_get_strptr(AbstractMemory* ptr, long offset)
{
void* tmp = NULL;
if (ptr != NULL && ptr->address != NULL) {
checkRead(ptr);
checkBounds(ptr, offset, sizeof(tmp));
memcpy(&tmp, ptr->address + offset, sizeof(tmp));
}
return tmp != NULL ? rb_tainted_str_new2(tmp) : Qnil;
}
static void
memory_op_put_strptr(AbstractMemory* ptr, long offset, VALUE value)
{
rb_raise(rb_eArgError, "Cannot set :string fields");
}
static MemoryOp memory_op_strptr = { memory_op_get_strptr, memory_op_put_strptr };
MemoryOps rbffi_AbstractMemoryOps = {
&memory_op_int8, /*.int8 */
&memory_op_uint8, /* .uint8 */
&memory_op_int16, /* .int16 */
&memory_op_uint16, /* .uint16 */
&memory_op_int32, /* .int32 */
&memory_op_uint32, /* .uint32 */
&memory_op_int64, /* .int64 */
&memory_op_uint64, /* .uint64 */
&memory_op_long, /* .slong */
&memory_op_ulong, /* .uslong */
&memory_op_float32, /* .float32 */
&memory_op_float64, /* .float64 */
&memory_op_longdouble, /* .longdouble */
&memory_op_pointer, /* .pointer */
&memory_op_strptr, /* .strptr */
&memory_op_bool /* .boolOp */
};
void
rbffi_AbstractMemory_Init(VALUE moduleFFI)
{
/*
* Document-class: FFI::AbstractMemory
*
* {AbstractMemory} is the base class for many memory management classes such as {Buffer}.
*
* This class has a lot of methods to work with integers :
* * put_int<i>size</i>(offset, value)
* * get_int<i>size</i>(offset)
* * put_uint<i>size</i>(offset, value)
* * get_uint<i>size</i>(offset)
* * writeuint<i>size</i>(value)
* * read_int<i>size</i>
* * write_uint<i>size</i>(value)
* * read_uint<i>size</i>
* * put_array_of_int<i>size</i>(offset, ary)
* * get_array_of_int<i>size</i>(offset, length)
* * put_array_of_uint<i>size</i>(offset, ary)
* * get_array_of_uint<i>size</i>(offset, length)
* * write_array_of_int<i>size</i>(ary)
* * read_array_of_int<i>size</i>(length)
* * write_array_of_uint<i>size</i>(ary)
* * read_array_of_uint<i>size</i>(length)
* where _size_ is 8, 16, 32 or 64. Same methods exist for long type.
*
* Aliases exist : _char_ for _int8_, _short_ for _int16_, _int_ for _int32_ and <i>long_long</i> for _int64_.
*
* Others methods are listed below.
*/
VALUE classMemory = rb_define_class_under(moduleFFI, "AbstractMemory", rb_cObject);
rbffi_AbstractMemoryClass = classMemory;
/*
* Document-variable: FFI::AbstractMemory
*/
rb_global_variable(&rbffi_AbstractMemoryClass);
rb_define_alloc_func(classMemory, memory_allocate);
NullPointerErrorClass = rb_define_class_under(moduleFFI, "NullPointerError", rb_eRuntimeError);
/* Document-variable: NullPointerError */
rb_global_variable(&NullPointerErrorClass);
#undef INT
#define INT(type) \
rb_define_method(classMemory, "put_" #type, memory_put_##type, 2); \
rb_define_method(classMemory, "get_" #type, memory_get_##type, 1); \
rb_define_method(classMemory, "put_u" #type, memory_put_u##type, 2); \
rb_define_method(classMemory, "get_u" #type, memory_get_u##type, 1); \
rb_define_method(classMemory, "write_" #type, memory_write_##type, 1); \
rb_define_method(classMemory, "read_" #type, memory_read_##type, 0); \
rb_define_method(classMemory, "write_u" #type, memory_write_u##type, 1); \
rb_define_method(classMemory, "read_u" #type, memory_read_u##type, 0); \
rb_define_method(classMemory, "put_array_of_" #type, memory_put_array_of_##type, 2); \
rb_define_method(classMemory, "get_array_of_" #type, memory_get_array_of_##type, 2); \
rb_define_method(classMemory, "put_array_of_u" #type, memory_put_array_of_u##type, 2); \
rb_define_method(classMemory, "get_array_of_u" #type, memory_get_array_of_u##type, 2); \
rb_define_method(classMemory, "write_array_of_" #type, memory_write_array_of_##type, 1); \
rb_define_method(classMemory, "read_array_of_" #type, memory_read_array_of_##type, 1); \
rb_define_method(classMemory, "write_array_of_u" #type, memory_write_array_of_u##type, 1); \
rb_define_method(classMemory, "read_array_of_u" #type, memory_read_array_of_u##type, 1);
INT(int8);
INT(int16);
INT(int32);
INT(int64);
INT(long);
#define ALIAS(name, old) \
rb_define_alias(classMemory, "put_" #name, "put_" #old); \
rb_define_alias(classMemory, "get_" #name, "get_" #old); \
rb_define_alias(classMemory, "put_u" #name, "put_u" #old); \
rb_define_alias(classMemory, "get_u" #name, "get_u" #old); \
rb_define_alias(classMemory, "write_" #name, "write_" #old); \
rb_define_alias(classMemory, "read_" #name, "read_" #old); \
rb_define_alias(classMemory, "write_u" #name, "write_u" #old); \
rb_define_alias(classMemory, "read_u" #name, "read_u" #old); \
rb_define_alias(classMemory, "put_array_of_" #name, "put_array_of_" #old); \
rb_define_alias(classMemory, "get_array_of_" #name, "get_array_of_" #old); \
rb_define_alias(classMemory, "put_array_of_u" #name, "put_array_of_u" #old); \
rb_define_alias(classMemory, "get_array_of_u" #name, "get_array_of_u" #old); \
rb_define_alias(classMemory, "write_array_of_" #name, "write_array_of_" #old); \
rb_define_alias(classMemory, "read_array_of_" #name, "read_array_of_" #old); \
rb_define_alias(classMemory, "write_array_of_u" #name, "write_array_of_u" #old); \
rb_define_alias(classMemory, "read_array_of_u" #name, "read_array_of_u" #old);
ALIAS(char, int8);
ALIAS(short, int16);
ALIAS(int, int32);
ALIAS(long_long, int64);
/*
* Document-method: put_float32
* call-seq: memory.put_float32offset, value)
* @param [Numeric] offset
* @param [Numeric] value
* @return [self]
* Put +value+ as a 32-bit float in memory at offset +offset+ (alias: #put_float).
*/
rb_define_method(classMemory, "put_float32", memory_put_float32, 2);
/*
* Document-method: get_float32
* call-seq: memory.get_float32(offset)
* @param [Numeric] offset
* @return [Float]
* Get a 32-bit float from memory at offset +offset+ (alias: #get_float).
*/
rb_define_method(classMemory, "get_float32", memory_get_float32, 1);
rb_define_alias(classMemory, "put_float", "put_float32");
rb_define_alias(classMemory, "get_float", "get_float32");
/*
* Document-method: write_float
* call-seq: memory.write_float(value)
* @param [Numeric] value
* @return [self]
* Write +value+ as a 32-bit float in memory.
*
* Same as:
* memory.put_float(0, value)
*/
rb_define_method(classMemory, "write_float", memory_write_float32, 1);
/*
* Document-method: read_float
* call-seq: memory.read_float
* @return [Float]
* Read a 32-bit float from memory.
*
* Same as:
* memory.get_float(0)
*/
rb_define_method(classMemory, "read_float", memory_read_float32, 0);
/*
* Document-method: put_array_of_float32
* call-seq: memory.put_array_of_float32(offset, ary)
* @param [Numeric] offset
* @param [Array<Numeric>] ary
* @return [self]
* Put values from +ary+ as 32-bit floats in memory from offset +offset+ (alias: #put_array_of_float).
*/
rb_define_method(classMemory, "put_array_of_float32", memory_put_array_of_float32, 2);
/*
* Document-method: get_array_of_float32
* call-seq: memory.get_array_of_float32(offset, length)
* @param [Numeric] offset
* @param [Numeric] length number of Float to get
* @return [Array<Float>]
* Get 32-bit floats in memory from offset +offset+ (alias: #get_array_of_float).
*/
rb_define_method(classMemory, "get_array_of_float32", memory_get_array_of_float32, 2);
/*
* Document-method: write_array_of_float
* call-seq: memory.write_array_of_float(ary)
* @param [Array<Numeric>] ary
* @return [self]
* Write values from +ary+ as 32-bit floats in memory.
*
* Same as:
* memory.put_array_of_float(0, ary)
*/
rb_define_method(classMemory, "write_array_of_float", memory_write_array_of_float32, 1);
/*
* Document-method: read_array_of_float
* call-seq: memory.read_array_of_float(length)
* @param [Numeric] length number of Float to read
* @return [Array<Float>]
* Read 32-bit floats from memory.
*
* Same as:
* memory.get_array_of_float(0, ary)
*/
rb_define_method(classMemory, "read_array_of_float", memory_read_array_of_float32, 1);
rb_define_alias(classMemory, "put_array_of_float", "put_array_of_float32");
rb_define_alias(classMemory, "get_array_of_float", "get_array_of_float32");
/*
* Document-method: put_float64
* call-seq: memory.put_float64(offset, value)
* @param [Numeric] offset
* @param [Numeric] value
* @return [self]
* Put +value+ as a 64-bit float (double) in memory at offset +offset+ (alias: #put_double).
*/
rb_define_method(classMemory, "put_float64", memory_put_float64, 2);
/*
* Document-method: get_float64
* call-seq: memory.get_float64(offset)
* @param [Numeric] offset
* @return [Float]
* Get a 64-bit float (double) from memory at offset +offset+ (alias: #get_double).
*/
rb_define_method(classMemory, "get_float64", memory_get_float64, 1);
rb_define_alias(classMemory, "put_double", "put_float64");
rb_define_alias(classMemory, "get_double", "get_float64");
/*
* Document-method: write_double
* call-seq: memory.write_double(value)
* @param [Numeric] value
* @return [self]
* Write +value+ as a 64-bit float (double) in memory.
*
* Same as:
* memory.put_double(0, value)
*/
rb_define_method(classMemory, "write_double", memory_write_float64, 1);
/*
* Document-method: read_double
* call-seq: memory.read_double
* @return [Float]
* Read a 64-bit float (double) from memory.
*
* Same as:
* memory.get_double(0)
*/
rb_define_method(classMemory, "read_double", memory_read_float64, 0);
/*
* Document-method: put_array_of_float64
* call-seq: memory.put_array_of_float64(offset, ary)
* @param [Numeric] offset
* @param [Array<Numeric>] ary
* @return [self]
* Put values from +ary+ as 64-bit floats (doubles) in memory from offset +offset+ (alias: #put_array_of_double).
*/
rb_define_method(classMemory, "put_array_of_float64", memory_put_array_of_float64, 2);
/*
* Document-method: get_array_of_float64
* call-seq: memory.get_array_of_float64(offset, length)
* @param [Numeric] offset
* @param [Numeric] length number of Float to get
* @return [Array<Float>]
* Get 64-bit floats (doubles) in memory from offset +offset+ (alias: #get_array_of_double).
*/
rb_define_method(classMemory, "get_array_of_float64", memory_get_array_of_float64, 2);
/*
* Document-method: write_array_of_double
* call-seq: memory.write_array_of_double(ary)
* @param [Array<Numeric>] ary
* @return [self]
* Write values from +ary+ as 64-bit floats (doubles) in memory.
*
* Same as:
* memory.put_array_of_double(0, ary)
*/
rb_define_method(classMemory, "write_array_of_double", memory_write_array_of_float64, 1);
/*
* Document-method: read_array_of_double
* call-seq: memory.read_array_of_double(length)
* @param [Numeric] length number of Float to read
* @return [Array<Float>]
* Read 64-bit floats (doubles) from memory.
*
* Same as:
* memory.get_array_of_double(0, ary)
*/
rb_define_method(classMemory, "read_array_of_double", memory_read_array_of_float64, 1);
rb_define_alias(classMemory, "put_array_of_double", "put_array_of_float64");
rb_define_alias(classMemory, "get_array_of_double", "get_array_of_float64");
/*
* Document-method: put_pointer
* call-seq: memory.put_pointer(offset, value)
* @param [Numeric] offset
* @param [nil,Pointer, Integer, #to_ptr] value
* @return [self]
* Put +value+ in memory from +offset+..
*/
rb_define_method(classMemory, "put_pointer", memory_put_pointer, 2);
/*
* Document-method: get_pointer
* call-seq: memory.get_pointer(offset)
* @param [Numeric] offset
* @return [Pointer]
* Get a {Pointer} to the memory from +offset+.
*/
rb_define_method(classMemory, "get_pointer", memory_get_pointer, 1);
/*
* Document-method: write_pointer
* call-seq: memory.write_pointer(value)
* @param [nil,Pointer, Integer, #to_ptr] value
* @return [self]
* Write +value+ in memory.
*
* Equivalent to:
* memory.put_pointer(0, value)
*/
rb_define_method(classMemory, "write_pointer", memory_write_pointer, 1);
/*
* Document-method: read_pointer
* call-seq: memory.read_pointer
* @return [Pointer]
* Get a {Pointer} to the memory from base address.
*
* Equivalent to:
* memory.get_pointer(0)
*/
rb_define_method(classMemory, "read_pointer", memory_read_pointer, 0);
/*
* Document-method: put_array_of_pointer
* call-seq: memory.put_array_of_pointer(offset, ary)
* @param [Numeric] offset
* @param [Array<#to_ptr>] ary
* @return [self]
* Put an array of {Pointer} into memory from +offset+.
*/
rb_define_method(classMemory, "put_array_of_pointer", memory_put_array_of_pointer, 2);
/*
* Document-method: get_array_of_pointer
* call-seq: memory.get_array_of_pointer(offset, length)
* @param [Numeric] offset
* @param [Numeric] length
* @return [Array<Pointer>]
* Get an array of {Pointer} of length +length+ from +offset+.
*/
rb_define_method(classMemory, "get_array_of_pointer", memory_get_array_of_pointer, 2);
/*
* Document-method: write_array_of_pointer
* call-seq: memory.write_array_of_pointer(ary)
* @param [Array<#to_ptr>] ary
* @return [self]
* Write an array of {Pointer} into memory from +offset+.
*
* Same as :
* memory.put_array_of_pointer(0, ary)
*/
rb_define_method(classMemory, "write_array_of_pointer", memory_write_array_of_pointer, 1);
/*
* Document-method: read_array_of_pointer
* call-seq: memory.read_array_of_pointer(length)
* @param [Numeric] length
* @return [Array<Pointer>]
* Read an array of {Pointer} of length +length+.
*
* Same as:
* memory.get_array_of_pointer(0, length)
*/
rb_define_method(classMemory, "read_array_of_pointer", memory_read_array_of_pointer, 1);
rb_define_method(classMemory, "get_string", memory_get_string, -1);
rb_define_method(classMemory, "put_string", memory_put_string, 2);
rb_define_method(classMemory, "get_bytes", memory_get_bytes, 2);
rb_define_method(classMemory, "put_bytes", memory_put_bytes, -1);
rb_define_method(classMemory, "read_bytes", memory_read_bytes, 1);
rb_define_method(classMemory, "write_bytes", memory_write_bytes, -1);
rb_define_method(classMemory, "get_array_of_string", memory_get_array_of_string, -1);
rb_define_method(classMemory, "clear", memory_clear, 0);
rb_define_method(classMemory, "total", memory_size, 0);
rb_define_alias(classMemory, "size", "total");
rb_define_method(classMemory, "type_size", memory_type_size, 0);
rb_define_method(classMemory, "[]", memory_aref, 1);
rb_define_method(classMemory, "__copy_from__", memory_copy_from, 2);
id_to_ptr = rb_intern("to_ptr");
id_call = rb_intern("call");
id_plus = rb_intern("+");
}
| mit |
havu73/cosc301-proj04 | mp.c | 354 | 3441 | // Multiprocessor support
// Search memory for MP description structures.
// http://developer.intel.com/design/pentium/datashts/24201606.pdf
#include "types.h"
#include "defs.h"
#include "param.h"
#include "memlayout.h"
#include "mp.h"
#include "x86.h"
#include "mmu.h"
#include "proc.h"
struct cpu cpus[NCPU];
static struct cpu *bcpu;
int ismp;
int ncpu;
uchar ioapicid;
int
mpbcpu(void)
{
return bcpu-cpus;
}
static uchar
sum(uchar *addr, int len)
{
int i, sum;
sum = 0;
for(i=0; i<len; i++)
sum += addr[i];
return sum;
}
// Look for an MP structure in the len bytes at addr.
static struct mp*
mpsearch1(uint a, int len)
{
uchar *e, *p, *addr;
addr = p2v(a);
e = addr+len;
for(p = addr; p < e; p += sizeof(struct mp))
if(memcmp(p, "_MP_", 4) == 0 && sum(p, sizeof(struct mp)) == 0)
return (struct mp*)p;
return 0;
}
// Search for the MP Floating Pointer Structure, which according to the
// spec is in one of the following three locations:
// 1) in the first KB of the EBDA;
// 2) in the last KB of system base memory;
// 3) in the BIOS ROM between 0xE0000 and 0xFFFFF.
static struct mp*
mpsearch(void)
{
uchar *bda;
uint p;
struct mp *mp;
bda = (uchar *) P2V(0x400);
if((p = ((bda[0x0F]<<8)| bda[0x0E]) << 4)){
if((mp = mpsearch1(p, 1024)))
return mp;
} else {
p = ((bda[0x14]<<8)|bda[0x13])*1024;
if((mp = mpsearch1(p-1024, 1024)))
return mp;
}
return mpsearch1(0xF0000, 0x10000);
}
// Search for an MP configuration table. For now,
// don't accept the default configurations (physaddr == 0).
// Check for correct signature, calculate the checksum and,
// if correct, check the version.
// To do: check extended table checksum.
static struct mpconf*
mpconfig(struct mp **pmp)
{
struct mpconf *conf;
struct mp *mp;
if((mp = mpsearch()) == 0 || mp->physaddr == 0)
return 0;
conf = (struct mpconf*) p2v((uint) mp->physaddr);
if(memcmp(conf, "PCMP", 4) != 0)
return 0;
if(conf->version != 1 && conf->version != 4)
return 0;
if(sum((uchar*)conf, conf->length) != 0)
return 0;
*pmp = mp;
return conf;
}
void
mpinit(void)
{
uchar *p, *e;
struct mp *mp;
struct mpconf *conf;
struct mpproc *proc;
struct mpioapic *ioapic;
bcpu = &cpus[0];
if((conf = mpconfig(&mp)) == 0)
return;
ismp = 1;
lapic = (uint*)conf->lapicaddr;
for(p=(uchar*)(conf+1), e=(uchar*)conf+conf->length; p<e; ){
switch(*p){
case MPPROC:
proc = (struct mpproc*)p;
if(ncpu != proc->apicid){
cprintf("mpinit: ncpu=%d apicid=%d\n", ncpu, proc->apicid);
ismp = 0;
}
if(proc->flags & MPBOOT)
bcpu = &cpus[ncpu];
cpus[ncpu].id = ncpu;
ncpu++;
p += sizeof(struct mpproc);
continue;
case MPIOAPIC:
ioapic = (struct mpioapic*)p;
ioapicid = ioapic->apicno;
p += sizeof(struct mpioapic);
continue;
case MPBUS:
case MPIOINTR:
case MPLINTR:
p += 8;
continue;
default:
cprintf("mpinit: unknown config type %x\n", *p);
ismp = 0;
}
}
if(!ismp){
// Didn't like what we found; fall back to no MP.
ncpu = 1;
lapic = 0;
ioapicid = 0;
return;
}
if(mp->imcrp){
// Bochs doesn't support IMCR, so this doesn't run on Bochs.
// But it would on real hardware.
outb(0x22, 0x70); // Select IMCR
outb(0x23, inb(0x23) | 1); // Mask external interrupts.
}
}
| mit |
RobertABT/heightmap | build/scipy/scipy/integrate/quadpack/dqagi.f | 109 | 8806 | subroutine dqagi(f,bound,inf,epsabs,epsrel,result,abserr,neval,
* ier,limit,lenw,last,iwork,work)
c***begin prologue dqagi
c***date written 800101 (yymmdd)
c***revision date 830518 (yymmdd)
c***category no. h2a3a1,h2a4a1
c***keywords automatic integrator, infinite intervals,
c general-purpose, transformation, extrapolation,
c globally adaptive
c***author piessens,robert,appl. math. & progr. div. - k.u.leuven
c de doncker,elise,appl. math. & progr. div. -k.u.leuven
c***purpose the routine calculates an approximation result to a given
c integral i = integral of f over (bound,+infinity)
c or i = integral of f over (-infinity,bound)
c or i = integral of f over (-infinity,+infinity)
c hopefully satisfying following claim for accuracy
c abs(i-result).le.max(epsabs,epsrel*abs(i)).
c***description
c
c integration over infinite intervals
c standard fortran subroutine
c
c parameters
c on entry
c f - double precision
c function subprogram defining the integrand
c function f(x). the actual name for f needs to be
c declared e x t e r n a l in the driver program.
c
c bound - double precision
c finite bound of integration range
c (has no meaning if interval is doubly-infinite)
c
c inf - integer
c indicating the kind of integration range involved
c inf = 1 corresponds to (bound,+infinity),
c inf = -1 to (-infinity,bound),
c inf = 2 to (-infinity,+infinity).
c
c epsabs - double precision
c absolute accuracy requested
c epsrel - double precision
c relative accuracy requested
c if epsabs.le.0
c and epsrel.lt.max(50*rel.mach.acc.,0.5d-28),
c the routine will end with ier = 6.
c
c
c on return
c result - double precision
c approximation to the integral
c
c abserr - double precision
c estimate of the modulus of the absolute error,
c which should equal or exceed abs(i-result)
c
c neval - integer
c number of integrand evaluations
c
c ier - integer
c ier = 0 normal and reliable termination of the
c routine. it is assumed that the requested
c accuracy has been achieved.
c - ier.gt.0 abnormal termination of the routine. the
c estimates for result and error are less
c reliable. it is assumed that the requested
c accuracy has not been achieved.
c error messages
c ier = 1 maximum number of subdivisions allowed
c has been achieved. one can allow more
c subdivisions by increasing the value of
c limit (and taking the according dimension
c adjustments into account). however, if
c this yields no improvement it is advised
c to analyze the integrand in order to
c determine the integration difficulties. if
c the position of a local difficulty can be
c determined (e.g. singularity,
c discontinuity within the interval) one
c will probably gain from splitting up the
c interval at this point and calling the
c integrator on the subranges. if possible,
c an appropriate special-purpose integrator
c should be used, which is designed for
c handling the type of difficulty involved.
c = 2 the occurrence of roundoff error is
c detected, which prevents the requested
c tolerance from being achieved.
c the error may be under-estimated.
c = 3 extremely bad integrand behaviour occurs
c at some points of the integration
c interval.
c = 4 the algorithm does not converge.
c roundoff error is detected in the
c extrapolation table.
c it is assumed that the requested tolerance
c cannot be achieved, and that the returned
c result is the best which can be obtained.
c = 5 the integral is probably divergent, or
c slowly convergent. it must be noted that
c divergence can occur with any other value
c of ier.
c = 6 the input is invalid, because
c (epsabs.le.0 and
c epsrel.lt.max(50*rel.mach.acc.,0.5d-28))
c or limit.lt.1 or leniw.lt.limit*4.
c result, abserr, neval, last are set to
c zero. exept when limit or leniw is
c invalid, iwork(1), work(limit*2+1) and
c work(limit*3+1) are set to zero, work(1)
c is set to a and work(limit+1) to b.
c
c dimensioning parameters
c limit - integer
c dimensioning parameter for iwork
c limit determines the maximum number of subintervals
c in the partition of the given integration interval
c (a,b), limit.ge.1.
c if limit.lt.1, the routine will end with ier = 6.
c
c lenw - integer
c dimensioning parameter for work
c lenw must be at least limit*4.
c if lenw.lt.limit*4, the routine will end
c with ier = 6.
c
c last - integer
c on return, last equals the number of subintervals
c produced in the subdivision process, which
c determines the number of significant elements
c actually in the work arrays.
c
c work arrays
c iwork - integer
c vector of dimension at least limit, the first
c k elements of which contain pointers
c to the error estimates over the subintervals,
c such that work(limit*3+iwork(1)),... ,
c work(limit*3+iwork(k)) form a decreasing
c sequence, with k = last if last.le.(limit/2+2), and
c k = limit+1-last otherwise
c
c work - double precision
c vector of dimension at least lenw
c on return
c work(1), ..., work(last) contain the left
c end points of the subintervals in the
c partition of (a,b),
c work(limit+1), ..., work(limit+last) contain
c the right end points,
c work(limit*2+1), ...,work(limit*2+last) contain the
c integral approximations over the subintervals,
c work(limit*3+1), ..., work(limit*3+last)
c contain the error estimates.
c***references (none)
c***routines called dqagie,xerror
c***end prologue dqagi
c
double precision abserr,bound,epsabs,epsrel,f,result,work
integer ier,inf,iwork,last,lenw,limit,lvl,l1,l2,l3,neval
c
dimension iwork(limit),work(lenw)
c
external f
c
c check validity of limit and lenw.
c
c***first executable statement dqagi
ier = 6
neval = 0
last = 0
result = 0.0d+00
abserr = 0.0d+00
if(limit.lt.1.or.lenw.lt.limit*4) go to 10
c
c prepare call for dqagie.
c
l1 = limit+1
l2 = limit+l1
l3 = limit+l2
c
call dqagie(f,bound,inf,epsabs,epsrel,limit,result,abserr,
* neval,ier,work(1),work(l1),work(l2),work(l3),iwork,last)
c
c call error handler if necessary.
c
lvl = 0
10 if(ier.eq.6) lvl = 1
if(ier.ne.0) call xerror('abnormal return from dqagi',26,ier,lvl)
return
end
| mit |
guillaumfloki/bodytracker | node_modules/node-sass/src/libsass/test/test_superselector.cpp | 877 | 2020 | #include "../ast.hpp"
#include "../context.hpp"
#include "../parser.hpp"
#include <string>
using namespace Sass;
Context ctx = Context(Context::Data());
Compound_Selector* compound_selector(std::string src)
{ return Parser::from_c_str(src.c_str(), ctx, "", Position()).parse_compound_selector(); }
Complex_Selector* complex_selector(std::string src)
{ return Parser::from_c_str(src.c_str(), ctx, "", Position()).parse_complex_selector(false); }
void check_compound(std::string s1, std::string s2)
{
std::cout << "Is "
<< s1
<< " a superselector of "
<< s2
<< "?\t"
<< compound_selector(s1 + ";")->is_superselector_of(compound_selector(s2 + ";"))
<< std::endl;
}
void check_complex(std::string s1, std::string s2)
{
std::cout << "Is "
<< s1
<< " a superselector of "
<< s2
<< "?\t"
<< complex_selector(s1 + ";")->is_superselector_of(complex_selector(s2 + ";"))
<< std::endl;
}
int main()
{
check_compound(".foo", ".foo.bar");
check_compound(".foo.bar", ".foo");
check_compound(".foo.bar", "div.foo");
check_compound(".foo", "div.foo");
check_compound("div.foo", ".foo");
check_compound("div.foo", "div.bar.foo");
check_compound("p.foo", "div.bar.foo");
check_compound(".hux", ".mumble");
std::cout << std::endl;
check_complex(".foo ~ .bar", ".foo + .bar");
check_complex(".foo .bar", ".foo + .bar");
check_complex(".foo .bar", ".foo > .bar");
check_complex(".foo .bar > .hux", ".foo.a .bar.b > .hux");
check_complex(".foo ~ .bar .hux", ".foo.a + .bar.b > .hux");
check_complex(".foo", ".bar .foo");
check_complex(".foo", ".foo.a");
check_complex(".foo.bar", ".foo");
check_complex(".foo .bar .hux", ".bar .hux");
check_complex(".foo ~ .bar .hux.x", ".foo.a + .bar.b > .hux.y");
check_complex(".foo ~ .bar .hux", ".foo.a + .bar.b > .mumble");
check_complex(".foo + .bar", ".foo ~ .bar");
check_complex("a c e", "a b c d e");
check_complex("c a e", "a b c d e");
return 0;
}
| mit |
suffolklibraries/sljekyll | vendor/bundle/ruby/2.4.0/gems/ffi-1.9.18/ext/ffi_c/libffi/testsuite/libffi.call/cls_7byte.c | 366 | 2768 | /* 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> 20030828 */
/* { dg-do run } */
#include "ffitest.h"
typedef struct cls_struct_7byte {
unsigned short a;
unsigned short b;
unsigned char c;
unsigned short d;
} 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;
printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d,
a2.a, a2.b, a2.c, a2.d,
result.a, result.b, result.c, result.d);
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[5];
ffi_type cls_struct_type;
ffi_type* dbl_arg_types[5];
cls_struct_type.size = 0;
cls_struct_type.alignment = 0;
cls_struct_type.type = FFI_TYPE_STRUCT;
cls_struct_type.elements = cls_struct_fields;
struct cls_struct_7byte g_dbl = { 127, 120, 1, 254 };
struct cls_struct_7byte f_dbl = { 12, 128, 9, 255 };
struct cls_struct_7byte res_dbl;
cls_struct_fields[0] = &ffi_type_ushort;
cls_struct_fields[1] = &ffi_type_ushort;
cls_struct_fields[2] = &ffi_type_uchar;
cls_struct_fields[3] = &ffi_type_ushort;
cls_struct_fields[4] = 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 254 12 128 9 255: 139 248 10 509" } */
printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
/* { dg-output "\nres: 139 248 10 509" } */
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 254 12 128 9 255: 139 248 10 509" } */
printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
/* { dg-output "\nres: 139 248 10 509" } */
exit(0);
}
| mit |
mozzria/mozzshare | src/qt/notificator.cpp | 367 | 9432 | #include "notificator.h"
#include <QMetaType>
#include <QVariant>
#include <QIcon>
#include <QApplication>
#include <QStyle>
#include <QByteArray>
#include <QSystemTrayIcon>
#include <QMessageBox>
#include <QTemporaryFile>
#include <QImageWriter>
#ifdef USE_DBUS
#include <QtDBus>
#include <stdint.h>
#endif
#ifdef Q_OS_MAC
#include <ApplicationServices/ApplicationServices.h>
extern bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret);
#endif
// https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128
const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;
Notificator::Notificator(const QString &programName, QSystemTrayIcon *trayicon, QWidget *parent):
QObject(parent),
parent(parent),
programName(programName),
mode(None),
trayIcon(trayicon)
#ifdef USE_DBUS
,interface(0)
#endif
{
if(trayicon && trayicon->supportsMessages())
{
mode = QSystemTray;
}
#ifdef USE_DBUS
interface = new QDBusInterface("org.freedesktop.Notifications",
"/org/freedesktop/Notifications", "org.freedesktop.Notifications");
if(interface->isValid())
{
mode = Freedesktop;
}
#endif
#ifdef Q_OS_MAC
// Check if Growl is installed (based on Qt's tray icon implementation)
CFURLRef cfurl;
OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
if (status != kLSApplicationNotFoundErr) {
CFBundleRef bundle = CFBundleCreate(0, cfurl);
if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) {
if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR("/Growl.app/")))
mode = Growl13;
else
mode = Growl12;
}
CFRelease(cfurl);
CFRelease(bundle);
}
#endif
}
Notificator::~Notificator()
{
#ifdef USE_DBUS
delete interface;
#endif
}
#ifdef USE_DBUS
// Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html
class FreedesktopImage
{
public:
FreedesktopImage() {}
FreedesktopImage(const QImage &img);
static int metaType();
// Image to variant that can be marshalled over DBus
static QVariant toVariant(const QImage &img);
private:
int width, height, stride;
bool hasAlpha;
int channels;
int bitsPerSample;
QByteArray image;
friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i);
friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i);
};
Q_DECLARE_METATYPE(FreedesktopImage);
// Image configuration settings
const int CHANNELS = 4;
const int BYTES_PER_PIXEL = 4;
const int BITS_PER_SAMPLE = 8;
FreedesktopImage::FreedesktopImage(const QImage &img):
width(img.width()),
height(img.height()),
stride(img.width() * BYTES_PER_PIXEL),
hasAlpha(true),
channels(CHANNELS),
bitsPerSample(BITS_PER_SAMPLE)
{
// Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format
QImage tmp = img.convertToFormat(QImage::Format_ARGB32);
const uint32_t *data = reinterpret_cast<const uint32_t*>(tmp.bits());
unsigned int num_pixels = width * height;
image.resize(num_pixels * BYTES_PER_PIXEL);
for(unsigned int ptr = 0; ptr < num_pixels; ++ptr)
{
image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; // R
image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8; // G
image[ptr*BYTES_PER_PIXEL+2] = data[ptr]; // B
image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; // A
}
}
QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i)
{
a.beginStructure();
a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i)
{
a.beginStructure();
a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;
a.endStructure();
return a;
}
int FreedesktopImage::metaType()
{
return qDBusRegisterMetaType<FreedesktopImage>();
}
QVariant FreedesktopImage::toVariant(const QImage &img)
{
FreedesktopImage fimg(img);
return QVariant(FreedesktopImage::metaType(), &fimg);
}
void Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
Q_UNUSED(cls);
// Arguments for DBus call:
QList<QVariant> args;
// Program Name:
args.append(programName);
// Unique ID of this notification type:
args.append(0U);
// Application Icon, empty string
args.append(QString());
// Summary
args.append(title);
// Body
args.append(text);
// Actions (none, actions are deprecated)
QStringList actions;
args.append(actions);
// Hints
QVariantMap hints;
// If no icon specified, set icon based on class
QIcon tmpicon;
if(icon.isNull())
{
QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
switch(cls)
{
case Information: sicon = QStyle::SP_MessageBoxInformation; break;
case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
default: break;
}
tmpicon = QApplication::style()->standardIcon(sicon);
}
else
{
tmpicon = icon;
}
hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());
args.append(hints);
// Timeout (in msec)
args.append(millisTimeout);
// "Fire and forget"
interface->callWithArgumentList(QDBus::NoBlock, "Notify", args);
}
#endif
void Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
Q_UNUSED(icon);
QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;
switch(cls) // Set icon based on class
{
case Information: sicon = QSystemTrayIcon::Information; break;
case Warning: sicon = QSystemTrayIcon::Warning; break;
case Critical: sicon = QSystemTrayIcon::Critical; break;
}
trayIcon->showMessage(title, text, sicon, millisTimeout);
}
// Based on Qt's tray icon implementation
#ifdef Q_OS_MAC
void Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon)
{
const QString script(
"tell application \"%5\"\n"
" set the allNotificationsList to {\"Notification\"}\n" // -- Make a list of all the notification types (all)
" set the enabledNotificationsList to {\"Notification\"}\n" // -- Make a list of the notifications (enabled)
" register as application \"%1\" all notifications allNotificationsList default notifications enabledNotificationsList\n" // -- Register our script with Growl
" notify with name \"Notification\" title \"%2\" description \"%3\" application name \"%1\"%4\n" // -- Send a Notification
"end tell"
);
QString notificationApp(QApplication::applicationName());
if (notificationApp.isEmpty())
notificationApp = "Application";
QPixmap notificationIconPixmap;
if (icon.isNull()) { // If no icon specified, set icon based on class
QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
switch (cls)
{
case Information: sicon = QStyle::SP_MessageBoxInformation; break;
case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
}
notificationIconPixmap = QApplication::style()->standardPixmap(sicon);
}
else {
QSize size = icon.actualSize(QSize(48, 48));
notificationIconPixmap = icon.pixmap(size);
}
QString notificationIcon;
QTemporaryFile notificationIconFile;
if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {
QImageWriter writer(¬ificationIconFile, "PNG");
if (writer.write(notificationIconPixmap.toImage()))
notificationIcon = QString(" image from location \"file://%1\"").arg(notificationIconFile.fileName());
}
QString quotedTitle(title), quotedText(text);
quotedTitle.replace("\\", "\\\\").replace("\"", "\\");
quotedText.replace("\\", "\\\\").replace("\"", "\\");
QString growlApp(this->mode == Notificator::Growl13 ? "Growl" : "GrowlHelperApp");
qt_mac_execute_apple_script(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp), 0);
}
#endif
void Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
switch(mode)
{
#ifdef USE_DBUS
case Freedesktop:
notifyDBus(cls, title, text, icon, millisTimeout);
break;
#endif
case QSystemTray:
notifySystray(cls, title, text, icon, millisTimeout);
break;
#ifdef Q_OS_MAC
case Growl12:
case Growl13:
notifyGrowl(cls, title, text, icon);
break;
#endif
default:
if(cls == Critical)
{
// Fall back to old fashioned pop-up dialog if critical and no other notification available
QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);
}
break;
}
}
| mit |
kakashidinho/HQEngine | HQEngine/Source/ImagesLoader/jpeg-8d/jidctflt.c | 115 | 8554 | /*
* jidctflt.c
*
* Copyright (C) 1994-1998, Thomas G. Lane.
* Modified 2010 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains a floating-point implementation of the
* inverse DCT (Discrete Cosine Transform). In the IJG code, this routine
* must also perform dequantization of the input coefficients.
*
* This implementation should be more accurate than either of the integer
* IDCT implementations. However, it may not give the same results on all
* machines because of differences in roundoff behavior. Speed will depend
* on the hardware's floating point capacity.
*
* A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
* on each row (or vice versa, but it's more convenient to emit a row at
* a time). Direct algorithms are also available, but they are much more
* complex and seem not to be any faster when reduced to code.
*
* This implementation is based on Arai, Agui, and Nakajima's algorithm for
* scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
* Japanese, but the algorithm is described in the Pennebaker & Mitchell
* JPEG textbook (see REFERENCES section in file README). The following code
* is based directly on figure 4-8 in P&M.
* While an 8-point DCT cannot be done in less than 11 multiplies, it is
* possible to arrange the computation so that many of the multiplies are
* simple scalings of the final outputs. These multiplies can then be
* folded into the multiplications or divisions by the JPEG quantization
* table entries. The AA&N method leaves only 5 multiplies and 29 adds
* to be done in the DCT itself.
* The primary disadvantage of this method is that with a fixed-point
* implementation, accuracy is lost due to imprecise representation of the
* scaled quantization values. However, that problem does not arise if
* we use floating point arithmetic.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jdct.h" /* Private declarations for DCT subsystem */
#ifdef DCT_FLOAT_SUPPORTED
/*
* This module is specialized to the case DCTSIZE = 8.
*/
#if DCTSIZE != 8
Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
#endif
/* Dequantize a coefficient by multiplying it by the multiplier-table
* entry; produce a float result.
*/
#define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
/*
* Perform dequantization and inverse DCT on one block of coefficients.
*/
GLOBAL(void)
jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block,
JSAMPARRAY output_buf, JDIMENSION output_col)
{
FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
FAST_FLOAT z5, z10, z11, z12, z13;
JCOEFPTR inptr;
FLOAT_MULT_TYPE * quantptr;
FAST_FLOAT * wsptr;
JSAMPROW outptr;
JSAMPLE *range_limit = cinfo->sample_range_limit;
int ctr;
FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
/* Pass 1: process columns from input, store into work array. */
inptr = coef_block;
quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
wsptr = workspace;
for (ctr = DCTSIZE; ctr > 0; ctr--) {
/* Due to quantization, we will usually find that many of the input
* coefficients are zero, especially the AC terms. We can exploit this
* by short-circuiting the IDCT calculation for any column in which all
* the AC terms are zero. In that case each output is equal to the
* DC coefficient (with scale factor as needed).
* With typical images and quantization tables, half or more of the
* column DCT calculations can be simplified this way.
*/
if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
inptr[DCTSIZE*7] == 0) {
/* AC terms all zero */
FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
wsptr[DCTSIZE*0] = dcval;
wsptr[DCTSIZE*1] = dcval;
wsptr[DCTSIZE*2] = dcval;
wsptr[DCTSIZE*3] = dcval;
wsptr[DCTSIZE*4] = dcval;
wsptr[DCTSIZE*5] = dcval;
wsptr[DCTSIZE*6] = dcval;
wsptr[DCTSIZE*7] = dcval;
inptr++; /* advance pointers to next column */
quantptr++;
wsptr++;
continue;
}
/* Even part */
tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
tmp10 = tmp0 + tmp2; /* phase 3 */
tmp11 = tmp0 - tmp2;
tmp13 = tmp1 + tmp3; /* phases 5-3 */
tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
tmp0 = tmp10 + tmp13; /* phase 2 */
tmp3 = tmp10 - tmp13;
tmp1 = tmp11 + tmp12;
tmp2 = tmp11 - tmp12;
/* Odd part */
tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
z13 = tmp6 + tmp5; /* phase 6 */
z10 = tmp6 - tmp5;
z11 = tmp4 + tmp7;
z12 = tmp4 - tmp7;
tmp7 = z11 + z13; /* phase 5 */
tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
tmp10 = z5 - z12 * ((FAST_FLOAT) 1.082392200); /* 2*(c2-c6) */
tmp12 = z5 - z10 * ((FAST_FLOAT) 2.613125930); /* 2*(c2+c6) */
tmp6 = tmp12 - tmp7; /* phase 2 */
tmp5 = tmp11 - tmp6;
tmp4 = tmp10 - tmp5;
wsptr[DCTSIZE*0] = tmp0 + tmp7;
wsptr[DCTSIZE*7] = tmp0 - tmp7;
wsptr[DCTSIZE*1] = tmp1 + tmp6;
wsptr[DCTSIZE*6] = tmp1 - tmp6;
wsptr[DCTSIZE*2] = tmp2 + tmp5;
wsptr[DCTSIZE*5] = tmp2 - tmp5;
wsptr[DCTSIZE*3] = tmp3 + tmp4;
wsptr[DCTSIZE*4] = tmp3 - tmp4;
inptr++; /* advance pointers to next column */
quantptr++;
wsptr++;
}
/* Pass 2: process rows from work array, store into output array. */
wsptr = workspace;
for (ctr = 0; ctr < DCTSIZE; ctr++) {
outptr = output_buf[ctr] + output_col;
/* Rows of zeroes can be exploited in the same way as we did with columns.
* However, the column calculation has created many nonzero AC terms, so
* the simplification applies less often (typically 5% to 10% of the time).
* And testing floats for zero is relatively expensive, so we don't bother.
*/
/* Even part */
/* Apply signed->unsigned and prepare float->int conversion */
z5 = wsptr[0] + ((FAST_FLOAT) CENTERJSAMPLE + (FAST_FLOAT) 0.5);
tmp10 = z5 + wsptr[4];
tmp11 = z5 - wsptr[4];
tmp13 = wsptr[2] + wsptr[6];
tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
tmp0 = tmp10 + tmp13;
tmp3 = tmp10 - tmp13;
tmp1 = tmp11 + tmp12;
tmp2 = tmp11 - tmp12;
/* Odd part */
z13 = wsptr[5] + wsptr[3];
z10 = wsptr[5] - wsptr[3];
z11 = wsptr[1] + wsptr[7];
z12 = wsptr[1] - wsptr[7];
tmp7 = z11 + z13;
tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
tmp10 = z5 - z12 * ((FAST_FLOAT) 1.082392200); /* 2*(c2-c6) */
tmp12 = z5 - z10 * ((FAST_FLOAT) 2.613125930); /* 2*(c2+c6) */
tmp6 = tmp12 - tmp7;
tmp5 = tmp11 - tmp6;
tmp4 = tmp10 - tmp5;
/* Final output stage: float->int conversion and range-limit */
outptr[0] = range_limit[((int) (tmp0 + tmp7)) & RANGE_MASK];
outptr[7] = range_limit[((int) (tmp0 - tmp7)) & RANGE_MASK];
outptr[1] = range_limit[((int) (tmp1 + tmp6)) & RANGE_MASK];
outptr[6] = range_limit[((int) (tmp1 - tmp6)) & RANGE_MASK];
outptr[2] = range_limit[((int) (tmp2 + tmp5)) & RANGE_MASK];
outptr[5] = range_limit[((int) (tmp2 - tmp5)) & RANGE_MASK];
outptr[3] = range_limit[((int) (tmp3 + tmp4)) & RANGE_MASK];
outptr[4] = range_limit[((int) (tmp3 - tmp4)) & RANGE_MASK];
wsptr += DCTSIZE; /* advance pointer to next row */
}
}
#endif /* DCT_FLOAT_SUPPORTED */
| mit |
tm011064/wrongnumberproject | cocos2d/tools/simulator/libsimulator/lib/platform/win32/PlayerWin.cpp | 116 | 1469 |
#include "PlayerWin.h"
USING_NS_CC;
PLAYER_NS_BEGIN
PlayerWin::PlayerWin()
: PlayerProtocol()
, _messageBoxService(nullptr)
, _menuService(nullptr)
, _editboxService(nullptr)
, _taskService(nullptr)
, _hwnd(NULL)
{
}
PlayerWin::~PlayerWin()
{
CC_SAFE_DELETE(_menuService);
CC_SAFE_DELETE(_messageBoxService);
CC_SAFE_DELETE(_fileDialogService);
}
PlayerWin *PlayerWin::createWithHwnd(HWND hWnd)
{
auto instance = new PlayerWin();
instance->_hwnd = hWnd;
instance->initServices();
return instance;
}
PlayerFileDialogServiceProtocol *PlayerWin::getFileDialogService()
{
return _fileDialogService;
}
PlayerMessageBoxServiceProtocol *PlayerWin::getMessageBoxService()
{
return _messageBoxService;
}
PlayerMenuServiceProtocol *PlayerWin::getMenuService()
{
return _menuService;
}
PlayerEditBoxServiceProtocol *PlayerWin::getEditBoxService()
{
return _editboxService;
}
PlayerTaskServiceProtocol *PlayerWin::getTaskService()
{
return _taskService;
}
// services
void PlayerWin::initServices()
{
CCASSERT(_menuService == nullptr, "CAN'T INITIALIZATION SERVICES MORE THAN ONCE");
_menuService = new PlayerMenuServiceWin(_hwnd);
_messageBoxService = new PlayerMessageBoxServiceWin(_hwnd);
_fileDialogService = new PlayerFileDialogServiceWin(_hwnd);
_editboxService = new PlayerEditBoxServiceWin(_hwnd);
_taskService = new PlayerTaskServiceWin(_hwnd);
}
PLAYER_NS_END
| mit |
ittscoin/ittscoin | need_for_windows/openssl-1.0.1o/apps/winrand.c | 125 | 5188 | /* apps/winrand.c */
/* ====================================================================
* Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/*-
* Usage: winrand [filename]
*
* Collects entropy from mouse movements and other events and writes
* random data to filename or .rnd
*/
#include <windows.h>
#include <openssl/opensslv.h>
#include <openssl/rand.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
const char *filename;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR cmdline, int iCmdShow)
{
static char appname[] = "OpenSSL";
HWND hwnd;
MSG msg;
WNDCLASSEX wndclass;
char buffer[200];
if (cmdline[0] == '\0')
filename = RAND_file_name(buffer, sizeof buffer);
else
filename = cmdline;
RAND_load_file(filename, -1);
wndclass.cbSize = sizeof(wndclass);
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = appname;
wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wndclass);
hwnd = CreateWindow(appname, OPENSSL_VERSION_TEXT,
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance,
NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rect;
static int seeded = 0;
switch (iMsg) {
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &rect);
DrawText(hdc, "Seeding the PRNG. Please move the mouse!", -1,
&rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
if (RAND_event(iMsg, wParam, lParam) == 1 && seeded == 0) {
seeded = 1;
if (RAND_write_file(filename) <= 0)
MessageBox(hwnd, "Couldn't write random file!",
"OpenSSL", MB_OK | MB_ICONERROR);
PostQuitMessage(0);
}
return DefWindowProc(hwnd, iMsg, wParam, lParam);
}
| mit |
dpodder/coreclr | src/pal/tests/palsuite/c_runtime/swscanf/test6/test6.cpp | 137 | 1370 | // 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: test6.c
**
** Purpose:Tests swscanf with octal numbers
**
**
**==========================================================================*/
#include <palsuite.h>
#include "../swscanf.h"
int __cdecl main(int argc, char *argv[])
{
int n65535 = 65535; /* Walkaround compiler strictness */
if (PAL_Initialize(argc, argv))
{
return FAIL;
}
DoNumTest(convert("1234d"), convert("%o"), 668);
DoNumTest(convert("1234d"), convert("%2o"), 10);
DoNumTest(convert("-1"), convert("%o"), -1);
DoNumTest(convert("0x1234"), convert("%o"), 0);
DoNumTest(convert("012"), convert("%o"), 10);
DoShortNumTest(convert("-1"), convert("%ho"), n65535);
DoShortNumTest(convert("200000"), convert("%ho"), 0);
DoNumTest(convert("-1"), convert("%lo"), -1);
DoNumTest(convert("200000"), convert("%lo"), 65536);
DoNumTest(convert("-1"), convert("%Lo"), -1);
DoNumTest(convert("200000"), convert("%Lo"), 65536);
DoI64NumTest(convert("40000000000"), convert("%I64o"), I64(4294967296));
PAL_Terminate();
return PASS;
}
| mit |
parjong/coreclr | src/pal/tests/palsuite/c_runtime/_wfopen/test4/test4.cpp | 137 | 2381 | // 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: test4.c
**
** Purpose: Tests the PAL implementation of the _wfopen function.
** Test to ensure that you can't write to a 'r' mode file.
** And that you can read from a 'r' mode file.
**
** Depends:
** fprintf
** fclose
** fgets
**
**
**===================================================================*/
#define UNICODE
#include <palsuite.h>
int __cdecl main(int argc, char **argv)
{
FILE *fp;
char buffer[128];
WCHAR filename[] = {'t','e','s','t','f','i','l','e','\0'};
WCHAR write[] = {'w','\0'};
WCHAR read[] = {'r','\0'};
if (PAL_Initialize(argc, argv))
{
return FAIL;
}
/* Open a file with 'w' mode */
if( (fp = _wfopen( filename, write )) == NULL )
{
Fail( "ERROR: The file failed to open with 'w' mode.\n" );
}
/* Write some text to the file */
if(fprintf(fp,"%s","some text") <= 0)
{
Fail("ERROR: Attempted to WRITE to a file opened with 'w' mode "
"but fprintf failed. Either fopen or fprintf have problems.");
}
if(fclose(fp))
{
Fail("ERROR: Attempted to close a file, but fclose failed. "
"This test depends upon it.");
}
/* Open a file with 'r' mode */
if( (fp = _wfopen( filename, read )) == NULL )
{
Fail( "ERROR: The file failed to open with 'r' mode.\n" );
}
/* Attempt to read from the 'r' only file, should pass */
if(fgets(buffer,10,fp) == NULL)
{
Fail("ERROR: Tried to READ from a file with 'r' mode set. "
"This should succeed, but fgets returned NULL. Either fgets "
"or fopen is broken.");
}
/* Write some text to the file */
if(fprintf(fp,"%s","some text") > 0)
{
Fail("ERROR: Attempted to WRITE to a file opened with 'r' mode "
"but fprintf succeeded It should have failed. "
"Either fopen or fprintf have problems.");
}
PAL_Terminate();
return PASS;
}
| mit |
TheBoyThePlay/godot | drivers/builtin_openssl2/crypto/jpake/jpake.c | 657 | 11830 | #include "jpake.h"
#include <openssl/crypto.h>
#include <openssl/sha.h>
#include <openssl/err.h>
#include <memory.h>
/*
* In the definition, (xa, xb, xc, xd) are Alice's (x1, x2, x3, x4) or
* Bob's (x3, x4, x1, x2). If you see what I mean.
*/
typedef struct
{
char *name; /* Must be unique */
char *peer_name;
BIGNUM *p;
BIGNUM *g;
BIGNUM *q;
BIGNUM *gxc; /* Alice's g^{x3} or Bob's g^{x1} */
BIGNUM *gxd; /* Alice's g^{x4} or Bob's g^{x2} */
} JPAKE_CTX_PUBLIC;
struct JPAKE_CTX
{
JPAKE_CTX_PUBLIC p;
BIGNUM *secret; /* The shared secret */
BN_CTX *ctx;
BIGNUM *xa; /* Alice's x1 or Bob's x3 */
BIGNUM *xb; /* Alice's x2 or Bob's x4 */
BIGNUM *key; /* The calculated (shared) key */
};
static void JPAKE_ZKP_init(JPAKE_ZKP *zkp)
{
zkp->gr = BN_new();
zkp->b = BN_new();
}
static void JPAKE_ZKP_release(JPAKE_ZKP *zkp)
{
BN_free(zkp->b);
BN_free(zkp->gr);
}
/* Two birds with one stone - make the global name as expected */
#define JPAKE_STEP_PART_init JPAKE_STEP2_init
#define JPAKE_STEP_PART_release JPAKE_STEP2_release
void JPAKE_STEP_PART_init(JPAKE_STEP_PART *p)
{
p->gx = BN_new();
JPAKE_ZKP_init(&p->zkpx);
}
void JPAKE_STEP_PART_release(JPAKE_STEP_PART *p)
{
JPAKE_ZKP_release(&p->zkpx);
BN_free(p->gx);
}
void JPAKE_STEP1_init(JPAKE_STEP1 *s1)
{
JPAKE_STEP_PART_init(&s1->p1);
JPAKE_STEP_PART_init(&s1->p2);
}
void JPAKE_STEP1_release(JPAKE_STEP1 *s1)
{
JPAKE_STEP_PART_release(&s1->p2);
JPAKE_STEP_PART_release(&s1->p1);
}
static void JPAKE_CTX_init(JPAKE_CTX *ctx, const char *name,
const char *peer_name, const BIGNUM *p,
const BIGNUM *g, const BIGNUM *q,
const BIGNUM *secret)
{
ctx->p.name = OPENSSL_strdup(name);
ctx->p.peer_name = OPENSSL_strdup(peer_name);
ctx->p.p = BN_dup(p);
ctx->p.g = BN_dup(g);
ctx->p.q = BN_dup(q);
ctx->secret = BN_dup(secret);
ctx->p.gxc = BN_new();
ctx->p.gxd = BN_new();
ctx->xa = BN_new();
ctx->xb = BN_new();
ctx->key = BN_new();
ctx->ctx = BN_CTX_new();
}
static void JPAKE_CTX_release(JPAKE_CTX *ctx)
{
BN_CTX_free(ctx->ctx);
BN_clear_free(ctx->key);
BN_clear_free(ctx->xb);
BN_clear_free(ctx->xa);
BN_free(ctx->p.gxd);
BN_free(ctx->p.gxc);
BN_clear_free(ctx->secret);
BN_free(ctx->p.q);
BN_free(ctx->p.g);
BN_free(ctx->p.p);
OPENSSL_free(ctx->p.peer_name);
OPENSSL_free(ctx->p.name);
memset(ctx, '\0', sizeof *ctx);
}
JPAKE_CTX *JPAKE_CTX_new(const char *name, const char *peer_name,
const BIGNUM *p, const BIGNUM *g, const BIGNUM *q,
const BIGNUM *secret)
{
JPAKE_CTX *ctx = OPENSSL_malloc(sizeof *ctx);
JPAKE_CTX_init(ctx, name, peer_name, p, g, q, secret);
return ctx;
}
void JPAKE_CTX_free(JPAKE_CTX *ctx)
{
JPAKE_CTX_release(ctx);
OPENSSL_free(ctx);
}
static void hashlength(SHA_CTX *sha, size_t l)
{
unsigned char b[2];
OPENSSL_assert(l <= 0xffff);
b[0] = l >> 8;
b[1] = l&0xff;
SHA1_Update(sha, b, 2);
}
static void hashstring(SHA_CTX *sha, const char *string)
{
size_t l = strlen(string);
hashlength(sha, l);
SHA1_Update(sha, string, l);
}
static void hashbn(SHA_CTX *sha, const BIGNUM *bn)
{
size_t l = BN_num_bytes(bn);
unsigned char *bin = OPENSSL_malloc(l);
hashlength(sha, l);
BN_bn2bin(bn, bin);
SHA1_Update(sha, bin, l);
OPENSSL_free(bin);
}
/* h=hash(g, g^r, g^x, name) */
static void zkp_hash(BIGNUM *h, const BIGNUM *zkpg, const JPAKE_STEP_PART *p,
const char *proof_name)
{
unsigned char md[SHA_DIGEST_LENGTH];
SHA_CTX sha;
/*
* XXX: hash should not allow moving of the boundaries - Java code
* is flawed in this respect. Length encoding seems simplest.
*/
SHA1_Init(&sha);
hashbn(&sha, zkpg);
OPENSSL_assert(!BN_is_zero(p->zkpx.gr));
hashbn(&sha, p->zkpx.gr);
hashbn(&sha, p->gx);
hashstring(&sha, proof_name);
SHA1_Final(md, &sha);
BN_bin2bn(md, SHA_DIGEST_LENGTH, h);
}
/*
* Prove knowledge of x
* Note that p->gx has already been calculated
*/
static void generate_zkp(JPAKE_STEP_PART *p, const BIGNUM *x,
const BIGNUM *zkpg, JPAKE_CTX *ctx)
{
BIGNUM *r = BN_new();
BIGNUM *h = BN_new();
BIGNUM *t = BN_new();
/*
* r in [0,q)
* XXX: Java chooses r in [0, 2^160) - i.e. distribution not uniform
*/
BN_rand_range(r, ctx->p.q);
/* g^r */
BN_mod_exp(p->zkpx.gr, zkpg, r, ctx->p.p, ctx->ctx);
/* h=hash... */
zkp_hash(h, zkpg, p, ctx->p.name);
/* b = r - x*h */
BN_mod_mul(t, x, h, ctx->p.q, ctx->ctx);
BN_mod_sub(p->zkpx.b, r, t, ctx->p.q, ctx->ctx);
/* cleanup */
BN_free(t);
BN_free(h);
BN_free(r);
}
static int verify_zkp(const JPAKE_STEP_PART *p, const BIGNUM *zkpg,
JPAKE_CTX *ctx)
{
BIGNUM *h = BN_new();
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
BIGNUM *t3 = BN_new();
int ret = 0;
zkp_hash(h, zkpg, p, ctx->p.peer_name);
/* t1 = g^b */
BN_mod_exp(t1, zkpg, p->zkpx.b, ctx->p.p, ctx->ctx);
/* t2 = (g^x)^h = g^{hx} */
BN_mod_exp(t2, p->gx, h, ctx->p.p, ctx->ctx);
/* t3 = t1 * t2 = g^{hx} * g^b = g^{hx+b} = g^r (allegedly) */
BN_mod_mul(t3, t1, t2, ctx->p.p, ctx->ctx);
/* verify t3 == g^r */
if(BN_cmp(t3, p->zkpx.gr) == 0)
ret = 1;
else
JPAKEerr(JPAKE_F_VERIFY_ZKP, JPAKE_R_ZKP_VERIFY_FAILED);
/* cleanup */
BN_free(t3);
BN_free(t2);
BN_free(t1);
BN_free(h);
return ret;
}
static void generate_step_part(JPAKE_STEP_PART *p, const BIGNUM *x,
const BIGNUM *g, JPAKE_CTX *ctx)
{
BN_mod_exp(p->gx, g, x, ctx->p.p, ctx->ctx);
generate_zkp(p, x, g, ctx);
}
/* Generate each party's random numbers. xa is in [0, q), xb is in [1, q). */
static void genrand(JPAKE_CTX *ctx)
{
BIGNUM *qm1;
/* xa in [0, q) */
BN_rand_range(ctx->xa, ctx->p.q);
/* q-1 */
qm1 = BN_new();
BN_copy(qm1, ctx->p.q);
BN_sub_word(qm1, 1);
/* ... and xb in [0, q-1) */
BN_rand_range(ctx->xb, qm1);
/* [1, q) */
BN_add_word(ctx->xb, 1);
/* cleanup */
BN_free(qm1);
}
int JPAKE_STEP1_generate(JPAKE_STEP1 *send, JPAKE_CTX *ctx)
{
genrand(ctx);
generate_step_part(&send->p1, ctx->xa, ctx->p.g, ctx);
generate_step_part(&send->p2, ctx->xb, ctx->p.g, ctx);
return 1;
}
/* g^x is a legal value */
static int is_legal(const BIGNUM *gx, const JPAKE_CTX *ctx)
{
BIGNUM *t;
int res;
if(BN_is_negative(gx) || BN_is_zero(gx) || BN_cmp(gx, ctx->p.p) >= 0)
return 0;
t = BN_new();
BN_mod_exp(t, gx, ctx->p.q, ctx->p.p, ctx->ctx);
res = BN_is_one(t);
BN_free(t);
return res;
}
int JPAKE_STEP1_process(JPAKE_CTX *ctx, const JPAKE_STEP1 *received)
{
if(!is_legal(received->p1.gx, ctx))
{
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_G_TO_THE_X3_IS_NOT_LEGAL);
return 0;
}
if(!is_legal(received->p2.gx, ctx))
{
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_G_TO_THE_X4_IS_NOT_LEGAL);
return 0;
}
/* verify their ZKP(xc) */
if(!verify_zkp(&received->p1, ctx->p.g, ctx))
{
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_VERIFY_X3_FAILED);
return 0;
}
/* verify their ZKP(xd) */
if(!verify_zkp(&received->p2, ctx->p.g, ctx))
{
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_VERIFY_X4_FAILED);
return 0;
}
/* g^xd != 1 */
if(BN_is_one(received->p2.gx))
{
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_G_TO_THE_X4_IS_ONE);
return 0;
}
/* Save the bits we need for later */
BN_copy(ctx->p.gxc, received->p1.gx);
BN_copy(ctx->p.gxd, received->p2.gx);
return 1;
}
int JPAKE_STEP2_generate(JPAKE_STEP2 *send, JPAKE_CTX *ctx)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
/*
* X = g^{(xa + xc + xd) * xb * s}
* t1 = g^xa
*/
BN_mod_exp(t1, ctx->p.g, ctx->xa, ctx->p.p, ctx->ctx);
/* t2 = t1 * g^{xc} = g^{xa} * g^{xc} = g^{xa + xc} */
BN_mod_mul(t2, t1, ctx->p.gxc, ctx->p.p, ctx->ctx);
/* t1 = t2 * g^{xd} = g^{xa + xc + xd} */
BN_mod_mul(t1, t2, ctx->p.gxd, ctx->p.p, ctx->ctx);
/* t2 = xb * s */
BN_mod_mul(t2, ctx->xb, ctx->secret, ctx->p.q, ctx->ctx);
/*
* ZKP(xb * s)
* XXX: this is kinda funky, because we're using
*
* g' = g^{xa + xc + xd}
*
* as the generator, which means X is g'^{xb * s}
* X = t1^{t2} = t1^{xb * s} = g^{(xa + xc + xd) * xb * s}
*/
generate_step_part(send, t2, t1, ctx);
/* cleanup */
BN_free(t1);
BN_free(t2);
return 1;
}
/* gx = g^{xc + xa + xb} * xd * s */
static int compute_key(JPAKE_CTX *ctx, const BIGNUM *gx)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
BIGNUM *t3 = BN_new();
/*
* K = (gx/g^{xb * xd * s})^{xb}
* = (g^{(xc + xa + xb) * xd * s - xb * xd *s})^{xb}
* = (g^{(xa + xc) * xd * s})^{xb}
* = g^{(xa + xc) * xb * xd * s}
* [which is the same regardless of who calculates it]
*/
/* t1 = (g^{xd})^{xb} = g^{xb * xd} */
BN_mod_exp(t1, ctx->p.gxd, ctx->xb, ctx->p.p, ctx->ctx);
/* t2 = -s = q-s */
BN_sub(t2, ctx->p.q, ctx->secret);
/* t3 = t1^t2 = g^{-xb * xd * s} */
BN_mod_exp(t3, t1, t2, ctx->p.p, ctx->ctx);
/* t1 = gx * t3 = X/g^{xb * xd * s} */
BN_mod_mul(t1, gx, t3, ctx->p.p, ctx->ctx);
/* K = t1^{xb} */
BN_mod_exp(ctx->key, t1, ctx->xb, ctx->p.p, ctx->ctx);
/* cleanup */
BN_free(t3);
BN_free(t2);
BN_free(t1);
return 1;
}
int JPAKE_STEP2_process(JPAKE_CTX *ctx, const JPAKE_STEP2 *received)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
int ret = 0;
/*
* g' = g^{xc + xa + xb} [from our POV]
* t1 = xa + xb
*/
BN_mod_add(t1, ctx->xa, ctx->xb, ctx->p.q, ctx->ctx);
/* t2 = g^{t1} = g^{xa+xb} */
BN_mod_exp(t2, ctx->p.g, t1, ctx->p.p, ctx->ctx);
/* t1 = g^{xc} * t2 = g^{xc + xa + xb} */
BN_mod_mul(t1, ctx->p.gxc, t2, ctx->p.p, ctx->ctx);
if(verify_zkp(received, t1, ctx))
ret = 1;
else
JPAKEerr(JPAKE_F_JPAKE_STEP2_PROCESS, JPAKE_R_VERIFY_B_FAILED);
compute_key(ctx, received->gx);
/* cleanup */
BN_free(t2);
BN_free(t1);
return ret;
}
static void quickhashbn(unsigned char *md, const BIGNUM *bn)
{
SHA_CTX sha;
SHA1_Init(&sha);
hashbn(&sha, bn);
SHA1_Final(md, &sha);
}
void JPAKE_STEP3A_init(JPAKE_STEP3A *s3a)
{}
int JPAKE_STEP3A_generate(JPAKE_STEP3A *send, JPAKE_CTX *ctx)
{
quickhashbn(send->hhk, ctx->key);
SHA1(send->hhk, sizeof send->hhk, send->hhk);
return 1;
}
int JPAKE_STEP3A_process(JPAKE_CTX *ctx, const JPAKE_STEP3A *received)
{
unsigned char hhk[SHA_DIGEST_LENGTH];
quickhashbn(hhk, ctx->key);
SHA1(hhk, sizeof hhk, hhk);
if(memcmp(hhk, received->hhk, sizeof hhk))
{
JPAKEerr(JPAKE_F_JPAKE_STEP3A_PROCESS, JPAKE_R_HASH_OF_HASH_OF_KEY_MISMATCH);
return 0;
}
return 1;
}
void JPAKE_STEP3A_release(JPAKE_STEP3A *s3a)
{}
void JPAKE_STEP3B_init(JPAKE_STEP3B *s3b)
{}
int JPAKE_STEP3B_generate(JPAKE_STEP3B *send, JPAKE_CTX *ctx)
{
quickhashbn(send->hk, ctx->key);
return 1;
}
int JPAKE_STEP3B_process(JPAKE_CTX *ctx, const JPAKE_STEP3B *received)
{
unsigned char hk[SHA_DIGEST_LENGTH];
quickhashbn(hk, ctx->key);
if(memcmp(hk, received->hk, sizeof hk))
{
JPAKEerr(JPAKE_F_JPAKE_STEP3B_PROCESS, JPAKE_R_HASH_OF_KEY_MISMATCH);
return 0;
}
return 1;
}
void JPAKE_STEP3B_release(JPAKE_STEP3B *s3b)
{}
const BIGNUM *JPAKE_get_shared_key(JPAKE_CTX *ctx)
{
return ctx->key;
}
| mit |
planet-training/meteor | scripts/windows/installer/WiXBalExtension/wixstdba/WixStandardBootstrapperApplication.cpp | 157 | 125947 | //-------------------------------------------------------------------------------------------------
// <copyright file="WixStandardBootstrapperApplication.cpp" company="Outercurve Foundation">
// Copyright (c) 2004, Outercurve Foundation.
// This software is released under Microsoft Reciprocal License (MS-RL).
// The license and further copyright text can be found in the file
// LICENSE.TXT at the root directory of the distribution.
// </copyright>
//-------------------------------------------------------------------------------------------------
#include "precomp.h"
#include "regutil.h"
#include "JSON.h"
#include <windows.h>
#include <string>
#include <sstream>
static const HRESULT E_WIXSTDBA_CONDITION_FAILED = MAKE_HRESULT(SEVERITY_ERROR, 500, 1);
static const LPCWSTR WIXBUNDLE_VARIABLE_ELEVATED = L"WixBundleElevated";
static const LPCWSTR WIXSTDBA_WINDOW_CLASS = L"WixExtBA";
static const LPCWSTR WIXSTDBA_VARIABLE_INSTALL_FOLDER = L"InstallFolder";
static const LPCWSTR WIXSTDBA_VARIABLE_INSTALL_REGPATH = L"InstallRegPath";
static const LPCWSTR WIXSTDBA_VARIABLE_LAUNCH_TARGET_PATH = L"LaunchTarget";
static const LPCWSTR WIXSTDBA_VARIABLE_LAUNCH_ARGUMENTS = L"LaunchArguments";
static const LPCWSTR WIXSTDBA_VARIABLE_LAUNCH_HIDDEN = L"LaunchHidden";
static const LPCWSTR WIXSTDBA_VARIABLE_LAUNCHAFTERINSTALL_TARGET_PATH = L"LaunchAfterInstallTarget";
static const LPCWSTR WIXSTDBA_VARIABLE_LAUNCHAFTERINSTALL_ARGUMENTS = L"LaunchAfterInstallArguments";
static const LPCWSTR WIXSTDBA_VARIABLE_PROGRESS_HEADER = L"varProgressHeader";
static const LPCWSTR WIXSTDBA_VARIABLE_PROGRESS_INFO = L"varProgressInfo";
static const LPCWSTR WIXSTDBA_VARIABLE_SUCCESS_HEADER = L"varSuccessHeader";
static const LPCWSTR WIXSTDBA_VARIABLE_SUCCESS_INFO = L"varSuccessInfo";
static const LPCWSTR WIXSTDBA_VARIABLE_FAILURE_HEADER = L"varFailureHeader";
static const LPCWSTR WIXSTDBA_VARIABLE_SUCCESS_ERRINF = L"varSuccessErrorInfoText";
static const LPCWSTR WIXSTDBA_VARIABLE_SUCCESS_ERRMSG = L"varSuccessErrorMessageText";
static const LPCWSTR WIXSTDBA_VARIABLE_PERMACHINE_INSTALL = L"PerMachineInstall";
static const LPCWSTR WIXSTDBA_VARIABLE_PERMACHINE_INSTALL_FOLDER = L"PerMachineInstallFolder";
static const LPCWSTR WIXSTDBA_VARIABLE_PERUSER_INSTALL_FOLDER = L"PerUserInstallFolder";
static const LPCWSTR WIXSTDBA_VARIABLE_USERMETEORSESSIONFILE = L"UserMeteorSessionFile";
static const LPCWSTR WIXSTDBA_VARIABLE_REG_MAIL = L"RegisterEmail";
static const LPCWSTR WIXSTDBA_VARIABLE_REG_USER = L"RegisterUser";
static const LPCWSTR WIXSTDBA_VARIABLE_REG_PASS = L"RegisterPass";
static const LPCWSTR WIXSTDBA_VARIABLE_LOG_USERNAME_OR_MAIL = L"LoginUsernameOrEmail";
static const LPCWSTR WIXSTDBA_VARIABLE_LOG_PASS = L"LoginPass";
static const LPCWSTR WIXSTDBA_VARIABLE_LOGSPATH = L"QCInstallLogsPath";
static const DWORD WIXSTDBA_ACQUIRE_PERCENTAGE = 1;
enum WIXSTDBA_STATE
{
WIXSTDBA_STATE_INSTALLDIR,
WIXSTDBA_STATE_SVC_OPTIONS,
WIXSTDBA_STATE_INITIALIZING,
WIXSTDBA_STATE_INITIALIZED,
WIXSTDBA_STATE_HELP,
WIXSTDBA_STATE_DETECTING,
WIXSTDBA_STATE_DETECTED,
WIXSTDBA_STATE_PLANNING,
WIXSTDBA_STATE_PLANNED,
WIXSTDBA_STATE_APPLYING,
WIXSTDBA_STATE_CACHING,
WIXSTDBA_STATE_CACHED,
WIXSTDBA_STATE_EXECUTING,
WIXSTDBA_STATE_EXECUTED,
WIXSTDBA_STATE_APPLIED,
WIXSTDBA_STATE_FAILED,
};
enum WM_WIXSTDBA
{
WM_WIXSTDBA_SHOW_HELP = WM_APP + 100,
WM_WIXSTDBA_DETECT_PACKAGES,
WM_WIXSTDBA_PLAN_PACKAGES,
WM_WIXSTDBA_APPLY_PACKAGES,
WM_WIXSTDBA_CHANGE_STATE,
};
// This enum must be kept in the same order as the vrgwzPageNames array.
enum WIXSTDBA_PAGE
{
WIXSTDBA_PAGE_LOADING,
WIXSTDBA_PAGE_HELP,
WIXSTDBA_PAGE_INSTALL,
WIXSTDBA_PAGE_INSTALLDIR,
WIXSTDBA_PAGE_SVC_OPTIONS,
WIXSTDBA_PAGE_MODIFY,
WIXSTDBA_PAGE_PROGRESS,
WIXSTDBA_PAGE_PROGRESS_PASSIVE,
WIXSTDBA_PAGE_SUCCESS,
WIXSTDBA_PAGE_FAILURE,
COUNT_WIXSTDBA_PAGE,
};
// This array must be kept in the same order as the WIXSTDBA_PAGE enum.
static LPCWSTR vrgwzPageNames[] = {
L"Loading",
L"Help",
L"Install",
L"InstallDir",
L"SvcOptions",
L"Modify",
L"Progress",
L"ProgressPassive",
L"Success",
L"Failure",
};
enum WIXSTDBA_CONTROL
{
// Non-paged controls
WIXSTDBA_CONTROL_CLOSE_BUTTON = THEME_FIRST_ASSIGN_CONTROL_ID,
WIXSTDBA_CONTROL_MINIMIZE_BUTTON,
// Help page
WIXSTDBA_CONTROL_HELP_CANCEL_BUTTON,
// Welcome page
WIXSTDBA_CONTROL_INSTALL_BUTTON,
WIXSTDBA_CONTROL_OPTIONS_BUTTON,
WIXSTDBA_CONTROL_EULA_RICHEDIT,
WIXSTDBA_CONTROL_EULA_LINK,
WIXSTDBA_CONTROL_EULA_ACCEPT_CHECKBOX,
WIXSTDBA_CONTROL_WELCOME_CANCEL_BUTTON,
WIXSTDBA_CONTROL_VERSION_LABEL,
WIXSTDBA_CONTROL_UPGRADE_LINK,
WIXSTDBA_CONTROL_NEXT_BUTTON,
WIXSTDBA_CONTROL_BACK_BUTTON,
WIXSTDBA_CONTROL_SKIP_BUTTON,
// Options page
WIXSTDBA_CONTROL_PERMACHINE_RADIO,
WIXSTDBA_CONTROL_PERUSER_RADIO,
WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX,
WIXSTDBA_CONTROL_BROWSE_BUTTON,
WIXSTDBA_CONTROL_REGSIGNIN_RADIO,
WIXSTDBA_CONTROL_REGCREATE_RADIO,
WIXSTDBA_CONTROL_REGMAIL_LABEL,
WIXSTDBA_CONTROL_REGUSER_LABEL,
WIXSTDBA_CONTROL_REGPASS_LABEL,
WIXSTDBA_CONTROL_REGMAIL_EDIT,
WIXSTDBA_CONTROL_REGUSER_EDIT,
WIXSTDBA_CONTROL_REGPASS_EDIT,
WIXSTDBA_CONTROL_LOGUSER_OR_MAIL_LABEL,
WIXSTDBA_CONTROL_LOGPASS_LABEL,
WIXSTDBA_CONTROL_LOGUSER_OR_MAIL_EDIT,
WIXSTDBA_CONTROL_LOGPASS_EDIT,
WIXSTDBA_CONTROL_SKIPREG_CHECKBOX,
WIXSTDBA_CONTROL_OK_BUTTON,
WIXSTDBA_CONTROL_CANCEL_BUTTON,
// Modify page
WIXSTDBA_CONTROL_REPAIR_BUTTON,
WIXSTDBA_CONTROL_UNINSTALL_BUTTON,
WIXSTDBA_CONTROL_MODIFY_CANCEL_BUTTON,
// Progress page
WIXSTDBA_CONTROL_CACHE_PROGRESS_PACKAGE_TEXT,
WIXSTDBA_CONTROL_CACHE_PROGRESS_BAR,
WIXSTDBA_CONTROL_CACHE_PROGRESS_TEXT,
WIXSTDBA_CONTROL_EXECUTE_PROGRESS_PACKAGE_TEXT,
WIXSTDBA_CONTROL_EXECUTE_PROGRESS_BAR,
WIXSTDBA_CONTROL_EXECUTE_PROGRESS_TEXT,
WIXSTDBA_CONTROL_EXECUTE_PROGRESS_ACTIONDATA_TEXT,
WIXSTDBA_CONTROL_OVERALL_PROGRESS_PACKAGE_TEXT,
WIXSTDBA_CONTROL_OVERALL_PROGRESS_BAR,
WIXSTDBA_CONTROL_OVERALL_CALCULATED_PROGRESS_BAR,
WIXSTDBA_CONTROL_OVERALL_PROGRESS_TEXT,
WIXSTDBA_CONTROL_PROGRESS_INSTALLING_HEADER,
WIXSTDBA_CONTROL_PROGRESS_CANCEL_BUTTON,
// Success page
WIXSTDBA_CONTROL_LAUNCH_BUTTON,
WIXSTDBA_CONTROL_SUCCESS_RESTART_TEXT,
WIXSTDBA_CONTROL_SUCCESS_RESTART_BUTTON,
WIXSTDBA_CONTROL_SUCCESS_CANCEL_BUTTON,
WIXSTDBA_CONTROL_SUCCESS_ERRINF_TEXT,
WIXSTDBA_CONTROL_SUCCESS_ERRMSG_TEXT,
// Failure page
WIXSTDBA_CONTROL_FAILURE_LOGFILE_LINK,
WIXSTDBA_CONTROL_FAILURE_MESSAGE_TEXT,
WIXSTDBA_CONTROL_FAILURE_RESTART_TEXT,
WIXSTDBA_CONTROL_FAILURE_RESTART_BUTTON,
WIXSTDBA_CONTROL_FAILURE_CANCEL_BUTTON,
};
static THEME_ASSIGN_CONTROL_ID vrgInitControls[] = {
{ WIXSTDBA_CONTROL_CLOSE_BUTTON, L"CloseButton" },
{ WIXSTDBA_CONTROL_MINIMIZE_BUTTON, L"MinimizeButton" },
{ WIXSTDBA_CONTROL_HELP_CANCEL_BUTTON, L"HelpCancelButton" },
{ WIXSTDBA_CONTROL_INSTALL_BUTTON, L"InstallButton" },
{ WIXSTDBA_CONTROL_OPTIONS_BUTTON, L"OptionsButton" },
{ WIXSTDBA_CONTROL_EULA_RICHEDIT, L"EulaRichedit" },
{ WIXSTDBA_CONTROL_EULA_LINK, L"EulaHyperlink" },
{ WIXSTDBA_CONTROL_EULA_ACCEPT_CHECKBOX, L"EulaAcceptCheckbox" },
{ WIXSTDBA_CONTROL_WELCOME_CANCEL_BUTTON, L"WelcomeCancelButton" },
{ WIXSTDBA_CONTROL_VERSION_LABEL, L"InstallVersion" },
{ WIXSTDBA_CONTROL_UPGRADE_LINK, L"UpgradeHyperlink" },
{ WIXSTDBA_CONTROL_NEXT_BUTTON, L"NextButton" },
{ WIXSTDBA_CONTROL_BACK_BUTTON, L"BackButton" },
{ WIXSTDBA_CONTROL_SKIP_BUTTON, L"SkipButton" },
{WIXSTDBA_CONTROL_PERMACHINE_RADIO, L"PerMachineInstall" },
{WIXSTDBA_CONTROL_PERUSER_RADIO, L"PerUserInstall" },
{ WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX, L"InstallFolderEditbox" },
{ WIXSTDBA_CONTROL_BROWSE_BUTTON, L"BrowseButton" },
{WIXSTDBA_CONTROL_REGSIGNIN_RADIO, L"SignInRButton"},
{WIXSTDBA_CONTROL_REGCREATE_RADIO, L"CreateRButton"},
{WIXSTDBA_CONTROL_REGMAIL_LABEL, L"RegisterEmailLabel"},
{WIXSTDBA_CONTROL_REGUSER_LABEL, L"RegisterUserLabel"},
{WIXSTDBA_CONTROL_REGPASS_LABEL, L"RegisterPassLabel"},
{WIXSTDBA_CONTROL_REGMAIL_EDIT, L"RegisterEmail"},
{WIXSTDBA_CONTROL_REGUSER_EDIT, L"RegisterUser"},
{WIXSTDBA_CONTROL_REGPASS_EDIT, L"RegisterPass"},
{WIXSTDBA_CONTROL_LOGUSER_OR_MAIL_LABEL, L"LoginUsernameOrEmailLabel"},
{WIXSTDBA_CONTROL_LOGPASS_LABEL, L"LoginPassLabel"},
{WIXSTDBA_CONTROL_LOGUSER_OR_MAIL_EDIT, L"LoginUsernameOrEmail"},
{WIXSTDBA_CONTROL_LOGPASS_EDIT, L"LoginPass"},
{WIXSTDBA_CONTROL_SKIPREG_CHECKBOX, L"SkipRegistration"},
{ WIXSTDBA_CONTROL_REPAIR_BUTTON, L"RepairButton" },
{ WIXSTDBA_CONTROL_UNINSTALL_BUTTON, L"UninstallButton" },
{ WIXSTDBA_CONTROL_MODIFY_CANCEL_BUTTON, L"ModifyCancelButton" },
{ WIXSTDBA_CONTROL_CACHE_PROGRESS_PACKAGE_TEXT, L"CacheProgressPackageText" },
{ WIXSTDBA_CONTROL_CACHE_PROGRESS_BAR, L"CacheProgressbar" },
{ WIXSTDBA_CONTROL_CACHE_PROGRESS_TEXT, L"CacheProgressText" },
{ WIXSTDBA_CONTROL_EXECUTE_PROGRESS_PACKAGE_TEXT, L"ExecuteProgressPackageText" },
{ WIXSTDBA_CONTROL_EXECUTE_PROGRESS_BAR, L"ExecuteProgressbar" },
{ WIXSTDBA_CONTROL_EXECUTE_PROGRESS_TEXT, L"ExecuteProgressText" },
{ WIXSTDBA_CONTROL_EXECUTE_PROGRESS_ACTIONDATA_TEXT, L"ExecuteProgressActionDataText"},
{ WIXSTDBA_CONTROL_OVERALL_PROGRESS_PACKAGE_TEXT, L"OverallProgressPackageText" },
{ WIXSTDBA_CONTROL_OVERALL_PROGRESS_BAR, L"OverallProgressbar" },
{ WIXSTDBA_CONTROL_OVERALL_CALCULATED_PROGRESS_BAR, L"OverallCalculatedProgressbar" },
{ WIXSTDBA_CONTROL_OVERALL_PROGRESS_TEXT, L"OverallProgressText" },
{ WIXSTDBA_CONTROL_PROGRESS_CANCEL_BUTTON, L"ProgressCancelButton" },
{ WIXSTDBA_CONTROL_PROGRESS_INSTALLING_HEADER, L"InstallingHeader" },
{ WIXSTDBA_CONTROL_LAUNCH_BUTTON, L"LaunchButton" },
{ WIXSTDBA_CONTROL_SUCCESS_RESTART_TEXT, L"SuccessRestartText" },
{ WIXSTDBA_CONTROL_SUCCESS_RESTART_BUTTON, L"SuccessRestartButton" },
{ WIXSTDBA_CONTROL_SUCCESS_CANCEL_BUTTON, L"SuccessCancelButton" },
{ WIXSTDBA_CONTROL_SUCCESS_ERRINF_TEXT, L"SuccessErrorInfoText" },
{ WIXSTDBA_CONTROL_SUCCESS_ERRMSG_TEXT, L"SuccessErrorMessageText" },
{ WIXSTDBA_CONTROL_FAILURE_LOGFILE_LINK, L"FailureLogFileLink" },
{ WIXSTDBA_CONTROL_FAILURE_MESSAGE_TEXT, L"FailureMessageText" },
{ WIXSTDBA_CONTROL_FAILURE_RESTART_TEXT, L"FailureRestartText" },
{ WIXSTDBA_CONTROL_FAILURE_RESTART_BUTTON, L"FailureRestartButton" },
{ WIXSTDBA_CONTROL_FAILURE_CANCEL_BUTTON, L"FailureCloseButton" },
};
void ExtractActionProgressText(
__in_z LPCWSTR wzActionMessage,
__in_z LPCWSTR *pwzActionProgressText
)
{
if (!wzActionMessage)
return;
DWORD i = 0;
LPCWSTR wzActionProgressText = wzActionMessage;
LPCWSTR wz = wzActionMessage;
while (*wz)
{
if (L' ' == *wz) ++i;
if (i <= 2) wzActionProgressText++;
++wz;
}
*pwzActionProgressText = wzActionProgressText;
return;
}
class CWixStandardBootstrapperApplication : public CBalBaseBootstrapperApplication
{
public: // IBootstrapperApplication
virtual STDMETHODIMP OnStartup()
{
HRESULT hr = S_OK;
DWORD dwUIThreadId = 0;
// create UI thread
m_hUiThread = ::CreateThread(NULL, 0, UiThreadProc, this, 0, &dwUIThreadId);
if (!m_hUiThread)
{
ExitWithLastError(hr, "Failed to create UI thread.");
}
LExit:
return hr;
}
virtual STDMETHODIMP_(int) OnShutdown()
{
int nResult = IDNOACTION;
// wait for UI thread to terminate
if (m_hUiThread)
{
::WaitForSingleObject(m_hUiThread, INFINITE);
ReleaseHandle(m_hUiThread);
}
// If a restart was required.
if (m_fRestartRequired)
{
if (m_fAllowRestart)
{
nResult = IDRESTART;
}
if (m_sczPrereqPackage)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, m_fAllowRestart ? "The prerequisites scheduled a restart. The bootstrapper application will be reloaded after the computer is restarted."
: "A restart is required by the prerequisites but the user delayed it. The bootstrapper application will be reloaded after the computer is restarted.");
}
}
else if (m_fPrereqInstalled)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "The prerequisites were successfully installed. The bootstrapper application will be reloaded.");
nResult = IDRELOAD_BOOTSTRAPPER;
}
else if (m_fPrereqAlreadyInstalled)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "The prerequisites were already installed. The bootstrapper application will not be reloaded to prevent an infinite loop.");
}
else if (m_fPrereq)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "The prerequisites were not successfully installed, error: 0x%x. The bootstrapper application will be not reloaded.", m_hrFinal);
}
return nResult;
}
virtual STDMETHODIMP_(int) OnDetectRelatedBundle(
__in LPCWSTR wzBundleId,
__in BOOTSTRAPPER_RELATION_TYPE relationType,
__in LPCWSTR /*wzBundleTag*/,
__in BOOL fPerMachine,
__in DWORD64 /*dw64Version*/,
__in BOOTSTRAPPER_RELATED_OPERATION operation
)
{
BalInfoAddRelatedBundleAsPackage(&m_Bundle.packages, wzBundleId, relationType, fPerMachine);
// If we're not doing a pre-req install, remember when our bundle would cause a downgrade.
if (!m_sczPrereqPackage && BOOTSTRAPPER_RELATED_OPERATION_DOWNGRADE == operation)
{
m_fDowngrading = TRUE;
}
m_Operation = operation; // Save operation
return CheckCanceled() ? IDCANCEL : IDOK;
}
virtual STDMETHODIMP_(void) OnDetectPackageComplete(
__in LPCWSTR wzPackageId,
__in HRESULT /*hrStatus*/,
__in BOOTSTRAPPER_PACKAGE_STATE state
)
{
// If the prereq package is already installed, remember that.
if (m_sczPrereqPackage && BOOTSTRAPPER_PACKAGE_STATE_PRESENT == state &&
CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, 0, wzPackageId, -1, m_sczPrereqPackage, -1))
{
m_fPrereqAlreadyInstalled = TRUE;
}
}
// OnDetectUpdateBegin - called when the engine begins detection for bundle update.
virtual STDMETHODIMP_(int) OnDetectUpdateBegin(
__in_z LPCWSTR wzUpdateLocation,
__in int nRecommendation
)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Update location: %ls.", wzUpdateLocation);
m_wzUpdateLocation = wzUpdateLocation;
// If there is an upgrade link, check for update on a background thread
if (ThemeControlExists(m_pTheme, WIXSTDBA_CONTROL_UPGRADE_LINK))
{
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_UPGRADE_LINK, FALSE);
::CreateThread(NULL, 0, ThreadProc, this, 0, NULL);
}
return nRecommendation;
}
virtual STDMETHODIMP_(int) OnDetectBegin(
__in BOOL /*fInstalled*/,
__in DWORD /*cPackages*/
)
{
return IDNOACTION;
}
virtual STDMETHODIMP_(void) OnDetectComplete(
__in HRESULT hrStatus
)
{
if (SUCCEEDED(hrStatus) && m_pBAFunction)
{
m_pBAFunction->OnDetectComplete();
}
if (SUCCEEDED(hrStatus))
{
hrStatus = EvaluateConditions();
}
if (m_command.action == BOOTSTRAPPER_ACTION_UNINSTALL)
this->OnPlan(BOOTSTRAPPER_ACTION_UNINSTALL);
else
this->OnPlan(BOOTSTRAPPER_ACTION_INSTALL);
// Doing some custom vars handling
//if (BalStringVariableExists(WIXSTDBA_VARIABLE_DETECT_POSTGRES))
//{
// LONGLONG llValue = 0;
// BalGetNumericVariable(WIXSTDBA_VARIABLE_DETECT_POSTGRES, &llValue);
// if (llValue == 1)
// m_pEngine->SetVariableNumeric(WIXSTDBA_VARIABLE_INSTALL_POSTGRES, 0);
//}
// If we're not interacting with the user or we're doing a layout or we're just after a force restart
// then automatically start planning.
if (BOOTSTRAPPER_DISPLAY_FULL > m_command.display || BOOTSTRAPPER_ACTION_LAYOUT == m_command.action || BOOTSTRAPPER_RESUME_TYPE_REBOOT == m_command.resumeType)
{
if (SUCCEEDED(hrStatus))
{
::PostMessageW(m_hWnd, WM_WIXSTDBA_PLAN_PACKAGES, 0, m_command.action);
}
}
}
virtual STDMETHODIMP_(int) OnPlanRelatedBundle(
__in_z LPCWSTR /*wzBundleId*/,
__inout_z BOOTSTRAPPER_REQUEST_STATE* pRequestedState
)
{
// If we're only installing prereq, do not touch related bundles.
if (m_sczPrereqPackage)
{
*pRequestedState = BOOTSTRAPPER_REQUEST_STATE_NONE;
}
else if (BOOTSTRAPPER_RELATED_OPERATION_NONE == m_Operation &&
BOOTSTRAPPER_REQUEST_STATE_NONE == *pRequestedState &&
BOOTSTRAPPER_RELATION_UPGRADE != m_command.relationType)
{
// Same version upgrade detected, mark absent so the install runs
*pRequestedState = BOOTSTRAPPER_REQUEST_STATE_ABSENT;
}
return CheckCanceled() ? IDCANCEL : IDOK;
}
virtual STDMETHODIMP_(int) OnPlanPackageBegin(
__in_z LPCWSTR wzPackageId,
__inout BOOTSTRAPPER_REQUEST_STATE *pRequestState
)
{
// If we're planning to install a pre-req, install it. The pre-req needs to be installed
// in all cases (even uninstall!) so the BA can load next.
if (m_sczPrereqPackage)
{
if (CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, 0, wzPackageId, -1, m_sczPrereqPackage, -1))
{
*pRequestState = BOOTSTRAPPER_REQUEST_STATE_PRESENT;
}
else // skip everything else.
{
*pRequestState = BOOTSTRAPPER_REQUEST_STATE_NONE;
}
}
else if (m_sczAfterForcedRestartPackage) // after force restart skip packages until after the package that caused the restart.
{
// After restart we need to finish the dependency registration for our package so allow the package
// to go present.
if (CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, 0, wzPackageId, -1, m_sczAfterForcedRestartPackage, -1))
{
// Do not allow a repair because that could put us in a perpetual restart loop.
if (BOOTSTRAPPER_REQUEST_STATE_REPAIR == *pRequestState)
{
*pRequestState = BOOTSTRAPPER_REQUEST_STATE_PRESENT;
}
ReleaseNullStr(m_sczAfterForcedRestartPackage); // no more skipping now.
}
else // not the matching package, so skip it.
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Skipping package: %ls, after restart because it was applied before the restart.", wzPackageId);
*pRequestState = BOOTSTRAPPER_REQUEST_STATE_NONE;
}
}
return CheckCanceled() ? IDCANCEL : IDOK;
}
virtual STDMETHODIMP_(void) OnPlanComplete(
__in HRESULT hrStatus
)
{
if (SUCCEEDED(hrStatus) && m_pBAFunction)
{
m_pBAFunction->OnPlanComplete();
}
SetState(WIXSTDBA_STATE_PLANNED, hrStatus);
if (SUCCEEDED(hrStatus))
{
::PostMessageW(m_hWnd, WM_WIXSTDBA_APPLY_PACKAGES, 0, 0);
}
m_fStartedExecution = FALSE;
m_dwCalculatedCacheProgress = 0;
m_dwCalculatedExecuteProgress = 0;
}
virtual STDMETHODIMP_(int) OnCachePackageBegin(
__in_z LPCWSTR wzPackageId,
__in DWORD cCachePayloads,
__in DWORD64 dw64PackageCacheSize
)
{
if (wzPackageId && *wzPackageId)
{
BAL_INFO_PACKAGE* pPackage = NULL;
HRESULT hr = BalInfoFindPackageById(&m_Bundle.packages, wzPackageId, &pPackage);
LPCWSTR wz = (SUCCEEDED(hr) && pPackage->sczDisplayName) ? pPackage->sczDisplayName : wzPackageId;
WCHAR wzInfo[1024] = { };
::StringCchPrintfW(wzInfo, countof(wzInfo), L"Acquiring %s package...", wz);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_CACHE_PROGRESS_PACKAGE_TEXT, wzInfo);
// If something started executing, leave it in the overall progress text.
if (!m_fStartedExecution)
{
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_OVERALL_PROGRESS_PACKAGE_TEXT, wzInfo);
}
}
return __super::OnCachePackageBegin(wzPackageId, cCachePayloads, dw64PackageCacheSize);
}
virtual STDMETHODIMP_(int) OnCacheAcquireProgress(
__in_z LPCWSTR wzPackageOrContainerId,
__in_z_opt LPCWSTR wzPayloadId,
__in DWORD64 dw64Progress,
__in DWORD64 dw64Total,
__in DWORD dwOverallPercentage
)
{
WCHAR wzProgress[5] = { };
#ifdef DEBUG
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "WIXSTDBA: OnCacheAcquireProgress() - container/package: %ls, payload: %ls, progress: %I64u, total: %I64u, overall progress: %u%%", wzPackageOrContainerId, wzPayloadId, dw64Progress, dw64Total, dwOverallPercentage);
#endif
::StringCchPrintfW(wzProgress, countof(wzProgress), L"%u%%", dwOverallPercentage);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_CACHE_PROGRESS_TEXT, wzProgress);
ThemeSetProgressControl(m_pTheme, WIXSTDBA_CONTROL_CACHE_PROGRESS_BAR, dwOverallPercentage);
BAL_INFO_PACKAGE* pPackage = NULL;
HRESULT hr = BalInfoFindPackageById(&m_Bundle.packages, wzPackageOrContainerId, &pPackage);
LPCWSTR wzPackageName = (SUCCEEDED(hr) && pPackage->sczDisplayName) ? pPackage->sczDisplayName : wzPackageOrContainerId;
WCHAR wzInfo[1024] = { };
::StringCchPrintfW(wzInfo, countof(wzInfo), L"Acquiring %s package... [ %u%% ]", wzPackageName, dwOverallPercentage);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_OVERALL_PROGRESS_PACKAGE_TEXT, wzInfo);
// Restrict progress to 100% to hide burn engine progress bug.
// m_dwCalculatedCacheProgress = min(dwOverallPercentage, 100) * WIXSTDBA_ACQUIRE_PERCENTAGE / 100;
#ifdef DEBUG
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "WIXSTDBA: OnCacheAcquireProgress() - calculated progress: %u%%, displayed progress: %u%%", m_dwCalculatedCacheProgress, m_dwCalculatedCacheProgress + m_dwCalculatedExecuteProgress);
#endif
m_dwCalculatedCacheProgress = dwOverallPercentage * WIXSTDBA_ACQUIRE_PERCENTAGE / 100;
ThemeSetProgressControl(m_pTheme, WIXSTDBA_CONTROL_OVERALL_CALCULATED_PROGRESS_BAR, m_dwCalculatedCacheProgress + m_dwCalculatedExecuteProgress);
SetTaskbarButtonProgress(m_dwCalculatedCacheProgress + m_dwCalculatedExecuteProgress);
return __super::OnCacheAcquireProgress(wzPackageOrContainerId, wzPayloadId, dw64Progress, dw64Total, dwOverallPercentage);
}
virtual STDMETHODIMP_(int) OnCacheAcquireComplete(
__in_z LPCWSTR wzPackageOrContainerId,
__in_z_opt LPCWSTR wzPayloadId,
__in HRESULT hrStatus,
__in int nRecommendation
)
{
SetProgressState(hrStatus);
return __super::OnCacheAcquireComplete(wzPackageOrContainerId, wzPayloadId, hrStatus, nRecommendation);
}
virtual STDMETHODIMP_(int) OnCacheVerifyComplete(
__in_z LPCWSTR wzPackageId,
__in_z LPCWSTR wzPayloadId,
__in HRESULT hrStatus,
__in int nRecommendation
)
{
SetProgressState(hrStatus);
return __super::OnCacheVerifyComplete(wzPackageId, wzPayloadId, hrStatus, nRecommendation);
}
virtual STDMETHODIMP_(void) OnCacheComplete(
__in HRESULT /*hrStatus*/
)
{
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_CACHE_PROGRESS_PACKAGE_TEXT, L"");
SetState(WIXSTDBA_STATE_CACHED, S_OK); // we always return success here and let OnApplyComplete() deal with the error.
}
virtual STDMETHODIMP_(int) OnError(
__in BOOTSTRAPPER_ERROR_TYPE errorType,
__in LPCWSTR wzPackageId,
__in DWORD dwCode,
__in_z LPCWSTR wzError,
__in DWORD dwUIHint,
__in DWORD /*cData*/,
__in_ecount_z_opt(cData) LPCWSTR* /*rgwzData*/,
__in int nRecommendation
)
{
int nResult = nRecommendation;
LPWSTR sczError = NULL;
if (BOOTSTRAPPER_DISPLAY_EMBEDDED == m_command.display)
{
HRESULT hr = m_pEngine->SendEmbeddedError(dwCode, wzError, dwUIHint, &nResult);
if (FAILED(hr))
{
nResult = IDERROR;
}
}
else if (BOOTSTRAPPER_DISPLAY_FULL == m_command.display)
{
// If this is an authentication failure, let the engine try to handle it for us.
if (BOOTSTRAPPER_ERROR_TYPE_HTTP_AUTH_SERVER == errorType || BOOTSTRAPPER_ERROR_TYPE_HTTP_AUTH_PROXY == errorType)
{
nResult = IDTRYAGAIN;
}
else // show a generic error message box.
{
BalRetryErrorOccurred(wzPackageId, dwCode);
if (!m_fShowingInternalUiThisPackage)
{
// If no error message was provided, use the error code to try and get an error message.
if (!wzError || !*wzError || BOOTSTRAPPER_ERROR_TYPE_WINDOWS_INSTALLER != errorType)
{
HRESULT hr = StrAllocFromError(&sczError, dwCode, NULL);
if (FAILED(hr) || !sczError || !*sczError)
{
StrAllocFormatted(&sczError, L"0x%x", dwCode);
}
}
nResult = ::MessageBoxW(m_hWnd, sczError ? sczError : wzError, m_pTheme->sczCaption, dwUIHint);
}
}
SetProgressState(HRESULT_FROM_WIN32(dwCode));
}
else // just take note of the error code and let things continue.
{
BalRetryErrorOccurred(wzPackageId, dwCode);
}
ReleaseStr(sczError);
return nResult;
}
virtual STDMETHODIMP_(int) OnExecuteMsiMessage(
__in_z LPCWSTR wzPackageId,
__in INSTALLMESSAGE mt,
__in UINT uiFlags,
__in_z LPCWSTR wzMessage,
__in DWORD cData,
__in_ecount_z_opt(cData) LPCWSTR* rgwzData,
__in int nRecommendation
)
{
#ifdef DEBUG
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "WIXSTDBA: OnExecuteMsiMessage() - package: %ls, message: %ls", wzPackageId, wzMessage);
#endif
if (BOOTSTRAPPER_DISPLAY_FULL == m_command.display && (INSTALLMESSAGE_WARNING == mt || INSTALLMESSAGE_USER == mt))
{
int nResult = ::MessageBoxW(m_hWnd, wzMessage, m_pTheme->sczCaption, uiFlags);
return nResult;
}
if (INSTALLMESSAGE_ACTIONSTART == mt)
{
LPCWSTR wzActionProgressText = NULL;
ExtractActionProgressText(wzMessage, &wzActionProgressText);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_EXECUTE_PROGRESS_ACTIONDATA_TEXT, wzActionProgressText);
}
return __super::OnExecuteMsiMessage(wzPackageId, mt, uiFlags, wzMessage, cData, rgwzData, nRecommendation);
}
virtual STDMETHODIMP_(int) OnProgress(
__in DWORD dwProgressPercentage,
__in DWORD dwOverallProgressPercentage
)
{
WCHAR wzProgress[5] = { };
#ifdef DEBUG
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "WIXSTDBA: OnProgress() - progress: %u%%, overall progress: %u%%", dwProgressPercentage, dwOverallProgressPercentage);
#endif
::StringCchPrintfW(wzProgress, countof(wzProgress), L"%u%%", dwOverallProgressPercentage);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_OVERALL_PROGRESS_TEXT, wzProgress);
ThemeSetProgressControl(m_pTheme, WIXSTDBA_CONTROL_OVERALL_PROGRESS_BAR, dwOverallProgressPercentage);
SetTaskbarButtonProgress(dwOverallProgressPercentage);
return __super::OnProgress(dwProgressPercentage, dwOverallProgressPercentage);
}
virtual STDMETHODIMP_(int) OnExecutePackageBegin(
__in_z LPCWSTR wzPackageId,
__in BOOL fExecute
)
{
if (m_fIsUninstall) {
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_PROGRESS_INSTALLING_HEADER, L"Uninstalling Meteor,\nThe JavaScript App Platform");
} else {
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_PROGRESS_INSTALLING_HEADER, L"Installing Meteor,\nThe JavaScript App Platform");
}
LPWSTR sczFormattedString = NULL;
m_fStartedExecution = TRUE;
if (wzPackageId && *wzPackageId)
{
BAL_INFO_PACKAGE* pPackage = NULL;
BalInfoFindPackageById(&m_Bundle.packages, wzPackageId, &pPackage);
LPCWSTR wz = wzPackageId;
if (pPackage)
{
LOC_STRING* pLocString = NULL;
switch (pPackage->type)
{
case BAL_INFO_PACKAGE_TYPE_BUNDLE_ADDON:
LocGetString(m_pWixLoc, L"#(loc.ExecuteAddonRelatedBundleMessage)", &pLocString);
break;
case BAL_INFO_PACKAGE_TYPE_BUNDLE_PATCH:
LocGetString(m_pWixLoc, L"#(loc.ExecutePatchRelatedBundleMessage)", &pLocString);
break;
case BAL_INFO_PACKAGE_TYPE_BUNDLE_UPGRADE:
LocGetString(m_pWixLoc, L"#(loc.ExecuteUpgradeRelatedBundleMessage)", &pLocString);
break;
}
if (pLocString)
{
BalFormatString(pLocString->wzText, &sczFormattedString);
}
wz = sczFormattedString ? sczFormattedString : pPackage->sczDisplayName ? pPackage->sczDisplayName : wzPackageId;
}
m_fShowingInternalUiThisPackage = pPackage && pPackage->fDisplayInternalUI;
WCHAR wzInfo[1024] = { };
if (m_fIsUninstall)
::StringCchPrintfW(wzInfo, countof(wzInfo), L"Uninstalling %s...", wz);
else
::StringCchPrintfW(wzInfo, countof(wzInfo), L"Installing %s...", wz);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_EXECUTE_PROGRESS_PACKAGE_TEXT, wz);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_OVERALL_PROGRESS_PACKAGE_TEXT, wz);
}
else
{
m_fShowingInternalUiThisPackage = FALSE;
}
ReleaseStr(sczFormattedString);
return __super::OnExecutePackageBegin(wzPackageId, fExecute);
}
virtual int __stdcall OnExecuteProgress(
__in_z LPCWSTR wzPackageId,
__in DWORD dwProgressPercentage,
__in DWORD dwOverallProgressPercentage
)
{
WCHAR wzProgress[5] = { };
#ifdef DEBUG
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "WIXSTDBA: OnExecuteProgress() - package: %ls, progress: %u%%, overall progress: %u%%", wzPackageId, dwProgressPercentage, dwOverallProgressPercentage);
#endif
::StringCchPrintfW(wzProgress, countof(wzProgress), L"%u%%", dwOverallProgressPercentage);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_EXECUTE_PROGRESS_TEXT, wzProgress);
ThemeSetProgressControl(m_pTheme, WIXSTDBA_CONTROL_EXECUTE_PROGRESS_BAR, dwOverallProgressPercentage);
BAL_INFO_PACKAGE* pPackage = NULL;
HRESULT hr = BalInfoFindPackageById(&m_Bundle.packages, wzPackageId, &pPackage);
LPCWSTR wzPackageName = (SUCCEEDED(hr) && pPackage->sczDisplayName) ? pPackage->sczDisplayName : wzPackageId;
WCHAR wzInfo[1024] = { };
if (m_fIsUninstall)
::StringCchPrintfW(wzInfo, countof(wzInfo), L"Uninstalling %s...", wzPackageName, dwProgressPercentage);
else
::StringCchPrintfW(wzInfo, countof(wzInfo), L"Installing %s...", wzPackageName, dwProgressPercentage);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_OVERALL_PROGRESS_PACKAGE_TEXT, wzInfo);
m_dwCalculatedExecuteProgress = dwOverallProgressPercentage * (100 - WIXSTDBA_ACQUIRE_PERCENTAGE) / 100;
#ifdef DEBUG
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "WIXSTDBA: OnExecuteProgress() - calculated progress: %u%%, displayed progress: %u%%", m_dwCalculatedExecuteProgress, m_dwCalculatedCacheProgress + m_dwCalculatedExecuteProgress);
#endif
ThemeSetProgressControl(m_pTheme, WIXSTDBA_CONTROL_OVERALL_CALCULATED_PROGRESS_BAR, m_dwCalculatedCacheProgress + m_dwCalculatedExecuteProgress);
SetTaskbarButtonProgress(m_dwCalculatedCacheProgress + m_dwCalculatedExecuteProgress);
return __super::OnExecuteProgress(wzPackageId, dwProgressPercentage, dwOverallProgressPercentage);
}
virtual STDMETHODIMP_(int) OnExecutePackageComplete(
__in_z LPCWSTR wzPackageId,
__in HRESULT hrExitCode,
__in BOOTSTRAPPER_APPLY_RESTART restart,
__in int nRecommendation
)
{
SetProgressState(hrExitCode);
int nResult = __super::OnExecutePackageComplete(wzPackageId, hrExitCode, restart, nRecommendation);
if (m_sczPrereqPackage && CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, 0, wzPackageId, -1, m_sczPrereqPackage, -1))
{
m_fPrereqInstalled = SUCCEEDED(hrExitCode);
// If the pre-req required a restart (any restart) then do an immediate
// restart to ensure that the bundle will get launched again post reboot.
if (BOOTSTRAPPER_APPLY_RESTART_NONE != restart)
{
nResult = IDRESTART;
}
}
/// On package install complete, if WIXSTDBA_VARIABLE_LOGSPATH is defined
/// then will move the package installation log to the specified path.
if (BalStringVariableExists(WIXSTDBA_VARIABLE_LOGSPATH))
{
LPWSTR wzVarPackageLog = NULL;
StrAllocFormatted(&wzVarPackageLog, L"WixBundleLog_%s", wzPackageId);
if (BalStringVariableExists(wzVarPackageLog))
{
LPWSTR wzPackageLog = NULL;
LPWSTR wzInstallLogPath = NULL;
LPWSTR wzDstPackageLog = NULL;
if ( SUCCEEDED(BalGetStringVariable(WIXSTDBA_VARIABLE_LOGSPATH, &wzInstallLogPath)) &&
SUCCEEDED(BalGetStringVariable(wzVarPackageLog, &wzPackageLog)))
{
StrAllocFormatted(&wzDstPackageLog, L"%s\\%s", wzInstallLogPath, PathFile(wzPackageLog));
DirEnsureExists(wzInstallLogPath, NULL);
FileEnsureMove(wzPackageLog, wzDstPackageLog, TRUE, TRUE);
} else
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Setup was unable to copy logs to the specified installation log path.");
}
}
return nResult;
}
virtual STDMETHODIMP_(void) OnExecuteComplete(
__in HRESULT hrStatus
)
{
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_EXECUTE_PROGRESS_PACKAGE_TEXT, L"");
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_EXECUTE_PROGRESS_ACTIONDATA_TEXT, L"");
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_OVERALL_PROGRESS_PACKAGE_TEXT, L"");
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_PROGRESS_CANCEL_BUTTON, FALSE); // no more cancel.
SetState(WIXSTDBA_STATE_EXECUTED, S_OK); // we always return success here and let OnApplyComplete() deal with the error.
SetProgressState(hrStatus);
}
virtual STDMETHODIMP_(int) OnResolveSource(
__in_z LPCWSTR wzPackageOrContainerId,
__in_z_opt LPCWSTR wzPayloadId,
__in_z LPCWSTR wzLocalSource,
__in_z_opt LPCWSTR wzDownloadSource
)
{
int nResult = IDERROR; // assume we won't resolve source and that is unexpected.
if (BOOTSTRAPPER_DISPLAY_FULL == m_command.display)
{
if (wzDownloadSource)
{
nResult = IDDOWNLOAD;
}
else // prompt to change the source location.
{
OPENFILENAMEW ofn = { };
WCHAR wzFile[MAX_PATH] = { };
::StringCchCopyW(wzFile, countof(wzFile), wzLocalSource);
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = m_hWnd;
ofn.lpstrFile = wzFile;
ofn.nMaxFile = countof(wzFile);
ofn.lpstrFilter = L"All Files\0*.*\0";
ofn.nFilterIndex = 1;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
ofn.lpstrTitle = m_pTheme->sczCaption;
if (::GetOpenFileNameW(&ofn))
{
HRESULT hr = m_pEngine->SetLocalSource(wzPackageOrContainerId, wzPayloadId, ofn.lpstrFile);
nResult = SUCCEEDED(hr) ? IDRETRY : IDERROR;
}
else
{
nResult = IDCANCEL;
}
}
}
else if (wzDownloadSource)
{
// If doing a non-interactive install and download source is available, let's try downloading the package silently
nResult = IDDOWNLOAD;
}
// else there's nothing more we can do in non-interactive mode
return CheckCanceled() ? IDCANCEL : nResult;
}
virtual STDMETHODIMP_(int) OnApplyComplete(
__in HRESULT hrStatus,
__in BOOTSTRAPPER_APPLY_RESTART restart
)
{
m_restartResult = restart; // remember the restart result so we return the correct error code no matter what the user chooses to do in the UI.
// If a restart was encountered and we are not suppressing restarts, then restart is required.
m_fRestartRequired = (BOOTSTRAPPER_APPLY_RESTART_NONE != restart && BOOTSTRAPPER_RESTART_NEVER < m_command.restart);
// If a restart is required and we're not displaying a UI or we are not supposed to prompt for restart then allow the restart.
m_fAllowRestart = m_fRestartRequired && (BOOTSTRAPPER_DISPLAY_FULL > m_command.display || BOOTSTRAPPER_RESTART_PROMPT < m_command.restart);
// If we are showing UI, wait a beat before moving to the final screen.
if (BOOTSTRAPPER_DISPLAY_NONE < m_command.display)
{
::Sleep(250);
}
if (m_command.action == BOOTSTRAPPER_ACTION_UNINSTALL || BOOTSTRAPPER_DISPLAY_FULL > m_command.display)
SetState(WIXSTDBA_STATE_APPLIED, S_OK);
else
SetState(WIXSTDBA_STATE_SVC_OPTIONS, hrStatus);
// If we successfully applied an update close the window since the new Bundle should be running now.
if (SUCCEEDED(hrStatus) && m_fUpdating)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Update downloaded, close bundle.");
::PostMessageW(m_hWnd, WM_CLOSE, 0, 0);
}
return IDNOACTION;
}
private: // privates
//
// UiThreadProc - entrypoint for UI thread.
//
static DWORD WINAPI UiThreadProc(
__in LPVOID pvContext
)
{
HRESULT hr = S_OK;
CWixStandardBootstrapperApplication* pThis = (CWixStandardBootstrapperApplication*)pvContext;
BOOL fComInitialized = FALSE;
BOOL fRet = FALSE;
MSG msg = { };
// Initialize COM and theme.
hr = ::CoInitialize(NULL);
BalExitOnFailure(hr, "Failed to initialize COM.");
fComInitialized = TRUE;
hr = ThemeInitialize(pThis->m_hModule);
BalExitOnFailure(hr, "Failed to initialize theme manager.");
hr = pThis->InitializeData();
BalExitOnFailure(hr, "Failed to initialize data in bootstrapper application.");
// Create main window.
pThis->InitializeTaskbarButton();
hr = pThis->CreateMainWindow();
BalExitOnFailure(hr, "Failed to create main window.");
// Okay, we're ready for packages now.
pThis->SetState(WIXSTDBA_STATE_INITIALIZED, hr);
::PostMessageW(pThis->m_hWnd, BOOTSTRAPPER_ACTION_HELP == pThis->m_command.action ? WM_WIXSTDBA_SHOW_HELP : WM_WIXSTDBA_DETECT_PACKAGES, 0, 0);
// message pump
while (0 != (fRet = ::GetMessageW(&msg, NULL, 0, 0)))
{
if (-1 == fRet)
{
hr = E_UNEXPECTED;
BalExitOnFailure(hr, "Unexpected return value from message pump.");
}
else if (!ThemeHandleKeyboardMessage(pThis->m_pTheme, msg.hwnd, &msg))
{
::TranslateMessage(&msg);
::DispatchMessageW(&msg);
}
}
// Succeeded thus far, check to see if anything went wrong while actually
// executing changes.
if (FAILED(pThis->m_hrFinal))
{
hr = pThis->m_hrFinal;
}
else if (pThis->CheckCanceled())
{
hr = HRESULT_FROM_WIN32(ERROR_INSTALL_USEREXIT);
}
LExit:
// destroy main window
pThis->DestroyMainWindow();
// initiate engine shutdown
DWORD dwQuit = HRESULT_CODE(hr);
if (BOOTSTRAPPER_APPLY_RESTART_INITIATED == pThis->m_restartResult)
{
dwQuit = ERROR_SUCCESS_REBOOT_INITIATED;
}
else if (BOOTSTRAPPER_APPLY_RESTART_REQUIRED == pThis->m_restartResult)
{
dwQuit = ERROR_SUCCESS_REBOOT_REQUIRED;
}
pThis->m_pEngine->Quit(dwQuit);
ReleaseTheme(pThis->m_pTheme);
ThemeUninitialize();
// uninitialize COM
if (fComInitialized)
{
::CoUninitialize();
}
return hr;
}
static DWORD WINAPI ThreadProc(
__in LPVOID pvContext
)
{
CWixStandardBootstrapperApplication* pThis = static_cast<CWixStandardBootstrapperApplication*>(pvContext);;
HRESULT hr = S_OK;
IXMLDOMDocument *pixd = NULL;
IXMLDOMNode* pNode = NULL;
LPWSTR sczUpdateUrl = NULL;
DWORD64 qwSize = 0;
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Checking for update.");
// Load the update XML from a location url and parse it for an update.
//
// <?xml version="1.0" encoding="utf-8"?>
// <Setup>
// <Upgrade Url="https://somewhere.co.uk/download/Setup.exe" Size="123" />
// </Setup>
hr = XmlLoadDocumentFromFile(pThis->m_wzUpdateLocation, &pixd);
BalExitOnFailure(hr, "Failed to load version check XML document.");
hr = XmlSelectSingleNode(pixd, L"/Setup/Upgrade", &pNode);
BalExitOnFailure(hr, "Failed to select upgrade node.");
if (S_OK == hr)
{
hr = XmlGetAttributeEx(pNode, L"Url", &sczUpdateUrl);
BalExitOnFailure(hr, "Failed to get url attribute.");
hr = XmlGetAttributeLargeNumber(pNode, L"Size", &qwSize);
}
if (sczUpdateUrl && *sczUpdateUrl)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Update available, url: %ls; size: %I64u.", sczUpdateUrl, qwSize);
// Show upgrade on install and modify pages
if (pThis->m_rgdwPageIds[WIXSTDBA_PAGE_INSTALL] == pThis->m_dwCurrentPage ||
pThis->m_rgdwPageIds[WIXSTDBA_PAGE_MODIFY] == pThis->m_dwCurrentPage)
{
pThis->m_pEngine->SetUpdate(NULL, sczUpdateUrl, qwSize, BOOTSTRAPPER_UPDATE_HASH_TYPE_NONE, NULL, 0);
ThemeControlEnable(pThis->m_pTheme, WIXSTDBA_CONTROL_UPGRADE_LINK, TRUE);
}
}
else
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "No update available.");
}
LExit:
ReleaseObject(pixd);
ReleaseObject(pNode);
ReleaseStr(sczUpdateUrl);
return 0;
}
//
// InitializeData - initializes all the package and prereq information.
//
HRESULT InitializeData()
{
HRESULT hr = S_OK;
LPWSTR sczModulePath = NULL;
IXMLDOMDocument *pixdManifest = NULL;
hr = BalManifestLoad(m_hModule, &pixdManifest);
BalExitOnFailure(hr, "Failed to load bootstrapper application manifest.");
hr = ParseOverridableVariablesFromXml(pixdManifest);
BalExitOnFailure(hr, "Failed to read overridable variables.");
hr = ProcessCommandLine(&m_sczLanguage);
ExitOnFailure(hr, "Unknown commandline parameters.");
// Override default language to correctly support UK English (this is not required in WiX 3.8)
if (!(m_sczLanguage && *m_sczLanguage))
{
hr = StrAllocFormatted(&m_sczLanguage, L"%u", ::GetUserDefaultLangID());
BalExitOnFailure(hr, "Failed to set language.");
}
hr = PathRelativeToModule(&sczModulePath, NULL, m_hModule);
BalExitOnFailure(hr, "Failed to get module path.");
hr = LoadLocalization(sczModulePath, m_sczLanguage);
ExitOnFailure(hr, "Failed to load localization.");
hr = LoadTheme(sczModulePath, m_sczLanguage);
ExitOnFailure(hr, "Failed to load theme.");
hr = BalInfoParseFromXml(&m_Bundle, pixdManifest);
BalExitOnFailure(hr, "Failed to load bundle information.");
hr = BalConditionsParseFromXml(&m_Conditions, pixdManifest, m_pWixLoc);
BalExitOnFailure(hr, "Failed to load conditions from XML.");
LoadBootstrapperBAFunctions();
hr = ParseBootrapperApplicationDataFromXml(pixdManifest);
BalExitOnFailure(hr, "Failed to read bootstrapper application data.");
LOC_STRING* pLocString = NULL;
LocGetString(m_pWixLoc, L"#(loc.ProgressHeader)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_PROGRESS_HEADER, pLocString->wzText);
LocGetString(m_pWixLoc, L"#(loc.ProgressInfo)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_PROGRESS_INFO, pLocString->wzText);
LocGetString(m_pWixLoc, L"#(loc.SuccessHeader)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_SUCCESS_HEADER, pLocString->wzText);
LocGetString(m_pWixLoc, L"#(loc.SuccessInfo)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_SUCCESS_INFO, pLocString->wzText);
LocGetString(m_pWixLoc, L"#(loc.FailureHeader)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_FAILURE_HEADER, pLocString->wzText);
if (m_fPrereq)
{
hr = ParsePrerequisiteInformationFromXml(pixdManifest);
BalExitOnFailure(hr, "Failed to read prerequisite information.");
}
else
{
hr = ParseBootrapperApplicationDataFromXml(pixdManifest);
BalExitOnFailure(hr, "Failed to read bootstrapper application data.");
}
if (m_fOutputToConsole)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Write to console command was detected! Trying to attach to the parent console process");
BOOL bAttCons = AttachConsole(ATTACH_PARENT_PROCESS);
if (!bAttCons)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Failed to attach to parent process.");
}
if (bAttCons)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Successfully attached to parent console process.");
m_fStdConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
m_fAttachedToConsole = ((m_fStdConsoleHandle != NULL) && (m_fStdConsoleHandle != INVALID_HANDLE_VALUE));
if (!m_fAttachedToConsole)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Failed to get the console handle");
FreeConsole();
}
}
if (!m_fAttachedToConsole)
{
hr = E_UNEXPECTED;
BalExitOnFailure(hr, "Failed to setup console output. Setup will exit now!");
}
}
LExit:
ReleaseObject(pixdManifest);
ReleaseStr(sczModulePath);
return hr;
}
//
// ProcessCommandLine - process the provided command line arguments.
//
HRESULT ProcessCommandLine(
__inout LPWSTR* psczLanguage
)
{
HRESULT hr = S_OK;
int argc = 0;
LPWSTR* argv = NULL;
LPWSTR sczVariableName = NULL;
LPWSTR sczVariableValue = NULL;
if (m_command.wzCommandLine && *m_command.wzCommandLine)
{
argv = ::CommandLineToArgvW(m_command.wzCommandLine, &argc);
ExitOnNullWithLastError(argv, hr, "Failed to get command line.");
for (int i = 0; i < argc; ++i)
{
if (argv[i][0] == L'-' || argv[i][0] == L'/')
{
if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, &argv[i][1], -1, L"lang", -1))
{
if (i + 1 >= argc)
{
hr = E_INVALIDARG;
BalExitOnFailure(hr, "Must specify a language.");
}
++i;
hr = StrAllocString(psczLanguage, &argv[i][0], 0);
BalExitOnFailure(hr, "Failed to copy language.");
}
}
if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, &argv[i][1], -1, L"toconsole", -1))
{
m_fOutputToConsole = TRUE;
m_command.display = BOOTSTRAPPER_DISPLAY_NONE;
if (BOOTSTRAPPER_RESTART_UNKNOWN == m_command.restart)
{
m_command.restart = BOOTSTRAPPER_RESTART_AUTOMATIC;
}
}
else if (m_sdOverridableVariables)
{
const wchar_t* pwc = wcschr(argv[i], L'=');
if (pwc)
{
hr = StrAllocString(&sczVariableName, argv[i], pwc - argv[i]);
BalExitOnFailure(hr, "Failed to copy variable name.");
hr = DictKeyExists(m_sdOverridableVariables, sczVariableName);
if (E_NOTFOUND == hr)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Ignoring attempt to set non-overridable variable: '%ls'.", sczVariableName);
hr = S_OK;
continue;
}
ExitOnFailure(hr, "Failed to check the dictionary of overridable variables.");
hr = StrAllocString(&sczVariableValue, ++pwc, 0);
BalExitOnFailure(hr, "Failed to copy variable value.");
hr = m_pEngine->SetVariableString(sczVariableName, sczVariableValue);
BalExitOnFailure(hr, "Failed to set variable.");
}
else
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Ignoring unknown argument: %ls", argv[i]);
}
}
}
}
LExit:
if (argv)
{
::LocalFree(argv);
}
ReleaseStr(sczVariableName);
ReleaseStr(sczVariableValue);
return hr;
}
HRESULT LoadLocalization(
__in_z LPCWSTR wzModulePath,
__in_z_opt LPCWSTR wzLanguage
)
{
HRESULT hr = S_OK;
LPWSTR sczLocPath = NULL;
LPCWSTR wzLocFileName = L"thm.wxl";
hr = LocProbeForFile(wzModulePath, wzLocFileName, wzLanguage, &sczLocPath);
BalExitOnFailure2(hr, "Failed to probe for loc file: %ls in path: %ls", wzLocFileName, wzModulePath);
hr = LocLoadFromFile(sczLocPath, &m_pWixLoc);
BalExitOnFailure1(hr, "Failed to load loc file from path: %ls", sczLocPath);
if (WIX_LOCALIZATION_LANGUAGE_NOT_SET != m_pWixLoc->dwLangId)
{
::SetThreadLocale(m_pWixLoc->dwLangId);
}
hr = StrAllocString(&m_sczConfirmCloseMessage, L"#(loc.ConfirmCancelMessage)", 0);
ExitOnFailure(hr, "Failed to initialize confirm message loc identifier.");
hr = LocLocalizeString(m_pWixLoc, &m_sczConfirmCloseMessage);
BalExitOnFailure1(hr, "Failed to localize confirm close message: %ls", m_sczConfirmCloseMessage);
LExit:
ReleaseStr(sczLocPath);
return hr;
}
HRESULT LoadTheme(
__in_z LPCWSTR wzModulePath,
__in_z_opt LPCWSTR wzLanguage
)
{
HRESULT hr = S_OK;
LPWSTR sczThemePath = NULL;
LPCWSTR wzThemeFileName = L"thm.xml";
LPWSTR sczCaption = NULL;
hr = LocProbeForFile(wzModulePath, wzThemeFileName, wzLanguage, &sczThemePath);
BalExitOnFailure2(hr, "Failed to probe for theme file: %ls in path: %ls", wzThemeFileName, wzModulePath);
hr = ThemeLoadFromFile(sczThemePath, &m_pTheme);
BalExitOnFailure1(hr, "Failed to load theme from path: %ls", sczThemePath);
hr = ThemeLocalize(m_pTheme, m_pWixLoc);
BalExitOnFailure1(hr, "Failed to localize theme: %ls", sczThemePath);
// Update the caption if there are any formatted strings in it.
hr = BalFormatString(m_pTheme->sczCaption, &sczCaption);
if (SUCCEEDED(hr))
{
ThemeUpdateCaption(m_pTheme, sczCaption);
}
LExit:
ReleaseStr(sczCaption);
ReleaseStr(sczThemePath);
return hr;
}
HRESULT ParseOverridableVariablesFromXml(
__in IXMLDOMDocument* pixdManifest
)
{
HRESULT hr = S_OK;
IXMLDOMNode* pNode = NULL;
IXMLDOMNodeList* pNodes = NULL;
DWORD cNodes = 0;
LPWSTR scz = NULL;
// get the list of variables users can override on the command line
hr = XmlSelectNodes(pixdManifest, L"/BootstrapperApplicationData/WixStdbaOverridableVariable", &pNodes);
if (S_FALSE == hr)
{
ExitFunction1(hr = S_OK);
}
ExitOnFailure(hr, "Failed to select overridable variable nodes.");
hr = pNodes->get_length((long*)&cNodes);
ExitOnFailure(hr, "Failed to get overridable variable node count.");
if (cNodes)
{
hr = DictCreateStringList(&m_sdOverridableVariables, 32, DICT_FLAG_NONE);
ExitOnFailure(hr, "Failed to create the string dictionary.");
for (DWORD i = 0; i < cNodes; ++i)
{
hr = XmlNextElement(pNodes, &pNode, NULL);
ExitOnFailure(hr, "Failed to get next node.");
// @Name
hr = XmlGetAttributeEx(pNode, L"Name", &scz);
ExitOnFailure(hr, "Failed to get @Name.");
hr = DictAddKey(m_sdOverridableVariables, scz);
ExitOnFailure1(hr, "Failed to add \"%ls\" to the string dictionary.", scz);
// prepare next iteration
ReleaseNullObject(pNode);
}
}
LExit:
ReleaseObject(pNode);
ReleaseObject(pNodes);
ReleaseStr(scz);
return hr;
}
HRESULT ParsePrerequisiteInformationFromXml(
__in IXMLDOMDocument* pixdManifest
)
{
HRESULT hr = S_OK;
IXMLDOMNode* pNode = NULL;
hr = XmlSelectSingleNode(pixdManifest, L"/BootstrapperApplicationData/WixMbaPrereqInformation", &pNode);
if (S_FALSE == hr)
{
hr = E_INVALIDARG;
}
BalExitOnFailure(hr, "BootstrapperApplication.xml manifest is missing prerequisite information.");
hr = XmlGetAttributeEx(pNode, L"PackageId", &m_sczPrereqPackage);
BalExitOnFailure(hr, "Failed to get prerequisite package identifier.");
hr = XmlGetAttributeEx(pNode, L"LicenseUrl", &m_sczLicenseUrl);
if (E_NOTFOUND == hr)
{
hr = S_OK;
}
BalExitOnFailure(hr, "Failed to get prerequisite license URL.");
hr = XmlGetAttributeEx(pNode, L"LicenseFile", &m_sczLicenseFile);
if (E_NOTFOUND == hr)
{
hr = S_OK;
}
BalExitOnFailure(hr, "Failed to get prerequisite license file.");
LExit:
ReleaseObject(pNode);
return hr;
}
HRESULT ParseBootrapperApplicationDataFromXml(
__in IXMLDOMDocument* pixdManifest
)
{
HRESULT hr = S_OK;
IXMLDOMNode* pNode = NULL;
DWORD dwBool = 0;
hr = XmlSelectSingleNode(pixdManifest, L"/BootstrapperApplicationData/WixExtbaInformation", &pNode);
if (S_FALSE == hr)
{
hr = E_INVALIDARG;
}
BalExitOnFailure(hr, "BootstrapperApplication.xml manifest is missing wixextba information.");
hr = XmlGetAttributeEx(pNode, L"LicenseFile", &m_sczLicenseFile);
if (E_NOTFOUND == hr)
{
hr = S_OK;
}
BalExitOnFailure(hr, "Failed to get license file.");
hr = XmlGetAttributeEx(pNode, L"LicenseUrl", &m_sczLicenseUrl);
if (E_NOTFOUND == hr)
{
hr = S_OK;
}
BalExitOnFailure(hr, "Failed to get license URL.");
ReleaseObject(pNode);
hr = XmlSelectSingleNode(pixdManifest, L"/BootstrapperApplicationData/WixExtbaOptions", &pNode);
if (S_FALSE == hr)
{
ExitFunction1(hr = S_OK);
}
BalExitOnFailure(hr, "Failed to read wixextba options from BootstrapperApplication.xml manifest.");
hr = XmlGetAttributeNumber(pNode, L"SuppressOptionsUI", &dwBool);
if (E_NOTFOUND == hr)
{
hr = S_OK;
}
else if (SUCCEEDED(hr))
{
m_fSuppressOptionsUI = 0 < dwBool;
}
BalExitOnFailure(hr, "Failed to get SuppressOptionsUI value.");
dwBool = 0;
hr = XmlGetAttributeNumber(pNode, L"SuppressDowngradeFailure", &dwBool);
if (E_NOTFOUND == hr)
{
hr = S_OK;
}
else if (SUCCEEDED(hr))
{
m_fSuppressDowngradeFailure = 0 < dwBool;
}
BalExitOnFailure(hr, "Failed to get SuppressDowngradeFailure value.");
dwBool = 0;
hr = XmlGetAttributeNumber(pNode, L"SuppressRepair", &dwBool);
if (E_NOTFOUND == hr)
{
hr = S_OK;
}
else if (SUCCEEDED(hr))
{
m_fSuppressRepair = 0 < dwBool;
}
BalExitOnFailure(hr, "Failed to get SuppressRepair value.");
hr = XmlGetAttributeNumber(pNode, L"ShowVersion", &dwBool);
if (E_NOTFOUND == hr)
{
hr = S_OK;
}
else if (SUCCEEDED(hr))
{
m_fShowVersion = 0 < dwBool;
}
BalExitOnFailure(hr, "Failed to get ShowVersion value.");
LExit:
ReleaseObject(pNode);
return hr;
}
//
// CreateMainWindow - creates the main install window.
//
HRESULT CreateMainWindow()
{
HRESULT hr = S_OK;
HICON hIcon = reinterpret_cast<HICON>(m_pTheme->hIcon);
WNDCLASSW wc = { };
DWORD dwWindowStyle = 0;
int x = CW_USEDEFAULT;
int y = CW_USEDEFAULT;
POINT ptCursor = { };
HMONITOR hMonitor = NULL;
MONITORINFO mi = { };
// If the theme did not provide an icon, try using the icon from the bundle engine.
if (!hIcon)
{
HMODULE hBootstrapperEngine = ::GetModuleHandleW(NULL);
if (hBootstrapperEngine)
{
hIcon = ::LoadIconW(hBootstrapperEngine, MAKEINTRESOURCEW(1));
}
}
// Register the window class and create the window.
wc.lpfnWndProc = CWixStandardBootstrapperApplication::WndProc;
wc.hInstance = m_hModule;
wc.hIcon = hIcon;
wc.hCursor = ::LoadCursorW(NULL, (LPCWSTR)IDC_ARROW);
wc.hbrBackground = m_pTheme->rgFonts[m_pTheme->dwFontId].hBackground;
wc.lpszMenuName = NULL;
wc.lpszClassName = WIXSTDBA_WINDOW_CLASS;
if (!::RegisterClassW(&wc))
{
ExitWithLastError(hr, "Failed to register window.");
}
m_fRegistered = TRUE;
// Calculate the window style based on the theme style and command display value.
dwWindowStyle = m_pTheme->dwStyle;
if (BOOTSTRAPPER_DISPLAY_NONE >= m_command.display)
{
dwWindowStyle &= ~WS_VISIBLE;
}
// Don't show the window if there is a splash screen (it will be made visible when the splash screen is hidden)
if (::IsWindow(m_command.hwndSplashScreen))
{
dwWindowStyle &= ~WS_VISIBLE;
}
// Center the window on the monitor with the mouse.
if (::GetCursorPos(&ptCursor))
{
hMonitor = ::MonitorFromPoint(ptCursor, MONITOR_DEFAULTTONEAREST);
if (hMonitor)
{
mi.cbSize = sizeof(mi);
if (::GetMonitorInfoW(hMonitor, &mi))
{
x = mi.rcWork.left + (mi.rcWork.right - mi.rcWork.left - m_pTheme->nWidth) / 2;
y = mi.rcWork.top + (mi.rcWork.bottom - mi.rcWork.top - m_pTheme->nHeight) / 2;
}
}
}
m_hWnd = ::CreateWindowExW(0, wc.lpszClassName, m_pTheme->sczCaption, dwWindowStyle, x, y, m_pTheme->nWidth, m_pTheme->nHeight, HWND_DESKTOP, NULL, m_hModule, this);
ExitOnNullWithLastError(m_hWnd, hr, "Failed to create window.");
hr = S_OK;
LExit:
return hr;
}
//
// InitializeTaskbarButton - initializes taskbar button for progress.
//
void InitializeTaskbarButton()
{
HRESULT hr = S_OK;
hr = ::CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL, __uuidof(ITaskbarList3), reinterpret_cast<LPVOID*>(&m_pTaskbarList));
if (REGDB_E_CLASSNOTREG == hr) // not supported before Windows 7
{
ExitFunction1(hr = S_OK);
}
BalExitOnFailure(hr, "Failed to create ITaskbarList3. Continuing.");
m_uTaskbarButtonCreatedMessage = ::RegisterWindowMessageW(L"TaskbarButtonCreated");
BalExitOnNullWithLastError(m_uTaskbarButtonCreatedMessage, hr, "Failed to get TaskbarButtonCreated message. Continuing.");
LExit:
return;
}
//
// DestroyMainWindow - clean up all the window registration.
//
void DestroyMainWindow()
{
if (::IsWindow(m_hWnd))
{
::DestroyWindow(m_hWnd);
m_hWnd = NULL;
m_fTaskbarButtonOK = FALSE;
}
if (m_fRegistered)
{
::UnregisterClassW(WIXSTDBA_WINDOW_CLASS, m_hModule);
m_fRegistered = FALSE;
}
}
//
// WndProc - standard windows message handler.
//
static LRESULT CALLBACK WndProc(
__in HWND hWnd,
__in UINT uMsg,
__in WPARAM wParam,
__in LPARAM lParam
)
{
#pragma warning(suppress:4312)
CWixStandardBootstrapperApplication* pBA = reinterpret_cast<CWixStandardBootstrapperApplication*>(::GetWindowLongPtrW(hWnd, GWLP_USERDATA));
switch (uMsg)
{
case WM_NCCREATE:
{
LPCREATESTRUCT lpcs = reinterpret_cast<LPCREATESTRUCT>(lParam);
pBA = reinterpret_cast<CWixStandardBootstrapperApplication*>(lpcs->lpCreateParams);
#pragma warning(suppress:4244)
::SetWindowLongPtrW(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pBA));
}
break;
case WM_NCDESTROY:
{
LRESULT lres = ThemeDefWindowProc(pBA ? pBA->m_pTheme : NULL, hWnd, uMsg, wParam, lParam);
::SetWindowLongPtrW(hWnd, GWLP_USERDATA, 0);
return lres;
}
case WM_CREATE:
if (!pBA->OnCreate(hWnd))
{
return -1;
}
break;
case WM_QUERYENDSESSION:
return IDCANCEL != pBA->OnSystemShutdown(static_cast<DWORD>(lParam), IDCANCEL);
case WM_CLOSE:
// If the user chose not to close, do *not* let the default window proc handle the message.
if (!pBA->OnClose())
{
return 0;
}
break;
case WM_DESTROY:
::PostQuitMessage(0);
break;
case WM_WIXSTDBA_SHOW_HELP:
pBA->OnShowHelp();
return 0;
case WM_WIXSTDBA_DETECT_PACKAGES:
pBA->OnDetect();
return 0;
case WM_WIXSTDBA_PLAN_PACKAGES:
pBA->OnPlan(static_cast<BOOTSTRAPPER_ACTION>(lParam));
return 0;
case WM_WIXSTDBA_APPLY_PACKAGES:
pBA->OnApply();
return 0;
case WM_WIXSTDBA_CHANGE_STATE:
pBA->OnChangeState(static_cast<WIXSTDBA_STATE>(lParam));
return 0;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case WIXSTDBA_CONTROL_EULA_ACCEPT_CHECKBOX:
pBA->OnClickAcceptCheckbox();
return 0;
case WIXSTDBA_CONTROL_PERMACHINE_RADIO: __fallthrough;
case WIXSTDBA_CONTROL_PERUSER_RADIO:
pBA->OnClickInstallScope();
return 0;
case WIXSTDBA_CONTROL_REGSIGNIN_RADIO: __fallthrough;
case WIXSTDBA_CONTROL_REGCREATE_RADIO: __fallthrough;
case WIXSTDBA_CONTROL_SKIPREG_CHECKBOX:
pBA->OnClickSkipRegistrationCheckbox();
return 0;
case WIXSTDBA_CONTROL_OPTIONS_BUTTON:
pBA->OnClickOptionsButton();
return 0;
case WIXSTDBA_CONTROL_BROWSE_BUTTON:
pBA->OnClickOptionsBrowseButton(WIXSTDBA_CONTROL_BROWSE_BUTTON);
return 0;
case WIXSTDBA_CONTROL_OK_BUTTON:
pBA->OnClickOptionsOkButton();
return 0;
case WIXSTDBA_CONTROL_CANCEL_BUTTON:
pBA->OnClickOptionsCancelButton();
return 0;
case WIXSTDBA_CONTROL_SKIP_BUTTON:
pBA->SetState(WIXSTDBA_STATE_APPLIED, S_OK);
return 0;
case WIXSTDBA_CONTROL_INSTALL_BUTTON:
pBA->OnSignIn();
return 0;
case WIXSTDBA_CONTROL_REPAIR_BUTTON:
pBA->OnClickRepairButton();
return 0;
case WIXSTDBA_CONTROL_UNINSTALL_BUTTON:
pBA->OnClickUninstallButton();
return 0;
case WIXSTDBA_CONTROL_LAUNCH_BUTTON:
pBA->OnClickLaunchButton();
return 0;
case WIXSTDBA_CONTROL_SUCCESS_RESTART_BUTTON: __fallthrough;
case WIXSTDBA_CONTROL_FAILURE_RESTART_BUTTON:
pBA->OnClickRestartButton();
return 0;
case WIXSTDBA_CONTROL_HELP_CANCEL_BUTTON: __fallthrough;
case WIXSTDBA_CONTROL_WELCOME_CANCEL_BUTTON: __fallthrough;
case WIXSTDBA_CONTROL_MODIFY_CANCEL_BUTTON: __fallthrough;
case WIXSTDBA_CONTROL_PROGRESS_CANCEL_BUTTON: __fallthrough;
case WIXSTDBA_CONTROL_SUCCESS_CANCEL_BUTTON: __fallthrough;
case WIXSTDBA_CONTROL_FAILURE_CANCEL_BUTTON: __fallthrough;
case WIXSTDBA_CONTROL_CLOSE_BUTTON:
pBA->OnClickCloseButton();
return 0;
case WIXSTDBA_CONTROL_NEXT_BUTTON:
pBA->OnClickNextButton();
return 0;
case WIXSTDBA_CONTROL_BACK_BUTTON:
pBA->OnClickBackButton();
return 0;
}
break;
case WM_NOTIFY:
if (lParam)
{
LPNMHDR pnmhdr = reinterpret_cast<LPNMHDR>(lParam);
switch (pnmhdr->code)
{
case NM_CLICK: __fallthrough;
case NM_RETURN:
switch (static_cast<DWORD>(pnmhdr->idFrom))
{
case WIXSTDBA_CONTROL_EULA_LINK:
pBA->OnClickEulaLink();
return 1;
case WIXSTDBA_CONTROL_FAILURE_LOGFILE_LINK:
pBA->OnClickLogFileLink();
return 1;
case WIXSTDBA_CONTROL_UPGRADE_LINK:
pBA->OnClickUpgradeLink();
return 1;
}
}
}
break;
}
if (pBA && pBA->m_pTaskbarList && uMsg == pBA->m_uTaskbarButtonCreatedMessage)
{
pBA->m_fTaskbarButtonOK = TRUE;
return 0;
}
return ThemeDefWindowProc(pBA ? pBA->m_pTheme : NULL, hWnd, uMsg, wParam, lParam);
}
//
// OnCreate - finishes loading the theme.
//
BOOL OnCreate(
__in HWND hWnd
)
{
HRESULT hr = S_OK;
LPWSTR sczText = NULL;
LPWSTR sczLicenseFormatted = NULL;
LPWSTR sczLicensePath = NULL;
LPWSTR sczLicenseDirectory = NULL;
LPWSTR sczLicenseFilename = NULL;
hr = ThemeLoadControls(m_pTheme, hWnd, vrgInitControls, countof(vrgInitControls));
BalExitOnFailure(hr, "Failed to load theme controls.");
C_ASSERT(COUNT_WIXSTDBA_PAGE == countof(vrgwzPageNames));
C_ASSERT(countof(m_rgdwPageIds) == countof(vrgwzPageNames));
ThemeGetPageIds(m_pTheme, vrgwzPageNames, m_rgdwPageIds, countof(m_rgdwPageIds));
// Initialize the text on all "application" (non-page) controls.
for (DWORD i = 0; i < m_pTheme->cControls; ++i)
{
THEME_CONTROL* pControl = m_pTheme->rgControls + i;
if (!pControl->wPageId && pControl->sczText && *pControl->sczText)
{
HRESULT hrFormat = BalFormatString(pControl->sczText, &sczText);
if (SUCCEEDED(hrFormat))
{
ThemeSetTextControl(m_pTheme, pControl->wId, sczText);
}
}
}
// Load the RTF EULA control with text if the control exists.
if (ThemeControlExists(m_pTheme, WIXSTDBA_CONTROL_EULA_RICHEDIT))
{
hr = (m_sczLicenseFile && *m_sczLicenseFile) ? S_OK : E_INVALIDDATA;
if (SUCCEEDED(hr))
{
hr = StrAllocString(&sczLicenseFormatted, m_sczLicenseFile, 0);
if (SUCCEEDED(hr))
{
hr = LocLocalizeString(m_pWixLoc, &sczLicenseFormatted);
if (SUCCEEDED(hr))
{
hr = BalFormatString(sczLicenseFormatted, &sczLicenseFormatted);
if (SUCCEEDED(hr))
{
hr = PathRelativeToModule(&sczLicensePath, sczLicenseFormatted, m_hModule);
if (SUCCEEDED(hr))
{
hr = PathGetDirectory(sczLicensePath, &sczLicenseDirectory);
if (SUCCEEDED(hr))
{
hr = StrAllocString(&sczLicenseFilename, PathFile(sczLicenseFormatted), 0);
if (SUCCEEDED(hr))
{
hr = LocProbeForFile(sczLicenseDirectory, sczLicenseFilename, m_sczLanguage, &sczLicensePath);
if (SUCCEEDED(hr))
{
hr = ThemeLoadRichEditFromFile(m_pTheme, WIXSTDBA_CONTROL_EULA_RICHEDIT, sczLicensePath, m_hModule);
}
}
}
}
}
}
}
}
if (FAILED(hr))
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Failed to load file into license richedit control from path '%ls' manifest value: %ls", sczLicensePath, m_sczLicenseFile);
hr = S_OK;
}
}
LExit:
ReleaseStr(sczLicenseFilename);
ReleaseStr(sczLicenseDirectory);
ReleaseStr(sczLicensePath);
ReleaseStr(sczLicenseFormatted);
ReleaseStr(sczText);
return SUCCEEDED(hr);
}
//
// OnShowHelp - display the help page.
//
void OnShowHelp()
{
SetState(WIXSTDBA_STATE_HELP, S_OK);
// If the UI should be visible, display it now and hide the splash screen
if (BOOTSTRAPPER_DISPLAY_NONE < m_command.display)
{
::ShowWindow(m_pTheme->hwndParent, SW_SHOW);
}
m_pEngine->CloseSplashScreen();
return;
}
//
// OnDetect - start the processing of packages.
//
void OnDetect()
{
HRESULT hr = S_OK;
if (m_pBAFunction)
{
hr = m_pBAFunction->OnDetect();
BalExitOnFailure(hr, "Failed calling detect BA function.");
}
SetState(WIXSTDBA_STATE_DETECTING, hr);
// If the UI should be visible, display it now and hide the splash screen
if (BOOTSTRAPPER_DISPLAY_NONE < m_command.display)
{
::ShowWindow(m_pTheme->hwndParent, SW_SHOW);
}
m_pEngine->CloseSplashScreen();
// Tell the core we're ready for the packages to be processed now.
hr = m_pEngine->Detect();
BalExitOnFailure(hr, "Failed to start detecting chain.");
LExit:
if (FAILED(hr))
{
SetState(WIXSTDBA_STATE_DETECTING, hr);
}
return;
}
//
// OnPlan - plan the detected changes.
//
void OnPlan(
__in BOOTSTRAPPER_ACTION action
)
{
HRESULT hr = S_OK;
m_plannedAction = action;
LOC_STRING* pLocString = NULL;
if (m_plannedAction == BOOTSTRAPPER_ACTION_UNINSTALL)
{
m_fIsUninstall = TRUE;
LocGetString(m_pWixLoc, L"#(loc.ProgressHeaderUninstall)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_PROGRESS_HEADER, pLocString->wzText);
LocGetString(m_pWixLoc, L"#(loc.ProgressInfoUninstall)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_PROGRESS_INFO, pLocString->wzText);
}
if (m_plannedAction == BOOTSTRAPPER_ACTION_REPAIR)
{
m_fIsRepair = TRUE;
LocGetString(m_pWixLoc, L"#(loc.ProgressHeaderRepair)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_PROGRESS_HEADER, pLocString->wzText);
LocGetString(m_pWixLoc, L"#(loc.ProgressInfoRepair)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_PROGRESS_INFO, pLocString->wzText);
}
// If we are going to apply a downgrade, bail.
if (m_fDowngrading && BOOTSTRAPPER_ACTION_UNINSTALL < action)
{
if (m_fSuppressDowngradeFailure)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "A newer version of this product is installed but downgrade failure has been suppressed; continuing...");
}
else
{
hr = HRESULT_FROM_WIN32(ERROR_PRODUCT_VERSION);
BalExitOnFailure(hr, "Cannot install a product when a newer version is installed.");
}
}
SetState(WIXSTDBA_STATE_PLANNING, hr);
if (m_pBAFunction)
{
m_pBAFunction->OnPlan();
}
hr = m_pEngine->Plan(action);
BalExitOnFailure(hr, "Failed to start planning packages.");
LExit:
if (FAILED(hr))
{
SetState(WIXSTDBA_STATE_PLANNING, hr);
}
return;
}
//
// OnApply - apply the packages.
//
void OnApply()
{
HRESULT hr = S_OK;
SetState(WIXSTDBA_STATE_APPLYING, hr);
SetProgressState(hr);
if (m_fAttachedToConsole)
{
char *szPgLine;
if (m_fIsUninstall) {
szPgLine = "\nInstalling...\n";
} else {
szPgLine = "\nUninstalling...\n";
}
DWORD dSzWritten;
WriteConsole(m_fStdConsoleHandle, szPgLine, strlen(szPgLine), &dSzWritten, NULL);
}
SetTaskbarButtonProgress(0);
hr = m_pEngine->Apply(m_hWnd);
BalExitOnFailure(hr, "Failed to start applying packages.");
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_PROGRESS_CANCEL_BUTTON, TRUE); // ensure the cancel button is enabled before starting.
LExit:
if (FAILED(hr))
{
SetState(WIXSTDBA_STATE_APPLYING, hr);
}
return;
}
//
// OnChangeState - change state.
//
void OnChangeState(
__in WIXSTDBA_STATE state
)
{
WIXSTDBA_STATE stateOld = m_state;
DWORD dwOldPageId = 0;
DWORD dwNewPageId = 0;
LPWSTR sczText = NULL;
LPWSTR sczUnformattedText = NULL;
LPWSTR sczControlState = NULL;
LPWSTR sczControlName = NULL;
LOC_STRING* pLocString = NULL;
m_state = state;
// If our install is at the end (success or failure) and we're not showing full UI or
// we successfully installed the prerequisite then exit (prompt for restart if required).
if ((WIXSTDBA_STATE_APPLIED <= m_state && BOOTSTRAPPER_DISPLAY_FULL > m_command.display) ||
(WIXSTDBA_STATE_APPLIED == m_state && m_fPrereq))
{
// If a restart was required but we were not automatically allowed to
// accept the reboot then do the prompt.
if (m_fRestartRequired && !m_fAllowRestart)
{
StrAllocFromError(&sczUnformattedText, HRESULT_FROM_WIN32(ERROR_SUCCESS_REBOOT_REQUIRED), NULL);
int nResult = ::MessageBoxW(m_hWnd, sczUnformattedText ? sczUnformattedText : L"The requested operation is successful. Changes will not be effective until the system is rebooted.", m_pTheme->sczCaption, MB_ICONEXCLAMATION | MB_OKCANCEL);
m_fAllowRestart = (IDOK == nResult);
}
// Quietly exit.
::PostMessageW(m_hWnd, WM_CLOSE, 0, 0);
}
else // try to change the pages.
{
DeterminePageId(stateOld, &dwOldPageId);
DeterminePageId(m_state, &dwNewPageId);
if (dwOldPageId != dwNewPageId)
{
// Enable disable controls per-page.
if (m_rgdwPageIds[WIXSTDBA_PAGE_INSTALL] == dwNewPageId) // on the "Install" page, ensure the install button is enabled/disabled correctly.
{
LONGLONG llElevated = 0;
if (m_Bundle.fPerMachine)
{
BalGetNumericVariable(WIXBUNDLE_VARIABLE_ELEVATED, &llElevated);
}
ThemeControlElevates(m_pTheme, WIXSTDBA_CONTROL_INSTALL_BUTTON, (m_Bundle.fPerMachine && !llElevated));
// If the EULA control exists, show it only if a license URL is provided as well.
if (ThemeControlExists(m_pTheme, WIXSTDBA_CONTROL_EULA_LINK))
{
BOOL fEulaLink = (m_sczLicenseUrl && *m_sczLicenseUrl);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_EULA_LINK, fEulaLink);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_EULA_ACCEPT_CHECKBOX, fEulaLink);
}
BOOL fAcceptedLicense = !ThemeControlExists(m_pTheme, WIXSTDBA_CONTROL_EULA_ACCEPT_CHECKBOX) || !ThemeControlEnabled(m_pTheme, WIXSTDBA_CONTROL_EULA_ACCEPT_CHECKBOX) || ThemeIsControlChecked(m_pTheme, WIXSTDBA_CONTROL_EULA_ACCEPT_CHECKBOX);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_INSTALL_BUTTON, fAcceptedLicense);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_NEXT_BUTTON, fAcceptedLicense);
// If there is an "Options" page, the "Options" button exists, and it hasn't been suppressed, then enable the button.
BOOL fOptionsEnabled = m_rgdwPageIds[WIXSTDBA_PAGE_INSTALLDIR] && ThemeControlExists(m_pTheme, WIXSTDBA_CONTROL_OPTIONS_BUTTON) && !m_fSuppressOptionsUI;
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_OPTIONS_BUTTON, fOptionsEnabled);
// Show/Hide the version label if it exists.
if (m_rgdwPageIds[WIXSTDBA_PAGE_INSTALLDIR] && ThemeControlExists(m_pTheme, WIXSTDBA_CONTROL_VERSION_LABEL) && !m_fShowVersion)
{
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_VERSION_LABEL, SW_HIDE);
}
}
else if (m_rgdwPageIds[WIXSTDBA_PAGE_MODIFY] == dwNewPageId)
{
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_REPAIR_BUTTON, !m_fSuppressRepair);
}
else if (m_rgdwPageIds[WIXSTDBA_PAGE_INSTALLDIR] == dwNewPageId)
{
HRESULT hr = BalGetStringVariable(WIXSTDBA_VARIABLE_INSTALL_FOLDER, &sczUnformattedText);
if (SUCCEEDED(hr))
{
BalFormatString(sczUnformattedText, &sczText);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX, sczText);
}
}
else if (m_rgdwPageIds[WIXSTDBA_PAGE_SUCCESS] == dwNewPageId) // on the "Success" page, check if the restart or launch button should be enabled.
{
BOOL fShowRestartButton = FALSE;
BOOL fLaunchTargetExists = FALSE;
if (m_fIsRepair)
{
LocGetString(m_pWixLoc, L"#(loc.SuccessHeaderRepair)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_SUCCESS_HEADER, pLocString->wzText);
LocGetString(m_pWixLoc, L"#(loc.SuccessInfoRepair)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_SUCCESS_INFO, pLocString->wzText);
}
else if (m_fIsUninstall)
{
LocGetString(m_pWixLoc, L"#(loc.SuccessHeaderUninstall)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_SUCCESS_HEADER, pLocString->wzText);
LocGetString(m_pWixLoc, L"#(loc.SuccessInfoUninstall)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_SUCCESS_INFO, pLocString->wzText);
}
else
{
m_fInstallSucceed = TRUE;
// If we have left some kind of error message file from MSI the show that
if (BalStringVariableExists(L"MSICustomErrFile"))
{
LPWSTR sczUnFormatedErrFile = NULL;
LPWSTR sczErrFile = NULL;
LPWSTR sczSuccessErrMsg = NULL;
FILE_ENCODING feEncodingFound = FILE_ENCODING_UNSPECIFIED;
BalGetStringVariable(L"MSICustomErrFile", &sczUnFormatedErrFile);
BalFormatString(sczUnFormatedErrFile, &sczErrFile);
if (SUCCEEDED(FileToString(sczErrFile, &sczSuccessErrMsg, &feEncodingFound)))
{
LocGetString(m_pWixLoc, L"#(loc.SuccessErrorInfoText)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_SUCCESS_ERRINF, pLocString->wzText);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_SUCCESS_ERRMSG, sczSuccessErrMsg);
FileEnsureDelete(sczErrFile);
}
}
}
if (m_fRestartRequired)
{
if (BOOTSTRAPPER_RESTART_PROMPT == m_command.restart)
{
fShowRestartButton = TRUE;
}
}
else if (ThemeControlExists(m_pTheme, WIXSTDBA_CONTROL_LAUNCH_BUTTON))
{
fLaunchTargetExists = BalStringVariableExists(WIXSTDBA_VARIABLE_LAUNCH_TARGET_PATH);
}
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_LAUNCH_BUTTON, fLaunchTargetExists && BOOTSTRAPPER_ACTION_UNINSTALL < m_plannedAction);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_SUCCESS_RESTART_TEXT, fShowRestartButton);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_SUCCESS_RESTART_BUTTON, fShowRestartButton);
}
else if (m_rgdwPageIds[WIXSTDBA_PAGE_FAILURE] == dwNewPageId) // on the "Failure" page, show error message and check if the restart button should be enabled.
{
BOOL fShowLogLink = (m_Bundle.sczLogVariable && *m_Bundle.sczLogVariable); // if there is a log file variable then we'll assume the log file exists.
BOOL fShowErrorMessage = FALSE;
BOOL fShowRestartButton = FALSE;
if (m_fIsRepair)
{
LocGetString(m_pWixLoc, L"#(loc.FailureHeaderRepair)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_FAILURE_HEADER, pLocString->wzText);
}
if (m_fIsUninstall)
{
LocGetString(m_pWixLoc, L"#(loc.FailureHeaderUninstall)", &pLocString);
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_FAILURE_HEADER, pLocString->wzText);
}
if (FAILED(m_hrFinal))
{
// If we know the failure message, use that.
if (m_sczFailedMessage && *m_sczFailedMessage)
{
StrAllocString(&sczUnformattedText, m_sczFailedMessage, 0);
}
else // try to get the error message from the error code.
{
StrAllocFromError(&sczUnformattedText, m_hrFinal, NULL);
if (!sczUnformattedText || !*sczUnformattedText)
{
StrAllocFromError(&sczUnformattedText, E_FAIL, NULL);
}
}
StrAllocFormatted(&sczText, L"0x%08x - %ls", m_hrFinal, sczUnformattedText);
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_FAILURE_MESSAGE_TEXT, sczText);
fShowErrorMessage = TRUE;
}
if (m_fRestartRequired)
{
if (BOOTSTRAPPER_RESTART_PROMPT == m_command.restart)
{
fShowRestartButton = TRUE;
}
}
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_FAILURE_LOGFILE_LINK, fShowLogLink);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_FAILURE_MESSAGE_TEXT, fShowErrorMessage);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_FAILURE_RESTART_TEXT, fShowRestartButton);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_FAILURE_RESTART_BUTTON, fShowRestartButton);
}
// Hide the upgrade link
if (ThemeControlExists(m_pTheme, WIXSTDBA_CONTROL_UPGRADE_LINK))
{
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_UPGRADE_LINK, FALSE);
}
// Process each control for special handling in the new page.
THEME_PAGE* pPage = ThemeGetPage(m_pTheme, dwNewPageId);
if (pPage)
{
for (DWORD i = 0; i < pPage->cControlIndices; ++i)
{
THEME_CONTROL* pControl = m_pTheme->rgControls + pPage->rgdwControlIndices[i];
// If we are on the install, options or modify pages and this is a named control, try to set its default state.
if ((m_rgdwPageIds[WIXSTDBA_PAGE_INSTALL] == dwNewPageId ||
m_rgdwPageIds[WIXSTDBA_PAGE_INSTALLDIR] == dwNewPageId ||
m_rgdwPageIds[WIXSTDBA_PAGE_SVC_OPTIONS] == dwNewPageId ||
m_rgdwPageIds[WIXSTDBA_PAGE_MODIFY] == dwNewPageId) &&
pControl->sczName && *pControl->sczName)
{
// If this is a checkbox control, try to set its default state to the state of a matching named Burn variable.
if (THEME_CONTROL_TYPE_CHECKBOX == pControl->type && WIXSTDBA_CONTROL_EULA_ACCEPT_CHECKBOX != pControl->wId)
{
LONGLONG llValue = 0;
HRESULT hr = BalGetNumericVariable(pControl->sczName, &llValue);
ThemeSendControlMessage(m_pTheme, pControl->wId, BM_SETCHECK, SUCCEEDED(hr) && llValue ? BST_CHECKED : BST_UNCHECKED, 0);
}
// If this is a button control with the BS_AUTORADIOBUTTON style, try to set its default
// state to the state of a matching named Burn variable.
if (THEME_CONTROL_TYPE_BUTTON == pControl->type && (BS_AUTORADIOBUTTON == (BS_AUTORADIOBUTTON & pControl->dwStyle)))
{
LONGLONG llValue = 0;
HRESULT hr = BalGetNumericVariable(pControl->sczName, &llValue);
// If the control value isn't set then disable it.
if (!SUCCEEDED(hr))
{
ThemeControlEnable(m_pTheme, pControl->wId, FALSE);
}
else
{
ThemeSendControlMessage(m_pTheme, pControl->wId, BM_SETCHECK, SUCCEEDED(hr) && llValue ? BST_CHECKED : BST_UNCHECKED, 0);
}
}
// Hide or disable controls based on the control name with 'State' appended
HRESULT hr = StrAllocFormatted(&sczControlName, L"%lsState", pControl->sczName);
if (SUCCEEDED(hr))
{
hr = BalGetStringVariable(sczControlName, &sczControlState);
if (SUCCEEDED(hr) && sczControlState && *sczControlState)
{
if (CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, 0, sczControlState, -1, L"disable", -1))
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Disable control %ls", pControl->sczName);
ThemeControlEnable(m_pTheme, pControl->wId, FALSE);
}
else if (CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, 0, sczControlState, -1, L"hide", -1))
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Hide control %ls", pControl->sczName);
// TODO: This doesn't work
ThemeShowControl(m_pTheme, pControl->wId, SW_HIDE);
}
}
}
}
// Format the text in each of the new page's controls (if they have any text).
if (pControl->sczText && *pControl->sczText)
{
HRESULT hr = BalFormatString(pControl->sczText, &sczText);
if (SUCCEEDED(hr))
{
ThemeSetTextControl(m_pTheme, pControl->wId, sczText);
}
}
}
}
// See #Hidden
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_LOGUSER_OR_MAIL_LABEL, false);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_LOGPASS_LABEL, false);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_LOGUSER_OR_MAIL_EDIT, false);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_LOGPASS_EDIT, false);
// XXX why do we need this??
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_LOGUSER_OR_MAIL_LABEL, true);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_LOGPASS_LABEL, true);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_LOGUSER_OR_MAIL_EDIT, true);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_LOGPASS_EDIT, true);
ThemeShowPage(m_pTheme, dwOldPageId, SW_HIDE);
ThemeShowPage(m_pTheme, dwNewPageId, SW_SHOW);
// Remember current page
m_dwCurrentPage = dwNewPageId;
// On the install page set the focus to the install button or the next enabled control if install is disabled
if (m_rgdwPageIds[WIXSTDBA_PAGE_INSTALL] == dwNewPageId)
{
HWND hwndFocus = ::GetDlgItem(m_pTheme->hwndParent, WIXSTDBA_CONTROL_INSTALL_BUTTON);
if (hwndFocus && !ThemeControlEnabled(m_pTheme, WIXSTDBA_CONTROL_INSTALL_BUTTON))
{
hwndFocus = ::GetNextDlgTabItem(m_pTheme->hwndParent, hwndFocus, FALSE);
}
if (hwndFocus)
{
::SetFocus(hwndFocus);
}
}
}
}
ReleaseStr(sczText);
ReleaseStr(sczUnformattedText);
ReleaseStr(sczControlState);
ReleaseStr(sczControlName);
}
//
// OnClose - called when the window is trying to be closed.
//
BOOL OnClose()
{
BOOL fClose = FALSE;
// If we've already succeeded or failed or showing the help page, just close (prompts are annoying if the bootstrapper is done).
// Also, allow people to simply close out at the signin stage
if (WIXSTDBA_STATE_APPLIED <= m_state || WIXSTDBA_STATE_HELP == m_state || WIXSTDBA_STATE_SVC_OPTIONS == m_state)
{
fClose = TRUE;
}
else // prompt the user or force the cancel if there is no UI.
{
fClose = PromptCancel(m_hWnd, BOOTSTRAPPER_DISPLAY_FULL != m_command.display, m_sczConfirmCloseMessage ? m_sczConfirmCloseMessage : L"Are you sure you want to cancel?", m_pTheme->sczCaption);
}
// If we're doing progress then we never close, we just cancel to let rollback occur.
if (WIXSTDBA_STATE_APPLYING <= m_state && WIXSTDBA_STATE_APPLIED > m_state)
{
// If we canceled disable cancel button since clicking it again is silly.
if (fClose)
{
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_PROGRESS_CANCEL_BUTTON, FALSE);
}
fClose = FALSE;
}
return fClose;
}
//
// OnClickAcceptCheckbox - allow the install to continue.
//
void OnClickAcceptCheckbox()
{
BOOL fAcceptedLicense = ThemeIsControlChecked(m_pTheme, WIXSTDBA_CONTROL_EULA_ACCEPT_CHECKBOX);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_INSTALL_BUTTON, fAcceptedLicense);
ThemeControlEnable(m_pTheme, WIXSTDBA_CONTROL_NEXT_BUTTON, fAcceptedLicense);
}
//
// OnClickOptionsButton - show the options page.
//
void OnClickOptionsButton()
{
SavePageSettings(WIXSTDBA_PAGE_INSTALL);
m_stateInstallPage = m_state;
SetState(WIXSTDBA_STATE_INSTALLDIR, S_OK);
}
BOOL CheckNonEmptyField(LPCWSTR wzEditVarID)
{
BOOL bRes = TRUE;
LPWSTR sczFieldValue = NULL;
if (SUCCEEDED(BalGetStringVariable(wzEditVarID, &sczFieldValue)))
{
if (StrCmpCW(sczFieldValue, L"") == 0)
{
LOC_STRING* pLocString = NULL;
LPWSTR wzLoc = NULL;
LPWSTR sczMessageText = NULL;
StrAllocFormatted(&wzLoc, L"#(loc.%s)", wzEditVarID);
LocGetString(m_pWixLoc, wzLoc, &pLocString);
StrAllocFormatted(&sczMessageText, L"The field \"%s\" cannot be blank! In order to continue with setup you should fill it.", pLocString->wzText);
::MessageBoxW(m_hWnd, sczMessageText, m_pTheme->sczCaption, MB_ICONEXCLAMATION | MB_OK);
bRes = FALSE;
}
}
return bRes;
}
BOOL CheckCurrentUserPassword(LPCWSTR wzPasswordVarID)
{
LPWSTR sczUserNameValue = NULL;
LPWSTR sczDomainValue = NULL;
LPWSTR sczPasswordValue = NULL;
BOOL bRes = SUCCEEDED(BalGetStringVariable(L"ComputerName", &sczDomainValue)) &&
SUCCEEDED(BalGetStringVariable(L"LogonUser", &sczUserNameValue)) &&
SUCCEEDED(BalGetStringVariable(wzPasswordVarID, &sczPasswordValue));
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "CheckCurrentUserPassword. 1");
if (bRes)
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "CheckCurrentUserPassword. 2");
HANDLE hToken;
if (!LogonUserW(sczUserNameValue, sczDomainValue, sczPasswordValue, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &hToken))
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "CheckCurrentUserPassword. 3 - Failed");
LPWSTR sczMessageText = NULL;
StrAllocFormatted(&sczMessageText, L"Setup was unable to validate specified password for \"%s\\%s\"! Please double check it.", sczDomainValue, sczUserNameValue);
::MessageBoxW(m_hWnd, sczMessageText, m_pTheme->sczCaption, MB_ICONEXCLAMATION | MB_OK);
bRes = FALSE;
}
else
{
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "CheckCurrentUserPassword. 4 - Succeed");
}
}
return bRes;
}
/*
BOOL CheckPostgreSQLConnection(LPCWSTR VAR_HOST, LPCWSTR VAR_USER, LPCWSTR VAR_PASS, LPCWSTR DB_ToCheck, BOOL DB_ShouldExists)
{
BOOL bPSQLOk = CheckNonEmptyField(VAR_HOST) && CheckNonEmptyField(VAR_USER) && CheckNonEmptyField(VAR_PASS);
// if (!bPSQLOk) return FALSE;
LPWSTR sczPSQLPath = NULL;
LPWSTR sczPSQLDirectory = NULL;
if (bPSQLOk && SUCCEEDED(PathRelativeToModule(&sczPSQLPath, L"qcPSQL.exe", m_hModule)) && SUCCEEDED(PathGetDirectory(sczPSQLPath, &sczPSQLDirectory)))
{
LPWSTR sczPSQLHost = NULL;
LPWSTR sczPSQLUser = NULL;
LPWSTR sczPSQLPass = NULL;
if (SUCCEEDED(BalGetStringVariable(VAR_HOST, &sczPSQLHost)) &&
SUCCEEDED(BalGetStringVariable(VAR_USER, &sczPSQLUser)) &&
SUCCEEDED(BalGetStringVariable(VAR_PASS, &sczPSQLPass)) )
{
DWORD exitcode = 0;
LPWSTR sczCmdParam = NULL;
if (DB_ToCheck == NULL)
StrAllocFormatted(&sczCmdParam, L"\"%s\" checkconnection -H%s -U%s -P%s", sczPSQLPath, sczPSQLHost, sczPSQLUser, sczPSQLPass);
else
StrAllocFormatted(&sczCmdParam, L"\"%s\" checkdbexists -H%s -U%s -P%s -CKDB%s", sczPSQLPath, sczPSQLHost, sczPSQLUser, sczPSQLPass, DB_ToCheck);
_STARTUPINFOW si;
_PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
// Start the child process.
if( CreateProcessW(NULL, // No module name (use command line)
sczCmdParam, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NO_WINDOW, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// get the process exit code
GetExitCodeProcess(pi.hProcess, (LPDWORD)&exitcode);
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
LPWSTR sczMessageText = NULL;
switch (exitcode)
{
case QCPSQL_ERROR_UNKNOWN:
sczMessageText = L"Setup was unable to connect to the specified database server. Unknown error.\nWould you like to continue anyway?";
break;
case QCPSQL_ERROR_EXECSQL:
sczMessageText = L"Setup was unable to execute specified command.\nWould you like to continue anyway?";
break;
case QCPSQL_ERROR_CONNECT:
sczMessageText = L"Setup was unable to connect to the specified database server.\nWould you like to continue anyway?";
break;
case QCPSQL_ERROR_INVALIDARGS:
sczMessageText = L"Setup was unable to connect to the specified database server. Invalid arguments.\nWould you like to continue anyway?";
break;
case QCPSQL_SUCCESS_DBNOTEXISTS:
if ((DB_ToCheck != NULL) && (DB_ShouldExists))
StrAllocFormatted(&sczMessageText, L"The database \"%s\" does not exists on the host \"%s\".\nWould you like to continue anyway?", DB_ToCheck, sczPSQLHost);
break;
case QCPSQL_SUCCESS_DBEXISTS:
if ((DB_ToCheck != NULL) && (!DB_ShouldExists))
StrAllocFormatted(&sczMessageText, L"The database \"%s\" already exists on the host \"%s\".\nWould you like to continue anyway?", DB_ToCheck, sczPSQLHost);
break;
default:
break;
}
if (sczMessageText != NULL)
bPSQLOk = (IDYES == ::MessageBoxW(m_hWnd, sczMessageText, m_pTheme->sczCaption, MB_ICONEXCLAMATION | MB_YESNO));
}
}
return bPSQLOk;
}
*/
BOOL CheckInstallPathIsValid(LPCWSTR wzInstallPath)
{
BOOL bPathIsValid = TRUE;
if (StrCmpCW(wzInstallPath, L"") == 0)
{
bPathIsValid = FALSE;
::MessageBoxW(m_hWnd, L"The install location cannot be blank. You must enter a full path with drive letter, like:\n\tC:\\Program Files\\App\n\nor a UNC path, like\n\t\\\\ServerName\\AppShare", m_pTheme->sczCaption, MB_ICONEXCLAMATION | MB_OK);
} else {
DWORD i = 0;
LPCWSTR wz = wzInstallPath;
BOOL bInvalidCharFound = FALSE;
while (*wz)
{
++i;
if ((L'/' == *wz) || ((L':' == *wz) && (i != 2)) || (L'*' == *wz) || (L'?' == *wz) ||
(L'"' == *wz) || (L'<' == *wz) || (L'>' == *wz) || (L'|' == *wz))
bInvalidCharFound = TRUE;
++wz;
}
if (bInvalidCharFound)
{
bPathIsValid = FALSE;
::MessageBoxW(m_hWnd, L"The install location cannot include any of the following characters:\n\n/ : * ? \" < > |", m_pTheme->sczCaption, MB_ICONEXCLAMATION | MB_OK);
}
}
return bPathIsValid;
}
BOOL CheckEmailAddressIsValid(LPCWSTR wzEmailVarID, LPCWSTR wzPassVarID = NULL, BOOL AllowBlank = TRUE)
{
BOOL bRes = TRUE;
LPWSTR sczEmailValue = NULL;
LPWSTR sczPassValue = NULL;
if (SUCCEEDED(BalGetStringVariable(wzEmailVarID, &sczEmailValue)))
{
LOC_STRING* pLocString = NULL;
LPWSTR wzLoc = NULL;
LPWSTR sczMessageText = NULL;
StrAllocFormatted(&wzLoc, L"#(loc.%s)", wzEmailVarID);
LocGetString(m_pWixLoc, wzLoc, &pLocString);
BOOL bIsBlank = (StrCmpCW(sczEmailValue, L"") == 0);
if (bIsBlank && AllowBlank)
return TRUE;
if (bIsBlank)
{
bRes = FALSE;
StrAllocFormatted(&sczMessageText, L"The field \"%s\" cannot be blank! In order to continue with setup you should fill it.", pLocString->wzText);
} else {
DWORD i = 0;
DWORD iAt = 0;
DWORD iPt = 0;
LPCWSTR wz = sczEmailValue;
while (*wz)
{
++i;
if (L'@' == *wz) iAt = i;
if (L'.' == *wz) iPt = i;
++wz;
}
bRes = (1 < iAt) && (iAt < iPt);
if (!bRes)
StrAllocFormatted(&sczMessageText, L"The field \"%s\" dosen't seems to be a valid email address! Please double check that.", pLocString->wzText);
}
if (!bRes)
::MessageBoxW(m_hWnd, sczMessageText, m_pTheme->sczCaption, MB_ICONEXCLAMATION | MB_OK);
else {
if (wzPassVarID != NULL)
{
if (SUCCEEDED(BalGetStringVariable(wzPassVarID, &sczPassValue)))
if (StrCmpCW(sczEmailValue, L"") == 0) {
bRes = FALSE;
::MessageBoxW(m_hWnd, L"You specified a valid email address but the account password is blank. The password is required!", m_pTheme->sczCaption, MB_ICONEXCLAMATION | MB_OK);
}
}
}
}
return bRes;
}
void OnClickNextButton()
{
BOOL bOkToContinue = TRUE;
LPWSTR sczPath = NULL;
switch (m_state)
{
// this clause is dead code, since we cancelled the "choose an
// install directory" screen. but let's leave it in, in case we
// bring it back.
case WIXSTDBA_STATE_INSTALLDIR:
ThemeGetTextControl(m_pTheme, WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX, &sczPath);
bOkToContinue = CheckInstallPathIsValid(sczPath);
if (bOkToContinue) {
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_INSTALL_FOLDER, sczPath);
SavePageSettings(WIXSTDBA_PAGE_INSTALLDIR);
SetState(WIXSTDBA_STATE_SVC_OPTIONS, S_OK);
// Display the elevation shield if perMachine installation
LONGLONG llElevated = 0;
if (SUCCEEDED(BalGetNumericVariable(WIXSTDBA_VARIABLE_PERMACHINE_INSTALL, &llElevated)))
ThemeControlElevates(m_pTheme, WIXSTDBA_CONTROL_INSTALL_BUTTON, (llElevated == 1));
}
break;
default:
SavePageSettings(WIXSTDBA_PAGE_INSTALL);
m_stateInstallPage = m_state;
SetState(WIXSTDBA_STATE_SVC_OPTIONS, S_OK);
break;
}
}
//
// OnClickInstallScope - allow user to choose between a perMachine and perUser install
//
void OnClickInstallScope()
{
LPWSTR sczPath = NULL;
LPWSTR sczFPath = NULL;
BOOL fPerMachineInst = ThemeIsControlChecked(m_pTheme, WIXSTDBA_CONTROL_PERMACHINE_RADIO);
if (fPerMachineInst)
{
if (SUCCEEDED(BalGetStringVariable(WIXSTDBA_VARIABLE_PERMACHINE_INSTALL_FOLDER, &sczPath))
&& SUCCEEDED(BalFormatString(sczPath, &sczFPath)))
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX, sczFPath);
}
else
{
if (SUCCEEDED(BalGetStringVariable(WIXSTDBA_VARIABLE_PERUSER_INSTALL_FOLDER, &sczPath))
&& SUCCEEDED(BalFormatString(sczPath, &sczFPath)))
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX, sczFPath);
}
}
//
// OnClickInstallPostgressCheckbox - we will set defaults value and disable controls if checkbox was checked.
//
void OnClickSkipRegistrationCheckbox()
{
BOOL fSignIn = ThemeIsControlChecked(m_pTheme, WIXSTDBA_CONTROL_REGSIGNIN_RADIO);
//if (fSkipReg)
//{
// ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_DBHOST_EDIT, L"localhost");
// ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_DBUSER_EDIT, L"postgres");
// ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_DBPASS_EDIT, L"postgres");
//}
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_REGMAIL_LABEL, !fSignIn);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_REGUSER_LABEL, !fSignIn);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_REGPASS_LABEL, !fSignIn);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_REGMAIL_EDIT, !fSignIn);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_REGUSER_EDIT, !fSignIn);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_REGPASS_EDIT, !fSignIn);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_LOGUSER_OR_MAIL_LABEL, fSignIn);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_LOGPASS_LABEL, fSignIn);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_LOGUSER_OR_MAIL_EDIT, fSignIn);
ThemeShowControl(m_pTheme, WIXSTDBA_CONTROL_LOGPASS_EDIT, fSignIn);
}
void OnSignIn()
{
BOOL fSignIn = ThemeIsControlChecked(m_pTheme, WIXSTDBA_CONTROL_REGSIGNIN_RADIO);
BOOL bOkToContinue = false;
SavePageSettings(WIXSTDBA_PAGE_SVC_OPTIONS);
if (fSignIn)
{
LPWSTR wzUserNameOrEmail = NULL;
LPWSTR wzUserPass = NULL;
if (SUCCEEDED(BalGetStringVariable(WIXSTDBA_VARIABLE_LOG_USERNAME_OR_MAIL, &wzUserNameOrEmail)) &&
SUCCEEDED(BalGetStringVariable(WIXSTDBA_VARIABLE_LOG_PASS, &wzUserPass)))
{
bOkToContinue = REST_SignInOrRegister(true, wzUserNameOrEmail, NULL, NULL, wzUserPass);
}
}
else
{
LPWSTR wzUserName = NULL;
LPWSTR wzEmail = NULL;
LPWSTR wzUserPass = NULL;
if (SUCCEEDED(BalGetStringVariable(WIXSTDBA_VARIABLE_REG_MAIL, &wzEmail)) &&
SUCCEEDED(BalGetStringVariable(WIXSTDBA_VARIABLE_REG_USER, &wzUserName)) &&
SUCCEEDED(BalGetStringVariable(WIXSTDBA_VARIABLE_REG_PASS, &wzUserPass)))
{
bOkToContinue = REST_SignInOrRegister(false, NULL, wzUserName, wzEmail, wzUserPass);
}
}
if (bOkToContinue)
this->SetState(WIXSTDBA_STATE_APPLIED, S_OK);
}
void OnClickBackButton()
{
BOOL bOkToContinue = TRUE;
LPWSTR sczPath = NULL;
switch (m_state)
{
case WIXSTDBA_STATE_INSTALLDIR:
ThemeGetTextControl(m_pTheme, WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX, &sczPath);
bOkToContinue = CheckInstallPathIsValid(sczPath);
if (bOkToContinue) {
m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_INSTALL_FOLDER, sczPath);
SavePageSettings(WIXSTDBA_PAGE_INSTALLDIR);
SetState(m_stateInstallPage, S_OK);
}
break;
case WIXSTDBA_STATE_SVC_OPTIONS:
SavePageSettings(WIXSTDBA_PAGE_SVC_OPTIONS);
SetState(WIXSTDBA_STATE_DETECTED, S_OK);
break;
}
}
//
// OnClickOptionsBrowseButton - browse for install folder on the options page.
//
void OnClickOptionsBrowseButton(DWORD dwControl)
{
WCHAR wzPath[MAX_PATH] = { };
BROWSEINFOW browseInfo = { };
PIDLIST_ABSOLUTE pidl = NULL;
PIDLIST_ABSOLUTE pidlRoot = NULL;
::SHGetFolderLocation(m_hWnd, CSIDL_DRIVES, NULL, 0, &pidlRoot);
browseInfo.hwndOwner = m_hWnd;
browseInfo.pszDisplayName = wzPath;
browseInfo.lpszTitle = m_pTheme->sczCaption;
browseInfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_USENEWUI;
browseInfo.pidlRoot = pidlRoot;
pidl = ::SHBrowseForFolderW(&browseInfo);
if (pidl && ::SHGetPathFromIDListW(pidl, wzPath))
{
switch (dwControl)
{
case WIXSTDBA_CONTROL_BROWSE_BUTTON:
ThemeSetTextControl(m_pTheme, WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX, wzPath);
break;
}
}
if (pidl)
{
::CoTaskMemFree(pidl);
}
return;
}
//
// OnClickOptionsOkButton - accept the changes made by the options page.
//
void OnClickOptionsOkButton()
{
HRESULT hr = S_OK;
LPWSTR sczPath = NULL;
if (ThemeControlExists(m_pTheme, WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX))
{
hr = ThemeGetTextControl(m_pTheme, WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX, &sczPath);
ExitOnFailure(hr, "Failed to get text from folder edit box.");
// TODO: verify the path is valid.
hr = m_pEngine->SetVariableString(WIXSTDBA_VARIABLE_INSTALL_FOLDER, sczPath);
ExitOnFailure(hr, "Failed to set the install folder.");
}
SavePageSettings(WIXSTDBA_PAGE_INSTALLDIR);
LExit:
SetState(m_stateInstallPage, S_OK);
return;
}
//
// OnClickOptionsCancelButton - discard the changes made by the options page.
//
void OnClickOptionsCancelButton()
{
SetState(m_stateInstallPage, S_OK);
}
//
// OnClickRepairButton - start the repair.
//
void OnClickRepairButton()
{
this->OnPlan(BOOTSTRAPPER_ACTION_REPAIR);
}
//
// OnClickUninstallButton - start the uninstall.
//
void OnClickUninstallButton()
{
this->OnPlan(BOOTSTRAPPER_ACTION_UNINSTALL);
}
void TryLaunchAfterInstall(LPWSTR wzVarTargetPath)
{
BOOL fLaunchAfterInstallTargetExists = BalStringVariableExists(wzVarTargetPath);
HRESULT hr = S_OK;
LPWSTR sczUnformattedLaunchTarget = NULL;
LPWSTR sczLaunchTarget = NULL;
LPWSTR sczUnformattedArguments = NULL;
LPWSTR sczArguments = NULL;
LPWSTR sczRunOnceValue = NULL;
int nCmdShow = SW_SHOWNORMAL;
if (fLaunchAfterInstallTargetExists)
{
hr = BalGetStringVariable(wzVarTargetPath, &sczUnformattedLaunchTarget);
hr = BalFormatString(sczUnformattedLaunchTarget, &sczLaunchTarget);
}
if (m_fInstallSucceed && fLaunchAfterInstallTargetExists)
{
if (!m_fRestartRequired)
{
DWORD dwAttr;
if (FileExistsEx(sczLaunchTarget, &dwAttr))
ShelExec(sczLaunchTarget, sczArguments, L"open", NULL, nCmdShow, m_hWnd, NULL);
}
}
ReleaseStr(sczUnformattedLaunchTarget);
ReleaseStr(sczLaunchTarget);
ReleaseStr(sczUnformattedArguments);
ReleaseStr(sczArguments);
ReleaseStr(sczRunOnceValue);
return;
}
//
// OnClickCloseButton - close the application.
//
void OnClickCloseButton()
{
TryLaunchAfterInstall(L"Launch_IISStartServerPath");
TryLaunchAfterInstall(L"Launch_EverywarePOSPath");
::SendMessageW(m_hWnd, WM_CLOSE, 0, 0);
return;
}
//
// OnClickEulaLink - show the end user license agreement.
//
void OnClickEulaLink()
{
HRESULT hr = S_OK;
LPWSTR sczLicenseUrl = NULL;
LPWSTR sczLicensePath = NULL;
LPWSTR sczLicenseDirectory = NULL;
URI_PROTOCOL protocol = URI_PROTOCOL_UNKNOWN;
hr = StrAllocString(&sczLicenseUrl, m_sczLicenseUrl, 0);
BalExitOnFailure1(hr, "Failed to copy license URL: %ls", m_sczLicenseUrl);
hr = LocLocalizeString(m_pWixLoc, &sczLicenseUrl);
BalExitOnFailure1(hr, "Failed to localize license URL: %ls", m_sczLicenseUrl);
hr = BalFormatString(sczLicenseUrl, &sczLicenseUrl);
BalExitOnFailure1(hr, "Failed to get formatted license URL: %ls", m_sczLicenseUrl);
hr = UriProtocol(sczLicenseUrl, &protocol);
if (FAILED(hr) || URI_PROTOCOL_UNKNOWN == protocol)
{
// Probe for localised license file
hr = PathRelativeToModule(&sczLicensePath, sczLicenseUrl, m_hModule);
if (SUCCEEDED(hr))
{
hr = PathGetDirectory(sczLicensePath, &sczLicenseDirectory);
if (SUCCEEDED(hr))
{
hr = LocProbeForFile(sczLicenseDirectory, PathFile(sczLicenseUrl), m_sczLanguage, &sczLicensePath);
}
}
}
hr = ShelExec(sczLicensePath ? sczLicensePath : sczLicenseUrl, NULL, L"open", NULL, SW_SHOWDEFAULT, m_hWnd, NULL);
BalExitOnFailure(hr, "Failed to launch URL to EULA.");
LExit:
ReleaseStr(sczLicensePath);
ReleaseStr(sczLicenseUrl);
ReleaseStr(sczLicenseDirectory);
return;
}
//
// OnClickUpgradeLink - download the upgrade.
//
void OnClickUpgradeLink()
{
this->OnPlan(BOOTSTRAPPER_ACTION_UPDATE_REPLACE);
m_fUpdating = TRUE;
return;
}
//
// OnClickLaunchButton - launch the app from the success page.
//
void OnClickLaunchButton()
{
HRESULT hr = S_OK;
LPWSTR sczUnformattedLaunchTarget = NULL;
LPWSTR sczLaunchTarget = NULL;
LPWSTR sczUnformattedArguments = NULL;
LPWSTR sczArguments = NULL;
int nCmdShow = SW_SHOWNORMAL;
hr = BalGetStringVariable(WIXSTDBA_VARIABLE_LAUNCH_TARGET_PATH, &sczUnformattedLaunchTarget);
BalExitOnFailure1(hr, "Failed to get launch target variable '%ls'.", WIXSTDBA_VARIABLE_LAUNCH_TARGET_PATH);
hr = BalFormatString(sczUnformattedLaunchTarget, &sczLaunchTarget);
BalExitOnFailure1(hr, "Failed to format launch target variable: %ls", sczUnformattedLaunchTarget);
if (BalStringVariableExists(WIXSTDBA_VARIABLE_LAUNCH_ARGUMENTS))
{
hr = BalGetStringVariable(WIXSTDBA_VARIABLE_LAUNCH_ARGUMENTS, &sczUnformattedArguments);
BalExitOnFailure1(hr, "Failed to get launch arguments '%ls'.", WIXSTDBA_VARIABLE_LAUNCH_ARGUMENTS);
hr = BalFormatString(sczUnformattedArguments, &sczArguments);
BalExitOnFailure1(hr, "Failed to format launch arguments variable: %ls", sczUnformattedArguments);
}
if (BalStringVariableExists(WIXSTDBA_VARIABLE_LAUNCH_HIDDEN))
{
nCmdShow = SW_HIDE;
}
hr = ShelExec(sczLaunchTarget, sczArguments, L"open", NULL, nCmdShow, m_hWnd, NULL);
BalExitOnFailure1(hr, "Failed to launch target: %ls", sczLaunchTarget);
::PostMessageW(m_hWnd, WM_CLOSE, 0, 0);
LExit:
ReleaseStr(sczLaunchTarget);
ReleaseStr(sczUnformattedLaunchTarget);
ReleaseStr(sczArguments);
ReleaseStr(sczUnformattedArguments);
return;
}
//
// OnClickRestartButton - allows the restart and closes the app.
//
void OnClickRestartButton()
{
AssertSz(m_fRestartRequired, "Restart must be requested to be able to click on the restart button.");
m_fAllowRestart = TRUE;
::SendMessageW(m_hWnd, WM_CLOSE, 0, 0);
return;
}
//
// OnClickLogFileLink - show the log file.
//
void OnClickLogFileLink()
{
HRESULT hr = S_OK;
LPWSTR sczLogFile = NULL;
hr = BalGetStringVariable(m_Bundle.sczLogVariable, &sczLogFile);
BalExitOnFailure1(hr, "Failed to get log file variable '%ls'.", m_Bundle.sczLogVariable);
hr = ShelExec(L"notepad.exe", sczLogFile, L"open", NULL, SW_SHOWDEFAULT, m_hWnd, NULL);
BalExitOnFailure1(hr, "Failed to open log file target: %ls", sczLogFile);
LExit:
ReleaseStr(sczLogFile);
return;
}
//
// SetState
//
void SetState(
__in WIXSTDBA_STATE state,
__in HRESULT hrStatus
)
{
if (FAILED(hrStatus))
{
m_hrFinal = hrStatus;
}
if (FAILED(m_hrFinal))
{
state = WIXSTDBA_STATE_FAILED;
}
if (WIXSTDBA_STATE_INSTALLDIR == state || m_state < state)
{
::PostMessageW(m_hWnd, WM_WIXSTDBA_CHANGE_STATE, 0, state);
}
if (WIXSTDBA_STATE_INSTALLDIR == state || m_state < state)
{
::PostMessageW(m_hWnd, WM_WIXSTDBA_CHANGE_STATE, 0, state);
}
if (WIXSTDBA_STATE_SVC_OPTIONS == state || m_state < state)
{
::PostMessageW(m_hWnd, WM_WIXSTDBA_CHANGE_STATE, 0, state);
}
}
void DeterminePageId(
__in WIXSTDBA_STATE state,
__out DWORD* pdwPageId
)
{
if (BOOTSTRAPPER_DISPLAY_PASSIVE == m_command.display)
{
switch (state)
{
case WIXSTDBA_STATE_INITIALIZED:
*pdwPageId = BOOTSTRAPPER_ACTION_HELP == m_command.action ? m_rgdwPageIds[WIXSTDBA_PAGE_HELP] : m_rgdwPageIds[WIXSTDBA_PAGE_LOADING];
break;
case WIXSTDBA_STATE_HELP:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_HELP];
break;
case WIXSTDBA_STATE_DETECTING:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_LOADING] ? m_rgdwPageIds[WIXSTDBA_PAGE_LOADING] : m_rgdwPageIds[WIXSTDBA_PAGE_PROGRESS_PASSIVE] ? m_rgdwPageIds[WIXSTDBA_PAGE_PROGRESS_PASSIVE] : m_rgdwPageIds[WIXSTDBA_PAGE_PROGRESS];
break;
case WIXSTDBA_STATE_DETECTED: __fallthrough;
case WIXSTDBA_STATE_PLANNING: __fallthrough;
case WIXSTDBA_STATE_PLANNED: __fallthrough;
case WIXSTDBA_STATE_APPLYING: __fallthrough;
case WIXSTDBA_STATE_CACHING: __fallthrough;
case WIXSTDBA_STATE_CACHED: __fallthrough;
case WIXSTDBA_STATE_EXECUTING: __fallthrough;
case WIXSTDBA_STATE_EXECUTED:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_PROGRESS_PASSIVE] ? m_rgdwPageIds[WIXSTDBA_PAGE_PROGRESS_PASSIVE] : m_rgdwPageIds[WIXSTDBA_PAGE_PROGRESS];
break;
default:
*pdwPageId = 0;
break;
}
}
else if (BOOTSTRAPPER_DISPLAY_FULL == m_command.display)
{
switch (state)
{
case WIXSTDBA_STATE_INITIALIZING:
*pdwPageId = 0;
break;
case WIXSTDBA_STATE_INITIALIZED:
*pdwPageId = BOOTSTRAPPER_ACTION_HELP == m_command.action ? m_rgdwPageIds[WIXSTDBA_PAGE_HELP] : m_rgdwPageIds[WIXSTDBA_PAGE_LOADING];
break;
case WIXSTDBA_STATE_HELP:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_HELP];
break;
case WIXSTDBA_STATE_DETECTING:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_LOADING];
break;
case WIXSTDBA_STATE_DETECTED:
switch (m_command.action)
{
case BOOTSTRAPPER_ACTION_INSTALL:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_INSTALL];
break;
case BOOTSTRAPPER_ACTION_MODIFY: __fallthrough;
case BOOTSTRAPPER_ACTION_REPAIR: __fallthrough;
case BOOTSTRAPPER_ACTION_UNINSTALL:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_MODIFY];
break;
}
break;
case WIXSTDBA_STATE_INSTALLDIR:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_INSTALLDIR];
break;
case WIXSTDBA_STATE_SVC_OPTIONS:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_SVC_OPTIONS];
break;
case WIXSTDBA_STATE_PLANNING: __fallthrough;
case WIXSTDBA_STATE_PLANNED: __fallthrough;
case WIXSTDBA_STATE_APPLYING: __fallthrough;
case WIXSTDBA_STATE_CACHING: __fallthrough;
case WIXSTDBA_STATE_CACHED: __fallthrough;
case WIXSTDBA_STATE_EXECUTING: __fallthrough;
case WIXSTDBA_STATE_EXECUTED:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_PROGRESS];
break;
case WIXSTDBA_STATE_APPLIED:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_SUCCESS];
CopyBundleLogToSpecifiedPath();
break;
case WIXSTDBA_STATE_FAILED:
*pdwPageId = m_rgdwPageIds[WIXSTDBA_PAGE_FAILURE];
CopyBundleLogToSpecifiedPath();
break;
}
}
}
HRESULT EvaluateConditions()
{
HRESULT hr = S_OK;
BOOL fResult = FALSE;
for (DWORD i = 0; i < m_Conditions.cConditions; ++i)
{
BAL_CONDITION* pCondition = m_Conditions.rgConditions + i;
hr = BalConditionEvaluate(pCondition, m_pEngine, &fResult, &m_sczFailedMessage);
BalExitOnFailure(hr, "Failed to evaluate condition.");
if (!fResult)
{
hr = E_WIXSTDBA_CONDITION_FAILED;
BalExitOnFailure1(hr, "Bundle condition evaluated to false: %ls", pCondition->sczCondition);
}
}
ReleaseNullStr(m_sczFailedMessage);
LExit:
return hr;
}
void CopyBundleLogToSpecifiedPath()
{
/// On package install complete, if WIXSTDBA_VARIABLE_LOGSPATH is defined
/// then will move bundle installation log to the specified path.
if (!m_fOverallInstallationStarted)
return;
if (BalStringVariableExists(WIXSTDBA_VARIABLE_LOGSPATH))
{
LPWSTR wzBundleLog = NULL;
LPWSTR wzInstallLogPath = NULL;
LPWSTR wzDstBundleLog = NULL;
if ( SUCCEEDED(BalGetStringVariable(WIXSTDBA_VARIABLE_LOGSPATH, &wzInstallLogPath)) &&
SUCCEEDED(BalGetStringVariable(L"WixBundleLog", &wzBundleLog)))
{
StrAllocFormatted(&wzDstBundleLog, L"%s\\%s", wzInstallLogPath, PathFile(wzBundleLog));
DirEnsureExists(wzInstallLogPath, NULL);
FileEnsureCopy(wzBundleLog, wzDstBundleLog, TRUE);
} else
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Setup was unable to copy bundle log to the specified installation log path.");
}
return;
}
void SetTaskbarButtonProgress(
__in DWORD dwOverallPercentage
)
{
HRESULT hr = S_OK;
if (m_fAttachedToConsole)
{
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
if (GetConsoleScreenBufferInfo(m_fStdConsoleHandle, &csbiInfo))
{
csbiInfo.dwCursorPosition.X = 0;
SetConsoleCursorPosition(m_fStdConsoleHandle, csbiInfo.dwCursorPosition);
}
int lnWidth = 79;
int barWidth = 60;
int pos = int(barWidth * dwOverallPercentage/100);
char szPgLine[200] = "[";
for (int i = 0; i < barWidth; ++i)
{
if (i < pos)
{
sprintf_s(szPgLine, lnWidth, "%s%s", szPgLine, "=");
}
else if (i == pos)
{
sprintf_s(szPgLine, lnWidth, "%s%s", szPgLine, ">");
}
else
{
sprintf_s(szPgLine, lnWidth, "%s%s", szPgLine, " ");
}
}
sprintf_s(szPgLine, lnWidth, "%s] %u%%", szPgLine, dwOverallPercentage);
DWORD dSzWritten;
WriteConsole(m_fStdConsoleHandle, szPgLine, strlen(szPgLine), &dSzWritten, NULL);
// m_fStdConsoleHandle = NULL;
}
if (m_fTaskbarButtonOK)
{
// hr = m_pTaskbarList->SetProgressValue(m_hWnd, dwOverallPercentage, 100UL);
BalExitOnFailure1(hr, "Failed to set taskbar button progress to: %d%%.", dwOverallPercentage);
}
LExit:
return;
}
void SetTaskbarButtonState(
__in TBPFLAG tbpFlags
)
{
HRESULT hr = S_OK;
if (m_fTaskbarButtonOK)
{
hr = m_pTaskbarList->SetProgressState(m_hWnd, tbpFlags);
BalExitOnFailure1(hr, "Failed to set taskbar button state.", tbpFlags);
}
LExit:
return;
}
void SetProgressState(
__in HRESULT hrStatus
)
{
TBPFLAG flag = TBPF_NORMAL;
if (IsCanceled() || HRESULT_FROM_WIN32(ERROR_INSTALL_USEREXIT) == hrStatus)
{
flag = TBPF_PAUSED;
}
else if (IsRollingBack() || FAILED(hrStatus))
{
flag = TBPF_ERROR;
}
SetTaskbarButtonState(flag);
}
void SavePageSettings(
__in WIXSTDBA_PAGE page
)
{
THEME_PAGE* pPage = NULL;
pPage = ThemeGetPage(m_pTheme, m_rgdwPageIds[page]);
if (pPage)
{
for (DWORD i = 0; i < pPage->cControlIndices; ++i)
{
// Loop through all the checkbox controls (or buttons with BS_AUTORADIOBUTTON) with names and set a Burn variable with that name to true or false.
THEME_CONTROL* pControl = m_pTheme->rgControls + pPage->rgdwControlIndices[i];
if ((THEME_CONTROL_TYPE_CHECKBOX == pControl->type) ||
(THEME_CONTROL_TYPE_BUTTON == pControl->type && (BS_AUTORADIOBUTTON == (BS_AUTORADIOBUTTON & pControl->dwStyle)) &&
pControl->sczName && *pControl->sczName))
{
BOOL bChecked = ThemeIsControlChecked(m_pTheme, pControl->wId);
m_pEngine->SetVariableNumeric(pControl->sczName, bChecked ? 1 : 0);
}
// Loop through all the editbox controls with names and set a Burn variable with that name to the contents.
if (THEME_CONTROL_TYPE_EDITBOX == pControl->type && pControl->sczName && *pControl->sczName &&
(WIXSTDBA_CONTROL_INSTALLFOLDER_EDITBOX != pControl->wId))
{
LPWSTR sczValue = NULL;
ThemeGetTextControl(m_pTheme, pControl->wId, &sczValue);
m_pEngine->SetVariableString(pControl->sczName, sczValue);
}
}
}
}
HRESULT LoadBootstrapperBAFunctions()
{
HRESULT hr = S_OK;
LPWSTR sczBafPath = NULL;
hr = PathRelativeToModule(&sczBafPath, L"bafunctions.dll", m_hModule);
BalExitOnFailure(hr, "Failed to get path to BA function DLL.");
#ifdef DEBUG
BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "WIXEXTBA: LoadBootstrapperBAFunctions() - BA function DLL '%ls'", sczBafPath);
#endif
m_hBAFModule = ::LoadLibraryW(sczBafPath);
if (m_hBAFModule)
{
PFN_BOOTSTRAPPER_BA_FUNCTION_CREATE pfnBAFunctionCreate = reinterpret_cast<PFN_BOOTSTRAPPER_BA_FUNCTION_CREATE>(::GetProcAddress(m_hBAFModule, "CreateBootstrapperBAFunction"));
BalExitOnNullWithLastError1(pfnBAFunctionCreate, hr, "Failed to get CreateBootstrapperBAFunction entry-point from: %ls", sczBafPath);
hr = pfnBAFunctionCreate(m_pEngine, m_hBAFModule, &m_pBAFunction);
BalExitOnFailure(hr, "Failed to create BA function.");
}
#ifdef DEBUG
else
{
BalLogError(HRESULT_FROM_WIN32(::GetLastError()), "WIXEXTBA: LoadBootstrapperBAFunctions() - Failed to load DLL %ls", sczBafPath);
}
#endif
LExit:
if (m_hBAFModule && !m_pBAFunction)
{
::FreeLibrary(m_hBAFModule);
m_hBAFModule = NULL;
}
ReleaseStr(sczBafPath);
return hr;
}
typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
bool getWindowsUserAgent(std::string &str){
OSVERSIONINFOEX osvi;
SYSTEM_INFO si;
BOOL bOsVersionInfoEx;
ZeroMemory(&si, sizeof(SYSTEM_INFO));
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*) &osvi); if(bOsVersionInfoEx == 0)
return false;
PGNSI pGNSI = (PGNSI) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo");
if(NULL != pGNSI)
pGNSI(&si);
else GetSystemInfo(&si);
std::stringstream os;
os << "Installer/wix os/win32 (Windows_NT; ";
os << osvi.dwMajorVersion << "." << osvi.dwMinorVersion << "." << osvi.dwBuildNumber;
os << "; ia32;)";
str = os.str();
return true;
}
#pragma comment( lib,"Wininet.lib")
#define BUF_LEN 1024
BOOL POSTRequest(
__in LPCSTR szHost,
__in LPCSTR szApiPath,
__in LPSTR szFormData,
__out LPSTR *ppszResponseMessage)
{
BOOL bRes = false;
StrAnsiAlloc(ppszResponseMessage, BUF_LEN);
std::string header = "Content-Type: application/x-www-form-urlencoded";
std::string userAgent;
if (getWindowsUserAgent(userAgent)) {
header += std::string("\nUser-Agent: ");
header += userAgent;
}
LPCSTR method = "POST";
LPCSTR agent = "Mozilla/4.0 (compatible; MSIE 1.0)";
HINTERNET internet = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if(internet != NULL)
{
HINTERNET connect = InternetConnectA(internet, szHost, INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
if(connect != NULL)
{
HINTERNET request = HttpOpenRequestA(connect, method, szApiPath, "HTTP/1.1", NULL, NULL,
INTERNET_FLAG_HYPERLINK |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
INTERNET_FLAG_NO_AUTH |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_NO_UI |
INTERNET_FLAG_PRAGMA_NOCACHE |
INTERNET_FLAG_RELOAD |
INTERNET_FLAG_SECURE, NULL);
if(request != NULL)
{
int datalen = 0;
if(szFormData != NULL) datalen = strlen(szFormData);
int headerlen = 0;
headerlen = (int)header.length();
if(HttpSendRequestA(request, header.c_str(), headerlen, szFormData, datalen))
{
// We have succesfully sent the POST request
bRes = true;
// Now we should read the response
DWORD bytesRead;
char holdBuff[4096];
char* temp = holdBuff;
while (InternetReadFile(request, temp, 1024, &bytesRead) == TRUE && bytesRead > 0)
{
temp += bytesRead;
}
*temp = '\0'; // manually append NULL terminator
StringCchPrintfA(*ppszResponseMessage, BUF_LEN, holdBuff);
}
else
StringCchPrintfA(*ppszResponseMessage, BUF_LEN, "Failed to send http request. Error code: %d", ::GetLastError());
InternetCloseHandle(request);
}
else
StringCchPrintfA(*ppszResponseMessage, BUF_LEN, "Failed to open http request.");
}
else
StringCchPrintfA(*ppszResponseMessage, BUF_LEN, "Connectiong to %s failed.", szHost);
InternetCloseHandle(connect);
}
else
StringCchPrintfA(*ppszResponseMessage, BUF_LEN, "Initialize internet resources failed.");
InternetCloseHandle(internet);
return bRes;
}
BOOL REST_SignInOrRegister(
__in BOOL fSignIn,
__in LPCWSTR wzSignInUserNameOrEmail,
__in LPCWSTR wzRegisterUsername,
__in LPCWSTR wzRegisterEmail,
__in LPCWSTR wzPassword/*,
__out LPWSTR *ppwzErrorMessage*/
)
{
BOOL bRes = false;
wchar_t wzFormData[BUF_LEN] = L"";
DWORD escapedLength;
escapedLength = BUF_LEN;
wchar_t wzPasswordEscaped[BUF_LEN];
UrlEscapeW(wzPassword, wzPasswordEscaped, &escapedLength, NULL);
if (fSignIn) {
// sign in
wchar_t *wzUsernameOrEmailKey;
if (wcschr(wzSignInUserNameOrEmail, L'@')) {
wzUsernameOrEmailKey = L"meteorAccountsLoginInfo[email]";
} else {
wzUsernameOrEmailKey = L"meteorAccountsLoginInfo[username]";
}
escapedLength = BUF_LEN;
wchar_t wzSignInUserNameOrEmailEscaped[BUF_LEN];
UrlEscapeW(wzSignInUserNameOrEmail, wzSignInUserNameOrEmailEscaped, &escapedLength, NULL);
StringCchPrintfW(wzFormData, BUF_LEN, L"%s=%s&meteorAccountsLoginInfo[password]=%s", wzUsernameOrEmailKey, wzSignInUserNameOrEmailEscaped, wzPasswordEscaped);
} else {
escapedLength = BUF_LEN;
wchar_t wzRegisterUsernameEscaped[BUF_LEN];
UrlEscapeW(wzRegisterUsername, wzRegisterUsernameEscaped, &escapedLength, NULL);
escapedLength = BUF_LEN;
wchar_t wzRegisterEmailEscaped[BUF_LEN];
UrlEscapeW(wzRegisterEmail, wzRegisterEmailEscaped, &escapedLength, NULL);
// register
StringCchPrintfW(wzFormData, BUF_LEN, L"username=%s&email=%s&password=%s", wzRegisterUsernameEscaped, wzRegisterEmailEscaped, wzPasswordEscaped);
}
// agentInfo part of the query
wchar_t aiHostW[BUF_LEN] = L"";
DWORD aiHostSize = BUF_LEN;
GetComputerNameW(aiHostW, &aiHostSize);
wchar_t wzAgentInfo[BUF_LEN] = L"";
StringCchPrintfW(wzAgentInfo, BUF_LEN, L"agentInfo[host]=%s&agentInfo[agent]=%s&agentInfo[agentVersion]=%s&agentInfo[arch]=%s",
aiHostW, L"Windows Installer", L"0.0", L"os.windows.x64_32");
StringCchCatW(wzFormData, BUF_LEN, L"&");
StringCchCatW(wzFormData, BUF_LEN, wzAgentInfo);
size_t i;
char *pMBFormData = (char *)malloc( BUF_LEN );
wcstombs_s(&i, pMBFormData, (size_t)BUF_LEN, wzFormData, (size_t)BUF_LEN );
char *pMBDataResponse = NULL;
wchar_t wzErrorMessage[BUF_LEN] = L"";
char *path = fSignIn ? "/api/v1/private/login"
: "/api/v1/private/register";
if (POSTRequest("www.meteor.com", path, pMBFormData, &pMBDataResponse))
{
JSONValue *JSONResponse = JSON::Parse(pMBDataResponse);
if (JSONResponse != NULL)
{
size_t n;
// Retrieve the main object
JSONObject JSONRoot;
if (JSONResponse->IsObject() == false)
{
mbstowcs_s(&n, wzErrorMessage, BUF_LEN, pMBDataResponse, BUF_LEN);
}
else
{
JSONRoot = JSONResponse->AsObject();
if (JSONRoot.find(L"reason") != JSONRoot.end() && JSONRoot[L"reason"]->IsString())
{
StringCchPrintfW(wzErrorMessage, BUF_LEN, JSONRoot[L"reason"]->AsString().c_str());
}
else
{
bRes = true;
LPWSTR wzUMSFilePath = NULL;
LPWSTR wzUMSFileExpPath = NULL;
if (SUCCEEDED(BalGetStringVariable(WIXSTDBA_VARIABLE_USERMETEORSESSIONFILE, &wzUMSFilePath)))
{
if (SUCCEEDED(BalFormatString(wzUMSFilePath, &wzUMSFileExpPath)))
{
FileEnsureDelete(wzUMSFileExpPath);
HANDLE hFile = CreateFileW(wzUMSFileExpPath, GENERIC_ALL, 0, 0L, 1, 0x80L, 0);
if (hFile != INVALID_HANDLE_VALUE)
{
std::string innerSession = pMBDataResponse;
// In JS this would be: innerSession.userId = innerSession.id; delete innerSession.id;
innerSession.replace(innerSession.find("\"id\":"), strlen("\"id\":"), "\"userId\":");
// In JS this would be: innerSession.type = "meteor-account"
innerSession.replace(innerSession.find("{"), 1, "{\"type\": \"meteor-account\", ");
// In JS this would be: sessionData = {sessions: {"www.meteor.com": innerSession}}
std::string sessionData = "{\"sessions\": {\"www.meteor.com\": ";
sessionData += innerSession;
sessionData += "}}";
char sessionDataStr[BUF_LEN];
strcpy_s(sessionDataStr, BUF_LEN, sessionData.c_str());
DWORD bytesWritten;
WriteFile(hFile, sessionDataStr, strlen(sessionDataStr), &bytesWritten, NULL);
CloseHandle(hFile);
}
}
}
}
}
}
else {
wcsncat_s(wzErrorMessage, L"Unknown error.", BUF_LEN-1);
}
// Clean up JSON object
delete JSONResponse;
} else {
wcsncat_s(wzErrorMessage, L"Network error contacting the Meteor accounts server. Please retry, or skip this step and complete your registration later.", BUF_LEN-1);
}
if (bRes == false)
{
wchar_t wzMessage[BUF_LEN] = L"";
StringCchPrintfW(wzMessage, BUF_LEN, L"%s", wzErrorMessage);
MessageBoxW(m_hWnd, wzMessage, m_pTheme->sczCaption, MB_ICONEXCLAMATION | MB_OK);
}
return bRes;
}
HRESULT DAPI LocGetString(
__in const WIX_LOCALIZATION* pWixLoc,
__in_z LPCWSTR wzId,
__out LOC_STRING** ppLocString
)
{
HRESULT hr = E_NOTFOUND;
LOC_STRING* pLocString = NULL;
for (DWORD i = 0; i < pWixLoc->cLocStrings; ++i)
{
pLocString = pWixLoc->rgLocStrings + i;
if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, pLocString->wzId, -1, wzId, -1))
{
*ppLocString = pLocString;
hr = S_OK;
break;
}
}
return hr;
}
public:
//
// Constructor - intitialize member variables.
//
CWixStandardBootstrapperApplication(
__in HMODULE hModule,
__in BOOL fPrereq,
__in IBootstrapperEngine* pEngine,
__in const BOOTSTRAPPER_COMMAND* pCommand
) : CBalBaseBootstrapperApplication(pEngine, pCommand, 3, 3000)
{
m_hModule = hModule;
memcpy_s(&m_command, sizeof(m_command), pCommand, sizeof(BOOTSTRAPPER_COMMAND));
// Pre-req BA should only show help or do an install (to launch the Managed BA which can then do the right action).
if (fPrereq && BOOTSTRAPPER_ACTION_HELP != m_command.action && BOOTSTRAPPER_ACTION_INSTALL != m_command.action)
{
m_command.action = BOOTSTRAPPER_ACTION_INSTALL;
}
else // maybe modify the action state if the bundle is or is not already installed.
{
LONGLONG llInstalled = 0;
HRESULT hr = BalGetNumericVariable(L"WixBundleInstalled", &llInstalled);
if (SUCCEEDED(hr) && BOOTSTRAPPER_RESUME_TYPE_REBOOT != m_command.resumeType && 0 < llInstalled && BOOTSTRAPPER_ACTION_INSTALL == m_command.action)
{
m_command.action = BOOTSTRAPPER_ACTION_MODIFY;
}
else if (0 == llInstalled && (BOOTSTRAPPER_ACTION_MODIFY == m_command.action || BOOTSTRAPPER_ACTION_REPAIR == m_command.action))
{
m_command.action = BOOTSTRAPPER_ACTION_INSTALL;
}
}
m_plannedAction = BOOTSTRAPPER_ACTION_UNKNOWN;
// When resuming from restart doing some install-like operation, try to find the package that forced the
// restart. We'll use this information during planning.
m_sczAfterForcedRestartPackage = NULL;
if (BOOTSTRAPPER_RESUME_TYPE_REBOOT == m_command.resumeType && BOOTSTRAPPER_ACTION_UNINSTALL < m_command.action)
{
// Ensure the forced restart package variable is null when it is an empty string.
HRESULT hr = BalGetStringVariable(L"WixBundleForcedRestartPackage", &m_sczAfterForcedRestartPackage);
if (FAILED(hr) || !m_sczAfterForcedRestartPackage || !*m_sczAfterForcedRestartPackage)
{
ReleaseNullStr(m_sczAfterForcedRestartPackage);
}
}
m_pWixLoc = NULL;
memset(&m_Bundle, 0, sizeof(m_Bundle));
memset(&m_Conditions, 0, sizeof(m_Conditions));
m_sczConfirmCloseMessage = NULL;
m_sczFailedMessage = NULL;
m_sczLanguage = NULL;
m_pTheme = NULL;
memset(m_rgdwPageIds, 0, sizeof(m_rgdwPageIds));
m_dwCurrentPage = 0;
m_hUiThread = NULL;
m_fRegistered = FALSE;
m_hWnd = NULL;
m_state = WIXSTDBA_STATE_INITIALIZING;
m_hrFinal = S_OK;
m_fDowngrading = FALSE;
m_restartResult = BOOTSTRAPPER_APPLY_RESTART_NONE;
m_fRestartRequired = FALSE;
m_fAllowRestart = FALSE;
m_sczLicenseFile = NULL;
m_sczLicenseUrl = NULL;
m_fSuppressOptionsUI = FALSE;
m_fSuppressDowngradeFailure = FALSE;
m_fSuppressRepair = FALSE;
m_fShowVersion = FALSE;
m_fIsRepair = FALSE;
m_fIsUninstall = FALSE;
m_fInstallSucceed = FALSE;
m_fIsProductCore = FALSE;
m_sdOverridableVariables = NULL;
m_pTaskbarList = NULL;
m_uTaskbarButtonCreatedMessage = UINT_MAX;
m_fTaskbarButtonOK = FALSE;
m_fShowingInternalUiThisPackage = FALSE;
m_fPrereq = fPrereq;
m_sczPrereqPackage = NULL;
m_fPrereqInstalled = FALSE;
m_fPrereqAlreadyInstalled = FALSE;
m_fOverallInstallationStarted = FALSE;
m_fUpdating = FALSE;
m_fOutputToConsole = FALSE;
m_fAttachedToConsole = FALSE;
m_fStdConsoleHandle = NULL;
pEngine->AddRef();
m_pEngine = pEngine;
m_hBAFModule = NULL;
m_pBAFunction = NULL;
}
//
// Destructor - release member variables.
//
~CWixStandardBootstrapperApplication()
{
CopyBundleLogToSpecifiedPath();
AssertSz(!::IsWindow(m_hWnd), "Window should have been destroyed before destructor.");
AssertSz(!m_pTheme, "Theme should have been released before destuctor.");
if (m_fAttachedToConsole)
{
FreeConsole();
}
ReleaseObject(m_pTaskbarList);
ReleaseDict(m_sdOverridableVariables);
ReleaseStr(m_sczFailedMessage);
ReleaseStr(m_sczConfirmCloseMessage);
BalConditionsUninitialize(&m_Conditions);
BalInfoUninitialize(&m_Bundle);
LocFree(m_pWixLoc);
ReleaseStr(m_sczLanguage);
ReleaseStr(m_sczLicenseFile);
ReleaseStr(m_sczLicenseUrl);
ReleaseStr(m_sczPrereqPackage);
ReleaseStr(m_sczAfterForcedRestartPackage);
ReleaseNullObject(m_pEngine);
if (m_hBAFModule)
{
::FreeLibrary(m_hBAFModule);
m_hBAFModule = NULL;
}
}
private:
HMODULE m_hModule;
BOOTSTRAPPER_COMMAND m_command;
IBootstrapperEngine* m_pEngine;
BOOTSTRAPPER_ACTION m_plannedAction;
LPWSTR m_sczAfterForcedRestartPackage;
WIX_LOCALIZATION* m_pWixLoc;
BAL_INFO_BUNDLE m_Bundle;
BAL_CONDITIONS m_Conditions;
LPWSTR m_sczFailedMessage;
LPWSTR m_sczConfirmCloseMessage;
LPWSTR m_sczLanguage;
THEME* m_pTheme;
DWORD m_rgdwPageIds[countof(vrgwzPageNames)];
DWORD m_dwCurrentPage;
HANDLE m_hUiThread;
BOOL m_fRegistered;
HWND m_hWnd;
WIXSTDBA_STATE m_state;
WIXSTDBA_STATE m_stateInstallPage;
HRESULT m_hrFinal;
BOOL m_fStartedExecution;
DWORD m_dwCalculatedCacheProgress;
DWORD m_dwCalculatedExecuteProgress;
BOOL m_fDowngrading;
BOOTSTRAPPER_APPLY_RESTART m_restartResult;
BOOL m_fRestartRequired;
BOOL m_fAllowRestart;
LPWSTR m_sczLicenseFile;
LPWSTR m_sczLicenseUrl;
BOOL m_fSuppressOptionsUI;
BOOL m_fSuppressDowngradeFailure;
BOOL m_fSuppressRepair;
BOOL m_fShowVersion;
BOOL m_fIsRepair;
BOOL m_fIsUninstall;
BOOL m_fInstallSucceed;
BOOTSTRAPPER_RELATED_OPERATION m_Operation;
BOOL m_fIsProductCore;
BOOL m_fOverallInstallationStarted;
STRINGDICT_HANDLE m_sdOverridableVariables;
BOOL m_fPrereq;
LPWSTR m_sczPrereqPackage;
BOOL m_fPrereqInstalled;
BOOL m_fPrereqAlreadyInstalled;
BOOL m_fOutputToConsole;
BOOL m_fAttachedToConsole;
HANDLE m_fStdConsoleHandle;
ITaskbarList3* m_pTaskbarList;
UINT m_uTaskbarButtonCreatedMessage;
BOOL m_fTaskbarButtonOK;
BOOL m_fShowingInternalUiThisPackage;
BOOL m_fUpdating;
LPCWSTR m_wzUpdateLocation;
HMODULE m_hBAFModule;
IBootstrapperBAFunction* m_pBAFunction;
};
//
// CreateUserExperience - creates a new IBurnUserExperience object.
//
HRESULT CreateBootstrapperApplication(
__in HMODULE hModule,
__in BOOL fPrereq,
__in IBootstrapperEngine* pEngine,
__in const BOOTSTRAPPER_COMMAND* pCommand,
__out IBootstrapperApplication** ppApplication
)
{
HRESULT hr = S_OK;
CWixStandardBootstrapperApplication* pApplication = NULL;
pApplication = new CWixStandardBootstrapperApplication(hModule, fPrereq, pEngine, pCommand);
ExitOnNull(pApplication, hr, E_OUTOFMEMORY, "Failed to create new standard bootstrapper application object.");
*ppApplication = pApplication;
pApplication = NULL;
LExit:
ReleaseObject(pApplication);
return hr;
}
| mit |
ruikong/WinObjC | deps/3rdparty/icu/icu/source/test/cintltst/ccapitst.c | 167 | 135004 | /********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2015, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************/
/*****************************************************************************
*
* File ccapitst.c
*
* Modification History:
* Name Description
* Madhu Katragadda Ported for C API
******************************************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "unicode/uloc.h"
#include "unicode/ucnv.h"
#include "unicode/ucnv_err.h"
#include "unicode/putil.h"
#include "unicode/uset.h"
#include "unicode/ustring.h"
#include "ucnv_bld.h" /* for sizeof(UConverter) */
#include "cmemory.h" /* for UAlignedMemory */
#include "cintltst.h"
#include "ccapitst.h"
#include "cstring.h"
#define NUM_CODEPAGE 1
#define MAX_FILE_LEN 1024*20
#define UCS_FILE_NAME_SIZE 512
/*returns an action other than the one provided*/
#if !UCONFIG_NO_LEGACY_CONVERSION
static UConverterFromUCallback otherUnicodeAction(UConverterFromUCallback MIA);
static UConverterToUCallback otherCharAction(UConverterToUCallback MIA);
#endif
static UConverter *
cnv_open(const char *name, UErrorCode *pErrorCode) {
if(name!=NULL && name[0]=='*') {
return ucnv_openPackage(loadTestData(pErrorCode), name+1, pErrorCode);
} else {
return ucnv_open(name, pErrorCode);
}
}
static void ListNames(void);
static void TestFlushCache(void);
static void TestDuplicateAlias(void);
static void TestCCSID(void);
static void TestJ932(void);
static void TestJ1968(void);
#if !UCONFIG_NO_FILE_IO && !UCONFIG_NO_LEGACY_CONVERSION
static void TestLMBCSMaxChar(void);
#endif
#if !UCONFIG_NO_LEGACY_CONVERSION
static void TestConvertSafeCloneCallback(void);
#endif
static void TestEBCDICSwapLFNL(void);
static void TestConvertEx(void);
static void TestConvertExFromUTF8(void);
static void TestConvertExFromUTF8_C5F0(void);
static void TestConvertAlgorithmic(void);
void TestDefaultConverterError(void); /* defined in cctest.c */
void TestDefaultConverterSet(void); /* defined in cctest.c */
static void TestToUCountPending(void);
static void TestFromUCountPending(void);
static void TestDefaultName(void);
static void TestCompareNames(void);
static void TestSubstString(void);
static void InvalidArguments(void);
static void TestGetName(void);
static void TestUTFBOM(void);
void addTestConvert(TestNode** root);
void addTestConvert(TestNode** root)
{
addTest(root, &ListNames, "tsconv/ccapitst/ListNames");
addTest(root, &TestConvert, "tsconv/ccapitst/TestConvert");
addTest(root, &TestFlushCache, "tsconv/ccapitst/TestFlushCache");
addTest(root, &TestAlias, "tsconv/ccapitst/TestAlias");
addTest(root, &TestDuplicateAlias, "tsconv/ccapitst/TestDuplicateAlias");
addTest(root, &TestConvertSafeClone, "tsconv/ccapitst/TestConvertSafeClone");
#if !UCONFIG_NO_LEGACY_CONVERSION
addTest(root, &TestConvertSafeCloneCallback,"tsconv/ccapitst/TestConvertSafeCloneCallback");
#endif
addTest(root, &TestCCSID, "tsconv/ccapitst/TestCCSID");
addTest(root, &TestJ932, "tsconv/ccapitst/TestJ932");
addTest(root, &TestJ1968, "tsconv/ccapitst/TestJ1968");
#if !UCONFIG_NO_FILE_IO && !UCONFIG_NO_LEGACY_CONVERSION
addTest(root, &TestLMBCSMaxChar, "tsconv/ccapitst/TestLMBCSMaxChar");
#endif
addTest(root, &TestEBCDICSwapLFNL, "tsconv/ccapitst/TestEBCDICSwapLFNL");
addTest(root, &TestConvertEx, "tsconv/ccapitst/TestConvertEx");
addTest(root, &TestConvertExFromUTF8, "tsconv/ccapitst/TestConvertExFromUTF8");
addTest(root, &TestConvertExFromUTF8_C5F0, "tsconv/ccapitst/TestConvertExFromUTF8_C5F0");
addTest(root, &TestConvertAlgorithmic, "tsconv/ccapitst/TestConvertAlgorithmic");
addTest(root, &TestDefaultConverterError, "tsconv/ccapitst/TestDefaultConverterError");
addTest(root, &TestDefaultConverterSet, "tsconv/ccapitst/TestDefaultConverterSet");
#if !UCONFIG_NO_FILE_IO
addTest(root, &TestToUCountPending, "tsconv/ccapitst/TestToUCountPending");
addTest(root, &TestFromUCountPending, "tsconv/ccapitst/TestFromUCountPending");
#endif
addTest(root, &TestDefaultName, "tsconv/ccapitst/TestDefaultName");
addTest(root, &TestCompareNames, "tsconv/ccapitst/TestCompareNames");
addTest(root, &TestSubstString, "tsconv/ccapitst/TestSubstString");
addTest(root, &InvalidArguments, "tsconv/ccapitst/InvalidArguments");
addTest(root, &TestGetName, "tsconv/ccapitst/TestGetName");
addTest(root, &TestUTFBOM, "tsconv/ccapitst/TestUTFBOM");
}
static void ListNames(void) {
UErrorCode err = U_ZERO_ERROR;
int32_t testLong1 = 0;
const char* available_conv;
UEnumeration *allNamesEnum = NULL;
int32_t allNamesCount = 0;
uint16_t count;
log_verbose("Testing ucnv_openAllNames()...");
allNamesEnum = ucnv_openAllNames(&err);
if(U_FAILURE(err)) {
log_data_err("FAILURE! ucnv_openAllNames() -> %s\n", myErrorName(err));
}
else {
const char *string = NULL;
int32_t len = 0;
int32_t count1 = 0;
int32_t count2 = 0;
allNamesCount = uenum_count(allNamesEnum, &err);
while ((string = uenum_next(allNamesEnum, &len, &err))) {
count1++;
log_verbose("read \"%s\", length %i\n", string, len);
}
if (U_FAILURE(err)) {
log_err("FAILURE! uenum_next(allNamesEnum...) set an error: %s\n", u_errorName(err));
err = U_ZERO_ERROR;
}
uenum_reset(allNamesEnum, &err);
while ((string = uenum_next(allNamesEnum, &len, &err))) {
count2++;
ucnv_close(ucnv_open(string, &err));
log_verbose("read \"%s\", length %i (%s)\n", string, len, U_SUCCESS(err) ? "available" : "unavailable");
err = U_ZERO_ERROR;
}
if (count1 != count2) {
log_err("FAILURE! uenum_reset(allNamesEnum, &err); doesn't work\n");
}
}
uenum_close(allNamesEnum);
err = U_ZERO_ERROR;
/*Tests ucnv_getAvailableName(), getAvialableCount()*/
log_verbose("Testing ucnv_countAvailable()...");
testLong1=ucnv_countAvailable();
log_info("Number of available codepages: %d/%d\n", testLong1, allNamesCount);
log_verbose("\n---Testing ucnv_getAvailableName.."); /*need to check this out */
available_conv = ucnv_getAvailableName(testLong1);
/*test ucnv_getAvailableName with err condition*/
log_verbose("\n---Testing ucnv_getAvailableName..with index < 0 ");
available_conv = ucnv_getAvailableName(-1);
if(available_conv != NULL){
log_err("ucnv_getAvailableName() with index < 0) should return NULL\n");
}
/* Test ucnv_countAliases() etc. */
count = ucnv_countAliases("utf-8", &err);
if(U_FAILURE(err)) {
log_data_err("FAILURE! ucnv_countAliases(\"utf-8\") -> %s\n", myErrorName(err));
} else if(count <= 0) {
log_err("FAILURE! ucnv_countAliases(\"utf-8\") -> %d aliases\n", count);
} else {
/* try to get the aliases individually */
const char *alias;
alias = ucnv_getAlias("utf-8", 0, &err);
if(U_FAILURE(err)) {
log_err("FAILURE! ucnv_getAlias(\"utf-8\", 0) -> %s\n", myErrorName(err));
} else if(strcmp("UTF-8", alias) != 0) {
log_err("FAILURE! ucnv_getAlias(\"utf-8\", 0) -> %s instead of UTF-8\n", alias);
} else {
uint16_t aliasNum;
for(aliasNum = 0; aliasNum < count; ++aliasNum) {
alias = ucnv_getAlias("utf-8", aliasNum, &err);
if(U_FAILURE(err)) {
log_err("FAILURE! ucnv_getAlias(\"utf-8\", %d) -> %s\n", aliasNum, myErrorName(err));
} else if(strlen(alias) > 20) {
/* sanity check */
log_err("FAILURE! ucnv_getAlias(\"utf-8\", %d) -> alias %s insanely long, corrupt?!\n", aliasNum, alias);
} else {
log_verbose("alias %d for utf-8: %s\n", aliasNum, alias);
}
}
if(U_SUCCESS(err)) {
/* try to fill an array with all aliases */
const char **aliases;
aliases=(const char **)malloc(count * sizeof(const char *));
if(aliases != 0) {
ucnv_getAliases("utf-8", aliases, &err);
if(U_FAILURE(err)) {
log_err("FAILURE! ucnv_getAliases(\"utf-8\") -> %s\n", myErrorName(err));
} else {
for(aliasNum = 0; aliasNum < count; ++aliasNum) {
/* compare the pointers with the ones returned individually */
alias = ucnv_getAlias("utf-8", aliasNum, &err);
if(U_FAILURE(err)) {
log_err("FAILURE! ucnv_getAlias(\"utf-8\", %d) -> %s\n", aliasNum, myErrorName(err));
} else if(aliases[aliasNum] != alias) {
log_err("FAILURE! ucnv_getAliases(\"utf-8\")[%d] != ucnv_getAlias(\"utf-8\", %d)\n", aliasNum, aliasNum);
}
}
}
free((char **)aliases);
}
}
}
}
}
static void TestConvert()
{
#if !UCONFIG_NO_LEGACY_CONVERSION
char myptr[4];
char save[4];
int32_t testLong1 = 0;
uint16_t rest = 0;
int32_t len = 0;
int32_t x = 0;
FILE* ucs_file_in = NULL;
UChar BOM = 0x0000;
UChar myUChar = 0x0000;
char* mytarget; /* [MAX_FILE_LEN] */
char* mytarget_1;
char* mytarget_use;
UChar* consumedUni = NULL;
char* consumed = NULL;
char* output_cp_buffer; /* [MAX_FILE_LEN] */
UChar* ucs_file_buffer; /* [MAX_FILE_LEN] */
UChar* ucs_file_buffer_use;
UChar* my_ucs_file_buffer; /* [MAX_FILE_LEN] */
UChar* my_ucs_file_buffer_1;
int8_t ii = 0;
uint16_t codepage_index = 0;
int32_t cp = 0;
UErrorCode err = U_ZERO_ERROR;
char ucs_file_name[UCS_FILE_NAME_SIZE];
UConverterFromUCallback MIA1, MIA1_2;
UConverterToUCallback MIA2, MIA2_2;
const void *MIA1Context, *MIA1Context2, *MIA2Context, *MIA2Context2;
UConverter* someConverters[5];
UConverter* myConverter = 0;
UChar* displayname = 0;
const char* locale;
UChar* uchar1 = 0;
UChar* uchar2 = 0;
UChar* uchar3 = 0;
int32_t targetcapacity2;
int32_t targetcapacity;
int32_t targetsize;
int32_t disnamelen;
const UChar* tmp_ucs_buf;
const UChar* tmp_consumedUni=NULL;
const char* tmp_mytarget_use;
const char* tmp_consumed;
/******************************************************************
Checking Unicode -> ksc
******************************************************************/
const char* CodePagesToTest[NUM_CODEPAGE] =
{
"ibm-949_P110-1999"
};
const uint16_t CodePageNumberToTest[NUM_CODEPAGE] =
{
949
};
const int8_t CodePagesMinChars[NUM_CODEPAGE] =
{
1
};
const int8_t CodePagesMaxChars[NUM_CODEPAGE] =
{
2
};
const uint16_t CodePagesSubstitutionChars[NUM_CODEPAGE] =
{
0xAFFE
};
const char* CodePagesTestFiles[NUM_CODEPAGE] =
{
"uni-text.bin"
};
const UConverterPlatform CodePagesPlatform[NUM_CODEPAGE] =
{
UCNV_IBM
};
const char* CodePagesLocale[NUM_CODEPAGE] =
{
"ko_KR"
};
UConverterFromUCallback oldFromUAction = NULL;
UConverterToUCallback oldToUAction = NULL;
const void* oldFromUContext = NULL;
const void* oldToUContext = NULL;
/* Allocate memory */
mytarget = (char*) malloc(MAX_FILE_LEN * sizeof(mytarget[0]));
output_cp_buffer = (char*) malloc(MAX_FILE_LEN * sizeof(output_cp_buffer[0]));
ucs_file_buffer = (UChar*) malloc(MAX_FILE_LEN * sizeof(ucs_file_buffer[0]));
my_ucs_file_buffer = (UChar*) malloc(MAX_FILE_LEN * sizeof(my_ucs_file_buffer[0]));
ucs_file_buffer_use = ucs_file_buffer;
mytarget_1=mytarget;
mytarget_use = mytarget;
my_ucs_file_buffer_1=my_ucs_file_buffer;
/* flush the converter cache to get a consistent state before the flushing is tested */
ucnv_flushCache();
/*Testing ucnv_openU()*/
{
UChar converterName[]={ 0x0069, 0x0062, 0x006d, 0x002d, 0x0039, 0x0034, 0x0033, 0x0000}; /*ibm-943*/
UChar firstSortedName[]={ 0x0021, 0x0000}; /* ! */
UChar lastSortedName[]={ 0x007E, 0x0000}; /* ~ */
const char *illegalNameChars={ "ibm-943 ibm-943 ibm-943 ibm-943 ibm-943 ibm-943 ibm-943 ibm-943 ibm-943 ibm-943"};
UChar illegalName[100];
UConverter *converter=NULL;
err=U_ZERO_ERROR;
converter=ucnv_openU(converterName, &err);
if(U_FAILURE(err)){
log_data_err("FAILURE! ucnv_openU(ibm-943, err) failed. %s\n", myErrorName(err));
}
ucnv_close(converter);
err=U_ZERO_ERROR;
converter=ucnv_openU(NULL, &err);
if(U_FAILURE(err)){
log_err("FAILURE! ucnv_openU(NULL, err) failed. %s\n", myErrorName(err));
}
ucnv_close(converter);
/*testing with error value*/
err=U_ILLEGAL_ARGUMENT_ERROR;
converter=ucnv_openU(converterName, &err);
if(!(converter == NULL)){
log_data_err("FAILURE! ucnv_openU(ibm-943, U_ILLEGAL_ARGUMENT_ERROR) is expected to fail\n");
}
ucnv_close(converter);
err=U_ZERO_ERROR;
u_uastrcpy(illegalName, "");
u_uastrcpy(illegalName, illegalNameChars);
ucnv_openU(illegalName, &err);
if(!(err==U_ILLEGAL_ARGUMENT_ERROR)){
log_err("FAILURE! ucnv_openU(illegalName, err) is expected to fail\n");
}
err=U_ZERO_ERROR;
ucnv_openU(firstSortedName, &err);
if(err!=U_FILE_ACCESS_ERROR){
log_err("FAILURE! ucnv_openU(firstSortedName, err) is expected to fail\n");
}
err=U_ZERO_ERROR;
ucnv_openU(lastSortedName, &err);
if(err!=U_FILE_ACCESS_ERROR){
log_err("FAILURE! ucnv_openU(lastSortedName, err) is expected to fail\n");
}
err=U_ZERO_ERROR;
}
log_verbose("Testing ucnv_open() with converter name greater than 7 characters\n");
{
UConverter *cnv=NULL;
err=U_ZERO_ERROR;
cnv=ucnv_open("ibm-949,Madhu", &err);
if(U_FAILURE(err)){
log_data_err("FAILURE! ucnv_open(\"ibm-949,Madhu\", err) failed. %s\n", myErrorName(err));
}
ucnv_close(cnv);
}
/*Testing ucnv_convert()*/
{
int32_t targetLimit=0, sourceLimit=0, i=0, targetCapacity=0;
const uint8_t source[]={ 0x00, 0x04, 0x05, 0x06, 0xa2, 0xb4, 0x00};
const uint8_t expectedTarget[]={ 0x00, 0x37, 0x2d, 0x2e, 0x0e, 0x49, 0x62, 0x0f, 0x00};
char *target=0;
sourceLimit=sizeof(source)/sizeof(source[0]);
err=U_ZERO_ERROR;
targetLimit=0;
targetCapacity=ucnv_convert("ibm-1364", "ibm-1363", NULL, targetLimit , (const char*)source, sourceLimit, &err);
if(err == U_BUFFER_OVERFLOW_ERROR){
err=U_ZERO_ERROR;
targetLimit=targetCapacity+1;
target=(char*)malloc(sizeof(char) * targetLimit);
targetCapacity=ucnv_convert("ibm-1364", "ibm-1363", target, targetLimit , (const char*)source, sourceLimit, &err);
}
if(U_FAILURE(err)){
log_data_err("FAILURE! ucnv_convert(ibm-1363->ibm-1364) failed. %s\n", myErrorName(err));
}
else {
for(i=0; i<targetCapacity; i++){
if(target[i] != expectedTarget[i]){
log_err("FAIL: ucnv_convert(ibm-1363->ibm-1364) failed.at index \n i=%d, Expected: %lx Got: %lx\n", i, (UChar)expectedTarget[i], (uint8_t)target[i]);
}
}
i=ucnv_convert("ibm-1364", "ibm-1363", target, targetLimit , (const char*)source+1, -1, &err);
if(U_FAILURE(err) || i!=7){
log_err("FAILURE! ucnv_convert() with sourceLimit=-1 failed: %s, returned %d instead of 7\n",
u_errorName(err), i);
}
/*Test error conditions*/
err=U_ZERO_ERROR;
i=ucnv_convert("ibm-1364", "ibm-1363", target, targetLimit , (const char*)source, 0, &err);
if(i !=0){
log_err("FAILURE! ucnv_convert() with sourceLimit=0 is expected to return 0\n");
}
err=U_ILLEGAL_ARGUMENT_ERROR;
sourceLimit=sizeof(source)/sizeof(source[0]);
i=ucnv_convert("ibm-1364", "ibm-1363", target, targetLimit , (const char*)source, sourceLimit, &err);
if(i !=0 ){
log_err("FAILURE! ucnv_convert() with err=U_ILLEGAL_ARGUMENT_ERROR is expected to return 0\n");
}
err=U_ZERO_ERROR;
sourceLimit=sizeof(source)/sizeof(source[0]);
targetLimit=0;
i=ucnv_convert("ibm-1364", "ibm-1363", target, targetLimit , (const char*)source, sourceLimit, &err);
if(!(U_FAILURE(err) && err==U_BUFFER_OVERFLOW_ERROR)){
log_err("FAILURE! ucnv_convert() with targetLimit=0 is expected to throw U_BUFFER_OVERFLOW_ERROR\n");
}
err=U_ZERO_ERROR;
free(target);
}
}
/*Testing ucnv_openCCSID and ucnv_open with error conditions*/
log_verbose("\n---Testing ucnv_open with err ! = U_ZERO_ERROR...\n");
err=U_ILLEGAL_ARGUMENT_ERROR;
if(ucnv_open(NULL, &err) != NULL){
log_err("ucnv_open with err != U_ZERO_ERROR is supposed to fail\n");
}
if(ucnv_openCCSID(1051, UCNV_IBM, &err) != NULL){
log_err("ucnv_open with err != U_ZERO_ERROR is supposed to fail\n");
}
err=U_ZERO_ERROR;
/* Testing ucnv_openCCSID(), ucnv_open(), ucnv_getName() */
log_verbose("\n---Testing ucnv_open default...\n");
someConverters[0] = ucnv_open(NULL,&err);
someConverters[1] = ucnv_open(NULL,&err);
someConverters[2] = ucnv_open("utf8", &err);
someConverters[3] = ucnv_openCCSID(949,UCNV_IBM,&err);
ucnv_close(ucnv_openCCSID(1051, UCNV_IBM, &err)); /* test for j350; ucnv_close(NULL) is safe */
if (U_FAILURE(err)){ log_data_err("FAILURE! %s\n", myErrorName(err));}
/* Testing ucnv_getName()*/
/*default code page */
ucnv_getName(someConverters[0], &err);
if(U_FAILURE(err)) {
log_data_err("getName[0] failed\n");
} else {
log_verbose("getName(someConverters[0]) returned %s\n", ucnv_getName(someConverters[0], &err));
}
ucnv_getName(someConverters[1], &err);
if(U_FAILURE(err)) {
log_data_err("getName[1] failed\n");
} else {
log_verbose("getName(someConverters[1]) returned %s\n", ucnv_getName(someConverters[1], &err));
}
ucnv_close(someConverters[0]);
ucnv_close(someConverters[1]);
ucnv_close(someConverters[2]);
ucnv_close(someConverters[3]);
for (codepage_index=0; codepage_index < NUM_CODEPAGE; ++codepage_index)
{
int32_t i = 0;
err = U_ZERO_ERROR;
#ifdef U_TOPSRCDIR
strcpy(ucs_file_name, U_TOPSRCDIR U_FILE_SEP_STRING"test"U_FILE_SEP_STRING"testdata"U_FILE_SEP_STRING);
#else
strcpy(ucs_file_name, loadTestData(&err));
if(U_FAILURE(err)){
log_err("\nCouldn't get the test data directory... Exiting...Error:%s\n", u_errorName(err));
return;
}
{
char* index = strrchr(ucs_file_name,(char)U_FILE_SEP_CHAR);
if((unsigned int)(index-ucs_file_name) != (strlen(ucs_file_name)-1)){
*(index+1)=0;
}
}
strcat(ucs_file_name,".."U_FILE_SEP_STRING);
#endif
strcat(ucs_file_name, CodePagesTestFiles[codepage_index]);
ucs_file_in = fopen(ucs_file_name,"rb");
if (!ucs_file_in)
{
log_data_err("Couldn't open the Unicode file [%s]... Exiting...\n", ucs_file_name);
return;
}
/*Creates a converter and testing ucnv_openCCSID(u_int code_page, platform, errstatus*/
/* myConverter =ucnv_openCCSID(CodePageNumberToTest[codepage_index],UCNV_IBM, &err); */
/* ucnv_flushCache(); */
myConverter =ucnv_open( "ibm-949", &err);
if (!myConverter || U_FAILURE(err))
{
log_data_err("Error creating the ibm-949 converter - %s \n", u_errorName(err));
fclose(ucs_file_in);
break;
}
/*testing for ucnv_getName() */
log_verbose("Testing ucnv_getName()...\n");
ucnv_getName(myConverter, &err);
if(U_FAILURE(err))
log_err("Error in getName\n");
else
{
log_verbose("getName o.k. %s\n", ucnv_getName(myConverter, &err));
}
if (uprv_stricmp(ucnv_getName(myConverter, &err), CodePagesToTest[codepage_index]))
log_err("getName failed\n");
else
log_verbose("getName ok\n");
/*Test getName with error condition*/
{
const char* name=0;
err=U_ILLEGAL_ARGUMENT_ERROR;
log_verbose("Testing ucnv_getName with err != U_ZERO_ERROR");
name=ucnv_getName(myConverter, &err);
if(name != NULL){
log_err("ucnv_getName() with err != U_ZERO_ERROR is expected to fail");
}
err=U_ZERO_ERROR;
}
/*Tests ucnv_getMaxCharSize() and ucnv_getMinCharSize()*/
log_verbose("Testing ucnv_getMaxCharSize()...\n");
if (ucnv_getMaxCharSize(myConverter)==CodePagesMaxChars[codepage_index])
log_verbose("Max byte per character OK\n");
else
log_err("Max byte per character failed\n");
log_verbose("\n---Testing ucnv_getMinCharSize()...\n");
if (ucnv_getMinCharSize(myConverter)==CodePagesMinChars[codepage_index])
log_verbose("Min byte per character OK\n");
else
log_err("Min byte per character failed\n");
/*Testing for ucnv_getSubstChars() and ucnv_setSubstChars()*/
log_verbose("\n---Testing ucnv_getSubstChars...\n");
ii=4;
ucnv_getSubstChars(myConverter, myptr, &ii, &err);
if (ii <= 0) {
log_err("ucnv_getSubstChars returned a negative number %d\n", ii);
}
for(x=0;x<ii;x++)
rest = (uint16_t)(((unsigned char)rest << 8) + (unsigned char)myptr[x]);
if (rest==CodePagesSubstitutionChars[codepage_index])
log_verbose("Substitution character ok\n");
else
log_err("Substitution character failed.\n");
log_verbose("\n---Testing ucnv_setSubstChars RoundTrip Test ...\n");
ucnv_setSubstChars(myConverter, myptr, ii, &err);
if (U_FAILURE(err))
{
log_err("FAILURE! %s\n", myErrorName(err));
}
ucnv_getSubstChars(myConverter,save, &ii, &err);
if (U_FAILURE(err))
{
log_err("FAILURE! %s\n", myErrorName(err));
}
if (strncmp(save, myptr, ii))
log_err("Saved substitution character failed\n");
else
log_verbose("Saved substitution character ok\n");
/*Testing for ucnv_getSubstChars() and ucnv_setSubstChars() with error conditions*/
log_verbose("\n---Testing ucnv_getSubstChars.. with len < minBytesPerChar\n");
ii=1;
ucnv_getSubstChars(myConverter, myptr, &ii, &err);
if(err != U_INDEX_OUTOFBOUNDS_ERROR){
log_err("ucnv_getSubstChars() with len < minBytesPerChar should throw U_INDEX_OUTOFBOUNDS_ERROR Got %s\n", myErrorName(err));
}
err=U_ZERO_ERROR;
ii=4;
ucnv_getSubstChars(myConverter, myptr, &ii, &err);
log_verbose("\n---Testing ucnv_setSubstChars.. with len < minBytesPerChar\n");
ucnv_setSubstChars(myConverter, myptr, 0, &err);
if(err != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ucnv_setSubstChars() with len < minBytesPerChar should throw U_ILLEGAL_ARGUMENT_ERROR Got %s\n", myErrorName(err));
}
log_verbose("\n---Testing ucnv_setSubstChars.. with err != U_ZERO_ERROR \n");
strcpy(myptr, "abc");
ucnv_setSubstChars(myConverter, myptr, ii, &err);
err=U_ZERO_ERROR;
ucnv_getSubstChars(myConverter, save, &ii, &err);
if(strncmp(save, myptr, ii) == 0){
log_err("uncv_setSubstChars() with err != U_ZERO_ERROR shouldn't set the SubstChars and just return\n");
}
log_verbose("\n---Testing ucnv_getSubstChars.. with err != U_ZERO_ERROR \n");
err=U_ZERO_ERROR;
strcpy(myptr, "abc");
ucnv_setSubstChars(myConverter, myptr, ii, &err);
err=U_ILLEGAL_ARGUMENT_ERROR;
ucnv_getSubstChars(myConverter, save, &ii, &err);
if(strncmp(save, myptr, ii) == 0){
log_err("uncv_setSubstChars() with err != U_ZERO_ERROR shouldn't fill the SubstChars in the buffer, it just returns\n");
}
err=U_ZERO_ERROR;
/*------*/
#ifdef U_ENABLE_GENERIC_ISO_2022
/*resetState ucnv_reset()*/
log_verbose("\n---Testing ucnv_reset()..\n");
ucnv_reset(myConverter);
{
UChar32 c;
const uint8_t in[]={ 0x1b, 0x25, 0x42, 0x31, 0x32, 0x61, 0xc0, 0x80, 0xe0, 0x80, 0x80, 0xf0, 0x80, 0x80, 0x80};
const char *source=(const char *)in, *limit=(const char *)in+sizeof(in);
UConverter *cnv=ucnv_open("ISO_2022", &err);
if(U_FAILURE(err)) {
log_err("Unable to open a iso-2022 converter: %s\n", u_errorName(err));
}
c=ucnv_getNextUChar(cnv, &source, limit, &err);
if((U_FAILURE(err) || c != (UChar32)0x0031)) {
log_err("ucnv_getNextUChar() failed: %s\n", u_errorName(err));
}
ucnv_reset(cnv);
ucnv_close(cnv);
}
#endif
/*getDisplayName*/
log_verbose("\n---Testing ucnv_getDisplayName()...\n");
locale=CodePagesLocale[codepage_index];
len=0;
displayname=NULL;
disnamelen = ucnv_getDisplayName(myConverter, locale, displayname, len, &err);
if(err==U_BUFFER_OVERFLOW_ERROR) {
err=U_ZERO_ERROR;
displayname=(UChar*)malloc((disnamelen+1) * sizeof(UChar));
ucnv_getDisplayName(myConverter,locale,displayname,disnamelen+1, &err);
if(U_FAILURE(err)) {
log_err("getDisplayName failed. The error is %s\n", myErrorName(err));
}
else {
log_verbose(" getDisplayName o.k.\n");
}
free(displayname);
displayname=NULL;
}
else {
log_err("getDisplayName preflight doesn't work. Error is %s\n", myErrorName(err));
}
/*test ucnv_getDiaplayName with error condition*/
err= U_ILLEGAL_ARGUMENT_ERROR;
len=ucnv_getDisplayName(myConverter,locale,NULL,0, &err);
if( len !=0 ){
log_err("ucnv_getDisplayName() with err != U_ZERO_ERROR is supposed to return 0\n");
}
/*test ucnv_getDiaplayName with error condition*/
err=U_ZERO_ERROR;
len=ucnv_getDisplayName(NULL,locale,NULL,0, &err);
if( len !=0 || U_SUCCESS(err)){
log_err("ucnv_getDisplayName(NULL) with cnv == NULL is supposed to return 0\n");
}
err=U_ZERO_ERROR;
/* testing ucnv_setFromUCallBack() and ucnv_getFromUCallBack()*/
ucnv_getFromUCallBack(myConverter, &MIA1, &MIA1Context);
log_verbose("\n---Testing ucnv_setFromUCallBack...\n");
ucnv_setFromUCallBack(myConverter, otherUnicodeAction(MIA1), &BOM, &oldFromUAction, &oldFromUContext, &err);
if (U_FAILURE(err) || oldFromUAction != MIA1 || oldFromUContext != MIA1Context)
{
log_err("FAILURE! %s\n", myErrorName(err));
}
ucnv_getFromUCallBack(myConverter, &MIA1_2, &MIA1Context2);
if (MIA1_2 != otherUnicodeAction(MIA1) || MIA1Context2 != &BOM)
log_err("get From UCallBack failed\n");
else
log_verbose("get From UCallBack ok\n");
log_verbose("\n---Testing getFromUCallBack Roundtrip...\n");
ucnv_setFromUCallBack(myConverter,MIA1, MIA1Context, &oldFromUAction, &oldFromUContext, &err);
if (U_FAILURE(err) || oldFromUAction != otherUnicodeAction(MIA1) || oldFromUContext != &BOM)
{
log_err("FAILURE! %s\n", myErrorName(err));
}
ucnv_getFromUCallBack(myConverter, &MIA1_2, &MIA1Context2);
if (MIA1_2 != MIA1 || MIA1Context2 != MIA1Context)
log_err("get From UCallBack action failed\n");
else
log_verbose("get From UCallBack action ok\n");
/*testing ucnv_setToUCallBack with error conditions*/
err=U_ILLEGAL_ARGUMENT_ERROR;
log_verbose("\n---Testing setFromUCallBack. with err != U_ZERO_ERROR..\n");
ucnv_setFromUCallBack(myConverter, otherUnicodeAction(MIA1), &BOM, &oldFromUAction, &oldFromUContext, &err);
ucnv_getFromUCallBack(myConverter, &MIA1_2, &MIA1Context2);
if(MIA1_2 == otherUnicodeAction(MIA1) || MIA1Context2 == &BOM){
log_err("To setFromUCallBack with err != U_ZERO_ERROR is supposed to fail\n");
}
err=U_ZERO_ERROR;
/*testing ucnv_setToUCallBack() and ucnv_getToUCallBack()*/
ucnv_getToUCallBack(myConverter, &MIA2, &MIA2Context);
log_verbose("\n---Testing setTo UCallBack...\n");
ucnv_setToUCallBack(myConverter,otherCharAction(MIA2), &BOM, &oldToUAction, &oldToUContext, &err);
if (U_FAILURE(err) || oldToUAction != MIA2 || oldToUContext != MIA2Context)
{
log_err("FAILURE! %s\n", myErrorName(err));
}
ucnv_getToUCallBack(myConverter, &MIA2_2, &MIA2Context2);
if (MIA2_2 != otherCharAction(MIA2) || MIA2Context2 != &BOM)
log_err("To UCallBack failed\n");
else
log_verbose("To UCallBack ok\n");
log_verbose("\n---Testing setTo UCallBack Roundtrip...\n");
ucnv_setToUCallBack(myConverter,MIA2, MIA2Context, &oldToUAction, &oldToUContext, &err);
if (U_FAILURE(err) || oldToUAction != otherCharAction(MIA2) || oldToUContext != &BOM)
{ log_err("FAILURE! %s\n", myErrorName(err)); }
ucnv_getToUCallBack(myConverter, &MIA2_2, &MIA2Context2);
if (MIA2_2 != MIA2 || MIA2Context2 != MIA2Context)
log_err("To UCallBack failed\n");
else
log_verbose("To UCallBack ok\n");
/*testing ucnv_setToUCallBack with error conditions*/
err=U_ILLEGAL_ARGUMENT_ERROR;
log_verbose("\n---Testing setToUCallBack. with err != U_ZERO_ERROR..\n");
ucnv_setToUCallBack(myConverter,otherCharAction(MIA2), NULL, &oldToUAction, &oldToUContext, &err);
ucnv_getToUCallBack(myConverter, &MIA2_2, &MIA2Context2);
if (MIA2_2 == otherCharAction(MIA2) || MIA2Context2 == &BOM){
log_err("To setToUCallBack with err != U_ZERO_ERROR is supposed to fail\n");
}
err=U_ZERO_ERROR;
/*getcodepageid testing ucnv_getCCSID() */
log_verbose("\n----Testing getCCSID....\n");
cp = ucnv_getCCSID(myConverter,&err);
if (U_FAILURE(err))
{
log_err("FAILURE!..... %s\n", myErrorName(err));
}
if (cp != CodePageNumberToTest[codepage_index])
log_err("Codepage number test failed\n");
else
log_verbose("Codepage number test OK\n");
/*testing ucnv_getCCSID() with err != U_ZERO_ERROR*/
err=U_ILLEGAL_ARGUMENT_ERROR;
if( ucnv_getCCSID(myConverter,&err) != -1){
log_err("ucnv_getCCSID() with err != U_ZERO_ERROR is supposed to fail\n");
}
err=U_ZERO_ERROR;
/*getCodepagePlatform testing ucnv_getPlatform()*/
log_verbose("\n---Testing getCodepagePlatform ..\n");
if (CodePagesPlatform[codepage_index]!=ucnv_getPlatform(myConverter, &err))
log_err("Platform codepage test failed\n");
else
log_verbose("Platform codepage test ok\n");
if (U_FAILURE(err))
{
log_err("FAILURE! %s\n", myErrorName(err));
}
/*testing ucnv_getPlatform() with err != U_ZERO_ERROR*/
err= U_ILLEGAL_ARGUMENT_ERROR;
if(ucnv_getPlatform(myConverter, &err) != UCNV_UNKNOWN){
log_err("ucnv)getPlatform with err != U_ZERO_ERROR is supposed to fail\n");
}
err=U_ZERO_ERROR;
/*Reads the BOM*/
{
// Note: gcc produces a compile warning if the return value from fread() is ignored.
size_t numRead = fread(&BOM, sizeof(UChar), 1, ucs_file_in);
(void)numRead;
}
if (BOM!=0xFEFF && BOM!=0xFFFE)
{
log_err("File Missing BOM...Bailing!\n");
fclose(ucs_file_in);
break;
}
/*Reads in the file*/
while(!feof(ucs_file_in)&&(i+=fread(ucs_file_buffer+i, sizeof(UChar), 1, ucs_file_in)))
{
myUChar = ucs_file_buffer[i-1];
ucs_file_buffer[i-1] = (UChar)((BOM==0xFEFF)?myUChar:((myUChar >> 8) | (myUChar << 8))); /*adjust if BIG_ENDIAN*/
}
myUChar = ucs_file_buffer[i-1];
ucs_file_buffer[i-1] = (UChar)((BOM==0xFEFF)?myUChar:((myUChar >> 8) | (myUChar << 8))); /*adjust if BIG_ENDIAN Corner Case*/
/*testing ucnv_fromUChars() and ucnv_toUChars() */
/*uchar1---fromUChar--->output_cp_buffer --toUChar--->uchar2*/
uchar1=(UChar*)malloc(sizeof(UChar) * (i+1));
u_uastrcpy(uchar1,"");
u_strncpy(uchar1,ucs_file_buffer,i);
uchar1[i] = 0;
uchar3=(UChar*)malloc(sizeof(UChar)*(i+1));
u_uastrcpy(uchar3,"");
u_strncpy(uchar3,ucs_file_buffer,i);
uchar3[i] = 0;
/*Calls the Conversion Routine */
testLong1 = MAX_FILE_LEN;
log_verbose("\n---Testing ucnv_fromUChars()\n");
targetcapacity = ucnv_fromUChars(myConverter, output_cp_buffer, testLong1, uchar1, -1, &err);
if (U_FAILURE(err))
{
log_err("\nFAILURE...%s\n", myErrorName(err));
}
else
log_verbose(" ucnv_fromUChars() o.k.\n");
/*test the conversion routine */
log_verbose("\n---Testing ucnv_toUChars()\n");
/*call it first time for trapping the targetcapacity and size needed to allocate memory for the buffer uchar2 */
targetcapacity2=0;
targetsize = ucnv_toUChars(myConverter,
NULL,
targetcapacity2,
output_cp_buffer,
strlen(output_cp_buffer),
&err);
/*if there is an buffer overflow then trap the values and pass them and make the actual call*/
if(err==U_BUFFER_OVERFLOW_ERROR)
{
err=U_ZERO_ERROR;
uchar2=(UChar*)malloc((targetsize+1) * sizeof(UChar));
targetsize = ucnv_toUChars(myConverter,
uchar2,
targetsize+1,
output_cp_buffer,
strlen(output_cp_buffer),
&err);
if(U_FAILURE(err))
log_err("ucnv_toUChars() FAILED %s\n", myErrorName(err));
else
log_verbose(" ucnv_toUChars() o.k.\n");
if(u_strcmp(uchar1,uchar2)!=0)
log_err("equality test failed with conversion routine\n");
}
else
{
log_err("ERR: calling toUChars: Didn't get U_BUFFER_OVERFLOW .. expected it.\n");
}
/*Testing ucnv_fromUChars and ucnv_toUChars with error conditions*/
err=U_ILLEGAL_ARGUMENT_ERROR;
log_verbose("\n---Testing ucnv_fromUChars() with err != U_ZERO_ERROR\n");
targetcapacity = ucnv_fromUChars(myConverter, output_cp_buffer, testLong1, uchar1, -1, &err);
if (targetcapacity !=0) {
log_err("\nFAILURE: ucnv_fromUChars with err != U_ZERO_ERROR is expected to fail and return 0\n");
}
err=U_ZERO_ERROR;
log_verbose("\n---Testing ucnv_fromUChars() with converter=NULL\n");
targetcapacity = ucnv_fromUChars(NULL, output_cp_buffer, testLong1, uchar1, -1, &err);
if (targetcapacity !=0 || err != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("\nFAILURE: ucnv_fromUChars with converter=NULL is expected to fail\n");
}
err=U_ZERO_ERROR;
log_verbose("\n---Testing ucnv_fromUChars() with sourceLength = 0\n");
targetcapacity = ucnv_fromUChars(myConverter, output_cp_buffer, testLong1, uchar1, 0, &err);
if (targetcapacity !=0) {
log_err("\nFAILURE: ucnv_fromUChars with sourceLength 0 is expected to return 0\n");
}
log_verbose("\n---Testing ucnv_fromUChars() with targetLength = 0\n");
targetcapacity = ucnv_fromUChars(myConverter, output_cp_buffer, 0, uchar1, -1, &err);
if (err != U_BUFFER_OVERFLOW_ERROR) {
log_err("\nFAILURE: ucnv_fromUChars with targetLength 0 is expected to fail and throw U_BUFFER_OVERFLOW_ERROR\n");
}
/*toUChars with error conditions*/
targetsize = ucnv_toUChars(myConverter, uchar2, targetsize, output_cp_buffer, strlen(output_cp_buffer), &err);
if(targetsize != 0){
log_err("\nFAILURE: ucnv_toUChars with err != U_ZERO_ERROR is expected to fail and return 0\n");
}
err=U_ZERO_ERROR;
targetsize = ucnv_toUChars(myConverter, uchar2, -1, output_cp_buffer, strlen(output_cp_buffer), &err);
if(targetsize != 0 || err != U_ILLEGAL_ARGUMENT_ERROR){
log_err("\nFAILURE: ucnv_toUChars with targetsize < 0 is expected to throw U_ILLEGAL_ARGUMENT_ERROR and return 0\n");
}
err=U_ZERO_ERROR;
targetsize = ucnv_toUChars(myConverter, uchar2, 0, output_cp_buffer, 0, &err);
if (targetsize !=0) {
log_err("\nFAILURE: ucnv_toUChars with sourceLength 0 is expected to return 0\n");
}
targetcapacity2=0;
targetsize = ucnv_toUChars(myConverter, NULL, targetcapacity2, output_cp_buffer, strlen(output_cp_buffer), &err);
if (err != U_STRING_NOT_TERMINATED_WARNING) {
log_err("\nFAILURE: ucnv_toUChars(targetLength)->%s instead of U_STRING_NOT_TERMINATED_WARNING\n",
u_errorName(err));
}
err=U_ZERO_ERROR;
/*-----*/
/*testing for ucnv_fromUnicode() and ucnv_toUnicode() */
/*Clean up re-usable vars*/
log_verbose("Testing ucnv_fromUnicode().....\n");
tmp_ucs_buf=ucs_file_buffer_use;
ucnv_fromUnicode(myConverter, &mytarget_1,
mytarget + MAX_FILE_LEN,
&tmp_ucs_buf,
ucs_file_buffer_use+i,
NULL,
TRUE,
&err);
consumedUni = (UChar*)tmp_consumedUni;
(void)consumedUni; /* Suppress set but not used warning. */
if (U_FAILURE(err))
{
log_err("FAILURE! %s\n", myErrorName(err));
}
else
log_verbose("ucnv_fromUnicode() o.k.\n");
/*Uni1 ----ToUnicode----> Cp2 ----FromUnicode---->Uni3 */
log_verbose("Testing ucnv_toUnicode().....\n");
tmp_mytarget_use=mytarget_use;
tmp_consumed = consumed;
ucnv_toUnicode(myConverter, &my_ucs_file_buffer_1,
my_ucs_file_buffer + MAX_FILE_LEN,
&tmp_mytarget_use,
mytarget_use + (mytarget_1 - mytarget),
NULL,
FALSE,
&err);
consumed = (char*)tmp_consumed;
if (U_FAILURE(err))
{
log_err("FAILURE! %s\n", myErrorName(err));
}
else
log_verbose("ucnv_toUnicode() o.k.\n");
log_verbose("\n---Testing RoundTrip ...\n");
u_strncpy(uchar3, my_ucs_file_buffer,i);
uchar3[i] = 0;
if(u_strcmp(uchar1,uchar3)==0)
log_verbose("Equality test o.k.\n");
else
log_err("Equality test failed\n");
/*sanity compare */
if(uchar2 == NULL)
{
log_err("uchar2 was NULL (ccapitst.c line %d), couldn't do sanity check\n", __LINE__);
}
else
{
if(u_strcmp(uchar2, uchar3)==0)
log_verbose("Equality test o.k.\n");
else
log_err("Equality test failed\n");
}
fclose(ucs_file_in);
ucnv_close(myConverter);
if (uchar1 != 0) free(uchar1);
if (uchar2 != 0) free(uchar2);
if (uchar3 != 0) free(uchar3);
}
free((void*)mytarget);
free((void*)output_cp_buffer);
free((void*)ucs_file_buffer);
free((void*)my_ucs_file_buffer);
#endif
}
#if !UCONFIG_NO_LEGACY_CONVERSION
static UConverterFromUCallback otherUnicodeAction(UConverterFromUCallback MIA)
{
return (MIA==(UConverterFromUCallback)UCNV_FROM_U_CALLBACK_STOP)?(UConverterFromUCallback)UCNV_FROM_U_CALLBACK_SUBSTITUTE:(UConverterFromUCallback)UCNV_FROM_U_CALLBACK_STOP;
}
static UConverterToUCallback otherCharAction(UConverterToUCallback MIA)
{
return (MIA==(UConverterToUCallback)UCNV_TO_U_CALLBACK_STOP)?(UConverterToUCallback)UCNV_TO_U_CALLBACK_SUBSTITUTE:(UConverterToUCallback)UCNV_TO_U_CALLBACK_STOP;
}
#endif
static void TestFlushCache(void) {
#if !UCONFIG_NO_LEGACY_CONVERSION
UErrorCode err = U_ZERO_ERROR;
UConverter* someConverters[5];
int flushCount = 0;
/* flush the converter cache to get a consistent state before the flushing is tested */
ucnv_flushCache();
/*Testing ucnv_open()*/
/* Note: These converters have been chosen because they do NOT
encode the Latin characters (U+0041, ...), and therefore are
highly unlikely to be chosen as system default codepages */
someConverters[0] = ucnv_open("ibm-1047", &err);
if (U_FAILURE(err)) {
log_data_err("FAILURE! %s\n", myErrorName(err));
}
someConverters[1] = ucnv_open("ibm-1047", &err);
if (U_FAILURE(err)) {
log_data_err("FAILURE! %s\n", myErrorName(err));
}
someConverters[2] = ucnv_open("ibm-1047", &err);
if (U_FAILURE(err)) {
log_data_err("FAILURE! %s\n", myErrorName(err));
}
someConverters[3] = ucnv_open("gb18030", &err);
if (U_FAILURE(err)) {
log_data_err("FAILURE! %s\n", myErrorName(err));
}
someConverters[4] = ucnv_open("ibm-954", &err);
if (U_FAILURE(err)) {
log_data_err("FAILURE! %s\n", myErrorName(err));
}
/* Testing ucnv_flushCache() */
log_verbose("\n---Testing ucnv_flushCache...\n");
if ((flushCount=ucnv_flushCache())==0)
log_verbose("Flush cache ok\n");
else
log_data_err("Flush Cache failed [line %d], expect 0 got %d \n", __LINE__, flushCount);
/*testing ucnv_close() and ucnv_flushCache() */
ucnv_close(someConverters[0]);
ucnv_close(someConverters[1]);
if ((flushCount=ucnv_flushCache())==0)
log_verbose("Flush cache ok\n");
else
log_data_err("Flush Cache failed [line %d], expect 0 got %d \n", __LINE__, flushCount);
ucnv_close(someConverters[2]);
ucnv_close(someConverters[3]);
if ((flushCount=ucnv_flushCache())==2)
log_verbose("Flush cache ok\n"); /*because first, second and third are same */
else
log_data_err("Flush Cache failed line %d, got %d expected 2 or there is an error in ucnv_close()\n",
__LINE__,
flushCount);
ucnv_close(someConverters[4]);
if ( (flushCount=ucnv_flushCache())==1)
log_verbose("Flush cache ok\n");
else
log_data_err("Flush Cache failed line %d, expected 1 got %d \n", __LINE__, flushCount);
#endif
}
/**
* Test the converter alias API, specifically the fuzzy matching of
* alias names and the alias table integrity. Make sure each
* converter has at least one alias (itself), and that its listed
* aliases map back to itself. Check some hard-coded UTF-8 and
* ISO_2022 aliases to make sure they work.
*/
static void TestAlias() {
int32_t i, ncnv;
UErrorCode status = U_ZERO_ERROR;
/* Predetermined aliases that we expect to map back to ISO_2022
* and UTF-8. UPDATE THIS DATA AS NECESSARY. */
const char* ISO_2022_NAMES[] =
{"ISO_2022,locale=ja,version=2", "ISO-2022-JP-2", "csISO2022JP2",
"Iso-2022jP2", "isO-2022_Jp_2", "iSo--2022,locale=ja,version=2"};
int32_t ISO_2022_NAMES_LENGTH = UPRV_LENGTHOF(ISO_2022_NAMES);
const char *UTF8_NAMES[] =
{ "UTF-8", "utf-8", "utf8", "ibm-1208",
"utf_8", "ibm1208", "cp1208" };
int32_t UTF8_NAMES_LENGTH = UPRV_LENGTHOF(UTF8_NAMES);
struct {
const char *name;
const char *alias;
} CONVERTERS_NAMES[] = {
{ "UTF-32BE", "UTF32_BigEndian" },
{ "UTF-32LE", "UTF32_LittleEndian" },
{ "UTF-32", "ISO-10646-UCS-4" },
{ "UTF32_PlatformEndian", "UTF32_PlatformEndian" },
{ "UTF-32", "ucs-4" }
};
int32_t CONVERTERS_NAMES_LENGTH = sizeof(CONVERTERS_NAMES) / sizeof(*CONVERTERS_NAMES);
/* When there are bugs in gencnval or in ucnv_io, converters can
appear to have no aliases. */
ncnv = ucnv_countAvailable();
log_verbose("%d converters\n", ncnv);
for (i=0; i<ncnv; ++i) {
const char *name = ucnv_getAvailableName(i);
const char *alias0;
uint16_t na = ucnv_countAliases(name, &status);
uint16_t j;
UConverter *cnv;
if (na == 0) {
log_err("FAIL: Converter \"%s\" (i=%d)"
" has no aliases; expect at least one\n",
name, i);
continue;
}
cnv = ucnv_open(name, &status);
if (U_FAILURE(status)) {
log_data_err("FAIL: Converter \"%s\" (i=%d)"
" can't be opened.\n",
name, i);
}
else {
if (strcmp(ucnv_getName(cnv, &status), name) != 0
&& (strstr(name, "PlatformEndian") == 0 && strstr(name, "OppositeEndian") == 0)) {
log_err("FAIL: Converter \"%s\" returned \"%s\" for getName. "
"They should be the same\n",
name, ucnv_getName(cnv, &status));
}
}
ucnv_close(cnv);
status = U_ZERO_ERROR;
alias0 = ucnv_getAlias(name, 0, &status);
for (j=1; j<na; ++j) {
const char *alias;
/* Make sure each alias maps back to the the same list of
aliases. Assume that if alias 0 is the same, the whole
list is the same (this should always be true). */
const char *mapBack;
status = U_ZERO_ERROR;
alias = ucnv_getAlias(name, j, &status);
if (status == U_AMBIGUOUS_ALIAS_WARNING) {
log_err("FAIL: Converter \"%s\"is ambiguous\n", name);
}
if (alias == NULL) {
log_err("FAIL: Converter \"%s\" -> "
"alias[%d]=NULL\n",
name, j);
continue;
}
mapBack = ucnv_getAlias(alias, 0, &status);
if (mapBack == NULL) {
log_err("FAIL: Converter \"%s\" -> "
"alias[%d]=\"%s\" -> "
"alias[0]=NULL, exp. \"%s\"\n",
name, j, alias, alias0);
continue;
}
if (0 != strcmp(alias0, mapBack)) {
int32_t idx;
UBool foundAlias = FALSE;
if (status == U_AMBIGUOUS_ALIAS_WARNING) {
/* Make sure that we only get this mismapping when there is
an ambiguous alias, and the other converter has this alias too. */
for (idx = 0; idx < ucnv_countAliases(mapBack, &status); idx++) {
if (strcmp(ucnv_getAlias(mapBack, (uint16_t)idx, &status), alias) == 0) {
foundAlias = TRUE;
break;
}
}
}
/* else not ambiguous, and this is a real problem. foundAlias = FALSE */
if (!foundAlias) {
log_err("FAIL: Converter \"%s\" -> "
"alias[%d]=\"%s\" -> "
"alias[0]=\"%s\", exp. \"%s\"\n",
name, j, alias, mapBack, alias0);
}
}
}
}
/* Check a list of predetermined aliases that we expect to map
* back to ISO_2022 and UTF-8. */
for (i=1; i<ISO_2022_NAMES_LENGTH; ++i) {
const char* mapBack = ucnv_getAlias(ISO_2022_NAMES[i], 0, &status);
if(!mapBack) {
log_data_err("Couldn't get alias for %s. You probably have no data\n", ISO_2022_NAMES[i]);
continue;
}
if (0 != strcmp(mapBack, ISO_2022_NAMES[0])) {
log_err("FAIL: \"%s\" -> \"%s\", expect \"ISO_2022,locale=ja,version=2\"\n",
ISO_2022_NAMES[i], mapBack);
}
}
for (i=1; i<UTF8_NAMES_LENGTH; ++i) {
const char* mapBack = ucnv_getAlias(UTF8_NAMES[i], 0, &status);
if(!mapBack) {
log_data_err("Couldn't get alias for %s. You probably have no data\n", UTF8_NAMES[i]);
continue;
}
if (mapBack && 0 != strcmp(mapBack, UTF8_NAMES[0])) {
log_err("FAIL: \"%s\" -> \"%s\", expect UTF-8\n",
UTF8_NAMES[i], mapBack);
}
}
/*
* Check a list of predetermined aliases that we expect to map
* back to predermined converter names.
*/
for (i = 0; i < CONVERTERS_NAMES_LENGTH; ++i) {
const char* mapBack = ucnv_getAlias(CONVERTERS_NAMES[i].alias, 0, &status);
if(!mapBack) {
log_data_err("Couldn't get alias for %s. You probably have no data\n", CONVERTERS_NAMES[i].name);
continue;
}
if (0 != strcmp(mapBack, CONVERTERS_NAMES[i].name)) {
log_err("FAIL: \"%s\" -> \"%s\", expect %s\n",
CONVERTERS_NAMES[i].alias, mapBack, CONVERTERS_NAMES[i].name);
}
}
}
static void TestDuplicateAlias(void) {
const char *alias;
UErrorCode status = U_ZERO_ERROR;
status = U_ZERO_ERROR;
alias = ucnv_getStandardName("Shift_JIS", "IBM", &status);
if (alias == NULL || strcmp(alias, "ibm-943") != 0 || status != U_AMBIGUOUS_ALIAS_WARNING) {
log_data_err("FAIL: Didn't get ibm-943 for Shift_JIS {IBM}. Got %s\n", alias);
}
status = U_ZERO_ERROR;
alias = ucnv_getStandardName("ibm-943", "IANA", &status);
if (alias == NULL || strcmp(alias, "Shift_JIS") != 0 || status != U_AMBIGUOUS_ALIAS_WARNING) {
log_data_err("FAIL: Didn't get Shift_JIS for ibm-943 {IANA}. Got %s\n", alias);
}
status = U_ZERO_ERROR;
alias = ucnv_getStandardName("ibm-943_P130-2000", "IANA", &status);
if (alias != NULL || status == U_AMBIGUOUS_ALIAS_WARNING) {
log_data_err("FAIL: Didn't get NULL for ibm-943 {IANA}. Got %s\n", alias);
}
}
/* Test safe clone callback */
static uint32_t TSCC_nextSerial()
{
static uint32_t n = 1;
return (n++);
}
typedef struct
{
uint32_t magic; /* 0xC0FFEE to identify that the object is OK */
uint32_t serial; /* minted from nextSerial, above */
UBool wasClosed; /* close happened on the object */
} TSCCContext;
static TSCCContext *TSCC_clone(TSCCContext *ctx)
{
TSCCContext *newCtx = (TSCCContext *)malloc(sizeof(TSCCContext));
newCtx->serial = TSCC_nextSerial();
newCtx->wasClosed = 0;
newCtx->magic = 0xC0FFEE;
log_verbose("TSCC_clone: %p:%d -> new context %p:%d\n", ctx, ctx->serial, newCtx, newCtx->serial);
return newCtx;
}
#if !UCONFIG_NO_LEGACY_CONVERSION
static void TSCC_fromU(const void *context,
UConverterFromUnicodeArgs *fromUArgs,
const UChar* codeUnits,
int32_t length,
UChar32 codePoint,
UConverterCallbackReason reason,
UErrorCode * err)
{
TSCCContext *ctx = (TSCCContext*)context;
UConverterFromUCallback junkFrom;
log_verbose("TSCC_fromU: Context %p:%d called, reason %d on cnv %p\n", ctx, ctx->serial, reason, fromUArgs->converter);
if(ctx->magic != 0xC0FFEE) {
log_err("TSCC_fromU: Context %p:%d magic is 0x%x should be 0xC0FFEE.\n", ctx,ctx->serial, ctx->magic);
return;
}
if(reason == UCNV_CLONE) {
UErrorCode subErr = U_ZERO_ERROR;
TSCCContext *newCtx;
TSCCContext *junkCtx;
TSCCContext **pjunkCtx = &junkCtx;
/* "recreate" it */
log_verbose("TSCC_fromU: cloning..\n");
newCtx = TSCC_clone(ctx);
if(newCtx == NULL) {
log_err("TSCC_fromU: internal clone failed on %p\n", ctx);
}
/* now, SET it */
ucnv_getFromUCallBack(fromUArgs->converter, &junkFrom, (const void**)pjunkCtx);
ucnv_setFromUCallBack(fromUArgs->converter, junkFrom, newCtx, NULL, NULL, &subErr);
if(U_FAILURE(subErr)) {
*err = subErr;
}
}
if(reason == UCNV_CLOSE) {
log_verbose("TSCC_fromU: Context %p:%d closing\n", ctx, ctx->serial);
ctx->wasClosed = TRUE;
}
}
static void TSCC_toU(const void *context,
UConverterToUnicodeArgs *toUArgs,
const char* codeUnits,
int32_t length,
UConverterCallbackReason reason,
UErrorCode * err)
{
TSCCContext *ctx = (TSCCContext*)context;
UConverterToUCallback junkFrom;
log_verbose("TSCC_toU: Context %p:%d called, reason %d on cnv %p\n", ctx, ctx->serial, reason, toUArgs->converter);
if(ctx->magic != 0xC0FFEE) {
log_err("TSCC_toU: Context %p:%d magic is 0x%x should be 0xC0FFEE.\n", ctx,ctx->serial, ctx->magic);
return;
}
if(reason == UCNV_CLONE) {
UErrorCode subErr = U_ZERO_ERROR;
TSCCContext *newCtx;
TSCCContext *junkCtx;
TSCCContext **pjunkCtx = &junkCtx;
/* "recreate" it */
log_verbose("TSCC_toU: cloning..\n");
newCtx = TSCC_clone(ctx);
if(newCtx == NULL) {
log_err("TSCC_toU: internal clone failed on %p\n", ctx);
}
/* now, SET it */
ucnv_getToUCallBack(toUArgs->converter, &junkFrom, (const void**)pjunkCtx);
ucnv_setToUCallBack(toUArgs->converter, junkFrom, newCtx, NULL, NULL, &subErr);
if(U_FAILURE(subErr)) {
*err = subErr;
}
}
if(reason == UCNV_CLOSE) {
log_verbose("TSCC_toU: Context %p:%d closing\n", ctx, ctx->serial);
ctx->wasClosed = TRUE;
}
}
static void TSCC_init(TSCCContext *q)
{
q->magic = 0xC0FFEE;
q->serial = TSCC_nextSerial();
q->wasClosed = 0;
}
static void TSCC_print_log(TSCCContext *q, const char *name)
{
if(q==NULL) {
log_verbose("TSCContext: %s is NULL!!\n", name);
} else {
if(q->magic != 0xC0FFEE) {
log_err("TSCCContext: %p:%d's magic is %x, supposed to be 0xC0FFEE\n",
q,q->serial, q->magic);
}
log_verbose("TSCCContext %p:%d=%s - magic %x, %s\n",
q, q->serial, name, q->magic, q->wasClosed?"CLOSED":"open");
}
}
static void TestConvertSafeCloneCallback()
{
UErrorCode err = U_ZERO_ERROR;
TSCCContext from1, to1;
TSCCContext *from2, *from3, *to2, *to3;
TSCCContext **pfrom2 = &from2, **pfrom3 = &from3, **pto2 = &to2, **pto3 = &to3;
char hunk[8192];
int32_t hunkSize = 8192;
UConverterFromUCallback junkFrom;
UConverterToUCallback junkTo;
UConverter *conv1, *conv2 = NULL;
conv1 = ucnv_open("iso-8859-3", &err);
if(U_FAILURE(err)) {
log_data_err("Err opening iso-8859-3, %s\n", u_errorName(err));
return;
}
log_verbose("Opened conv1=%p\n", conv1);
TSCC_init(&from1);
TSCC_init(&to1);
TSCC_print_log(&from1, "from1");
TSCC_print_log(&to1, "to1");
ucnv_setFromUCallBack(conv1, TSCC_fromU, &from1, NULL, NULL, &err);
log_verbose("Set from1 on conv1\n");
TSCC_print_log(&from1, "from1");
ucnv_setToUCallBack(conv1, TSCC_toU, &to1, NULL, NULL, &err);
log_verbose("Set to1 on conv1\n");
TSCC_print_log(&to1, "to1");
conv2 = ucnv_safeClone(conv1, hunk, &hunkSize, &err);
if(U_FAILURE(err)) {
log_err("safeClone failed: %s\n", u_errorName(err));
return;
}
log_verbose("Cloned to conv2=%p.\n", conv2);
/********** from *********************/
ucnv_getFromUCallBack(conv2, &junkFrom, (const void**)pfrom2);
ucnv_getFromUCallBack(conv1, &junkFrom, (const void**)pfrom3);
TSCC_print_log(from2, "from2");
TSCC_print_log(from3, "from3(==from1)");
if(from2 == NULL) {
log_err("FAIL! from2 is null \n");
return;
}
if(from3 == NULL) {
log_err("FAIL! from3 is null \n");
return;
}
if(from3 != (&from1) ) {
log_err("FAIL! conv1's FROM context changed!\n");
}
if(from2 == (&from1) ) {
log_err("FAIL! conv1's FROM context is the same as conv2's!\n");
}
if(from1.wasClosed) {
log_err("FAIL! from1 is closed \n");
}
if(from2->wasClosed) {
log_err("FAIL! from2 was closed\n");
}
/********** to *********************/
ucnv_getToUCallBack(conv2, &junkTo, (const void**)pto2);
ucnv_getToUCallBack(conv1, &junkTo, (const void**)pto3);
TSCC_print_log(to2, "to2");
TSCC_print_log(to3, "to3(==to1)");
if(to2 == NULL) {
log_err("FAIL! to2 is null \n");
return;
}
if(to3 == NULL) {
log_err("FAIL! to3 is null \n");
return;
}
if(to3 != (&to1) ) {
log_err("FAIL! conv1's TO context changed!\n");
}
if(to2 == (&to1) ) {
log_err("FAIL! conv1's TO context is the same as conv2's!\n");
}
if(to1.wasClosed) {
log_err("FAIL! to1 is closed \n");
}
if(to2->wasClosed) {
log_err("FAIL! to2 was closed\n");
}
/*************************************/
ucnv_close(conv1);
log_verbose("ucnv_closed (conv1)\n");
TSCC_print_log(&from1, "from1");
TSCC_print_log(from2, "from2");
TSCC_print_log(&to1, "to1");
TSCC_print_log(to2, "to2");
if(from1.wasClosed == FALSE) {
log_err("FAIL! from1 is NOT closed \n");
}
if(from2->wasClosed) {
log_err("FAIL! from2 was closed\n");
}
if(to1.wasClosed == FALSE) {
log_err("FAIL! to1 is NOT closed \n");
}
if(to2->wasClosed) {
log_err("FAIL! to2 was closed\n");
}
ucnv_close(conv2);
log_verbose("ucnv_closed (conv2)\n");
TSCC_print_log(&from1, "from1");
TSCC_print_log(from2, "from2");
if(from1.wasClosed == FALSE) {
log_err("FAIL! from1 is NOT closed \n");
}
if(from2->wasClosed == FALSE) {
log_err("FAIL! from2 was NOT closed\n");
}
TSCC_print_log(&to1, "to1");
TSCC_print_log(to2, "to2");
if(to1.wasClosed == FALSE) {
log_err("FAIL! to1 is NOT closed \n");
}
if(to2->wasClosed == FALSE) {
log_err("FAIL! to2 was NOT closed\n");
}
if(to2 != (&to1)) {
free(to2); /* to1 is stack based */
}
if(from2 != (&from1)) {
free(from2); /* from1 is stack based */
}
}
#endif
static UBool
containsAnyOtherByte(uint8_t *p, int32_t length, uint8_t b) {
while(length>0) {
if(*p!=b) {
return TRUE;
}
++p;
--length;
}
return FALSE;
}
static void TestConvertSafeClone()
{
/* one 'regular' & all the 'private stateful' converters */
static const char *const names[] = {
#if !UCONFIG_NO_LEGACY_CONVERSION
"ibm-1047",
"ISO_2022,locale=zh,version=1",
#endif
"SCSU",
#if !UCONFIG_NO_LEGACY_CONVERSION
"HZ",
"lmbcs",
"ISCII,version=0",
"ISO_2022,locale=kr,version=1",
"ISO_2022,locale=jp,version=2",
#endif
"BOCU-1",
"UTF-7",
#if !UCONFIG_NO_LEGACY_CONVERSION
"IMAP-mailbox-name",
"ibm-1047-s390"
#else
"IMAP=mailbox-name"
#endif
};
/* store the actual sizes of each converter */
int32_t actualSizes[UPRV_LENGTHOF(names)];
static const int32_t bufferSizes[] = {
U_CNV_SAFECLONE_BUFFERSIZE,
(int32_t)(3*sizeof(UConverter))/2, /* 1.5*sizeof(UConverter) */
(int32_t)sizeof(UConverter)/2 /* 0.5*sizeof(UConverter) */
};
char charBuffer[21]; /* Leave at an odd number for alignment testing */
uint8_t buffer[3] [U_CNV_SAFECLONE_BUFFERSIZE];
int32_t bufferSize, maxBufferSize;
const char *maxName;
UConverter * cnv, *cnv2;
UErrorCode err;
char *pCharBuffer;
const char *pConstCharBuffer;
const char *charBufferLimit = charBuffer + sizeof(charBuffer)/sizeof(*charBuffer);
UChar uniBuffer[] = {0x0058, 0x0059, 0x005A}; /* "XYZ" */
UChar uniCharBuffer[20];
char charSourceBuffer[] = { 0x1b, 0x24, 0x42 };
const char *pCharSource = charSourceBuffer;
const char *pCharSourceLimit = charSourceBuffer + sizeof(charSourceBuffer);
UChar *pUCharTarget = uniCharBuffer;
UChar *pUCharTargetLimit = uniCharBuffer + sizeof(uniCharBuffer)/sizeof(*uniCharBuffer);
const UChar * pUniBuffer;
const UChar *uniBufferLimit = uniBuffer + sizeof(uniBuffer)/sizeof(*uniBuffer);
int32_t idx, j;
err = U_ZERO_ERROR;
cnv = ucnv_open(names[0], &err);
if(U_SUCCESS(err)) {
/* Check the various error & informational states: */
/* Null status - just returns NULL */
bufferSize = U_CNV_SAFECLONE_BUFFERSIZE;
if (NULL != ucnv_safeClone(cnv, buffer[0], &bufferSize, NULL))
{
log_err("FAIL: Cloned converter failed to deal correctly with null status\n");
}
/* error status - should return 0 & keep error the same */
err = U_MEMORY_ALLOCATION_ERROR;
if (NULL != ucnv_safeClone(cnv, buffer[0], &bufferSize, &err) || err != U_MEMORY_ALLOCATION_ERROR)
{
log_err("FAIL: Cloned converter failed to deal correctly with incoming error status\n");
}
err = U_ZERO_ERROR;
/* Null buffer size pointer is ok */
if (NULL == (cnv2 = ucnv_safeClone(cnv, buffer[0], NULL, &err)) || U_FAILURE(err))
{
log_err("FAIL: Cloned converter failed to deal correctly with null bufferSize pointer\n");
}
ucnv_close(cnv2);
err = U_ZERO_ERROR;
/* buffer size pointer is 0 - fill in pbufferSize with a size */
bufferSize = 0;
if (NULL != ucnv_safeClone(cnv, buffer[0], &bufferSize, &err) || U_FAILURE(err) || bufferSize <= 0)
{
log_err("FAIL: Cloned converter failed a sizing request ('preflighting')\n");
}
/* Verify our define is large enough */
if (U_CNV_SAFECLONE_BUFFERSIZE < bufferSize)
{
log_err("FAIL: Pre-calculated buffer size is too small\n");
}
/* Verify we can use this run-time calculated size */
if (NULL == (cnv2 = ucnv_safeClone(cnv, buffer[0], &bufferSize, &err)) || U_FAILURE(err))
{
log_err("FAIL: Converter can't be cloned with run-time size\n");
}
if (cnv2) {
ucnv_close(cnv2);
}
/* size one byte too small - should allocate & let us know */
--bufferSize;
if (NULL == (cnv2 = ucnv_safeClone(cnv, NULL, &bufferSize, &err)) || err != U_SAFECLONE_ALLOCATED_WARNING)
{
log_err("FAIL: Cloned converter failed to deal correctly with too-small buffer size\n");
}
if (cnv2) {
ucnv_close(cnv2);
}
err = U_ZERO_ERROR;
bufferSize = U_CNV_SAFECLONE_BUFFERSIZE;
/* Null buffer pointer - return converter & set error to U_SAFECLONE_ALLOCATED_ERROR */
if (NULL == (cnv2 = ucnv_safeClone(cnv, NULL, &bufferSize, &err)) || err != U_SAFECLONE_ALLOCATED_WARNING)
{
log_err("FAIL: Cloned converter failed to deal correctly with null buffer pointer\n");
}
if (cnv2) {
ucnv_close(cnv2);
}
err = U_ZERO_ERROR;
/* Null converter - return NULL & set U_ILLEGAL_ARGUMENT_ERROR */
if (NULL != ucnv_safeClone(NULL, buffer[0], &bufferSize, &err) || err != U_ILLEGAL_ARGUMENT_ERROR)
{
log_err("FAIL: Cloned converter failed to deal correctly with null converter pointer\n");
}
ucnv_close(cnv);
}
maxBufferSize = 0;
maxName = "";
/* Do these cloned converters work at all - shuffle UChars to chars & back again..*/
for(j = 0; j < UPRV_LENGTHOF(bufferSizes); ++j) {
for (idx = 0; idx < UPRV_LENGTHOF(names); idx++)
{
err = U_ZERO_ERROR;
cnv = ucnv_open(names[idx], &err);
if(U_FAILURE(err)) {
log_data_err("ucnv_open(\"%s\") failed - %s\n", names[idx], u_errorName(err));
continue;
}
if(j == 0) {
/* preflight to get maxBufferSize */
actualSizes[idx] = 0;
ucnv_safeClone(cnv, NULL, &actualSizes[idx], &err);
if(actualSizes[idx] > maxBufferSize) {
maxBufferSize = actualSizes[idx];
maxName = names[idx];
}
}
memset(buffer, 0xaa, sizeof(buffer));
bufferSize = bufferSizes[j];
cnv2 = ucnv_safeClone(cnv, buffer[1], &bufferSize, &err);
/* close the original immediately to make sure that the clone works by itself */
ucnv_close(cnv);
if( actualSizes[idx] <= (bufferSizes[j] - (int32_t)sizeof(UAlignedMemory)) &&
err == U_SAFECLONE_ALLOCATED_WARNING
) {
log_err("ucnv_safeClone(%s) did a heap clone although the buffer was large enough\n", names[idx]);
}
/* check if the clone function overwrote any bytes that it is not supposed to touch */
if(bufferSize <= bufferSizes[j]) {
/* used the stack buffer */
if( containsAnyOtherByte(buffer[0], (int32_t)sizeof(buffer[0]), 0xaa) ||
containsAnyOtherByte(buffer[1]+bufferSize, (int32_t)(sizeof(buffer)-(sizeof(buffer[0])+bufferSize)), 0xaa)
) {
log_err("cloning %s in a stack buffer overwrote bytes outside the bufferSize %d (requested %d)\n",
names[idx], bufferSize, bufferSizes[j]);
}
} else {
/* heap-allocated the clone */
if(containsAnyOtherByte(buffer[0], (int32_t)sizeof(buffer), 0xaa)) {
log_err("cloning %s used the heap (bufferSize %d, requested %d) but overwrote stack buffer bytes\n",
names[idx], bufferSize, bufferSizes[j]);
}
}
pCharBuffer = charBuffer;
pUniBuffer = uniBuffer;
ucnv_fromUnicode(cnv2,
&pCharBuffer,
charBufferLimit,
&pUniBuffer,
uniBufferLimit,
NULL,
TRUE,
&err);
if(U_FAILURE(err)){
log_err("FAIL: cloned converter failed to do fromU conversion. Error: %s\n",u_errorName(err));
}
ucnv_toUnicode(cnv2,
&pUCharTarget,
pUCharTargetLimit,
&pCharSource,
pCharSourceLimit,
NULL,
TRUE,
&err
);
if(U_FAILURE(err)){
log_err("FAIL: cloned converter failed to do toU conversion. Error: %s\n",u_errorName(err));
}
pConstCharBuffer = charBuffer;
if (uniBuffer [0] != ucnv_getNextUChar(cnv2, &pConstCharBuffer, pCharBuffer, &err))
{
log_err("FAIL: Cloned converter failed to do conversion. Error: %s\n",u_errorName(err));
}
ucnv_close(cnv2);
}
}
log_verbose("ucnv_safeClone(): sizeof(UConverter)=%lu max preflighted clone size=%d (%s) U_CNV_SAFECLONE_BUFFERSIZE=%d\n",
sizeof(UConverter), maxBufferSize, maxName, (int)U_CNV_SAFECLONE_BUFFERSIZE);
if(maxBufferSize > U_CNV_SAFECLONE_BUFFERSIZE) {
log_err("ucnv_safeClone(): max preflighted clone size=%d (%s) is larger than U_CNV_SAFECLONE_BUFFERSIZE=%d\n",
maxBufferSize, maxName, (int)U_CNV_SAFECLONE_BUFFERSIZE);
}
}
static void TestCCSID() {
#if !UCONFIG_NO_LEGACY_CONVERSION
UConverter *cnv;
UErrorCode errorCode;
int32_t ccsids[]={ 37, 850, 943, 949, 950, 1047, 1252, 1392, 33722 };
int32_t i, ccsid;
for(i=0; i<(int32_t)(sizeof(ccsids)/sizeof(int32_t)); ++i) {
ccsid=ccsids[i];
errorCode=U_ZERO_ERROR;
cnv=ucnv_openCCSID(ccsid, UCNV_IBM, &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("error: ucnv_openCCSID(%ld) failed (%s)\n", ccsid, u_errorName(errorCode));
continue;
}
if(ccsid!=ucnv_getCCSID(cnv, &errorCode)) {
log_err("error: ucnv_getCCSID(ucnv_openCCSID(%ld))=%ld\n", ccsid, ucnv_getCCSID(cnv, &errorCode));
}
/* skip gb18030(ccsid 1392) */
if(ccsid != 1392 && UCNV_IBM!=ucnv_getPlatform(cnv, &errorCode)) {
log_err("error: ucnv_getPlatform(ucnv_openCCSID(%ld))=%ld!=UCNV_IBM\n", ccsid, ucnv_getPlatform(cnv, &errorCode));
}
ucnv_close(cnv);
}
#endif
}
/* jitterbug 932: ucnv_convert() bugs --------------------------------------- */
/* CHUNK_SIZE defined in common\ucnv.c: */
#define CHUNK_SIZE 1024
static void bug1(void);
static void bug2(void);
static void bug3(void);
static void
TestJ932(void)
{
bug1(); /* Unicode intermediate buffer straddle bug */
bug2(); /* pre-flighting size incorrect caused by simple overflow */
bug3(); /* pre-flighting size incorrect caused by expansion overflow */
}
/*
* jitterbug 932: test chunking boundary conditions in
int32_t ucnv_convert(const char *toConverterName,
const char *fromConverterName,
char *target,
int32_t targetSize,
const char *source,
int32_t sourceSize,
UErrorCode * err)
* See discussions on the icu mailing list in
* 2001-April with the subject "converter 'flush' question".
*
* Bug report and test code provided by Edward J. Batutis.
*/
static void bug1()
{
#if !UCONFIG_NO_LEGACY_CONVERSION
char char_in[CHUNK_SIZE+32];
char char_out[CHUNK_SIZE*2];
/* GB 18030 equivalent of U+10000 is 90308130 */
static const char test_seq[]={ (char)0x90u, 0x30, (char)0x81u, 0x30 };
UErrorCode err = U_ZERO_ERROR;
int32_t i, test_seq_len = sizeof(test_seq);
/*
* causes straddle bug in Unicode intermediate buffer by sliding the test sequence forward
* until the straddle bug appears. I didn't want to hard-code everything so this test could
* be expanded - however this is the only type of straddle bug I can think of at the moment -
* a high surrogate in the last position of the Unicode intermediate buffer. Apparently no
* other Unicode sequences cause a bug since combining sequences are not supported by the
* converters.
*/
for (i = test_seq_len; i >= 0; i--) {
/* put character sequence into input buffer */
memset(char_in, 0x61, sizeof(char_in)); /* GB 18030 'a' */
memcpy(char_in + (CHUNK_SIZE - i), test_seq, test_seq_len);
/* do the conversion */
ucnv_convert("us-ascii", /* out */
"gb18030", /* in */
char_out,
sizeof(char_out),
char_in,
sizeof(char_in),
&err);
/* bug1: */
if (err == U_TRUNCATED_CHAR_FOUND) {
/* this happens when surrogate pair straddles the intermediate buffer in
* T_UConverter_fromCodepageToCodepage */
log_err("error j932 bug 1: expected success, got U_TRUNCATED_CHAR_FOUND\n");
}
}
#endif
}
/* bug2: pre-flighting loop bug: simple overflow causes bug */
static void bug2()
{
/* US-ASCII "1234567890" */
static const char source[]={ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 };
#if !UCONFIG_ONLY_HTML_CONVERSION
static const char sourceUTF8[]={ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, (char)0xef, (char)0x80, (char)0x80 };
static const char sourceUTF32[]={ 0x00, 0x00, 0x00, 0x30,
0x00, 0x00, 0x00, 0x31,
0x00, 0x00, 0x00, 0x32,
0x00, 0x00, 0x00, 0x33,
0x00, 0x00, 0x00, 0x34,
0x00, 0x00, 0x00, 0x35,
0x00, 0x00, 0x00, 0x36,
0x00, 0x00, 0x00, 0x37,
0x00, 0x00, 0x00, 0x38,
0x00, 0x00, (char)0xf0, 0x00};
#endif
static char target[5];
UErrorCode err = U_ZERO_ERROR;
int32_t size;
/* do the conversion */
size = ucnv_convert("iso-8859-1", /* out */
"us-ascii", /* in */
target,
sizeof(target),
source,
sizeof(source),
&err);
if ( size != 10 ) {
/* bug2: size is 5, should be 10 */
log_data_err("error j932 bug 2 us-ascii->iso-8859-1: got preflighting size %d instead of 10\n", size);
}
#if !UCONFIG_ONLY_HTML_CONVERSION
err = U_ZERO_ERROR;
/* do the conversion */
size = ucnv_convert("UTF-32BE", /* out */
"UTF-8", /* in */
target,
sizeof(target),
sourceUTF8,
sizeof(sourceUTF8),
&err);
if ( size != 32 ) {
/* bug2: size is 5, should be 32 */
log_err("error j932 bug 2 UTF-8->UTF-32BE: got preflighting size %d instead of 32\n", size);
}
err = U_ZERO_ERROR;
/* do the conversion */
size = ucnv_convert("UTF-8", /* out */
"UTF-32BE", /* in */
target,
sizeof(target),
sourceUTF32,
sizeof(sourceUTF32),
&err);
if ( size != 12 ) {
/* bug2: size is 5, should be 12 */
log_err("error j932 bug 2 UTF-32BE->UTF-8: got preflighting size %d instead of 12\n", size);
}
#endif
}
/*
* bug3: when the characters expand going from source to target codepage
* you get bug3 in addition to bug2
*/
static void bug3()
{
#if !UCONFIG_NO_LEGACY_CONVERSION && !UCONFIG_ONLY_HTML_CONVERSION
char char_in[CHUNK_SIZE*4];
char target[5];
UErrorCode err = U_ZERO_ERROR;
int32_t size;
/*
* first get the buggy size from bug2 then
* compare it to buggy size with an expansion
*/
memset(char_in, 0x61, sizeof(char_in)); /* US-ASCII 'a' */
/* do the conversion */
size = ucnv_convert("lmbcs", /* out */
"us-ascii", /* in */
target,
sizeof(target),
char_in,
sizeof(char_in),
&err);
if ( size != sizeof(char_in) ) {
/*
* bug2: size is 0x2805 (CHUNK_SIZE*2+5 - maybe 5 is the size of the overflow buffer
* in the converter?), should be CHUNK_SIZE*4
*
* Markus 2001-05-18: 5 is the size of our target[] here, ucnv_convert() did not reset targetSize...
*/
log_data_err("error j932 bug 2/3a: expected preflighting size 0x%04x, got 0x%04x\n", sizeof(char_in), size);
}
/*
* now do the conversion with expansion
* ascii 0x08 expands to 0x0F 0x28 in lmbcs
*/
memset(char_in, 8, sizeof(char_in));
err = U_ZERO_ERROR;
/* do the conversion */
size = ucnv_convert("lmbcs", /* out */
"us-ascii", /* in */
target,
sizeof(target),
char_in,
sizeof(char_in),
&err);
/* expect 2X expansion */
if ( size != sizeof(char_in) * 2 ) {
/*
* bug3:
* bug2 would lead us to expect 0x2805, but it isn't that either, it is 0x3c05:
*/
log_data_err("error j932 bug 3b: expected 0x%04x, got 0x%04x\n", sizeof(char_in) * 2, size);
}
#endif
}
static void
convertExStreaming(UConverter *srcCnv, UConverter *targetCnv,
const char *src, int32_t srcLength,
const char *expectTarget, int32_t expectTargetLength,
int32_t chunkSize,
const char *testName,
UErrorCode expectCode) {
UChar pivotBuffer[CHUNK_SIZE];
UChar *pivotSource, *pivotTarget;
const UChar *pivotLimit;
char targetBuffer[CHUNK_SIZE];
char *target;
const char *srcLimit, *finalSrcLimit, *targetLimit;
int32_t targetLength;
UBool flush;
UErrorCode errorCode;
/* setup */
if(chunkSize>CHUNK_SIZE) {
chunkSize=CHUNK_SIZE;
}
pivotSource=pivotTarget=pivotBuffer;
pivotLimit=pivotBuffer+chunkSize;
finalSrcLimit=src+srcLength;
target=targetBuffer;
targetLimit=targetBuffer+chunkSize;
ucnv_resetToUnicode(srcCnv);
ucnv_resetFromUnicode(targetCnv);
errorCode=U_ZERO_ERROR;
flush=FALSE;
/* convert, streaming-style (both converters and pivot keep state) */
for(;;) {
/* for testing, give ucnv_convertEx() at most <chunkSize> input/pivot/output units at a time */
if(src+chunkSize<=finalSrcLimit) {
srcLimit=src+chunkSize;
} else {
srcLimit=finalSrcLimit;
}
ucnv_convertEx(targetCnv, srcCnv,
&target, targetLimit,
&src, srcLimit,
pivotBuffer, &pivotSource, &pivotTarget, pivotLimit,
FALSE, flush, &errorCode);
targetLength=(int32_t)(target-targetBuffer);
if(target>targetLimit) {
log_err("ucnv_convertEx(%s) chunk[%d] target %p exceeds targetLimit %p\n",
testName, chunkSize, target, targetLimit);
break; /* TODO: major problem! */
}
if(errorCode==U_BUFFER_OVERFLOW_ERROR) {
/* continue converting another chunk */
errorCode=U_ZERO_ERROR;
if(targetLength+chunkSize<=sizeof(targetBuffer)) {
targetLimit=target+chunkSize;
} else {
targetLimit=targetBuffer+sizeof(targetBuffer);
}
} else if(U_FAILURE(errorCode)) {
/* failure */
break;
} else if(flush) {
/* all done */
break;
} else if(src==finalSrcLimit && pivotSource==pivotTarget) {
/* all consumed, now flush without input (separate from conversion for testing) */
flush=TRUE;
}
}
if(!(errorCode==expectCode || (expectCode==U_ZERO_ERROR && errorCode==U_STRING_NOT_TERMINATED_WARNING))) {
log_err("ucnv_convertEx(%s) chunk[%d] results in %s instead of %s\n",
testName, chunkSize, u_errorName(errorCode), u_errorName(expectCode));
} else if(targetLength!=expectTargetLength) {
log_err("ucnv_convertEx(%s) chunk[%d] writes %d bytes instead of %d\n",
testName, chunkSize, targetLength, expectTargetLength);
} else if(memcmp(targetBuffer, expectTarget, targetLength)!=0) {
log_err("ucnv_convertEx(%s) chunk[%d] writes different bytes than expected\n",
testName, chunkSize);
}
}
static void
convertExMultiStreaming(UConverter *srcCnv, UConverter *targetCnv,
const char *src, int32_t srcLength,
const char *expectTarget, int32_t expectTargetLength,
const char *testName,
UErrorCode expectCode) {
convertExStreaming(srcCnv, targetCnv,
src, srcLength,
expectTarget, expectTargetLength,
1, testName, expectCode);
convertExStreaming(srcCnv, targetCnv,
src, srcLength,
expectTarget, expectTargetLength,
3, testName, expectCode);
convertExStreaming(srcCnv, targetCnv,
src, srcLength,
expectTarget, expectTargetLength,
7, testName, expectCode);
}
static void TestConvertEx() {
#if !UCONFIG_NO_LEGACY_CONVERSION
static const uint8_t
utf8[]={
/* 4e00 30a1 ff61 0410 */
0xe4, 0xb8, 0x80, 0xe3, 0x82, 0xa1, 0xef, 0xbd, 0xa1, 0xd0, 0x90
},
shiftJIS[]={
0x88, 0xea, 0x83, 0x40, 0xa1, 0x84, 0x40
},
errorTarget[]={
/*
* expected output when converting shiftJIS[] from UTF-8 to Shift-JIS:
* SUB, SUB, 0x40, SUB, SUB, 0x40
*/
0xfc, 0xfc, 0xfc, 0xfc, 0x40, 0xfc, 0xfc, 0xfc, 0xfc, 0x40
};
char srcBuffer[100], targetBuffer[100];
const char *src;
char *target;
UChar pivotBuffer[100];
UChar *pivotSource, *pivotTarget;
UConverter *cnv1, *cnv2;
UErrorCode errorCode;
errorCode=U_ZERO_ERROR;
cnv1=ucnv_open("UTF-8", &errorCode);
if(U_FAILURE(errorCode)) {
log_err("unable to open a UTF-8 converter - %s\n", u_errorName(errorCode));
return;
}
cnv2=ucnv_open("Shift-JIS", &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("unable to open a Shift-JIS converter - %s\n", u_errorName(errorCode));
ucnv_close(cnv1);
return;
}
/* test ucnv_convertEx() with streaming conversion style */
convertExMultiStreaming(cnv1, cnv2,
(const char *)utf8, sizeof(utf8), (const char *)shiftJIS, sizeof(shiftJIS),
"UTF-8 -> Shift-JIS", U_ZERO_ERROR);
convertExMultiStreaming(cnv2, cnv1,
(const char *)shiftJIS, sizeof(shiftJIS), (const char *)utf8, sizeof(utf8),
"Shift-JIS -> UTF-8", U_ZERO_ERROR);
/* U_ZERO_ERROR because by default the SUB callbacks are set */
convertExMultiStreaming(cnv1, cnv2,
(const char *)shiftJIS, sizeof(shiftJIS), (const char *)errorTarget, sizeof(errorTarget),
"shiftJIS[] UTF-8 -> Shift-JIS", U_ZERO_ERROR);
/* test some simple conversions */
/* NUL-terminated source and target */
errorCode=U_STRING_NOT_TERMINATED_WARNING;
memcpy(srcBuffer, utf8, sizeof(utf8));
srcBuffer[sizeof(utf8)]=0;
src=srcBuffer;
target=targetBuffer;
ucnv_convertEx(cnv2, cnv1, &target, targetBuffer+sizeof(targetBuffer), &src, NULL,
NULL, NULL, NULL, NULL, TRUE, TRUE, &errorCode);
if( errorCode!=U_ZERO_ERROR ||
target-targetBuffer!=sizeof(shiftJIS) ||
*target!=0 ||
memcmp(targetBuffer, shiftJIS, sizeof(shiftJIS))!=0
) {
log_err("ucnv_convertEx(simple UTF-8 -> Shift_JIS) fails: %s - writes %d bytes, expect %d\n",
u_errorName(errorCode), target-targetBuffer, sizeof(shiftJIS));
}
/* NUL-terminated source and U_STRING_NOT_TERMINATED_WARNING */
errorCode=U_AMBIGUOUS_ALIAS_WARNING;
memset(targetBuffer, 0xff, sizeof(targetBuffer));
src=srcBuffer;
target=targetBuffer;
ucnv_convertEx(cnv2, cnv1, &target, targetBuffer+sizeof(shiftJIS), &src, NULL,
NULL, NULL, NULL, NULL, TRUE, TRUE, &errorCode);
if( errorCode!=U_STRING_NOT_TERMINATED_WARNING ||
target-targetBuffer!=sizeof(shiftJIS) ||
*target!=(char)0xff ||
memcmp(targetBuffer, shiftJIS, sizeof(shiftJIS))!=0
) {
log_err("ucnv_convertEx(simple UTF-8 -> Shift_JIS) fails: %s, expect U_STRING_NOT_TERMINATED_WARNING - writes %d bytes, expect %d\n",
u_errorName(errorCode), target-targetBuffer, sizeof(shiftJIS));
}
/* bad arguments */
errorCode=U_MESSAGE_PARSE_ERROR;
src=srcBuffer;
target=targetBuffer;
ucnv_convertEx(cnv2, cnv1, &target, targetBuffer+sizeof(targetBuffer), &src, NULL,
NULL, NULL, NULL, NULL, TRUE, TRUE, &errorCode);
if(errorCode!=U_MESSAGE_PARSE_ERROR) {
log_err("ucnv_convertEx(U_MESSAGE_PARSE_ERROR) sets %s\n", u_errorName(errorCode));
}
/* pivotLimit==pivotStart */
errorCode=U_ZERO_ERROR;
pivotSource=pivotTarget=pivotBuffer;
ucnv_convertEx(cnv2, cnv1, &target, targetBuffer+sizeof(targetBuffer), &src, NULL,
pivotBuffer, &pivotSource, &pivotTarget, pivotBuffer, TRUE, TRUE, &errorCode);
if(errorCode!=U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ucnv_convertEx(pivotLimit==pivotStart) sets %s\n", u_errorName(errorCode));
}
/* *pivotSource==NULL */
errorCode=U_ZERO_ERROR;
pivotSource=NULL;
ucnv_convertEx(cnv2, cnv1, &target, targetBuffer+sizeof(targetBuffer), &src, NULL,
pivotBuffer, &pivotSource, &pivotTarget, pivotBuffer+1, TRUE, TRUE, &errorCode);
if(errorCode!=U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ucnv_convertEx(*pivotSource==NULL) sets %s\n", u_errorName(errorCode));
}
/* *source==NULL */
errorCode=U_ZERO_ERROR;
src=NULL;
pivotSource=pivotBuffer;
ucnv_convertEx(cnv2, cnv1, &target, targetBuffer+sizeof(targetBuffer), &src, NULL,
pivotBuffer, &pivotSource, &pivotTarget, pivotBuffer+1, TRUE, TRUE, &errorCode);
if(errorCode!=U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ucnv_convertEx(*source==NULL) sets %s\n", u_errorName(errorCode));
}
/* streaming conversion without a pivot buffer */
errorCode=U_ZERO_ERROR;
src=srcBuffer;
pivotSource=pivotBuffer;
ucnv_convertEx(cnv2, cnv1, &target, targetBuffer+sizeof(targetBuffer), &src, NULL,
NULL, &pivotSource, &pivotTarget, pivotBuffer+1, TRUE, FALSE, &errorCode);
if(errorCode!=U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ucnv_convertEx(pivotStart==NULL) sets %s\n", u_errorName(errorCode));
}
ucnv_close(cnv1);
ucnv_close(cnv2);
#endif
}
/* Test illegal UTF-8 input: Data and functions for TestConvertExFromUTF8(). */
static const char *const badUTF8[]={
/* trail byte */
"\x80",
/* truncated multi-byte sequences */
"\xd0",
"\xe0",
"\xe1",
"\xed",
"\xee",
"\xf0",
"\xf1",
"\xf4",
"\xf8",
"\xfc",
"\xe0\x80",
"\xe0\xa0",
"\xe1\x80",
"\xed\x80",
"\xed\xa0",
"\xee\x80",
"\xf0\x80",
"\xf0\x90",
"\xf1\x80",
"\xf4\x80",
"\xf4\x90",
"\xf8\x80",
"\xfc\x80",
"\xf0\x80\x80",
"\xf0\x90\x80",
"\xf1\x80\x80",
"\xf4\x80\x80",
"\xf4\x90\x80",
"\xf8\x80\x80",
"\xfc\x80\x80",
"\xf8\x80\x80\x80",
"\xfc\x80\x80\x80",
"\xfc\x80\x80\x80\x80",
/* complete sequences but non-shortest forms or out of range etc. */
"\xc0\x80",
"\xe0\x80\x80",
"\xed\xa0\x80",
"\xf0\x80\x80\x80",
"\xf4\x90\x80\x80",
"\xf8\x80\x80\x80\x80",
"\xfc\x80\x80\x80\x80\x80",
"\xfe",
"\xff"
};
#define ARG_CHAR_ARR_SIZE 8
/* get some character that can be converted and convert it */
static UBool getTestChar(UConverter *cnv, const char *converterName,
char charUTF8[4], int32_t *pCharUTF8Length,
char char0[ARG_CHAR_ARR_SIZE], int32_t *pChar0Length,
char char1[ARG_CHAR_ARR_SIZE], int32_t *pChar1Length) {
UChar utf16[U16_MAX_LENGTH];
int32_t utf16Length;
const UChar *utf16Source;
char *target;
USet *set;
UChar32 c;
UErrorCode errorCode;
errorCode=U_ZERO_ERROR;
set=uset_open(1, 0);
ucnv_getUnicodeSet(cnv, set, UCNV_ROUNDTRIP_SET, &errorCode);
c=uset_charAt(set, uset_size(set)/2);
uset_close(set);
utf16Length=0;
U16_APPEND_UNSAFE(utf16, utf16Length, c);
*pCharUTF8Length=0;
U8_APPEND_UNSAFE(charUTF8, *pCharUTF8Length, c);
utf16Source=utf16;
target=char0;
ucnv_fromUnicode(cnv,
&target, char0+ARG_CHAR_ARR_SIZE,
&utf16Source, utf16+utf16Length,
NULL, FALSE, &errorCode);
*pChar0Length=(int32_t)(target-char0);
utf16Source=utf16;
target=char1;
ucnv_fromUnicode(cnv,
&target, char1+ARG_CHAR_ARR_SIZE,
&utf16Source, utf16+utf16Length,
NULL, FALSE, &errorCode);
*pChar1Length=(int32_t)(target-char1);
if(U_FAILURE(errorCode)) {
log_err("unable to get test character for %s - %s\n", converterName, u_errorName(errorCode));
return FALSE;
}
return TRUE;
}
static void testFromTruncatedUTF8(UConverter *utf8Cnv, UConverter *cnv, const char *converterName,
char charUTF8[4], int32_t charUTF8Length,
char char0[8], int32_t char0Length,
char char1[8], int32_t char1Length) {
char utf8[16];
int32_t utf8Length;
char output[16];
int32_t outputLength;
char invalidChars[8];
int8_t invalidLength;
const char *source;
char *target;
UChar pivotBuffer[8];
UChar *pivotSource, *pivotTarget;
UErrorCode errorCode;
int32_t i;
/* test truncated sequences */
errorCode=U_ZERO_ERROR;
ucnv_setToUCallBack(utf8Cnv, UCNV_TO_U_CALLBACK_STOP, NULL, NULL, NULL, &errorCode);
memcpy(utf8, charUTF8, charUTF8Length);
for(i=0; i<UPRV_LENGTHOF(badUTF8); ++i) {
/* truncated sequence? */
int32_t length=strlen(badUTF8[i]);
if(length>=(1+U8_COUNT_TRAIL_BYTES(badUTF8[i][0]))) {
continue;
}
/* assemble a string with the test character and the truncated sequence */
memcpy(utf8+charUTF8Length, badUTF8[i], length);
utf8Length=charUTF8Length+length;
/* convert and check the invalidChars */
source=utf8;
target=output;
pivotSource=pivotTarget=pivotBuffer;
errorCode=U_ZERO_ERROR;
ucnv_convertEx(cnv, utf8Cnv,
&target, output+sizeof(output),
&source, utf8+utf8Length,
pivotBuffer, &pivotSource, &pivotTarget, pivotBuffer+UPRV_LENGTHOF(pivotBuffer),
TRUE, TRUE, /* reset & flush */
&errorCode);
outputLength=(int32_t)(target-output);
(void)outputLength; /* Suppress set but not used warning. */
if(errorCode!=U_TRUNCATED_CHAR_FOUND || pivotSource!=pivotBuffer) {
log_err("unexpected error %s from %s badUTF8[%ld]\n", u_errorName(errorCode), converterName, (long)i);
continue;
}
errorCode=U_ZERO_ERROR;
invalidLength=(int8_t)sizeof(invalidChars);
ucnv_getInvalidChars(utf8Cnv, invalidChars, &invalidLength, &errorCode);
if(invalidLength!=length || 0!=memcmp(invalidChars, badUTF8[i], length)) {
log_err("wrong invalidChars from %s badUTF8[%ld]\n", converterName, (long)i);
}
}
}
static void testFromBadUTF8(UConverter *utf8Cnv, UConverter *cnv, const char *converterName,
char charUTF8[4], int32_t charUTF8Length,
char char0[8], int32_t char0Length,
char char1[8], int32_t char1Length) {
char utf8[600], expect[600];
int32_t utf8Length, expectLength;
char testName[32];
UErrorCode errorCode;
int32_t i;
errorCode=U_ZERO_ERROR;
ucnv_setToUCallBack(utf8Cnv, UCNV_TO_U_CALLBACK_SKIP, NULL, NULL, NULL, &errorCode);
/*
* assemble an input string with the test character between each
* bad sequence,
* and an expected string with repeated test character output
*/
memcpy(utf8, charUTF8, charUTF8Length);
utf8Length=charUTF8Length;
memcpy(expect, char0, char0Length);
expectLength=char0Length;
for(i=0; i<UPRV_LENGTHOF(badUTF8); ++i) {
int32_t length=strlen(badUTF8[i]);
memcpy(utf8+utf8Length, badUTF8[i], length);
utf8Length+=length;
memcpy(utf8+utf8Length, charUTF8, charUTF8Length);
utf8Length+=charUTF8Length;
memcpy(expect+expectLength, char1, char1Length);
expectLength+=char1Length;
}
/* expect that each bad UTF-8 sequence is detected and skipped */
strcpy(testName, "from bad UTF-8 to ");
strcat(testName, converterName);
convertExMultiStreaming(utf8Cnv, cnv,
utf8, utf8Length,
expect, expectLength,
testName,
U_ZERO_ERROR);
}
/* Test illegal UTF-8 input. */
static void TestConvertExFromUTF8() {
static const char *const converterNames[]={
#if !UCONFIG_NO_LEGACY_CONVERSION
"windows-1252",
"shift-jis",
#endif
"us-ascii",
"iso-8859-1",
"utf-8"
};
UConverter *utf8Cnv, *cnv;
UErrorCode errorCode;
int32_t i;
/* fromUnicode versions of some character, from initial state and later */
char charUTF8[4], char0[8], char1[8];
int32_t charUTF8Length, char0Length, char1Length;
errorCode=U_ZERO_ERROR;
utf8Cnv=ucnv_open("UTF-8", &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("unable to open UTF-8 converter - %s\n", u_errorName(errorCode));
return;
}
for(i=0; i<UPRV_LENGTHOF(converterNames); ++i) {
errorCode=U_ZERO_ERROR;
cnv=ucnv_open(converterNames[i], &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("unable to open %s converter - %s\n", converterNames[i], u_errorName(errorCode));
continue;
}
if(!getTestChar(cnv, converterNames[i], charUTF8, &charUTF8Length, char0, &char0Length, char1, &char1Length)) {
continue;
}
testFromTruncatedUTF8(utf8Cnv, cnv, converterNames[i], charUTF8, charUTF8Length, char0, char0Length, char1, char1Length);
testFromBadUTF8(utf8Cnv, cnv, converterNames[i], charUTF8, charUTF8Length, char0, char0Length, char1, char1Length);
ucnv_close(cnv);
}
ucnv_close(utf8Cnv);
}
static void TestConvertExFromUTF8_C5F0() {
static const char *const converterNames[]={
#if !UCONFIG_NO_LEGACY_CONVERSION
"windows-1251",
"shift-jis",
#endif
"us-ascii",
"iso-8859-1",
"utf-8"
};
UConverter *utf8Cnv, *cnv;
UErrorCode errorCode;
int32_t i;
static const char bad_utf8[2]={ (char)0xC5, (char)0xF0 };
/* Expect "��" (2x U+FFFD as decimal NCRs) */
static const char twoNCRs[16]={
0x26, 0x23, 0x36, 0x35, 0x35, 0x33, 0x33, 0x3B,
0x26, 0x23, 0x36, 0x35, 0x35, 0x33, 0x33, 0x3B
};
static const char twoFFFD[6]={
(char)0xef, (char)0xbf, (char)0xbd,
(char)0xef, (char)0xbf, (char)0xbd
};
const char *expected;
int32_t expectedLength;
char dest[20]; /* longer than longest expectedLength */
const char *src;
char *target;
UChar pivotBuffer[128];
UChar *pivotSource, *pivotTarget;
errorCode=U_ZERO_ERROR;
utf8Cnv=ucnv_open("UTF-8", &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("unable to open UTF-8 converter - %s\n", u_errorName(errorCode));
return;
}
for(i=0; i<UPRV_LENGTHOF(converterNames); ++i) {
errorCode=U_ZERO_ERROR;
cnv=ucnv_open(converterNames[i], &errorCode);
ucnv_setFromUCallBack(cnv, UCNV_FROM_U_CALLBACK_ESCAPE, UCNV_ESCAPE_XML_DEC,
NULL, NULL, &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("unable to open %s converter - %s\n",
converterNames[i], u_errorName(errorCode));
continue;
}
src=bad_utf8;
target=dest;
uprv_memset(dest, 9, sizeof(dest));
if(i==UPRV_LENGTHOF(converterNames)-1) {
/* conversion to UTF-8 yields two U+FFFD directly */
expected=twoFFFD;
expectedLength=6;
} else {
/* conversion to a non-Unicode charset yields two NCRs */
expected=twoNCRs;
expectedLength=16;
}
pivotBuffer[0]=0;
pivotBuffer[1]=1;
pivotBuffer[2]=2;
pivotSource=pivotTarget=pivotBuffer;
ucnv_convertEx(
cnv, utf8Cnv,
&target, dest+expectedLength,
&src, bad_utf8+sizeof(bad_utf8),
pivotBuffer, &pivotSource, &pivotTarget, pivotBuffer+UPRV_LENGTHOF(pivotBuffer),
TRUE, TRUE, &errorCode);
if( errorCode!=U_STRING_NOT_TERMINATED_WARNING || src!=bad_utf8+2 ||
target!=dest+expectedLength || 0!=uprv_memcmp(dest, expected, expectedLength) ||
dest[expectedLength]!=9
) {
log_err("ucnv_convertEx(UTF-8 C5 F0 -> %s/decimal NCRs) failed\n", converterNames[i]);
}
ucnv_close(cnv);
}
ucnv_close(utf8Cnv);
}
static void
TestConvertAlgorithmic() {
#if !UCONFIG_NO_LEGACY_CONVERSION
static const uint8_t
utf8[]={
/* 4e00 30a1 ff61 0410 */
0xe4, 0xb8, 0x80, 0xe3, 0x82, 0xa1, 0xef, 0xbd, 0xa1, 0xd0, 0x90
},
shiftJIS[]={
0x88, 0xea, 0x83, 0x40, 0xa1, 0x84, 0x40
},
/*errorTarget[]={*/
/*
* expected output when converting shiftJIS[] from UTF-8 to Shift-JIS:
* SUB, SUB, 0x40, SUB, SUB, 0x40
*/
/* 0x81, 0xa1, 0x81, 0xa1, 0x40, 0x81, 0xa1, 0x81, 0xa1, 0x40*/
/*},*/
utf16[]={
0xfe, 0xff /* BOM only, no text */
};
#if !UCONFIG_ONLY_HTML_CONVERSION
static const uint8_t utf32[]={
0xff, 0xfe, 0, 0 /* BOM only, no text */
};
#endif
char target[100], utf8NUL[100], shiftJISNUL[100];
UConverter *cnv;
UErrorCode errorCode;
int32_t length;
errorCode=U_ZERO_ERROR;
cnv=ucnv_open("Shift-JIS", &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("unable to open a Shift-JIS converter - %s\n", u_errorName(errorCode));
ucnv_close(cnv);
return;
}
memcpy(utf8NUL, utf8, sizeof(utf8));
utf8NUL[sizeof(utf8)]=0;
memcpy(shiftJISNUL, shiftJIS, sizeof(shiftJIS));
shiftJISNUL[sizeof(shiftJIS)]=0;
/*
* The to/from algorithmic convenience functions share a common implementation,
* so we need not test all permutations of them.
*/
/* length in, not terminated out */
errorCode=U_ZERO_ERROR;
length=ucnv_fromAlgorithmic(cnv, UCNV_UTF8, target, sizeof(shiftJIS), (const char *)utf8, sizeof(utf8), &errorCode);
if( errorCode!=U_STRING_NOT_TERMINATED_WARNING ||
length!=sizeof(shiftJIS) ||
memcmp(target, shiftJIS, length)!=0
) {
log_err("ucnv_fromAlgorithmic(UTF-8 -> Shift-JIS) fails (%s expect U_STRING_NOT_TERMINATED_WARNING), returns %d expect %d\n",
u_errorName(errorCode), length, sizeof(shiftJIS));
}
/* terminated in and out */
memset(target, 0x55, sizeof(target));
errorCode=U_STRING_NOT_TERMINATED_WARNING;
length=ucnv_toAlgorithmic(UCNV_UTF8, cnv, target, sizeof(target), shiftJISNUL, -1, &errorCode);
if( errorCode!=U_ZERO_ERROR ||
length!=sizeof(utf8) ||
memcmp(target, utf8, length)!=0
) {
log_err("ucnv_toAlgorithmic(Shift-JIS -> UTF-8) fails (%s expect U_ZERO_ERROR), returns %d expect %d\n",
u_errorName(errorCode), length, sizeof(shiftJIS));
}
/* empty string, some target buffer */
errorCode=U_STRING_NOT_TERMINATED_WARNING;
length=ucnv_toAlgorithmic(UCNV_UTF8, cnv, target, sizeof(target), shiftJISNUL, 0, &errorCode);
if( errorCode!=U_ZERO_ERROR ||
length!=0
) {
log_err("ucnv_toAlgorithmic(empty string -> UTF-8) fails (%s expect U_ZERO_ERROR), returns %d expect 0\n",
u_errorName(errorCode), length);
}
/* pseudo-empty string, no target buffer */
errorCode=U_ZERO_ERROR;
length=ucnv_fromAlgorithmic(cnv, UCNV_UTF16, target, 0, (const char *)utf16, 2, &errorCode);
if( errorCode!=U_STRING_NOT_TERMINATED_WARNING ||
length!=0
) {
log_err("ucnv_fromAlgorithmic(UTF-16 only BOM -> Shift-JIS) fails (%s expect U_STRING_NOT_TERMINATED_WARNING), returns %d expect 0\n",
u_errorName(errorCode), length);
}
#if !UCONFIG_ONLY_HTML_CONVERSION
errorCode=U_ZERO_ERROR;
length=ucnv_fromAlgorithmic(cnv, UCNV_UTF32, target, 0, (const char *)utf32, 4, &errorCode);
if( errorCode!=U_STRING_NOT_TERMINATED_WARNING ||
length!=0
) {
log_err("ucnv_fromAlgorithmic(UTF-32 only BOM -> Shift-JIS) fails (%s expect U_STRING_NOT_TERMINATED_WARNING), returns %d expect 0\n",
u_errorName(errorCode), length);
}
#endif
/* bad arguments */
errorCode=U_MESSAGE_PARSE_ERROR;
length=ucnv_fromAlgorithmic(cnv, UCNV_UTF16, target, 0, (const char *)utf16, 2, &errorCode);
if(errorCode!=U_MESSAGE_PARSE_ERROR) {
log_err("ucnv_fromAlgorithmic(U_MESSAGE_PARSE_ERROR) sets %s\n", u_errorName(errorCode));
}
/* source==NULL */
errorCode=U_ZERO_ERROR;
length=ucnv_fromAlgorithmic(cnv, UCNV_UTF16, target, 0, NULL, 2, &errorCode);
if(errorCode!=U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ucnv_fromAlgorithmic(source==NULL) sets %s\n", u_errorName(errorCode));
}
/* illegal alg. type */
errorCode=U_ZERO_ERROR;
length=ucnv_fromAlgorithmic(cnv, (UConverterType)99, target, 0, (const char *)utf16, 2, &errorCode);
if(errorCode!=U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ucnv_fromAlgorithmic(illegal alg. type) sets %s\n", u_errorName(errorCode));
}
ucnv_close(cnv);
#endif
}
#if !UCONFIG_NO_FILE_IO && !UCONFIG_NO_LEGACY_CONVERSION
static void TestLMBCSMaxChar(void) {
static const struct {
int8_t maxSize;
const char *name;
} converter[] = {
/* some non-LMBCS converters - perfect test setup here */
{ 1, "US-ASCII"},
{ 1, "ISO-8859-1"},
{ 2, "UTF-16"},
{ 2, "UTF-16BE"},
{ 3, "UTF-8"},
{ 3, "CESU-8"},
{ 3, "SCSU"},
{ 4, "UTF-32"},
{ 4, "UTF-7"},
{ 4, "IMAP-mailbox-name"},
{ 4, "BOCU-1"},
{ 1, "windows-1256"},
{ 2, "Shift-JIS"},
{ 2, "ibm-16684"},
{ 3, "ibm-930"},
{ 3, "ibm-1390"},
{ 4, "*test3"},
{ 16,"*test4"},
{ 4, "ISCII"},
{ 4, "HZ"},
{ 3, "ISO-2022"},
{ 3, "ISO-2022-KR"},
{ 6, "ISO-2022-JP"},
{ 8, "ISO-2022-CN"},
/* LMBCS */
{ 3, "LMBCS-1"},
{ 3, "LMBCS-2"},
{ 3, "LMBCS-3"},
{ 3, "LMBCS-4"},
{ 3, "LMBCS-5"},
{ 3, "LMBCS-6"},
{ 3, "LMBCS-8"},
{ 3, "LMBCS-11"},
{ 3, "LMBCS-16"},
{ 3, "LMBCS-17"},
{ 3, "LMBCS-18"},
{ 3, "LMBCS-19"}
};
int32_t idx;
for (idx = 0; idx < UPRV_LENGTHOF(converter); idx++) {
UErrorCode status = U_ZERO_ERROR;
UConverter *cnv = cnv_open(converter[idx].name, &status);
if (U_FAILURE(status)) {
continue;
}
if (converter[idx].maxSize != ucnv_getMaxCharSize(cnv)) {
log_err("error: ucnv_getMaxCharSize(%s) expected %d, got %d\n",
converter[idx].name, converter[idx].maxSize, ucnv_getMaxCharSize(cnv));
}
ucnv_close(cnv);
}
/* mostly test that the macro compiles */
if(UCNV_GET_MAX_BYTES_FOR_STRING(1, 2)<10) {
log_err("error UCNV_GET_MAX_BYTES_FOR_STRING(1, 2)<10\n");
}
}
#endif
static void TestJ1968(void) {
UErrorCode err = U_ZERO_ERROR;
UConverter *cnv;
char myConvName[] = "My really really really really really really really really really really really"
" really really really really really really really really really really really"
" really really really really really really really really long converter name";
UChar myConvNameU[sizeof(myConvName)];
u_charsToUChars(myConvName, myConvNameU, sizeof(myConvName));
err = U_ZERO_ERROR;
myConvNameU[UCNV_MAX_CONVERTER_NAME_LENGTH+1] = 0;
cnv = ucnv_openU(myConvNameU, &err);
if (cnv || err != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("1U) Didn't get U_ILLEGAL_ARGUMENT_ERROR as expected %s\n", u_errorName(err));
}
err = U_ZERO_ERROR;
myConvNameU[UCNV_MAX_CONVERTER_NAME_LENGTH] = 0;
cnv = ucnv_openU(myConvNameU, &err);
if (cnv || err != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("2U) Didn't get U_ILLEGAL_ARGUMENT_ERROR as expected %s\n", u_errorName(err));
}
err = U_ZERO_ERROR;
myConvNameU[UCNV_MAX_CONVERTER_NAME_LENGTH-1] = 0;
cnv = ucnv_openU(myConvNameU, &err);
if (cnv || err != U_FILE_ACCESS_ERROR) {
log_err("3U) Didn't get U_FILE_ACCESS_ERROR as expected %s\n", u_errorName(err));
}
err = U_ZERO_ERROR;
cnv = ucnv_open(myConvName, &err);
if (cnv || err != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("1) Didn't get U_ILLEGAL_ARGUMENT_ERROR as expected %s\n", u_errorName(err));
}
err = U_ZERO_ERROR;
myConvName[UCNV_MAX_CONVERTER_NAME_LENGTH] = ',';
cnv = ucnv_open(myConvName, &err);
if (cnv || err != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("2) Didn't get U_ILLEGAL_ARGUMENT_ERROR as expected %s\n", u_errorName(err));
}
err = U_ZERO_ERROR;
myConvName[UCNV_MAX_CONVERTER_NAME_LENGTH-1] = ',';
cnv = ucnv_open(myConvName, &err);
if (cnv || err != U_FILE_ACCESS_ERROR) {
log_err("3) Didn't get U_FILE_ACCESS_ERROR as expected %s\n", u_errorName(err));
}
err = U_ZERO_ERROR;
myConvName[UCNV_MAX_CONVERTER_NAME_LENGTH-1] = ',';
strncpy(myConvName + UCNV_MAX_CONVERTER_NAME_LENGTH, "locale=", 7);
cnv = ucnv_open(myConvName, &err);
if (cnv || err != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("4) Didn't get U_ILLEGAL_ARGUMENT_ERROR as expected %s\n", u_errorName(err));
}
/* The comma isn't really a part of the converter name. */
err = U_ZERO_ERROR;
myConvName[UCNV_MAX_CONVERTER_NAME_LENGTH] = 0;
cnv = ucnv_open(myConvName, &err);
if (cnv || err != U_FILE_ACCESS_ERROR) {
log_err("5) Didn't get U_FILE_ACCESS_ERROR as expected %s\n", u_errorName(err));
}
err = U_ZERO_ERROR;
myConvName[UCNV_MAX_CONVERTER_NAME_LENGTH-1] = ' ';
cnv = ucnv_open(myConvName, &err);
if (cnv || err != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("6) Didn't get U_ILLEGAL_ARGUMENT_ERROR as expected %s\n", u_errorName(err));
}
err = U_ZERO_ERROR;
myConvName[UCNV_MAX_CONVERTER_NAME_LENGTH-1] = 0;
cnv = ucnv_open(myConvName, &err);
if (cnv || err != U_FILE_ACCESS_ERROR) {
log_err("7) Didn't get U_FILE_ACCESS_ERROR as expected %s\n", u_errorName(err));
}
}
#if !UCONFIG_NO_LEGACY_CONVERSION
static void
testSwap(const char *name, UBool swap) {
/*
* Test Unicode text.
* Contains characters that are the highest for some of the
* tested conversions, to make sure that the ucnvmbcs.c code that modifies the
* tables copies the entire tables.
*/
static const UChar text[]={
0x61, 0xd, 0x62, 0xa, 0x4e00, 0x3000, 0xfffd, 0xa, 0x20, 0x85, 0xff5e, 0x7a
};
UChar uNormal[32], uSwapped[32];
char normal[32], swapped[32];
const UChar *pcu;
UChar *pu;
char *pc;
int32_t i, normalLength, swappedLength;
UChar u;
char c;
const char *swappedName;
UConverter *cnv, *swapCnv;
UErrorCode errorCode;
/* if the swap flag is FALSE, then the test encoding is not EBCDIC and must not swap */
/* open both the normal and the LF/NL-swapping converters */
strcpy(swapped, name);
strcat(swapped, UCNV_SWAP_LFNL_OPTION_STRING);
errorCode=U_ZERO_ERROR;
swapCnv=ucnv_open(swapped, &errorCode);
cnv=ucnv_open(name, &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("TestEBCDICSwapLFNL error: unable to open %s or %s (%s)\n", name, swapped, u_errorName(errorCode));
goto cleanup;
}
/* the name must contain the swap option if and only if we expect the converter to swap */
swappedName=ucnv_getName(swapCnv, &errorCode);
if(U_FAILURE(errorCode)) {
log_err("TestEBCDICSwapLFNL error: ucnv_getName(%s,swaplfnl) failed (%s)\n", name, u_errorName(errorCode));
goto cleanup;
}
pc=strstr(swappedName, UCNV_SWAP_LFNL_OPTION_STRING);
if(swap != (pc!=NULL)) {
log_err("TestEBCDICSwapLFNL error: ucnv_getName(%s,swaplfnl)=%s should (%d) contain 'swaplfnl'\n", name, swappedName, swap);
goto cleanup;
}
/* convert to EBCDIC */
pcu=text;
pc=normal;
ucnv_fromUnicode(cnv, &pc, normal+UPRV_LENGTHOF(normal), &pcu, text+UPRV_LENGTHOF(text), NULL, TRUE, &errorCode);
normalLength=(int32_t)(pc-normal);
pcu=text;
pc=swapped;
ucnv_fromUnicode(swapCnv, &pc, swapped+UPRV_LENGTHOF(swapped), &pcu, text+UPRV_LENGTHOF(text), NULL, TRUE, &errorCode);
swappedLength=(int32_t)(pc-swapped);
if(U_FAILURE(errorCode)) {
log_err("TestEBCDICSwapLFNL error converting to %s - (%s)\n", name, u_errorName(errorCode));
goto cleanup;
}
/* compare EBCDIC output */
if(normalLength!=swappedLength) {
log_err("TestEBCDICSwapLFNL error converting to %s - output lengths %d vs. %d\n", name, normalLength, swappedLength);
goto cleanup;
}
for(i=0; i<normalLength; ++i) {
/* swap EBCDIC LF/NL for comparison */
c=normal[i];
if(swap) {
if(c==0x15) {
c=0x25;
} else if(c==0x25) {
c=0x15;
}
}
if(c!=swapped[i]) {
log_err("TestEBCDICSwapLFNL error converting to %s - did not swap properly, output[%d]=0x%02x\n", name, i, (uint8_t)swapped[i]);
goto cleanup;
}
}
/* convert back to Unicode (may not roundtrip) */
pc=normal;
pu=uNormal;
ucnv_toUnicode(cnv, &pu, uNormal+UPRV_LENGTHOF(uNormal), (const char **)&pc, normal+normalLength, NULL, TRUE, &errorCode);
normalLength=(int32_t)(pu-uNormal);
pc=normal;
pu=uSwapped;
ucnv_toUnicode(swapCnv, &pu, uSwapped+UPRV_LENGTHOF(uSwapped), (const char **)&pc, normal+swappedLength, NULL, TRUE, &errorCode);
swappedLength=(int32_t)(pu-uSwapped);
if(U_FAILURE(errorCode)) {
log_err("TestEBCDICSwapLFNL error converting from %s - (%s)\n", name, u_errorName(errorCode));
goto cleanup;
}
/* compare EBCDIC output */
if(normalLength!=swappedLength) {
log_err("TestEBCDICSwapLFNL error converting from %s - output lengths %d vs. %d\n", name, normalLength, swappedLength);
goto cleanup;
}
for(i=0; i<normalLength; ++i) {
/* swap EBCDIC LF/NL for comparison */
u=uNormal[i];
if(swap) {
if(u==0xa) {
u=0x85;
} else if(u==0x85) {
u=0xa;
}
}
if(u!=uSwapped[i]) {
log_err("TestEBCDICSwapLFNL error converting from %s - did not swap properly, output[%d]=U+%04x\n", name, i, uSwapped[i]);
goto cleanup;
}
}
/* clean up */
cleanup:
ucnv_close(cnv);
ucnv_close(swapCnv);
}
static void
TestEBCDICSwapLFNL() {
static const struct {
const char *name;
UBool swap;
} tests[]={
{ "ibm-37", TRUE },
{ "ibm-1047", TRUE },
{ "ibm-1140", TRUE },
{ "ibm-930", TRUE },
{ "iso-8859-3", FALSE }
};
int i;
for(i=0; i<UPRV_LENGTHOF(tests); ++i) {
testSwap(tests[i].name, tests[i].swap);
}
}
#else
static void
TestEBCDICSwapLFNL() {
/* test nothing... */
}
#endif
static void TestFromUCountPending(){
#if !UCONFIG_NO_LEGACY_CONVERSION
UErrorCode status = U_ZERO_ERROR;
/* const UChar expectedUnicode[] = { 0x20ac, 0x0005, 0x0006, 0x000b, 0xdbc4, 0xde34, 0xd84d, 0xdc56, 0xfffd}; */
static const struct {
UChar input[6];
int32_t len;
int32_t exp;
}fromUnicodeTests[] = {
/*m:n conversion*/
{{0xdbc4},1,1},
{{ 0xdbc4, 0xde34, 0xd84d},3,1},
{{ 0xdbc4, 0xde34, 0xd900},3,3},
};
int i;
UConverter* cnv = ucnv_openPackage(loadTestData(&status), "test3", &status);
if(U_FAILURE(status)){
log_data_err("Could not create converter for test3. Error: %s\n", u_errorName(status));
return;
}
for(i=0; i<UPRV_LENGTHOF(fromUnicodeTests); ++i) {
char tgt[10];
char* target = tgt;
char* targetLimit = target + 10;
const UChar* source = fromUnicodeTests[i].input;
const UChar* sourceLimit = source + fromUnicodeTests[i].len;
int32_t len = 0;
ucnv_reset(cnv);
ucnv_fromUnicode(cnv,&target, targetLimit, &source, sourceLimit, NULL, FALSE, &status);
len = ucnv_fromUCountPending(cnv, &status);
if(U_FAILURE(status)){
log_err("ucnv_fromUnicode call did not succeed. Error: %s\n", u_errorName(status));
status = U_ZERO_ERROR;
continue;
}
if(len != fromUnicodeTests[i].exp){
log_err("Did not get the expeced output for ucnv_fromUInputConsumed.\n");
}
}
status = U_ZERO_ERROR;
{
/*
* The converter has to read the tail before it knows that
* only head alone matches.
* At the end, the output for head will overflow the target,
* middle will be pending, and tail will not have been consumed.
*/
/*
\U00101234 -> x (<U101234> \x07 |0)
\U00101234\U00050005 -> y (<U101234>+<U50005> \x07+\x00+\x01\x02\x0e+\x05 |0)
\U00101234\U00050005\U00060006 -> z (<U101234>+<U50005>+<U60006> \x07+\x00+\x01\x02\x0f+\x09 |0)
\U00060007 -> unassigned
*/
static const UChar head[] = {0xDBC4,0xDE34,0xD900,0xDC05,0x0000};/* \U00101234\U00050005 */
static const UChar middle[] = {0xD940,0x0000}; /* first half of \U00060006 or \U00060007 */
static const UChar tail[] = {0xDC07,0x0000};/* second half of \U00060007 */
char tgt[10];
char* target = tgt;
char* targetLimit = target + 2; /* expect overflow from converting \U00101234\U00050005 */
const UChar* source = head;
const UChar* sourceLimit = source + u_strlen(head);
int32_t len = 0;
ucnv_reset(cnv);
ucnv_fromUnicode(cnv,&target, targetLimit, &source, sourceLimit, NULL, FALSE, &status);
len = ucnv_fromUCountPending(cnv, &status);
if(U_FAILURE(status)){
log_err("ucnv_fromUnicode call did not succeed. Error: %s\n", u_errorName(status));
status = U_ZERO_ERROR;
}
if(len!=4){
log_err("ucnv_fromUInputHeld did not return correct length for head\n");
}
source = middle;
sourceLimit = source + u_strlen(middle);
ucnv_fromUnicode(cnv,&target, targetLimit, &source, sourceLimit, NULL, FALSE, &status);
len = ucnv_fromUCountPending(cnv, &status);
if(U_FAILURE(status)){
log_err("ucnv_fromUnicode call did not succeed. Error: %s\n", u_errorName(status));
status = U_ZERO_ERROR;
}
if(len!=5){
log_err("ucnv_fromUInputHeld did not return correct length for middle\n");
}
source = tail;
sourceLimit = source + u_strlen(tail);
ucnv_fromUnicode(cnv,&target, targetLimit, &source, sourceLimit, NULL, FALSE, &status);
if(status != U_BUFFER_OVERFLOW_ERROR){
log_err("ucnv_fromUnicode call did not succeed. Error: %s\n", u_errorName(status));
}
status = U_ZERO_ERROR;
len = ucnv_fromUCountPending(cnv, &status);
/* middle[1] is pending, tail has not been consumed */
if(U_FAILURE(status)){
log_err("ucnv_fromUInputHeld call did not succeed. Error: %s\n", u_errorName(status));
}
if(len!=1){
log_err("ucnv_fromUInputHeld did not return correct length for tail\n");
}
}
ucnv_close(cnv);
#endif
}
static void
TestToUCountPending(){
#if !UCONFIG_NO_LEGACY_CONVERSION
UErrorCode status = U_ZERO_ERROR;
static const struct {
char input[6];
int32_t len;
int32_t exp;
}toUnicodeTests[] = {
/*m:n conversion*/
{{0x05, 0x01, 0x02},3,3},
{{0x01, 0x02},2,2},
{{0x07, 0x00, 0x01, 0x02},4,4},
};
int i;
UConverterToUCallback *oldToUAction= NULL;
UConverter* cnv = ucnv_openPackage(loadTestData(&status), "test3", &status);
if(U_FAILURE(status)){
log_data_err("Could not create converter for test3. Error: %s\n", u_errorName(status));
return;
}
ucnv_setToUCallBack(cnv, UCNV_TO_U_CALLBACK_STOP, NULL, oldToUAction, NULL, &status);
for(i=0; i<UPRV_LENGTHOF(toUnicodeTests); ++i) {
UChar tgt[20];
UChar* target = tgt;
UChar* targetLimit = target + 20;
const char* source = toUnicodeTests[i].input;
const char* sourceLimit = source + toUnicodeTests[i].len;
int32_t len = 0;
ucnv_reset(cnv);
ucnv_toUnicode(cnv, &target, targetLimit, &source, sourceLimit, NULL, FALSE, &status);
len = ucnv_toUCountPending(cnv,&status);
if(U_FAILURE(status)){
log_err("ucnv_toUnicode call did not succeed. Error: %s\n", u_errorName(status));
status = U_ZERO_ERROR;
continue;
}
if(len != toUnicodeTests[i].exp){
log_err("Did not get the expeced output for ucnv_toUInputConsumed.\n");
}
}
status = U_ZERO_ERROR;
ucnv_close(cnv);
{
/*
* The converter has to read the tail before it knows that
* only head alone matches.
* At the end, the output for head will overflow the target,
* mid will be pending, and tail will not have been consumed.
*/
char head[] = { 0x01, 0x02, 0x03, 0x0a , 0x00};
char mid[] = { 0x01, 0x02, 0x03, 0x0b, 0x00 };
char tail[] = { 0x01, 0x02, 0x03, 0x0d, 0x00 };
/*
0x01, 0x02, 0x03, 0x0a -> x (<U23456> \x01\x02\x03\x0a |0)
0x01, 0x02, 0x03, 0x0b -> y (<U000b> \x01\x02\x03\x0b |0)
0x01, 0x02, 0x03, 0x0d -> z (<U34567> \x01\x02\x03\x0d |3)
0x01, 0x02, 0x03, 0x0a + 0x01, 0x02, 0x03, 0x0b + 0x01 + many more -> z (see test4 "many bytes, and bytes per UChar")
*/
UChar tgt[10];
UChar* target = tgt;
UChar* targetLimit = target + 1; /* expect overflow from converting */
const char* source = head;
const char* sourceLimit = source + strlen(head);
int32_t len = 0;
cnv = ucnv_openPackage(loadTestData(&status), "test4", &status);
if(U_FAILURE(status)){
log_err("Could not create converter for test3. Error: %s\n", u_errorName(status));
return;
}
ucnv_setToUCallBack(cnv, UCNV_TO_U_CALLBACK_STOP, NULL, oldToUAction, NULL, &status);
ucnv_toUnicode(cnv,&target, targetLimit, &source, sourceLimit, NULL, FALSE, &status);
len = ucnv_toUCountPending(cnv,&status);
if(U_FAILURE(status)){
log_err("ucnv_toUnicode call did not succeed. Error: %s\n", u_errorName(status));
}
if(len != 4){
log_err("Did not get the expected len for head.\n");
}
source=mid;
sourceLimit = source+strlen(mid);
ucnv_toUnicode(cnv,&target, targetLimit, &source, sourceLimit, NULL, FALSE, &status);
len = ucnv_toUCountPending(cnv,&status);
if(U_FAILURE(status)){
log_err("ucnv_toUnicode call did not succeed. Error: %s\n", u_errorName(status));
}
if(len != 8){
log_err("Did not get the expected len for mid.\n");
}
source=tail;
sourceLimit = source+strlen(tail);
targetLimit = target;
ucnv_toUnicode(cnv,&target, targetLimit, &source, sourceLimit, NULL, FALSE, &status);
if(status != U_BUFFER_OVERFLOW_ERROR){
log_err("ucnv_toUnicode call did not succeed. Error: %s\n", u_errorName(status));
}
status = U_ZERO_ERROR;
len = ucnv_toUCountPending(cnv,&status);
/* mid[4] is pending, tail has not been consumed */
if(U_FAILURE(status)){
log_err("ucnv_toUCountPending call did not succeed. Error: %s\n", u_errorName(status));
}
if(len != 4){
log_err("Did not get the expected len for tail.\n");
}
ucnv_close(cnv);
}
#endif
}
static void TestOneDefaultNameChange(const char *name, const char *expected) {
UErrorCode status = U_ZERO_ERROR;
UConverter *cnv;
ucnv_setDefaultName(name);
if(strcmp(ucnv_getDefaultName(), expected)==0)
log_verbose("setDefaultName of %s works.\n", name);
else
log_err("setDefaultName of %s failed\n", name);
cnv=ucnv_open(NULL, &status);
if (U_FAILURE(status) || cnv == NULL) {
log_err("opening the default converter of %s failed\n", name);
return;
}
if(strcmp(ucnv_getName(cnv, &status), expected)==0)
log_verbose("ucnv_getName of %s works.\n", name);
else
log_err("ucnv_getName of %s failed\n", name);
ucnv_close(cnv);
}
static void TestDefaultName(void) {
/*Testing ucnv_getDefaultName() and ucnv_setDefaultNAme()*/
static char defaultName[UCNV_MAX_CONVERTER_NAME_LENGTH + 1];
strcpy(defaultName, ucnv_getDefaultName());
log_verbose("getDefaultName returned %s\n", defaultName);
/*change the default name by setting it */
TestOneDefaultNameChange("UTF-8", "UTF-8");
#if U_CHARSET_IS_UTF8
TestOneDefaultNameChange("ISCII,version=1", "UTF-8");
TestOneDefaultNameChange("ISCII,version=2", "UTF-8");
TestOneDefaultNameChange("ISO-8859-1", "UTF-8");
#else
# if !UCONFIG_NO_LEGACY_CONVERSION && !UCONFIG_ONLY_HTML_CONVERSION
TestOneDefaultNameChange("ISCII,version=1", "ISCII,version=1");
TestOneDefaultNameChange("ISCII,version=2", "ISCII,version=2");
# endif
TestOneDefaultNameChange("ISO-8859-1", "ISO-8859-1");
#endif
/*set the default name back*/
ucnv_setDefaultName(defaultName);
}
/* Test that ucnv_compareNames() matches names according to spec. ----------- */
static int
sign(int n) {
if(n==0) {
return 0;
} else if(n<0) {
return -1;
} else /* n>0 */ {
return 1;
}
}
static void
compareNames(const char **names) {
const char *relation, *name1, *name2;
int rel, result;
relation=*names++;
if(*relation=='=') {
rel = 0;
} else if(*relation=='<') {
rel = -1;
} else {
rel = 1;
}
name1=*names++;
if(name1==NULL) {
return;
}
while((name2=*names++)!=NULL) {
result=ucnv_compareNames(name1, name2);
if(sign(result)!=rel) {
log_err("ucnv_compareNames(\"%s\", \"%s\")=%d, sign!=%d\n", name1, name2, result, rel);
}
name1=name2;
}
}
static void
TestCompareNames() {
static const char *equalUTF8[]={ "=", "UTF-8", "utf_8", "u*T@f08", "Utf 8", NULL };
static const char *equalIBM[]={ "=", "ibm-37", "IBM037", "i-B-m 00037", "ibm-0037", "IBM00037", NULL };
static const char *lessMac[]={ "<", "macos-0_1-10.2", "macos-1-10.0.2", "macos-1-10.2", NULL };
static const char *lessUTF080[]={ "<", "UTF-0008", "utf$080", "u*T@f0800", "Utf 0000000009", NULL };
compareNames(equalUTF8);
compareNames(equalIBM);
compareNames(lessMac);
compareNames(lessUTF080);
}
static void
TestSubstString() {
static const UChar surrogate[1]={ 0xd900 };
char buffer[16];
static const UChar sub[5]={ 0x61, 0x62, 0x63, 0x64, 0x65 };
static const char subChars[5]={ 0x61, 0x62, 0x63, 0x64, 0x65 };
UConverter *cnv;
UErrorCode errorCode;
int32_t length;
int8_t len8;
/* UTF-16/32: test that the BOM is output before the sub character */
errorCode=U_ZERO_ERROR;
cnv=ucnv_open("UTF-16", &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("ucnv_open(UTF-16) failed - %s\n", u_errorName(errorCode));
return;
}
length=ucnv_fromUChars(cnv, buffer, (int32_t)sizeof(buffer), surrogate, 1, &errorCode);
ucnv_close(cnv);
if(U_FAILURE(errorCode) ||
length!=4 ||
NULL == ucnv_detectUnicodeSignature(buffer, length, NULL, &errorCode)
) {
log_err("ucnv_fromUChars(UTF-16, U+D900) did not write a BOM\n");
}
errorCode=U_ZERO_ERROR;
cnv=ucnv_open("UTF-32", &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("ucnv_open(UTF-32) failed - %s\n", u_errorName(errorCode));
return;
}
length=ucnv_fromUChars(cnv, buffer, (int32_t)sizeof(buffer), surrogate, 1, &errorCode);
ucnv_close(cnv);
if(U_FAILURE(errorCode) ||
length!=8 ||
NULL == ucnv_detectUnicodeSignature(buffer, length, NULL, &errorCode)
) {
log_err("ucnv_fromUChars(UTF-32, U+D900) did not write a BOM\n");
}
/* Simple API test of ucnv_setSubstString() + ucnv_getSubstChars(). */
errorCode=U_ZERO_ERROR;
cnv=ucnv_open("ISO-8859-1", &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("ucnv_open(ISO-8859-1) failed - %s\n", u_errorName(errorCode));
return;
}
ucnv_setSubstString(cnv, sub, UPRV_LENGTHOF(sub), &errorCode);
if(U_FAILURE(errorCode)) {
log_err("ucnv_setSubstString(ISO-8859-1, sub[5]) failed - %s\n", u_errorName(errorCode));
} else {
len8 = sizeof(buffer);
ucnv_getSubstChars(cnv, buffer, &len8, &errorCode);
/* Stateless converter, we expect the string converted to charset bytes. */
if(U_FAILURE(errorCode) || len8!=sizeof(subChars) || 0!=uprv_memcmp(buffer, subChars, len8)) {
log_err("ucnv_getSubstChars(ucnv_setSubstString(ISO-8859-1, sub[5])) failed - %s\n", u_errorName(errorCode));
}
}
ucnv_close(cnv);
#if !UCONFIG_NO_LEGACY_CONVERSION
errorCode=U_ZERO_ERROR;
cnv=ucnv_open("HZ", &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("ucnv_open(HZ) failed - %s\n", u_errorName(errorCode));
return;
}
ucnv_setSubstString(cnv, sub, UPRV_LENGTHOF(sub), &errorCode);
if(U_FAILURE(errorCode)) {
log_err("ucnv_setSubstString(HZ, sub[5]) failed - %s\n", u_errorName(errorCode));
} else {
len8 = sizeof(buffer);
ucnv_getSubstChars(cnv, buffer, &len8, &errorCode);
/* Stateful converter, we expect that the Unicode string was set and that we get an empty char * string now. */
if(U_FAILURE(errorCode) || len8!=0) {
log_err("ucnv_getSubstChars(ucnv_setSubstString(HZ, sub[5])) failed - %s\n", u_errorName(errorCode));
}
}
ucnv_close(cnv);
#endif
/*
* Further testing of ucnv_setSubstString() is done via intltest convert.
* We do not test edge cases of illegal arguments and similar because the
* function implementation uses all of its parameters in calls to other
* functions with UErrorCode parameters.
*/
}
static void
InvalidArguments() {
UConverter *cnv;
UErrorCode errorCode;
char charBuffer[2] = {1, 1};
char ucharAsCharBuffer[2] = {2, 2};
char *charsPtr = charBuffer;
UChar *ucharsPtr = (UChar *)ucharAsCharBuffer;
UChar *ucharsBadPtr = (UChar *)(ucharAsCharBuffer + 1);
errorCode=U_ZERO_ERROR;
cnv=ucnv_open("UTF-8", &errorCode);
if(U_FAILURE(errorCode)) {
log_err("ucnv_open() failed - %s\n", u_errorName(errorCode));
return;
}
errorCode=U_ZERO_ERROR;
/* This one should fail because an incomplete UChar is being passed in */
ucnv_fromUnicode(cnv, &charsPtr, charsPtr, (const UChar **)&ucharsPtr, ucharsBadPtr, NULL, TRUE, &errorCode);
if(errorCode != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ucnv_fromUnicode() failed to return U_ILLEGAL_ARGUMENT_ERROR for incomplete UChar * buffer - %s\n", u_errorName(errorCode));
}
errorCode=U_ZERO_ERROR;
/* This one should fail because ucharsBadPtr is > than ucharsPtr */
ucnv_fromUnicode(cnv, &charsPtr, charsPtr, (const UChar **)&ucharsBadPtr, ucharsPtr, NULL, TRUE, &errorCode);
if(errorCode != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ucnv_fromUnicode() failed to return U_ILLEGAL_ARGUMENT_ERROR for bad limit pointer - %s\n", u_errorName(errorCode));
}
errorCode=U_ZERO_ERROR;
/* This one should fail because an incomplete UChar is being passed in */
ucnv_toUnicode(cnv, &ucharsPtr, ucharsBadPtr, (const char **)&charsPtr, charsPtr, NULL, TRUE, &errorCode);
if(errorCode != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ucnv_toUnicode() failed to return U_ILLEGAL_ARGUMENT_ERROR for incomplete UChar * buffer - %s\n", u_errorName(errorCode));
}
errorCode=U_ZERO_ERROR;
/* This one should fail because ucharsBadPtr is > than ucharsPtr */
ucnv_toUnicode(cnv, &ucharsBadPtr, ucharsPtr, (const char **)&charsPtr, charsPtr, NULL, TRUE, &errorCode);
if(errorCode != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ucnv_toUnicode() failed to return U_ILLEGAL_ARGUMENT_ERROR for bad limit pointer - %s\n", u_errorName(errorCode));
}
if (charBuffer[0] != 1 || charBuffer[1] != 1
|| ucharAsCharBuffer[0] != 2 || ucharAsCharBuffer[1] != 2)
{
log_err("Data was incorrectly written to buffers\n");
}
ucnv_close(cnv);
}
static void TestGetName() {
static const char *const names[] = {
"Unicode", "UTF-16",
"UnicodeBigUnmarked", "UTF-16BE",
"UnicodeBig", "UTF-16BE,version=1",
"UnicodeLittleUnmarked", "UTF-16LE",
"UnicodeLittle", "UTF-16LE,version=1",
"x-UTF-16LE-BOM", "UTF-16LE,version=1"
};
int32_t i;
for(i = 0; i < UPRV_LENGTHOF(names); i += 2) {
UErrorCode errorCode = U_ZERO_ERROR;
UConverter *cnv = ucnv_open(names[i], &errorCode);
if(U_SUCCESS(errorCode)) {
const char *name = ucnv_getName(cnv, &errorCode);
if(U_FAILURE(errorCode) || 0 != strcmp(name, names[i+1])) {
log_err("ucnv_getName(%s) = %s != %s -- %s\n",
names[i], name, names[i+1], u_errorName(errorCode));
}
ucnv_close(cnv);
}
}
}
static void TestUTFBOM() {
static const UChar a16[] = { 0x61 };
static const char *const names[] = {
"UTF-16",
"UTF-16,version=1",
"UTF-16BE",
"UnicodeBig",
"UTF-16LE",
"UnicodeLittle"
};
static const uint8_t expected[][5] = {
#if U_IS_BIG_ENDIAN
{ 4, 0xfe, 0xff, 0, 0x61 },
{ 4, 0xfe, 0xff, 0, 0x61 },
#else
{ 4, 0xff, 0xfe, 0x61, 0 },
{ 4, 0xff, 0xfe, 0x61, 0 },
#endif
{ 2, 0, 0x61 },
{ 4, 0xfe, 0xff, 0, 0x61 },
{ 2, 0x61, 0 },
{ 4, 0xff, 0xfe, 0x61, 0 }
};
char bytes[10];
int32_t i;
for(i = 0; i < UPRV_LENGTHOF(names); ++i) {
UErrorCode errorCode = U_ZERO_ERROR;
UConverter *cnv = ucnv_open(names[i], &errorCode);
int32_t length = 0;
const uint8_t *exp = expected[i];
if (U_FAILURE(errorCode)) {
log_err_status(errorCode, "Unable to open converter: %s got error code: %s\n", names[i], u_errorName(errorCode));
continue;
}
length = ucnv_fromUChars(cnv, bytes, (int32_t)sizeof(bytes), a16, 1, &errorCode);
if(U_FAILURE(errorCode) || length != exp[0] || 0 != memcmp(bytes, exp+1, length)) {
log_err("unexpected %s BOM writing behavior -- %s\n",
names[i], u_errorName(errorCode));
}
ucnv_close(cnv);
}
}
| mit |
cpipero/ArduinoLadder | Libs/arduino-1.6.3-windows/arduino-1.6.3/hardware/arduino/avr/firmwares/wifishield/wifi_dnld/src/SOFTWARE_FRAMEWORK/BOARDS/EVK1105/led.c | 680 | 10679 | /* This source file is part of the ATMEL AVR-UC3-SoftwareFramework-1.7.0 Release */
/*This file is prepared for Doxygen automatic documentation generation.*/
/*! \file *********************************************************************
*
* \brief AT32UC3A EVK1105 board LEDs support package.
*
* This file contains definitions and services related to the LED features of
* the EVK1105 board.
*
* - Compiler: IAR EWAVR32 and GNU GCC for AVR32
* - Supported devices: All AVR32 AT32UC3A devices can be used.
* - AppNote:
*
* \author Atmel Corporation: http://www.atmel.com \n
* Support and FAQ: http://support.atmel.no/
*
******************************************************************************/
/* Copyright (c) 2009 Atmel 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:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an Atmel
* AVR product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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 <avr32/io.h>
#include "preprocessor.h"
#include "compiler.h"
#include "evk1105.h"
#include "led.h"
//! Structure describing LED hardware connections.
typedef const struct
{
struct
{
U32 PORT; //!< LED GPIO port.
U32 PIN_MASK; //!< Bit-mask of LED pin in GPIO port.
} GPIO; //!< LED GPIO descriptor.
struct
{
S32 CHANNEL; //!< LED PWM channel (< 0 if N/A).
S32 FUNCTION; //!< LED pin PWM function (< 0 if N/A).
} PWM; //!< LED PWM descriptor.
} tLED_DESCRIPTOR;
//! Hardware descriptors of all LEDs.
static tLED_DESCRIPTOR LED_DESCRIPTOR[LED_COUNT] =
{
#define INSERT_LED_DESCRIPTOR(LED_NO, unused) \
{ \
{LED##LED_NO##_GPIO / 32, 1 << (LED##LED_NO##_GPIO % 32)},\
{LED##LED_NO##_PWM, LED##LED_NO##_PWM_FUNCTION } \
},
MREPEAT(LED_COUNT, INSERT_LED_DESCRIPTOR, ~)
#undef INSERT_LED_DESCRIPTOR
};
//! Saved state of all LEDs.
static volatile U32 LED_State = (1 << LED_COUNT) - 1;
U32 LED_Read_Display(void)
{
return LED_State;
}
void LED_Display(U32 leds)
{
// Use the LED descriptors to get the connections of a given LED to the MCU.
tLED_DESCRIPTOR *led_descriptor;
volatile avr32_gpio_port_t *led_gpio_port;
// Make sure only existing LEDs are specified.
leds &= (1 << LED_COUNT) - 1;
// Update the saved state of all LEDs with the requested changes.
LED_State = leds;
// For all LEDs...
for (led_descriptor = &LED_DESCRIPTOR[0];
led_descriptor < LED_DESCRIPTOR + LED_COUNT;
led_descriptor++)
{
// Set the LED to the requested state.
led_gpio_port = &AVR32_GPIO.port[led_descriptor->GPIO.PORT];
if (leds & 1)
{
led_gpio_port->ovrc = led_descriptor->GPIO.PIN_MASK;
}
else
{
led_gpio_port->ovrs = led_descriptor->GPIO.PIN_MASK;
}
led_gpio_port->oders = led_descriptor->GPIO.PIN_MASK;
led_gpio_port->gpers = led_descriptor->GPIO.PIN_MASK;
leds >>= 1;
}
}
U32 LED_Read_Display_Mask(U32 mask)
{
return Rd_bits(LED_State, mask);
}
void LED_Display_Mask(U32 mask, U32 leds)
{
// Use the LED descriptors to get the connections of a given LED to the MCU.
tLED_DESCRIPTOR *led_descriptor = &LED_DESCRIPTOR[0] - 1;
volatile avr32_gpio_port_t *led_gpio_port;
U8 led_shift;
// Make sure only existing LEDs are specified.
mask &= (1 << LED_COUNT) - 1;
// Update the saved state of all LEDs with the requested changes.
Wr_bits(LED_State, mask, leds);
// While there are specified LEDs left to manage...
while (mask)
{
// Select the next specified LED and set it to the requested state.
led_shift = 1 + ctz(mask);
led_descriptor += led_shift;
led_gpio_port = &AVR32_GPIO.port[led_descriptor->GPIO.PORT];
leds >>= led_shift - 1;
if (leds & 1)
{
led_gpio_port->ovrc = led_descriptor->GPIO.PIN_MASK;
}
else
{
led_gpio_port->ovrs = led_descriptor->GPIO.PIN_MASK;
}
led_gpio_port->oders = led_descriptor->GPIO.PIN_MASK;
led_gpio_port->gpers = led_descriptor->GPIO.PIN_MASK;
leds >>= 1;
mask >>= led_shift;
}
}
Bool LED_Test(U32 leds)
{
return Tst_bits(LED_State, leds);
}
void LED_Off(U32 leds)
{
// Use the LED descriptors to get the connections of a given LED to the MCU.
tLED_DESCRIPTOR *led_descriptor = &LED_DESCRIPTOR[0] - 1;
volatile avr32_gpio_port_t *led_gpio_port;
U8 led_shift;
// Make sure only existing LEDs are specified.
leds &= (1 << LED_COUNT) - 1;
// Update the saved state of all LEDs with the requested changes.
Clr_bits(LED_State, leds);
// While there are specified LEDs left to manage...
while (leds)
{
// Select the next specified LED and turn it off.
led_shift = 1 + ctz(leds);
led_descriptor += led_shift;
led_gpio_port = &AVR32_GPIO.port[led_descriptor->GPIO.PORT];
led_gpio_port->ovrs = led_descriptor->GPIO.PIN_MASK;
led_gpio_port->oders = led_descriptor->GPIO.PIN_MASK;
led_gpio_port->gpers = led_descriptor->GPIO.PIN_MASK;
leds >>= led_shift;
}
}
void LED_On(U32 leds)
{
// Use the LED descriptors to get the connections of a given LED to the MCU.
tLED_DESCRIPTOR *led_descriptor = &LED_DESCRIPTOR[0] - 1;
volatile avr32_gpio_port_t *led_gpio_port;
U8 led_shift;
// Make sure only existing LEDs are specified.
leds &= (1 << LED_COUNT) - 1;
// Update the saved state of all LEDs with the requested changes.
Set_bits(LED_State, leds);
// While there are specified LEDs left to manage...
while (leds)
{
// Select the next specified LED and turn it on.
led_shift = 1 + ctz(leds);
led_descriptor += led_shift;
led_gpio_port = &AVR32_GPIO.port[led_descriptor->GPIO.PORT];
led_gpio_port->ovrc = led_descriptor->GPIO.PIN_MASK;
led_gpio_port->oders = led_descriptor->GPIO.PIN_MASK;
led_gpio_port->gpers = led_descriptor->GPIO.PIN_MASK;
leds >>= led_shift;
}
}
void LED_Toggle(U32 leds)
{
// Use the LED descriptors to get the connections of a given LED to the MCU.
tLED_DESCRIPTOR *led_descriptor = &LED_DESCRIPTOR[0] - 1;
volatile avr32_gpio_port_t *led_gpio_port;
U8 led_shift;
// Make sure only existing LEDs are specified.
leds &= (1 << LED_COUNT) - 1;
// Update the saved state of all LEDs with the requested changes.
Tgl_bits(LED_State, leds);
// While there are specified LEDs left to manage...
while (leds)
{
// Select the next specified LED and toggle it.
led_shift = 1 + ctz(leds);
led_descriptor += led_shift;
led_gpio_port = &AVR32_GPIO.port[led_descriptor->GPIO.PORT];
led_gpio_port->ovrt = led_descriptor->GPIO.PIN_MASK;
led_gpio_port->oders = led_descriptor->GPIO.PIN_MASK;
led_gpio_port->gpers = led_descriptor->GPIO.PIN_MASK;
leds >>= led_shift;
}
}
U32 LED_Read_Display_Field(U32 field)
{
return Rd_bitfield(LED_State, field);
}
void LED_Display_Field(U32 field, U32 leds)
{
// Move the bit-field to the appropriate position for the bit-mask.
LED_Display_Mask(field, leds << ctz(field));
}
U8 LED_Get_Intensity(U32 led)
{
tLED_DESCRIPTOR *led_descriptor;
// Check that the argument value is valid.
led = ctz(led);
led_descriptor = &LED_DESCRIPTOR[led];
if (led >= LED_COUNT || led_descriptor->PWM.CHANNEL < 0) return 0;
// Return the duty cycle value if the LED PWM channel is enabled, else 0.
return (AVR32_PWM.sr & (1 << led_descriptor->PWM.CHANNEL)) ?
AVR32_PWM.channel[led_descriptor->PWM.CHANNEL].cdty : 0;
}
void LED_Set_Intensity(U32 leds, U8 intensity)
{
tLED_DESCRIPTOR *led_descriptor = &LED_DESCRIPTOR[0] - 1;
volatile avr32_pwm_channel_t *led_pwm_channel;
volatile avr32_gpio_port_t *led_gpio_port;
U8 led_shift;
// For each specified LED...
for (leds &= (1 << LED_COUNT) - 1; leds; leds >>= led_shift)
{
// Select the next specified LED and check that it has a PWM channel.
led_shift = 1 + ctz(leds);
led_descriptor += led_shift;
if (led_descriptor->PWM.CHANNEL < 0) continue;
// Initialize or update the LED PWM channel.
led_pwm_channel = &AVR32_PWM.channel[led_descriptor->PWM.CHANNEL];
if (!(AVR32_PWM.sr & (1 << led_descriptor->PWM.CHANNEL)))
{
led_pwm_channel->cmr = (AVR32_PWM_CPRE_MCK << AVR32_PWM_CPRE_OFFSET) &
~(AVR32_PWM_CALG_MASK |
AVR32_PWM_CPOL_MASK |
AVR32_PWM_CPD_MASK);
led_pwm_channel->cprd = 0x000000FF;
led_pwm_channel->cdty = intensity;
AVR32_PWM.ena = 1 << led_descriptor->PWM.CHANNEL;
}
else
{
AVR32_PWM.isr;
while (!(AVR32_PWM.isr & (1 << led_descriptor->PWM.CHANNEL)));
led_pwm_channel->cupd = intensity;
}
// Switch the LED pin to its PWM function.
led_gpio_port = &AVR32_GPIO.port[led_descriptor->GPIO.PORT];
if (led_descriptor->PWM.FUNCTION & 0x1)
{
led_gpio_port->pmr0s = led_descriptor->GPIO.PIN_MASK;
}
else
{
led_gpio_port->pmr0c = led_descriptor->GPIO.PIN_MASK;
}
if (led_descriptor->PWM.FUNCTION & 0x2)
{
led_gpio_port->pmr1s = led_descriptor->GPIO.PIN_MASK;
}
else
{
led_gpio_port->pmr1c = led_descriptor->GPIO.PIN_MASK;
}
led_gpio_port->gperc = led_descriptor->GPIO.PIN_MASK;
}
}
| mit |
dooglus/bitcoin | src/json/json_spirit_reader.cpp | 5033 | 3402 | // Copyright John W. Wilkinson 2007 - 2009.
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.03
#include "json_spirit_reader.h"
#include "json_spirit_reader_template.h"
using namespace json_spirit;
bool json_spirit::read( const std::string& s, Value& value )
{
return read_string( s, value );
}
void json_spirit::read_or_throw( const std::string& s, Value& value )
{
read_string_or_throw( s, value );
}
bool json_spirit::read( std::istream& is, Value& value )
{
return read_stream( is, value );
}
void json_spirit::read_or_throw( std::istream& is, Value& value )
{
read_stream_or_throw( is, value );
}
bool json_spirit::read( std::string::const_iterator& begin, std::string::const_iterator end, Value& value )
{
return read_range( begin, end, value );
}
void json_spirit::read_or_throw( std::string::const_iterator& begin, std::string::const_iterator end, Value& value )
{
begin = read_range_or_throw( begin, end, value );
}
#ifndef BOOST_NO_STD_WSTRING
bool json_spirit::read( const std::wstring& s, wValue& value )
{
return read_string( s, value );
}
void json_spirit::read_or_throw( const std::wstring& s, wValue& value )
{
read_string_or_throw( s, value );
}
bool json_spirit::read( std::wistream& is, wValue& value )
{
return read_stream( is, value );
}
void json_spirit::read_or_throw( std::wistream& is, wValue& value )
{
read_stream_or_throw( is, value );
}
bool json_spirit::read( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wValue& value )
{
return read_range( begin, end, value );
}
void json_spirit::read_or_throw( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wValue& value )
{
begin = read_range_or_throw( begin, end, value );
}
#endif
bool json_spirit::read( const std::string& s, mValue& value )
{
return read_string( s, value );
}
void json_spirit::read_or_throw( const std::string& s, mValue& value )
{
read_string_or_throw( s, value );
}
bool json_spirit::read( std::istream& is, mValue& value )
{
return read_stream( is, value );
}
void json_spirit::read_or_throw( std::istream& is, mValue& value )
{
read_stream_or_throw( is, value );
}
bool json_spirit::read( std::string::const_iterator& begin, std::string::const_iterator end, mValue& value )
{
return read_range( begin, end, value );
}
void json_spirit::read_or_throw( std::string::const_iterator& begin, std::string::const_iterator end, mValue& value )
{
begin = read_range_or_throw( begin, end, value );
}
#ifndef BOOST_NO_STD_WSTRING
bool json_spirit::read( const std::wstring& s, wmValue& value )
{
return read_string( s, value );
}
void json_spirit::read_or_throw( const std::wstring& s, wmValue& value )
{
read_string_or_throw( s, value );
}
bool json_spirit::read( std::wistream& is, wmValue& value )
{
return read_stream( is, value );
}
void json_spirit::read_or_throw( std::wistream& is, wmValue& value )
{
read_stream_or_throw( is, value );
}
bool json_spirit::read( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wmValue& value )
{
return read_range( begin, end, value );
}
void json_spirit::read_or_throw( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wmValue& value )
{
begin = read_range_or_throw( begin, end, value );
}
#endif
| mit |
brextonpham/WinObjC | deps/3rdparty/iculegacy/source/layout/StateTableProcessor.cpp | 178 | 2336 | /*
*
* (C) Copyright IBM Corp. 1998-2004 - All Rights Reserved
*
*/
#include "LETypes.h"
#include "MorphTables.h"
#include "StateTables.h"
#include "MorphStateTables.h"
#include "SubtableProcessor.h"
#include "StateTableProcessor.h"
#include "LEGlyphStorage.h"
#include "LESwaps.h"
U_NAMESPACE_BEGIN
StateTableProcessor::StateTableProcessor()
{
}
StateTableProcessor::StateTableProcessor(const MorphSubtableHeader *morphSubtableHeader)
: SubtableProcessor(morphSubtableHeader)
{
stateTableHeader = (const MorphStateTableHeader *) morphSubtableHeader;
stateSize = SWAPW(stateTableHeader->stHeader.stateSize);
classTableOffset = SWAPW(stateTableHeader->stHeader.classTableOffset);
stateArrayOffset = SWAPW(stateTableHeader->stHeader.stateArrayOffset);
entryTableOffset = SWAPW(stateTableHeader->stHeader.entryTableOffset);
classTable = (const ClassTable *) ((char *) &stateTableHeader->stHeader + classTableOffset);
firstGlyph = SWAPW(classTable->firstGlyph);
lastGlyph = firstGlyph + SWAPW(classTable->nGlyphs);
}
StateTableProcessor::~StateTableProcessor()
{
}
void StateTableProcessor::process(LEGlyphStorage &glyphStorage)
{
// Start at state 0
// XXX: How do we know when to start at state 1?
ByteOffset currentState = stateArrayOffset;
// XXX: reverse?
le_int32 currGlyph = 0;
le_int32 glyphCount = glyphStorage.getGlyphCount();
beginStateTable();
while (currGlyph <= glyphCount) {
ClassCode classCode = classCodeOOB;
if (currGlyph == glyphCount) {
// XXX: How do we handle EOT vs. EOL?
classCode = classCodeEOT;
} else {
TTGlyphID glyphCode = (TTGlyphID) LE_GET_GLYPH(glyphStorage[currGlyph]);
if (glyphCode == 0xFFFF) {
classCode = classCodeDEL;
} else if ((glyphCode >= firstGlyph) && (glyphCode < lastGlyph)) {
classCode = classTable->classArray[glyphCode - firstGlyph];
}
}
const EntryTableIndex *stateArray = (const EntryTableIndex *) ((char *) &stateTableHeader->stHeader + currentState);
EntryTableIndex entryTableIndex = stateArray[(le_uint8)classCode];
currentState = processStateEntry(glyphStorage, currGlyph, entryTableIndex);
}
endStateTable();
}
U_NAMESPACE_END
| mit |
laborautonomo/poedit | deps/icu4c/source/layout/LigatureSubstProc.cpp | 184 | 4702 | /*
*
* (C) Copyright IBM Corp. 1998-2013 - All Rights Reserved
*
*/
#include "LETypes.h"
#include "MorphTables.h"
#include "StateTables.h"
#include "MorphStateTables.h"
#include "SubtableProcessor.h"
#include "StateTableProcessor.h"
#include "LigatureSubstProc.h"
#include "LEGlyphStorage.h"
#include "LESwaps.h"
U_NAMESPACE_BEGIN
#define ExtendedComplement(m) ((le_int32) (~((le_uint32) (m))))
#define SignBit(m) ((ExtendedComplement(m) >> 1) & (le_int32)(m))
#define SignExtend(v,m) (((v) & SignBit(m))? ((v) | ExtendedComplement(m)): (v))
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(LigatureSubstitutionProcessor)
LigatureSubstitutionProcessor::LigatureSubstitutionProcessor(const LEReferenceTo<MorphSubtableHeader> &morphSubtableHeader, LEErrorCode &success)
: StateTableProcessor(morphSubtableHeader, success), ligatureSubstitutionHeader(morphSubtableHeader, success)
{
if(LE_FAILURE(success)) return;
ligatureActionTableOffset = SWAPW(ligatureSubstitutionHeader->ligatureActionTableOffset);
componentTableOffset = SWAPW(ligatureSubstitutionHeader->componentTableOffset);
ligatureTableOffset = SWAPW(ligatureSubstitutionHeader->ligatureTableOffset);
entryTable = LEReferenceToArrayOf<LigatureSubstitutionStateEntry>(stHeader, success, entryTableOffset, LE_UNBOUNDED_ARRAY);
}
LigatureSubstitutionProcessor::~LigatureSubstitutionProcessor()
{
}
void LigatureSubstitutionProcessor::beginStateTable()
{
m = -1;
}
ByteOffset LigatureSubstitutionProcessor::processStateEntry(LEGlyphStorage &glyphStorage, le_int32 &currGlyph, EntryTableIndex index)
{
LEErrorCode success = LE_NO_ERROR;
const LigatureSubstitutionStateEntry *entry = entryTable.getAlias(index, success);
ByteOffset newState = SWAPW(entry->newStateOffset);
le_int16 flags = SWAPW(entry->flags);
if (flags & lsfSetComponent) {
if (++m >= nComponents) {
m = 0;
}
componentStack[m] = currGlyph;
} else if ( m == -1) {
// bad font- skip this glyph.
currGlyph++;
return newState;
}
ByteOffset actionOffset = flags & lsfActionOffsetMask;
if (actionOffset != 0) {
LEReferenceTo<LigatureActionEntry> ap(stHeader, success, actionOffset);
LigatureActionEntry action;
le_int32 offset, i = 0;
le_int32 stack[nComponents];
le_int16 mm = -1;
do {
le_uint32 componentGlyph = componentStack[m--];
action = SWAPL(*ap.getAlias());
ap.addObject(success); // ap++
if (m < 0) {
m = nComponents - 1;
}
offset = action & lafComponentOffsetMask;
if (offset != 0) {
LEReferenceToArrayOf<le_int16> offsetTable(stHeader, success, 2 * SignExtend(offset, lafComponentOffsetMask), LE_UNBOUNDED_ARRAY);
if(LE_FAILURE(success)) {
currGlyph++;
LE_DEBUG_BAD_FONT("off end of ligature substitution header");
return newState; // get out! bad font
}
if(componentGlyph > (le_uint32)glyphStorage.getGlyphCount()) {
LE_DEBUG_BAD_FONT("preposterous componentGlyph");
currGlyph++;
return newState; // get out! bad font
}
i += SWAPW(offsetTable.getObject(LE_GET_GLYPH(glyphStorage[componentGlyph]), success));
if (action & (lafLast | lafStore)) {
LEReferenceTo<TTGlyphID> ligatureOffset(stHeader, success, i);
TTGlyphID ligatureGlyph = SWAPW(*ligatureOffset.getAlias());
glyphStorage[componentGlyph] = LE_SET_GLYPH(glyphStorage[componentGlyph], ligatureGlyph);
if(mm==nComponents) {
LE_DEBUG_BAD_FONT("exceeded nComponents");
mm--; // don't overrun the stack.
}
stack[++mm] = componentGlyph;
i = 0;
} else {
glyphStorage[componentGlyph] = LE_SET_GLYPH(glyphStorage[componentGlyph], 0xFFFF);
}
}
#if LE_ASSERT_BAD_FONT
if(m<0) {
LE_DEBUG_BAD_FONT("m<0")
}
#endif
} while (!(action & lafLast) && (m>=0) ); // stop if last bit is set, or if run out of items
while (mm >= 0) {
if (++m >= nComponents) {
m = 0;
}
componentStack[m] = stack[mm--];
}
}
if (!(flags & lsfDontAdvance)) {
// should handle reverse too!
currGlyph += 1;
}
return newState;
}
void LigatureSubstitutionProcessor::endStateTable()
{
}
U_NAMESPACE_END
| mit |
litshares/litshares | src/test/sigopcount_tests.cpp | 2239 | 1587 | #include <vector>
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include "script.h"
#include "key.h"
using namespace std;
// Helpers:
static std::vector<unsigned char>
Serialize(const CScript& s)
{
std::vector<unsigned char> sSerialized(s);
return sSerialized;
}
BOOST_AUTO_TEST_SUITE(sigopcount_tests)
BOOST_AUTO_TEST_CASE(GetSigOpCount)
{
// Test CScript::GetSigOpCount()
CScript s1;
BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 0);
BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 0);
uint160 dummy;
s1 << OP_1 << dummy << dummy << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 2);
s1 << OP_IF << OP_CHECKSIG << OP_ENDIF;
BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 3);
BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 21);
CScript p2sh;
p2sh.SetDestination(s1.GetID());
CScript scriptSig;
scriptSig << OP_0 << Serialize(s1);
BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig), 3);
std::vector<CKey> keys;
for (int i = 0; i < 3; i++)
{
CKey k;
k.MakeNewKey(true);
keys.push_back(k);
}
CScript s2;
s2.SetMultisig(1, keys);
BOOST_CHECK_EQUAL(s2.GetSigOpCount(true), 3);
BOOST_CHECK_EQUAL(s2.GetSigOpCount(false), 20);
p2sh.SetDestination(s2.GetID());
BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(true), 0);
BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(false), 0);
CScript scriptSig2;
scriptSig2 << OP_1 << dummy << dummy << Serialize(s2);
BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig2), 3);
}
BOOST_AUTO_TEST_SUITE_END()
| mit |
teamblubee/godot | drivers/theora/x86/mmxfrag.c | 194 | 9400 | /********************************************************************
* *
* THIS FILE IS PART OF THE OggTheora SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE Theora SOURCE CODE IS COPYRIGHT (C) 2002-2009 *
* by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
* *
********************************************************************
function:
last mod: $Id: mmxfrag.c 16503 2009-08-22 18:14:02Z giles $
********************************************************************/
/*MMX acceleration of fragment reconstruction for motion compensation.
Originally written by Rudolf Marek.
Additional optimization by Nils Pipenbrinck.
Note: Loops are unrolled for best performance.
The iteration each instruction belongs to is marked in the comments as #i.*/
#include <stddef.h>
#include "x86int.h"
#include "mmxfrag.h"
#if defined(OC_X86_ASM)
/*Copies an 8x8 block of pixels from _src to _dst, assuming _ystride bytes
between rows.*/
void oc_frag_copy_mmx(unsigned char *_dst,
const unsigned char *_src,int _ystride){
OC_FRAG_COPY_MMX(_dst,_src,_ystride);
}
void oc_frag_recon_intra_mmx(unsigned char *_dst,int _ystride,
const ogg_int16_t *_residue){
__asm__ __volatile__(
/*Set mm0 to 0xFFFFFFFFFFFFFFFF.*/
"pcmpeqw %%mm0,%%mm0\n\t"
/*#0 Load low residue.*/
"movq 0*8(%[residue]),%%mm1\n\t"
/*#0 Load high residue.*/
"movq 1*8(%[residue]),%%mm2\n\t"
/*Set mm0 to 0x8000800080008000.*/
"psllw $15,%%mm0\n\t"
/*#1 Load low residue.*/
"movq 2*8(%[residue]),%%mm3\n\t"
/*#1 Load high residue.*/
"movq 3*8(%[residue]),%%mm4\n\t"
/*Set mm0 to 0x0080008000800080.*/
"psrlw $8,%%mm0\n\t"
/*#2 Load low residue.*/
"movq 4*8(%[residue]),%%mm5\n\t"
/*#2 Load high residue.*/
"movq 5*8(%[residue]),%%mm6\n\t"
/*#0 Bias low residue.*/
"paddsw %%mm0,%%mm1\n\t"
/*#0 Bias high residue.*/
"paddsw %%mm0,%%mm2\n\t"
/*#0 Pack to byte.*/
"packuswb %%mm2,%%mm1\n\t"
/*#1 Bias low residue.*/
"paddsw %%mm0,%%mm3\n\t"
/*#1 Bias high residue.*/
"paddsw %%mm0,%%mm4\n\t"
/*#1 Pack to byte.*/
"packuswb %%mm4,%%mm3\n\t"
/*#2 Bias low residue.*/
"paddsw %%mm0,%%mm5\n\t"
/*#2 Bias high residue.*/
"paddsw %%mm0,%%mm6\n\t"
/*#2 Pack to byte.*/
"packuswb %%mm6,%%mm5\n\t"
/*#0 Write row.*/
"movq %%mm1,(%[dst])\n\t"
/*#1 Write row.*/
"movq %%mm3,(%[dst],%[ystride])\n\t"
/*#2 Write row.*/
"movq %%mm5,(%[dst],%[ystride],2)\n\t"
/*#3 Load low residue.*/
"movq 6*8(%[residue]),%%mm1\n\t"
/*#3 Load high residue.*/
"movq 7*8(%[residue]),%%mm2\n\t"
/*#4 Load high residue.*/
"movq 8*8(%[residue]),%%mm3\n\t"
/*#4 Load high residue.*/
"movq 9*8(%[residue]),%%mm4\n\t"
/*#5 Load high residue.*/
"movq 10*8(%[residue]),%%mm5\n\t"
/*#5 Load high residue.*/
"movq 11*8(%[residue]),%%mm6\n\t"
/*#3 Bias low residue.*/
"paddsw %%mm0,%%mm1\n\t"
/*#3 Bias high residue.*/
"paddsw %%mm0,%%mm2\n\t"
/*#3 Pack to byte.*/
"packuswb %%mm2,%%mm1\n\t"
/*#4 Bias low residue.*/
"paddsw %%mm0,%%mm3\n\t"
/*#4 Bias high residue.*/
"paddsw %%mm0,%%mm4\n\t"
/*#4 Pack to byte.*/
"packuswb %%mm4,%%mm3\n\t"
/*#5 Bias low residue.*/
"paddsw %%mm0,%%mm5\n\t"
/*#5 Bias high residue.*/
"paddsw %%mm0,%%mm6\n\t"
/*#5 Pack to byte.*/
"packuswb %%mm6,%%mm5\n\t"
/*#3 Write row.*/
"movq %%mm1,(%[dst],%[ystride3])\n\t"
/*#4 Write row.*/
"movq %%mm3,(%[dst4])\n\t"
/*#5 Write row.*/
"movq %%mm5,(%[dst4],%[ystride])\n\t"
/*#6 Load low residue.*/
"movq 12*8(%[residue]),%%mm1\n\t"
/*#6 Load high residue.*/
"movq 13*8(%[residue]),%%mm2\n\t"
/*#7 Load low residue.*/
"movq 14*8(%[residue]),%%mm3\n\t"
/*#7 Load high residue.*/
"movq 15*8(%[residue]),%%mm4\n\t"
/*#6 Bias low residue.*/
"paddsw %%mm0,%%mm1\n\t"
/*#6 Bias high residue.*/
"paddsw %%mm0,%%mm2\n\t"
/*#6 Pack to byte.*/
"packuswb %%mm2,%%mm1\n\t"
/*#7 Bias low residue.*/
"paddsw %%mm0,%%mm3\n\t"
/*#7 Bias high residue.*/
"paddsw %%mm0,%%mm4\n\t"
/*#7 Pack to byte.*/
"packuswb %%mm4,%%mm3\n\t"
/*#6 Write row.*/
"movq %%mm1,(%[dst4],%[ystride],2)\n\t"
/*#7 Write row.*/
"movq %%mm3,(%[dst4],%[ystride3])\n\t"
:
:[residue]"r"(_residue),
[dst]"r"(_dst),
[dst4]"r"(_dst+(_ystride<<2)),
[ystride]"r"((ptrdiff_t)_ystride),
[ystride3]"r"((ptrdiff_t)_ystride*3)
:"memory"
);
}
void oc_frag_recon_inter_mmx(unsigned char *_dst,const unsigned char *_src,
int _ystride,const ogg_int16_t *_residue){
int i;
/*Zero mm0.*/
__asm__ __volatile__("pxor %%mm0,%%mm0\n\t"::);
for(i=4;i-->0;){
__asm__ __volatile__(
/*#0 Load source.*/
"movq (%[src]),%%mm3\n\t"
/*#1 Load source.*/
"movq (%[src],%[ystride]),%%mm7\n\t"
/*#0 Get copy of src.*/
"movq %%mm3,%%mm4\n\t"
/*#0 Expand high source.*/
"punpckhbw %%mm0,%%mm4\n\t"
/*#0 Expand low source.*/
"punpcklbw %%mm0,%%mm3\n\t"
/*#0 Add residue high.*/
"paddsw 8(%[residue]),%%mm4\n\t"
/*#1 Get copy of src.*/
"movq %%mm7,%%mm2\n\t"
/*#0 Add residue low.*/
"paddsw (%[residue]), %%mm3\n\t"
/*#1 Expand high source.*/
"punpckhbw %%mm0,%%mm2\n\t"
/*#0 Pack final row pixels.*/
"packuswb %%mm4,%%mm3\n\t"
/*#1 Expand low source.*/
"punpcklbw %%mm0,%%mm7\n\t"
/*#1 Add residue low.*/
"paddsw 16(%[residue]),%%mm7\n\t"
/*#1 Add residue high.*/
"paddsw 24(%[residue]),%%mm2\n\t"
/*Advance residue.*/
"lea 32(%[residue]),%[residue]\n\t"
/*#1 Pack final row pixels.*/
"packuswb %%mm2,%%mm7\n\t"
/*Advance src.*/
"lea (%[src],%[ystride],2),%[src]\n\t"
/*#0 Write row.*/
"movq %%mm3,(%[dst])\n\t"
/*#1 Write row.*/
"movq %%mm7,(%[dst],%[ystride])\n\t"
/*Advance dst.*/
"lea (%[dst],%[ystride],2),%[dst]\n\t"
:[residue]"+r"(_residue),[dst]"+r"(_dst),[src]"+r"(_src)
:[ystride]"r"((ptrdiff_t)_ystride)
:"memory"
);
}
}
void oc_frag_recon_inter2_mmx(unsigned char *_dst,const unsigned char *_src1,
const unsigned char *_src2,int _ystride,const ogg_int16_t *_residue){
int i;
/*Zero mm7.*/
__asm__ __volatile__("pxor %%mm7,%%mm7\n\t"::);
for(i=4;i-->0;){
__asm__ __volatile__(
/*#0 Load src1.*/
"movq (%[src1]),%%mm0\n\t"
/*#0 Load src2.*/
"movq (%[src2]),%%mm2\n\t"
/*#0 Copy src1.*/
"movq %%mm0,%%mm1\n\t"
/*#0 Copy src2.*/
"movq %%mm2,%%mm3\n\t"
/*#1 Load src1.*/
"movq (%[src1],%[ystride]),%%mm4\n\t"
/*#0 Unpack lower src1.*/
"punpcklbw %%mm7,%%mm0\n\t"
/*#1 Load src2.*/
"movq (%[src2],%[ystride]),%%mm5\n\t"
/*#0 Unpack higher src1.*/
"punpckhbw %%mm7,%%mm1\n\t"
/*#0 Unpack lower src2.*/
"punpcklbw %%mm7,%%mm2\n\t"
/*#0 Unpack higher src2.*/
"punpckhbw %%mm7,%%mm3\n\t"
/*Advance src1 ptr.*/
"lea (%[src1],%[ystride],2),%[src1]\n\t"
/*Advance src2 ptr.*/
"lea (%[src2],%[ystride],2),%[src2]\n\t"
/*#0 Lower src1+src2.*/
"paddsw %%mm2,%%mm0\n\t"
/*#0 Higher src1+src2.*/
"paddsw %%mm3,%%mm1\n\t"
/*#1 Copy src1.*/
"movq %%mm4,%%mm2\n\t"
/*#0 Build lo average.*/
"psraw $1,%%mm0\n\t"
/*#1 Copy src2.*/
"movq %%mm5,%%mm3\n\t"
/*#1 Unpack lower src1.*/
"punpcklbw %%mm7,%%mm4\n\t"
/*#0 Build hi average.*/
"psraw $1,%%mm1\n\t"
/*#1 Unpack higher src1.*/
"punpckhbw %%mm7,%%mm2\n\t"
/*#0 low+=residue.*/
"paddsw (%[residue]),%%mm0\n\t"
/*#1 Unpack lower src2.*/
"punpcklbw %%mm7,%%mm5\n\t"
/*#0 high+=residue.*/
"paddsw 8(%[residue]),%%mm1\n\t"
/*#1 Unpack higher src2.*/
"punpckhbw %%mm7,%%mm3\n\t"
/*#1 Lower src1+src2.*/
"paddsw %%mm4,%%mm5\n\t"
/*#0 Pack and saturate.*/
"packuswb %%mm1,%%mm0\n\t"
/*#1 Higher src1+src2.*/
"paddsw %%mm2,%%mm3\n\t"
/*#0 Write row.*/
"movq %%mm0,(%[dst])\n\t"
/*#1 Build lo average.*/
"psraw $1,%%mm5\n\t"
/*#1 Build hi average.*/
"psraw $1,%%mm3\n\t"
/*#1 low+=residue.*/
"paddsw 16(%[residue]),%%mm5\n\t"
/*#1 high+=residue.*/
"paddsw 24(%[residue]),%%mm3\n\t"
/*#1 Pack and saturate.*/
"packuswb %%mm3,%%mm5\n\t"
/*#1 Write row ptr.*/
"movq %%mm5,(%[dst],%[ystride])\n\t"
/*Advance residue ptr.*/
"add $32,%[residue]\n\t"
/*Advance dest ptr.*/
"lea (%[dst],%[ystride],2),%[dst]\n\t"
:[dst]"+r"(_dst),[residue]"+r"(_residue),
[src1]"+%r"(_src1),[src2]"+r"(_src2)
:[ystride]"r"((ptrdiff_t)_ystride)
:"memory"
);
}
}
void oc_restore_fpu_mmx(void){
__asm__ __volatile__("emms\n\t");
}
#endif
| mit |
taoguan/WinObjC | deps/3rdparty/icu/icu/source/test/cintltst/utmstest.c | 196 | 17649 | /*
****************************************************************************
* Copyright (c) 1997-2014, International Business Machines Corporation and *
* others. All Rights Reserved. *
****************************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/utmscale.h"
#include "unicode/ucal.h"
#include "cintltst.h"
#include "cmemory.h"
#include <stdlib.h>
#include <time.h>
#define LOOP_COUNT 10000
static void TestAPI(void);
static void TestData(void);
static void TestMonkey(void);
static void TestDotNet(void);
void addUtmsTest(TestNode** root);
void addUtmsTest(TestNode** root)
{
addTest(root, &TestAPI, "tsformat/utmstest/TestAPI");
addTest(root, &TestData, "tsformat/utmstest/TestData");
addTest(root, &TestMonkey, "tsformat/utmstest/TestMonkey");
addTest(root, &TestDotNet, "tsformat/utmstest/TestDotNet");
}
/**
* Return a random int64_t where U_INT64_MIN <= ran <= U_INT64_MAX.
*/
static uint64_t randomInt64(void)
{
int64_t ran = 0;
int32_t i;
static UBool initialized = FALSE;
if (!initialized) {
srand((unsigned)time(NULL));
initialized = TRUE;
}
/* Assume rand has at least 12 bits of precision */
for (i = 0; i < sizeof(ran); i += 1) {
((char*)&ran)[i] = (char)((rand() & 0x0FF0) >> 4);
}
return ran;
}
static int64_t ranInt;
static int64_t ranMin;
static int64_t ranMax;
static void initRandom(int64_t min, int64_t max)
{
uint64_t interval = max - min;
ranMin = min;
ranMax = max;
ranInt = 0;
/* Verify that we don't have a huge interval. */
if (interval < (uint64_t)U_INT64_MAX) {
ranInt = interval;
}
}
static int64_t randomInRange(void)
{
int64_t value;
if (ranInt != 0) {
value = randomInt64() % ranInt;
if (value < 0) {
value = -value;
}
value += ranMin;
} else {
do {
value = randomInt64();
} while (value < ranMin || value > ranMax);
}
return value;
}
static void roundTripTest(int64_t value, UDateTimeScale scale)
{
UErrorCode status = U_ZERO_ERROR;
int64_t rt = utmscale_toInt64(utmscale_fromInt64(value, scale, &status), scale, &status);
if (rt != value) {
log_err("Round-trip error: time scale = %d, value = %lld, round-trip = %lld.\n", scale, value, rt);
}
}
static void toLimitTest(int64_t toLimit, int64_t fromLimit, UDateTimeScale scale)
{
UErrorCode status = U_ZERO_ERROR;
int64_t result = utmscale_toInt64(toLimit, scale, &status);
if (result != fromLimit) {
log_err("toLimit failure: scale = %d, toLimit = %lld , utmscale_toInt64(toLimit, scale, &status) = %lld, fromLimit = %lld.\n",
scale, toLimit, result, fromLimit);
}
}
static void epochOffsetTest(int64_t epochOffset, int64_t units, UDateTimeScale scale)
{
UErrorCode status = U_ZERO_ERROR;
int64_t universal = 0;
int64_t universalEpoch = epochOffset * units;
int64_t local = utmscale_toInt64(universalEpoch, scale, &status);
if (local != 0) {
log_err("utmscale_toInt64(epochOffset, scale, &status): scale = %d epochOffset = %lld, result = %lld.\n", scale, epochOffset, local);
}
local = utmscale_toInt64(0, scale, &status);
if (local != -epochOffset) {
log_err("utmscale_toInt64(0, scale): scale = %d, result = %lld.\n", scale, local);
}
universal = utmscale_fromInt64(-epochOffset, scale, &status);
if (universal != 0) {
log_err("from(-epochOffest, scale): scale = %d, epochOffset = %lld, result = %lld.\n", scale, epochOffset, universal);
}
universal = utmscale_fromInt64(0, scale, &status);
if (universal != universalEpoch) {
log_err("utmscale_fromInt64(0, scale): scale = %d, result = %lld.\n", scale, universal);
}
}
static void TestEpochOffsets(void)
{
UErrorCode status = U_ZERO_ERROR;
int32_t scale;
for (scale = 0; scale < UDTS_MAX_SCALE; scale += 1) {
int64_t units = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_UNITS_VALUE, &status);
int64_t epochOffset = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_EPOCH_OFFSET_VALUE, &status);
epochOffsetTest(epochOffset, units, (UDateTimeScale)scale);
}
}
static void TestFromLimits(void)
{
UErrorCode status = U_ZERO_ERROR;
int32_t scale;
for (scale = 0; scale < UDTS_MAX_SCALE; scale += 1) {
int64_t fromMin = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_FROM_MIN_VALUE, &status);
int64_t fromMax = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_FROM_MAX_VALUE, &status);
roundTripTest(fromMin, (UDateTimeScale)scale);
roundTripTest(fromMax, (UDateTimeScale)scale);
}
}
static void TestToLimits(void)
{
UErrorCode status = U_ZERO_ERROR;
int32_t scale;
for (scale = 0; scale < UDTS_MAX_SCALE; scale += 1) {
int64_t fromMin = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_FROM_MIN_VALUE, &status);
int64_t fromMax = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_FROM_MAX_VALUE, &status);
int64_t toMin = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_TO_MIN_VALUE, &status);
int64_t toMax = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_TO_MAX_VALUE, &status);
toLimitTest(toMin, fromMin, (UDateTimeScale)scale);
toLimitTest(toMax, fromMax, (UDateTimeScale)scale);
}
}
static void TestFromInt64(void)
{
int32_t scale;
int64_t result;
UErrorCode status = U_ZERO_ERROR;
result = utmscale_fromInt64(0, -1, &status);
(void)result; /* Suppress set but not used warning. */
if (status != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_fromInt64(0, -1, status) did not set status to U_ILLEGAL_ARGUMENT_ERROR.\n");
}
for (scale = 0; scale < UDTS_MAX_SCALE; scale += 1) {
int64_t fromMin, fromMax;
status = U_ZERO_ERROR;
fromMin = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_FROM_MIN_VALUE, &status);
fromMax = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_FROM_MAX_VALUE, &status);
status = U_ZERO_ERROR;
result = utmscale_fromInt64(0, (UDateTimeScale)scale, &status);
if (status == U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_fromInt64(0, %d, &status) generated U_ILLEGAL_ARGUMENT_ERROR.\n", scale);
}
status = U_ZERO_ERROR;
result = utmscale_fromInt64(fromMin, (UDateTimeScale)scale, &status);
if (status == U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_fromInt64(fromMin, %d, &status) generated U_ILLEGAL_ARGUMENT_ERROR.\n", scale);
}
if (fromMin > U_INT64_MIN) {
status = U_ZERO_ERROR;
result = utmscale_fromInt64(fromMin - 1, (UDateTimeScale)scale, &status);
if (status != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_fromInt64(fromMin - 1, %d, &status) did not generate U_ILLEGAL_ARGUMENT_ERROR.\n", scale);
}
}
status = U_ZERO_ERROR;
result = utmscale_fromInt64(fromMax, (UDateTimeScale)scale, &status);
if (status == U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_fromInt64(fromMax, %d, &status) generated U_ILLEGAL_ARGUMENT_ERROR.\n", scale);
}
if (fromMax < U_INT64_MAX) {
status = U_ZERO_ERROR;
result = utmscale_fromInt64(fromMax + 1, (UDateTimeScale)scale, &status);
if (status != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_fromInt64(fromMax + 1, %d, &status) didn't generate U_ILLEGAL_ARGUMENT_ERROR.\n", scale);
}
}
}
status = U_ZERO_ERROR;
result = utmscale_fromInt64(0, UDTS_MAX_SCALE, &status);
if (status != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_fromInt64(0, UDTS_MAX_SCALE, &status) did not generate U_ILLEGAL_ARGUMENT_ERROR.\n");
}
}
static void TestToInt64(void)
{
int32_t scale;
int64_t result;
UErrorCode status = U_ZERO_ERROR;
result = utmscale_toInt64(0, -1, &status);
(void)result; /* suppress set but not used warning. */
if (status != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_toInt64(0, -1, &status) did not generate U_ILLEGAL_ARGUMENT_ERROR.\n");
}
for (scale = 0; scale < UDTS_MAX_SCALE; scale += 1) {
int64_t toMin, toMax;
status = U_ZERO_ERROR;
toMin = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_TO_MIN_VALUE, &status);
toMax = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_TO_MAX_VALUE, &status);
status = U_ZERO_ERROR;
result = utmscale_toInt64(0, (UDateTimeScale)scale, &status);
if (status == U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_toInt64(0, %d, &status) generated U_ILLEGAL_ARGUMENT_ERROR.\n", scale);
}
status = U_ZERO_ERROR;
result = utmscale_toInt64(toMin, (UDateTimeScale)scale, &status);
if (status == U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_toInt64(toMin, %d, &status) generated U_ILLEGAL_ARGUMENT_ERROR.\n", scale);
}
if (toMin > U_INT64_MIN) {
status = U_ZERO_ERROR;
result = utmscale_toInt64(toMin - 1, (UDateTimeScale)scale, &status);
if (status != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_toInt64(toMin - 1, %d, &status) did not generate U_ILLEGAL_ARGUMENT_ERROR.\n", scale);
}
}
status = U_ZERO_ERROR;
result = utmscale_toInt64(toMax, (UDateTimeScale)scale, &status);
if (status == U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_toInt64(toMax, %d, &status) generated U_ILLEGAL_ARGUMENT_ERROR.\n", scale);
}
if (toMax < U_INT64_MAX) {
status = U_ZERO_ERROR;
result = utmscale_toInt64(toMax + 1, (UDateTimeScale)scale, &status);
if (status != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_toInt64(toMax + 1, %d, &status) did not generate U_ILLEGAL_ARGUMENT_ERROR.\n", scale);
}
}
}
status = U_ZERO_ERROR;
result = utmscale_toInt64(0, UDTS_MAX_SCALE, &status);
if (status != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("utmscale_toInt64(0, UDTS_MAX_SCALE, &status) did not generate U_ILLEGAL_ARGUMENT_ERROR.\n");
}
}
static void TestAPI(void)
{
TestFromInt64();
TestToInt64();
}
static void TestData(void)
{
TestEpochOffsets();
TestFromLimits();
TestToLimits();
}
static void TestMonkey(void)
{
int32_t scale;
UErrorCode status = U_ZERO_ERROR;
for (scale = 0; scale < UDTS_MAX_SCALE; scale += 1) {
int64_t fromMin = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_FROM_MIN_VALUE, &status);
int64_t fromMax = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_FROM_MAX_VALUE, &status);
int32_t i;
initRandom(fromMin, fromMax);
for (i = 0; i < LOOP_COUNT; i += 1) {
int64_t value = randomInRange();
roundTripTest(value, (UDateTimeScale)scale);
}
}
}
struct DotNetDateTimeTicks {
int32_t year;
int32_t month;
int32_t day;
int64_t ticks;
};
typedef struct DotNetDateTimeTicks DotNetDateTimeTicks;
/*
* This data was generated by C++.Net code like
* Console::WriteLine(L" {{ {0}, 1, 1, INT64_C({1}) }},", year, DateTime(year, 1, 1).Ticks);
* with the DateTime constructor taking int values for year, month, and date.
*/
static const DotNetDateTimeTicks dotNetDateTimeTicks[]={
/* year, month, day, ticks */
{ 100, 1, 1, INT64_C(31241376000000000) },
{ 100, 3, 1, INT64_C(31292352000000000) },
{ 200, 1, 1, INT64_C(62798112000000000) },
{ 200, 3, 1, INT64_C(62849088000000000) },
{ 300, 1, 1, INT64_C(94354848000000000) },
{ 300, 3, 1, INT64_C(94405824000000000) },
{ 400, 1, 1, INT64_C(125911584000000000) },
{ 400, 3, 1, INT64_C(125963424000000000) },
{ 500, 1, 1, INT64_C(157469184000000000) },
{ 500, 3, 1, INT64_C(157520160000000000) },
{ 600, 1, 1, INT64_C(189025920000000000) },
{ 600, 3, 1, INT64_C(189076896000000000) },
{ 700, 1, 1, INT64_C(220582656000000000) },
{ 700, 3, 1, INT64_C(220633632000000000) },
{ 800, 1, 1, INT64_C(252139392000000000) },
{ 800, 3, 1, INT64_C(252191232000000000) },
{ 900, 1, 1, INT64_C(283696992000000000) },
{ 900, 3, 1, INT64_C(283747968000000000) },
{ 1000, 1, 1, INT64_C(315253728000000000) },
{ 1000, 3, 1, INT64_C(315304704000000000) },
{ 1100, 1, 1, INT64_C(346810464000000000) },
{ 1100, 3, 1, INT64_C(346861440000000000) },
{ 1200, 1, 1, INT64_C(378367200000000000) },
{ 1200, 3, 1, INT64_C(378419040000000000) },
{ 1300, 1, 1, INT64_C(409924800000000000) },
{ 1300, 3, 1, INT64_C(409975776000000000) },
{ 1400, 1, 1, INT64_C(441481536000000000) },
{ 1400, 3, 1, INT64_C(441532512000000000) },
{ 1500, 1, 1, INT64_C(473038272000000000) },
{ 1500, 3, 1, INT64_C(473089248000000000) },
{ 1600, 1, 1, INT64_C(504595008000000000) },
{ 1600, 3, 1, INT64_C(504646848000000000) },
{ 1700, 1, 1, INT64_C(536152608000000000) },
{ 1700, 3, 1, INT64_C(536203584000000000) },
{ 1800, 1, 1, INT64_C(567709344000000000) },
{ 1800, 3, 1, INT64_C(567760320000000000) },
{ 1900, 1, 1, INT64_C(599266080000000000) },
{ 1900, 3, 1, INT64_C(599317056000000000) },
{ 2000, 1, 1, INT64_C(630822816000000000) },
{ 2000, 3, 1, INT64_C(630874656000000000) },
{ 2100, 1, 1, INT64_C(662380416000000000) },
{ 2100, 3, 1, INT64_C(662431392000000000) },
{ 2200, 1, 1, INT64_C(693937152000000000) },
{ 2200, 3, 1, INT64_C(693988128000000000) },
{ 2300, 1, 1, INT64_C(725493888000000000) },
{ 2300, 3, 1, INT64_C(725544864000000000) },
{ 2400, 1, 1, INT64_C(757050624000000000) },
{ 2400, 3, 1, INT64_C(757102464000000000) },
{ 2500, 1, 1, INT64_C(788608224000000000) },
{ 2500, 3, 1, INT64_C(788659200000000000) },
{ 2600, 1, 1, INT64_C(820164960000000000) },
{ 2600, 3, 1, INT64_C(820215936000000000) },
{ 2700, 1, 1, INT64_C(851721696000000000) },
{ 2700, 3, 1, INT64_C(851772672000000000) },
{ 2800, 1, 1, INT64_C(883278432000000000) },
{ 2800, 3, 1, INT64_C(883330272000000000) },
{ 2900, 1, 1, INT64_C(914836032000000000) },
{ 2900, 3, 1, INT64_C(914887008000000000) },
{ 3000, 1, 1, INT64_C(946392768000000000) },
{ 3000, 3, 1, INT64_C(946443744000000000) },
{ 1, 1, 1, INT64_C(0) },
{ 1601, 1, 1, INT64_C(504911232000000000) },
{ 1899, 12, 31, INT64_C(599265216000000000) },
{ 1904, 1, 1, INT64_C(600527520000000000) },
{ 1970, 1, 1, INT64_C(621355968000000000) },
{ 2001, 1, 1, INT64_C(631139040000000000) },
{ 9900, 3, 1, INT64_C(3123873216000000000) },
{ 9999, 12, 31, INT64_C(3155378112000000000) }
};
/*
* ICU's Universal Time Scale is designed to be tick-for-tick compatible with
* .Net System.DateTime. Verify that this is so for the
* .Net-supported date range (years 1-9999 AD).
* This requires a proleptic Gregorian calendar because that's what .Net uses.
* Proleptic: No Julian/Gregorian switchover, or a switchover before
* any date that we test, that is, before 0001 AD.
*/
static void
TestDotNet() {
static const UChar utc[] = { 0x45, 0x74, 0x63, 0x2f, 0x47, 0x4d, 0x54, 0 }; /* "Etc/GMT" */
const int32_t dayMillis = 86400 * INT64_C(1000); /* 1 day = 86400 seconds */
const int64_t dayTicks = 86400 * INT64_C(10000000);
const DotNetDateTimeTicks *dt;
UCalendar *cal;
UErrorCode errorCode;
UDate icuDate;
int64_t ticks, millis;
int32_t i;
/* Open a proleptic Gregorian calendar. */
errorCode = U_ZERO_ERROR;
cal = ucal_open(utc, -1, "", UCAL_GREGORIAN, &errorCode);
ucal_setGregorianChange(cal, -1000000 * (dayMillis * (UDate)1), &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("ucal_open(UTC/proleptic Gregorian) failed: %s - (Are you missing data?)\n", u_errorName(errorCode));
ucal_close(cal);
return;
}
for(i = 0; i < UPRV_LENGTHOF(dotNetDateTimeTicks); ++i) {
/* Test conversion from .Net/Universal time to ICU time. */
dt = dotNetDateTimeTicks + i;
millis = utmscale_toInt64(dt->ticks, UDTS_ICU4C_TIME, &errorCode);
ucal_clear(cal);
ucal_setDate(cal, dt->year, dt->month - 1, dt->day, &errorCode); /* Java & ICU use January = month 0. */
icuDate = ucal_getMillis(cal, &errorCode);
if(millis != icuDate) {
/* Print days not millis to stay within printf() range. */
log_err("utmscale_toInt64(ticks[%d], ICU4C)=%dd != %dd=ucal_getMillis(%04d-%02d-%02d)\n",
(int)i, (int)(millis/dayMillis), (int)(icuDate/dayMillis), (int)dt->year, (int)dt->month, (int)dt->day);
}
/* Test conversion from ICU time to .Net/Universal time. */
ticks = utmscale_fromInt64((int64_t)icuDate, UDTS_ICU4C_TIME, &errorCode);
if(ticks != dt->ticks) {
/* Print days not ticks to stay within printf() range. */
log_err("utmscale_fromInt64(date[%d], ICU4C)=%dd != %dd=.Net System.DateTime(%04d-%02d-%02d).Ticks\n",
(int)i, (int)(ticks/dayTicks), (int)(dt->ticks/dayTicks), (int)dt->year, (int)dt->month, (int)dt->day);
}
}
ucal_close(cal);
}
#endif /* #if !UCONFIG_NO_FORMATTING */
| mit |
jianwoo/WinObjC | deps/3rdparty/icu/icu/source/i18n/rbt_data.cpp | 196 | 3438 | /*
**********************************************************************
* Copyright (C) 1999-2014, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Date Name Description
* 11/17/99 aliu Creation.
**********************************************************************
*/
#include "unicode/utypes.h"
#include "umutex.h"
#if !UCONFIG_NO_TRANSLITERATION
#include "unicode/unistr.h"
#include "unicode/uniset.h"
#include "rbt_data.h"
#include "hash.h"
#include "cmemory.h"
U_NAMESPACE_BEGIN
TransliterationRuleData::TransliterationRuleData(UErrorCode& status)
: UMemory(), ruleSet(status), variableNames(status),
variables(0), variablesAreOwned(TRUE)
{
if (U_FAILURE(status)) {
return;
}
variableNames.setValueDeleter(uprv_deleteUObject);
variables = 0;
variablesLength = 0;
}
TransliterationRuleData::TransliterationRuleData(const TransliterationRuleData& other) :
UMemory(other), ruleSet(other.ruleSet),
variablesAreOwned(TRUE),
variablesBase(other.variablesBase),
variablesLength(other.variablesLength)
{
UErrorCode status = U_ZERO_ERROR;
int32_t i = 0;
variableNames.setValueDeleter(uprv_deleteUObject);
int32_t pos = UHASH_FIRST;
const UHashElement *e;
while ((e = other.variableNames.nextElement(pos)) != 0) {
UnicodeString* value =
new UnicodeString(*(const UnicodeString*)e->value.pointer);
// Exit out if value could not be created.
if (value == NULL) {
return;
}
variableNames.put(*(UnicodeString*)e->key.pointer, value, status);
}
variables = 0;
if (other.variables != 0) {
variables = (UnicodeFunctor **)uprv_malloc(variablesLength * sizeof(UnicodeFunctor *));
/* test for NULL */
if (variables == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
for (i=0; i<variablesLength; ++i) {
variables[i] = other.variables[i]->clone();
if (variables[i] == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
break;
}
}
}
// Remove the array and exit if memory allocation error occured.
if (U_FAILURE(status)) {
for (int32_t n = i-1; n >= 0; n--) {
delete variables[n];
}
uprv_free(variables);
variables = NULL;
return;
}
// Do this last, _after_ setting up variables[].
ruleSet.setData(this); // ruleSet must already be frozen
}
TransliterationRuleData::~TransliterationRuleData() {
if (variablesAreOwned && variables != 0) {
for (int32_t i=0; i<variablesLength; ++i) {
delete variables[i];
}
}
uprv_free(variables);
}
UnicodeFunctor*
TransliterationRuleData::lookup(UChar32 standIn) const {
int32_t i = standIn - variablesBase;
return (i >= 0 && i < variablesLength) ? variables[i] : 0;
}
UnicodeMatcher*
TransliterationRuleData::lookupMatcher(UChar32 standIn) const {
UnicodeFunctor *f = lookup(standIn);
return (f != 0) ? f->toMatcher() : 0;
}
UnicodeReplacer*
TransliterationRuleData::lookupReplacer(UChar32 standIn) const {
UnicodeFunctor *f = lookup(standIn);
return (f != 0) ? f->toReplacer() : 0;
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_TRANSLITERATION */
| mit |
menlatin/flappycoin | src/leveldb/db/c_test.c | 4294 | 11634 | /* Copyright (c) 2011 The LevelDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. See the AUTHORS file for names of contributors. */
#include "leveldb/c.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
const char* phase = "";
static char dbname[200];
static void StartPhase(const char* name) {
fprintf(stderr, "=== Test %s\n", name);
phase = name;
}
static const char* GetTempDir(void) {
const char* ret = getenv("TEST_TMPDIR");
if (ret == NULL || ret[0] == '\0')
ret = "/tmp";
return ret;
}
#define CheckNoError(err) \
if ((err) != NULL) { \
fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, phase, (err)); \
abort(); \
}
#define CheckCondition(cond) \
if (!(cond)) { \
fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, phase, #cond); \
abort(); \
}
static void CheckEqual(const char* expected, const char* v, size_t n) {
if (expected == NULL && v == NULL) {
// ok
} else if (expected != NULL && v != NULL && n == strlen(expected) &&
memcmp(expected, v, n) == 0) {
// ok
return;
} else {
fprintf(stderr, "%s: expected '%s', got '%s'\n",
phase,
(expected ? expected : "(null)"),
(v ? v : "(null"));
abort();
}
}
static void Free(char** ptr) {
if (*ptr) {
free(*ptr);
*ptr = NULL;
}
}
static void CheckGet(
leveldb_t* db,
const leveldb_readoptions_t* options,
const char* key,
const char* expected) {
char* err = NULL;
size_t val_len;
char* val;
val = leveldb_get(db, options, key, strlen(key), &val_len, &err);
CheckNoError(err);
CheckEqual(expected, val, val_len);
Free(&val);
}
static void CheckIter(leveldb_iterator_t* iter,
const char* key, const char* val) {
size_t len;
const char* str;
str = leveldb_iter_key(iter, &len);
CheckEqual(key, str, len);
str = leveldb_iter_value(iter, &len);
CheckEqual(val, str, len);
}
// Callback from leveldb_writebatch_iterate()
static void CheckPut(void* ptr,
const char* k, size_t klen,
const char* v, size_t vlen) {
int* state = (int*) ptr;
CheckCondition(*state < 2);
switch (*state) {
case 0:
CheckEqual("bar", k, klen);
CheckEqual("b", v, vlen);
break;
case 1:
CheckEqual("box", k, klen);
CheckEqual("c", v, vlen);
break;
}
(*state)++;
}
// Callback from leveldb_writebatch_iterate()
static void CheckDel(void* ptr, const char* k, size_t klen) {
int* state = (int*) ptr;
CheckCondition(*state == 2);
CheckEqual("bar", k, klen);
(*state)++;
}
static void CmpDestroy(void* arg) { }
static int CmpCompare(void* arg, const char* a, size_t alen,
const char* b, size_t blen) {
int n = (alen < blen) ? alen : blen;
int r = memcmp(a, b, n);
if (r == 0) {
if (alen < blen) r = -1;
else if (alen > blen) r = +1;
}
return r;
}
static const char* CmpName(void* arg) {
return "foo";
}
// Custom filter policy
static unsigned char fake_filter_result = 1;
static void FilterDestroy(void* arg) { }
static const char* FilterName(void* arg) {
return "TestFilter";
}
static char* FilterCreate(
void* arg,
const char* const* key_array, const size_t* key_length_array,
int num_keys,
size_t* filter_length) {
*filter_length = 4;
char* result = malloc(4);
memcpy(result, "fake", 4);
return result;
}
unsigned char FilterKeyMatch(
void* arg,
const char* key, size_t length,
const char* filter, size_t filter_length) {
CheckCondition(filter_length == 4);
CheckCondition(memcmp(filter, "fake", 4) == 0);
return fake_filter_result;
}
int main(int argc, char** argv) {
leveldb_t* db;
leveldb_comparator_t* cmp;
leveldb_cache_t* cache;
leveldb_env_t* env;
leveldb_options_t* options;
leveldb_readoptions_t* roptions;
leveldb_writeoptions_t* woptions;
char* err = NULL;
int run = -1;
CheckCondition(leveldb_major_version() >= 1);
CheckCondition(leveldb_minor_version() >= 1);
snprintf(dbname, sizeof(dbname),
"%s/leveldb_c_test-%d",
GetTempDir(),
((int) geteuid()));
StartPhase("create_objects");
cmp = leveldb_comparator_create(NULL, CmpDestroy, CmpCompare, CmpName);
env = leveldb_create_default_env();
cache = leveldb_cache_create_lru(100000);
options = leveldb_options_create();
leveldb_options_set_comparator(options, cmp);
leveldb_options_set_error_if_exists(options, 1);
leveldb_options_set_cache(options, cache);
leveldb_options_set_env(options, env);
leveldb_options_set_info_log(options, NULL);
leveldb_options_set_write_buffer_size(options, 100000);
leveldb_options_set_paranoid_checks(options, 1);
leveldb_options_set_max_open_files(options, 10);
leveldb_options_set_block_size(options, 1024);
leveldb_options_set_block_restart_interval(options, 8);
leveldb_options_set_compression(options, leveldb_no_compression);
roptions = leveldb_readoptions_create();
leveldb_readoptions_set_verify_checksums(roptions, 1);
leveldb_readoptions_set_fill_cache(roptions, 0);
woptions = leveldb_writeoptions_create();
leveldb_writeoptions_set_sync(woptions, 1);
StartPhase("destroy");
leveldb_destroy_db(options, dbname, &err);
Free(&err);
StartPhase("open_error");
db = leveldb_open(options, dbname, &err);
CheckCondition(err != NULL);
Free(&err);
StartPhase("leveldb_free");
db = leveldb_open(options, dbname, &err);
CheckCondition(err != NULL);
leveldb_free(err);
err = NULL;
StartPhase("open");
leveldb_options_set_create_if_missing(options, 1);
db = leveldb_open(options, dbname, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", NULL);
StartPhase("put");
leveldb_put(db, woptions, "foo", 3, "hello", 5, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", "hello");
StartPhase("compactall");
leveldb_compact_range(db, NULL, 0, NULL, 0);
CheckGet(db, roptions, "foo", "hello");
StartPhase("compactrange");
leveldb_compact_range(db, "a", 1, "z", 1);
CheckGet(db, roptions, "foo", "hello");
StartPhase("writebatch");
{
leveldb_writebatch_t* wb = leveldb_writebatch_create();
leveldb_writebatch_put(wb, "foo", 3, "a", 1);
leveldb_writebatch_clear(wb);
leveldb_writebatch_put(wb, "bar", 3, "b", 1);
leveldb_writebatch_put(wb, "box", 3, "c", 1);
leveldb_writebatch_delete(wb, "bar", 3);
leveldb_write(db, woptions, wb, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", "hello");
CheckGet(db, roptions, "bar", NULL);
CheckGet(db, roptions, "box", "c");
int pos = 0;
leveldb_writebatch_iterate(wb, &pos, CheckPut, CheckDel);
CheckCondition(pos == 3);
leveldb_writebatch_destroy(wb);
}
StartPhase("iter");
{
leveldb_iterator_t* iter = leveldb_create_iterator(db, roptions);
CheckCondition(!leveldb_iter_valid(iter));
leveldb_iter_seek_to_first(iter);
CheckCondition(leveldb_iter_valid(iter));
CheckIter(iter, "box", "c");
leveldb_iter_next(iter);
CheckIter(iter, "foo", "hello");
leveldb_iter_prev(iter);
CheckIter(iter, "box", "c");
leveldb_iter_prev(iter);
CheckCondition(!leveldb_iter_valid(iter));
leveldb_iter_seek_to_last(iter);
CheckIter(iter, "foo", "hello");
leveldb_iter_seek(iter, "b", 1);
CheckIter(iter, "box", "c");
leveldb_iter_get_error(iter, &err);
CheckNoError(err);
leveldb_iter_destroy(iter);
}
StartPhase("approximate_sizes");
{
int i;
int n = 20000;
char keybuf[100];
char valbuf[100];
uint64_t sizes[2];
const char* start[2] = { "a", "k00000000000000010000" };
size_t start_len[2] = { 1, 21 };
const char* limit[2] = { "k00000000000000010000", "z" };
size_t limit_len[2] = { 21, 1 };
leveldb_writeoptions_set_sync(woptions, 0);
for (i = 0; i < n; i++) {
snprintf(keybuf, sizeof(keybuf), "k%020d", i);
snprintf(valbuf, sizeof(valbuf), "v%020d", i);
leveldb_put(db, woptions, keybuf, strlen(keybuf), valbuf, strlen(valbuf),
&err);
CheckNoError(err);
}
leveldb_approximate_sizes(db, 2, start, start_len, limit, limit_len, sizes);
CheckCondition(sizes[0] > 0);
CheckCondition(sizes[1] > 0);
}
StartPhase("property");
{
char* prop = leveldb_property_value(db, "nosuchprop");
CheckCondition(prop == NULL);
prop = leveldb_property_value(db, "leveldb.stats");
CheckCondition(prop != NULL);
Free(&prop);
}
StartPhase("snapshot");
{
const leveldb_snapshot_t* snap;
snap = leveldb_create_snapshot(db);
leveldb_delete(db, woptions, "foo", 3, &err);
CheckNoError(err);
leveldb_readoptions_set_snapshot(roptions, snap);
CheckGet(db, roptions, "foo", "hello");
leveldb_readoptions_set_snapshot(roptions, NULL);
CheckGet(db, roptions, "foo", NULL);
leveldb_release_snapshot(db, snap);
}
StartPhase("repair");
{
leveldb_close(db);
leveldb_options_set_create_if_missing(options, 0);
leveldb_options_set_error_if_exists(options, 0);
leveldb_repair_db(options, dbname, &err);
CheckNoError(err);
db = leveldb_open(options, dbname, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", NULL);
CheckGet(db, roptions, "bar", NULL);
CheckGet(db, roptions, "box", "c");
leveldb_options_set_create_if_missing(options, 1);
leveldb_options_set_error_if_exists(options, 1);
}
StartPhase("filter");
for (run = 0; run < 2; run++) {
// First run uses custom filter, second run uses bloom filter
CheckNoError(err);
leveldb_filterpolicy_t* policy;
if (run == 0) {
policy = leveldb_filterpolicy_create(
NULL, FilterDestroy, FilterCreate, FilterKeyMatch, FilterName);
} else {
policy = leveldb_filterpolicy_create_bloom(10);
}
// Create new database
leveldb_close(db);
leveldb_destroy_db(options, dbname, &err);
leveldb_options_set_filter_policy(options, policy);
db = leveldb_open(options, dbname, &err);
CheckNoError(err);
leveldb_put(db, woptions, "foo", 3, "foovalue", 8, &err);
CheckNoError(err);
leveldb_put(db, woptions, "bar", 3, "barvalue", 8, &err);
CheckNoError(err);
leveldb_compact_range(db, NULL, 0, NULL, 0);
fake_filter_result = 1;
CheckGet(db, roptions, "foo", "foovalue");
CheckGet(db, roptions, "bar", "barvalue");
if (phase == 0) {
// Must not find value when custom filter returns false
fake_filter_result = 0;
CheckGet(db, roptions, "foo", NULL);
CheckGet(db, roptions, "bar", NULL);
fake_filter_result = 1;
CheckGet(db, roptions, "foo", "foovalue");
CheckGet(db, roptions, "bar", "barvalue");
}
leveldb_options_set_filter_policy(options, NULL);
leveldb_filterpolicy_destroy(policy);
}
StartPhase("cleanup");
leveldb_close(db);
leveldb_options_destroy(options);
leveldb_readoptions_destroy(roptions);
leveldb_writeoptions_destroy(woptions);
leveldb_cache_destroy(cache);
leveldb_comparator_destroy(cmp);
leveldb_env_destroy(env);
fprintf(stderr, "PASS\n");
return 0;
}
| mit |
VvXx/VvXx-master | src/leveldb/db/c_test.c | 4294 | 11634 | /* Copyright (c) 2011 The LevelDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. See the AUTHORS file for names of contributors. */
#include "leveldb/c.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
const char* phase = "";
static char dbname[200];
static void StartPhase(const char* name) {
fprintf(stderr, "=== Test %s\n", name);
phase = name;
}
static const char* GetTempDir(void) {
const char* ret = getenv("TEST_TMPDIR");
if (ret == NULL || ret[0] == '\0')
ret = "/tmp";
return ret;
}
#define CheckNoError(err) \
if ((err) != NULL) { \
fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, phase, (err)); \
abort(); \
}
#define CheckCondition(cond) \
if (!(cond)) { \
fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, phase, #cond); \
abort(); \
}
static void CheckEqual(const char* expected, const char* v, size_t n) {
if (expected == NULL && v == NULL) {
// ok
} else if (expected != NULL && v != NULL && n == strlen(expected) &&
memcmp(expected, v, n) == 0) {
// ok
return;
} else {
fprintf(stderr, "%s: expected '%s', got '%s'\n",
phase,
(expected ? expected : "(null)"),
(v ? v : "(null"));
abort();
}
}
static void Free(char** ptr) {
if (*ptr) {
free(*ptr);
*ptr = NULL;
}
}
static void CheckGet(
leveldb_t* db,
const leveldb_readoptions_t* options,
const char* key,
const char* expected) {
char* err = NULL;
size_t val_len;
char* val;
val = leveldb_get(db, options, key, strlen(key), &val_len, &err);
CheckNoError(err);
CheckEqual(expected, val, val_len);
Free(&val);
}
static void CheckIter(leveldb_iterator_t* iter,
const char* key, const char* val) {
size_t len;
const char* str;
str = leveldb_iter_key(iter, &len);
CheckEqual(key, str, len);
str = leveldb_iter_value(iter, &len);
CheckEqual(val, str, len);
}
// Callback from leveldb_writebatch_iterate()
static void CheckPut(void* ptr,
const char* k, size_t klen,
const char* v, size_t vlen) {
int* state = (int*) ptr;
CheckCondition(*state < 2);
switch (*state) {
case 0:
CheckEqual("bar", k, klen);
CheckEqual("b", v, vlen);
break;
case 1:
CheckEqual("box", k, klen);
CheckEqual("c", v, vlen);
break;
}
(*state)++;
}
// Callback from leveldb_writebatch_iterate()
static void CheckDel(void* ptr, const char* k, size_t klen) {
int* state = (int*) ptr;
CheckCondition(*state == 2);
CheckEqual("bar", k, klen);
(*state)++;
}
static void CmpDestroy(void* arg) { }
static int CmpCompare(void* arg, const char* a, size_t alen,
const char* b, size_t blen) {
int n = (alen < blen) ? alen : blen;
int r = memcmp(a, b, n);
if (r == 0) {
if (alen < blen) r = -1;
else if (alen > blen) r = +1;
}
return r;
}
static const char* CmpName(void* arg) {
return "foo";
}
// Custom filter policy
static unsigned char fake_filter_result = 1;
static void FilterDestroy(void* arg) { }
static const char* FilterName(void* arg) {
return "TestFilter";
}
static char* FilterCreate(
void* arg,
const char* const* key_array, const size_t* key_length_array,
int num_keys,
size_t* filter_length) {
*filter_length = 4;
char* result = malloc(4);
memcpy(result, "fake", 4);
return result;
}
unsigned char FilterKeyMatch(
void* arg,
const char* key, size_t length,
const char* filter, size_t filter_length) {
CheckCondition(filter_length == 4);
CheckCondition(memcmp(filter, "fake", 4) == 0);
return fake_filter_result;
}
int main(int argc, char** argv) {
leveldb_t* db;
leveldb_comparator_t* cmp;
leveldb_cache_t* cache;
leveldb_env_t* env;
leveldb_options_t* options;
leveldb_readoptions_t* roptions;
leveldb_writeoptions_t* woptions;
char* err = NULL;
int run = -1;
CheckCondition(leveldb_major_version() >= 1);
CheckCondition(leveldb_minor_version() >= 1);
snprintf(dbname, sizeof(dbname),
"%s/leveldb_c_test-%d",
GetTempDir(),
((int) geteuid()));
StartPhase("create_objects");
cmp = leveldb_comparator_create(NULL, CmpDestroy, CmpCompare, CmpName);
env = leveldb_create_default_env();
cache = leveldb_cache_create_lru(100000);
options = leveldb_options_create();
leveldb_options_set_comparator(options, cmp);
leveldb_options_set_error_if_exists(options, 1);
leveldb_options_set_cache(options, cache);
leveldb_options_set_env(options, env);
leveldb_options_set_info_log(options, NULL);
leveldb_options_set_write_buffer_size(options, 100000);
leveldb_options_set_paranoid_checks(options, 1);
leveldb_options_set_max_open_files(options, 10);
leveldb_options_set_block_size(options, 1024);
leveldb_options_set_block_restart_interval(options, 8);
leveldb_options_set_compression(options, leveldb_no_compression);
roptions = leveldb_readoptions_create();
leveldb_readoptions_set_verify_checksums(roptions, 1);
leveldb_readoptions_set_fill_cache(roptions, 0);
woptions = leveldb_writeoptions_create();
leveldb_writeoptions_set_sync(woptions, 1);
StartPhase("destroy");
leveldb_destroy_db(options, dbname, &err);
Free(&err);
StartPhase("open_error");
db = leveldb_open(options, dbname, &err);
CheckCondition(err != NULL);
Free(&err);
StartPhase("leveldb_free");
db = leveldb_open(options, dbname, &err);
CheckCondition(err != NULL);
leveldb_free(err);
err = NULL;
StartPhase("open");
leveldb_options_set_create_if_missing(options, 1);
db = leveldb_open(options, dbname, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", NULL);
StartPhase("put");
leveldb_put(db, woptions, "foo", 3, "hello", 5, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", "hello");
StartPhase("compactall");
leveldb_compact_range(db, NULL, 0, NULL, 0);
CheckGet(db, roptions, "foo", "hello");
StartPhase("compactrange");
leveldb_compact_range(db, "a", 1, "z", 1);
CheckGet(db, roptions, "foo", "hello");
StartPhase("writebatch");
{
leveldb_writebatch_t* wb = leveldb_writebatch_create();
leveldb_writebatch_put(wb, "foo", 3, "a", 1);
leveldb_writebatch_clear(wb);
leveldb_writebatch_put(wb, "bar", 3, "b", 1);
leveldb_writebatch_put(wb, "box", 3, "c", 1);
leveldb_writebatch_delete(wb, "bar", 3);
leveldb_write(db, woptions, wb, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", "hello");
CheckGet(db, roptions, "bar", NULL);
CheckGet(db, roptions, "box", "c");
int pos = 0;
leveldb_writebatch_iterate(wb, &pos, CheckPut, CheckDel);
CheckCondition(pos == 3);
leveldb_writebatch_destroy(wb);
}
StartPhase("iter");
{
leveldb_iterator_t* iter = leveldb_create_iterator(db, roptions);
CheckCondition(!leveldb_iter_valid(iter));
leveldb_iter_seek_to_first(iter);
CheckCondition(leveldb_iter_valid(iter));
CheckIter(iter, "box", "c");
leveldb_iter_next(iter);
CheckIter(iter, "foo", "hello");
leveldb_iter_prev(iter);
CheckIter(iter, "box", "c");
leveldb_iter_prev(iter);
CheckCondition(!leveldb_iter_valid(iter));
leveldb_iter_seek_to_last(iter);
CheckIter(iter, "foo", "hello");
leveldb_iter_seek(iter, "b", 1);
CheckIter(iter, "box", "c");
leveldb_iter_get_error(iter, &err);
CheckNoError(err);
leveldb_iter_destroy(iter);
}
StartPhase("approximate_sizes");
{
int i;
int n = 20000;
char keybuf[100];
char valbuf[100];
uint64_t sizes[2];
const char* start[2] = { "a", "k00000000000000010000" };
size_t start_len[2] = { 1, 21 };
const char* limit[2] = { "k00000000000000010000", "z" };
size_t limit_len[2] = { 21, 1 };
leveldb_writeoptions_set_sync(woptions, 0);
for (i = 0; i < n; i++) {
snprintf(keybuf, sizeof(keybuf), "k%020d", i);
snprintf(valbuf, sizeof(valbuf), "v%020d", i);
leveldb_put(db, woptions, keybuf, strlen(keybuf), valbuf, strlen(valbuf),
&err);
CheckNoError(err);
}
leveldb_approximate_sizes(db, 2, start, start_len, limit, limit_len, sizes);
CheckCondition(sizes[0] > 0);
CheckCondition(sizes[1] > 0);
}
StartPhase("property");
{
char* prop = leveldb_property_value(db, "nosuchprop");
CheckCondition(prop == NULL);
prop = leveldb_property_value(db, "leveldb.stats");
CheckCondition(prop != NULL);
Free(&prop);
}
StartPhase("snapshot");
{
const leveldb_snapshot_t* snap;
snap = leveldb_create_snapshot(db);
leveldb_delete(db, woptions, "foo", 3, &err);
CheckNoError(err);
leveldb_readoptions_set_snapshot(roptions, snap);
CheckGet(db, roptions, "foo", "hello");
leveldb_readoptions_set_snapshot(roptions, NULL);
CheckGet(db, roptions, "foo", NULL);
leveldb_release_snapshot(db, snap);
}
StartPhase("repair");
{
leveldb_close(db);
leveldb_options_set_create_if_missing(options, 0);
leveldb_options_set_error_if_exists(options, 0);
leveldb_repair_db(options, dbname, &err);
CheckNoError(err);
db = leveldb_open(options, dbname, &err);
CheckNoError(err);
CheckGet(db, roptions, "foo", NULL);
CheckGet(db, roptions, "bar", NULL);
CheckGet(db, roptions, "box", "c");
leveldb_options_set_create_if_missing(options, 1);
leveldb_options_set_error_if_exists(options, 1);
}
StartPhase("filter");
for (run = 0; run < 2; run++) {
// First run uses custom filter, second run uses bloom filter
CheckNoError(err);
leveldb_filterpolicy_t* policy;
if (run == 0) {
policy = leveldb_filterpolicy_create(
NULL, FilterDestroy, FilterCreate, FilterKeyMatch, FilterName);
} else {
policy = leveldb_filterpolicy_create_bloom(10);
}
// Create new database
leveldb_close(db);
leveldb_destroy_db(options, dbname, &err);
leveldb_options_set_filter_policy(options, policy);
db = leveldb_open(options, dbname, &err);
CheckNoError(err);
leveldb_put(db, woptions, "foo", 3, "foovalue", 8, &err);
CheckNoError(err);
leveldb_put(db, woptions, "bar", 3, "barvalue", 8, &err);
CheckNoError(err);
leveldb_compact_range(db, NULL, 0, NULL, 0);
fake_filter_result = 1;
CheckGet(db, roptions, "foo", "foovalue");
CheckGet(db, roptions, "bar", "barvalue");
if (phase == 0) {
// Must not find value when custom filter returns false
fake_filter_result = 0;
CheckGet(db, roptions, "foo", NULL);
CheckGet(db, roptions, "bar", NULL);
fake_filter_result = 1;
CheckGet(db, roptions, "foo", "foovalue");
CheckGet(db, roptions, "bar", "barvalue");
}
leveldb_options_set_filter_policy(options, NULL);
leveldb_filterpolicy_destroy(policy);
}
StartPhase("cleanup");
leveldb_close(db);
leveldb_options_destroy(options);
leveldb_readoptions_destroy(roptions);
leveldb_writeoptions_destroy(woptions);
leveldb_cache_destroy(cache);
leveldb_comparator_destroy(cmp);
leveldb_env_destroy(env);
fprintf(stderr, "PASS\n");
return 0;
}
| mit |
creeptonik/videojs-live-card | node_modules/node-sass/src/libsass/src/prelexer.cpp | 468 | 46683 | #include "sass.hpp"
#include <cctype>
#include <cstddef>
#include <iostream>
#include <iomanip>
#include "util.hpp"
#include "position.hpp"
#include "prelexer.hpp"
#include "constants.hpp"
namespace Sass {
// using namespace Lexer;
using namespace Constants;
namespace Prelexer {
/*
def string_re(open, close)
/#{open}((?:\\.|\#(?!\{)|[^#{close}\\#])*)(#{close}|#\{)/m
end
end
# A hash of regular expressions that are used for tokenizing strings.
#
# The key is a `[Symbol, Boolean]` pair.
# The symbol represents which style of quotation to use,
# while the boolean represents whether or not the string
# is following an interpolated segment.
STRING_REGULAR_EXPRESSIONS = {
:double => {
/#{open}((?:\\.|\#(?!\{)|[^#{close}\\#])*)(#{close}|#\{)/m
false => string_re('"', '"'),
true => string_re('', '"')
},
:single => {
false => string_re("'", "'"),
true => string_re('', "'")
},
:uri => {
false => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
},
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
# non-standard version of http://www.w3.org/TR/css3-conditional/
:url_prefix => {
false => /url-prefix\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
},
:domain => {
false => /domain\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
}
}
*/
/*
/#{open}
(
\\.
|
\# (?!\{)
|
[^#{close}\\#]
)*
(#{close}|#\{)
/m
false => string_re('"', '"'),
true => string_re('', '"')
*/
extern const char string_double_negates[] = "\"\\#";
const char* re_string_double_close(const char* src)
{
return sequence <
// valid chars
zero_plus <
alternatives <
// escaped char
sequence <
exactly <'\\'>,
any_char
>,
// non interpolate hash
sequence <
exactly <'#'>,
negate <
exactly <'{'>
>
>,
// other valid chars
neg_class_char <
string_double_negates
>
>
>,
// quoted string closer
// or interpolate opening
alternatives <
exactly <'"'>,
lookahead < exactly< hash_lbrace > >
>
>(src);
}
const char* re_string_double_open(const char* src)
{
return sequence <
// quoted string opener
exactly <'"'>,
// valid chars
zero_plus <
alternatives <
// escaped char
sequence <
exactly <'\\'>,
any_char
>,
// non interpolate hash
sequence <
exactly <'#'>,
negate <
exactly <'{'>
>
>,
// other valid chars
neg_class_char <
string_double_negates
>
>
>,
// quoted string closer
// or interpolate opening
alternatives <
exactly <'"'>,
lookahead < exactly< hash_lbrace > >
>
>(src);
}
extern const char string_single_negates[] = "'\\#";
const char* re_string_single_close(const char* src)
{
return sequence <
// valid chars
zero_plus <
alternatives <
// escaped char
sequence <
exactly <'\\'>,
any_char
>,
// non interpolate hash
sequence <
exactly <'#'>,
negate <
exactly <'{'>
>
>,
// other valid chars
neg_class_char <
string_single_negates
>
>
>,
// quoted string closer
// or interpolate opening
alternatives <
exactly <'\''>,
lookahead < exactly< hash_lbrace > >
>
>(src);
}
const char* re_string_single_open(const char* src)
{
return sequence <
// quoted string opener
exactly <'\''>,
// valid chars
zero_plus <
alternatives <
// escaped char
sequence <
exactly <'\\'>,
any_char
>,
// non interpolate hash
sequence <
exactly <'#'>,
negate <
exactly <'{'>
>
>,
// other valid chars
neg_class_char <
string_single_negates
>
>
>,
// quoted string closer
// or interpolate opening
alternatives <
exactly <'\''>,
lookahead < exactly< hash_lbrace > >
>
>(src);
}
/*
:uri => {
false => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
},
*/
const char* re_string_uri_close(const char* src)
{
return sequence <
non_greedy<
alternatives<
class_char< real_uri_chars >,
uri_character,
NONASCII,
ESCAPE
>,
alternatives<
sequence < optional < W >, exactly <')'> >,
lookahead < exactly< hash_lbrace > >
>
>,
optional <
sequence < optional < W >, exactly <')'> >
>
>(src);
}
const char* re_string_uri_open(const char* src)
{
return sequence <
exactly <'u'>,
exactly <'r'>,
exactly <'l'>,
exactly <'('>,
W,
non_greedy<
alternatives<
class_char< real_uri_chars >,
uri_character,
NONASCII,
ESCAPE
>,
alternatives<
sequence < W, exactly <')'> >,
exactly< hash_lbrace >
>
>
>(src);
}
// Match a line comment (/.*?(?=\n|\r\n?|\Z)/.
const char* line_comment(const char* src)
{
return sequence<
exactly <
slash_slash
>,
non_greedy<
any_char,
end_of_line
>
>(src);
}
// Match a block comment.
const char* block_comment(const char* src)
{
return sequence<
delimited_by<
slash_star,
star_slash,
false
>
>(src);
}
/* not use anymore - remove?
const char* block_comment_prefix(const char* src) {
return exactly<slash_star>(src);
}
// Match either comment.
const char* comment(const char* src) {
return line_comment(src);
}
*/
// Match zero plus white-space or line_comments
const char* optional_css_whitespace(const char* src) {
return zero_plus< alternatives<spaces, line_comment> >(src);
}
const char* css_whitespace(const char* src) {
return one_plus< alternatives<spaces, line_comment> >(src);
}
// Match optional_css_whitepace plus block_comments
const char* optional_css_comments(const char* src) {
return zero_plus< alternatives<spaces, line_comment, block_comment> >(src);
}
const char* css_comments(const char* src) {
return one_plus< alternatives<spaces, line_comment, block_comment> >(src);
}
// Match one backslash escaped char /\\./
const char* escape_seq(const char* src)
{
return sequence<
exactly<'\\'>,
alternatives <
minmax_range<
1, 3, xdigit
>,
any_char
>,
optional <
exactly <' '>
>
>(src);
}
// Match identifier start
const char* identifier_alpha(const char* src)
{
return alternatives<
unicode_seq,
alpha,
unicode,
exactly<'-'>,
exactly<'_'>,
NONASCII,
ESCAPE,
escape_seq
>(src);
}
// Match identifier after start
const char* identifier_alnum(const char* src)
{
return alternatives<
unicode_seq,
alnum,
unicode,
exactly<'-'>,
exactly<'_'>,
NONASCII,
ESCAPE,
escape_seq
>(src);
}
// Match CSS identifiers.
const char* strict_identifier(const char* src)
{
return sequence<
one_plus < strict_identifier_alpha >,
zero_plus < strict_identifier_alnum >
// word_boundary not needed
>(src);
}
// Match CSS identifiers.
const char* identifier(const char* src)
{
return sequence<
zero_plus< exactly<'-'> >,
one_plus < identifier_alpha >,
zero_plus < identifier_alnum >
// word_boundary not needed
>(src);
}
const char* strict_identifier_alpha(const char* src)
{
return alternatives <
alpha,
unicode,
escape_seq,
exactly<'_'>
>(src);
}
const char* strict_identifier_alnum(const char* src)
{
return alternatives <
alnum,
unicode,
escape_seq,
exactly<'_'>
>(src);
}
// Match a single CSS unit
const char* one_unit(const char* src)
{
return sequence <
optional < exactly <'-'> >,
strict_identifier_alpha,
zero_plus < alternatives<
strict_identifier_alnum,
sequence <
one_plus < exactly<'-'> >,
strict_identifier_alpha
>
> >
>(src);
}
// Match numerator/denominator CSS units
const char* multiple_units(const char* src)
{
return
sequence <
one_unit,
zero_plus <
sequence <
exactly <'*'>,
one_unit
>
>
>(src);
}
// Match complex CSS unit identifiers
const char* unit_identifier(const char* src)
{
return sequence <
multiple_units,
optional <
sequence <
exactly <'/'>,
multiple_units
> >
>(src);
}
const char* identifier_alnums(const char* src)
{
return one_plus< identifier_alnum >(src);
}
// Match number prefix ([\+\-]+)
const char* number_prefix(const char* src) {
return alternatives <
exactly < '+' >,
sequence <
exactly < '-' >,
optional_css_whitespace,
exactly< '-' >
>
>(src);
}
// Match interpolant schemas
const char* identifier_schema(const char* src) {
return sequence <
one_plus <
sequence <
zero_plus <
alternatives <
sequence <
optional <
exactly <'$'>
>,
identifier
>,
exactly <'-'>
>
>,
interpolant,
zero_plus <
alternatives <
digits,
sequence <
optional <
exactly <'$'>
>,
identifier
>,
quoted_string,
exactly<'-'>
>
>
>
>,
negate <
exactly<'%'>
>
> (src);
}
// interpolants can be recursive/nested
const char* interpolant(const char* src) {
return recursive_scopes< exactly<hash_lbrace>, exactly<rbrace> >(src);
}
// $re_squote = /'(?:$re_itplnt|\\.|[^'])*'/
const char* single_quoted_string(const char* src) {
// match a single quoted string, while skipping interpolants
return sequence <
exactly <'\''>,
zero_plus <
alternatives <
// skip escapes
sequence <
exactly < '\\' >,
re_linebreak
>,
escape_seq,
unicode_seq,
// skip interpolants
interpolant,
// skip non delimiters
any_char_but < '\'' >
>
>,
exactly <'\''>
>(src);
}
// $re_dquote = /"(?:$re_itp|\\.|[^"])*"/
const char* double_quoted_string(const char* src) {
// match a single quoted string, while skipping interpolants
return sequence <
exactly <'"'>,
zero_plus <
alternatives <
// skip escapes
sequence <
exactly < '\\' >,
re_linebreak
>,
escape_seq,
unicode_seq,
// skip interpolants
interpolant,
// skip non delimiters
any_char_but < '"' >
>
>,
exactly <'"'>
>(src);
}
// $re_quoted = /(?:$re_squote|$re_dquote)/
const char* quoted_string(const char* src) {
// match a quoted string, while skipping interpolants
return alternatives<
single_quoted_string,
double_quoted_string
>(src);
}
const char* sass_value(const char* src) {
return alternatives <
quoted_string,
identifier,
percentage,
hex,
dimension,
number
>(src);
}
// this is basically `one_plus < sass_value >`
// takes care to not parse invalid combinations
const char* value_combinations(const char* src) {
// `2px-2px` is invalid combo
bool was_number = false;
const char* pos = src;
while (src) {
if ((pos = alternatives < quoted_string, identifier, percentage, hex >(src))) {
was_number = false;
src = pos;
} else if (!was_number && !exactly<'+'>(src) && (pos = alternatives < dimension, number >(src))) {
was_number = true;
src = pos;
} else {
break;
}
}
return src;
}
// must be at least one interpolant
// can be surrounded by sass values
// make sure to never parse (dim)(dim)
// since this wrongly consumes `2px-1px`
// `2px1px` is valid number (unit `px1px`)
const char* value_schema(const char* src)
{
return sequence <
one_plus <
sequence <
optional < value_combinations >,
interpolant,
optional < value_combinations >
>
>
>(src);
}
// Match CSS '@' keywords.
const char* at_keyword(const char* src) {
return sequence<exactly<'@'>, identifier>(src);
}
/*
tok(%r{
(
\\.
|
(?!url\()
[^"'/\#!;\{\}] # "
|
/(?![\*\/])
|
\#(?!\{)
|
!(?![a-z]) # TODO: never consume "!" when issue 1126 is fixed.
)+
}xi) || tok(COMMENT) || tok(SINGLE_LINE_COMMENT) || interp_string || interp_uri ||
interpolation(:warn_for_color)
*/
const char* re_almost_any_value_token(const char* src) {
return alternatives <
one_plus <
alternatives <
sequence <
exactly <'\\'>,
any_char
>,
sequence <
negate <
sequence <
exactly < url_kwd >,
exactly <'('>
>
>,
neg_class_char <
almost_any_value_class
>
>,
sequence <
exactly <'/'>,
negate <
alternatives <
exactly <'/'>,
exactly <'*'>
>
>
>,
sequence <
exactly <'\\'>,
exactly <'#'>,
negate <
exactly <'{'>
>
>,
sequence <
exactly <'!'>,
negate <
alpha
>
>
>
>,
block_comment,
line_comment,
interpolant,
space,
sequence <
exactly<'u'>,
exactly<'r'>,
exactly<'l'>,
exactly<'('>,
zero_plus <
alternatives <
class_char< real_uri_chars >,
uri_character,
NONASCII,
ESCAPE
>
>,
// false => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
// true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
exactly<')'>
>
>(src);
}
/*
DIRECTIVES = Set[:mixin, :include, :function, :return, :debug, :warn, :for,
:each, :while, :if, :else, :extend, :import, :media, :charset, :content,
:_moz_document, :at_root, :error]
*/
const char* re_special_directive(const char* src) {
return alternatives <
word < mixin_kwd >,
word < include_kwd >,
word < function_kwd >,
word < return_kwd >,
word < debug_kwd >,
word < warn_kwd >,
word < for_kwd >,
word < each_kwd >,
word < while_kwd >,
word < if_kwd >,
word < else_kwd >,
word < extend_kwd >,
word < import_kwd >,
word < media_kwd >,
word < charset_kwd >,
word < content_kwd >,
// exactly < moz_document_kwd >,
word < at_root_kwd >,
word < error_kwd >
>(src);
}
const char* re_prefixed_directive(const char* src) {
return sequence <
optional <
sequence <
exactly <'-'>,
one_plus < alnum >,
exactly <'-'>
>
>,
exactly < supports_kwd >
>(src);
}
const char* re_reference_combinator(const char* src) {
return sequence <
optional <
sequence <
zero_plus <
exactly <'-'>
>,
identifier,
exactly <'|'>
>
>,
zero_plus <
exactly <'-'>
>,
identifier
>(src);
}
const char* static_reference_combinator(const char* src) {
return sequence <
exactly <'/'>,
re_reference_combinator,
exactly <'/'>
>(src);
}
const char* schema_reference_combinator(const char* src) {
return sequence <
exactly <'/'>,
optional <
sequence <
css_ip_identifier,
exactly <'|'>
>
>,
css_ip_identifier,
exactly <'/'>
> (src);
}
const char* kwd_import(const char* src) {
return word<import_kwd>(src);
}
const char* kwd_at_root(const char* src) {
return word<at_root_kwd>(src);
}
const char* kwd_with_directive(const char* src) {
return word<with_kwd>(src);
}
const char* kwd_without_directive(const char* src) {
return word<without_kwd>(src);
}
const char* kwd_media(const char* src) {
return word<media_kwd>(src);
}
const char* kwd_supports_directive(const char* src) {
return word<supports_kwd>(src);
}
const char* kwd_mixin(const char* src) {
return word<mixin_kwd>(src);
}
const char* kwd_function(const char* src) {
return word<function_kwd>(src);
}
const char* kwd_return_directive(const char* src) {
return word<return_kwd>(src);
}
const char* kwd_include_directive(const char* src) {
return word<include_kwd>(src);
}
const char* kwd_content_directive(const char* src) {
return word<content_kwd>(src);
}
const char* kwd_charset_directive(const char* src) {
return word<charset_kwd>(src);
}
const char* kwd_extend(const char* src) {
return word<extend_kwd>(src);
}
const char* kwd_if_directive(const char* src) {
return word<if_kwd>(src);
}
const char* kwd_else_directive(const char* src) {
return word<else_kwd>(src);
}
const char* elseif_directive(const char* src) {
return sequence< exactly< else_kwd >,
optional_css_comments,
word< if_after_else_kwd > >(src);
}
const char* kwd_for_directive(const char* src) {
return word<for_kwd>(src);
}
const char* kwd_from(const char* src) {
return word<from_kwd>(src);
}
const char* kwd_to(const char* src) {
return word<to_kwd>(src);
}
const char* kwd_through(const char* src) {
return word<through_kwd>(src);
}
const char* kwd_each_directive(const char* src) {
return word<each_kwd>(src);
}
const char* kwd_in(const char* src) {
return word<in_kwd>(src);
}
const char* kwd_while_directive(const char* src) {
return word<while_kwd>(src);
}
const char* name(const char* src) {
return one_plus< alternatives< alnum,
exactly<'-'>,
exactly<'_'>,
escape_seq > >(src);
}
const char* kwd_warn(const char* src) {
return word<warn_kwd>(src);
}
const char* kwd_err(const char* src) {
return word<error_kwd>(src);
}
const char* kwd_dbg(const char* src) {
return word<debug_kwd>(src);
}
/* not used anymore - remove?
const char* directive(const char* src) {
return sequence< exactly<'@'>, identifier >(src);
} */
const char* kwd_null(const char* src) {
return word<null_kwd>(src);
}
const char* css_identifier(const char* src) {
return sequence <
zero_plus <
exactly <'-'>
>,
identifier
>(src);
}
const char* css_ip_identifier(const char* src) {
return sequence <
zero_plus <
exactly <'-'>
>,
alternatives <
identifier,
interpolant
>
>(src);
}
// Match CSS type selectors
const char* namespace_prefix(const char* src) {
return sequence <
optional <
alternatives <
exactly <'*'>,
css_identifier
>
>,
exactly <'|'>,
negate <
exactly <'='>
>
>(src);
}
// Match CSS type selectors
const char* namespace_schema(const char* src) {
return sequence <
optional <
alternatives <
exactly <'*'>,
css_ip_identifier
>
>,
exactly<'|'>,
negate <
exactly <'='>
>
>(src);
}
const char* hyphens_and_identifier(const char* src) {
return sequence< zero_plus< exactly< '-' > >, identifier_alnums >(src);
}
const char* hyphens_and_name(const char* src) {
return sequence< zero_plus< exactly< '-' > >, name >(src);
}
const char* universal(const char* src) {
return sequence< optional<namespace_schema>, exactly<'*'> >(src);
}
// Match CSS id names.
const char* id_name(const char* src) {
return sequence<exactly<'#'>, identifier_alnums >(src);
}
// Match CSS class names.
const char* class_name(const char* src) {
return sequence<exactly<'.'>, identifier >(src);
}
// Attribute name in an attribute selector.
const char* attribute_name(const char* src) {
return alternatives< sequence< optional<namespace_schema>, identifier>,
identifier >(src);
}
// match placeholder selectors
const char* placeholder(const char* src) {
return sequence<exactly<'%'>, identifier_alnums >(src);
}
// Match CSS numeric constants.
const char* op(const char* src) {
return class_char<op_chars>(src);
}
const char* sign(const char* src) {
return class_char<sign_chars>(src);
}
const char* unsigned_number(const char* src) {
return alternatives<sequence< zero_plus<digits>,
exactly<'.'>,
one_plus<digits> >,
digits>(src);
}
const char* number(const char* src) {
return sequence< optional<sign>, unsigned_number>(src);
}
const char* coefficient(const char* src) {
return alternatives< sequence< optional<sign>, digits >,
sign >(src);
}
const char* binomial(const char* src) {
return sequence <
optional < sign >,
optional < digits >,
exactly <'n'>,
zero_plus < sequence <
optional_css_whitespace, sign,
optional_css_whitespace, digits
> >
>(src);
}
const char* percentage(const char* src) {
return sequence< number, exactly<'%'> >(src);
}
const char* ampersand(const char* src) {
return exactly<'&'>(src);
}
/* not used anymore - remove?
const char* em(const char* src) {
return sequence< number, exactly<em_kwd> >(src);
} */
const char* dimension(const char* src) {
return sequence<number, unit_identifier >(src);
}
const char* hex(const char* src) {
const char* p = sequence< exactly<'#'>, one_plus<xdigit> >(src);
ptrdiff_t len = p - src;
return (len != 4 && len != 7) ? 0 : p;
}
const char* hexa(const char* src) {
const char* p = sequence< exactly<'#'>, one_plus<xdigit> >(src);
ptrdiff_t len = p - src;
return (len != 4 && len != 7 && len != 9) ? 0 : p;
}
const char* hex0(const char* src) {
const char* p = sequence< exactly<'0'>, exactly<'x'>, one_plus<xdigit> >(src);
ptrdiff_t len = p - src;
return (len != 5 && len != 8) ? 0 : p;
}
/* no longer used - remove?
const char* rgb_prefix(const char* src) {
return word<rgb_kwd>(src);
}*/
// Match CSS uri specifiers.
const char* uri_prefix(const char* src) {
return sequence <
exactly <
url_kwd
>,
zero_plus <
sequence <
exactly <'-'>,
one_plus <
alpha
>
>
>,
exactly <'('>
>(src);
}
// TODO: rename the following two functions
/* no longer used - remove?
const char* uri(const char* src) {
return sequence< exactly<url_kwd>,
optional<spaces>,
quoted_string,
optional<spaces>,
exactly<')'> >(src);
}*/
/* no longer used - remove?
const char* url_value(const char* src) {
return sequence< optional< sequence< identifier, exactly<':'> > >, // optional protocol
one_plus< sequence< zero_plus< exactly<'/'> >, filename > >, // one or more folders and/or trailing filename
optional< exactly<'/'> > >(src);
}*/
/* no longer used - remove?
const char* url_schema(const char* src) {
return sequence< optional< sequence< identifier, exactly<':'> > >, // optional protocol
filename_schema >(src); // optional trailing slash
}*/
// Match CSS "!important" keyword.
const char* kwd_important(const char* src) {
return sequence< exactly<'!'>,
optional_css_whitespace,
word<important_kwd> >(src);
}
// Match CSS "!optional" keyword.
const char* kwd_optional(const char* src) {
return sequence< exactly<'!'>,
optional_css_whitespace,
word<optional_kwd> >(src);
}
// Match Sass "!default" keyword.
const char* default_flag(const char* src) {
return sequence< exactly<'!'>,
optional_css_whitespace,
word<default_kwd> >(src);
}
// Match Sass "!global" keyword.
const char* global_flag(const char* src) {
return sequence< exactly<'!'>,
optional_css_whitespace,
word<global_kwd> >(src);
}
// Match CSS pseudo-class/element prefixes.
const char* pseudo_prefix(const char* src) {
return sequence< exactly<':'>, optional< exactly<':'> > >(src);
}
// Match CSS function call openers.
const char* functional_schema(const char* src) {
return sequence <
one_plus <
sequence <
zero_plus <
alternatives <
identifier,
exactly <'-'>
>
>,
one_plus <
sequence <
interpolant,
alternatives <
digits,
identifier,
exactly<'+'>,
exactly<'-'>
>
>
>
>
>,
negate <
exactly <'%'>
>,
lookahead <
exactly <'('>
>
> (src);
}
const char* re_nothing(const char* src) {
return src;
}
const char* re_functional(const char* src) {
return sequence< identifier, optional < block_comment >, exactly<'('> >(src);
}
const char* re_pseudo_selector(const char* src) {
return sequence< identifier, optional < block_comment >, exactly<'('> >(src);
}
// Match the CSS negation pseudo-class.
const char* pseudo_not(const char* src) {
return word< pseudo_not_kwd >(src);
}
// Match CSS 'odd' and 'even' keywords for functional pseudo-classes.
const char* even(const char* src) {
return word<even_kwd>(src);
}
const char* odd(const char* src) {
return word<odd_kwd>(src);
}
// Match CSS attribute-matching operators.
const char* exact_match(const char* src) { return exactly<'='>(src); }
const char* class_match(const char* src) { return exactly<tilde_equal>(src); }
const char* dash_match(const char* src) { return exactly<pipe_equal>(src); }
const char* prefix_match(const char* src) { return exactly<caret_equal>(src); }
const char* suffix_match(const char* src) { return exactly<dollar_equal>(src); }
const char* substring_match(const char* src) { return exactly<star_equal>(src); }
// Match CSS combinators.
/* not used anymore - remove?
const char* adjacent_to(const char* src) {
return sequence< optional_spaces, exactly<'+'> >(src);
}
const char* precedes(const char* src) {
return sequence< optional_spaces, exactly<'~'> >(src);
}
const char* parent_of(const char* src) {
return sequence< optional_spaces, exactly<'>'> >(src);
}
const char* ancestor_of(const char* src) {
return sequence< spaces, negate< exactly<'{'> > >(src);
}*/
// Match SCSS variable names.
const char* variable(const char* src) {
return sequence<exactly<'$'>, identifier>(src);
}
// parse `calc`, `-a-calc` and `--b-c-calc`
// but do not parse `foocalc` or `foo-calc`
const char* calc_fn_call(const char* src) {
return sequence <
optional < sequence <
hyphens,
one_plus < sequence <
strict_identifier,
hyphens
> >
> >,
exactly < calc_fn_kwd >,
word_boundary
>(src);
}
// Match Sass boolean keywords.
const char* kwd_true(const char* src) {
return word<true_kwd>(src);
}
const char* kwd_false(const char* src) {
return word<false_kwd>(src);
}
const char* kwd_only(const char* src) {
return keyword < only_kwd >(src);
}
const char* kwd_and(const char* src) {
return keyword < and_kwd >(src);
}
const char* kwd_or(const char* src) {
return keyword < or_kwd >(src);
}
const char* kwd_not(const char* src) {
return keyword < not_kwd >(src);
}
const char* kwd_eq(const char* src) {
return exactly<eq>(src);
}
const char* kwd_neq(const char* src) {
return exactly<neq>(src);
}
const char* kwd_gt(const char* src) {
return exactly<gt>(src);
}
const char* kwd_gte(const char* src) {
return exactly<gte>(src);
}
const char* kwd_lt(const char* src) {
return exactly<lt>(src);
}
const char* kwd_lte(const char* src) {
return exactly<lte>(src);
}
// match specific IE syntax
const char* ie_progid(const char* src) {
return sequence <
word<progid_kwd>,
exactly<':'>,
alternatives< identifier_schema, identifier >,
zero_plus< sequence<
exactly<'.'>,
alternatives< identifier_schema, identifier >
> >,
zero_plus < sequence<
exactly<'('>,
optional_css_whitespace,
optional < sequence<
alternatives< variable, identifier_schema, identifier >,
optional_css_whitespace,
exactly<'='>,
optional_css_whitespace,
alternatives< variable, identifier_schema, identifier, quoted_string, number, hexa >,
zero_plus< sequence<
optional_css_whitespace,
exactly<','>,
optional_css_whitespace,
sequence<
alternatives< variable, identifier_schema, identifier >,
optional_css_whitespace,
exactly<'='>,
optional_css_whitespace,
alternatives< variable, identifier_schema, identifier, quoted_string, number, hexa >
>
> >
> >,
optional_css_whitespace,
exactly<')'>
> >
>(src);
}
const char* ie_expression(const char* src) {
return sequence < word<expression_kwd>, exactly<'('>, skip_over_scopes< exactly<'('>, exactly<')'> > >(src);
}
const char* ie_property(const char* src) {
return alternatives < ie_expression, ie_progid >(src);
}
// const char* ie_args(const char* src) {
// return sequence< alternatives< ie_keyword_arg, value_schema, quoted_string, interpolant, number, identifier, delimited_by< '(', ')', true> >,
// zero_plus< sequence< optional_css_whitespace, exactly<','>, optional_css_whitespace, alternatives< ie_keyword_arg, value_schema, quoted_string, interpolant, number, identifier, delimited_by<'(', ')', true> > > > >(src);
// }
const char* ie_keyword_arg_property(const char* src) {
return alternatives <
variable,
identifier_schema,
identifier
>(src);
}
const char* ie_keyword_arg_value(const char* src) {
return alternatives <
variable,
identifier_schema,
identifier,
quoted_string,
number,
hexa,
sequence <
exactly < '(' >,
skip_over_scopes <
exactly < '(' >,
exactly < ')' >
>
>
>(src);
}
const char* ie_keyword_arg(const char* src) {
return sequence <
ie_keyword_arg_property,
optional_css_whitespace,
exactly<'='>,
optional_css_whitespace,
ie_keyword_arg_value
>(src);
}
// Path matching functions.
/* not used anymore - remove?
const char* folder(const char* src) {
return sequence< zero_plus< any_char_except<'/'> >,
exactly<'/'> >(src);
}
const char* folders(const char* src) {
return zero_plus< folder >(src);
}*/
/* not used anymore - remove?
const char* chunk(const char* src) {
char inside_str = 0;
const char* p = src;
size_t depth = 0;
while (true) {
if (!*p) {
return 0;
}
else if (!inside_str && (*p == '"' || *p == '\'')) {
inside_str = *p;
}
else if (*p == inside_str && *(p-1) != '\\') {
inside_str = 0;
}
else if (*p == '(' && !inside_str) {
++depth;
}
else if (*p == ')' && !inside_str) {
if (depth == 0) return p;
else --depth;
}
++p;
}
// unreachable
return 0;
}
*/
// follow the CSS spec more closely and see if this helps us scan URLs correctly
/* not used anymore - remove?
const char* NL(const char* src) {
return alternatives< exactly<'\n'>,
sequence< exactly<'\r'>, exactly<'\n'> >,
exactly<'\r'>,
exactly<'\f'> >(src);
}*/
const char* H(const char* src) {
return std::isxdigit(*src) ? src+1 : 0;
}
const char* W(const char* src) {
return zero_plus< alternatives<
space,
exactly< '\t' >,
exactly< '\r' >,
exactly< '\n' >,
exactly< '\f' >
> >(src);
}
const char* UUNICODE(const char* src) {
return sequence< exactly<'\\'>,
between<H, 1, 6>,
optional< W >
>(src);
}
const char* NONASCII(const char* src) {
return nonascii(src);
}
const char* ESCAPE(const char* src) {
return alternatives<
UUNICODE,
sequence<
exactly<'\\'>,
alternatives<
NONASCII,
escapable_character
>
>
>(src);
}
// const char* real_uri_prefix(const char* src) {
// return alternatives<
// exactly< url_kwd >,
// exactly< url_prefix_kwd >
// >(src);
// }
const char* real_uri_suffix(const char* src) {
return sequence< W, exactly< ')' > >(src);
}
const char* real_uri_value(const char* src) {
return
sequence<
non_greedy<
alternatives<
class_char< real_uri_chars >,
uri_character,
NONASCII,
ESCAPE
>,
alternatives<
real_uri_suffix,
exactly< hash_lbrace >
>
>
>
(src);
}
const char* static_string(const char* src) {
const char* pos = src;
const char * s = quoted_string(pos);
Token t(pos, s);
const unsigned int p = count_interval< interpolant >(t.begin, t.end);
return (p == 0) ? t.end : 0;
}
const char* unicode_seq(const char* src) {
return sequence <
alternatives <
exactly< 'U' >,
exactly< 'u' >
>,
exactly< '+' >,
padded_token <
6, xdigit,
exactly < '?' >
>
>(src);
}
const char* static_component(const char* src) {
return alternatives< identifier,
static_string,
percentage,
hex,
exactly<'|'>,
// exactly<'+'>,
sequence < number, unit_identifier >,
number,
sequence< exactly<'!'>, word<important_kwd> >
>(src);
}
const char* static_property(const char* src) {
return
sequence <
zero_plus<
sequence <
optional_css_comments,
alternatives <
exactly<','>,
exactly<'('>,
exactly<')'>,
kwd_optional,
quoted_string,
interpolant,
identifier,
percentage,
dimension,
variable,
alnum,
sequence <
exactly <'\\'>,
any_char
>
>
>
>,
lookahead <
sequence <
optional_css_comments,
alternatives <
exactly <';'>,
exactly <'}'>,
end_of_file
>
>
>
>(src);
}
const char* static_value(const char* src) {
return sequence< sequence<
static_component,
zero_plus< identifier >
>,
zero_plus < sequence<
alternatives<
sequence< optional_spaces, alternatives<
exactly < '/' >,
exactly < ',' >,
exactly < ' ' >
>, optional_spaces >,
spaces
>,
static_component
> >,
zero_plus < spaces >,
alternatives< exactly<';'>, exactly<'}'> >
>(src);
}
const char* parenthese_scope(const char* src) {
return sequence <
exactly < '(' >,
skip_over_scopes <
exactly < '(' >,
exactly < ')' >
>
>(src);
}
const char* re_selector_list(const char* src) {
return alternatives <
// partial bem selector
sequence <
ampersand,
one_plus <
exactly < '-' >
>,
word_boundary,
optional_spaces
>,
// main selector matching
one_plus <
alternatives <
// consume whitespace and comments
spaces, block_comment, line_comment,
// match `/deep/` selector (pass-trough)
// there is no functionality for it yet
schema_reference_combinator,
// match selector ops /[*&%,\[\]]/
class_char < selector_lookahead_ops >,
// match selector combinators /[>+~]/
class_char < selector_combinator_ops >,
// match attribute compare operators
sequence <
exactly <'('>,
optional_spaces,
optional <re_selector_list>,
optional_spaces,
exactly <')'>
>,
alternatives <
exact_match, class_match, dash_match,
prefix_match, suffix_match, substring_match
>,
// main selector match
sequence <
// allow namespace prefix
optional < namespace_schema >,
// modifiers prefixes
alternatives <
sequence <
exactly <'#'>,
// not for interpolation
negate < exactly <'{'> >
>,
// class match
exactly <'.'>,
// single or double colon
optional < pseudo_prefix >
>,
// accept hypens in token
one_plus < sequence <
// can start with hyphens
zero_plus < exactly<'-'> >,
// now the main token
alternatives <
kwd_optional,
exactly <'*'>,
quoted_string,
interpolant,
identifier,
variable,
percentage,
binomial,
dimension,
alnum
>
> >,
// can also end with hyphens
zero_plus < exactly<'-'> >
>
>
>
>(src);
}
const char* type_selector(const char* src) {
return sequence< optional<namespace_schema>, identifier>(src);
}
const char* re_type_selector(const char* src) {
return alternatives< type_selector, universal, quoted_string, dimension, percentage, number, identifier_alnums >(src);
}
const char* re_type_selector2(const char* src) {
return alternatives< type_selector, universal, quoted_string, dimension, percentage, number, identifier_alnums >(src);
}
const char* re_static_expression(const char* src) {
return sequence< number, optional_spaces, exactly<'/'>, optional_spaces, number >(src);
}
// lexer special_fn: these functions cannot be overloaded
// (/((-[\w-]+-)?(calc|element)|expression|progid:[a-z\.]*)\(/i)
const char* re_special_fun(const char* src) {
// match this first as we test prefix hyphens
if (const char* calc = calc_fn_call(src)) {
return calc;
}
return sequence <
optional <
sequence <
exactly <'-'>,
one_plus <
alternatives <
alpha,
exactly <'+'>,
exactly <'-'>
>
>
>
>,
alternatives <
word < expression_kwd >,
sequence <
sequence <
exactly < progid_kwd >,
exactly <':'>
>,
zero_plus <
alternatives <
char_range <'a', 'z'>,
exactly <'.'>
>
>
>
>
>(src);
}
}
}
| mit |
karthikbadam/karthikbadam.github.io | node_modules/node-sass/src/libsass/test/test_subset_map.cpp | 740 | 12410 | #include <string>
#include <iostream>
#include <assert.h>
#include "../subset_map.hpp"
Subset_Map<std::string, std::string> ssm;
string toString(std::vector<std::string> v);
string toString(std::vector<std::pair<std::string, std::vector<std::string>>> v);
void assertEqual(string std::sExpected, std::string sResult);
void setup() {
ssm.clear();
//@ssm[Set[1, 2]] = "Foo"
std::vector<std::string> s1;
s1.push_back("1");
s1.push_back("2");
ssm.put(s1, "Foo");
//@ssm[Set["fizz", "fazz"]] = "Bar"
std::vector<std::string> s2;
s2.push_back("fizz");
s2.push_back("fazz");
ssm.put(s2, "Bar");
//@ssm[Set[:foo, :bar]] = "Baz"
std::vector<std::string> s3;
s3.push_back(":foo");
s3.push_back(":bar");
ssm.put(s3, "Baz");
//@ssm[Set[:foo, :bar, :baz]] = "Bang"
std::vector<std::string> s4;
s4.push_back(":foo");
s4.push_back(":bar");
s4.push_back(":baz");
ssm.put(s4, "Bang");
//@ssm[Set[:bip, :bop, :blip]] = "Qux"
std::vector<std::string> s5;
s5.push_back(":bip");
s5.push_back(":bop");
s5.push_back(":blip");
ssm.put(s5, "Qux");
//@ssm[Set[:bip, :bop]] = "Thram"
std::vector<std::string> s6;
s6.push_back(":bip");
s6.push_back(":bop");
ssm.put(s6, "Thram");
}
void testEqualKeys() {
std::cout << "testEqualKeys" << std::endl;
//assert_equal [["Foo", Set[1, 2]]], @ssm.get(Set[1, 2])
std::vector<std::string> k1;
k1.push_back("1");
k1.push_back("2");
assertEqual("[[Foo, Set[1, 2]]]", toString(ssm.get_kv(k1)));
//assert_equal [["Bar", Set["fizz", "fazz"]]], @ssm.get(Set["fizz", "fazz"])
std::vector<std::string> k2;
k2.push_back("fizz");
k2.push_back("fazz");
assertEqual("[[Bar, Set[fizz, fazz]]]", toString(ssm.get_kv(k2)));
std::cout << std::endl;
}
void testSubsetKeys() {
std::cout << "testSubsetKeys" << std::endl;
//assert_equal [["Foo", Set[1, 2]]], @ssm.get(Set[1, 2, "fuzz"])
std::vector<std::string> k1;
k1.push_back("1");
k1.push_back("2");
k1.push_back("fuzz");
assertEqual("[[Foo, Set[1, 2]]]", toString(ssm.get_kv(k1)));
//assert_equal [["Bar", Set["fizz", "fazz"]]], @ssm.get(Set["fizz", "fazz", 3])
std::vector<std::string> k2;
k2.push_back("fizz");
k2.push_back("fazz");
k2.push_back("3");
assertEqual("[[Bar, Set[fizz, fazz]]]", toString(ssm.get_kv(k2)));
std::cout << std::endl;
}
void testSupersetKeys() {
std::cout << "testSupersetKeys" << std::endl;
//assert_equal [], @ssm.get(Set[1])
std::vector<std::string> k1;
k1.push_back("1");
assertEqual("[]", toString(ssm.get_kv(k1)));
//assert_equal [], @ssm.get(Set[2])
std::vector<std::string> k2;
k2.push_back("2");
assertEqual("[]", toString(ssm.get_kv(k2)));
//assert_equal [], @ssm.get(Set["fizz"])
std::vector<std::string> k3;
k3.push_back("fizz");
assertEqual("[]", toString(ssm.get_kv(k3)));
//assert_equal [], @ssm.get(Set["fazz"])
std::vector<std::string> k4;
k4.push_back("fazz");
assertEqual("[]", toString(ssm.get_kv(k4)));
std::cout << std::endl;
}
void testDisjointKeys() {
std::cout << "testDisjointKeys" << std::endl;
//assert_equal [], @ssm.get(Set[3, 4])
std::vector<std::string> k1;
k1.push_back("3");
k1.push_back("4");
assertEqual("[]", toString(ssm.get_kv(k1)));
//assert_equal [], @ssm.get(Set["fuzz", "frizz"])
std::vector<std::string> k2;
k2.push_back("fuzz");
k2.push_back("frizz");
assertEqual("[]", toString(ssm.get_kv(k2)));
//assert_equal [], @ssm.get(Set["gran", 15])
std::vector<std::string> k3;
k3.push_back("gran");
k3.push_back("15");
assertEqual("[]", toString(ssm.get_kv(k3)));
std::cout << std::endl;
}
void testSemiDisjointKeys() {
std::cout << "testSemiDisjointKeys" << std::endl;
//assert_equal [], @ssm.get(Set[2, 3])
std::vector<std::string> k1;
k1.push_back("2");
k1.push_back("3");
assertEqual("[]", toString(ssm.get_kv(k1)));
//assert_equal [], @ssm.get(Set["fizz", "fuzz"])
std::vector<std::string> k2;
k2.push_back("fizz");
k2.push_back("fuzz");
assertEqual("[]", toString(ssm.get_kv(k2)));
//assert_equal [], @ssm.get(Set[1, "fazz"])
std::vector<std::string> k3;
k3.push_back("1");
k3.push_back("fazz");
assertEqual("[]", toString(ssm.get_kv(k3)));
std::cout << std::endl;
}
void testEmptyKeySet() {
std::cout << "testEmptyKeySet" << std::endl;
//assert_raises(ArgumentError) {@ssm[Set[]] = "Fail"}
std::vector<std::string> s1;
try {
ssm.put(s1, "Fail");
}
catch (const char* &e) {
assertEqual("internal error: subset map keys may not be empty", e);
}
}
void testEmptyKeyGet() {
std::cout << "testEmptyKeyGet" << std::endl;
//assert_equal [], @ssm.get(Set[])
std::vector<std::string> k1;
assertEqual("[]", toString(ssm.get_kv(k1)));
std::cout << std::endl;
}
void testMultipleSubsets() {
std::cout << "testMultipleSubsets" << std::endl;
//assert_equal [["Foo", Set[1, 2]], ["Bar", Set["fizz", "fazz"]]], @ssm.get(Set[1, 2, "fizz", "fazz"])
std::vector<std::string> k1;
k1.push_back("1");
k1.push_back("2");
k1.push_back("fizz");
k1.push_back("fazz");
assertEqual("[[Foo, Set[1, 2]], [Bar, Set[fizz, fazz]]]", toString(ssm.get_kv(k1)));
//assert_equal [["Foo", Set[1, 2]], ["Bar", Set["fizz", "fazz"]]], @ssm.get(Set[1, 2, 3, "fizz", "fazz", "fuzz"])
std::vector<std::string> k2;
k2.push_back("1");
k2.push_back("2");
k2.push_back("3");
k2.push_back("fizz");
k2.push_back("fazz");
k2.push_back("fuzz");
assertEqual("[[Foo, Set[1, 2]], [Bar, Set[fizz, fazz]]]", toString(ssm.get_kv(k2)));
//assert_equal [["Baz", Set[:foo, :bar]]], @ssm.get(Set[:foo, :bar])
std::vector<std::string> k3;
k3.push_back(":foo");
k3.push_back(":bar");
assertEqual("[[Baz, Set[:foo, :bar]]]", toString(ssm.get_kv(k3)));
//assert_equal [["Baz", Set[:foo, :bar]], ["Bang", Set[:foo, :bar, :baz]]], @ssm.get(Set[:foo, :bar, :baz])
std::vector<std::string> k4;
k4.push_back(":foo");
k4.push_back(":bar");
k4.push_back(":baz");
assertEqual("[[Baz, Set[:foo, :bar]], [Bang, Set[:foo, :bar, :baz]]]", toString(ssm.get_kv(k4)));
std::cout << std::endl;
}
void testBracketBracket() {
std::cout << "testBracketBracket" << std::endl;
//assert_equal ["Foo"], @ssm[Set[1, 2, "fuzz"]]
std::vector<std::string> k1;
k1.push_back("1");
k1.push_back("2");
k1.push_back("fuzz");
assertEqual("[Foo]", toString(ssm.get_v(k1)));
//assert_equal ["Baz", "Bang"], @ssm[Set[:foo, :bar, :baz]]
std::vector<std::string> k2;
k2.push_back(":foo");
k2.push_back(":bar");
k2.push_back(":baz");
assertEqual("[Baz, Bang]", toString(ssm.get_v(k2)));
std::cout << std::endl;
}
void testKeyOrder() {
std::cout << "testEqualKeys" << std::endl;
//assert_equal [["Foo", Set[1, 2]]], @ssm.get(Set[2, 1])
std::vector<std::string> k1;
k1.push_back("2");
k1.push_back("1");
assertEqual("[[Foo, Set[1, 2]]]", toString(ssm.get_kv(k1)));
std::cout << std::endl;
}
void testOrderPreserved() {
std::cout << "testOrderPreserved" << std::endl;
//@ssm[Set[10, 11, 12]] = 1
std::vector<std::string> s1;
s1.push_back("10");
s1.push_back("11");
s1.push_back("12");
ssm.put(s1, "1");
//@ssm[Set[10, 11]] = 2
std::vector<std::string> s2;
s2.push_back("10");
s2.push_back("11");
ssm.put(s2, "2");
//@ssm[Set[11]] = 3
std::vector<std::string> s3;
s3.push_back("11");
ssm.put(s3, "3");
//@ssm[Set[11, 12]] = 4
std::vector<std::string> s4;
s4.push_back("11");
s4.push_back("12");
ssm.put(s4, "4");
//@ssm[Set[9, 10, 11, 12, 13]] = 5
std::vector<std::string> s5;
s5.push_back("9");
s5.push_back("10");
s5.push_back("11");
s5.push_back("12");
s5.push_back("13");
ssm.put(s5, "5");
//@ssm[Set[10, 13]] = 6
std::vector<std::string> s6;
s6.push_back("10");
s6.push_back("13");
ssm.put(s6, "6");
//assert_equal([[1, Set[10, 11, 12]], [2, Set[10, 11]], [3, Set[11]], [4, Set[11, 12]], [5, Set[9, 10, 11, 12, 13]], [6, Set[10, 13]]], @ssm.get(Set[9, 10, 11, 12, 13]))
std::vector<std::string> k1;
k1.push_back("9");
k1.push_back("10");
k1.push_back("11");
k1.push_back("12");
k1.push_back("13");
assertEqual("[[1, Set[10, 11, 12]], [2, Set[10, 11]], [3, Set[11]], [4, Set[11, 12]], [5, Set[9, 10, 11, 12, 13]], [6, Set[10, 13]]]", toString(ssm.get_kv(k1)));
std::cout << std::endl;
}
void testMultipleEqualValues() {
std::cout << "testMultipleEqualValues" << std::endl;
//@ssm[Set[11, 12]] = 1
std::vector<std::string> s1;
s1.push_back("11");
s1.push_back("12");
ssm.put(s1, "1");
//@ssm[Set[12, 13]] = 2
std::vector<std::string> s2;
s2.push_back("12");
s2.push_back("13");
ssm.put(s2, "2");
//@ssm[Set[13, 14]] = 1
std::vector<std::string> s3;
s3.push_back("13");
s3.push_back("14");
ssm.put(s3, "1");
//@ssm[Set[14, 15]] = 1
std::vector<std::string> s4;
s4.push_back("14");
s4.push_back("15");
ssm.put(s4, "1");
//assert_equal([[1, Set[11, 12]], [2, Set[12, 13]], [1, Set[13, 14]], [1, Set[14, 15]]], @ssm.get(Set[11, 12, 13, 14, 15]))
std::vector<std::string> k1;
k1.push_back("11");
k1.push_back("12");
k1.push_back("13");
k1.push_back("14");
k1.push_back("15");
assertEqual("[[1, Set[11, 12]], [2, Set[12, 13]], [1, Set[13, 14]], [1, Set[14, 15]]]", toString(ssm.get_kv(k1)));
std::cout << std::endl;
}
int main()
{
std::vector<std::string> s1;
s1.push_back("1");
s1.push_back("2");
std::vector<std::string> s2;
s2.push_back("2");
s2.push_back("3");
std::vector<std::string> s3;
s3.push_back("3");
s3.push_back("4");
ssm.put(s1, "value1");
ssm.put(s2, "value2");
ssm.put(s3, "value3");
std::vector<std::string> s4;
s4.push_back("1");
s4.push_back("2");
s4.push_back("3");
std::vector<std::pair<string, std::vector<std::string> > > fetched(ssm.get_kv(s4));
std::cout << "PRINTING RESULTS:" << std::endl;
for (size_t i = 0, S = fetched.size(); i < S; ++i) {
std::cout << fetched[i].first << std::endl;
}
Subset_Map<string, string> ssm2;
ssm2.put(s1, "foo");
ssm2.put(s2, "bar");
ssm2.put(s4, "hux");
std::vector<std::pair<string, std::vector<std::string> > > fetched2(ssm2.get_kv(s4));
std::cout << std::endl << "PRINTING RESULTS:" << std::endl;
for (size_t i = 0, S = fetched2.size(); i < S; ++i) {
std::cout << fetched2[i].first << std::endl;
}
std::cout << "TRYING ON A SELECTOR-LIKE OBJECT" << std::endl;
Subset_Map<string, string> sel_ssm;
std::vector<std::string> target;
target.push_back("desk");
target.push_back(".wood");
std::vector<std::string> actual;
actual.push_back("desk");
actual.push_back(".wood");
actual.push_back(".mine");
sel_ssm.put(target, "has-aquarium");
std::vector<std::pair<string, std::vector<std::string> > > fetched3(sel_ssm.get_kv(actual));
std::cout << "RESULTS:" << std::endl;
for (size_t i = 0, S = fetched3.size(); i < S; ++i) {
std::cout << fetched3[i].first << std::endl;
}
std::cout << std::endl;
// BEGIN PORTED RUBY TESTS FROM /test/sass/util/subset_map_test.rb
setup();
testEqualKeys();
testSubsetKeys();
testSupersetKeys();
testDisjointKeys();
testSemiDisjointKeys();
testEmptyKeySet();
testEmptyKeyGet();
testMultipleSubsets();
testBracketBracket();
testKeyOrder();
setup();
testOrderPreserved();
setup();
testMultipleEqualValues();
return 0;
}
string toString(std::vector<std::pair<string, std::vector<std::string>>> v)
{
std::stringstream buffer;
buffer << "[";
for (size_t i = 0, S = v.size(); i < S; ++i) {
buffer << "[" << v[i].first;
buffer << ", Set[";
for (size_t j = 0, S = v[i].second.size(); j < S; ++j) {
buffer << v[i].second[j];
if (j < S-1) {
buffer << ", ";
}
}
buffer << "]]";
if (i < S-1) {
buffer << ", ";
}
}
buffer << "]";
return buffer.str();
}
string toString(std::vector<std::string> v)
{
std::stringstream buffer;
buffer << "[";
for (size_t i = 0, S = v.size(); i < S; ++i) {
buffer << v[i];
if (i < S-1) {
buffer << ", ";
}
}
buffer << "]";
return buffer.str();
}
void assertEqual(string sExpected, string sResult) {
std::cout << "Expected: " << sExpected << std::endl;
std::cout << "Result: " << sResult << std::endl;
assert(sExpected == sResult);
}
| mit |
triyoifanto/Mean-BookStore | node_modules/node-sass/src/libsass/src/sass2scss.cpp | 255 | 23857 | /**
* sass2scss
* Licensed under the MIT License
* Copyright (c) Marcel Greter
*/
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_DEPRECATE
#endif
// include library
#include <stack>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <stdio.h>
///*
//
// src comments: comments in sass syntax (staring with //)
// css comments: multiline comments in css syntax (starting with /*)
//
// KEEP_COMMENT: keep src comments in the resulting css code
// STRIP_COMMENT: strip out all comments (either src or css)
// CONVERT_COMMENT: convert all src comments to css comments
//
//*/
// our own header
#include "sass2scss.h"
// add namespace for c++
namespace Sass
{
// return the actual prettify value from options
#define PRETTIFY(converter) (converter.options - (converter.options & 248))
// query the options integer to check if the option is enables
#define KEEP_COMMENT(converter) ((converter.options & SASS2SCSS_KEEP_COMMENT) == SASS2SCSS_KEEP_COMMENT)
#define STRIP_COMMENT(converter) ((converter.options & SASS2SCSS_STRIP_COMMENT) == SASS2SCSS_STRIP_COMMENT)
#define CONVERT_COMMENT(converter) ((converter.options & SASS2SCSS_CONVERT_COMMENT) == SASS2SCSS_CONVERT_COMMENT)
// some makros to access the indentation stack
#define INDENT(converter) (converter.indents.top())
// some makros to query comment parser status
#define IS_PARSING(converter) (converter.comment == "")
#define IS_COMMENT(converter) (converter.comment != "")
#define IS_SRC_COMMENT(converter) (converter.comment == "//" && ! CONVERT_COMMENT(converter))
#define IS_CSS_COMMENT(converter) (converter.comment == "/*" || (converter.comment == "//" && CONVERT_COMMENT(converter)))
// pretty printer helper function
static std::string closer (const converter& converter)
{
return PRETTIFY(converter) == 0 ? " }" :
PRETTIFY(converter) <= 1 ? " }" :
"\n" + INDENT(converter) + "}";
}
// pretty printer helper function
static std::string opener (const converter& converter)
{
return PRETTIFY(converter) == 0 ? " { " :
PRETTIFY(converter) <= 2 ? " {" :
"\n" + INDENT(converter) + "{";
}
// check if the given string is a pseudo selector
// needed to differentiate from sass property syntax
static bool isPseudoSelector (std::string& sel)
{
size_t len = sel.length();
if (len < 1) return false;
size_t pos = sel.find_first_not_of("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1);
if (pos != std::string::npos) sel.erase(pos, std::string::npos);
size_t i = sel.length();
while (i -- > 0) { sel.at(i) = tolower(sel.at(i)); }
// CSS Level 1 - Recommendation
if (sel == ":link") return true;
if (sel == ":visited") return true;
if (sel == ":active") return true;
// CSS Level 2 (Revision 1) - Recommendation
if (sel == ":lang") return true;
if (sel == ":first-child") return true;
if (sel == ":hover") return true;
if (sel == ":focus") return true;
// disabled - also valid properties
// if (sel == ":left") return true;
// if (sel == ":right") return true;
if (sel == ":first") return true;
// Selectors Level 3 - Recommendation
if (sel == ":target") return true;
if (sel == ":root") return true;
if (sel == ":nth-child") return true;
if (sel == ":nth-last-of-child") return true;
if (sel == ":nth-of-type") return true;
if (sel == ":nth-last-of-type") return true;
if (sel == ":last-child") return true;
if (sel == ":first-of-type") return true;
if (sel == ":last-of-type") return true;
if (sel == ":only-child") return true;
if (sel == ":only-of-type") return true;
if (sel == ":empty") return true;
if (sel == ":not") return true;
// CSS Basic User Interface Module Level 3 - Working Draft
if (sel == ":default") return true;
if (sel == ":valid") return true;
if (sel == ":invalid") return true;
if (sel == ":in-range") return true;
if (sel == ":out-of-range") return true;
if (sel == ":required") return true;
if (sel == ":optional") return true;
if (sel == ":read-only") return true;
if (sel == ":read-write") return true;
if (sel == ":dir") return true;
if (sel == ":enabled") return true;
if (sel == ":disabled") return true;
if (sel == ":checked") return true;
if (sel == ":indeterminate") return true;
if (sel == ":nth-last-child") return true;
// Selectors Level 4 - Working Draft
if (sel == ":any-link") return true;
if (sel == ":local-link") return true;
if (sel == ":scope") return true;
if (sel == ":active-drop-target") return true;
if (sel == ":valid-drop-target") return true;
if (sel == ":invalid-drop-target") return true;
if (sel == ":current") return true;
if (sel == ":past") return true;
if (sel == ":future") return true;
if (sel == ":placeholder-shown") return true;
if (sel == ":user-error") return true;
if (sel == ":blank") return true;
if (sel == ":nth-match") return true;
if (sel == ":nth-last-match") return true;
if (sel == ":nth-column") return true;
if (sel == ":nth-last-column") return true;
if (sel == ":matches") return true;
// Fullscreen API - Living Standard
if (sel == ":fullscreen") return true;
// not a pseudo selector
return false;
}
// check if there is some char data
// will ignore everything in comments
static bool hasCharData (std::string& sass)
{
size_t col_pos = 0;
while (true)
{
// try to find some meaningfull char
col_pos = sass.find_first_not_of(" \t\n\v\f\r", col_pos);
// there was no meaningfull char found
if (col_pos == std::string::npos) return false;
// found a multiline comment opener
if (sass.substr(col_pos, 2) == "/*")
{
// find the multiline comment closer
col_pos = sass.find("*/", col_pos);
// maybe we did not find the closer here
if (col_pos == std::string::npos) return false;
// skip closer
col_pos += 2;
}
else
{
return true;
}
}
}
// EO hasCharData
// find src comment opener
// correctly skips quoted strings
static size_t findCommentOpener (std::string& sass)
{
size_t col_pos = 0;
bool apoed = false;
bool quoted = false;
bool comment = false;
size_t brackets = 0;
while (col_pos != std::string::npos)
{
// process all interesting chars
col_pos = sass.find_first_of("\"\'/\\*()", col_pos);
// assertion for valid result
if (col_pos != std::string::npos)
{
char character = sass.at(col_pos);
if (character == '(')
{
if (!quoted && !apoed) brackets ++;
}
else if (character == ')')
{
if (!quoted && !apoed) brackets --;
}
else if (character == '\"')
{
// invert quote bool
if (!apoed && !comment) quoted = !quoted;
}
else if (character == '\'')
{
// invert quote bool
if (!quoted && !comment) apoed = !apoed;
}
else if (col_pos > 0 && character == '/')
{
if (sass.at(col_pos - 1) == '*')
{
comment = false;
}
// next needs to be a slash too
else if (sass.at(col_pos - 1) == '/')
{
// only found if not in single or double quote, bracket or comment
if (!quoted && !apoed && !comment && brackets == 0) return col_pos - 1;
}
}
else if (character == '\\')
{
// skip next char if in quote
if (quoted || apoed) col_pos ++;
}
// this might be a comment opener
else if (col_pos > 0 && character == '*')
{
// opening a multiline comment
if (sass.at(col_pos - 1) == '/')
{
// we are now in a comment
if (!quoted && !apoed) comment = true;
}
}
// skip char
col_pos ++;
}
}
// EO while
return col_pos;
}
// EO findCommentOpener
// remove multiline comments from sass string
// correctly skips quoted strings
static std::string removeMultilineComment (std::string &sass)
{
std::string clean = "";
size_t col_pos = 0;
size_t open_pos = 0;
size_t close_pos = 0;
bool apoed = false;
bool quoted = false;
bool comment = false;
// process sass til string end
while (col_pos != std::string::npos)
{
// process all interesting chars
col_pos = sass.find_first_of("\"\'/\\*", col_pos);
// assertion for valid result
if (col_pos != std::string::npos)
{
char character = sass.at(col_pos);
// found quoted string delimiter
if (character == '\"')
{
if (!apoed && !comment) quoted = !quoted;
}
else if (character == '\'')
{
if (!quoted && !comment) apoed = !apoed;
}
// found possible comment closer
else if (character == '/')
{
// look back to see if it is actually a closer
if (comment && col_pos > 0 && sass.at(col_pos - 1) == '*')
{
close_pos = col_pos + 1; comment = false;
}
}
else if (character == '\\')
{
// skip escaped char
if (quoted || apoed) col_pos ++;
}
// this might be a comment opener
else if (character == '*')
{
// look back to see if it is actually an opener
if (!quoted && !apoed && col_pos > 0 && sass.at(col_pos - 1) == '/')
{
comment = true; open_pos = col_pos - 1;
clean += sass.substr(close_pos, open_pos - close_pos);
}
}
// skip char
col_pos ++;
}
}
// EO while
// add final parts (add half open comment text)
if (comment) clean += sass.substr(open_pos);
else clean += sass.substr(close_pos);
// return string
return clean;
}
// EO removeMultilineComment
// right trim a given string
std::string rtrim(const std::string &sass)
{
std::string trimmed = sass;
size_t pos_ws = trimmed.find_last_not_of(" \t\n\v\f\r");
if (pos_ws != std::string::npos)
{ trimmed.erase(pos_ws + 1); }
else { trimmed.clear(); }
return trimmed;
}
// EO rtrim
// flush whitespace and print additional text, but
// only print additional chars and buffer whitespace
std::string flush (std::string& sass, converter& converter)
{
// return flushed
std::string scss = "";
// print whitespace buffer
scss += PRETTIFY(converter) > 0 ?
converter.whitespace : "";
// reset whitespace buffer
converter.whitespace = "";
// remove possible newlines from string
size_t pos_right = sass.find_last_not_of("\n\r");
if (pos_right == std::string::npos) return scss;
// get the linefeeds from the string
std::string lfs = sass.substr(pos_right + 1);
sass = sass.substr(0, pos_right + 1);
// find some source comment opener
size_t comment_pos = findCommentOpener(sass);
// check if there was a source comment
if (comment_pos != std::string::npos)
{
// convert comment (but only outside other coments)
if (CONVERT_COMMENT(converter) && !IS_COMMENT(converter))
{
// convert to multiline comment
sass.at(comment_pos + 1) = '*';
// add comment node to the whitespace
sass += " */";
}
// not at line start
if (comment_pos > 0)
{
// also include whitespace before the actual comment opener
size_t ws_pos = sass.find_last_not_of(SASS2SCSS_FIND_WHITESPACE, comment_pos - 1);
comment_pos = ws_pos == std::string::npos ? 0 : ws_pos + 1;
}
if (!STRIP_COMMENT(converter))
{
// add comment node to the whitespace
converter.whitespace += sass.substr(comment_pos);
}
else
{
// sass = removeMultilineComments(sass);
}
// update the actual sass code
sass = sass.substr(0, comment_pos);
}
// add newline as getline discharged it
converter.whitespace += lfs + "\n";
// maybe remove any leading whitespace
if (PRETTIFY(converter) == 0)
{
// remove leading whitespace and update string
size_t pos_left = sass.find_first_not_of(SASS2SCSS_FIND_WHITESPACE);
if (pos_left != std::string::npos) sass = sass.substr(pos_left);
}
// add flushed data
scss += sass;
// return string
return scss;
}
// EO flush
// process a line of the sass text
std::string process (std::string& sass, converter& converter)
{
// resulting string
std::string scss = "";
// strip multi line comments
if (STRIP_COMMENT(converter))
{
sass = removeMultilineComment(sass);
}
// right trim input
sass = rtrim(sass);
// get postion of first meaningfull character in string
size_t pos_left = sass.find_first_not_of(SASS2SCSS_FIND_WHITESPACE);
// special case for final run
if (converter.end_of_file) pos_left = 0;
// maybe has only whitespace
if (pos_left == std::string::npos)
{
// just add complete whitespace
converter.whitespace += sass + "\n";
}
// have meaningfull first char
else
{
// extract and store indentation string
std::string indent = sass.substr(0, pos_left);
// check if current line starts a comment
std::string open = sass.substr(pos_left, 2);
// line has less or same indentation
// finalize previous open parser context
if (indent.length() <= INDENT(converter).length())
{
// close multilinie comment
if (IS_CSS_COMMENT(converter))
{
// check if comments will be stripped anyway
if (!STRIP_COMMENT(converter)) scss += " */";
}
// close src comment comment
else if (IS_SRC_COMMENT(converter))
{
// add a newline to avoid closer on same line
// this would put the bracket in the comment node
// no longer needed since we parse them correctly
// if (KEEP_COMMENT(converter)) scss += "\n";
}
// close css properties
else if (converter.property)
{
// add closer unless in concat mode
if (!converter.comma)
{
// if there was no colon we have a selector
// looks like there were no inner properties
if (converter.selector) scss += " {}";
// add final semicolon
else if (!converter.semicolon) scss += ";";
}
}
// reset comment state
converter.comment = "";
}
// make sure we close every "higher" block
while (indent.length() < INDENT(converter).length())
{
// pop stacked context
converter.indents.pop();
// print close bracket
if (IS_PARSING(converter))
{ scss += closer(converter); }
else { scss += " */"; }
// reset comment state
converter.comment = "";
}
// reset converter state
converter.selector = false;
// check if we have sass property syntax
if (sass.substr(pos_left, 1) == ":" && sass.substr(pos_left, 2) != "::")
{
// default to a selector
// change back if property found
converter.selector = true;
// get postion of first whitespace char
size_t pos_wspace = sass.find_first_of(SASS2SCSS_FIND_WHITESPACE, pos_left);
// assertion check for valid result
if (pos_wspace != std::string::npos)
{
// get the possible pseudo selector
std::string pseudo = sass.substr(pos_left, pos_wspace - pos_left);
// get position of the first real property value char
// pseudo selectors get this far, but have no actual value
size_t pos_value = sass.find_first_not_of(SASS2SCSS_FIND_WHITESPACE, pos_wspace);
// assertion check for valid result
if (pos_value != std::string::npos)
{
// only process if not (fallowed by a semicolon or is a pseudo selector)
if (!(sass.at(pos_value) == ':' || isPseudoSelector(pseudo)))
{
// create new string by interchanging the colon sign for property and value
sass = indent + sass.substr(pos_left + 1, pos_wspace - pos_left - 1) + ":" + sass.substr(pos_wspace);
// try to find a colon in the current line, but only ...
size_t pos_colon = sass.find_first_not_of(":", pos_left);
// assertion for valid result
if (pos_colon != std::string::npos)
{
// ... after the first word (skip begining colons)
pos_colon = sass.find_first_of(":", pos_colon);
// it is a selector if there was no colon found
converter.selector = pos_colon == std::string::npos;
}
}
}
}
}
// terminate some statements immediately
else if (
sass.substr(pos_left, 5) == "@warn" ||
sass.substr(pos_left, 6) == "@debug" ||
sass.substr(pos_left, 6) == "@error" ||
sass.substr(pos_left, 8) == "@charset"
) { sass = indent + sass.substr(pos_left); }
// replace some specific sass shorthand directives (if not fallowed by a white space character)
else if (sass.substr(pos_left, 1) == "=" && sass.find_first_of(SASS2SCSS_FIND_WHITESPACE, pos_left) != pos_left + 1)
{ sass = indent + "@mixin " + sass.substr(pos_left + 1); }
else if (sass.substr(pos_left, 1) == "+" && sass.find_first_of(SASS2SCSS_FIND_WHITESPACE, pos_left) != pos_left + 1)
{ sass = indent + "@include " + sass.substr(pos_left + 1); }
// add quotes for import if needed
else if (sass.substr(pos_left, 7) == "@import")
{
// get positions for the actual import url
size_t pos_import = sass.find_first_of(SASS2SCSS_FIND_WHITESPACE, pos_left + 7);
size_t pos_quote = sass.find_first_not_of(SASS2SCSS_FIND_WHITESPACE, pos_import);
// leave proper urls untouched
if (sass.substr(pos_quote, 4) != "url(")
{
// check if the url appears to be already quoted
if (sass.substr(pos_quote, 1) != "\"" && sass.substr(pos_quote, 1) != "\'")
{
// get position of the last char on the line
size_t pos_end = sass.find_last_not_of(SASS2SCSS_FIND_WHITESPACE);
// assertion check for valid result
if (pos_end != std::string::npos)
{
// add quotes around the full line after the import statement
sass = sass.substr(0, pos_quote) + "\"" + sass.substr(pos_quote, pos_end - pos_quote + 1) + "\"";
}
}
}
}
else if (
sass.substr(pos_left, 7) != "@return" &&
sass.substr(pos_left, 7) != "@extend" &&
sass.substr(pos_left, 8) != "@include" &&
sass.substr(pos_left, 8) != "@content"
) {
// probably a selector anyway
converter.selector = true;
// try to find first colon in the current line
size_t pos_colon = sass.find_first_of(":", pos_left);
// assertion that we have a colon
if (pos_colon != std::string::npos)
{
// it is not a selector if we have a space after a colon
if (sass[pos_colon+1] == ' ') converter.selector = false;
if (sass[pos_colon+1] == ' ') converter.selector = false;
}
}
// current line has more indentation
if (indent.length() >= INDENT(converter).length())
{
// not in comment mode
if (IS_PARSING(converter))
{
// has meaningfull chars
if (hasCharData(sass))
{
// is probably a property
// also true for selectors
converter.property = true;
}
}
}
// current line has more indentation
if (indent.length() > INDENT(converter).length())
{
// not in comment mode
if (IS_PARSING(converter))
{
// had meaningfull chars
if (converter.property)
{
// print block opener
scss += opener(converter);
// push new stack context
converter.indents.push("");
// store block indentation
INDENT(converter) = indent;
}
}
// is and will be a src comment
else if (!IS_CSS_COMMENT(converter))
{
// scss does not allow multiline src comments
// therefore add forward slashes to all lines
sass.at(INDENT(converter).length()+0) = '/';
// there is an edge case here if indentation
// is minimal (will overwrite the fist char)
sass.at(INDENT(converter).length()+1) = '/';
// could code around that, but I dont' think
// this will ever be the cause for any trouble
}
}
// line is opening a new comment
if (open == "/*" || open == "//")
{
// reset the property state
converter.property = false;
// close previous comment
if (IS_CSS_COMMENT(converter) && open != "")
{
if (!STRIP_COMMENT(converter) && !CONVERT_COMMENT(converter)) scss += " */";
}
// force single line comments
// into a correct css comment
if (CONVERT_COMMENT(converter))
{
if (IS_PARSING(converter))
{ sass.at(pos_left + 1) = '*'; }
}
// set comment flag
converter.comment = open;
}
// flush data only under certain conditions
if (!(
// strip css and src comments if option is set
(IS_COMMENT(converter) && STRIP_COMMENT(converter)) ||
// strip src comment even if strip option is not set
// but only if the keep src comment option is not set
(IS_SRC_COMMENT(converter) && ! KEEP_COMMENT(converter))
))
{
// flush data and buffer whitespace
scss += flush(sass, converter);
}
// get postion of last meaningfull char
size_t pos_right = sass.find_last_not_of(SASS2SCSS_FIND_WHITESPACE);
// check for invalid result
if (pos_right != std::string::npos)
{
// get the last meaningfull char
std::string close = sass.substr(pos_right, 1);
// check if next line should be concatenated (list mode)
converter.comma = IS_PARSING(converter) && close == ",";
converter.semicolon = IS_PARSING(converter) && close == ";";
// check if we have more than
// one meaningfull char
if (pos_right > 0)
{
// get the last two chars from string
std::string close = sass.substr(pos_right - 1, 2);
// update parser status for expicitly closed comment
if (close == "*/") converter.comment = "";
}
}
// EO have meaningfull chars from end
}
// EO have meaningfull chars from start
// return scss
return scss;
}
// EO process
// read line with either CR, LF or CR LF format
// http://stackoverflow.com/a/6089413/1550314
static std::istream& safeGetline(std::istream& is, std::string& t)
{
t.clear();
// The characters in the stream are read one-by-one using a std::streambuf.
// That is faster than reading them one-by-one using the std::istream.
// Code that uses streambuf this way must be guarded by a sentry object.
// The sentry object performs various tasks,
// such as thread synchronization and updating the stream state.
std::istream::sentry se(is, true);
std::streambuf* sb = is.rdbuf();
for(;;) {
int c = sb->sbumpc();
switch (c) {
case '\n':
return is;
case '\r':
if(sb->sgetc() == '\n')
sb->sbumpc();
return is;
case EOF:
// Also handle the case when the last line has no line ending
if(t.empty())
is.setstate(std::ios::eofbit);
return is;
default:
t += (char)c;
}
}
}
// the main converter function for c++
char* sass2scss (const std::string& sass, const int options)
{
// local variables
std::string line;
std::string scss = "";
std::stringstream stream(sass);
// create converter variable
converter converter;
// initialise all options
converter.comma = false;
converter.property = false;
converter.selector = false;
converter.semicolon = false;
converter.end_of_file = false;
converter.comment = "";
converter.whitespace = "";
converter.indents.push("");
converter.options = options;
// read line by line and process them
while(safeGetline(stream, line) && !stream.eof())
{ scss += process(line, converter); }
// create mutable string
std::string closer = "";
// set the end of file flag
converter.end_of_file = true;
// process to close all open blocks
scss += process(closer, converter);
// allocate new memory on the heap
// caller has to free it after use
char * cstr = (char*) malloc (scss.length() + 1);
// create a copy of the string
strcpy (cstr, scss.c_str());
// return pointer
return &cstr[0];
}
// EO sass2scss
}
// EO namespace
// implement for c
extern "C"
{
char* ADDCALL sass2scss (const char* sass, const int options)
{
return Sass::sass2scss(sass, options);
}
// Get compiled sass2scss version
const char* ADDCALL sass2scss_version(void) {
return SASS2SCSS_VERSION;
}
}
| mit |
xwuxy/C-Programming-Projects | c8-14.c | 1 | 1803 | /* C Programming Language Chapter 8 Project 14 */
/* print the reversal of a sentence without using data structure */
#include <stdio.h>
#include <stdbool.h>
#define STRLENGTH 100
/* Mistake Handling: */
/* Don't use "string" for 'char' */
/* Always check the boundary conditions */
/**** The following mistake program is for reverse all the characters ***/
/*
int main(void){
printf("Enter a sentense: ");
char str[STRLENGTH] = { 0 };
int i = 0;
char ch = 0;
while(true) {
ch = getchar();
str[i] = ch;
i++;
if(i >= STRLENGTH - 1) {
break;
}
if(ch == '?' || ch == '!') {
str[i] = ch;
break;
} else if(ch == '\n') {
break;
}
}
for(i = i -1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");
return 0;
}
*/
int main(void) {
printf("Enter a sentense: ");
char str[STRLENGTH] = { 0 };
int i = 0;
char ch = 0;
char mark = 0;
while(true) {
ch = getchar();
if(ch == '?' || ch == '!') {
mark = ch;
break;
}
if(ch == '\n') {
break;
}
str[i] = ch;
i++;
}
// j is a index that points to the end of the last space
// k is the index that iterates through the small str
// now, i is the index that iterates through the whole str
/* Now the array would not contain \n or mark \n */
int j = i;
int k = 0;
for(; i>= 0; i--) {
if(str[i] == ' ' || i == 0) {
// In case when it reaches 0, k should start from 0
if(i == 0){
k = 0;
} else {
k = i + 1;
}
for(; k < j; k++) {
printf("%c", str[k]);
}
if(i == 0) { break; };
printf(" ");
j = i;
}
}
if( mark != 0) {
printf("%c", mark);
}
printf("\n");
return 0;
}
// How to deal with the ? Question mark?
| cc0-1.0 |
tigertooth4/Kossel-XL | Firmware/jrocholl-Marlin-deltabot/ArduinoAddons/Arduino_0.xx/libraries/U8glib/utility/u8g_com_arduino_parallel.c | 411 | 5309 | /*
u8g_arduino_parallel.c
Universal 8bit Graphics Library
Copyright (c) 2011, olikraus@gmail.com
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.
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.
PIN_D0 8
PIN_D1 9
PIN_D2 10
PIN_D3 11
PIN_D4 4
PIN_D5 5
PIN_D6 6
PIN_D7 7
PIN_CS1 14
PIN_CS2 15
PIN_RW 16
PIN_DI 17
PIN_EN 18
u8g_Init8Bit(u8g, dev, d0, d1, d2, d3, d4, d5, d6, d7, en, cs1, cs2, di, rw, reset)
u8g_Init8Bit(u8g, dev, 8, 9, 10, 11, 4, 5, 6, 7, 18, 14, 15, 17, 16, U8G_PIN_NONE)
*/
#include "u8g.h"
#if defined(ARDUINO)
#if ARDUINO < 100
#include <WProgram.h>
#else
#include <Arduino.h>
#endif
void u8g_com_arduino_parallel_write(u8g_t *u8g, uint8_t val)
{
u8g_com_arduino_digital_write(u8g, U8G_PI_D0, val&1);
val >>= 1;
u8g_com_arduino_digital_write(u8g, U8G_PI_D1, val&1);
val >>= 1;
u8g_com_arduino_digital_write(u8g, U8G_PI_D2, val&1);
val >>= 1;
u8g_com_arduino_digital_write(u8g, U8G_PI_D3, val&1);
val >>= 1;
u8g_com_arduino_digital_write(u8g, U8G_PI_D4, val&1);
val >>= 1;
u8g_com_arduino_digital_write(u8g, U8G_PI_D5, val&1);
val >>= 1;
u8g_com_arduino_digital_write(u8g, U8G_PI_D6, val&1);
val >>= 1;
u8g_com_arduino_digital_write(u8g, U8G_PI_D7, val&1);
/* EN cycle time must be 1 micro second, digitalWrite is slow enough to do this */
//u8g_Delay(1);
u8g_com_arduino_digital_write(u8g, U8G_PI_EN, HIGH);
//u8g_Delay(1);
u8g_MicroDelay(); /* delay by 1000ns, reference: ST7920: 140ns, SBN1661: 100ns */
u8g_com_arduino_digital_write(u8g, U8G_PI_EN, LOW);
u8g_10MicroDelay(); /* ST7920 commands: 72us */
//u8g_Delay(2);
}
uint8_t u8g_com_arduino_parallel_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr)
{
switch(msg)
{
case U8G_COM_MSG_INIT:
/* setup the RW pin as output and force it to low */
if ( u8g->pin_list[U8G_PI_RW] != U8G_PIN_NONE )
{
pinMode(u8g->pin_list[U8G_PI_RW], OUTPUT);
u8g_com_arduino_digital_write(u8g, U8G_PI_RW, LOW);
}
/* set all pins (except RW pin) */
u8g_com_arduino_assign_pin_output_high(u8g);
break;
case U8G_COM_MSG_STOP:
break;
case U8G_COM_MSG_CHIP_SELECT:
if ( arg_val == 0 )
{
/* disable */
u8g_com_arduino_digital_write(u8g, U8G_PI_CS1, HIGH);
u8g_com_arduino_digital_write(u8g, U8G_PI_CS2, HIGH);
}
else if ( arg_val == 1 )
{
/* enable */
u8g_com_arduino_digital_write(u8g, U8G_PI_CS1, LOW);
u8g_com_arduino_digital_write(u8g, U8G_PI_CS2, HIGH);
}
else if ( arg_val == 2 )
{
/* enable */
u8g_com_arduino_digital_write(u8g, U8G_PI_CS1, HIGH);
u8g_com_arduino_digital_write(u8g, U8G_PI_CS2, LOW);
}
else
{
/* enable */
u8g_com_arduino_digital_write(u8g, U8G_PI_CS1, LOW);
u8g_com_arduino_digital_write(u8g, U8G_PI_CS2, LOW);
}
break;
case U8G_COM_MSG_WRITE_BYTE:
u8g_com_arduino_parallel_write(u8g, arg_val);
break;
case U8G_COM_MSG_WRITE_SEQ:
{
register uint8_t *ptr = arg_ptr;
while( arg_val > 0 )
{
u8g_com_arduino_parallel_write(u8g, *ptr++);
arg_val--;
}
}
break;
case U8G_COM_MSG_WRITE_SEQ_P:
{
register uint8_t *ptr = arg_ptr;
while( arg_val > 0 )
{
u8g_com_arduino_parallel_write(u8g, u8g_pgm_read(ptr));
ptr++;
arg_val--;
}
}
break;
case U8G_COM_MSG_ADDRESS: /* define cmd (arg_val = 0) or data mode (arg_val = 1) */
u8g_com_arduino_digital_write(u8g, U8G_PI_DI, arg_val);
break;
case U8G_COM_MSG_RESET:
if ( u8g->pin_list[U8G_PI_RESET] != U8G_PIN_NONE )
u8g_com_arduino_digital_write(u8g, U8G_PI_RESET, arg_val);
break;
}
return 1;
}
#else
uint8_t u8g_com_arduino_parallel_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr)
{
return 1;
}
#endif /* ARDUINO */
| cc0-1.0 |
cheehieu/linux | kernel/cpuset.c | 256 | 77035 | /*
* kernel/cpuset.c
*
* Processor and Memory placement constraints for sets of tasks.
*
* Copyright (C) 2003 BULL SA.
* Copyright (C) 2004-2007 Silicon Graphics, Inc.
* Copyright (C) 2006 Google, Inc
*
* Portions derived from Patrick Mochel's sysfs code.
* sysfs is Copyright (c) 2001-3 Patrick Mochel
*
* 2003-10-10 Written by Simon Derr.
* 2003-10-22 Updates by Stephen Hemminger.
* 2004 May-July Rework by Paul Jackson.
* 2006 Rework by Paul Menage to use generic cgroups
* 2008 Rework of the scheduler domains and CPU hotplug handling
* by Max Krasnyansky
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of the Linux
* distribution for more details.
*/
#include <linux/cpu.h>
#include <linux/cpumask.h>
#include <linux/cpuset.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/kmod.h>
#include <linux/list.h>
#include <linux/mempolicy.h>
#include <linux/mm.h>
#include <linux/memory.h>
#include <linux/export.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/pagemap.h>
#include <linux/proc_fs.h>
#include <linux/rcupdate.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/security.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/time.h>
#include <linux/backing-dev.h>
#include <linux/sort.h>
#include <asm/uaccess.h>
#include <linux/atomic.h>
#include <linux/mutex.h>
#include <linux/workqueue.h>
#include <linux/cgroup.h>
#include <linux/wait.h>
struct static_key cpusets_enabled_key __read_mostly = STATIC_KEY_INIT_FALSE;
/* See "Frequency meter" comments, below. */
struct fmeter {
int cnt; /* unprocessed events count */
int val; /* most recent output value */
time_t time; /* clock (secs) when val computed */
spinlock_t lock; /* guards read or write of above */
};
struct cpuset {
struct cgroup_subsys_state css;
unsigned long flags; /* "unsigned long" so bitops work */
/*
* On default hierarchy:
*
* The user-configured masks can only be changed by writing to
* cpuset.cpus and cpuset.mems, and won't be limited by the
* parent masks.
*
* The effective masks is the real masks that apply to the tasks
* in the cpuset. They may be changed if the configured masks are
* changed or hotplug happens.
*
* effective_mask == configured_mask & parent's effective_mask,
* and if it ends up empty, it will inherit the parent's mask.
*
*
* On legacy hierachy:
*
* The user-configured masks are always the same with effective masks.
*/
/* user-configured CPUs and Memory Nodes allow to tasks */
cpumask_var_t cpus_allowed;
nodemask_t mems_allowed;
/* effective CPUs and Memory Nodes allow to tasks */
cpumask_var_t effective_cpus;
nodemask_t effective_mems;
/*
* This is old Memory Nodes tasks took on.
*
* - top_cpuset.old_mems_allowed is initialized to mems_allowed.
* - A new cpuset's old_mems_allowed is initialized when some
* task is moved into it.
* - old_mems_allowed is used in cpuset_migrate_mm() when we change
* cpuset.mems_allowed and have tasks' nodemask updated, and
* then old_mems_allowed is updated to mems_allowed.
*/
nodemask_t old_mems_allowed;
struct fmeter fmeter; /* memory_pressure filter */
/*
* Tasks are being attached to this cpuset. Used to prevent
* zeroing cpus/mems_allowed between ->can_attach() and ->attach().
*/
int attach_in_progress;
/* partition number for rebuild_sched_domains() */
int pn;
/* for custom sched domain */
int relax_domain_level;
};
static inline struct cpuset *css_cs(struct cgroup_subsys_state *css)
{
return css ? container_of(css, struct cpuset, css) : NULL;
}
/* Retrieve the cpuset for a task */
static inline struct cpuset *task_cs(struct task_struct *task)
{
return css_cs(task_css(task, cpuset_cgrp_id));
}
static inline struct cpuset *parent_cs(struct cpuset *cs)
{
return css_cs(cs->css.parent);
}
#ifdef CONFIG_NUMA
static inline bool task_has_mempolicy(struct task_struct *task)
{
return task->mempolicy;
}
#else
static inline bool task_has_mempolicy(struct task_struct *task)
{
return false;
}
#endif
/* bits in struct cpuset flags field */
typedef enum {
CS_ONLINE,
CS_CPU_EXCLUSIVE,
CS_MEM_EXCLUSIVE,
CS_MEM_HARDWALL,
CS_MEMORY_MIGRATE,
CS_SCHED_LOAD_BALANCE,
CS_SPREAD_PAGE,
CS_SPREAD_SLAB,
} cpuset_flagbits_t;
/* convenient tests for these bits */
static inline bool is_cpuset_online(const struct cpuset *cs)
{
return test_bit(CS_ONLINE, &cs->flags);
}
static inline int is_cpu_exclusive(const struct cpuset *cs)
{
return test_bit(CS_CPU_EXCLUSIVE, &cs->flags);
}
static inline int is_mem_exclusive(const struct cpuset *cs)
{
return test_bit(CS_MEM_EXCLUSIVE, &cs->flags);
}
static inline int is_mem_hardwall(const struct cpuset *cs)
{
return test_bit(CS_MEM_HARDWALL, &cs->flags);
}
static inline int is_sched_load_balance(const struct cpuset *cs)
{
return test_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
}
static inline int is_memory_migrate(const struct cpuset *cs)
{
return test_bit(CS_MEMORY_MIGRATE, &cs->flags);
}
static inline int is_spread_page(const struct cpuset *cs)
{
return test_bit(CS_SPREAD_PAGE, &cs->flags);
}
static inline int is_spread_slab(const struct cpuset *cs)
{
return test_bit(CS_SPREAD_SLAB, &cs->flags);
}
static struct cpuset top_cpuset = {
.flags = ((1 << CS_ONLINE) | (1 << CS_CPU_EXCLUSIVE) |
(1 << CS_MEM_EXCLUSIVE)),
};
/**
* cpuset_for_each_child - traverse online children of a cpuset
* @child_cs: loop cursor pointing to the current child
* @pos_css: used for iteration
* @parent_cs: target cpuset to walk children of
*
* Walk @child_cs through the online children of @parent_cs. Must be used
* with RCU read locked.
*/
#define cpuset_for_each_child(child_cs, pos_css, parent_cs) \
css_for_each_child((pos_css), &(parent_cs)->css) \
if (is_cpuset_online(((child_cs) = css_cs((pos_css)))))
/**
* cpuset_for_each_descendant_pre - pre-order walk of a cpuset's descendants
* @des_cs: loop cursor pointing to the current descendant
* @pos_css: used for iteration
* @root_cs: target cpuset to walk ancestor of
*
* Walk @des_cs through the online descendants of @root_cs. Must be used
* with RCU read locked. The caller may modify @pos_css by calling
* css_rightmost_descendant() to skip subtree. @root_cs is included in the
* iteration and the first node to be visited.
*/
#define cpuset_for_each_descendant_pre(des_cs, pos_css, root_cs) \
css_for_each_descendant_pre((pos_css), &(root_cs)->css) \
if (is_cpuset_online(((des_cs) = css_cs((pos_css)))))
/*
* There are two global locks guarding cpuset structures - cpuset_mutex and
* callback_lock. We also require taking task_lock() when dereferencing a
* task's cpuset pointer. See "The task_lock() exception", at the end of this
* comment.
*
* A task must hold both locks to modify cpusets. If a task holds
* cpuset_mutex, then it blocks others wanting that mutex, ensuring that it
* is the only task able to also acquire callback_lock and be able to
* modify cpusets. It can perform various checks on the cpuset structure
* first, knowing nothing will change. It can also allocate memory while
* just holding cpuset_mutex. While it is performing these checks, various
* callback routines can briefly acquire callback_lock to query cpusets.
* Once it is ready to make the changes, it takes callback_lock, blocking
* everyone else.
*
* Calls to the kernel memory allocator can not be made while holding
* callback_lock, as that would risk double tripping on callback_lock
* from one of the callbacks into the cpuset code from within
* __alloc_pages().
*
* If a task is only holding callback_lock, then it has read-only
* access to cpusets.
*
* Now, the task_struct fields mems_allowed and mempolicy may be changed
* by other task, we use alloc_lock in the task_struct fields to protect
* them.
*
* The cpuset_common_file_read() handlers only hold callback_lock across
* small pieces of code, such as when reading out possibly multi-word
* cpumasks and nodemasks.
*
* Accessing a task's cpuset should be done in accordance with the
* guidelines for accessing subsystem state in kernel/cgroup.c
*/
static DEFINE_MUTEX(cpuset_mutex);
static DEFINE_SPINLOCK(callback_lock);
/*
* CPU / memory hotplug is handled asynchronously.
*/
static void cpuset_hotplug_workfn(struct work_struct *work);
static DECLARE_WORK(cpuset_hotplug_work, cpuset_hotplug_workfn);
static DECLARE_WAIT_QUEUE_HEAD(cpuset_attach_wq);
/*
* This is ugly, but preserves the userspace API for existing cpuset
* users. If someone tries to mount the "cpuset" filesystem, we
* silently switch it to mount "cgroup" instead
*/
static struct dentry *cpuset_mount(struct file_system_type *fs_type,
int flags, const char *unused_dev_name, void *data)
{
struct file_system_type *cgroup_fs = get_fs_type("cgroup");
struct dentry *ret = ERR_PTR(-ENODEV);
if (cgroup_fs) {
char mountopts[] =
"cpuset,noprefix,"
"release_agent=/sbin/cpuset_release_agent";
ret = cgroup_fs->mount(cgroup_fs, flags,
unused_dev_name, mountopts);
put_filesystem(cgroup_fs);
}
return ret;
}
static struct file_system_type cpuset_fs_type = {
.name = "cpuset",
.mount = cpuset_mount,
};
/*
* Return in pmask the portion of a cpusets's cpus_allowed that
* are online. If none are online, walk up the cpuset hierarchy
* until we find one that does have some online cpus. The top
* cpuset always has some cpus online.
*
* One way or another, we guarantee to return some non-empty subset
* of cpu_online_mask.
*
* Call with callback_lock or cpuset_mutex held.
*/
static void guarantee_online_cpus(struct cpuset *cs, struct cpumask *pmask)
{
while (!cpumask_intersects(cs->effective_cpus, cpu_online_mask))
cs = parent_cs(cs);
cpumask_and(pmask, cs->effective_cpus, cpu_online_mask);
}
/*
* Return in *pmask the portion of a cpusets's mems_allowed that
* are online, with memory. If none are online with memory, walk
* up the cpuset hierarchy until we find one that does have some
* online mems. The top cpuset always has some mems online.
*
* One way or another, we guarantee to return some non-empty subset
* of node_states[N_MEMORY].
*
* Call with callback_lock or cpuset_mutex held.
*/
static void guarantee_online_mems(struct cpuset *cs, nodemask_t *pmask)
{
while (!nodes_intersects(cs->effective_mems, node_states[N_MEMORY]))
cs = parent_cs(cs);
nodes_and(*pmask, cs->effective_mems, node_states[N_MEMORY]);
}
/*
* update task's spread flag if cpuset's page/slab spread flag is set
*
* Call with callback_lock or cpuset_mutex held.
*/
static void cpuset_update_task_spread_flag(struct cpuset *cs,
struct task_struct *tsk)
{
if (is_spread_page(cs))
task_set_spread_page(tsk);
else
task_clear_spread_page(tsk);
if (is_spread_slab(cs))
task_set_spread_slab(tsk);
else
task_clear_spread_slab(tsk);
}
/*
* is_cpuset_subset(p, q) - Is cpuset p a subset of cpuset q?
*
* One cpuset is a subset of another if all its allowed CPUs and
* Memory Nodes are a subset of the other, and its exclusive flags
* are only set if the other's are set. Call holding cpuset_mutex.
*/
static int is_cpuset_subset(const struct cpuset *p, const struct cpuset *q)
{
return cpumask_subset(p->cpus_allowed, q->cpus_allowed) &&
nodes_subset(p->mems_allowed, q->mems_allowed) &&
is_cpu_exclusive(p) <= is_cpu_exclusive(q) &&
is_mem_exclusive(p) <= is_mem_exclusive(q);
}
/**
* alloc_trial_cpuset - allocate a trial cpuset
* @cs: the cpuset that the trial cpuset duplicates
*/
static struct cpuset *alloc_trial_cpuset(struct cpuset *cs)
{
struct cpuset *trial;
trial = kmemdup(cs, sizeof(*cs), GFP_KERNEL);
if (!trial)
return NULL;
if (!alloc_cpumask_var(&trial->cpus_allowed, GFP_KERNEL))
goto free_cs;
if (!alloc_cpumask_var(&trial->effective_cpus, GFP_KERNEL))
goto free_cpus;
cpumask_copy(trial->cpus_allowed, cs->cpus_allowed);
cpumask_copy(trial->effective_cpus, cs->effective_cpus);
return trial;
free_cpus:
free_cpumask_var(trial->cpus_allowed);
free_cs:
kfree(trial);
return NULL;
}
/**
* free_trial_cpuset - free the trial cpuset
* @trial: the trial cpuset to be freed
*/
static void free_trial_cpuset(struct cpuset *trial)
{
free_cpumask_var(trial->effective_cpus);
free_cpumask_var(trial->cpus_allowed);
kfree(trial);
}
/*
* validate_change() - Used to validate that any proposed cpuset change
* follows the structural rules for cpusets.
*
* If we replaced the flag and mask values of the current cpuset
* (cur) with those values in the trial cpuset (trial), would
* our various subset and exclusive rules still be valid? Presumes
* cpuset_mutex held.
*
* 'cur' is the address of an actual, in-use cpuset. Operations
* such as list traversal that depend on the actual address of the
* cpuset in the list must use cur below, not trial.
*
* 'trial' is the address of bulk structure copy of cur, with
* perhaps one or more of the fields cpus_allowed, mems_allowed,
* or flags changed to new, trial values.
*
* Return 0 if valid, -errno if not.
*/
static int validate_change(struct cpuset *cur, struct cpuset *trial)
{
struct cgroup_subsys_state *css;
struct cpuset *c, *par;
int ret;
rcu_read_lock();
/* Each of our child cpusets must be a subset of us */
ret = -EBUSY;
cpuset_for_each_child(c, css, cur)
if (!is_cpuset_subset(c, trial))
goto out;
/* Remaining checks don't apply to root cpuset */
ret = 0;
if (cur == &top_cpuset)
goto out;
par = parent_cs(cur);
/* On legacy hiearchy, we must be a subset of our parent cpuset. */
ret = -EACCES;
if (!cgroup_on_dfl(cur->css.cgroup) && !is_cpuset_subset(trial, par))
goto out;
/*
* If either I or some sibling (!= me) is exclusive, we can't
* overlap
*/
ret = -EINVAL;
cpuset_for_each_child(c, css, par) {
if ((is_cpu_exclusive(trial) || is_cpu_exclusive(c)) &&
c != cur &&
cpumask_intersects(trial->cpus_allowed, c->cpus_allowed))
goto out;
if ((is_mem_exclusive(trial) || is_mem_exclusive(c)) &&
c != cur &&
nodes_intersects(trial->mems_allowed, c->mems_allowed))
goto out;
}
/*
* Cpusets with tasks - existing or newly being attached - can't
* be changed to have empty cpus_allowed or mems_allowed.
*/
ret = -ENOSPC;
if ((cgroup_has_tasks(cur->css.cgroup) || cur->attach_in_progress)) {
if (!cpumask_empty(cur->cpus_allowed) &&
cpumask_empty(trial->cpus_allowed))
goto out;
if (!nodes_empty(cur->mems_allowed) &&
nodes_empty(trial->mems_allowed))
goto out;
}
/*
* We can't shrink if we won't have enough room for SCHED_DEADLINE
* tasks.
*/
ret = -EBUSY;
if (is_cpu_exclusive(cur) &&
!cpuset_cpumask_can_shrink(cur->cpus_allowed,
trial->cpus_allowed))
goto out;
ret = 0;
out:
rcu_read_unlock();
return ret;
}
#ifdef CONFIG_SMP
/*
* Helper routine for generate_sched_domains().
* Do cpusets a, b have overlapping effective cpus_allowed masks?
*/
static int cpusets_overlap(struct cpuset *a, struct cpuset *b)
{
return cpumask_intersects(a->effective_cpus, b->effective_cpus);
}
static void
update_domain_attr(struct sched_domain_attr *dattr, struct cpuset *c)
{
if (dattr->relax_domain_level < c->relax_domain_level)
dattr->relax_domain_level = c->relax_domain_level;
return;
}
static void update_domain_attr_tree(struct sched_domain_attr *dattr,
struct cpuset *root_cs)
{
struct cpuset *cp;
struct cgroup_subsys_state *pos_css;
rcu_read_lock();
cpuset_for_each_descendant_pre(cp, pos_css, root_cs) {
/* skip the whole subtree if @cp doesn't have any CPU */
if (cpumask_empty(cp->cpus_allowed)) {
pos_css = css_rightmost_descendant(pos_css);
continue;
}
if (is_sched_load_balance(cp))
update_domain_attr(dattr, cp);
}
rcu_read_unlock();
}
/*
* generate_sched_domains()
*
* This function builds a partial partition of the systems CPUs
* A 'partial partition' is a set of non-overlapping subsets whose
* union is a subset of that set.
* The output of this function needs to be passed to kernel/sched/core.c
* partition_sched_domains() routine, which will rebuild the scheduler's
* load balancing domains (sched domains) as specified by that partial
* partition.
*
* See "What is sched_load_balance" in Documentation/cgroups/cpusets.txt
* for a background explanation of this.
*
* Does not return errors, on the theory that the callers of this
* routine would rather not worry about failures to rebuild sched
* domains when operating in the severe memory shortage situations
* that could cause allocation failures below.
*
* Must be called with cpuset_mutex held.
*
* The three key local variables below are:
* q - a linked-list queue of cpuset pointers, used to implement a
* top-down scan of all cpusets. This scan loads a pointer
* to each cpuset marked is_sched_load_balance into the
* array 'csa'. For our purposes, rebuilding the schedulers
* sched domains, we can ignore !is_sched_load_balance cpusets.
* csa - (for CpuSet Array) Array of pointers to all the cpusets
* that need to be load balanced, for convenient iterative
* access by the subsequent code that finds the best partition,
* i.e the set of domains (subsets) of CPUs such that the
* cpus_allowed of every cpuset marked is_sched_load_balance
* is a subset of one of these domains, while there are as
* many such domains as possible, each as small as possible.
* doms - Conversion of 'csa' to an array of cpumasks, for passing to
* the kernel/sched/core.c routine partition_sched_domains() in a
* convenient format, that can be easily compared to the prior
* value to determine what partition elements (sched domains)
* were changed (added or removed.)
*
* Finding the best partition (set of domains):
* The triple nested loops below over i, j, k scan over the
* load balanced cpusets (using the array of cpuset pointers in
* csa[]) looking for pairs of cpusets that have overlapping
* cpus_allowed, but which don't have the same 'pn' partition
* number and gives them in the same partition number. It keeps
* looping on the 'restart' label until it can no longer find
* any such pairs.
*
* The union of the cpus_allowed masks from the set of
* all cpusets having the same 'pn' value then form the one
* element of the partition (one sched domain) to be passed to
* partition_sched_domains().
*/
static int generate_sched_domains(cpumask_var_t **domains,
struct sched_domain_attr **attributes)
{
struct cpuset *cp; /* scans q */
struct cpuset **csa; /* array of all cpuset ptrs */
int csn; /* how many cpuset ptrs in csa so far */
int i, j, k; /* indices for partition finding loops */
cpumask_var_t *doms; /* resulting partition; i.e. sched domains */
cpumask_var_t non_isolated_cpus; /* load balanced CPUs */
struct sched_domain_attr *dattr; /* attributes for custom domains */
int ndoms = 0; /* number of sched domains in result */
int nslot; /* next empty doms[] struct cpumask slot */
struct cgroup_subsys_state *pos_css;
doms = NULL;
dattr = NULL;
csa = NULL;
if (!alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL))
goto done;
cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
/* Special case for the 99% of systems with one, full, sched domain */
if (is_sched_load_balance(&top_cpuset)) {
ndoms = 1;
doms = alloc_sched_domains(ndoms);
if (!doms)
goto done;
dattr = kmalloc(sizeof(struct sched_domain_attr), GFP_KERNEL);
if (dattr) {
*dattr = SD_ATTR_INIT;
update_domain_attr_tree(dattr, &top_cpuset);
}
cpumask_and(doms[0], top_cpuset.effective_cpus,
non_isolated_cpus);
goto done;
}
csa = kmalloc(nr_cpusets() * sizeof(cp), GFP_KERNEL);
if (!csa)
goto done;
csn = 0;
rcu_read_lock();
cpuset_for_each_descendant_pre(cp, pos_css, &top_cpuset) {
if (cp == &top_cpuset)
continue;
/*
* Continue traversing beyond @cp iff @cp has some CPUs and
* isn't load balancing. The former is obvious. The
* latter: All child cpusets contain a subset of the
* parent's cpus, so just skip them, and then we call
* update_domain_attr_tree() to calc relax_domain_level of
* the corresponding sched domain.
*/
if (!cpumask_empty(cp->cpus_allowed) &&
!(is_sched_load_balance(cp) &&
cpumask_intersects(cp->cpus_allowed, non_isolated_cpus)))
continue;
if (is_sched_load_balance(cp))
csa[csn++] = cp;
/* skip @cp's subtree */
pos_css = css_rightmost_descendant(pos_css);
}
rcu_read_unlock();
for (i = 0; i < csn; i++)
csa[i]->pn = i;
ndoms = csn;
restart:
/* Find the best partition (set of sched domains) */
for (i = 0; i < csn; i++) {
struct cpuset *a = csa[i];
int apn = a->pn;
for (j = 0; j < csn; j++) {
struct cpuset *b = csa[j];
int bpn = b->pn;
if (apn != bpn && cpusets_overlap(a, b)) {
for (k = 0; k < csn; k++) {
struct cpuset *c = csa[k];
if (c->pn == bpn)
c->pn = apn;
}
ndoms--; /* one less element */
goto restart;
}
}
}
/*
* Now we know how many domains to create.
* Convert <csn, csa> to <ndoms, doms> and populate cpu masks.
*/
doms = alloc_sched_domains(ndoms);
if (!doms)
goto done;
/*
* The rest of the code, including the scheduler, can deal with
* dattr==NULL case. No need to abort if alloc fails.
*/
dattr = kmalloc(ndoms * sizeof(struct sched_domain_attr), GFP_KERNEL);
for (nslot = 0, i = 0; i < csn; i++) {
struct cpuset *a = csa[i];
struct cpumask *dp;
int apn = a->pn;
if (apn < 0) {
/* Skip completed partitions */
continue;
}
dp = doms[nslot];
if (nslot == ndoms) {
static int warnings = 10;
if (warnings) {
pr_warn("rebuild_sched_domains confused: nslot %d, ndoms %d, csn %d, i %d, apn %d\n",
nslot, ndoms, csn, i, apn);
warnings--;
}
continue;
}
cpumask_clear(dp);
if (dattr)
*(dattr + nslot) = SD_ATTR_INIT;
for (j = i; j < csn; j++) {
struct cpuset *b = csa[j];
if (apn == b->pn) {
cpumask_or(dp, dp, b->effective_cpus);
cpumask_and(dp, dp, non_isolated_cpus);
if (dattr)
update_domain_attr_tree(dattr + nslot, b);
/* Done with this partition */
b->pn = -1;
}
}
nslot++;
}
BUG_ON(nslot != ndoms);
done:
free_cpumask_var(non_isolated_cpus);
kfree(csa);
/*
* Fallback to the default domain if kmalloc() failed.
* See comments in partition_sched_domains().
*/
if (doms == NULL)
ndoms = 1;
*domains = doms;
*attributes = dattr;
return ndoms;
}
/*
* Rebuild scheduler domains.
*
* If the flag 'sched_load_balance' of any cpuset with non-empty
* 'cpus' changes, or if the 'cpus' allowed changes in any cpuset
* which has that flag enabled, or if any cpuset with a non-empty
* 'cpus' is removed, then call this routine to rebuild the
* scheduler's dynamic sched domains.
*
* Call with cpuset_mutex held. Takes get_online_cpus().
*/
static void rebuild_sched_domains_locked(void)
{
struct sched_domain_attr *attr;
cpumask_var_t *doms;
int ndoms;
lockdep_assert_held(&cpuset_mutex);
get_online_cpus();
/*
* We have raced with CPU hotplug. Don't do anything to avoid
* passing doms with offlined cpu to partition_sched_domains().
* Anyways, hotplug work item will rebuild sched domains.
*/
if (!cpumask_equal(top_cpuset.effective_cpus, cpu_active_mask))
goto out;
/* Generate domain masks and attrs */
ndoms = generate_sched_domains(&doms, &attr);
/* Have scheduler rebuild the domains */
partition_sched_domains(ndoms, doms, attr);
out:
put_online_cpus();
}
#else /* !CONFIG_SMP */
static void rebuild_sched_domains_locked(void)
{
}
#endif /* CONFIG_SMP */
void rebuild_sched_domains(void)
{
mutex_lock(&cpuset_mutex);
rebuild_sched_domains_locked();
mutex_unlock(&cpuset_mutex);
}
/**
* update_tasks_cpumask - Update the cpumasks of tasks in the cpuset.
* @cs: the cpuset in which each task's cpus_allowed mask needs to be changed
*
* Iterate through each task of @cs updating its cpus_allowed to the
* effective cpuset's. As this function is called with cpuset_mutex held,
* cpuset membership stays stable.
*/
static void update_tasks_cpumask(struct cpuset *cs)
{
struct css_task_iter it;
struct task_struct *task;
css_task_iter_start(&cs->css, &it);
while ((task = css_task_iter_next(&it)))
set_cpus_allowed_ptr(task, cs->effective_cpus);
css_task_iter_end(&it);
}
/*
* update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
* @cs: the cpuset to consider
* @new_cpus: temp variable for calculating new effective_cpus
*
* When congifured cpumask is changed, the effective cpumasks of this cpuset
* and all its descendants need to be updated.
*
* On legacy hierachy, effective_cpus will be the same with cpu_allowed.
*
* Called with cpuset_mutex held
*/
static void update_cpumasks_hier(struct cpuset *cs, struct cpumask *new_cpus)
{
struct cpuset *cp;
struct cgroup_subsys_state *pos_css;
bool need_rebuild_sched_domains = false;
rcu_read_lock();
cpuset_for_each_descendant_pre(cp, pos_css, cs) {
struct cpuset *parent = parent_cs(cp);
cpumask_and(new_cpus, cp->cpus_allowed, parent->effective_cpus);
/*
* If it becomes empty, inherit the effective mask of the
* parent, which is guaranteed to have some CPUs.
*/
if (cgroup_on_dfl(cp->css.cgroup) && cpumask_empty(new_cpus))
cpumask_copy(new_cpus, parent->effective_cpus);
/* Skip the whole subtree if the cpumask remains the same. */
if (cpumask_equal(new_cpus, cp->effective_cpus)) {
pos_css = css_rightmost_descendant(pos_css);
continue;
}
if (!css_tryget_online(&cp->css))
continue;
rcu_read_unlock();
spin_lock_irq(&callback_lock);
cpumask_copy(cp->effective_cpus, new_cpus);
spin_unlock_irq(&callback_lock);
WARN_ON(!cgroup_on_dfl(cp->css.cgroup) &&
!cpumask_equal(cp->cpus_allowed, cp->effective_cpus));
update_tasks_cpumask(cp);
/*
* If the effective cpumask of any non-empty cpuset is changed,
* we need to rebuild sched domains.
*/
if (!cpumask_empty(cp->cpus_allowed) &&
is_sched_load_balance(cp))
need_rebuild_sched_domains = true;
rcu_read_lock();
css_put(&cp->css);
}
rcu_read_unlock();
if (need_rebuild_sched_domains)
rebuild_sched_domains_locked();
}
/**
* update_cpumask - update the cpus_allowed mask of a cpuset and all tasks in it
* @cs: the cpuset to consider
* @trialcs: trial cpuset
* @buf: buffer of cpu numbers written to this cpuset
*/
static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs,
const char *buf)
{
int retval;
/* top_cpuset.cpus_allowed tracks cpu_online_mask; it's read-only */
if (cs == &top_cpuset)
return -EACCES;
/*
* An empty cpus_allowed is ok only if the cpuset has no tasks.
* Since cpulist_parse() fails on an empty mask, we special case
* that parsing. The validate_change() call ensures that cpusets
* with tasks have cpus.
*/
if (!*buf) {
cpumask_clear(trialcs->cpus_allowed);
} else {
retval = cpulist_parse(buf, trialcs->cpus_allowed);
if (retval < 0)
return retval;
if (!cpumask_subset(trialcs->cpus_allowed,
top_cpuset.cpus_allowed))
return -EINVAL;
}
/* Nothing to do if the cpus didn't change */
if (cpumask_equal(cs->cpus_allowed, trialcs->cpus_allowed))
return 0;
retval = validate_change(cs, trialcs);
if (retval < 0)
return retval;
spin_lock_irq(&callback_lock);
cpumask_copy(cs->cpus_allowed, trialcs->cpus_allowed);
spin_unlock_irq(&callback_lock);
/* use trialcs->cpus_allowed as a temp variable */
update_cpumasks_hier(cs, trialcs->cpus_allowed);
return 0;
}
/*
* cpuset_migrate_mm
*
* Migrate memory region from one set of nodes to another.
*
* Temporarilly set tasks mems_allowed to target nodes of migration,
* so that the migration code can allocate pages on these nodes.
*
* While the mm_struct we are migrating is typically from some
* other task, the task_struct mems_allowed that we are hacking
* is for our current task, which must allocate new pages for that
* migrating memory region.
*/
static void cpuset_migrate_mm(struct mm_struct *mm, const nodemask_t *from,
const nodemask_t *to)
{
struct task_struct *tsk = current;
tsk->mems_allowed = *to;
do_migrate_pages(mm, from, to, MPOL_MF_MOVE_ALL);
rcu_read_lock();
guarantee_online_mems(task_cs(tsk), &tsk->mems_allowed);
rcu_read_unlock();
}
/*
* cpuset_change_task_nodemask - change task's mems_allowed and mempolicy
* @tsk: the task to change
* @newmems: new nodes that the task will be set
*
* In order to avoid seeing no nodes if the old and new nodes are disjoint,
* we structure updates as setting all new allowed nodes, then clearing newly
* disallowed ones.
*/
static void cpuset_change_task_nodemask(struct task_struct *tsk,
nodemask_t *newmems)
{
bool need_loop;
/*
* Allow tasks that have access to memory reserves because they have
* been OOM killed to get memory anywhere.
*/
if (unlikely(test_thread_flag(TIF_MEMDIE)))
return;
if (current->flags & PF_EXITING) /* Let dying task have memory */
return;
task_lock(tsk);
/*
* Determine if a loop is necessary if another thread is doing
* read_mems_allowed_begin(). If at least one node remains unchanged and
* tsk does not have a mempolicy, then an empty nodemask will not be
* possible when mems_allowed is larger than a word.
*/
need_loop = task_has_mempolicy(tsk) ||
!nodes_intersects(*newmems, tsk->mems_allowed);
if (need_loop) {
local_irq_disable();
write_seqcount_begin(&tsk->mems_allowed_seq);
}
nodes_or(tsk->mems_allowed, tsk->mems_allowed, *newmems);
mpol_rebind_task(tsk, newmems, MPOL_REBIND_STEP1);
mpol_rebind_task(tsk, newmems, MPOL_REBIND_STEP2);
tsk->mems_allowed = *newmems;
if (need_loop) {
write_seqcount_end(&tsk->mems_allowed_seq);
local_irq_enable();
}
task_unlock(tsk);
}
static void *cpuset_being_rebound;
/**
* update_tasks_nodemask - Update the nodemasks of tasks in the cpuset.
* @cs: the cpuset in which each task's mems_allowed mask needs to be changed
*
* Iterate through each task of @cs updating its mems_allowed to the
* effective cpuset's. As this function is called with cpuset_mutex held,
* cpuset membership stays stable.
*/
static void update_tasks_nodemask(struct cpuset *cs)
{
static nodemask_t newmems; /* protected by cpuset_mutex */
struct css_task_iter it;
struct task_struct *task;
cpuset_being_rebound = cs; /* causes mpol_dup() rebind */
guarantee_online_mems(cs, &newmems);
/*
* The mpol_rebind_mm() call takes mmap_sem, which we couldn't
* take while holding tasklist_lock. Forks can happen - the
* mpol_dup() cpuset_being_rebound check will catch such forks,
* and rebind their vma mempolicies too. Because we still hold
* the global cpuset_mutex, we know that no other rebind effort
* will be contending for the global variable cpuset_being_rebound.
* It's ok if we rebind the same mm twice; mpol_rebind_mm()
* is idempotent. Also migrate pages in each mm to new nodes.
*/
css_task_iter_start(&cs->css, &it);
while ((task = css_task_iter_next(&it))) {
struct mm_struct *mm;
bool migrate;
cpuset_change_task_nodemask(task, &newmems);
mm = get_task_mm(task);
if (!mm)
continue;
migrate = is_memory_migrate(cs);
mpol_rebind_mm(mm, &cs->mems_allowed);
if (migrate)
cpuset_migrate_mm(mm, &cs->old_mems_allowed, &newmems);
mmput(mm);
}
css_task_iter_end(&it);
/*
* All the tasks' nodemasks have been updated, update
* cs->old_mems_allowed.
*/
cs->old_mems_allowed = newmems;
/* We're done rebinding vmas to this cpuset's new mems_allowed. */
cpuset_being_rebound = NULL;
}
/*
* update_nodemasks_hier - Update effective nodemasks and tasks in the subtree
* @cs: the cpuset to consider
* @new_mems: a temp variable for calculating new effective_mems
*
* When configured nodemask is changed, the effective nodemasks of this cpuset
* and all its descendants need to be updated.
*
* On legacy hiearchy, effective_mems will be the same with mems_allowed.
*
* Called with cpuset_mutex held
*/
static void update_nodemasks_hier(struct cpuset *cs, nodemask_t *new_mems)
{
struct cpuset *cp;
struct cgroup_subsys_state *pos_css;
rcu_read_lock();
cpuset_for_each_descendant_pre(cp, pos_css, cs) {
struct cpuset *parent = parent_cs(cp);
nodes_and(*new_mems, cp->mems_allowed, parent->effective_mems);
/*
* If it becomes empty, inherit the effective mask of the
* parent, which is guaranteed to have some MEMs.
*/
if (cgroup_on_dfl(cp->css.cgroup) && nodes_empty(*new_mems))
*new_mems = parent->effective_mems;
/* Skip the whole subtree if the nodemask remains the same. */
if (nodes_equal(*new_mems, cp->effective_mems)) {
pos_css = css_rightmost_descendant(pos_css);
continue;
}
if (!css_tryget_online(&cp->css))
continue;
rcu_read_unlock();
spin_lock_irq(&callback_lock);
cp->effective_mems = *new_mems;
spin_unlock_irq(&callback_lock);
WARN_ON(!cgroup_on_dfl(cp->css.cgroup) &&
!nodes_equal(cp->mems_allowed, cp->effective_mems));
update_tasks_nodemask(cp);
rcu_read_lock();
css_put(&cp->css);
}
rcu_read_unlock();
}
/*
* Handle user request to change the 'mems' memory placement
* of a cpuset. Needs to validate the request, update the
* cpusets mems_allowed, and for each task in the cpuset,
* update mems_allowed and rebind task's mempolicy and any vma
* mempolicies and if the cpuset is marked 'memory_migrate',
* migrate the tasks pages to the new memory.
*
* Call with cpuset_mutex held. May take callback_lock during call.
* Will take tasklist_lock, scan tasklist for tasks in cpuset cs,
* lock each such tasks mm->mmap_sem, scan its vma's and rebind
* their mempolicies to the cpusets new mems_allowed.
*/
static int update_nodemask(struct cpuset *cs, struct cpuset *trialcs,
const char *buf)
{
int retval;
/*
* top_cpuset.mems_allowed tracks node_stats[N_MEMORY];
* it's read-only
*/
if (cs == &top_cpuset) {
retval = -EACCES;
goto done;
}
/*
* An empty mems_allowed is ok iff there are no tasks in the cpuset.
* Since nodelist_parse() fails on an empty mask, we special case
* that parsing. The validate_change() call ensures that cpusets
* with tasks have memory.
*/
if (!*buf) {
nodes_clear(trialcs->mems_allowed);
} else {
retval = nodelist_parse(buf, trialcs->mems_allowed);
if (retval < 0)
goto done;
if (!nodes_subset(trialcs->mems_allowed,
top_cpuset.mems_allowed)) {
retval = -EINVAL;
goto done;
}
}
if (nodes_equal(cs->mems_allowed, trialcs->mems_allowed)) {
retval = 0; /* Too easy - nothing to do */
goto done;
}
retval = validate_change(cs, trialcs);
if (retval < 0)
goto done;
spin_lock_irq(&callback_lock);
cs->mems_allowed = trialcs->mems_allowed;
spin_unlock_irq(&callback_lock);
/* use trialcs->mems_allowed as a temp variable */
update_nodemasks_hier(cs, &cs->mems_allowed);
done:
return retval;
}
int current_cpuset_is_being_rebound(void)
{
int ret;
rcu_read_lock();
ret = task_cs(current) == cpuset_being_rebound;
rcu_read_unlock();
return ret;
}
static int update_relax_domain_level(struct cpuset *cs, s64 val)
{
#ifdef CONFIG_SMP
if (val < -1 || val >= sched_domain_level_max)
return -EINVAL;
#endif
if (val != cs->relax_domain_level) {
cs->relax_domain_level = val;
if (!cpumask_empty(cs->cpus_allowed) &&
is_sched_load_balance(cs))
rebuild_sched_domains_locked();
}
return 0;
}
/**
* update_tasks_flags - update the spread flags of tasks in the cpuset.
* @cs: the cpuset in which each task's spread flags needs to be changed
*
* Iterate through each task of @cs updating its spread flags. As this
* function is called with cpuset_mutex held, cpuset membership stays
* stable.
*/
static void update_tasks_flags(struct cpuset *cs)
{
struct css_task_iter it;
struct task_struct *task;
css_task_iter_start(&cs->css, &it);
while ((task = css_task_iter_next(&it)))
cpuset_update_task_spread_flag(cs, task);
css_task_iter_end(&it);
}
/*
* update_flag - read a 0 or a 1 in a file and update associated flag
* bit: the bit to update (see cpuset_flagbits_t)
* cs: the cpuset to update
* turning_on: whether the flag is being set or cleared
*
* Call with cpuset_mutex held.
*/
static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs,
int turning_on)
{
struct cpuset *trialcs;
int balance_flag_changed;
int spread_flag_changed;
int err;
trialcs = alloc_trial_cpuset(cs);
if (!trialcs)
return -ENOMEM;
if (turning_on)
set_bit(bit, &trialcs->flags);
else
clear_bit(bit, &trialcs->flags);
err = validate_change(cs, trialcs);
if (err < 0)
goto out;
balance_flag_changed = (is_sched_load_balance(cs) !=
is_sched_load_balance(trialcs));
spread_flag_changed = ((is_spread_slab(cs) != is_spread_slab(trialcs))
|| (is_spread_page(cs) != is_spread_page(trialcs)));
spin_lock_irq(&callback_lock);
cs->flags = trialcs->flags;
spin_unlock_irq(&callback_lock);
if (!cpumask_empty(trialcs->cpus_allowed) && balance_flag_changed)
rebuild_sched_domains_locked();
if (spread_flag_changed)
update_tasks_flags(cs);
out:
free_trial_cpuset(trialcs);
return err;
}
/*
* Frequency meter - How fast is some event occurring?
*
* These routines manage a digitally filtered, constant time based,
* event frequency meter. There are four routines:
* fmeter_init() - initialize a frequency meter.
* fmeter_markevent() - called each time the event happens.
* fmeter_getrate() - returns the recent rate of such events.
* fmeter_update() - internal routine used to update fmeter.
*
* A common data structure is passed to each of these routines,
* which is used to keep track of the state required to manage the
* frequency meter and its digital filter.
*
* The filter works on the number of events marked per unit time.
* The filter is single-pole low-pass recursive (IIR). The time unit
* is 1 second. Arithmetic is done using 32-bit integers scaled to
* simulate 3 decimal digits of precision (multiplied by 1000).
*
* With an FM_COEF of 933, and a time base of 1 second, the filter
* has a half-life of 10 seconds, meaning that if the events quit
* happening, then the rate returned from the fmeter_getrate()
* will be cut in half each 10 seconds, until it converges to zero.
*
* It is not worth doing a real infinitely recursive filter. If more
* than FM_MAXTICKS ticks have elapsed since the last filter event,
* just compute FM_MAXTICKS ticks worth, by which point the level
* will be stable.
*
* Limit the count of unprocessed events to FM_MAXCNT, so as to avoid
* arithmetic overflow in the fmeter_update() routine.
*
* Given the simple 32 bit integer arithmetic used, this meter works
* best for reporting rates between one per millisecond (msec) and
* one per 32 (approx) seconds. At constant rates faster than one
* per msec it maxes out at values just under 1,000,000. At constant
* rates between one per msec, and one per second it will stabilize
* to a value N*1000, where N is the rate of events per second.
* At constant rates between one per second and one per 32 seconds,
* it will be choppy, moving up on the seconds that have an event,
* and then decaying until the next event. At rates slower than
* about one in 32 seconds, it decays all the way back to zero between
* each event.
*/
#define FM_COEF 933 /* coefficient for half-life of 10 secs */
#define FM_MAXTICKS ((time_t)99) /* useless computing more ticks than this */
#define FM_MAXCNT 1000000 /* limit cnt to avoid overflow */
#define FM_SCALE 1000 /* faux fixed point scale */
/* Initialize a frequency meter */
static void fmeter_init(struct fmeter *fmp)
{
fmp->cnt = 0;
fmp->val = 0;
fmp->time = 0;
spin_lock_init(&fmp->lock);
}
/* Internal meter update - process cnt events and update value */
static void fmeter_update(struct fmeter *fmp)
{
time_t now = get_seconds();
time_t ticks = now - fmp->time;
if (ticks == 0)
return;
ticks = min(FM_MAXTICKS, ticks);
while (ticks-- > 0)
fmp->val = (FM_COEF * fmp->val) / FM_SCALE;
fmp->time = now;
fmp->val += ((FM_SCALE - FM_COEF) * fmp->cnt) / FM_SCALE;
fmp->cnt = 0;
}
/* Process any previous ticks, then bump cnt by one (times scale). */
static void fmeter_markevent(struct fmeter *fmp)
{
spin_lock(&fmp->lock);
fmeter_update(fmp);
fmp->cnt = min(FM_MAXCNT, fmp->cnt + FM_SCALE);
spin_unlock(&fmp->lock);
}
/* Process any previous ticks, then return current value. */
static int fmeter_getrate(struct fmeter *fmp)
{
int val;
spin_lock(&fmp->lock);
fmeter_update(fmp);
val = fmp->val;
spin_unlock(&fmp->lock);
return val;
}
static struct cpuset *cpuset_attach_old_cs;
/* Called by cgroups to determine if a cpuset is usable; cpuset_mutex held */
static int cpuset_can_attach(struct cgroup_subsys_state *css,
struct cgroup_taskset *tset)
{
struct cpuset *cs = css_cs(css);
struct task_struct *task;
int ret;
/* used later by cpuset_attach() */
cpuset_attach_old_cs = task_cs(cgroup_taskset_first(tset));
mutex_lock(&cpuset_mutex);
/* allow moving tasks into an empty cpuset if on default hierarchy */
ret = -ENOSPC;
if (!cgroup_on_dfl(css->cgroup) &&
(cpumask_empty(cs->cpus_allowed) || nodes_empty(cs->mems_allowed)))
goto out_unlock;
cgroup_taskset_for_each(task, tset) {
ret = task_can_attach(task, cs->cpus_allowed);
if (ret)
goto out_unlock;
ret = security_task_setscheduler(task);
if (ret)
goto out_unlock;
}
/*
* Mark attach is in progress. This makes validate_change() fail
* changes which zero cpus/mems_allowed.
*/
cs->attach_in_progress++;
ret = 0;
out_unlock:
mutex_unlock(&cpuset_mutex);
return ret;
}
static void cpuset_cancel_attach(struct cgroup_subsys_state *css,
struct cgroup_taskset *tset)
{
mutex_lock(&cpuset_mutex);
css_cs(css)->attach_in_progress--;
mutex_unlock(&cpuset_mutex);
}
/*
* Protected by cpuset_mutex. cpus_attach is used only by cpuset_attach()
* but we can't allocate it dynamically there. Define it global and
* allocate from cpuset_init().
*/
static cpumask_var_t cpus_attach;
static void cpuset_attach(struct cgroup_subsys_state *css,
struct cgroup_taskset *tset)
{
/* static buf protected by cpuset_mutex */
static nodemask_t cpuset_attach_nodemask_to;
struct mm_struct *mm;
struct task_struct *task;
struct task_struct *leader = cgroup_taskset_first(tset);
struct cpuset *cs = css_cs(css);
struct cpuset *oldcs = cpuset_attach_old_cs;
mutex_lock(&cpuset_mutex);
/* prepare for attach */
if (cs == &top_cpuset)
cpumask_copy(cpus_attach, cpu_possible_mask);
else
guarantee_online_cpus(cs, cpus_attach);
guarantee_online_mems(cs, &cpuset_attach_nodemask_to);
cgroup_taskset_for_each(task, tset) {
/*
* can_attach beforehand should guarantee that this doesn't
* fail. TODO: have a better way to handle failure here
*/
WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
cpuset_change_task_nodemask(task, &cpuset_attach_nodemask_to);
cpuset_update_task_spread_flag(cs, task);
}
/*
* Change mm, possibly for multiple threads in a threadgroup. This is
* expensive and may sleep.
*/
cpuset_attach_nodemask_to = cs->effective_mems;
mm = get_task_mm(leader);
if (mm) {
mpol_rebind_mm(mm, &cpuset_attach_nodemask_to);
/*
* old_mems_allowed is the same with mems_allowed here, except
* if this task is being moved automatically due to hotplug.
* In that case @mems_allowed has been updated and is empty,
* so @old_mems_allowed is the right nodesets that we migrate
* mm from.
*/
if (is_memory_migrate(cs)) {
cpuset_migrate_mm(mm, &oldcs->old_mems_allowed,
&cpuset_attach_nodemask_to);
}
mmput(mm);
}
cs->old_mems_allowed = cpuset_attach_nodemask_to;
cs->attach_in_progress--;
if (!cs->attach_in_progress)
wake_up(&cpuset_attach_wq);
mutex_unlock(&cpuset_mutex);
}
/* The various types of files and directories in a cpuset file system */
typedef enum {
FILE_MEMORY_MIGRATE,
FILE_CPULIST,
FILE_MEMLIST,
FILE_EFFECTIVE_CPULIST,
FILE_EFFECTIVE_MEMLIST,
FILE_CPU_EXCLUSIVE,
FILE_MEM_EXCLUSIVE,
FILE_MEM_HARDWALL,
FILE_SCHED_LOAD_BALANCE,
FILE_SCHED_RELAX_DOMAIN_LEVEL,
FILE_MEMORY_PRESSURE_ENABLED,
FILE_MEMORY_PRESSURE,
FILE_SPREAD_PAGE,
FILE_SPREAD_SLAB,
} cpuset_filetype_t;
static int cpuset_write_u64(struct cgroup_subsys_state *css, struct cftype *cft,
u64 val)
{
struct cpuset *cs = css_cs(css);
cpuset_filetype_t type = cft->private;
int retval = 0;
mutex_lock(&cpuset_mutex);
if (!is_cpuset_online(cs)) {
retval = -ENODEV;
goto out_unlock;
}
switch (type) {
case FILE_CPU_EXCLUSIVE:
retval = update_flag(CS_CPU_EXCLUSIVE, cs, val);
break;
case FILE_MEM_EXCLUSIVE:
retval = update_flag(CS_MEM_EXCLUSIVE, cs, val);
break;
case FILE_MEM_HARDWALL:
retval = update_flag(CS_MEM_HARDWALL, cs, val);
break;
case FILE_SCHED_LOAD_BALANCE:
retval = update_flag(CS_SCHED_LOAD_BALANCE, cs, val);
break;
case FILE_MEMORY_MIGRATE:
retval = update_flag(CS_MEMORY_MIGRATE, cs, val);
break;
case FILE_MEMORY_PRESSURE_ENABLED:
cpuset_memory_pressure_enabled = !!val;
break;
case FILE_MEMORY_PRESSURE:
retval = -EACCES;
break;
case FILE_SPREAD_PAGE:
retval = update_flag(CS_SPREAD_PAGE, cs, val);
break;
case FILE_SPREAD_SLAB:
retval = update_flag(CS_SPREAD_SLAB, cs, val);
break;
default:
retval = -EINVAL;
break;
}
out_unlock:
mutex_unlock(&cpuset_mutex);
return retval;
}
static int cpuset_write_s64(struct cgroup_subsys_state *css, struct cftype *cft,
s64 val)
{
struct cpuset *cs = css_cs(css);
cpuset_filetype_t type = cft->private;
int retval = -ENODEV;
mutex_lock(&cpuset_mutex);
if (!is_cpuset_online(cs))
goto out_unlock;
switch (type) {
case FILE_SCHED_RELAX_DOMAIN_LEVEL:
retval = update_relax_domain_level(cs, val);
break;
default:
retval = -EINVAL;
break;
}
out_unlock:
mutex_unlock(&cpuset_mutex);
return retval;
}
/*
* Common handling for a write to a "cpus" or "mems" file.
*/
static ssize_t cpuset_write_resmask(struct kernfs_open_file *of,
char *buf, size_t nbytes, loff_t off)
{
struct cpuset *cs = css_cs(of_css(of));
struct cpuset *trialcs;
int retval = -ENODEV;
buf = strstrip(buf);
/*
* CPU or memory hotunplug may leave @cs w/o any execution
* resources, in which case the hotplug code asynchronously updates
* configuration and transfers all tasks to the nearest ancestor
* which can execute.
*
* As writes to "cpus" or "mems" may restore @cs's execution
* resources, wait for the previously scheduled operations before
* proceeding, so that we don't end up keep removing tasks added
* after execution capability is restored.
*
* cpuset_hotplug_work calls back into cgroup core via
* cgroup_transfer_tasks() and waiting for it from a cgroupfs
* operation like this one can lead to a deadlock through kernfs
* active_ref protection. Let's break the protection. Losing the
* protection is okay as we check whether @cs is online after
* grabbing cpuset_mutex anyway. This only happens on the legacy
* hierarchies.
*/
css_get(&cs->css);
kernfs_break_active_protection(of->kn);
flush_work(&cpuset_hotplug_work);
mutex_lock(&cpuset_mutex);
if (!is_cpuset_online(cs))
goto out_unlock;
trialcs = alloc_trial_cpuset(cs);
if (!trialcs) {
retval = -ENOMEM;
goto out_unlock;
}
switch (of_cft(of)->private) {
case FILE_CPULIST:
retval = update_cpumask(cs, trialcs, buf);
break;
case FILE_MEMLIST:
retval = update_nodemask(cs, trialcs, buf);
break;
default:
retval = -EINVAL;
break;
}
free_trial_cpuset(trialcs);
out_unlock:
mutex_unlock(&cpuset_mutex);
kernfs_unbreak_active_protection(of->kn);
css_put(&cs->css);
return retval ?: nbytes;
}
/*
* These ascii lists should be read in a single call, by using a user
* buffer large enough to hold the entire map. If read in smaller
* chunks, there is no guarantee of atomicity. Since the display format
* used, list of ranges of sequential numbers, is variable length,
* and since these maps can change value dynamically, one could read
* gibberish by doing partial reads while a list was changing.
*/
static int cpuset_common_seq_show(struct seq_file *sf, void *v)
{
struct cpuset *cs = css_cs(seq_css(sf));
cpuset_filetype_t type = seq_cft(sf)->private;
int ret = 0;
spin_lock_irq(&callback_lock);
switch (type) {
case FILE_CPULIST:
seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->cpus_allowed));
break;
case FILE_MEMLIST:
seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->mems_allowed));
break;
case FILE_EFFECTIVE_CPULIST:
seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->effective_cpus));
break;
case FILE_EFFECTIVE_MEMLIST:
seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->effective_mems));
break;
default:
ret = -EINVAL;
}
spin_unlock_irq(&callback_lock);
return ret;
}
static u64 cpuset_read_u64(struct cgroup_subsys_state *css, struct cftype *cft)
{
struct cpuset *cs = css_cs(css);
cpuset_filetype_t type = cft->private;
switch (type) {
case FILE_CPU_EXCLUSIVE:
return is_cpu_exclusive(cs);
case FILE_MEM_EXCLUSIVE:
return is_mem_exclusive(cs);
case FILE_MEM_HARDWALL:
return is_mem_hardwall(cs);
case FILE_SCHED_LOAD_BALANCE:
return is_sched_load_balance(cs);
case FILE_MEMORY_MIGRATE:
return is_memory_migrate(cs);
case FILE_MEMORY_PRESSURE_ENABLED:
return cpuset_memory_pressure_enabled;
case FILE_MEMORY_PRESSURE:
return fmeter_getrate(&cs->fmeter);
case FILE_SPREAD_PAGE:
return is_spread_page(cs);
case FILE_SPREAD_SLAB:
return is_spread_slab(cs);
default:
BUG();
}
/* Unreachable but makes gcc happy */
return 0;
}
static s64 cpuset_read_s64(struct cgroup_subsys_state *css, struct cftype *cft)
{
struct cpuset *cs = css_cs(css);
cpuset_filetype_t type = cft->private;
switch (type) {
case FILE_SCHED_RELAX_DOMAIN_LEVEL:
return cs->relax_domain_level;
default:
BUG();
}
/* Unrechable but makes gcc happy */
return 0;
}
/*
* for the common functions, 'private' gives the type of file
*/
static struct cftype files[] = {
{
.name = "cpus",
.seq_show = cpuset_common_seq_show,
.write = cpuset_write_resmask,
.max_write_len = (100U + 6 * NR_CPUS),
.private = FILE_CPULIST,
},
{
.name = "mems",
.seq_show = cpuset_common_seq_show,
.write = cpuset_write_resmask,
.max_write_len = (100U + 6 * MAX_NUMNODES),
.private = FILE_MEMLIST,
},
{
.name = "effective_cpus",
.seq_show = cpuset_common_seq_show,
.private = FILE_EFFECTIVE_CPULIST,
},
{
.name = "effective_mems",
.seq_show = cpuset_common_seq_show,
.private = FILE_EFFECTIVE_MEMLIST,
},
{
.name = "cpu_exclusive",
.read_u64 = cpuset_read_u64,
.write_u64 = cpuset_write_u64,
.private = FILE_CPU_EXCLUSIVE,
},
{
.name = "mem_exclusive",
.read_u64 = cpuset_read_u64,
.write_u64 = cpuset_write_u64,
.private = FILE_MEM_EXCLUSIVE,
},
{
.name = "mem_hardwall",
.read_u64 = cpuset_read_u64,
.write_u64 = cpuset_write_u64,
.private = FILE_MEM_HARDWALL,
},
{
.name = "sched_load_balance",
.read_u64 = cpuset_read_u64,
.write_u64 = cpuset_write_u64,
.private = FILE_SCHED_LOAD_BALANCE,
},
{
.name = "sched_relax_domain_level",
.read_s64 = cpuset_read_s64,
.write_s64 = cpuset_write_s64,
.private = FILE_SCHED_RELAX_DOMAIN_LEVEL,
},
{
.name = "memory_migrate",
.read_u64 = cpuset_read_u64,
.write_u64 = cpuset_write_u64,
.private = FILE_MEMORY_MIGRATE,
},
{
.name = "memory_pressure",
.read_u64 = cpuset_read_u64,
.write_u64 = cpuset_write_u64,
.private = FILE_MEMORY_PRESSURE,
.mode = S_IRUGO,
},
{
.name = "memory_spread_page",
.read_u64 = cpuset_read_u64,
.write_u64 = cpuset_write_u64,
.private = FILE_SPREAD_PAGE,
},
{
.name = "memory_spread_slab",
.read_u64 = cpuset_read_u64,
.write_u64 = cpuset_write_u64,
.private = FILE_SPREAD_SLAB,
},
{
.name = "memory_pressure_enabled",
.flags = CFTYPE_ONLY_ON_ROOT,
.read_u64 = cpuset_read_u64,
.write_u64 = cpuset_write_u64,
.private = FILE_MEMORY_PRESSURE_ENABLED,
},
{ } /* terminate */
};
/*
* cpuset_css_alloc - allocate a cpuset css
* cgrp: control group that the new cpuset will be part of
*/
static struct cgroup_subsys_state *
cpuset_css_alloc(struct cgroup_subsys_state *parent_css)
{
struct cpuset *cs;
if (!parent_css)
return &top_cpuset.css;
cs = kzalloc(sizeof(*cs), GFP_KERNEL);
if (!cs)
return ERR_PTR(-ENOMEM);
if (!alloc_cpumask_var(&cs->cpus_allowed, GFP_KERNEL))
goto free_cs;
if (!alloc_cpumask_var(&cs->effective_cpus, GFP_KERNEL))
goto free_cpus;
set_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
cpumask_clear(cs->cpus_allowed);
nodes_clear(cs->mems_allowed);
cpumask_clear(cs->effective_cpus);
nodes_clear(cs->effective_mems);
fmeter_init(&cs->fmeter);
cs->relax_domain_level = -1;
return &cs->css;
free_cpus:
free_cpumask_var(cs->cpus_allowed);
free_cs:
kfree(cs);
return ERR_PTR(-ENOMEM);
}
static int cpuset_css_online(struct cgroup_subsys_state *css)
{
struct cpuset *cs = css_cs(css);
struct cpuset *parent = parent_cs(cs);
struct cpuset *tmp_cs;
struct cgroup_subsys_state *pos_css;
if (!parent)
return 0;
mutex_lock(&cpuset_mutex);
set_bit(CS_ONLINE, &cs->flags);
if (is_spread_page(parent))
set_bit(CS_SPREAD_PAGE, &cs->flags);
if (is_spread_slab(parent))
set_bit(CS_SPREAD_SLAB, &cs->flags);
cpuset_inc();
spin_lock_irq(&callback_lock);
if (cgroup_on_dfl(cs->css.cgroup)) {
cpumask_copy(cs->effective_cpus, parent->effective_cpus);
cs->effective_mems = parent->effective_mems;
}
spin_unlock_irq(&callback_lock);
if (!test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags))
goto out_unlock;
/*
* Clone @parent's configuration if CGRP_CPUSET_CLONE_CHILDREN is
* set. This flag handling is implemented in cgroup core for
* histrical reasons - the flag may be specified during mount.
*
* Currently, if any sibling cpusets have exclusive cpus or mem, we
* refuse to clone the configuration - thereby refusing the task to
* be entered, and as a result refusing the sys_unshare() or
* clone() which initiated it. If this becomes a problem for some
* users who wish to allow that scenario, then this could be
* changed to grant parent->cpus_allowed-sibling_cpus_exclusive
* (and likewise for mems) to the new cgroup.
*/
rcu_read_lock();
cpuset_for_each_child(tmp_cs, pos_css, parent) {
if (is_mem_exclusive(tmp_cs) || is_cpu_exclusive(tmp_cs)) {
rcu_read_unlock();
goto out_unlock;
}
}
rcu_read_unlock();
spin_lock_irq(&callback_lock);
cs->mems_allowed = parent->mems_allowed;
cs->effective_mems = parent->mems_allowed;
cpumask_copy(cs->cpus_allowed, parent->cpus_allowed);
cpumask_copy(cs->effective_cpus, parent->cpus_allowed);
spin_unlock_irq(&callback_lock);
out_unlock:
mutex_unlock(&cpuset_mutex);
return 0;
}
/*
* If the cpuset being removed has its flag 'sched_load_balance'
* enabled, then simulate turning sched_load_balance off, which
* will call rebuild_sched_domains_locked().
*/
static void cpuset_css_offline(struct cgroup_subsys_state *css)
{
struct cpuset *cs = css_cs(css);
mutex_lock(&cpuset_mutex);
if (is_sched_load_balance(cs))
update_flag(CS_SCHED_LOAD_BALANCE, cs, 0);
cpuset_dec();
clear_bit(CS_ONLINE, &cs->flags);
mutex_unlock(&cpuset_mutex);
}
static void cpuset_css_free(struct cgroup_subsys_state *css)
{
struct cpuset *cs = css_cs(css);
free_cpumask_var(cs->effective_cpus);
free_cpumask_var(cs->cpus_allowed);
kfree(cs);
}
static void cpuset_bind(struct cgroup_subsys_state *root_css)
{
mutex_lock(&cpuset_mutex);
spin_lock_irq(&callback_lock);
if (cgroup_on_dfl(root_css->cgroup)) {
cpumask_copy(top_cpuset.cpus_allowed, cpu_possible_mask);
top_cpuset.mems_allowed = node_possible_map;
} else {
cpumask_copy(top_cpuset.cpus_allowed,
top_cpuset.effective_cpus);
top_cpuset.mems_allowed = top_cpuset.effective_mems;
}
spin_unlock_irq(&callback_lock);
mutex_unlock(&cpuset_mutex);
}
struct cgroup_subsys cpuset_cgrp_subsys = {
.css_alloc = cpuset_css_alloc,
.css_online = cpuset_css_online,
.css_offline = cpuset_css_offline,
.css_free = cpuset_css_free,
.can_attach = cpuset_can_attach,
.cancel_attach = cpuset_cancel_attach,
.attach = cpuset_attach,
.bind = cpuset_bind,
.legacy_cftypes = files,
.early_init = 1,
};
/**
* cpuset_init - initialize cpusets at system boot
*
* Description: Initialize top_cpuset and the cpuset internal file system,
**/
int __init cpuset_init(void)
{
int err = 0;
if (!alloc_cpumask_var(&top_cpuset.cpus_allowed, GFP_KERNEL))
BUG();
if (!alloc_cpumask_var(&top_cpuset.effective_cpus, GFP_KERNEL))
BUG();
cpumask_setall(top_cpuset.cpus_allowed);
nodes_setall(top_cpuset.mems_allowed);
cpumask_setall(top_cpuset.effective_cpus);
nodes_setall(top_cpuset.effective_mems);
fmeter_init(&top_cpuset.fmeter);
set_bit(CS_SCHED_LOAD_BALANCE, &top_cpuset.flags);
top_cpuset.relax_domain_level = -1;
err = register_filesystem(&cpuset_fs_type);
if (err < 0)
return err;
if (!alloc_cpumask_var(&cpus_attach, GFP_KERNEL))
BUG();
return 0;
}
/*
* If CPU and/or memory hotplug handlers, below, unplug any CPUs
* or memory nodes, we need to walk over the cpuset hierarchy,
* removing that CPU or node from all cpusets. If this removes the
* last CPU or node from a cpuset, then move the tasks in the empty
* cpuset to its next-highest non-empty parent.
*/
static void remove_tasks_in_empty_cpuset(struct cpuset *cs)
{
struct cpuset *parent;
/*
* Find its next-highest non-empty parent, (top cpuset
* has online cpus, so can't be empty).
*/
parent = parent_cs(cs);
while (cpumask_empty(parent->cpus_allowed) ||
nodes_empty(parent->mems_allowed))
parent = parent_cs(parent);
if (cgroup_transfer_tasks(parent->css.cgroup, cs->css.cgroup)) {
pr_err("cpuset: failed to transfer tasks out of empty cpuset ");
pr_cont_cgroup_name(cs->css.cgroup);
pr_cont("\n");
}
}
static void
hotplug_update_tasks_legacy(struct cpuset *cs,
struct cpumask *new_cpus, nodemask_t *new_mems,
bool cpus_updated, bool mems_updated)
{
bool is_empty;
spin_lock_irq(&callback_lock);
cpumask_copy(cs->cpus_allowed, new_cpus);
cpumask_copy(cs->effective_cpus, new_cpus);
cs->mems_allowed = *new_mems;
cs->effective_mems = *new_mems;
spin_unlock_irq(&callback_lock);
/*
* Don't call update_tasks_cpumask() if the cpuset becomes empty,
* as the tasks will be migratecd to an ancestor.
*/
if (cpus_updated && !cpumask_empty(cs->cpus_allowed))
update_tasks_cpumask(cs);
if (mems_updated && !nodes_empty(cs->mems_allowed))
update_tasks_nodemask(cs);
is_empty = cpumask_empty(cs->cpus_allowed) ||
nodes_empty(cs->mems_allowed);
mutex_unlock(&cpuset_mutex);
/*
* Move tasks to the nearest ancestor with execution resources,
* This is full cgroup operation which will also call back into
* cpuset. Should be done outside any lock.
*/
if (is_empty)
remove_tasks_in_empty_cpuset(cs);
mutex_lock(&cpuset_mutex);
}
static void
hotplug_update_tasks(struct cpuset *cs,
struct cpumask *new_cpus, nodemask_t *new_mems,
bool cpus_updated, bool mems_updated)
{
if (cpumask_empty(new_cpus))
cpumask_copy(new_cpus, parent_cs(cs)->effective_cpus);
if (nodes_empty(*new_mems))
*new_mems = parent_cs(cs)->effective_mems;
spin_lock_irq(&callback_lock);
cpumask_copy(cs->effective_cpus, new_cpus);
cs->effective_mems = *new_mems;
spin_unlock_irq(&callback_lock);
if (cpus_updated)
update_tasks_cpumask(cs);
if (mems_updated)
update_tasks_nodemask(cs);
}
/**
* cpuset_hotplug_update_tasks - update tasks in a cpuset for hotunplug
* @cs: cpuset in interest
*
* Compare @cs's cpu and mem masks against top_cpuset and if some have gone
* offline, update @cs accordingly. If @cs ends up with no CPU or memory,
* all its tasks are moved to the nearest ancestor with both resources.
*/
static void cpuset_hotplug_update_tasks(struct cpuset *cs)
{
static cpumask_t new_cpus;
static nodemask_t new_mems;
bool cpus_updated;
bool mems_updated;
retry:
wait_event(cpuset_attach_wq, cs->attach_in_progress == 0);
mutex_lock(&cpuset_mutex);
/*
* We have raced with task attaching. We wait until attaching
* is finished, so we won't attach a task to an empty cpuset.
*/
if (cs->attach_in_progress) {
mutex_unlock(&cpuset_mutex);
goto retry;
}
cpumask_and(&new_cpus, cs->cpus_allowed, parent_cs(cs)->effective_cpus);
nodes_and(new_mems, cs->mems_allowed, parent_cs(cs)->effective_mems);
cpus_updated = !cpumask_equal(&new_cpus, cs->effective_cpus);
mems_updated = !nodes_equal(new_mems, cs->effective_mems);
if (cgroup_on_dfl(cs->css.cgroup))
hotplug_update_tasks(cs, &new_cpus, &new_mems,
cpus_updated, mems_updated);
else
hotplug_update_tasks_legacy(cs, &new_cpus, &new_mems,
cpus_updated, mems_updated);
mutex_unlock(&cpuset_mutex);
}
/**
* cpuset_hotplug_workfn - handle CPU/memory hotunplug for a cpuset
*
* This function is called after either CPU or memory configuration has
* changed and updates cpuset accordingly. The top_cpuset is always
* synchronized to cpu_active_mask and N_MEMORY, which is necessary in
* order to make cpusets transparent (of no affect) on systems that are
* actively using CPU hotplug but making no active use of cpusets.
*
* Non-root cpusets are only affected by offlining. If any CPUs or memory
* nodes have been taken down, cpuset_hotplug_update_tasks() is invoked on
* all descendants.
*
* Note that CPU offlining during suspend is ignored. We don't modify
* cpusets across suspend/resume cycles at all.
*/
static void cpuset_hotplug_workfn(struct work_struct *work)
{
static cpumask_t new_cpus;
static nodemask_t new_mems;
bool cpus_updated, mems_updated;
bool on_dfl = cgroup_on_dfl(top_cpuset.css.cgroup);
mutex_lock(&cpuset_mutex);
/* fetch the available cpus/mems and find out which changed how */
cpumask_copy(&new_cpus, cpu_active_mask);
new_mems = node_states[N_MEMORY];
cpus_updated = !cpumask_equal(top_cpuset.effective_cpus, &new_cpus);
mems_updated = !nodes_equal(top_cpuset.effective_mems, new_mems);
/* synchronize cpus_allowed to cpu_active_mask */
if (cpus_updated) {
spin_lock_irq(&callback_lock);
if (!on_dfl)
cpumask_copy(top_cpuset.cpus_allowed, &new_cpus);
cpumask_copy(top_cpuset.effective_cpus, &new_cpus);
spin_unlock_irq(&callback_lock);
/* we don't mess with cpumasks of tasks in top_cpuset */
}
/* synchronize mems_allowed to N_MEMORY */
if (mems_updated) {
spin_lock_irq(&callback_lock);
if (!on_dfl)
top_cpuset.mems_allowed = new_mems;
top_cpuset.effective_mems = new_mems;
spin_unlock_irq(&callback_lock);
update_tasks_nodemask(&top_cpuset);
}
mutex_unlock(&cpuset_mutex);
/* if cpus or mems changed, we need to propagate to descendants */
if (cpus_updated || mems_updated) {
struct cpuset *cs;
struct cgroup_subsys_state *pos_css;
rcu_read_lock();
cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
if (cs == &top_cpuset || !css_tryget_online(&cs->css))
continue;
rcu_read_unlock();
cpuset_hotplug_update_tasks(cs);
rcu_read_lock();
css_put(&cs->css);
}
rcu_read_unlock();
}
/* rebuild sched domains if cpus_allowed has changed */
if (cpus_updated)
rebuild_sched_domains();
}
void cpuset_update_active_cpus(bool cpu_online)
{
/*
* We're inside cpu hotplug critical region which usually nests
* inside cgroup synchronization. Bounce actual hotplug processing
* to a work item to avoid reverse locking order.
*
* We still need to do partition_sched_domains() synchronously;
* otherwise, the scheduler will get confused and put tasks to the
* dead CPU. Fall back to the default single domain.
* cpuset_hotplug_workfn() will rebuild it as necessary.
*/
partition_sched_domains(1, NULL, NULL);
schedule_work(&cpuset_hotplug_work);
}
/*
* Keep top_cpuset.mems_allowed tracking node_states[N_MEMORY].
* Call this routine anytime after node_states[N_MEMORY] changes.
* See cpuset_update_active_cpus() for CPU hotplug handling.
*/
static int cpuset_track_online_nodes(struct notifier_block *self,
unsigned long action, void *arg)
{
schedule_work(&cpuset_hotplug_work);
return NOTIFY_OK;
}
static struct notifier_block cpuset_track_online_nodes_nb = {
.notifier_call = cpuset_track_online_nodes,
.priority = 10, /* ??! */
};
/**
* cpuset_init_smp - initialize cpus_allowed
*
* Description: Finish top cpuset after cpu, node maps are initialized
*/
void __init cpuset_init_smp(void)
{
cpumask_copy(top_cpuset.cpus_allowed, cpu_active_mask);
top_cpuset.mems_allowed = node_states[N_MEMORY];
top_cpuset.old_mems_allowed = top_cpuset.mems_allowed;
cpumask_copy(top_cpuset.effective_cpus, cpu_active_mask);
top_cpuset.effective_mems = node_states[N_MEMORY];
register_hotmemory_notifier(&cpuset_track_online_nodes_nb);
}
/**
* cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
* @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
* @pmask: pointer to struct cpumask variable to receive cpus_allowed set.
*
* Description: Returns the cpumask_var_t cpus_allowed of the cpuset
* attached to the specified @tsk. Guaranteed to return some non-empty
* subset of cpu_online_mask, even if this means going outside the
* tasks cpuset.
**/
void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
{
unsigned long flags;
spin_lock_irqsave(&callback_lock, flags);
rcu_read_lock();
guarantee_online_cpus(task_cs(tsk), pmask);
rcu_read_unlock();
spin_unlock_irqrestore(&callback_lock, flags);
}
void cpuset_cpus_allowed_fallback(struct task_struct *tsk)
{
rcu_read_lock();
do_set_cpus_allowed(tsk, task_cs(tsk)->effective_cpus);
rcu_read_unlock();
/*
* We own tsk->cpus_allowed, nobody can change it under us.
*
* But we used cs && cs->cpus_allowed lockless and thus can
* race with cgroup_attach_task() or update_cpumask() and get
* the wrong tsk->cpus_allowed. However, both cases imply the
* subsequent cpuset_change_cpumask()->set_cpus_allowed_ptr()
* which takes task_rq_lock().
*
* If we are called after it dropped the lock we must see all
* changes in tsk_cs()->cpus_allowed. Otherwise we can temporary
* set any mask even if it is not right from task_cs() pov,
* the pending set_cpus_allowed_ptr() will fix things.
*
* select_fallback_rq() will fix things ups and set cpu_possible_mask
* if required.
*/
}
void __init cpuset_init_current_mems_allowed(void)
{
nodes_setall(current->mems_allowed);
}
/**
* cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
* @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
*
* Description: Returns the nodemask_t mems_allowed of the cpuset
* attached to the specified @tsk. Guaranteed to return some non-empty
* subset of node_states[N_MEMORY], even if this means going outside the
* tasks cpuset.
**/
nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
{
nodemask_t mask;
unsigned long flags;
spin_lock_irqsave(&callback_lock, flags);
rcu_read_lock();
guarantee_online_mems(task_cs(tsk), &mask);
rcu_read_unlock();
spin_unlock_irqrestore(&callback_lock, flags);
return mask;
}
/**
* cpuset_nodemask_valid_mems_allowed - check nodemask vs. curremt mems_allowed
* @nodemask: the nodemask to be checked
*
* Are any of the nodes in the nodemask allowed in current->mems_allowed?
*/
int cpuset_nodemask_valid_mems_allowed(nodemask_t *nodemask)
{
return nodes_intersects(*nodemask, current->mems_allowed);
}
/*
* nearest_hardwall_ancestor() - Returns the nearest mem_exclusive or
* mem_hardwall ancestor to the specified cpuset. Call holding
* callback_lock. If no ancestor is mem_exclusive or mem_hardwall
* (an unusual configuration), then returns the root cpuset.
*/
static struct cpuset *nearest_hardwall_ancestor(struct cpuset *cs)
{
while (!(is_mem_exclusive(cs) || is_mem_hardwall(cs)) && parent_cs(cs))
cs = parent_cs(cs);
return cs;
}
/**
* cpuset_node_allowed - Can we allocate on a memory node?
* @node: is this an allowed node?
* @gfp_mask: memory allocation flags
*
* If we're in interrupt, yes, we can always allocate. If @node is set in
* current's mems_allowed, yes. If it's not a __GFP_HARDWALL request and this
* node is set in the nearest hardwalled cpuset ancestor to current's cpuset,
* yes. If current has access to memory reserves due to TIF_MEMDIE, yes.
* Otherwise, no.
*
* GFP_USER allocations are marked with the __GFP_HARDWALL bit,
* and do not allow allocations outside the current tasks cpuset
* unless the task has been OOM killed as is marked TIF_MEMDIE.
* GFP_KERNEL allocations are not so marked, so can escape to the
* nearest enclosing hardwalled ancestor cpuset.
*
* Scanning up parent cpusets requires callback_lock. The
* __alloc_pages() routine only calls here with __GFP_HARDWALL bit
* _not_ set if it's a GFP_KERNEL allocation, and all nodes in the
* current tasks mems_allowed came up empty on the first pass over
* the zonelist. So only GFP_KERNEL allocations, if all nodes in the
* cpuset are short of memory, might require taking the callback_lock.
*
* The first call here from mm/page_alloc:get_page_from_freelist()
* has __GFP_HARDWALL set in gfp_mask, enforcing hardwall cpusets,
* so no allocation on a node outside the cpuset is allowed (unless
* in interrupt, of course).
*
* The second pass through get_page_from_freelist() doesn't even call
* here for GFP_ATOMIC calls. For those calls, the __alloc_pages()
* variable 'wait' is not set, and the bit ALLOC_CPUSET is not set
* in alloc_flags. That logic and the checks below have the combined
* affect that:
* in_interrupt - any node ok (current task context irrelevant)
* GFP_ATOMIC - any node ok
* TIF_MEMDIE - any node ok
* GFP_KERNEL - any node in enclosing hardwalled cpuset ok
* GFP_USER - only nodes in current tasks mems allowed ok.
*/
int __cpuset_node_allowed(int node, gfp_t gfp_mask)
{
struct cpuset *cs; /* current cpuset ancestors */
int allowed; /* is allocation in zone z allowed? */
unsigned long flags;
if (in_interrupt())
return 1;
if (node_isset(node, current->mems_allowed))
return 1;
/*
* Allow tasks that have access to memory reserves because they have
* been OOM killed to get memory anywhere.
*/
if (unlikely(test_thread_flag(TIF_MEMDIE)))
return 1;
if (gfp_mask & __GFP_HARDWALL) /* If hardwall request, stop here */
return 0;
if (current->flags & PF_EXITING) /* Let dying task have memory */
return 1;
/* Not hardwall and node outside mems_allowed: scan up cpusets */
spin_lock_irqsave(&callback_lock, flags);
rcu_read_lock();
cs = nearest_hardwall_ancestor(task_cs(current));
allowed = node_isset(node, cs->mems_allowed);
rcu_read_unlock();
spin_unlock_irqrestore(&callback_lock, flags);
return allowed;
}
/**
* cpuset_mem_spread_node() - On which node to begin search for a file page
* cpuset_slab_spread_node() - On which node to begin search for a slab page
*
* If a task is marked PF_SPREAD_PAGE or PF_SPREAD_SLAB (as for
* tasks in a cpuset with is_spread_page or is_spread_slab set),
* and if the memory allocation used cpuset_mem_spread_node()
* to determine on which node to start looking, as it will for
* certain page cache or slab cache pages such as used for file
* system buffers and inode caches, then instead of starting on the
* local node to look for a free page, rather spread the starting
* node around the tasks mems_allowed nodes.
*
* We don't have to worry about the returned node being offline
* because "it can't happen", and even if it did, it would be ok.
*
* The routines calling guarantee_online_mems() are careful to
* only set nodes in task->mems_allowed that are online. So it
* should not be possible for the following code to return an
* offline node. But if it did, that would be ok, as this routine
* is not returning the node where the allocation must be, only
* the node where the search should start. The zonelist passed to
* __alloc_pages() will include all nodes. If the slab allocator
* is passed an offline node, it will fall back to the local node.
* See kmem_cache_alloc_node().
*/
static int cpuset_spread_node(int *rotor)
{
int node;
node = next_node(*rotor, current->mems_allowed);
if (node == MAX_NUMNODES)
node = first_node(current->mems_allowed);
*rotor = node;
return node;
}
int cpuset_mem_spread_node(void)
{
if (current->cpuset_mem_spread_rotor == NUMA_NO_NODE)
current->cpuset_mem_spread_rotor =
node_random(¤t->mems_allowed);
return cpuset_spread_node(¤t->cpuset_mem_spread_rotor);
}
int cpuset_slab_spread_node(void)
{
if (current->cpuset_slab_spread_rotor == NUMA_NO_NODE)
current->cpuset_slab_spread_rotor =
node_random(¤t->mems_allowed);
return cpuset_spread_node(¤t->cpuset_slab_spread_rotor);
}
EXPORT_SYMBOL_GPL(cpuset_mem_spread_node);
/**
* cpuset_mems_allowed_intersects - Does @tsk1's mems_allowed intersect @tsk2's?
* @tsk1: pointer to task_struct of some task.
* @tsk2: pointer to task_struct of some other task.
*
* Description: Return true if @tsk1's mems_allowed intersects the
* mems_allowed of @tsk2. Used by the OOM killer to determine if
* one of the task's memory usage might impact the memory available
* to the other.
**/
int cpuset_mems_allowed_intersects(const struct task_struct *tsk1,
const struct task_struct *tsk2)
{
return nodes_intersects(tsk1->mems_allowed, tsk2->mems_allowed);
}
/**
* cpuset_print_task_mems_allowed - prints task's cpuset and mems_allowed
* @tsk: pointer to task_struct of some task.
*
* Description: Prints @task's name, cpuset name, and cached copy of its
* mems_allowed to the kernel log.
*/
void cpuset_print_task_mems_allowed(struct task_struct *tsk)
{
struct cgroup *cgrp;
rcu_read_lock();
cgrp = task_cs(tsk)->css.cgroup;
pr_info("%s cpuset=", tsk->comm);
pr_cont_cgroup_name(cgrp);
pr_cont(" mems_allowed=%*pbl\n", nodemask_pr_args(&tsk->mems_allowed));
rcu_read_unlock();
}
/*
* Collection of memory_pressure is suppressed unless
* this flag is enabled by writing "1" to the special
* cpuset file 'memory_pressure_enabled' in the root cpuset.
*/
int cpuset_memory_pressure_enabled __read_mostly;
/**
* cpuset_memory_pressure_bump - keep stats of per-cpuset reclaims.
*
* Keep a running average of the rate of synchronous (direct)
* page reclaim efforts initiated by tasks in each cpuset.
*
* This represents the rate at which some task in the cpuset
* ran low on memory on all nodes it was allowed to use, and
* had to enter the kernels page reclaim code in an effort to
* create more free memory by tossing clean pages or swapping
* or writing dirty pages.
*
* Display to user space in the per-cpuset read-only file
* "memory_pressure". Value displayed is an integer
* representing the recent rate of entry into the synchronous
* (direct) page reclaim by any task attached to the cpuset.
**/
void __cpuset_memory_pressure_bump(void)
{
rcu_read_lock();
fmeter_markevent(&task_cs(current)->fmeter);
rcu_read_unlock();
}
#ifdef CONFIG_PROC_PID_CPUSET
/*
* proc_cpuset_show()
* - Print tasks cpuset path into seq_file.
* - Used for /proc/<pid>/cpuset.
* - No need to task_lock(tsk) on this tsk->cpuset reference, as it
* doesn't really matter if tsk->cpuset changes after we read it,
* and we take cpuset_mutex, keeping cpuset_attach() from changing it
* anyway.
*/
int proc_cpuset_show(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *tsk)
{
char *buf, *p;
struct cgroup_subsys_state *css;
int retval;
retval = -ENOMEM;
buf = kmalloc(PATH_MAX, GFP_KERNEL);
if (!buf)
goto out;
retval = -ENAMETOOLONG;
rcu_read_lock();
css = task_css(tsk, cpuset_cgrp_id);
p = cgroup_path(css->cgroup, buf, PATH_MAX);
rcu_read_unlock();
if (!p)
goto out_free;
seq_puts(m, p);
seq_putc(m, '\n');
retval = 0;
out_free:
kfree(buf);
out:
return retval;
}
#endif /* CONFIG_PROC_PID_CPUSET */
/* Display task mems_allowed in /proc/<pid>/status file. */
void cpuset_task_status_allowed(struct seq_file *m, struct task_struct *task)
{
seq_printf(m, "Mems_allowed:\t%*pb\n",
nodemask_pr_args(&task->mems_allowed));
seq_printf(m, "Mems_allowed_list:\t%*pbl\n",
nodemask_pr_args(&task->mems_allowed));
}
| gpl-2.0 |
Kali-/htc-kernel | arch/powerpc/sysdev/qe_lib/gpio.c | 768 | 8789 | /*
* QUICC Engine GPIOs
*
* Copyright (c) MontaVista Software, Inc. 2008.
*
* Author: Anton Vorontsov <avorontsov@ru.mvista.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/of_gpio.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#include <asm/qe.h>
struct qe_gpio_chip {
struct of_mm_gpio_chip mm_gc;
spinlock_t lock;
unsigned long pin_flags[QE_PIO_PINS];
#define QE_PIN_REQUESTED 0
/* shadowed data register to clear/set bits safely */
u32 cpdata;
/* saved_regs used to restore dedicated functions */
struct qe_pio_regs saved_regs;
};
static inline struct qe_gpio_chip *
to_qe_gpio_chip(struct of_mm_gpio_chip *mm_gc)
{
return container_of(mm_gc, struct qe_gpio_chip, mm_gc);
}
static void qe_gpio_save_regs(struct of_mm_gpio_chip *mm_gc)
{
struct qe_gpio_chip *qe_gc = to_qe_gpio_chip(mm_gc);
struct qe_pio_regs __iomem *regs = mm_gc->regs;
qe_gc->cpdata = in_be32(®s->cpdata);
qe_gc->saved_regs.cpdata = qe_gc->cpdata;
qe_gc->saved_regs.cpdir1 = in_be32(®s->cpdir1);
qe_gc->saved_regs.cpdir2 = in_be32(®s->cpdir2);
qe_gc->saved_regs.cppar1 = in_be32(®s->cppar1);
qe_gc->saved_regs.cppar2 = in_be32(®s->cppar2);
qe_gc->saved_regs.cpodr = in_be32(®s->cpodr);
}
static int qe_gpio_get(struct gpio_chip *gc, unsigned int gpio)
{
struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc);
struct qe_pio_regs __iomem *regs = mm_gc->regs;
u32 pin_mask = 1 << (QE_PIO_PINS - 1 - gpio);
return in_be32(®s->cpdata) & pin_mask;
}
static void qe_gpio_set(struct gpio_chip *gc, unsigned int gpio, int val)
{
struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc);
struct qe_gpio_chip *qe_gc = to_qe_gpio_chip(mm_gc);
struct qe_pio_regs __iomem *regs = mm_gc->regs;
unsigned long flags;
u32 pin_mask = 1 << (QE_PIO_PINS - 1 - gpio);
spin_lock_irqsave(&qe_gc->lock, flags);
if (val)
qe_gc->cpdata |= pin_mask;
else
qe_gc->cpdata &= ~pin_mask;
out_be32(®s->cpdata, qe_gc->cpdata);
spin_unlock_irqrestore(&qe_gc->lock, flags);
}
static int qe_gpio_dir_in(struct gpio_chip *gc, unsigned int gpio)
{
struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc);
struct qe_gpio_chip *qe_gc = to_qe_gpio_chip(mm_gc);
unsigned long flags;
spin_lock_irqsave(&qe_gc->lock, flags);
__par_io_config_pin(mm_gc->regs, gpio, QE_PIO_DIR_IN, 0, 0, 0);
spin_unlock_irqrestore(&qe_gc->lock, flags);
return 0;
}
static int qe_gpio_dir_out(struct gpio_chip *gc, unsigned int gpio, int val)
{
struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc);
struct qe_gpio_chip *qe_gc = to_qe_gpio_chip(mm_gc);
unsigned long flags;
qe_gpio_set(gc, gpio, val);
spin_lock_irqsave(&qe_gc->lock, flags);
__par_io_config_pin(mm_gc->regs, gpio, QE_PIO_DIR_OUT, 0, 0, 0);
spin_unlock_irqrestore(&qe_gc->lock, flags);
return 0;
}
struct qe_pin {
/*
* The qe_gpio_chip name is unfortunate, we should change that to
* something like qe_pio_controller. Someday.
*/
struct qe_gpio_chip *controller;
int num;
};
/**
* qe_pin_request - Request a QE pin
* @np: device node to get a pin from
* @index: index of a pin in the device tree
* Context: non-atomic
*
* This function return qe_pin so that you could use it with the rest of
* the QE Pin Multiplexing API.
*/
struct qe_pin *qe_pin_request(struct device_node *np, int index)
{
struct qe_pin *qe_pin;
struct device_node *gc;
struct of_gpio_chip *of_gc = NULL;
struct of_mm_gpio_chip *mm_gc;
struct qe_gpio_chip *qe_gc;
int err;
int size;
const void *gpio_spec;
const u32 *gpio_cells;
unsigned long flags;
qe_pin = kzalloc(sizeof(*qe_pin), GFP_KERNEL);
if (!qe_pin) {
pr_debug("%s: can't allocate memory\n", __func__);
return ERR_PTR(-ENOMEM);
}
err = of_parse_phandles_with_args(np, "gpios", "#gpio-cells", index,
&gc, &gpio_spec);
if (err) {
pr_debug("%s: can't parse gpios property\n", __func__);
goto err0;
}
if (!of_device_is_compatible(gc, "fsl,mpc8323-qe-pario-bank")) {
pr_debug("%s: tried to get a non-qe pin\n", __func__);
err = -EINVAL;
goto err1;
}
of_gc = gc->data;
if (!of_gc) {
pr_debug("%s: gpio controller %s isn't registered\n",
np->full_name, gc->full_name);
err = -ENODEV;
goto err1;
}
gpio_cells = of_get_property(gc, "#gpio-cells", &size);
if (!gpio_cells || size != sizeof(*gpio_cells) ||
*gpio_cells != of_gc->gpio_cells) {
pr_debug("%s: wrong #gpio-cells for %s\n",
np->full_name, gc->full_name);
err = -EINVAL;
goto err1;
}
err = of_gc->xlate(of_gc, np, gpio_spec, NULL);
if (err < 0)
goto err1;
mm_gc = to_of_mm_gpio_chip(&of_gc->gc);
qe_gc = to_qe_gpio_chip(mm_gc);
spin_lock_irqsave(&qe_gc->lock, flags);
if (test_and_set_bit(QE_PIN_REQUESTED, &qe_gc->pin_flags[err]) == 0) {
qe_pin->controller = qe_gc;
qe_pin->num = err;
err = 0;
} else {
err = -EBUSY;
}
spin_unlock_irqrestore(&qe_gc->lock, flags);
if (!err)
return qe_pin;
err1:
of_node_put(gc);
err0:
kfree(qe_pin);
pr_debug("%s failed with status %d\n", __func__, err);
return ERR_PTR(err);
}
EXPORT_SYMBOL(qe_pin_request);
/**
* qe_pin_free - Free a pin
* @qe_pin: pointer to the qe_pin structure
* Context: any
*
* This function frees the qe_pin structure and makes a pin available
* for further qe_pin_request() calls.
*/
void qe_pin_free(struct qe_pin *qe_pin)
{
struct qe_gpio_chip *qe_gc = qe_pin->controller;
unsigned long flags;
const int pin = qe_pin->num;
spin_lock_irqsave(&qe_gc->lock, flags);
test_and_clear_bit(QE_PIN_REQUESTED, &qe_gc->pin_flags[pin]);
spin_unlock_irqrestore(&qe_gc->lock, flags);
kfree(qe_pin);
}
EXPORT_SYMBOL(qe_pin_free);
/**
* qe_pin_set_dedicated - Revert a pin to a dedicated peripheral function mode
* @qe_pin: pointer to the qe_pin structure
* Context: any
*
* This function resets a pin to a dedicated peripheral function that
* has been set up by the firmware.
*/
void qe_pin_set_dedicated(struct qe_pin *qe_pin)
{
struct qe_gpio_chip *qe_gc = qe_pin->controller;
struct qe_pio_regs __iomem *regs = qe_gc->mm_gc.regs;
struct qe_pio_regs *sregs = &qe_gc->saved_regs;
int pin = qe_pin->num;
u32 mask1 = 1 << (QE_PIO_PINS - (pin + 1));
u32 mask2 = 0x3 << (QE_PIO_PINS - (pin % (QE_PIO_PINS / 2) + 1) * 2);
bool second_reg = pin > (QE_PIO_PINS / 2) - 1;
unsigned long flags;
spin_lock_irqsave(&qe_gc->lock, flags);
if (second_reg) {
clrsetbits_be32(®s->cpdir2, mask2, sregs->cpdir2 & mask2);
clrsetbits_be32(®s->cppar2, mask2, sregs->cppar2 & mask2);
} else {
clrsetbits_be32(®s->cpdir1, mask2, sregs->cpdir1 & mask2);
clrsetbits_be32(®s->cppar1, mask2, sregs->cppar1 & mask2);
}
if (sregs->cpdata & mask1)
qe_gc->cpdata |= mask1;
else
qe_gc->cpdata &= ~mask1;
out_be32(®s->cpdata, qe_gc->cpdata);
clrsetbits_be32(®s->cpodr, mask1, sregs->cpodr & mask1);
spin_unlock_irqrestore(&qe_gc->lock, flags);
}
EXPORT_SYMBOL(qe_pin_set_dedicated);
/**
* qe_pin_set_gpio - Set a pin to the GPIO mode
* @qe_pin: pointer to the qe_pin structure
* Context: any
*
* This function sets a pin to the GPIO mode.
*/
void qe_pin_set_gpio(struct qe_pin *qe_pin)
{
struct qe_gpio_chip *qe_gc = qe_pin->controller;
struct qe_pio_regs __iomem *regs = qe_gc->mm_gc.regs;
unsigned long flags;
spin_lock_irqsave(&qe_gc->lock, flags);
/* Let's make it input by default, GPIO API is able to change that. */
__par_io_config_pin(regs, qe_pin->num, QE_PIO_DIR_IN, 0, 0, 0);
spin_unlock_irqrestore(&qe_gc->lock, flags);
}
EXPORT_SYMBOL(qe_pin_set_gpio);
static int __init qe_add_gpiochips(void)
{
struct device_node *np;
for_each_compatible_node(np, NULL, "fsl,mpc8323-qe-pario-bank") {
int ret;
struct qe_gpio_chip *qe_gc;
struct of_mm_gpio_chip *mm_gc;
struct of_gpio_chip *of_gc;
struct gpio_chip *gc;
qe_gc = kzalloc(sizeof(*qe_gc), GFP_KERNEL);
if (!qe_gc) {
ret = -ENOMEM;
goto err;
}
spin_lock_init(&qe_gc->lock);
mm_gc = &qe_gc->mm_gc;
of_gc = &mm_gc->of_gc;
gc = &of_gc->gc;
mm_gc->save_regs = qe_gpio_save_regs;
of_gc->gpio_cells = 2;
gc->ngpio = QE_PIO_PINS;
gc->direction_input = qe_gpio_dir_in;
gc->direction_output = qe_gpio_dir_out;
gc->get = qe_gpio_get;
gc->set = qe_gpio_set;
ret = of_mm_gpiochip_add(np, mm_gc);
if (ret)
goto err;
continue;
err:
pr_err("%s: registration failed with status %d\n",
np->full_name, ret);
kfree(qe_gc);
/* try others anyway */
}
return 0;
}
arch_initcall(qe_add_gpiochips);
| gpl-2.0 |
jackalchen/linux | net/sunrpc/auth_gss/gss_krb5_seqnum.c | 1024 | 4638 | /*
* linux/net/sunrpc/gss_krb5_seqnum.c
*
* Adapted from MIT Kerberos 5-1.2.1 lib/gssapi/krb5/util_seqnum.c
*
* Copyright (c) 2000 The Regents of the University of Michigan.
* All rights reserved.
*
* Andy Adamson <andros@umich.edu>
*/
/*
* Copyright 1993 by OpenVision Technologies, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appears in all copies and
* that both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of OpenVision not be used
* in advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. OpenVision makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
* OPENVISION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL OPENVISION BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/types.h>
#include <linux/sunrpc/gss_krb5.h>
#include <linux/crypto.h>
#if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
# define RPCDBG_FACILITY RPCDBG_AUTH
#endif
static s32
krb5_make_rc4_seq_num(struct krb5_ctx *kctx, int direction, s32 seqnum,
unsigned char *cksum, unsigned char *buf)
{
struct crypto_blkcipher *cipher;
unsigned char plain[8];
s32 code;
dprintk("RPC: %s:\n", __func__);
cipher = crypto_alloc_blkcipher(kctx->gk5e->encrypt_name, 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(cipher))
return PTR_ERR(cipher);
plain[0] = (unsigned char) ((seqnum >> 24) & 0xff);
plain[1] = (unsigned char) ((seqnum >> 16) & 0xff);
plain[2] = (unsigned char) ((seqnum >> 8) & 0xff);
plain[3] = (unsigned char) ((seqnum >> 0) & 0xff);
plain[4] = direction;
plain[5] = direction;
plain[6] = direction;
plain[7] = direction;
code = krb5_rc4_setup_seq_key(kctx, cipher, cksum);
if (code)
goto out;
code = krb5_encrypt(cipher, cksum, plain, buf, 8);
out:
crypto_free_blkcipher(cipher);
return code;
}
s32
krb5_make_seq_num(struct krb5_ctx *kctx,
struct crypto_blkcipher *key,
int direction,
u32 seqnum,
unsigned char *cksum, unsigned char *buf)
{
unsigned char plain[8];
if (kctx->enctype == ENCTYPE_ARCFOUR_HMAC)
return krb5_make_rc4_seq_num(kctx, direction, seqnum,
cksum, buf);
plain[0] = (unsigned char) (seqnum & 0xff);
plain[1] = (unsigned char) ((seqnum >> 8) & 0xff);
plain[2] = (unsigned char) ((seqnum >> 16) & 0xff);
plain[3] = (unsigned char) ((seqnum >> 24) & 0xff);
plain[4] = direction;
plain[5] = direction;
plain[6] = direction;
plain[7] = direction;
return krb5_encrypt(key, cksum, plain, buf, 8);
}
static s32
krb5_get_rc4_seq_num(struct krb5_ctx *kctx, unsigned char *cksum,
unsigned char *buf, int *direction, s32 *seqnum)
{
struct crypto_blkcipher *cipher;
unsigned char plain[8];
s32 code;
dprintk("RPC: %s:\n", __func__);
cipher = crypto_alloc_blkcipher(kctx->gk5e->encrypt_name, 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(cipher))
return PTR_ERR(cipher);
code = krb5_rc4_setup_seq_key(kctx, cipher, cksum);
if (code)
goto out;
code = krb5_decrypt(cipher, cksum, buf, plain, 8);
if (code)
goto out;
if ((plain[4] != plain[5]) || (plain[4] != plain[6])
|| (plain[4] != plain[7])) {
code = (s32)KG_BAD_SEQ;
goto out;
}
*direction = plain[4];
*seqnum = ((plain[0] << 24) | (plain[1] << 16) |
(plain[2] << 8) | (plain[3]));
out:
crypto_free_blkcipher(cipher);
return code;
}
s32
krb5_get_seq_num(struct krb5_ctx *kctx,
unsigned char *cksum,
unsigned char *buf,
int *direction, u32 *seqnum)
{
s32 code;
unsigned char plain[8];
struct crypto_blkcipher *key = kctx->seq;
dprintk("RPC: krb5_get_seq_num:\n");
if (kctx->enctype == ENCTYPE_ARCFOUR_HMAC)
return krb5_get_rc4_seq_num(kctx, cksum, buf,
direction, seqnum);
if ((code = krb5_decrypt(key, cksum, buf, plain, 8)))
return code;
if ((plain[4] != plain[5]) || (plain[4] != plain[6]) ||
(plain[4] != plain[7]))
return (s32)KG_BAD_SEQ;
*direction = plain[4];
*seqnum = ((plain[0]) |
(plain[1] << 8) | (plain[2] << 16) | (plain[3] << 24));
return 0;
}
| gpl-2.0 |
direct-code-execution/net-next-sim | sound/arm/aaci.c | 1280 | 25391 | /*
* linux/sound/arm/aaci.c - ARM PrimeCell AACI PL041 driver
*
* Copyright (C) 2003 Deep Blue Solutions Ltd, 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 as
* published by the Free Software Foundation.
*
* Documentation: ARM DDI 0173B
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/err.h>
#include <linux/amba/bus.h>
#include <linux/io.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/ac97_codec.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include "aaci.h"
#define DRIVER_NAME "aaci-pl041"
#define FRAME_PERIOD_US 21
/*
* PM support is not complete. Turn it off.
*/
#undef CONFIG_PM
static void aaci_ac97_select_codec(struct aaci *aaci, struct snd_ac97 *ac97)
{
u32 v, maincr = aaci->maincr | MAINCR_SCRA(ac97->num);
/*
* Ensure that the slot 1/2 RX registers are empty.
*/
v = readl(aaci->base + AACI_SLFR);
if (v & SLFR_2RXV)
readl(aaci->base + AACI_SL2RX);
if (v & SLFR_1RXV)
readl(aaci->base + AACI_SL1RX);
if (maincr != readl(aaci->base + AACI_MAINCR)) {
writel(maincr, aaci->base + AACI_MAINCR);
readl(aaci->base + AACI_MAINCR);
udelay(1);
}
}
/*
* P29:
* The recommended use of programming the external codec through slot 1
* and slot 2 data is to use the channels during setup routines and the
* slot register at any other time. The data written into slot 1, slot 2
* and slot 12 registers is transmitted only when their corresponding
* SI1TxEn, SI2TxEn and SI12TxEn bits are set in the AACI_MAINCR
* register.
*/
static void aaci_ac97_write(struct snd_ac97 *ac97, unsigned short reg,
unsigned short val)
{
struct aaci *aaci = ac97->private_data;
int timeout;
u32 v;
if (ac97->num >= 4)
return;
mutex_lock(&aaci->ac97_sem);
aaci_ac97_select_codec(aaci, ac97);
/*
* P54: You must ensure that AACI_SL2TX is always written
* to, if required, before data is written to AACI_SL1TX.
*/
writel(val << 4, aaci->base + AACI_SL2TX);
writel(reg << 12, aaci->base + AACI_SL1TX);
/* Initially, wait one frame period */
udelay(FRAME_PERIOD_US);
/* And then wait an additional eight frame periods for it to be sent */
timeout = FRAME_PERIOD_US * 8;
do {
udelay(1);
v = readl(aaci->base + AACI_SLFR);
} while ((v & (SLFR_1TXB|SLFR_2TXB)) && --timeout);
if (v & (SLFR_1TXB|SLFR_2TXB))
dev_err(&aaci->dev->dev,
"timeout waiting for write to complete\n");
mutex_unlock(&aaci->ac97_sem);
}
/*
* Read an AC'97 register.
*/
static unsigned short aaci_ac97_read(struct snd_ac97 *ac97, unsigned short reg)
{
struct aaci *aaci = ac97->private_data;
int timeout, retries = 10;
u32 v;
if (ac97->num >= 4)
return ~0;
mutex_lock(&aaci->ac97_sem);
aaci_ac97_select_codec(aaci, ac97);
/*
* Write the register address to slot 1.
*/
writel((reg << 12) | (1 << 19), aaci->base + AACI_SL1TX);
/* Initially, wait one frame period */
udelay(FRAME_PERIOD_US);
/* And then wait an additional eight frame periods for it to be sent */
timeout = FRAME_PERIOD_US * 8;
do {
udelay(1);
v = readl(aaci->base + AACI_SLFR);
} while ((v & SLFR_1TXB) && --timeout);
if (v & SLFR_1TXB) {
dev_err(&aaci->dev->dev, "timeout on slot 1 TX busy\n");
v = ~0;
goto out;
}
/* Now wait for the response frame */
udelay(FRAME_PERIOD_US);
/* And then wait an additional eight frame periods for data */
timeout = FRAME_PERIOD_US * 8;
do {
udelay(1);
cond_resched();
v = readl(aaci->base + AACI_SLFR) & (SLFR_1RXV|SLFR_2RXV);
} while ((v != (SLFR_1RXV|SLFR_2RXV)) && --timeout);
if (v != (SLFR_1RXV|SLFR_2RXV)) {
dev_err(&aaci->dev->dev, "timeout on RX valid\n");
v = ~0;
goto out;
}
do {
v = readl(aaci->base + AACI_SL1RX) >> 12;
if (v == reg) {
v = readl(aaci->base + AACI_SL2RX) >> 4;
break;
} else if (--retries) {
dev_warn(&aaci->dev->dev,
"ac97 read back fail. retry\n");
continue;
} else {
dev_warn(&aaci->dev->dev,
"wrong ac97 register read back (%x != %x)\n",
v, reg);
v = ~0;
}
} while (retries);
out:
mutex_unlock(&aaci->ac97_sem);
return v;
}
static inline void
aaci_chan_wait_ready(struct aaci_runtime *aacirun, unsigned long mask)
{
u32 val;
int timeout = 5000;
do {
udelay(1);
val = readl(aacirun->base + AACI_SR);
} while (val & mask && timeout--);
}
/*
* Interrupt support.
*/
static void aaci_fifo_irq(struct aaci *aaci, int channel, u32 mask)
{
if (mask & ISR_ORINTR) {
dev_warn(&aaci->dev->dev, "RX overrun on chan %d\n", channel);
writel(ICLR_RXOEC1 << channel, aaci->base + AACI_INTCLR);
}
if (mask & ISR_RXTOINTR) {
dev_warn(&aaci->dev->dev, "RX timeout on chan %d\n", channel);
writel(ICLR_RXTOFEC1 << channel, aaci->base + AACI_INTCLR);
}
if (mask & ISR_RXINTR) {
struct aaci_runtime *aacirun = &aaci->capture;
bool period_elapsed = false;
void *ptr;
if (!aacirun->substream || !aacirun->start) {
dev_warn(&aaci->dev->dev, "RX interrupt???\n");
writel(0, aacirun->base + AACI_IE);
return;
}
spin_lock(&aacirun->lock);
ptr = aacirun->ptr;
do {
unsigned int len = aacirun->fifo_bytes;
u32 val;
if (aacirun->bytes <= 0) {
aacirun->bytes += aacirun->period;
period_elapsed = true;
}
if (!(aacirun->cr & CR_EN))
break;
val = readl(aacirun->base + AACI_SR);
if (!(val & SR_RXHF))
break;
if (!(val & SR_RXFF))
len >>= 1;
aacirun->bytes -= len;
/* reading 16 bytes at a time */
for( ; len > 0; len -= 16) {
asm(
"ldmia %1, {r0, r1, r2, r3}\n\t"
"stmia %0!, {r0, r1, r2, r3}"
: "+r" (ptr)
: "r" (aacirun->fifo)
: "r0", "r1", "r2", "r3", "cc");
if (ptr >= aacirun->end)
ptr = aacirun->start;
}
} while(1);
aacirun->ptr = ptr;
spin_unlock(&aacirun->lock);
if (period_elapsed)
snd_pcm_period_elapsed(aacirun->substream);
}
if (mask & ISR_URINTR) {
dev_dbg(&aaci->dev->dev, "TX underrun on chan %d\n", channel);
writel(ICLR_TXUEC1 << channel, aaci->base + AACI_INTCLR);
}
if (mask & ISR_TXINTR) {
struct aaci_runtime *aacirun = &aaci->playback;
bool period_elapsed = false;
void *ptr;
if (!aacirun->substream || !aacirun->start) {
dev_warn(&aaci->dev->dev, "TX interrupt???\n");
writel(0, aacirun->base + AACI_IE);
return;
}
spin_lock(&aacirun->lock);
ptr = aacirun->ptr;
do {
unsigned int len = aacirun->fifo_bytes;
u32 val;
if (aacirun->bytes <= 0) {
aacirun->bytes += aacirun->period;
period_elapsed = true;
}
if (!(aacirun->cr & CR_EN))
break;
val = readl(aacirun->base + AACI_SR);
if (!(val & SR_TXHE))
break;
if (!(val & SR_TXFE))
len >>= 1;
aacirun->bytes -= len;
/* writing 16 bytes at a time */
for ( ; len > 0; len -= 16) {
asm(
"ldmia %0!, {r0, r1, r2, r3}\n\t"
"stmia %1, {r0, r1, r2, r3}"
: "+r" (ptr)
: "r" (aacirun->fifo)
: "r0", "r1", "r2", "r3", "cc");
if (ptr >= aacirun->end)
ptr = aacirun->start;
}
} while (1);
aacirun->ptr = ptr;
spin_unlock(&aacirun->lock);
if (period_elapsed)
snd_pcm_period_elapsed(aacirun->substream);
}
}
static irqreturn_t aaci_irq(int irq, void *devid)
{
struct aaci *aaci = devid;
u32 mask;
int i;
mask = readl(aaci->base + AACI_ALLINTS);
if (mask) {
u32 m = mask;
for (i = 0; i < 4; i++, m >>= 7) {
if (m & 0x7f) {
aaci_fifo_irq(aaci, i, m);
}
}
}
return mask ? IRQ_HANDLED : IRQ_NONE;
}
/*
* ALSA support.
*/
static struct snd_pcm_hardware aaci_hw_info = {
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_RESUME,
/*
* ALSA doesn't support 18-bit or 20-bit packed into 32-bit
* words. It also doesn't support 12-bit at all.
*/
.formats = SNDRV_PCM_FMTBIT_S16_LE,
/* rates are setup from the AC'97 codec */
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = 64 * 1024,
.period_bytes_min = 256,
.period_bytes_max = PAGE_SIZE,
.periods_min = 4,
.periods_max = PAGE_SIZE / 16,
};
/*
* We can support two and four channel audio. Unfortunately
* six channel audio requires a non-standard channel ordering:
* 2 -> FL(3), FR(4)
* 4 -> FL(3), FR(4), SL(7), SR(8)
* 6 -> FL(3), FR(4), SL(7), SR(8), C(6), LFE(9) (required)
* FL(3), FR(4), C(6), SL(7), SR(8), LFE(9) (actual)
* This requires an ALSA configuration file to correct.
*/
static int aaci_rule_channels(struct snd_pcm_hw_params *p,
struct snd_pcm_hw_rule *rule)
{
static unsigned int channel_list[] = { 2, 4, 6 };
struct aaci *aaci = rule->private;
unsigned int mask = 1 << 0, slots;
/* pcms[0] is the our 5.1 PCM instance. */
slots = aaci->ac97_bus->pcms[0].r[0].slots;
if (slots & (1 << AC97_SLOT_PCM_SLEFT)) {
mask |= 1 << 1;
if (slots & (1 << AC97_SLOT_LFE))
mask |= 1 << 2;
}
return snd_interval_list(hw_param_interval(p, rule->var),
ARRAY_SIZE(channel_list), channel_list, mask);
}
static int aaci_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci *aaci = substream->private_data;
struct aaci_runtime *aacirun;
int ret = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
aacirun = &aaci->playback;
} else {
aacirun = &aaci->capture;
}
aacirun->substream = substream;
runtime->private_data = aacirun;
runtime->hw = aaci_hw_info;
runtime->hw.rates = aacirun->pcm->rates;
snd_pcm_limit_hw_rates(runtime);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
runtime->hw.channels_max = 6;
/* Add rule describing channel dependency. */
ret = snd_pcm_hw_rule_add(substream->runtime, 0,
SNDRV_PCM_HW_PARAM_CHANNELS,
aaci_rule_channels, aaci,
SNDRV_PCM_HW_PARAM_CHANNELS, -1);
if (ret)
return ret;
if (aacirun->pcm->r[1].slots)
snd_ac97_pcm_double_rate_rules(runtime);
}
/*
* ALSA wants the byte-size of the FIFOs. As we only support
* 16-bit samples, this is twice the FIFO depth irrespective
* of whether it's in compact mode or not.
*/
runtime->hw.fifo_size = aaci->fifo_depth * 2;
mutex_lock(&aaci->irq_lock);
if (!aaci->users++) {
ret = request_irq(aaci->dev->irq[0], aaci_irq,
IRQF_SHARED, DRIVER_NAME, aaci);
if (ret != 0)
aaci->users--;
}
mutex_unlock(&aaci->irq_lock);
return ret;
}
/*
* Common ALSA stuff
*/
static int aaci_pcm_close(struct snd_pcm_substream *substream)
{
struct aaci *aaci = substream->private_data;
struct aaci_runtime *aacirun = substream->runtime->private_data;
WARN_ON(aacirun->cr & CR_EN);
aacirun->substream = NULL;
mutex_lock(&aaci->irq_lock);
if (!--aaci->users)
free_irq(aaci->dev->irq[0], aaci);
mutex_unlock(&aaci->irq_lock);
return 0;
}
static int aaci_pcm_hw_free(struct snd_pcm_substream *substream)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
/*
* This must not be called with the device enabled.
*/
WARN_ON(aacirun->cr & CR_EN);
if (aacirun->pcm_open)
snd_ac97_pcm_close(aacirun->pcm);
aacirun->pcm_open = 0;
/*
* Clear out the DMA and any allocated buffers.
*/
snd_pcm_lib_free_pages(substream);
return 0;
}
/* Channel to slot mask */
static const u32 channels_to_slotmask[] = {
[2] = CR_SL3 | CR_SL4,
[4] = CR_SL3 | CR_SL4 | CR_SL7 | CR_SL8,
[6] = CR_SL3 | CR_SL4 | CR_SL7 | CR_SL8 | CR_SL6 | CR_SL9,
};
static int aaci_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
unsigned int channels = params_channels(params);
unsigned int rate = params_rate(params);
int dbl = rate > 48000;
int err;
aaci_pcm_hw_free(substream);
if (aacirun->pcm_open) {
snd_ac97_pcm_close(aacirun->pcm);
aacirun->pcm_open = 0;
}
/* channels is already limited to 2, 4, or 6 by aaci_rule_channels */
if (dbl && channels != 2)
return -EINVAL;
err = snd_pcm_lib_malloc_pages(substream,
params_buffer_bytes(params));
if (err >= 0) {
struct aaci *aaci = substream->private_data;
err = snd_ac97_pcm_open(aacirun->pcm, rate, channels,
aacirun->pcm->r[dbl].slots);
aacirun->pcm_open = err == 0;
aacirun->cr = CR_FEN | CR_COMPACT | CR_SZ16;
aacirun->cr |= channels_to_slotmask[channels + dbl * 2];
/*
* fifo_bytes is the number of bytes we transfer to/from
* the FIFO, including padding. So that's x4. As we're
* in compact mode, the FIFO is half the size.
*/
aacirun->fifo_bytes = aaci->fifo_depth * 4 / 2;
}
return err;
}
static int aaci_pcm_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci_runtime *aacirun = runtime->private_data;
aacirun->period = snd_pcm_lib_period_bytes(substream);
aacirun->start = runtime->dma_area;
aacirun->end = aacirun->start + snd_pcm_lib_buffer_bytes(substream);
aacirun->ptr = aacirun->start;
aacirun->bytes = aacirun->period;
return 0;
}
static snd_pcm_uframes_t aaci_pcm_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci_runtime *aacirun = runtime->private_data;
ssize_t bytes = aacirun->ptr - aacirun->start;
return bytes_to_frames(runtime, bytes);
}
/*
* Playback specific ALSA stuff
*/
static void aaci_pcm_playback_stop(struct aaci_runtime *aacirun)
{
u32 ie;
ie = readl(aacirun->base + AACI_IE);
ie &= ~(IE_URIE|IE_TXIE);
writel(ie, aacirun->base + AACI_IE);
aacirun->cr &= ~CR_EN;
aaci_chan_wait_ready(aacirun, SR_TXB);
writel(aacirun->cr, aacirun->base + AACI_TXCR);
}
static void aaci_pcm_playback_start(struct aaci_runtime *aacirun)
{
u32 ie;
aaci_chan_wait_ready(aacirun, SR_TXB);
aacirun->cr |= CR_EN;
ie = readl(aacirun->base + AACI_IE);
ie |= IE_URIE | IE_TXIE;
writel(ie, aacirun->base + AACI_IE);
writel(aacirun->cr, aacirun->base + AACI_TXCR);
}
static int aaci_pcm_playback_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&aacirun->lock, flags);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
aaci_pcm_playback_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_RESUME:
aaci_pcm_playback_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_STOP:
aaci_pcm_playback_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_SUSPEND:
aaci_pcm_playback_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
break;
default:
ret = -EINVAL;
}
spin_unlock_irqrestore(&aacirun->lock, flags);
return ret;
}
static struct snd_pcm_ops aaci_playback_ops = {
.open = aaci_pcm_open,
.close = aaci_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = aaci_pcm_hw_params,
.hw_free = aaci_pcm_hw_free,
.prepare = aaci_pcm_prepare,
.trigger = aaci_pcm_playback_trigger,
.pointer = aaci_pcm_pointer,
};
static void aaci_pcm_capture_stop(struct aaci_runtime *aacirun)
{
u32 ie;
aaci_chan_wait_ready(aacirun, SR_RXB);
ie = readl(aacirun->base + AACI_IE);
ie &= ~(IE_ORIE | IE_RXIE);
writel(ie, aacirun->base+AACI_IE);
aacirun->cr &= ~CR_EN;
writel(aacirun->cr, aacirun->base + AACI_RXCR);
}
static void aaci_pcm_capture_start(struct aaci_runtime *aacirun)
{
u32 ie;
aaci_chan_wait_ready(aacirun, SR_RXB);
#ifdef DEBUG
/* RX Timeout value: bits 28:17 in RXCR */
aacirun->cr |= 0xf << 17;
#endif
aacirun->cr |= CR_EN;
writel(aacirun->cr, aacirun->base + AACI_RXCR);
ie = readl(aacirun->base + AACI_IE);
ie |= IE_ORIE |IE_RXIE; // overrun and rx interrupt -- half full
writel(ie, aacirun->base + AACI_IE);
}
static int aaci_pcm_capture_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&aacirun->lock, flags);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
aaci_pcm_capture_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_RESUME:
aaci_pcm_capture_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_STOP:
aaci_pcm_capture_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_SUSPEND:
aaci_pcm_capture_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
break;
default:
ret = -EINVAL;
}
spin_unlock_irqrestore(&aacirun->lock, flags);
return ret;
}
static int aaci_pcm_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci *aaci = substream->private_data;
aaci_pcm_prepare(substream);
/* allow changing of sample rate */
aaci_ac97_write(aaci->ac97, AC97_EXTENDED_STATUS, 0x0001); /* VRA */
aaci_ac97_write(aaci->ac97, AC97_PCM_LR_ADC_RATE, runtime->rate);
aaci_ac97_write(aaci->ac97, AC97_PCM_MIC_ADC_RATE, runtime->rate);
/* Record select: Mic: 0, Aux: 3, Line: 4 */
aaci_ac97_write(aaci->ac97, AC97_REC_SEL, 0x0404);
return 0;
}
static struct snd_pcm_ops aaci_capture_ops = {
.open = aaci_pcm_open,
.close = aaci_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = aaci_pcm_hw_params,
.hw_free = aaci_pcm_hw_free,
.prepare = aaci_pcm_capture_prepare,
.trigger = aaci_pcm_capture_trigger,
.pointer = aaci_pcm_pointer,
};
/*
* Power Management.
*/
#ifdef CONFIG_PM
static int aaci_do_suspend(struct snd_card *card)
{
struct aaci *aaci = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3cold);
snd_pcm_suspend_all(aaci->pcm);
return 0;
}
static int aaci_do_resume(struct snd_card *card)
{
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
static int aaci_suspend(struct device *dev)
{
struct snd_card *card = dev_get_drvdata(dev);
return card ? aaci_do_suspend(card) : 0;
}
static int aaci_resume(struct device *dev)
{
struct snd_card *card = dev_get_drvdata(dev);
return card ? aaci_do_resume(card) : 0;
}
static SIMPLE_DEV_PM_OPS(aaci_dev_pm_ops, aaci_suspend, aaci_resume);
#define AACI_DEV_PM_OPS (&aaci_dev_pm_ops)
#else
#define AACI_DEV_PM_OPS NULL
#endif
static struct ac97_pcm ac97_defs[] = {
[0] = { /* Front PCM */
.exclusive = 1,
.r = {
[0] = {
.slots = (1 << AC97_SLOT_PCM_LEFT) |
(1 << AC97_SLOT_PCM_RIGHT) |
(1 << AC97_SLOT_PCM_CENTER) |
(1 << AC97_SLOT_PCM_SLEFT) |
(1 << AC97_SLOT_PCM_SRIGHT) |
(1 << AC97_SLOT_LFE),
},
[1] = {
.slots = (1 << AC97_SLOT_PCM_LEFT) |
(1 << AC97_SLOT_PCM_RIGHT) |
(1 << AC97_SLOT_PCM_LEFT_0) |
(1 << AC97_SLOT_PCM_RIGHT_0),
},
},
},
[1] = { /* PCM in */
.stream = 1,
.exclusive = 1,
.r = {
[0] = {
.slots = (1 << AC97_SLOT_PCM_LEFT) |
(1 << AC97_SLOT_PCM_RIGHT),
},
},
},
[2] = { /* Mic in */
.stream = 1,
.exclusive = 1,
.r = {
[0] = {
.slots = (1 << AC97_SLOT_MIC),
},
},
}
};
static struct snd_ac97_bus_ops aaci_bus_ops = {
.write = aaci_ac97_write,
.read = aaci_ac97_read,
};
static int aaci_probe_ac97(struct aaci *aaci)
{
struct snd_ac97_template ac97_template;
struct snd_ac97_bus *ac97_bus;
struct snd_ac97 *ac97;
int ret;
/*
* Assert AACIRESET for 2us
*/
writel(0, aaci->base + AACI_RESET);
udelay(2);
writel(RESET_NRST, aaci->base + AACI_RESET);
/*
* Give the AC'97 codec more than enough time
* to wake up. (42us = ~2 frames at 48kHz.)
*/
udelay(FRAME_PERIOD_US * 2);
ret = snd_ac97_bus(aaci->card, 0, &aaci_bus_ops, aaci, &ac97_bus);
if (ret)
goto out;
ac97_bus->clock = 48000;
aaci->ac97_bus = ac97_bus;
memset(&ac97_template, 0, sizeof(struct snd_ac97_template));
ac97_template.private_data = aaci;
ac97_template.num = 0;
ac97_template.scaps = AC97_SCAP_SKIP_MODEM;
ret = snd_ac97_mixer(ac97_bus, &ac97_template, &ac97);
if (ret)
goto out;
aaci->ac97 = ac97;
/*
* Disable AC97 PC Beep input on audio codecs.
*/
if (ac97_is_audio(ac97))
snd_ac97_write_cache(ac97, AC97_PC_BEEP, 0x801e);
ret = snd_ac97_pcm_assign(ac97_bus, ARRAY_SIZE(ac97_defs), ac97_defs);
if (ret)
goto out;
aaci->playback.pcm = &ac97_bus->pcms[0];
aaci->capture.pcm = &ac97_bus->pcms[1];
out:
return ret;
}
static void aaci_free_card(struct snd_card *card)
{
struct aaci *aaci = card->private_data;
iounmap(aaci->base);
}
static struct aaci *aaci_init_card(struct amba_device *dev)
{
struct aaci *aaci;
struct snd_card *card;
int err;
err = snd_card_new(&dev->dev, SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1,
THIS_MODULE, sizeof(struct aaci), &card);
if (err < 0)
return NULL;
card->private_free = aaci_free_card;
strlcpy(card->driver, DRIVER_NAME, sizeof(card->driver));
strlcpy(card->shortname, "ARM AC'97 Interface", sizeof(card->shortname));
snprintf(card->longname, sizeof(card->longname),
"%s PL%03x rev%u at 0x%08llx, irq %d",
card->shortname, amba_part(dev), amba_rev(dev),
(unsigned long long)dev->res.start, dev->irq[0]);
aaci = card->private_data;
mutex_init(&aaci->ac97_sem);
mutex_init(&aaci->irq_lock);
aaci->card = card;
aaci->dev = dev;
/* Set MAINCR to allow slot 1 and 2 data IO */
aaci->maincr = MAINCR_IE | MAINCR_SL1RXEN | MAINCR_SL1TXEN |
MAINCR_SL2RXEN | MAINCR_SL2TXEN;
return aaci;
}
static int aaci_init_pcm(struct aaci *aaci)
{
struct snd_pcm *pcm;
int ret;
ret = snd_pcm_new(aaci->card, "AACI AC'97", 0, 1, 1, &pcm);
if (ret == 0) {
aaci->pcm = pcm;
pcm->private_data = aaci;
pcm->info_flags = 0;
strlcpy(pcm->name, DRIVER_NAME, sizeof(pcm->name));
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &aaci_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &aaci_capture_ops);
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
NULL, 0, 64 * 1024);
}
return ret;
}
static unsigned int aaci_size_fifo(struct aaci *aaci)
{
struct aaci_runtime *aacirun = &aaci->playback;
int i;
/*
* Enable the channel, but don't assign it to any slots, so
* it won't empty onto the AC'97 link.
*/
writel(CR_FEN | CR_SZ16 | CR_EN, aacirun->base + AACI_TXCR);
for (i = 0; !(readl(aacirun->base + AACI_SR) & SR_TXFF) && i < 4096; i++)
writel(0, aacirun->fifo);
writel(0, aacirun->base + AACI_TXCR);
/*
* Re-initialise the AACI after the FIFO depth test, to
* ensure that the FIFOs are empty. Unfortunately, merely
* disabling the channel doesn't clear the FIFO.
*/
writel(aaci->maincr & ~MAINCR_IE, aaci->base + AACI_MAINCR);
readl(aaci->base + AACI_MAINCR);
udelay(1);
writel(aaci->maincr, aaci->base + AACI_MAINCR);
/*
* If we hit 4096 entries, we failed. Go back to the specified
* fifo depth.
*/
if (i == 4096)
i = 8;
return i;
}
static int aaci_probe(struct amba_device *dev,
const struct amba_id *id)
{
struct aaci *aaci;
int ret, i;
ret = amba_request_regions(dev, NULL);
if (ret)
return ret;
aaci = aaci_init_card(dev);
if (!aaci) {
ret = -ENOMEM;
goto out;
}
aaci->base = ioremap(dev->res.start, resource_size(&dev->res));
if (!aaci->base) {
ret = -ENOMEM;
goto out;
}
/*
* Playback uses AACI channel 0
*/
spin_lock_init(&aaci->playback.lock);
aaci->playback.base = aaci->base + AACI_CSCH1;
aaci->playback.fifo = aaci->base + AACI_DR1;
/*
* Capture uses AACI channel 0
*/
spin_lock_init(&aaci->capture.lock);
aaci->capture.base = aaci->base + AACI_CSCH1;
aaci->capture.fifo = aaci->base + AACI_DR1;
for (i = 0; i < 4; i++) {
void __iomem *base = aaci->base + i * 0x14;
writel(0, base + AACI_IE);
writel(0, base + AACI_TXCR);
writel(0, base + AACI_RXCR);
}
writel(0x1fff, aaci->base + AACI_INTCLR);
writel(aaci->maincr, aaci->base + AACI_MAINCR);
/*
* Fix: ac97 read back fail errors by reading
* from any arbitrary aaci register.
*/
readl(aaci->base + AACI_CSCH1);
ret = aaci_probe_ac97(aaci);
if (ret)
goto out;
/*
* Size the FIFOs (must be multiple of 16).
* This is the number of entries in the FIFO.
*/
aaci->fifo_depth = aaci_size_fifo(aaci);
if (aaci->fifo_depth & 15) {
printk(KERN_WARNING "AACI: FIFO depth %d not supported\n",
aaci->fifo_depth);
ret = -ENODEV;
goto out;
}
ret = aaci_init_pcm(aaci);
if (ret)
goto out;
ret = snd_card_register(aaci->card);
if (ret == 0) {
dev_info(&dev->dev, "%s\n", aaci->card->longname);
dev_info(&dev->dev, "FIFO %u entries\n", aaci->fifo_depth);
amba_set_drvdata(dev, aaci->card);
return ret;
}
out:
if (aaci)
snd_card_free(aaci->card);
amba_release_regions(dev);
return ret;
}
static int aaci_remove(struct amba_device *dev)
{
struct snd_card *card = amba_get_drvdata(dev);
if (card) {
struct aaci *aaci = card->private_data;
writel(0, aaci->base + AACI_MAINCR);
snd_card_free(card);
amba_release_regions(dev);
}
return 0;
}
static struct amba_id aaci_ids[] = {
{
.id = 0x00041041,
.mask = 0x000fffff,
},
{ 0, 0 },
};
MODULE_DEVICE_TABLE(amba, aaci_ids);
static struct amba_driver aaci_driver = {
.drv = {
.name = DRIVER_NAME,
.pm = AACI_DEV_PM_OPS,
},
.probe = aaci_probe,
.remove = aaci_remove,
.id_table = aaci_ids,
};
module_amba_driver(aaci_driver);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("ARM PrimeCell PL041 Advanced Audio CODEC Interface driver");
| gpl-2.0 |
JB1tz/kernel-msm | net/sctp/output.c | 1536 | 22712 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
*
* This file is part of the SCTP kernel implementation
*
* These functions handle output processing.
*
* This SCTP implementation is free software;
* you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This SCTP implementation is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* ************************
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <lksctp-developers@lists.sourceforge.net>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Karl Knutson <karl@athena.chicago.il.us>
* Jon Grimm <jgrimm@austin.ibm.com>
* Sridhar Samudrala <sri@us.ibm.com>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <net/inet_ecn.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/net_namespace.h>
#include <linux/socket.h> /* for sa_family_t */
#include <net/sock.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/checksum.h>
/* Forward declarations for private helpers. */
static sctp_xmit_t sctp_packet_can_append_data(struct sctp_packet *packet,
struct sctp_chunk *chunk);
static void sctp_packet_append_data(struct sctp_packet *packet,
struct sctp_chunk *chunk);
static sctp_xmit_t sctp_packet_will_fit(struct sctp_packet *packet,
struct sctp_chunk *chunk,
u16 chunk_len);
static void sctp_packet_reset(struct sctp_packet *packet)
{
packet->size = packet->overhead;
packet->has_cookie_echo = 0;
packet->has_sack = 0;
packet->has_data = 0;
packet->has_auth = 0;
packet->ipfragok = 0;
packet->auth = NULL;
}
/* Config a packet.
* This appears to be a followup set of initializations.
*/
struct sctp_packet *sctp_packet_config(struct sctp_packet *packet,
__u32 vtag, int ecn_capable)
{
struct sctp_chunk *chunk = NULL;
SCTP_DEBUG_PRINTK("%s: packet:%p vtag:0x%x\n", __func__,
packet, vtag);
packet->vtag = vtag;
if (ecn_capable && sctp_packet_empty(packet)) {
chunk = sctp_get_ecne_prepend(packet->transport->asoc);
/* If there a is a prepend chunk stick it on the list before
* any other chunks get appended.
*/
if (chunk)
sctp_packet_append_chunk(packet, chunk);
}
return packet;
}
/* Initialize the packet structure. */
struct sctp_packet *sctp_packet_init(struct sctp_packet *packet,
struct sctp_transport *transport,
__u16 sport, __u16 dport)
{
struct sctp_association *asoc = transport->asoc;
size_t overhead;
SCTP_DEBUG_PRINTK("%s: packet:%p transport:%p\n", __func__,
packet, transport);
packet->transport = transport;
packet->source_port = sport;
packet->destination_port = dport;
INIT_LIST_HEAD(&packet->chunk_list);
if (asoc) {
struct sctp_sock *sp = sctp_sk(asoc->base.sk);
overhead = sp->pf->af->net_header_len;
} else {
overhead = sizeof(struct ipv6hdr);
}
overhead += sizeof(struct sctphdr);
packet->overhead = overhead;
sctp_packet_reset(packet);
packet->vtag = 0;
packet->malloced = 0;
return packet;
}
/* Free a packet. */
void sctp_packet_free(struct sctp_packet *packet)
{
struct sctp_chunk *chunk, *tmp;
SCTP_DEBUG_PRINTK("%s: packet:%p\n", __func__, packet);
list_for_each_entry_safe(chunk, tmp, &packet->chunk_list, list) {
list_del_init(&chunk->list);
sctp_chunk_free(chunk);
}
if (packet->malloced)
kfree(packet);
}
/* This routine tries to append the chunk to the offered packet. If adding
* the chunk causes the packet to exceed the path MTU and COOKIE_ECHO chunk
* is not present in the packet, it transmits the input packet.
* Data can be bundled with a packet containing a COOKIE_ECHO chunk as long
* as it can fit in the packet, but any more data that does not fit in this
* packet can be sent only after receiving the COOKIE_ACK.
*/
sctp_xmit_t sctp_packet_transmit_chunk(struct sctp_packet *packet,
struct sctp_chunk *chunk,
int one_packet)
{
sctp_xmit_t retval;
int error = 0;
SCTP_DEBUG_PRINTK("%s: packet:%p chunk:%p\n", __func__,
packet, chunk);
switch ((retval = (sctp_packet_append_chunk(packet, chunk)))) {
case SCTP_XMIT_PMTU_FULL:
if (!packet->has_cookie_echo) {
error = sctp_packet_transmit(packet);
if (error < 0)
chunk->skb->sk->sk_err = -error;
/* If we have an empty packet, then we can NOT ever
* return PMTU_FULL.
*/
if (!one_packet)
retval = sctp_packet_append_chunk(packet,
chunk);
}
break;
case SCTP_XMIT_RWND_FULL:
case SCTP_XMIT_OK:
case SCTP_XMIT_NAGLE_DELAY:
break;
}
return retval;
}
/* Try to bundle an auth chunk into the packet. */
static sctp_xmit_t sctp_packet_bundle_auth(struct sctp_packet *pkt,
struct sctp_chunk *chunk)
{
struct sctp_association *asoc = pkt->transport->asoc;
struct sctp_chunk *auth;
sctp_xmit_t retval = SCTP_XMIT_OK;
/* if we don't have an association, we can't do authentication */
if (!asoc)
return retval;
/* See if this is an auth chunk we are bundling or if
* auth is already bundled.
*/
if (chunk->chunk_hdr->type == SCTP_CID_AUTH || pkt->has_auth)
return retval;
/* if the peer did not request this chunk to be authenticated,
* don't do it
*/
if (!chunk->auth)
return retval;
auth = sctp_make_auth(asoc);
if (!auth)
return retval;
retval = sctp_packet_append_chunk(pkt, auth);
return retval;
}
/* Try to bundle a SACK with the packet. */
static sctp_xmit_t sctp_packet_bundle_sack(struct sctp_packet *pkt,
struct sctp_chunk *chunk)
{
sctp_xmit_t retval = SCTP_XMIT_OK;
/* If sending DATA and haven't aleady bundled a SACK, try to
* bundle one in to the packet.
*/
if (sctp_chunk_is_data(chunk) && !pkt->has_sack &&
!pkt->has_cookie_echo) {
struct sctp_association *asoc;
struct timer_list *timer;
asoc = pkt->transport->asoc;
timer = &asoc->timers[SCTP_EVENT_TIMEOUT_SACK];
/* If the SACK timer is running, we have a pending SACK */
if (timer_pending(timer)) {
struct sctp_chunk *sack;
asoc->a_rwnd = asoc->rwnd;
sack = sctp_make_sack(asoc);
if (sack) {
retval = sctp_packet_append_chunk(pkt, sack);
asoc->peer.sack_needed = 0;
if (del_timer(timer))
sctp_association_put(asoc);
}
}
}
return retval;
}
/* Append a chunk to the offered packet reporting back any inability to do
* so.
*/
sctp_xmit_t sctp_packet_append_chunk(struct sctp_packet *packet,
struct sctp_chunk *chunk)
{
sctp_xmit_t retval = SCTP_XMIT_OK;
__u16 chunk_len = WORD_ROUND(ntohs(chunk->chunk_hdr->length));
SCTP_DEBUG_PRINTK("%s: packet:%p chunk:%p\n", __func__, packet,
chunk);
/* Data chunks are special. Before seeing what else we can
* bundle into this packet, check to see if we are allowed to
* send this DATA.
*/
if (sctp_chunk_is_data(chunk)) {
retval = sctp_packet_can_append_data(packet, chunk);
if (retval != SCTP_XMIT_OK)
goto finish;
}
/* Try to bundle AUTH chunk */
retval = sctp_packet_bundle_auth(packet, chunk);
if (retval != SCTP_XMIT_OK)
goto finish;
/* Try to bundle SACK chunk */
retval = sctp_packet_bundle_sack(packet, chunk);
if (retval != SCTP_XMIT_OK)
goto finish;
/* Check to see if this chunk will fit into the packet */
retval = sctp_packet_will_fit(packet, chunk, chunk_len);
if (retval != SCTP_XMIT_OK)
goto finish;
/* We believe that this chunk is OK to add to the packet */
switch (chunk->chunk_hdr->type) {
case SCTP_CID_DATA:
/* Account for the data being in the packet */
sctp_packet_append_data(packet, chunk);
/* Disallow SACK bundling after DATA. */
packet->has_sack = 1;
/* Disallow AUTH bundling after DATA */
packet->has_auth = 1;
/* Let it be knows that packet has DATA in it */
packet->has_data = 1;
/* timestamp the chunk for rtx purposes */
chunk->sent_at = jiffies;
break;
case SCTP_CID_COOKIE_ECHO:
packet->has_cookie_echo = 1;
break;
case SCTP_CID_SACK:
packet->has_sack = 1;
break;
case SCTP_CID_AUTH:
packet->has_auth = 1;
packet->auth = chunk;
break;
}
/* It is OK to send this chunk. */
list_add_tail(&chunk->list, &packet->chunk_list);
packet->size += chunk_len;
chunk->transport = packet->transport;
finish:
return retval;
}
static void sctp_packet_release_owner(struct sk_buff *skb)
{
sk_free(skb->sk);
}
static void sctp_packet_set_owner_w(struct sk_buff *skb, struct sock *sk)
{
skb_orphan(skb);
skb->sk = sk;
skb->destructor = sctp_packet_release_owner;
/*
* The data chunks have already been accounted for in sctp_sendmsg(),
* therefore only reserve a single byte to keep socket around until
* the packet has been transmitted.
*/
atomic_inc(&sk->sk_wmem_alloc);
}
/* All packets are sent to the network through this function from
* sctp_outq_tail().
*
* The return value is a normal kernel error return value.
*/
int sctp_packet_transmit(struct sctp_packet *packet)
{
struct sctp_transport *tp = packet->transport;
struct sctp_association *asoc = tp->asoc;
struct sctphdr *sh;
struct sk_buff *nskb;
struct sctp_chunk *chunk, *tmp;
struct sock *sk;
int err = 0;
int padding; /* How much padding do we need? */
__u8 has_data = 0;
struct dst_entry *dst = tp->dst;
unsigned char *auth = NULL; /* pointer to auth in skb data */
__u32 cksum_buf_len = sizeof(struct sctphdr);
SCTP_DEBUG_PRINTK("%s: packet:%p\n", __func__, packet);
/* Do NOT generate a chunkless packet. */
if (list_empty(&packet->chunk_list))
return err;
/* Set up convenience variables... */
chunk = list_entry(packet->chunk_list.next, struct sctp_chunk, list);
sk = chunk->skb->sk;
/* Allocate the new skb. */
nskb = alloc_skb(packet->size + LL_MAX_HEADER, GFP_ATOMIC);
if (!nskb)
goto nomem;
/* Make sure the outbound skb has enough header room reserved. */
skb_reserve(nskb, packet->overhead + LL_MAX_HEADER);
/* Set the owning socket so that we know where to get the
* destination IP address.
*/
sctp_packet_set_owner_w(nskb, sk);
if (!sctp_transport_dst_check(tp)) {
sctp_transport_route(tp, NULL, sctp_sk(sk));
if (asoc && (asoc->param_flags & SPP_PMTUD_ENABLE)) {
sctp_assoc_sync_pmtu(asoc);
}
}
dst = dst_clone(tp->dst);
skb_dst_set(nskb, dst);
if (!dst)
goto no_route;
/* Build the SCTP header. */
sh = (struct sctphdr *)skb_push(nskb, sizeof(struct sctphdr));
skb_reset_transport_header(nskb);
sh->source = htons(packet->source_port);
sh->dest = htons(packet->destination_port);
/* From 6.8 Adler-32 Checksum Calculation:
* After the packet is constructed (containing the SCTP common
* header and one or more control or DATA chunks), the
* transmitter shall:
*
* 1) Fill in the proper Verification Tag in the SCTP common
* header and initialize the checksum field to 0's.
*/
sh->vtag = htonl(packet->vtag);
sh->checksum = 0;
/**
* 6.10 Bundling
*
* An endpoint bundles chunks by simply including multiple
* chunks in one outbound SCTP packet. ...
*/
/**
* 3.2 Chunk Field Descriptions
*
* The total length of a chunk (including Type, Length and
* Value fields) MUST be a multiple of 4 bytes. If the length
* of the chunk is not a multiple of 4 bytes, the sender MUST
* pad the chunk with all zero bytes and this padding is not
* included in the chunk length field. The sender should
* never pad with more than 3 bytes.
*
* [This whole comment explains WORD_ROUND() below.]
*/
SCTP_DEBUG_PRINTK("***sctp_transmit_packet***\n");
list_for_each_entry_safe(chunk, tmp, &packet->chunk_list, list) {
list_del_init(&chunk->list);
if (sctp_chunk_is_data(chunk)) {
/* 6.3.1 C4) When data is in flight and when allowed
* by rule C5, a new RTT measurement MUST be made each
* round trip. Furthermore, new RTT measurements
* SHOULD be made no more than once per round-trip
* for a given destination transport address.
*/
if (!tp->rto_pending) {
chunk->rtt_in_progress = 1;
tp->rto_pending = 1;
}
has_data = 1;
}
padding = WORD_ROUND(chunk->skb->len) - chunk->skb->len;
if (padding)
memset(skb_put(chunk->skb, padding), 0, padding);
/* if this is the auth chunk that we are adding,
* store pointer where it will be added and put
* the auth into the packet.
*/
if (chunk == packet->auth)
auth = skb_tail_pointer(nskb);
cksum_buf_len += chunk->skb->len;
memcpy(skb_put(nskb, chunk->skb->len),
chunk->skb->data, chunk->skb->len);
SCTP_DEBUG_PRINTK("%s %p[%s] %s 0x%x, %s %d, %s %d, %s %d\n",
"*** Chunk", chunk,
sctp_cname(SCTP_ST_CHUNK(
chunk->chunk_hdr->type)),
chunk->has_tsn ? "TSN" : "No TSN",
chunk->has_tsn ?
ntohl(chunk->subh.data_hdr->tsn) : 0,
"length", ntohs(chunk->chunk_hdr->length),
"chunk->skb->len", chunk->skb->len,
"rtt_in_progress", chunk->rtt_in_progress);
/*
* If this is a control chunk, this is our last
* reference. Free data chunks after they've been
* acknowledged or have failed.
*/
if (!sctp_chunk_is_data(chunk))
sctp_chunk_free(chunk);
}
/* SCTP-AUTH, Section 6.2
* The sender MUST calculate the MAC as described in RFC2104 [2]
* using the hash function H as described by the MAC Identifier and
* the shared association key K based on the endpoint pair shared key
* described by the shared key identifier. The 'data' used for the
* computation of the AUTH-chunk is given by the AUTH chunk with its
* HMAC field set to zero (as shown in Figure 6) followed by all
* chunks that are placed after the AUTH chunk in the SCTP packet.
*/
if (auth)
sctp_auth_calculate_hmac(asoc, nskb,
(struct sctp_auth_chunk *)auth,
GFP_ATOMIC);
/* 2) Calculate the Adler-32 checksum of the whole packet,
* including the SCTP common header and all the
* chunks.
*
* Note: Adler-32 is no longer applicable, as has been replaced
* by CRC32-C as described in <draft-ietf-tsvwg-sctpcsum-02.txt>.
*/
if (!sctp_checksum_disable) {
if (!(dst->dev->features & NETIF_F_SCTP_CSUM)) {
__u32 crc32 = sctp_start_cksum((__u8 *)sh, cksum_buf_len);
/* 3) Put the resultant value into the checksum field in the
* common header, and leave the rest of the bits unchanged.
*/
sh->checksum = sctp_end_cksum(crc32);
} else {
/* no need to seed pseudo checksum for SCTP */
nskb->ip_summed = CHECKSUM_PARTIAL;
nskb->csum_start = (skb_transport_header(nskb) -
nskb->head);
nskb->csum_offset = offsetof(struct sctphdr, checksum);
}
}
/* IP layer ECN support
* From RFC 2481
* "The ECN-Capable Transport (ECT) bit would be set by the
* data sender to indicate that the end-points of the
* transport protocol are ECN-capable."
*
* Now setting the ECT bit all the time, as it should not cause
* any problems protocol-wise even if our peer ignores it.
*
* Note: The works for IPv6 layer checks this bit too later
* in transmission. See IP6_ECN_flow_xmit().
*/
(*tp->af_specific->ecn_capable)(nskb->sk);
/* Set up the IP options. */
/* BUG: not implemented
* For v4 this all lives somewhere in sk->sk_opt...
*/
/* Dump that on IP! */
if (asoc && asoc->peer.last_sent_to != tp) {
/* Considering the multiple CPU scenario, this is a
* "correcter" place for last_sent_to. --xguo
*/
asoc->peer.last_sent_to = tp;
}
if (has_data) {
struct timer_list *timer;
unsigned long timeout;
/* Restart the AUTOCLOSE timer when sending data. */
if (sctp_state(asoc, ESTABLISHED) && asoc->autoclose) {
timer = &asoc->timers[SCTP_EVENT_TIMEOUT_AUTOCLOSE];
timeout = asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE];
if (!mod_timer(timer, jiffies + timeout))
sctp_association_hold(asoc);
}
}
SCTP_DEBUG_PRINTK("***sctp_transmit_packet*** skb len %d\n",
nskb->len);
nskb->local_df = packet->ipfragok;
(*tp->af_specific->sctp_xmit)(nskb, tp);
out:
sctp_packet_reset(packet);
return err;
no_route:
kfree_skb(nskb);
IP_INC_STATS_BH(&init_net, IPSTATS_MIB_OUTNOROUTES);
/* FIXME: Returning the 'err' will effect all the associations
* associated with a socket, although only one of the paths of the
* association is unreachable.
* The real failure of a transport or association can be passed on
* to the user via notifications. So setting this error may not be
* required.
*/
/* err = -EHOSTUNREACH; */
err:
/* Control chunks are unreliable so just drop them. DATA chunks
* will get resent or dropped later.
*/
list_for_each_entry_safe(chunk, tmp, &packet->chunk_list, list) {
list_del_init(&chunk->list);
if (!sctp_chunk_is_data(chunk))
sctp_chunk_free(chunk);
}
goto out;
nomem:
err = -ENOMEM;
goto err;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* This private function check to see if a chunk can be added */
static sctp_xmit_t sctp_packet_can_append_data(struct sctp_packet *packet,
struct sctp_chunk *chunk)
{
sctp_xmit_t retval = SCTP_XMIT_OK;
size_t datasize, rwnd, inflight, flight_size;
struct sctp_transport *transport = packet->transport;
struct sctp_association *asoc = transport->asoc;
struct sctp_outq *q = &asoc->outqueue;
/* RFC 2960 6.1 Transmission of DATA Chunks
*
* A) At any given time, the data sender MUST NOT transmit new data to
* any destination transport address if its peer's rwnd indicates
* that the peer has no buffer space (i.e. rwnd is 0, see Section
* 6.2.1). However, regardless of the value of rwnd (including if it
* is 0), the data sender can always have one DATA chunk in flight to
* the receiver if allowed by cwnd (see rule B below). This rule
* allows the sender to probe for a change in rwnd that the sender
* missed due to the SACK having been lost in transit from the data
* receiver to the data sender.
*/
rwnd = asoc->peer.rwnd;
inflight = q->outstanding_bytes;
flight_size = transport->flight_size;
datasize = sctp_data_size(chunk);
if (datasize > rwnd) {
if (inflight > 0) {
/* We have (at least) one data chunk in flight,
* so we can't fall back to rule 6.1 B).
*/
retval = SCTP_XMIT_RWND_FULL;
goto finish;
}
}
/* RFC 2960 6.1 Transmission of DATA Chunks
*
* B) At any given time, the sender MUST NOT transmit new data
* to a given transport address if it has cwnd or more bytes
* of data outstanding to that transport address.
*/
/* RFC 7.2.4 & the Implementers Guide 2.8.
*
* 3) ...
* When a Fast Retransmit is being performed the sender SHOULD
* ignore the value of cwnd and SHOULD NOT delay retransmission.
*/
if (chunk->fast_retransmit != SCTP_NEED_FRTX)
if (flight_size >= transport->cwnd) {
retval = SCTP_XMIT_RWND_FULL;
goto finish;
}
/* Nagle's algorithm to solve small-packet problem:
* Inhibit the sending of new chunks when new outgoing data arrives
* if any previously transmitted data on the connection remains
* unacknowledged.
*/
if (!sctp_sk(asoc->base.sk)->nodelay && sctp_packet_empty(packet) &&
inflight && sctp_state(asoc, ESTABLISHED)) {
unsigned max = transport->pathmtu - packet->overhead;
unsigned len = chunk->skb->len + q->out_qlen;
/* Check whether this chunk and all the rest of pending
* data will fit or delay in hopes of bundling a full
* sized packet.
* Don't delay large message writes that may have been
* fragmeneted into small peices.
*/
if ((len < max) && chunk->msg->can_delay) {
retval = SCTP_XMIT_NAGLE_DELAY;
goto finish;
}
}
finish:
return retval;
}
/* This private function does management things when adding DATA chunk */
static void sctp_packet_append_data(struct sctp_packet *packet,
struct sctp_chunk *chunk)
{
struct sctp_transport *transport = packet->transport;
size_t datasize = sctp_data_size(chunk);
struct sctp_association *asoc = transport->asoc;
u32 rwnd = asoc->peer.rwnd;
/* Keep track of how many bytes are in flight over this transport. */
transport->flight_size += datasize;
/* Keep track of how many bytes are in flight to the receiver. */
asoc->outqueue.outstanding_bytes += datasize;
/* Update our view of the receiver's rwnd. */
if (datasize < rwnd)
rwnd -= datasize;
else
rwnd = 0;
asoc->peer.rwnd = rwnd;
/* Has been accepted for transmission. */
if (!asoc->peer.prsctp_capable)
chunk->msg->can_abandon = 0;
sctp_chunk_assign_tsn(chunk);
sctp_chunk_assign_ssn(chunk);
}
static sctp_xmit_t sctp_packet_will_fit(struct sctp_packet *packet,
struct sctp_chunk *chunk,
u16 chunk_len)
{
size_t psize;
size_t pmtu;
int too_big;
sctp_xmit_t retval = SCTP_XMIT_OK;
psize = packet->size;
pmtu = ((packet->transport->asoc) ?
(packet->transport->asoc->pathmtu) :
(packet->transport->pathmtu));
too_big = (psize + chunk_len > pmtu);
/* Decide if we need to fragment or resubmit later. */
if (too_big) {
/* It's OK to fragmet at IP level if any one of the following
* is true:
* 1. The packet is empty (meaning this chunk is greater
* the MTU)
* 2. The chunk we are adding is a control chunk
* 3. The packet doesn't have any data in it yet and data
* requires authentication.
*/
if (sctp_packet_empty(packet) || !sctp_chunk_is_data(chunk) ||
(!packet->has_data && chunk->auth)) {
/* We no longer do re-fragmentation.
* Just fragment at the IP layer, if we
* actually hit this condition
*/
packet->ipfragok = 1;
} else {
retval = SCTP_XMIT_PMTU_FULL;
}
}
return retval;
}
| gpl-2.0 |
ztemt/A476_V1B_5.1_kernel | drivers/tty/sysrq.c | 1792 | 25139 | /*
* Linux Magic System Request Key Hacks
*
* (c) 1997 Martin Mares <mj@atrey.karlin.mff.cuni.cz>
* based on ideas by Pavel Machek <pavel@atrey.karlin.mff.cuni.cz>
*
* (c) 2000 Crutcher Dunnavant <crutcher+kernel@datastacks.com>
* overhauled to use key registration
* based upon discusions in irc://irc.openprojects.net/#kernelnewbies
*
* Copyright (c) 2010 Dmitry Torokhov
* Input handler conversion
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/sched.h>
#include <linux/sched/rt.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/mount.h>
#include <linux/kdev_t.h>
#include <linux/major.h>
#include <linux/reboot.h>
#include <linux/sysrq.h>
#include <linux/kbd_kern.h>
#include <linux/proc_fs.h>
#include <linux/nmi.h>
#include <linux/quotaops.h>
#include <linux/perf_event.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/suspend.h>
#include <linux/writeback.h>
#include <linux/swap.h>
#include <linux/spinlock.h>
#include <linux/vt_kern.h>
#include <linux/workqueue.h>
#include <linux/hrtimer.h>
#include <linux/oom.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/uaccess.h>
#include <linux/moduleparam.h>
#include <linux/jiffies.h>
#include <asm/ptrace.h>
#include <asm/irq_regs.h>
/* Whether we react on sysrq keys or just ignore them */
static int __read_mostly sysrq_enabled = SYSRQ_DEFAULT_ENABLE;
static bool __read_mostly sysrq_always_enabled;
unsigned short platform_sysrq_reset_seq[] __weak = { KEY_RESERVED };
int sysrq_reset_downtime_ms __weak;
static bool sysrq_on(void)
{
return sysrq_enabled || sysrq_always_enabled;
}
/*
* A value of 1 means 'all', other nonzero values are an op mask:
*/
static bool sysrq_on_mask(int mask)
{
return sysrq_always_enabled ||
sysrq_enabled == 1 ||
(sysrq_enabled & mask);
}
static int __init sysrq_always_enabled_setup(char *str)
{
sysrq_always_enabled = true;
pr_info("sysrq always enabled.\n");
return 1;
}
__setup("sysrq_always_enabled", sysrq_always_enabled_setup);
static void sysrq_handle_loglevel(int key)
{
int i;
i = key - '0';
console_loglevel = 7;
printk("Loglevel set to %d\n", i);
console_loglevel = i;
}
static struct sysrq_key_op sysrq_loglevel_op = {
.handler = sysrq_handle_loglevel,
.help_msg = "loglevel(0-9)",
.action_msg = "Changing Loglevel",
.enable_mask = SYSRQ_ENABLE_LOG,
};
#ifdef CONFIG_VT
static void sysrq_handle_SAK(int key)
{
struct work_struct *SAK_work = &vc_cons[fg_console].SAK_work;
schedule_work(SAK_work);
}
static struct sysrq_key_op sysrq_SAK_op = {
.handler = sysrq_handle_SAK,
.help_msg = "sak(k)",
.action_msg = "SAK",
.enable_mask = SYSRQ_ENABLE_KEYBOARD,
};
#else
#define sysrq_SAK_op (*(struct sysrq_key_op *)NULL)
#endif
#ifdef CONFIG_VT
static void sysrq_handle_unraw(int key)
{
vt_reset_unicode(fg_console);
}
static struct sysrq_key_op sysrq_unraw_op = {
.handler = sysrq_handle_unraw,
.help_msg = "unraw(r)",
.action_msg = "Keyboard mode set to system default",
.enable_mask = SYSRQ_ENABLE_KEYBOARD,
};
#else
#define sysrq_unraw_op (*(struct sysrq_key_op *)NULL)
#endif /* CONFIG_VT */
static void sysrq_handle_crash(int key)
{
char *killer = NULL;
panic_on_oops = 1; /* force panic */
wmb();
*killer = 1;
}
static struct sysrq_key_op sysrq_crash_op = {
.handler = sysrq_handle_crash,
.help_msg = "crash(c)",
.action_msg = "Trigger a crash",
.enable_mask = SYSRQ_ENABLE_DUMP,
};
static void sysrq_handle_reboot(int key)
{
lockdep_off();
local_irq_enable();
emergency_restart();
}
static struct sysrq_key_op sysrq_reboot_op = {
.handler = sysrq_handle_reboot,
.help_msg = "reboot(b)",
.action_msg = "Resetting",
.enable_mask = SYSRQ_ENABLE_BOOT,
};
static void sysrq_handle_sync(int key)
{
emergency_sync();
}
static struct sysrq_key_op sysrq_sync_op = {
.handler = sysrq_handle_sync,
.help_msg = "sync(s)",
.action_msg = "Emergency Sync",
.enable_mask = SYSRQ_ENABLE_SYNC,
};
static void sysrq_handle_show_timers(int key)
{
sysrq_timer_list_show();
}
static struct sysrq_key_op sysrq_show_timers_op = {
.handler = sysrq_handle_show_timers,
.help_msg = "show-all-timers(q)",
.action_msg = "Show clockevent devices & pending hrtimers (no others)",
};
static void sysrq_handle_mountro(int key)
{
emergency_remount();
}
static struct sysrq_key_op sysrq_mountro_op = {
.handler = sysrq_handle_mountro,
.help_msg = "unmount(u)",
.action_msg = "Emergency Remount R/O",
.enable_mask = SYSRQ_ENABLE_REMOUNT,
};
#ifdef CONFIG_LOCKDEP
static void sysrq_handle_showlocks(int key)
{
debug_show_all_locks();
}
static struct sysrq_key_op sysrq_showlocks_op = {
.handler = sysrq_handle_showlocks,
.help_msg = "show-all-locks(d)",
.action_msg = "Show Locks Held",
};
#else
#define sysrq_showlocks_op (*(struct sysrq_key_op *)NULL)
#endif
#ifdef CONFIG_SMP
static DEFINE_SPINLOCK(show_lock);
static void showacpu(void *dummy)
{
unsigned long flags;
/* Idle CPUs have no interesting backtrace. */
if (idle_cpu(smp_processor_id()))
return;
spin_lock_irqsave(&show_lock, flags);
printk(KERN_INFO "CPU%d:\n", smp_processor_id());
show_stack(NULL, NULL);
spin_unlock_irqrestore(&show_lock, flags);
}
static void sysrq_showregs_othercpus(struct work_struct *dummy)
{
smp_call_function(showacpu, NULL, 0);
}
static DECLARE_WORK(sysrq_showallcpus, sysrq_showregs_othercpus);
static void sysrq_handle_showallcpus(int key)
{
/*
* Fall back to the workqueue based printing if the
* backtrace printing did not succeed or the
* architecture has no support for it:
*/
if (!trigger_all_cpu_backtrace()) {
struct pt_regs *regs = get_irq_regs();
if (regs) {
printk(KERN_INFO "CPU%d:\n", smp_processor_id());
show_regs(regs);
}
schedule_work(&sysrq_showallcpus);
}
}
static struct sysrq_key_op sysrq_showallcpus_op = {
.handler = sysrq_handle_showallcpus,
.help_msg = "show-backtrace-all-active-cpus(l)",
.action_msg = "Show backtrace of all active CPUs",
.enable_mask = SYSRQ_ENABLE_DUMP,
};
#endif
static void sysrq_handle_showregs(int key)
{
struct pt_regs *regs = get_irq_regs();
if (regs)
show_regs(regs);
perf_event_print_debug();
}
static struct sysrq_key_op sysrq_showregs_op = {
.handler = sysrq_handle_showregs,
.help_msg = "show-registers(p)",
.action_msg = "Show Regs",
.enable_mask = SYSRQ_ENABLE_DUMP,
};
static void sysrq_handle_showstate(int key)
{
show_state();
}
static struct sysrq_key_op sysrq_showstate_op = {
.handler = sysrq_handle_showstate,
.help_msg = "show-task-states(t)",
.action_msg = "Show State",
.enable_mask = SYSRQ_ENABLE_DUMP,
};
static void sysrq_handle_showstate_blocked(int key)
{
show_state_filter(TASK_UNINTERRUPTIBLE);
}
static struct sysrq_key_op sysrq_showstate_blocked_op = {
.handler = sysrq_handle_showstate_blocked,
.help_msg = "show-blocked-tasks(w)",
.action_msg = "Show Blocked State",
.enable_mask = SYSRQ_ENABLE_DUMP,
};
#ifdef CONFIG_TRACING
#include <linux/ftrace.h>
static void sysrq_ftrace_dump(int key)
{
ftrace_dump(DUMP_ALL);
}
static struct sysrq_key_op sysrq_ftrace_dump_op = {
.handler = sysrq_ftrace_dump,
.help_msg = "dump-ftrace-buffer(z)",
.action_msg = "Dump ftrace buffer",
.enable_mask = SYSRQ_ENABLE_DUMP,
};
#else
#define sysrq_ftrace_dump_op (*(struct sysrq_key_op *)NULL)
#endif
static void sysrq_handle_showmem(int key)
{
show_mem(0);
}
static struct sysrq_key_op sysrq_showmem_op = {
.handler = sysrq_handle_showmem,
.help_msg = "show-memory-usage(m)",
.action_msg = "Show Memory",
.enable_mask = SYSRQ_ENABLE_DUMP,
};
/*
* Signal sysrq helper function. Sends a signal to all user processes.
*/
static void send_sig_all(int sig)
{
struct task_struct *p;
read_lock(&tasklist_lock);
for_each_process(p) {
if (p->flags & PF_KTHREAD)
continue;
if (is_global_init(p))
continue;
do_send_sig_info(sig, SEND_SIG_FORCED, p, true);
}
read_unlock(&tasklist_lock);
}
static void sysrq_handle_term(int key)
{
send_sig_all(SIGTERM);
console_loglevel = 8;
}
static struct sysrq_key_op sysrq_term_op = {
.handler = sysrq_handle_term,
.help_msg = "terminate-all-tasks(e)",
.action_msg = "Terminate All Tasks",
.enable_mask = SYSRQ_ENABLE_SIGNAL,
};
static void moom_callback(struct work_struct *ignored)
{
out_of_memory(node_zonelist(first_online_node, GFP_KERNEL), GFP_KERNEL,
0, NULL, true);
}
static DECLARE_WORK(moom_work, moom_callback);
static void sysrq_handle_moom(int key)
{
schedule_work(&moom_work);
}
static struct sysrq_key_op sysrq_moom_op = {
.handler = sysrq_handle_moom,
.help_msg = "memory-full-oom-kill(f)",
.action_msg = "Manual OOM execution",
.enable_mask = SYSRQ_ENABLE_SIGNAL,
};
#ifdef CONFIG_BLOCK
static void sysrq_handle_thaw(int key)
{
emergency_thaw_all();
}
static struct sysrq_key_op sysrq_thaw_op = {
.handler = sysrq_handle_thaw,
.help_msg = "thaw-filesystems(j)",
.action_msg = "Emergency Thaw of all frozen filesystems",
.enable_mask = SYSRQ_ENABLE_SIGNAL,
};
#endif
static void sysrq_handle_kill(int key)
{
send_sig_all(SIGKILL);
console_loglevel = 8;
}
static struct sysrq_key_op sysrq_kill_op = {
.handler = sysrq_handle_kill,
.help_msg = "kill-all-tasks(i)",
.action_msg = "Kill All Tasks",
.enable_mask = SYSRQ_ENABLE_SIGNAL,
};
static void sysrq_handle_unrt(int key)
{
normalize_rt_tasks();
}
static struct sysrq_key_op sysrq_unrt_op = {
.handler = sysrq_handle_unrt,
.help_msg = "nice-all-RT-tasks(n)",
.action_msg = "Nice All RT Tasks",
.enable_mask = SYSRQ_ENABLE_RTNICE,
};
/* Key Operations table and lock */
static DEFINE_SPINLOCK(sysrq_key_table_lock);
static struct sysrq_key_op *sysrq_key_table[36] = {
&sysrq_loglevel_op, /* 0 */
&sysrq_loglevel_op, /* 1 */
&sysrq_loglevel_op, /* 2 */
&sysrq_loglevel_op, /* 3 */
&sysrq_loglevel_op, /* 4 */
&sysrq_loglevel_op, /* 5 */
&sysrq_loglevel_op, /* 6 */
&sysrq_loglevel_op, /* 7 */
&sysrq_loglevel_op, /* 8 */
&sysrq_loglevel_op, /* 9 */
/*
* a: Don't use for system provided sysrqs, it is handled specially on
* sparc and will never arrive.
*/
NULL, /* a */
&sysrq_reboot_op, /* b */
&sysrq_crash_op, /* c & ibm_emac driver debug */
&sysrq_showlocks_op, /* d */
&sysrq_term_op, /* e */
&sysrq_moom_op, /* f */
/* g: May be registered for the kernel debugger */
NULL, /* g */
NULL, /* h - reserved for help */
&sysrq_kill_op, /* i */
#ifdef CONFIG_BLOCK
&sysrq_thaw_op, /* j */
#else
NULL, /* j */
#endif
&sysrq_SAK_op, /* k */
#ifdef CONFIG_SMP
&sysrq_showallcpus_op, /* l */
#else
NULL, /* l */
#endif
&sysrq_showmem_op, /* m */
&sysrq_unrt_op, /* n */
/* o: This will often be registered as 'Off' at init time */
NULL, /* o */
&sysrq_showregs_op, /* p */
&sysrq_show_timers_op, /* q */
&sysrq_unraw_op, /* r */
&sysrq_sync_op, /* s */
&sysrq_showstate_op, /* t */
&sysrq_mountro_op, /* u */
/* v: May be registered for frame buffer console restore */
NULL, /* v */
&sysrq_showstate_blocked_op, /* w */
/* x: May be registered on ppc/powerpc for xmon */
/* x: May be registered on sparc64 for global PMU dump */
NULL, /* x */
/* y: May be registered on sparc64 for global register dump */
NULL, /* y */
&sysrq_ftrace_dump_op, /* z */
};
/* key2index calculation, -1 on invalid index */
static int sysrq_key_table_key2index(int key)
{
int retval;
if ((key >= '0') && (key <= '9'))
retval = key - '0';
else if ((key >= 'a') && (key <= 'z'))
retval = key + 10 - 'a';
else
retval = -1;
return retval;
}
/*
* get and put functions for the table, exposed to modules.
*/
struct sysrq_key_op *__sysrq_get_key_op(int key)
{
struct sysrq_key_op *op_p = NULL;
int i;
i = sysrq_key_table_key2index(key);
if (i != -1)
op_p = sysrq_key_table[i];
return op_p;
}
static void __sysrq_put_key_op(int key, struct sysrq_key_op *op_p)
{
int i = sysrq_key_table_key2index(key);
if (i != -1)
sysrq_key_table[i] = op_p;
}
void __handle_sysrq(int key, bool check_mask)
{
struct sysrq_key_op *op_p;
int orig_log_level;
int i;
unsigned long flags;
spin_lock_irqsave(&sysrq_key_table_lock, flags);
/*
* Raise the apparent loglevel to maximum so that the sysrq header
* is shown to provide the user with positive feedback. We do not
* simply emit this at KERN_EMERG as that would change message
* routing in the consumers of /proc/kmsg.
*/
orig_log_level = console_loglevel;
console_loglevel = 7;
printk(KERN_INFO "SysRq : ");
op_p = __sysrq_get_key_op(key);
if (op_p) {
/*
* Should we check for enabled operations (/proc/sysrq-trigger
* should not) and is the invoked operation enabled?
*/
if (!check_mask || sysrq_on_mask(op_p->enable_mask)) {
printk("%s\n", op_p->action_msg);
console_loglevel = orig_log_level;
op_p->handler(key);
} else {
printk("This sysrq operation is disabled.\n");
}
} else {
printk("HELP : ");
/* Only print the help msg once per handler */
for (i = 0; i < ARRAY_SIZE(sysrq_key_table); i++) {
if (sysrq_key_table[i]) {
int j;
for (j = 0; sysrq_key_table[i] !=
sysrq_key_table[j]; j++)
;
if (j != i)
continue;
printk("%s ", sysrq_key_table[i]->help_msg);
}
}
printk("\n");
console_loglevel = orig_log_level;
}
spin_unlock_irqrestore(&sysrq_key_table_lock, flags);
}
void handle_sysrq(int key)
{
if (sysrq_on())
__handle_sysrq(key, true);
}
EXPORT_SYMBOL(handle_sysrq);
#ifdef CONFIG_INPUT
/* Simple translation table for the SysRq keys */
static const unsigned char sysrq_xlate[KEY_CNT] =
"\000\0331234567890-=\177\t" /* 0x00 - 0x0f */
"qwertyuiop[]\r\000as" /* 0x10 - 0x1f */
"dfghjkl;'`\000\\zxcv" /* 0x20 - 0x2f */
"bnm,./\000*\000 \000\201\202\203\204\205" /* 0x30 - 0x3f */
"\206\207\210\211\212\000\000789-456+1" /* 0x40 - 0x4f */
"230\177\000\000\213\214\000\000\000\000\000\000\000\000\000\000" /* 0x50 - 0x5f */
"\r\000/"; /* 0x60 - 0x6f */
struct sysrq_state {
struct input_handle handle;
struct work_struct reinject_work;
unsigned long key_down[BITS_TO_LONGS(KEY_CNT)];
unsigned int alt;
unsigned int alt_use;
bool active;
bool need_reinject;
bool reinjecting;
/* reset sequence handling */
bool reset_canceled;
unsigned long reset_keybit[BITS_TO_LONGS(KEY_CNT)];
int reset_seq_len;
int reset_seq_cnt;
int reset_seq_version;
struct timer_list keyreset_timer;
};
#define SYSRQ_KEY_RESET_MAX 20 /* Should be plenty */
static unsigned short sysrq_reset_seq[SYSRQ_KEY_RESET_MAX];
static unsigned int sysrq_reset_seq_len;
static unsigned int sysrq_reset_seq_version = 1;
static void sysrq_parse_reset_sequence(struct sysrq_state *state)
{
int i;
unsigned short key;
state->reset_seq_cnt = 0;
for (i = 0; i < sysrq_reset_seq_len; i++) {
key = sysrq_reset_seq[i];
if (key == KEY_RESERVED || key > KEY_MAX)
break;
__set_bit(key, state->reset_keybit);
state->reset_seq_len++;
if (test_bit(key, state->key_down))
state->reset_seq_cnt++;
}
/* Disable reset until old keys are not released */
state->reset_canceled = state->reset_seq_cnt != 0;
state->reset_seq_version = sysrq_reset_seq_version;
}
static void sysrq_do_reset(unsigned long dummy)
{
__handle_sysrq(sysrq_xlate[KEY_B], false);
}
static void sysrq_handle_reset_request(struct sysrq_state *state)
{
if (sysrq_reset_downtime_ms)
mod_timer(&state->keyreset_timer,
jiffies + msecs_to_jiffies(sysrq_reset_downtime_ms));
else
sysrq_do_reset(0);
}
static void sysrq_detect_reset_sequence(struct sysrq_state *state,
unsigned int code, int value)
{
if (!test_bit(code, state->reset_keybit)) {
/*
* Pressing any key _not_ in reset sequence cancels
* the reset sequence. Also cancelling the timer in
* case additional keys were pressed after a reset
* has been requested.
*/
if (value && state->reset_seq_cnt) {
state->reset_canceled = true;
del_timer(&state->keyreset_timer);
}
} else if (value == 0) {
/*
* Key release - all keys in the reset sequence need
* to be pressed and held for the reset timeout
* to hold.
*/
del_timer(&state->keyreset_timer);
if (--state->reset_seq_cnt == 0)
state->reset_canceled = false;
} else if (value == 1) {
/* key press, not autorepeat */
if (++state->reset_seq_cnt == state->reset_seq_len &&
!state->reset_canceled) {
sysrq_handle_reset_request(state);
}
}
}
static void sysrq_reinject_alt_sysrq(struct work_struct *work)
{
struct sysrq_state *sysrq =
container_of(work, struct sysrq_state, reinject_work);
struct input_handle *handle = &sysrq->handle;
unsigned int alt_code = sysrq->alt_use;
if (sysrq->need_reinject) {
/* we do not want the assignment to be reordered */
sysrq->reinjecting = true;
mb();
/* Simulate press and release of Alt + SysRq */
input_inject_event(handle, EV_KEY, alt_code, 1);
input_inject_event(handle, EV_KEY, KEY_SYSRQ, 1);
input_inject_event(handle, EV_SYN, SYN_REPORT, 1);
input_inject_event(handle, EV_KEY, KEY_SYSRQ, 0);
input_inject_event(handle, EV_KEY, alt_code, 0);
input_inject_event(handle, EV_SYN, SYN_REPORT, 1);
mb();
sysrq->reinjecting = false;
}
}
static bool sysrq_handle_keypress(struct sysrq_state *sysrq,
unsigned int code, int value)
{
bool was_active = sysrq->active;
bool suppress;
switch (code) {
case KEY_LEFTALT:
case KEY_RIGHTALT:
if (!value) {
/* One of ALTs is being released */
if (sysrq->active && code == sysrq->alt_use)
sysrq->active = false;
sysrq->alt = KEY_RESERVED;
} else if (value != 2) {
sysrq->alt = code;
sysrq->need_reinject = false;
}
break;
case KEY_SYSRQ:
if (value == 1 && sysrq->alt != KEY_RESERVED) {
sysrq->active = true;
sysrq->alt_use = sysrq->alt;
/*
* If nothing else will be pressed we'll need
* to re-inject Alt-SysRq keysroke.
*/
sysrq->need_reinject = true;
}
/*
* Pretend that sysrq was never pressed at all. This
* is needed to properly handle KGDB which will try
* to release all keys after exiting debugger. If we
* do not clear key bit it KGDB will end up sending
* release events for Alt and SysRq, potentially
* triggering print screen function.
*/
if (sysrq->active)
clear_bit(KEY_SYSRQ, sysrq->handle.dev->key);
break;
default:
if (sysrq->active && value && value != 2) {
sysrq->need_reinject = false;
__handle_sysrq(sysrq_xlate[code], true);
}
break;
}
suppress = sysrq->active;
if (!sysrq->active) {
/*
* See if reset sequence has changed since the last time.
*/
if (sysrq->reset_seq_version != sysrq_reset_seq_version)
sysrq_parse_reset_sequence(sysrq);
/*
* If we are not suppressing key presses keep track of
* keyboard state so we can release keys that have been
* pressed before entering SysRq mode.
*/
if (value)
set_bit(code, sysrq->key_down);
else
clear_bit(code, sysrq->key_down);
if (was_active)
schedule_work(&sysrq->reinject_work);
/* Check for reset sequence */
sysrq_detect_reset_sequence(sysrq, code, value);
} else if (value == 0 && test_and_clear_bit(code, sysrq->key_down)) {
/*
* Pass on release events for keys that was pressed before
* entering SysRq mode.
*/
suppress = false;
}
return suppress;
}
static bool sysrq_filter(struct input_handle *handle,
unsigned int type, unsigned int code, int value)
{
struct sysrq_state *sysrq = handle->private;
bool suppress;
/*
* Do not filter anything if we are in the process of re-injecting
* Alt+SysRq combination.
*/
if (sysrq->reinjecting)
return false;
switch (type) {
case EV_SYN:
suppress = false;
break;
case EV_KEY:
suppress = sysrq_handle_keypress(sysrq, code, value);
break;
default:
suppress = sysrq->active;
break;
}
return suppress;
}
static int sysrq_connect(struct input_handler *handler,
struct input_dev *dev,
const struct input_device_id *id)
{
struct sysrq_state *sysrq;
int error;
sysrq = kzalloc(sizeof(struct sysrq_state), GFP_KERNEL);
if (!sysrq)
return -ENOMEM;
INIT_WORK(&sysrq->reinject_work, sysrq_reinject_alt_sysrq);
sysrq->handle.dev = dev;
sysrq->handle.handler = handler;
sysrq->handle.name = "sysrq";
sysrq->handle.private = sysrq;
setup_timer(&sysrq->keyreset_timer, sysrq_do_reset, 0);
error = input_register_handle(&sysrq->handle);
if (error) {
pr_err("Failed to register input sysrq handler, error %d\n",
error);
goto err_free;
}
error = input_open_device(&sysrq->handle);
if (error) {
pr_err("Failed to open input device, error %d\n", error);
goto err_unregister;
}
return 0;
err_unregister:
input_unregister_handle(&sysrq->handle);
err_free:
kfree(sysrq);
return error;
}
static void sysrq_disconnect(struct input_handle *handle)
{
struct sysrq_state *sysrq = handle->private;
input_close_device(handle);
cancel_work_sync(&sysrq->reinject_work);
del_timer_sync(&sysrq->keyreset_timer);
input_unregister_handle(handle);
kfree(sysrq);
}
/*
* We are matching on KEY_LEFTALT instead of KEY_SYSRQ because not all
* keyboards have SysRq key predefined and so user may add it to keymap
* later, but we expect all such keyboards to have left alt.
*/
static const struct input_device_id sysrq_ids[] = {
{
.flags = INPUT_DEVICE_ID_MATCH_EVBIT |
INPUT_DEVICE_ID_MATCH_KEYBIT,
.evbit = { BIT_MASK(EV_KEY) },
.keybit = { BIT_MASK(KEY_LEFTALT) },
},
{ },
};
static struct input_handler sysrq_handler = {
.filter = sysrq_filter,
.connect = sysrq_connect,
.disconnect = sysrq_disconnect,
.name = "sysrq",
.id_table = sysrq_ids,
};
static bool sysrq_handler_registered;
static inline void sysrq_register_handler(void)
{
unsigned short key;
int error;
int i;
for (i = 0; i < ARRAY_SIZE(sysrq_reset_seq); i++) {
key = platform_sysrq_reset_seq[i];
if (key == KEY_RESERVED || key > KEY_MAX)
break;
sysrq_reset_seq[sysrq_reset_seq_len++] = key;
}
error = input_register_handler(&sysrq_handler);
if (error)
pr_err("Failed to register input handler, error %d", error);
else
sysrq_handler_registered = true;
}
static inline void sysrq_unregister_handler(void)
{
if (sysrq_handler_registered) {
input_unregister_handler(&sysrq_handler);
sysrq_handler_registered = false;
}
}
static int sysrq_reset_seq_param_set(const char *buffer,
const struct kernel_param *kp)
{
unsigned long val;
int error;
error = strict_strtoul(buffer, 0, &val);
if (error < 0)
return error;
if (val > KEY_MAX)
return -EINVAL;
*((unsigned short *)kp->arg) = val;
sysrq_reset_seq_version++;
return 0;
}
static struct kernel_param_ops param_ops_sysrq_reset_seq = {
.get = param_get_ushort,
.set = sysrq_reset_seq_param_set,
};
#define param_check_sysrq_reset_seq(name, p) \
__param_check(name, p, unsigned short)
module_param_array_named(reset_seq, sysrq_reset_seq, sysrq_reset_seq,
&sysrq_reset_seq_len, 0644);
module_param_named(sysrq_downtime_ms, sysrq_reset_downtime_ms, int, 0644);
#else
static inline void sysrq_register_handler(void)
{
}
static inline void sysrq_unregister_handler(void)
{
}
#endif /* CONFIG_INPUT */
int sysrq_toggle_support(int enable_mask)
{
bool was_enabled = sysrq_on();
sysrq_enabled = enable_mask;
if (was_enabled != sysrq_on()) {
if (sysrq_on())
sysrq_register_handler();
else
sysrq_unregister_handler();
}
return 0;
}
static int __sysrq_swap_key_ops(int key, struct sysrq_key_op *insert_op_p,
struct sysrq_key_op *remove_op_p)
{
int retval;
unsigned long flags;
spin_lock_irqsave(&sysrq_key_table_lock, flags);
if (__sysrq_get_key_op(key) == remove_op_p) {
__sysrq_put_key_op(key, insert_op_p);
retval = 0;
} else {
retval = -1;
}
spin_unlock_irqrestore(&sysrq_key_table_lock, flags);
return retval;
}
int register_sysrq_key(int key, struct sysrq_key_op *op_p)
{
return __sysrq_swap_key_ops(key, op_p, NULL);
}
EXPORT_SYMBOL(register_sysrq_key);
int unregister_sysrq_key(int key, struct sysrq_key_op *op_p)
{
return __sysrq_swap_key_ops(key, NULL, op_p);
}
EXPORT_SYMBOL(unregister_sysrq_key);
#ifdef CONFIG_PROC_FS
/*
* writing 'C' to /proc/sysrq-trigger is like sysrq-C
*/
static ssize_t write_sysrq_trigger(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
if (count) {
char c;
if (get_user(c, buf))
return -EFAULT;
__handle_sysrq(c, false);
}
return count;
}
static const struct file_operations proc_sysrq_trigger_operations = {
.write = write_sysrq_trigger,
.llseek = noop_llseek,
};
static void sysrq_init_procfs(void)
{
if (!proc_create("sysrq-trigger", S_IWUSR, NULL,
&proc_sysrq_trigger_operations))
pr_err("Failed to register proc interface\n");
}
#else
static inline void sysrq_init_procfs(void)
{
}
#endif /* CONFIG_PROC_FS */
static int __init sysrq_init(void)
{
sysrq_init_procfs();
if (sysrq_on())
sysrq_register_handler();
return 0;
}
module_init(sysrq_init);
| gpl-2.0 |
saafir7/exynos7420 | arch/arm/mach-s5pv210/mach-aquila.c | 2048 | 16978 | /* linux/arch/arm/mach-s5pv210/mach-aquila.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/serial_core.h>
#include <linux/fb.h>
#include <linux/i2c.h>
#include <linux/i2c-gpio.h>
#include <linux/mfd/max8998.h>
#include <linux/mfd/wm8994/pdata.h>
#include <linux/regulator/fixed.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/gpio.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <video/samsung_fimd.h>
#include <mach/map.h>
#include <mach/regs-clock.h>
#include <plat/gpio-cfg.h>
#include <plat/regs-serial.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/fb.h>
#include <plat/fimc-core.h>
#include <plat/sdhci.h>
#include <plat/samsung-time.h>
#include "common.h"
/* Following are default values for UCON, ULCON and UFCON UART registers */
#define AQUILA_UCON_DEFAULT (S3C2410_UCON_TXILEVEL | \
S3C2410_UCON_RXILEVEL | \
S3C2410_UCON_TXIRQMODE | \
S3C2410_UCON_RXIRQMODE | \
S3C2410_UCON_RXFIFO_TOI | \
S3C2443_UCON_RXERR_IRQEN)
#define AQUILA_ULCON_DEFAULT S3C2410_LCON_CS8
#define AQUILA_UFCON_DEFAULT S3C2410_UFCON_FIFOMODE
static struct s3c2410_uartcfg aquila_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = AQUILA_UCON_DEFAULT,
.ulcon = AQUILA_ULCON_DEFAULT,
/*
* Actually UART0 can support 256 bytes fifo, but aquila board
* supports 128 bytes fifo because of initial chip bug
*/
.ufcon = AQUILA_UFCON_DEFAULT |
S5PV210_UFCON_TXTRIG128 | S5PV210_UFCON_RXTRIG128,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = AQUILA_UCON_DEFAULT,
.ulcon = AQUILA_ULCON_DEFAULT,
.ufcon = AQUILA_UFCON_DEFAULT |
S5PV210_UFCON_TXTRIG64 | S5PV210_UFCON_RXTRIG64,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = AQUILA_UCON_DEFAULT,
.ulcon = AQUILA_ULCON_DEFAULT,
.ufcon = AQUILA_UFCON_DEFAULT |
S5PV210_UFCON_TXTRIG16 | S5PV210_UFCON_RXTRIG16,
},
[3] = {
.hwport = 3,
.flags = 0,
.ucon = AQUILA_UCON_DEFAULT,
.ulcon = AQUILA_ULCON_DEFAULT,
.ufcon = AQUILA_UFCON_DEFAULT |
S5PV210_UFCON_TXTRIG16 | S5PV210_UFCON_RXTRIG16,
},
};
/* Frame Buffer */
static struct s3c_fb_pd_win aquila_fb_win0 = {
.max_bpp = 32,
.default_bpp = 16,
.xres = 480,
.yres = 800,
};
static struct s3c_fb_pd_win aquila_fb_win1 = {
.max_bpp = 32,
.default_bpp = 16,
.xres = 480,
.yres = 800,
};
static struct fb_videomode aquila_lcd_timing = {
.left_margin = 16,
.right_margin = 16,
.upper_margin = 3,
.lower_margin = 28,
.hsync_len = 2,
.vsync_len = 2,
.xres = 480,
.yres = 800,
};
static struct s3c_fb_platdata aquila_lcd_pdata __initdata = {
.win[0] = &aquila_fb_win0,
.win[1] = &aquila_fb_win1,
.vtiming = &aquila_lcd_timing,
.vidcon0 = VIDCON0_VIDOUT_RGB | VIDCON0_PNRMODE_RGB,
.vidcon1 = VIDCON1_INV_HSYNC | VIDCON1_INV_VSYNC |
VIDCON1_INV_VCLK | VIDCON1_INV_VDEN,
.setup_gpio = s5pv210_fb_gpio_setup_24bpp,
};
/* MAX8998 regulators */
#if defined(CONFIG_REGULATOR_MAX8998) || defined(CONFIG_REGULATOR_MAX8998_MODULE)
static struct regulator_init_data aquila_ldo2_data = {
.constraints = {
.name = "VALIVE_1.1V",
.min_uV = 1100000,
.max_uV = 1100000,
.apply_uV = 1,
.always_on = 1,
.state_mem = {
.enabled = 1,
},
},
};
static struct regulator_init_data aquila_ldo3_data = {
.constraints = {
.name = "VUSB+MIPI_1.1V",
.min_uV = 1100000,
.max_uV = 1100000,
.apply_uV = 1,
.always_on = 1,
},
};
static struct regulator_init_data aquila_ldo4_data = {
.constraints = {
.name = "VDAC_3.3V",
.min_uV = 3300000,
.max_uV = 3300000,
.apply_uV = 1,
},
};
static struct regulator_init_data aquila_ldo5_data = {
.constraints = {
.name = "VTF_2.8V",
.min_uV = 2800000,
.max_uV = 2800000,
.apply_uV = 1,
},
};
static struct regulator_init_data aquila_ldo6_data = {
.constraints = {
.name = "VCC_3.3V",
.min_uV = 3300000,
.max_uV = 3300000,
.apply_uV = 1,
},
};
static struct regulator_init_data aquila_ldo7_data = {
.constraints = {
.name = "VCC_3.0V",
.min_uV = 3000000,
.max_uV = 3000000,
.apply_uV = 1,
.boot_on = 1,
.always_on = 1,
},
};
static struct regulator_init_data aquila_ldo8_data = {
.constraints = {
.name = "VUSB+VADC_3.3V",
.min_uV = 3300000,
.max_uV = 3300000,
.apply_uV = 1,
.always_on = 1,
},
};
static struct regulator_init_data aquila_ldo9_data = {
.constraints = {
.name = "VCC+VCAM_2.8V",
.min_uV = 2800000,
.max_uV = 2800000,
.apply_uV = 1,
.always_on = 1,
},
};
static struct regulator_init_data aquila_ldo10_data = {
.constraints = {
.name = "VPLL_1.1V",
.min_uV = 1100000,
.max_uV = 1100000,
.apply_uV = 1,
.boot_on = 1,
},
};
static struct regulator_init_data aquila_ldo11_data = {
.constraints = {
.name = "CAM_IO_2.8V",
.min_uV = 2800000,
.max_uV = 2800000,
.apply_uV = 1,
.always_on = 1,
},
};
static struct regulator_init_data aquila_ldo12_data = {
.constraints = {
.name = "CAM_ISP_1.2V",
.min_uV = 1200000,
.max_uV = 1200000,
.apply_uV = 1,
.always_on = 1,
},
};
static struct regulator_init_data aquila_ldo13_data = {
.constraints = {
.name = "CAM_A_2.8V",
.min_uV = 2800000,
.max_uV = 2800000,
.apply_uV = 1,
.always_on = 1,
},
};
static struct regulator_init_data aquila_ldo14_data = {
.constraints = {
.name = "CAM_CIF_1.8V",
.min_uV = 1800000,
.max_uV = 1800000,
.apply_uV = 1,
.always_on = 1,
},
};
static struct regulator_init_data aquila_ldo15_data = {
.constraints = {
.name = "CAM_AF_3.3V",
.min_uV = 3300000,
.max_uV = 3300000,
.apply_uV = 1,
.always_on = 1,
},
};
static struct regulator_init_data aquila_ldo16_data = {
.constraints = {
.name = "VMIPI_1.8V",
.min_uV = 1800000,
.max_uV = 1800000,
.apply_uV = 1,
.always_on = 1,
},
};
static struct regulator_init_data aquila_ldo17_data = {
.constraints = {
.name = "CAM_8M_1.8V",
.min_uV = 1800000,
.max_uV = 1800000,
.apply_uV = 1,
.always_on = 1,
},
};
/* BUCK */
static struct regulator_consumer_supply buck1_consumer =
REGULATOR_SUPPLY("vddarm", NULL);
static struct regulator_consumer_supply buck2_consumer =
REGULATOR_SUPPLY("vddint", NULL);
static struct regulator_init_data aquila_buck1_data = {
.constraints = {
.name = "VARM_1.2V",
.min_uV = 1200000,
.max_uV = 1200000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = 1,
.consumer_supplies = &buck1_consumer,
};
static struct regulator_init_data aquila_buck2_data = {
.constraints = {
.name = "VINT_1.2V",
.min_uV = 1200000,
.max_uV = 1200000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = 1,
.consumer_supplies = &buck2_consumer,
};
static struct regulator_init_data aquila_buck3_data = {
.constraints = {
.name = "VCC_1.8V",
.min_uV = 1800000,
.max_uV = 1800000,
.apply_uV = 1,
.state_mem = {
.enabled = 1,
},
},
};
static struct regulator_init_data aquila_buck4_data = {
.constraints = {
.name = "CAM_CORE_1.2V",
.min_uV = 1200000,
.max_uV = 1200000,
.apply_uV = 1,
.always_on = 1,
},
};
static struct max8998_regulator_data aquila_regulators[] = {
{ MAX8998_LDO2, &aquila_ldo2_data },
{ MAX8998_LDO3, &aquila_ldo3_data },
{ MAX8998_LDO4, &aquila_ldo4_data },
{ MAX8998_LDO5, &aquila_ldo5_data },
{ MAX8998_LDO6, &aquila_ldo6_data },
{ MAX8998_LDO7, &aquila_ldo7_data },
{ MAX8998_LDO8, &aquila_ldo8_data },
{ MAX8998_LDO9, &aquila_ldo9_data },
{ MAX8998_LDO10, &aquila_ldo10_data },
{ MAX8998_LDO11, &aquila_ldo11_data },
{ MAX8998_LDO12, &aquila_ldo12_data },
{ MAX8998_LDO13, &aquila_ldo13_data },
{ MAX8998_LDO14, &aquila_ldo14_data },
{ MAX8998_LDO15, &aquila_ldo15_data },
{ MAX8998_LDO16, &aquila_ldo16_data },
{ MAX8998_LDO17, &aquila_ldo17_data },
{ MAX8998_BUCK1, &aquila_buck1_data },
{ MAX8998_BUCK2, &aquila_buck2_data },
{ MAX8998_BUCK3, &aquila_buck3_data },
{ MAX8998_BUCK4, &aquila_buck4_data },
};
static struct max8998_platform_data aquila_max8998_pdata = {
.num_regulators = ARRAY_SIZE(aquila_regulators),
.regulators = aquila_regulators,
.buck1_set1 = S5PV210_GPH0(3),
.buck1_set2 = S5PV210_GPH0(4),
.buck2_set3 = S5PV210_GPH0(5),
.buck1_voltage1 = 1200000,
.buck1_voltage2 = 1200000,
.buck1_voltage3 = 1200000,
.buck1_voltage4 = 1200000,
.buck2_voltage1 = 1200000,
.buck2_voltage2 = 1200000,
};
#endif
static struct regulator_consumer_supply wm8994_fixed_voltage0_supplies[] = {
REGULATOR_SUPPLY("DBVDD", "5-001a"),
REGULATOR_SUPPLY("AVDD2", "5-001a"),
REGULATOR_SUPPLY("CPVDD", "5-001a"),
};
static struct regulator_consumer_supply wm8994_fixed_voltage1_supplies[] = {
REGULATOR_SUPPLY("SPKVDD1", "5-001a"),
REGULATOR_SUPPLY("SPKVDD2", "5-001a"),
};
static struct regulator_init_data wm8994_fixed_voltage0_init_data = {
.constraints = {
.always_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(wm8994_fixed_voltage0_supplies),
.consumer_supplies = wm8994_fixed_voltage0_supplies,
};
static struct regulator_init_data wm8994_fixed_voltage1_init_data = {
.constraints = {
.always_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(wm8994_fixed_voltage1_supplies),
.consumer_supplies = wm8994_fixed_voltage1_supplies,
};
static struct fixed_voltage_config wm8994_fixed_voltage0_config = {
.supply_name = "VCC_1.8V_PDA",
.microvolts = 1800000,
.gpio = -EINVAL,
.init_data = &wm8994_fixed_voltage0_init_data,
};
static struct fixed_voltage_config wm8994_fixed_voltage1_config = {
.supply_name = "V_BAT",
.microvolts = 3700000,
.gpio = -EINVAL,
.init_data = &wm8994_fixed_voltage1_init_data,
};
static struct platform_device wm8994_fixed_voltage0 = {
.name = "reg-fixed-voltage",
.id = 0,
.dev = {
.platform_data = &wm8994_fixed_voltage0_config,
},
};
static struct platform_device wm8994_fixed_voltage1 = {
.name = "reg-fixed-voltage",
.id = 1,
.dev = {
.platform_data = &wm8994_fixed_voltage1_config,
},
};
static struct regulator_consumer_supply wm8994_avdd1_supply =
REGULATOR_SUPPLY("AVDD1", "5-001a");
static struct regulator_consumer_supply wm8994_dcvdd_supply =
REGULATOR_SUPPLY("DCVDD", "5-001a");
static struct regulator_init_data wm8994_ldo1_data = {
.constraints = {
.name = "AVDD1_3.0V",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = 1,
.consumer_supplies = &wm8994_avdd1_supply,
};
static struct regulator_init_data wm8994_ldo2_data = {
.constraints = {
.name = "DCVDD_1.0V",
},
.num_consumer_supplies = 1,
.consumer_supplies = &wm8994_dcvdd_supply,
};
static struct wm8994_pdata wm8994_platform_data = {
/* configure gpio1 function: 0x0001(Logic level input/output) */
.gpio_defaults[0] = 0x0001,
/* configure gpio3/4/5/7 function for AIF2 voice */
.gpio_defaults[2] = 0x8100,
.gpio_defaults[3] = 0x8100,
.gpio_defaults[4] = 0x8100,
.gpio_defaults[6] = 0x0100,
/* configure gpio8/9/10/11 function for AIF3 BT */
.gpio_defaults[7] = 0x8100,
.gpio_defaults[8] = 0x0100,
.gpio_defaults[9] = 0x0100,
.gpio_defaults[10] = 0x0100,
.ldo[0] = { S5PV210_MP03(6), &wm8994_ldo1_data }, /* XM0FRNB_2 */
.ldo[1] = { 0, &wm8994_ldo2_data },
};
/* GPIO I2C PMIC */
#define AP_I2C_GPIO_PMIC_BUS_4 4
static struct i2c_gpio_platform_data aquila_i2c_gpio_pmic_data = {
.sda_pin = S5PV210_GPJ4(0), /* XMSMCSN */
.scl_pin = S5PV210_GPJ4(3), /* XMSMIRQN */
};
static struct platform_device aquila_i2c_gpio_pmic = {
.name = "i2c-gpio",
.id = AP_I2C_GPIO_PMIC_BUS_4,
.dev = {
.platform_data = &aquila_i2c_gpio_pmic_data,
},
};
static struct i2c_board_info i2c_gpio_pmic_devs[] __initdata = {
#if defined(CONFIG_REGULATOR_MAX8998) || defined(CONFIG_REGULATOR_MAX8998_MODULE)
{
/* 0xCC when SRAD = 0 */
I2C_BOARD_INFO("max8998", 0xCC >> 1),
.platform_data = &aquila_max8998_pdata,
},
#endif
};
/* GPIO I2C AP 1.8V */
#define AP_I2C_GPIO_BUS_5 5
static struct i2c_gpio_platform_data aquila_i2c_gpio5_data = {
.sda_pin = S5PV210_MP05(3), /* XM0ADDR_11 */
.scl_pin = S5PV210_MP05(2), /* XM0ADDR_10 */
};
static struct platform_device aquila_i2c_gpio5 = {
.name = "i2c-gpio",
.id = AP_I2C_GPIO_BUS_5,
.dev = {
.platform_data = &aquila_i2c_gpio5_data,
},
};
static struct i2c_board_info i2c_gpio5_devs[] __initdata = {
{
/* CS/ADDR = low 0x34 (FYI: high = 0x36) */
I2C_BOARD_INFO("wm8994", 0x1a),
.platform_data = &wm8994_platform_data,
},
};
/* PMIC Power button */
static struct gpio_keys_button aquila_gpio_keys_table[] = {
{
.code = KEY_POWER,
.gpio = S5PV210_GPH2(6),
.desc = "gpio-keys: KEY_POWER",
.type = EV_KEY,
.active_low = 1,
.wakeup = 1,
.debounce_interval = 1,
},
};
static struct gpio_keys_platform_data aquila_gpio_keys_data = {
.buttons = aquila_gpio_keys_table,
.nbuttons = ARRAY_SIZE(aquila_gpio_keys_table),
};
static struct platform_device aquila_device_gpiokeys = {
.name = "gpio-keys",
.dev = {
.platform_data = &aquila_gpio_keys_data,
},
};
static void __init aquila_pmic_init(void)
{
/* AP_PMIC_IRQ: EINT7 */
s3c_gpio_cfgpin(S5PV210_GPH0(7), S3C_GPIO_SFN(0xf));
s3c_gpio_setpull(S5PV210_GPH0(7), S3C_GPIO_PULL_UP);
/* nPower: EINT22 */
s3c_gpio_cfgpin(S5PV210_GPH2(6), S3C_GPIO_SFN(0xf));
s3c_gpio_setpull(S5PV210_GPH2(6), S3C_GPIO_PULL_UP);
}
/* MoviNAND */
static struct s3c_sdhci_platdata aquila_hsmmc0_data __initdata = {
.max_width = 4,
.cd_type = S3C_SDHCI_CD_PERMANENT,
};
/* Wireless LAN */
static struct s3c_sdhci_platdata aquila_hsmmc1_data __initdata = {
.max_width = 4,
.cd_type = S3C_SDHCI_CD_EXTERNAL,
/* ext_cd_{init,cleanup} callbacks will be added later */
};
/* External Flash */
#define AQUILA_EXT_FLASH_EN S5PV210_MP05(4)
#define AQUILA_EXT_FLASH_CD S5PV210_GPH3(4)
static struct s3c_sdhci_platdata aquila_hsmmc2_data __initdata = {
.max_width = 4,
.cd_type = S3C_SDHCI_CD_GPIO,
.ext_cd_gpio = AQUILA_EXT_FLASH_CD,
.ext_cd_gpio_invert = 1,
};
static void aquila_setup_sdhci(void)
{
gpio_request_one(AQUILA_EXT_FLASH_EN, GPIOF_OUT_INIT_HIGH, "FLASH_EN");
s3c_sdhci0_set_platdata(&aquila_hsmmc0_data);
s3c_sdhci1_set_platdata(&aquila_hsmmc1_data);
s3c_sdhci2_set_platdata(&aquila_hsmmc2_data);
};
/* Audio device */
static struct platform_device aquila_device_audio = {
.name = "smdk-audio",
.id = -1,
};
static struct platform_device *aquila_devices[] __initdata = {
&aquila_i2c_gpio_pmic,
&aquila_i2c_gpio5,
&aquila_device_gpiokeys,
&aquila_device_audio,
&s3c_device_fb,
&s5p_device_onenand,
&s3c_device_hsmmc0,
&s3c_device_hsmmc1,
&s3c_device_hsmmc2,
&s5p_device_fimc0,
&s5p_device_fimc1,
&s5p_device_fimc2,
&s5p_device_fimc_md,
&s5pv210_device_iis0,
&wm8994_fixed_voltage0,
&wm8994_fixed_voltage1,
};
static void __init aquila_sound_init(void)
{
unsigned int gpio;
/* CODEC_XTAL_EN
*
* The Aquila board have a oscillator which provide main clock
* to WM8994 codec. The oscillator provide 24MHz clock to WM8994
* clock. Set gpio setting of "CODEC_XTAL_EN" to enable a oscillator.
* */
gpio = S5PV210_GPH3(2); /* XEINT_26 */
gpio_request(gpio, "CODEC_XTAL_EN");
s3c_gpio_cfgpin(gpio, S3C_GPIO_OUTPUT);
s3c_gpio_setpull(gpio, S3C_GPIO_PULL_NONE);
/* Ths main clock of WM8994 codec uses the output of CLKOUT pin.
* The CLKOUT[9:8] set to 0x3(XUSBXTI) of 0xE010E000(OTHERS)
* because it needs 24MHz clock to operate WM8994 codec.
*/
__raw_writel(__raw_readl(S5P_OTHERS) | (0x3 << 8), S5P_OTHERS);
}
static void __init aquila_map_io(void)
{
s5pv210_init_io(NULL, 0);
s3c24xx_init_clocks(24000000);
s3c24xx_init_uarts(aquila_uartcfgs, ARRAY_SIZE(aquila_uartcfgs));
samsung_set_timer_source(SAMSUNG_PWM3, SAMSUNG_PWM4);
}
static void __init aquila_machine_init(void)
{
/* PMIC */
aquila_pmic_init();
i2c_register_board_info(AP_I2C_GPIO_PMIC_BUS_4, i2c_gpio_pmic_devs,
ARRAY_SIZE(i2c_gpio_pmic_devs));
/* SDHCI */
aquila_setup_sdhci();
s3c_fimc_setname(0, "s5p-fimc");
s3c_fimc_setname(1, "s5p-fimc");
s3c_fimc_setname(2, "s5p-fimc");
/* SOUND */
aquila_sound_init();
i2c_register_board_info(AP_I2C_GPIO_BUS_5, i2c_gpio5_devs,
ARRAY_SIZE(i2c_gpio5_devs));
/* FB */
s3c_fb_set_platdata(&aquila_lcd_pdata);
platform_add_devices(aquila_devices, ARRAY_SIZE(aquila_devices));
}
MACHINE_START(AQUILA, "Aquila")
/* Maintainers:
Marek Szyprowski <m.szyprowski@samsung.com>
Kyungmin Park <kyungmin.park@samsung.com> */
.atag_offset = 0x100,
.init_irq = s5pv210_init_irq,
.map_io = aquila_map_io,
.init_machine = aquila_machine_init,
.init_time = samsung_timer_init,
.restart = s5pv210_restart,
MACHINE_END
| gpl-2.0 |
simone201/neak-gs3-jb2 | 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 |
tilaksidduram/Stock_kernel | drivers/mmc/host/wbsd.c | 2816 | 40832 | /*
* linux/drivers/mmc/host/wbsd.c - Winbond W83L51xD SD/MMC driver
*
* Copyright (C) 2004-2007 Pierre Ossman, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
*
* Warning!
*
* Changes to the FIFO system should be done with extreme care since
* the hardware is full of bugs related to the FIFO. Known issues are:
*
* - FIFO size field in FSR is always zero.
*
* - FIFO interrupts tend not to work as they should. Interrupts are
* triggered only for full/empty events, not for threshold values.
*
* - On APIC systems the FIFO empty interrupt is sometimes lost.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <linux/pnp.h>
#include <linux/highmem.h>
#include <linux/mmc/host.h>
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <asm/dma.h>
#include "wbsd.h"
#define DRIVER_NAME "wbsd"
#define DBG(x...) \
pr_debug(DRIVER_NAME ": " x)
#define DBGF(f, x...) \
pr_debug(DRIVER_NAME " [%s()]: " f, __func__ , ##x)
/*
* Device resources
*/
#ifdef CONFIG_PNP
static const struct pnp_device_id pnp_dev_table[] = {
{ "WEC0517", 0 },
{ "WEC0518", 0 },
{ "", 0 },
};
MODULE_DEVICE_TABLE(pnp, pnp_dev_table);
#endif /* CONFIG_PNP */
static const int config_ports[] = { 0x2E, 0x4E };
static const int unlock_codes[] = { 0x83, 0x87 };
static const int valid_ids[] = {
0x7112,
};
#ifdef CONFIG_PNP
static unsigned int param_nopnp = 0;
#else
static const unsigned int param_nopnp = 1;
#endif
static unsigned int param_io = 0x248;
static unsigned int param_irq = 6;
static int param_dma = 2;
/*
* Basic functions
*/
static inline void wbsd_unlock_config(struct wbsd_host *host)
{
BUG_ON(host->config == 0);
outb(host->unlock_code, host->config);
outb(host->unlock_code, host->config);
}
static inline void wbsd_lock_config(struct wbsd_host *host)
{
BUG_ON(host->config == 0);
outb(LOCK_CODE, host->config);
}
static inline void wbsd_write_config(struct wbsd_host *host, u8 reg, u8 value)
{
BUG_ON(host->config == 0);
outb(reg, host->config);
outb(value, host->config + 1);
}
static inline u8 wbsd_read_config(struct wbsd_host *host, u8 reg)
{
BUG_ON(host->config == 0);
outb(reg, host->config);
return inb(host->config + 1);
}
static inline void wbsd_write_index(struct wbsd_host *host, u8 index, u8 value)
{
outb(index, host->base + WBSD_IDXR);
outb(value, host->base + WBSD_DATAR);
}
static inline u8 wbsd_read_index(struct wbsd_host *host, u8 index)
{
outb(index, host->base + WBSD_IDXR);
return inb(host->base + WBSD_DATAR);
}
/*
* Common routines
*/
static void wbsd_init_device(struct wbsd_host *host)
{
u8 setup, ier;
/*
* Reset chip (SD/MMC part) and fifo.
*/
setup = wbsd_read_index(host, WBSD_IDX_SETUP);
setup |= WBSD_FIFO_RESET | WBSD_SOFT_RESET;
wbsd_write_index(host, WBSD_IDX_SETUP, setup);
/*
* Set DAT3 to input
*/
setup &= ~WBSD_DAT3_H;
wbsd_write_index(host, WBSD_IDX_SETUP, setup);
host->flags &= ~WBSD_FIGNORE_DETECT;
/*
* Read back default clock.
*/
host->clk = wbsd_read_index(host, WBSD_IDX_CLK);
/*
* Power down port.
*/
outb(WBSD_POWER_N, host->base + WBSD_CSR);
/*
* Set maximum timeout.
*/
wbsd_write_index(host, WBSD_IDX_TAAC, 0x7F);
/*
* Test for card presence
*/
if (inb(host->base + WBSD_CSR) & WBSD_CARDPRESENT)
host->flags |= WBSD_FCARD_PRESENT;
else
host->flags &= ~WBSD_FCARD_PRESENT;
/*
* Enable interesting interrupts.
*/
ier = 0;
ier |= WBSD_EINT_CARD;
ier |= WBSD_EINT_FIFO_THRE;
ier |= WBSD_EINT_CRC;
ier |= WBSD_EINT_TIMEOUT;
ier |= WBSD_EINT_TC;
outb(ier, host->base + WBSD_EIR);
/*
* Clear interrupts.
*/
inb(host->base + WBSD_ISR);
}
static void wbsd_reset(struct wbsd_host *host)
{
u8 setup;
printk(KERN_ERR "%s: Resetting chip\n", mmc_hostname(host->mmc));
/*
* Soft reset of chip (SD/MMC part).
*/
setup = wbsd_read_index(host, WBSD_IDX_SETUP);
setup |= WBSD_SOFT_RESET;
wbsd_write_index(host, WBSD_IDX_SETUP, setup);
}
static void wbsd_request_end(struct wbsd_host *host, struct mmc_request *mrq)
{
unsigned long dmaflags;
if (host->dma >= 0) {
/*
* Release ISA DMA controller.
*/
dmaflags = claim_dma_lock();
disable_dma(host->dma);
clear_dma_ff(host->dma);
release_dma_lock(dmaflags);
/*
* Disable DMA on host.
*/
wbsd_write_index(host, WBSD_IDX_DMA, 0);
}
host->mrq = NULL;
/*
* MMC layer might call back into the driver so first unlock.
*/
spin_unlock(&host->lock);
mmc_request_done(host->mmc, mrq);
spin_lock(&host->lock);
}
/*
* Scatter/gather functions
*/
static inline void wbsd_init_sg(struct wbsd_host *host, struct mmc_data *data)
{
/*
* Get info. about SG list from data structure.
*/
host->cur_sg = data->sg;
host->num_sg = data->sg_len;
host->offset = 0;
host->remain = host->cur_sg->length;
}
static inline int wbsd_next_sg(struct wbsd_host *host)
{
/*
* Skip to next SG entry.
*/
host->cur_sg++;
host->num_sg--;
/*
* Any entries left?
*/
if (host->num_sg > 0) {
host->offset = 0;
host->remain = host->cur_sg->length;
}
return host->num_sg;
}
static inline char *wbsd_sg_to_buffer(struct wbsd_host *host)
{
return sg_virt(host->cur_sg);
}
static inline void wbsd_sg_to_dma(struct wbsd_host *host, struct mmc_data *data)
{
unsigned int len, i;
struct scatterlist *sg;
char *dmabuf = host->dma_buffer;
char *sgbuf;
sg = data->sg;
len = data->sg_len;
for (i = 0; i < len; i++) {
sgbuf = sg_virt(&sg[i]);
memcpy(dmabuf, sgbuf, sg[i].length);
dmabuf += sg[i].length;
}
}
static inline void wbsd_dma_to_sg(struct wbsd_host *host, struct mmc_data *data)
{
unsigned int len, i;
struct scatterlist *sg;
char *dmabuf = host->dma_buffer;
char *sgbuf;
sg = data->sg;
len = data->sg_len;
for (i = 0; i < len; i++) {
sgbuf = sg_virt(&sg[i]);
memcpy(sgbuf, dmabuf, sg[i].length);
dmabuf += sg[i].length;
}
}
/*
* Command handling
*/
static inline void wbsd_get_short_reply(struct wbsd_host *host,
struct mmc_command *cmd)
{
/*
* Correct response type?
*/
if (wbsd_read_index(host, WBSD_IDX_RSPLEN) != WBSD_RSP_SHORT) {
cmd->error = -EILSEQ;
return;
}
cmd->resp[0] = wbsd_read_index(host, WBSD_IDX_RESP12) << 24;
cmd->resp[0] |= wbsd_read_index(host, WBSD_IDX_RESP13) << 16;
cmd->resp[0] |= wbsd_read_index(host, WBSD_IDX_RESP14) << 8;
cmd->resp[0] |= wbsd_read_index(host, WBSD_IDX_RESP15) << 0;
cmd->resp[1] = wbsd_read_index(host, WBSD_IDX_RESP16) << 24;
}
static inline void wbsd_get_long_reply(struct wbsd_host *host,
struct mmc_command *cmd)
{
int i;
/*
* Correct response type?
*/
if (wbsd_read_index(host, WBSD_IDX_RSPLEN) != WBSD_RSP_LONG) {
cmd->error = -EILSEQ;
return;
}
for (i = 0; i < 4; i++) {
cmd->resp[i] =
wbsd_read_index(host, WBSD_IDX_RESP1 + i * 4) << 24;
cmd->resp[i] |=
wbsd_read_index(host, WBSD_IDX_RESP2 + i * 4) << 16;
cmd->resp[i] |=
wbsd_read_index(host, WBSD_IDX_RESP3 + i * 4) << 8;
cmd->resp[i] |=
wbsd_read_index(host, WBSD_IDX_RESP4 + i * 4) << 0;
}
}
static void wbsd_send_command(struct wbsd_host *host, struct mmc_command *cmd)
{
int i;
u8 status, isr;
/*
* Clear accumulated ISR. The interrupt routine
* will fill this one with events that occur during
* transfer.
*/
host->isr = 0;
/*
* Send the command (CRC calculated by host).
*/
outb(cmd->opcode, host->base + WBSD_CMDR);
for (i = 3; i >= 0; i--)
outb((cmd->arg >> (i * 8)) & 0xff, host->base + WBSD_CMDR);
cmd->error = 0;
/*
* Wait for the request to complete.
*/
do {
status = wbsd_read_index(host, WBSD_IDX_STATUS);
} while (status & WBSD_CARDTRAFFIC);
/*
* Do we expect a reply?
*/
if (cmd->flags & MMC_RSP_PRESENT) {
/*
* Read back status.
*/
isr = host->isr;
/* Card removed? */
if (isr & WBSD_INT_CARD)
cmd->error = -ENOMEDIUM;
/* Timeout? */
else if (isr & WBSD_INT_TIMEOUT)
cmd->error = -ETIMEDOUT;
/* CRC? */
else if ((cmd->flags & MMC_RSP_CRC) && (isr & WBSD_INT_CRC))
cmd->error = -EILSEQ;
/* All ok */
else {
if (cmd->flags & MMC_RSP_136)
wbsd_get_long_reply(host, cmd);
else
wbsd_get_short_reply(host, cmd);
}
}
}
/*
* Data functions
*/
static void wbsd_empty_fifo(struct wbsd_host *host)
{
struct mmc_data *data = host->mrq->cmd->data;
char *buffer;
int i, fsr, fifo;
/*
* Handle excessive data.
*/
if (host->num_sg == 0)
return;
buffer = wbsd_sg_to_buffer(host) + host->offset;
/*
* Drain the fifo. This has a tendency to loop longer
* than the FIFO length (usually one block).
*/
while (!((fsr = inb(host->base + WBSD_FSR)) & WBSD_FIFO_EMPTY)) {
/*
* The size field in the FSR is broken so we have to
* do some guessing.
*/
if (fsr & WBSD_FIFO_FULL)
fifo = 16;
else if (fsr & WBSD_FIFO_FUTHRE)
fifo = 8;
else
fifo = 1;
for (i = 0; i < fifo; i++) {
*buffer = inb(host->base + WBSD_DFR);
buffer++;
host->offset++;
host->remain--;
data->bytes_xfered++;
/*
* End of scatter list entry?
*/
if (host->remain == 0) {
/*
* Get next entry. Check if last.
*/
if (!wbsd_next_sg(host))
return;
buffer = wbsd_sg_to_buffer(host);
}
}
}
/*
* This is a very dirty hack to solve a
* hardware problem. The chip doesn't trigger
* FIFO threshold interrupts properly.
*/
if ((data->blocks * data->blksz - data->bytes_xfered) < 16)
tasklet_schedule(&host->fifo_tasklet);
}
static void wbsd_fill_fifo(struct wbsd_host *host)
{
struct mmc_data *data = host->mrq->cmd->data;
char *buffer;
int i, fsr, fifo;
/*
* Check that we aren't being called after the
* entire buffer has been transferred.
*/
if (host->num_sg == 0)
return;
buffer = wbsd_sg_to_buffer(host) + host->offset;
/*
* Fill the fifo. This has a tendency to loop longer
* than the FIFO length (usually one block).
*/
while (!((fsr = inb(host->base + WBSD_FSR)) & WBSD_FIFO_FULL)) {
/*
* The size field in the FSR is broken so we have to
* do some guessing.
*/
if (fsr & WBSD_FIFO_EMPTY)
fifo = 0;
else if (fsr & WBSD_FIFO_EMTHRE)
fifo = 8;
else
fifo = 15;
for (i = 16; i > fifo; i--) {
outb(*buffer, host->base + WBSD_DFR);
buffer++;
host->offset++;
host->remain--;
data->bytes_xfered++;
/*
* End of scatter list entry?
*/
if (host->remain == 0) {
/*
* Get next entry. Check if last.
*/
if (!wbsd_next_sg(host))
return;
buffer = wbsd_sg_to_buffer(host);
}
}
}
/*
* The controller stops sending interrupts for
* 'FIFO empty' under certain conditions. So we
* need to be a bit more pro-active.
*/
tasklet_schedule(&host->fifo_tasklet);
}
static void wbsd_prepare_data(struct wbsd_host *host, struct mmc_data *data)
{
u16 blksize;
u8 setup;
unsigned long dmaflags;
unsigned int size;
/*
* Calculate size.
*/
size = data->blocks * data->blksz;
/*
* Check timeout values for overflow.
* (Yes, some cards cause this value to overflow).
*/
if (data->timeout_ns > 127000000)
wbsd_write_index(host, WBSD_IDX_TAAC, 127);
else {
wbsd_write_index(host, WBSD_IDX_TAAC,
data->timeout_ns / 1000000);
}
if (data->timeout_clks > 255)
wbsd_write_index(host, WBSD_IDX_NSAC, 255);
else
wbsd_write_index(host, WBSD_IDX_NSAC, data->timeout_clks);
/*
* Inform the chip of how large blocks will be
* sent. It needs this to determine when to
* calculate CRC.
*
* Space for CRC must be included in the size.
* Two bytes are needed for each data line.
*/
if (host->bus_width == MMC_BUS_WIDTH_1) {
blksize = data->blksz + 2;
wbsd_write_index(host, WBSD_IDX_PBSMSB, (blksize >> 4) & 0xF0);
wbsd_write_index(host, WBSD_IDX_PBSLSB, blksize & 0xFF);
} else if (host->bus_width == MMC_BUS_WIDTH_4) {
blksize = data->blksz + 2 * 4;
wbsd_write_index(host, WBSD_IDX_PBSMSB,
((blksize >> 4) & 0xF0) | WBSD_DATA_WIDTH);
wbsd_write_index(host, WBSD_IDX_PBSLSB, blksize & 0xFF);
} else {
data->error = -EINVAL;
return;
}
/*
* Clear the FIFO. This is needed even for DMA
* transfers since the chip still uses the FIFO
* internally.
*/
setup = wbsd_read_index(host, WBSD_IDX_SETUP);
setup |= WBSD_FIFO_RESET;
wbsd_write_index(host, WBSD_IDX_SETUP, setup);
/*
* DMA transfer?
*/
if (host->dma >= 0) {
/*
* The buffer for DMA is only 64 kB.
*/
BUG_ON(size > 0x10000);
if (size > 0x10000) {
data->error = -EINVAL;
return;
}
/*
* Transfer data from the SG list to
* the DMA buffer.
*/
if (data->flags & MMC_DATA_WRITE)
wbsd_sg_to_dma(host, data);
/*
* Initialise the ISA DMA controller.
*/
dmaflags = claim_dma_lock();
disable_dma(host->dma);
clear_dma_ff(host->dma);
if (data->flags & MMC_DATA_READ)
set_dma_mode(host->dma, DMA_MODE_READ & ~0x40);
else
set_dma_mode(host->dma, DMA_MODE_WRITE & ~0x40);
set_dma_addr(host->dma, host->dma_addr);
set_dma_count(host->dma, size);
enable_dma(host->dma);
release_dma_lock(dmaflags);
/*
* Enable DMA on the host.
*/
wbsd_write_index(host, WBSD_IDX_DMA, WBSD_DMA_ENABLE);
} else {
/*
* This flag is used to keep printk
* output to a minimum.
*/
host->firsterr = 1;
/*
* Initialise the SG list.
*/
wbsd_init_sg(host, data);
/*
* Turn off DMA.
*/
wbsd_write_index(host, WBSD_IDX_DMA, 0);
/*
* Set up FIFO threshold levels (and fill
* buffer if doing a write).
*/
if (data->flags & MMC_DATA_READ) {
wbsd_write_index(host, WBSD_IDX_FIFOEN,
WBSD_FIFOEN_FULL | 8);
} else {
wbsd_write_index(host, WBSD_IDX_FIFOEN,
WBSD_FIFOEN_EMPTY | 8);
wbsd_fill_fifo(host);
}
}
data->error = 0;
}
static void wbsd_finish_data(struct wbsd_host *host, struct mmc_data *data)
{
unsigned long dmaflags;
int count;
u8 status;
WARN_ON(host->mrq == NULL);
/*
* Send a stop command if needed.
*/
if (data->stop)
wbsd_send_command(host, data->stop);
/*
* Wait for the controller to leave data
* transfer state.
*/
do {
status = wbsd_read_index(host, WBSD_IDX_STATUS);
} while (status & (WBSD_BLOCK_READ | WBSD_BLOCK_WRITE));
/*
* DMA transfer?
*/
if (host->dma >= 0) {
/*
* Disable DMA on the host.
*/
wbsd_write_index(host, WBSD_IDX_DMA, 0);
/*
* Turn of ISA DMA controller.
*/
dmaflags = claim_dma_lock();
disable_dma(host->dma);
clear_dma_ff(host->dma);
count = get_dma_residue(host->dma);
release_dma_lock(dmaflags);
data->bytes_xfered = host->mrq->data->blocks *
host->mrq->data->blksz - count;
data->bytes_xfered -= data->bytes_xfered % data->blksz;
/*
* Any leftover data?
*/
if (count) {
printk(KERN_ERR "%s: Incomplete DMA transfer. "
"%d bytes left.\n",
mmc_hostname(host->mmc), count);
if (!data->error)
data->error = -EIO;
} else {
/*
* Transfer data from DMA buffer to
* SG list.
*/
if (data->flags & MMC_DATA_READ)
wbsd_dma_to_sg(host, data);
}
if (data->error) {
if (data->bytes_xfered)
data->bytes_xfered -= data->blksz;
}
}
wbsd_request_end(host, host->mrq);
}
/*****************************************************************************\
* *
* MMC layer callbacks *
* *
\*****************************************************************************/
static void wbsd_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct wbsd_host *host = mmc_priv(mmc);
struct mmc_command *cmd;
/*
* Disable tasklets to avoid a deadlock.
*/
spin_lock_bh(&host->lock);
BUG_ON(host->mrq != NULL);
cmd = mrq->cmd;
host->mrq = mrq;
/*
* Check that there is actually a card in the slot.
*/
if (!(host->flags & WBSD_FCARD_PRESENT)) {
cmd->error = -ENOMEDIUM;
goto done;
}
if (cmd->data) {
/*
* The hardware is so delightfully stupid that it has a list
* of "data" commands. If a command isn't on this list, it'll
* just go back to the idle state and won't send any data
* interrupts.
*/
switch (cmd->opcode) {
case 11:
case 17:
case 18:
case 20:
case 24:
case 25:
case 26:
case 27:
case 30:
case 42:
case 56:
break;
/* ACMDs. We don't keep track of state, so we just treat them
* like any other command. */
case 51:
break;
default:
#ifdef CONFIG_MMC_DEBUG
printk(KERN_WARNING "%s: Data command %d is not "
"supported by this controller.\n",
mmc_hostname(host->mmc), cmd->opcode);
#endif
cmd->error = -EINVAL;
goto done;
};
}
/*
* Does the request include data?
*/
if (cmd->data) {
wbsd_prepare_data(host, cmd->data);
if (cmd->data->error)
goto done;
}
wbsd_send_command(host, cmd);
/*
* If this is a data transfer the request
* will be finished after the data has
* transferred.
*/
if (cmd->data && !cmd->error) {
/*
* Dirty fix for hardware bug.
*/
if (host->dma == -1)
tasklet_schedule(&host->fifo_tasklet);
spin_unlock_bh(&host->lock);
return;
}
done:
wbsd_request_end(host, mrq);
spin_unlock_bh(&host->lock);
}
static void wbsd_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct wbsd_host *host = mmc_priv(mmc);
u8 clk, setup, pwr;
spin_lock_bh(&host->lock);
/*
* Reset the chip on each power off.
* Should clear out any weird states.
*/
if (ios->power_mode == MMC_POWER_OFF)
wbsd_init_device(host);
if (ios->clock >= 24000000)
clk = WBSD_CLK_24M;
else if (ios->clock >= 16000000)
clk = WBSD_CLK_16M;
else if (ios->clock >= 12000000)
clk = WBSD_CLK_12M;
else
clk = WBSD_CLK_375K;
/*
* Only write to the clock register when
* there is an actual change.
*/
if (clk != host->clk) {
wbsd_write_index(host, WBSD_IDX_CLK, clk);
host->clk = clk;
}
/*
* Power up card.
*/
if (ios->power_mode != MMC_POWER_OFF) {
pwr = inb(host->base + WBSD_CSR);
pwr &= ~WBSD_POWER_N;
outb(pwr, host->base + WBSD_CSR);
}
/*
* MMC cards need to have pin 1 high during init.
* It wreaks havoc with the card detection though so
* that needs to be disabled.
*/
setup = wbsd_read_index(host, WBSD_IDX_SETUP);
if (ios->chip_select == MMC_CS_HIGH) {
BUG_ON(ios->bus_width != MMC_BUS_WIDTH_1);
setup |= WBSD_DAT3_H;
host->flags |= WBSD_FIGNORE_DETECT;
} else {
if (setup & WBSD_DAT3_H) {
setup &= ~WBSD_DAT3_H;
/*
* We cannot resume card detection immediately
* because of capacitance and delays in the chip.
*/
mod_timer(&host->ignore_timer, jiffies + HZ / 100);
}
}
wbsd_write_index(host, WBSD_IDX_SETUP, setup);
/*
* Store bus width for later. Will be used when
* setting up the data transfer.
*/
host->bus_width = ios->bus_width;
spin_unlock_bh(&host->lock);
}
static int wbsd_get_ro(struct mmc_host *mmc)
{
struct wbsd_host *host = mmc_priv(mmc);
u8 csr;
spin_lock_bh(&host->lock);
csr = inb(host->base + WBSD_CSR);
csr |= WBSD_MSLED;
outb(csr, host->base + WBSD_CSR);
mdelay(1);
csr = inb(host->base + WBSD_CSR);
csr &= ~WBSD_MSLED;
outb(csr, host->base + WBSD_CSR);
spin_unlock_bh(&host->lock);
return !!(csr & WBSD_WRPT);
}
static const struct mmc_host_ops wbsd_ops = {
.request = wbsd_request,
.set_ios = wbsd_set_ios,
.get_ro = wbsd_get_ro,
};
/*****************************************************************************\
* *
* Interrupt handling *
* *
\*****************************************************************************/
/*
* Helper function to reset detection ignore
*/
static void wbsd_reset_ignore(unsigned long data)
{
struct wbsd_host *host = (struct wbsd_host *)data;
BUG_ON(host == NULL);
DBG("Resetting card detection ignore\n");
spin_lock_bh(&host->lock);
host->flags &= ~WBSD_FIGNORE_DETECT;
/*
* Card status might have changed during the
* blackout.
*/
tasklet_schedule(&host->card_tasklet);
spin_unlock_bh(&host->lock);
}
/*
* Tasklets
*/
static inline struct mmc_data *wbsd_get_data(struct wbsd_host *host)
{
WARN_ON(!host->mrq);
if (!host->mrq)
return NULL;
WARN_ON(!host->mrq->cmd);
if (!host->mrq->cmd)
return NULL;
WARN_ON(!host->mrq->cmd->data);
if (!host->mrq->cmd->data)
return NULL;
return host->mrq->cmd->data;
}
static void wbsd_tasklet_card(unsigned long param)
{
struct wbsd_host *host = (struct wbsd_host *)param;
u8 csr;
int delay = -1;
spin_lock(&host->lock);
if (host->flags & WBSD_FIGNORE_DETECT) {
spin_unlock(&host->lock);
return;
}
csr = inb(host->base + WBSD_CSR);
WARN_ON(csr == 0xff);
if (csr & WBSD_CARDPRESENT) {
if (!(host->flags & WBSD_FCARD_PRESENT)) {
DBG("Card inserted\n");
host->flags |= WBSD_FCARD_PRESENT;
delay = 500;
}
} else if (host->flags & WBSD_FCARD_PRESENT) {
DBG("Card removed\n");
host->flags &= ~WBSD_FCARD_PRESENT;
if (host->mrq) {
printk(KERN_ERR "%s: Card removed during transfer!\n",
mmc_hostname(host->mmc));
wbsd_reset(host);
host->mrq->cmd->error = -ENOMEDIUM;
tasklet_schedule(&host->finish_tasklet);
}
delay = 0;
}
/*
* Unlock first since we might get a call back.
*/
spin_unlock(&host->lock);
if (delay != -1)
mmc_detect_change(host->mmc, msecs_to_jiffies(delay));
}
static void wbsd_tasklet_fifo(unsigned long param)
{
struct wbsd_host *host = (struct wbsd_host *)param;
struct mmc_data *data;
spin_lock(&host->lock);
if (!host->mrq)
goto end;
data = wbsd_get_data(host);
if (!data)
goto end;
if (data->flags & MMC_DATA_WRITE)
wbsd_fill_fifo(host);
else
wbsd_empty_fifo(host);
/*
* Done?
*/
if (host->num_sg == 0) {
wbsd_write_index(host, WBSD_IDX_FIFOEN, 0);
tasklet_schedule(&host->finish_tasklet);
}
end:
spin_unlock(&host->lock);
}
static void wbsd_tasklet_crc(unsigned long param)
{
struct wbsd_host *host = (struct wbsd_host *)param;
struct mmc_data *data;
spin_lock(&host->lock);
if (!host->mrq)
goto end;
data = wbsd_get_data(host);
if (!data)
goto end;
DBGF("CRC error\n");
data->error = -EILSEQ;
tasklet_schedule(&host->finish_tasklet);
end:
spin_unlock(&host->lock);
}
static void wbsd_tasklet_timeout(unsigned long param)
{
struct wbsd_host *host = (struct wbsd_host *)param;
struct mmc_data *data;
spin_lock(&host->lock);
if (!host->mrq)
goto end;
data = wbsd_get_data(host);
if (!data)
goto end;
DBGF("Timeout\n");
data->error = -ETIMEDOUT;
tasklet_schedule(&host->finish_tasklet);
end:
spin_unlock(&host->lock);
}
static void wbsd_tasklet_finish(unsigned long param)
{
struct wbsd_host *host = (struct wbsd_host *)param;
struct mmc_data *data;
spin_lock(&host->lock);
WARN_ON(!host->mrq);
if (!host->mrq)
goto end;
data = wbsd_get_data(host);
if (!data)
goto end;
wbsd_finish_data(host, data);
end:
spin_unlock(&host->lock);
}
/*
* Interrupt handling
*/
static irqreturn_t wbsd_irq(int irq, void *dev_id)
{
struct wbsd_host *host = dev_id;
int isr;
isr = inb(host->base + WBSD_ISR);
/*
* Was it actually our hardware that caused the interrupt?
*/
if (isr == 0xff || isr == 0x00)
return IRQ_NONE;
host->isr |= isr;
/*
* Schedule tasklets as needed.
*/
if (isr & WBSD_INT_CARD)
tasklet_schedule(&host->card_tasklet);
if (isr & WBSD_INT_FIFO_THRE)
tasklet_schedule(&host->fifo_tasklet);
if (isr & WBSD_INT_CRC)
tasklet_hi_schedule(&host->crc_tasklet);
if (isr & WBSD_INT_TIMEOUT)
tasklet_hi_schedule(&host->timeout_tasklet);
if (isr & WBSD_INT_TC)
tasklet_schedule(&host->finish_tasklet);
return IRQ_HANDLED;
}
/*****************************************************************************\
* *
* Device initialisation and shutdown *
* *
\*****************************************************************************/
/*
* Allocate/free MMC structure.
*/
static int __devinit wbsd_alloc_mmc(struct device *dev)
{
struct mmc_host *mmc;
struct wbsd_host *host;
/*
* Allocate MMC structure.
*/
mmc = mmc_alloc_host(sizeof(struct wbsd_host), dev);
if (!mmc)
return -ENOMEM;
host = mmc_priv(mmc);
host->mmc = mmc;
host->dma = -1;
/*
* Set host parameters.
*/
mmc->ops = &wbsd_ops;
mmc->f_min = 375000;
mmc->f_max = 24000000;
mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34;
mmc->caps = MMC_CAP_4_BIT_DATA;
spin_lock_init(&host->lock);
/*
* Set up timers
*/
init_timer(&host->ignore_timer);
host->ignore_timer.data = (unsigned long)host;
host->ignore_timer.function = wbsd_reset_ignore;
/*
* Maximum number of segments. Worst case is one sector per segment
* so this will be 64kB/512.
*/
mmc->max_segs = 128;
/*
* Maximum request size. Also limited by 64KiB buffer.
*/
mmc->max_req_size = 65536;
/*
* Maximum segment size. Could be one segment with the maximum number
* of bytes.
*/
mmc->max_seg_size = mmc->max_req_size;
/*
* Maximum block size. We have 12 bits (= 4095) but have to subtract
* space for CRC. So the maximum is 4095 - 4*2 = 4087.
*/
mmc->max_blk_size = 4087;
/*
* Maximum block count. There is no real limit so the maximum
* request size will be the only restriction.
*/
mmc->max_blk_count = mmc->max_req_size;
dev_set_drvdata(dev, mmc);
return 0;
}
static void wbsd_free_mmc(struct device *dev)
{
struct mmc_host *mmc;
struct wbsd_host *host;
mmc = dev_get_drvdata(dev);
if (!mmc)
return;
host = mmc_priv(mmc);
BUG_ON(host == NULL);
del_timer_sync(&host->ignore_timer);
mmc_free_host(mmc);
dev_set_drvdata(dev, NULL);
}
/*
* Scan for known chip id:s
*/
static int __devinit wbsd_scan(struct wbsd_host *host)
{
int i, j, k;
int id;
/*
* Iterate through all ports, all codes to
* find hardware that is in our known list.
*/
for (i = 0; i < ARRAY_SIZE(config_ports); i++) {
if (!request_region(config_ports[i], 2, DRIVER_NAME))
continue;
for (j = 0; j < ARRAY_SIZE(unlock_codes); j++) {
id = 0xFFFF;
host->config = config_ports[i];
host->unlock_code = unlock_codes[j];
wbsd_unlock_config(host);
outb(WBSD_CONF_ID_HI, config_ports[i]);
id = inb(config_ports[i] + 1) << 8;
outb(WBSD_CONF_ID_LO, config_ports[i]);
id |= inb(config_ports[i] + 1);
wbsd_lock_config(host);
for (k = 0; k < ARRAY_SIZE(valid_ids); k++) {
if (id == valid_ids[k]) {
host->chip_id = id;
return 0;
}
}
if (id != 0xFFFF) {
DBG("Unknown hardware (id %x) found at %x\n",
id, config_ports[i]);
}
}
release_region(config_ports[i], 2);
}
host->config = 0;
host->unlock_code = 0;
return -ENODEV;
}
/*
* Allocate/free io port ranges
*/
static int __devinit wbsd_request_region(struct wbsd_host *host, int base)
{
if (base & 0x7)
return -EINVAL;
if (!request_region(base, 8, DRIVER_NAME))
return -EIO;
host->base = base;
return 0;
}
static void wbsd_release_regions(struct wbsd_host *host)
{
if (host->base)
release_region(host->base, 8);
host->base = 0;
if (host->config)
release_region(host->config, 2);
host->config = 0;
}
/*
* Allocate/free DMA port and buffer
*/
static void __devinit wbsd_request_dma(struct wbsd_host *host, int dma)
{
if (dma < 0)
return;
if (request_dma(dma, DRIVER_NAME))
goto err;
/*
* We need to allocate a special buffer in
* order for ISA to be able to DMA to it.
*/
host->dma_buffer = kmalloc(WBSD_DMA_SIZE,
GFP_NOIO | GFP_DMA | __GFP_REPEAT | __GFP_NOWARN);
if (!host->dma_buffer)
goto free;
/*
* Translate the address to a physical address.
*/
host->dma_addr = dma_map_single(mmc_dev(host->mmc), host->dma_buffer,
WBSD_DMA_SIZE, DMA_BIDIRECTIONAL);
/*
* ISA DMA must be aligned on a 64k basis.
*/
if ((host->dma_addr & 0xffff) != 0)
goto kfree;
/*
* ISA cannot access memory above 16 MB.
*/
else if (host->dma_addr >= 0x1000000)
goto kfree;
host->dma = dma;
return;
kfree:
/*
* If we've gotten here then there is some kind of alignment bug
*/
BUG_ON(1);
dma_unmap_single(mmc_dev(host->mmc), host->dma_addr,
WBSD_DMA_SIZE, DMA_BIDIRECTIONAL);
host->dma_addr = 0;
kfree(host->dma_buffer);
host->dma_buffer = NULL;
free:
free_dma(dma);
err:
printk(KERN_WARNING DRIVER_NAME ": Unable to allocate DMA %d. "
"Falling back on FIFO.\n", dma);
}
static void wbsd_release_dma(struct wbsd_host *host)
{
if (host->dma_addr) {
dma_unmap_single(mmc_dev(host->mmc), host->dma_addr,
WBSD_DMA_SIZE, DMA_BIDIRECTIONAL);
}
kfree(host->dma_buffer);
if (host->dma >= 0)
free_dma(host->dma);
host->dma = -1;
host->dma_buffer = NULL;
host->dma_addr = 0;
}
/*
* Allocate/free IRQ.
*/
static int __devinit wbsd_request_irq(struct wbsd_host *host, int irq)
{
int ret;
/*
* Set up tasklets. Must be done before requesting interrupt.
*/
tasklet_init(&host->card_tasklet, wbsd_tasklet_card,
(unsigned long)host);
tasklet_init(&host->fifo_tasklet, wbsd_tasklet_fifo,
(unsigned long)host);
tasklet_init(&host->crc_tasklet, wbsd_tasklet_crc,
(unsigned long)host);
tasklet_init(&host->timeout_tasklet, wbsd_tasklet_timeout,
(unsigned long)host);
tasklet_init(&host->finish_tasklet, wbsd_tasklet_finish,
(unsigned long)host);
/*
* Allocate interrupt.
*/
ret = request_irq(irq, wbsd_irq, IRQF_SHARED, DRIVER_NAME, host);
if (ret)
return ret;
host->irq = irq;
return 0;
}
static void wbsd_release_irq(struct wbsd_host *host)
{
if (!host->irq)
return;
free_irq(host->irq, host);
host->irq = 0;
tasklet_kill(&host->card_tasklet);
tasklet_kill(&host->fifo_tasklet);
tasklet_kill(&host->crc_tasklet);
tasklet_kill(&host->timeout_tasklet);
tasklet_kill(&host->finish_tasklet);
}
/*
* Allocate all resources for the host.
*/
static int __devinit wbsd_request_resources(struct wbsd_host *host,
int base, int irq, int dma)
{
int ret;
/*
* Allocate I/O ports.
*/
ret = wbsd_request_region(host, base);
if (ret)
return ret;
/*
* Allocate interrupt.
*/
ret = wbsd_request_irq(host, irq);
if (ret)
return ret;
/*
* Allocate DMA.
*/
wbsd_request_dma(host, dma);
return 0;
}
/*
* Release all resources for the host.
*/
static void wbsd_release_resources(struct wbsd_host *host)
{
wbsd_release_dma(host);
wbsd_release_irq(host);
wbsd_release_regions(host);
}
/*
* Configure the resources the chip should use.
*/
static void wbsd_chip_config(struct wbsd_host *host)
{
wbsd_unlock_config(host);
/*
* Reset the chip.
*/
wbsd_write_config(host, WBSD_CONF_SWRST, 1);
wbsd_write_config(host, WBSD_CONF_SWRST, 0);
/*
* Select SD/MMC function.
*/
wbsd_write_config(host, WBSD_CONF_DEVICE, DEVICE_SD);
/*
* Set up card detection.
*/
wbsd_write_config(host, WBSD_CONF_PINS, WBSD_PINS_DETECT_GP11);
/*
* Configure chip
*/
wbsd_write_config(host, WBSD_CONF_PORT_HI, host->base >> 8);
wbsd_write_config(host, WBSD_CONF_PORT_LO, host->base & 0xff);
wbsd_write_config(host, WBSD_CONF_IRQ, host->irq);
if (host->dma >= 0)
wbsd_write_config(host, WBSD_CONF_DRQ, host->dma);
/*
* Enable and power up chip.
*/
wbsd_write_config(host, WBSD_CONF_ENABLE, 1);
wbsd_write_config(host, WBSD_CONF_POWER, 0x20);
wbsd_lock_config(host);
}
/*
* Check that configured resources are correct.
*/
static int wbsd_chip_validate(struct wbsd_host *host)
{
int base, irq, dma;
wbsd_unlock_config(host);
/*
* Select SD/MMC function.
*/
wbsd_write_config(host, WBSD_CONF_DEVICE, DEVICE_SD);
/*
* Read configuration.
*/
base = wbsd_read_config(host, WBSD_CONF_PORT_HI) << 8;
base |= wbsd_read_config(host, WBSD_CONF_PORT_LO);
irq = wbsd_read_config(host, WBSD_CONF_IRQ);
dma = wbsd_read_config(host, WBSD_CONF_DRQ);
wbsd_lock_config(host);
/*
* Validate against given configuration.
*/
if (base != host->base)
return 0;
if (irq != host->irq)
return 0;
if ((dma != host->dma) && (host->dma != -1))
return 0;
return 1;
}
/*
* Powers down the SD function
*/
static void wbsd_chip_poweroff(struct wbsd_host *host)
{
wbsd_unlock_config(host);
wbsd_write_config(host, WBSD_CONF_DEVICE, DEVICE_SD);
wbsd_write_config(host, WBSD_CONF_ENABLE, 0);
wbsd_lock_config(host);
}
/*****************************************************************************\
* *
* Devices setup and shutdown *
* *
\*****************************************************************************/
static int __devinit wbsd_init(struct device *dev, int base, int irq, int dma,
int pnp)
{
struct wbsd_host *host = NULL;
struct mmc_host *mmc = NULL;
int ret;
ret = wbsd_alloc_mmc(dev);
if (ret)
return ret;
mmc = dev_get_drvdata(dev);
host = mmc_priv(mmc);
/*
* Scan for hardware.
*/
ret = wbsd_scan(host);
if (ret) {
if (pnp && (ret == -ENODEV)) {
printk(KERN_WARNING DRIVER_NAME
": Unable to confirm device presence. You may "
"experience lock-ups.\n");
} else {
wbsd_free_mmc(dev);
return ret;
}
}
/*
* Request resources.
*/
ret = wbsd_request_resources(host, base, irq, dma);
if (ret) {
wbsd_release_resources(host);
wbsd_free_mmc(dev);
return ret;
}
/*
* See if chip needs to be configured.
*/
if (pnp) {
if ((host->config != 0) && !wbsd_chip_validate(host)) {
printk(KERN_WARNING DRIVER_NAME
": PnP active but chip not configured! "
"You probably have a buggy BIOS. "
"Configuring chip manually.\n");
wbsd_chip_config(host);
}
} else
wbsd_chip_config(host);
/*
* Power Management stuff. No idea how this works.
* Not tested.
*/
#ifdef CONFIG_PM
if (host->config) {
wbsd_unlock_config(host);
wbsd_write_config(host, WBSD_CONF_PME, 0xA0);
wbsd_lock_config(host);
}
#endif
/*
* Allow device to initialise itself properly.
*/
mdelay(5);
/*
* Reset the chip into a known state.
*/
wbsd_init_device(host);
mmc_add_host(mmc);
printk(KERN_INFO "%s: W83L51xD", mmc_hostname(mmc));
if (host->chip_id != 0)
printk(" id %x", (int)host->chip_id);
printk(" at 0x%x irq %d", (int)host->base, (int)host->irq);
if (host->dma >= 0)
printk(" dma %d", (int)host->dma);
else
printk(" FIFO");
if (pnp)
printk(" PnP");
printk("\n");
return 0;
}
static void __devexit wbsd_shutdown(struct device *dev, int pnp)
{
struct mmc_host *mmc = dev_get_drvdata(dev);
struct wbsd_host *host;
if (!mmc)
return;
host = mmc_priv(mmc);
mmc_remove_host(mmc);
/*
* Power down the SD/MMC function.
*/
if (!pnp)
wbsd_chip_poweroff(host);
wbsd_release_resources(host);
wbsd_free_mmc(dev);
}
/*
* Non-PnP
*/
static int __devinit wbsd_probe(struct platform_device *dev)
{
/* Use the module parameters for resources */
return wbsd_init(&dev->dev, param_io, param_irq, param_dma, 0);
}
static int __devexit wbsd_remove(struct platform_device *dev)
{
wbsd_shutdown(&dev->dev, 0);
return 0;
}
/*
* PnP
*/
#ifdef CONFIG_PNP
static int __devinit
wbsd_pnp_probe(struct pnp_dev *pnpdev, const struct pnp_device_id *dev_id)
{
int io, irq, dma;
/*
* Get resources from PnP layer.
*/
io = pnp_port_start(pnpdev, 0);
irq = pnp_irq(pnpdev, 0);
if (pnp_dma_valid(pnpdev, 0))
dma = pnp_dma(pnpdev, 0);
else
dma = -1;
DBGF("PnP resources: port %3x irq %d dma %d\n", io, irq, dma);
return wbsd_init(&pnpdev->dev, io, irq, dma, 1);
}
static void __devexit wbsd_pnp_remove(struct pnp_dev *dev)
{
wbsd_shutdown(&dev->dev, 1);
}
#endif /* CONFIG_PNP */
/*
* Power management
*/
#ifdef CONFIG_PM
static int wbsd_suspend(struct wbsd_host *host, pm_message_t state)
{
BUG_ON(host == NULL);
return mmc_suspend_host(host->mmc);
}
static int wbsd_resume(struct wbsd_host *host)
{
BUG_ON(host == NULL);
wbsd_init_device(host);
return mmc_resume_host(host->mmc);
}
static int wbsd_platform_suspend(struct platform_device *dev,
pm_message_t state)
{
struct mmc_host *mmc = platform_get_drvdata(dev);
struct wbsd_host *host;
int ret;
if (mmc == NULL)
return 0;
DBGF("Suspending...\n");
host = mmc_priv(mmc);
ret = wbsd_suspend(host, state);
if (ret)
return ret;
wbsd_chip_poweroff(host);
return 0;
}
static int wbsd_platform_resume(struct platform_device *dev)
{
struct mmc_host *mmc = platform_get_drvdata(dev);
struct wbsd_host *host;
if (mmc == NULL)
return 0;
DBGF("Resuming...\n");
host = mmc_priv(mmc);
wbsd_chip_config(host);
/*
* Allow device to initialise itself properly.
*/
mdelay(5);
return wbsd_resume(host);
}
#ifdef CONFIG_PNP
static int wbsd_pnp_suspend(struct pnp_dev *pnp_dev, pm_message_t state)
{
struct mmc_host *mmc = dev_get_drvdata(&pnp_dev->dev);
struct wbsd_host *host;
if (mmc == NULL)
return 0;
DBGF("Suspending...\n");
host = mmc_priv(mmc);
return wbsd_suspend(host, state);
}
static int wbsd_pnp_resume(struct pnp_dev *pnp_dev)
{
struct mmc_host *mmc = dev_get_drvdata(&pnp_dev->dev);
struct wbsd_host *host;
if (mmc == NULL)
return 0;
DBGF("Resuming...\n");
host = mmc_priv(mmc);
/*
* See if chip needs to be configured.
*/
if (host->config != 0) {
if (!wbsd_chip_validate(host)) {
printk(KERN_WARNING DRIVER_NAME
": PnP active but chip not configured! "
"You probably have a buggy BIOS. "
"Configuring chip manually.\n");
wbsd_chip_config(host);
}
}
/*
* Allow device to initialise itself properly.
*/
mdelay(5);
return wbsd_resume(host);
}
#endif /* CONFIG_PNP */
#else /* CONFIG_PM */
#define wbsd_platform_suspend NULL
#define wbsd_platform_resume NULL
#define wbsd_pnp_suspend NULL
#define wbsd_pnp_resume NULL
#endif /* CONFIG_PM */
static struct platform_device *wbsd_device;
static struct platform_driver wbsd_driver = {
.probe = wbsd_probe,
.remove = __devexit_p(wbsd_remove),
.suspend = wbsd_platform_suspend,
.resume = wbsd_platform_resume,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
};
#ifdef CONFIG_PNP
static struct pnp_driver wbsd_pnp_driver = {
.name = DRIVER_NAME,
.id_table = pnp_dev_table,
.probe = wbsd_pnp_probe,
.remove = __devexit_p(wbsd_pnp_remove),
.suspend = wbsd_pnp_suspend,
.resume = wbsd_pnp_resume,
};
#endif /* CONFIG_PNP */
/*
* Module loading/unloading
*/
static int __init wbsd_drv_init(void)
{
int result;
printk(KERN_INFO DRIVER_NAME
": Winbond W83L51xD SD/MMC card interface driver\n");
printk(KERN_INFO DRIVER_NAME ": Copyright(c) Pierre Ossman\n");
#ifdef CONFIG_PNP
if (!param_nopnp) {
result = pnp_register_driver(&wbsd_pnp_driver);
if (result < 0)
return result;
}
#endif /* CONFIG_PNP */
if (param_nopnp) {
result = platform_driver_register(&wbsd_driver);
if (result < 0)
return result;
wbsd_device = platform_device_alloc(DRIVER_NAME, -1);
if (!wbsd_device) {
platform_driver_unregister(&wbsd_driver);
return -ENOMEM;
}
result = platform_device_add(wbsd_device);
if (result) {
platform_device_put(wbsd_device);
platform_driver_unregister(&wbsd_driver);
return result;
}
}
return 0;
}
static void __exit wbsd_drv_exit(void)
{
#ifdef CONFIG_PNP
if (!param_nopnp)
pnp_unregister_driver(&wbsd_pnp_driver);
#endif /* CONFIG_PNP */
if (param_nopnp) {
platform_device_unregister(wbsd_device);
platform_driver_unregister(&wbsd_driver);
}
DBG("unloaded\n");
}
module_init(wbsd_drv_init);
module_exit(wbsd_drv_exit);
#ifdef CONFIG_PNP
module_param_named(nopnp, param_nopnp, uint, 0444);
#endif
module_param_named(io, param_io, uint, 0444);
module_param_named(irq, param_irq, uint, 0444);
module_param_named(dma, param_dma, int, 0444);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Pierre Ossman <pierre@ossman.eu>");
MODULE_DESCRIPTION("Winbond W83L51xD SD/MMC card interface driver");
#ifdef CONFIG_PNP
MODULE_PARM_DESC(nopnp, "Scan for device instead of relying on PNP. (default 0)");
#endif
MODULE_PARM_DESC(io, "I/O base to allocate. Must be 8 byte aligned. (default 0x248)");
MODULE_PARM_DESC(irq, "IRQ to allocate. (default 6)");
MODULE_PARM_DESC(dma, "DMA channel to allocate. -1 for no DMA. (default 2)");
| gpl-2.0 |
engine95/navelA-990 | drivers/net/wireless/mwifiex/join.c | 3328 | 44107 | /*
* Marvell Wireless LAN device driver: association and ad-hoc start/join
*
* Copyright (C) 2011, 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 "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "wmm.h"
#include "11n.h"
#define CAPINFO_MASK (~(BIT(15) | BIT(14) | BIT(12) | BIT(11) | BIT(9)))
/*
* Append a generic IE as a pass through TLV to a TLV buffer.
*
* This function is called from the network join command preparation routine.
*
* If the IE buffer has been setup by the application, this routine appends
* the buffer as a pass through TLV type to the request.
*/
static int
mwifiex_cmd_append_generic_ie(struct mwifiex_private *priv, u8 **buffer)
{
int ret_len = 0;
struct mwifiex_ie_types_header ie_header;
/* Null Checks */
if (!buffer)
return 0;
if (!(*buffer))
return 0;
/*
* If there is a generic ie buffer setup, append it to the return
* parameter buffer pointer.
*/
if (priv->gen_ie_buf_len) {
dev_dbg(priv->adapter->dev,
"info: %s: append generic ie len %d to %p\n",
__func__, priv->gen_ie_buf_len, *buffer);
/* Wrap the generic IE buffer with a pass through TLV type */
ie_header.type = cpu_to_le16(TLV_TYPE_PASSTHROUGH);
ie_header.len = cpu_to_le16(priv->gen_ie_buf_len);
memcpy(*buffer, &ie_header, sizeof(ie_header));
/* Increment the return size and the return buffer pointer
param */
*buffer += sizeof(ie_header);
ret_len += sizeof(ie_header);
/* Copy the generic IE buffer to the output buffer, advance
pointer */
memcpy(*buffer, priv->gen_ie_buf, priv->gen_ie_buf_len);
/* Increment the return size and the return buffer pointer
param */
*buffer += priv->gen_ie_buf_len;
ret_len += priv->gen_ie_buf_len;
/* Reset the generic IE buffer */
priv->gen_ie_buf_len = 0;
}
/* return the length appended to the buffer */
return ret_len;
}
/*
* Append TSF tracking info from the scan table for the target AP.
*
* This function is called from the network join command preparation routine.
*
* The TSF table TSF sent to the firmware contains two TSF values:
* - The TSF of the target AP from its previous beacon/probe response
* - The TSF timestamp of our local MAC at the time we observed the
* beacon/probe response.
*
* The firmware uses the timestamp values to set an initial TSF value
* in the MAC for the new association after a reassociation attempt.
*/
static int
mwifiex_cmd_append_tsf_tlv(struct mwifiex_private *priv, u8 **buffer,
struct mwifiex_bssdescriptor *bss_desc)
{
struct mwifiex_ie_types_tsf_timestamp tsf_tlv;
__le64 tsf_val;
/* Null Checks */
if (buffer == NULL)
return 0;
if (*buffer == NULL)
return 0;
memset(&tsf_tlv, 0x00, sizeof(struct mwifiex_ie_types_tsf_timestamp));
tsf_tlv.header.type = cpu_to_le16(TLV_TYPE_TSFTIMESTAMP);
tsf_tlv.header.len = cpu_to_le16(2 * sizeof(tsf_val));
memcpy(*buffer, &tsf_tlv, sizeof(tsf_tlv.header));
*buffer += sizeof(tsf_tlv.header);
/* TSF at the time when beacon/probe_response was received */
tsf_val = cpu_to_le64(bss_desc->network_tsf);
memcpy(*buffer, &tsf_val, sizeof(tsf_val));
*buffer += sizeof(tsf_val);
memcpy(&tsf_val, bss_desc->time_stamp, sizeof(tsf_val));
dev_dbg(priv->adapter->dev,
"info: %s: TSF offset calc: %016llx - %016llx\n",
__func__, tsf_val, bss_desc->network_tsf);
memcpy(*buffer, &tsf_val, sizeof(tsf_val));
*buffer += sizeof(tsf_val);
return sizeof(tsf_tlv.header) + (2 * sizeof(tsf_val));
}
/*
* This function finds out the common rates between rate1 and rate2.
*
* It will fill common rates in rate1 as output if found.
*
* NOTE: Setting the MSB of the basic rates needs to be taken
* care of, either before or after calling this function.
*/
static int mwifiex_get_common_rates(struct mwifiex_private *priv, u8 *rate1,
u32 rate1_size, u8 *rate2, u32 rate2_size)
{
int ret;
u8 *ptr = rate1, *tmp;
u32 i, j;
tmp = kmemdup(rate1, rate1_size, GFP_KERNEL);
if (!tmp) {
dev_err(priv->adapter->dev, "failed to alloc tmp buf\n");
return -ENOMEM;
}
memset(rate1, 0, rate1_size);
for (i = 0; rate2[i] && i < rate2_size; i++) {
for (j = 0; tmp[j] && j < rate1_size; j++) {
/* Check common rate, excluding the bit for
basic rate */
if ((rate2[i] & 0x7F) == (tmp[j] & 0x7F)) {
*rate1++ = tmp[j];
break;
}
}
}
dev_dbg(priv->adapter->dev, "info: Tx data rate set to %#x\n",
priv->data_rate);
if (!priv->is_data_rate_auto) {
while (*ptr) {
if ((*ptr & 0x7f) == priv->data_rate) {
ret = 0;
goto done;
}
ptr++;
}
dev_err(priv->adapter->dev, "previously set fixed data rate %#x"
" is not compatible with the network\n",
priv->data_rate);
ret = -1;
goto done;
}
ret = 0;
done:
kfree(tmp);
return ret;
}
/*
* This function creates the intersection of the rates supported by a
* target BSS and our adapter settings for use in an assoc/join command.
*/
static int
mwifiex_setup_rates_from_bssdesc(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc,
u8 *out_rates, u32 *out_rates_size)
{
u8 card_rates[MWIFIEX_SUPPORTED_RATES];
u32 card_rates_size;
/* Copy AP supported rates */
memcpy(out_rates, bss_desc->supported_rates, MWIFIEX_SUPPORTED_RATES);
/* Get the STA supported rates */
card_rates_size = mwifiex_get_active_data_rates(priv, card_rates);
/* Get the common rates between AP and STA supported rates */
if (mwifiex_get_common_rates(priv, out_rates, MWIFIEX_SUPPORTED_RATES,
card_rates, card_rates_size)) {
*out_rates_size = 0;
dev_err(priv->adapter->dev, "%s: cannot get common rates\n",
__func__);
return -1;
}
*out_rates_size =
min_t(size_t, strlen(out_rates), MWIFIEX_SUPPORTED_RATES);
return 0;
}
/*
* This function appends a WAPI IE.
*
* This function is called from the network join command preparation routine.
*
* If the IE buffer has been setup by the application, this routine appends
* the buffer as a WAPI TLV type to the request.
*/
static int
mwifiex_cmd_append_wapi_ie(struct mwifiex_private *priv, u8 **buffer)
{
int retLen = 0;
struct mwifiex_ie_types_header ie_header;
/* Null Checks */
if (buffer == NULL)
return 0;
if (*buffer == NULL)
return 0;
/*
* If there is a wapi ie buffer setup, append it to the return
* parameter buffer pointer.
*/
if (priv->wapi_ie_len) {
dev_dbg(priv->adapter->dev, "cmd: append wapi ie %d to %p\n",
priv->wapi_ie_len, *buffer);
/* Wrap the generic IE buffer with a pass through TLV type */
ie_header.type = cpu_to_le16(TLV_TYPE_WAPI_IE);
ie_header.len = cpu_to_le16(priv->wapi_ie_len);
memcpy(*buffer, &ie_header, sizeof(ie_header));
/* Increment the return size and the return buffer pointer
param */
*buffer += sizeof(ie_header);
retLen += sizeof(ie_header);
/* Copy the wapi IE buffer to the output buffer, advance
pointer */
memcpy(*buffer, priv->wapi_ie, priv->wapi_ie_len);
/* Increment the return size and the return buffer pointer
param */
*buffer += priv->wapi_ie_len;
retLen += priv->wapi_ie_len;
}
/* return the length appended to the buffer */
return retLen;
}
/*
* This function appends rsn ie tlv for wpa/wpa2 security modes.
* It is called from the network join command preparation routine.
*/
static int mwifiex_append_rsn_ie_wpa_wpa2(struct mwifiex_private *priv,
u8 **buffer)
{
struct mwifiex_ie_types_rsn_param_set *rsn_ie_tlv;
int rsn_ie_len;
if (!buffer || !(*buffer))
return 0;
rsn_ie_tlv = (struct mwifiex_ie_types_rsn_param_set *) (*buffer);
rsn_ie_tlv->header.type = cpu_to_le16((u16) priv->wpa_ie[0]);
rsn_ie_tlv->header.type = cpu_to_le16(
le16_to_cpu(rsn_ie_tlv->header.type) & 0x00FF);
rsn_ie_tlv->header.len = cpu_to_le16((u16) priv->wpa_ie[1]);
rsn_ie_tlv->header.len = cpu_to_le16(le16_to_cpu(rsn_ie_tlv->header.len)
& 0x00FF);
if (le16_to_cpu(rsn_ie_tlv->header.len) <= (sizeof(priv->wpa_ie) - 2))
memcpy(rsn_ie_tlv->rsn_ie, &priv->wpa_ie[2],
le16_to_cpu(rsn_ie_tlv->header.len));
else
return -1;
rsn_ie_len = sizeof(rsn_ie_tlv->header) +
le16_to_cpu(rsn_ie_tlv->header.len);
*buffer += rsn_ie_len;
return rsn_ie_len;
}
/*
* This function prepares command for association.
*
* This sets the following parameters -
* - Peer MAC address
* - Listen interval
* - Beacon interval
* - Capability information
*
* ...and the following TLVs, as required -
* - SSID TLV
* - PHY TLV
* - SS TLV
* - Rates TLV
* - Authentication TLV
* - Channel TLV
* - WPA/WPA2 IE
* - 11n TLV
* - Vendor specific TLV
* - WMM TLV
* - WAPI IE
* - Generic IE
* - TSF TLV
*
* Preparation also includes -
* - Setting command ID and proper size
* - Ensuring correct endian-ness
*/
int mwifiex_cmd_802_11_associate(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd,
struct mwifiex_bssdescriptor *bss_desc)
{
struct host_cmd_ds_802_11_associate *assoc = &cmd->params.associate;
struct mwifiex_ie_types_ssid_param_set *ssid_tlv;
struct mwifiex_ie_types_phy_param_set *phy_tlv;
struct mwifiex_ie_types_ss_param_set *ss_tlv;
struct mwifiex_ie_types_rates_param_set *rates_tlv;
struct mwifiex_ie_types_auth_type *auth_tlv;
struct mwifiex_ie_types_chan_list_param_set *chan_tlv;
u8 rates[MWIFIEX_SUPPORTED_RATES];
u32 rates_size;
u16 tmp_cap;
u8 *pos;
int rsn_ie_len = 0;
pos = (u8 *) assoc;
mwifiex_cfg_tx_buf(priv, bss_desc);
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_ASSOCIATE);
/* Save so we know which BSS Desc to use in the response handler */
priv->attempted_bss_desc = bss_desc;
memcpy(assoc->peer_sta_addr,
bss_desc->mac_address, sizeof(assoc->peer_sta_addr));
pos += sizeof(assoc->peer_sta_addr);
/* Set the listen interval */
assoc->listen_interval = cpu_to_le16(priv->listen_interval);
/* Set the beacon period */
assoc->beacon_period = cpu_to_le16(bss_desc->beacon_period);
pos += sizeof(assoc->cap_info_bitmap);
pos += sizeof(assoc->listen_interval);
pos += sizeof(assoc->beacon_period);
pos += sizeof(assoc->dtim_period);
ssid_tlv = (struct mwifiex_ie_types_ssid_param_set *) pos;
ssid_tlv->header.type = cpu_to_le16(WLAN_EID_SSID);
ssid_tlv->header.len = cpu_to_le16((u16) bss_desc->ssid.ssid_len);
memcpy(ssid_tlv->ssid, bss_desc->ssid.ssid,
le16_to_cpu(ssid_tlv->header.len));
pos += sizeof(ssid_tlv->header) + le16_to_cpu(ssid_tlv->header.len);
phy_tlv = (struct mwifiex_ie_types_phy_param_set *) pos;
phy_tlv->header.type = cpu_to_le16(WLAN_EID_DS_PARAMS);
phy_tlv->header.len = cpu_to_le16(sizeof(phy_tlv->fh_ds.ds_param_set));
memcpy(&phy_tlv->fh_ds.ds_param_set,
&bss_desc->phy_param_set.ds_param_set.current_chan,
sizeof(phy_tlv->fh_ds.ds_param_set));
pos += sizeof(phy_tlv->header) + le16_to_cpu(phy_tlv->header.len);
ss_tlv = (struct mwifiex_ie_types_ss_param_set *) pos;
ss_tlv->header.type = cpu_to_le16(WLAN_EID_CF_PARAMS);
ss_tlv->header.len = cpu_to_le16(sizeof(ss_tlv->cf_ibss.cf_param_set));
pos += sizeof(ss_tlv->header) + le16_to_cpu(ss_tlv->header.len);
/* Get the common rates supported between the driver and the BSS Desc */
if (mwifiex_setup_rates_from_bssdesc
(priv, bss_desc, rates, &rates_size))
return -1;
/* Save the data rates into Current BSS state structure */
priv->curr_bss_params.num_of_rates = rates_size;
memcpy(&priv->curr_bss_params.data_rates, rates, rates_size);
/* Setup the Rates TLV in the association command */
rates_tlv = (struct mwifiex_ie_types_rates_param_set *) pos;
rates_tlv->header.type = cpu_to_le16(WLAN_EID_SUPP_RATES);
rates_tlv->header.len = cpu_to_le16((u16) rates_size);
memcpy(rates_tlv->rates, rates, rates_size);
pos += sizeof(rates_tlv->header) + rates_size;
dev_dbg(priv->adapter->dev, "info: ASSOC_CMD: rates size = %d\n",
rates_size);
/* Add the Authentication type to be used for Auth frames */
auth_tlv = (struct mwifiex_ie_types_auth_type *) pos;
auth_tlv->header.type = cpu_to_le16(TLV_TYPE_AUTH_TYPE);
auth_tlv->header.len = cpu_to_le16(sizeof(auth_tlv->auth_type));
if (priv->sec_info.wep_enabled)
auth_tlv->auth_type = cpu_to_le16(
(u16) priv->sec_info.authentication_mode);
else
auth_tlv->auth_type = cpu_to_le16(NL80211_AUTHTYPE_OPEN_SYSTEM);
pos += sizeof(auth_tlv->header) + le16_to_cpu(auth_tlv->header.len);
if (IS_SUPPORT_MULTI_BANDS(priv->adapter) &&
!(ISSUPP_11NENABLED(priv->adapter->fw_cap_info) &&
(!bss_desc->disable_11n) &&
(priv->adapter->config_bands & BAND_GN ||
priv->adapter->config_bands & BAND_AN) &&
(bss_desc->bcn_ht_cap)
)
) {
/* Append a channel TLV for the channel the attempted AP was
found on */
chan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos;
chan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
chan_tlv->header.len =
cpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set));
memset(chan_tlv->chan_scan_param, 0x00,
sizeof(struct mwifiex_chan_scan_param_set));
chan_tlv->chan_scan_param[0].chan_number =
(bss_desc->phy_param_set.ds_param_set.current_chan);
dev_dbg(priv->adapter->dev, "info: Assoc: TLV Chan = %d\n",
chan_tlv->chan_scan_param[0].chan_number);
chan_tlv->chan_scan_param[0].radio_type =
mwifiex_band_to_radio_type((u8) bss_desc->bss_band);
dev_dbg(priv->adapter->dev, "info: Assoc: TLV Band = %d\n",
chan_tlv->chan_scan_param[0].radio_type);
pos += sizeof(chan_tlv->header) +
sizeof(struct mwifiex_chan_scan_param_set);
}
if (!priv->wps.session_enable) {
if (priv->sec_info.wpa_enabled || priv->sec_info.wpa2_enabled)
rsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos);
if (rsn_ie_len == -1)
return -1;
}
if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info) &&
(!bss_desc->disable_11n) &&
(priv->adapter->config_bands & BAND_GN ||
priv->adapter->config_bands & BAND_AN))
mwifiex_cmd_append_11n_tlv(priv, bss_desc, &pos);
/* Append vendor specific IE TLV */
mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_ASSOC, &pos);
mwifiex_wmm_process_association_req(priv, &pos, &bss_desc->wmm_ie,
bss_desc->bcn_ht_cap);
if (priv->sec_info.wapi_enabled && priv->wapi_ie_len)
mwifiex_cmd_append_wapi_ie(priv, &pos);
mwifiex_cmd_append_generic_ie(priv, &pos);
mwifiex_cmd_append_tsf_tlv(priv, &pos, bss_desc);
cmd->size = cpu_to_le16((u16) (pos - (u8 *) assoc) + S_DS_GEN);
/* Set the Capability info at last */
tmp_cap = bss_desc->cap_info_bitmap;
if (priv->adapter->config_bands == BAND_B)
tmp_cap &= ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
tmp_cap &= CAPINFO_MASK;
dev_dbg(priv->adapter->dev, "info: ASSOC_CMD: tmp_cap=%4X CAPINFO_MASK=%4lX\n",
tmp_cap, CAPINFO_MASK);
assoc->cap_info_bitmap = cpu_to_le16(tmp_cap);
return 0;
}
/*
* Association firmware command response handler
*
* The response buffer for the association command has the following
* memory layout.
*
* For cases where an association response was not received (indicated
* by the CapInfo and AId field):
*
* .------------------------------------------------------------.
* | Header(4 * sizeof(t_u16)): Standard command response hdr |
* .------------------------------------------------------------.
* | cap_info/Error Return(t_u16): |
* | 0xFFFF(-1): Internal error |
* | 0xFFFE(-2): Authentication unhandled message |
* | 0xFFFD(-3): Authentication refused |
* | 0xFFFC(-4): Timeout waiting for AP response |
* .------------------------------------------------------------.
* | status_code(t_u16): |
* | If cap_info is -1: |
* | An internal firmware failure prevented the |
* | command from being processed. The status_code |
* | will be set to 1. |
* | |
* | If cap_info is -2: |
* | An authentication frame was received but was |
* | not handled by the firmware. IEEE Status |
* | code for the failure is returned. |
* | |
* | If cap_info is -3: |
* | An authentication frame was received and the |
* | status_code is the IEEE Status reported in the |
* | response. |
* | |
* | If cap_info is -4: |
* | (1) Association response timeout |
* | (2) Authentication response timeout |
* .------------------------------------------------------------.
* | a_id(t_u16): 0xFFFF |
* .------------------------------------------------------------.
*
*
* For cases where an association response was received, the IEEE
* standard association response frame is returned:
*
* .------------------------------------------------------------.
* | Header(4 * sizeof(t_u16)): Standard command response hdr |
* .------------------------------------------------------------.
* | cap_info(t_u16): IEEE Capability |
* .------------------------------------------------------------.
* | status_code(t_u16): IEEE Status Code |
* .------------------------------------------------------------.
* | a_id(t_u16): IEEE Association ID |
* .------------------------------------------------------------.
* | IEEE IEs(variable): Any received IEs comprising the |
* | remaining portion of a received |
* | association response frame. |
* .------------------------------------------------------------.
*
* For simplistic handling, the status_code field can be used to determine
* an association success (0) or failure (non-zero).
*/
int mwifiex_ret_802_11_associate(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct mwifiex_adapter *adapter = priv->adapter;
int ret = 0;
struct ieee_types_assoc_rsp *assoc_rsp;
struct mwifiex_bssdescriptor *bss_desc;
u8 enable_data = true;
assoc_rsp = (struct ieee_types_assoc_rsp *) &resp->params;
priv->assoc_rsp_size = min(le16_to_cpu(resp->size) - S_DS_GEN,
sizeof(priv->assoc_rsp_buf));
memcpy(priv->assoc_rsp_buf, &resp->params, priv->assoc_rsp_size);
if (le16_to_cpu(assoc_rsp->status_code)) {
priv->adapter->dbg.num_cmd_assoc_failure++;
dev_err(priv->adapter->dev,
"ASSOC_RESP: failed, status code=%d err=%#x a_id=%#x\n",
le16_to_cpu(assoc_rsp->status_code),
le16_to_cpu(assoc_rsp->cap_info_bitmap),
le16_to_cpu(assoc_rsp->a_id));
ret = le16_to_cpu(assoc_rsp->status_code);
goto done;
}
/* Send a Media Connected event, according to the Spec */
priv->media_connected = true;
priv->adapter->ps_state = PS_STATE_AWAKE;
priv->adapter->pps_uapsd_mode = false;
priv->adapter->tx_lock_flag = false;
/* Set the attempted BSSID Index to current */
bss_desc = priv->attempted_bss_desc;
dev_dbg(priv->adapter->dev, "info: ASSOC_RESP: %s\n",
bss_desc->ssid.ssid);
/* Make a copy of current BSSID descriptor */
memcpy(&priv->curr_bss_params.bss_descriptor,
bss_desc, sizeof(struct mwifiex_bssdescriptor));
/* Update curr_bss_params */
priv->curr_bss_params.bss_descriptor.channel
= bss_desc->phy_param_set.ds_param_set.current_chan;
priv->curr_bss_params.band = (u8) bss_desc->bss_band;
if (bss_desc->wmm_ie.vend_hdr.element_id == WLAN_EID_VENDOR_SPECIFIC)
priv->curr_bss_params.wmm_enabled = true;
else
priv->curr_bss_params.wmm_enabled = false;
if ((priv->wmm_required || bss_desc->bcn_ht_cap) &&
priv->curr_bss_params.wmm_enabled)
priv->wmm_enabled = true;
else
priv->wmm_enabled = false;
priv->curr_bss_params.wmm_uapsd_enabled = false;
if (priv->wmm_enabled)
priv->curr_bss_params.wmm_uapsd_enabled
= ((bss_desc->wmm_ie.qos_info_bitmap &
IEEE80211_WMM_IE_AP_QOSINFO_UAPSD) ? 1 : 0);
dev_dbg(priv->adapter->dev, "info: ASSOC_RESP: curr_pkt_filter is %#x\n",
priv->curr_pkt_filter);
if (priv->sec_info.wpa_enabled || priv->sec_info.wpa2_enabled)
priv->wpa_is_gtk_set = false;
if (priv->wmm_enabled) {
/* Don't re-enable carrier until we get the WMM_GET_STATUS
event */
enable_data = false;
} else {
/* Since WMM is not enabled, setup the queues with the
defaults */
mwifiex_wmm_setup_queue_priorities(priv, NULL);
mwifiex_wmm_setup_ac_downgrade(priv);
}
if (enable_data)
dev_dbg(priv->adapter->dev,
"info: post association, re-enabling data flow\n");
/* Reset SNR/NF/RSSI values */
priv->data_rssi_last = 0;
priv->data_nf_last = 0;
priv->data_rssi_avg = 0;
priv->data_nf_avg = 0;
priv->bcn_rssi_last = 0;
priv->bcn_nf_last = 0;
priv->bcn_rssi_avg = 0;
priv->bcn_nf_avg = 0;
priv->rxpd_rate = 0;
priv->rxpd_htinfo = 0;
mwifiex_save_curr_bcn(priv);
priv->adapter->dbg.num_cmd_assoc_success++;
dev_dbg(priv->adapter->dev, "info: ASSOC_RESP: associated\n");
/* Add the ra_list here for infra mode as there will be only 1 ra
always */
mwifiex_ralist_add(priv,
priv->curr_bss_params.bss_descriptor.mac_address);
if (!netif_carrier_ok(priv->netdev))
netif_carrier_on(priv->netdev);
if (netif_queue_stopped(priv->netdev))
netif_wake_queue(priv->netdev);
if (priv->sec_info.wpa_enabled || priv->sec_info.wpa2_enabled)
priv->scan_block = true;
done:
/* Need to indicate IOCTL complete */
if (adapter->curr_cmd->wait_q_enabled) {
if (ret)
adapter->cmd_wait_q.status = -1;
else
adapter->cmd_wait_q.status = 0;
}
return ret;
}
/*
* This function prepares command for ad-hoc start.
*
* Driver will fill up SSID, BSS mode, IBSS parameters, physical
* parameters, probe delay, and capability information. Firmware
* will fill up beacon period, basic rates and operational rates.
*
* In addition, the following TLVs are added -
* - Channel TLV
* - Vendor specific IE
* - WPA/WPA2 IE
* - HT Capabilities IE
* - HT Information IE
*
* Preparation also includes -
* - Setting command ID and proper size
* - Ensuring correct endian-ness
*/
int
mwifiex_cmd_802_11_ad_hoc_start(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd,
struct cfg80211_ssid *req_ssid)
{
int rsn_ie_len = 0;
struct mwifiex_adapter *adapter = priv->adapter;
struct host_cmd_ds_802_11_ad_hoc_start *adhoc_start =
&cmd->params.adhoc_start;
struct mwifiex_bssdescriptor *bss_desc;
u32 cmd_append_size = 0;
u32 i;
u16 tmp_cap;
struct mwifiex_ie_types_chan_list_param_set *chan_tlv;
u8 radio_type;
struct mwifiex_ie_types_htcap *ht_cap;
struct mwifiex_ie_types_htinfo *ht_info;
u8 *pos = (u8 *) adhoc_start +
sizeof(struct host_cmd_ds_802_11_ad_hoc_start);
if (!adapter)
return -1;
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_AD_HOC_START);
bss_desc = &priv->curr_bss_params.bss_descriptor;
priv->attempted_bss_desc = bss_desc;
/*
* Fill in the parameters for 2 data structures:
* 1. struct host_cmd_ds_802_11_ad_hoc_start command
* 2. bss_desc
* Driver will fill up SSID, bss_mode,IBSS param, Physical Param,
* probe delay, and Cap info.
* Firmware will fill up beacon period, Basic rates
* and operational rates.
*/
memset(adhoc_start->ssid, 0, IEEE80211_MAX_SSID_LEN);
memcpy(adhoc_start->ssid, req_ssid->ssid, req_ssid->ssid_len);
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: SSID = %s\n",
adhoc_start->ssid);
memset(bss_desc->ssid.ssid, 0, IEEE80211_MAX_SSID_LEN);
memcpy(bss_desc->ssid.ssid, req_ssid->ssid, req_ssid->ssid_len);
bss_desc->ssid.ssid_len = req_ssid->ssid_len;
/* Set the BSS mode */
adhoc_start->bss_mode = HostCmd_BSS_MODE_IBSS;
bss_desc->bss_mode = NL80211_IFTYPE_ADHOC;
adhoc_start->beacon_period = cpu_to_le16(priv->beacon_period);
bss_desc->beacon_period = priv->beacon_period;
/* Set Physical param set */
/* Parameter IE Id */
#define DS_PARA_IE_ID 3
/* Parameter IE length */
#define DS_PARA_IE_LEN 1
adhoc_start->phy_param_set.ds_param_set.element_id = DS_PARA_IE_ID;
adhoc_start->phy_param_set.ds_param_set.len = DS_PARA_IE_LEN;
if (!mwifiex_get_cfp(priv, adapter->adhoc_start_band,
(u16) priv->adhoc_channel, 0)) {
struct mwifiex_chan_freq_power *cfp;
cfp = mwifiex_get_cfp(priv, adapter->adhoc_start_band,
FIRST_VALID_CHANNEL, 0);
if (cfp)
priv->adhoc_channel = (u8) cfp->channel;
}
if (!priv->adhoc_channel) {
dev_err(adapter->dev, "ADHOC_S_CMD: adhoc_channel cannot be 0\n");
return -1;
}
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: creating ADHOC on channel %d\n",
priv->adhoc_channel);
priv->curr_bss_params.bss_descriptor.channel = priv->adhoc_channel;
priv->curr_bss_params.band = adapter->adhoc_start_band;
bss_desc->channel = priv->adhoc_channel;
adhoc_start->phy_param_set.ds_param_set.current_chan =
priv->adhoc_channel;
memcpy(&bss_desc->phy_param_set, &adhoc_start->phy_param_set,
sizeof(union ieee_types_phy_param_set));
/* Set IBSS param set */
/* IBSS parameter IE Id */
#define IBSS_PARA_IE_ID 6
/* IBSS parameter IE length */
#define IBSS_PARA_IE_LEN 2
adhoc_start->ss_param_set.ibss_param_set.element_id = IBSS_PARA_IE_ID;
adhoc_start->ss_param_set.ibss_param_set.len = IBSS_PARA_IE_LEN;
adhoc_start->ss_param_set.ibss_param_set.atim_window
= cpu_to_le16(priv->atim_window);
memcpy(&bss_desc->ss_param_set, &adhoc_start->ss_param_set,
sizeof(union ieee_types_ss_param_set));
/* Set Capability info */
bss_desc->cap_info_bitmap |= WLAN_CAPABILITY_IBSS;
tmp_cap = le16_to_cpu(adhoc_start->cap_info_bitmap);
tmp_cap &= ~WLAN_CAPABILITY_ESS;
tmp_cap |= WLAN_CAPABILITY_IBSS;
/* Set up privacy in bss_desc */
if (priv->sec_info.encryption_mode) {
/* Ad-Hoc capability privacy on */
dev_dbg(adapter->dev,
"info: ADHOC_S_CMD: wep_status set privacy to WEP\n");
bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_8021X_WEP;
tmp_cap |= WLAN_CAPABILITY_PRIVACY;
} else {
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: wep_status NOT set,"
" setting privacy to ACCEPT ALL\n");
bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_ACCEPT_ALL;
}
memset(adhoc_start->data_rate, 0, sizeof(adhoc_start->data_rate));
mwifiex_get_active_data_rates(priv, adhoc_start->data_rate);
if ((adapter->adhoc_start_band & BAND_G) &&
(priv->curr_pkt_filter & HostCmd_ACT_MAC_ADHOC_G_PROTECTION_ON)) {
if (mwifiex_send_cmd_async(priv, HostCmd_CMD_MAC_CONTROL,
HostCmd_ACT_GEN_SET, 0,
&priv->curr_pkt_filter)) {
dev_err(adapter->dev,
"ADHOC_S_CMD: G Protection config failed\n");
return -1;
}
}
/* Find the last non zero */
for (i = 0; i < sizeof(adhoc_start->data_rate); i++)
if (!adhoc_start->data_rate[i])
break;
priv->curr_bss_params.num_of_rates = i;
/* Copy the ad-hoc creating rates into Current BSS rate structure */
memcpy(&priv->curr_bss_params.data_rates,
&adhoc_start->data_rate, priv->curr_bss_params.num_of_rates);
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: rates=%02x %02x %02x %02x\n",
adhoc_start->data_rate[0], adhoc_start->data_rate[1],
adhoc_start->data_rate[2], adhoc_start->data_rate[3]);
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: AD-HOC Start command is ready\n");
if (IS_SUPPORT_MULTI_BANDS(adapter)) {
/* Append a channel TLV */
chan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos;
chan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
chan_tlv->header.len =
cpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set));
memset(chan_tlv->chan_scan_param, 0x00,
sizeof(struct mwifiex_chan_scan_param_set));
chan_tlv->chan_scan_param[0].chan_number =
(u8) priv->curr_bss_params.bss_descriptor.channel;
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: TLV Chan = %d\n",
chan_tlv->chan_scan_param[0].chan_number);
chan_tlv->chan_scan_param[0].radio_type
= mwifiex_band_to_radio_type(priv->curr_bss_params.band);
if (adapter->adhoc_start_band & BAND_GN ||
adapter->adhoc_start_band & BAND_AN) {
if (adapter->sec_chan_offset ==
IEEE80211_HT_PARAM_CHA_SEC_ABOVE)
chan_tlv->chan_scan_param[0].radio_type |=
(IEEE80211_HT_PARAM_CHA_SEC_ABOVE << 4);
else if (adapter->sec_chan_offset ==
IEEE80211_HT_PARAM_CHA_SEC_ABOVE)
chan_tlv->chan_scan_param[0].radio_type |=
(IEEE80211_HT_PARAM_CHA_SEC_BELOW << 4);
}
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: TLV Band = %d\n",
chan_tlv->chan_scan_param[0].radio_type);
pos += sizeof(chan_tlv->header) +
sizeof(struct mwifiex_chan_scan_param_set);
cmd_append_size +=
sizeof(chan_tlv->header) +
sizeof(struct mwifiex_chan_scan_param_set);
}
/* Append vendor specific IE TLV */
cmd_append_size += mwifiex_cmd_append_vsie_tlv(priv,
MWIFIEX_VSIE_MASK_ADHOC, &pos);
if (priv->sec_info.wpa_enabled) {
rsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos);
if (rsn_ie_len == -1)
return -1;
cmd_append_size += rsn_ie_len;
}
if (adapter->adhoc_11n_enabled) {
/* Fill HT CAPABILITY */
ht_cap = (struct mwifiex_ie_types_htcap *) pos;
memset(ht_cap, 0, sizeof(struct mwifiex_ie_types_htcap));
ht_cap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY);
ht_cap->header.len =
cpu_to_le16(sizeof(struct ieee80211_ht_cap));
radio_type = mwifiex_band_to_radio_type(
priv->adapter->config_bands);
mwifiex_fill_cap_info(priv, radio_type, ht_cap);
pos += sizeof(struct mwifiex_ie_types_htcap);
cmd_append_size += sizeof(struct mwifiex_ie_types_htcap);
/* Fill HT INFORMATION */
ht_info = (struct mwifiex_ie_types_htinfo *) pos;
memset(ht_info, 0, sizeof(struct mwifiex_ie_types_htinfo));
ht_info->header.type = cpu_to_le16(WLAN_EID_HT_INFORMATION);
ht_info->header.len =
cpu_to_le16(sizeof(struct ieee80211_ht_info));
ht_info->ht_info.control_chan =
(u8) priv->curr_bss_params.bss_descriptor.channel;
if (adapter->sec_chan_offset) {
ht_info->ht_info.ht_param = adapter->sec_chan_offset;
ht_info->ht_info.ht_param |=
IEEE80211_HT_PARAM_CHAN_WIDTH_ANY;
}
ht_info->ht_info.operation_mode =
cpu_to_le16(IEEE80211_HT_OP_MODE_NON_GF_STA_PRSNT);
ht_info->ht_info.basic_set[0] = 0xff;
pos += sizeof(struct mwifiex_ie_types_htinfo);
cmd_append_size +=
sizeof(struct mwifiex_ie_types_htinfo);
}
cmd->size =
cpu_to_le16((u16)(sizeof(struct host_cmd_ds_802_11_ad_hoc_start)
+ S_DS_GEN + cmd_append_size));
if (adapter->adhoc_start_band == BAND_B)
tmp_cap &= ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
else
tmp_cap |= WLAN_CAPABILITY_SHORT_SLOT_TIME;
adhoc_start->cap_info_bitmap = cpu_to_le16(tmp_cap);
return 0;
}
/*
* This function prepares command for ad-hoc join.
*
* Most of the parameters are set up by copying from the target BSS descriptor
* from the scan response.
*
* In addition, the following TLVs are added -
* - Channel TLV
* - Vendor specific IE
* - WPA/WPA2 IE
* - 11n IE
*
* Preparation also includes -
* - Setting command ID and proper size
* - Ensuring correct endian-ness
*/
int
mwifiex_cmd_802_11_ad_hoc_join(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd,
struct mwifiex_bssdescriptor *bss_desc)
{
int rsn_ie_len = 0;
struct host_cmd_ds_802_11_ad_hoc_join *adhoc_join =
&cmd->params.adhoc_join;
struct mwifiex_ie_types_chan_list_param_set *chan_tlv;
u32 cmd_append_size = 0;
u16 tmp_cap;
u32 i, rates_size = 0;
u16 curr_pkt_filter;
u8 *pos =
(u8 *) adhoc_join +
sizeof(struct host_cmd_ds_802_11_ad_hoc_join);
/* Use G protection */
#define USE_G_PROTECTION 0x02
if (bss_desc->erp_flags & USE_G_PROTECTION) {
curr_pkt_filter =
priv->
curr_pkt_filter | HostCmd_ACT_MAC_ADHOC_G_PROTECTION_ON;
if (mwifiex_send_cmd_async(priv, HostCmd_CMD_MAC_CONTROL,
HostCmd_ACT_GEN_SET, 0,
&curr_pkt_filter)) {
dev_err(priv->adapter->dev,
"ADHOC_J_CMD: G Protection config failed\n");
return -1;
}
}
priv->attempted_bss_desc = bss_desc;
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_AD_HOC_JOIN);
adhoc_join->bss_descriptor.bss_mode = HostCmd_BSS_MODE_IBSS;
adhoc_join->bss_descriptor.beacon_period
= cpu_to_le16(bss_desc->beacon_period);
memcpy(&adhoc_join->bss_descriptor.bssid,
&bss_desc->mac_address, ETH_ALEN);
memcpy(&adhoc_join->bss_descriptor.ssid,
&bss_desc->ssid.ssid, bss_desc->ssid.ssid_len);
memcpy(&adhoc_join->bss_descriptor.phy_param_set,
&bss_desc->phy_param_set,
sizeof(union ieee_types_phy_param_set));
memcpy(&adhoc_join->bss_descriptor.ss_param_set,
&bss_desc->ss_param_set, sizeof(union ieee_types_ss_param_set));
tmp_cap = bss_desc->cap_info_bitmap;
tmp_cap &= CAPINFO_MASK;
dev_dbg(priv->adapter->dev,
"info: ADHOC_J_CMD: tmp_cap=%4X CAPINFO_MASK=%4lX\n",
tmp_cap, CAPINFO_MASK);
/* Information on BSSID descriptor passed to FW */
dev_dbg(priv->adapter->dev, "info: ADHOC_J_CMD: BSSID=%pM, SSID='%s'\n",
adhoc_join->bss_descriptor.bssid,
adhoc_join->bss_descriptor.ssid);
for (i = 0; bss_desc->supported_rates[i] &&
i < MWIFIEX_SUPPORTED_RATES;
i++)
;
rates_size = i;
/* Copy Data Rates from the Rates recorded in scan response */
memset(adhoc_join->bss_descriptor.data_rates, 0,
sizeof(adhoc_join->bss_descriptor.data_rates));
memcpy(adhoc_join->bss_descriptor.data_rates,
bss_desc->supported_rates, rates_size);
/* Copy the adhoc join rates into Current BSS state structure */
priv->curr_bss_params.num_of_rates = rates_size;
memcpy(&priv->curr_bss_params.data_rates, bss_desc->supported_rates,
rates_size);
/* Copy the channel information */
priv->curr_bss_params.bss_descriptor.channel = bss_desc->channel;
priv->curr_bss_params.band = (u8) bss_desc->bss_band;
if (priv->sec_info.wep_enabled || priv->sec_info.wpa_enabled)
tmp_cap |= WLAN_CAPABILITY_PRIVACY;
if (IS_SUPPORT_MULTI_BANDS(priv->adapter)) {
/* Append a channel TLV */
chan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos;
chan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
chan_tlv->header.len =
cpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set));
memset(chan_tlv->chan_scan_param, 0x00,
sizeof(struct mwifiex_chan_scan_param_set));
chan_tlv->chan_scan_param[0].chan_number =
(bss_desc->phy_param_set.ds_param_set.current_chan);
dev_dbg(priv->adapter->dev, "info: ADHOC_J_CMD: TLV Chan=%d\n",
chan_tlv->chan_scan_param[0].chan_number);
chan_tlv->chan_scan_param[0].radio_type =
mwifiex_band_to_radio_type((u8) bss_desc->bss_band);
dev_dbg(priv->adapter->dev, "info: ADHOC_J_CMD: TLV Band=%d\n",
chan_tlv->chan_scan_param[0].radio_type);
pos += sizeof(chan_tlv->header) +
sizeof(struct mwifiex_chan_scan_param_set);
cmd_append_size += sizeof(chan_tlv->header) +
sizeof(struct mwifiex_chan_scan_param_set);
}
if (priv->sec_info.wpa_enabled)
rsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos);
if (rsn_ie_len == -1)
return -1;
cmd_append_size += rsn_ie_len;
if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info))
cmd_append_size += mwifiex_cmd_append_11n_tlv(priv,
bss_desc, &pos);
/* Append vendor specific IE TLV */
cmd_append_size += mwifiex_cmd_append_vsie_tlv(priv,
MWIFIEX_VSIE_MASK_ADHOC, &pos);
cmd->size = cpu_to_le16
((u16) (sizeof(struct host_cmd_ds_802_11_ad_hoc_join)
+ S_DS_GEN + cmd_append_size));
adhoc_join->bss_descriptor.cap_info_bitmap = cpu_to_le16(tmp_cap);
return 0;
}
/*
* This function handles the command response of ad-hoc start and
* ad-hoc join.
*
* The function generates a device-connected event to notify
* the applications, in case of successful ad-hoc start/join, and
* saves the beacon buffer.
*/
int mwifiex_ret_802_11_ad_hoc(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
int ret = 0;
struct mwifiex_adapter *adapter = priv->adapter;
struct host_cmd_ds_802_11_ad_hoc_result *adhoc_result;
struct mwifiex_bssdescriptor *bss_desc;
adhoc_result = &resp->params.adhoc_result;
bss_desc = priv->attempted_bss_desc;
/* Join result code 0 --> SUCCESS */
if (le16_to_cpu(resp->result)) {
dev_err(priv->adapter->dev, "ADHOC_RESP: failed\n");
if (priv->media_connected)
mwifiex_reset_connect_state(priv);
memset(&priv->curr_bss_params.bss_descriptor,
0x00, sizeof(struct mwifiex_bssdescriptor));
ret = -1;
goto done;
}
/* Send a Media Connected event, according to the Spec */
priv->media_connected = true;
if (le16_to_cpu(resp->command) == HostCmd_CMD_802_11_AD_HOC_START) {
dev_dbg(priv->adapter->dev, "info: ADHOC_S_RESP %s\n",
bss_desc->ssid.ssid);
/* Update the created network descriptor with the new BSSID */
memcpy(bss_desc->mac_address,
adhoc_result->bssid, ETH_ALEN);
priv->adhoc_state = ADHOC_STARTED;
} else {
/*
* Now the join cmd should be successful.
* If BSSID has changed use SSID to compare instead of BSSID
*/
dev_dbg(priv->adapter->dev, "info: ADHOC_J_RESP %s\n",
bss_desc->ssid.ssid);
/*
* Make a copy of current BSSID descriptor, only needed for
* join since the current descriptor is already being used
* for adhoc start
*/
memcpy(&priv->curr_bss_params.bss_descriptor,
bss_desc, sizeof(struct mwifiex_bssdescriptor));
priv->adhoc_state = ADHOC_JOINED;
}
dev_dbg(priv->adapter->dev, "info: ADHOC_RESP: channel = %d\n",
priv->adhoc_channel);
dev_dbg(priv->adapter->dev, "info: ADHOC_RESP: BSSID = %pM\n",
priv->curr_bss_params.bss_descriptor.mac_address);
if (!netif_carrier_ok(priv->netdev))
netif_carrier_on(priv->netdev);
if (netif_queue_stopped(priv->netdev))
netif_wake_queue(priv->netdev);
mwifiex_save_curr_bcn(priv);
done:
/* Need to indicate IOCTL complete */
if (adapter->curr_cmd->wait_q_enabled) {
if (ret)
adapter->cmd_wait_q.status = -1;
else
adapter->cmd_wait_q.status = 0;
}
return ret;
}
/*
* This function associates to a specific BSS discovered in a scan.
*
* It clears any past association response stored for application
* retrieval and calls the command preparation routine to send the
* command to firmware.
*/
int mwifiex_associate(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
u8 current_bssid[ETH_ALEN];
/* Return error if the adapter or table entry is not marked as infra */
if ((priv->bss_mode != NL80211_IFTYPE_STATION) ||
(bss_desc->bss_mode != NL80211_IFTYPE_STATION))
return -1;
memcpy(¤t_bssid,
&priv->curr_bss_params.bss_descriptor.mac_address,
sizeof(current_bssid));
/* Clear any past association response stored for application
retrieval */
priv->assoc_rsp_size = 0;
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_ASSOCIATE,
HostCmd_ACT_GEN_SET, 0, bss_desc);
}
/*
* This function starts an ad-hoc network.
*
* It calls the command preparation routine to send the command to firmware.
*/
int
mwifiex_adhoc_start(struct mwifiex_private *priv,
struct cfg80211_ssid *adhoc_ssid)
{
dev_dbg(priv->adapter->dev, "info: Adhoc Channel = %d\n",
priv->adhoc_channel);
dev_dbg(priv->adapter->dev, "info: curr_bss_params.channel = %d\n",
priv->curr_bss_params.bss_descriptor.channel);
dev_dbg(priv->adapter->dev, "info: curr_bss_params.band = %d\n",
priv->curr_bss_params.band);
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_AD_HOC_START,
HostCmd_ACT_GEN_SET, 0, adhoc_ssid);
}
/*
* This function joins an ad-hoc network found in a previous scan.
*
* It calls the command preparation routine to send the command to firmware,
* if already not connected to the requested SSID.
*/
int mwifiex_adhoc_join(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
dev_dbg(priv->adapter->dev, "info: adhoc join: curr_bss ssid =%s\n",
priv->curr_bss_params.bss_descriptor.ssid.ssid);
dev_dbg(priv->adapter->dev, "info: adhoc join: curr_bss ssid_len =%u\n",
priv->curr_bss_params.bss_descriptor.ssid.ssid_len);
dev_dbg(priv->adapter->dev, "info: adhoc join: ssid =%s\n",
bss_desc->ssid.ssid);
dev_dbg(priv->adapter->dev, "info: adhoc join: ssid_len =%u\n",
bss_desc->ssid.ssid_len);
/* Check if the requested SSID is already joined */
if (priv->curr_bss_params.bss_descriptor.ssid.ssid_len &&
!mwifiex_ssid_cmp(&bss_desc->ssid,
&priv->curr_bss_params.bss_descriptor.ssid) &&
(priv->curr_bss_params.bss_descriptor.bss_mode ==
NL80211_IFTYPE_ADHOC)) {
dev_dbg(priv->adapter->dev, "info: ADHOC_J_CMD: new ad-hoc SSID"
" is the same as current; not attempting to re-join\n");
return -1;
}
dev_dbg(priv->adapter->dev, "info: curr_bss_params.channel = %d\n",
priv->curr_bss_params.bss_descriptor.channel);
dev_dbg(priv->adapter->dev, "info: curr_bss_params.band = %c\n",
priv->curr_bss_params.band);
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_AD_HOC_JOIN,
HostCmd_ACT_GEN_SET, 0, bss_desc);
}
/*
* This function deauthenticates/disconnects from infra network by sending
* deauthentication request.
*/
static int mwifiex_deauthenticate_infra(struct mwifiex_private *priv, u8 *mac)
{
u8 mac_address[ETH_ALEN];
int ret;
u8 zero_mac[ETH_ALEN] = { 0, 0, 0, 0, 0, 0 };
if (mac) {
if (!memcmp(mac, zero_mac, sizeof(zero_mac)))
memcpy((u8 *) &mac_address,
(u8 *) &priv->curr_bss_params.bss_descriptor.
mac_address, ETH_ALEN);
else
memcpy((u8 *) &mac_address, (u8 *) mac, ETH_ALEN);
} else {
memcpy((u8 *) &mac_address, (u8 *) &priv->curr_bss_params.
bss_descriptor.mac_address, ETH_ALEN);
}
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_DEAUTHENTICATE,
HostCmd_ACT_GEN_SET, 0, &mac_address);
return ret;
}
/*
* This function deauthenticates/disconnects from a BSS.
*
* In case of infra made, it sends deauthentication request, and
* in case of ad-hoc mode, a stop network request is sent to the firmware.
*/
int mwifiex_deauthenticate(struct mwifiex_private *priv, u8 *mac)
{
int ret = 0;
if (priv->media_connected) {
if (priv->bss_mode == NL80211_IFTYPE_STATION) {
ret = mwifiex_deauthenticate_infra(priv, mac);
} else if (priv->bss_mode == NL80211_IFTYPE_ADHOC) {
ret = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_AD_HOC_STOP,
HostCmd_ACT_GEN_SET, 0, NULL);
}
}
return ret;
}
EXPORT_SYMBOL_GPL(mwifiex_deauthenticate);
/*
* This function converts band to radio type used in channel TLV.
*/
u8
mwifiex_band_to_radio_type(u8 band)
{
switch (band) {
case BAND_A:
case BAND_AN:
case BAND_A | BAND_AN:
return HostCmd_SCAN_RADIO_TYPE_A;
case BAND_B:
case BAND_G:
case BAND_B | BAND_G:
default:
return HostCmd_SCAN_RADIO_TYPE_BG;
}
}
| gpl-2.0 |
koying/buildroot-linux-kernel-m3-pivos | arch/powerpc/platforms/40x/ep405.c | 4096 | 3177 | /*
* Architecture- / platform-specific boot-time initialization code for
* IBM PowerPC 4xx based boards. Adapted from original
* code by Gary Thomas, Cort Dougan <cort@fsmlabs.com>, and Dan Malek
* <dan@net4x.com>.
*
* Copyright(c) 1999-2000 Grant Erickson <grant@lcse.umn.edu>
*
* Rewritten and ported to the merged powerpc tree:
* Copyright 2007 IBM Corporation
* Josh Boyer <jwboyer@linux.vnet.ibm.com>
*
* Adapted to EP405 by Ben. Herrenschmidt <benh@kernel.crashing.org>
*
* TODO: Wire up the PCI IRQ mux and the southbridge interrupts
*
* 2002 (c) MontaVista, Software, Inc. This file is licensed under
* the terms of the GNU General Public License version 2. This program
* is licensed "as is" without any warranty of any kind, whether express
* or implied.
*/
#include <linux/init.h>
#include <linux/of_platform.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/udbg.h>
#include <asm/time.h>
#include <asm/uic.h>
#include <asm/pci-bridge.h>
#include <asm/ppc4xx.h>
static struct device_node *bcsr_node;
static void __iomem *bcsr_regs;
/* BCSR registers */
#define BCSR_ID 0
#define BCSR_PCI_CTRL 1
#define BCSR_FLASH_NV_POR_CTRL 2
#define BCSR_FENET_UART_CTRL 3
#define BCSR_PCI_IRQ 4
#define BCSR_XIRQ_SELECT 5
#define BCSR_XIRQ_ROUTING 6
#define BCSR_XIRQ_STATUS 7
#define BCSR_XIRQ_STATUS2 8
#define BCSR_SW_STAT_LED_CTRL 9
#define BCSR_GPIO_IRQ_PAR_CTRL 10
/* there's more, can't be bothered typing them tho */
static __initdata struct of_device_id ep405_of_bus[] = {
{ .compatible = "ibm,plb3", },
{ .compatible = "ibm,opb", },
{ .compatible = "ibm,ebc", },
{},
};
static int __init ep405_device_probe(void)
{
of_platform_bus_probe(NULL, ep405_of_bus, NULL);
return 0;
}
machine_device_initcall(ep405, ep405_device_probe);
static void __init ep405_init_bcsr(void)
{
const u8 *irq_routing;
int i;
/* Find the bloody thing & map it */
bcsr_node = of_find_compatible_node(NULL, NULL, "ep405-bcsr");
if (bcsr_node == NULL) {
printk(KERN_ERR "EP405 BCSR not found !\n");
return;
}
bcsr_regs = of_iomap(bcsr_node, 0);
if (bcsr_regs == NULL) {
printk(KERN_ERR "EP405 BCSR failed to map !\n");
return;
}
/* Get the irq-routing property and apply the routing to the CPLD */
irq_routing = of_get_property(bcsr_node, "irq-routing", NULL);
if (irq_routing == NULL)
return;
for (i = 0; i < 16; i++) {
u8 irq = irq_routing[i];
out_8(bcsr_regs + BCSR_XIRQ_SELECT, i);
out_8(bcsr_regs + BCSR_XIRQ_ROUTING, irq);
}
in_8(bcsr_regs + BCSR_XIRQ_SELECT);
mb();
out_8(bcsr_regs + BCSR_GPIO_IRQ_PAR_CTRL, 0xfe);
}
static void __init ep405_setup_arch(void)
{
/* Find & init the BCSR CPLD */
ep405_init_bcsr();
ppc_pci_set_flags(PPC_PCI_REASSIGN_ALL_RSRC);
}
static int __init ep405_probe(void)
{
unsigned long root = of_get_flat_dt_root();
if (!of_flat_dt_is_compatible(root, "ep405"))
return 0;
return 1;
}
define_machine(ep405) {
.name = "EP405",
.probe = ep405_probe,
.setup_arch = ep405_setup_arch,
.progress = udbg_progress,
.init_IRQ = uic_init_tree,
.get_irq = uic_get_irq,
.restart = ppc4xx_reset_system,
.calibrate_decr = generic_calibrate_decr,
};
| gpl-2.0 |
android-ia/kernel_intel-uefi | 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 |
shinkumara/sprout_shinkumara_kernel | arch/arm/mach-ks8695/time.c | 4864 | 3726 | /*
* arch/arm/mach-ks8695/time.c
*
* Copyright (C) 2006 Ben Dooks <ben@simtec.co.uk>
* Copyright (C) 2006 Simtec Electronics
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/io.h>
#include <asm/mach/time.h>
#include <asm/system_misc.h>
#include <mach/regs-timer.h>
#include <mach/regs-irq.h>
#include "generic.h"
/*
* Returns number of ms since last clock interrupt. Note that interrupts
* will have been disabled by do_gettimeoffset()
*/
static unsigned long ks8695_gettimeoffset (void)
{
unsigned long elapsed, tick2, intpending;
/*
* Get the current number of ticks. Note that there is a race
* condition between us reading the timer and checking for an
* interrupt. We solve this by ensuring that the counter has not
* reloaded between our two reads.
*/
elapsed = __raw_readl(KS8695_TMR_VA + KS8695_T1TC) + __raw_readl(KS8695_TMR_VA + KS8695_T1PD);
do {
tick2 = elapsed;
intpending = __raw_readl(KS8695_IRQ_VA + KS8695_INTST) & (1 << KS8695_IRQ_TIMER1);
elapsed = __raw_readl(KS8695_TMR_VA + KS8695_T1TC) + __raw_readl(KS8695_TMR_VA + KS8695_T1PD);
} while (elapsed > tick2);
/* Convert to number of ticks expired (not remaining) */
elapsed = (CLOCK_TICK_RATE / HZ) - elapsed;
/* Is interrupt pending? If so, then timer has been reloaded already. */
if (intpending)
elapsed += (CLOCK_TICK_RATE / HZ);
/* Convert ticks to usecs */
return (unsigned long)(elapsed * (tick_nsec / 1000)) / LATCH;
}
/*
* IRQ handler for the timer.
*/
static irqreturn_t ks8695_timer_interrupt(int irq, void *dev_id)
{
timer_tick();
return IRQ_HANDLED;
}
static struct irqaction ks8695_timer_irq = {
.name = "ks8695_tick",
.flags = IRQF_DISABLED | IRQF_TIMER,
.handler = ks8695_timer_interrupt,
};
static void ks8695_timer_setup(void)
{
unsigned long tmout = CLOCK_TICK_RATE / HZ;
unsigned long tmcon;
/* disable timer1 */
tmcon = __raw_readl(KS8695_TMR_VA + KS8695_TMCON);
__raw_writel(tmcon & ~TMCON_T1EN, KS8695_TMR_VA + KS8695_TMCON);
__raw_writel(tmout / 2, KS8695_TMR_VA + KS8695_T1TC);
__raw_writel(tmout / 2, KS8695_TMR_VA + KS8695_T1PD);
/* re-enable timer1 */
__raw_writel(tmcon | TMCON_T1EN, KS8695_TMR_VA + KS8695_TMCON);
}
static void __init ks8695_timer_init (void)
{
ks8695_timer_setup();
/* Enable timer interrupts */
setup_irq(KS8695_IRQ_TIMER1, &ks8695_timer_irq);
}
struct sys_timer ks8695_timer = {
.init = ks8695_timer_init,
.offset = ks8695_gettimeoffset,
.resume = ks8695_timer_setup,
};
void ks8695_restart(char mode, const char *cmd)
{
unsigned int reg;
if (mode == 's')
soft_restart(0);
/* disable timer0 */
reg = __raw_readl(KS8695_TMR_VA + KS8695_TMCON);
__raw_writel(reg & ~TMCON_T0EN, KS8695_TMR_VA + KS8695_TMCON);
/* enable watchdog mode */
__raw_writel((10 << 8) | T0TC_WATCHDOG, KS8695_TMR_VA + KS8695_T0TC);
/* re-enable timer0 */
__raw_writel(reg | TMCON_T0EN, KS8695_TMR_VA + KS8695_TMCON);
}
| gpl-2.0 |
mparus/android_kernel_huawei_msm8916-caf | arch/avr32/boards/hammerhead/setup.c | 6912 | 6062 | /*
* Board-specific setup code for the Miromico Hammerhead board
*
* Copyright (C) 2008 Miromico AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/atmel-mci.h>
#include <linux/clk.h>
#include <linux/fb.h>
#include <linux/etherdevice.h>
#include <linux/i2c.h>
#include <linux/i2c-gpio.h>
#include <linux/init.h>
#include <linux/linkage.h>
#include <linux/platform_device.h>
#include <linux/types.h>
#include <linux/spi/spi.h>
#include <video/atmel_lcdc.h>
#include <linux/io.h>
#include <asm/setup.h>
#include <mach/at32ap700x.h>
#include <mach/board.h>
#include <mach/init.h>
#include <mach/portmux.h>
#include <sound/atmel-ac97c.h>
#include "../../mach-at32ap/clock.h"
#include "flash.h"
/* Oscillator frequencies. These are board-specific */
unsigned long at32_board_osc_rates[3] = {
[0] = 32768, /* 32.768 kHz on RTC osc */
[1] = 25000000, /* 25MHz on osc0 */
[2] = 12000000, /* 12 MHz on osc1 */
};
/* Initialized by bootloader-specific startup code. */
struct tag *bootloader_tags __initdata;
#ifdef CONFIG_BOARD_HAMMERHEAD_LCD
static struct fb_videomode __initdata hda350tlv_modes[] = {
{
.name = "320x240 @ 75",
.refresh = 75,
.xres = 320,
.yres = 240,
.pixclock = KHZ2PICOS(6891),
.left_margin = 48,
.right_margin = 18,
.upper_margin = 18,
.lower_margin = 4,
.hsync_len = 20,
.vsync_len = 2,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
},
};
static struct fb_monspecs __initdata hammerhead_hda350t_monspecs = {
.manufacturer = "HAN",
.monitor = "HDA350T-LV",
.modedb = hda350tlv_modes,
.modedb_len = ARRAY_SIZE(hda350tlv_modes),
.hfmin = 14900,
.hfmax = 22350,
.vfmin = 60,
.vfmax = 90,
.dclkmax = 10000000,
};
struct atmel_lcdfb_info __initdata hammerhead_lcdc_data = {
.default_bpp = 24,
.default_dmacon = ATMEL_LCDC_DMAEN | ATMEL_LCDC_DMA2DEN,
.default_lcdcon2 = (ATMEL_LCDC_DISTYPE_TFT
| ATMEL_LCDC_INVCLK
| ATMEL_LCDC_CLKMOD_ALWAYSACTIVE
| ATMEL_LCDC_MEMOR_BIG),
.default_monspecs = &hammerhead_hda350t_monspecs,
.guard_time = 2,
};
#endif
static struct mci_platform_data __initdata mci0_data = {
.slot[0] = {
.bus_width = 4,
.detect_pin = -ENODEV,
.wp_pin = -ENODEV,
},
};
struct eth_addr {
u8 addr[6];
};
static struct eth_addr __initdata hw_addr[1];
static struct macb_platform_data __initdata eth_data[1];
/*
* The next two functions should go away as the boot loader is
* supposed to initialize the macb address registers with a valid
* ethernet address. But we need to keep it around for a while until
* we can be reasonably sure the boot loader does this.
*
* The phy_id is ignored as the driver will probe for it.
*/
static int __init parse_tag_ethernet(struct tag *tag)
{
int i = tag->u.ethernet.mac_index;
if (i < ARRAY_SIZE(hw_addr))
memcpy(hw_addr[i].addr, tag->u.ethernet.hw_address,
sizeof(hw_addr[i].addr));
return 0;
}
__tagtable(ATAG_ETHERNET, parse_tag_ethernet);
static void __init set_hw_addr(struct platform_device *pdev)
{
struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
const u8 *addr;
void __iomem *regs;
struct clk *pclk;
if (!res)
return;
if (pdev->id >= ARRAY_SIZE(hw_addr))
return;
addr = hw_addr[pdev->id].addr;
if (!is_valid_ether_addr(addr))
return;
/*
* Since this is board-specific code, we'll cheat and use the
* physical address directly as we happen to know that it's
* the same as the virtual address.
*/
regs = (void __iomem __force *)res->start;
pclk = clk_get(&pdev->dev, "pclk");
if (IS_ERR(pclk))
return;
clk_enable(pclk);
__raw_writel((addr[3] << 24) | (addr[2] << 16) | (addr[1] << 8) |
addr[0], regs + 0x98);
__raw_writel((addr[5] << 8) | addr[4], regs + 0x9c);
clk_disable(pclk);
clk_put(pclk);
}
void __init setup_board(void)
{
at32_map_usart(1, 0, 0); /* USART 1: /dev/ttyS0, DB9 */
at32_setup_serial_console(0);
}
static struct i2c_gpio_platform_data i2c_gpio_data = {
.sda_pin = GPIO_PIN_PA(6),
.scl_pin = GPIO_PIN_PA(7),
.sda_is_open_drain = 1,
.scl_is_open_drain = 1,
.udelay = 2, /* close to 100 kHz */
};
static struct platform_device i2c_gpio_device = {
.name = "i2c-gpio",
.id = 0,
.dev = { .platform_data = &i2c_gpio_data, },
};
static struct i2c_board_info __initdata i2c_info[] = {};
#ifdef CONFIG_BOARD_HAMMERHEAD_SND
static struct ac97c_platform_data ac97c_data = {
.reset_pin = GPIO_PIN_PA(16),
};
#endif
static int __init hammerhead_init(void)
{
/*
* Hammerhead uses 32-bit SDRAM interface. Reserve the
* SDRAM-specific pins so that nobody messes with them.
*/
at32_reserve_pin(GPIO_PIOE_BASE, ATMEL_EBI_PE_DATA_ALL);
at32_add_device_usart(0);
/* Reserve PB29 (GCLK3). This pin is used as clock source
* for ETH PHY (25MHz). GCLK3 setup is done by U-Boot.
*/
at32_reserve_pin(GPIO_PIOB_BASE, (1<<29));
/*
* Hammerhead uses only one ethernet port, so we don't set
* address of second port
*/
set_hw_addr(at32_add_device_eth(0, ð_data[0]));
#ifdef CONFIG_BOARD_HAMMERHEAD_FPGA
at32_add_device_hh_fpga();
#endif
at32_add_device_mci(0, &mci0_data);
#ifdef CONFIG_BOARD_HAMMERHEAD_USB
at32_add_device_usba(0, NULL);
#endif
#ifdef CONFIG_BOARD_HAMMERHEAD_LCD
at32_add_device_lcdc(0, &hammerhead_lcdc_data, fbmem_start,
fbmem_size, ATMEL_LCDC_PRI_24BIT);
#endif
at32_select_gpio(i2c_gpio_data.sda_pin,
AT32_GPIOF_MULTIDRV | AT32_GPIOF_OUTPUT |
AT32_GPIOF_HIGH);
at32_select_gpio(i2c_gpio_data.scl_pin,
AT32_GPIOF_MULTIDRV | AT32_GPIOF_OUTPUT |
AT32_GPIOF_HIGH);
platform_device_register(&i2c_gpio_device);
i2c_register_board_info(0, i2c_info, ARRAY_SIZE(i2c_info));
#ifdef CONFIG_BOARD_HAMMERHEAD_SND
at32_add_device_ac97c(0, &ac97c_data, AC97C_BOTH);
#endif
/* Select the Touchscreen interrupt pin mode */
at32_select_periph(GPIO_PIOB_BASE, 0x08000000, GPIO_PERIPH_A, 0);
return 0;
}
postcore_initcall(hammerhead_init);
| gpl-2.0 |
wooshy1/kernel-olympus-3.1 | net/netfilter/xt_ipvs.c | 8192 | 4324 | /*
* xt_ipvs - kernel module to match IPVS connection properties
*
* Author: Hannes Eder <heder@google.com>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/spinlock.h>
#include <linux/skbuff.h>
#ifdef CONFIG_IP_VS_IPV6
#include <net/ipv6.h>
#endif
#include <linux/ip_vs.h>
#include <linux/types.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_ipvs.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/ip_vs.h>
MODULE_AUTHOR("Hannes Eder <heder@google.com>");
MODULE_DESCRIPTION("Xtables: match IPVS connection properties");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ipt_ipvs");
MODULE_ALIAS("ip6t_ipvs");
/* borrowed from xt_conntrack */
static bool ipvs_mt_addrcmp(const union nf_inet_addr *kaddr,
const union nf_inet_addr *uaddr,
const union nf_inet_addr *umask,
unsigned int l3proto)
{
if (l3proto == NFPROTO_IPV4)
return ((kaddr->ip ^ uaddr->ip) & umask->ip) == 0;
#ifdef CONFIG_IP_VS_IPV6
else if (l3proto == NFPROTO_IPV6)
return ipv6_masked_addr_cmp(&kaddr->in6, &umask->in6,
&uaddr->in6) == 0;
#endif
else
return false;
}
static bool
ipvs_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct xt_ipvs_mtinfo *data = par->matchinfo;
/* ipvs_mt_check ensures that family is only NFPROTO_IPV[46]. */
const u_int8_t family = par->family;
struct ip_vs_iphdr iph;
struct ip_vs_protocol *pp;
struct ip_vs_conn *cp;
bool match = true;
if (data->bitmask == XT_IPVS_IPVS_PROPERTY) {
match = skb->ipvs_property ^
!!(data->invert & XT_IPVS_IPVS_PROPERTY);
goto out;
}
/* other flags than XT_IPVS_IPVS_PROPERTY are set */
if (!skb->ipvs_property) {
match = false;
goto out;
}
ip_vs_fill_iphdr(family, skb_network_header(skb), &iph);
if (data->bitmask & XT_IPVS_PROTO)
if ((iph.protocol == data->l4proto) ^
!(data->invert & XT_IPVS_PROTO)) {
match = false;
goto out;
}
pp = ip_vs_proto_get(iph.protocol);
if (unlikely(!pp)) {
match = false;
goto out;
}
/*
* Check if the packet belongs to an existing entry
*/
cp = pp->conn_out_get(family, skb, &iph, iph.len, 1 /* inverse */);
if (unlikely(cp == NULL)) {
match = false;
goto out;
}
/*
* We found a connection, i.e. ct != 0, make sure to call
* __ip_vs_conn_put before returning. In our case jump to out_put_con.
*/
if (data->bitmask & XT_IPVS_VPORT)
if ((cp->vport == data->vport) ^
!(data->invert & XT_IPVS_VPORT)) {
match = false;
goto out_put_cp;
}
if (data->bitmask & XT_IPVS_VPORTCTL)
if ((cp->control != NULL &&
cp->control->vport == data->vportctl) ^
!(data->invert & XT_IPVS_VPORTCTL)) {
match = false;
goto out_put_cp;
}
if (data->bitmask & XT_IPVS_DIR) {
enum ip_conntrack_info ctinfo;
struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
if (ct == NULL || nf_ct_is_untracked(ct)) {
match = false;
goto out_put_cp;
}
if ((ctinfo >= IP_CT_IS_REPLY) ^
!!(data->invert & XT_IPVS_DIR)) {
match = false;
goto out_put_cp;
}
}
if (data->bitmask & XT_IPVS_METHOD)
if (((cp->flags & IP_VS_CONN_F_FWD_MASK) == data->fwd_method) ^
!(data->invert & XT_IPVS_METHOD)) {
match = false;
goto out_put_cp;
}
if (data->bitmask & XT_IPVS_VADDR) {
if (ipvs_mt_addrcmp(&cp->vaddr, &data->vaddr,
&data->vmask, family) ^
!(data->invert & XT_IPVS_VADDR)) {
match = false;
goto out_put_cp;
}
}
out_put_cp:
__ip_vs_conn_put(cp);
out:
pr_debug("match=%d\n", match);
return match;
}
static int ipvs_mt_check(const struct xt_mtchk_param *par)
{
if (par->family != NFPROTO_IPV4
#ifdef CONFIG_IP_VS_IPV6
&& par->family != NFPROTO_IPV6
#endif
) {
pr_info("protocol family %u not supported\n", par->family);
return -EINVAL;
}
return 0;
}
static struct xt_match xt_ipvs_mt_reg __read_mostly = {
.name = "ipvs",
.revision = 0,
.family = NFPROTO_UNSPEC,
.match = ipvs_mt,
.checkentry = ipvs_mt_check,
.matchsize = XT_ALIGN(sizeof(struct xt_ipvs_mtinfo)),
.me = THIS_MODULE,
};
static int __init ipvs_mt_init(void)
{
return xt_register_match(&xt_ipvs_mt_reg);
}
static void __exit ipvs_mt_exit(void)
{
xt_unregister_match(&xt_ipvs_mt_reg);
}
module_init(ipvs_mt_init);
module_exit(ipvs_mt_exit);
| gpl-2.0 |
ChepKun/android_kernel_huawei_u8951 | tools/perf/builtin-list.c | 8192 | 1387 | /*
* builtin-list.c
*
* Builtin list command: list all event types
*
* Copyright (C) 2009, Thomas Gleixner <tglx@linutronix.de>
* Copyright (C) 2008-2009, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
* Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
*/
#include "builtin.h"
#include "perf.h"
#include "util/parse-events.h"
#include "util/cache.h"
int cmd_list(int argc, const char **argv, const char *prefix __used)
{
setup_pager();
if (argc == 1)
print_events(NULL);
else {
int i;
for (i = 1; i < argc; ++i) {
if (i > 1)
putchar('\n');
if (strncmp(argv[i], "tracepoint", 10) == 0)
print_tracepoint_events(NULL, NULL);
else if (strcmp(argv[i], "hw") == 0 ||
strcmp(argv[i], "hardware") == 0)
print_events_type(PERF_TYPE_HARDWARE);
else if (strcmp(argv[i], "sw") == 0 ||
strcmp(argv[i], "software") == 0)
print_events_type(PERF_TYPE_SOFTWARE);
else if (strcmp(argv[i], "cache") == 0 ||
strcmp(argv[i], "hwcache") == 0)
print_hwcache_events(NULL);
else {
char *sep = strchr(argv[i], ':'), *s;
int sep_idx;
if (sep == NULL) {
print_events(argv[i]);
continue;
}
sep_idx = sep - argv[i];
s = strdup(argv[i]);
if (s == NULL)
return -1;
s[sep_idx] = '\0';
print_tracepoint_events(s, s + sep_idx + 1);
free(s);
}
}
}
return 0;
}
| gpl-2.0 |
caplio/HTCJ-diff-test | 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 |
sgp-blackphone/Blackphone-BP1-Kernel | tools/power/cpupower/utils/idle_monitor/nhm_idle.c | 10240 | 4899 | /*
* (C) 2010,2011 Thomas Renninger <trenn@suse.de>, Novell Inc.
*
* Licensed under the terms of the GNU GPL License version 2.
*
* Based on Len Brown's <lenb@kernel.org> turbostat tool.
*/
#if defined(__i386__) || defined(__x86_64__)
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "helpers/helpers.h"
#include "idle_monitor/cpupower-monitor.h"
#define MSR_PKG_C3_RESIDENCY 0x3F8
#define MSR_PKG_C6_RESIDENCY 0x3F9
#define MSR_CORE_C3_RESIDENCY 0x3FC
#define MSR_CORE_C6_RESIDENCY 0x3FD
#define MSR_TSC 0x10
#define NHM_CSTATE_COUNT 4
enum intel_nhm_id { C3 = 0, C6, PC3, PC6, TSC = 0xFFFF };
static int nhm_get_count_percent(unsigned int self_id, double *percent,
unsigned int cpu);
static cstate_t nhm_cstates[NHM_CSTATE_COUNT] = {
{
.name = "C3",
.desc = N_("Processor Core C3"),
.id = C3,
.range = RANGE_CORE,
.get_count_percent = nhm_get_count_percent,
},
{
.name = "C6",
.desc = N_("Processor Core C6"),
.id = C6,
.range = RANGE_CORE,
.get_count_percent = nhm_get_count_percent,
},
{
.name = "PC3",
.desc = N_("Processor Package C3"),
.id = PC3,
.range = RANGE_PACKAGE,
.get_count_percent = nhm_get_count_percent,
},
{
.name = "PC6",
.desc = N_("Processor Package C6"),
.id = PC6,
.range = RANGE_PACKAGE,
.get_count_percent = nhm_get_count_percent,
},
};
static unsigned long long tsc_at_measure_start;
static unsigned long long tsc_at_measure_end;
static unsigned long long *previous_count[NHM_CSTATE_COUNT];
static unsigned long long *current_count[NHM_CSTATE_COUNT];
/* valid flag for all CPUs. If a MSR read failed it will be zero */
static int *is_valid;
static int nhm_get_count(enum intel_nhm_id id, unsigned long long *val,
unsigned int cpu)
{
int msr;
switch (id) {
case C3:
msr = MSR_CORE_C3_RESIDENCY;
break;
case C6:
msr = MSR_CORE_C6_RESIDENCY;
break;
case PC3:
msr = MSR_PKG_C3_RESIDENCY;
break;
case PC6:
msr = MSR_PKG_C6_RESIDENCY;
break;
case TSC:
msr = MSR_TSC;
break;
default:
return -1;
};
if (read_msr(cpu, msr, val))
return -1;
return 0;
}
static int nhm_get_count_percent(unsigned int id, double *percent,
unsigned int cpu)
{
*percent = 0.0;
if (!is_valid[cpu])
return -1;
*percent = (100.0 *
(current_count[id][cpu] - previous_count[id][cpu])) /
(tsc_at_measure_end - tsc_at_measure_start);
dprint("%s: previous: %llu - current: %llu - (%u)\n",
nhm_cstates[id].name, previous_count[id][cpu],
current_count[id][cpu], cpu);
dprint("%s: tsc_diff: %llu - count_diff: %llu - percent: %2.f (%u)\n",
nhm_cstates[id].name,
(unsigned long long) tsc_at_measure_end - tsc_at_measure_start,
current_count[id][cpu] - previous_count[id][cpu],
*percent, cpu);
return 0;
}
static int nhm_start(void)
{
int num, cpu;
unsigned long long dbg, val;
nhm_get_count(TSC, &tsc_at_measure_start, 0);
for (num = 0; num < NHM_CSTATE_COUNT; num++) {
for (cpu = 0; cpu < cpu_count; cpu++) {
is_valid[cpu] = !nhm_get_count(num, &val, cpu);
previous_count[num][cpu] = val;
}
}
nhm_get_count(TSC, &dbg, 0);
dprint("TSC diff: %llu\n", dbg - tsc_at_measure_start);
return 0;
}
static int nhm_stop(void)
{
unsigned long long val;
unsigned long long dbg;
int num, cpu;
nhm_get_count(TSC, &tsc_at_measure_end, 0);
for (num = 0; num < NHM_CSTATE_COUNT; num++) {
for (cpu = 0; cpu < cpu_count; cpu++) {
is_valid[cpu] = !nhm_get_count(num, &val, cpu);
current_count[num][cpu] = val;
}
}
nhm_get_count(TSC, &dbg, 0);
dprint("TSC diff: %llu\n", dbg - tsc_at_measure_end);
return 0;
}
struct cpuidle_monitor intel_nhm_monitor;
struct cpuidle_monitor *intel_nhm_register(void)
{
int num;
if (cpupower_cpu_info.vendor != X86_VENDOR_INTEL)
return NULL;
if (!(cpupower_cpu_info.caps & CPUPOWER_CAP_INV_TSC))
return NULL;
if (!(cpupower_cpu_info.caps & CPUPOWER_CAP_APERF))
return NULL;
/* Free this at program termination */
is_valid = calloc(cpu_count, sizeof(int));
for (num = 0; num < NHM_CSTATE_COUNT; num++) {
previous_count[num] = calloc(cpu_count,
sizeof(unsigned long long));
current_count[num] = calloc(cpu_count,
sizeof(unsigned long long));
}
intel_nhm_monitor.name_len = strlen(intel_nhm_monitor.name);
return &intel_nhm_monitor;
}
void intel_nhm_unregister(void)
{
int num;
for (num = 0; num < NHM_CSTATE_COUNT; num++) {
free(previous_count[num]);
free(current_count[num]);
}
free(is_valid);
}
struct cpuidle_monitor intel_nhm_monitor = {
.name = "Nehalem",
.hw_states_num = NHM_CSTATE_COUNT,
.hw_states = nhm_cstates,
.start = nhm_start,
.stop = nhm_stop,
.do_register = intel_nhm_register,
.unregister = intel_nhm_unregister,
.needs_root = 1,
.overflow_s = 922000000 /* 922337203 seconds TSC overflow
at 20GHz */
};
#endif
| gpl-2.0 |
tommytarts/QuantumKernelM8-Sense | 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 |
samsung-msm/android_kernel_samsung_msm8960 | arch/sh/boards/mach-sdk7786/nmi.c | 12288 | 1709 | /*
* SDK7786 FPGA NMI Support.
*
* Copyright (C) 2010 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <mach/fpga.h>
enum {
NMI_MODE_MANUAL,
NMI_MODE_AUX,
NMI_MODE_MASKED,
NMI_MODE_ANY,
NMI_MODE_UNKNOWN,
};
/*
* Default to the manual NMI switch.
*/
static unsigned int __initdata nmi_mode = NMI_MODE_ANY;
static int __init nmi_mode_setup(char *str)
{
if (!str)
return 0;
if (strcmp(str, "manual") == 0)
nmi_mode = NMI_MODE_MANUAL;
else if (strcmp(str, "aux") == 0)
nmi_mode = NMI_MODE_AUX;
else if (strcmp(str, "masked") == 0)
nmi_mode = NMI_MODE_MASKED;
else if (strcmp(str, "any") == 0)
nmi_mode = NMI_MODE_ANY;
else {
nmi_mode = NMI_MODE_UNKNOWN;
pr_warning("Unknown NMI mode %s\n", str);
}
printk("Set NMI mode to %d\n", nmi_mode);
return 0;
}
early_param("nmi_mode", nmi_mode_setup);
void __init sdk7786_nmi_init(void)
{
unsigned int source, mask, tmp;
switch (nmi_mode) {
case NMI_MODE_MANUAL:
source = NMISR_MAN_NMI;
mask = NMIMR_MAN_NMIM;
break;
case NMI_MODE_AUX:
source = NMISR_AUX_NMI;
mask = NMIMR_AUX_NMIM;
break;
case NMI_MODE_ANY:
source = NMISR_MAN_NMI | NMISR_AUX_NMI;
mask = NMIMR_MAN_NMIM | NMIMR_AUX_NMIM;
break;
case NMI_MODE_MASKED:
case NMI_MODE_UNKNOWN:
default:
source = mask = 0;
break;
}
/* Set the NMI source */
tmp = fpga_read_reg(NMISR);
tmp &= ~NMISR_MASK;
tmp |= source;
fpga_write_reg(tmp, NMISR);
/* And the IRQ masking */
fpga_write_reg(NMIMR_MASK ^ mask, NMIMR);
}
| gpl-2.0 |
371816210/kk44 | arch/sh/boards/mach-sdk7786/nmi.c | 12288 | 1709 | /*
* SDK7786 FPGA NMI Support.
*
* Copyright (C) 2010 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <mach/fpga.h>
enum {
NMI_MODE_MANUAL,
NMI_MODE_AUX,
NMI_MODE_MASKED,
NMI_MODE_ANY,
NMI_MODE_UNKNOWN,
};
/*
* Default to the manual NMI switch.
*/
static unsigned int __initdata nmi_mode = NMI_MODE_ANY;
static int __init nmi_mode_setup(char *str)
{
if (!str)
return 0;
if (strcmp(str, "manual") == 0)
nmi_mode = NMI_MODE_MANUAL;
else if (strcmp(str, "aux") == 0)
nmi_mode = NMI_MODE_AUX;
else if (strcmp(str, "masked") == 0)
nmi_mode = NMI_MODE_MASKED;
else if (strcmp(str, "any") == 0)
nmi_mode = NMI_MODE_ANY;
else {
nmi_mode = NMI_MODE_UNKNOWN;
pr_warning("Unknown NMI mode %s\n", str);
}
printk("Set NMI mode to %d\n", nmi_mode);
return 0;
}
early_param("nmi_mode", nmi_mode_setup);
void __init sdk7786_nmi_init(void)
{
unsigned int source, mask, tmp;
switch (nmi_mode) {
case NMI_MODE_MANUAL:
source = NMISR_MAN_NMI;
mask = NMIMR_MAN_NMIM;
break;
case NMI_MODE_AUX:
source = NMISR_AUX_NMI;
mask = NMIMR_AUX_NMIM;
break;
case NMI_MODE_ANY:
source = NMISR_MAN_NMI | NMISR_AUX_NMI;
mask = NMIMR_MAN_NMIM | NMIMR_AUX_NMIM;
break;
case NMI_MODE_MASKED:
case NMI_MODE_UNKNOWN:
default:
source = mask = 0;
break;
}
/* Set the NMI source */
tmp = fpga_read_reg(NMISR);
tmp &= ~NMISR_MASK;
tmp |= source;
fpga_write_reg(tmp, NMISR);
/* And the IRQ masking */
fpga_write_reg(NMIMR_MASK ^ mask, NMIMR);
}
| gpl-2.0 |
michellab/Sire | corelib/src/libs/SireMM/dihedralrestraint.cpp | 1 | 19812 | /********************************************\
*
* Sire - Molecular Simulation Framework
*
* Copyright (C) 2009 Christopher Woods
*
* 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
*
* For full details of the license please see the COPYING file
* that should have come with this distribution.
*
* You can contact the authors via the developer's mailing list
* at http://siremol.org
*
\*********************************************/
#include "dihedralrestraint.h"
#include "SireFF/forcetable.h"
#include "SireCAS/symbols.h"
#include "SireCAS/values.h"
#include "SireCAS/conditional.h"
#include "SireCAS/power.h"
#include "SireID/index.h"
#include "SireUnits/units.h"
#include "SireUnits/angle.h"
#include "SireStream/datastream.h"
#include "SireStream/shareddatastream.h"
#include "SireCAS/errors.h"
using namespace SireMM;
using namespace SireMol;
using namespace SireFF;
using namespace SireID;
using namespace SireBase;
using namespace SireCAS;
using namespace SireMaths;
using namespace SireStream;
using namespace SireUnits;
using namespace SireUnits::Dimension;
////////////
//////////// Implementation of DihedralRestraint
////////////
static const RegisterMetaType<DihedralRestraint> r_dihrest;
/** Serialise to a binary datastream */
QDataStream &operator<<(QDataStream &ds,
const DihedralRestraint &dihrest)
{
writeHeader(ds, r_dihrest, 1);
SharedDataStream sds(ds);
sds << dihrest.p[0] << dihrest.p[1] << dihrest.p[2] << dihrest.p[3]
<< dihrest.force_expression
<< static_cast<const ExpressionRestraint3D&>(dihrest);
return ds;
}
/** Extract from a binary datastream */
QDataStream &operator>>(QDataStream &ds, DihedralRestraint &dihrest)
{
VersionID v = readHeader(ds, r_dihrest);
if (v == 1)
{
SharedDataStream sds(ds);
sds >> dihrest.p[0] >> dihrest.p[1] >> dihrest.p[2] >> dihrest.p[3]
>> dihrest.force_expression
>> static_cast<ExpressionRestraint3D&>(dihrest);
dihrest.intra_molecule_points = Point::areIntraMoleculePoints(dihrest.p[0],
dihrest.p[1]) and
Point::areIntraMoleculePoints(dihrest.p[0],
dihrest.p[2]) and
Point::areIntraMoleculePoints(dihrest.p[0],
dihrest.p[3]);
}
else
throw version_error( v, "1", r_dihrest, CODELOC );
return ds;
}
Q_GLOBAL_STATIC_WITH_ARGS( Symbol, getPhiSymbol, ("phi") );
/** Return the symbol that represents the dihedral angle between the points (phi) */
const Symbol& DihedralRestraint::phi()
{
return *(getPhiSymbol());
}
/** Constructor */
DihedralRestraint::DihedralRestraint()
: ConcreteProperty<DihedralRestraint,ExpressionRestraint3D>()
{}
void DihedralRestraint::calculatePhi()
{
if (this->restraintFunction().isFunction(phi()))
{
SireUnits::Dimension::Angle angle;
if (intra_molecule_points)
//we don't use the space when calculating intra-molecular angles
angle = Vector::dihedral( p[0].read().point(), p[1].read().point(),
p[2].read().point(), p[3].read().point() );
else
angle = this->space().calcDihedral( p[0].read().point(),
p[1].read().point(),
p[2].read().point(),
p[3].read().point() );
ExpressionRestraint3D::_pvt_setValue( phi(), angle );
}
}
/** Construct a restraint that acts on the angle within the
three points 'point0', 'point1' and 'point2' (theta == a(012)),
restraining the angle within these points using the expression
'restraint' */
DihedralRestraint::DihedralRestraint(const PointRef &point0, const PointRef &point1,
const PointRef &point2, const PointRef &point3,
const Expression &restraint)
: ConcreteProperty<DihedralRestraint,ExpressionRestraint3D>(restraint)
{
p[0] = point0;
p[1] = point1;
p[2] = point2;
p[3] = point3;
force_expression = this->restraintFunction().differentiate(phi());
if (force_expression.isConstant())
force_expression = force_expression.evaluate(Values());
intra_molecule_points = Point::areIntraMoleculePoints(p[0], p[1]) and
Point::areIntraMoleculePoints(p[0], p[2]) and
Point::areIntraMoleculePoints(p[0], p[3]);
this->calculatePhi();
}
/** Construct a restraint that acts on the angle within the
three points 'point0', 'point1' and 'point2' (theta == a(012)),
restraining the angle within these points using the expression
'restraint' */
DihedralRestraint::DihedralRestraint(const PointRef &point0, const PointRef &point1,
const PointRef &point2, const PointRef &point3,
const Expression &restraint, const Values &values)
: ConcreteProperty<DihedralRestraint,ExpressionRestraint3D>(restraint, values)
{
p[0] = point0;
p[1] = point1;
p[2] = point2;
p[3] = point3;
force_expression = this->restraintFunction().differentiate(phi());
if (force_expression.isConstant())
force_expression = force_expression.evaluate(Values());
intra_molecule_points = Point::areIntraMoleculePoints(p[0], p[1]) and
Point::areIntraMoleculePoints(p[0], p[2]) and
Point::areIntraMoleculePoints(p[0], p[3]);
this->calculatePhi();
}
/** Internal constructor used to construct a restraint using the specified
points, energy expression and force expression */
DihedralRestraint::DihedralRestraint(const PointRef &point0, const PointRef &point1,
const PointRef &point2, const PointRef &point3,
const Expression &nrg_restraint,
const Expression &force_restraint)
: ConcreteProperty<DihedralRestraint,ExpressionRestraint3D>(nrg_restraint),
force_expression(force_restraint)
{
p[0] = point0;
p[1] = point1;
p[2] = point2;
p[3] = point3;
if (force_expression.isConstant())
{
force_expression = force_expression.evaluate(Values());
}
else
{
if (not this->restraintFunction().symbols().contains(force_expression.symbols()))
throw SireError::incompatible_error( QObject::tr(
"You cannot use a force function which uses more symbols "
"(%1) than the energy function (%2).")
.arg( Sire::toString(force_expression.symbols()),
Sire::toString(restraintFunction().symbols()) ), CODELOC );
}
intra_molecule_points = Point::areIntraMoleculePoints(p[0], p[1]) and
Point::areIntraMoleculePoints(p[0], p[2]) and
Point::areIntraMoleculePoints(p[0], p[3]);
this->calculatePhi();
}
/** Copy constructor */
DihedralRestraint::DihedralRestraint(const DihedralRestraint &other)
: ConcreteProperty<DihedralRestraint,ExpressionRestraint3D>(other),
force_expression(other.force_expression),
intra_molecule_points(other.intra_molecule_points)
{
for (int i=0; i<this->nPoints(); ++i)
{
p[i] = other.p[i];
}
}
/** Destructor */
DihedralRestraint::~DihedralRestraint()
{}
/** Copy assignment operator */
DihedralRestraint& DihedralRestraint::operator=(const DihedralRestraint &other)
{
if (this != &other)
{
ExpressionRestraint3D::operator=(other);
for (int i=0; i<this->nPoints(); ++i)
{
p[i] = other.p[i];
}
force_expression = other.force_expression;
intra_molecule_points = other.intra_molecule_points;
}
return *this;
}
/** Comparison operator */
bool DihedralRestraint::operator==(const DihedralRestraint &other) const
{
return this == &other or
( ExpressionRestraint3D::operator==(other) and
p[0] == other.p[0] and p[1] == other.p[1] and
p[2] == other.p[2] and p[3] == other.p[3] and
force_expression == other.force_expression);
}
/** Comparison operator */
bool DihedralRestraint::operator!=(const DihedralRestraint &other) const
{
return not DihedralRestraint::operator==(other);
}
const char* DihedralRestraint::typeName()
{
return QMetaType::typeName( qMetaTypeId<DihedralRestraint>() );
}
/** This restraint involves four points */
int DihedralRestraint::nPoints() const
{
return 4;
}
/** Return the ith point */
const Point& DihedralRestraint::point(int i) const
{
i = Index(i).map( this->nPoints() );
return p[i].read();
}
/** Return the first point */
const Point& DihedralRestraint::point0() const
{
return p[0].read();
}
/** Return the second point */
const Point& DihedralRestraint::point1() const
{
return p[1].read();
}
/** Return the third point */
const Point& DihedralRestraint::point2() const
{
return p[2].read();
}
/** Return the fourth point */
const Point& DihedralRestraint::point3() const
{
return p[3].read();
}
/** Return the built-in symbols for this restraint */
Symbols DihedralRestraint::builtinSymbols() const
{
if (this->restraintFunction().isFunction(phi()))
return phi();
else
return Symbols();
}
/** Return the values of the built-in symbols of this restraint */
Values DihedralRestraint::builtinValues() const
{
if (this->restraintFunction().isFunction(phi()))
return phi() == this->values()[phi()];
else
return Values();
}
/** Return the differential of this restraint with respect to
the symbol 'symbol'
\throw SireCAS::unavailable_differential
*/
RestraintPtr DihedralRestraint::differentiate(const Symbol &symbol) const
{
if (this->restraintFunction().isFunction(symbol))
return DihedralRestraint( p[0], p[1], p[2], p[3],
restraintFunction().differentiate(symbol),
this->values() );
else
return NullRestraint();
}
/** Set the space used to evaluate the energy of this restraint
\throw SireVol::incompatible_space
*/
void DihedralRestraint::setSpace(const Space &new_space)
{
if (not this->space().equals(new_space))
{
DihedralRestraint old_state(*this);
try
{
for (int i=0; i<this->nPoints(); ++i)
{
p[i].edit().setSpace(new_space);
}
Restraint3D::setSpace(new_space);
this->calculatePhi();
}
catch(...)
{
DihedralRestraint::operator=(old_state);
throw;
}
}
}
/** Return the function used to calculate the restraint force */
const Expression& DihedralRestraint::differentialRestraintFunction() const
{
return force_expression;
}
/** Calculate the force acting on the molecule in the forcetable 'forcetable'
caused by this restraint, and add it on to the forcetable scaled by
'scale_force' */
void DihedralRestraint::force(MolForceTable &forcetable, double scale_force) const
{
bool in_p0 = p[0].read().contains(forcetable.molNum());
bool in_p1 = p[1].read().contains(forcetable.molNum());
bool in_p2 = p[2].read().contains(forcetable.molNum());
bool in_p3 = p[3].read().contains(forcetable.molNum());
if (not (in_p0 or in_p1 or in_p2 or in_p3))
//this molecule is not affected by the restraint
return;
throw SireError::incomplete_code( QObject::tr(
"Haven't yet written the code to calculate forces caused "
"by a dihedral restraint."), CODELOC );
}
/** Calculate the force acting on the molecules in the forcetable 'forcetable'
caused by this restraint, and add it on to the forcetable scaled by
'scale_force' */
void DihedralRestraint::force(ForceTable &forcetable, double scale_force) const
{
bool in_p0 = p[0].read().usesMoleculesIn(forcetable);
bool in_p1 = p[1].read().usesMoleculesIn(forcetable);
bool in_p2 = p[2].read().usesMoleculesIn(forcetable);
bool in_p3 = p[3].read().usesMoleculesIn(forcetable);
if (not (in_p0 or in_p1 or in_p2 or in_p3))
//this molecule is not affected by the restraint
return;
throw SireError::incomplete_code( QObject::tr(
"Haven't yet written the code to calculate forces caused "
"by a dihedral restraint."), CODELOC );
}
/** Update the points of this restraint using new molecule data from 'moldata'
\throw SireBase::missing_property
\throw SireError::invalid_cast
\throw SireError::incompatible_error
*/
void DihedralRestraint::update(const MoleculeData &moldata)
{
if (this->contains(moldata.number()))
{
DihedralRestraint old_state(*this);
try
{
for (int i=0; i<this->nPoints(); ++i)
{
p[i].edit().update(moldata);
}
this->calculatePhi();
}
catch(...)
{
DihedralRestraint::operator=(old_state);
throw;
}
}
}
/** Update the points of this restraint using new molecule data from 'molecules'
\throw SireBase::missing_property
\throw SireError::invalid_cast
\throw SireError::incompatible_error
*/
void DihedralRestraint::update(const Molecules &molecules)
{
if (this->usesMoleculesIn(molecules))
{
DihedralRestraint old_state(*this);
try
{
for (int i=0; i<this->nPoints(); ++i)
{
p[i].edit().update(molecules);
}
this->calculatePhi();
}
catch(...)
{
DihedralRestraint::operator=(old_state);
throw;
}
}
}
/** Return the molecules used in this restraint */
Molecules DihedralRestraint::molecules() const
{
Molecules mols;
for (int i=0; i<this->nPoints(); ++i)
{
mols += p[i].read().molecules();
}
return mols;
}
/** Return whether or not this restraint affects the molecule
with number 'molnum' */
bool DihedralRestraint::contains(MolNum molnum) const
{
return p[0].read().contains(molnum) or p[1].read().contains(molnum) or
p[2].read().contains(molnum) or p[3].read().contains(molnum);
}
/** Return whether or not this restraint affects the molecule
with ID 'molid' */
bool DihedralRestraint::contains(const MolID &molid) const
{
return p[0].read().contains(molid) or p[1].read().contains(molid) or
p[2].read().contains(molid) or p[3].read().contains(molid);
}
/** Return whether or not this restraint involves any of the molecules
that are in the forcetable 'forcetable' */
bool DihedralRestraint::usesMoleculesIn(const ForceTable &forcetable) const
{
return p[0].read().usesMoleculesIn(forcetable) or
p[1].read().usesMoleculesIn(forcetable) or
p[2].read().usesMoleculesIn(forcetable) or
p[3].read().usesMoleculesIn(forcetable);
}
/** Return whether or not this restraint involves any of the molecules
in 'molecules' */
bool DihedralRestraint::usesMoleculesIn(const Molecules &molecules) const
{
return p[0].read().usesMoleculesIn(molecules) or
p[1].read().usesMoleculesIn(molecules) or
p[2].read().usesMoleculesIn(molecules) or
p[3].read().usesMoleculesIn(molecules);
}
static Expression harmonicFunction(double force_constant)
{
if (SireMaths::isZero(force_constant))
return 0;
else
return force_constant * pow(DihedralRestraint::phi(), 2);
}
static Expression diffHarmonicFunction(double force_constant)
{
if (SireMaths::isZero(force_constant))
return 0;
else
return (2*force_constant) * DihedralRestraint::phi();
}
/** Return a distance restraint that applies a harmonic potential between
the points 'point0' and 'point1' using a force constant 'force_constant' */
DihedralRestraint DihedralRestraint::harmonic(
const PointRef &point0,
const PointRef &point1,
const PointRef &point2,
const PointRef &point3,
const HarmonicAngleForceConstant &force_constant)
{
return DihedralRestraint(point0, point1, point2, point3,
::harmonicFunction(force_constant),
::diffHarmonicFunction(force_constant));
}
static Expression halfHarmonicFunction(double force_constant, double angle)
{
if ( SireMaths::isZero(force_constant) )
return 0;
else if ( angle <= 0 )
//this is just a harmonic function
return ::harmonicFunction(force_constant);
else
{
const Symbol &phi = DihedralRestraint::phi();
return Conditional(
GreaterThan(phi, angle), force_constant * pow(phi-angle, 2), 0 );
}
}
static Expression diffHalfHarmonicFunction(double force_constant, double angle)
{
if ( SireMaths::isZero(force_constant) )
return 0;
else if (angle <= 0)
//this is just a harmonic function
return ::diffHarmonicFunction(force_constant);
else
{
const Symbol &phi = DihedralRestraint::phi();
return Conditional( GreaterThan(phi, angle),
(2*force_constant) * (phi-angle), 0 );
}
}
/** Return a distance restraint that applied a half-harmonic potential
between the points 'point0' and 'point1' above a distance 'distance'
using a force constant 'force_constant' */
DihedralRestraint DihedralRestraint::halfHarmonic(
const PointRef &point0,
const PointRef &point1,
const PointRef &point2,
const PointRef &point3,
const Angle &angle,
const HarmonicAngleForceConstant &force_constant)
{
double ang = angle.to(radians);
return DihedralRestraint(point0, point1, point2, point3,
::halfHarmonicFunction(force_constant, ang),
::diffHalfHarmonicFunction(force_constant, ang));
}
| gpl-2.0 |
rabbitircd/rabbitircd | src/ircd.c | 1 | 41930 | /************************************************************************
* Unreal Internet Relay Chat Daemon, src/ircd.c
* Copyright (C) 1990 Jarkko Oikarinen and
* University of Oulu, Computing Center
*
* 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 1, 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.
*/
#ifndef CLEAN_COMPILE
static char sccsid[] =
"@(#)ircd.c 2.48 3/9/94 (C) 1988 University of Oulu, \
Computing Center and Jarkko Oikarinen";
#endif
#include "config.h"
#include "struct.h"
#include "common.h"
#include "sys.h"
#include "numeric.h"
#include "msg.h"
#include "mempool.h"
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/file.h>
#include <pwd.h>
#include <grp.h>
#include <sys/time.h>
#ifdef HPUX
#define _KERNEL /* HPUX has the world's worst headers... */
#endif
#include <sys/resource.h>
#ifdef HPUX
#undef _KERNEL
#endif
#include <errno.h>
#ifdef HAVE_PSSTRINGS
#include <sys/exec.h>
#endif
#ifdef HAVE_PSTAT
#include <sys/pstat.h>
#endif
#include "h.h"
#include "fdlist.h"
#include "version.h"
#include "proto.h"
ID_Copyright
("(C) 1988 University of Oulu, Computing Center and Jarkko Oikarinen");
ID_Notes("2.48 3/9/94");
#ifdef __FreeBSD__
char *malloc_options = "h" MALLOC_FLAGS_EXTRA;
#endif
int SVSNOOP = 0;
extern MODVAR char *buildid;
time_t timeofday = 0;
int tainted = 0;
LoopStruct loop;
MODVAR MemoryInfo StatsZ;
uid_t irc_uid = 0;
gid_t irc_gid = 0;
int R_do_dns, R_fin_dns, R_fin_dnsc, R_fail_dns, R_do_id, R_fin_id, R_fail_id;
char REPORT_DO_DNS[256], REPORT_FIN_DNS[256], REPORT_FIN_DNSC[256],
REPORT_FAIL_DNS[256], REPORT_DO_ID[256], REPORT_FIN_ID[256],
REPORT_FAIL_ID[256];
ircstats IRCstats;
aClient me; /* That's me */
MODVAR char *me_hash;
extern char backupbuf[8192];
unsigned char conf_debuglevel = 0;
time_t highesttimeofday=0, oldtimeofday=0, lasthighwarn=0;
void save_stats(void)
{
FILE *stats = fopen("ircd.stats", "w");
if (!stats)
return;
fprintf(stats, "%i\n", IRCstats.clients);
fprintf(stats, "%i\n", IRCstats.invisible);
fprintf(stats, "%i\n", IRCstats.servers);
fprintf(stats, "%i\n", IRCstats.operators);
fprintf(stats, "%i\n", IRCstats.unknown);
fprintf(stats, "%i\n", IRCstats.me_clients);
fprintf(stats, "%i\n", IRCstats.me_servers);
fprintf(stats, "%i\n", IRCstats.me_max);
fprintf(stats, "%i\n", IRCstats.global_max);
fclose(stats);
}
void server_reboot(char *);
void restart(char *);
static void open_debugfile(), setup_signals();
extern void init_glines(void);
extern void tkl_init(void);
MODVAR TS last_garbage_collect = 0;
MODVAR char **myargv;
int portnum = -1; /* Server port number, listening this */
char *configfile = CONFIGFILE; /* Server configuration file */
int debuglevel = 10; /* Server debug level */
int bootopt = 0; /* Server boot option flags */
char *debugmode = ""; /* -"- -"- -"- */
char *sbrk0; /* initial sbrk(0) */
static int dorehash = 0, dorestart = 0;
static char *dpath = DPATH;
MODVAR int booted = FALSE;
MODVAR TS lastlucheck = 0;
#ifdef UNREAL_DEBUG
#undef CHROOTDIR
#define CHROOT
#endif
MODVAR TS NOW;
#ifdef PROFIL
extern etext();
VOIDSIG s_monitor(void)
{
static int mon = 0;
#ifdef POSIX_SIGNALS
struct sigaction act;
#endif
(void)moncontrol(mon);
mon = 1 - mon;
#ifdef POSIX_SIGNALS
act.sa_handler = s_rehash;
act.sa_flags = 0;
(void)sigemptyset(&act.sa_mask);
(void)sigaddset(&act.sa_mask, SIGUSR1);
(void)sigaction(SIGUSR1, &act, NULL);
#else
(void)signal(SIGUSR1, s_monitor);
#endif
}
#endif
VOIDSIG s_die()
{
unload_all_modules();
exit(-1);
}
static VOIDSIG s_rehash()
{
#ifdef POSIX_SIGNALS
struct sigaction act;
#endif
dorehash = 1;
#ifdef POSIX_SIGNALS
act.sa_handler = s_rehash;
act.sa_flags = 0;
(void)sigemptyset(&act.sa_mask);
(void)sigaddset(&act.sa_mask, SIGHUP);
(void)sigaction(SIGHUP, &act, NULL);
#else
(void)signal(SIGHUP, s_rehash); /* sysV -argv */
#endif
}
void restart(char *mesg)
{
server_reboot(mesg);
}
VOIDSIG s_restart()
{
dorestart = 1;
#if 0
static int restarting = 0;
if (restarting == 0) {
/*
* Send (or attempt to) a dying scream to oper if present
*/
restarting = 1;
server_reboot("SIGINT");
}
#endif
}
VOIDSIG dummy()
{
#ifndef HAVE_RELIABLE_SIGNALS
(void)signal(SIGALRM, dummy);
(void)signal(SIGPIPE, dummy);
#ifndef HPUX /* Only 9k/800 series require this, but don't know how to.. */
# ifdef SIGWINCH
(void)signal(SIGWINCH, dummy);
# endif
#endif
#else
# ifdef POSIX_SIGNALS
struct sigaction act;
act.sa_handler = dummy;
act.sa_flags = 0;
(void)sigemptyset(&act.sa_mask);
(void)sigaddset(&act.sa_mask, SIGALRM);
(void)sigaddset(&act.sa_mask, SIGPIPE);
# ifdef SIGWINCH
(void)sigaddset(&act.sa_mask, SIGWINCH);
# endif
(void)sigaction(SIGALRM, &act, (struct sigaction *)NULL);
(void)sigaction(SIGPIPE, &act, (struct sigaction *)NULL);
# ifdef SIGWINCH
(void)sigaction(SIGWINCH, &act, (struct sigaction *)NULL);
# endif
# endif
#endif
}
void server_reboot(char *mesg)
{
int i;
aClient *cptr;
sendto_realops("Aieeeee!!! Restarting server... %s", mesg);
Debug((DEBUG_NOTICE, "Restarting server... %s", mesg));
list_for_each_entry(cptr, &lclient_list, lclient_node)
(void) send_queued(cptr);
/*
* ** fd 0 must be 'preserved' if either the -d or -i options have
* ** been passed to us before restarting.
*/
#ifdef HAVE_SYSLOG
(void)closelog();
#endif
for (i = 3; i < MAXCONNECTIONS; i++)
(void)close(i);
if (!(bootopt & (BOOT_TTY | BOOT_DEBUG)))
(void)close(2);
(void)close(1);
(void)close(0);
(void)execv(MYNAME, myargv);
Debug((DEBUG_FATAL, "Couldn't restart server: %s", strerror(errno)));
unload_all_modules();
exit(-1);
}
MODVAR char *areason;
EVENT(loop_event)
{
if (loop.do_garbage_collect == 1) {
garbage_collect(NULL);
}
}
EVENT(garbage_collect)
{
extern int freelinks;
extern Link *freelink;
Link p;
int ii;
if (loop.do_garbage_collect == 1)
sendto_realops("Doing garbage collection ..");
if (freelinks > HOW_MANY_FREELINKS_ALLOWED) {
ii = freelinks;
while (freelink && (freelinks > HOW_MANY_FREELINKS_ALLOWED)) {
freelinks--;
p.next = freelink;
freelink = freelink->next;
MyFree(p.next);
}
if (loop.do_garbage_collect == 1) {
loop.do_garbage_collect = 0;
sendto_realops
("Cleaned up %i garbage blocks", (ii - freelinks));
}
}
if (loop.do_garbage_collect == 1)
loop.do_garbage_collect = 0;
}
/*
** try_connections
**
** Scan through configuration and try new connections.
** Returns the calendar time when the next call to this
** function should be made latest. (No harm done if this
** is called earlier or later...)
*/
EVENT(try_connections)
{
ConfigItem_link *aconf;
ConfigItem_deny_link *deny;
aClient *cptr;
int confrq;
ConfigItem_class *cltmp;
for (aconf = conf_link; aconf; aconf = (ConfigItem_link *) aconf->next) {
/*
* Also when already connecting! (update holdtimes) --SRB
*/
if (!(aconf->options & CONNECT_AUTO) || (aconf->flag.temporary == 1))
continue;
cltmp = aconf->class;
/*
* ** Skip this entry if the use of it is still on hold until
* ** future. Otherwise handle this entry (and set it on hold
* ** until next time). Will reset only hold times, if already
* ** made one successfull connection... [this algorithm is
* ** a bit fuzzy... -- msa >;) ]
*/
if ((aconf->hold > TStime()))
continue;
confrq = cltmp->connfreq;
aconf->hold = TStime() + confrq;
/*
* ** Found a CONNECT config with port specified, scan clients
* ** and see if this server is already connected?
*/
cptr = find_name(aconf->servername, (aClient *)NULL);
if (!cptr && (cltmp->clients < cltmp->maxclients)) {
/*
* Check connect rules to see if we're allowed to try
*/
for (deny = conf_deny_link; deny;
deny = (ConfigItem_deny_link *) deny->next)
if (!match(deny->mask, aconf->servername)
&& crule_eval(deny->rule))
break;
if (!deny && connect_server(aconf, (aClient *)NULL,
(struct hostent *)NULL) == 0)
sendto_realops
("Connection to %s[%s] activated.",
aconf->servername, aconf->hostname);
}
}
}
/* I have separated the TKL verification code from the ping checking
* code. This way we can just trigger a TKL check when we need to,
* instead of complicating the ping checking code, which is presently
* more than sufficiently hairy. The advantage of checking bans at the
* same time as pings is really negligible because we rarely process TKLs
* anyway. --nenolod
*/
void check_tkls(void)
{
aClient *cptr, *cptr2;
ConfigItem_ban *bconf = NULL;
char killflag = 0;
char banbuf[1024];
list_for_each_entry_safe(cptr, cptr2, &lclient_list, lclient_node)
{
if (find_tkline_match(cptr, 0) < 0)
continue;
find_shun(cptr);
if (!killflag && IsPerson(cptr)) {
/*
* If it's a user, we check for CONF_BAN_USER
*/
bconf = Find_ban(cptr, make_user_host(cptr->
user ? cptr->user->username : cptr->
username,
cptr->user ? cptr->user->realhost : cptr->
sockhost), CONF_BAN_USER);
if (bconf != NULL)
killflag++;
if (!killflag && !IsAnOper(cptr) && (bconf = Find_ban(NULL, cptr->info, CONF_BAN_REALNAME)))
killflag++;
}
/*
* If no cookie, we search for Z:lines
*/
if (!killflag && (bconf = Find_ban(cptr, Inet_ia2p(&cptr->ip), CONF_BAN_IP)))
killflag++;
if (killflag) {
if (IsPerson(cptr))
sendto_realops("Ban active for %s (%s)",
get_client_name(cptr, FALSE),
bconf->reason ? bconf->reason : "no reason");
if (IsServer(cptr))
sendto_realops("Ban active for server %s (%s)",
get_client_name(cptr, FALSE),
bconf->reason ? bconf->reason : "no reason");
if (bconf->reason) {
if (IsPerson(cptr))
snprintf(banbuf, sizeof(banbuf), "User has been banned (%s)", bconf->reason);
else
snprintf(banbuf, sizeof(banbuf), "Banned (%s)", bconf->reason);
(void)exit_client(cptr, cptr, &me, banbuf);
} else {
if (IsPerson(cptr))
(void)exit_client(cptr, cptr, &me, "User has been banned");
else
(void)exit_client(cptr, cptr, &me, "Banned");
}
continue;
}
if (IsPerson(cptr) && find_spamfilter_user(cptr, SPAMFLAG_NOWARN) == FLUSH_BUFFER)
continue;
if (IsPerson(cptr) && cptr->user->away != NULL &&
dospamfilter(cptr, cptr->user->away, SPAMF_AWAY, NULL, SPAMFLAG_NOWARN, NULL) == FLUSH_BUFFER)
continue;
}
}
/*
* TODO:
* This is really messy at the moment, but the k-line stuff is recurse-safe, so I removed it
* a while back (see above).
*
* Other things that should likely go:
* - FLAGS_DEADSOCKET handling... just kill them off more towards the event that needs to
* kill them off. Or perhaps kill the DEADSOCKET stuff entirely. That also works...
* - identd/dns timeout checking (should go to it's own event, idea here is that we just
* keep you in "unknown" state until you actually get 001, so we can cull the unknown list)
*
* No need to worry about server list vs lclient list because servers are on lclient. There are
* no good reasons for it not to be, considering that 95% of iterations of the lclient list apply
* to both clients and servers.
* - nenolod
*/
/*
* Check UNKNOWN connections - if they have been in this state
* for more than CONNECTTIMEOUT seconds, close them.
*/
EVENT(check_unknowns)
{
aClient *cptr, *cptr2;
list_for_each_entry_safe(cptr, cptr2, &unknown_list, lclient_node)
{
if (cptr->firsttime && ((TStime() - cptr->firsttime) > CONNECTTIMEOUT))
(void)exit_client(cptr, cptr, &me, "Registration Timeout");
}
}
/*
* Check registered connections for PING timeout.
* XXX: also does some other stuff still, need to sort this. --nenolod
*/
EVENT(check_pings)
{
aClient *cptr, *cptr2;
ConfigItem_ban *bconf = NULL;
int i = 0;
char banbuf[1024];
char scratch[64];
int ping = 0;
TS currenttime = TStime();
list_for_each_entry_safe(cptr, cptr2, &lclient_list, lclient_node)
{
/*
* ** Note: No need to notify opers here. It's
* ** already done when "FLAGS_DEADSOCKET" is set.
*/
if (cptr->flags & FLAGS_DEADSOCKET) {
(void)exit_client(cptr, cptr, &me, cptr->error_str ? cptr->error_str : "Dead socket");
continue;
}
/*
* We go into ping phase
*/
ping =
IsRegistered(cptr) ? (cptr->class ? cptr->
class->pingfreq : CONNECTTIMEOUT) : CONNECTTIMEOUT;
Debug((DEBUG_DEBUG, "c(%s)=%d p %d a %d", cptr->name,
cptr->status, ping,
currenttime - cptr->lasttime));
/* If ping is less than or equal to the last time we received a command from them */
if (ping <= (currenttime - cptr->lasttime))
{
if (
/* If we have sent a ping */
((cptr->flags & FLAGS_PINGSENT)
/* And they had 2x ping frequency to respond */
&& ((currenttime - cptr->lasttime) >= (2 * ping)))
||
/* Or isn't registered and time spent is larger than ping .. */
(!IsRegistered(cptr) && (currenttime - cptr->since >= ping))
)
{
/* if it's registered and doing dns/auth, timeout */
if (!IsRegistered(cptr) && (DoingDNS(cptr) || DoingAuth(cptr)))
{
if (cptr->authfd >= 0) {
fd_close(cptr->authfd);
--OpenFiles;
cptr->authfd = -1;
cptr->count = 0;
*cptr->buffer = '\0';
}
if (SHOWCONNECTINFO && !cptr->serv) {
if (DoingDNS(cptr))
sendto_one(cptr, "%s", REPORT_FAIL_DNS);
else if (DoingAuth(cptr))
sendto_one(cptr, "%s", REPORT_FAIL_ID);
}
Debug((DEBUG_NOTICE,
"DNS/AUTH timeout %s",
get_client_name(cptr, TRUE)));
unrealdns_delreq_bycptr(cptr);
ClearAuth(cptr);
ClearDNS(cptr);
SetAccess(cptr);
cptr->firsttime = currenttime;
cptr->lasttime = currenttime;
continue;
}
if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr) || IsSSLConnectHandshake(cptr)) {
sendto_realops
("No response from %s, closing link",
get_client_name(cptr, FALSE));
sendto_server(&me, 0, 0,
":%s GLOBOPS :No response from %s, closing link",
me.name, get_client_name(cptr,
FALSE));
}
if (IsSSLAcceptHandshake(cptr))
Debug((DEBUG_DEBUG, "ssl accept handshake timeout: %s (%li-%li > %li)", cptr->sockhost,
currenttime, cptr->since, ping));
(void)ircsnprintf(scratch, sizeof(scratch), "Ping timeout: %ld seconds",
(long) (TStime() - cptr->lasttime));
exit_client(cptr, cptr, &me, scratch);
continue;
}
else if (IsRegistered(cptr) &&
((cptr->flags & FLAGS_PINGSENT) == 0)) {
/*
* if we havent PINGed the connection and we havent
* heard from it in a while, PING it to make sure
* it is still alive.
*/
cptr->flags |= FLAGS_PINGSENT;
/*
* not nice but does the job
*/
cptr->lasttime = TStime() - ping;
sendto_one(cptr, "PING :%s", me.name);
}
}
}
}
/*
** bad_command
** This is called when the commandline is not acceptable.
** Give error message and exit without starting anything.
*/
static int bad_command(const char *argv0)
{
if (!argv0)
argv0 = "ircd";
(void)printf
("Usage: %s [-f <config>] [-h <servername>] [-p <port>] [-x <loglevel>] [-t] [-F]\n"
"\n"
"RabbitIRCd\n"
" -f <config> Load configuration from <config> instead of the default\n"
" (%s).\n"
" -h <servername> Override the me::name configuration setting with\n"
" <servername>.\n"
" -p <port> Listen on <port> in addition to the ports specified by\n"
" the listen blocks.\n"
" -x <loglevel> Set the log level to <loglevel>.\n"
" -t Dump information to stdout as if you were a linked-in\n"
" server.\n"
" -F Don't fork() when starting up. Use this when running\n"
" RabbitIRCd under gdb or when playing around with settings\n"
" on a non-production setup.\n"
"\n",
argv0, CONFIGFILE);
(void)printf("Server not started\n\n");
return (-1);
}
char chess[] = {
85, 110, 114, 101, 97, 108, 0
};
static void version_check_logerror(char *fmt, ...)
{
va_list va;
char buf[1024];
va_start(va, fmt);
vsnprintf(buf, sizeof(buf), fmt, va);
va_end(va);
fprintf(stderr, "[!!!] %s\n", buf);
}
/** Ugly version checker that ensures ssl/curl runtime libraries match the
* version we compiled for.
*/
static void do_version_check()
{
const char *compiledfor, *runtime;
int error = 0;
compiledfor = OPENSSL_VERSION_TEXT;
runtime = SSLeay_version(SSLEAY_VERSION);
if (strcasecmp(compiledfor, runtime))
{
version_check_logerror("OpenSSL version mismatch: compiled for '%s', library is '%s'",
compiledfor, runtime);
error=1;
}
if (error)
{
version_check_logerror("Header<->library mismatches can make RabbitIRCd *CRASH*! "
"Make sure you don't have multiple versions of openssl installed (eg: "
"one in /usr and one in /usr/local). And, if you recently upgraded them, "
"be sure to recompile the ircd.");
tainted = 1;
}
}
extern MODVAR Event *events;
extern struct MODVAR ThrottlingBucket *ThrottlingHash[THROTTLING_HASH_SIZE+1];
/** This functions resets a couple of timers and does other things that
* are absolutely cruicial when the clock is adjusted - particularly
* when the clock goes backwards. -- Syzop
*/
void fix_timers(void)
{
int i, cnt;
aClient *acptr;
Event *e;
struct ThrottlingBucket *n;
struct ThrottlingBucket z = { NULL, NULL, {0}, 0, 0};
list_for_each_entry(acptr, &lclient_list, lclient_node)
{
if (acptr->since > TStime())
{
Debug((DEBUG_DEBUG, "fix_timers(): %s: acptr->since %ld -> %ld",
acptr->name, acptr->since, TStime()));
acptr->since = TStime();
}
if (acptr->lasttime > TStime())
{
Debug((DEBUG_DEBUG, "fix_timers(): %s: acptr->lasttime %ld -> %ld",
acptr->name, acptr->lasttime, TStime()));
acptr->lasttime = TStime();
}
if (acptr->last > TStime())
{
Debug((DEBUG_DEBUG, "fix_timers(): %s: acptr->last %ld -> %ld",
acptr->name, acptr->last, TStime()));
acptr->last = TStime();
}
/* users */
if (MyClient(acptr))
{
if (acptr->nextnick > TStime())
{
Debug((DEBUG_DEBUG, "fix_timers(): %s: acptr->nextnick %ld -> %ld",
acptr->name, acptr->nextnick, TStime()));
acptr->nextnick = TStime();
}
if (acptr->nexttarget > TStime())
{
Debug((DEBUG_DEBUG, "fix_timers(): %s: acptr->nexttarget %ld -> %ld",
acptr->name, acptr->nexttarget, TStime()));
acptr->nexttarget = TStime();
}
}
}
/* Reset all event timers */
for (e = events; e; e = e->next)
{
if (e->last > TStime())
{
Debug((DEBUG_DEBUG, "fix_timers(): %s: e->last %ld -> %ld",
e->name, e->last, TStime()-1));
e->last = TStime()-1;
}
}
/* Just flush all throttle stuff... */
cnt = 0;
for (i = 0; i < THROTTLING_HASH_SIZE; i++)
for (n = ThrottlingHash[i]; n; n = n->next)
{
z.next = (struct ThrottlingBucket *) DelListItem(n, ThrottlingHash[i]);
cnt++;
MyFree(n);
n = &z;
}
Debug((DEBUG_DEBUG, "fix_timers(): removed %d throttling item(s)", cnt));
}
static void generate_cloakkeys()
{
/* Generate 3 cloak keys */
#define GENERATE_CLOAKKEY_MINLEN 16
#define GENERATE_CLOAKKEY_MAXLEN 32 /* Length of cloak keys to generate. */
char keyBuf[GENERATE_CLOAKKEY_MAXLEN + 1];
int keyNum;
int keyLen;
int charIndex;
int value;
short has_upper;
short has_lower;
short has_num;
fprintf(stderr, "Here are 3 random cloak keys:\n");
for (keyNum = 0; keyNum < 3; ++keyNum)
{
has_upper = 0;
has_lower = 0;
has_num = 0;
keyLen = (getrandom8() % (GENERATE_CLOAKKEY_MAXLEN - GENERATE_CLOAKKEY_MINLEN + 1)) + GENERATE_CLOAKKEY_MINLEN;
for (charIndex = 0; charIndex < keyLen; ++charIndex)
{
switch (getrandom8() % 3)
{
case 0: /* Uppercase. */
keyBuf[charIndex] = (char)('A' + (getrandom8() % ('Z' - 'A')));
has_upper = 1;
break;
case 1: /* Lowercase. */
keyBuf[charIndex] = (char)('a' + (getrandom8() % ('z' - 'a')));
has_lower = 1;
break;
case 2: /* Digit. */
keyBuf[charIndex] = (char)('0' + (getrandom8() % ('9' - '0')));
has_num = 1;
break;
}
}
keyBuf[keyLen] = '\0';
if (has_upper && has_lower && has_num)
(void)fprintf(stderr, "%s\n", keyBuf);
else
/* Try again. For this reason, keyNum must be signed. */
keyNum--;
}
}
/* MY tdiff... because 'double' sucks.
* This should work until 2038, and very likely after that as well
* because 'long' should be 64 bit on all systems by then... -- Syzop
*/
#define mytdiff(a, b) ((long)a - (long)b)
int main(int argc, char *argv[])
{
uid_t uid, euid;
gid_t gid, egid;
TS delay = 0;
struct passwd *pw;
struct group *gr;
#ifdef HAVE_PSTAT
union pstun pstats;
#endif
int portarg = 0;
#ifdef FORCE_CORE
struct rlimit corelim;
#endif
memset(&botmotd, '\0', sizeof(aMotdFile));
memset(&rules, '\0', sizeof(aMotdFile));
memset(&opermotd, '\0', sizeof(aMotdFile));
memset(&motd, '\0', sizeof(aMotdFile));
memset(&smotd, '\0', sizeof(aMotdFile));
memset(&svsmotd, '\0', sizeof(aMotdFile));
SetupEvents();
sbrk0 = (char *)sbrk((size_t)0);
uid = getuid();
euid = geteuid();
gid = getgid();
egid = getegid();
#ifndef IRC_USER
if (!euid)
{
fprintf(stderr,
"WARNING: You are running UnrealIRCd as root and it is not\n"
" configured to drop priviliges. This is _very_ dangerous,\n"
" as any compromise of your UnrealIRCd is the same as\n"
" giving a cracker root SSH access to your box.\n"
" You should either start UnrealIRCd under a different\n"
" account than root, or set IRC_USER in include/config.h\n"
" to a nonprivileged username and recompile.\n");
}
#endif /* IRC_USER */
# ifdef PROFIL
(void)monstartup(0, etext);
(void)moncontrol(1);
(void)signal(SIGUSR1, s_monitor);
# endif
#if defined(IRC_USER) && defined(IRC_GROUP)
if ((int)getuid() == 0) {
pw = getpwnam(IRC_USER);
gr = getgrnam(IRC_GROUP);
if ((pw == NULL) || (gr == NULL)) {
fprintf(stderr, "ERROR: Unable to lookup to specified user (IRC_USER) or group (IRC_GROUP): %s\n", strerror(errno));
exit(-1);
} else {
irc_uid = pw->pw_uid;
irc_gid = gr->gr_gid;
}
}
#endif
#ifdef CHROOTDIR
if (chdir(dpath)) {
perror("chdir");
fprintf(stderr, "ERROR: Unable to change to directory '%s'\n", dpath);
exit(-1);
}
if (geteuid() != 0)
fprintf(stderr, "WARNING: IRCd compiled with CHROOTDIR but effective user id is not root!? "
"Booting is very likely to fail...\n");
init_resolver(1);
{
struct stat sb;
mode_t umaskold;
umaskold = umask(0);
if (mkdir("dev", S_IRUSR|S_IWUSR|S_IXUSR|S_IXGRP|S_IXOTH) != 0 && errno != EEXIST)
{
fprintf(stderr, "ERROR: Cannot mkdir dev: %s\n", strerror(errno));
exit(5);
}
if (stat("/dev/urandom", &sb) != 0)
{
fprintf(stderr, "ERROR: Cannot stat /dev/urandom: %s\n", strerror(errno));
exit(5);
}
if (mknod("dev/urandom", sb.st_mode, sb.st_rdev) != 0 && errno != EEXIST)
{
fprintf(stderr, "ERROR: Cannot mknod dev/urandom: %s\n", strerror(errno));
exit(5);
}
if (stat("/dev/null", &sb) != 0)
{
fprintf(stderr, "ERROR: Cannot stat /dev/null: %s\n", strerror(errno));
exit(5);
}
if (mknod("dev/null", sb.st_mode, sb.st_rdev) != 0 && errno != EEXIST)
{
fprintf(stderr, "ERROR: Cannot mknod dev/null: %s\n", strerror(errno));
exit(5);
}
if (stat("/dev/tty", &sb) != 0)
{
fprintf(stderr, "ERROR: Cannot stat /dev/tty: %s\n", strerror(errno));
exit(5);
}
if (mknod("dev/tty", sb.st_mode, sb.st_rdev) != 0 && errno != EEXIST)
{
fprintf(stderr, "ERROR: Cannot mknod dev/tty: %s\n", strerror(errno));
exit(5);
}
umask(umaskold);
}
if (chroot(DPATH)) {
(void)fprintf(stderr, "ERROR: Cannot (chdir/)chroot to directory '%s'\n", dpath);
exit(5);
}
#endif /*CHROOTDIR*/
myargv = argv;
(void)umask(077); /* better safe than sorry --SRB */
bzero((char *)&me, sizeof(me));
bzero(&StatsZ, sizeof(StatsZ));
setup_signals();
charsys_reset();
memset(&IRCstats, '\0', sizeof(ircstats));
IRCstats.servers = 1;
mp_pool_init();
dbuf_init();
tkl_init();
umode_init();
extcmode_init();
extban_init();
clear_scache_hash_table();
#ifdef FORCE_CORE
corelim.rlim_cur = corelim.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &corelim))
printf("unlimit core size failed; errno = %d\n", errno);
#endif
/*
* ** All command line parameters have the syntax "-fstring"
* ** or "-f string" (e.g. the space is optional). String may
* ** be empty. Flag characters cannot be concatenated (like
* ** "-fxyz"), it would conflict with the form "-fstring".
*/
while (--argc > 0 && (*++argv)[0] == '-') {
char *p = argv[0] + 1;
int flag = *p++;
if (flag == '\0' || *p == '\0') {
if (argc > 1 && argv[1][0] != '-') {
p = *++argv;
argc -= 1;
} else
p = "";
}
switch (flag) {
case 'a':
bootopt |= BOOT_AUTODIE;
break;
case 'c':
bootopt |= BOOT_CONSOLE;
break;
case 'q':
bootopt |= BOOT_QUICK;
break;
case 'd':
if (setuid((uid_t) uid) == -1)
printf("WARNING: Could not drop privileges: %s\n", strerror(errno));
dpath = p;
break;
case 'F':
bootopt |= BOOT_NOFORK;
break;
case 'f':
#ifndef CMDLINE_CONFIG
if ((uid == euid) && (gid == egid))
configfile = p;
else
printf("ERROR: Command line config with a setuid/setgid ircd is not allowed");
#else
if (setuid((uid_t) uid) == -1)
printf("WARNING: could not drop privileges: %s\n", strerror(errno));
configfile = p;
#endif
break;
case 'h':
if (!strchr(p, '.')) {
(void)printf
("ERROR: %s is not valid: Server names must contain at least 1 \".\"\n",
p);
exit(1);
}
strlcpy(me.name, p, sizeof(me.name));
break;
case 'P':{
const char *type;
const char *result;
srandom(TStime());
if ((auth_lookup_ops(p)) == NULL) {
printf("No such auth type %s\n", p);
exit(0);
}
type = p;
p = *++argv;
argc--;
if (!(result = Auth_Make(type, p))) {
printf("Authentication failed\n");
exit(0);
}
printf("Encrypted password is: %s\n", result);
exit(0);
break;
}
case 'p':
if ((portarg = atoi(p)) > 0)
portnum = portarg;
break;
case 's':
(void)printf("sizeof(aClient) == %ld\n",
(long)sizeof(aClient));
(void)printf("sizeof(aChannel) == %ld\n",
(long)sizeof(aChannel));
(void)printf("sizeof(aServer) == %ld\n",
(long)sizeof(aServer));
(void)printf("sizeof(Link) == %ld\n",
(long)sizeof(Link));
(void)printf("sizeof(anUser) == %ld\n",
(long)sizeof(anUser));
(void)printf("sizeof(aTKline) == %ld\n",
(long)sizeof(aTKline));
(void)printf("sizeof(struct ircstatsx) == %ld\n",
(long)sizeof(struct ircstatsx));
(void)printf("aClient remote == %ld\n",
(long)CLIENT_REMOTE_SIZE);
exit(0);
break;
case 't':
if (setuid((uid_t) uid) == -1)
printf("WARNING: Could not drop privileges: %s\n", strerror(errno));
bootopt |= BOOT_TTY;
break;
case 'v':
(void)printf("%s build %s\n", version, buildid);
exit(0);
case 'C':
config_verbose = atoi(p);
break;
case 'x':
#ifdef DEBUGMODE
if (setuid((uid_t) uid) == -1)
printf("WARNING: Could not drop privileges: %s\n", strerror(errno));
debuglevel = atoi(p);
debugmode = *p ? p : "0";
bootopt |= BOOT_DEBUG;
#else
(void)fprintf(stderr,
"%s: DEBUGMODE must be defined for -x y\n",
myargv[0]);
exit(0);
#endif
break;
case 'k':
generate_cloakkeys();
exit(0);
default:
return bad_command(myargv[0]);
break;
}
}
do_version_check();
#ifndef CHROOTDIR
if (chdir(dpath)) {
perror("chdir");
fprintf(stderr, "ERROR: Unable to change to directory '%s'\n", dpath);
exit(-1);
}
#endif
mkdir("tmp", S_IRUSR|S_IWUSR|S_IXUSR); /* Create the tmp dir, if it doesn't exist */
/*
* didn't set debuglevel
*/
/*
* but asked for debugging output to tty
*/
if ((debuglevel < 0) && (bootopt & BOOT_TTY)) {
(void)fprintf(stderr,
"you specified -t without -x. use -x <n>\n");
exit(-1);
}
if (argc > 0)
return bad_command(myargv[0]); /* This should exit out */
fprintf(stderr, "rabbitircd %s is starting.\n", VERSIONONLY);
fprintf(stderr, " using %s\n", tre_version());
fprintf(stderr, " using %s\n", SSLeay_version(SSLEAY_VERSION));
fprintf(stderr, "\n");
clear_client_hash_table();
clear_channel_hash_table();
clear_watch_hash_table();
bzero(&loop, sizeof(loop));
init_CommandHash();
initlists();
initwhowas();
initstats();
DeleteTempModules();
booted = FALSE;
/* Hack to stop people from being able to read the config file */
#if !defined(OSXTIGER) && DEFAULT_PERMISSIONS != 0
chmod(CPATH, DEFAULT_PERMISSIONS);
#endif
init_dynconf();
#ifdef STATIC_LINKING
{
ModuleInfo ModCoreInfo;
ModCoreInfo.size = sizeof(ModuleInfo);
ModCoreInfo.module_load = 0;
ModCoreInfo.handle = NULL;
l_commands_Test(&ModCoreInfo);
}
#endif
/*
* Add default class
*/
default_class =
(ConfigItem_class *) MyMallocEx(sizeof(ConfigItem_class));
default_class->flag.permanent = 1;
default_class->pingfreq = PINGFREQUENCY;
default_class->maxclients = 100;
default_class->sendq = MAXSENDQLENGTH;
default_class->name = "default";
AddListItem(default_class, conf_class);
if (init_conf(configfile, 0) < 0)
{
exit(-1);
}
booted = TRUE;
make_umodestr();
make_cmodestr();
make_extcmodestr();
make_extbanstr();
isupport_init();
if (!find_Command_simple("AWAY") /*|| !find_Command_simple("KILL") ||
!find_Command_simple("OPER") || !find_Command_simple("PING")*/)
{
config_error("Someone forgot to load modules with proper commands in them. READ THE DOCUMENTATION");
exit(-4);
}
fprintf(stderr, "* Initializing SSL.\n");
init_ssl();
fprintf(stderr,
"* Dynamic configuration initialized .. booting IRCd.\n");
fprintf(stderr,
"---------------------------------------------------------------------\n");
open_debugfile();
if (portnum < 0)
portnum = PORTNUM;
me.port = portnum;
(void)init_sys();
me.flags = FLAGS_LISTEN;
me.fd = -1;
SetMe(&me);
make_server(&me);
#ifdef HAVE_SYSLOG
openlog("ircd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
#endif
/*
* Put in our info
*/
strlcpy(me.info, conf_me->info, sizeof(me.info));
strlcpy(me.name, conf_me->name, sizeof(me.name));
strlcpy(me.id, conf_me->sid, sizeof(me.name));
uid_init();
run_configuration();
ircd_log(LOG_ERROR, "UnrealIRCd started.");
read_motd(conf_files->botmotd_file, &botmotd);
read_motd(conf_files->rules_file, &rules);
read_motd(conf_files->opermotd_file, &opermotd);
read_motd(conf_files->motd_file, &motd);
read_motd(conf_files->smotd_file, &smotd);
read_motd(conf_files->svsmotd_file, &svsmotd);
me.hopcount = 0;
me.authfd = -1;
me.user = NULL;
me.from = &me;
/*
* This listener will never go away
*/
me_hash = find_or_add(me.name);
me.serv->up = me_hash;
timeofday = time(NULL);
me.lasttime = me.since = me.firsttime = TStime();
(void)add_to_client_hash_table(me.name, &me);
(void)add_to_id_hash_table(me.id, &me);
list_add(&me.client_node, &global_server_list);
#ifndef NO_FORKING
if (!(bootopt & BOOT_NOFORK))
if (fork())
exit(0);
#endif
(void)ircsnprintf(REPORT_DO_DNS, sizeof(REPORT_DO_DNS), ":%s %s", me.name, BREPORT_DO_DNS);
(void)ircsnprintf(REPORT_FIN_DNS, sizeof(REPORT_FIN_DNS), ":%s %s", me.name, BREPORT_FIN_DNS);
(void)ircsnprintf(REPORT_FIN_DNSC, sizeof(REPORT_FIN_DNSC), ":%s %s", me.name, BREPORT_FIN_DNSC);
(void)ircsnprintf(REPORT_FAIL_DNS, sizeof(REPORT_FAIL_DNS), ":%s %s", me.name, BREPORT_FAIL_DNS);
(void)ircsnprintf(REPORT_DO_ID, sizeof(REPORT_DO_ID), ":%s %s", me.name, BREPORT_DO_ID);
(void)ircsnprintf(REPORT_FIN_ID, sizeof(REPORT_FIN_ID), ":%s %s", me.name, BREPORT_FIN_ID);
(void)ircsnprintf(REPORT_FAIL_ID, sizeof(REPORT_FAIL_ID), ":%s %s", me.name, BREPORT_FAIL_ID);
R_do_dns = strlen(REPORT_DO_DNS);
R_fin_dns = strlen(REPORT_FIN_DNS);
R_fin_dnsc = strlen(REPORT_FIN_DNSC);
R_fail_dns = strlen(REPORT_FAIL_DNS);
R_do_id = strlen(REPORT_DO_ID);
R_fin_id = strlen(REPORT_FIN_ID);
R_fail_id = strlen(REPORT_FAIL_ID);
#if !defined(IRC_USER)
if ((uid != euid) && !euid) {
(void)fprintf(stderr,
"ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
exit(-1);
}
#endif
#if defined(IRC_USER) && defined(IRC_GROUP)
if ((int)getuid() == 0) {
/* NOTE: irc_uid/irc_gid have been looked up earlier, before the chrooting code */
if ((irc_uid == 0) || (irc_gid == 0)) {
(void)fprintf(stderr,
"ERROR: SETUID and SETGID have not been set properly"
"\nPlease read your documentation\n(HINT: IRC_USER and IRC_GROUP in include/config.h cannot be root/wheel)\n");
exit(-1);
} else {
/*
* run as a specified user
*/
(void)fprintf(stderr, "WARNING: ircd invoked as root\n");
(void)fprintf(stderr, " changing to uid %d\n", irc_uid);
(void)fprintf(stderr, " changing to gid %d\n", irc_gid);
if (setgid(irc_gid))
{
fprintf(stderr, "ERROR: Unable to change group: %s\n", strerror(errno));
exit(-1);
}
if (setuid(irc_uid))
{
fprintf(stderr, "ERROR: Unable to change userid: %s\n", strerror(errno));
exit(-1);
}
}
}
#endif
fix_timers(); /* Fix timers AFTER reading tune file */
write_pidfile();
Debug((DEBUG_NOTICE, "Server ready..."));
init_throttling_hash();
init_modef();
loop.ircd_booted = 1;
#if defined(HAVE_SETPROCTITLE)
setproctitle("%s", me.name);
#elif defined(HAVE_PSTAT)
pstats.pst_command = me.name;
pstat(PSTAT_SETCMD, pstats, strlen(me.name), 0, 0);
#elif defined(HAVE_PSSTRINGS)
PS_STRINGS->ps_nargvstr = 1;
PS_STRINGS->ps_argvstr = me.name;
#endif
module_loadall(0);
#ifdef STATIC_LINKING
l_commands_Load(0);
#endif
for (;;)
{
#define NEGATIVE_SHIFT_WARN -15
#define POSITIVE_SHIFT_WARN 20
timeofday = time(NULL);
if (oldtimeofday == 0)
oldtimeofday = timeofday; /* pretend everything is ok the first time.. */
if (mytdiff(timeofday, oldtimeofday) < NEGATIVE_SHIFT_WARN) {
/* tdiff = # of seconds of time set backwards (positive number! eg: 60) */
long tdiff = oldtimeofday - timeofday;
ircd_log(LOG_ERROR, "WARNING: Time running backwards! Clock set back ~%ld seconds (%ld -> %ld)",
tdiff, oldtimeofday, timeofday);
ircd_log(LOG_ERROR, "[TimeShift] Resetting a few timers to prevent IRCd freeze!");
sendto_realops("WARNING: Time running backwards! Clock set back ~%ld seconds (%ld -> %ld)",
tdiff, oldtimeofday, timeofday);
sendto_realops("Incorrect time for IRC servers is a serious problem. "
"Time being set backwards (by resetting the clock) is "
"even more serious and can cause clients to freeze, channels to be "
"taken over, and other issues.");
sendto_realops("Please be sure your clock is always synchronized before "
"the IRCd is started.");
sendto_realops("[TimeShift] Resetting a few timers to prevent IRCd freeze!");
fix_timers();
} else
if (mytdiff(timeofday, oldtimeofday) > POSITIVE_SHIFT_WARN) /* do not set too low or you get false positives */
{
/* tdiff = # of seconds of time set forward (eg: 60) */
long tdiff = timeofday - oldtimeofday;
ircd_log(LOG_ERROR, "WARNING: Time jumped ~%ld seconds ahead! (%ld -> %ld)",
tdiff, oldtimeofday, timeofday);
ircd_log(LOG_ERROR, "[TimeShift] Resetting some timers!");
sendto_realops("WARNING: Time jumped ~%ld seconds ahead! (%ld -> %ld)",
tdiff, oldtimeofday, timeofday);
sendto_realops("Incorrect time for IRC servers is a serious problem. "
"Time being adjusted (by resetting the clock) "
"more than a few seconds forward/backward can lead to serious issues.");
sendto_realops("Please be sure your clock is always synchronized before "
"the IRCd is started.");
sendto_realops("[TimeShift] Resetting some timers!");
fix_timers();
}
if (highesttimeofday+NEGATIVE_SHIFT_WARN > timeofday)
{
if (lasthighwarn > timeofday)
lasthighwarn = timeofday;
if (timeofday - lasthighwarn > 300)
{
ircd_log(LOG_ERROR, "[TimeShift] The (IRCd) clock was set backwards. "
"Waiting for time to be OK again. This will be in %ld seconds",
highesttimeofday - timeofday);
sendto_realops("[TimeShift] The (IRCd) clock was set backwards. Timers, nick- "
"and channel-timestamps are possibly incorrect. This message will "
"repeat itself until we catch up with the original time, which will be "
"in %ld seconds", highesttimeofday - timeofday);
lasthighwarn = timeofday;
}
} else {
highesttimeofday = timeofday;
}
oldtimeofday = timeofday;
LockEventSystem();
DoEvents();
UnlockEventSystem();
/*
* ** Run through the hashes and check lusers every
* ** second
* ** also check for expiring glines
*/
if (IRCstats.clients > IRCstats.global_max)
IRCstats.global_max = IRCstats.clients;
if (IRCstats.me_clients > IRCstats.me_max)
IRCstats.me_max = IRCstats.me_clients;
/*
* ** Adjust delay to something reasonable [ad hoc values]
* ** (one might think something more clever here... --msa)
* ** We don't really need to check that often and as long
* ** as we don't delay too long, everything should be ok.
* ** waiting too long can cause things to timeout...
* ** i.e. PINGS -> a disconnection :(
* ** - avalon
*/
if (delay < 1)
delay = 1;
else
delay = MIN(delay, TIMESEC);
fd_select(delay * 1000);
timeofday = time(NULL);
/*
* Debug((DEBUG_DEBUG, "Got message(s)"));
*/
/*
* ** ...perhaps should not do these loops every time,
* ** but only if there is some chance of something
* ** happening (but, note that conf->hold times may
* ** be changed elsewhere--so precomputed next event
* ** time might be too far away... (similarly with
* ** ping times) --msa
*/
if (dorehash)
{
(void)rehash(&me, &me, 1);
dorehash = 0;
}
if (dorestart)
{
server_reboot("SIGINT");
}
}
}
/*
* open_debugfile
*
* If the -t option is not given on the command line when the server is
* started, all debugging output is sent to the file set by LPATH in config.h
* Here we just open that file and make sure it is opened to fd 2 so that
* any fprintf's to stderr also goto the logfile. If the debuglevel is not
* set from the command line by -x, use /dev/null as the dummy logfile as long
* as DEBUGMODE has been defined, else dont waste the fd.
*/
static void open_debugfile(void)
{
#ifdef DEBUGMODE
int fd;
aClient *cptr;
if (debuglevel >= 0) {
cptr = make_client(NULL, NULL);
cptr->fd = 2;
SetLog(cptr);
cptr->port = debuglevel;
cptr->flags = 0;
(void)strlcpy(cptr->sockhost, me.sockhost,
sizeof cptr->sockhost);
(void)printf("isatty = %d ttyname = %#x\n",
isatty(2), (u_int)(uint64_t)ttyname(2));
if (!(bootopt & BOOT_TTY)) { /* leave debugging output on fd 2 */
if (truncate(LOGFILE, 0) <0) exit(-1);
if ((fd = open(LOGFILE, O_WRONLY | O_CREAT, 0600)) < 0)
if ((fd = open("/dev/null", O_WRONLY)) < 0)
exit(-1);
if (fd != 2) {
(void)dup2(fd, 2);
(void)close(fd);
}
strlcpy(cptr->name, LOGFILE, sizeof(cptr->name));
} else if (isatty(2) && ttyname(2))
strlcpy(cptr->name, ttyname(2), sizeof(cptr->name));
else
strlcpy(cptr->name, "FD2-Pipe", sizeof(cptr->name));
Debug((DEBUG_FATAL,
"Debug: File <%s> Level: %d at %s", cptr->name,
cptr->port, myctime(time(NULL))));
}
#endif
}
static void setup_signals()
{
#ifdef POSIX_SIGNALS
struct sigaction act;
act.sa_handler = SIG_IGN;
act.sa_flags = 0;
(void)sigemptyset(&act.sa_mask);
(void)sigaddset(&act.sa_mask, SIGPIPE);
(void)sigaddset(&act.sa_mask, SIGALRM);
# ifdef SIGWINCH
(void)sigaddset(&act.sa_mask, SIGWINCH);
(void)sigaction(SIGWINCH, &act, NULL);
# endif
(void)sigaction(SIGPIPE, &act, NULL);
act.sa_handler = dummy;
(void)sigaction(SIGALRM, &act, NULL);
act.sa_handler = s_rehash;
(void)sigemptyset(&act.sa_mask);
(void)sigaddset(&act.sa_mask, SIGHUP);
(void)sigaction(SIGHUP, &act, NULL);
act.sa_handler = s_restart;
(void)sigaddset(&act.sa_mask, SIGINT);
(void)sigaction(SIGINT, &act, NULL);
act.sa_handler = s_die;
(void)sigaddset(&act.sa_mask, SIGTERM);
(void)sigaction(SIGTERM, &act, NULL);
#else
# ifndef HAVE_RELIABLE_SIGNALS
(void)signal(SIGPIPE, dummy);
# ifdef SIGWINCH
(void)signal(SIGWINCH, dummy);
# endif
# else
# ifdef SIGWINCH
(void)signal(SIGWINCH, SIG_IGN);
# endif
(void)signal(SIGPIPE, SIG_IGN);
# endif
(void)signal(SIGALRM, dummy);
(void)signal(SIGHUP, s_rehash);
(void)signal(SIGTERM, s_die);
(void)signal(SIGINT, s_restart);
#endif
}
| gpl-2.0 |
masterfeizz/EDuke3D | source/sw/src/copysect.c | 1 | 9430 | //-------------------------------------------------------------------------
/*
Copyright (C) 1997, 2005 - 3D Realms Entertainment
This file is part of Shadow Warrior version 1.2
Shadow Warrior 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.
Original Source: 1997 - Frank Maddin and Jim Norwood
Prepared for public release: 03/28/2005 - Charlie Wiederhold, 3D Realms
*/
//-------------------------------------------------------------------------
#include "build.h"
#include "names2.h"
#include "game.h"
#include "tags.h"
#include "weapon.h"
#include "sprite.h"
#include "track.h"
void CopySectorWalls(short dest_sectnum, short src_sectnum)
{
short dest_wall_num, src_wall_num, start_wall;
dest_wall_num = sector[dest_sectnum].wallptr;
src_wall_num = sector[src_sectnum].wallptr;
start_wall = dest_wall_num;
do
{
wall[dest_wall_num].picnum = wall[src_wall_num].picnum;
wall[dest_wall_num].xrepeat = wall[src_wall_num].xrepeat;
wall[dest_wall_num].yrepeat = wall[src_wall_num].yrepeat;
wall[dest_wall_num].overpicnum = wall[src_wall_num].overpicnum;
wall[dest_wall_num].pal = wall[src_wall_num].pal;
wall[dest_wall_num].cstat = wall[src_wall_num].cstat;
wall[dest_wall_num].shade = wall[src_wall_num].shade;
wall[dest_wall_num].xpanning = wall[src_wall_num].xpanning;
wall[dest_wall_num].ypanning = wall[src_wall_num].ypanning;
wall[dest_wall_num].hitag = wall[src_wall_num].hitag;
wall[dest_wall_num].lotag = wall[src_wall_num].lotag;
wall[dest_wall_num].extra = wall[src_wall_num].extra;
if (wall[dest_wall_num].nextwall >= 0 && wall[src_wall_num].nextwall >= 0)
{
wall[wall[dest_wall_num].nextwall].picnum = wall[wall[src_wall_num].nextwall].picnum;
wall[wall[dest_wall_num].nextwall].xrepeat = wall[wall[src_wall_num].nextwall].xrepeat;
wall[wall[dest_wall_num].nextwall].yrepeat = wall[wall[src_wall_num].nextwall].yrepeat;
wall[wall[dest_wall_num].nextwall].overpicnum = wall[wall[src_wall_num].nextwall].overpicnum;
wall[wall[dest_wall_num].nextwall].pal = wall[wall[src_wall_num].nextwall].pal;
wall[wall[dest_wall_num].nextwall].cstat = wall[wall[src_wall_num].nextwall].cstat;
wall[wall[dest_wall_num].nextwall].shade = wall[wall[src_wall_num].nextwall].shade;
wall[wall[dest_wall_num].nextwall].xpanning = wall[wall[src_wall_num].nextwall].xpanning;
wall[wall[dest_wall_num].nextwall].ypanning = wall[wall[src_wall_num].nextwall].ypanning;
wall[wall[dest_wall_num].nextwall].hitag = wall[wall[src_wall_num].nextwall].hitag;
wall[wall[dest_wall_num].nextwall].lotag = wall[wall[src_wall_num].nextwall].lotag;
wall[wall[dest_wall_num].nextwall].extra = wall[wall[src_wall_num].nextwall].extra;
}
dest_wall_num = wall[dest_wall_num].point2;
src_wall_num = wall[src_wall_num].point2;
}
while (dest_wall_num != start_wall);
}
void CopySectorMatch(short match)
{
short ed,nexted,ss,nextss;
SPRITEp dest_sp, src_sp;
SECTORp dsectp,ssectp;
short kill, nextkill;
SPRITEp k;
TRAVERSE_SPRITE_STAT(headspritestat[STAT_COPY_DEST], ed, nexted)
{
dest_sp = &sprite[ed];
dsectp = §or[dest_sp->sectnum];
if (match != sprite[ed].lotag)
continue;
TRAVERSE_SPRITE_STAT(headspritestat[STAT_COPY_SOURCE], ss, nextss)
{
src_sp = &sprite[ss];
if (SP_TAG2(src_sp) == SPRITE_TAG2(ed) &&
SP_TAG3(src_sp) == SPRITE_TAG3(ed))
{
short src_move, nextsrc_move;
ssectp = §or[src_sp->sectnum];
// !!!!!AAAAAAAAAAAAAAAAAAAAAAHHHHHHHHHHHHHHHHHHHHHH
// Don't kill anything you don't have to
// this wall killing things on a Queue causing
// invalid situations
#if 1
// kill all sprites in the dest sector that need to be
TRAVERSE_SPRITE_SECT(headspritesect[dest_sp->sectnum], kill, nextkill)
{
k = &sprite[kill];
// kill anything not invisible
if (!TEST(k->cstat, CSTAT_SPRITE_INVISIBLE))
{
if (User[kill])
{
// be safe with the killing
//SetSuicide(kill);
}
else
{
SpriteQueueDelete(kill); // new function to allow killing - hopefully
KillSprite(kill);
}
}
}
#endif
CopySectorWalls(dest_sp->sectnum, src_sp->sectnum);
TRAVERSE_SPRITE_SECT(headspritesect[src_sp->sectnum], src_move, nextsrc_move)
{
// don't move ST1 Copy Tags
if (SPRITE_TAG1(src_move) != SECT_COPY_SOURCE)
{
int sx,sy,dx,dy,src_xoff,src_yoff,trash;
// move sprites from source to dest - use center offset
// get center of src and dest sect
SectorMidPoint(src_sp->sectnum, &sx, &sy, &trash);
SectorMidPoint(dest_sp->sectnum, &dx, &dy, &trash);
// get offset
src_xoff = sx - sprite[src_move].x;
src_yoff = sy - sprite[src_move].y;
// move sprite to dest sector
sprite[src_move].x = dx - src_xoff;
sprite[src_move].y = dy - src_yoff;
// change sector
changespritesect(src_move, dest_sp->sectnum);
// check to see if it moved on to a sector object
if (TEST(sector[dest_sp->sectnum].extra, SECTFX_SECTOR_OBJECT))
{
SECTOR_OBJECTp sop;
extern int GlobSpeedSO;
// find and add sprite to SO
sop = DetectSectorObject(§or[sprite[src_move].sectnum]);
AddSpriteToSectorObject(src_move, sop);
// update sprites postions so they aren't in the
// wrong place for one frame
GlobSpeedSO = 0;
RefreshPoints(sop, 0, 0, TRUE);
}
}
}
// copy sector user if there is one
if (SectUser[src_sp->sectnum] || SectUser[dest_sp->sectnum])
{
SECT_USERp ssectu = GetSectUser(src_sp->sectnum);
SECT_USERp dsectu = GetSectUser(dest_sp->sectnum);
memcpy(dsectu, ssectu, sizeof(SECT_USER));
}
dsectp->hitag = ssectp->hitag;
dsectp->lotag = ssectp->lotag;
dsectp->floorz = ssectp->floorz;
dsectp->ceilingz = ssectp->ceilingz;
dsectp->floorshade = ssectp->floorshade;
dsectp->ceilingshade = ssectp->ceilingshade;
dsectp->floorpicnum = ssectp->floorpicnum;
dsectp->ceilingpicnum = ssectp->ceilingpicnum;
dsectp->floorheinum = ssectp->floorheinum;
dsectp->ceilingheinum = ssectp->ceilingheinum;
dsectp->floorpal = ssectp->floorpal;
dsectp->ceilingpal = ssectp->ceilingpal;
dsectp->floorxpanning = ssectp->floorxpanning;
dsectp->ceilingxpanning = ssectp->ceilingxpanning;
dsectp->floorypanning = ssectp->floorypanning;
dsectp->ceilingypanning = ssectp->ceilingypanning;
dsectp->floorstat = ssectp->floorstat;
dsectp->ceilingstat = ssectp->ceilingstat;
dsectp->extra = ssectp->extra;
dsectp->visibility = ssectp->visibility;
}
}
}
// do this outside of processing loop for safety
// kill all matching dest
TRAVERSE_SPRITE_STAT(headspritestat[STAT_COPY_DEST], ed, nexted)
{
if (match == sprite[ed].lotag)
KillSprite(ed);
}
// kill all matching sources
TRAVERSE_SPRITE_STAT(headspritestat[STAT_COPY_SOURCE], ss, nextss)
{
if (match == sprite[ss].lotag)
KillSprite(ss);
}
}
| gpl-2.0 |
pastewka/lammps | lib/kokkos/core/src/eti/OpenMP/Kokkos_OpenMP_ViewCopyETIInst_int_double_LayoutRight_Rank4.cpp | 1 | 2524 | //@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Kokkos is licensed under 3-clause BSD terms of use:
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
#define KOKKOS_IMPL_COMPILING_LIBRARY true
#include <Kokkos_Core.hpp>
namespace Kokkos {
namespace Impl {
KOKKOS_IMPL_VIEWCOPY_ETI_INST(double****, LayoutRight, LayoutRight, OpenMP, int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(double****, LayoutRight, LayoutLeft, OpenMP, int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(double****, LayoutRight, LayoutStride, OpenMP,
int)
KOKKOS_IMPL_VIEWFILL_ETI_INST(double****, LayoutRight, OpenMP, int)
} // namespace Impl
} // namespace Kokkos
| gpl-2.0 |
tedchoward/Frontier | Common/source/opwinpad.c | 1 | 15379 |
/* $Id$ */
/******************************************************************************
UserLand Frontier(tm) -- High performance Web content management,
object database, system-level and Internet scripting environment,
including source code editing and debugging.
Copyright (C) 1992-2004 UserLand Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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 <standard.h>
#include "config.h"
#include "dialogs.h"
#include "memory.h"
#include "strings.h"
#include "quickdraw.h"
#include "font.h"
#include "cursor.h"
#include "file.h"
#include "ops.h"
#include "resources.h"
#include "search.h"
#include "shell.h"
#include "shellhooks.h"
#include "shellundo.h"
#include "lang.h"
#include "langexternal.h"
#include "langinternal.h"
#include "tablestructure.h"
#include "process.h"
#include "op.h"
#include "opinternal.h"
#include "opverbs.h"
#include "wpengine.h"
#include "scripts.h"
#include "kernelverbdefs.h"
#include "osacomponent.h"
#define opstringlist 159
#define optypestring 1
#define scripttypestring 2
#define opsizestring 3
#define operrorlist 259
#define noooutlineerror 1
#define internalerror 2
#define namenotoutlineerror 3
#define namenotscripterror 4
#define rejectmenubarnum 5
enum {
runbutton = 1,
debugbutton,
recordbutton,
stepbutton,
inbutton,
outbutton,
followbutton,
gobutton,
stopbutton,
killbutton,
localsbutton,
installbutton
};
#define maxchainedlocals 80 /*limit for local table nesting in debugged process*/
#define maxnestedsources 40 /*local handlers count as nested sources*/
typedef struct tysourcerecord {
WindowPtr pwindow; /*window containing running script; nil if closed or unknown*/
hdlhashnode hnode; /*hash node containing script variable*/
hdloutlinerecord houtline; /*script outline itself*/
} tysourcerecord;
typedef struct tydebuggerrecord {
hdlprocessrecord scriptprocess;
tysourcerecord scriptsourcestack [maxnestedsources]; /*for stepping other scripts*/
short topscriptsource; /*source stack pointer*/
short sourcesteplevel; /*level in source stack at which we suspend after step/in/out*/
tydirection stepdir; /*left,right,down & flatdown for out,in,step & trace*/
short lastlnum; /*the last line number stepped onto*/
hdlhashtable hlocaltable; /*the most local table in our process*/
hdlhashnode localtablestack [maxchainedlocals]; /*nodes of tables in the runtimestack*/
/***Handle localtableformatsstack [maxchainedlocals]; /*nodes of tables in the runtimestack*/
short toplocaltable; /*table stack pointer*/
/*
short deferredbuttonnum; /*see scriptdeferbutton%/
WindowPtr deferredwindow; /*ditto%/
*/
hdlheadrecord hbarcursor; /*the headline we've most recently shown*/
ComponentInstance servercomp; /*component that we have open for this script*/
OSType servertype; /*the component's type*/
OSAID idscript; /*while recording, this is the id of the script*/
short lastindent;
boolean flscriptsuspended: 1; /*user is debugging a script*/
boolean flstepping: 1; /*single-stepping thru scripts*/
boolean flfollowing: 1; /*does the bar cursor follow the interpreter?*/
boolean flscriptkilled: 1; /*true if the script has been killed*/
boolean flscriptrunning: 1; /*true when the script is running*/
boolean flwindowclosed: 1; /*false if script's window is open*/
boolean fllangerror: 1; /*are we stopped with an error?*/
boolean flrecording: 1; /*are we recording into this script?*/
boolean flcontextlocked: 1; /*is out context being operated on externally?*/
long scriptrefcon; /*copied from outline refcon*/
} tydebuggerrecord, *ptrdebuggerrecord, **hdldebuggerrecord;
static hdldebuggerrecord debuggerdata = nil;
static boolean scriptinruntimestack (void) {
/*
is the current script part of the current process?
6/24/92 dmb: compare outlines in loop, not windows; windows may not yet
be assigned into stack (if opened manaually or by Error Info)
*/
register hdldebuggerrecord hd = debuggerdata;
register short ix;
for (ix = 0; ix < (**hd).topscriptsource; ix++) { /*visit every window in stack*/
/*
if (outlinewindow == (**hd).scriptsourcestack [ix].pwindow) {
*/
if (outlinedata == (**hd).scriptsourcestack [ix].houtline) {
if (ix == 0) /*main source window. make sure same script is displayed*/
return ((**hd).scriptrefcon == (**outlinedata).outlinerefcon);
return (true);
}
}
return (false);
} /*scriptinruntimestack*/
static void scriptkillbutton (void) {
/*
11/5/91 dmb: use new scriptprocess field to make kill more explicit
*/
register hdldebuggerrecord hd = debuggerdata;
// processkill ((**hd).scriptprocess);
(**hd).flscriptkilled = true;
(**hd).flscriptsuspended = false; /*allow script to resume, so it can die*/
} /*scriptkillbutton*/
static boolean scriptnewprocess (short buttonnum) {
Handle hlangtext = nil;
bigstring bsresult;
if (!opgetlangtext (outlinedata, false, &hlangtext))
return (false);
langrunhandle (hlangtext, bsresult);
alertdialog (bsresult);
return (true);
} /*scriptnewprocess*/
static boolean scriptbutton (short buttonnum) {
register hdldebuggerrecord hd = debuggerdata;
if (buttonnum != localsbutton) /*exit edit mode on any button hit except locals*/
opsettextmode (false);
switch (buttonnum) {
case runbutton:
if (scriptnewprocess (runbutton))
shellupdatenow (outlinewindow);
return (true);
case killbutton:
scriptkillbutton ();
return (true);
} /*switch*/
return (true);
} /*scriptbutton*/
static boolean scriptbuttonenabled (short buttonnum) {
register short x = buttonnum;
register hdldebuggerrecord hd = debuggerdata;
register boolean flscriptrunning = (**hd).flscriptrunning;
register boolean flscriptsuspended = (**hd).flscriptsuspended;
register boolean flrunningthisscript;
if (outlinedata == NULL)
return (false);
flrunningthisscript = flscriptrunning && scriptinruntimestack ();
if (flscriptrunning) {
if ((x != installbutton) && (x != killbutton)) /*rule 3*/
if (!flrunningthisscript)
return (false);
}
if ((**hd).flrecording)
return (x == stopbutton);
if ((**hd).flcontextlocked)
return (false);
/*
else {
if ((x != runbutton) && (x != debugbutton) && (x != installbutton)) /*rule 1%/
return (false);
}
*/
switch (x) {
case runbutton:
return (!flscriptrunning);
case debugbutton:
return (!flscriptrunning && ((**outlinedata).outlinesignature == typeLAND));
case stopbutton:
return (!flscriptsuspended);
case gobutton:
return ((flscriptsuspended || (**hd).flfollowing) && !(**hd).fllangerror);
case followbutton:
case stepbutton:
case inbutton:
case outbutton:
return (flscriptrunning && flscriptsuspended && !(**hd).fllangerror);
case localsbutton:
return (flscriptrunning && flscriptsuspended); /*(**hd).flstepping && (!(**hd).flfollowing))*/
case killbutton:
return (flscriptrunning);
} /*switch*/
return (true);
} /*scriptbuttonenabled*/
static boolean scriptbuttondisplayed (short buttonnum) {
register hdldebuggerrecord hd = debuggerdata;
register hdlprocessrecord hp = (**hd).scriptprocess;
register boolean flscriptrunning = (**hd).flscriptrunning;
register boolean flrunningthisscript;
register boolean fldebuggingthisscript;
register short x = buttonnum;
flrunningthisscript = flscriptrunning && scriptinruntimestack (); /*1/2/91*/
fldebuggingthisscript = flrunningthisscript && (**hp).fldebugging;
if ((**hd).flrecording)
return ((x == recordbutton) || (x == stopbutton));
switch (x) {
case recordbutton:
case runbutton:
case debugbutton:
return (!flscriptrunning);
case stopbutton:
return (fldebuggingthisscript && !(**hd).flscriptsuspended);
case gobutton:
return (fldebuggingthisscript && (**hd).flscriptsuspended);
case followbutton:
case stepbutton:
case inbutton:
case outbutton:
case localsbutton:
return (fldebuggingthisscript);
case killbutton:
return (flscriptrunning);
} /*switch*/
return (true);
} /*scriptbuttondisplayed*/
static boolean scriptbuttonstatus (short buttonnum, tybuttonstatus *status) {
(*status).flenabled = scriptbuttonenabled (buttonnum);
(*status).fldisplay = scriptbuttondisplayed (buttonnum);
(*status).flbold = false; /*our buttons are never bold*/
return (true);
} /*scriptbuttonstatus*/
static boolean opverbsetscrollbarsroutine (void) {
register ptrwindowinfo pw = *outlinewindowinfo;
register ptroutlinerecord po = *outlinedata;
(*pw).vertscrollinfo = (*po).vertscrollinfo;
(*pw).horizscrollinfo = (*po).horizscrollinfo;
(*pw).fldirtyscrollbars = true; /*force a refresh of scrollbars by the shell*/
return (true);
} /*opverbsetscrollbarsroutine*/
static void opverbsetcallbacks (hdloutlinerecord houtline) {
register hdloutlinerecord ho = houtline;
(**ho).setscrollbarsroutine = &opverbsetscrollbarsroutine;
/*link in the line layout callbacks*/ /*{
(**ho).drawlinecallback = &claydrawline;
(**ho).postdrawlinecallback = &claypostdrawline;
(**ho).predrawlinecallback = &claypredrawline;
(**ho).drawiconcallback = &claydrawnodeicon;
(**ho).gettextrectcallback = &claygettextrect;
(**ho).geticonrectcallback = &claygeticonrect;
(**ho).getlineheightcallback = &claygetlineheight;
(**ho).getlinewidthcallback = &claygetlinewidth;
(**ho).pushstylecallback = &claypushnodestyle;
(**ho).postfontchangecallback = (opvoidcallback) &claybrowserinitdraw;
(**ho).getfullrectcallback = (opgefullrectcallback) &claygetnodeframe;
}*/
} /*opverbsetcallbacks*/
static void opverbcheckwindowrect (hdloutlinerecord houtline) {
register hdloutlinerecord ho = houtline;
hdlwindowinfo hinfo = outlinewindowinfo;
if ((**ho).flwindowopen) { /*make windowrect reflect current window size & position*/
Rect r;
shellgetglobalwindowrect (hinfo, &r);
if (!equalrects (r, (**ho).windowrect)) {
(**ho).windowrect = r;
(**ho).fldirty = true;
}
}
} /*opverbcheckwindowrect*/
static void opverbresize (void) {
opresize ((**outlinewindowinfo).contentrect);
} /*opverbresize*/
boolean opverbclose (void) {
register hdloutlinerecord ho = outlinedata;
opverbcheckwindowrect (ho);
killundo (); /*must toss undos before they're stranded*/
if ((**ho).fldirty) { /*we have to keep the in-memory version around*/
(**ho).flwindowopen = false;
opcloseoutline (); /*prepare for dormancy, not in a window anymore*/
}
return (true);
} /*opverbclose*/
static boolean opverbsetfont (void) {
return (opsetfont ((**outlinewindowinfo).selectioninfo.fontnum));
} /*opverbsetfont*/
static boolean opverbsetsize (void) {
return (opsetsize ((**outlinewindowinfo).selectioninfo.fontsize));
} /*opverbsetsize*/
static boolean opwinnewrecord (void) {
register hdloutlinerecord ho;
if (!opnewrecord ((**outlinewindowinfo).contentrect))
return (false);
ho = outlinedata; /*copy into register*/
(**outlinewindowinfo).hdata = (Handle) ho;
(**ho).flwindowopen = true;
(**ho).fldirty = true; /*needs to be saved*/
opverbsetcallbacks (ho);
return (true);
} /*opwinnewrecord*/
static boolean opwindisposerecord (void) {
opdisposeoutline (outlinedata, true);
outlinedata = nil;
(**outlinewindowinfo).hdata = nil;
return true;
} /*opwindisposerecord*/
static boolean opwinloadfile (hdlfilenum fnum, short rnum) {
Handle hpackedop;
register hdloutlinerecord ho;
boolean fl;
long ixload = 0;
if (!filereadhandle (fnum, &hpackedop))
return (false);
fl = opunpack (hpackedop, &ixload);
disposehandle (hpackedop);
if (!fl)
return (false);
ho = outlinedata; /*remember for linking into variable structure*/
(**outlinewindowinfo).hdata = (Handle) ho;
(**ho).flwindowopen = true;
(**ho).fldirty = true; /*never been saved, can't be clean*/
opverbsetcallbacks (ho);
return (true);
} /*opwinloadfile*/
static boolean opwinsavefile (hdlfilenum fnum, short rnum, boolean flsaveas) {
Handle hpackedop = nil;
boolean fl;
if (!oppack (&hpackedop))
return (false);
fl =
fileseteof (fnum, 0) &&
filesetposition (fnum, 0) &&
filewritehandle (fnum, hpackedop);
disposehandle (hpackedop);
return (fl);
} /*opwinsavefile*/
boolean opstart (void) {
/*
set up callback routines record, and link our data into the shell's
data structure.
*/
ptrcallbacks callbacks;
register ptrcallbacks cb;
opinitdisplayvariables ();
shellnewcallbacks (&callbacks);
cb = callbacks; /*copy into register*/
loadconfigresource (idscriptconfig, &(*cb).config);
(*cb).config.flnewonlaunch = true; // *** need to update resource
(*cb).configresnum = idscriptconfig;
(*cb).windowholder = &outlinewindow;
(*cb).dataholder = (Handle *) &outlinedata;
(*cb).infoholder = &outlinewindowinfo;
(*cb).initroutine = &wpinit;
(*cb).quitroutine = &wpshutdown;
(*cb).setglobalsroutine = &opeditsetglobals;
(*cb).newrecordroutine = opwinnewrecord;
(*cb).disposerecordroutine = opwindisposerecord;
(*cb).loadroutine = opwinloadfile;
(*cb).saveroutine = opwinsavefile;
(*cb).updateroutine = &opupdate;
(*cb).activateroutine = &opactivate;
(*cb).getcontentsizeroutine = &opgetoutinesize;
(*cb).resizeroutine = &opverbresize;
(*cb).scrollroutine = &opscroll;
(*cb).setscrollbarroutine = &opresetscrollbars;
(*cb).mouseroutine = &opmousedown;
(*cb).keystrokeroutine = &opkeystroke;
(*cb).getundoglobalsroutine = &opeditgetundoglobals;
(*cb).setundoglobalsroutine = &opeditsetundoglobals;
(*cb).cutroutine = &opcut;
(*cb).copyroutine = &opcopy;
(*cb).pasteroutine = &oppaste;
(*cb).clearroutine = &opclear;
(*cb).selectallroutine = &opselectall;
(*cb).fontroutine = &opverbsetfont;
(*cb).sizeroutine = &opverbsetsize;
(*cb).setselectioninforoutine = &opsetselectioninfo;
(*cb).idleroutine = &opidle;
(*cb).adjustcursorroutine = &opsetcursor;
(*cb).setprintinfoproutine = &opsetprintinfo;
(*cb).printroutine = &opprint;
(*cb).settextmoderoutine = &opsettextmode;
(*cb).cmdkeyfilterroutine = &opcmdkeyfilter;
(*cb).closeroutine = &opverbclose;
(*cb).buttonroutine = &scriptbutton;
(*cb).buttonstatusroutine = &scriptbuttonstatus;
if (!newclearhandle (longsizeof (tydebuggerrecord), (Handle *) &debuggerdata)) /*all fields are cool at 0*/
return (false);
return (true);
} /*opstart*/
| gpl-2.0 |
xerpi/3ds-arm9-linux | linux-2.6.x/drivers/input/joystick/warrior.c | 1 | 6639 | /*
* $Id: warrior.c 573 2006-02-20 17:09:11Z stsp2 $
*
* Copyright (c) 1999-2001 Vojtech Pavlik
*/
/*
* Logitech WingMan Warrior joystick driver for Linux
*/
/*
* This program is free warftware; 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
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "Logitech WingMan Warrior joystick driver"
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Constants.
*/
#define WARRIOR_MAX_LENGTH 16
static char warrior_lengths[] = { 0, 4, 12, 3, 4, 4, 0, 0 };
static char *warrior_name = "Logitech WingMan Warrior";
/*
* Per-Warrior data.
*/
struct warrior {
struct input_dev dev;
int idx, len;
unsigned char data[WARRIOR_MAX_LENGTH];
char phys[32];
};
/*
* warrior_process_packet() decodes packets the driver receives from the
* Warrior. It updates the data accordingly.
*/
static void warrior_process_packet(struct warrior *warrior, struct pt_regs *regs)
{
struct input_dev *dev = &warrior->dev;
unsigned char *data = warrior->data;
if (!warrior->idx) return;
input_regs(dev, regs);
switch ((data[0] >> 4) & 7) {
case 1: /* Button data */
input_report_key(dev, BTN_TRIGGER, data[3] & 1);
input_report_key(dev, BTN_THUMB, (data[3] >> 1) & 1);
input_report_key(dev, BTN_TOP, (data[3] >> 2) & 1);
input_report_key(dev, BTN_TOP2, (data[3] >> 3) & 1);
break;
case 3: /* XY-axis info->data */
input_report_abs(dev, ABS_X, ((data[0] & 8) << 5) - (data[2] | ((data[0] & 4) << 5)));
input_report_abs(dev, ABS_Y, (data[1] | ((data[0] & 1) << 7)) - ((data[0] & 2) << 7));
break;
case 5: /* Throttle, spinner, hat info->data */
input_report_abs(dev, ABS_THROTTLE, (data[1] | ((data[0] & 1) << 7)) - ((data[0] & 2) << 7));
input_report_abs(dev, ABS_HAT0X, (data[3] & 2 ? 1 : 0) - (data[3] & 1 ? 1 : 0));
input_report_abs(dev, ABS_HAT0Y, (data[3] & 8 ? 1 : 0) - (data[3] & 4 ? 1 : 0));
input_report_rel(dev, REL_DIAL, (data[2] | ((data[0] & 4) << 5)) - ((data[0] & 8) << 5));
break;
}
input_sync(dev);
}
/*
* warrior_interrupt() is called by the low level driver when characters
* are ready for us. We then buffer them for further processing, or call the
* packet processing routine.
*/
static irqreturn_t warrior_interrupt(struct serio *serio,
unsigned char data, unsigned int flags, struct pt_regs *regs)
{
struct warrior *warrior = serio_get_drvdata(serio);
if (data & 0x80) {
if (warrior->idx) warrior_process_packet(warrior, regs);
warrior->idx = 0;
warrior->len = warrior_lengths[(data >> 4) & 7];
}
if (warrior->idx < warrior->len)
warrior->data[warrior->idx++] = data;
if (warrior->idx == warrior->len) {
if (warrior->idx) warrior_process_packet(warrior, regs);
warrior->idx = 0;
warrior->len = 0;
}
return IRQ_HANDLED;
}
/*
* warrior_disconnect() is the opposite of warrior_connect()
*/
static void warrior_disconnect(struct serio *serio)
{
struct warrior *warrior = serio_get_drvdata(serio);
input_unregister_device(&warrior->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
kfree(warrior);
}
/*
* warrior_connect() is the routine that is called when someone adds a
* new serio device. It looks for the Warrior, and if found, registers
* it as an input device.
*/
static int warrior_connect(struct serio *serio, struct serio_driver *drv)
{
struct warrior *warrior;
int i;
int err;
if (!(warrior = kmalloc(sizeof(struct warrior), GFP_KERNEL)))
return -ENOMEM;
memset(warrior, 0, sizeof(struct warrior));
warrior->dev.evbit[0] = BIT(EV_KEY) | BIT(EV_REL) | BIT(EV_ABS);
warrior->dev.keybit[LONG(BTN_TRIGGER)] = BIT(BTN_TRIGGER) | BIT(BTN_THUMB) | BIT(BTN_TOP) | BIT(BTN_TOP2);
warrior->dev.relbit[0] = BIT(REL_DIAL);
warrior->dev.absbit[0] = BIT(ABS_X) | BIT(ABS_Y) | BIT(ABS_THROTTLE) | BIT(ABS_HAT0X) | BIT(ABS_HAT0Y);
sprintf(warrior->phys, "%s/input0", serio->phys);
init_input_dev(&warrior->dev);
warrior->dev.name = warrior_name;
warrior->dev.phys = warrior->phys;
warrior->dev.id.bustype = BUS_RS232;
warrior->dev.id.vendor = SERIO_WARRIOR;
warrior->dev.id.product = 0x0001;
warrior->dev.id.version = 0x0100;
warrior->dev.dev = &serio->dev;
for (i = 0; i < 2; i++) {
warrior->dev.absmax[ABS_X+i] = -64;
warrior->dev.absmin[ABS_X+i] = 64;
warrior->dev.absflat[ABS_X+i] = 8;
}
warrior->dev.absmax[ABS_THROTTLE] = -112;
warrior->dev.absmin[ABS_THROTTLE] = 112;
for (i = 0; i < 2; i++) {
warrior->dev.absmax[ABS_HAT0X+i] = -1;
warrior->dev.absmin[ABS_HAT0X+i] = 1;
}
warrior->dev.private = warrior;
serio_set_drvdata(serio, warrior);
err = serio_open(serio, drv);
if (err) {
serio_set_drvdata(serio, NULL);
kfree(warrior);
return err;
}
input_register_device(&warrior->dev);
printk(KERN_INFO "input: Logitech WingMan Warrior on %s\n", serio->phys);
return 0;
}
/*
* The serio driver structure.
*/
static struct serio_device_id warrior_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_WARRIOR,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, warrior_serio_ids);
static struct serio_driver warrior_drv = {
.driver = {
.name = "warrior",
},
.description = DRIVER_DESC,
.id_table = warrior_serio_ids,
.interrupt = warrior_interrupt,
.connect = warrior_connect,
.disconnect = warrior_disconnect,
};
/*
* The functions for inserting/removing us as a module.
*/
static int __init warrior_init(void)
{
serio_register_driver(&warrior_drv);
return 0;
}
static void __exit warrior_exit(void)
{
serio_unregister_driver(&warrior_drv);
}
module_init(warrior_init);
module_exit(warrior_exit);
| gpl-2.0 |
LordPsyan/InfinityCore | src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp | 1 | 7591 | /*
* This file is part of the OregonCore Project. See AUTHORS file for Copyright information
*
* 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/>.
*/
/* ScriptData
SDName: Instance_Arcatraz
SD%Complete: 80
SDComment: Mainly Harbringer Skyriss event
SDCategory: Tempest Keep, The Arcatraz
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "arcatraz.h"
/* Arcatraz encounters:
1 - Zereketh the Unbound event
2 - Dalliah the Doomsayer event
3 - Wrath-Scryer Soccothrates event
4 - Harbinger Skyriss event, 5 sub-events
*/
class instance_arcatraz : public InstanceMapScript
{
public:
instance_arcatraz() : InstanceMapScript("instance_arcatraz", 552) { }
struct instance_arcatrazAI : public ScriptedInstance
{
instance_arcatrazAI(Map* map) : ScriptedInstance(map)
{
Initialize();
};
uint32 Encounter[EncounterCount];
GameObject* Containment_Core_Security_Field_Alpha;
GameObject* Containment_Core_Security_Field_Beta;
GameObject* Pod_Alpha;
GameObject* Pod_Gamma;
GameObject* Pod_Beta;
GameObject* Pod_Delta;
GameObject* Pod_Omega;
GameObject* Wardens_Shield;
uint64 GoSphereGUID;
uint64 MellicharGUID;
void Initialize()
{
Containment_Core_Security_Field_Alpha = NULL;
Containment_Core_Security_Field_Beta = NULL;
Pod_Alpha = NULL;
Pod_Beta = NULL;
Pod_Delta = NULL;
Pod_Gamma = NULL;
Pod_Omega = NULL;
Wardens_Shield = NULL;
GoSphereGUID = 0;
MellicharGUID = 0;
for (uint8 i = 0; i < EncounterCount; i++)
Encounter[i] = NOT_STARTED;
}
bool IsEncounterInProgress() const
{
for (uint8 i = 0; i < EncounterCount; i++)
if (Encounter[i] == IN_PROGRESS)
return true;
return false;
}
void OnGameObjectCreate(GameObject* pGo, bool /*add*/)
{
switch (pGo->GetEntry())
{
case CONTAINMENT_CORE_SECURITY_FIELD_ALPHA:
Containment_Core_Security_Field_Alpha = pGo;
break;
case CONTAINMENT_CORE_SECURITY_FIELD_BETA:
Containment_Core_Security_Field_Beta = pGo;
break;
case POD_ALPHA:
Pod_Alpha = pGo;
break;
case POD_BETA:
Pod_Beta = pGo;
break;
case POD_DELTA:
Pod_Delta = pGo;
break;
case POD_GAMMA:
Pod_Gamma = pGo;
break;
case POD_OMEGA:
Pod_Omega = pGo;
break;
case SEAL_SPHERE:
GoSphereGUID = pGo->GetGUID();
break;
//case WARDENS_SHIELD: Wardens_Shield = pGo; break;
}
}
void OnCreatureCreate(Creature* pCreature, bool /*add*/)
{
if (pCreature->GetEntry() == NPC_MELLICHAR)
MellicharGUID = pCreature->GetGUID();
}
void SetData(uint32 type, uint32 data)
{
switch (type)
{
case DATA_ZEREKETH:
Encounter[0] = data;
break;
case DATA_DALLIAH:
if (data == DONE)
if (Containment_Core_Security_Field_Beta)
Containment_Core_Security_Field_Beta->UseDoorOrButton();
Encounter[1] = data;
break;
case DATA_SOCCOTHRATES:
if (data == DONE)
if (Containment_Core_Security_Field_Alpha)
Containment_Core_Security_Field_Alpha->UseDoorOrButton();
Encounter[2] = data;
break;
case DATA_HARBINGERSKYRISS:
if (data == NOT_STARTED || data == FAIL)
{
Encounter[4] = NOT_STARTED;
Encounter[5] = NOT_STARTED;
Encounter[6] = NOT_STARTED;
Encounter[7] = NOT_STARTED;
Encounter[8] = NOT_STARTED;
}
Encounter[3] = data;
break;
case DATA_WARDEN_1:
if (data == IN_PROGRESS)
if (Pod_Alpha)
Pod_Alpha->UseDoorOrButton();
Encounter[4] = data;
break;
case DATA_WARDEN_2:
if (data == IN_PROGRESS)
if (Pod_Beta)
Pod_Beta->UseDoorOrButton();
Encounter[5] = data;
break;
case DATA_WARDEN_3:
if (data == IN_PROGRESS)
if (Pod_Delta)
Pod_Delta->UseDoorOrButton();
Encounter[6] = data;
break;
case DATA_WARDEN_4:
if (data == IN_PROGRESS)
if (Pod_Gamma)
Pod_Gamma->UseDoorOrButton();
Encounter[7] = data;
break;
case DATA_WARDEN_5:
if (data == IN_PROGRESS)
if (Pod_Omega)
Pod_Omega->UseDoorOrButton();
Encounter[8] = data;
break;
case DATA_SHIELD_OPEN:
if (data == IN_PROGRESS)
if (Wardens_Shield)
Wardens_Shield->UseDoorOrButton();
break;
case DATA_CONVERSATION:
Encounter[12] = data;
break;
}
}
uint32 GetData(uint32 type)
{
switch (type)
{
case DATA_HARBINGERSKYRISS: return Encounter[3];
case DATA_WARDEN_1: return Encounter[4];
case DATA_WARDEN_2: return Encounter[5];
case DATA_WARDEN_3: return Encounter[6];
case DATA_WARDEN_4: return Encounter[7];
case DATA_WARDEN_5: return Encounter[8];
case DATA_CONVERSATION: return Encounter[12];
}
return 0;
}
uint64 GetData64(uint32 data)
{
switch (data)
{
case DATA_MELLICHAR:
return MellicharGUID;
case DATA_SPHERE_SHIELD:
return GoSphereGUID;
}
return 0;
}
};
InstanceData* GetInstanceScript(InstanceMap* map) const override
{
return new instance_arcatrazAI(map);
}
};
void AddSC_instance_arcatraz()
{
new instance_arcatraz();
}
| gpl-2.0 |
hreinecke/s390-tools | ziomon/ziomon_util.c | 1 | 34519 | /*
* FCP adapter trace utility
*
* Utilization data collector for zfcp adapters
*
* Copyright IBM Corp. 2008
* Author(s): Stefan Raspl <raspl@linux.vnet.ibm.com>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <dirent.h>
#include <time.h>
#include <limits.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <getopt.h>
#include <limits.h>
#include <math.h>
#include <assert.h>
#include "ziomon_util.h"
#include "zt_common.h"
#ifdef WITH_MAIN
const char *toolname = "ziomon_util";
#else
extern const char *toolname;
#endif
struct overall_result_wrp {
long mtype; /* must be long due to msg-passing
interface */
struct utilization_data o_res;
};
struct ioerr_wrp {
long mtype;
struct ioerr_data data;
};
__u32 get_result_sz(struct utilization_data *res)
{
return (sizeof(struct utilization_data)
+ res->num_adapters * sizeof(struct adapter_utilization));
}
__u32 get_ioerr_data_sz(struct ioerr_data *wrp)
{
return (sizeof(struct ioerr_data)
+ wrp->num_luns * sizeof(struct ioerr_cnt));
}
void print_utilization_result(struct utilization_data *res)
{
int i;
struct adapter_utilization *a_res;
struct utilization_stats *u_res;
time_t t;
t = res->timestamp;
printf("timestamp : %s", ctime(&t));
printf("num adapters : %d\n", res->num_adapters);
for (i = 0; i < res->num_adapters; ++i) {
a_res = &res->adapt_utils[i];
u_res = &a_res->stats;
if (i != 0)
printf("\n");
printf("utilization of host adapter %d\n", a_res->adapter_no);
printf("\tnum samples: %llu\n", (unsigned long long)u_res->count);
if (u_res->count > 0) {
printf("\tqueue full incidents: %d\n", u_res->queue_full);
printf("\taverage queue utilization: %.1lf slots\n",
u_res->queue_util_integral / (double)u_res->queue_util_interval);
printf("\tadapter:\n");
print_abbrev_stat(&u_res->adapter, u_res->count);
printf("\tbus:\n");
print_abbrev_stat(&u_res->bus, u_res->count);
printf("\tprocessor:\n");
print_abbrev_stat(&u_res->cpu, u_res->count);
}
}
}
static void swap_overall_result(struct utilization_data *res)
{
int i;
struct adapter_utilization *a_res;
struct utilization_stats *u_res;
swap_64(res->timestamp);
for (i = 0; i < res->num_adapters; ++i) {
a_res = &res->adapt_utils[i];
swap_32(a_res->adapter_no);
swap_16(a_res->valid);
u_res = &a_res->stats;
swap_64(u_res->count);
swap_32(u_res->queue_full);
swap_64(u_res->queue_util_integral);
swap_64(u_res->queue_util_interval);
swap_abbrev_stat(&u_res->adapter);
swap_abbrev_stat(&u_res->bus);
swap_abbrev_stat(&u_res->cpu);
}
}
void conv_overall_result_to_BE(struct utilization_data *res)
{
swap_overall_result(res);
swap_16(res->num_adapters);
}
void conv_overall_result_from_BE(struct utilization_data *res)
{
swap_16(res->num_adapters);
swap_overall_result(res);
}
int compare_hctl_idents(const struct hctl_ident *src,
const struct hctl_ident *tgt)
{
if (src->host == tgt->host) {
if (src->channel == tgt->channel) {
if (src->target == tgt->target)
return (src->lun - tgt->lun);
else
return (src->target - tgt->target);
}
else
return (src->channel - tgt->channel);
}
else
return (src->host - tgt->host);
}
void aggregate_utilization_data(const struct utilization_data *src,
struct utilization_data *tgt)
{
int i;
assert(tgt->timestamp = src->timestamp);
tgt->timestamp = src->timestamp;
if (src->num_adapters != tgt->num_adapters)
fprintf(stderr, "%s: Warning: inconsistent"
" number of adapters: %d %d\n", toolname,
src->num_adapters, tgt->num_adapters);
for (i = 0; i < src->num_adapters; ++i)
aggregate_adapter_result(&src->adapt_utils[i], &tgt->adapt_utils[i]);
return;
}
void aggregate_adapter_result(const struct adapter_utilization *src,
struct adapter_utilization *tgt)
{
if (src->valid) {
/* in case we aggregate over different adapters,
we clearly indicate that this is not valid anymore */
if (src->adapter_no != tgt->adapter_no)
tgt->adapter_no = -1;
tgt->stats.queue_full += src->stats.queue_full;
tgt->stats.queue_util_integral +=
src->stats.queue_util_integral;
tgt->stats.queue_util_interval +=
src->stats.queue_util_interval;
tgt->stats.count += src->stats.count;
aggregate_abbrev_stat(&src->stats.adapter,
&tgt->stats.adapter);
aggregate_abbrev_stat(&src->stats.bus,
&tgt->stats.bus);
aggregate_abbrev_stat(&src->stats.cpu,
&tgt->stats.cpu);
}
}
void print_ioerr_data(struct ioerr_data *data)
{
__u64 i;
struct ioerr_cnt *cnt;
time_t t;
t = data->timestamp;
fprintf(stdout, "timestamp : %s", ctime(&t));
fprintf(stdout, "num luns : %lld\n", (long long)data->num_luns);
for (i = 0; i < data->num_luns; ++i) {
cnt = &data->ioerrors[i];
fprintf(stdout, "\t%d:%d:%d:%d: %lld I/O errors\n",
cnt->identifier.host, cnt->identifier.channel,
cnt->identifier.target, cnt->identifier.lun,
(long long)cnt->num_ioerr);
}
}
static void swap_ioerr_data(struct ioerr_data *data)
{
__u64 i;
struct ioerr_cnt *cnt;
swap_64(data->timestamp);
for (i = 0; i < data->num_luns; ++i) {
cnt = &data->ioerrors[i];
swap_32(cnt->identifier.host);
swap_32(cnt->identifier.channel);
swap_32(cnt->identifier.target);
swap_32(cnt->identifier.lun);
swap_64(cnt->num_ioerr);
}
}
void conv_ioerr_data_to_BE(struct ioerr_data *data)
{
swap_ioerr_data(data);
swap_64(data->num_luns);
}
void conv_ioerr_data_from_BE(struct ioerr_data *data)
{
swap_64(data->num_luns);
swap_ioerr_data(data);
}
void aggregate_ioerr_cnt(const struct ioerr_cnt *src, struct ioerr_cnt *tgt)
{
/* in case we aggregate over different devices,
we clearly indicate that this is not valid anymore */
if (compare_hctl_idents(&src->identifier, &tgt->identifier) != 0)
memset(&tgt->identifier, 0xff, sizeof(struct hctl_ident));
tgt->num_ioerr += src->num_ioerr;
}
void aggregate_ioerr_data(const struct ioerr_data *src, struct ioerr_data *tgt)
{
__u64 i;
assert(tgt->timestamp <= src->timestamp);
tgt->timestamp = src->timestamp;
for (i=0; i<src->num_luns; ++i)
aggregate_ioerr_cnt(&src->ioerrors[i], &tgt->ioerrors[i]);
}
#ifdef WITH_MAIN
#define SAMPLE_INTERVAL_DFT 2
#define SAMPLE_INTERVAL_DFT_STR "2"
static int keep_running;
int verbose=0;
struct util_data {
int queue_full; /* # queue full instances in frame */
int queue_full_prev; /* previous absolut value
of queue_full */
__u64 queue_util_integral;
__u64 queue_util_interval;
__u64 queue_util_prev; /* previous absolut value
of queue_util_integral */
struct timeval queue_util_timestamp;
struct abbrev_stat adapter;
struct abbrev_stat bus;
struct abbrev_stat cpu;
long count;
};
struct adapter_data {
int host_nr;
char *path;
char *q_full_path;
int status; /* 0 if good != 0 in case of failure */
struct util_data data;
};
struct adapters {
int num_adapters;
struct adapter_data adapters[0];
};
#define MAX_HOST_PATH_LEN 42
#define MAX_LUN_PATH_LEN strlen("/sys/bus/scsi/devices/4000000000:4000000000:4000000000:4000000000/ioerr_cnt")
struct options {
int num_hosts; /* total number of hosts */
int num_hosts_a; /* number of allocated host & lun structures */
long *host_nr; /* array if host numbers. to trace */
char **host_path; /* array of paths to utilization files */
int num_luns; /* number of luns */
char **luns; /* array of luns to monitor */
__u32 *luns_prev; /* array of previous values of luns */
long duration; /* overall duration in seconds */
long s_duration; /* ssample duration in seconds */
long i_duration; /* interval duration in seconds */
char *msg_q_path;
int msg_q_id;
int msg_q; /* msg q handle */
long msg_id; /* msg id to use in msg q */
long msg_id_ioerr; /* msg id to use in msg q for ioerr messages*/
};
static void init_opts(struct options *opts)
{
opts->i_duration = -1;
opts->duration = -1;
opts->s_duration = SAMPLE_INTERVAL_DFT;
opts->num_hosts = 0;
opts->num_hosts_a = 0;
opts->host_nr = NULL;
opts->host_path = NULL;
opts->num_luns = 0;
opts->luns = NULL;
opts->luns_prev = NULL;
opts->msg_q_path = NULL;
opts->msg_q_id = -1;
opts->msg_q = -1;
opts->msg_id = LONG_MIN;
opts->msg_id_ioerr = LONG_MIN;
}
static void deinit_opts(struct options *opts)
{
int i;
free(opts->host_nr);
opts->host_nr = NULL;
if (opts->host_path) {
for (i = 0; i < opts->num_hosts_a; ++i)
free(opts->host_path[i]);
free(opts->host_path);
opts->host_path = NULL;
}
for (i=0; i<opts->num_hosts_a; ++i)
free(opts->luns[i]);
opts->num_hosts_a = 0;
opts->msg_q = -1;
free(opts->luns);
free(opts->luns_prev);
}
static void init_util_data(struct util_data *data)
{
init_abbrev_stat(&data->adapter);
init_abbrev_stat(&data->bus);
init_abbrev_stat(&data->cpu);
data->count = 0;
}
static int init_ioerr_cnt(struct ioerr_cnt *cnt, char *str)
{
cnt->num_ioerr = 0;
return (sscanf(str, "%d:%d:%d:%d", &cnt->identifier.host,
&cnt->identifier.channel, &cnt->identifier.target,
&cnt->identifier.lun) == 5);
}
static int init_host_opts(struct options *opts, int num_hosts)
{
int i;
free(opts->host_nr);
if (opts->host_path) {
for (i = 0; i < opts->num_hosts_a; ++i)
free(opts->host_path[i]);
free(opts->host_path);
}
opts->host_nr = calloc(num_hosts, sizeof(long));
if (!opts->host_nr) {
fprintf(stderr, "%s: calloc opts->host_nr: %s\n",
toolname, strerror(errno));
return -1;
}
opts->host_path = malloc(num_hosts * sizeof(char *));
if (!opts->host_path) {
fprintf(stderr, "%s: malloc opts->host_path: %s\n",
toolname, strerror(errno));
return -1;
}
for (i = 0; i < num_hosts; ++i) {
opts->host_path[i] = malloc(sizeof(char) * MAX_HOST_PATH_LEN + 1);
if (!opts->host_path[i]) {
fprintf(stderr, "%s: malloc opts->host_path[]: %s\n",
toolname, strerror(errno));
return -1;
}
}
free(opts->luns);
opts->luns = calloc(num_hosts, sizeof(char *));
free(opts->luns_prev);
opts->luns_prev = calloc(num_hosts, sizeof(__u32));
if (!opts->luns || !opts->luns_prev) {
fprintf(stderr, "%s: malloc opts->luns: %s\n",
toolname, strerror(errno));
return -1;
}
for (i = 0; i < num_hosts; ++i) {
opts->luns[i] = malloc(sizeof(char) * MAX_LUN_PATH_LEN + 1);
if (!opts->host_path[i]) {
fprintf(stderr, "%s: malloc opts->luns[]: %s\n",
toolname, strerror(errno));
return -1;
}
}
opts->num_hosts_a = num_hosts;
return 0;
}
#define LINE_LEN 255
static int read_attribute(char *path, char *line, int *status)
{
int fd;
int rc = 0;
fd = open(path, O_RDONLY);
if (fd < 0) {
rc = -1; /* adapter gone */
goto out;
}
rc = read(fd, line, LINE_LEN);
if (rc < 0) {
rc = -2; /* I/O error */
goto out;
}
rc = 0;
close(fd);
out:
if (status)
*status = rc;
return rc;
}
static int poll_utilization(struct adapters *all_adapters)
{
char line[LINE_LEN];
int cpu, bus, adapter;
int rc = 0, grc = 0;
struct adapter_data *adpt;
struct util_data *u_data;
int i;
for (i = 0; i < all_adapters->num_adapters; ++i) {
adpt = &all_adapters->adapters[i];
u_data = &adpt->data;
/* read utilization attribute */
if (read_attribute(adpt->path, line, &adpt->status)) {
grc++;
continue;
}
rc = sscanf(line, "%d %d %d", &cpu, &bus, &adapter);
if (rc != 3) {
fprintf(stderr, "%s: Warning:"
" Could not parse %s: %s\n", toolname,
line, strerror(errno));
adpt->status = 3;
continue;
}
update_abbrev_stat(&u_data->adapter, adapter);
update_abbrev_stat(&u_data->bus, bus);
update_abbrev_stat(&u_data->cpu, cpu);
verbose_msg("data read for adapter %d: adapter=%d, bus=%d,"
" cpu=%d\n",
adpt->host_nr, adapter, bus, cpu);
u_data->count++;
}
return grc;
}
static int calc_overflow(__u64 old_val, __u64 new_val)
{
double ofl_val = 0;
int i = 0;
assert(old_val > new_val);
while (ofl_val < old_val) {
ofl_val = pow(2, i);
++i;
}
return (new_val + (int)(ofl_val - old_val));
}
static int poll_queue_full(int init, struct adapters *all_adapters)
{
char line[LINE_LEN];
int rc = 0;
struct adapter_data *adpt;
struct util_data *u_data;
int queue_full_tmp;
long long unsigned int queue_util_tmp;
int i;
struct timeval tmp, cur_time;
for (i = 0; i < all_adapters->num_adapters; ++i) {
adpt = &all_adapters->adapters[i];
u_data = &adpt->data;
/* read queue_full attribute */
if (read_attribute(adpt->q_full_path, line, &adpt->status))
continue;
rc = sscanf(line, "%d %Lu", &queue_full_tmp, &queue_util_tmp);
if (rc == 1) {
fprintf(stderr, "%s: Only one value in"
" %s, your kernel level is probably too old.\n",
toolname, adpt->q_full_path);
return -1;
}
if (rc != 2) {
fprintf(stderr, "%s: Warning:"
" Could not parse %s: %s\n",
toolname, line, strerror(errno));
adpt->status = 6;
continue;
}
gettimeofday(&cur_time, NULL);
if (!init) {
if (queue_full_tmp < u_data->queue_full_prev)
u_data->queue_full =
calc_overflow(u_data->queue_full_prev,
queue_full_tmp);
else
u_data->queue_full = queue_full_tmp
- u_data->queue_full_prev;
if (queue_util_tmp < u_data->queue_util_prev)
u_data->queue_util_integral =
calc_overflow(u_data->queue_util_prev,
queue_util_tmp);
else
u_data->queue_util_integral = queue_util_tmp
- u_data->queue_util_prev;
timersub(&cur_time, &u_data->queue_util_timestamp, &tmp);
u_data->queue_util_interval = tmp.tv_sec * 1000000
+ tmp.tv_usec;
}
u_data->queue_full_prev = queue_full_tmp;
u_data->queue_util_prev = queue_util_tmp;
u_data->queue_util_timestamp = cur_time;
}
return 0;
}
static int poll_ioerr_cnt(int init, struct ioerr_data *data,
struct options *opts)
{
char line[LINE_LEN];
int rc = 0, grc = 0;
int i;
__u32 tmp;
if (!init)
data->timestamp = time(NULL);
for (i=0; i<opts->num_luns; ++i) {
/* read ioerr_cnt attribute */
if (read_attribute(opts->luns[i], line, NULL)) {
fprintf(stderr, "%s: Warning: Could not read %s\n",
toolname, opts->luns[i]);
grc++;
continue;
}
rc = sscanf(line, "%i", &tmp);
if (rc != 1) {
fprintf(stderr, "%s: Warning:"
" Could not parse ioerr line %s: %s\n",
toolname, line, strerror(errno));
grc++;
continue;
}
if (!init) {
if (tmp < opts->luns_prev[i])
data->ioerrors[i].num_ioerr = calc_overflow(
opts->luns_prev[i], tmp);
else
data->ioerrors[i].num_ioerr = tmp
- opts->luns_prev[i];
verbose_msg("data read for i/o err %s: ioerr_cnt=%d\n",
opts->luns[i], data->ioerrors[i].num_ioerr);
}
opts->luns_prev[i] = tmp;
}
return grc;
}
static void reinit_adapters(struct adapters *adptrs)
{
int i;
for (i = 0; i < adptrs->num_adapters; ++i)
init_util_data(&adptrs->adapters[i].data);
}
static int init_adapters(struct adapters *all_adapters, struct options *opts)
{
struct adapter_data *adapter;
struct stat buf;
int i, rc = 0;
if (opts)
all_adapters->num_adapters = opts->num_hosts;
for (i = 0; i < all_adapters->num_adapters; ++i) {
adapter = &all_adapters->adapters[i];
if (opts) {
adapter->host_nr = opts->host_nr[i];
adapter->path = malloc(sizeof(char)*MAX_HOST_PATH_LEN);
sprintf(adapter->path, "%s/utilization",
opts->host_path[i]);
if (stat(adapter->path, &buf)) {
fprintf(stderr, "%s: Path does not exist: %s - correct kernel version?\n",
toolname, adapter->path);
rc++;
}
adapter->q_full_path =
malloc(sizeof(char)*MAX_HOST_PATH_LEN);
sprintf(adapter->q_full_path, "%s/queue_full",
opts->host_path[i]);
if (stat(adapter->path, &buf)) {
fprintf(stderr, "%s: Path does not exist: %s - correct kernel version?\n",
toolname, adapter->q_full_path);
rc++;
}
adapter->status = 0;
}
init_util_data(&all_adapters->adapters[i].data);
}
if (poll_queue_full(1, all_adapters))
return -1;
return rc;
}
static void deinit_adapters(struct adapters *all_adapters)
{
int i;
for (i = 0; i < all_adapters->num_adapters; ++i) {
free(all_adapters->adapters[i].path);
free(all_adapters->adapters[i].q_full_path);
}
}
/**
* set up structures for the lun result message and replace lun identifiers
* with complete path to respective ioerr_cnts.
*/
static int init_ioerr_wrp(struct ioerr_wrp **wrp, struct options *opts)
{
int i;
struct stat buf;
char tmp[255];
*wrp = malloc(sizeof(struct ioerr_wrp)
+ opts->num_luns*sizeof(struct ioerr_cnt));
if (!*wrp) {
fprintf(stderr, "%s: Memory allocation failed\n", toolname);
return -1;
}
(*wrp)->mtype = opts->msg_id_ioerr;
(*wrp)->data.num_luns = opts->num_luns;
for (i=0; i<opts->num_luns; ++i) {
if (init_ioerr_cnt(&(*wrp)->data.ioerrors[i], opts->luns[i])) {
fprintf(stderr, "%s: Could not parse %s\n",
toolname, opts->luns[i]);
return -2;
}
strcpy(tmp, opts->luns[i]);
sprintf(opts->luns[i], "/sys/bus/scsi/devices/%s/ioerr_cnt", tmp);
if (stat(opts->luns[i], &buf)) {
fprintf(stderr, "%s: Could not open %s: %s\n",
toolname, opts->luns[i], strerror(errno));
return -3;
}
}
if (poll_ioerr_cnt(1, NULL, opts)) {
fprintf(stderr, "%s: Could not read initial values of ioerr"
" attributes.\n", toolname);
return -1;
}
return 0;
}
static void init_result_wrp(struct overall_result_wrp **res, int num_adapters,
struct options *opts)
{
*res = malloc(sizeof(struct overall_result_wrp) + (num_adapters * sizeof(struct adapter_utilization)));
(*res)->o_res.num_adapters = num_adapters;
(*res)->mtype = opts->msg_id;
}
static void deinit_result_wrp(struct overall_result_wrp **res)
{
free(*res);
res = NULL;
}
static void print_version(void)
{
fprintf(stdout, "%s: ziomon utilization monitor, version %s\n"
"Copyright IBM Corp. 2008\n",
toolname, RELEASE_STRING);
}
static int get_argument_long(long *param, char opt)
{
char *p;
if (!optarg) {
fprintf(stderr, "%s: Argument missing"
" to option %c\n", toolname, opt);
return -1;
}
*param = strtol(optarg, &p, 0);
if (errno) {
fprintf(stderr, "%s: Unrecognized"
" parameter to option %c: %s\n", toolname, opt,
strerror(errno));
return -2;
}
if (*p != '\0') {
fprintf(stderr, "%s: Unrecognized"
" parameter to option %c\n", toolname, opt);
return -3;
}
return 0;
}
static int hostdir_filter(const struct dirent *dir)
{
return !strncmp(dir->d_name, "host", 4);
}
static int check_host_param(long *host_nr, char *host_path)
{
struct stat buf;
char *tmp;
if (*host_nr > 9999) {
fprintf(stderr, "%s: Host number out"
" of range\n", toolname);
return -1;
}
sprintf(host_path, "/sys/class/scsi_host/host%ld", *host_nr);
if (stat(host_path, &buf)) {
fprintf(stderr, "%s: Cannot access %s:"
" %s\n", toolname, host_path, strerror(errno));
return -1;
}
tmp = malloc(strlen(host_path) + strlen("/queue_full") + 1);
sprintf(tmp, "%s/queue_full", host_path);
if (stat(host_path, &buf)) {
fprintf(stderr, "%s: Cannot access %s."
" Your installed kernel is probably too old. Please"
" check that your kernel matches the level in the"
" documentation.\n", toolname, tmp);
free(tmp);
return -1;
}
free(tmp);
verbose_msg("host path : %s\n", host_path);
return 0;
}
static int find_all_hosts(struct options *opts)
{
char *h_path = "/sys/class/scsi_host";
struct dirent **namelist;
int num_dirents;
int i, k;
int rc = 0;
verbose_msg("no host adapter(s) specified, scanning...\n");
num_dirents = scandir(h_path, &namelist, hostdir_filter, alphasort);
if (num_dirents <= 0) {
fprintf(stderr, "%s: No host adapter(s) found\n", toolname);
rc = -3;
goto out;
}
if (init_host_opts(opts, num_dirents))
return -1;
opts->num_hosts = num_dirents;
for (i = 0; i < num_dirents; ++i) {
k = sscanf(namelist[i]->d_name, "host%ld", &opts->host_nr[i]);
if (k != 1) {
fprintf(stderr, "%s: Internal error while scanning"
" host adapter no\n", toolname);
rc = -4;
} else
check_host_param(&opts->host_nr[i],
opts->host_path[i]);
}
out:
for (i = 0; i < num_dirents; i++)
free(namelist[i]);
free(namelist);
return rc;
}
static int host_adapter_compare(const void *a, const void *b)
{
return (*(long *)a > *(long *)b);
}
static int setup_msg_q(struct options *opts)
{
key_t util_q;
int wait=0;
if (opts->msg_id <= 0) {
fprintf(stderr, "%s: Invalid or missing msg"
" id for utilization messages\n", toolname);
return -1;
}
if (opts->msg_id_ioerr <= 0) {
fprintf(stderr, "%s: Invalid or missing msg"
" id for I/O error messages\n", toolname);
return -1;
}
if (opts->msg_id == opts->msg_id_ioerr) {
fprintf(stderr, "%s: Message IDs for"
" I/O error count and utilization messages must be"
" different\n", toolname);
return -1;
}
util_q = ftok(opts->msg_q_path, opts->msg_q_id);
verbose_msg("message queue key is %d\n", util_q);
while (keep_running) {
opts->msg_q = msgget(util_q, S_IRWXU);
if (opts->msg_q >= 0) {
if (wait)
fprintf(stderr, "%s: Message queue is up!\n",
toolname);
break;
}
if (!wait) {
wait = 1;
fprintf(stderr, "%s: Warning: Message queue not"
" up yet, waiting...\n", toolname);
}
usleep(200000);
}
verbose_msg("message queue id is %d\n", opts->msg_q);
if (opts->msg_q_path) {
verbose_msg("message queue path : %s\n", opts->msg_q_path);
verbose_msg("message queue id : %d\n", opts->msg_q_id);
verbose_msg("message id : %ld\n", opts->msg_id);
verbose_msg("message id : %ld\n", opts->msg_id);
}
return (opts->msg_q >= 0 ? 0 : -1);
}
static void generate_result(struct utilization_data *ures,
struct adapters *all_adapters)
{
struct adapter_data *a_data;
struct util_data *u_data;
struct adapter_utilization *a_res;
struct utilization_stats *u_res;
int i;
ures->num_adapters = all_adapters->num_adapters;
ures->timestamp = time(NULL);
for (i = 0; i < all_adapters->num_adapters; ++i) {
a_data = &all_adapters->adapters[i];
a_res = &ures->adapt_utils[i];
a_res->adapter_no = a_data->host_nr;
u_data = &a_data->data;
a_res->valid = u_data->count;
if (a_res->valid) {
u_res = &a_res->stats;
u_res->queue_full = u_data->queue_full;
u_res->queue_util_integral = u_data->queue_util_integral;
u_res->queue_util_interval = u_data->queue_util_interval;
u_res->count = u_data->count;
copy_abbrev_stat(&u_res->adapter, &u_data->adapter);
copy_abbrev_stat(&u_res->bus, &u_data->bus);
copy_abbrev_stat(&u_res->cpu, &u_data->cpu);
}
}
}
static const char help_text[] =
"Usage: ziomon_util [-h] [-v] [-V] [-i n] [-s n] "
"[-Q <msgq_path> -q <msgq_id>\n"
" -m <msg_id>] -d n -a <n> -l <lun>\n"
"\n"
"Start the monitor for the host adapter utilization.\n"
"Example: ziomon_util -d 60 -i 4 -a 0\n"
"\n"
"-h, --help Print usage information and exit.\n"
"-v, --version Print version information and exit.\n"
"-V, --verbose Be verbose.\n"
"-s, --sample-length Duration between each sample in seconds.\n"
" Defaults to "SAMPLE_INTERVAL_DFT_STR" seconds.\n"
"-i, --interval-length Aggregate samples over this duration (in seconds).\n"
" Defaults to 'duration'.\n"
"-d, --duration Overall duration in seconds.\n"
"-a, --adapter Host adapter no. to watch. Specify each host"
" adapter\n"
" separately.\n"
"-l, --lun watch I/O error count of LUN. Specify each LUN\n"
" separately in h:b:t:l format.\n"
"-Q, --msg-queue-name Specify the message queue path name.\n"
"-q, --msg-queue-id Specify the message queue id.\n"
"-m, --msg-id Specify the message id to use.\n"
"-L, --msg-id-ioerr Specify the message id for I/O error count"
" messages.\n";
static void print_help(void)
{
fprintf(stdout, "%s", help_text);
}
static int parse_params(int argc, char **argv, struct options *opts)
{
int c;
int index, i;
static struct option long_options[] = {
{ "version", no_argument, NULL, 'v'},
{ "help", no_argument, NULL, 'h'},
{ "verbose", no_argument, NULL, 'V'},
{ "msg-queue-name", required_argument, NULL, 'Q'},
{ "msg-queue-id", required_argument, NULL, 'q'},
{ "msg-id", required_argument, NULL, 'm'},
{ "msg-id-ioerr", required_argument, NULL, 'L'},
{ "sample-length", required_argument, NULL, 's'},
{ "interval-length",required_argument, NULL, 'i'},
{ "duration", required_argument, NULL, 'd'},
{ "adapter", required_argument, NULL, 'a'},
{ "lun", required_argument, NULL, 'l'},
{ NULL, 0, NULL, 0 }
};
if (argc <= 1) {
print_help();
return 1;
}
/* this is too much, but argc/2 is a reliable upper boundary
and saves us the trouble of figuring out how many host
adapters were specified up front */
init_host_opts(opts, argc/2);
while ((c = getopt_long(argc, argv, "L:l:m:Q:q:a:s:d:i:vhV", long_options,
&index)) != EOF) {
switch (c) {
case 'V':
verbose = 1;
break;
case 'a':
if (get_argument_long(&opts->host_nr[opts->num_hosts], c))
return -1;
(opts->num_hosts)++;
break;
case 'l':
if (!optarg) {
fprintf(stderr, "%s: Argument missing to"
" option '-l'\n", toolname);
return -1;
}
strcpy(opts->luns[opts->num_luns], optarg);
(opts->num_luns)++;
break;
case 'L':
if (get_argument_long(&opts->msg_id_ioerr, c))
return -1;
break;
case 'i':
if (get_argument_long(&opts->i_duration, c))
return -1;
break;
case 's':
if (get_argument_long(&opts->s_duration, c))
return -1;
break;
case 'd':
if (get_argument_long(&opts->duration, c))
return -1;
break;
case 'm':
if (get_argument_long(&opts->msg_id, c))
return -1;
break;
case 'Q':
if (!optarg) {
fprintf(stderr, "%s: Argument missing to"
" option '-Q'\n", toolname);
return -1;
}
opts->msg_q_path = optarg;
break;
case 'q':
if (!optarg) {
fprintf(stderr, "%s: Argument missing to"
" option '-Q'\n", toolname);
return -1;
}
opts->msg_q_id = atoi(optarg);
if (opts->msg_q_id < 0) {
fprintf(stderr, "%s: Parameter to option '-q'"
" must be greater than 0\n", toolname);
return -1;
}
break;
case 'v':
print_version();
return 1;
case 'h':
print_help();
return 1;
default:
fprintf(stderr, "%s: Try '%s --help' for more"
" information.\n", toolname, toolname);
return -1;
}
}
if (opts->duration < 0) {
fprintf(stderr, "%s: No duration specified\n", toolname);
return -1;
}
if (opts->i_duration < 0)
opts->i_duration = opts->duration;
if (opts->i_duration < opts->s_duration) {
fprintf(stderr, "%s: Sample duration"
" must be at least the interval duration\n", toolname);
return -1;
}
if (opts->duration < opts->i_duration) {
fprintf(stderr, "%s: Overall duration"
" must be at least the interval duration\n", toolname);
return -1;
}
if (opts->s_duration && opts->i_duration % opts->s_duration) {
fprintf(stderr, "%s: Sample duration"
" must be a multiple of sample duration\n", toolname);
return -1;
}
if (opts->i_duration && opts->duration % opts->i_duration) {
fprintf(stderr, "%s: overall duration"
" must be a multiple of section duration\n", toolname);
return -1;
}
if (opts->num_hosts > 0) {
qsort(opts->host_nr, opts->num_hosts, sizeof(long),
host_adapter_compare);
for (c = 0; c < opts->num_hosts; ++c) {
if (check_host_param(&opts->host_nr[c],
opts->host_path[c]))
return -1;
}
} else {
if (find_all_hosts(opts))
return -1;
}
if (opts->msg_q_path || opts->msg_q_id >= 0
|| opts->msg_id != LONG_MIN) {
if (!opts->msg_q_path || opts->msg_q_id < 0
|| opts->msg_id == LONG_MIN) {
fprintf(stderr, "%s: Make sure to"
" specify all required arguments for message"
" queue.\n", toolname);
return -1;
}
}
verbose_msg("num adapters : %d\n", opts->num_hosts);
verbose_msg("num luns : %d\n", opts->num_luns);
for (i=0; i<opts->num_luns; ++i)
verbose_msg("lun : %s\n", opts->luns[i]);
verbose_msg("overall duration : %lds\n", opts->duration);
verbose_msg("interval duration : %lds\n", opts->i_duration);
verbose_msg("sample duration : %lds\n", opts->s_duration);
return 0;
}
static void send_message(int msg_q, void *data, size_t data_sz)
{
if (msgsnd(msg_q, data, data_sz, 0) < 0) {
/* somehow we don't get this signal if queue is shut down
though we should... */
if (errno == EIDRM) {
keep_running = 0;
verbose_msg("msgqueue removed, shutting down...\n");
} else {
fprintf(stderr, "%s: Failed to send"
" message: %s\n", toolname, strerror(errno));
verbose_msg("msgsnd() returned error code %d\n",
errno);
}
}
}
static int has_ioerrs(struct ioerr_data *ioerr)
{
__u64 i;
for (i = 0; i < ioerr->num_luns; ++i) {
if (ioerr->ioerrors[i].num_ioerr != 0)
return 1;
}
return 0;
}
static int has_non_null_stats(struct abbrev_stat *var)
{
return !(var->max == 0 && var->min == 0);
}
static int has_adapter_traffic(struct utilization_data *res)
{
int i;
struct adapter_utilization *a_res;
for (i=0; i<res->num_adapters; ++i) {
a_res = &res->adapt_utils[i];
if (!a_res->valid)
return 1;
if (a_res->stats.queue_full != 0)
return 1;
/* makes sure that we don't send messages when essentially no
data is processed. Reading the 'utilization' sysfs attribute
causes traffic, hence we would always send a message without
this threshold! */
if (a_res->stats.queue_util_integral
/ (double)a_res->stats.queue_util_interval >= 0.05)
return 1;
if (has_non_null_stats(&a_res->stats.adapter)
|| has_non_null_stats(&a_res->stats.bus)
|| has_non_null_stats(&a_res->stats.cpu))
return 1;
}
return 0;
}
static void print_to_msg_q(struct overall_result_wrp *res_wrp,
struct ioerr_wrp *ioerr,
struct options *opts,
int force)
{
size_t msg_size;
if (has_adapter_traffic(&res_wrp->o_res) || force) {
msg_size = get_result_sz(&res_wrp->o_res);
if (verbose)
print_utilization_result(&res_wrp->o_res);
verbose_msg("write utilization result to msg q %d (msg-type: %ld, msg-size: %d)\n",
opts->msg_q, res_wrp->mtype, (unsigned int)msg_size);
conv_overall_result_to_BE(&res_wrp->o_res);
send_message(opts->msg_q, res_wrp, msg_size);
}
if (has_ioerrs(&ioerr->data) || force) {
msg_size = get_ioerr_data_sz(&ioerr->data);
if (verbose)
print_ioerr_data(&ioerr->data);
verbose_msg("write ioerr result to msg q %d (msg-type: %ld, msg-size: %d)\n",
opts->msg_q, ioerr->mtype, (unsigned int)msg_size);
conv_ioerr_data_to_BE(&ioerr->data);
send_message(opts->msg_q, ioerr, msg_size);
}
}
static void void_handler(int sig)
{
verbose_msg("interrupted by signal %u\n", sig);
keep_running = 0;
}
static void setup_signals(void)
{
signal(SIGALRM, void_handler);
signal(SIGINT, void_handler);
signal(SIGTERM, void_handler);
signal(SIGQUIT, void_handler);
}
static void sleep_until(struct timeval *end)
{
struct timeval tmp;
do {
gettimeofday(&tmp, NULL);
if (timercmp(&tmp, end, >=))
break;
timersub(end, &tmp, &tmp);
verbose_msg("sleep for %ld msec\n", tmp.tv_sec * 1000000
+ tmp.tv_usec);
usleep(tmp.tv_sec * 1000000 + tmp.tv_usec);
} while (keep_running);
}
/*
* Params:
* -h : host nr.
* -t : duration
*/
int main(int argc, char **argv)
{
struct options opts;
struct adapters *all_adapters = NULL;
struct overall_result_wrp *result_wrp = NULL;
struct timeval sample_end;
struct timeval interval_end;
struct timeval duration_end;
struct timeval first_interval;
struct ioerr_wrp *ioerr = NULL;
int rc = 0;
verbose = 0;
keep_running = 1;
setup_signals();
init_opts(&opts);
if (parse_params(argc, argv, &opts)) {
rc = -1;
goto out2;
}
if (opts.msg_q_path && setup_msg_q(&opts)) {
rc = -2;
goto out2;
}
all_adapters = malloc(sizeof(struct adapters)
+ opts.num_hosts * sizeof(struct adapter_data));
if (init_adapters(all_adapters, &opts)) {
rc = -8;
goto out2;
}
init_result_wrp(&result_wrp, all_adapters->num_adapters, &opts);
if (init_ioerr_wrp(&ioerr, &opts)) {
rc = -3;
goto out;
}
gettimeofday(&sample_end, NULL);
timerclear(&interval_end);
timerclear(&duration_end);
timerclear(&first_interval);
timeradd(&interval_end, &sample_end, &interval_end);
timeradd(&first_interval, &sample_end, &first_interval);
first_interval.tv_sec += opts.i_duration;
timeradd(&duration_end, &sample_end, &duration_end);
duration_end.tv_sec += opts.duration;
do {
interval_end.tv_sec += opts.i_duration;
reinit_adapters(all_adapters);
do {
sample_end.tv_sec += opts.s_duration;
sleep_until(&sample_end);
poll_utilization(all_adapters);
if (timercmp(&sample_end, &interval_end, >=)) {
/* final sample in interval */
if (poll_queue_full(0, all_adapters)) {
rc = -3;
goto out;
}
if (poll_ioerr_cnt(0, &ioerr->data, &opts)) {
rc = -7;
goto out;
}
}
} while (keep_running
&& timercmp(&sample_end, &interval_end, <));
if (!keep_running)
break; /* only publish results after a full cycle */
generate_result(&result_wrp->o_res, all_adapters);
if (opts.msg_q >= 0)
/* Always print the first and the last message */
print_to_msg_q(result_wrp, ioerr, &opts,
(timercmp(&interval_end, &first_interval, ==)
|| timercmp(&interval_end, &duration_end, >=)));
else {
print_utilization_result(&result_wrp->o_res);
print_ioerr_data(&ioerr->data);
}
/* we only have to sleep in case d_interval is not
a multiple of i_interval */
sleep_until(&interval_end);
} while (keep_running && timercmp(&interval_end, &duration_end, <));
if (!keep_running)
verbose_msg("signal received, ending...\n");
out:
deinit_adapters(all_adapters);
deinit_result_wrp(&result_wrp);
out2:
deinit_opts(&opts);
free(all_adapters);
free(ioerr);
return rc;
}
#endif
| gpl-2.0 |
Maximuzzzzz/myagent-im | src/gui/contactinfolistwindow.cpp | 1 | 3399 | /***************************************************************************
* Copyright (C) 2008 by Alexander Volkov *
* volkov0aa@gmail.com *
* *
* This file is part of instant messenger MyAgent-IM *
* *
* MyAgent-IM 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. *
* *
* MyAgent-IM is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "contactinfolistwindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QCheckBox>
#include "gui/contactinfolistwidget.h"
#include "gui/centerwindow.h"
ContactInfoListWindow::ContactInfoListWindow(Account* account)
{
setWindowTitle(tr("Contacts found"));
setWindowIcon(QIcon(":icons/cl_add_contact.png"));
setAttribute(Qt::WA_DeleteOnClose);
QVBoxLayout* layout = new QVBoxLayout;
infoListWidget = new ContactInfoListWidget(account, this);
QCheckBox* showPhotosCheckBox = new QCheckBox(tr("Show photos"));
connect(showPhotosCheckBox, SIGNAL(toggled(bool)), infoListWidget, SLOT(showPhotos(bool)));
QPushButton* addButton = new QPushButton(tr("Add contact"));
connect(addButton, SIGNAL(clicked(bool)), this, SLOT(slotAddButtonClicked()));
moreContactsButton = new QPushButton();
connect(moreContactsButton, SIGNAL(clicked(bool)), SIGNAL(moreContactsButtonClicked()));
QPushButton* newSearchButton = new QPushButton(tr("New search"));
connect(newSearchButton, SIGNAL(clicked(bool)), SIGNAL(newSearchButtonClicked()));
QHBoxLayout* buttonsLayout = new QHBoxLayout;
buttonsLayout->addWidget(showPhotosCheckBox);
buttonsLayout->addStretch();
buttonsLayout->addWidget(addButton);
buttonsLayout->addWidget(moreContactsButton);
buttonsLayout->addWidget(newSearchButton);
layout->addWidget(infoListWidget);
layout->addLayout(buttonsLayout);
setLayout(layout);
}
void ContactInfoListWindow::setInfo(const QList<ContactInfo>& info, uint maxRows)
{
infoListWidget->setInfo(info);
moreContactsButton->setText(tr("Another %1 contacts").arg(maxRows));
if (info.size() < maxRows)
moreContactsButton->setDisabled(true);
else
moreContactsButton->setEnabled(true);
resize(sizeHint());
centerWindow(this);
}
void ContactInfoListWindow::slotAddButtonClicked()
{
if (infoListWidget->hasSelection())
Q_EMIT addButtonClicked(infoListWidget->selectedInfo());
}
| gpl-2.0 |
empeg/empeg-hijack | arch/i386/kdb/kdb_io.c | 1 | 4934 | /*
* Kernel Debugger Console I/O handler
*
* Copyright 1999, Silicon Graphics, Inc.
*
* Written March 1999 by Scott Lurndal at Silicon Graphics, Inc.
*
* Modifications from:
* Chuck Fleckenstein 1999/07/20
* Move kdb_info struct declaration to this file
* for cases where serial support is not compiled into
* the kernel.
*
* Masahiro Adegawa 1999/07/20
* Handle some peculiarities of japanese 86/106
* keyboards.
*
* marc@mucom.co.il 1999/07/20
* Catch buffer overflow for serial input.
*/
#include "linux/kernel.h"
#include "asm/io.h"
#include "pc_keyb.h"
#include "linux/console.h"
#include "linux/serial_reg.h"
int kdb_port = 0;
/*
* This module contains code to read characters from the keyboard or a serial
* port.
*
* It is used by the kernel debugger, and is polled, not interrupt driven.
*
*/
/*
* send: Send a byte to the keyboard controller. Used primarily to
* alter LED settings.
*/
static void
kdb_kbdsend(unsigned char byte)
{
while (inb(KBD_STATUS_REG) & KBD_STAT_IBF)
;
outb(KBD_DATA_REG, byte);
}
static void
kdb_kbdsetled(int leds)
{
kdb_kbdsend(KBD_CMD_SET_LEDS);
kdb_kbdsend((unsigned char)leds);
}
char *
kdb_getscancode(char *buffer, size_t bufsize)
{
char *cp = buffer;
int scancode, scanstatus;
static int shift_lock = 0; /* CAPS LOCK state (0-off, 1-on) */
static int shift_key = 0; /* Shift next keypress */
static int ctrl_key = 0;
static int leds = 2; /* Num lock */
u_short keychar;
extern u_short plain_map[], shift_map[], ctrl_map[];
bufsize -= 2; /* Reserve space for newline and null byte */
/*
* If we came in via a serial console, we allow that to
* be the input window for kdb.
*/
if (kdb_port != 0) {
char ch;
int status;
#define serial_inp(info, offset) inb((info) + (offset))
#define serial_out(info, offset, v) outb((v), (info) + (offset))
while(1) {
while ((status = serial_inp(kdb_port, UART_LSR))
& UART_LSR_DR) {
readchar:
ch = serial_inp(kdb_port, UART_RX);
if (ch == 8) { /* BS */
if (cp > buffer) {
--cp, bufsize++;
printk("%c %c", 0x08, 0x08);
}
continue;
}
serial_out(kdb_port, UART_TX, ch);
if (ch == 13) { /* CR */
*cp++ = '\n';
*cp++ = '\0';
serial_out(kdb_port, UART_TX, 10);
return(buffer);
}
/*
* Discard excess characters
*/
if (bufsize > 0) {
*cp++ = ch;
bufsize--;
}
}
while (((status = serial_inp(kdb_port, UART_LSR))
& UART_LSR_DR) == 0);
}
}
while (1) {
/*
* Wait for a valid scancode
*/
while ((inb(KBD_STATUS_REG) & KBD_STAT_OBF) == 0)
;
/*
* Fetch the scancode
*/
scancode = inb(KBD_DATA_REG);
scanstatus = inb(KBD_STATUS_REG);
/*
* Ignore mouse events.
*/
if (scanstatus & KBD_STAT_MOUSE_OBF)
continue;
/*
* Ignore release, trigger on make
* (except for shift keys, where we want to
* keep the shift state so long as the key is
* held down).
*/
if (((scancode&0x7f) == 0x2a)
|| ((scancode&0x7f) == 0x36)) {
/*
* Next key may use shift table
*/
if ((scancode & 0x80) == 0) {
shift_key=1;
} else {
shift_key=0;
}
continue;
}
if ((scancode&0x7f) == 0x1d) {
/*
* Left ctrl key
*/
if ((scancode & 0x80) == 0) {
ctrl_key = 1;
} else {
ctrl_key = 0;
}
continue;
}
if ((scancode & 0x80) != 0)
continue;
scancode &= 0x7f;
/*
* Translate scancode
*/
if (scancode == 0x3a) {
/*
* Toggle caps lock
*/
shift_lock ^= 1;
leds ^= 0x4; /* toggle caps lock led */
kdb_kbdsetled(leds);
continue;
}
if (scancode == 0x0e) {
/*
* Backspace
*/
if (cp > buffer) {
--cp, bufsize++;
/*
* XXX - erase character on screen
*/
printk("%c %c", 0x08, 0x08);
}
continue;
}
if (scancode == 0xe0) {
continue;
}
/*
* For Japanese 86/106 keyboards
* See comment in drivers/char/pc_keyb.c.
* - Masahiro Adegawa
*/
if (scancode == 0x73) {
scancode = 0x59;
} else if (scancode == 0x7d) {
scancode = 0x7c;
}
if (!shift_lock && !shift_key) {
keychar = plain_map[scancode];
} else if (shift_lock || shift_key) {
keychar = shift_map[scancode];
} else if (ctrl_key) {
keychar = ctrl_map[scancode];
} else {
keychar = 0x0020;
printk("Unknown state/scancode (%d)\n", scancode);
}
if ((scancode & 0x7f) == 0x1c) {
/*
* enter key. All done.
*/
printk("\n");
break;
}
/*
* echo the character.
*/
printk("%c", keychar&0xff);
if (bufsize) {
--bufsize;
*cp++ = keychar&0xff;
} else {
printk("buffer overflow\n");
break;
}
}
*cp++ = '\n'; /* White space for parser */
*cp++ = '\0'; /* String termination */
#if defined(NOTNOW)
cp = buffer;
while (*cp) {
printk("char 0x%x\n", *cp++);
}
#endif
return buffer;
}
| gpl-2.0 |
linuxdeepin/deepin-nautilus-properties | libnautilus-private/nautilus-monitor.c | 1 | 4717 | /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*-
nautilus-monitor.c: file and directory change monitoring for nautilus
Copyright (C) 2000, 2001 Eazel, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public
License along with this program; if not, see <http://www.gnu.org/licenses/>.
Authors: Seth Nickell <seth@eazel.com>
Darin Adler <darin@bentspoon.com>
Alex Graveley <alex@ximian.com>
*/
#include <config.h>
#include "nautilus-monitor.h"
#include "nautilus-file-changes-queue.h"
#include "nautilus-file-utilities.h"
#include <gio/gio.h>
struct NautilusMonitor {
GFileMonitor *monitor;
GVolumeMonitor *volume_monitor;
GFile *location;
};
gboolean
nautilus_monitor_active (void)
{
static gboolean tried_monitor = FALSE;
static gboolean monitor_success;
GFileMonitor *dir_monitor;
GFile *file;
if (tried_monitor == FALSE) {
file = g_file_new_for_path (g_get_home_dir ());
dir_monitor = g_file_monitor_directory (file, G_FILE_MONITOR_NONE, NULL, NULL);
g_object_unref (file);
monitor_success = (dir_monitor != NULL);
if (dir_monitor) {
g_object_unref (dir_monitor);
}
tried_monitor = TRUE;
}
return monitor_success;
}
static gboolean call_consume_changes_idle_id = 0;
static gboolean
call_consume_changes_idle_cb (gpointer not_used)
{
nautilus_file_changes_consume_changes (TRUE);
call_consume_changes_idle_id = 0;
return FALSE;
}
static void
schedule_call_consume_changes (void)
{
if (call_consume_changes_idle_id == 0) {
call_consume_changes_idle_id =
g_idle_add (call_consume_changes_idle_cb, NULL);
}
}
static void
mount_removed (GVolumeMonitor *volume_monitor,
GMount *mount,
gpointer user_data)
{
NautilusMonitor *monitor = user_data;
GFile *mount_location;
mount_location = g_mount_get_root (mount);
if (g_file_has_prefix (monitor->location, mount_location)) {
nautilus_file_changes_queue_file_removed (monitor->location);
schedule_call_consume_changes ();
}
g_object_unref (mount_location);
}
static void
dir_changed (GFileMonitor* monitor,
GFile *child,
GFile *other_file,
GFileMonitorEvent event_type,
gpointer user_data)
{
char *uri, *to_uri;
uri = g_file_get_uri (child);
to_uri = NULL;
if (other_file) {
to_uri = g_file_get_uri (other_file);
}
switch (event_type) {
default:
case G_FILE_MONITOR_EVENT_CHANGED:
/* ignore */
break;
case G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED:
case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
nautilus_file_changes_queue_file_changed (child);
break;
case G_FILE_MONITOR_EVENT_UNMOUNTED:
case G_FILE_MONITOR_EVENT_DELETED:
nautilus_file_changes_queue_file_removed (child);
break;
case G_FILE_MONITOR_EVENT_CREATED:
nautilus_file_changes_queue_file_added (child);
break;
}
g_free (uri);
g_free (to_uri);
schedule_call_consume_changes ();
}
NautilusMonitor *
nautilus_monitor_directory (GFile *location)
{
GFileMonitor *dir_monitor;
NautilusMonitor *ret;
ret = g_slice_new0 (NautilusMonitor);
dir_monitor = g_file_monitor_directory (location, G_FILE_MONITOR_WATCH_MOUNTS, NULL, NULL);
if (dir_monitor != NULL) {
ret->monitor = dir_monitor;
} else if (!g_file_is_native (location)) {
ret->location = g_object_ref (location);
ret->volume_monitor = g_volume_monitor_get ();
}
if (ret->monitor != NULL) {
g_signal_connect (ret->monitor, "changed",
G_CALLBACK (dir_changed), ret);
}
if (ret->volume_monitor != NULL) {
g_signal_connect (ret->volume_monitor, "mount-removed",
G_CALLBACK (mount_removed), ret);
}
/* We return a monitor even on failure, so we can avoid later trying again */
return ret;
}
void
nautilus_monitor_cancel (NautilusMonitor *monitor)
{
if (monitor->monitor != NULL) {
g_signal_handlers_disconnect_by_func (monitor->monitor, dir_changed, monitor);
g_file_monitor_cancel (monitor->monitor);
g_object_unref (monitor->monitor);
}
if (monitor->volume_monitor != NULL) {
g_signal_handlers_disconnect_by_func (monitor->volume_monitor, mount_removed, monitor);
g_object_unref (monitor->volume_monitor);
}
g_clear_object (&monitor->location);
g_slice_free (NautilusMonitor, monitor);
}
| gpl-2.0 |
nslu2/linux-2.4.x | arch/microblaze/kernel/procfs.c | 1 | 1422 | /*
* arch/microblaze/kernel/procfs.c -- Introspection functions for /proc filesystem
*
* Copyright (C) 2003 John Williams <jwilliams@itee.uq.edu.au>
*
* based heavily on v850 code that was
*
* Copyright (C) 2001,2002 NEC Corporation
* Copyright (C) 2001,2002 Miles Bader <miles@gnu.org>
*
* 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.
*
* Written by Miles Bader <miles@gnu.org>
*/
#include "mach.h"
static int cpuinfo_print (struct seq_file *m, void *v)
{
extern unsigned long loops_per_jiffy;
return seq_printf (m,
"CPU-Family: microblaze\n"
"CPU-Arch: %s\n"
"CPU-Model: %s\n"
"CPU-MHz: %lu.%02lu\n"
"BogoMips: %lu.%02lu\n",
CPU_ARCH,
CPU_MODEL,
CONFIG_CPU_CLOCK_FREQ/1000000,
CONFIG_CPU_CLOCK_FREQ % 1000000,
loops_per_jiffy/(500000/HZ),
(loops_per_jiffy/(5000/HZ)) % 100);
}
static void *cpuinfo_start (struct seq_file *m, loff_t *pos)
{
return *pos < NR_CPUS ? ((void *) 0x12345678) : NULL;
}
static void *cpuinfo_next (struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return cpuinfo_start (m, pos);
}
static void cpuinfo_stop (struct seq_file *m, void *v)
{
}
struct seq_operations cpuinfo_op = {
start: cpuinfo_start,
next: cpuinfo_next,
stop: cpuinfo_stop,
show: cpuinfo_print
};
| gpl-2.0 |
pgavin/or1k-gcc | libgo/go/bytes/indexbyte.c | 1 | 1098 | /* indexbyte.c -- implement bytes.IndexByte for Go.
Copyright 2009 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file. */
#include <stddef.h>
#include "runtime.h"
#include "array.h"
/* This is in C so that the compiler can optimize it appropriately.
We deliberately don't split the stack in case it does call the
library function, which shouldn't need much stack space. */
intgo IndexByte (struct __go_open_array, char)
asm ("bytes.IndexByte")
__attribute__ ((no_split_stack));
intgo
IndexByte (struct __go_open_array s, char b)
{
char *p;
p = __builtin_memchr (s.__values, b, s.__count);
if (p == NULL)
return -1;
return p - (char *) s.__values;
}
/* Comparison. */
_Bool Equal (struct __go_open_array a, struct __go_open_array b)
asm ("bytes.Equal")
__attribute__ ((no_split_stack));
_Bool
Equal (struct __go_open_array a, struct __go_open_array b)
{
if (a.__count != b.__count)
return 0;
return __builtin_memcmp (a.__values, b.__values, a.__count) == 0;
}
| gpl-2.0 |
sujithshankar/NetworkManager | src/settings/plugins/ifcfg-rh/writer.c | 1 | 80423 | /* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager system settings service - keyfile plugin
*
* 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.
*
* Copyright 2009 - 2014 Red Hat, Inc.
*/
#include "config.h"
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <nm-setting-connection.h>
#include <nm-setting-wired.h>
#include <nm-setting-wireless.h>
#include <nm-setting-8021x.h>
#include <nm-setting-ip4-config.h>
#include <nm-setting-ip6-config.h>
#include <nm-setting-pppoe.h>
#include <nm-setting-vlan.h>
#include <nm-setting-team.h>
#include <nm-setting-team-port.h>
#include "nm-core-internal.h"
#include <nm-utils.h>
#include "nm-logging.h"
#include "common.h"
#include "shvar.h"
#include "reader.h"
#include "writer.h"
#include "utils.h"
#include "crypto.h"
static void
save_secret_flags (shvarFile *ifcfg,
const char *key,
NMSettingSecretFlags flags)
{
GString *str;
g_return_if_fail (ifcfg != NULL);
g_return_if_fail (key != NULL);
if (flags == NM_SETTING_SECRET_FLAG_NONE) {
svSetValue (ifcfg, key, NULL, FALSE);
return;
}
/* Convert flags bitfield into string representation */
str = g_string_sized_new (20);
if (flags & NM_SETTING_SECRET_FLAG_AGENT_OWNED)
g_string_append (str, SECRET_FLAG_AGENT);
if (flags & NM_SETTING_SECRET_FLAG_NOT_SAVED) {
if (str->len)
g_string_append_c (str, ' ');
g_string_append (str, SECRET_FLAG_NOT_SAVED);
}
if (flags & NM_SETTING_SECRET_FLAG_NOT_REQUIRED) {
if (str->len)
g_string_append_c (str, ' ');
g_string_append (str, SECRET_FLAG_NOT_REQUIRED);
}
svSetValue (ifcfg, key, str->len ? str->str : NULL, FALSE);
g_string_free (str, TRUE);
}
static void
set_secret (shvarFile *ifcfg,
const char *key,
const char *value,
const char *flags_key,
NMSettingSecretFlags flags,
gboolean verbatim)
{
shvarFile *keyfile;
GError *error = NULL;
/* Clear the secret from the ifcfg and the associated "keys" file */
svSetValue (ifcfg, key, NULL, FALSE);
/* Save secret flags */
save_secret_flags (ifcfg, flags_key, flags);
keyfile = utils_get_keys_ifcfg (ifcfg->fileName, TRUE);
if (!keyfile) {
nm_log_warn (LOGD_SETTINGS, " could not create ifcfg file for '%s'", ifcfg->fileName);
goto error;
}
/* Clear the secret from the associated "keys" file */
svSetValue (keyfile, key, NULL, FALSE);
/* Only write the secret if it's system owned and supposed to be saved */
if (flags == NM_SETTING_SECRET_FLAG_NONE)
svSetValue (keyfile, key, value, verbatim);
if (!svWriteFile (keyfile, 0600, &error)) {
nm_log_warn (LOGD_SETTINGS, " could not update ifcfg file '%s': %s",
keyfile->fileName, error->message);
g_clear_error (&error);
svCloseFile (keyfile);
goto error;
}
svCloseFile (keyfile);
return;
error:
/* Try setting the secret in the actual ifcfg */
svSetValue (ifcfg, key, value, FALSE);
}
static gboolean
write_secret_file (const char *path,
const char *data,
gsize len,
GError **error)
{
char *tmppath;
int fd = -1, written;
gboolean success = FALSE;
tmppath = g_malloc0 (strlen (path) + 10);
memcpy (tmppath, path, strlen (path));
strcat (tmppath, ".XXXXXX");
errno = 0;
fd = mkstemp (tmppath);
if (fd < 0) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Could not create temporary file for '%s': %d",
path, errno);
goto out;
}
/* Only readable by root */
errno = 0;
if (fchmod (fd, S_IRUSR | S_IWUSR)) {
close (fd);
unlink (tmppath);
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Could not set permissions for temporary file '%s': %d",
path, errno);
goto out;
}
errno = 0;
written = write (fd, data, len);
if (written != len) {
close (fd);
unlink (tmppath);
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Could not write temporary file for '%s': %d",
path, errno);
goto out;
}
close (fd);
/* Try to rename */
errno = 0;
if (rename (tmppath, path)) {
unlink (tmppath);
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Could not rename temporary file to '%s': %d",
path, errno);
goto out;
}
success = TRUE;
out:
g_free (tmppath);
return success;
}
typedef struct ObjectType {
const char *setting_key;
NMSetting8021xCKScheme (*scheme_func)(NMSetting8021x *setting);
const char * (*path_func) (NMSetting8021x *setting);
GBytes * (*blob_func) (NMSetting8021x *setting);
const char *ifcfg_key;
const char *suffix;
} ObjectType;
static const ObjectType ca_type = {
NM_SETTING_802_1X_CA_CERT,
nm_setting_802_1x_get_ca_cert_scheme,
nm_setting_802_1x_get_ca_cert_path,
nm_setting_802_1x_get_ca_cert_blob,
"IEEE_8021X_CA_CERT",
"ca-cert.der"
};
static const ObjectType phase2_ca_type = {
NM_SETTING_802_1X_PHASE2_CA_CERT,
nm_setting_802_1x_get_phase2_ca_cert_scheme,
nm_setting_802_1x_get_phase2_ca_cert_path,
nm_setting_802_1x_get_phase2_ca_cert_blob,
"IEEE_8021X_INNER_CA_CERT",
"inner-ca-cert.der"
};
static const ObjectType client_type = {
NM_SETTING_802_1X_CLIENT_CERT,
nm_setting_802_1x_get_client_cert_scheme,
nm_setting_802_1x_get_client_cert_path,
nm_setting_802_1x_get_client_cert_blob,
"IEEE_8021X_CLIENT_CERT",
"client-cert.der"
};
static const ObjectType phase2_client_type = {
NM_SETTING_802_1X_PHASE2_CLIENT_CERT,
nm_setting_802_1x_get_phase2_client_cert_scheme,
nm_setting_802_1x_get_phase2_client_cert_path,
nm_setting_802_1x_get_phase2_client_cert_blob,
"IEEE_8021X_INNER_CLIENT_CERT",
"inner-client-cert.der"
};
static const ObjectType pk_type = {
NM_SETTING_802_1X_PRIVATE_KEY,
nm_setting_802_1x_get_private_key_scheme,
nm_setting_802_1x_get_private_key_path,
nm_setting_802_1x_get_private_key_blob,
"IEEE_8021X_PRIVATE_KEY",
"private-key.pem"
};
static const ObjectType phase2_pk_type = {
NM_SETTING_802_1X_PHASE2_PRIVATE_KEY,
nm_setting_802_1x_get_phase2_private_key_scheme,
nm_setting_802_1x_get_phase2_private_key_path,
nm_setting_802_1x_get_phase2_private_key_blob,
"IEEE_8021X_INNER_PRIVATE_KEY",
"inner-private-key.pem"
};
static const ObjectType p12_type = {
NM_SETTING_802_1X_PRIVATE_KEY,
nm_setting_802_1x_get_private_key_scheme,
nm_setting_802_1x_get_private_key_path,
nm_setting_802_1x_get_private_key_blob,
"IEEE_8021X_PRIVATE_KEY",
"private-key.p12"
};
static const ObjectType phase2_p12_type = {
NM_SETTING_802_1X_PHASE2_PRIVATE_KEY,
nm_setting_802_1x_get_phase2_private_key_scheme,
nm_setting_802_1x_get_phase2_private_key_path,
nm_setting_802_1x_get_phase2_private_key_blob,
"IEEE_8021X_INNER_PRIVATE_KEY",
"inner-private-key.p12"
};
static gboolean
write_object (NMSetting8021x *s_8021x,
shvarFile *ifcfg,
const ObjectType *objtype,
GError **error)
{
NMSetting8021xCKScheme scheme;
const char *path = NULL;
GBytes *blob = NULL;
g_return_val_if_fail (ifcfg != NULL, FALSE);
g_return_val_if_fail (objtype != NULL, FALSE);
scheme = (*(objtype->scheme_func))(s_8021x);
switch (scheme) {
case NM_SETTING_802_1X_CK_SCHEME_BLOB:
blob = (*(objtype->blob_func))(s_8021x);
break;
case NM_SETTING_802_1X_CK_SCHEME_PATH:
path = (*(objtype->path_func))(s_8021x);
break;
default:
break;
}
/* If certificate/private key wasn't sent, the connection may no longer be
* 802.1x and thus we clear out the paths and certs.
*/
if (!path && !blob) {
char *standard_file;
int ignored;
/* Since no cert/private key is now being used, delete any standard file
* that was created for this connection, but leave other files alone.
* Thus, for example,
* /etc/sysconfig/network-scripts/ca-cert-Test_Write_Wifi_WPA_EAP-TLS.der
* will be deleted, but /etc/pki/tls/cert.pem will not.
*/
standard_file = utils_cert_path (ifcfg->fileName, objtype->suffix);
if (g_file_test (standard_file, G_FILE_TEST_EXISTS))
ignored = unlink (standard_file);
g_free (standard_file);
svSetValue (ifcfg, objtype->ifcfg_key, NULL, FALSE);
return TRUE;
}
/* If the object path was specified, prefer that over any raw cert data that
* may have been sent.
*/
if (path) {
svSetValue (ifcfg, objtype->ifcfg_key, path, FALSE);
return TRUE;
}
/* If it's raw certificate data, write the data out to the standard file */
if (blob) {
gboolean success;
char *new_file;
GError *write_error = NULL;
new_file = utils_cert_path (ifcfg->fileName, objtype->suffix);
if (!new_file) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Could not create file path for %s / %s",
NM_SETTING_802_1X_SETTING_NAME, objtype->setting_key);
return FALSE;
}
/* Write the raw certificate data out to the standard file so that we
* can use paths from now on instead of pushing around the certificate
* data itself.
*/
success = write_secret_file (new_file,
(const char *) g_bytes_get_data (blob, NULL),
g_bytes_get_size (blob),
&write_error);
if (success) {
svSetValue (ifcfg, objtype->ifcfg_key, new_file, FALSE);
g_free (new_file);
return TRUE;
} else {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Could not write certificate/key for %s / %s: %s",
NM_SETTING_802_1X_SETTING_NAME, objtype->setting_key,
(write_error && write_error->message) ? write_error->message : "(unknown)");
g_clear_error (&write_error);
}
g_free (new_file);
}
return FALSE;
}
static gboolean
write_8021x_certs (NMSetting8021x *s_8021x,
gboolean phase2,
shvarFile *ifcfg,
GError **error)
{
const char *password = NULL;
gboolean success = FALSE, is_pkcs12 = FALSE;
const ObjectType *otype = NULL;
NMSettingSecretFlags flags = NM_SETTING_SECRET_FLAG_NONE;
/* CA certificate */
if (!write_object (s_8021x, ifcfg, phase2 ? &phase2_ca_type : &ca_type, error))
return FALSE;
/* Private key */
if (phase2) {
otype = &phase2_pk_type;
if (nm_setting_802_1x_get_phase2_private_key_format (s_8021x) == NM_SETTING_802_1X_CK_FORMAT_PKCS12) {
otype = &phase2_p12_type;
is_pkcs12 = TRUE;
}
password = nm_setting_802_1x_get_phase2_private_key_password (s_8021x);
flags = nm_setting_802_1x_get_phase2_private_key_password_flags (s_8021x);
} else {
otype = &pk_type;
if (nm_setting_802_1x_get_private_key_format (s_8021x) == NM_SETTING_802_1X_CK_FORMAT_PKCS12) {
otype = &p12_type;
is_pkcs12 = TRUE;
}
password = nm_setting_802_1x_get_private_key_password (s_8021x);
flags = nm_setting_802_1x_get_private_key_password_flags (s_8021x);
}
/* Save the private key */
if (!write_object (s_8021x, ifcfg, otype, error))
goto out;
/* Private key password */
if (phase2) {
set_secret (ifcfg,
"IEEE_8021X_INNER_PRIVATE_KEY_PASSWORD",
password,
"IEEE_8021X_INNER_PRIVATE_KEY_PASSWORD_FLAGS",
flags,
FALSE);
} else {
set_secret (ifcfg,
"IEEE_8021X_PRIVATE_KEY_PASSWORD",
password,
"IEEE_8021X_PRIVATE_KEY_PASSWORD_FLAGS",
flags,
FALSE);
}
/* Client certificate */
if (is_pkcs12) {
/* Don't need a client certificate with PKCS#12 since the file is both
* the client certificate and the private key in one file.
*/
svSetValue (ifcfg,
phase2 ? "IEEE_8021X_INNER_CLIENT_CERT" : "IEEE_8021X_CLIENT_CERT",
NULL, FALSE);
} else {
/* Save the client certificate */
if (!write_object (s_8021x, ifcfg, phase2 ? &phase2_client_type : &client_type, error))
goto out;
}
success = TRUE;
out:
return success;
}
static gboolean
write_8021x_setting (NMConnection *connection,
shvarFile *ifcfg,
gboolean wired,
GError **error)
{
NMSetting8021x *s_8021x;
const char *value, *match;
char *tmp = NULL;
gboolean success = FALSE;
GString *phase2_auth;
GString *str;
guint32 i, num;
s_8021x = nm_connection_get_setting_802_1x (connection);
if (!s_8021x) {
/* If wired, clear KEY_MGMT */
if (wired)
svSetValue (ifcfg, "KEY_MGMT", NULL, FALSE);
return TRUE;
}
/* If wired, write KEY_MGMT */
if (wired)
svSetValue (ifcfg, "KEY_MGMT", "IEEE8021X", FALSE);
/* EAP method */
if (nm_setting_802_1x_get_num_eap_methods (s_8021x)) {
value = nm_setting_802_1x_get_eap_method (s_8021x, 0);
if (value)
tmp = g_ascii_strup (value, -1);
}
svSetValue (ifcfg, "IEEE_8021X_EAP_METHODS", tmp ? tmp : NULL, FALSE);
g_free (tmp);
svSetValue (ifcfg, "IEEE_8021X_IDENTITY",
nm_setting_802_1x_get_identity (s_8021x),
FALSE);
svSetValue (ifcfg, "IEEE_8021X_ANON_IDENTITY",
nm_setting_802_1x_get_anonymous_identity (s_8021x),
FALSE);
set_secret (ifcfg,
"IEEE_8021X_PASSWORD",
nm_setting_802_1x_get_password (s_8021x),
"IEEE_8021X_PASSWORD_FLAGS",
nm_setting_802_1x_get_password_flags (s_8021x),
FALSE);
/* PEAP version */
value = nm_setting_802_1x_get_phase1_peapver (s_8021x);
svSetValue (ifcfg, "IEEE_8021X_PEAP_VERSION", NULL, FALSE);
if (value && (!strcmp (value, "0") || !strcmp (value, "1")))
svSetValue (ifcfg, "IEEE_8021X_PEAP_VERSION", value, FALSE);
/* Force new PEAP label */
value = nm_setting_802_1x_get_phase1_peaplabel (s_8021x);
svSetValue (ifcfg, "IEEE_8021X_PEAP_FORCE_NEW_LABEL", NULL, FALSE);
if (value && !strcmp (value, "1"))
svSetValue (ifcfg, "IEEE_8021X_PEAP_FORCE_NEW_LABEL", "yes", FALSE);
/* PAC file */
value = nm_setting_802_1x_get_pac_file (s_8021x);
svSetValue (ifcfg, "IEEE_8021X_PAC_FILE", NULL, FALSE);
if (value)
svSetValue (ifcfg, "IEEE_8021X_PAC_FILE", value, FALSE);
/* FAST PAC provisioning */
value = nm_setting_802_1x_get_phase1_fast_provisioning (s_8021x);
svSetValue (ifcfg, "IEEE_8021X_FAST_PROVISIONING", NULL, FALSE);
if (value) {
if (strcmp (value, "1") == 0)
svSetValue (ifcfg, "IEEE_8021X_FAST_PROVISIONING", "allow-unauth", FALSE);
else if (strcmp (value, "2") == 0)
svSetValue (ifcfg, "IEEE_8021X_FAST_PROVISIONING", "allow-auth", FALSE);
else if (strcmp (value, "3") == 0)
svSetValue (ifcfg, "IEEE_8021X_FAST_PROVISIONING", "allow-unauth allow-auth", FALSE);
}
/* Phase2 auth methods */
svSetValue (ifcfg, "IEEE_8021X_INNER_AUTH_METHODS", NULL, FALSE);
phase2_auth = g_string_new (NULL);
value = nm_setting_802_1x_get_phase2_auth (s_8021x);
if (value) {
tmp = g_ascii_strup (value, -1);
g_string_append (phase2_auth, tmp);
g_free (tmp);
}
value = nm_setting_802_1x_get_phase2_autheap (s_8021x);
if (value) {
if (phase2_auth->len)
g_string_append_c (phase2_auth, ' ');
tmp = g_ascii_strup (value, -1);
g_string_append_printf (phase2_auth, "EAP-%s", tmp);
g_free (tmp);
}
svSetValue (ifcfg, "IEEE_8021X_INNER_AUTH_METHODS",
phase2_auth->len ? phase2_auth->str : NULL,
FALSE);
g_string_free (phase2_auth, TRUE);
svSetValue (ifcfg, "IEEE_8021X_SUBJECT_MATCH",
nm_setting_802_1x_get_subject_match (s_8021x),
FALSE);
svSetValue (ifcfg, "IEEE_8021X_PHASE2_SUBJECT_MATCH",
nm_setting_802_1x_get_phase2_subject_match (s_8021x),
FALSE);
svSetValue (ifcfg, "IEEE_8021X_ALTSUBJECT_MATCHES", NULL, FALSE);
str = g_string_new (NULL);
num = nm_setting_802_1x_get_num_altsubject_matches (s_8021x);
for (i = 0; i < num; i++) {
if (i > 0)
g_string_append_c (str, ' ');
match = nm_setting_802_1x_get_altsubject_match (s_8021x, i);
g_string_append (str, match);
}
if (str->len > 0)
svSetValue (ifcfg, "IEEE_8021X_ALTSUBJECT_MATCHES", str->str, FALSE);
g_string_free (str, TRUE);
svSetValue (ifcfg, "IEEE_8021X_PHASE2_ALTSUBJECT_MATCHES", NULL, FALSE);
str = g_string_new (NULL);
num = nm_setting_802_1x_get_num_phase2_altsubject_matches (s_8021x);
for (i = 0; i < num; i++) {
if (i > 0)
g_string_append_c (str, ' ');
match = nm_setting_802_1x_get_phase2_altsubject_match (s_8021x, i);
g_string_append (str, match);
}
if (str->len > 0)
svSetValue (ifcfg, "IEEE_8021X_PHASE2_ALTSUBJECT_MATCHES", str->str, FALSE);
g_string_free (str, TRUE);
success = write_8021x_certs (s_8021x, FALSE, ifcfg, error);
if (success) {
/* phase2/inner certs */
success = write_8021x_certs (s_8021x, TRUE, ifcfg, error);
}
return success;
}
static gboolean
write_wireless_security_setting (NMConnection *connection,
shvarFile *ifcfg,
gboolean adhoc,
gboolean *no_8021x,
GError **error)
{
NMSettingWirelessSecurity *s_wsec;
const char *key_mgmt, *auth_alg, *key, *proto, *cipher, *psk;
gboolean wep = FALSE, wpa = FALSE, dynamic_wep = FALSE;
char *tmp;
guint32 i, num;
GString *str;
s_wsec = nm_connection_get_setting_wireless_security (connection);
if (!s_wsec) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing '%s' setting", NM_SETTING_WIRELESS_SECURITY_SETTING_NAME);
return FALSE;
}
key_mgmt = nm_setting_wireless_security_get_key_mgmt (s_wsec);
g_assert (key_mgmt);
auth_alg = nm_setting_wireless_security_get_auth_alg (s_wsec);
svSetValue (ifcfg, "DEFAULTKEY", NULL, FALSE);
if (!strcmp (key_mgmt, "none")) {
svSetValue (ifcfg, "KEY_MGMT", NULL, FALSE);
wep = TRUE;
*no_8021x = TRUE;
} else if (!strcmp (key_mgmt, "wpa-none") || !strcmp (key_mgmt, "wpa-psk")) {
svSetValue (ifcfg, "KEY_MGMT", "WPA-PSK", FALSE);
wpa = TRUE;
*no_8021x = TRUE;
} else if (!strcmp (key_mgmt, "ieee8021x")) {
svSetValue (ifcfg, "KEY_MGMT", "IEEE8021X", FALSE);
dynamic_wep = TRUE;
} else if (!strcmp (key_mgmt, "wpa-eap")) {
svSetValue (ifcfg, "KEY_MGMT", "WPA-EAP", FALSE);
wpa = TRUE;
}
svSetValue (ifcfg, "SECURITYMODE", NULL, FALSE);
if (auth_alg) {
if (!strcmp (auth_alg, "shared"))
svSetValue (ifcfg, "SECURITYMODE", "restricted", FALSE);
else if (!strcmp (auth_alg, "open"))
svSetValue (ifcfg, "SECURITYMODE", "open", FALSE);
else if (!strcmp (auth_alg, "leap")) {
svSetValue (ifcfg, "SECURITYMODE", "leap", FALSE);
svSetValue (ifcfg, "IEEE_8021X_IDENTITY",
nm_setting_wireless_security_get_leap_username (s_wsec),
FALSE);
set_secret (ifcfg,
"IEEE_8021X_PASSWORD",
nm_setting_wireless_security_get_leap_password (s_wsec),
"IEEE_8021X_PASSWORD_FLAGS",
nm_setting_wireless_security_get_leap_password_flags (s_wsec),
FALSE);
*no_8021x = TRUE;
}
}
/* WEP keys */
/* Clear any default key */
set_secret (ifcfg, "KEY", NULL, "WEP_KEY_FLAGS", NM_SETTING_SECRET_FLAG_NONE, FALSE);
/* Clear existing keys */
for (i = 0; i < 4; i++) {
tmp = g_strdup_printf ("KEY_PASSPHRASE%d", i + 1);
set_secret (ifcfg, tmp, NULL, "WEP_KEY_FLAGS", NM_SETTING_SECRET_FLAG_NONE, FALSE);
g_free (tmp);
tmp = g_strdup_printf ("KEY%d", i + 1);
set_secret (ifcfg, tmp, NULL, "WEP_KEY_FLAGS", NM_SETTING_SECRET_FLAG_NONE, FALSE);
g_free (tmp);
}
/* And write the new ones out */
if (wep) {
/* Default WEP TX key index */
tmp = g_strdup_printf ("%d", nm_setting_wireless_security_get_wep_tx_keyidx (s_wsec) + 1);
svSetValue (ifcfg, "DEFAULTKEY", tmp, FALSE);
g_free (tmp);
for (i = 0; i < 4; i++) {
NMWepKeyType key_type;
key = nm_setting_wireless_security_get_wep_key (s_wsec, i);
if (key) {
char *ascii_key = NULL;
/* Passphrase needs a different ifcfg key since with WEP, there
* are some passphrases that are indistinguishable from WEP hex
* keys.
*/
key_type = nm_setting_wireless_security_get_wep_key_type (s_wsec);
if (key_type == NM_WEP_KEY_TYPE_PASSPHRASE)
tmp = g_strdup_printf ("KEY_PASSPHRASE%d", i + 1);
else {
tmp = g_strdup_printf ("KEY%d", i + 1);
/* Add 's:' prefix for ASCII keys */
if (strlen (key) == 5 || strlen (key) == 13) {
ascii_key = g_strdup_printf ("s:%s", key);
key = ascii_key;
}
}
set_secret (ifcfg,
tmp,
key,
"WEP_KEY_FLAGS",
nm_setting_wireless_security_get_wep_key_flags (s_wsec),
FALSE);
g_free (tmp);
g_free (ascii_key);
}
}
}
/* WPA protos */
svSetValue (ifcfg, "WPA_ALLOW_WPA", NULL, FALSE);
svSetValue (ifcfg, "WPA_ALLOW_WPA2", NULL, FALSE);
num = nm_setting_wireless_security_get_num_protos (s_wsec);
for (i = 0; i < num; i++) {
proto = nm_setting_wireless_security_get_proto (s_wsec, i);
if (proto && !strcmp (proto, "wpa"))
svSetValue (ifcfg, "WPA_ALLOW_WPA", "yes", FALSE);
else if (proto && !strcmp (proto, "rsn"))
svSetValue (ifcfg, "WPA_ALLOW_WPA2", "yes", FALSE);
}
/* WPA Pairwise ciphers */
svSetValue (ifcfg, "CIPHER_PAIRWISE", NULL, FALSE);
str = g_string_new (NULL);
num = nm_setting_wireless_security_get_num_pairwise (s_wsec);
for (i = 0; i < num; i++) {
if (i > 0)
g_string_append_c (str, ' ');
cipher = nm_setting_wireless_security_get_pairwise (s_wsec, i);
/* Don't write out WEP40 or WEP104 if for some reason they are set; they
* are not valid pairwise ciphers.
*/
if (strcmp (cipher, "wep40") && strcmp (cipher, "wep104")) {
tmp = g_ascii_strup (cipher, -1);
g_string_append (str, tmp);
g_free (tmp);
}
}
if (strlen (str->str) && (dynamic_wep == FALSE))
svSetValue (ifcfg, "CIPHER_PAIRWISE", str->str, FALSE);
g_string_free (str, TRUE);
/* WPA Group ciphers */
svSetValue (ifcfg, "CIPHER_GROUP", NULL, FALSE);
str = g_string_new (NULL);
num = nm_setting_wireless_security_get_num_groups (s_wsec);
for (i = 0; i < num; i++) {
if (i > 0)
g_string_append_c (str, ' ');
cipher = nm_setting_wireless_security_get_group (s_wsec, i);
tmp = g_ascii_strup (cipher, -1);
g_string_append (str, tmp);
g_free (tmp);
}
if (strlen (str->str) && (dynamic_wep == FALSE))
svSetValue (ifcfg, "CIPHER_GROUP", str->str, FALSE);
g_string_free (str, TRUE);
/* WPA Passphrase */
if (wpa) {
char *quoted = NULL;
psk = nm_setting_wireless_security_get_psk (s_wsec);
if (psk && (strlen (psk) != 64)) {
/* Quote the PSK since it's a passphrase */
quoted = utils_single_quote_string (psk);
}
set_secret (ifcfg,
"WPA_PSK",
quoted ? quoted : psk,
"WPA_PSK_FLAGS",
nm_setting_wireless_security_get_psk_flags (s_wsec),
TRUE);
g_free (quoted);
} else {
set_secret (ifcfg,
"WPA_PSK",
NULL,
"WPA_PSK_FLAGS",
NM_SETTING_SECRET_FLAG_NONE,
FALSE);
}
return TRUE;
}
static gboolean
write_wireless_setting (NMConnection *connection,
shvarFile *ifcfg,
gboolean *no_8021x,
GError **error)
{
NMSettingWireless *s_wireless;
char *tmp, *tmp2;
GBytes *ssid;
const guint8 *ssid_data;
gsize ssid_len;
const char *mode, *bssid;
const char *device_mac, *cloned_mac;
char buf[33];
guint32 mtu, chan, i;
gboolean adhoc = FALSE, hex_ssid = FALSE;
const char * const *macaddr_blacklist;
s_wireless = nm_connection_get_setting_wireless (connection);
if (!s_wireless) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing '%s' setting", NM_SETTING_WIRELESS_SETTING_NAME);
return FALSE;
}
device_mac = nm_setting_wireless_get_mac_address (s_wireless);
svSetValue (ifcfg, "HWADDR", device_mac, FALSE);
cloned_mac = nm_setting_wireless_get_cloned_mac_address (s_wireless);
svSetValue (ifcfg, "MACADDR", cloned_mac, FALSE);
svSetValue (ifcfg, "HWADDR_BLACKLIST", NULL, FALSE);
macaddr_blacklist = nm_setting_wireless_get_mac_address_blacklist (s_wireless);
if (macaddr_blacklist[0]) {
char *blacklist_str;
blacklist_str = g_strjoinv (" ", (char **) macaddr_blacklist);
svSetValue (ifcfg, "HWADDR_BLACKLIST", blacklist_str, FALSE);
g_free (blacklist_str);
}
svSetValue (ifcfg, "MTU", NULL, FALSE);
mtu = nm_setting_wireless_get_mtu (s_wireless);
if (mtu) {
tmp = g_strdup_printf ("%u", mtu);
svSetValue (ifcfg, "MTU", tmp, FALSE);
g_free (tmp);
}
ssid = nm_setting_wireless_get_ssid (s_wireless);
if (!ssid) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing SSID in '%s' setting", NM_SETTING_WIRELESS_SETTING_NAME);
return FALSE;
}
ssid_data = g_bytes_get_data (ssid, &ssid_len);
if (!ssid_len || ssid_len > 32) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Invalid SSID in '%s' setting", NM_SETTING_WIRELESS_SETTING_NAME);
return FALSE;
}
/* If the SSID contains any non-printable characters, we need to use the
* hex notation of the SSID instead.
*/
for (i = 0; i < ssid_len; i++) {
if (!g_ascii_isprint (ssid_data[i])) {
hex_ssid = TRUE;
break;
}
}
if (hex_ssid) {
GString *str;
/* Hex SSIDs don't get quoted */
str = g_string_sized_new (ssid_len * 2 + 3);
g_string_append (str, "0x");
for (i = 0; i < ssid_len; i++)
g_string_append_printf (str, "%02X", ssid_data[i]);
svSetValue (ifcfg, "ESSID", str->str, TRUE);
g_string_free (str, TRUE);
} else {
/* Printable SSIDs always get quoted */
memset (buf, 0, sizeof (buf));
memcpy (buf, ssid_data, ssid_len);
tmp = svEscape (buf);
/* svEscape will usually quote the string, but just for consistency,
* if svEscape doesn't quote the ESSID, we quote it ourselves.
*/
if (tmp[0] != '"' && tmp[strlen (tmp) - 1] != '"') {
tmp2 = g_strdup_printf ("\"%s\"", tmp);
svSetValue (ifcfg, "ESSID", tmp2, TRUE);
g_free (tmp2);
} else
svSetValue (ifcfg, "ESSID", tmp, TRUE);
g_free (tmp);
}
mode = nm_setting_wireless_get_mode (s_wireless);
if (!mode || !strcmp (mode, "infrastructure")) {
svSetValue (ifcfg, "MODE", "Managed", FALSE);
} else if (!strcmp (mode, "adhoc")) {
svSetValue (ifcfg, "MODE", "Ad-Hoc", FALSE);
adhoc = TRUE;
} else if (!strcmp (mode, "ap")) {
svSetValue (ifcfg, "MODE", "Ap", FALSE);
} else {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Invalid mode '%s' in '%s' setting",
mode, NM_SETTING_WIRELESS_SETTING_NAME);
return FALSE;
}
svSetValue (ifcfg, "CHANNEL", NULL, FALSE);
svSetValue (ifcfg, "BAND", NULL, FALSE);
chan = nm_setting_wireless_get_channel (s_wireless);
if (chan) {
tmp = g_strdup_printf ("%u", chan);
svSetValue (ifcfg, "CHANNEL", tmp, FALSE);
g_free (tmp);
} else {
/* Band only set if channel is not, since channel implies band */
svSetValue (ifcfg, "BAND", nm_setting_wireless_get_band (s_wireless), FALSE);
}
bssid = nm_setting_wireless_get_bssid (s_wireless);
svSetValue (ifcfg, "BSSID", bssid, FALSE);
/* Ensure DEFAULTKEY and SECURITYMODE are cleared unless there's security;
* otherwise there's no way to detect WEP vs. open when WEP keys aren't
* saved.
*/
svSetValue (ifcfg, "DEFAULTKEY", NULL, FALSE);
svSetValue (ifcfg, "SECURITYMODE", NULL, FALSE);
if (nm_connection_get_setting_wireless_security (connection)) {
if (!write_wireless_security_setting (connection, ifcfg, adhoc, no_8021x, error))
return FALSE;
} else {
char *keys_path;
/* Clear out wifi security keys */
svSetValue (ifcfg, "KEY_MGMT", NULL, FALSE);
svSetValue (ifcfg, "IEEE_8021X_IDENTITY", NULL, FALSE);
set_secret (ifcfg, "IEEE_8021X_PASSWORD", NULL, "IEEE_8021X_PASSWORD_FLAGS", NM_SETTING_SECRET_FLAG_NONE, FALSE);
svSetValue (ifcfg, "SECURITYMODE", NULL, FALSE);
/* Clear existing keys */
set_secret (ifcfg, "KEY", NULL, "WEP_KEY_FLAGS", NM_SETTING_SECRET_FLAG_NONE, FALSE);
for (i = 0; i < 4; i++) {
tmp = g_strdup_printf ("KEY_PASSPHRASE%d", i + 1);
set_secret (ifcfg, tmp, NULL, "WEP_KEY_FLAGS", NM_SETTING_SECRET_FLAG_NONE, FALSE);
g_free (tmp);
tmp = g_strdup_printf ("KEY%d", i + 1);
set_secret (ifcfg, tmp, NULL, "WEP_KEY_FLAGS", NM_SETTING_SECRET_FLAG_NONE, FALSE);
g_free (tmp);
}
svSetValue (ifcfg, "DEFAULTKEY", NULL, FALSE);
svSetValue (ifcfg, "WPA_ALLOW_WPA", NULL, FALSE);
svSetValue (ifcfg, "WPA_ALLOW_WPA2", NULL, FALSE);
svSetValue (ifcfg, "CIPHER_PAIRWISE", NULL, FALSE);
svSetValue (ifcfg, "CIPHER_GROUP", NULL, FALSE);
set_secret (ifcfg, "WPA_PSK", NULL, "WPA_PSK_FLAGS", NM_SETTING_SECRET_FLAG_NONE, FALSE);
/* Kill any old keys file */
keys_path = utils_get_keys_path (ifcfg->fileName);
(void) unlink (keys_path);
g_free (keys_path);
}
svSetValue (ifcfg, "SSID_HIDDEN", nm_setting_wireless_get_hidden (s_wireless) ? "yes" : NULL, TRUE);
svSetValue (ifcfg, "TYPE", TYPE_WIRELESS, FALSE);
return TRUE;
}
static gboolean
write_infiniband_setting (NMConnection *connection, shvarFile *ifcfg, GError **error)
{
NMSettingInfiniband *s_infiniband;
char *tmp;
const char *mac, *transport_mode, *parent;
guint32 mtu;
int p_key;
s_infiniband = nm_connection_get_setting_infiniband (connection);
if (!s_infiniband) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing '%s' setting", NM_SETTING_INFINIBAND_SETTING_NAME);
return FALSE;
}
mac = nm_setting_infiniband_get_mac_address (s_infiniband);
svSetValue (ifcfg, "HWADDR", mac, FALSE);
svSetValue (ifcfg, "MTU", NULL, FALSE);
mtu = nm_setting_infiniband_get_mtu (s_infiniband);
if (mtu) {
tmp = g_strdup_printf ("%u", mtu);
svSetValue (ifcfg, "MTU", tmp, FALSE);
g_free (tmp);
}
transport_mode = nm_setting_infiniband_get_transport_mode (s_infiniband);
svSetValue (ifcfg, "CONNECTED_MODE",
strcmp (transport_mode, "connected") == 0 ? "yes" : "no",
FALSE);
p_key = nm_setting_infiniband_get_p_key (s_infiniband);
if (p_key != -1) {
svSetValue (ifcfg, "PKEY", "yes", FALSE);
tmp = g_strdup_printf ("%u", p_key);
svSetValue (ifcfg, "PKEY_ID", tmp, FALSE);
g_free (tmp);
parent = nm_setting_infiniband_get_parent (s_infiniband);
if (parent)
svSetValue (ifcfg, "PHYSDEV", parent, FALSE);
}
svSetValue (ifcfg, "TYPE", TYPE_INFINIBAND, FALSE);
return TRUE;
}
static gboolean
write_wired_setting (NMConnection *connection, shvarFile *ifcfg, GError **error)
{
NMSettingWired *s_wired;
const char *device_mac, *cloned_mac;
char *tmp;
const char *nettype, *portname, *ctcprot, *s390_key, *s390_val;
guint32 mtu, num_opts, i;
const char *const *s390_subchannels;
GString *str;
const char * const *macaddr_blacklist;
s_wired = nm_connection_get_setting_wired (connection);
if (!s_wired) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing '%s' setting", NM_SETTING_WIRED_SETTING_NAME);
return FALSE;
}
device_mac = nm_setting_wired_get_mac_address (s_wired);
svSetValue (ifcfg, "HWADDR", device_mac, FALSE);
cloned_mac = nm_setting_wired_get_cloned_mac_address (s_wired);
svSetValue (ifcfg, "MACADDR", cloned_mac, FALSE);
svSetValue (ifcfg, "HWADDR_BLACKLIST", NULL, FALSE);
macaddr_blacklist = nm_setting_wired_get_mac_address_blacklist (s_wired);
if (macaddr_blacklist[0]) {
char *blacklist_str;
blacklist_str = g_strjoinv (" ", (char **) macaddr_blacklist);
svSetValue (ifcfg, "HWADDR_BLACKLIST", blacklist_str, FALSE);
g_free (blacklist_str);
}
svSetValue (ifcfg, "MTU", NULL, FALSE);
mtu = nm_setting_wired_get_mtu (s_wired);
if (mtu) {
tmp = g_strdup_printf ("%u", mtu);
svSetValue (ifcfg, "MTU", tmp, FALSE);
g_free (tmp);
}
svSetValue (ifcfg, "SUBCHANNELS", NULL, FALSE);
s390_subchannels = nm_setting_wired_get_s390_subchannels (s_wired);
if (s390_subchannels) {
int len = g_strv_length ((char **)s390_subchannels);
tmp = NULL;
if (len == 2) {
tmp = g_strdup_printf ("%s,%s", s390_subchannels[0], s390_subchannels[1]);
} else if (len == 3) {
tmp = g_strdup_printf ("%s,%s,%s", s390_subchannels[0], s390_subchannels[1],
s390_subchannels[2]);
}
svSetValue (ifcfg, "SUBCHANNELS", tmp, FALSE);
g_free (tmp);
}
svSetValue (ifcfg, "NETTYPE", NULL, FALSE);
nettype = nm_setting_wired_get_s390_nettype (s_wired);
if (nettype)
svSetValue (ifcfg, "NETTYPE", nettype, FALSE);
svSetValue (ifcfg, "PORTNAME", NULL, FALSE);
portname = nm_setting_wired_get_s390_option_by_key (s_wired, "portname");
if (portname)
svSetValue (ifcfg, "PORTNAME", portname, FALSE);
svSetValue (ifcfg, "CTCPROT", NULL, FALSE);
ctcprot = nm_setting_wired_get_s390_option_by_key (s_wired, "ctcprot");
if (ctcprot)
svSetValue (ifcfg, "CTCPROT", ctcprot, FALSE);
svSetValue (ifcfg, "OPTIONS", NULL, FALSE);
num_opts = nm_setting_wired_get_num_s390_options (s_wired);
if (s390_subchannels && num_opts) {
str = g_string_sized_new (30);
for (i = 0; i < num_opts; i++) {
nm_setting_wired_get_s390_option (s_wired, i, &s390_key, &s390_val);
/* portname is handled separately */
if (!strcmp (s390_key, "portname") || !strcmp (s390_key, "ctcprot"))
continue;
if (str->len)
g_string_append_c (str, ' ');
g_string_append_printf (str, "%s=%s", s390_key, s390_val);
}
if (str->len)
svSetValue (ifcfg, "OPTIONS", str->str, FALSE);
g_string_free (str, TRUE);
}
svSetValue (ifcfg, "TYPE", TYPE_ETHERNET, FALSE);
return TRUE;
}
static char *
vlan_priority_maplist_to_stringlist (NMSettingVlan *s_vlan, NMVlanPriorityMap map)
{
char **strlist;
char *value;
if (map == NM_VLAN_INGRESS_MAP)
g_object_get (G_OBJECT (s_vlan), NM_SETTING_VLAN_INGRESS_PRIORITY_MAP, &strlist, NULL);
else if (map == NM_VLAN_EGRESS_MAP)
g_object_get (G_OBJECT (s_vlan), NM_SETTING_VLAN_EGRESS_PRIORITY_MAP, &strlist, NULL);
else
return NULL;
if (strlist[0])
value = g_strjoinv (",", strlist);
else
value = NULL;
g_strfreev (strlist);
return value;
}
static gboolean
write_vlan_setting (NMConnection *connection, shvarFile *ifcfg, gboolean *wired, GError **error)
{
NMSettingVlan *s_vlan;
NMSettingConnection *s_con;
NMSettingWired *s_wired;
char *tmp;
guint32 vlan_flags = 0;
s_con = nm_connection_get_setting_connection (connection);
if (!s_con) {
g_set_error_literal (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing connection setting");
return FALSE;
}
s_vlan = nm_connection_get_setting_vlan (connection);
if (!s_vlan) {
g_set_error_literal (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing VLAN setting");
return FALSE;
}
svSetValue (ifcfg, "VLAN", "yes", FALSE);
svSetValue (ifcfg, "TYPE", TYPE_VLAN, FALSE);
svSetValue (ifcfg, "DEVICE", nm_setting_connection_get_interface_name (s_con), FALSE);
svSetValue (ifcfg, "PHYSDEV", nm_setting_vlan_get_parent (s_vlan), FALSE);
tmp = g_strdup_printf ("%d", nm_setting_vlan_get_id (s_vlan));
svSetValue (ifcfg, "VLAN_ID", tmp, FALSE);
g_free (tmp);
vlan_flags = nm_setting_vlan_get_flags (s_vlan);
if (vlan_flags & NM_VLAN_FLAG_REORDER_HEADERS)
svSetValue (ifcfg, "REORDER_HDR", "1", FALSE);
else
svSetValue (ifcfg, "REORDER_HDR", "0", FALSE);
svSetValue (ifcfg, "VLAN_FLAGS", NULL, FALSE);
if (vlan_flags & NM_VLAN_FLAG_GVRP) {
if (vlan_flags & NM_VLAN_FLAG_LOOSE_BINDING)
svSetValue (ifcfg, "VLAN_FLAGS", "GVRP,LOOSE_BINDING", FALSE);
else
svSetValue (ifcfg, "VLAN_FLAGS", "GVRP", FALSE);
} else if (vlan_flags & NM_VLAN_FLAG_LOOSE_BINDING)
svSetValue (ifcfg, "VLAN_FLAGS", "LOOSE_BINDING", FALSE);
tmp = vlan_priority_maplist_to_stringlist (s_vlan, NM_VLAN_INGRESS_MAP);
svSetValue (ifcfg, "VLAN_INGRESS_PRIORITY_MAP", tmp, FALSE);
g_free (tmp);
tmp = vlan_priority_maplist_to_stringlist (s_vlan, NM_VLAN_EGRESS_MAP);
svSetValue (ifcfg, "VLAN_EGRESS_PRIORITY_MAP", tmp, FALSE);
g_free (tmp);
svSetValue (ifcfg, "HWADDR", NULL, FALSE);
svSetValue (ifcfg, "MACADDR", NULL, FALSE);
svSetValue (ifcfg, "MTU", NULL, FALSE);
s_wired = nm_connection_get_setting_wired (connection);
if (s_wired) {
const char *device_mac, *cloned_mac;
guint32 mtu;
*wired = TRUE;
device_mac = nm_setting_wired_get_mac_address (s_wired);
if (device_mac)
svSetValue (ifcfg, "HWADDR", device_mac, FALSE);
cloned_mac = nm_setting_wired_get_cloned_mac_address (s_wired);
if (cloned_mac)
svSetValue (ifcfg, "MACADDR", cloned_mac, FALSE);
mtu = nm_setting_wired_get_mtu (s_wired);
if (mtu) {
tmp = g_strdup_printf ("%u", mtu);
svSetValue (ifcfg, "MTU", tmp, FALSE);
g_free (tmp);
}
}
return TRUE;
}
static gboolean
write_bonding_setting (NMConnection *connection, shvarFile *ifcfg, GError **error)
{
NMSettingBond *s_bond;
const char *iface;
guint32 i, num_opts;
s_bond = nm_connection_get_setting_bond (connection);
if (!s_bond) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing '%s' setting", NM_SETTING_BOND_SETTING_NAME);
return FALSE;
}
iface = nm_connection_get_interface_name (connection);
if (!iface) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing interface name");
return FALSE;
}
svSetValue (ifcfg, "DEVICE", iface, FALSE);
svSetValue (ifcfg, "BONDING_OPTS", NULL, FALSE);
num_opts = nm_setting_bond_get_num_options (s_bond);
if (num_opts > 0) {
GString *str = g_string_sized_new (64);
for (i = 0; i < nm_setting_bond_get_num_options (s_bond); i++) {
const char *key, *value;
if (!nm_setting_bond_get_option (s_bond, i, &key, &value))
continue;
if (str->len)
g_string_append_c (str, ' ');
g_string_append_printf (str, "%s=%s", key, value);
}
if (str->len)
svSetValue (ifcfg, "BONDING_OPTS", str->str, FALSE);
g_string_free (str, TRUE);
}
svSetValue (ifcfg, "TYPE", TYPE_BOND, FALSE);
svSetValue (ifcfg, "BONDING_MASTER", "yes", FALSE);
return TRUE;
}
static gboolean
write_team_setting (NMConnection *connection, shvarFile *ifcfg, GError **error)
{
NMSettingTeam *s_team;
const char *iface;
const char *config;
s_team = nm_connection_get_setting_team (connection);
if (!s_team) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing '%s' setting", NM_SETTING_TEAM_SETTING_NAME);
return FALSE;
}
iface = nm_connection_get_interface_name (connection);
if (!iface) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing interface name");
return FALSE;
}
svSetValue (ifcfg, "DEVICE", iface, FALSE);
config = nm_setting_team_get_config (s_team);
svSetValue (ifcfg, "TEAM_CONFIG", config, FALSE);
svSetValue (ifcfg, "DEVICETYPE", TYPE_TEAM, FALSE);
return TRUE;
}
static guint32
get_setting_default (NMSetting *setting, const char *prop)
{
GParamSpec *pspec;
GValue val = G_VALUE_INIT;
guint32 ret = 0;
pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (setting), prop);
g_assert (pspec);
g_value_init (&val, pspec->value_type);
g_param_value_set_default (pspec, &val);
g_assert (G_VALUE_HOLDS_UINT (&val));
ret = g_value_get_uint (&val);
g_value_unset (&val);
return ret;
}
static gboolean
write_bridge_setting (NMConnection *connection, shvarFile *ifcfg, GError **error)
{
NMSettingBridge *s_bridge;
const char *iface;
guint32 i;
GString *opts;
const char *mac;
char *s;
s_bridge = nm_connection_get_setting_bridge (connection);
if (!s_bridge) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing '%s' setting", NM_SETTING_BRIDGE_SETTING_NAME);
return FALSE;
}
iface = nm_connection_get_interface_name (connection);
if (!iface) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing interface name");
return FALSE;
}
svSetValue (ifcfg, "DEVICE", iface, FALSE);
svSetValue (ifcfg, "BRIDGING_OPTS", NULL, FALSE);
svSetValue (ifcfg, "STP", "no", FALSE);
svSetValue (ifcfg, "DELAY", NULL, FALSE);
mac = nm_setting_bridge_get_mac_address (s_bridge);
svSetValue (ifcfg, "MACADDR", mac, FALSE);
/* Bridge options */
opts = g_string_sized_new (32);
if (nm_setting_bridge_get_stp (s_bridge)) {
svSetValue (ifcfg, "STP", "yes", FALSE);
i = nm_setting_bridge_get_forward_delay (s_bridge);
if (i != get_setting_default (NM_SETTING (s_bridge), NM_SETTING_BRIDGE_FORWARD_DELAY)) {
s = g_strdup_printf ("%u", i);
svSetValue (ifcfg, "DELAY", s, FALSE);
g_free (s);
}
g_string_append_printf (opts, "priority=%u", nm_setting_bridge_get_priority (s_bridge));
i = nm_setting_bridge_get_hello_time (s_bridge);
if (i != get_setting_default (NM_SETTING (s_bridge), NM_SETTING_BRIDGE_HELLO_TIME)) {
if (opts->len)
g_string_append_c (opts, ' ');
g_string_append_printf (opts, "hello_time=%u", i);
}
i = nm_setting_bridge_get_max_age (s_bridge);
if (i != get_setting_default (NM_SETTING (s_bridge), NM_SETTING_BRIDGE_MAX_AGE)) {
if (opts->len)
g_string_append_c (opts, ' ');
g_string_append_printf (opts, "max_age=%u", i);
}
}
i = nm_setting_bridge_get_ageing_time (s_bridge);
if (i != get_setting_default (NM_SETTING (s_bridge), NM_SETTING_BRIDGE_AGEING_TIME)) {
if (opts->len)
g_string_append_c (opts, ' ');
g_string_append_printf (opts, "ageing_time=%u", i);
}
if (opts->len)
svSetValue (ifcfg, "BRIDGING_OPTS", opts->str, FALSE);
g_string_free (opts, TRUE);
svSetValue (ifcfg, "TYPE", TYPE_BRIDGE, FALSE);
return TRUE;
}
static gboolean
write_bridge_port_setting (NMConnection *connection, shvarFile *ifcfg, GError **error)
{
NMSettingBridgePort *s_port;
guint32 i;
GString *opts;
s_port = nm_connection_get_setting_bridge_port (connection);
if (!s_port)
return TRUE;
svSetValue (ifcfg, "BRIDGING_OPTS", NULL, FALSE);
/* Bridge options */
opts = g_string_sized_new (32);
i = nm_setting_bridge_port_get_priority (s_port);
if (i != get_setting_default (NM_SETTING (s_port), NM_SETTING_BRIDGE_PORT_PRIORITY))
g_string_append_printf (opts, "priority=%u", i);
i = nm_setting_bridge_port_get_path_cost (s_port);
if (i != get_setting_default (NM_SETTING (s_port), NM_SETTING_BRIDGE_PORT_PATH_COST)) {
if (opts->len)
g_string_append_c (opts, ' ');
g_string_append_printf (opts, "path_cost=%u", i);
}
if (nm_setting_bridge_port_get_hairpin_mode (s_port)) {
if (opts->len)
g_string_append_c (opts, ' ');
g_string_append_printf (opts, "hairpin_mode=1");
}
if (opts->len)
svSetValue (ifcfg, "BRIDGING_OPTS", opts->str, FALSE);
g_string_free (opts, TRUE);
return TRUE;
}
static gboolean
write_team_port_setting (NMConnection *connection, shvarFile *ifcfg, GError **error)
{
NMSettingTeamPort *s_port;
const char *config;
s_port = nm_connection_get_setting_team_port (connection);
if (!s_port)
return TRUE;
config = nm_setting_team_port_get_config (s_port);
svSetValue (ifcfg, "TEAM_PORT_CONFIG", config, FALSE);
return TRUE;
}
static void
write_dcb_flags (shvarFile *ifcfg, const char *tag, NMSettingDcbFlags flags)
{
char *prop;
prop = g_strdup_printf ("DCB_%s_ENABLE", tag);
svSetValue (ifcfg, prop, (flags & NM_SETTING_DCB_FLAG_ENABLE) ? "yes" : NULL, FALSE);
g_free (prop);
prop = g_strdup_printf ("DCB_%s_ADVERTISE", tag);
svSetValue (ifcfg, prop, (flags & NM_SETTING_DCB_FLAG_ADVERTISE) ? "yes" : NULL, FALSE);
g_free (prop);
prop = g_strdup_printf ("DCB_%s_WILLING", tag);
svSetValue (ifcfg, prop, (flags & NM_SETTING_DCB_FLAG_WILLING) ? "yes" : NULL, FALSE);
g_free (prop);
}
static void
write_dcb_app (shvarFile *ifcfg,
const char *tag,
NMSettingDcbFlags flags,
gint priority)
{
char *prop, *tmp = NULL;
write_dcb_flags (ifcfg, tag, flags);
if ((flags & NM_SETTING_DCB_FLAG_ENABLE) && (priority >= 0))
tmp = g_strdup_printf ("%d", priority);
prop = g_strdup_printf ("DCB_%s_PRIORITY", tag);
svSetValue (ifcfg, prop, tmp, FALSE);
g_free (prop);
g_free (tmp);
}
typedef gboolean (*DcbGetBoolFunc) (NMSettingDcb *, guint);
static void
write_dcb_bool_array (shvarFile *ifcfg,
const char *key,
NMSettingDcb *s_dcb,
NMSettingDcbFlags flags,
DcbGetBoolFunc get_func)
{
char str[9];
guint i;
if (!(flags & NM_SETTING_DCB_FLAG_ENABLE)) {
svSetValue (ifcfg, key, NULL, FALSE);
return;
}
str[8] = 0;
for (i = 0; i < 8; i++)
str[i] = get_func (s_dcb, i) ? '1' : '0';
svSetValue (ifcfg, key, str, FALSE);
}
typedef guint (*DcbGetUintFunc) (NMSettingDcb *, guint);
static void
write_dcb_uint_array (shvarFile *ifcfg,
const char *key,
NMSettingDcb *s_dcb,
NMSettingDcbFlags flags,
DcbGetUintFunc get_func)
{
char str[9];
guint i, num;
if (!(flags & NM_SETTING_DCB_FLAG_ENABLE)) {
svSetValue (ifcfg, key, NULL, FALSE);
return;
}
str[8] = 0;
for (i = 0; i < 8; i++) {
num = get_func (s_dcb, i);
if (num < 10)
str[i] = '0' + num;
else if (num == 15)
str[i] = 'f';
else
g_assert_not_reached ();
}
svSetValue (ifcfg, key, str, FALSE);
}
static void
write_dcb_percent_array (shvarFile *ifcfg,
const char *key,
NMSettingDcb *s_dcb,
NMSettingDcbFlags flags,
DcbGetUintFunc get_func)
{
GString *str;
guint i;
if (!(flags & NM_SETTING_DCB_FLAG_ENABLE)) {
svSetValue (ifcfg, key, NULL, FALSE);
return;
}
str = g_string_sized_new (30);
for (i = 0; i < 8; i++) {
if (str->len)
g_string_append_c (str, ',');
g_string_append_printf (str, "%d", get_func (s_dcb, i));
}
svSetValue (ifcfg, key, str->str, FALSE);
g_string_free (str, TRUE);
}
static gboolean
write_dcb_setting (NMConnection *connection, shvarFile *ifcfg, GError **error)
{
NMSettingDcb *s_dcb;
NMSettingDcbFlags flags;
s_dcb = nm_connection_get_setting_dcb (connection);
if (!s_dcb) {
static const char *clear_keys[] = {
"DCB",
KEY_DCB_APP_FCOE_ENABLE,
KEY_DCB_APP_FCOE_ADVERTISE,
KEY_DCB_APP_FCOE_WILLING,
KEY_DCB_APP_FCOE_MODE,
KEY_DCB_APP_ISCSI_ENABLE,
KEY_DCB_APP_ISCSI_ADVERTISE,
KEY_DCB_APP_ISCSI_WILLING,
KEY_DCB_APP_FIP_ENABLE,
KEY_DCB_APP_FIP_ADVERTISE,
KEY_DCB_APP_FIP_WILLING,
KEY_DCB_PFC_ENABLE,
KEY_DCB_PFC_ADVERTISE,
KEY_DCB_PFC_WILLING,
KEY_DCB_PFC_UP,
KEY_DCB_PG_ENABLE,
KEY_DCB_PG_ADVERTISE,
KEY_DCB_PG_WILLING,
KEY_DCB_PG_ID,
KEY_DCB_PG_PCT,
KEY_DCB_PG_UPPCT,
KEY_DCB_PG_STRICT,
KEY_DCB_PG_UP2TC,
NULL };
const char **iter;
for (iter = clear_keys; *iter; iter++)
svSetValue (ifcfg, *iter, NULL, FALSE);
return TRUE;
}
svSetValue (ifcfg, "DCB", "yes", FALSE);
write_dcb_app (ifcfg, "APP_FCOE",
nm_setting_dcb_get_app_fcoe_flags (s_dcb),
nm_setting_dcb_get_app_fcoe_priority (s_dcb));
if (nm_setting_dcb_get_app_fcoe_flags (s_dcb) & NM_SETTING_DCB_FLAG_ENABLE)
svSetValue (ifcfg, KEY_DCB_APP_FCOE_MODE, nm_setting_dcb_get_app_fcoe_mode (s_dcb), FALSE);
else
svSetValue (ifcfg, KEY_DCB_APP_FCOE_MODE, NULL, FALSE);
write_dcb_app (ifcfg, "APP_ISCSI",
nm_setting_dcb_get_app_iscsi_flags (s_dcb),
nm_setting_dcb_get_app_iscsi_priority (s_dcb));
write_dcb_app (ifcfg, "APP_FIP",
nm_setting_dcb_get_app_fip_flags (s_dcb),
nm_setting_dcb_get_app_fip_priority (s_dcb));
write_dcb_flags (ifcfg, "PFC", nm_setting_dcb_get_priority_flow_control_flags (s_dcb));
write_dcb_bool_array (ifcfg, KEY_DCB_PFC_UP, s_dcb,
nm_setting_dcb_get_priority_flow_control_flags (s_dcb),
nm_setting_dcb_get_priority_flow_control);
flags = nm_setting_dcb_get_priority_group_flags (s_dcb);
write_dcb_flags (ifcfg, "PG", flags);
write_dcb_uint_array (ifcfg, KEY_DCB_PG_ID, s_dcb, flags, nm_setting_dcb_get_priority_group_id);
write_dcb_percent_array (ifcfg, KEY_DCB_PG_PCT, s_dcb, flags, nm_setting_dcb_get_priority_group_bandwidth);
write_dcb_percent_array (ifcfg, KEY_DCB_PG_UPPCT, s_dcb, flags, nm_setting_dcb_get_priority_bandwidth);
write_dcb_bool_array (ifcfg, KEY_DCB_PG_STRICT, s_dcb, flags, nm_setting_dcb_get_priority_strict_bandwidth);
write_dcb_uint_array (ifcfg, KEY_DCB_PG_UP2TC, s_dcb, flags, nm_setting_dcb_get_priority_traffic_class);
return TRUE;
}
static void
write_connection_setting (NMSettingConnection *s_con, shvarFile *ifcfg)
{
guint32 n, i;
GString *str;
const char *master;
char *tmp;
gint i_int;
svSetValue (ifcfg, "NAME", nm_setting_connection_get_id (s_con), FALSE);
svSetValue (ifcfg, "UUID", nm_setting_connection_get_uuid (s_con), FALSE);
svSetValue (ifcfg, "DEVICE", nm_setting_connection_get_interface_name (s_con), FALSE);
svSetValue (ifcfg, "ONBOOT",
nm_setting_connection_get_autoconnect (s_con) ? "yes" : "no",
FALSE);
i_int = nm_setting_connection_get_autoconnect_priority (s_con);
tmp = i_int != NM_SETTING_CONNECTION_AUTOCONNECT_PRIORITY_DEFAULT
? g_strdup_printf ("%d", i_int) : NULL;
svSetValue (ifcfg, "AUTOCONNECT_PRIORITY", tmp, FALSE);
g_free (tmp);
/* Permissions */
svSetValue (ifcfg, "USERS", NULL, FALSE);
n = nm_setting_connection_get_num_permissions (s_con);
if (n > 0) {
str = g_string_sized_new (n * 20);
for (i = 0; i < n; i++) {
const char *puser = NULL;
/* Items separated by space for consistency with eg
* IPV6ADDR_SECONDARIES and DOMAIN.
*/
if (str->len)
g_string_append_c (str, ' ');
if (nm_setting_connection_get_permission (s_con, i, NULL, &puser, NULL))
g_string_append (str, puser);
}
svSetValue (ifcfg, "USERS", str->str, FALSE);
g_string_free (str, TRUE);
}
svSetValue (ifcfg, "ZONE", nm_setting_connection_get_zone(s_con), FALSE);
master = nm_setting_connection_get_master (s_con);
if (master) {
if (nm_setting_connection_is_slave_type (s_con, NM_SETTING_BOND_SETTING_NAME)) {
svSetValue (ifcfg, "MASTER", master, FALSE);
svSetValue (ifcfg, "SLAVE", "yes", FALSE);
} else if (nm_setting_connection_is_slave_type (s_con, NM_SETTING_BRIDGE_SETTING_NAME))
svSetValue (ifcfg, "BRIDGE", master, FALSE);
else if (nm_setting_connection_is_slave_type (s_con, NM_SETTING_TEAM_SETTING_NAME)) {
svSetValue (ifcfg, "TEAM_MASTER", master, FALSE);
svSetValue (ifcfg, "DEVICETYPE", TYPE_TEAM_PORT, FALSE);
svSetValue (ifcfg, "TYPE", NULL, FALSE);
}
}
/* secondary connection UUIDs */
svSetValue (ifcfg, "SECONDARY_UUIDS", NULL, FALSE);
n = nm_setting_connection_get_num_secondaries (s_con);
if (n > 0) {
str = g_string_sized_new (n * 37);
for (i = 0; i < n; i++) {
const char *uuid;
/* Items separated by space for consistency with eg
* IPV6ADDR_SECONDARIES and DOMAIN.
*/
if (str->len)
g_string_append_c (str, ' ');
if ((uuid = nm_setting_connection_get_secondary (s_con, i)) != NULL)
g_string_append (str, uuid);
}
svSetValue (ifcfg, "SECONDARY_UUIDS", str->str, FALSE);
g_string_free (str, TRUE);
}
svSetValue (ifcfg, "GATEWAY_PING_TIMEOUT", NULL, FALSE);
if (nm_setting_connection_get_gateway_ping_timeout (s_con)) {
tmp = g_strdup_printf ("%" G_GUINT32_FORMAT, nm_setting_connection_get_gateway_ping_timeout (s_con));
svSetValue (ifcfg, "GATEWAY_PING_TIMEOUT", tmp, FALSE);
g_free (tmp);
}
}
static gboolean
write_route_file_legacy (const char *filename, NMSettingIPConfig *s_ip4, GError **error)
{
const char *dest, *next_hop;
char **route_items;
char *route_contents;
NMIPRoute *route;
guint32 prefix;
gint64 metric;
guint32 i, num;
gboolean success = FALSE;
g_return_val_if_fail (filename != NULL, FALSE);
g_return_val_if_fail (s_ip4 != NULL, FALSE);
g_return_val_if_fail (error != NULL, FALSE);
g_return_val_if_fail (*error == NULL, FALSE);
num = nm_setting_ip_config_get_num_routes (s_ip4);
if (num == 0) {
unlink (filename);
return TRUE;
}
route_items = g_malloc0 (sizeof (char*) * (num + 1));
for (i = 0; i < num; i++) {
route = nm_setting_ip_config_get_route (s_ip4, i);
dest = nm_ip_route_get_dest (route);
prefix = nm_ip_route_get_prefix (route);
next_hop = nm_ip_route_get_next_hop (route);
metric = nm_ip_route_get_metric (route);
if (metric == -1)
route_items[i] = g_strdup_printf ("%s/%u via %s\n", dest, prefix, next_hop);
else
route_items[i] = g_strdup_printf ("%s/%u via %s metric %u\n", dest, prefix, next_hop, (guint32) metric);
}
route_items[num] = NULL;
route_contents = g_strjoinv (NULL, route_items);
g_strfreev (route_items);
if (!g_file_set_contents (filename, route_contents, -1, NULL)) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Writing route file '%s' failed", filename);
goto error;
}
success = TRUE;
error:
g_free (route_contents);
return success;
}
static gboolean
write_ip4_setting (NMConnection *connection, shvarFile *ifcfg, GError **error)
{
NMSettingIPConfig *s_ip4;
const char *value;
char *addr_key, *prefix_key, *netmask_key, *gw_key, *metric_key, *tmp;
char *route_path = NULL;
gint32 j;
guint32 i, n, num;
gint64 route_metric;
GString *searches;
gboolean success = FALSE;
gboolean fake_ip4 = FALSE;
const char *method = NULL;
s_ip4 = nm_connection_get_setting_ip4_config (connection);
if (s_ip4)
method = nm_setting_ip_config_get_method (s_ip4);
/* Missing IP4 setting is assumed to be DHCP */
if (!method)
method = NM_SETTING_IP4_CONFIG_METHOD_AUTO;
if (!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED)) {
int result;
/* IPv4 disabled, clear IPv4 related parameters */
svSetValue (ifcfg, "BOOTPROTO", NULL, FALSE);
for (j = -1; j < 256; j++) {
if (j == -1) {
addr_key = g_strdup ("IPADDR");
prefix_key = g_strdup ("PREFIX");
netmask_key = g_strdup ("NETMASK");
gw_key = g_strdup ("GATEWAY");
} else {
addr_key = g_strdup_printf ("IPADDR%d", j);
prefix_key = g_strdup_printf ("PREFIX%d", j);
netmask_key = g_strdup_printf ("NETMASK%d", j);
gw_key = g_strdup_printf ("GATEWAY%d", j);
}
svSetValue (ifcfg, addr_key, NULL, FALSE);
svSetValue (ifcfg, prefix_key, NULL, FALSE);
svSetValue (ifcfg, netmask_key, NULL, FALSE);
svSetValue (ifcfg, gw_key, NULL, FALSE);
g_free (addr_key);
g_free (prefix_key);
g_free (netmask_key);
g_free (gw_key);
}
route_path = utils_get_route_path (ifcfg->fileName);
result = unlink (route_path);
g_free (route_path);
return TRUE;
}
/* Temporarily create fake IP4 setting if missing; method set to DHCP above */
if (!s_ip4) {
s_ip4 = (NMSettingIPConfig *) nm_setting_ip4_config_new ();
fake_ip4 = TRUE;
}
if (!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO))
svSetValue (ifcfg, "BOOTPROTO", "dhcp", FALSE);
else if (!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_MANUAL))
svSetValue (ifcfg, "BOOTPROTO", "none", FALSE);
else if (!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL))
svSetValue (ifcfg, "BOOTPROTO", "autoip", FALSE);
else if (!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED))
svSetValue (ifcfg, "BOOTPROTO", "shared", FALSE);
/* Clear out un-numbered IP address fields */
svSetValue (ifcfg, "IPADDR", NULL, FALSE);
svSetValue (ifcfg, "PREFIX", NULL, FALSE);
svSetValue (ifcfg, "NETMASK", NULL, FALSE);
svSetValue (ifcfg, "GATEWAY", NULL, FALSE);
/* Clear out zero-indexed IP address fields */
svSetValue (ifcfg, "IPADDR0", NULL, FALSE);
svSetValue (ifcfg, "PREFIX0", NULL, FALSE);
svSetValue (ifcfg, "NETMASK0", NULL, FALSE);
svSetValue (ifcfg, "GATEWAY0", NULL, FALSE);
/* Write out IPADDR<n>, PREFIX<n>, GATEWAY<n> for current IP addresses
* without labels. Unset obsolete NETMASK<n>.
*/
num = nm_setting_ip_config_get_num_addresses (s_ip4);
for (i = n = 0; i < num; i++) {
NMIPAddress *addr;
addr = nm_setting_ip_config_get_address (s_ip4, i);
if (i > 0) {
GVariant *label;
label = nm_ip_address_get_attribute (addr, "label");
if (label)
continue;
}
if (n == 0) {
/* Instead of index 0 use un-numbered variables.
* It's needed for compatibility with ifup that only recognizes 'GATEAWAY'
* See https://bugzilla.redhat.com/show_bug.cgi?id=771673
* and https://bugzilla.redhat.com/show_bug.cgi?id=1105770
*/
addr_key = g_strdup ("IPADDR");
prefix_key = g_strdup ("PREFIX");
netmask_key = g_strdup ("NETMASK");
gw_key = g_strdup ("GATEWAY");
} else {
addr_key = g_strdup_printf ("IPADDR%d", n);
prefix_key = g_strdup_printf ("PREFIX%d", n);
netmask_key = g_strdup_printf ("NETMASK%d", n);
gw_key = g_strdup_printf ("GATEWAY%d", n);
}
svSetValue (ifcfg, addr_key, nm_ip_address_get_address (addr), FALSE);
tmp = g_strdup_printf ("%u", nm_ip_address_get_prefix (addr));
svSetValue (ifcfg, prefix_key, tmp, FALSE);
g_free (tmp);
svSetValue (ifcfg, netmask_key, NULL, FALSE);
svSetValue (ifcfg, gw_key, NULL, FALSE);
g_free (addr_key);
g_free (prefix_key);
g_free (netmask_key);
g_free (gw_key);
n++;
}
/* Clear remaining IPADDR<n..255>, etc */
for (; n < 256; n++) {
addr_key = g_strdup_printf ("IPADDR%d", n);
prefix_key = g_strdup_printf ("PREFIX%d", n);
netmask_key = g_strdup_printf ("NETMASK%d", n);
gw_key = g_strdup_printf ("GATEWAY%d", n);
svSetValue (ifcfg, addr_key, NULL, FALSE);
svSetValue (ifcfg, prefix_key, NULL, FALSE);
svSetValue (ifcfg, netmask_key, NULL, FALSE);
svSetValue (ifcfg, gw_key, NULL, FALSE);
g_free (addr_key);
g_free (prefix_key);
g_free (netmask_key);
g_free (gw_key);
}
svSetValue (ifcfg, "GATEWAY", nm_setting_ip_config_get_gateway (s_ip4), FALSE);
num = nm_setting_ip_config_get_num_dns (s_ip4);
for (i = 0; i < 254; i++) {
const char *dns;
addr_key = g_strdup_printf ("DNS%d", i + 1);
if (i >= num)
svSetValue (ifcfg, addr_key, NULL, FALSE);
else {
dns = nm_setting_ip_config_get_dns (s_ip4, i);
svSetValue (ifcfg, addr_key, dns, FALSE);
}
g_free (addr_key);
}
num = nm_setting_ip_config_get_num_dns_searches (s_ip4);
if (num > 0) {
searches = g_string_new (NULL);
for (i = 0; i < num; i++) {
if (i > 0)
g_string_append_c (searches, ' ');
g_string_append (searches, nm_setting_ip_config_get_dns_search (s_ip4, i));
}
svSetValue (ifcfg, "DOMAIN", searches->str, FALSE);
g_string_free (searches, TRUE);
} else
svSetValue (ifcfg, "DOMAIN", NULL, FALSE);
/* DEFROUTE; remember that it has the opposite meaning from never-default */
svSetValue (ifcfg, "DEFROUTE",
nm_setting_ip_config_get_never_default (s_ip4) ? "no" : "yes",
FALSE);
svSetValue (ifcfg, "PEERDNS", NULL, FALSE);
svSetValue (ifcfg, "PEERROUTES", NULL, FALSE);
svSetValue (ifcfg, "DHCP_CLIENT_ID", NULL, FALSE);
if (!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO)) {
svSetValue (ifcfg, "PEERDNS",
nm_setting_ip_config_get_ignore_auto_dns (s_ip4) ? "no" : "yes",
FALSE);
svSetValue (ifcfg, "PEERROUTES",
nm_setting_ip_config_get_ignore_auto_routes (s_ip4) ? "no" : "yes",
FALSE);
value = nm_setting_ip_config_get_dhcp_hostname (s_ip4);
if (value)
svSetValue (ifcfg, "DHCP_HOSTNAME", value, FALSE);
/* Missing DHCP_SEND_HOSTNAME means TRUE, and we prefer not write it explicitly
* in that case, because it is NM-specific variable
*/
svSetValue (ifcfg, "DHCP_SEND_HOSTNAME",
nm_setting_ip_config_get_dhcp_send_hostname (s_ip4) ? NULL : "no",
FALSE);
value = nm_setting_ip4_config_get_dhcp_client_id (NM_SETTING_IP4_CONFIG (s_ip4));
if (value)
svSetValue (ifcfg, "DHCP_CLIENT_ID", value, FALSE);
}
svSetValue (ifcfg, "IPV4_FAILURE_FATAL",
nm_setting_ip_config_get_may_fail (s_ip4) ? "no" : "yes",
FALSE);
route_metric = nm_setting_ip_config_get_route_metric (s_ip4);
tmp = route_metric != -1 ? g_strdup_printf ("%"G_GINT64_FORMAT, route_metric) : NULL;
svSetValue (ifcfg, "IPV4_ROUTE_METRIC", tmp, FALSE);
g_free (tmp);
/* Static routes - route-<name> file */
route_path = utils_get_route_path (ifcfg->fileName);
if (!route_path) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Could not get route file path for '%s'", ifcfg->fileName);
goto out;
}
if (utils_has_route_file_new_syntax (route_path)) {
shvarFile *routefile;
routefile = utils_get_route_ifcfg (ifcfg->fileName, TRUE);
if (!routefile) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Could not create route file '%s'", route_path);
g_free (route_path);
goto out;
}
g_free (route_path);
num = nm_setting_ip_config_get_num_routes (s_ip4);
for (i = 0; i < 256; i++) {
char buf[INET_ADDRSTRLEN];
NMIPRoute *route;
guint32 netmask;
gint64 metric;
addr_key = g_strdup_printf ("ADDRESS%d", i);
netmask_key = g_strdup_printf ("NETMASK%d", i);
gw_key = g_strdup_printf ("GATEWAY%d", i);
metric_key = g_strdup_printf ("METRIC%d", i);
if (i >= num) {
svSetValue (routefile, addr_key, NULL, FALSE);
svSetValue (routefile, netmask_key, NULL, FALSE);
svSetValue (routefile, gw_key, NULL, FALSE);
svSetValue (routefile, metric_key, NULL, FALSE);
} else {
route = nm_setting_ip_config_get_route (s_ip4, i);
svSetValue (routefile, addr_key, nm_ip_route_get_dest (route), FALSE);
memset (buf, 0, sizeof (buf));
netmask = nm_utils_ip4_prefix_to_netmask (nm_ip_route_get_prefix (route));
inet_ntop (AF_INET, (const void *) &netmask, &buf[0], sizeof (buf));
svSetValue (routefile, netmask_key, &buf[0], FALSE);
svSetValue (routefile, gw_key, nm_ip_route_get_next_hop (route), FALSE);
memset (buf, 0, sizeof (buf));
metric = nm_ip_route_get_metric (route);
if (metric == -1)
svSetValue (routefile, metric_key, NULL, FALSE);
else {
tmp = g_strdup_printf ("%u", (guint32) metric);
svSetValue (routefile, metric_key, tmp, FALSE);
g_free (tmp);
}
}
g_free (addr_key);
g_free (netmask_key);
g_free (gw_key);
g_free (metric_key);
}
if (!svWriteFile (routefile, 0644, error)) {
svCloseFile (routefile);
goto out;
}
svCloseFile (routefile);
} else {
write_route_file_legacy (route_path, s_ip4, error);
g_free (route_path);
if (error && *error)
goto out;
}
success = TRUE;
out:
if (fake_ip4)
g_object_unref (s_ip4);
return success;
}
static void
write_ip4_aliases (NMConnection *connection, char *base_ifcfg_path)
{
NMSettingIPConfig *s_ip4;
char *base_ifcfg_dir, *base_ifcfg_name, *base_name;
int i, num, base_ifcfg_name_len, base_name_len;
GDir *dir;
base_ifcfg_dir = g_path_get_dirname (base_ifcfg_path);
base_ifcfg_name = g_path_get_basename (base_ifcfg_path);
base_ifcfg_name_len = strlen (base_ifcfg_name);
base_name = base_ifcfg_name + strlen (IFCFG_TAG);
base_name_len = strlen (base_name);
/* Remove all existing aliases for this file first */
dir = g_dir_open (base_ifcfg_dir, 0, NULL);
if (dir) {
const char *item;
while ((item = g_dir_read_name (dir))) {
char *full_path;
if ( strncmp (item, base_ifcfg_name, base_ifcfg_name_len) != 0
|| item[base_ifcfg_name_len] != ':')
continue;
full_path = g_build_filename (base_ifcfg_dir, item, NULL);
unlink (full_path);
g_free (full_path);
}
g_dir_close (dir);
}
if (utils_ignore_ip_config (connection))
return;
s_ip4 = nm_connection_get_setting_ip4_config (connection);
if (!s_ip4)
return;
num = nm_setting_ip_config_get_num_addresses (s_ip4);
for (i = 0; i < num; i++) {
GVariant *label_var;
const char *label, *p;
char *path, *tmp;
NMIPAddress *addr;
shvarFile *ifcfg;
addr = nm_setting_ip_config_get_address (s_ip4, i);
label_var = nm_ip_address_get_attribute (addr, "label");
if (!label_var)
continue;
label = g_variant_get_string (label_var, NULL);
if ( strncmp (label, base_name, base_name_len) != 0
|| label[base_name_len] != ':')
continue;
for (p = label; *p; p++) {
if (!g_ascii_isalnum (*p) && *p != '_' && *p != ':')
break;
}
if (*p)
continue;
path = g_strdup_printf ("%s%s", base_ifcfg_path, label + base_name_len);
ifcfg = svCreateFile (path);
g_free (path);
svSetValue (ifcfg, "DEVICE", label, FALSE);
addr = nm_setting_ip_config_get_address (s_ip4, i);
svSetValue (ifcfg, "IPADDR", nm_ip_address_get_address (addr), FALSE);
tmp = g_strdup_printf ("%u", nm_ip_address_get_prefix (addr));
svSetValue (ifcfg, "PREFIX", tmp, FALSE);
g_free (tmp);
svWriteFile (ifcfg, 0644, NULL);
svCloseFile (ifcfg);
}
g_free (base_ifcfg_name);
g_free (base_ifcfg_dir);
}
static gboolean
write_route6_file (const char *filename, NMSettingIPConfig *s_ip6, GError **error)
{
char **route_items;
char *route_contents;
NMIPRoute *route;
guint32 i, num;
gboolean success = FALSE;
g_return_val_if_fail (filename != NULL, FALSE);
g_return_val_if_fail (s_ip6 != NULL, FALSE);
g_return_val_if_fail (error != NULL, FALSE);
g_return_val_if_fail (*error == NULL, FALSE);
num = nm_setting_ip_config_get_num_routes (s_ip6);
if (num == 0) {
unlink (filename);
return TRUE;
}
route_items = g_malloc0 (sizeof (char*) * (num + 1));
for (i = 0; i < num; i++) {
route = nm_setting_ip_config_get_route (s_ip6, i);
if (nm_ip_route_get_metric (route) == -1) {
route_items[i] = g_strdup_printf ("%s/%u via %s\n",
nm_ip_route_get_dest (route),
nm_ip_route_get_prefix (route),
nm_ip_route_get_next_hop (route));
} else {
route_items[i] = g_strdup_printf ("%s/%u via %s metric %u\n",
nm_ip_route_get_dest (route),
nm_ip_route_get_prefix (route),
nm_ip_route_get_next_hop (route),
(guint32) nm_ip_route_get_metric (route));
}
}
route_items[num] = NULL;
route_contents = g_strjoinv (NULL, route_items);
g_strfreev (route_items);
if (!g_file_set_contents (filename, route_contents, -1, NULL)) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Writing route6 file '%s' failed", filename);
goto error;
}
success = TRUE;
error:
g_free (route_contents);
return success;
}
static gboolean
write_ip6_setting (NMConnection *connection, shvarFile *ifcfg, GError **error)
{
NMSettingIPConfig *s_ip6;
NMSettingIPConfig *s_ip4;
const char *value;
char *addr_key;
char *tmp;
guint32 i, num, num4;
GString *searches;
NMIPAddress *addr;
const char *dns;
gint64 route_metric;
GString *ip_str1, *ip_str2, *ip_ptr;
char *route6_path;
s_ip6 = nm_connection_get_setting_ip6_config (connection);
if (!s_ip6) {
/* Treat missing IPv6 setting as a setting with method "auto" */
svSetValue (ifcfg, "IPV6INIT", "yes", FALSE);
svSetValue (ifcfg, "IPV6_AUTOCONF", "yes", FALSE);
svSetValue (ifcfg, "DHCPV6C", NULL, FALSE);
svSetValue (ifcfg, "IPV6_DEFROUTE", "yes", FALSE);
svSetValue (ifcfg, "IPV6_PEERDNS", "yes", FALSE);
svSetValue (ifcfg, "IPV6_PEERROUTES", "yes", FALSE);
svSetValue (ifcfg, "IPV6_FAILURE_FATAL", "no", FALSE);
svSetValue (ifcfg, "IPV6_ROUTE_METRIC", NULL, FALSE);
return TRUE;
}
value = nm_setting_ip_config_get_method (s_ip6);
g_assert (value);
if (!strcmp (value, NM_SETTING_IP6_CONFIG_METHOD_IGNORE)) {
svSetValue (ifcfg, "IPV6INIT", "no", FALSE);
svSetValue (ifcfg, "DHCPV6C", NULL, FALSE);
return TRUE;
} else if (!strcmp (value, NM_SETTING_IP6_CONFIG_METHOD_AUTO)) {
svSetValue (ifcfg, "IPV6INIT", "yes", FALSE);
svSetValue (ifcfg, "IPV6_AUTOCONF", "yes", FALSE);
svSetValue (ifcfg, "DHCPV6C", NULL, FALSE);
} else if (!strcmp (value, NM_SETTING_IP6_CONFIG_METHOD_DHCP)) {
const char *hostname;
svSetValue (ifcfg, "IPV6INIT", "yes", FALSE);
svSetValue (ifcfg, "IPV6_AUTOCONF", "no", FALSE);
svSetValue (ifcfg, "DHCPV6C", "yes", FALSE);
hostname = nm_setting_ip_config_get_dhcp_hostname (s_ip6);
if (hostname)
svSetValue (ifcfg, "DHCP_HOSTNAME", hostname, FALSE);
} else if (!strcmp (value, NM_SETTING_IP6_CONFIG_METHOD_MANUAL)) {
svSetValue (ifcfg, "IPV6INIT", "yes", FALSE);
svSetValue (ifcfg, "IPV6_AUTOCONF", "no", FALSE);
svSetValue (ifcfg, "DHCPV6C", NULL, FALSE);
} else if (!strcmp (value, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL)) {
svSetValue (ifcfg, "IPV6INIT", "yes", FALSE);
svSetValue (ifcfg, "IPV6_AUTOCONF", "no", FALSE);
svSetValue (ifcfg, "DHCPV6C", NULL, FALSE);
} else if (!strcmp (value, NM_SETTING_IP6_CONFIG_METHOD_SHARED)) {
svSetValue (ifcfg, "IPV6INIT", "yes", FALSE);
svSetValue (ifcfg, "DHCPV6C", NULL, FALSE);
/* TODO */
}
/* Write out IP addresses */
num = nm_setting_ip_config_get_num_addresses (s_ip6);
ip_str1 = g_string_new (NULL);
ip_str2 = g_string_new (NULL);
for (i = 0; i < num; i++) {
if (i == 0)
ip_ptr = ip_str1;
else
ip_ptr = ip_str2;
addr = nm_setting_ip_config_get_address (s_ip6, i);
if (i > 1)
g_string_append_c (ip_ptr, ' '); /* separate addresses in IPV6ADDR_SECONDARIES */
g_string_append_printf (ip_ptr, "%s/%u",
nm_ip_address_get_address (addr),
nm_ip_address_get_prefix (addr));
}
svSetValue (ifcfg, "IPV6ADDR", ip_str1->str, FALSE);
svSetValue (ifcfg, "IPV6ADDR_SECONDARIES", ip_str2->str, FALSE);
svSetValue (ifcfg, "IPV6_DEFAULTGW", nm_setting_ip_config_get_gateway (s_ip6), FALSE);
g_string_free (ip_str1, TRUE);
g_string_free (ip_str2, TRUE);
/* Write out DNS - 'DNS' key is used both for IPv4 and IPv6 */
s_ip4 = nm_connection_get_setting_ip4_config (connection);
num4 = s_ip4 ? nm_setting_ip_config_get_num_dns (s_ip4) : 0; /* from where to start with IPv6 entries */
num = nm_setting_ip_config_get_num_dns (s_ip6);
for (i = 0; i < 254; i++) {
addr_key = g_strdup_printf ("DNS%d", i + num4 + 1);
if (i >= num)
svSetValue (ifcfg, addr_key, NULL, FALSE);
else {
dns = nm_setting_ip_config_get_dns (s_ip6, i);
svSetValue (ifcfg, addr_key, dns, FALSE);
}
g_free (addr_key);
}
/* Write out DNS domains - 'DOMAIN' key is shared for both IPv4 and IPv6 domains */
num = nm_setting_ip_config_get_num_dns_searches (s_ip6);
if (num > 0) {
char *ip4_domains;
ip4_domains = svGetValue (ifcfg, "DOMAIN", FALSE);
searches = g_string_new (ip4_domains);
for (i = 0; i < num; i++) {
if (searches->len > 0)
g_string_append_c (searches, ' ');
g_string_append (searches, nm_setting_ip_config_get_dns_search (s_ip6, i));
}
svSetValue (ifcfg, "DOMAIN", searches->str, FALSE);
g_string_free (searches, TRUE);
g_free (ip4_domains);
}
/* handle IPV6_DEFROUTE */
/* IPV6_DEFROUTE has the opposite meaning from 'never-default' */
if (nm_setting_ip_config_get_never_default(s_ip6))
svSetValue (ifcfg, "IPV6_DEFROUTE", "no", FALSE);
else
svSetValue (ifcfg, "IPV6_DEFROUTE", "yes", FALSE);
svSetValue (ifcfg, "IPV6_PEERDNS", NULL, FALSE);
svSetValue (ifcfg, "IPV6_PEERROUTES", NULL, FALSE);
if (!strcmp (value, NM_SETTING_IP6_CONFIG_METHOD_AUTO)) {
svSetValue (ifcfg, "IPV6_PEERDNS",
nm_setting_ip_config_get_ignore_auto_dns (s_ip6) ? "no" : "yes",
FALSE);
svSetValue (ifcfg, "IPV6_PEERROUTES",
nm_setting_ip_config_get_ignore_auto_routes (s_ip6) ? "no" : "yes",
FALSE);
}
svSetValue (ifcfg, "IPV6_FAILURE_FATAL",
nm_setting_ip_config_get_may_fail (s_ip6) ? "no" : "yes",
FALSE);
route_metric = nm_setting_ip_config_get_route_metric (s_ip6);
tmp = route_metric != -1 ? g_strdup_printf ("%"G_GINT64_FORMAT, route_metric) : NULL;
svSetValue (ifcfg, "IPV6_ROUTE_METRIC", tmp, FALSE);
g_free (tmp);
/* IPv6 Privacy Extensions */
svSetValue (ifcfg, "IPV6_PRIVACY", NULL, FALSE);
svSetValue (ifcfg, "IPV6_PRIVACY_PREFER_PUBLIC_IP", NULL, FALSE);
switch (nm_setting_ip6_config_get_ip6_privacy (NM_SETTING_IP6_CONFIG (s_ip6))){
case NM_SETTING_IP6_CONFIG_PRIVACY_DISABLED:
svSetValue (ifcfg, "IPV6_PRIVACY", "no", FALSE);
break;
case NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR:
svSetValue (ifcfg, "IPV6_PRIVACY", "rfc3041", FALSE);
svSetValue (ifcfg, "IPV6_PRIVACY_PREFER_PUBLIC_IP", "yes", FALSE);
break;
case NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR:
svSetValue (ifcfg, "IPV6_PRIVACY", "rfc3041", FALSE);
break;
default:
break;
}
/* Static routes go to route6-<dev> file */
route6_path = utils_get_route6_path (ifcfg->fileName);
if (!route6_path) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Could not get route6 file path for '%s'", ifcfg->fileName);
goto error;
}
write_route6_file (route6_path, s_ip6, error);
g_free (route6_path);
if (error && *error)
goto error;
return TRUE;
error:
return FALSE;
}
static char *
escape_id (const char *id)
{
char *escaped = g_strdup (id);
char *p = escaped;
/* Escape random stuff */
while (*p) {
if (*p == ' ')
*p = '_';
else if (strchr ("\\][|/=()!", *p))
*p = '-';
p++;
}
return escaped;
}
static gboolean
write_connection (NMConnection *connection,
const char *ifcfg_dir,
const char *filename,
const char *keyfile,
char **out_filename,
GError **error)
{
NMSettingConnection *s_con;
gboolean success = FALSE;
shvarFile *ifcfg = NULL;
char *ifcfg_name = NULL;
const char *type;
gboolean no_8021x = FALSE;
gboolean wired = FALSE;
if (!writer_can_write_connection (connection, error))
return FALSE;
s_con = nm_connection_get_setting_connection (connection);
g_assert (s_con);
if (filename) {
/* For existing connections, 'filename' should be full path to ifcfg file */
ifcfg = svOpenFile (filename, error);
if (!ifcfg)
return FALSE;
ifcfg_name = g_strdup (filename);
} else {
char *escaped;
escaped = escape_id (nm_setting_connection_get_id (s_con));
ifcfg_name = g_strdup_printf ("%s/ifcfg-%s", ifcfg_dir, escaped);
/* If a file with this path already exists then we need another name.
* Multiple connections can have the same ID (ie if two connections with
* the same ID are visible to different users) but of course can't have
* the same path.
*/
if (g_file_test (ifcfg_name, G_FILE_TEST_EXISTS)) {
guint32 idx = 0;
g_free (ifcfg_name);
while (idx++ < 500) {
ifcfg_name = g_strdup_printf ("%s/ifcfg-%s-%u", ifcfg_dir, escaped, idx);
if (g_file_test (ifcfg_name, G_FILE_TEST_EXISTS) == FALSE)
break;
g_free (ifcfg_name);
ifcfg_name = NULL;
}
}
g_free (escaped);
if (ifcfg_name == NULL) {
g_set_error_literal (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Failed to find usable ifcfg file name");
return FALSE;
}
ifcfg = svCreateFile (ifcfg_name);
}
type = nm_setting_connection_get_connection_type (s_con);
if (!type) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Missing connection type!");
goto out;
}
if (!strcmp (type, NM_SETTING_WIRED_SETTING_NAME)) {
// FIXME: can't write PPPoE at this time
if (nm_connection_get_setting_pppoe (connection)) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Can't write connection type '%s'",
NM_SETTING_PPPOE_SETTING_NAME);
goto out;
}
if (!write_wired_setting (connection, ifcfg, error))
goto out;
wired = TRUE;
} else if (!strcmp (type, NM_SETTING_VLAN_SETTING_NAME)) {
if (!write_vlan_setting (connection, ifcfg, &wired, error))
goto out;
} else if (!strcmp (type, NM_SETTING_WIRELESS_SETTING_NAME)) {
if (!write_wireless_setting (connection, ifcfg, &no_8021x, error))
goto out;
} else if (!strcmp (type, NM_SETTING_INFINIBAND_SETTING_NAME)) {
if (!write_infiniband_setting (connection, ifcfg, error))
goto out;
} else if (!strcmp (type, NM_SETTING_BOND_SETTING_NAME)) {
if (!write_bonding_setting (connection, ifcfg, error))
goto out;
} else if (!strcmp (type, NM_SETTING_TEAM_SETTING_NAME)) {
if (!write_team_setting (connection, ifcfg, error))
goto out;
} else if (!strcmp (type, NM_SETTING_BRIDGE_SETTING_NAME)) {
if (!write_bridge_setting (connection, ifcfg, error))
goto out;
} else {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Can't write connection type '%s'", type);
goto out;
}
if (!no_8021x) {
if (!write_8021x_setting (connection, ifcfg, wired, error))
goto out;
}
if (!write_bridge_port_setting (connection, ifcfg, error))
goto out;
if (!write_team_port_setting (connection, ifcfg, error))
goto out;
if (!write_dcb_setting (connection, ifcfg, error))
goto out;
if (!utils_ignore_ip_config (connection)) {
svSetValue (ifcfg, "DHCP_HOSTNAME", NULL, FALSE);
if (!write_ip4_setting (connection, ifcfg, error))
goto out;
write_ip4_aliases (connection, ifcfg_name);
if (!write_ip6_setting (connection, ifcfg, error))
goto out;
}
write_connection_setting (s_con, ifcfg);
if (!svWriteFile (ifcfg, 0644, error))
goto out;
/* Only return the filename if this was a newly written ifcfg */
if (out_filename && !filename)
*out_filename = g_strdup (ifcfg_name);
success = TRUE;
out:
if (ifcfg)
svCloseFile (ifcfg);
g_free (ifcfg_name);
return success;
}
gboolean
writer_can_write_connection (NMConnection *connection, GError **error)
{
NMSettingConnection *s_con;
if ( ( nm_connection_is_type (connection, NM_SETTING_WIRED_SETTING_NAME)
&& !nm_connection_get_setting_pppoe (connection))
|| nm_connection_is_type (connection, NM_SETTING_VLAN_SETTING_NAME)
|| nm_connection_is_type (connection, NM_SETTING_WIRELESS_SETTING_NAME)
|| nm_connection_is_type (connection, NM_SETTING_INFINIBAND_SETTING_NAME)
|| nm_connection_is_type (connection, NM_SETTING_BOND_SETTING_NAME)
|| nm_connection_is_type (connection, NM_SETTING_TEAM_SETTING_NAME)
|| nm_connection_is_type (connection, NM_SETTING_BRIDGE_SETTING_NAME))
return TRUE;
s_con = nm_connection_get_setting_connection (connection);
g_assert (s_con);
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"The ifcfg-rh plugin cannot write the connection '%s' (type '%s' pppoe %d)",
nm_connection_get_id (connection),
nm_setting_connection_get_connection_type (s_con),
!!nm_connection_get_setting_pppoe (connection));
return FALSE;
}
gboolean
writer_new_connection (NMConnection *connection,
const char *ifcfg_dir,
char **out_filename,
GError **error)
{
return write_connection (connection, ifcfg_dir, NULL, NULL, out_filename, error);
}
gboolean
writer_update_connection (NMConnection *connection,
const char *ifcfg_dir,
const char *filename,
const char *keyfile,
GError **error)
{
if (utils_has_complex_routes (filename)) {
g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
"Cannot modify a connection that has an associated 'rule-' or 'rule6-' file");
return FALSE;
}
return write_connection (connection, ifcfg_dir, filename, keyfile, NULL, error);
}
| gpl-2.0 |
devicenull/frr | bgpd/bgp_zebra.c | 1 | 99460 | /* zebra client
* Copyright (C) 1997, 98, 99 Kunihiro Ishiguro
*
* This file is part of GNU Zebra.
*
* GNU Zebra is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* GNU Zebra 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; see the file COPYING; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <zebra.h>
#include "command.h"
#include "stream.h"
#include "network.h"
#include "prefix.h"
#include "log.h"
#include "sockunion.h"
#include "zclient.h"
#include "routemap.h"
#include "thread.h"
#include "queue.h"
#include "memory.h"
#include "lib/json.h"
#include "lib/bfd.h"
#include "lib/route_opaque.h"
#include "filter.h"
#include "mpls.h"
#include "vxlan.h"
#include "pbr.h"
#include "bgpd/bgpd.h"
#include "bgpd/bgp_route.h"
#include "bgpd/bgp_attr.h"
#include "bgpd/bgp_aspath.h"
#include "bgpd/bgp_nexthop.h"
#include "bgpd/bgp_zebra.h"
#include "bgpd/bgp_fsm.h"
#include "bgpd/bgp_debug.h"
#include "bgpd/bgp_errors.h"
#include "bgpd/bgp_mpath.h"
#include "bgpd/bgp_nexthop.h"
#include "bgpd/bgp_nht.h"
#include "bgpd/bgp_bfd.h"
#include "bgpd/bgp_label.h"
#ifdef ENABLE_BGP_VNC
#include "bgpd/rfapi/rfapi_backend.h"
#include "bgpd/rfapi/vnc_export_bgp.h"
#endif
#include "bgpd/bgp_evpn.h"
#include "bgpd/bgp_mplsvpn.h"
#include "bgpd/bgp_labelpool.h"
#include "bgpd/bgp_pbr.h"
#include "bgpd/bgp_evpn_private.h"
#include "bgpd/bgp_evpn_mh.h"
#include "bgpd/bgp_mac.h"
#include "bgpd/bgp_trace.h"
#include "bgpd/bgp_community.h"
#include "bgpd/bgp_lcommunity.h"
/* All information about zebra. */
struct zclient *zclient = NULL;
/* hook to indicate vrf status change for SNMP */
DEFINE_HOOK(bgp_vrf_status_changed, (struct bgp *bgp, struct interface *ifp),
(bgp, ifp));
DEFINE_MTYPE_STATIC(BGPD, BGP_IF_INFO, "BGP interface context");
/* Can we install into zebra? */
static inline bool bgp_install_info_to_zebra(struct bgp *bgp)
{
if (zclient->sock <= 0)
return false;
if (!IS_BGP_INST_KNOWN_TO_ZEBRA(bgp)) {
zlog_debug(
"%s: No zebra instance to talk to, not installing information",
__func__);
return false;
}
return true;
}
int zclient_num_connects;
/* Router-id update message from zebra. */
static int bgp_router_id_update(ZAPI_CALLBACK_ARGS)
{
struct prefix router_id;
zebra_router_id_update_read(zclient->ibuf, &router_id);
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Rx Router Id update VRF %u Id %pFX", vrf_id,
&router_id);
bgp_router_id_zebra_bump(vrf_id, &router_id);
return 0;
}
/* Nexthop update message from zebra. */
static int bgp_read_nexthop_update(ZAPI_CALLBACK_ARGS)
{
bgp_parse_nexthop_update(cmd, vrf_id);
return 0;
}
/* Set or clear interface on which unnumbered neighbor is configured. This
* would in turn cause BGP to initiate or turn off IPv6 RAs on this
* interface.
*/
static void bgp_update_interface_nbrs(struct bgp *bgp, struct interface *ifp,
struct interface *upd_ifp)
{
struct listnode *node, *nnode;
struct peer *peer;
for (ALL_LIST_ELEMENTS(bgp->peer, node, nnode, peer)) {
if (peer->conf_if && (strcmp(peer->conf_if, ifp->name) == 0)) {
if (upd_ifp) {
peer->ifp = upd_ifp;
bgp_zebra_initiate_radv(bgp, peer);
} else {
bgp_zebra_terminate_radv(bgp, peer);
peer->ifp = upd_ifp;
}
}
}
}
static int bgp_read_fec_update(ZAPI_CALLBACK_ARGS)
{
bgp_parse_fec_update();
return 0;
}
static void bgp_start_interface_nbrs(struct bgp *bgp, struct interface *ifp)
{
struct listnode *node, *nnode;
struct peer *peer;
for (ALL_LIST_ELEMENTS(bgp->peer, node, nnode, peer)) {
if (peer->conf_if && (strcmp(peer->conf_if, ifp->name) == 0)
&& !peer_established(peer)) {
if (peer_active(peer))
BGP_EVENT_ADD(peer, BGP_Stop);
BGP_EVENT_ADD(peer, BGP_Start);
}
}
}
static void bgp_nbr_connected_add(struct bgp *bgp, struct nbr_connected *ifc)
{
struct listnode *node;
struct connected *connected;
struct interface *ifp;
struct prefix *p;
/* Kick-off the FSM for any relevant peers only if there is a
* valid local address on the interface.
*/
ifp = ifc->ifp;
for (ALL_LIST_ELEMENTS_RO(ifp->connected, node, connected)) {
p = connected->address;
if (p->family == AF_INET6
&& IN6_IS_ADDR_LINKLOCAL(&p->u.prefix6))
break;
}
if (!connected)
return;
bgp_start_interface_nbrs(bgp, ifp);
}
static void bgp_nbr_connected_delete(struct bgp *bgp, struct nbr_connected *ifc,
int del)
{
struct listnode *node, *nnode;
struct peer *peer;
struct interface *ifp;
for (ALL_LIST_ELEMENTS(bgp->peer, node, nnode, peer)) {
if (peer->conf_if
&& (strcmp(peer->conf_if, ifc->ifp->name) == 0)) {
peer->last_reset = PEER_DOWN_NBR_ADDR_DEL;
BGP_EVENT_ADD(peer, BGP_Stop);
}
}
/* Free neighbor also, if we're asked to. */
if (del) {
ifp = ifc->ifp;
listnode_delete(ifp->nbr_connected, ifc);
nbr_connected_free(ifc);
}
}
static int bgp_ifp_destroy(struct interface *ifp)
{
struct bgp *bgp;
bgp = ifp->vrf->info;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Rx Intf del VRF %u IF %s", ifp->vrf->vrf_id,
ifp->name);
if (bgp) {
bgp_update_interface_nbrs(bgp, ifp, NULL);
hook_call(bgp_vrf_status_changed, bgp, ifp);
}
bgp_mac_del_mac_entry(ifp);
return 0;
}
static int bgp_ifp_up(struct interface *ifp)
{
struct connected *c;
struct nbr_connected *nc;
struct listnode *node, *nnode;
struct bgp *bgp;
bgp = ifp->vrf->info;
bgp_mac_add_mac_entry(ifp);
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Rx Intf up VRF %u IF %s", ifp->vrf->vrf_id,
ifp->name);
if (!bgp)
return 0;
for (ALL_LIST_ELEMENTS(ifp->connected, node, nnode, c))
bgp_connected_add(bgp, c);
for (ALL_LIST_ELEMENTS(ifp->nbr_connected, node, nnode, nc))
bgp_nbr_connected_add(bgp, nc);
hook_call(bgp_vrf_status_changed, bgp, ifp);
bgp_nht_ifp_up(ifp);
return 0;
}
static int bgp_ifp_down(struct interface *ifp)
{
struct connected *c;
struct nbr_connected *nc;
struct listnode *node, *nnode;
struct bgp *bgp;
struct peer *peer;
bgp = ifp->vrf->info;
bgp_mac_del_mac_entry(ifp);
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Rx Intf down VRF %u IF %s", ifp->vrf->vrf_id,
ifp->name);
if (!bgp)
return 0;
for (ALL_LIST_ELEMENTS(ifp->connected, node, nnode, c))
bgp_connected_delete(bgp, c);
for (ALL_LIST_ELEMENTS(ifp->nbr_connected, node, nnode, nc))
bgp_nbr_connected_delete(bgp, nc, 1);
/* Fast external-failover */
if (!CHECK_FLAG(bgp->flags, BGP_FLAG_NO_FAST_EXT_FAILOVER)) {
for (ALL_LIST_ELEMENTS(bgp->peer, node, nnode, peer)) {
/* Take down directly connected peers. */
if ((peer->ttl != BGP_DEFAULT_TTL)
&& (peer->gtsm_hops != BGP_GTSM_HOPS_CONNECTED))
continue;
if (ifp == peer->nexthop.ifp) {
BGP_EVENT_ADD(peer, BGP_Stop);
peer->last_reset = PEER_DOWN_IF_DOWN;
}
}
}
hook_call(bgp_vrf_status_changed, bgp, ifp);
bgp_nht_ifp_down(ifp);
return 0;
}
static int bgp_interface_address_add(ZAPI_CALLBACK_ARGS)
{
struct connected *ifc;
struct bgp *bgp;
bgp = bgp_lookup_by_vrf_id(vrf_id);
ifc = zebra_interface_address_read(cmd, zclient->ibuf, vrf_id);
if (ifc == NULL)
return 0;
if (bgp_debug_zebra(ifc->address))
zlog_debug("Rx Intf address add VRF %u IF %s addr %pFX", vrf_id,
ifc->ifp->name, ifc->address);
if (!bgp)
return 0;
if (if_is_operative(ifc->ifp)) {
bgp_connected_add(bgp, ifc);
/* If we have learnt of any neighbors on this interface,
* check to kick off any BGP interface-based neighbors,
* but only if this is a link-local address.
*/
if (IN6_IS_ADDR_LINKLOCAL(&ifc->address->u.prefix6)
&& !list_isempty(ifc->ifp->nbr_connected))
bgp_start_interface_nbrs(bgp, ifc->ifp);
}
return 0;
}
static int bgp_interface_address_delete(ZAPI_CALLBACK_ARGS)
{
struct listnode *node, *nnode;
struct connected *ifc;
struct peer *peer;
struct bgp *bgp;
struct prefix *addr;
bgp = bgp_lookup_by_vrf_id(vrf_id);
ifc = zebra_interface_address_read(cmd, zclient->ibuf, vrf_id);
if (ifc == NULL)
return 0;
if (bgp_debug_zebra(ifc->address))
zlog_debug("Rx Intf address del VRF %u IF %s addr %pFX", vrf_id,
ifc->ifp->name, ifc->address);
if (bgp && if_is_operative(ifc->ifp)) {
bgp_connected_delete(bgp, ifc);
}
addr = ifc->address;
if (bgp) {
/*
* When we are using the v6 global as part of the peering
* nexthops and we are removing it, then we need to
* clear the peer data saved for that nexthop and
* cause a re-announcement of the route. Since
* we do not want the peering to bounce.
*/
for (ALL_LIST_ELEMENTS(bgp->peer, node, nnode, peer)) {
afi_t afi;
safi_t safi;
if (addr->family == AF_INET)
continue;
if (!IN6_IS_ADDR_LINKLOCAL(&addr->u.prefix6)
&& memcmp(&peer->nexthop.v6_global,
&addr->u.prefix6, 16)
== 0) {
memset(&peer->nexthop.v6_global, 0, 16);
FOREACH_AFI_SAFI (afi, safi)
bgp_announce_route(peer, afi, safi,
true);
}
}
}
connected_free(&ifc);
return 0;
}
static int bgp_interface_nbr_address_add(ZAPI_CALLBACK_ARGS)
{
struct nbr_connected *ifc = NULL;
struct bgp *bgp;
ifc = zebra_interface_nbr_address_read(cmd, zclient->ibuf, vrf_id);
if (ifc == NULL)
return 0;
if (bgp_debug_zebra(ifc->address))
zlog_debug("Rx Intf neighbor add VRF %u IF %s addr %pFX",
vrf_id, ifc->ifp->name, ifc->address);
if (if_is_operative(ifc->ifp)) {
bgp = bgp_lookup_by_vrf_id(vrf_id);
if (bgp)
bgp_nbr_connected_add(bgp, ifc);
}
return 0;
}
static int bgp_interface_nbr_address_delete(ZAPI_CALLBACK_ARGS)
{
struct nbr_connected *ifc = NULL;
struct bgp *bgp;
ifc = zebra_interface_nbr_address_read(cmd, zclient->ibuf, vrf_id);
if (ifc == NULL)
return 0;
if (bgp_debug_zebra(ifc->address))
zlog_debug("Rx Intf neighbor del VRF %u IF %s addr %pFX",
vrf_id, ifc->ifp->name, ifc->address);
if (if_is_operative(ifc->ifp)) {
bgp = bgp_lookup_by_vrf_id(vrf_id);
if (bgp)
bgp_nbr_connected_delete(bgp, ifc, 0);
}
nbr_connected_free(ifc);
return 0;
}
/* VRF update for an interface. */
static int bgp_interface_vrf_update(ZAPI_CALLBACK_ARGS)
{
struct interface *ifp;
vrf_id_t new_vrf_id;
struct connected *c;
struct nbr_connected *nc;
struct listnode *node, *nnode;
struct bgp *bgp;
struct peer *peer;
ifp = zebra_interface_vrf_update_read(zclient->ibuf, vrf_id,
&new_vrf_id);
if (!ifp)
return 0;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Rx Intf VRF change VRF %u IF %s NewVRF %u", vrf_id,
ifp->name, new_vrf_id);
bgp = bgp_lookup_by_vrf_id(vrf_id);
if (bgp) {
for (ALL_LIST_ELEMENTS(ifp->connected, node, nnode, c))
bgp_connected_delete(bgp, c);
for (ALL_LIST_ELEMENTS(ifp->nbr_connected, node, nnode, nc))
bgp_nbr_connected_delete(bgp, nc, 1);
/* Fast external-failover */
if (!CHECK_FLAG(bgp->flags, BGP_FLAG_NO_FAST_EXT_FAILOVER)) {
for (ALL_LIST_ELEMENTS(bgp->peer, node, nnode, peer)) {
if ((peer->ttl != BGP_DEFAULT_TTL)
&& (peer->gtsm_hops
!= BGP_GTSM_HOPS_CONNECTED))
continue;
if (ifp == peer->nexthop.ifp)
BGP_EVENT_ADD(peer, BGP_Stop);
}
}
}
if_update_to_new_vrf(ifp, new_vrf_id);
bgp = bgp_lookup_by_vrf_id(new_vrf_id);
if (!bgp)
return 0;
for (ALL_LIST_ELEMENTS(ifp->connected, node, nnode, c))
bgp_connected_add(bgp, c);
for (ALL_LIST_ELEMENTS(ifp->nbr_connected, node, nnode, nc))
bgp_nbr_connected_add(bgp, nc);
hook_call(bgp_vrf_status_changed, bgp, ifp);
return 0;
}
/* Zebra route add and delete treatment. */
static int zebra_read_route(ZAPI_CALLBACK_ARGS)
{
enum nexthop_types_t nhtype;
enum blackhole_type bhtype = BLACKHOLE_UNSPEC;
struct zapi_route api;
union g_addr nexthop = {};
ifindex_t ifindex;
int add, i;
struct bgp *bgp;
bgp = bgp_lookup_by_vrf_id(vrf_id);
if (!bgp)
return 0;
if (zapi_route_decode(zclient->ibuf, &api) < 0)
return -1;
/* we completely ignore srcdest routes for now. */
if (CHECK_FLAG(api.message, ZAPI_MESSAGE_SRCPFX))
return 0;
/* ignore link-local address. */
if (api.prefix.family == AF_INET6
&& IN6_IS_ADDR_LINKLOCAL(&api.prefix.u.prefix6))
return 0;
ifindex = api.nexthops[0].ifindex;
nhtype = api.nexthops[0].type;
/* api_nh structure has union of gate and bh_type */
if (nhtype == NEXTHOP_TYPE_BLACKHOLE) {
/* bh_type is only applicable if NEXTHOP_TYPE_BLACKHOLE*/
bhtype = api.nexthops[0].bh_type;
} else
nexthop = api.nexthops[0].gate;
add = (cmd == ZEBRA_REDISTRIBUTE_ROUTE_ADD);
if (add) {
/*
* The ADD message is actually an UPDATE and there is no
* explicit DEL
* for a prior redistributed route, if any. So, perform an
* implicit
* DEL processing for the same redistributed route from any
* other
* source type.
*/
for (i = 0; i < ZEBRA_ROUTE_MAX; i++) {
if (i != api.type)
bgp_redistribute_delete(bgp, &api.prefix, i,
api.instance);
}
/* Now perform the add/update. */
bgp_redistribute_add(bgp, &api.prefix, &nexthop, ifindex,
nhtype, bhtype, api.distance, api.metric,
api.type, api.instance, api.tag);
} else {
bgp_redistribute_delete(bgp, &api.prefix, api.type,
api.instance);
}
if (bgp_debug_zebra(&api.prefix)) {
char buf[PREFIX_STRLEN];
if (add) {
inet_ntop(api.prefix.family, &nexthop, buf,
sizeof(buf));
zlog_debug(
"Rx route ADD VRF %u %s[%d] %pFX nexthop %s (type %d if %u) metric %u distance %u tag %" ROUTE_TAG_PRI,
vrf_id, zebra_route_string(api.type),
api.instance, &api.prefix, buf, nhtype, ifindex,
api.metric, api.distance, api.tag);
} else {
zlog_debug("Rx route DEL VRF %u %s[%d] %pFX", vrf_id,
zebra_route_string(api.type), api.instance,
&api.prefix);
}
}
return 0;
}
struct interface *if_lookup_by_ipv4(struct in_addr *addr, vrf_id_t vrf_id)
{
struct vrf *vrf;
struct listnode *cnode;
struct interface *ifp;
struct connected *connected;
struct prefix_ipv4 p;
struct prefix *cp;
vrf = vrf_lookup_by_id(vrf_id);
if (!vrf)
return NULL;
p.family = AF_INET;
p.prefix = *addr;
p.prefixlen = IPV4_MAX_BITLEN;
FOR_ALL_INTERFACES (vrf, ifp) {
for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, connected)) {
cp = connected->address;
if (cp->family == AF_INET)
if (prefix_match(cp, (struct prefix *)&p))
return ifp;
}
}
return NULL;
}
struct interface *if_lookup_by_ipv4_exact(struct in_addr *addr, vrf_id_t vrf_id)
{
struct vrf *vrf;
struct listnode *cnode;
struct interface *ifp;
struct connected *connected;
struct prefix *cp;
vrf = vrf_lookup_by_id(vrf_id);
if (!vrf)
return NULL;
FOR_ALL_INTERFACES (vrf, ifp) {
for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, connected)) {
cp = connected->address;
if (cp->family == AF_INET)
if (IPV4_ADDR_SAME(&cp->u.prefix4, addr))
return ifp;
}
}
return NULL;
}
struct interface *if_lookup_by_ipv6(struct in6_addr *addr, ifindex_t ifindex,
vrf_id_t vrf_id)
{
struct vrf *vrf;
struct listnode *cnode;
struct interface *ifp;
struct connected *connected;
struct prefix_ipv6 p;
struct prefix *cp;
vrf = vrf_lookup_by_id(vrf_id);
if (!vrf)
return NULL;
p.family = AF_INET6;
p.prefix = *addr;
p.prefixlen = IPV6_MAX_BITLEN;
FOR_ALL_INTERFACES (vrf, ifp) {
for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, connected)) {
cp = connected->address;
if (cp->family == AF_INET6)
if (prefix_match(cp, (struct prefix *)&p)) {
if (IN6_IS_ADDR_LINKLOCAL(
&cp->u.prefix6)) {
if (ifindex == ifp->ifindex)
return ifp;
} else
return ifp;
}
}
}
return NULL;
}
struct interface *if_lookup_by_ipv6_exact(struct in6_addr *addr,
ifindex_t ifindex, vrf_id_t vrf_id)
{
struct vrf *vrf;
struct listnode *cnode;
struct interface *ifp;
struct connected *connected;
struct prefix *cp;
vrf = vrf_lookup_by_id(vrf_id);
if (!vrf)
return NULL;
FOR_ALL_INTERFACES (vrf, ifp) {
for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, connected)) {
cp = connected->address;
if (cp->family == AF_INET6)
if (IPV6_ADDR_SAME(&cp->u.prefix6, addr)) {
if (IN6_IS_ADDR_LINKLOCAL(
&cp->u.prefix6)) {
if (ifindex == ifp->ifindex)
return ifp;
} else
return ifp;
}
}
}
return NULL;
}
static int if_get_ipv6_global(struct interface *ifp, struct in6_addr *addr)
{
struct listnode *cnode;
struct connected *connected;
struct prefix *cp;
for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, connected)) {
cp = connected->address;
if (cp->family == AF_INET6)
if (!IN6_IS_ADDR_LINKLOCAL(&cp->u.prefix6)) {
memcpy(addr, &cp->u.prefix6, IPV6_MAX_BYTELEN);
return 1;
}
}
return 0;
}
static bool if_get_ipv6_local(struct interface *ifp, struct in6_addr *addr)
{
struct listnode *cnode;
struct connected *connected;
struct prefix *cp;
for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, connected)) {
cp = connected->address;
if (cp->family == AF_INET6)
if (IN6_IS_ADDR_LINKLOCAL(&cp->u.prefix6)) {
memcpy(addr, &cp->u.prefix6, IPV6_MAX_BYTELEN);
return true;
}
}
return false;
}
static int if_get_ipv4_address(struct interface *ifp, struct in_addr *addr)
{
struct listnode *cnode;
struct connected *connected;
struct prefix *cp;
for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, connected)) {
cp = connected->address;
if ((cp->family == AF_INET)
&& !ipv4_martian(&(cp->u.prefix4))) {
*addr = cp->u.prefix4;
return 1;
}
}
return 0;
}
bool bgp_zebra_nexthop_set(union sockunion *local, union sockunion *remote,
struct bgp_nexthop *nexthop, struct peer *peer)
{
int ret = 0;
struct interface *ifp = NULL;
bool v6_ll_avail = true;
memset(nexthop, 0, sizeof(struct bgp_nexthop));
if (!local)
return false;
if (!remote)
return false;
if (local->sa.sa_family == AF_INET) {
nexthop->v4 = local->sin.sin_addr;
if (peer->update_if)
ifp = if_lookup_by_name(peer->update_if,
peer->bgp->vrf_id);
else
ifp = if_lookup_by_ipv4_exact(&local->sin.sin_addr,
peer->bgp->vrf_id);
}
if (local->sa.sa_family == AF_INET6) {
memcpy(&nexthop->v6_global, &local->sin6.sin6_addr, IPV6_MAX_BYTELEN);
if (IN6_IS_ADDR_LINKLOCAL(&local->sin6.sin6_addr)) {
if (peer->conf_if || peer->ifname)
ifp = if_lookup_by_name(peer->conf_if
? peer->conf_if
: peer->ifname,
peer->bgp->vrf_id);
else if (peer->update_if)
ifp = if_lookup_by_name(peer->update_if,
peer->bgp->vrf_id);
} else if (peer->update_if)
ifp = if_lookup_by_name(peer->update_if,
peer->bgp->vrf_id);
else
ifp = if_lookup_by_ipv6_exact(&local->sin6.sin6_addr,
local->sin6.sin6_scope_id,
peer->bgp->vrf_id);
}
if (!ifp) {
/*
* BGP views do not currently get proper data
* from zebra( when attached ) to be able to
* properly resolve nexthops, so give this
* instance type a pass.
*/
if (peer->bgp->inst_type == BGP_INSTANCE_TYPE_VIEW)
return true;
/*
* If we have no interface data but we have established
* some connection w/ zebra than something has gone
* terribly terribly wrong here, so say this failed
* If we do not any zebra connection then not
* having a ifp pointer is ok.
*/
return zclient_num_connects ? false : true;
}
nexthop->ifp = ifp;
/* IPv4 connection, fetch and store IPv6 local address(es) if any. */
if (local->sa.sa_family == AF_INET) {
/* IPv6 nexthop*/
ret = if_get_ipv6_global(ifp, &nexthop->v6_global);
if (!ret) {
/* There is no global nexthop. Use link-local address as
* both the
* global and link-local nexthop. In this scenario, the
* expectation
* for interop is that the network admin would use a
* route-map to
* specify the global IPv6 nexthop.
*/
v6_ll_avail =
if_get_ipv6_local(ifp, &nexthop->v6_global);
memcpy(&nexthop->v6_local, &nexthop->v6_global,
IPV6_MAX_BYTELEN);
} else
v6_ll_avail =
if_get_ipv6_local(ifp, &nexthop->v6_local);
/*
* If we are a v4 connection and we are not doing unnumbered
* not having a v6 LL address is ok
*/
if (!v6_ll_avail && !peer->conf_if)
v6_ll_avail = true;
if (if_lookup_by_ipv4(&remote->sin.sin_addr, peer->bgp->vrf_id))
peer->shared_network = 1;
else
peer->shared_network = 0;
}
/* IPv6 connection, fetch and store IPv4 local address if any. */
if (local->sa.sa_family == AF_INET6) {
struct interface *direct = NULL;
/* IPv4 nexthop. */
ret = if_get_ipv4_address(ifp, &nexthop->v4);
if (!ret && peer->local_id.s_addr != INADDR_ANY)
nexthop->v4 = peer->local_id;
/* Global address*/
if (!IN6_IS_ADDR_LINKLOCAL(&local->sin6.sin6_addr)) {
memcpy(&nexthop->v6_global, &local->sin6.sin6_addr,
IPV6_MAX_BYTELEN);
/* If directory connected set link-local address. */
direct = if_lookup_by_ipv6(&remote->sin6.sin6_addr,
remote->sin6.sin6_scope_id,
peer->bgp->vrf_id);
if (direct)
v6_ll_avail = if_get_ipv6_local(
ifp, &nexthop->v6_local);
/*
* It's fine to not have a v6 LL when using
* update-source loopback/vrf
*/
if (!v6_ll_avail && if_is_loopback(ifp))
v6_ll_avail = true;
else {
flog_warn(
EC_BGP_NO_LL_ADDRESS_AVAILABLE,
"Interface: %s does not have a v6 LL address associated with it, waiting until one is created for it",
ifp->name);
}
} else
/* Link-local address. */
{
ret = if_get_ipv6_global(ifp, &nexthop->v6_global);
/* If there is no global address. Set link-local
address as
global. I know this break RFC specification... */
/* In this scenario, the expectation for interop is that
* the
* network admin would use a route-map to specify the
* global
* IPv6 nexthop.
*/
if (!ret)
memcpy(&nexthop->v6_global,
&local->sin6.sin6_addr,
IPV6_MAX_BYTELEN);
/* Always set the link-local address */
memcpy(&nexthop->v6_local, &local->sin6.sin6_addr,
IPV6_MAX_BYTELEN);
}
if (IN6_IS_ADDR_LINKLOCAL(&local->sin6.sin6_addr)
|| if_lookup_by_ipv6(&remote->sin6.sin6_addr,
remote->sin6.sin6_scope_id,
peer->bgp->vrf_id))
peer->shared_network = 1;
else
peer->shared_network = 0;
}
/* KAME stack specific treatment. */
#ifdef KAME
if (IN6_IS_ADDR_LINKLOCAL(&nexthop->v6_global)
&& IN6_LINKLOCAL_IFINDEX(nexthop->v6_global)) {
SET_IN6_LINKLOCAL_IFINDEX(nexthop->v6_global, 0);
}
if (IN6_IS_ADDR_LINKLOCAL(&nexthop->v6_local)
&& IN6_LINKLOCAL_IFINDEX(nexthop->v6_local)) {
SET_IN6_LINKLOCAL_IFINDEX(nexthop->v6_local, 0);
}
#endif /* KAME */
/* If we have identified the local interface, there is no error for now.
*/
return v6_ll_avail;
}
static struct in6_addr *
bgp_path_info_to_ipv6_nexthop(struct bgp_path_info *path, ifindex_t *ifindex)
{
struct in6_addr *nexthop = NULL;
/* Only global address nexthop exists. */
if (path->attr->mp_nexthop_len == BGP_ATTR_NHLEN_IPV6_GLOBAL
|| path->attr->mp_nexthop_len == BGP_ATTR_NHLEN_VPNV6_GLOBAL) {
nexthop = &path->attr->mp_nexthop_global;
if (IN6_IS_ADDR_LINKLOCAL(nexthop))
*ifindex = path->attr->nh_ifindex;
}
/* If both global and link-local address present. */
if (path->attr->mp_nexthop_len == BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL
|| path->attr->mp_nexthop_len
== BGP_ATTR_NHLEN_VPNV6_GLOBAL_AND_LL) {
/* Check if route-map is set to prefer global over link-local */
if (path->attr->mp_nexthop_prefer_global) {
nexthop = &path->attr->mp_nexthop_global;
if (IN6_IS_ADDR_LINKLOCAL(nexthop))
*ifindex = path->attr->nh_ifindex;
} else {
/* Workaround for Cisco's nexthop bug. */
if (IN6_IS_ADDR_UNSPECIFIED(
&path->attr->mp_nexthop_global)
&& path->peer->su_remote
&& path->peer->su_remote->sa.sa_family
== AF_INET6) {
nexthop =
&path->peer->su_remote->sin6.sin6_addr;
if (IN6_IS_ADDR_LINKLOCAL(nexthop))
*ifindex = path->peer->nexthop.ifp
->ifindex;
} else {
nexthop = &path->attr->mp_nexthop_local;
if (IN6_IS_ADDR_LINKLOCAL(nexthop))
*ifindex = path->attr->nh_lla_ifindex;
}
}
}
return nexthop;
}
static bool bgp_table_map_apply(struct route_map *map, const struct prefix *p,
struct bgp_path_info *path)
{
route_map_result_t ret;
ret = route_map_apply(map, p, path);
bgp_attr_flush(path->attr);
if (ret != RMAP_DENYMATCH)
return true;
if (bgp_debug_zebra(p)) {
if (p->family == AF_INET) {
zlog_debug(
"Zebra rmap deny: IPv4 route %pFX nexthop %pI4",
p, &path->attr->nexthop);
}
if (p->family == AF_INET6) {
ifindex_t ifindex;
struct in6_addr *nexthop;
nexthop = bgp_path_info_to_ipv6_nexthop(path, &ifindex);
zlog_debug(
"Zebra rmap deny: IPv6 route %pFX nexthop %pI6",
p, nexthop);
}
}
return false;
}
static struct thread *bgp_tm_thread_connect;
static bool bgp_tm_status_connected;
static bool bgp_tm_chunk_obtained;
#define BGP_FLOWSPEC_TABLE_CHUNK 100000
static uint32_t bgp_tm_min, bgp_tm_max, bgp_tm_chunk_size;
struct bgp *bgp_tm_bgp;
static void bgp_zebra_tm_connect(struct thread *t)
{
struct zclient *zclient;
int delay = 10, ret = 0;
zclient = THREAD_ARG(t);
if (bgp_tm_status_connected && zclient->sock > 0)
delay = 60;
else {
bgp_tm_status_connected = false;
ret = tm_table_manager_connect(zclient);
}
if (ret < 0) {
zlog_info("Error connecting to table manager!");
bgp_tm_status_connected = false;
} else {
if (!bgp_tm_status_connected)
zlog_debug("Connecting to table manager. Success");
bgp_tm_status_connected = true;
if (!bgp_tm_chunk_obtained) {
if (bgp_zebra_get_table_range(bgp_tm_chunk_size,
&bgp_tm_min,
&bgp_tm_max) >= 0) {
bgp_tm_chunk_obtained = true;
/* parse non installed entries */
bgp_zebra_announce_table(bgp_tm_bgp, AFI_IP, SAFI_FLOWSPEC);
}
}
}
thread_add_timer(bm->master, bgp_zebra_tm_connect, zclient, delay,
&bgp_tm_thread_connect);
}
bool bgp_zebra_tm_chunk_obtained(void)
{
return bgp_tm_chunk_obtained;
}
uint32_t bgp_zebra_tm_get_id(void)
{
static int table_id;
if (!bgp_tm_chunk_obtained)
return ++table_id;
return bgp_tm_min++;
}
void bgp_zebra_init_tm_connect(struct bgp *bgp)
{
int delay = 1;
/* if already set, do nothing
*/
if (bgp_tm_thread_connect != NULL)
return;
bgp_tm_status_connected = false;
bgp_tm_chunk_obtained = false;
bgp_tm_min = bgp_tm_max = 0;
bgp_tm_chunk_size = BGP_FLOWSPEC_TABLE_CHUNK;
bgp_tm_bgp = bgp;
thread_add_timer(bm->master, bgp_zebra_tm_connect, zclient, delay,
&bgp_tm_thread_connect);
}
int bgp_zebra_get_table_range(uint32_t chunk_size,
uint32_t *start, uint32_t *end)
{
int ret;
if (!bgp_tm_status_connected)
return -1;
ret = tm_get_table_chunk(zclient, chunk_size, start, end);
if (ret < 0) {
flog_err(EC_BGP_TABLE_CHUNK,
"BGP: Error getting table chunk %u", chunk_size);
return -1;
}
zlog_info("BGP: Table Manager returns range from chunk %u is [%u %u]",
chunk_size, *start, *end);
return 0;
}
static bool update_ipv4nh_for_route_install(int nh_othervrf, struct bgp *nh_bgp,
struct in_addr *nexthop,
struct attr *attr, bool is_evpn,
struct zapi_nexthop *api_nh)
{
api_nh->gate.ipv4 = *nexthop;
api_nh->vrf_id = nh_bgp->vrf_id;
/* Need to set fields appropriately for EVPN routes imported into
* a VRF (which are programmed as onlink on l3-vni SVI) as well as
* connected routes leaked into a VRF.
*/
if (attr->nh_type == NEXTHOP_TYPE_BLACKHOLE) {
api_nh->type = attr->nh_type;
api_nh->bh_type = attr->bh_type;
} else if (is_evpn) {
/*
* If the nexthop is EVPN overlay index gateway IP,
* treat the nexthop as NEXTHOP_TYPE_IPV4
* Else, mark the nexthop as onlink.
*/
if (attr->evpn_overlay.type == OVERLAY_INDEX_GATEWAY_IP)
api_nh->type = NEXTHOP_TYPE_IPV4;
else {
api_nh->type = NEXTHOP_TYPE_IPV4_IFINDEX;
SET_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_EVPN);
SET_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_ONLINK);
api_nh->ifindex = nh_bgp->l3vni_svi_ifindex;
}
} else if (nh_othervrf && api_nh->gate.ipv4.s_addr == INADDR_ANY) {
api_nh->type = NEXTHOP_TYPE_IFINDEX;
api_nh->ifindex = attr->nh_ifindex;
} else
api_nh->type = NEXTHOP_TYPE_IPV4;
return true;
}
static bool update_ipv6nh_for_route_install(int nh_othervrf, struct bgp *nh_bgp,
struct in6_addr *nexthop,
ifindex_t ifindex,
struct bgp_path_info *pi,
struct bgp_path_info *best_pi,
bool is_evpn,
struct zapi_nexthop *api_nh)
{
struct attr *attr;
attr = pi->attr;
api_nh->vrf_id = nh_bgp->vrf_id;
if (attr->nh_type == NEXTHOP_TYPE_BLACKHOLE) {
api_nh->type = attr->nh_type;
api_nh->bh_type = attr->bh_type;
} else if (is_evpn) {
/*
* If the nexthop is EVPN overlay index gateway IP,
* treat the nexthop as NEXTHOP_TYPE_IPV4
* Else, mark the nexthop as onlink.
*/
if (attr->evpn_overlay.type == OVERLAY_INDEX_GATEWAY_IP)
api_nh->type = NEXTHOP_TYPE_IPV6;
else {
api_nh->type = NEXTHOP_TYPE_IPV6_IFINDEX;
SET_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_EVPN);
SET_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_ONLINK);
api_nh->ifindex = nh_bgp->l3vni_svi_ifindex;
}
} else if (nh_othervrf) {
if (IN6_IS_ADDR_UNSPECIFIED(nexthop)) {
api_nh->type = NEXTHOP_TYPE_IFINDEX;
api_nh->ifindex = attr->nh_ifindex;
} else if (IN6_IS_ADDR_LINKLOCAL(nexthop)) {
if (ifindex == 0)
return false;
api_nh->type = NEXTHOP_TYPE_IPV6_IFINDEX;
api_nh->ifindex = ifindex;
} else {
api_nh->type = NEXTHOP_TYPE_IPV6;
api_nh->ifindex = 0;
}
} else {
if (IN6_IS_ADDR_LINKLOCAL(nexthop)) {
if (pi == best_pi
&& attr->mp_nexthop_len
== BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL)
if (pi->peer->nexthop.ifp)
ifindex =
pi->peer->nexthop.ifp->ifindex;
if (!ifindex) {
if (pi->peer->conf_if)
ifindex = pi->peer->ifp->ifindex;
else if (pi->peer->ifname)
ifindex = ifname2ifindex(
pi->peer->ifname,
pi->peer->bgp->vrf_id);
else if (pi->peer->nexthop.ifp)
ifindex =
pi->peer->nexthop.ifp->ifindex;
}
if (ifindex == 0)
return false;
api_nh->type = NEXTHOP_TYPE_IPV6_IFINDEX;
api_nh->ifindex = ifindex;
} else {
api_nh->type = NEXTHOP_TYPE_IPV6;
api_nh->ifindex = 0;
}
}
/* api_nh structure has union of gate and bh_type */
if (nexthop && api_nh->type != NEXTHOP_TYPE_BLACKHOLE)
api_nh->gate.ipv6 = *nexthop;
return true;
}
static bool bgp_zebra_use_nhop_weighted(struct bgp *bgp, struct attr *attr,
uint64_t tot_bw, uint32_t *nh_weight)
{
uint32_t bw;
uint64_t tmp;
bw = attr->link_bw;
/* zero link-bandwidth and link-bandwidth not present are treated
* as the same situation.
*/
if (!bw) {
/* the only situations should be if we're either told
* to skip or use default weight.
*/
if (bgp->lb_handling == BGP_LINK_BW_SKIP_MISSING)
return false;
*nh_weight = BGP_ZEBRA_DEFAULT_NHOP_WEIGHT;
} else {
tmp = (uint64_t)bw * 100;
*nh_weight = ((uint32_t)(tmp / tot_bw));
}
return true;
}
void bgp_zebra_announce(struct bgp_dest *dest, const struct prefix *p,
struct bgp_path_info *info, struct bgp *bgp, afi_t afi,
safi_t safi)
{
struct zapi_route api = { 0 };
struct zapi_nexthop *api_nh;
int nh_family;
unsigned int valid_nh_count = 0;
bool allow_recursion = false;
uint8_t distance;
struct peer *peer;
struct bgp_path_info *mpinfo;
struct bgp *bgp_orig;
uint32_t metric;
struct attr local_attr;
struct bgp_path_info local_info;
struct bgp_path_info *mpinfo_cp = &local_info;
route_tag_t tag;
mpls_label_t label;
struct bgp_sid_info *sid_info;
int nh_othervrf = 0;
bool nh_updated = false;
bool do_wt_ecmp;
uint64_t cum_bw = 0;
uint32_t nhg_id = 0;
bool is_add;
uint32_t ttl = 0;
uint32_t bos = 0;
uint32_t exp = 0;
/* Don't try to install if we're not connected to Zebra or Zebra doesn't
* know of this instance.
*/
if (!bgp_install_info_to_zebra(bgp))
return;
if (bgp->main_zebra_update_hold)
return;
if (safi == SAFI_FLOWSPEC) {
bgp_pbr_update_entry(bgp, bgp_dest_get_prefix(dest), info, afi,
safi, true);
return;
}
/*
* vrf leaking support (will have only one nexthop)
*/
if (info->extra && info->extra->bgp_orig)
nh_othervrf = 1;
/* Make Zebra API structure. */
api.vrf_id = bgp->vrf_id;
api.type = ZEBRA_ROUTE_BGP;
api.safi = safi;
api.prefix = *p;
SET_FLAG(api.message, ZAPI_MESSAGE_NEXTHOP);
peer = info->peer;
if (info->type == ZEBRA_ROUTE_BGP
&& info->sub_type == BGP_ROUTE_IMPORTED) {
/* Obtain peer from parent */
if (info->extra && info->extra->parent)
peer = ((struct bgp_path_info *)(info->extra->parent))
->peer;
}
tag = info->attr->tag;
if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED
|| info->sub_type == BGP_ROUTE_AGGREGATE) {
SET_FLAG(api.flags, ZEBRA_FLAG_IBGP);
SET_FLAG(api.flags, ZEBRA_FLAG_ALLOW_RECURSION);
}
if ((peer->sort == BGP_PEER_EBGP && peer->ttl != BGP_DEFAULT_TTL)
|| CHECK_FLAG(peer->flags, PEER_FLAG_DISABLE_CONNECTED_CHECK)
|| CHECK_FLAG(bgp->flags, BGP_FLAG_DISABLE_NH_CONNECTED_CHK))
allow_recursion = true;
if (info->attr->rmap_table_id) {
SET_FLAG(api.message, ZAPI_MESSAGE_TABLEID);
api.tableid = info->attr->rmap_table_id;
}
if (CHECK_FLAG(info->attr->flag, ATTR_FLAG_BIT(BGP_ATTR_SRTE_COLOR)))
SET_FLAG(api.message, ZAPI_MESSAGE_SRTE);
/* Metric is currently based on the best-path only */
metric = info->attr->med;
/* Determine if we're doing weighted ECMP or not */
do_wt_ecmp = bgp_path_info_mpath_chkwtd(bgp, info);
if (do_wt_ecmp)
cum_bw = bgp_path_info_mpath_cumbw(info);
/* EVPN MAC-IP routes are installed with a L3 NHG id */
if (bgp_evpn_path_es_use_nhg(bgp, info, &nhg_id)) {
mpinfo = NULL;
api.nhgid = nhg_id;
if (nhg_id)
SET_FLAG(api.message, ZAPI_MESSAGE_NHG);
} else {
mpinfo = info;
}
for (; mpinfo; mpinfo = bgp_path_info_mpath_next(mpinfo)) {
uint32_t nh_weight;
bool is_evpn;
if (valid_nh_count >= multipath_num)
break;
*mpinfo_cp = *mpinfo;
nh_weight = 0;
/* Get nexthop address-family */
if (p->family == AF_INET &&
!BGP_ATTR_MP_NEXTHOP_LEN_IP6(mpinfo_cp->attr))
nh_family = AF_INET;
else if (p->family == AF_INET6 ||
(p->family == AF_INET &&
BGP_ATTR_MP_NEXTHOP_LEN_IP6(mpinfo_cp->attr)))
nh_family = AF_INET6;
else
continue;
/* If processing for weighted ECMP, determine the next hop's
* weight. Based on user setting, we may skip the next hop
* in some situations.
*/
if (do_wt_ecmp) {
if (!bgp_zebra_use_nhop_weighted(bgp, mpinfo->attr,
cum_bw, &nh_weight))
continue;
}
api_nh = &api.nexthops[valid_nh_count];
if (CHECK_FLAG(info->attr->flag,
ATTR_FLAG_BIT(BGP_ATTR_SRTE_COLOR)))
api_nh->srte_color = info->attr->srte_color;
if (bgp_debug_zebra(&api.prefix)) {
if (mpinfo->extra) {
zlog_debug("%s: p=%pFX, bgp_is_valid_label: %d",
__func__, p,
bgp_is_valid_label(
&mpinfo->extra->label[0]));
} else {
zlog_debug(
"%s: p=%pFX, extra is NULL, no label",
__func__, p);
}
}
if (bgp->table_map[afi][safi].name) {
/* Copy info and attributes, so the route-map
apply doesn't modify the BGP route info. */
local_attr = *mpinfo->attr;
mpinfo_cp->attr = &local_attr;
if (!bgp_table_map_apply(bgp->table_map[afi][safi].map,
p, mpinfo_cp))
continue;
/* metric/tag is only allowed to be
* overridden on 1st nexthop */
if (mpinfo == info) {
metric = mpinfo_cp->attr->med;
tag = mpinfo_cp->attr->tag;
}
}
BGP_ORIGINAL_UPDATE(bgp_orig, mpinfo, bgp);
if (nh_family == AF_INET) {
is_evpn = is_route_parent_evpn(mpinfo);
nh_updated = update_ipv4nh_for_route_install(
nh_othervrf, bgp_orig,
&mpinfo_cp->attr->nexthop, mpinfo_cp->attr,
is_evpn, api_nh);
} else {
ifindex_t ifindex = IFINDEX_INTERNAL;
struct in6_addr *nexthop;
nexthop = bgp_path_info_to_ipv6_nexthop(mpinfo_cp,
&ifindex);
is_evpn = is_route_parent_evpn(mpinfo);
if (!nexthop)
nh_updated = update_ipv4nh_for_route_install(
nh_othervrf, bgp_orig,
&mpinfo_cp->attr->nexthop,
mpinfo_cp->attr, is_evpn, api_nh);
else
nh_updated = update_ipv6nh_for_route_install(
nh_othervrf, bgp_orig, nexthop, ifindex,
mpinfo, info, is_evpn, api_nh);
}
/* Did we get proper nexthop info to update zebra? */
if (!nh_updated)
continue;
/* Allow recursion if it is a multipath group with both
* eBGP and iBGP paths.
*/
if (!allow_recursion
&& CHECK_FLAG(bgp->flags, BGP_FLAG_PEERTYPE_MULTIPATH_RELAX)
&& (mpinfo->peer->sort == BGP_PEER_IBGP
|| mpinfo->peer->sort == BGP_PEER_CONFED))
allow_recursion = true;
if (mpinfo->extra &&
bgp_is_valid_label(&mpinfo->extra->label[0]) &&
!CHECK_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_EVPN)) {
mpls_lse_decode(mpinfo->extra->label[0], &label, &ttl,
&exp, &bos);
SET_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_LABEL);
api_nh->label_num = 1;
api_nh->labels[0] = label;
}
if (is_evpn
&& mpinfo->attr->evpn_overlay.type
!= OVERLAY_INDEX_GATEWAY_IP)
memcpy(&api_nh->rmac, &(mpinfo->attr->rmac),
sizeof(struct ethaddr));
api_nh->weight = nh_weight;
if (mpinfo->extra && !sid_zero(&mpinfo->extra->sid[0].sid) &&
!CHECK_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_EVPN)) {
sid_info = &mpinfo->extra->sid[0];
memcpy(&api_nh->seg6_segs, &sid_info->sid,
sizeof(api_nh->seg6_segs));
if (sid_info->transposition_len != 0) {
if (!bgp_is_valid_label(
&mpinfo->extra->label[0]))
continue;
mpls_lse_decode(mpinfo->extra->label[0], &label,
&ttl, &exp, &bos);
transpose_sid(&api_nh->seg6_segs, label,
sid_info->transposition_offset,
sid_info->transposition_len);
}
SET_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_SEG6);
}
valid_nh_count++;
}
is_add = (valid_nh_count || nhg_id) ? true : false;
if (is_add && CHECK_FLAG(bm->flags, BM_FLAG_SEND_EXTRA_DATA_TO_ZEBRA)) {
struct bgp_zebra_opaque bzo = {};
const char *reason =
bgp_path_selection_reason2str(dest->reason);
strlcpy(bzo.aspath, info->attr->aspath->str,
sizeof(bzo.aspath));
if (info->attr->flag & ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES))
strlcpy(bzo.community,
bgp_attr_get_community(info->attr)->str,
sizeof(bzo.community));
if (info->attr->flag
& ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES))
strlcpy(bzo.lcommunity,
bgp_attr_get_lcommunity(info->attr)->str,
sizeof(bzo.lcommunity));
strlcpy(bzo.selection_reason, reason,
sizeof(bzo.selection_reason));
SET_FLAG(api.message, ZAPI_MESSAGE_OPAQUE);
api.opaque.length = MIN(sizeof(struct bgp_zebra_opaque),
ZAPI_MESSAGE_OPAQUE_LENGTH);
memcpy(api.opaque.data, &bzo, api.opaque.length);
}
if (allow_recursion)
SET_FLAG(api.flags, ZEBRA_FLAG_ALLOW_RECURSION);
/*
* When we create an aggregate route we must also
* install a Null0 route in the RIB, so overwrite
* what was written into api with a blackhole route
*/
if (info->sub_type == BGP_ROUTE_AGGREGATE)
zapi_route_set_blackhole(&api, BLACKHOLE_NULL);
else
api.nexthop_num = valid_nh_count;
SET_FLAG(api.message, ZAPI_MESSAGE_METRIC);
api.metric = metric;
if (tag) {
SET_FLAG(api.message, ZAPI_MESSAGE_TAG);
api.tag = tag;
}
distance = bgp_distance_apply(p, info, afi, safi, bgp);
if (distance) {
SET_FLAG(api.message, ZAPI_MESSAGE_DISTANCE);
api.distance = distance;
}
if (bgp_debug_zebra(p)) {
char nh_buf[INET6_ADDRSTRLEN];
char eth_buf[ETHER_ADDR_STRLEN + 7] = {'\0'};
char buf1[ETHER_ADDR_STRLEN];
char label_buf[20];
char sid_buf[20];
char segs_buf[256];
int i;
zlog_debug(
"Tx route %s VRF %u %pFX metric %u tag %" ROUTE_TAG_PRI
" count %d nhg %d",
valid_nh_count ? "add" : "delete", bgp->vrf_id,
&api.prefix, api.metric, api.tag, api.nexthop_num,
nhg_id);
for (i = 0; i < api.nexthop_num; i++) {
api_nh = &api.nexthops[i];
switch (api_nh->type) {
case NEXTHOP_TYPE_IFINDEX:
nh_buf[0] = '\0';
break;
case NEXTHOP_TYPE_IPV4:
case NEXTHOP_TYPE_IPV4_IFINDEX:
nh_family = AF_INET;
inet_ntop(nh_family, &api_nh->gate, nh_buf,
sizeof(nh_buf));
break;
case NEXTHOP_TYPE_IPV6:
case NEXTHOP_TYPE_IPV6_IFINDEX:
nh_family = AF_INET6;
inet_ntop(nh_family, &api_nh->gate, nh_buf,
sizeof(nh_buf));
break;
case NEXTHOP_TYPE_BLACKHOLE:
strlcpy(nh_buf, "blackhole", sizeof(nh_buf));
break;
default:
/* Note: add new nexthop case */
assert(0);
break;
}
label_buf[0] = '\0';
eth_buf[0] = '\0';
segs_buf[0] = '\0';
if (CHECK_FLAG(api_nh->flags,
ZAPI_NEXTHOP_FLAG_LABEL) &&
!CHECK_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_EVPN))
snprintf(label_buf, sizeof(label_buf),
"label %u", api_nh->labels[0]);
if (CHECK_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_SEG6) &&
!CHECK_FLAG(api_nh->flags,
ZAPI_NEXTHOP_FLAG_EVPN)) {
inet_ntop(AF_INET6, &api_nh->seg6_segs,
sid_buf, sizeof(sid_buf));
snprintf(segs_buf, sizeof(segs_buf), "segs %s",
sid_buf);
}
if (CHECK_FLAG(api_nh->flags, ZAPI_NEXTHOP_FLAG_EVPN) &&
!is_zero_mac(&api_nh->rmac))
snprintf(eth_buf, sizeof(eth_buf), " RMAC %s",
prefix_mac2str(&api_nh->rmac,
buf1, sizeof(buf1)));
zlog_debug(" nhop [%d]: %s if %u VRF %u wt %u %s %s %s",
i + 1, nh_buf, api_nh->ifindex,
api_nh->vrf_id, api_nh->weight,
label_buf, segs_buf, eth_buf);
}
int recursion_flag = 0;
if (CHECK_FLAG(api.flags, ZEBRA_FLAG_ALLOW_RECURSION))
recursion_flag = 1;
zlog_debug("%s: %pFX: announcing to zebra (recursion %sset)",
__func__, p, (recursion_flag ? "" : "NOT "));
}
zclient_route_send(is_add ? ZEBRA_ROUTE_ADD : ZEBRA_ROUTE_DELETE,
zclient, &api);
}
/* Announce all routes of a table to zebra */
void bgp_zebra_announce_table(struct bgp *bgp, afi_t afi, safi_t safi)
{
struct bgp_dest *dest;
struct bgp_table *table;
struct bgp_path_info *pi;
/* Don't try to install if we're not connected to Zebra or Zebra doesn't
* know of this instance.
*/
if (!bgp_install_info_to_zebra(bgp))
return;
table = bgp->rib[afi][safi];
if (!table)
return;
for (dest = bgp_table_top(table); dest; dest = bgp_route_next(dest))
for (pi = bgp_dest_get_bgp_path_info(dest); pi; pi = pi->next)
if (CHECK_FLAG(pi->flags, BGP_PATH_SELECTED) &&
(pi->type == ZEBRA_ROUTE_BGP
&& (pi->sub_type == BGP_ROUTE_NORMAL
|| pi->sub_type == BGP_ROUTE_IMPORTED)))
bgp_zebra_announce(dest,
bgp_dest_get_prefix(dest),
pi, bgp, afi, safi);
}
/* Announce routes of any bgp subtype of a table to zebra */
void bgp_zebra_announce_table_all_subtypes(struct bgp *bgp, afi_t afi,
safi_t safi)
{
struct bgp_dest *dest;
struct bgp_table *table;
struct bgp_path_info *pi;
if (!bgp_install_info_to_zebra(bgp))
return;
table = bgp->rib[afi][safi];
if (!table)
return;
for (dest = bgp_table_top(table); dest; dest = bgp_route_next(dest))
for (pi = bgp_dest_get_bgp_path_info(dest); pi; pi = pi->next)
if (CHECK_FLAG(pi->flags, BGP_PATH_SELECTED) &&
pi->type == ZEBRA_ROUTE_BGP)
bgp_zebra_announce(dest,
bgp_dest_get_prefix(dest),
pi, bgp, afi, safi);
}
void bgp_zebra_withdraw(const struct prefix *p, struct bgp_path_info *info,
struct bgp *bgp, safi_t safi)
{
struct zapi_route api;
struct peer *peer;
/* Don't try to install if we're not connected to Zebra or Zebra doesn't
* know of this instance.
*/
if (!bgp_install_info_to_zebra(bgp))
return;
if (safi == SAFI_FLOWSPEC) {
peer = info->peer;
bgp_pbr_update_entry(peer->bgp, p, info, AFI_IP, safi, false);
return;
}
memset(&api, 0, sizeof(api));
api.vrf_id = bgp->vrf_id;
api.type = ZEBRA_ROUTE_BGP;
api.safi = safi;
api.prefix = *p;
if (info->attr->rmap_table_id) {
SET_FLAG(api.message, ZAPI_MESSAGE_TABLEID);
api.tableid = info->attr->rmap_table_id;
}
if (bgp_debug_zebra(p))
zlog_debug("Tx route delete VRF %u %pFX", bgp->vrf_id,
&api.prefix);
zclient_route_send(ZEBRA_ROUTE_DELETE, zclient, &api);
}
/* Withdraw all entries in a BGP instances RIB table from Zebra */
void bgp_zebra_withdraw_table_all_subtypes(struct bgp *bgp, afi_t afi, safi_t safi)
{
struct bgp_dest *dest;
struct bgp_table *table;
struct bgp_path_info *pi;
if (!bgp_install_info_to_zebra(bgp))
return;
table = bgp->rib[afi][safi];
if (!table)
return;
for (dest = bgp_table_top(table); dest; dest = bgp_route_next(dest)) {
for (pi = bgp_dest_get_bgp_path_info(dest); pi; pi = pi->next) {
if (CHECK_FLAG(pi->flags, BGP_PATH_SELECTED)
&& (pi->type == ZEBRA_ROUTE_BGP))
bgp_zebra_withdraw(bgp_dest_get_prefix(dest),
pi, bgp, safi);
}
}
}
struct bgp_redist *bgp_redist_lookup(struct bgp *bgp, afi_t afi, uint8_t type,
unsigned short instance)
{
struct list *red_list;
struct listnode *node;
struct bgp_redist *red;
red_list = bgp->redist[afi][type];
if (!red_list)
return (NULL);
for (ALL_LIST_ELEMENTS_RO(red_list, node, red))
if (red->instance == instance)
return red;
return NULL;
}
struct bgp_redist *bgp_redist_add(struct bgp *bgp, afi_t afi, uint8_t type,
unsigned short instance)
{
struct list *red_list;
struct bgp_redist *red;
red = bgp_redist_lookup(bgp, afi, type, instance);
if (red)
return red;
if (!bgp->redist[afi][type])
bgp->redist[afi][type] = list_new();
red_list = bgp->redist[afi][type];
red = XCALLOC(MTYPE_BGP_REDIST, sizeof(struct bgp_redist));
red->instance = instance;
listnode_add(red_list, red);
return red;
}
static void bgp_redist_del(struct bgp *bgp, afi_t afi, uint8_t type,
unsigned short instance)
{
struct bgp_redist *red;
red = bgp_redist_lookup(bgp, afi, type, instance);
if (red) {
listnode_delete(bgp->redist[afi][type], red);
XFREE(MTYPE_BGP_REDIST, red);
if (!bgp->redist[afi][type]->count)
list_delete(&bgp->redist[afi][type]);
}
}
/* Other routes redistribution into BGP. */
int bgp_redistribute_set(struct bgp *bgp, afi_t afi, int type,
unsigned short instance, bool changed)
{
/* If redistribute options are changed call
* bgp_redistribute_unreg() to reset the option and withdraw
* the routes
*/
if (changed)
bgp_redistribute_unreg(bgp, afi, type, instance);
/* Return if already redistribute flag is set. */
if (instance) {
if (redist_check_instance(&zclient->mi_redist[afi][type],
instance))
return CMD_WARNING;
redist_add_instance(&zclient->mi_redist[afi][type], instance);
} else {
if (vrf_bitmap_check(zclient->redist[afi][type], bgp->vrf_id))
return CMD_WARNING;
#ifdef ENABLE_BGP_VNC
if (EVPN_ENABLED(bgp) && type == ZEBRA_ROUTE_VNC_DIRECT) {
vnc_export_bgp_enable(
bgp, afi); /* only enables if mode bits cfg'd */
}
#endif
vrf_bitmap_set(zclient->redist[afi][type], bgp->vrf_id);
}
/*
* Don't try to register if we're not connected to Zebra or Zebra
* doesn't know of this instance.
*
* When we come up later well resend if needed.
*/
if (!bgp_install_info_to_zebra(bgp))
return CMD_SUCCESS;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Tx redistribute add VRF %u afi %d %s %d",
bgp->vrf_id, afi, zebra_route_string(type),
instance);
/* Send distribute add message to zebra. */
zebra_redistribute_send(ZEBRA_REDISTRIBUTE_ADD, zclient, afi, type,
instance, bgp->vrf_id);
return CMD_SUCCESS;
}
int bgp_redistribute_resend(struct bgp *bgp, afi_t afi, int type,
unsigned short instance)
{
/* Don't try to send if we're not connected to Zebra or Zebra doesn't
* know of this instance.
*/
if (!bgp_install_info_to_zebra(bgp))
return -1;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Tx redistribute del/add VRF %u afi %d %s %d",
bgp->vrf_id, afi, zebra_route_string(type),
instance);
/* Send distribute add message to zebra. */
zebra_redistribute_send(ZEBRA_REDISTRIBUTE_DELETE, zclient, afi, type,
instance, bgp->vrf_id);
zebra_redistribute_send(ZEBRA_REDISTRIBUTE_ADD, zclient, afi, type,
instance, bgp->vrf_id);
return 0;
}
/* Redistribute with route-map specification. */
bool bgp_redistribute_rmap_set(struct bgp_redist *red, const char *name,
struct route_map *route_map)
{
if (red->rmap.name && (strcmp(red->rmap.name, name) == 0))
return false;
XFREE(MTYPE_ROUTE_MAP_NAME, red->rmap.name);
/* Decrement the count for existing routemap and
* increment the count for new route map.
*/
route_map_counter_decrement(red->rmap.map);
red->rmap.name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, name);
red->rmap.map = route_map;
route_map_counter_increment(red->rmap.map);
return true;
}
/* Redistribute with metric specification. */
bool bgp_redistribute_metric_set(struct bgp *bgp, struct bgp_redist *red,
afi_t afi, int type, uint32_t metric)
{
struct bgp_dest *dest;
struct bgp_path_info *pi;
if (red->redist_metric_flag && red->redist_metric == metric)
return false;
red->redist_metric_flag = 1;
red->redist_metric = metric;
for (dest = bgp_table_top(bgp->rib[afi][SAFI_UNICAST]); dest;
dest = bgp_route_next(dest)) {
for (pi = bgp_dest_get_bgp_path_info(dest); pi; pi = pi->next) {
if (pi->sub_type == BGP_ROUTE_REDISTRIBUTE
&& pi->type == type
&& pi->instance == red->instance) {
struct attr *old_attr;
struct attr new_attr;
new_attr = *pi->attr;
new_attr.med = red->redist_metric;
old_attr = pi->attr;
pi->attr = bgp_attr_intern(&new_attr);
bgp_attr_unintern(&old_attr);
bgp_path_info_set_flag(dest, pi,
BGP_PATH_ATTR_CHANGED);
bgp_process(bgp, dest, afi, SAFI_UNICAST);
}
}
}
return true;
}
/* Unset redistribution. */
int bgp_redistribute_unreg(struct bgp *bgp, afi_t afi, int type,
unsigned short instance)
{
struct bgp_redist *red;
red = bgp_redist_lookup(bgp, afi, type, instance);
if (!red)
return CMD_SUCCESS;
/* Return if zebra connection is disabled. */
if (instance) {
if (!redist_check_instance(&zclient->mi_redist[afi][type],
instance))
return CMD_WARNING;
redist_del_instance(&zclient->mi_redist[afi][type], instance);
} else {
if (!vrf_bitmap_check(zclient->redist[afi][type], bgp->vrf_id))
return CMD_WARNING;
vrf_bitmap_unset(zclient->redist[afi][type], bgp->vrf_id);
}
if (bgp_install_info_to_zebra(bgp)) {
/* Send distribute delete message to zebra. */
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Tx redistribute del VRF %u afi %d %s %d",
bgp->vrf_id, afi, zebra_route_string(type),
instance);
zebra_redistribute_send(ZEBRA_REDISTRIBUTE_DELETE, zclient, afi,
type, instance, bgp->vrf_id);
}
/* Withdraw redistributed routes from current BGP's routing table. */
bgp_redistribute_withdraw(bgp, afi, type, instance);
return CMD_SUCCESS;
}
/* Unset redistribution. */
int bgp_redistribute_unset(struct bgp *bgp, afi_t afi, int type,
unsigned short instance)
{
struct bgp_redist *red;
/*
* vnc and vpn->vrf checks must be before red check because
* they operate within bgpd irrespective of zebra connection
* status. red lookup fails if there is no zebra connection.
*/
#ifdef ENABLE_BGP_VNC
if (EVPN_ENABLED(bgp) && type == ZEBRA_ROUTE_VNC_DIRECT) {
vnc_export_bgp_disable(bgp, afi);
}
#endif
red = bgp_redist_lookup(bgp, afi, type, instance);
if (!red)
return CMD_SUCCESS;
bgp_redistribute_unreg(bgp, afi, type, instance);
/* Unset route-map. */
XFREE(MTYPE_ROUTE_MAP_NAME, red->rmap.name);
route_map_counter_decrement(red->rmap.map);
red->rmap.map = NULL;
/* Unset metric. */
red->redist_metric_flag = 0;
red->redist_metric = 0;
bgp_redist_del(bgp, afi, type, instance);
return CMD_SUCCESS;
}
void bgp_redistribute_redo(struct bgp *bgp)
{
afi_t afi;
int i;
struct list *red_list;
struct listnode *node;
struct bgp_redist *red;
for (afi = AFI_IP; afi < AFI_MAX; afi++) {
for (i = 0; i < ZEBRA_ROUTE_MAX; i++) {
red_list = bgp->redist[afi][i];
if (!red_list)
continue;
for (ALL_LIST_ELEMENTS_RO(red_list, node, red)) {
bgp_redistribute_resend(bgp, afi, i,
red->instance);
}
}
}
}
void bgp_zclient_reset(void)
{
zclient_reset(zclient);
}
/* Register this instance with Zebra. Invoked upon connect (for
* default instance) and when other VRFs are learnt (or created and
* already learnt).
*/
void bgp_zebra_instance_register(struct bgp *bgp)
{
/* Don't try to register if we're not connected to Zebra */
if (!zclient || zclient->sock < 0)
return;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Registering VRF %u", bgp->vrf_id);
/* Register for router-id, interfaces, redistributed routes. */
zclient_send_reg_requests(zclient, bgp->vrf_id);
/* For EVPN instance, register to learn about VNIs, if appropriate. */
if (bgp->advertise_all_vni)
bgp_zebra_advertise_all_vni(bgp, 1);
bgp_nht_register_nexthops(bgp);
}
/* Deregister this instance with Zebra. Invoked upon the instance
* being deleted (default or VRF) and it is already registered.
*/
void bgp_zebra_instance_deregister(struct bgp *bgp)
{
/* Don't try to deregister if we're not connected to Zebra */
if (zclient->sock < 0)
return;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Deregistering VRF %u", bgp->vrf_id);
/* For EVPN instance, unregister learning about VNIs, if appropriate. */
if (bgp->advertise_all_vni)
bgp_zebra_advertise_all_vni(bgp, 0);
/* Deregister for router-id, interfaces, redistributed routes. */
zclient_send_dereg_requests(zclient, bgp->vrf_id);
}
void bgp_zebra_initiate_radv(struct bgp *bgp, struct peer *peer)
{
uint32_t ra_interval = BGP_UNNUM_DEFAULT_RA_INTERVAL;
/* Don't try to initiate if we're not connected to Zebra */
if (zclient->sock < 0)
return;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%u: Initiating RA for peer %s", bgp->vrf_id,
peer->host);
/*
* If unnumbered peer (peer->ifp) call thru zapi to start RAs.
* If we don't have an ifp pointer, call function to find the
* ifps for a numbered enhe peer to turn RAs on.
*/
peer->ifp ? zclient_send_interface_radv_req(zclient, bgp->vrf_id,
peer->ifp, 1, ra_interval)
: bgp_nht_reg_enhe_cap_intfs(peer);
}
void bgp_zebra_terminate_radv(struct bgp *bgp, struct peer *peer)
{
/* Don't try to terminate if we're not connected to Zebra */
if (zclient->sock < 0)
return;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%u: Terminating RA for peer %s", bgp->vrf_id,
peer->host);
/*
* If unnumbered peer (peer->ifp) call thru zapi to stop RAs.
* If we don't have an ifp pointer, call function to find the
* ifps for a numbered enhe peer to turn RAs off.
*/
peer->ifp ? zclient_send_interface_radv_req(zclient, bgp->vrf_id,
peer->ifp, 0, 0)
: bgp_nht_dereg_enhe_cap_intfs(peer);
}
int bgp_zebra_advertise_subnet(struct bgp *bgp, int advertise, vni_t vni)
{
struct stream *s = NULL;
/* Check socket. */
if (!zclient || zclient->sock < 0)
return 0;
/* Don't try to register if Zebra doesn't know of this instance. */
if (!IS_BGP_INST_KNOWN_TO_ZEBRA(bgp)) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug(
"%s: No zebra instance to talk to, cannot advertise subnet",
__func__);
return 0;
}
s = zclient->obuf;
stream_reset(s);
zclient_create_header(s, ZEBRA_ADVERTISE_SUBNET, bgp->vrf_id);
stream_putc(s, advertise);
stream_put3(s, vni);
stream_putw_at(s, 0, stream_get_endp(s));
return zclient_send_message(zclient);
}
int bgp_zebra_advertise_svi_macip(struct bgp *bgp, int advertise, vni_t vni)
{
struct stream *s = NULL;
/* Check socket. */
if (!zclient || zclient->sock < 0)
return 0;
/* Don't try to register if Zebra doesn't know of this instance. */
if (!IS_BGP_INST_KNOWN_TO_ZEBRA(bgp))
return 0;
s = zclient->obuf;
stream_reset(s);
zclient_create_header(s, ZEBRA_ADVERTISE_SVI_MACIP, bgp->vrf_id);
stream_putc(s, advertise);
stream_putl(s, vni);
stream_putw_at(s, 0, stream_get_endp(s));
return zclient_send_message(zclient);
}
int bgp_zebra_advertise_gw_macip(struct bgp *bgp, int advertise, vni_t vni)
{
struct stream *s = NULL;
/* Check socket. */
if (!zclient || zclient->sock < 0)
return 0;
/* Don't try to register if Zebra doesn't know of this instance. */
if (!IS_BGP_INST_KNOWN_TO_ZEBRA(bgp)) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug(
"%s: No zebra instance to talk to, not installing gw_macip",
__func__);
return 0;
}
s = zclient->obuf;
stream_reset(s);
zclient_create_header(s, ZEBRA_ADVERTISE_DEFAULT_GW, bgp->vrf_id);
stream_putc(s, advertise);
stream_putl(s, vni);
stream_putw_at(s, 0, stream_get_endp(s));
return zclient_send_message(zclient);
}
int bgp_zebra_vxlan_flood_control(struct bgp *bgp,
enum vxlan_flood_control flood_ctrl)
{
struct stream *s;
/* Check socket. */
if (!zclient || zclient->sock < 0)
return 0;
/* Don't try to register if Zebra doesn't know of this instance. */
if (!IS_BGP_INST_KNOWN_TO_ZEBRA(bgp)) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug(
"%s: No zebra instance to talk to, not installing all vni",
__func__);
return 0;
}
s = zclient->obuf;
stream_reset(s);
zclient_create_header(s, ZEBRA_VXLAN_FLOOD_CONTROL, bgp->vrf_id);
stream_putc(s, flood_ctrl);
stream_putw_at(s, 0, stream_get_endp(s));
return zclient_send_message(zclient);
}
int bgp_zebra_advertise_all_vni(struct bgp *bgp, int advertise)
{
struct stream *s;
/* Check socket. */
if (!zclient || zclient->sock < 0)
return 0;
/* Don't try to register if Zebra doesn't know of this instance. */
if (!IS_BGP_INST_KNOWN_TO_ZEBRA(bgp))
return 0;
s = zclient->obuf;
stream_reset(s);
zclient_create_header(s, ZEBRA_ADVERTISE_ALL_VNI, bgp->vrf_id);
stream_putc(s, advertise);
/* Also inform current BUM handling setting. This is really
* relevant only when 'advertise' is set.
*/
stream_putc(s, bgp->vxlan_flood_ctrl);
stream_putw_at(s, 0, stream_get_endp(s));
return zclient_send_message(zclient);
}
int bgp_zebra_dup_addr_detection(struct bgp *bgp)
{
struct stream *s;
/* Check socket. */
if (!zclient || zclient->sock < 0)
return 0;
/* Don't try to register if Zebra doesn't know of this instance. */
if (!IS_BGP_INST_KNOWN_TO_ZEBRA(bgp))
return 0;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("dup addr detect %s max_moves %u time %u freeze %s freeze_time %u",
bgp->evpn_info->dup_addr_detect ?
"enable" : "disable",
bgp->evpn_info->dad_max_moves,
bgp->evpn_info->dad_time,
bgp->evpn_info->dad_freeze ?
"enable" : "disable",
bgp->evpn_info->dad_freeze_time);
s = zclient->obuf;
stream_reset(s);
zclient_create_header(s, ZEBRA_DUPLICATE_ADDR_DETECTION,
bgp->vrf_id);
stream_putl(s, bgp->evpn_info->dup_addr_detect);
stream_putl(s, bgp->evpn_info->dad_time);
stream_putl(s, bgp->evpn_info->dad_max_moves);
stream_putl(s, bgp->evpn_info->dad_freeze);
stream_putl(s, bgp->evpn_info->dad_freeze_time);
stream_putw_at(s, 0, stream_get_endp(s));
return zclient_send_message(zclient);
}
static int rule_notify_owner(ZAPI_CALLBACK_ARGS)
{
uint32_t seqno, priority, unique;
enum zapi_rule_notify_owner note;
struct bgp_pbr_action *bgp_pbra;
struct bgp_pbr_rule *bgp_pbr = NULL;
char ifname[INTERFACE_NAMSIZ + 1];
if (!zapi_rule_notify_decode(zclient->ibuf, &seqno, &priority, &unique,
ifname, ¬e))
return -1;
bgp_pbra = bgp_pbr_action_rule_lookup(vrf_id, unique);
if (!bgp_pbra) {
/* look in bgp pbr rule */
bgp_pbr = bgp_pbr_rule_lookup(vrf_id, unique);
if (!bgp_pbr && note != ZAPI_RULE_REMOVED) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Fail to look BGP rule (%u)",
__func__, unique);
return 0;
}
}
switch (note) {
case ZAPI_RULE_FAIL_INSTALL:
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received RULE_FAIL_INSTALL", __func__);
if (bgp_pbra) {
bgp_pbra->installed = false;
bgp_pbra->install_in_progress = false;
} else {
bgp_pbr->installed = false;
bgp_pbr->install_in_progress = false;
}
break;
case ZAPI_RULE_INSTALLED:
if (bgp_pbra) {
bgp_pbra->installed = true;
bgp_pbra->install_in_progress = false;
} else {
struct bgp_path_info *path;
struct bgp_path_info_extra *extra;
bgp_pbr->installed = true;
bgp_pbr->install_in_progress = false;
bgp_pbr->action->refcnt++;
/* link bgp_info to bgp_pbr */
path = (struct bgp_path_info *)bgp_pbr->path;
extra = bgp_path_info_extra_get(path);
listnode_add_force(&extra->bgp_fs_iprule,
bgp_pbr);
}
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received RULE_INSTALLED", __func__);
break;
case ZAPI_RULE_FAIL_REMOVE:
case ZAPI_RULE_REMOVED:
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received RULE REMOVED", __func__);
break;
}
return 0;
}
static int ipset_notify_owner(ZAPI_CALLBACK_ARGS)
{
uint32_t unique;
enum zapi_ipset_notify_owner note;
struct bgp_pbr_match *bgp_pbim;
if (!zapi_ipset_notify_decode(zclient->ibuf,
&unique,
¬e))
return -1;
bgp_pbim = bgp_pbr_match_ipset_lookup(vrf_id, unique);
if (!bgp_pbim) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Fail to look BGP match ( %u, ID %u)",
__func__, note, unique);
return 0;
}
switch (note) {
case ZAPI_IPSET_FAIL_INSTALL:
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received IPSET_FAIL_INSTALL", __func__);
bgp_pbim->installed = false;
bgp_pbim->install_in_progress = false;
break;
case ZAPI_IPSET_INSTALLED:
bgp_pbim->installed = true;
bgp_pbim->install_in_progress = false;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received IPSET_INSTALLED", __func__);
break;
case ZAPI_IPSET_FAIL_REMOVE:
case ZAPI_IPSET_REMOVED:
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received IPSET REMOVED", __func__);
break;
}
return 0;
}
static int ipset_entry_notify_owner(ZAPI_CALLBACK_ARGS)
{
uint32_t unique;
char ipset_name[ZEBRA_IPSET_NAME_SIZE];
enum zapi_ipset_entry_notify_owner note;
struct bgp_pbr_match_entry *bgp_pbime;
if (!zapi_ipset_entry_notify_decode(
zclient->ibuf,
&unique,
ipset_name,
¬e))
return -1;
bgp_pbime = bgp_pbr_match_ipset_entry_lookup(vrf_id,
ipset_name,
unique);
if (!bgp_pbime) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug(
"%s: Fail to look BGP match entry (%u, ID %u)",
__func__, note, unique);
return 0;
}
switch (note) {
case ZAPI_IPSET_ENTRY_FAIL_INSTALL:
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received IPSET_ENTRY_FAIL_INSTALL",
__func__);
bgp_pbime->installed = false;
bgp_pbime->install_in_progress = false;
break;
case ZAPI_IPSET_ENTRY_INSTALLED:
{
struct bgp_path_info *path;
struct bgp_path_info_extra *extra;
bgp_pbime->installed = true;
bgp_pbime->install_in_progress = false;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received IPSET_ENTRY_INSTALLED",
__func__);
/* link bgp_path_info to bpme */
path = (struct bgp_path_info *)bgp_pbime->path;
extra = bgp_path_info_extra_get(path);
listnode_add_force(&extra->bgp_fs_pbr, bgp_pbime);
}
break;
case ZAPI_IPSET_ENTRY_FAIL_REMOVE:
case ZAPI_IPSET_ENTRY_REMOVED:
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received IPSET_ENTRY_REMOVED",
__func__);
break;
}
return 0;
}
static int iptable_notify_owner(ZAPI_CALLBACK_ARGS)
{
uint32_t unique;
enum zapi_iptable_notify_owner note;
struct bgp_pbr_match *bgpm;
if (!zapi_iptable_notify_decode(
zclient->ibuf,
&unique,
¬e))
return -1;
bgpm = bgp_pbr_match_iptable_lookup(vrf_id, unique);
if (!bgpm) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Fail to look BGP iptable (%u %u)",
__func__, note, unique);
return 0;
}
switch (note) {
case ZAPI_IPTABLE_FAIL_INSTALL:
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received IPTABLE_FAIL_INSTALL",
__func__);
bgpm->installed_in_iptable = false;
bgpm->install_iptable_in_progress = false;
break;
case ZAPI_IPTABLE_INSTALLED:
bgpm->installed_in_iptable = true;
bgpm->install_iptable_in_progress = false;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received IPTABLE_INSTALLED", __func__);
bgpm->action->refcnt++;
break;
case ZAPI_IPTABLE_FAIL_REMOVE:
case ZAPI_IPTABLE_REMOVED:
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: Received IPTABLE REMOVED", __func__);
break;
}
return 0;
}
/* Process route notification messages from RIB */
static int bgp_zebra_route_notify_owner(int command, struct zclient *zclient,
zebra_size_t length, vrf_id_t vrf_id)
{
struct prefix p;
enum zapi_route_notify_owner note;
uint32_t table_id;
afi_t afi;
safi_t safi;
struct bgp_dest *dest;
struct bgp *bgp;
struct bgp_path_info *pi, *new_select;
if (!zapi_route_notify_decode(zclient->ibuf, &p, &table_id, ¬e,
&afi, &safi)) {
zlog_err("%s : error in msg decode", __func__);
return -1;
}
/* Get the bgp instance */
bgp = bgp_lookup_by_vrf_id(vrf_id);
if (!bgp) {
flog_err(EC_BGP_INVALID_BGP_INSTANCE,
"%s : bgp instance not found vrf %d", __func__,
vrf_id);
return -1;
}
/* Find the bgp route node */
dest = bgp_afi_node_lookup(bgp->rib[afi][safi], afi, safi, &p,
&bgp->vrf_prd);
if (!dest)
return -1;
switch (note) {
case ZAPI_ROUTE_INSTALLED:
new_select = NULL;
/* Clear the flags so that route can be processed */
UNSET_FLAG(dest->flags, BGP_NODE_FIB_INSTALL_PENDING);
SET_FLAG(dest->flags, BGP_NODE_FIB_INSTALLED);
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("route %pRN : INSTALLED", dest);
/* Find the best route */
for (pi = dest->info; pi; pi = pi->next) {
/* Process aggregate route */
bgp_aggregate_increment(bgp, &p, pi, afi, safi);
if (CHECK_FLAG(pi->flags, BGP_PATH_SELECTED))
new_select = pi;
}
/* Advertise the route */
if (new_select)
group_announce_route(bgp, afi, safi, dest, new_select);
else {
flog_err(EC_BGP_INVALID_ROUTE,
"selected route %pRN not found", dest);
bgp_dest_unlock_node(dest);
return -1;
}
break;
case ZAPI_ROUTE_REMOVED:
/* Route deleted from dataplane, reset the installed flag
* so that route can be reinstalled when client sends
* route add later
*/
UNSET_FLAG(dest->flags, BGP_NODE_FIB_INSTALLED);
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("route %pRN: Removed from Fib", dest);
break;
case ZAPI_ROUTE_FAIL_INSTALL:
new_select = NULL;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("route: %pRN Failed to Install into Fib",
dest);
UNSET_FLAG(dest->flags, BGP_NODE_FIB_INSTALL_PENDING);
UNSET_FLAG(dest->flags, BGP_NODE_FIB_INSTALLED);
for (pi = bgp_dest_get_bgp_path_info(dest); pi; pi = pi->next) {
if (CHECK_FLAG(pi->flags, BGP_PATH_SELECTED))
new_select = pi;
}
if (new_select)
group_announce_route(bgp, afi, safi, dest, new_select);
/* Error will be logged by zebra module */
break;
case ZAPI_ROUTE_BETTER_ADMIN_WON:
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("route: %pRN removed due to better admin won",
dest);
new_select = NULL;
UNSET_FLAG(dest->flags, BGP_NODE_FIB_INSTALL_PENDING);
UNSET_FLAG(dest->flags, BGP_NODE_FIB_INSTALLED);
for (pi = bgp_dest_get_bgp_path_info(dest); pi; pi = pi->next) {
bgp_aggregate_decrement(bgp, &p, pi, afi, safi);
if (CHECK_FLAG(pi->flags, BGP_PATH_SELECTED))
new_select = pi;
}
if (new_select)
group_announce_route(bgp, afi, safi, dest, new_select);
/* No action required */
break;
case ZAPI_ROUTE_REMOVE_FAIL:
zlog_warn("%s: Route %pRN failure to remove",
__func__, dest);
break;
}
bgp_dest_unlock_node(dest);
return 0;
}
/* this function is used to forge ip rule,
* - either for iptable/ipset using fwmark id
* - or for sample ip rule cmd
*/
static void bgp_encode_pbr_rule_action(struct stream *s,
struct bgp_pbr_action *pbra,
struct bgp_pbr_rule *pbr)
{
struct prefix pfx;
uint8_t fam = AF_INET;
char ifname[INTERFACE_NAMSIZ];
if (pbra->nh.type == NEXTHOP_TYPE_IPV6)
fam = AF_INET6;
stream_putl(s, 0); /* seqno unused */
if (pbr)
stream_putl(s, pbr->priority);
else
stream_putl(s, 0);
/* ruleno unused - priority change
* ruleno permits distinguishing various FS PBR entries
* - FS PBR entries based on ipset/iptables
* - FS PBR entries based on iprule
* the latter may contain default routing information injected by FS
*/
if (pbr)
stream_putl(s, pbr->unique);
else
stream_putl(s, pbra->unique);
stream_putc(s, 0); /* ip protocol being used */
if (pbr && pbr->flags & MATCH_IP_SRC_SET)
memcpy(&pfx, &(pbr->src), sizeof(struct prefix));
else {
memset(&pfx, 0, sizeof(pfx));
pfx.family = fam;
}
stream_putc(s, pfx.family);
stream_putc(s, pfx.prefixlen);
stream_put(s, &pfx.u.prefix, prefix_blen(&pfx));
stream_putw(s, 0); /* src port */
if (pbr && pbr->flags & MATCH_IP_DST_SET)
memcpy(&pfx, &(pbr->dst), sizeof(struct prefix));
else {
memset(&pfx, 0, sizeof(pfx));
pfx.family = fam;
}
stream_putc(s, pfx.family);
stream_putc(s, pfx.prefixlen);
stream_put(s, &pfx.u.prefix, prefix_blen(&pfx));
stream_putw(s, 0); /* dst port */
stream_putc(s, 0); /* dsfield */
/* if pbr present, fwmark is not used */
if (pbr)
stream_putl(s, 0);
else
stream_putl(s, pbra->fwmark); /* fwmark */
stream_putl(s, 0); /* queue id */
stream_putw(s, 0); /* vlan_id */
stream_putw(s, 0); /* vlan_flags */
stream_putw(s, 0); /* pcp */
stream_putl(s, pbra->table_id);
memset(ifname, 0, sizeof(ifname));
stream_put(s, ifname, INTERFACE_NAMSIZ); /* ifname unused */
}
static void bgp_encode_pbr_ipset_match(struct stream *s,
struct bgp_pbr_match *pbim)
{
stream_putl(s, pbim->unique);
stream_putl(s, pbim->type);
stream_putc(s, pbim->family);
stream_put(s, pbim->ipset_name,
ZEBRA_IPSET_NAME_SIZE);
}
static void bgp_encode_pbr_ipset_entry_match(struct stream *s,
struct bgp_pbr_match_entry *pbime)
{
stream_putl(s, pbime->unique);
/* check that back pointer is not null */
stream_put(s, pbime->backpointer->ipset_name,
ZEBRA_IPSET_NAME_SIZE);
stream_putc(s, pbime->src.family);
stream_putc(s, pbime->src.prefixlen);
stream_put(s, &pbime->src.u.prefix, prefix_blen(&pbime->src));
stream_putc(s, pbime->dst.family);
stream_putc(s, pbime->dst.prefixlen);
stream_put(s, &pbime->dst.u.prefix, prefix_blen(&pbime->dst));
stream_putw(s, pbime->src_port_min);
stream_putw(s, pbime->src_port_max);
stream_putw(s, pbime->dst_port_min);
stream_putw(s, pbime->dst_port_max);
stream_putc(s, pbime->proto);
}
static void bgp_encode_pbr_iptable_match(struct stream *s,
struct bgp_pbr_action *bpa,
struct bgp_pbr_match *pbm)
{
stream_putl(s, pbm->unique2);
stream_putl(s, pbm->type);
stream_putl(s, pbm->flags);
/* TODO: correlate with what is contained
* into bgp_pbr_action.
* currently only forward supported
*/
if (bpa->nh.type == NEXTHOP_TYPE_BLACKHOLE)
stream_putl(s, ZEBRA_IPTABLES_DROP);
else
stream_putl(s, ZEBRA_IPTABLES_FORWARD);
stream_putl(s, bpa->fwmark);
stream_put(s, pbm->ipset_name,
ZEBRA_IPSET_NAME_SIZE);
stream_putc(s, pbm->family);
stream_putw(s, pbm->pkt_len_min);
stream_putw(s, pbm->pkt_len_max);
stream_putw(s, pbm->tcp_flags);
stream_putw(s, pbm->tcp_mask_flags);
stream_putc(s, pbm->dscp_value);
stream_putc(s, pbm->fragment);
stream_putc(s, pbm->protocol);
stream_putw(s, pbm->flow_label);
}
/* BGP has established connection with Zebra. */
static void bgp_zebra_connected(struct zclient *zclient)
{
struct bgp *bgp;
zclient_num_connects++; /* increment even if not responding */
/* Send the client registration */
bfd_client_sendmsg(zclient, ZEBRA_BFD_CLIENT_REGISTER, VRF_DEFAULT);
/* At this point, we may or may not have BGP instances configured, but
* we're only interested in the default VRF (others wouldn't have learnt
* the VRF from Zebra yet.)
*/
bgp = bgp_get_default();
if (!bgp)
return;
bgp_zebra_instance_register(bgp);
/* tell label pool that zebra is connected */
bgp_lp_event_zebra_up();
/* TODO - What if we have peers and networks configured, do we have to
* kick-start them?
*/
BGP_GR_ROUTER_DETECT_AND_SEND_CAPABILITY_TO_ZEBRA(bgp, bgp->peer);
}
static int bgp_zebra_process_local_es_add(ZAPI_CALLBACK_ARGS)
{
esi_t esi;
struct bgp *bgp = NULL;
struct stream *s = NULL;
char buf[ESI_STR_LEN];
struct in_addr originator_ip;
uint8_t active;
uint8_t bypass;
uint16_t df_pref;
bgp = bgp_lookup_by_vrf_id(vrf_id);
if (!bgp)
return 0;
s = zclient->ibuf;
stream_get(&esi, s, sizeof(esi_t));
originator_ip.s_addr = stream_get_ipv4(s);
active = stream_getc(s);
df_pref = stream_getw(s);
bypass = stream_getc(s);
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug(
"Rx add ESI %s originator-ip %pI4 active %u df_pref %u %s",
esi_to_str(&esi, buf, sizeof(buf)), &originator_ip,
active, df_pref, bypass ? "bypass" : "");
frrtrace(5, frr_bgp, evpn_mh_local_es_add_zrecv, &esi, originator_ip,
active, bypass, df_pref);
bgp_evpn_local_es_add(bgp, &esi, originator_ip, active, df_pref,
!!bypass);
return 0;
}
static int bgp_zebra_process_local_es_del(ZAPI_CALLBACK_ARGS)
{
esi_t esi;
struct bgp *bgp = NULL;
struct stream *s = NULL;
char buf[ESI_STR_LEN];
memset(&esi, 0, sizeof(esi_t));
bgp = bgp_lookup_by_vrf_id(vrf_id);
if (!bgp)
return 0;
s = zclient->ibuf;
stream_get(&esi, s, sizeof(esi_t));
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Rx del ESI %s",
esi_to_str(&esi, buf, sizeof(buf)));
frrtrace(1, frr_bgp, evpn_mh_local_es_del_zrecv, &esi);
bgp_evpn_local_es_del(bgp, &esi);
return 0;
}
static int bgp_zebra_process_local_es_evi(ZAPI_CALLBACK_ARGS)
{
esi_t esi;
vni_t vni;
struct bgp *bgp;
struct stream *s;
char buf[ESI_STR_LEN];
bgp = bgp_lookup_by_vrf_id(vrf_id);
if (!bgp)
return 0;
s = zclient->ibuf;
stream_get(&esi, s, sizeof(esi_t));
vni = stream_getl(s);
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Rx %s ESI %s VNI %u",
(cmd == ZEBRA_VNI_ADD) ? "add" : "del",
esi_to_str(&esi, buf, sizeof(buf)), vni);
if (cmd == ZEBRA_LOCAL_ES_EVI_ADD) {
frrtrace(2, frr_bgp, evpn_mh_local_es_evi_add_zrecv, &esi, vni);
bgp_evpn_local_es_evi_add(bgp, &esi, vni);
} else {
frrtrace(2, frr_bgp, evpn_mh_local_es_evi_del_zrecv, &esi, vni);
bgp_evpn_local_es_evi_del(bgp, &esi, vni);
}
return 0;
}
static int bgp_zebra_process_local_l3vni(ZAPI_CALLBACK_ARGS)
{
int filter = 0;
vni_t l3vni = 0;
struct ethaddr svi_rmac, vrr_rmac = {.octet = {0} };
struct in_addr originator_ip;
struct stream *s;
ifindex_t svi_ifindex;
bool is_anycast_mac = false;
memset(&svi_rmac, 0, sizeof(svi_rmac));
memset(&originator_ip, 0, sizeof(originator_ip));
s = zclient->ibuf;
l3vni = stream_getl(s);
if (cmd == ZEBRA_L3VNI_ADD) {
stream_get(&svi_rmac, s, sizeof(struct ethaddr));
originator_ip.s_addr = stream_get_ipv4(s);
stream_get(&filter, s, sizeof(int));
svi_ifindex = stream_getl(s);
stream_get(&vrr_rmac, s, sizeof(struct ethaddr));
is_anycast_mac = stream_getl(s);
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug(
"Rx L3-VNI ADD VRF %s VNI %u RMAC svi-mac %pEA vrr-mac %pEA filter %s svi-if %u",
vrf_id_to_name(vrf_id), l3vni, &svi_rmac,
&vrr_rmac,
filter ? "prefix-routes-only" : "none",
svi_ifindex);
frrtrace(8, frr_bgp, evpn_local_l3vni_add_zrecv, l3vni, vrf_id,
&svi_rmac, &vrr_rmac, filter, originator_ip,
svi_ifindex, is_anycast_mac);
bgp_evpn_local_l3vni_add(l3vni, vrf_id, &svi_rmac, &vrr_rmac,
originator_ip, filter, svi_ifindex,
is_anycast_mac);
} else {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Rx L3-VNI DEL VRF %s VNI %u",
vrf_id_to_name(vrf_id), l3vni);
frrtrace(2, frr_bgp, evpn_local_l3vni_del_zrecv, l3vni, vrf_id);
bgp_evpn_local_l3vni_del(l3vni, vrf_id);
}
return 0;
}
static int bgp_zebra_process_local_vni(ZAPI_CALLBACK_ARGS)
{
struct stream *s;
vni_t vni;
struct bgp *bgp;
struct in_addr vtep_ip = {INADDR_ANY};
vrf_id_t tenant_vrf_id = VRF_DEFAULT;
struct in_addr mcast_grp = {INADDR_ANY};
ifindex_t svi_ifindex = 0;
s = zclient->ibuf;
vni = stream_getl(s);
if (cmd == ZEBRA_VNI_ADD) {
vtep_ip.s_addr = stream_get_ipv4(s);
stream_get(&tenant_vrf_id, s, sizeof(vrf_id_t));
mcast_grp.s_addr = stream_get_ipv4(s);
stream_get(&svi_ifindex, s, sizeof(ifindex_t));
}
bgp = bgp_lookup_by_vrf_id(vrf_id);
if (!bgp)
return 0;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug(
"Rx VNI %s VRF %s VNI %u tenant-vrf %s SVI ifindex %u",
(cmd == ZEBRA_VNI_ADD) ? "add" : "del",
vrf_id_to_name(vrf_id), vni,
vrf_id_to_name(tenant_vrf_id), svi_ifindex);
if (cmd == ZEBRA_VNI_ADD) {
frrtrace(4, frr_bgp, evpn_local_vni_add_zrecv, vni, vtep_ip,
tenant_vrf_id, mcast_grp);
return bgp_evpn_local_vni_add(
bgp, vni,
vtep_ip.s_addr != INADDR_ANY ? vtep_ip : bgp->router_id,
tenant_vrf_id, mcast_grp, svi_ifindex);
} else {
frrtrace(1, frr_bgp, evpn_local_vni_del_zrecv, vni);
return bgp_evpn_local_vni_del(bgp, vni);
}
}
static int bgp_zebra_process_local_macip(ZAPI_CALLBACK_ARGS)
{
struct stream *s;
vni_t vni;
struct bgp *bgp;
struct ethaddr mac;
struct ipaddr ip;
int ipa_len;
uint8_t flags = 0;
uint32_t seqnum = 0;
int state = 0;
char buf2[ESI_STR_LEN];
esi_t esi;
memset(&ip, 0, sizeof(ip));
s = zclient->ibuf;
vni = stream_getl(s);
stream_get(&mac.octet, s, ETH_ALEN);
ipa_len = stream_getl(s);
if (ipa_len != 0 && ipa_len != IPV4_MAX_BYTELEN
&& ipa_len != IPV6_MAX_BYTELEN) {
flog_err(EC_BGP_MACIP_LEN,
"%u:Recv MACIP %s with invalid IP addr length %d",
vrf_id, (cmd == ZEBRA_MACIP_ADD) ? "Add" : "Del",
ipa_len);
return -1;
}
if (ipa_len) {
ip.ipa_type =
(ipa_len == IPV4_MAX_BYTELEN) ? IPADDR_V4 : IPADDR_V6;
stream_get(&ip.ip.addr, s, ipa_len);
}
if (cmd == ZEBRA_MACIP_ADD) {
flags = stream_getc(s);
seqnum = stream_getl(s);
stream_get(&esi, s, sizeof(esi_t));
} else {
state = stream_getl(s);
memset(&esi, 0, sizeof(esi_t));
}
bgp = bgp_lookup_by_vrf_id(vrf_id);
if (!bgp)
return 0;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug(
"%u:Recv MACIP %s f 0x%x MAC %pEA IP %pIA VNI %u seq %u state %d ESI %s",
vrf_id, (cmd == ZEBRA_MACIP_ADD) ? "Add" : "Del", flags,
&mac, &ip, vni, seqnum, state,
esi_to_str(&esi, buf2, sizeof(buf2)));
if (cmd == ZEBRA_MACIP_ADD) {
frrtrace(6, frr_bgp, evpn_local_macip_add_zrecv, vni, &mac, &ip,
flags, seqnum, &esi);
return bgp_evpn_local_macip_add(bgp, vni, &mac, &ip,
flags, seqnum, &esi);
} else {
frrtrace(4, frr_bgp, evpn_local_macip_del_zrecv, vni, &mac, &ip,
state);
return bgp_evpn_local_macip_del(bgp, vni, &mac, &ip, state);
}
}
static int bgp_zebra_process_local_ip_prefix(ZAPI_CALLBACK_ARGS)
{
struct stream *s = NULL;
struct bgp *bgp_vrf = NULL;
struct prefix p;
memset(&p, 0, sizeof(p));
s = zclient->ibuf;
stream_get(&p, s, sizeof(struct prefix));
bgp_vrf = bgp_lookup_by_vrf_id(vrf_id);
if (!bgp_vrf)
return 0;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Recv prefix %pFX %s on vrf %s", &p,
(cmd == ZEBRA_IP_PREFIX_ROUTE_ADD) ? "ADD" : "DEL",
vrf_id_to_name(vrf_id));
if (cmd == ZEBRA_IP_PREFIX_ROUTE_ADD) {
if (p.family == AF_INET)
bgp_evpn_advertise_type5_route(bgp_vrf, &p, NULL,
AFI_IP, SAFI_UNICAST);
else
bgp_evpn_advertise_type5_route(bgp_vrf, &p, NULL,
AFI_IP6, SAFI_UNICAST);
} else {
if (p.family == AF_INET)
bgp_evpn_withdraw_type5_route(bgp_vrf, &p, AFI_IP,
SAFI_UNICAST);
else
bgp_evpn_withdraw_type5_route(bgp_vrf, &p, AFI_IP6,
SAFI_UNICAST);
}
return 0;
}
static int bgp_zebra_process_label_chunk(ZAPI_CALLBACK_ARGS)
{
struct stream *s = NULL;
uint8_t response_keep;
uint32_t first;
uint32_t last;
uint8_t proto;
unsigned short instance;
s = zclient->ibuf;
STREAM_GETC(s, proto);
STREAM_GETW(s, instance);
STREAM_GETC(s, response_keep);
STREAM_GETL(s, first);
STREAM_GETL(s, last);
if (zclient->redist_default != proto) {
flog_err(EC_BGP_LM_ERROR, "Got LM msg with wrong proto %u",
proto);
return 0;
}
if (zclient->instance != instance) {
flog_err(EC_BGP_LM_ERROR, "Got LM msg with wrong instance %u",
proto);
return 0;
}
if (first > last ||
first < MPLS_LABEL_UNRESERVED_MIN ||
last > MPLS_LABEL_UNRESERVED_MAX) {
flog_err(EC_BGP_LM_ERROR, "%s: Invalid Label chunk: %u - %u",
__func__, first, last);
return 0;
}
if (BGP_DEBUG(zebra, ZEBRA)) {
zlog_debug("Label Chunk assign: %u - %u (%u) ",
first, last, response_keep);
}
bgp_lp_event_chunk(response_keep, first, last);
return 0;
stream_failure: /* for STREAM_GETX */
return -1;
}
extern struct zebra_privs_t bgpd_privs;
static int bgp_ifp_create(struct interface *ifp)
{
struct bgp *bgp;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("Rx Intf add VRF %u IF %s", ifp->vrf->vrf_id,
ifp->name);
bgp = ifp->vrf->info;
if (!bgp)
return 0;
bgp_mac_add_mac_entry(ifp);
bgp_update_interface_nbrs(bgp, ifp, ifp);
hook_call(bgp_vrf_status_changed, bgp, ifp);
return 0;
}
static int bgp_zebra_process_srv6_locator_chunk(ZAPI_CALLBACK_ARGS)
{
struct stream *s = NULL;
struct bgp *bgp = bgp_get_default();
struct listnode *node;
struct srv6_locator_chunk *c;
struct srv6_locator_chunk *chunk = srv6_locator_chunk_alloc();
s = zclient->ibuf;
zapi_srv6_locator_chunk_decode(s, chunk);
if (strcmp(bgp->srv6_locator_name, chunk->locator_name) != 0) {
zlog_err("%s: Locator name unmatch %s:%s", __func__,
bgp->srv6_locator_name, chunk->locator_name);
srv6_locator_chunk_free(chunk);
return 0;
}
for (ALL_LIST_ELEMENTS_RO(bgp->srv6_locator_chunks, node, c)) {
if (!prefix_cmp(&c->prefix, &chunk->prefix)) {
srv6_locator_chunk_free(chunk);
return 0;
}
}
listnode_add(bgp->srv6_locator_chunks, chunk);
vpn_leak_postchange_all();
return 0;
}
static int bgp_zebra_process_srv6_locator_add(ZAPI_CALLBACK_ARGS)
{
struct srv6_locator loc = {};
struct bgp *bgp = bgp_get_default();
const char *loc_name = bgp->srv6_locator_name;
if (zapi_srv6_locator_decode(zclient->ibuf, &loc) < 0)
return -1;
if (!bgp || !bgp->srv6_enabled)
return 0;
if (bgp_zebra_srv6_manager_get_locator_chunk(loc_name) < 0)
return -1;
return 0;
}
static int bgp_zebra_process_srv6_locator_delete(ZAPI_CALLBACK_ARGS)
{
struct srv6_locator loc = {};
struct bgp *bgp = bgp_get_default();
struct listnode *node, *nnode;
struct srv6_locator_chunk *chunk;
struct bgp_srv6_function *func;
struct bgp *bgp_vrf;
struct in6_addr *tovpn_sid, *tovpn_sid_locator;
struct prefix_ipv6 tmp_prefi;
if (zapi_srv6_locator_decode(zclient->ibuf, &loc) < 0)
return -1;
// refresh chunks
for (ALL_LIST_ELEMENTS(bgp->srv6_locator_chunks, node, nnode, chunk))
if (prefix_match((struct prefix *)&loc.prefix,
(struct prefix *)&chunk->prefix)) {
listnode_delete(bgp->srv6_locator_chunks, chunk);
srv6_locator_chunk_free(chunk);
}
// refresh functions
for (ALL_LIST_ELEMENTS(bgp->srv6_functions, node, nnode, func)) {
tmp_prefi.family = AF_INET6;
tmp_prefi.prefixlen = 128;
tmp_prefi.prefix = func->sid;
if (prefix_match((struct prefix *)&loc.prefix,
(struct prefix *)&tmp_prefi)) {
listnode_delete(bgp->srv6_functions, func);
XFREE(MTYPE_BGP_SRV6_FUNCTION, func);
}
}
// refresh tovpn_sid
for (ALL_LIST_ELEMENTS_RO(bm->bgp, node, bgp_vrf)) {
if (bgp_vrf->inst_type != BGP_INSTANCE_TYPE_VRF)
continue;
// refresh vpnv4 tovpn_sid
tovpn_sid = bgp_vrf->vpn_policy[AFI_IP].tovpn_sid;
if (tovpn_sid) {
tmp_prefi.family = AF_INET6;
tmp_prefi.prefixlen = 128;
tmp_prefi.prefix = *tovpn_sid;
if (prefix_match((struct prefix *)&loc.prefix,
(struct prefix *)&tmp_prefi))
XFREE(MTYPE_BGP_SRV6_SID,
bgp_vrf->vpn_policy[AFI_IP].tovpn_sid);
}
// refresh vpnv6 tovpn_sid
tovpn_sid = bgp_vrf->vpn_policy[AFI_IP6].tovpn_sid;
if (tovpn_sid) {
tmp_prefi.family = AF_INET6;
tmp_prefi.prefixlen = 128;
tmp_prefi.prefix = *tovpn_sid;
if (prefix_match((struct prefix *)&loc.prefix,
(struct prefix *)&tmp_prefi))
XFREE(MTYPE_BGP_SRV6_SID,
bgp_vrf->vpn_policy[AFI_IP6].tovpn_sid);
}
}
vpn_leak_postchange_all();
/* refresh tovpn_sid_locator */
for (ALL_LIST_ELEMENTS_RO(bm->bgp, node, bgp_vrf)) {
if (bgp_vrf->inst_type != BGP_INSTANCE_TYPE_VRF)
continue;
/* refresh vpnv4 tovpn_sid_locator */
tovpn_sid_locator =
bgp_vrf->vpn_policy[AFI_IP].tovpn_sid_locator;
if (tovpn_sid_locator) {
tmp_prefi.family = AF_INET6;
tmp_prefi.prefixlen = IPV6_MAX_BITLEN;
tmp_prefi.prefix = *tovpn_sid_locator;
if (prefix_match((struct prefix *)&loc.prefix,
(struct prefix *)&tmp_prefi))
XFREE(MTYPE_BGP_SRV6_SID, tovpn_sid_locator);
}
/* refresh vpnv6 tovpn_sid_locator */
tovpn_sid_locator =
bgp_vrf->vpn_policy[AFI_IP6].tovpn_sid_locator;
if (tovpn_sid_locator) {
tmp_prefi.family = AF_INET6;
tmp_prefi.prefixlen = IPV6_MAX_BITLEN;
tmp_prefi.prefix = *tovpn_sid_locator;
if (prefix_match((struct prefix *)&loc.prefix,
(struct prefix *)&tmp_prefi))
XFREE(MTYPE_BGP_SRV6_SID, tovpn_sid_locator);
}
}
return 0;
}
static zclient_handler *const bgp_handlers[] = {
[ZEBRA_ROUTER_ID_UPDATE] = bgp_router_id_update,
[ZEBRA_INTERFACE_ADDRESS_ADD] = bgp_interface_address_add,
[ZEBRA_INTERFACE_ADDRESS_DELETE] = bgp_interface_address_delete,
[ZEBRA_INTERFACE_NBR_ADDRESS_ADD] = bgp_interface_nbr_address_add,
[ZEBRA_INTERFACE_NBR_ADDRESS_DELETE] = bgp_interface_nbr_address_delete,
[ZEBRA_INTERFACE_VRF_UPDATE] = bgp_interface_vrf_update,
[ZEBRA_REDISTRIBUTE_ROUTE_ADD] = zebra_read_route,
[ZEBRA_REDISTRIBUTE_ROUTE_DEL] = zebra_read_route,
[ZEBRA_NEXTHOP_UPDATE] = bgp_read_nexthop_update,
[ZEBRA_FEC_UPDATE] = bgp_read_fec_update,
[ZEBRA_LOCAL_ES_ADD] = bgp_zebra_process_local_es_add,
[ZEBRA_LOCAL_ES_DEL] = bgp_zebra_process_local_es_del,
[ZEBRA_VNI_ADD] = bgp_zebra_process_local_vni,
[ZEBRA_LOCAL_ES_EVI_ADD] = bgp_zebra_process_local_es_evi,
[ZEBRA_LOCAL_ES_EVI_DEL] = bgp_zebra_process_local_es_evi,
[ZEBRA_VNI_DEL] = bgp_zebra_process_local_vni,
[ZEBRA_MACIP_ADD] = bgp_zebra_process_local_macip,
[ZEBRA_MACIP_DEL] = bgp_zebra_process_local_macip,
[ZEBRA_L3VNI_ADD] = bgp_zebra_process_local_l3vni,
[ZEBRA_L3VNI_DEL] = bgp_zebra_process_local_l3vni,
[ZEBRA_IP_PREFIX_ROUTE_ADD] = bgp_zebra_process_local_ip_prefix,
[ZEBRA_IP_PREFIX_ROUTE_DEL] = bgp_zebra_process_local_ip_prefix,
[ZEBRA_GET_LABEL_CHUNK] = bgp_zebra_process_label_chunk,
[ZEBRA_RULE_NOTIFY_OWNER] = rule_notify_owner,
[ZEBRA_IPSET_NOTIFY_OWNER] = ipset_notify_owner,
[ZEBRA_IPSET_ENTRY_NOTIFY_OWNER] = ipset_entry_notify_owner,
[ZEBRA_IPTABLE_NOTIFY_OWNER] = iptable_notify_owner,
[ZEBRA_ROUTE_NOTIFY_OWNER] = bgp_zebra_route_notify_owner,
[ZEBRA_SRV6_LOCATOR_ADD] = bgp_zebra_process_srv6_locator_add,
[ZEBRA_SRV6_LOCATOR_DELETE] = bgp_zebra_process_srv6_locator_delete,
[ZEBRA_SRV6_MANAGER_GET_LOCATOR_CHUNK] =
bgp_zebra_process_srv6_locator_chunk,
};
static int bgp_if_new_hook(struct interface *ifp)
{
struct bgp_interface *iifp;
if (ifp->info)
return 0;
iifp = XCALLOC(MTYPE_BGP_IF_INFO, sizeof(struct bgp_interface));
ifp->info = iifp;
return 0;
}
static int bgp_if_delete_hook(struct interface *ifp)
{
XFREE(MTYPE_BGP_IF_INFO, ifp->info);
return 0;
}
void bgp_if_init(void)
{
/* Initialize Zebra interface data structure. */
hook_register_prio(if_add, 0, bgp_if_new_hook);
hook_register_prio(if_del, 0, bgp_if_delete_hook);
}
void bgp_zebra_init(struct thread_master *master, unsigned short instance)
{
zclient_num_connects = 0;
if_zapi_callbacks(bgp_ifp_create, bgp_ifp_up,
bgp_ifp_down, bgp_ifp_destroy);
/* Set default values. */
zclient = zclient_new(master, &zclient_options_default, bgp_handlers,
array_size(bgp_handlers));
zclient_init(zclient, ZEBRA_ROUTE_BGP, 0, &bgpd_privs);
zclient->zebra_connected = bgp_zebra_connected;
zclient->instance = instance;
}
void bgp_zebra_destroy(void)
{
if (zclient == NULL)
return;
zclient_stop(zclient);
zclient_free(zclient);
zclient = NULL;
}
int bgp_zebra_num_connects(void)
{
return zclient_num_connects;
}
void bgp_send_pbr_rule_action(struct bgp_pbr_action *pbra,
struct bgp_pbr_rule *pbr,
bool install)
{
struct stream *s;
if (pbra->install_in_progress && !pbr)
return;
if (pbr && pbr->install_in_progress)
return;
if (BGP_DEBUG(zebra, ZEBRA)) {
if (pbr)
zlog_debug("%s: table %d (ip rule) %d", __func__,
pbra->table_id, install);
else
zlog_debug("%s: table %d fwmark %d %d", __func__,
pbra->table_id, pbra->fwmark, install);
}
s = zclient->obuf;
stream_reset(s);
zclient_create_header(s,
install ? ZEBRA_RULE_ADD : ZEBRA_RULE_DELETE,
VRF_DEFAULT);
stream_putl(s, 1); /* send one pbr action */
bgp_encode_pbr_rule_action(s, pbra, pbr);
stream_putw_at(s, 0, stream_get_endp(s));
if ((zclient_send_message(zclient) != ZCLIENT_SEND_FAILURE)
&& install) {
if (!pbr)
pbra->install_in_progress = true;
else
pbr->install_in_progress = true;
}
}
void bgp_send_pbr_ipset_match(struct bgp_pbr_match *pbrim, bool install)
{
struct stream *s;
if (pbrim->install_in_progress)
return;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: name %s type %d %d, ID %u", __func__,
pbrim->ipset_name, pbrim->type, install,
pbrim->unique);
s = zclient->obuf;
stream_reset(s);
zclient_create_header(s,
install ? ZEBRA_IPSET_CREATE :
ZEBRA_IPSET_DESTROY,
VRF_DEFAULT);
stream_putl(s, 1); /* send one pbr action */
bgp_encode_pbr_ipset_match(s, pbrim);
stream_putw_at(s, 0, stream_get_endp(s));
if ((zclient_send_message(zclient) != ZCLIENT_SEND_FAILURE) && install)
pbrim->install_in_progress = true;
}
void bgp_send_pbr_ipset_entry_match(struct bgp_pbr_match_entry *pbrime,
bool install)
{
struct stream *s;
if (pbrime->install_in_progress)
return;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: name %s %d %d, ID %u", __func__,
pbrime->backpointer->ipset_name, pbrime->unique,
install, pbrime->unique);
s = zclient->obuf;
stream_reset(s);
zclient_create_header(s,
install ? ZEBRA_IPSET_ENTRY_ADD :
ZEBRA_IPSET_ENTRY_DELETE,
VRF_DEFAULT);
stream_putl(s, 1); /* send one pbr action */
bgp_encode_pbr_ipset_entry_match(s, pbrime);
stream_putw_at(s, 0, stream_get_endp(s));
if ((zclient_send_message(zclient) != ZCLIENT_SEND_FAILURE) && install)
pbrime->install_in_progress = true;
}
static void bgp_encode_pbr_interface_list(struct bgp *bgp, struct stream *s,
uint8_t family)
{
struct bgp_pbr_config *bgp_pbr_cfg = bgp->bgp_pbr_cfg;
struct bgp_pbr_interface_head *head;
struct bgp_pbr_interface *pbr_if;
struct interface *ifp;
if (!bgp_pbr_cfg)
return;
if (family == AF_INET)
head = &(bgp_pbr_cfg->ifaces_by_name_ipv4);
else
head = &(bgp_pbr_cfg->ifaces_by_name_ipv6);
RB_FOREACH (pbr_if, bgp_pbr_interface_head, head) {
ifp = if_lookup_by_name(pbr_if->name, bgp->vrf_id);
if (ifp)
stream_putl(s, ifp->ifindex);
}
}
static int bgp_pbr_get_ifnumber(struct bgp *bgp, uint8_t family)
{
struct bgp_pbr_config *bgp_pbr_cfg = bgp->bgp_pbr_cfg;
struct bgp_pbr_interface_head *head;
struct bgp_pbr_interface *pbr_if;
int cnt = 0;
if (!bgp_pbr_cfg)
return 0;
if (family == AF_INET)
head = &(bgp_pbr_cfg->ifaces_by_name_ipv4);
else
head = &(bgp_pbr_cfg->ifaces_by_name_ipv6);
RB_FOREACH (pbr_if, bgp_pbr_interface_head, head) {
if (if_lookup_by_name(pbr_if->name, bgp->vrf_id))
cnt++;
}
return cnt;
}
void bgp_send_pbr_iptable(struct bgp_pbr_action *pba,
struct bgp_pbr_match *pbm,
bool install)
{
struct stream *s;
int ret = 0;
int nb_interface;
if (pbm->install_iptable_in_progress)
return;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("%s: name %s type %d mark %d %d, ID %u", __func__,
pbm->ipset_name, pbm->type, pba->fwmark, install,
pbm->unique2);
s = zclient->obuf;
stream_reset(s);
zclient_create_header(s,
install ? ZEBRA_IPTABLE_ADD :
ZEBRA_IPTABLE_DELETE,
VRF_DEFAULT);
bgp_encode_pbr_iptable_match(s, pba, pbm);
nb_interface = bgp_pbr_get_ifnumber(pba->bgp, pbm->family);
stream_putl(s, nb_interface);
if (nb_interface)
bgp_encode_pbr_interface_list(pba->bgp, s, pbm->family);
stream_putw_at(s, 0, stream_get_endp(s));
ret = zclient_send_message(zclient);
if (install) {
if (ret != ZCLIENT_SEND_FAILURE)
pba->refcnt++;
else
pbm->install_iptable_in_progress = true;
}
}
/* inject in table <table_id> a default route to:
* - if nexthop IP is present : to this nexthop
* - if vrf is different from local : to the matching VRF
*/
void bgp_zebra_announce_default(struct bgp *bgp, struct nexthop *nh,
afi_t afi, uint32_t table_id, bool announce)
{
struct zapi_nexthop *api_nh;
struct zapi_route api;
struct prefix p;
if (!nh || (nh->type != NEXTHOP_TYPE_IPV4
&& nh->type != NEXTHOP_TYPE_IPV6)
|| nh->vrf_id == VRF_UNKNOWN)
return;
/* in vrf-lite, no default route has to be announced
* the table id of vrf is directly used to divert traffic
*/
if (!vrf_is_backend_netns() && bgp->vrf_id != nh->vrf_id)
return;
memset(&p, 0, sizeof(p));
if (afi != AFI_IP && afi != AFI_IP6)
return;
p.family = afi2family(afi);
memset(&api, 0, sizeof(api));
api.vrf_id = bgp->vrf_id;
api.type = ZEBRA_ROUTE_BGP;
api.safi = SAFI_UNICAST;
api.prefix = p;
api.tableid = table_id;
api.nexthop_num = 1;
SET_FLAG(api.message, ZAPI_MESSAGE_TABLEID);
SET_FLAG(api.message, ZAPI_MESSAGE_NEXTHOP);
api_nh = &api.nexthops[0];
api.distance = ZEBRA_EBGP_DISTANCE_DEFAULT;
SET_FLAG(api.message, ZAPI_MESSAGE_DISTANCE);
/* redirect IP */
if (afi == AFI_IP && nh->gate.ipv4.s_addr != INADDR_ANY) {
char buff[PREFIX_STRLEN];
api_nh->vrf_id = nh->vrf_id;
api_nh->gate.ipv4 = nh->gate.ipv4;
api_nh->type = NEXTHOP_TYPE_IPV4;
inet_ntop(AF_INET, &(nh->gate.ipv4), buff, INET_ADDRSTRLEN);
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("BGP: %s default route to %s table %d (redirect IP)",
announce ? "adding" : "withdrawing",
buff, table_id);
zclient_route_send(announce ? ZEBRA_ROUTE_ADD
: ZEBRA_ROUTE_DELETE,
zclient, &api);
} else if (afi == AFI_IP6 &&
memcmp(&nh->gate.ipv6,
&in6addr_any, sizeof(struct in6_addr))) {
char buff[PREFIX_STRLEN];
api_nh->vrf_id = nh->vrf_id;
memcpy(&api_nh->gate.ipv6, &nh->gate.ipv6,
sizeof(struct in6_addr));
api_nh->type = NEXTHOP_TYPE_IPV6;
inet_ntop(AF_INET6, &(nh->gate.ipv6), buff, INET_ADDRSTRLEN);
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("BGP: %s default route to %s table %d (redirect IP)",
announce ? "adding" : "withdrawing",
buff, table_id);
zclient_route_send(announce ? ZEBRA_ROUTE_ADD
: ZEBRA_ROUTE_DELETE,
zclient, &api);
} else if (nh->vrf_id != bgp->vrf_id) {
struct vrf *vrf;
struct interface *ifp;
vrf = vrf_lookup_by_id(nh->vrf_id);
if (!vrf)
return;
/* create default route with interface <VRF>
* with nexthop-vrf <VRF>
*/
ifp = if_lookup_by_name_vrf(vrf->name, vrf);
if (!ifp)
return;
api_nh->vrf_id = nh->vrf_id;
api_nh->type = NEXTHOP_TYPE_IFINDEX;
api_nh->ifindex = ifp->ifindex;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_info("BGP: %s default route to %s table %d (redirect VRF)",
announce ? "adding" : "withdrawing",
vrf->name, table_id);
zclient_route_send(announce ? ZEBRA_ROUTE_ADD
: ZEBRA_ROUTE_DELETE,
zclient, &api);
return;
}
}
/* Send capabilities to RIB */
int bgp_zebra_send_capabilities(struct bgp *bgp, bool disable)
{
struct zapi_cap api;
int ret = BGP_GR_SUCCESS;
if (zclient == NULL) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("zclient invalid");
return BGP_GR_FAILURE;
}
/* Check if the client is connected */
if ((zclient->sock < 0) || (zclient->t_connect)) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("client not connected");
return BGP_GR_FAILURE;
}
/* Check if capability is already sent. If the flag force is set
* send the capability since this can be initial bgp configuration
*/
memset(&api, 0, sizeof(api));
if (disable) {
api.cap = ZEBRA_CLIENT_GR_DISABLE;
api.vrf_id = bgp->vrf_id;
} else {
api.cap = ZEBRA_CLIENT_GR_CAPABILITIES;
api.stale_removal_time = bgp->rib_stale_time;
api.vrf_id = bgp->vrf_id;
}
if (zclient_capabilities_send(ZEBRA_CLIENT_CAPABILITIES, zclient, &api)
== ZCLIENT_SEND_FAILURE) {
zlog_err("error sending capability");
ret = BGP_GR_FAILURE;
} else {
if (disable)
bgp->present_zebra_gr_state = ZEBRA_GR_DISABLE;
else
bgp->present_zebra_gr_state = ZEBRA_GR_ENABLE;
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("send capabilty success");
ret = BGP_GR_SUCCESS;
}
return ret;
}
/* Send route update pesding or completed status to RIB for the
* specific AFI, SAFI
*/
int bgp_zebra_update(afi_t afi, safi_t safi, vrf_id_t vrf_id, int type)
{
struct zapi_cap api = {0};
if (zclient == NULL) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("zclient == NULL, invalid");
return BGP_GR_FAILURE;
}
/* Check if the client is connected */
if ((zclient->sock < 0) || (zclient->t_connect)) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("client not connected");
return BGP_GR_FAILURE;
}
api.afi = afi;
api.safi = safi;
api.vrf_id = vrf_id;
api.cap = type;
if (zclient_capabilities_send(ZEBRA_CLIENT_CAPABILITIES, zclient, &api)
== ZCLIENT_SEND_FAILURE) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("error sending capability");
return BGP_GR_FAILURE;
}
return BGP_GR_SUCCESS;
}
/* Send RIB stale timer update */
int bgp_zebra_stale_timer_update(struct bgp *bgp)
{
struct zapi_cap api;
if (zclient == NULL) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("zclient invalid");
return BGP_GR_FAILURE;
}
/* Check if the client is connected */
if ((zclient->sock < 0) || (zclient->t_connect)) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("client not connected");
return BGP_GR_FAILURE;
}
memset(&api, 0, sizeof(api));
api.cap = ZEBRA_CLIENT_RIB_STALE_TIME;
api.stale_removal_time = bgp->rib_stale_time;
api.vrf_id = bgp->vrf_id;
if (zclient_capabilities_send(ZEBRA_CLIENT_CAPABILITIES, zclient, &api)
== ZCLIENT_SEND_FAILURE) {
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("error sending capability");
return BGP_GR_FAILURE;
}
if (BGP_DEBUG(zebra, ZEBRA))
zlog_debug("send capabilty success");
return BGP_GR_SUCCESS;
}
int bgp_zebra_srv6_manager_get_locator_chunk(const char *name)
{
return srv6_manager_get_locator_chunk(zclient, name);
}
int bgp_zebra_srv6_manager_release_locator_chunk(const char *name)
{
return srv6_manager_release_locator_chunk(zclient, name);
}
| gpl-2.0 |
blitz/tcptrace | filter.c | 1 | 43984 | /*
* Copyright (c) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
* 2002, 2003, 2004
* Ohio University.
*
* ---
*
* Starting with the release of tcptrace version 6 in 2001, tcptrace
* is licensed under the GNU General Public License (GPL). We believe
* that, among the available licenses, the GPL will do the best job of
* allowing tcptrace to continue to be a valuable, freely-available
* and well-maintained tool for the networking community.
*
* Previous versions of tcptrace were released under a license that
* was much less restrictive with respect to how tcptrace could be
* used in commercial products. Because of this, I am willing to
* consider alternate license arrangements as allowed in Section 10 of
* the GNU GPL. Before I would consider licensing tcptrace under an
* alternate agreement with a particular individual or company,
* however, I would have to be convinced that such an alternative
* would be to the greater benefit of the networking community.
*
* ---
*
* This file is part of Tcptrace.
*
* Tcptrace was originally written and continues to be maintained by
* Shawn Ostermann with the help of a group of devoted students and
* users (see the file 'THANKS'). The work on tcptrace has been made
* possible over the years through the generous support of NASA GRC,
* the National Science Foundation, and Sun Microsystems.
*
* Tcptrace 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.
*
* Tcptrace 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 Tcptrace (in the file 'COPYING'); if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Author: Shawn Ostermann
* School of Electrical Engineering and Computer Science
* Ohio University
* Athens, OH
* ostermann@cs.ohiou.edu
* http://www.tcptrace.org/
*/
#include "tcptrace.h"
static char const GCC_UNUSED copyright[] =
"@(#)Copyright (c) 2004 -- Ohio University.\n";
static char const GCC_UNUSED rcsid[] =
"@(#)$Header$";
#include <stdio.h>
#include <stdarg.h>
#include "filter.h"
#include "filter_vars.h"
/* local routines */
static char *PrintConst(struct filter_node *pf);
static char *PrintVar(struct filter_node *pf);
static void EvalRelopUnsigned(tcp_pair *ptp, struct filter_res *pres, struct filter_node *pf);
static void EvalRelopSigned(tcp_pair *ptp, struct filter_res *pres, struct filter_node *pf);
static void EvalRelopIpaddr(tcp_pair *ptp, struct filter_res *pres, struct filter_node *pf);
static void EvalFilter(tcp_pair *ptp, struct filter_res *pres, struct filter_node *pf);
static void EvalRelopString(tcp_pair *ptp, struct filter_res *pres, struct filter_node *pf);
static void EvalVariable(tcp_pair *ptp, struct filter_res *pres, struct filter_node *pf);
static void EvalConstant(tcp_pair *ptp, struct filter_res *pres, struct filter_node *pf);
static char *PrintFilterInternal(struct filter_node *pf);
static char *Res2Str(struct filter_res *pres);
static struct filter_node *MustBeType(enum vartype var_needed, struct filter_node *pf);
static struct filter_node *LookupVar(char *varname, Bool fclient);
static void HelpFilterVariables(void);
/* local globals */
static char *exprstr = NULL;
static struct filter_node *filter_root = NULL;
char*
Op2Str(
enum optype op)
{
switch (op) {
case OP_AND: return("AND");
case OP_OR: return("OR");
case OP_GREATER: return(">");
case OP_GREATER_EQ: return(">=");
case OP_LESS: return("<");
case OP_LESS_EQ: return("<=");
case OP_EQUAL: return("==");
case OP_NEQUAL: return("!=");
case OP_PLUS: return("+");
case OP_MINUS: return("-");
case OP_TIMES: return("*");
case OP_DIVIDE: return("/");
case OP_MOD: return("%");
case OP_BAND: return("&");
case OP_BOR: return("|");
default: return("??");
}
}
char*
Vartype2BStr(
enum vartype vartype)
{
switch (vartype) {
case V_BOOL: return("BOOL");
case V_STRING: return("STRING");
case V_CHAR:
case V_FUNC:
case V_INT:
case V_LLONG:
case V_LONG:
case V_SHORT: return("SIGNED");
case V_UCHAR:
case V_UFUNC:
case V_UINT:
case V_ULLONG:
case V_ULONG:
case V_USHORT: return("UNSIGNED");
case V_IPADDR: return("IPADDR");
}
fprintf(stderr,"Vartype2BStr: Internal error, unknown type %d\n",
vartype);
exit(-1);
}
char*
Vartype2Str(
enum vartype vartype)
{
switch (vartype) {
case V_BOOL: return("BOOL");
case V_CHAR: return("CHAR");
case V_INT: return("INT");
case V_LONG: return("LONG");
case V_SHORT: return("SHORT");
case V_STRING: return("STRING");
case V_UCHAR: return("UCHAR");
case V_UINT: return("UINT");
case V_ULONG: return("ULONG");
case V_USHORT: return("USHORT");
case V_LLONG: return("LLONG");
case V_ULLONG: return("ULLONG");
case V_FUNC: return("FUNC");
case V_UFUNC: return("UFUNC");
case V_IPADDR: return("IPADDR");
}
fprintf(stderr,"Vartype2Str: Internal error, unknown type %d\n",
vartype);
exit(-1);
}
/**************************************************************/
/**************************************************************/
/** **/
/** The following routines are all for Making filter trees **/
/** **/
/**************************************************************/
/**************************************************************/
static struct filter_node *
MustBeType(
enum vartype var_needed,
struct filter_node *pf)
{
/* if they match, we're done */
if (pf->vartype == var_needed)
return(pf);
/* the only conversion we can do is unsigned to signed */
if ((pf->vartype == V_ULLONG) && (var_needed == V_LLONG)) {
struct filter_node *pf_new;
pf_new = MakeUnaryNode(OP_SIGNED,pf);
return(pf_new);
}
/* else it's an error */
fprintf(stderr,"Filter expression should be type %s, but isn't: ",
Vartype2Str(var_needed));
PrintFilter(pf);
exit(-1);
}
struct filter_node *
MakeUnaryNode(
enum optype op,
struct filter_node *pf_in)
{
struct filter_node *pf_ret = NULL;
struct filter_node *pf1;
/* walk everybody on the list and copy */
for (pf1 = pf_in; pf1; pf1=pf1->next_var) {
struct filter_node *pf_new;
/* type checking */
if (op == OP_NOT)
pf_in = MustBeType(V_BOOL,pf_in);
pf_new = MallocZ(sizeof(struct filter_node));
pf_new->op = op;
pf_new->vartype = pf1->vartype;
pf_new->un.unary.pf = pf1;
/* add to the linked list of unaries */
if (pf_ret == NULL) {
pf_ret = pf_new;
} else {
pf_new->next_var = pf_ret;
pf_ret = pf_new;
}
}
return(pf_ret);
}
static struct filter_node *
MakeDisjunction(
struct filter_node *left,
struct filter_node *right)
{
struct filter_node *pf;
/* construct a high-level OR to hook them together */
pf = MallocZ(sizeof(struct filter_node));
pf->op = OP_OR;
pf->vartype = V_BOOL;
/* hook the two opnodes together */
pf->un.binary.left = left;
pf->un.binary.right = right;
/* return the OR node */
return(pf);
}
static struct filter_node *
MakeConjunction(
struct filter_node *left,
struct filter_node *right)
{
struct filter_node *pf;
/* construct a high-level AND to hook them together */
pf = MallocZ(sizeof(struct filter_node));
pf->op = OP_AND;
pf->vartype = V_BOOL;
/* hook the two opnodes together */
pf->un.binary.left = left;
pf->un.binary.right = right;
/* return the OR node */
return(pf);
}
static struct filter_node *
MakeOneBinaryNode(
enum optype op,
struct filter_node *pf_left,
struct filter_node *pf_right)
{
struct filter_node *pf;
pf = MallocZ(sizeof(struct filter_node));
pf->op = op;
/* type checking */
switch (op) {
case OP_AND:
case OP_OR:
pf_left = MustBeType(V_BOOL,pf_left);
pf_right = MustBeType(V_BOOL,pf_right);
pf->vartype = V_BOOL;
break;
case OP_PLUS:
case OP_MINUS:
case OP_TIMES:
case OP_DIVIDE:
case OP_MOD:
case OP_BAND:
case OP_BOR:
if ((pf_left->vartype != V_LLONG) && (pf_left->vartype != V_ULLONG)) {
fprintf(stderr,"Arithmetic operator applied to non-number: ");
PrintFilter(pf_left);
exit(-1);
}
if ((pf_right->vartype != V_LLONG) && (pf_right->vartype != V_ULLONG)) {
fprintf(stderr,"Arithmetic operator applied to non-number: ");
PrintFilter(pf_right);
exit(-1);
}
/* else, they's both either signed or unsigned */
if ((pf_left->vartype == V_LLONG) && (pf_right->vartype == V_ULLONG)) {
/* convert right to signed */
pf_right = MustBeType(V_LLONG,pf_right);
} else if ((pf_left->vartype == V_ULLONG) && (pf_right->vartype == V_LLONG)) {
/* convert left to signed */
pf_left = MustBeType(V_LLONG,pf_left);
}
pf->vartype = pf_left->vartype;
break;
case OP_EQUAL:
case OP_NEQUAL:
case OP_GREATER:
case OP_GREATER_EQ:
case OP_LESS:
case OP_LESS_EQ:
/* IP addresses are special case */
if ((pf_left->vartype == V_IPADDR) ||
(pf_right->vartype == V_IPADDR)) {
/* must BOTH be addresses */
if ((pf_left->vartype != V_IPADDR) ||
(pf_right->vartype != V_IPADDR)) {
fprintf(stderr,
"IPaddreses can only be compared with each other: ");
PrintFilter(pf);
exit(-1);
}
pf->vartype = V_BOOL;
break;
}
/* Allow STRING variables like hostname, portname to be used as in
* -f'hostname=="masaka.cs.ohiou.edu"'
*/
if ((pf_left->vartype == V_STRING) && (pf_right->vartype == V_STRING)){
pf->vartype = V_BOOL;
break;
}
/* ... else, normal numeric stuff */
if ((pf_left->vartype != V_LLONG) && (pf_left->vartype != V_ULLONG)) {
fprintf(stderr,"Relational operator applied to non-number: ");
PrintFilter(pf_left);
exit(-1);
}
if ((pf_right->vartype != V_LLONG) && (pf_right->vartype != V_ULLONG)) {
fprintf(stderr,"Relational operator applied to non-number: ");
PrintFilter(pf_right);
exit(-1);
}
/* else, they's both either signed or unsigned */
if ((pf_left->vartype == V_LLONG) && (pf_right->vartype == V_ULLONG)) {
/* convert right to signed */
pf_right = MustBeType(V_LLONG,pf_right);
} else if ((pf_left->vartype == V_ULLONG) && (pf_right->vartype == V_LLONG)) {
/* convert left to signed */
pf_left = MustBeType(V_LLONG,pf_left);
}
pf->vartype = V_BOOL;
break;
default:
fprintf(stderr,"MakeBinaryNode: invalid binary operand type %d (%s)\n",
op, Op2Str(op));
exit(-1);
}
/* attach the children */
pf->un.binary.left = pf_left;
pf->un.binary.right = pf_right;
return(pf);
}
struct filter_node *
MakeBinaryNode(
enum optype op,
struct filter_node *pf_left,
struct filter_node *pf_right)
{
struct filter_node *pf_ret = NULL;
struct filter_node *pf1;
struct filter_node *pf2;
for (pf1 = pf_left; pf1; pf1=pf1->next_var) {
for (pf2 = pf_right; pf2; pf2=pf2->next_var) {
struct filter_node *pf_new;
/* make one copy */
pf_new = MakeOneBinaryNode(op,pf1,pf2);
if ((pf1->conjunction) || (pf2->conjunction))
pf_new->conjunction = TRUE;
if (debug>1)
printf("MakeBinaryNode: made %s (%c)\n",
Filter2Str(pf_new),
pf_new->conjunction?'c':'d');
/* hook together as appropriate */
switch (op) {
case OP_PLUS:
case OP_MINUS:
case OP_TIMES:
case OP_DIVIDE:
case OP_MOD:
case OP_BAND:
case OP_BOR:
/* just keep a list */
if (pf_ret == NULL) {
pf_ret = pf_new;
} else {
pf_new->next_var = pf_ret;
pf_ret = pf_new;
}
break;
case OP_AND:
case OP_OR:
case OP_EQUAL:
case OP_NEQUAL:
case OP_GREATER:
case OP_GREATER_EQ:
case OP_LESS:
case OP_LESS_EQ:
/* terminate the wildcard list by making OR nodes or AND nodes*/
if (pf_ret == NULL)
pf_ret = pf_new;
else {
if ((pf1->conjunction) || (pf2->conjunction))
pf_ret = MakeConjunction(pf_ret,pf_new);
else
pf_ret = MakeDisjunction(pf_ret,pf_new);
}
break;
default:
fprintf(stderr,"MakeBinaryNode: invalid binary operand type %d (%s)\n",
op, Op2Str(op));
exit(-1);
}
}
}
return(pf_ret);
}
struct filter_node *
MakeVarNode(
char *varname)
{
struct filter_node *pf;
if (strncasecmp(varname,"c_",2) == 0) {
/* just client */
pf = LookupVar(varname+2,TRUE);
} else if (strncasecmp(varname,"s_",2) == 0) {
/* just server */
pf = LookupVar(varname+2,FALSE);
} else if (strncasecmp(varname,"b_",2) == 0) {
/* they want a CONjunction, look up BOTH and return a list */
pf = LookupVar(varname+2,TRUE);/* client */
pf->next_var = LookupVar(varname+2,FALSE); /* server */
pf->conjunction = pf->next_var->conjunction = TRUE;
} else if (strncasecmp(varname,"e_",2) == 0) {
/* they want a DISjunction, look up BOTH and return a list */
pf = LookupVar(varname+2,TRUE);/* client */
pf->next_var = LookupVar(varname+2,FALSE); /* server */
} else {
/* look up BOTH and return a list (same as e_) */
pf = LookupVar(varname,TRUE);/* client */
pf->next_var = LookupVar(varname,FALSE); /* server */
}
return(pf);
}
struct filter_node *
MakeStringConstNode(
char *val)
{
struct filter_node *pf;
pf = MallocZ(sizeof(struct filter_node));
pf->op = OP_CONSTANT;
pf->vartype = V_STRING;
pf->un.constant.string = val;
return(pf);
}
struct filter_node *
MakeBoolConstNode(
Bool val)
{
struct filter_node *pf;
pf = MallocZ(sizeof(struct filter_node));
pf->vartype = V_BOOL;
pf->un.constant.bool = val;
return(pf);
}
struct filter_node *
MakeSignedConstNode(
llong val)
{
struct filter_node *pf;
pf = MallocZ(sizeof(struct filter_node));
pf->op = OP_CONSTANT;
pf->vartype = V_LLONG;
pf->un.constant.longint = val;
return(pf);
}
struct filter_node *
MakeUnsignedConstNode(
u_llong val)
{
struct filter_node *pf;
pf = MallocZ(sizeof(struct filter_node));
pf->op = OP_CONSTANT;
pf->vartype = V_ULLONG;
pf->un.constant.u_longint = val;
return(pf);
}
struct filter_node *
MakeIPaddrConstNode(
ipaddr *pipaddr)
{
struct filter_node *pf;
pf = MallocZ(sizeof(struct filter_node));
pf->op = OP_CONSTANT;
pf->vartype = V_IPADDR;
pf->un.constant.pipaddr = pipaddr;
return(pf);
}
/**************************************************************/
/**************************************************************/
/** **/
/** The folloing routines are all for PRINTING filter trees **/
/** **/
/**************************************************************/
/**************************************************************/
static char *
PrintConst(
struct filter_node *pf)
{
char buf[100];
/* for constants */
switch (pf->vartype) {
case V_ULLONG:
if (debug)
snprintf(buf,sizeof(buf),"ULLONG(%" FS_ULL ")",
pf->un.constant.u_longint);
else
snprintf(buf,sizeof(buf),"%" FS_ULL,pf->un.constant.u_longint);
break;
case V_LLONG:
if (debug)
snprintf(buf,sizeof(buf),"LLONG(%" FS_LL ")", pf->un.constant.longint);
else
snprintf(buf,sizeof(buf),"%" FS_LL, pf->un.constant.longint);
break;
case V_STRING:
if (debug)
snprintf(buf,sizeof(buf),"STRING(%s)",pf->un.constant.string);
else
snprintf(buf,sizeof(buf),"%s",pf->un.constant.string);
break;
case V_BOOL:
if (debug)
snprintf(buf,sizeof(buf),"BOOL(%s)", BOOL2STR(pf->un.constant.bool));
else
snprintf(buf,sizeof(buf),"%s", BOOL2STR(pf->un.constant.bool));
break;
case V_IPADDR:
if (debug)
snprintf(buf,sizeof(buf),"IPADDR(%s)", HostAddr(*pf->un.constant.pipaddr));
else
snprintf(buf,sizeof(buf),"%s", HostAddr(*pf->un.constant.pipaddr));
break;
default: {
fprintf(stderr,"PrintConst: unknown constant type %d (%s)\n",
pf->vartype, Vartype2Str(pf->vartype));
exit(-1);
}
}
/* small memory leak, but it's just done once for debugging... */
return(strdup(buf));
}
static char *
PrintVar(
struct filter_node *pf)
{
char buf[100];
if (debug)
snprintf(buf,sizeof(buf),"VAR(%s,'%s%s',%lu,%c)",
Vartype2Str(pf->vartype),
pf->un.variable.fclient?"c_":"s_",
pf->un.variable.name,
pf->un.variable.offset,
pf->conjunction?'c':'d');
else
snprintf(buf,sizeof(buf),"%s%s",
pf->un.variable.fclient?"c_":"s_",
pf->un.variable.name);
/* small memory leak, but it's just done once for debugging... */
return(strdup(buf));
}
/**************************************************************/
/**************************************************************/
/** **/
/** The folloing routines are all for access from tcptrace **/
/** **/
/**************************************************************/
/**************************************************************/
void
ParseFilter(
char *expr)
{
exprstr = strdup(expr);
if (debug)
printf("Parsefilter('%s') called\n", expr);
if (debug > 1)
filtyydebug = 1;
if (filtyyparse() == 0) {
/* it worked */
printf("Output filter: %s\n", Filter2Str(filter_root));
} else {
/* parsing failed */
fprintf(stderr,"Filter parsing failed\n");
exit(-1);
}
return;
}
static char *
Res2Str(
struct filter_res *pres)
{
char buf[100];
/* for constants */
switch (pres->vartype) {
case V_ULLONG: snprintf(buf,sizeof(buf),"ULLONG(%" FS_ULL ")",pres->val.u_longint); break;
case V_LLONG: snprintf(buf,sizeof(buf),"LLONG(%" FS_LL ")",pres->val.longint); break;
case V_STRING: snprintf(buf,sizeof(buf),"STRING(%s)",pres->val.string); break;
case V_BOOL: snprintf(buf,sizeof(buf),"BOOL(%s)", BOOL2STR(pres->val.bool)); break;
default: {
fprintf(stderr,"Res2Str: unknown constant type %d (%s)\n",
pres->vartype, Vartype2Str(pres->vartype));
exit(-1);
}
}
/* small memory leak, but it's just done once for debugging... */
return(strdup(buf));
}
void
PrintFilter(
struct filter_node *pf)
{
printf("%s\n", PrintFilterInternal(pf));
}
char *
Filter2Str(
struct filter_node *pf)
{
return(PrintFilterInternal(pf));
}
static char *
PrintFilterInternal(
struct filter_node *pf)
{
/* I'm tolerating a memory leak here because it's mostly just for debugging */
char buf[1024];
if (!pf)
return("");
switch(pf->op) {
case OP_CONSTANT:
snprintf(buf,sizeof(buf),"%s", PrintConst(pf));
return(strdup(buf));
case OP_VARIABLE:
snprintf(buf,sizeof(buf),"%s", PrintVar(pf));
return(strdup(buf));
case OP_AND:
case OP_OR:
case OP_EQUAL:
case OP_NEQUAL:
case OP_GREATER:
case OP_GREATER_EQ:
case OP_LESS:
case OP_LESS_EQ:
case OP_PLUS:
case OP_MINUS:
case OP_TIMES:
case OP_DIVIDE:
case OP_MOD:
case OP_BAND:
case OP_BOR:
snprintf(buf,sizeof(buf),"(%s%s%s)",
PrintFilterInternal(pf->un.binary.left),
Op2Str(pf->op),
PrintFilterInternal(pf->un.binary.right));
return(strdup(buf));
case OP_NOT:
snprintf(buf,sizeof(buf)," NOT(%s)",
PrintFilterInternal(pf->un.unary.pf));
return(strdup(buf));
case OP_SIGNED:
snprintf(buf,sizeof(buf)," SIGNED(%s)",
PrintFilterInternal(pf->un.unary.pf));
return(strdup(buf));
default:
fprintf(stderr,"PrintFilter: unknown op %d (%s)\n",
pf->op, Op2Str(pf->op));
exit(-1);
}
}
static struct filter_node *
LookupVar(
char *varname,
Bool fclient)
{
int i;
struct filter_node *pf;
void *ptr;
for (i=0; i < NUM_FILTERS; ++i) {
struct filter_line *pfl = &filters[i];
if (strcasecmp(varname,pfl->varname) == 0) {
/* we found it */
pf = MallocZ(sizeof(struct filter_node));
pf->op = OP_VARIABLE;
switch (pfl->vartype) {
case V_CHAR:
case V_INT:
case V_LLONG:
case V_LONG:
case V_SHORT:
case V_FUNC:
pf->vartype = V_LLONG; /* we'll promote on the fly */
break;
case V_UCHAR:
case V_UINT:
case V_ULLONG:
case V_ULONG:
case V_USHORT:
case V_UFUNC:
pf->vartype = V_ULLONG; /* we'll promote on the fly */
break;
case V_BOOL:
pf->vartype = V_BOOL;
break;
case V_IPADDR:
pf->vartype = V_IPADDR;
break;
case V_STRING:
pf->vartype = V_STRING;
break;
default:
pf->vartype = pf->vartype;
}
pf->un.variable.realtype = pfl->vartype;
pf->un.variable.name = strdup(varname);
if (fclient)
ptr = (void *)pfl->cl_addr;
else
ptr = (void *)pfl->sv_addr;
if ((pfl->vartype == V_FUNC) || (pfl->vartype == V_UFUNC))
pf->un.variable.offset = (u_long)ptr; /* FIXME? could still be a pointer bug here! */
else
pf->un.variable.offset = (char *)ptr - (char *)&ptp_dummy;
pf->un.variable.fclient = fclient;
return(pf);
}
}
/* not found */
fprintf(stderr,"Variable \"%s\" not found\n", varname);
HelpFilterVariables();
exit(-1);
}
static u_llong
Ptr2Signed(
tcp_pair *ptp,
enum vartype vartype,
void *ptr)
{
u_llong val;
switch (vartype) {
case V_LLONG: val = *((llong *) ptr); break;
case V_LONG: val = *((long *) ptr); break;
case V_INT: val = *((int *) ptr); break;
case V_SHORT: val = *((short *) ptr); break;
case V_CHAR: val = *((char *) ptr); break;
default: {
fprintf(stderr,
"Ptr2Signed: can't convert type %s to signed\n",
Vartype2Str(vartype));
exit(-1);
}
}
return(val);
}
static u_llong
Ptr2Unsigned(
tcp_pair *ptp,
enum vartype vartype,
void *ptr)
{
u_llong val;
switch (vartype) {
case V_ULLONG: val = *((u_llong *) ptr); break;
case V_ULONG: val = *((u_long *) ptr); break;
case V_UINT: val = *((u_int *) ptr); break;
case V_USHORT: val = *((u_short *) ptr); break;
case V_UCHAR: val = *((u_char *) ptr); break;
case V_BOOL: val = *((Bool *) ptr)==TRUE; break;
default: {
fprintf(stderr,
"Ptr2Unsigned: can't convert variable type %s to unsigned\n",
Vartype2Str(vartype));
exit(-1);
}
}
return(val);
}
static char *
Var2String(
tcp_pair *ptp,
struct filter_node *pf)
{
void *ptr;
char *str;
ptr = (char *)ptp + pf->un.variable.offset;
str = *((char **)ptr);
if (str == NULL)
str = "<NULL>";
if (debug)
printf("Var2String returns 0x%p (%s)\n",
str, str);
return(str);
}
static u_long
Var2Signed(
tcp_pair *ptp,
struct filter_node *pf)
{
void *ptr;
ptr = (char *)ptp + pf->un.variable.offset;
switch (pf->un.variable.realtype) {
case V_LLONG: return(Ptr2Signed(ptp,V_LLONG,ptr));
case V_LONG: return(Ptr2Signed(ptp,V_LONG,ptr));
case V_INT: return(Ptr2Signed(ptp,V_INT,ptr));
case V_SHORT: return(Ptr2Signed(ptp,V_SHORT,ptr));
case V_CHAR: return(Ptr2Signed(ptp,V_CHAR,ptr));
case V_FUNC:
{ /* call the function */
llong (*pfunc)(tcp_pair *ptp);
pfunc = (llong (*)(tcp_pair *))(pf->un.variable.offset);
return((*pfunc)(ptp));
}
default: {
fprintf(stderr,
"Filter eval error, can't convert variable type %s to signed\n",
Vartype2Str(pf->un.variable.realtype));
exit(-1);
}
}
}
static ipaddr *
Var2Ipaddr(
tcp_pair *ptp,
struct filter_node *pf)
{
void *ptr;
ptr = (char *)ptp + pf->un.variable.offset;
switch (pf->un.variable.realtype) {
case V_IPADDR: return(ptr);
default: {
fprintf(stderr,
"Filter eval error, can't convert variable type %s to ipaddr\n",
Vartype2Str(pf->un.variable.realtype));
exit(-1);
}
}
}
static u_long
Var2Unsigned(
tcp_pair *ptp,
struct filter_node *pf)
{
void *ptr;
ptr = (char *)ptp + pf->un.variable.offset;
switch (pf->un.variable.realtype) {
case V_ULLONG: return(Ptr2Unsigned(ptp,V_ULLONG,ptr));
case V_ULONG: return(Ptr2Unsigned(ptp,V_ULONG,ptr));
case V_UINT: return(Ptr2Unsigned(ptp,V_UINT,ptr));
case V_USHORT: return(Ptr2Unsigned(ptp,V_USHORT,ptr));
case V_UCHAR: return(Ptr2Unsigned(ptp,V_UCHAR,ptr));
case V_BOOL: return(Ptr2Unsigned(ptp,V_BOOL,ptr));
case V_UFUNC:
{ /* call the function */
u_llong (*pfunc)(tcp_pair *ptp);
pfunc = (u_llong (*)(tcp_pair *))(pf->un.variable.offset);
return((*pfunc)(ptp));
}
default: {
fprintf(stderr,
"Filter eval error, can't convert variable type %s to unsigned\n",
Vartype2Str(pf->un.variable.realtype));
exit(-1);
}
}
}
static u_llong
Const2Unsigned(
struct filter_node *pf)
{
switch (pf->vartype) {
case V_ULLONG: return((u_llong) pf->un.constant.u_longint);
case V_LLONG: return((u_llong) pf->un.constant.longint);
default: {
fprintf(stderr,
"Filter eval error, can't convert constant type %d (%s) to unsigned\n",
pf->vartype, Vartype2Str(pf->vartype));
exit(-1);
}
}
}
static llong
Const2Signed(
struct filter_node *pf)
{
switch (pf->vartype) {
case V_ULLONG: return((llong) pf->un.constant.u_longint);
case V_LLONG: return((llong) pf->un.constant.longint);
default: {
fprintf(stderr,
"Filter eval error, can't convert constant type %d (%s) to signed\n",
pf->vartype, Vartype2Str(pf->vartype));
exit(-1);
}
}
}
static ipaddr *
Const2Ipaddr(
struct filter_node *pf)
{
switch (pf->vartype) {
case V_IPADDR: return(pf->un.constant.pipaddr);
default: {
fprintf(stderr,
"Filter eval error, can't convert constant type %d (%s) to ipaddr\n",
pf->vartype, Vartype2Str(pf->vartype));
exit(-1);
}
}
}
static void
EvalMathopUnsigned(
tcp_pair *ptp,
struct filter_res *pres,
struct filter_node *pf)
{
u_llong varl;
u_llong varr;
struct filter_res res;
u_llong ret;
/* grab left hand side */
EvalFilter(ptp,&res,pf->un.binary.left);
varl = res.val.u_longint;
/* grab right hand side */
EvalFilter(ptp,&res,pf->un.binary.right);
varr = res.val.u_longint;
/* perform the operation */
switch (pf->op) {
case OP_PLUS: ret = (varl + varr); break;
case OP_MINUS: ret = (varl - varr); break;
case OP_TIMES: ret = (varl * varr); break;
case OP_DIVIDE: ret = (varl / varr); break;
case OP_MOD: ret = (varl % varr); break;
case OP_BAND: ret = (varl & varr); break;
case OP_BOR: ret = (varl | varr); break;
default: {
fprintf(stderr,"EvalMathodUnsigned: unsupported binary op: %d (%s)\n",
pf->op, Op2Str(pf->op));
exit(-1);
}
}
/* fill in the answer */
pres->vartype = V_ULLONG;
pres->val.u_longint = ret;
if (debug)
printf("EvalMathopUnsigned %" FS_ULL " %s %" FS_ULL " returns %s\n",
varl, Op2Str(pf->op), varr,
Res2Str(pres));
return;
}
static void
EvalMathopSigned(
tcp_pair *ptp,
struct filter_res *pres,
struct filter_node *pf)
{
llong varl;
llong varr;
struct filter_res res;
llong ret;
/* grab left hand side */
EvalFilter(ptp,&res,pf->un.binary.left);
varl = res.val.longint;
/* grab right hand side */
EvalFilter(ptp,&res,pf->un.binary.right);
varr = res.val.longint;
/* perform the operation */
switch (pf->op) {
case OP_PLUS: ret = (varl + varr); break;
case OP_MINUS: ret = (varl - varr); break;
case OP_TIMES: ret = (varl * varr); break;
case OP_DIVIDE: ret = (varl / varr); break;
case OP_MOD: ret = (varl % varr); break;
case OP_BAND: ret = (varl & varr); break;
case OP_BOR: ret = (varl | varr); break;
default: {
fprintf(stderr,"EvalMathodSigned: unsupported binary op: %d (%s)\n",
pf->op, Op2Str(pf->op));
exit(-1);
}
}
/* fill in the answer */
pres->vartype = V_LLONG;
pres->val.longint = ret;
if (debug)
printf("EvalMathopSigned %" FS_LL " %s %" FS_LL " returns %s\n",
varl, Op2Str(pf->op), varr,
Res2Str(pres));
return;
}
/* evaluate a leaf-node UNSigned NUMBER */
static void
EvalRelopUnsigned(
tcp_pair *ptp,
struct filter_res *pres,
struct filter_node *pf)
{
u_llong varl;
u_llong varr;
struct filter_res res;
Bool ret;
/* grab left hand side */
EvalFilter(ptp,&res,pf->un.binary.left);
varl = res.val.u_longint;
/* grab right hand side */
EvalFilter(ptp,&res,pf->un.binary.right);
varr = res.val.u_longint;
/* perform the operation */
switch (pf->op) {
case OP_GREATER: ret = (varl > varr); break;
case OP_GREATER_EQ: ret = (varl >= varr); break;
case OP_LESS: ret = (varl < varr); break;
case OP_LESS_EQ: ret = (varl <= varr); break;
case OP_EQUAL: ret = (varl == varr); break;
case OP_NEQUAL: ret = (varl != varr); break;
default: {
fprintf(stderr,"EvalUnsigned: unsupported binary op: %d (%s)\n",
pf->op, Op2Str(pf->op));
exit(-1);
}
}
/* fill in the answer */
pres->vartype = V_BOOL;
pres->val.bool = ret;
if (debug)
printf("EvalUnsigned %" FS_ULL " %s %" FS_ULL " returns %s\n",
varl, Op2Str(pf->op), varr,
BOOL2STR(ret));
return;
}
/* evaluate a leaf-node Signed NUMBER */
static void
EvalRelopSigned(
tcp_pair *ptp,
struct filter_res *pres,
struct filter_node *pf)
{
llong varl;
llong varr;
struct filter_res res;
Bool ret;
/* grab left hand side */
EvalFilter(ptp,&res,pf->un.binary.left);
varl = res.val.longint;
/* grab right hand side */
EvalFilter(ptp,&res,pf->un.binary.right);
varr = res.val.longint;
switch (pf->op) {
case OP_GREATER: ret = (varl > varr); break;
case OP_GREATER_EQ: ret = (varl >= varr); break;
case OP_LESS: ret = (varl < varr); break;
case OP_LESS_EQ: ret = (varl <= varr); break;
case OP_EQUAL: ret = (varl == varr); break;
case OP_NEQUAL: ret = (varl != varr); break;
default: {
fprintf(stderr,"EvalSigned: internal error\n");
exit(-1);
}
}
/* fill in the answer */
pres->vartype = V_BOOL;
pres->val.bool = ret;
if (debug)
printf("EvalSigned %" FS_LL " %s %" FS_LL " returns %s\n",
varl, Op2Str(pf->op), varr,
BOOL2STR(ret));
return;
}
/* evaluate a leaf-node IPaddress */
static void
EvalRelopIpaddr(
tcp_pair *ptp,
struct filter_res *pres,
struct filter_node *pf)
{
ipaddr *varl;
ipaddr *varr;
struct filter_res res;
int result;
Bool ret;
/* grab left hand side */
EvalFilter(ptp,&res,pf->un.binary.left);
varl = res.val.pipaddr;
/* grab right hand side */
EvalFilter(ptp,&res,pf->un.binary.right);
varr = res.val.pipaddr;
/* compare the 2 addresses */
result = IPcmp(varl,varr);
/* always evaluates FALSE unless both same type */
if (result == -2) {
if (debug) {
printf("EvalIpaddr %s", HostAddr(*varl));
printf("%s fails, different addr types\n",
HostAddr(*varr));
}
ret = FALSE;
} else {
switch (pf->op) {
case OP_GREATER: ret = (result > 0); break;
case OP_GREATER_EQ: ret = (result >= 0); break;
case OP_LESS: ret = (result < 0); break;
case OP_LESS_EQ: ret = (result <= 0); break;
case OP_EQUAL: ret = (result == 0); break;
case OP_NEQUAL: ret = (result != 0); break;
default: {
fprintf(stderr,"EvalIpaddr: internal error\n");
exit(-1);
}
}
}
/* fill in the answer */
pres->vartype = V_BOOL;
pres->val.bool = ret;
if (debug) {
printf("EvalIpaddr %s %s", HostAddr(*varl), Op2Str(pf->op));
printf("%s returns %s\n", HostAddr(*varr), BOOL2STR(ret));
}
return;
}
/* evaluate a leaf-node string */
static void
EvalRelopString(
tcp_pair *ptp,
struct filter_res *pres,
struct filter_node *pf)
{
char *varl;
char *varr;
struct filter_res res;
Bool ret;
int cmp;
/* grab left hand side */
EvalFilter(ptp,&res,pf->un.binary.left);
varl = res.val.string;
/* grab right hand side */
EvalFilter(ptp,&res,pf->un.binary.right);
varr = res.val.string;
/* compare the strings */
cmp = strcmp(varl,varr);
switch (pf->op) {
case OP_GREATER: ret = (cmp > 0); break;
case OP_GREATER_EQ: ret = (cmp >= 0); break;
case OP_LESS: ret = (cmp < 0); break;
case OP_LESS_EQ: ret = (cmp <= 0); break;
case OP_EQUAL: ret = (cmp == 0); break;
case OP_NEQUAL: ret = (cmp != 0); break;
default: {
fprintf(stderr,"EvalRelopString: unsupported operating %d (%s)\n",
pf->op, Op2Str(pf->op));
exit(-1);
}
}
/* fill in the answer */
pres->vartype = V_BOOL;
pres->val.bool = ret;
if (debug)
printf("EvalString '%s' %s '%s' returns %s\n",
varl, Op2Str(pf->op), varr,
BOOL2STR(ret));
return;
}
static void
EvalVariable(
tcp_pair *ptp,
struct filter_res *pres,
struct filter_node *pf)
{
switch (pf->vartype) {
case V_CHAR:
case V_SHORT:
case V_INT:
case V_LONG:
case V_LLONG:
pres->vartype = V_LLONG;
pres->val.u_longint = Var2Signed(ptp,pf);
break;
case V_UCHAR:
case V_USHORT:
case V_UINT:
case V_ULONG:
case V_ULLONG:
pres->vartype = V_ULLONG;
pres->val.longint = Var2Unsigned(ptp,pf);
break;
case V_STRING:
pres->vartype = V_STRING;
pres->val.string = Var2String(ptp,pf);
break;
case V_BOOL:
pres->vartype = V_BOOL;
pres->val.bool = (Var2Unsigned(ptp,pf) != 0);
break;
case V_IPADDR:
pres->vartype = V_IPADDR;
pres->val.pipaddr = Var2Ipaddr(ptp,pf);
break;
default:
fprintf(stderr,"EvalVariable: unknown var type %d (%s)\n",
pf->vartype, Vartype2Str(pf->vartype));
exit(-1);
}
}
static void
EvalConstant(
tcp_pair *ptp,
struct filter_res *pres,
struct filter_node *pf)
{
switch (pf->vartype) {
case V_CHAR:
case V_SHORT:
case V_INT:
case V_LONG:
case V_LLONG:
pres->vartype = V_LLONG;
pres->val.u_longint = Const2Signed(pf);
break;
case V_UCHAR:
case V_USHORT:
case V_UINT:
case V_ULONG:
case V_ULLONG:
pres->vartype = V_LLONG;
pres->val.longint = Const2Unsigned(pf);
break;
case V_STRING:
pres->vartype = V_STRING;
pres->val.string = pf->un.constant.string;
break;
case V_BOOL:
pres->vartype = V_BOOL;
pres->val.bool = (Var2Unsigned(ptp,pf) != 0);
break;
case V_IPADDR:
pres->vartype = V_IPADDR;
pres->val.pipaddr = Const2Ipaddr(pf);
break;
default:
fprintf(stderr,"EvalConstant: unknown var type %d (%s)\n",
pf->vartype, Vartype2Str(pf->vartype));
}
}
static void
EvalFilter(
tcp_pair *ptp,
struct filter_res *pres,
struct filter_node *pf)
{
struct filter_res res;
if (!pf) {
fprintf(stderr,"EvalFilter called with NULL!!!\n");
exit(-1);
}
/* variables are easy */
if (pf->op == OP_VARIABLE) {
EvalVariable(ptp,pres,pf);
return;
}
/* constants are easy */
if (pf->op == OP_CONSTANT) {
EvalConstant(ptp,pres,pf);
return;
}
switch (pf->op) {
case OP_EQUAL:
case OP_NEQUAL:
case OP_GREATER:
case OP_GREATER_EQ:
case OP_LESS:
case OP_LESS_EQ:
if (pf->un.binary.left->vartype == V_ULLONG) {
EvalRelopUnsigned(ptp,&res,pf);
pres->vartype = V_BOOL;
pres->val.bool = res.val.bool;
} else if (pf->un.binary.left->vartype == V_LLONG) {
EvalRelopSigned(ptp,&res,pf);
pres->vartype = V_BOOL;
pres->val.bool = res.val.bool;
} else if (pf->un.binary.left->vartype == V_STRING) {
EvalRelopString(ptp,&res,pf);
pres->vartype = V_LLONG;
pres->val.longint = res.val.longint;
} else if (pf->un.binary.left->vartype == V_IPADDR) {
EvalRelopIpaddr(ptp,&res,pf);
pres->vartype = V_BOOL;
pres->val.bool = res.val.bool;
} else {
fprintf(stderr,
"EvalFilter: binary op %d (%s) not supported on data type %d (%s)\n",
pf->op, Op2Str(pf->op),
pf->vartype, Vartype2Str(pf->un.binary.left->vartype));
exit(-1);
}
break;
case OP_PLUS:
case OP_MINUS:
case OP_TIMES:
case OP_DIVIDE:
case OP_MOD:
case OP_BAND:
case OP_BOR:
if (pf->un.binary.left->vartype == V_ULLONG) {
EvalMathopUnsigned(ptp,&res,pf);
pres->vartype = V_ULLONG;
pres->val.u_longint = res.val.u_longint;
} else if (pf->un.binary.left->vartype == V_LLONG) {
EvalMathopSigned(ptp,&res,pf);
pres->vartype = V_LLONG;
pres->val.longint = res.val.longint;
} else {
fprintf(stderr,
"EvalFilter: binary op %d (%s) not supported on data type %d (%s)\n",
pf->op, Op2Str(pf->op),
pf->vartype, Vartype2Str(pf->un.binary.left->vartype));
exit(-1);
}
break;
case OP_AND:
case OP_OR:
if (pf->vartype == V_BOOL) {
struct filter_res res1;
struct filter_res res2;
Bool ret;
if (pf->op == OP_OR) {
EvalFilter(ptp,&res1,pf->un.binary.left);
EvalFilter(ptp,&res2,pf->un.binary.right);
ret = res1.val.bool || res2.val.bool;
} else {
EvalFilter(ptp,&res1,pf->un.binary.left);
EvalFilter(ptp,&res2,pf->un.binary.right);
ret = res1.val.bool && res2.val.bool;
}
pres->vartype = V_BOOL;
pres->val.bool = ret;
} else {
fprintf(stderr,
"EvalFilter: binary op %d (%s) not supported on data type %d (%s)\n",
pf->op, Op2Str(pf->op),
pf->vartype, Vartype2Str(pf->un.binary.left->vartype));
exit(-1);
}
break;
case OP_NOT:
if (pf->vartype == V_BOOL) {
EvalFilter(ptp,&res,pf->un.unary.pf);
pres->vartype = V_BOOL;
pres->val.bool = !res.val.bool;
} else {
fprintf(stderr,
"EvalFilter: unary operation %d (%s) not supported on data type %d (%s)\n",
pf->op, Op2Str(pf->op),
pf->vartype, Vartype2Str(pf->vartype));
exit(-1);
}
break;
default:
fprintf(stderr,
"EvalFilter: operation %d (%s) not supported on data type %d (%s)\n",
pf->op,Op2Str(pf->op),
pf->vartype,Vartype2Str(pf->vartype));
exit(-1);
}
if (debug)
printf("EvalFilter('%s') returns %s\n",
Filter2Str(pf),Res2Str(pres));
return;
}
Bool
PassesFilter(
tcp_pair *ptp)
{
struct filter_res res;
Bool ret;
/* recurse down the tree */
EvalFilter(ptp,&res,filter_root);
ret = res.val.bool;
if (debug)
printf("PassesFilter('%s<->%s') returns %s\n",
ptp->a_endpoint, ptp->b_endpoint,
BOOL2STR(ret));
return(ret);
}
static void
HelpFilterVariables(void)
{
int i;
fprintf(stderr,"Filter Variables:\n");
fprintf(stderr," variable name type description\n");
fprintf(stderr," ----------------- -------- -----------------------\n");
for (i=0; i < NUM_FILTERS; ++i) {
struct filter_line *pf = &filters[i];
fprintf(stderr," %-17s %-8s %s\n",
pf->varname, Vartype2BStr(pf->vartype),pf->descr);
}
}
void
HelpFilter(void)
{
HelpFilterVariables();
fprintf(stderr,"\n\
Filter Syntax:\n\
numbers:\n\
variables:\n\
anything from the above table with a prefix of either 'c_' meaning\n\
the one for the Client or 's_' meaning the value for the Server. If\n\
the prefix is omitted, it means \"either one\" (effectively becoming\n\
\"c_VAR OR s_VAR)\"). As shorthand for a conjunction instead, you can\n\
use the syntax 'b_' (as in b_mss>100), meaning 'B'oth, (effectively\n\
becoming \"c_VAR AND s_VAR)\"). For completeness, 'e_' means 'E'ither,\n\
which is the normal default with no prefix.\n\
constant:\n\
strings: anything in double quotes\n\
booleans: TRUE FALSE\n\
numbers: signed or unsigned constants\n\
arithmetic operations: \n\
any of the operators + - * / %% \n\
performed on 'numbers'. Normal operator precedence\n\
is maintained (or use parens)\n\
relational operators\n\
any of < > = != >= <= applied to 'numbers'\n\
boolean operators\n\
AND, OR, NOT applied to the relational operators above\n\
misc\n\
use parens if you're not sure of the precedence\n\
use parens anyway, you might be smarter than I am! :-)\n\
you'll probably need to put the '-fexpr' expression in single quotes\n\
matched connection numbers are saved in file %s for later processing\n\
with '-o%s' (for graphing, for example). This is helpful, because\n\
all the work is done in one pass of the file, so if you graph while\n\
using a filter, you'll get ALL graphs, not just the ones you want.\n\
Just filter on a first pass, then use the \"-oPF\" flag with graphing\n\
on the second pass\n\
most common synonyms for NOT, AND, and OR also work (!,&&,||,-a,-o)\n\
(for those of us with very poor memories\n\
Examples\n\
tcptrace '-fsegs>10' file\n\
tcptrace '-fc_segs>10 OR s_segs>20 ' file\n\
tcptrace '-f c_segs+10 > s_segs ' file\n\
tcptrace -f'thruput>10000 and segs > 100' file\n\
tcptrace '-fb_segs>10' file\n\
", PASS_FILTER_FILENAME, PASS_FILTER_FILENAME);
}
void
InstallFilter(
struct filter_node *root)
{
/* result MUST be boolean */
if (root->vartype != V_BOOL) {
fprintf(stderr,"Filter expression is not boolean: %s\n",
Filter2Str(root));
exit(-1);
}
filter_root = root;
}
int
filter_getc()
{
static char *pinput = NULL;
int ch;
if (pinput == NULL)
pinput = exprstr;
if (*pinput == '\00') {
static int doneyet = 0;
if (++doneyet>1) {
if (debug > 4)
printf("filter_getc() returns EOF\n");
return(EOF);
} else {
if (debug > 4)
printf("filter_getc() returns newline\n");
return('\n');
}
}
ch = *pinput++;
if (debug > 4)
printf("filter_getc() returns char '%c'\n", ch);
return(ch);
}
/**************************************************************/
/**************************************************************/
/** **/
/** The following routines are for calculated values **/
/** **/
/**************************************************************/
/**************************************************************/
static u_llong
VFuncTput(
tcb *ptcb)
{
tcp_pair *ptp = ptcb->ptp;
u_llong tput;
double tput_f;
double etime;
etime = elapsed(ptp->first_time,ptp->last_time);
etime /= 1000000.0; /* convert to seconds */
if (etime == 0.0)
return(0);
tput_f = (double)(ptcb->unique_bytes) / etime;
tput = (u_llong)(tput_f+0.5);
if (debug)
printf("VFuncTput(%s<->%s) = %" FS_ULL "\n",
ptcb->ptp->a_endpoint,
ptcb->ptp->b_endpoint,
tput);
return(tput);
}
u_llong
VFuncClntTput(
tcp_pair *ptp)
{
return(VFuncTput(&ptp->a2b));
}
u_llong
VFuncServTput(
tcp_pair *ptp)
{
return(VFuncTput(&ptp->b2a));
}
| gpl-2.0 |
iegor/kdeedu | kmplot/kmplot/diagr.cpp | 1 | 13212 | /*
* KmPlot - a math. function plotter for the KDE-Desktop
*
* Copyright (C) 1998, 1999 Klaus-Dieter M�ler
* 2000, 2002 kd.moeller@t-online.de
*
* This file is part of the KDE Project.
* KmPlot is part of the KDE-EDU Project.
*
* 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.
*
*/
//local includes
#include "diagr.h"
#include "settings.h"
#ifdef __osf__
#include <nan.h>
#define isnan(x) IsNAN(x)
#define isinf(x) IsINF(X)
#endif
#ifdef USE_SOLARIS
#include <ieeefp.h>
int isinf(double x)
{
return !finite(x) && x==x;
}
#endif
#include <kdebug.h>
CDiagr::CDiagr()
{
frameColor=qRgb(0, 0, 0);
axesColor=qRgb(0, 0, 0);
gridColor=qRgb(192, 192, 192);
borderThickness=2;
axesLineWidth = Settings::axesLineWidth();
gridLineWidth = Settings::gridLineWidth();
ticWidth = Settings::ticWidth();
ticLength = Settings::ticLength();
g_mode = Settings::gridStyle();
ex=ey=1.;
}
CDiagr::~CDiagr()
{}
void CDiagr::Create(QPoint Ref, // Bezugspunkt links unten
int lx, int ly, // Achsenl�gen
double xmin, double xmax, // x-Wertebereich
double ymin, double ymax) // y-Wertebereich
{ int x, y, h, w;
CDiagr::xmin=xmin; // globale Variablen setzen
CDiagr::xmax=xmax;
CDiagr::ymin=ymin;
CDiagr::ymax=ymax;
xmd=xmax+1e-6;
ymd=ymax+1e-6;
tsx=ceil(xmin/ex)*ex;
tsy=ceil(ymin/ey)*ey;
skx=lx/(xmax-xmin); // Skalierungsfaktoren berechnen
sky=ly/(ymax-ymin);
ox=Ref.x()-skx*xmin+0.5; // Ursprungskoordinaten berechnen
oy=Ref.y()+sky*ymax+0.5;
PlotArea.setRect(x=Ref.x(), y=Ref.y(), w=lx, h=ly);
if( Settings::showExtraFrame() )
{
x-=20;
y-=20;
w+=40;
h+=40;
if( Settings::showLabel() && ymin>=0. )
h+=60;
}
m_frame.setRect(x, y, w, h);
}
void CDiagr::Skal( double ex, double ey )
{
CDiagr::ex=ex;
CDiagr::ey=ey;
g_mode = Settings::gridStyle();
tsx=ceil(xmin/ex)*ex;
tsy=ceil(ymin/ey)*ey;
}
void CDiagr::Plot(QPainter* pDC)
{
QPen pen(frameColor, borderThickness);
if( g_mode != GRID_NONE )
drawGrid( pDC ); // draw the grid
drawAxes( pDC ); // draw the axes
if( Settings::showLabel() )
drawLabels(pDC); // Achsen beschriften
if( Settings::showFrame() || Settings::showExtraFrame() )// FRAME zeichnen
{
pDC->setPen(pen);
pDC->drawRect(m_frame);
}
}
int CDiagr::Transx( double x ) // reale x-Koordinate
{
int xi; // transformierte x-Koordinate
static double lastx; // vorherige x-Koordinate
if(isnan(x))
{
xclipflg=1;
if(lastx<1. && lastx>-1.)
xi=(int)(ox-skx*lastx);
else
xi=(lastx<0)? PlotArea.left(): PlotArea.right();
}
else if(isinf(x)==-1)
{
xclipflg=0;
xi=PlotArea.left();
}
else if(isinf(x)==1)
{
xclipflg=0;
xi=PlotArea.right();
}
else if(x<xmin)
{
xclipflg=1;
xi=PlotArea.left();
}
else if(x>xmax)
{
xclipflg=1;
xi=PlotArea.right();
}
else
{
xclipflg=0;
xi=(int)(ox+skx*x);
}
lastx=x;
return xi;
}
int CDiagr::Transy(double y) // reale y-Koordinate
{
int yi; // transformierte y-Koordinate
static double lasty; // vorherige y-Koordinate
if(isnan(y))
{
yclipflg=1;
if(lasty<1. && lasty>-1.)
yi=(int)(oy-sky*lasty);
else
yi=(lasty<0)? PlotArea.bottom(): PlotArea.top();
}
else if(isinf(y)==-1)
{
yclipflg=0;
yi=PlotArea.bottom();
}
else if(isinf(y)==1)
{
yclipflg=0;
yi=PlotArea.top();
}
else if(y<ymin)
{
yclipflg=1;
yi=PlotArea.bottom();
}
else if(y>ymax)
{
yclipflg=1;
yi=PlotArea.top();
}
else
{
yclipflg=0;
yi=(int)(oy-sky*y);
}
lasty=y;
return yi;
}
double CDiagr::Transx(int x) // Bildschirmkoordinate
{ return (x-ox)/skx; // reale x-Koordinate
}
double CDiagr::Transy(int y) // Bildschirmkoordinate
{ return (oy-y)/sky; // reale y-Koordinate
}
void CDiagr::drawAxes( QPainter* pDC ) // draw axes
{ int a, b, tl;
double d, da, db;
if( Settings::showAxes() )
{
pDC->setPen( QPen( axesColor, axesLineWidth ) );
b = Transy(0.);
a = PlotArea.right();
pDC->Lineh(PlotArea.left(), b, a); // x-Achse
if( Settings::showArrows()) // ARROWS
{ int const dx=40;
int const dy=15;
pDC->Line(a, b, a-dx, b+dy);
pDC->Line(a, b, a-dx, b-dy);
}
a = Transx(0.);
b = PlotArea.top();
pDC->Linev(a, PlotArea.bottom(), b); // y-Achse
if( Settings::showArrows() ) // ARROWS
{ int const dx=15;
int const dy=40;
pDC->Line(a, b, a-dx, b+dy);
pDC->Line(a, b, a+dx, b+dy);
}
}
pDC->setPen( QPen( axesColor, ticWidth ) );
if( Settings::showAxes() )
{
da=oy-ticLength;
db=oy+ticLength;
tl= Settings::showFrame()? 0: ticLength;
d=tsx;
if(da<(double)PlotArea.top())
{
a=PlotArea.top()-tl;
b=PlotArea.top()+ticLength;
}
else if(db>(double)PlotArea.bottom())
{
b=PlotArea.bottom()+tl;
a=PlotArea.bottom()-ticLength;
}
else
{
a=(int)da;
b=(int)db;
}
while(d<xmd-ex/2.)
{
pDC->Linev(Transx(d), a, b);
d+=ex;
}
da=ox-ticLength;
db=ox+ticLength;
d=tsy;
if(da<(double)PlotArea.left())
{
a=PlotArea.left()-tl;
b=PlotArea.left()+ticLength;
}
else if(db>(double)PlotArea.right())
{
b=PlotArea.right()+tl;
a=PlotArea.right()-ticLength;
}
else
{
a=(int)da;
b=(int)db;
}
while(d<ymd-ey/2.)
{
pDC->Lineh(a, Transy(d), b);
d+=ey;
}
}
else if( Settings::showFrame() )
{
a=PlotArea.bottom()+ticLength;
b=PlotArea.top()-ticLength;
d=tsx;
while(d<xmd)
{
pDC->Linev(Transx(d), PlotArea.bottom(), a);
pDC->Linev(Transx(d), PlotArea.top(), b);
d+=ex;
}
a=PlotArea.left()+ticLength;
b=PlotArea.right()-ticLength;
d=tsy;
while(d<ymd)
{
pDC->Lineh(PlotArea.left(), Transy(d), a);
pDC->Lineh(PlotArea.right(), Transy(d), b);
d+=ey;
}
}
}
void CDiagr::drawGrid( QPainter* pDC )
{
int a, b;
double d, x, y;
QPen pen( gridColor, gridLineWidth );
pDC->setPen(pen);
if( g_mode==GRID_LINES )
{
d=tsx;
while(d<xmd)
{
pDC->Linev(Transx(d), PlotArea.bottom(), PlotArea.top());
d+=ex;
}
d=tsy;
while(d<ymd)
{
pDC->Lineh(PlotArea.left(), Transy(d), PlotArea.right());
d+=ey;
}
}
else if( g_mode==GRID_CROSSES )
{
int const dx = 5;
int const dy = 5;
for(x=tsx; x<xmd; x+=ex)
{
a=Transx(x);
for(y=tsy; y<ymd; y+=ey)
{
b=Transy(y);
pDC->Lineh(a-dx, b, a+dx);
pDC->Linev(a, b-dy, b+dy);
}
}
}
else if( g_mode==GRID_POLAR )
{
int y2;
double w;
QRect const rc=PlotArea;
pDC->setClipRect(pDC->xForm(rc));
double const c=hypot(xmd*skx, ymd*sky);
int const xm=(int)(c+ox);
int const dr=(int)(skx*ex);
int const d2r=(int)(2.*skx*ex);
int x1=(int)ox-dr;
int y1=(int)oy-dr;
int x2=y2=d2r;
do
{
pDC->drawEllipse(x1, y1, x2, y2);
x1-=dr;
y1-=dr;
x2+=d2r;
y2+=d2r;
}
while(x2<=xm);
x1=(int)ox;
y1=(int)oy;
for(w=0.; w<2.*M_PI; w+=M_PI/12.)
{
x2=(int)(ox+c*cos(w));
y2=(int)(oy+c*sin(w));
pDC->Line(x1, y1, x2, y2);
}
pDC->setClipping(false);
}
}
void CDiagr::drawLabels(QPainter* pDC)
{
int const dx=15;
int const dy=40;
QFont const font=QFont( Settings::axesFont(), Settings::axesFontSize() );
pDC->setFont(font);
int const x=Transx(0.);
int const y=Transy(0.);
double d;
int n;
QString s;
//pDC->drawText(x-dx, y+dy, 0, 0, Qt::AlignRight|Qt::AlignVCenter|Qt::DontClip, "0");
char draw_next=0;
QFontMetrics const test(font);
int swidth=0;
for(d=tsx, n=(int)ceil(xmin/ex); d<xmd; d+=ex, ++n)
{
if(n==0 || fabs(d-xmd)<=1.5*ex)
continue;
if(n<0)
s="-";
else
s="+";
if(fabs(ex-M_PI/2.)<1e-3)
{
if(n==-1 || n==1)
s+="pi/2";//s+=QChar(960)+QString("/2");
else if(n%2 == 0)
{
if(n==-2 || n==2)
s+="pi";//s+=QChar(960);
else
{
s=QString().sprintf("%+d", n/2);
s+="pi";//s+=QChar(960);
}
}
else
continue;
swidth = test.width(s);
if ( Transx(d)-x<swidth && Transx(d)-x>-swidth && draw_next==0)
{
draw_next=1;
continue;
}
if (draw_next>0)
{
if (draw_next==1)
{
draw_next++;
continue;
}
else
draw_next=0;
}
pDC->drawText(Transx(d), y+dy, 0, 0, Qt::AlignCenter|Qt::DontClip, s);
}
else if(fabs(ex-M_PI/3.)<1e-3)
{
if(n==-1 || n==1)
s+="pi/3";//s+=QChar(960)+QString("/3");
else if(n%3==0)
{
if(n==-3 || n==3)
s+="pi";//s+=QChar(960);
else
{
s=QString().sprintf("%+d", n/3);
s+="pi";//s+=QChar(960);
}
}
else
continue;
swidth = test.width(s);
if ( Transx(d)-x<swidth && Transx(d)-x>-swidth && draw_next==0)
{
draw_next=1;
continue;
}
if (draw_next>0)
{
if (draw_next==1)
{
draw_next++;
continue;
}
else
draw_next=0;
}
pDC->drawText(Transx(d), y+dy, 0, 0, Qt::AlignCenter|Qt::DontClip, s);
}
else if(fabs(ex-M_PI/4.)<1e-3)
{
if(n==-1 || n==1)
s+="pi/4";//s+=QChar(960)+QString("/4");
else if(n%4==0)
{
if(n==-4 || n==4)
s+="pi";//s+=QChar(960);
else
{
s=QString().sprintf("%+d", n/4);
s+="pi";//s+=QChar(960);
}
}
else
continue;
swidth = test.width(s);
if ( Transx(d)-x<swidth && Transx(d)-x>-swidth && draw_next==0)
{
draw_next=1;
continue;
}
if (draw_next>0)
{
if (draw_next==1)
{
draw_next++;
continue;
}
else
draw_next=0;
}
pDC->drawText(Transx(d), y+dy, 0, 0, Qt::AlignCenter|Qt::DontClip, s);
}
else if((n%5==0 || n==1 || n==-1 || draw_next))
{
s=QString().sprintf("%+0.3g", n*ex);
swidth = test.width(s);
if ( Transx(d)-x<swidth && Transx(d)-x>-swidth && draw_next==0)
{
draw_next=1;
continue;
}
if (draw_next>0)
{
if (draw_next==1)
{
draw_next++;
continue;
}
else
draw_next=0;
}
pDC->drawText(Transx(d), y+dy, 0, 0, Qt::AlignCenter|Qt::DontClip, s);
}
}
if(ymax<0 && xmax<0)
pDC->drawText(Transx(xmax)-(4*dx), y+(dy-20), 0, 0, Qt::AlignCenter|Qt::DontClip, "x");
else
pDC->drawText(Transx(xmax)-dx, y+dy, 0, 0, Qt::AlignCenter|Qt::DontClip, "x");
for(d=tsy, n=(int)ceil(ymin/ey); d<ymd; d+=ey, ++n)
{
if(n==0 || fabs(d-ymd)<=1.5*ey)
continue;
if(n<0)
s="-";
else
s="+";
if(fabs(ey-M_PI/2.)<1e-3)
{
if(n==-1 || n==1)
s+="pi/2";//s+=QChar(960)+QString("/2");
else if(n%2==0)
{
if(n==-2 || n==2)
s+="pi";//s+=QChar(960);
else
{
s=QString().sprintf("%+d", n/2);
s+="pi";//s+=QChar(960);
}
}
else
continue;
if (xmin>=0)
pDC->drawText(x+dx, Transy(d), 0, 0, Qt::AlignVCenter|Qt::AlignLeft|Qt::DontClip, s);
else
pDC->drawText(x-dx, Transy(d), 0, 0, Qt::AlignVCenter|Qt::AlignRight|Qt::DontClip, s);
}
else if(fabs(ey-M_PI/3.)<1e-3)
{
if(n==-1 || n==1)
s+="pi/3";//s+=QChar(960)+QString("/3");
else if(n%3==0)
{
if(n==-3 || n==3)
s+="pi";//s+=QChar(960);
else
{
s=QString().sprintf("%+d", n/3);
s+="pi";//s+=QChar(960);
}
}
else
continue;
if (xmin>=0)
pDC->drawText(x+dx, Transy(d), 0, 0, Qt::AlignVCenter|Qt::AlignLeft|Qt::DontClip, s);
else
pDC->drawText(x-dx, Transy(d), 0, 0, Qt::AlignVCenter|Qt::AlignRight|Qt::DontClip, s);
}
else if(fabs(ey-M_PI/4.)<1e-3)
{
if(n==-1 || n==1)
s+="pi/4";//s+=QChar(960)+QString("/4");
else if(n%4==0)
{
if(n==-4 || n==4)
s+="pi";//s+=QChar(960);
else
{
s=QString().sprintf("%+d", n/4);
s+="pi";//s+=QChar(960);
}
}
else
continue;
if (xmin>=0)
pDC->drawText(x+dx, Transy(d), 0, 0, Qt::AlignVCenter|Qt::AlignLeft|Qt::DontClip, s);
else
pDC->drawText(x-dx, Transy(d), 0, 0, Qt::AlignVCenter|Qt::AlignRight|Qt::DontClip, s);
}
else if((n%5==0 || n==1 || n==-1))
{
s=QString().sprintf("%+0.3g", n*ey);
if (xmin>=0)
pDC->drawText(x+dx, Transy(d), 0, 0, Qt::AlignVCenter|Qt::AlignLeft|Qt::DontClip, s);
else
pDC->drawText(x-dx, Transy(d), 0, 0, Qt::AlignVCenter|Qt::AlignRight|Qt::DontClip, s);
}
}
if(ymax<0 && xmax<0)
pDC->drawText(x-dx, Transy(ymax)+(2*dy), 0, 0, Qt::AlignVCenter|Qt::AlignRight|Qt::DontClip, "y");
else if (xmin>0)
pDC->drawText(x-(2*dx), Transy(ymax)+dy, 0, 0, Qt::AlignVCenter|Qt::AlignRight|Qt::DontClip, "y");
else
pDC->drawText(x-dx, Transy(ymax)+dy, 0, 0, Qt::AlignVCenter|Qt::AlignRight|Qt::DontClip, "y");
}
| gpl-2.0 |
ut-osa/txos | kernel/sys.c | 1 | 58308 | /*
* linux/kernel/sys.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/utsname.h>
#include <linux/mman.h>
#include <linux/smp_lock.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/prctl.h>
#include <linux/highuid.h>
#include <linux/fs.h>
#include <linux/resource.h>
#include <linux/kernel.h>
#include <linux/kexec.h>
#include <linux/workqueue.h>
#include <linux/capability.h>
#include <linux/device.h>
#include <linux/key.h>
#include <linux/times.h>
#include <linux/posix-timers.h>
#include <linux/security.h>
#include <linux/dcookies.h>
#include <linux/suspend.h>
#include <linux/tty.h>
#include <linux/signal.h>
#include <linux/cn_proc.h>
#include <linux/getcpu.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/compat.h>
#include <linux/syscalls.h>
#include <linux/kprobes.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/unistd.h>
#include <linux/tx_file.h>
#include <linux/transaction.h>
#include <linux/tx_signal.h>
#ifndef SET_UNALIGN_CTL
# define SET_UNALIGN_CTL(a,b) (-EINVAL)
#endif
#ifndef GET_UNALIGN_CTL
# define GET_UNALIGN_CTL(a,b) (-EINVAL)
#endif
#ifndef SET_FPEMU_CTL
# define SET_FPEMU_CTL(a,b) (-EINVAL)
#endif
#ifndef GET_FPEMU_CTL
# define GET_FPEMU_CTL(a,b) (-EINVAL)
#endif
#ifndef SET_FPEXC_CTL
# define SET_FPEXC_CTL(a,b) (-EINVAL)
#endif
#ifndef GET_FPEXC_CTL
# define GET_FPEXC_CTL(a,b) (-EINVAL)
#endif
#ifndef GET_ENDIAN
# define GET_ENDIAN(a,b) (-EINVAL)
#endif
#ifndef SET_ENDIAN
# define SET_ENDIAN(a,b) (-EINVAL)
#endif
/*
* this is where the system-wide overflow UID and GID are defined, for
* architectures that now have 32-bit UID/GID but didn't in the past
*/
int overflowuid = DEFAULT_OVERFLOWUID;
int overflowgid = DEFAULT_OVERFLOWGID;
#ifdef CONFIG_UID16
EXPORT_SYMBOL(overflowuid);
EXPORT_SYMBOL(overflowgid);
#endif
/*
* the same as above, but for filesystems which can only store a 16-bit
* UID and GID. as such, this is needed on all architectures
*/
int fs_overflowuid = DEFAULT_FS_OVERFLOWUID;
int fs_overflowgid = DEFAULT_FS_OVERFLOWUID;
EXPORT_SYMBOL(fs_overflowuid);
EXPORT_SYMBOL(fs_overflowgid);
/*
* this indicates whether you can reboot with ctrl-alt-del: the default is yes
*/
int C_A_D = 1;
struct pid *cad_pid;
EXPORT_SYMBOL(cad_pid);
/*
* Notifier list for kernel code which wants to be called
* at shutdown. This is used to stop any idling DMA operations
* and the like.
*/
static BLOCKING_NOTIFIER_HEAD(reboot_notifier_list);
/*
* Notifier chain core routines. The exported routines below
* are layered on top of these, with appropriate locking added.
*/
static int notifier_chain_register(struct notifier_block **nl,
struct notifier_block *n)
{
while ((*nl) != NULL) {
if (n->priority > (*nl)->priority)
break;
nl = &((*nl)->next);
}
n->next = *nl;
rcu_assign_pointer(*nl, n);
return 0;
}
static int notifier_chain_unregister(struct notifier_block **nl,
struct notifier_block *n)
{
while ((*nl) != NULL) {
if ((*nl) == n) {
rcu_assign_pointer(*nl, n->next);
return 0;
}
nl = &((*nl)->next);
}
return -ENOENT;
}
/**
* notifier_call_chain - Informs the registered notifiers about an event.
* @nl: Pointer to head of the blocking notifier chain
* @val: Value passed unmodified to notifier function
* @v: Pointer passed unmodified to notifier function
* @nr_to_call: Number of notifier functions to be called. Don't care
* value of this parameter is -1.
* @nr_calls: Records the number of notifications sent. Don't care
* value of this field is NULL.
* @returns: notifier_call_chain returns the value returned by the
* last notifier function called.
*/
static int __kprobes notifier_call_chain(struct notifier_block **nl,
unsigned long val, void *v,
int nr_to_call, int *nr_calls)
{
int ret = NOTIFY_DONE;
struct notifier_block *nb, *next_nb;
nb = rcu_dereference(*nl);
while (nb && nr_to_call) {
next_nb = rcu_dereference(nb->next);
ret = nb->notifier_call(nb, val, v);
if (nr_calls)
(*nr_calls)++;
if ((ret & NOTIFY_STOP_MASK) == NOTIFY_STOP_MASK)
break;
nb = next_nb;
nr_to_call--;
}
return ret;
}
/*
* Atomic notifier chain routines. Registration and unregistration
* use a spinlock, and call_chain is synchronized by RCU (no locks).
*/
/**
* atomic_notifier_chain_register - Add notifier to an atomic notifier chain
* @nh: Pointer to head of the atomic notifier chain
* @n: New entry in notifier chain
*
* Adds a notifier to an atomic notifier chain.
*
* Currently always returns zero.
*/
int atomic_notifier_chain_register(struct atomic_notifier_head *nh,
struct notifier_block *n)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&nh->lock, flags);
ret = notifier_chain_register(&nh->head, n);
spin_unlock_irqrestore(&nh->lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(atomic_notifier_chain_register);
/**
* atomic_notifier_chain_unregister - Remove notifier from an atomic notifier chain
* @nh: Pointer to head of the atomic notifier chain
* @n: Entry to remove from notifier chain
*
* Removes a notifier from an atomic notifier chain.
*
* Returns zero on success or %-ENOENT on failure.
*/
int atomic_notifier_chain_unregister(struct atomic_notifier_head *nh,
struct notifier_block *n)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&nh->lock, flags);
ret = notifier_chain_unregister(&nh->head, n);
spin_unlock_irqrestore(&nh->lock, flags);
synchronize_rcu();
return ret;
}
EXPORT_SYMBOL_GPL(atomic_notifier_chain_unregister);
/**
* __atomic_notifier_call_chain - Call functions in an atomic notifier chain
* @nh: Pointer to head of the atomic notifier chain
* @val: Value passed unmodified to notifier function
* @v: Pointer passed unmodified to notifier function
* @nr_to_call: See the comment for notifier_call_chain.
* @nr_calls: See the comment for notifier_call_chain.
*
* Calls each function in a notifier chain in turn. The functions
* run in an atomic context, so they must not block.
* This routine uses RCU to synchronize with changes to the chain.
*
* If the return value of the notifier can be and'ed
* with %NOTIFY_STOP_MASK then atomic_notifier_call_chain()
* will return immediately, with the return value of
* the notifier function which halted execution.
* Otherwise the return value is the return value
* of the last notifier function called.
*/
int __kprobes __atomic_notifier_call_chain(struct atomic_notifier_head *nh,
unsigned long val, void *v,
int nr_to_call, int *nr_calls)
{
int ret;
rcu_read_lock();
ret = notifier_call_chain(&nh->head, val, v, nr_to_call, nr_calls);
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL_GPL(__atomic_notifier_call_chain);
int __kprobes atomic_notifier_call_chain(struct atomic_notifier_head *nh,
unsigned long val, void *v)
{
return __atomic_notifier_call_chain(nh, val, v, -1, NULL);
}
EXPORT_SYMBOL_GPL(atomic_notifier_call_chain);
/*
* Blocking notifier chain routines. All access to the chain is
* synchronized by an rwsem.
*/
/**
* blocking_notifier_chain_register - Add notifier to a blocking notifier chain
* @nh: Pointer to head of the blocking notifier chain
* @n: New entry in notifier chain
*
* Adds a notifier to a blocking notifier chain.
* Must be called in process context.
*
* Currently always returns zero.
*/
int blocking_notifier_chain_register(struct blocking_notifier_head *nh,
struct notifier_block *n)
{
int ret;
/*
* This code gets used during boot-up, when task switching is
* not yet working and interrupts must remain disabled. At
* such times we must not call down_write().
*/
if (unlikely(system_state == SYSTEM_BOOTING))
return notifier_chain_register(&nh->head, n);
down_write(&nh->rwsem);
ret = notifier_chain_register(&nh->head, n);
up_write(&nh->rwsem);
return ret;
}
EXPORT_SYMBOL_GPL(blocking_notifier_chain_register);
/**
* blocking_notifier_chain_unregister - Remove notifier from a blocking notifier chain
* @nh: Pointer to head of the blocking notifier chain
* @n: Entry to remove from notifier chain
*
* Removes a notifier from a blocking notifier chain.
* Must be called from process context.
*
* Returns zero on success or %-ENOENT on failure.
*/
int blocking_notifier_chain_unregister(struct blocking_notifier_head *nh,
struct notifier_block *n)
{
int ret;
/*
* This code gets used during boot-up, when task switching is
* not yet working and interrupts must remain disabled. At
* such times we must not call down_write().
*/
if (unlikely(system_state == SYSTEM_BOOTING))
return notifier_chain_unregister(&nh->head, n);
down_write(&nh->rwsem);
ret = notifier_chain_unregister(&nh->head, n);
up_write(&nh->rwsem);
return ret;
}
EXPORT_SYMBOL_GPL(blocking_notifier_chain_unregister);
/**
* __blocking_notifier_call_chain - Call functions in a blocking notifier chain
* @nh: Pointer to head of the blocking notifier chain
* @val: Value passed unmodified to notifier function
* @v: Pointer passed unmodified to notifier function
* @nr_to_call: See comment for notifier_call_chain.
* @nr_calls: See comment for notifier_call_chain.
*
* Calls each function in a notifier chain in turn. The functions
* run in a process context, so they are allowed to block.
*
* If the return value of the notifier can be and'ed
* with %NOTIFY_STOP_MASK then blocking_notifier_call_chain()
* will return immediately, with the return value of
* the notifier function which halted execution.
* Otherwise the return value is the return value
* of the last notifier function called.
*/
int __blocking_notifier_call_chain(struct blocking_notifier_head *nh,
unsigned long val, void *v,
int nr_to_call, int *nr_calls)
{
int ret = NOTIFY_DONE;
/*
* We check the head outside the lock, but if this access is
* racy then it does not matter what the result of the test
* is, we re-check the list after having taken the lock anyway:
*/
if (rcu_dereference(nh->head)) {
down_read(&nh->rwsem);
ret = notifier_call_chain(&nh->head, val, v, nr_to_call,
nr_calls);
up_read(&nh->rwsem);
}
return ret;
}
EXPORT_SYMBOL_GPL(__blocking_notifier_call_chain);
int blocking_notifier_call_chain(struct blocking_notifier_head *nh,
unsigned long val, void *v)
{
return __blocking_notifier_call_chain(nh, val, v, -1, NULL);
}
EXPORT_SYMBOL_GPL(blocking_notifier_call_chain);
/*
* Raw notifier chain routines. There is no protection;
* the caller must provide it. Use at your own risk!
*/
/**
* raw_notifier_chain_register - Add notifier to a raw notifier chain
* @nh: Pointer to head of the raw notifier chain
* @n: New entry in notifier chain
*
* Adds a notifier to a raw notifier chain.
* All locking must be provided by the caller.
*
* Currently always returns zero.
*/
int raw_notifier_chain_register(struct raw_notifier_head *nh,
struct notifier_block *n)
{
return notifier_chain_register(&nh->head, n);
}
EXPORT_SYMBOL_GPL(raw_notifier_chain_register);
/**
* raw_notifier_chain_unregister - Remove notifier from a raw notifier chain
* @nh: Pointer to head of the raw notifier chain
* @n: Entry to remove from notifier chain
*
* Removes a notifier from a raw notifier chain.
* All locking must be provided by the caller.
*
* Returns zero on success or %-ENOENT on failure.
*/
int raw_notifier_chain_unregister(struct raw_notifier_head *nh,
struct notifier_block *n)
{
return notifier_chain_unregister(&nh->head, n);
}
EXPORT_SYMBOL_GPL(raw_notifier_chain_unregister);
/**
* __raw_notifier_call_chain - Call functions in a raw notifier chain
* @nh: Pointer to head of the raw notifier chain
* @val: Value passed unmodified to notifier function
* @v: Pointer passed unmodified to notifier function
* @nr_to_call: See comment for notifier_call_chain.
* @nr_calls: See comment for notifier_call_chain
*
* Calls each function in a notifier chain in turn. The functions
* run in an undefined context.
* All locking must be provided by the caller.
*
* If the return value of the notifier can be and'ed
* with %NOTIFY_STOP_MASK then raw_notifier_call_chain()
* will return immediately, with the return value of
* the notifier function which halted execution.
* Otherwise the return value is the return value
* of the last notifier function called.
*/
int __raw_notifier_call_chain(struct raw_notifier_head *nh,
unsigned long val, void *v,
int nr_to_call, int *nr_calls)
{
return notifier_call_chain(&nh->head, val, v, nr_to_call, nr_calls);
}
EXPORT_SYMBOL_GPL(__raw_notifier_call_chain);
int raw_notifier_call_chain(struct raw_notifier_head *nh,
unsigned long val, void *v)
{
return __raw_notifier_call_chain(nh, val, v, -1, NULL);
}
EXPORT_SYMBOL_GPL(raw_notifier_call_chain);
/*
* SRCU notifier chain routines. Registration and unregistration
* use a mutex, and call_chain is synchronized by SRCU (no locks).
*/
/**
* srcu_notifier_chain_register - Add notifier to an SRCU notifier chain
* @nh: Pointer to head of the SRCU notifier chain
* @n: New entry in notifier chain
*
* Adds a notifier to an SRCU notifier chain.
* Must be called in process context.
*
* Currently always returns zero.
*/
int srcu_notifier_chain_register(struct srcu_notifier_head *nh,
struct notifier_block *n)
{
int ret;
/*
* This code gets used during boot-up, when task switching is
* not yet working and interrupts must remain disabled. At
* such times we must not call mutex_lock().
*/
if (unlikely(system_state == SYSTEM_BOOTING))
return notifier_chain_register(&nh->head, n);
mutex_lock(&nh->mutex);
ret = notifier_chain_register(&nh->head, n);
mutex_unlock(&nh->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(srcu_notifier_chain_register);
/**
* srcu_notifier_chain_unregister - Remove notifier from an SRCU notifier chain
* @nh: Pointer to head of the SRCU notifier chain
* @n: Entry to remove from notifier chain
*
* Removes a notifier from an SRCU notifier chain.
* Must be called from process context.
*
* Returns zero on success or %-ENOENT on failure.
*/
int srcu_notifier_chain_unregister(struct srcu_notifier_head *nh,
struct notifier_block *n)
{
int ret;
/*
* This code gets used during boot-up, when task switching is
* not yet working and interrupts must remain disabled. At
* such times we must not call mutex_lock().
*/
if (unlikely(system_state == SYSTEM_BOOTING))
return notifier_chain_unregister(&nh->head, n);
mutex_lock(&nh->mutex);
ret = notifier_chain_unregister(&nh->head, n);
mutex_unlock(&nh->mutex);
synchronize_srcu(&nh->srcu);
return ret;
}
EXPORT_SYMBOL_GPL(srcu_notifier_chain_unregister);
/**
* __srcu_notifier_call_chain - Call functions in an SRCU notifier chain
* @nh: Pointer to head of the SRCU notifier chain
* @val: Value passed unmodified to notifier function
* @v: Pointer passed unmodified to notifier function
* @nr_to_call: See comment for notifier_call_chain.
* @nr_calls: See comment for notifier_call_chain
*
* Calls each function in a notifier chain in turn. The functions
* run in a process context, so they are allowed to block.
*
* If the return value of the notifier can be and'ed
* with %NOTIFY_STOP_MASK then srcu_notifier_call_chain()
* will return immediately, with the return value of
* the notifier function which halted execution.
* Otherwise the return value is the return value
* of the last notifier function called.
*/
int __srcu_notifier_call_chain(struct srcu_notifier_head *nh,
unsigned long val, void *v,
int nr_to_call, int *nr_calls)
{
int ret;
int idx;
idx = srcu_read_lock(&nh->srcu);
ret = notifier_call_chain(&nh->head, val, v, nr_to_call, nr_calls);
srcu_read_unlock(&nh->srcu, idx);
return ret;
}
EXPORT_SYMBOL_GPL(__srcu_notifier_call_chain);
int srcu_notifier_call_chain(struct srcu_notifier_head *nh,
unsigned long val, void *v)
{
return __srcu_notifier_call_chain(nh, val, v, -1, NULL);
}
EXPORT_SYMBOL_GPL(srcu_notifier_call_chain);
/**
* srcu_init_notifier_head - Initialize an SRCU notifier head
* @nh: Pointer to head of the srcu notifier chain
*
* Unlike other sorts of notifier heads, SRCU notifier heads require
* dynamic initialization. Be sure to call this routine before
* calling any of the other SRCU notifier routines for this head.
*
* If an SRCU notifier head is deallocated, it must first be cleaned
* up by calling srcu_cleanup_notifier_head(). Otherwise the head's
* per-cpu data (used by the SRCU mechanism) will leak.
*/
void srcu_init_notifier_head(struct srcu_notifier_head *nh)
{
mutex_init(&nh->mutex);
if (init_srcu_struct(&nh->srcu) < 0)
BUG();
nh->head = NULL;
}
EXPORT_SYMBOL_GPL(srcu_init_notifier_head);
/**
* register_reboot_notifier - Register function to be called at reboot time
* @nb: Info about notifier function to be called
*
* Registers a function with the list of functions
* to be called at reboot time.
*
* Currently always returns zero, as blocking_notifier_chain_register()
* always returns zero.
*/
int register_reboot_notifier(struct notifier_block * nb)
{
return blocking_notifier_chain_register(&reboot_notifier_list, nb);
}
EXPORT_SYMBOL(register_reboot_notifier);
/**
* unregister_reboot_notifier - Unregister previously registered reboot notifier
* @nb: Hook to be unregistered
*
* Unregisters a previously registered reboot
* notifier function.
*
* Returns zero on success, or %-ENOENT on failure.
*/
int unregister_reboot_notifier(struct notifier_block * nb)
{
return blocking_notifier_chain_unregister(&reboot_notifier_list, nb);
}
EXPORT_SYMBOL(unregister_reboot_notifier);
static int set_one_prio(struct task_struct *p, int niceval, int error)
{
int no_nice;
if (p->uid != current->euid &&
p->euid != current->euid && !capable(CAP_SYS_NICE)) {
error = -EPERM;
goto out;
}
if (niceval < task_nice(p) && !can_nice(p, niceval)) {
error = -EACCES;
goto out;
}
no_nice = security_task_setnice(p, niceval);
if (no_nice) {
error = no_nice;
goto out;
}
if (error == -ESRCH)
error = 0;
set_user_nice(p, niceval);
out:
return error;
}
asmlinkage long sys_setpriority(int which, int who, int niceval)
{
struct task_struct *g, *p;
struct user_struct *user;
int error = -EINVAL;
struct pid *pgrp;
if (which > PRIO_USER || which < PRIO_PROCESS)
goto out;
/* normalize: avoid signed division (rounding problems) */
error = -ESRCH;
if (niceval < -20)
niceval = -20;
if (niceval > 19)
niceval = 19;
read_lock(&tasklist_lock);
switch (which) {
case PRIO_PROCESS:
if (who)
p = find_task_by_pid(who);
else
p = current;
if (p)
error = set_one_prio(p, niceval, error);
break;
case PRIO_PGRP:
if (who)
pgrp = find_pid(who);
else
pgrp = task_pgrp(current);
do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
error = set_one_prio(p, niceval, error);
} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
break;
case PRIO_USER:
user = current->user;
if (!who)
who = current->uid;
else
if ((who != current->uid) && !(user = find_user(who)))
goto out_unlock; /* No processes for this user */
do_each_thread(g, p)
if (p->uid == who)
error = set_one_prio(p, niceval, error);
while_each_thread(g, p);
if (who != current->uid)
free_uid(user); /* For find_user() */
break;
}
out_unlock:
read_unlock(&tasklist_lock);
out:
return error;
}
/*
* Ugh. To avoid negative return values, "getpriority()" will
* not return the normal nice-value, but a negated value that
* has been offset by 20 (ie it returns 40..1 instead of -20..19)
* to stay compatible.
*/
asmlinkage long sys_getpriority(int which, int who)
{
struct task_struct *g, *p;
struct user_struct *user;
long niceval, retval = -ESRCH;
struct pid *pgrp;
if (which > PRIO_USER || which < PRIO_PROCESS)
return -EINVAL;
read_lock(&tasklist_lock);
switch (which) {
case PRIO_PROCESS:
if (who)
p = find_task_by_pid(who);
else
p = current;
if (p) {
niceval = 20 - task_nice(p);
if (niceval > retval)
retval = niceval;
}
break;
case PRIO_PGRP:
if (who)
pgrp = find_pid(who);
else
pgrp = task_pgrp(current);
do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
niceval = 20 - task_nice(p);
if (niceval > retval)
retval = niceval;
} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
break;
case PRIO_USER:
user = current->user;
if (!who)
who = current->uid;
else
if ((who != current->uid) && !(user = find_user(who)))
goto out_unlock; /* No processes for this user */
do_each_thread(g, p)
if (p->uid == who) {
niceval = 20 - task_nice(p);
if (niceval > retval)
retval = niceval;
}
while_each_thread(g, p);
if (who != current->uid)
free_uid(user); /* for find_user() */
break;
}
out_unlock:
read_unlock(&tasklist_lock);
return retval;
}
/**
* emergency_restart - reboot the system
*
* Without shutting down any hardware or taking any locks
* reboot the system. This is called when we know we are in
* trouble so this is our best effort to reboot. This is
* safe to call in interrupt context.
*/
void emergency_restart(void)
{
machine_emergency_restart();
}
EXPORT_SYMBOL_GPL(emergency_restart);
static void kernel_restart_prepare(char *cmd)
{
blocking_notifier_call_chain(&reboot_notifier_list, SYS_RESTART, cmd);
system_state = SYSTEM_RESTART;
device_shutdown();
}
/**
* kernel_restart - reboot the system
* @cmd: pointer to buffer containing command to execute for restart
* or %NULL
*
* Shutdown everything and perform a clean reboot.
* This is not safe to call in interrupt context.
*/
void kernel_restart(char *cmd)
{
kernel_restart_prepare(cmd);
if (!cmd)
printk(KERN_EMERG "Restarting system.\n");
else
printk(KERN_EMERG "Restarting system with command '%s'.\n", cmd);
machine_restart(cmd);
}
EXPORT_SYMBOL_GPL(kernel_restart);
/**
* kernel_kexec - reboot the system
*
* Move into place and start executing a preloaded standalone
* executable. If nothing was preloaded return an error.
*/
static void kernel_kexec(void)
{
#ifdef CONFIG_KEXEC
struct kimage *image;
image = xchg(&kexec_image, NULL);
if (!image)
return;
kernel_restart_prepare(NULL);
printk(KERN_EMERG "Starting new kernel\n");
machine_shutdown();
machine_kexec(image);
#endif
}
void kernel_shutdown_prepare(enum system_states state)
{
blocking_notifier_call_chain(&reboot_notifier_list,
(state == SYSTEM_HALT)?SYS_HALT:SYS_POWER_OFF, NULL);
system_state = state;
device_shutdown();
}
/**
* kernel_halt - halt the system
*
* Shutdown everything and perform a clean system halt.
*/
void kernel_halt(void)
{
kernel_shutdown_prepare(SYSTEM_HALT);
printk(KERN_EMERG "System halted.\n");
machine_halt();
}
EXPORT_SYMBOL_GPL(kernel_halt);
/**
* kernel_power_off - power_off the system
*
* Shutdown everything and perform a clean system power_off.
*/
void kernel_power_off(void)
{
kernel_shutdown_prepare(SYSTEM_POWER_OFF);
printk(KERN_EMERG "Power down.\n");
machine_power_off();
}
EXPORT_SYMBOL_GPL(kernel_power_off);
/*
* Reboot system call: for obvious reasons only root may call it,
* and even root needs to set up some magic numbers in the registers
* so that some mistake won't make this reboot the whole machine.
* You can also set the meaning of the ctrl-alt-del-key here.
*
* reboot doesn't sync: do that yourself before calling this.
*/
asmlinkage long sys_reboot(int magic1, int magic2, unsigned int cmd, void __user * arg)
{
char buffer[256];
/* We only trust the superuser with rebooting the system. */
if (!capable(CAP_SYS_BOOT))
return -EPERM;
/* For safety, we require "magic" arguments. */
if (magic1 != LINUX_REBOOT_MAGIC1 ||
(magic2 != LINUX_REBOOT_MAGIC2 &&
magic2 != LINUX_REBOOT_MAGIC2A &&
magic2 != LINUX_REBOOT_MAGIC2B &&
magic2 != LINUX_REBOOT_MAGIC2C))
return -EINVAL;
/* Instead of trying to make the power_off code look like
* halt when pm_power_off is not set do it the easy way.
*/
if ((cmd == LINUX_REBOOT_CMD_POWER_OFF) && !pm_power_off)
cmd = LINUX_REBOOT_CMD_HALT;
lock_kernel();
switch (cmd) {
case LINUX_REBOOT_CMD_RESTART:
kernel_restart(NULL);
break;
case LINUX_REBOOT_CMD_CAD_ON:
C_A_D = 1;
break;
case LINUX_REBOOT_CMD_CAD_OFF:
C_A_D = 0;
break;
case LINUX_REBOOT_CMD_HALT:
kernel_halt();
unlock_kernel();
do_exit(0);
break;
case LINUX_REBOOT_CMD_POWER_OFF:
kernel_power_off();
unlock_kernel();
do_exit(0);
break;
case LINUX_REBOOT_CMD_RESTART2:
if (strncpy_from_user(&buffer[0], arg, sizeof(buffer) - 1) < 0) {
unlock_kernel();
return -EFAULT;
}
buffer[sizeof(buffer) - 1] = '\0';
kernel_restart(buffer);
break;
case LINUX_REBOOT_CMD_KEXEC:
kernel_kexec();
unlock_kernel();
return -EINVAL;
#ifdef CONFIG_SOFTWARE_SUSPEND
case LINUX_REBOOT_CMD_SW_SUSPEND:
{
int ret = hibernate();
unlock_kernel();
return ret;
}
#endif
default:
unlock_kernel();
return -EINVAL;
}
unlock_kernel();
return 0;
}
static void deferred_cad(struct work_struct *dummy)
{
kernel_restart(NULL);
}
/*
* This function gets called by ctrl-alt-del - ie the keyboard interrupt.
* As it's called within an interrupt, it may NOT sync: the only choice
* is whether to reboot at once, or just ignore the ctrl-alt-del.
*/
void ctrl_alt_del(void)
{
static DECLARE_WORK(cad_work, deferred_cad);
if (C_A_D)
schedule_work(&cad_work);
else
kill_cad_pid(SIGINT, 1);
}
/*
* Unprivileged users may change the real gid to the effective gid
* or vice versa. (BSD-style)
*
* If you set the real gid at all, or set the effective gid to a value not
* equal to the real gid, then the saved gid is set to the new effective gid.
*
* This makes it possible for a setgid program to completely drop its
* privileges, which is often a useful assertion to make when you are doing
* a security audit over a program.
*
* The general idea is that a program which uses just setregid() will be
* 100% compatible with BSD. A program which uses just setgid() will be
* 100% compatible with POSIX with saved IDs.
*
* SMP: There are not races, the GIDs are checked only by filesystem
* operations (as far as semantic preservation is concerned).
*/
asmlinkage long sys_setregid(gid_t rgid, gid_t egid)
{
int old_rgid = current->gid;
int old_egid = current->egid;
int new_rgid = old_rgid;
int new_egid = old_egid;
int retval;
retval = security_task_setgid(rgid, egid, (gid_t)-1, LSM_SETID_RE);
if (retval)
return retval;
if (rgid != (gid_t) -1) {
if ((old_rgid == rgid) ||
(current->egid==rgid) ||
capable(CAP_SETGID))
new_rgid = rgid;
else
return -EPERM;
}
if (egid != (gid_t) -1) {
if ((old_rgid == egid) ||
(current->egid == egid) ||
(current->sgid == egid) ||
capable(CAP_SETGID))
new_egid = egid;
else
return -EPERM;
}
if (new_egid != old_egid) {
current->mm->dumpable = suid_dumpable;
smp_wmb();
}
tx_chkpt_task_fields(current);
if (rgid != (gid_t) -1 ||
(egid != (gid_t) -1 && egid != old_rgid)) {
current->sgid = new_egid;
}
current->fsgid = new_egid;
current->egid = new_egid;
current->gid = new_rgid;
if (!active_transaction()) {
//handled during commit to assure atomicity
key_fsgid_changed(current);
proc_id_connector(current, PROC_EVENT_GID);
}
return 0;
}
/*
* setgid() is implemented like SysV w/ SAVED_IDS
*
* SMP: Same implicit races as above.
*/
asmlinkage long sys_setgid(gid_t gid)
{
int old_egid = current->egid;
int retval;
retval = security_task_setgid(gid, (gid_t)-1, (gid_t)-1, LSM_SETID_ID);
if (retval)
return retval;
tx_chkpt_task_fields(current);
if (capable(CAP_SETGID)) {
if (old_egid != gid) {
current->mm->dumpable = suid_dumpable;
smp_wmb();
}
current->gid = current->egid = current->sgid = current->fsgid = gid;
} else if ((gid == current->gid) || (gid == current->sgid)) {
if (old_egid != gid) {
current->mm->dumpable = suid_dumpable;
smp_wmb();
}
current->egid = current->fsgid = gid;
}
else
return -EPERM;
if (!active_transaction()) {
key_fsgid_changed(current);
proc_id_connector(current, PROC_EVENT_GID);
}
return 0;
}
static int set_user(uid_t new_ruid, int dumpclear)
{
struct user_struct *new_user;
new_user = alloc_uid(new_ruid);
if (!new_user)
return -EAGAIN;
if (atomic_read(&new_user->processes) >=
current->signal->rlim[RLIMIT_NPROC].rlim_cur &&
new_user != &root_user) {
free_uid(new_user);
return -EAGAIN;
}
switch_uid(new_user);
if (dumpclear) {
current->mm->dumpable = suid_dumpable;
smp_wmb();
}
tx_chkpt_task_fields(current);
current->uid = new_ruid;
return 0;
}
/*
* Unprivileged users may change the real uid to the effective uid
* or vice versa. (BSD-style)
*
* If you set the real uid at all, or set the effective uid to a value not
* equal to the real uid, then the saved uid is set to the new effective uid.
*
* This makes it possible for a setuid program to completely drop its
* privileges, which is often a useful assertion to make when you are doing
* a security audit over a program.
*
* The general idea is that a program which uses just setreuid() will be
* 100% compatible with BSD. A program which uses just setuid() will be
* 100% compatible with POSIX with saved IDs.
*/
asmlinkage long sys_setreuid(uid_t ruid, uid_t euid)
{
int old_ruid, old_euid, old_suid, new_ruid, new_euid;
int retval;
retval = security_task_setuid(ruid, euid, (uid_t)-1, LSM_SETID_RE);
if (retval)
return retval;
new_ruid = old_ruid = current->uid;
new_euid = old_euid = current->euid;
old_suid = current->suid;
if (ruid != (uid_t) -1) {
new_ruid = ruid;
if ((old_ruid != ruid) &&
(current->euid != ruid) &&
!capable(CAP_SETUID))
return -EPERM;
}
if (euid != (uid_t) -1) {
new_euid = euid;
if ((old_ruid != euid) &&
(current->euid != euid) &&
(current->suid != euid) &&
!capable(CAP_SETUID))
return -EPERM;
}
if (new_ruid != old_ruid && set_user(new_ruid, new_euid != old_euid) < 0)
return -EAGAIN;
if (new_euid != old_euid) {
current->mm->dumpable = suid_dumpable;
smp_wmb();
}
tx_chkpt_task_fields(current);
current->fsuid = current->euid = new_euid;
if (ruid != (uid_t) -1 ||
(euid != (uid_t) -1 && euid != old_ruid)) {
current->suid = current->euid;
}
current->fsuid = current->euid;
if (!active_transaction()) {
key_fsuid_changed(current);
proc_id_connector(current, PROC_EVENT_UID);
}
return security_task_post_setuid(old_ruid, old_euid, old_suid, LSM_SETID_RE);
}
/*
* setuid() is implemented like SysV with SAVED_IDS
*
* Note that SAVED_ID's is deficient in that a setuid root program
* like sendmail, for example, cannot set its uid to be a normal
* user and then switch back, because if you're root, setuid() sets
* the saved uid too. If you don't like this, blame the bright people
* in the POSIX committee and/or USG. Note that the BSD-style setreuid()
* will allow a root program to temporarily drop privileges and be able to
* regain them by swapping the real and effective uid.
*/
asmlinkage long sys_setuid(uid_t uid)
{
int old_euid = current->euid;
int old_ruid, old_suid, new_suid;
int retval;
retval = security_task_setuid(uid, (uid_t)-1, (uid_t)-1, LSM_SETID_ID);
if (retval)
return retval;
old_ruid = current->uid;
old_suid = current->suid;
new_suid = old_suid;
if (capable(CAP_SETUID)) {
if (uid != old_ruid && set_user(uid, old_euid != uid) < 0)
return -EAGAIN;
new_suid = uid;
} else if ((uid != current->uid) && (uid != new_suid))
return -EPERM;
if (old_euid != uid) {
current->mm->dumpable = suid_dumpable;
smp_wmb();
}
tx_chkpt_task_fields(current);
current->fsuid = current->euid = uid;
current->suid = new_suid;
if (!active_transaction()) {
key_fsuid_changed(current);
proc_id_connector(current, PROC_EVENT_UID);
}
return security_task_post_setuid(old_ruid, old_euid, old_suid, LSM_SETID_ID);
}
/*
* This function implements a generic ability to update ruid, euid,
* and suid. This allows you to implement the 4.4 compatible seteuid().
*/
asmlinkage long sys_setresuid(uid_t ruid, uid_t euid, uid_t suid)
{
int old_ruid = current->uid;
int old_euid = current->euid;
int old_suid = current->suid;
int retval;
retval = security_task_setuid(ruid, euid, suid, LSM_SETID_RES);
if (retval)
return retval;
if (!capable(CAP_SETUID)) {
if ((ruid != (uid_t) -1) && (ruid != current->uid) &&
(ruid != current->euid) && (ruid != current->suid))
return -EPERM;
if ((euid != (uid_t) -1) && (euid != current->uid) &&
(euid != current->euid) && (euid != current->suid))
return -EPERM;
if ((suid != (uid_t) -1) && (suid != current->uid) &&
(suid != current->euid) && (suid != current->suid))
return -EPERM;
}
if (ruid != (uid_t) -1) {
if (ruid != current->uid && set_user(ruid, euid != current->euid) < 0)
return -EAGAIN;
}
tx_chkpt_task_fields(current);
if (euid != (uid_t) -1) {
if (euid != current->euid) {
current->mm->dumpable = suid_dumpable;
smp_wmb();
}
current->euid = euid;
}
current->fsuid = current->euid;
if (suid != (uid_t) -1) {
current->suid = suid;
}
if (!active_transaction()) {
key_fsuid_changed(current);
proc_id_connector(current, PROC_EVENT_UID);
}
return security_task_post_setuid(old_ruid, old_euid, old_suid, LSM_SETID_RES);
}
asmlinkage long sys_getresuid(uid_t __user *ruid, uid_t __user *euid, uid_t __user *suid)
{
int retval;
if (!(retval = put_user(current->uid, ruid)) &&
!(retval = put_user(current->euid, euid)))
retval = put_user(current->suid, suid);
return retval;
}
/*
* Same as above, but for rgid, egid, sgid.
*/
asmlinkage long sys_setresgid(gid_t rgid, gid_t egid, gid_t sgid)
{
int retval;
retval = security_task_setgid(rgid, egid, sgid, LSM_SETID_RES);
if (retval)
return retval;
if (!capable(CAP_SETGID)) {
if ((rgid != (gid_t) -1) && (rgid != current->gid) &&
(rgid != current->egid) && (rgid != current->sgid))
return -EPERM;
if ((egid != (gid_t) -1) && (egid != current->gid) &&
(egid != current->egid) && (egid != current->sgid))
return -EPERM;
if ((sgid != (gid_t) -1) && (sgid != current->gid) &&
(sgid != current->egid) && (sgid != current->sgid))
return -EPERM;
}
tx_chkpt_task_fields(current);
if (egid != (gid_t) -1) {
if (egid != current->egid) {
current->mm->dumpable = suid_dumpable;
smp_wmb();
}
current->egid = egid;
}
current->fsgid = current->egid;
if (rgid != (gid_t) -1)
current->gid = rgid;
if (sgid != (gid_t) -1)
current->sgid = sgid;
if (!active_transaction()) {
key_fsgid_changed(current);
proc_id_connector(current, PROC_EVENT_GID);
}
return 0;
}
asmlinkage long sys_getresgid(gid_t __user *rgid, gid_t __user *egid, gid_t __user *sgid)
{
int retval;
if (!(retval = put_user(current->gid, rgid)) &&
!(retval = put_user(current->egid, egid)))
retval = put_user(current->sgid, sgid);
return retval;
}
/*
* "setfsuid()" sets the fsuid - the uid used for filesystem checks. This
* is used for "access()" and for the NFS daemon (letting nfsd stay at
* whatever uid it wants to). It normally shadows "euid", except when
* explicitly set by setfsuid() or for access..
*/
asmlinkage long sys_setfsuid(uid_t uid)
{
int old_fsuid;
old_fsuid = current->fsuid;
if (security_task_setuid(uid, (uid_t)-1, (uid_t)-1, LSM_SETID_FS))
return old_fsuid;
tx_chkpt_task_fields(current);
if (uid == current->uid || uid == current->euid ||
uid == current->suid || uid == current->fsuid ||
capable(CAP_SETUID)) {
if (uid != old_fsuid) {
current->mm->dumpable = suid_dumpable;
smp_wmb();
}
current->fsuid = uid;
}
if (!active_transaction()) {
key_fsuid_changed(current);
proc_id_connector(current, PROC_EVENT_UID);
}
security_task_post_setuid(old_fsuid, (uid_t)-1, (uid_t)-1, LSM_SETID_FS);
return old_fsuid;
}
/*
* Samma pay (???) svenska..
*/
asmlinkage long sys_setfsgid(gid_t gid)
{
int old_fsgid;
old_fsgid = current->fsgid;
if (security_task_setgid(gid, (gid_t)-1, (gid_t)-1, LSM_SETID_FS))
return old_fsgid;
if (gid == current->gid || gid == current->egid ||
gid == current->sgid || gid == current->fsgid ||
capable(CAP_SETGID)) {
if (gid != old_fsgid) {
current->mm->dumpable = suid_dumpable;
smp_wmb();
}
tx_chkpt_task_fields(current);
current->fsgid = gid;
if (!active_transaction()) {
key_fsgid_changed(current);
proc_id_connector(current, PROC_EVENT_GID);
}
}
return old_fsgid;
}
asmlinkage long sys_times(struct tms __user * tbuf)
{
/*
* In the SMP world we might just be unlucky and have one of
* the times increment as we use it. Since the value is an
* atomically safe type this is just fine. Conceptually its
* as if the syscall took an instant longer to occur.
*/
if (tbuf) {
struct tms tmp;
struct task_struct *tsk = current;
struct task_struct *t;
cputime_t utime, stime, cutime, cstime;
spin_lock_irq(&tsk->sighand->siglock);
utime = tsk->signal->utime;
stime = tsk->signal->stime;
t = tsk;
do {
utime = cputime_add(utime, t->utime);
stime = cputime_add(stime, t->stime);
t = next_thread(t);
} while (t != tsk);
cutime = tsk->signal->cutime;
cstime = tsk->signal->cstime;
spin_unlock_irq(&tsk->sighand->siglock);
tmp.tms_utime = cputime_to_clock_t(utime);
tmp.tms_stime = cputime_to_clock_t(stime);
tmp.tms_cutime = cputime_to_clock_t(cutime);
tmp.tms_cstime = cputime_to_clock_t(cstime);
if (copy_to_user(tbuf, &tmp, sizeof(struct tms)))
return -EFAULT;
}
return (long) jiffies_64_to_clock_t(get_jiffies_64());
}
/*
* This needs some heavy checking ...
* I just haven't the stomach for it. I also don't fully
* understand sessions/pgrp etc. Let somebody who does explain it.
*
* OK, I think I have the protection semantics right.... this is really
* only important on a multi-user system anyway, to make sure one user
* can't send a signal to a process owned by another. -TYT, 12/12/91
*
* Auch. Had to add the 'did_exec' flag to conform completely to POSIX.
* LBT 04.03.94
*/
asmlinkage long sys_setpgid(pid_t pid, pid_t pgid)
{
struct task_struct *p;
struct task_struct *group_leader = current->group_leader;
int err = -EINVAL;
if (!pid)
pid = group_leader->pid;
if (!pgid)
pgid = pid;
if (pgid < 0)
return -EINVAL;
/* From this point forward we keep holding onto the tasklist lock
* so that our parent does not change from under us. -DaveM
*/
write_lock_irq(&tasklist_lock);
err = -ESRCH;
p = find_task_by_pid(pid);
if (!p)
goto out;
err = -EINVAL;
if (!thread_group_leader(p))
goto out;
if (p->real_parent == group_leader) {
err = -EPERM;
if (task_session(p) != task_session(group_leader))
goto out;
err = -EACCES;
if (p->did_exec)
goto out;
} else {
err = -ESRCH;
if (p != group_leader)
goto out;
}
err = -EPERM;
if (p->signal->leader)
goto out;
if (pgid != pid) {
struct task_struct *g =
find_task_by_pid_type(PIDTYPE_PGID, pgid);
if (!g || task_session(g) != task_session(group_leader))
goto out;
}
err = security_task_setpgid(p, pgid);
if (err)
goto out;
if (process_group(p) != pgid) {
detach_pid(p, PIDTYPE_PGID);
p->signal->pgrp = pgid;
attach_pid(p, PIDTYPE_PGID, find_pid(pgid));
}
err = 0;
out:
/* All paths lead to here, thus we are safe. -DaveM */
write_unlock_irq(&tasklist_lock);
return err;
}
asmlinkage long sys_getpgid(pid_t pid)
{
if (!pid)
return process_group(current);
else {
int retval;
struct task_struct *p;
read_lock(&tasklist_lock);
p = find_task_by_pid(pid);
retval = -ESRCH;
if (p) {
retval = security_task_getpgid(p);
if (!retval)
retval = process_group(p);
}
read_unlock(&tasklist_lock);
return retval;
}
}
#ifdef __ARCH_WANT_SYS_GETPGRP
asmlinkage long sys_getpgrp(void)
{
/* SMP - assuming writes are word atomic this is fine */
return process_group(current);
}
#endif
asmlinkage long sys_getsid(pid_t pid)
{
if (!pid)
return process_session(current);
else {
int retval;
struct task_struct *p;
read_lock(&tasklist_lock);
p = find_task_by_pid(pid);
retval = -ESRCH;
if (p) {
retval = security_task_getsid(p);
if (!retval)
retval = process_session(p);
}
read_unlock(&tasklist_lock);
return retval;
}
}
asmlinkage long sys_setsid(void)
{
struct task_struct *group_leader = current->group_leader;
pid_t session;
int err = -EPERM;
write_lock_irq(&tasklist_lock);
/* Fail if I am already a session leader */
if (group_leader->signal->leader)
goto out;
session = group_leader->pid;
/* Fail if a process group id already exists that equals the
* proposed session id.
*
* Don't check if session id == 1 because kernel threads use this
* session id and so the check will always fail and make it so
* init cannot successfully call setsid.
*/
if (session > 1 && find_task_by_pid_type(PIDTYPE_PGID, session))
goto out;
group_leader->signal->leader = 1;
__set_special_pids(session, session);
spin_lock(&group_leader->sighand->siglock);
group_leader->signal->tty = NULL;
spin_unlock(&group_leader->sighand->siglock);
err = process_group(group_leader);
out:
write_unlock_irq(&tasklist_lock);
return err;
}
/*
* Supplementary group IDs
*/
/* init to 2 - one for init_task, one to ensure it is never freed */
struct group_info init_groups = { .usage = ATOMIC_INIT(2) };
struct group_info *groups_alloc(int gidsetsize)
{
struct group_info *group_info;
int nblocks;
int i;
nblocks = (gidsetsize + NGROUPS_PER_BLOCK - 1) / NGROUPS_PER_BLOCK;
/* Make sure we always allocate at least one indirect block pointer */
nblocks = nblocks ? : 1;
group_info = kmalloc(sizeof(*group_info) + nblocks*sizeof(gid_t *), GFP_USER);
if (!group_info)
return NULL;
group_info->ngroups = gidsetsize;
group_info->nblocks = nblocks;
atomic_set(&group_info->usage, 1);
if (gidsetsize <= NGROUPS_SMALL)
group_info->blocks[0] = group_info->small_block;
else {
for (i = 0; i < nblocks; i++) {
gid_t *b;
b = (void *)__get_free_page(GFP_USER);
if (!b)
goto out_undo_partial_alloc;
group_info->blocks[i] = b;
}
}
return group_info;
out_undo_partial_alloc:
while (--i >= 0) {
free_page((unsigned long)group_info->blocks[i]);
}
kfree(group_info);
return NULL;
}
EXPORT_SYMBOL(groups_alloc);
void groups_free(struct group_info *group_info)
{
if (group_info->blocks[0] != group_info->small_block) {
int i;
for (i = 0; i < group_info->nblocks; i++)
free_page((unsigned long)group_info->blocks[i]);
}
kfree(group_info);
}
EXPORT_SYMBOL(groups_free);
/* export the group_info to a user-space array */
static int groups_to_user(gid_t __user *grouplist,
struct group_info *group_info)
{
int i;
int count = group_info->ngroups;
for (i = 0; i < group_info->nblocks; i++) {
int cp_count = min(NGROUPS_PER_BLOCK, count);
int off = i * NGROUPS_PER_BLOCK;
int len = cp_count * sizeof(*grouplist);
if (copy_to_user(grouplist+off, group_info->blocks[i], len))
return -EFAULT;
count -= cp_count;
}
return 0;
}
/* fill a group_info from a user-space array - it must be allocated already */
static int groups_from_user(struct group_info *group_info,
gid_t __user *grouplist)
{
int i;
int count = group_info->ngroups;
for (i = 0; i < group_info->nblocks; i++) {
int cp_count = min(NGROUPS_PER_BLOCK, count);
int off = i * NGROUPS_PER_BLOCK;
int len = cp_count * sizeof(*grouplist);
if (copy_from_user(group_info->blocks[i], grouplist+off, len))
return -EFAULT;
count -= cp_count;
}
return 0;
}
/* a simple Shell sort */
static void groups_sort(struct group_info *group_info)
{
int base, max, stride;
int gidsetsize = group_info->ngroups;
for (stride = 1; stride < gidsetsize; stride = 3 * stride + 1)
; /* nothing */
stride /= 3;
while (stride) {
max = gidsetsize - stride;
for (base = 0; base < max; base++) {
int left = base;
int right = left + stride;
gid_t tmp = GROUP_AT(group_info, right);
while (left >= 0 && GROUP_AT(group_info, left) > tmp) {
GROUP_AT(group_info, right) =
GROUP_AT(group_info, left);
right = left;
left -= stride;
}
GROUP_AT(group_info, right) = tmp;
}
stride /= 3;
}
}
/* a simple bsearch */
int groups_search(struct group_info *group_info, gid_t grp)
{
unsigned int left, right;
if (!group_info)
return 0;
left = 0;
right = group_info->ngroups;
while (left < right) {
unsigned int mid = (left+right)/2;
int cmp = grp - GROUP_AT(group_info, mid);
if (cmp > 0)
left = mid + 1;
else if (cmp < 0)
right = mid;
else
return 1;
}
return 0;
}
/* validate and set current->group_info */
int set_current_groups(struct group_info *group_info)
{
int retval;
struct group_info *old_info;
retval = security_task_setgroups(group_info);
if (retval)
return retval;
groups_sort(group_info);
get_group_info(group_info);
task_lock(current);
old_info = current->group_info;
current->group_info = group_info;
task_unlock(current);
put_group_info(old_info);
return 0;
}
EXPORT_SYMBOL(set_current_groups);
asmlinkage long sys_getgroups(int gidsetsize, gid_t __user *grouplist)
{
int i = 0;
/*
* SMP: Nobody else can change our grouplist. Thus we are
* safe.
*/
if (gidsetsize < 0)
return -EINVAL;
/* no need to grab task_lock here; it cannot change */
i = current->group_info->ngroups;
if (gidsetsize) {
if (i > gidsetsize) {
i = -EINVAL;
goto out;
}
if (groups_to_user(grouplist, current->group_info)) {
i = -EFAULT;
goto out;
}
}
out:
return i;
}
/*
* SMP: Our groups are copy-on-write. We can set them safely
* without another task interfering.
*/
asmlinkage long sys_setgroups(int gidsetsize, gid_t __user *grouplist)
{
struct group_info *group_info;
int retval;
if (!capable(CAP_SETGID))
return -EPERM;
if ((unsigned)gidsetsize > NGROUPS_MAX)
return -EINVAL;
group_info = groups_alloc(gidsetsize);
if (!group_info)
return -ENOMEM;
retval = groups_from_user(group_info, grouplist);
if (retval) {
put_group_info(group_info);
return retval;
}
retval = set_current_groups(group_info);
put_group_info(group_info);
return retval;
}
/*
* Check whether we're fsgid/egid or in the supplemental group..
*/
int in_group_p(gid_t grp)
{
int retval = 1;
if (grp != current->fsgid)
retval = groups_search(current->group_info, grp);
return retval;
}
EXPORT_SYMBOL(in_group_p);
int in_egroup_p(gid_t grp)
{
int retval = 1;
if (grp != current->egid)
retval = groups_search(current->group_info, grp);
return retval;
}
EXPORT_SYMBOL(in_egroup_p);
DECLARE_RWSEM(uts_sem);
EXPORT_SYMBOL(uts_sem);
asmlinkage long sys_newuname(struct new_utsname __user * name)
{
int errno = 0;
down_read(&uts_sem);
if (copy_to_user(name, utsname(), sizeof *name))
errno = -EFAULT;
up_read(&uts_sem);
return errno;
}
asmlinkage long sys_sethostname(char __user *name, int len)
{
int errno;
char tmp[__NEW_UTS_LEN];
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (len < 0 || len > __NEW_UTS_LEN)
return -EINVAL;
down_write(&uts_sem);
errno = -EFAULT;
if (!copy_from_user(tmp, name, len)) {
memcpy(utsname()->nodename, tmp, len);
utsname()->nodename[len] = 0;
errno = 0;
}
up_write(&uts_sem);
return errno;
}
#ifdef __ARCH_WANT_SYS_GETHOSTNAME
asmlinkage long sys_gethostname(char __user *name, int len)
{
int i, errno;
if (len < 0)
return -EINVAL;
down_read(&uts_sem);
i = 1 + strlen(utsname()->nodename);
if (i > len)
i = len;
errno = 0;
if (copy_to_user(name, utsname()->nodename, i))
errno = -EFAULT;
up_read(&uts_sem);
return errno;
}
#endif
/*
* Only setdomainname; getdomainname can be implemented by calling
* uname()
*/
asmlinkage long sys_setdomainname(char __user *name, int len)
{
int errno;
char tmp[__NEW_UTS_LEN];
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (len < 0 || len > __NEW_UTS_LEN)
return -EINVAL;
down_write(&uts_sem);
errno = -EFAULT;
if (!copy_from_user(tmp, name, len)) {
memcpy(utsname()->domainname, tmp, len);
utsname()->domainname[len] = 0;
errno = 0;
}
up_write(&uts_sem);
return errno;
}
asmlinkage long sys_getrlimit(unsigned int resource, struct rlimit __user *rlim)
{
if (resource >= RLIM_NLIMITS)
return -EINVAL;
else {
struct rlimit value;
task_lock(current->group_leader);
value = current->signal->rlim[resource];
task_unlock(current->group_leader);
return copy_to_user(rlim, &value, sizeof(*rlim)) ? -EFAULT : 0;
}
}
#ifdef __ARCH_WANT_SYS_OLD_GETRLIMIT
/*
* Back compatibility for getrlimit. Needed for some apps.
*/
asmlinkage long sys_old_getrlimit(unsigned int resource, struct rlimit __user *rlim)
{
struct rlimit x;
if (resource >= RLIM_NLIMITS)
return -EINVAL;
task_lock(current->group_leader);
x = current->signal->rlim[resource];
task_unlock(current->group_leader);
if (x.rlim_cur > 0x7FFFFFFF)
x.rlim_cur = 0x7FFFFFFF;
if (x.rlim_max > 0x7FFFFFFF)
x.rlim_max = 0x7FFFFFFF;
return copy_to_user(rlim, &x, sizeof(x))?-EFAULT:0;
}
#endif
asmlinkage long sys_setrlimit(unsigned int resource, struct rlimit __user *rlim)
{
struct rlimit new_rlim, *old_rlim;
unsigned long it_prof_secs;
int retval;
BUG_ON(active_transaction() && atomic_read(¤t->signal->count) > 1);
if (resource >= RLIM_NLIMITS)
return -EINVAL;
if (copy_from_user(&new_rlim, rlim, sizeof(*rlim)))
return -EFAULT;
if (new_rlim.rlim_cur > new_rlim.rlim_max)
return -EINVAL;
tx_chkpt_signal(current);
old_rlim = current->signal->rlim + resource;
if ((new_rlim.rlim_max > old_rlim->rlim_max) &&
!capable(CAP_SYS_RESOURCE))
return -EPERM;
if (resource == RLIMIT_NOFILE && new_rlim.rlim_max > NR_OPEN)
return -EPERM;
retval = security_task_setrlimit(resource, &new_rlim);
if (retval)
return retval;
if (resource == RLIMIT_CPU && new_rlim.rlim_cur == 0) {
/*
* The caller is asking for an immediate RLIMIT_CPU
* expiry. But we use the zero value to mean "it was
* never set". So let's cheat and make it one second
* instead
*/
new_rlim.rlim_cur = 1;
}
task_lock(current->group_leader);
*old_rlim = new_rlim;
task_unlock(current->group_leader);
if (resource != RLIMIT_CPU)
goto out;
/*
* RLIMIT_CPU handling. Note that the kernel fails to return an error
* code if it rejected the user's attempt to set RLIMIT_CPU. This is a
* very long-standing error, and fixing it now risks breakage of
* applications, so we live with it
*/
if (new_rlim.rlim_cur == RLIM_INFINITY)
goto out;
it_prof_secs = cputime_to_secs(current->signal->it_prof_expires);
if (it_prof_secs == 0 || new_rlim.rlim_cur <= it_prof_secs) {
unsigned long rlim_cur = new_rlim.rlim_cur;
cputime_t cputime;
cputime = secs_to_cputime(rlim_cur);
read_lock(&tasklist_lock);
spin_lock_irq(¤t->sighand->siglock);
set_process_cpu_timer(current, CPUCLOCK_PROF, &cputime, NULL);
spin_unlock_irq(¤t->sighand->siglock);
read_unlock(&tasklist_lock);
}
out:
return 0;
}
/*
* It would make sense to put struct rusage in the task_struct,
* except that would make the task_struct be *really big*. After
* task_struct gets moved into malloc'ed memory, it would
* make sense to do this. It will make moving the rest of the information
* a lot simpler! (Which we're not doing right now because we're not
* measuring them yet).
*
* When sampling multiple threads for RUSAGE_SELF, under SMP we might have
* races with threads incrementing their own counters. But since word
* reads are atomic, we either get new values or old values and we don't
* care which for the sums. We always take the siglock to protect reading
* the c* fields from p->signal from races with exit.c updating those
* fields when reaping, so a sample either gets all the additions of a
* given child after it's reaped, or none so this sample is before reaping.
*
* Locking:
* We need to take the siglock for CHILDEREN, SELF and BOTH
* for the cases current multithreaded, non-current single threaded
* non-current multithreaded. Thread traversal is now safe with
* the siglock held.
* Strictly speaking, we donot need to take the siglock if we are current and
* single threaded, as no one else can take our signal_struct away, no one
* else can reap the children to update signal->c* counters, and no one else
* can race with the signal-> fields. If we do not take any lock, the
* signal-> fields could be read out of order while another thread was just
* exiting. So we should place a read memory barrier when we avoid the lock.
* On the writer side, write memory barrier is implied in __exit_signal
* as __exit_signal releases the siglock spinlock after updating the signal->
* fields. But we don't do this yet to keep things simple.
*
*/
static void k_getrusage(struct task_struct *p, int who, struct rusage *r)
{
struct task_struct *t;
unsigned long flags;
cputime_t utime, stime;
memset((char *) r, 0, sizeof *r);
utime = stime = cputime_zero;
rcu_read_lock();
if (!lock_task_sighand(p, &flags)) {
rcu_read_unlock();
return;
}
switch (who) {
case RUSAGE_BOTH:
case RUSAGE_CHILDREN:
utime = p->signal->cutime;
stime = p->signal->cstime;
r->ru_nvcsw = p->signal->cnvcsw;
r->ru_nivcsw = p->signal->cnivcsw;
r->ru_minflt = p->signal->cmin_flt;
r->ru_majflt = p->signal->cmaj_flt;
r->ru_inblock = p->signal->cinblock;
r->ru_oublock = p->signal->coublock;
if (who == RUSAGE_CHILDREN)
break;
case RUSAGE_SELF:
utime = cputime_add(utime, p->signal->utime);
stime = cputime_add(stime, p->signal->stime);
r->ru_nvcsw += p->signal->nvcsw;
r->ru_nivcsw += p->signal->nivcsw;
r->ru_minflt += p->signal->min_flt;
r->ru_majflt += p->signal->maj_flt;
r->ru_inblock += p->signal->inblock;
r->ru_oublock += p->signal->oublock;
t = p;
do {
utime = cputime_add(utime, t->utime);
stime = cputime_add(stime, t->stime);
r->ru_nvcsw += t->nvcsw;
r->ru_nivcsw += t->nivcsw;
r->ru_minflt += t->min_flt;
r->ru_majflt += t->maj_flt;
r->ru_inblock += task_io_get_inblock(t);
r->ru_oublock += task_io_get_oublock(t);
t = next_thread(t);
} while (t != p);
break;
default:
BUG();
}
unlock_task_sighand(p, &flags);
rcu_read_unlock();
cputime_to_timeval(utime, &r->ru_utime);
cputime_to_timeval(stime, &r->ru_stime);
}
int getrusage(struct task_struct *p, int who, struct rusage __user *ru)
{
struct rusage r;
k_getrusage(p, who, &r);
return copy_to_user(ru, &r, sizeof(r)) ? -EFAULT : 0;
}
asmlinkage long sys_getrusage(int who, struct rusage __user *ru)
{
if (who != RUSAGE_SELF && who != RUSAGE_CHILDREN)
return -EINVAL;
return getrusage(current, who, ru);
}
asmlinkage long sys_umask(int mask)
{
struct fs_struct *fs = tx_cache_get_fs(current);
mask = xchg(&fs->umask, mask & S_IRWXUGO);
return mask;
}
asmlinkage long sys_prctl(int option, unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5)
{
long error;
error = security_task_prctl(option, arg2, arg3, arg4, arg5);
if (error)
return error;
switch (option) {
case PR_SET_PDEATHSIG:
if (!valid_signal(arg2)) {
error = -EINVAL;
break;
}
current->pdeath_signal = arg2;
break;
case PR_GET_PDEATHSIG:
error = put_user(current->pdeath_signal, (int __user *)arg2);
break;
case PR_GET_DUMPABLE:
error = current->mm->dumpable;
break;
case PR_SET_DUMPABLE:
if (arg2 < 0 || arg2 > 1) {
error = -EINVAL;
break;
}
current->mm->dumpable = arg2;
break;
case PR_SET_UNALIGN:
error = SET_UNALIGN_CTL(current, arg2);
break;
case PR_GET_UNALIGN:
error = GET_UNALIGN_CTL(current, arg2);
break;
case PR_SET_FPEMU:
error = SET_FPEMU_CTL(current, arg2);
break;
case PR_GET_FPEMU:
error = GET_FPEMU_CTL(current, arg2);
break;
case PR_SET_FPEXC:
error = SET_FPEXC_CTL(current, arg2);
break;
case PR_GET_FPEXC:
error = GET_FPEXC_CTL(current, arg2);
break;
case PR_GET_TIMING:
error = PR_TIMING_STATISTICAL;
break;
case PR_SET_TIMING:
if (arg2 == PR_TIMING_STATISTICAL)
error = 0;
else
error = -EINVAL;
break;
case PR_GET_KEEPCAPS:
if (current->keep_capabilities)
error = 1;
break;
case PR_SET_KEEPCAPS:
if (arg2 != 0 && arg2 != 1) {
error = -EINVAL;
break;
}
current->keep_capabilities = arg2;
break;
case PR_SET_NAME: {
struct task_struct *me = current;
unsigned char ncomm[sizeof(me->comm)];
ncomm[sizeof(me->comm)-1] = 0;
if (strncpy_from_user(ncomm, (char __user *)arg2,
sizeof(me->comm)-1) < 0)
return -EFAULT;
set_task_comm(me, ncomm);
return 0;
}
case PR_GET_NAME: {
struct task_struct *me = current;
unsigned char tcomm[sizeof(me->comm)];
get_task_comm(tcomm, me);
if (copy_to_user((char __user *)arg2, tcomm, sizeof(tcomm)))
return -EFAULT;
return 0;
}
case PR_GET_ENDIAN:
error = GET_ENDIAN(current, arg2);
break;
case PR_SET_ENDIAN:
error = SET_ENDIAN(current, arg2);
break;
default:
error = -EINVAL;
break;
}
return error;
}
asmlinkage long sys_getcpu(unsigned __user *cpup, unsigned __user *nodep,
struct getcpu_cache __user *cache)
{
int err = 0;
int cpu = raw_smp_processor_id();
if (cpup)
err |= put_user(cpu, cpup);
if (nodep)
err |= put_user(cpu_to_node(cpu), nodep);
if (cache) {
/*
* The cache is not needed for this implementation,
* but make sure user programs pass something
* valid. vsyscall implementations can instead make
* good use of the cache. Only use t0 and t1 because
* these are available in both 32bit and 64bit ABI (no
* need for a compat_getcpu). 32bit has enough
* padding
*/
unsigned long t0, t1;
get_user(t0, &cache->blob[0]);
get_user(t1, &cache->blob[1]);
t0++;
t1++;
put_user(t0, &cache->blob[0]);
put_user(t1, &cache->blob[1]);
}
return err ? -EFAULT : 0;
}
| gpl-2.0 |
luofei98/qgis | src/core/composer/qgsdoubleboxscalebarstyle.cpp | 1 | 3044 | /***************************************************************************
qgsdoubleboxscalebarstyle.cpp
-----------------------------
begin : June 2008
copyright : (C) 2008 by Marco Hugentobler
email : marco.hugentobler@karto.baug.ethz.ch
***************************************************************************/
/***************************************************************************
* *
* 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 "qgsdoubleboxscalebarstyle.h"
#include "qgscomposerscalebar.h"
#include "qgscomposerutils.h"
#include <QList>
#include <QPainter>
QgsDoubleBoxScaleBarStyle::QgsDoubleBoxScaleBarStyle( const QgsComposerScaleBar* bar ): QgsScaleBarStyle( bar )
{
}
QgsDoubleBoxScaleBarStyle::QgsDoubleBoxScaleBarStyle(): QgsScaleBarStyle( 0 )
{
}
QgsDoubleBoxScaleBarStyle::~QgsDoubleBoxScaleBarStyle()
{
}
QString QgsDoubleBoxScaleBarStyle::name() const
{
return "Double Box";
}
void QgsDoubleBoxScaleBarStyle::draw( QPainter* p, double xOffset ) const
{
if ( !mScaleBar )
{
return;
}
double barTopPosition = QgsComposerUtils::fontAscentMM( mScaleBar->font() ) + mScaleBar->labelBarSpace() + mScaleBar->boxContentSpace();
double segmentHeight = mScaleBar->height() / 2;
p->save();
//antialiasing on
p->setRenderHint( QPainter::Antialiasing, true );
p->setPen( mScaleBar->pen() );
QList<QPair<double, double> > segmentInfo;
mScaleBar->segmentPositions( segmentInfo );
bool useColor = true; //alternate brush color/white
QList<QPair<double, double> >::const_iterator segmentIt = segmentInfo.constBegin();
for ( ; segmentIt != segmentInfo.constEnd(); ++segmentIt )
{
//draw top half
if ( useColor )
{
p->setBrush( mScaleBar->brush() );
}
else //secondary color
{
p->setBrush( mScaleBar->brush2() );
}
QRectF segmentRectTop( segmentIt->first + xOffset, barTopPosition, segmentIt->second, segmentHeight );
p->drawRect( segmentRectTop );
//draw bottom half
if ( useColor )
{
//secondary color
p->setBrush( mScaleBar->brush2() );
}
else //primary color
{
p->setBrush( mScaleBar->brush() );
}
QRectF segmentRectBottom( segmentIt->first + xOffset, barTopPosition + segmentHeight, segmentIt->second, segmentHeight );
p->drawRect( segmentRectBottom );
useColor = !useColor;
}
p->restore();
//draw labels using the default method
drawLabels( p );
}
| gpl-2.0 |
unrealircd/unrealircd | src/modules/authprompt.c | 1 | 13139 | /*
* Auth prompt: SASL authentication for clients that don't support SASL
* (C) Copyright 2018 Bram Matthys ("Syzop") and the UnrealIRCd team
*
* 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 1, 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 "unrealircd.h"
ModuleHeader MOD_HEADER
= {
"authprompt",
"1.0",
"SASL authentication for clients that don't support SASL",
"UnrealIRCd Team",
"unrealircd-6",
};
/** Configuration settings */
struct {
int enabled;
MultiLine *message;
MultiLine *fail_message;
MultiLine *unconfirmed_message;
} cfg;
/** User struct */
typedef struct APUser APUser;
struct APUser {
char *authmsg;
};
/* Global variables */
ModDataInfo *authprompt_md = NULL;
/* Forward declarations */
static void free_config(void);
static void init_config(void);
static void config_postdefaults(void);
int authprompt_config_test(ConfigFile *, ConfigEntry *, int, int *);
int authprompt_config_run(ConfigFile *, ConfigEntry *, int);
int authprompt_sasl_continuation(Client *client, const char *buf);
int authprompt_sasl_result(Client *client, int success);
int authprompt_place_host_ban(Client *client, int action, const char *reason, long duration);
int authprompt_find_tkline_match(Client *client, TKL *tk);
int authprompt_pre_connect(Client *client);
CMD_FUNC(cmd_auth);
void authprompt_md_free(ModData *md);
/* Some macros */
#define SetAPUser(x, y) do { moddata_client(x, authprompt_md).ptr = y; } while(0)
#define SEUSER(x) ((APUser *)moddata_client(x, authprompt_md).ptr)
#define AGENT_SID(agent_p) (agent_p->user != NULL ? agent_p->user->server : agent_p->name)
MOD_TEST()
{
HookAdd(modinfo->handle, HOOKTYPE_CONFIGTEST, 0, authprompt_config_test);
return MOD_SUCCESS;
}
MOD_INIT()
{
ModDataInfo mreq;
MARK_AS_OFFICIAL_MODULE(modinfo);
memset(&mreq, 0, sizeof(mreq));
mreq.name = "authprompt";
mreq.type = MODDATATYPE_CLIENT;
mreq.free = authprompt_md_free;
authprompt_md = ModDataAdd(modinfo->handle, mreq);
if (!authprompt_md)
{
config_error("could not register authprompt moddata");
return MOD_FAILED;
}
init_config();
HookAdd(modinfo->handle, HOOKTYPE_CONFIGRUN, 0, authprompt_config_run);
HookAdd(modinfo->handle, HOOKTYPE_SASL_CONTINUATION, 0, authprompt_sasl_continuation);
HookAdd(modinfo->handle, HOOKTYPE_SASL_RESULT, 0, authprompt_sasl_result);
HookAdd(modinfo->handle, HOOKTYPE_PLACE_HOST_BAN, 0, authprompt_place_host_ban);
HookAdd(modinfo->handle, HOOKTYPE_FIND_TKLINE_MATCH, 0, authprompt_find_tkline_match);
/* For HOOKTYPE_PRE_LOCAL_CONNECT we want a low priority, so we are called last.
* This gives hooks like the one from the blacklist module (pending softban)
* a chance to be handled first.
*/
HookAdd(modinfo->handle, HOOKTYPE_PRE_LOCAL_CONNECT, -1000000, authprompt_pre_connect);
CommandAdd(modinfo->handle, "AUTH", cmd_auth, 1, CMD_UNREGISTERED);
return MOD_SUCCESS;
}
MOD_LOAD()
{
config_postdefaults();
return MOD_SUCCESS;
}
MOD_UNLOAD()
{
free_config();
return MOD_SUCCESS;
}
static void init_config(void)
{
/* This sets some default values */
memset(&cfg, 0, sizeof(cfg));
cfg.enabled = 0;
}
static void config_postdefaults(void)
{
if (!cfg.message)
{
addmultiline(&cfg.message, "The server requires clients from this IP address to authenticate with a registered nickname and password.");
addmultiline(&cfg.message, "Please reconnect using SASL, or authenticate now by typing: /QUOTE AUTH nick:password");
}
if (!cfg.fail_message)
{
addmultiline(&cfg.fail_message, "Authentication failed.");
}
if (!cfg.unconfirmed_message)
{
addmultiline(&cfg.unconfirmed_message, "You are trying to use an unconfirmed services account.");
addmultiline(&cfg.unconfirmed_message, "This services account can only be used after it has been activated/confirmed.");
}
}
static void free_config(void)
{
freemultiline(cfg.message);
freemultiline(cfg.fail_message);
freemultiline(cfg.unconfirmed_message);
memset(&cfg, 0, sizeof(cfg)); /* needed! */
}
int authprompt_config_test(ConfigFile *cf, ConfigEntry *ce, int type, int *errs)
{
int errors = 0;
ConfigEntry *cep;
if (type != CONFIG_SET)
return 0;
/* We are only interrested in set::authentication-prompt... */
if (!ce || !ce->name || strcmp(ce->name, "authentication-prompt"))
return 0;
for (cep = ce->items; cep; cep = cep->next)
{
if (!cep->value)
{
config_error("%s:%i: set::authentication-prompt::%s with no value",
cep->file->filename, cep->line_number, cep->name);
errors++;
} else
if (!strcmp(cep->name, "enabled"))
{
} else
if (!strcmp(cep->name, "message"))
{
} else
if (!strcmp(cep->name, "fail-message"))
{
} else
if (!strcmp(cep->name, "unconfirmed-message"))
{
} else
{
config_error("%s:%i: unknown directive set::authentication-prompt::%s",
cep->file->filename, cep->line_number, cep->name);
errors++;
}
}
*errs = errors;
return errors ? -1 : 1;
}
int authprompt_config_run(ConfigFile *cf, ConfigEntry *ce, int type)
{
ConfigEntry *cep;
if (type != CONFIG_SET)
return 0;
/* We are only interrested in set::authentication-prompt... */
if (!ce || !ce->name || strcmp(ce->name, "authentication-prompt"))
return 0;
for (cep = ce->items; cep; cep = cep->next)
{
if (!strcmp(cep->name, "enabled"))
{
cfg.enabled = config_checkval(cep->value, CFG_YESNO);
} else
if (!strcmp(cep->name, "message"))
{
addmultiline(&cfg.message, cep->value);
} else
if (!strcmp(cep->name, "fail-message"))
{
addmultiline(&cfg.fail_message, cep->value);
} else
if (!strcmp(cep->name, "unconfirmed-message"))
{
addmultiline(&cfg.unconfirmed_message, cep->value);
}
}
return 1;
}
void authprompt_md_free(ModData *md)
{
APUser *se = md->ptr;
if (se)
{
safe_free(se->authmsg);
safe_free(se);
md->ptr = se = NULL;
}
}
/** Parse an authentication request from the user (form: <user>:<pass>).
* @param str The input string with the request.
* @param username Pointer to the username string.
* @param password Pointer to the password string.
* @retval 1 if the format is correct, 0 if not.
* @note The returned 'username' and 'password' are valid until next call to parse_nickpass().
*/
int parse_nickpass(const char *str, char **username, char **password)
{
static char buf[250];
char *p;
strlcpy(buf, str, sizeof(buf));
p = strchr(buf, ':');
if (!p)
return 0;
*p++ = '\0';
*username = buf;
*password = p;
if (!*username[0] || !*password[0])
return 0;
return 1;
}
char *make_authbuf(const char *username, const char *password)
{
char inbuf[256];
static char outbuf[512];
int size;
size = strlen(username) + 1 + strlen(username) + 1 + strlen(password);
if (size >= sizeof(inbuf)-1)
return NULL; /* too long */
/* Because size limits are already checked above, we can cut some corners here: */
memset(inbuf, 0, sizeof(inbuf));
strcpy(inbuf, username);
strcpy(inbuf+strlen(username)+1, username);
strcpy(inbuf+strlen(username)+1+strlen(username)+1, password);
/* ^ normal people use stpcpy here ;) */
if (b64_encode(inbuf, size, outbuf, sizeof(outbuf)) < 0)
return NULL; /* base64 encoding error */
return outbuf;
}
/** Send first SASL authentication request (AUTHENTICATE PLAIN).
* Among other things, this is used to discover the agent
* which will later be used for this session.
*/
void send_first_auth(Client *client)
{
Client *sasl_server;
char *addr = BadPtr(client->ip) ? "0" : client->ip;
const char *certfp = moddata_client_get(client, "certfp");
sasl_server = find_client(SASL_SERVER, NULL);
if (!sasl_server)
{
/* Services down. */
return;
}
sendto_one(sasl_server, NULL, ":%s SASL %s %s H %s %s",
me.id, SASL_SERVER, client->id, addr, addr);
if (certfp)
sendto_one(sasl_server, NULL, ":%s SASL %s %s S %s %s",
me.id, SASL_SERVER, client->id, "PLAIN", certfp);
else
sendto_one(sasl_server, NULL, ":%s SASL %s %s S %s",
me.id, SASL_SERVER, client->id, "PLAIN");
/* The rest is sent from authprompt_sasl_continuation() */
client->local->sasl_out++;
}
CMD_FUNC(cmd_auth)
{
char *username = NULL;
char *password = NULL;
char *authbuf;
if (!SEUSER(client))
{
if (HasCapability(client, "sasl"))
sendnotice(client, "ERROR: Cannot use /AUTH when your client is doing SASL.");
else
sendnotice(client, "ERROR: /AUTH authentication request received before authentication prompt (too early!)");
return;
}
if ((parc < 2) || BadPtr(parv[1]) || !parse_nickpass(parv[1], &username, &password))
{
sendnotice(client, "ERROR: Syntax is: /AUTH <nickname>:<password>");
sendnotice(client, "Example: /AUTH mynick:secretpass");
return;
}
if (!SASL_SERVER)
{
sendnotice(client, "ERROR: SASL is not configured on this server, or services are down.");
// numeric instead? SERVICESDOWN?
return;
}
/* Presumably if the user is really fast, this could happen.. */
if (*client->local->sasl_agent || SEUSER(client)->authmsg)
{
sendnotice(client, "ERROR: Previous authentication request is still in progress. Please wait.");
return;
}
authbuf = make_authbuf(username, password);
if (!authbuf)
{
sendnotice(client, "ERROR: Internal error. Oversized username/password?");
return;
}
safe_strdup(SEUSER(client)->authmsg, authbuf);
send_first_auth(client);
}
void authprompt_tag_as_auth_required(Client *client)
{
/* Allocate, and therefore indicate, that we are going to handle SASL for this user */
if (!SEUSER(client))
SetAPUser(client, safe_alloc(sizeof(APUser)));
}
void authprompt_send_auth_required_message(Client *client)
{
/* Display set::authentication-prompt::message */
sendnotice_multiline(client, cfg.message);
}
/* Called upon "place a host ban on this user" (eg: spamfilter, blacklist, ..) */
int authprompt_place_host_ban(Client *client, int action, const char *reason, long duration)
{
/* If it's a soft-xx action and the user is not logged in
* and the user is not yet online, then we will handle this user.
*/
if (IsSoftBanAction(action) && !IsLoggedIn(client) && !IsUser(client))
{
/* Send ban reason */
if (reason)
sendnotice(client, "%s", reason);
/* And tag the user */
authprompt_tag_as_auth_required(client);
authprompt_send_auth_required_message(client);
return 1; /* pretend user is killed */
}
return 99; /* no action taken, proceed normally */
}
/** Called upon "check for KLINE/GLINE" */
int authprompt_find_tkline_match(Client *client, TKL *tkl)
{
/* If it's a soft-xx action and the user is not logged in
* and the user is not yet online, then we will handle this user.
*/
if (TKLIsServerBan(tkl) &&
(tkl->ptr.serverban->subtype & TKL_SUBTYPE_SOFT) &&
!IsLoggedIn(client) &&
!IsUser(client))
{
/* Send ban reason */
if (tkl->ptr.serverban->reason)
sendnotice(client, "%s", tkl->ptr.serverban->reason);
/* And tag the user */
authprompt_tag_as_auth_required(client);
authprompt_send_auth_required_message(client);
return 1; /* pretend user is killed */
}
return 99; /* no action taken, proceed normally */
}
int authprompt_pre_connect(Client *client)
{
/* If the user is tagged as auth required and not logged in, then.. */
if (SEUSER(client) && !IsLoggedIn(client))
{
authprompt_send_auth_required_message(client);
return HOOK_DENY; /* do not process register_user() */
}
return HOOK_CONTINUE; /* no action taken, proceed normally */
}
int authprompt_sasl_continuation(Client *client, const char *buf)
{
/* If it's not for us (eg: user is doing real SASL) then return 0. */
if (!SEUSER(client) || !SEUSER(client)->authmsg)
return 0;
if (!strcmp(buf, "+"))
{
Client *agent = find_client(client->local->sasl_agent, NULL);
if (agent)
{
sendto_one(agent, NULL, ":%s SASL %s %s C %s",
me.id, AGENT_SID(agent), client->id, SEUSER(client)->authmsg);
}
safe_free(SEUSER(client)->authmsg);
}
return 1; /* inhibit displaying of message */
}
int authprompt_sasl_result(Client *client, int success)
{
/* If it's not for us (eg: user is doing real SASL) then return 0. */
if (!SEUSER(client))
return 0;
if (!success)
{
sendnotice_multiline(client, cfg.fail_message);
return 1;
}
if (client->user && !IsLoggedIn(client))
{
sendnotice_multiline(client, cfg.unconfirmed_message);
return 1;
}
/* Authentication was a success */
if (*client->name && client->user && *client->user->username && IsNotSpoof(client))
{
register_user(client);
/* User MAY be killed now. But since we 'return 1' below, it's safe */
}
return 1; /* inhibit success/failure message */
}
| gpl-2.0 |
d4rkfly3r/Last-Stand-Engine | Source/main.cpp | 1 | 3227 | /*/-----------------------------------------------------------------------------------------------------------------/*/
/*/ /*/
/*/ ______________________________________ /*/
/*/ ________| |_______ /*/
/*/ \ | This file is a part of the | / /*/
/*/ \ | Last Stand Studio Game Engine | / /*/
/*/ / |______________________________________| \ /*/
/*/ /__________) (_________\ /*/
/*/ /*/
/*/ Copyright Last Stand Studio 2015 /*/
/*/ /*/
/*/ The Last Stand Gaming Engine 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 3 of the License, or /*/
/*/ (at your option) any later version. /*/
/*/ /*/
/*/ The Last Stand Gaming Engine is distributed in the hope that it will be useful, /*/
/*/ but WITHOUT ANY WARRANTY; without even the implied warranty of /*/
/*/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /*/
/*/ GNU General Public License for more details. /*/
/*/ /*/
/*/ You should have received a copy of the GNU General Public License /*/
/*/ along with The Last Stand Gaming Engine. If not, see <http://www.gnu.org/licenses/>. /*/
/*/ /*/
/*/ /*/
/*/-----------------------------------------------------------------------------------------------------------------/*/
#include "main.h"
int main ()
{
TheUniverse.Initialize();
TheUniverse.Start();
return 0;
}
| gpl-2.0 |
ajnelson/photorec-testdisk | src/file_apple.c | 1 | 2408 | /*
File: file_apple.c
Copyright (C) 2009 Christophe GRENIER <grenier@cgsecurity.org>
This software 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 the Free Software Foundation, Inc., 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#if !defined(SINGLE_FORMAT) || defined(SINGLE_FORMAT_apple)
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include <stdio.h>
#include "types.h"
#include "filegen.h"
/*@ requires \valid(file_stat); */
static void register_header_check_apple(file_stat_t *file_stat);
const file_hint_t file_hint_apple= {
.extension="apple",
.description="AppleSingle/AppleDouble",
.max_filesize=PHOTOREC_MAX_FILE_SIZE,
.recover=1,
.enable_by_default=1,
.register_header_check=®ister_header_check_apple
};
/*@
@ requires buffer_size > 0;
@ requires \valid_read(buffer+(0..buffer_size-1));
@ requires valid_file_recovery(file_recovery);
@ requires \valid(file_recovery_new);
@ requires file_recovery_new->blocksize > 0;
@ requires separation: \separated(&file_hint_apple, buffer+(..), file_recovery, file_recovery_new);
@ assigns *file_recovery_new;
@ ensures \result!=0 ==> valid_file_recovery(file_recovery_new);
@*/
static int header_check_apple(const unsigned char *buffer, const unsigned int buffer_size, const unsigned int safe_header_only, const file_recovery_t *file_recovery, file_recovery_t *file_recovery_new)
{
reset_file_recovery(file_recovery_new);
file_recovery_new->extension=file_hint_apple.extension;
return 1;
}
static void register_header_check_apple(file_stat_t *file_stat)
{
static const unsigned char apple_header[8]= {
0x00, 0x05, 0x16, 0x07, 0x00, 0x02, 0x00, 0x00
};
register_header_check(0, apple_header,sizeof(apple_header), &header_check_apple, file_stat);
}
#endif
| gpl-2.0 |
pigworlds/asuswrttest | release/src/router/miniupnpd/netfilter/iptcrdr.c | 1 | 41327 | /* $Id: iptcrdr.c,v 1.54 2015/03/09 10:02:54 nanard Exp $ */
/* MiniUPnP project
* http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
* (c) 2006-2015 Thomas Bernard
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <sys/errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <dlfcn.h>
#include <linux/version.h>
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,36)
#include <iptables.h>
#else
#include <xtables.h>
#endif
#include <linux/netfilter/xt_DSCP.h>
#include <libiptc/libiptc.h>
#if IPTABLES_143
/* IPTABLES API version >= 1.4.3 */
/* added in order to compile on gentoo :
* http://miniupnp.tuxfamily.org/forum/viewtopic.php?p=2183 */
#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
#define __must_be_array(a) \
BUILD_BUG_ON_ZERO(__builtin_types_compatible_p(typeof(a), typeof(&a[0])))
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
#define LIST_POISON2 ((void *) 0x00200200 )
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,36)
#include <linux/netfilter/nf_nat.h>
#else
#include "tiny_nf_nat.h"
#endif
#define ip_nat_multi_range nf_nat_multi_range
#define ip_nat_range nf_nat_range
#define IPTC_HANDLE struct iptc_handle *
#else
/* IPTABLES API version < 1.4.3 */
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,22)
#include <linux/netfilter_ipv4/ip_nat.h>
#else
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,36)
#include <linux/netfilter/nf_nat.h>
#else
#include "tiny_nf_nat.h"
#endif
#endif
#define IPTC_HANDLE iptc_handle_t
#endif
/* IPT_ALIGN was renamed XT_ALIGN in iptables-1.4.11 */
#ifndef IPT_ALIGN
#define IPT_ALIGN XT_ALIGN
#endif
#include "../macros.h"
#include "../config.h"
#include "iptcrdr.h"
#include "../upnpglobalvars.h"
/* local functions declarations */
static int
addnatrule(int proto, unsigned short eport,
const char * iaddr, unsigned short iport,
const char * rhost);
static int
add_filter_rule(int proto, const char * rhost,
const char * iaddr, unsigned short iport);
static int
addpeernatrule(int proto,
const char * eaddr, unsigned short eport,
const char * iaddr, unsigned short iport,
const char * rhost, unsigned short rport);
static int
addpeerdscprule(int proto, unsigned char dscp,
const char * iaddr, unsigned short iport,
const char * rhost, unsigned short rport);
/* dummy init and shutdown functions */
int init_redirect(void)
{
return 0;
}
void shutdown_redirect(void)
{
return;
}
/* convert an ip address to string */
static int snprintip(char * dst, size_t size, uint32_t ip)
{
return snprintf(dst, size,
"%u.%u.%u.%u", ip >> 24, (ip >> 16) & 0xff,
(ip >> 8) & 0xff, ip & 0xff);
}
/* netfilter cannot store redirection descriptions, so we use our
* own structure to store them */
struct rdr_desc {
struct rdr_desc * next;
unsigned int timestamp;
unsigned short eport;
short proto;
char str[];
};
/* pointer to the chained list where descriptions are stored */
static struct rdr_desc * rdr_desc_list = 0;
/* add a description to the list of redirection descriptions */
static void
add_redirect_desc(unsigned short eport, int proto,
const char * desc, unsigned int timestamp)
{
struct rdr_desc * p;
size_t l;
/* set a default description if none given */
if(!desc)
desc = "miniupnpd";
l = strlen(desc) + 1;
p = malloc(sizeof(struct rdr_desc) + l);
if(p)
{
p->next = rdr_desc_list;
p->timestamp = timestamp;
p->eport = eport;
p->proto = (short)proto;
memcpy(p->str, desc, l);
rdr_desc_list = p;
}
}
/* delete a description from the list */
static void
del_redirect_desc(unsigned short eport, int proto)
{
struct rdr_desc * p, * last;
p = rdr_desc_list;
last = 0;
while(p)
{
if(p->eport == eport && p->proto == proto)
{
if(!last)
rdr_desc_list = p->next;
else
last->next = p->next;
free(p);
return;
}
last = p;
p = p->next;
}
}
/* go through the list to find the description */
static void
get_redirect_desc(unsigned short eport, int proto,
char * desc, int desclen,
unsigned int * timestamp)
{
struct rdr_desc * p;
for(p = rdr_desc_list; p; p = p->next)
{
if(p->eport == eport && p->proto == (short)proto)
{
if(desc)
strncpy(desc, p->str, desclen);
if(timestamp)
*timestamp = p->timestamp;
return;
}
}
/* if no description was found, return miniupnpd as default */
if(desc)
strncpy(desc, "miniupnpd", desclen);
if(timestamp)
*timestamp = 0;
}
#if USE_INDEX_FROM_DESC_LIST
static int
get_redirect_desc_by_index(int index, unsigned short * eport, int * proto,
char * desc, int desclen, unsigned int * timestamp)
{
int i = 0;
struct rdr_desc * p;
if(!desc || (desclen == 0))
return -1;
for(p = rdr_desc_list; p; p = p->next, i++)
{
if(i == index)
{
*eport = p->eport;
*proto = (int)p->proto;
strncpy(desc, p->str, desclen);
if(timestamp)
*timestamp = p->timestamp;
return 0;
}
}
return -1;
}
#endif
/* add_redirect_rule2() */
int
add_redirect_rule2(const char * ifname,
const char * rhost, unsigned short eport,
const char * iaddr, unsigned short iport, int proto,
const char * desc, unsigned int timestamp)
{
int r;
UNUSED(ifname);
r = addnatrule(proto, eport, iaddr, iport, rhost);
if(r >= 0)
add_redirect_desc(eport, proto, desc, timestamp);
return r;
}
/* add_redirect_rule2() */
int
add_peer_redirect_rule2(const char * ifname,
const char * rhost, unsigned short rport,
const char * eaddr, unsigned short eport,
const char * iaddr, unsigned short iport, int proto,
const char * desc, unsigned int timestamp)
{
int r;
UNUSED(ifname);
r = addpeernatrule(proto, eaddr, eport, iaddr, iport, rhost, rport);
if(r >= 0)
add_redirect_desc(eport, proto, desc, timestamp);
return r;
}
int
add_peer_dscp_rule2(const char * ifname,
const char * rhost, unsigned short rport,
unsigned char dscp,
const char * iaddr, unsigned short iport, int proto,
const char * desc, unsigned int timestamp)
{
int r;
UNUSED(ifname);
UNUSED(desc);
UNUSED(timestamp);
r = addpeerdscprule(proto, dscp, iaddr, iport, rhost, rport);
/* if(r >= 0)
add_redirect_desc(dscp, proto, desc, timestamp); */
return r;
}
int
add_filter_rule2(const char * ifname,
const char * rhost, const char * iaddr,
unsigned short eport, unsigned short iport,
int proto, const char * desc)
{
UNUSED(ifname);
UNUSED(eport);
UNUSED(desc);
return add_filter_rule(proto, rhost, iaddr, iport);
}
/* get_redirect_rule()
* returns -1 if the rule is not found */
int
get_redirect_rule(const char * ifname, unsigned short eport, int proto,
char * iaddr, int iaddrlen, unsigned short * iport,
char * desc, int desclen,
char * rhost, int rhostlen,
unsigned int * timestamp,
u_int64_t * packets, u_int64_t * bytes)
{
return get_nat_redirect_rule(miniupnpd_nat_chain,
ifname, eport, proto,
iaddr, iaddrlen, iport,
desc, desclen,
rhost, rhostlen,
timestamp, packets, bytes);
}
int
get_nat_redirect_rule(const char * nat_chain_name, const char * ifname, unsigned short eport, int proto,
char * iaddr, int iaddrlen, unsigned short * iport,
char * desc, int desclen,
char * rhost, int rhostlen,
unsigned int * timestamp,
u_int64_t * packets, u_int64_t * bytes)
{
int r = -1;
IPTC_HANDLE h;
const struct ipt_entry * e;
const struct ipt_entry_target * target;
const struct ip_nat_multi_range * mr;
const struct ipt_entry_match *match;
UNUSED(ifname);
h = iptc_init("nat");
if(!h)
{
syslog(LOG_ERR, "get_redirect_rule() : "
"iptc_init() failed : %s",
iptc_strerror(errno));
return -1;
}
if(!iptc_is_chain(nat_chain_name, h))
{
syslog(LOG_ERR, "chain %s not found", nat_chain_name);
}
else
{
#ifdef IPTABLES_143
for(e = iptc_first_rule(nat_chain_name, h);
e;
e = iptc_next_rule(e, h))
#else
for(e = iptc_first_rule(nat_chain_name, &h);
e;
e = iptc_next_rule(e, &h))
#endif
{
if(proto==e->ip.proto)
{
match = (const struct ipt_entry_match *)&e->elems;
if(0 == strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN))
{
const struct ipt_tcp * info;
info = (const struct ipt_tcp *)match->data;
if(eport != info->dpts[0])
continue;
}
else
{
const struct ipt_udp * info;
info = (const struct ipt_udp *)match->data;
if(eport != info->dpts[0])
continue;
}
target = (void *)e + e->target_offset;
/* target = ipt_get_target(e); */
mr = (const struct ip_nat_multi_range *)&target->data[0];
snprintip(iaddr, iaddrlen, ntohl(mr->range[0].min_ip));
*iport = ntohs(mr->range[0].min.all);
get_redirect_desc(eport, proto, desc, desclen, timestamp);
if(packets)
*packets = e->counters.pcnt;
if(bytes)
*bytes = e->counters.bcnt;
/* rhost */
if(e->ip.src.s_addr && rhost) {
snprintip(rhost, rhostlen, ntohl(e->ip.src.s_addr));
}
r = 0;
break;
}
}
}
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
return r;
}
/* get_redirect_rule_by_index()
* return -1 when the rule was not found */
int
get_redirect_rule_by_index(int index,
char * ifname, unsigned short * eport,
char * iaddr, int iaddrlen, unsigned short * iport,
int * proto, char * desc, int desclen,
char * rhost, int rhostlen,
unsigned int * timestamp,
u_int64_t * packets, u_int64_t * bytes)
{
int r = -1;
#if USE_INDEX_FROM_DESC_LIST
r = get_redirect_desc_by_index(index, eport, proto,
desc, desclen, timestamp);
if (r==0)
{
r = get_redirect_rule(ifname, *eport, *proto, iaddr, iaddrlen, iport,
0, 0, packets, bytes);
}
#else
int i = 0;
IPTC_HANDLE h;
const struct ipt_entry * e;
const struct ipt_entry_target * target;
const struct ip_nat_multi_range * mr;
const struct ipt_entry_match *match;
UNUSED(ifname);
h = iptc_init("nat");
if(!h)
{
syslog(LOG_ERR, "get_redirect_rule_by_index() : "
"iptc_init() failed : %s",
iptc_strerror(errno));
return -1;
}
if(!iptc_is_chain(miniupnpd_nat_chain, h))
{
syslog(LOG_ERR, "chain %s not found", miniupnpd_nat_chain);
}
else
{
#ifdef IPTABLES_143
for(e = iptc_first_rule(miniupnpd_nat_chain, h);
e;
e = iptc_next_rule(e, h))
#else
for(e = iptc_first_rule(miniupnpd_nat_chain, &h);
e;
e = iptc_next_rule(e, &h))
#endif
{
if(i==index)
{
*proto = e->ip.proto;
match = (const struct ipt_entry_match *)&e->elems;
if(0 == strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN))
{
const struct ipt_tcp * info;
info = (const struct ipt_tcp *)match->data;
*eport = info->dpts[0];
}
else
{
const struct ipt_udp * info;
info = (const struct ipt_udp *)match->data;
*eport = info->dpts[0];
}
target = (void *)e + e->target_offset;
mr = (const struct ip_nat_multi_range *)&target->data[0];
snprintip(iaddr, iaddrlen, ntohl(mr->range[0].min_ip));
*iport = ntohs(mr->range[0].min.all);
get_redirect_desc(*eport, *proto, desc, desclen, timestamp);
if(packets)
*packets = e->counters.pcnt;
if(bytes)
*bytes = e->counters.bcnt;
/* rhost */
if(rhost && rhostlen > 0) {
if(e->ip.src.s_addr) {
snprintip(rhost, rhostlen, ntohl(e->ip.src.s_addr));
} else {
rhost[0] = '\0';
}
}
r = 0;
break;
}
i++;
}
}
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
#endif
return r;
}
/* get_peer_rule_by_index()
* return -1 when the rule was not found */
int
get_peer_rule_by_index(int index,
char * ifname, unsigned short * eport,
char * iaddr, int iaddrlen, unsigned short * iport,
int * proto, char * desc, int desclen,
char * rhost, int rhostlen, unsigned short * rport,
unsigned int * timestamp,
u_int64_t * packets, u_int64_t * bytes)
{
int r = -1;
#if USE_INDEX_FROM_DESC_LIST && 0
r = get_redirect_desc_by_index(index, eport, proto,
desc, desclen, timestamp);
if (r==0)
{
r = get_redirect_rule(ifname, *eport, *proto, iaddr, iaddrlen, iport,
0, 0, packets, bytes);
}
#else
int i = 0;
IPTC_HANDLE h;
const struct ipt_entry * e;
const struct ipt_entry_target * target;
const struct ip_nat_multi_range * mr;
const struct ipt_entry_match *match;
UNUSED(ifname);
h = iptc_init("nat");
if(!h)
{
syslog(LOG_ERR, "get_peer_rule_by_index() : "
"iptc_init() failed : %s",
iptc_strerror(errno));
return -1;
}
if(!iptc_is_chain(miniupnpd_peer_chain, h))
{
syslog(LOG_ERR, "chain %s not found", miniupnpd_peer_chain);
}
else
{
#ifdef IPTABLES_143
for(e = iptc_first_rule(miniupnpd_peer_chain, h);
e;
e = iptc_next_rule(e, h))
#else
for(e = iptc_first_rule(miniupnpd_peer_chain, &h);
e;
e = iptc_next_rule(e, &h))
#endif
{
if(i==index)
{
*proto = e->ip.proto;
match = (const struct ipt_entry_match *)&e->elems;
if(0 == strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN))
{
const struct ipt_tcp * info;
info = (const struct ipt_tcp *)match->data;
if (rport)
*rport = info->dpts[0];
if (iport)
*iport = info->spts[0];
}
else
{
const struct ipt_udp * info;
info = (const struct ipt_udp *)match->data;
if (rport)
*rport = info->dpts[0];
if (iport)
*iport = info->spts[0];
}
target = (void *)e + e->target_offset;
mr = (const struct ip_nat_multi_range *)&target->data[0];
*eport = ntohs(mr->range[0].min.all);
get_redirect_desc(*eport, *proto, desc, desclen, timestamp);
if(packets)
*packets = e->counters.pcnt;
if(bytes)
*bytes = e->counters.bcnt;
/* rhost */
if(rhost && rhostlen > 0) {
if(e->ip.dst.s_addr) {
snprintip(rhost, rhostlen, ntohl(e->ip.dst.s_addr));
} else {
rhost[0] = '\0';
}
}
if(iaddr && iaddrlen > 0) {
if(e->ip.src.s_addr) {
snprintip(iaddr, iaddrlen, ntohl(e->ip.src.s_addr));
} else {
rhost[0] = '\0';
}
}
r = 0;
break;
}
i++;
}
}
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
#endif
return r;
}
/* delete_rule_and_commit() :
* subfunction used in delete_redirect_and_filter_rules() */
static int
delete_rule_and_commit(unsigned int index, IPTC_HANDLE h,
const char * miniupnpd_chain,
const char * logcaller)
{
int r = 0;
#ifdef IPTABLES_143
if(!iptc_delete_num_entry(miniupnpd_chain, index, h))
#else
if(!iptc_delete_num_entry(miniupnpd_chain, index, &h))
#endif
{
syslog(LOG_ERR, "%s() : iptc_delete_num_entry(): %s\n",
logcaller, iptc_strerror(errno));
r = -1;
}
#ifdef IPTABLES_143
else if(!iptc_commit(h))
#else
else if(!iptc_commit(&h))
#endif
{
syslog(LOG_ERR, "%s() : iptc_commit(): %s\n",
logcaller, iptc_strerror(errno));
r = -1;
}
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
return r;
}
/* delete_redirect_and_filter_rules()
*/
int
delete_redirect_and_filter_rules(unsigned short eport, int proto)
{
int r = -1, r2 = -1;
unsigned index = 0;
unsigned i = 0;
IPTC_HANDLE h;
const struct ipt_entry * e;
const struct ipt_entry_target * target;
const struct ip_nat_multi_range * mr;
const struct ipt_entry_match *match;
unsigned short iport = 0;
uint32_t iaddr = 0;
h = iptc_init("nat");
if(!h)
{
syslog(LOG_ERR, "delete_redirect_and_filter_rules() : "
"iptc_init() failed : %s",
iptc_strerror(errno));
return -1;
}
/* First step : find the right nat rule */
if(!iptc_is_chain(miniupnpd_nat_chain, h))
{
syslog(LOG_ERR, "chain %s not found", miniupnpd_nat_chain);
}
else
{
#ifdef IPTABLES_143
for(e = iptc_first_rule(miniupnpd_nat_chain, h);
e;
e = iptc_next_rule(e, h), i++)
#else
for(e = iptc_first_rule(miniupnpd_nat_chain, &h);
e;
e = iptc_next_rule(e, &h), i++)
#endif
{
if(proto==e->ip.proto)
{
match = (const struct ipt_entry_match *)&e->elems;
if(0 == strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN))
{
const struct ipt_tcp * info;
info = (const struct ipt_tcp *)match->data;
if(eport != info->dpts[0])
continue;
}
else
{
const struct ipt_udp * info;
info = (const struct ipt_udp *)match->data;
if(eport != info->dpts[0])
continue;
}
/* get the index, the internal address and the internal port
* of the rule */
index = i;
target = (void *)e + e->target_offset;
mr = (const struct ip_nat_multi_range *)&target->data[0];
iaddr = mr->range[0].min_ip;
iport = ntohs(mr->range[0].min.all);
r = 0;
break;
}
}
}
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
if(r == 0)
{
syslog(LOG_INFO, "Trying to delete nat rule at index %u", index);
/* Now delete both rules */
/* first delete the nat rule */
h = iptc_init("nat");
if(h)
{
r = delete_rule_and_commit(index, h, miniupnpd_nat_chain, "delete_redirect_rule");
}
if((r == 0) && (h = iptc_init("filter")))
{
i = 0;
/* we must find the right index for the filter rule */
#ifdef IPTABLES_143
for(e = iptc_first_rule(miniupnpd_forward_chain, h);
e;
e = iptc_next_rule(e, h), i++)
#else
for(e = iptc_first_rule(miniupnpd_forward_chain, &h);
e;
e = iptc_next_rule(e, &h), i++)
#endif
{
if(proto==e->ip.proto)
{
match = (const struct ipt_entry_match *)&e->elems;
/*syslog(LOG_DEBUG, "filter rule #%u: %s %s",
i, match->u.user.name, inet_ntoa(e->ip.dst));*/
if(0 == strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN))
{
const struct ipt_tcp * info;
info = (const struct ipt_tcp *)match->data;
if(iport != info->dpts[0])
continue;
}
else
{
const struct ipt_udp * info;
info = (const struct ipt_udp *)match->data;
if(iport != info->dpts[0])
continue;
}
if(iaddr != e->ip.dst.s_addr)
continue;
index = i;
syslog(LOG_INFO, "Trying to delete filter rule at index %u", index);
r = delete_rule_and_commit(index, h, miniupnpd_forward_chain, "delete_filter_rule");
h = NULL;
break;
}
}
}
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
}
/*delete PEER rule*/
if((h = iptc_init("nat")))
{
i = 0;
/* we must find the right index for the filter rule */
#ifdef IPTABLES_143
for(e = iptc_first_rule(miniupnpd_peer_chain, h);
e;
e = iptc_next_rule(e, h), i++)
#else
for(e = iptc_first_rule(miniupnpd_peer_chain, &h);
e;
e = iptc_next_rule(e, &h), i++)
#endif
{
if(proto==e->ip.proto)
{
target = (void *)e + e->target_offset;
mr = (const struct ip_nat_multi_range *)&target->data[0];
if (eport != ntohs(mr->range[0].min.all)) {
continue;
}
iaddr = e->ip.src.s_addr;
match = (const struct ipt_entry_match *)&e->elems;
if(0 == strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN))
{
const struct ipt_tcp * info;
info = (const struct ipt_tcp *)match->data;
iport = info->spts[0];
}
else
{
const struct ipt_udp * info;
info = (const struct ipt_udp *)match->data;
iport = info->dpts[0];
}
index = i;
syslog(LOG_INFO, "Trying to delete peer rule at index %u", index);
r2 = delete_rule_and_commit(index, h, miniupnpd_peer_chain, "delete_peer_rule");
h = NULL;
break;
}
}
}
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
/*delete DSCP rule*/
if((r2==0)&&(h = iptc_init("mangle")))
{
i = 0;
index = -1;
/* we must find the right index for the filter rule */
#ifdef IPTABLES_143
for(e = iptc_first_rule(miniupnpd_nat_chain, h);
e;
e = iptc_next_rule(e, h), i++)
#else
for(e = iptc_first_rule(miniupnpd_nat_chain, &h);
e;
e = iptc_next_rule(e, &h), i++)
#endif
{
if(proto==e->ip.proto)
{
match = (const struct ipt_entry_match *)&e->elems;
/*syslog(LOG_DEBUG, "filter rule #%u: %s %s",
i, match->u.user.name, inet_ntoa(e->ip.dst));*/
if(0 == strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN))
{
const struct ipt_tcp * info;
info = (const struct ipt_tcp *)match->data;
if(iport != info->spts[0])
continue;
}
else
{
const struct ipt_udp * info;
info = (const struct ipt_udp *)match->data;
if(iport != info->spts[0])
continue;
}
if(iaddr != e->ip.src.s_addr)
continue;
index = i;
syslog(LOG_INFO, "Trying to delete dscp rule at index %u", index);
r2 = delete_rule_and_commit(index, h, miniupnpd_nat_chain, "delete_dscp_rule");
h = NULL;
break;
}
}
if (h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
}
del_redirect_desc(eport, proto);
return r*r2;
}
/* ==================================== */
/* TODO : add the -m state --state NEW,ESTABLISHED,RELATED
* only for the filter rule */
static struct ipt_entry_match *
get_tcp_match(unsigned short dport, unsigned short sport)
{
struct ipt_entry_match *match;
struct ipt_tcp * tcpinfo;
size_t size;
size = IPT_ALIGN(sizeof(struct ipt_entry_match))
+ IPT_ALIGN(sizeof(struct ipt_tcp));
match = calloc(1, size);
match->u.match_size = size;
strncpy(match->u.user.name, "tcp", sizeof(match->u.user.name));
tcpinfo = (struct ipt_tcp *)match->data;
if (sport == 0) {
tcpinfo->spts[0] = 0; /* all source ports */
tcpinfo->spts[1] = 0xFFFF;
} else {
tcpinfo->spts[0] = sport; /* specified source port */
tcpinfo->spts[1] = sport;
}
if (dport == 0) {
tcpinfo->dpts[0] = 0; /* all destination ports */
tcpinfo->dpts[1] = 0xFFFF;
} else {
tcpinfo->dpts[0] = dport; /* specified destination port */
tcpinfo->dpts[1] = dport;
}
return match;
}
static struct ipt_entry_match *
get_udp_match(unsigned short dport, unsigned short sport)
{
struct ipt_entry_match *match;
struct ipt_udp * udpinfo;
size_t size;
size = IPT_ALIGN(sizeof(struct ipt_entry_match))
+ IPT_ALIGN(sizeof(struct ipt_udp));
match = calloc(1, size);
match->u.match_size = size;
strncpy(match->u.user.name, "udp", sizeof(match->u.user.name));
udpinfo = (struct ipt_udp *)match->data;
if (sport == 0) {
udpinfo->spts[0] = 0; /* all source ports */
udpinfo->spts[1] = 0xFFFF;
} else {
udpinfo->spts[0] = sport; /* specified source port */
udpinfo->spts[1] = sport;
}
if (dport == 0) {
udpinfo->dpts[0] = 0; /* all destination ports */
udpinfo->dpts[1] = 0xFFFF;
} else {
udpinfo->dpts[0] = dport; /* specified destination port */
udpinfo->dpts[1] = dport;
}
return match;
}
static struct ipt_entry_target *
get_dnat_target(const char * daddr, unsigned short dport)
{
struct ipt_entry_target * target;
struct ip_nat_multi_range * mr;
struct ip_nat_range * range;
size_t size;
size = IPT_ALIGN(sizeof(struct ipt_entry_target))
+ IPT_ALIGN(sizeof(struct ip_nat_multi_range));
target = calloc(1, size);
target->u.target_size = size;
strncpy(target->u.user.name, "DNAT", sizeof(target->u.user.name));
/* one ip_nat_range already included in ip_nat_multi_range */
mr = (struct ip_nat_multi_range *)&target->data[0];
mr->rangesize = 1;
range = &mr->range[0];
range->min_ip = range->max_ip = inet_addr(daddr);
range->flags |= IP_NAT_RANGE_MAP_IPS;
range->min.all = range->max.all = htons(dport);
range->flags |= IP_NAT_RANGE_PROTO_SPECIFIED;
return target;
}
static struct ipt_entry_target *
get_snat_target(const char * saddr, unsigned short sport)
{
struct ipt_entry_target * target;
struct ip_nat_multi_range * mr;
struct ip_nat_range * range;
size_t size;
size = IPT_ALIGN(sizeof(struct ipt_entry_target))
+ IPT_ALIGN(sizeof(struct ip_nat_multi_range));
target = calloc(1, size);
target->u.target_size = size;
strncpy(target->u.user.name, "SNAT", sizeof(target->u.user.name));
/* one ip_nat_range already included in ip_nat_multi_range */
mr = (struct ip_nat_multi_range *)&target->data[0];
mr->rangesize = 1;
range = &mr->range[0];
range->min_ip = range->max_ip = inet_addr(saddr);
range->flags |= IP_NAT_RANGE_MAP_IPS;
range->min.all = range->max.all = htons(sport);
range->flags |= IP_NAT_RANGE_PROTO_SPECIFIED;
return target;
}
static struct ipt_entry_target *
get_dscp_target(unsigned char dscp)
{
struct ipt_entry_target * target;
struct xt_DSCP_info * di;
size_t size;
size = IPT_ALIGN(sizeof(struct ipt_entry_target))
+ IPT_ALIGN(sizeof(struct xt_DSCP_info));
target = calloc(1, size);
target->u.target_size = size;
strncpy(target->u.user.name, "DSCP", sizeof(target->u.user.name));
/* one ip_nat_range already included in ip_nat_multi_range */
di = (struct xt_DSCP_info *)&target->data[0];
di->dscp=dscp;
return target;
}
/* iptc_init_verify_and_append()
* return 0 on success, -1 on failure */
static int
iptc_init_verify_and_append(const char * table,
const char * miniupnpd_chain,
struct ipt_entry * e,
const char * logcaller)
{
IPTC_HANDLE h;
h = iptc_init(table);
if(!h)
{
syslog(LOG_ERR, "%s : iptc_init() error : %s\n",
logcaller, iptc_strerror(errno));
return -1;
}
if(!iptc_is_chain(miniupnpd_chain, h))
{
syslog(LOG_ERR, "%s : chain %s not found",
logcaller, miniupnpd_chain);
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
return -1;
}
/* iptc_insert_entry(miniupnpd_chain, e, n, h/&h) could also be used */
#ifdef IPTABLES_143
if(!iptc_append_entry(miniupnpd_chain, e, h))
#else
if(!iptc_append_entry(miniupnpd_chain, e, &h))
#endif
{
syslog(LOG_ERR, "%s : iptc_append_entry() error : %s\n",
logcaller, iptc_strerror(errno));
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
return -1;
}
#ifdef IPTABLES_143
if(!iptc_commit(h))
#else
if(!iptc_commit(&h))
#endif
{
syslog(LOG_ERR, "%s : iptc_commit() error : %s\n",
logcaller, iptc_strerror(errno));
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
return -1;
}
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
return 0;
}
/* add nat rule
* iptables -t nat -A MINIUPNPD -p proto --dport eport -j DNAT --to iaddr:iport
* */
static int
addnatrule(int proto, unsigned short eport,
const char * iaddr, unsigned short iport,
const char * rhost)
{
int r = 0;
struct ipt_entry * e;
struct ipt_entry * tmp;
struct ipt_entry_match *match = NULL;
struct ipt_entry_target *target = NULL;
e = calloc(1, sizeof(struct ipt_entry));
if(!e) {
syslog(LOG_ERR, "%s: calloc(%d) error", "addnatrule",
(int)sizeof(struct ipt_entry));
return -1;
}
e->ip.proto = proto;
if(proto == IPPROTO_TCP) {
match = get_tcp_match(eport, 0);
} else {
match = get_udp_match(eport, 0);
}
e->nfcache = NFC_IP_DST_PT;
target = get_dnat_target(iaddr, iport);
e->nfcache |= NFC_UNKNOWN;
tmp = realloc(e, sizeof(struct ipt_entry)
+ match->u.match_size
+ target->u.target_size);
if(!tmp) {
syslog(LOG_ERR, "%s: realloc(%d) error", "addnatrule",
(int)(sizeof(struct ipt_entry) + match->u.match_size + target->u.target_size));
free(e);
free(match);
free(target);
return -1;
}
e = tmp;
memcpy(e->elems, match, match->u.match_size);
memcpy(e->elems + match->u.match_size, target, target->u.target_size);
e->target_offset = sizeof(struct ipt_entry)
+ match->u.match_size;
e->next_offset = sizeof(struct ipt_entry)
+ match->u.match_size
+ target->u.target_size;
/* remote host */
if(rhost && (rhost[0] != '\0') && (0 != strcmp(rhost, "*"))) {
e->ip.src.s_addr = inet_addr(rhost);
e->ip.smsk.s_addr = INADDR_NONE;
}
r = iptc_init_verify_and_append("nat", miniupnpd_nat_chain, e, "addnatrule()");
free(target);
free(match);
free(e);
return r;
}
/* iptables -t nat -A MINIUPNPD-PCP-PEER -s iaddr -d rhost
* -p proto --sport iport --dport rport -j SNAT
* --to-source ext_ip:eport */
static int
addpeernatrule(int proto,
const char * eaddr, unsigned short eport,
const char * iaddr, unsigned short iport,
const char * rhost, unsigned short rport)
{
int r = 0;
struct ipt_entry * e;
struct ipt_entry * tmp;
struct ipt_entry_match *match = NULL;
struct ipt_entry_target *target = NULL;
e = calloc(1, sizeof(struct ipt_entry));
if(!e) {
syslog(LOG_ERR, "%s: calloc(%d) error", "addpeernatrule",
(int)sizeof(struct ipt_entry));
return -1;
}
e->ip.proto = proto;
/* TODO: Fill port matches and SNAT */
if(proto == IPPROTO_TCP) {
match = get_tcp_match(rport, iport);
} else {
match = get_udp_match(rport, iport);
}
e->nfcache = NFC_IP_DST_PT | NFC_IP_SRC_PT;
target = get_snat_target(eaddr, eport);
e->nfcache |= NFC_UNKNOWN;
tmp = realloc(e, sizeof(struct ipt_entry)
+ match->u.match_size
+ target->u.target_size);
if(!tmp) {
syslog(LOG_ERR, "%s: realloc(%d) error", "addpeernatrule",
(int)(sizeof(struct ipt_entry) + match->u.match_size + target->u.target_size));
free(e);
free(match);
free(target);
return -1;
}
e = tmp;
memcpy(e->elems, match, match->u.match_size);
memcpy(e->elems + match->u.match_size, target, target->u.target_size);
e->target_offset = sizeof(struct ipt_entry)
+ match->u.match_size;
e->next_offset = sizeof(struct ipt_entry)
+ match->u.match_size
+ target->u.target_size;
/* internal host */
if(iaddr && (iaddr[0] != '\0') && (0 != strcmp(iaddr, "*")))
{
e->ip.src.s_addr = inet_addr(iaddr);
e->ip.smsk.s_addr = INADDR_NONE;
}
/* remote host */
if(rhost && (rhost[0] != '\0') && (0 != strcmp(rhost, "*")))
{
e->ip.dst.s_addr = inet_addr(rhost);
e->ip.dmsk.s_addr = INADDR_NONE;
}
r = iptc_init_verify_and_append("nat", miniupnpd_peer_chain, e, "addpeernatrule()");
free(target);
free(match);
free(e);
return r;
}
/* iptables -t mangle -A MINIUPNPD -s iaddr -d rhost
* -p proto --sport iport --dport rport -j DSCP
* --set-dscp 0xXXXX */
static int
addpeerdscprule(int proto, unsigned char dscp,
const char * iaddr, unsigned short iport,
const char * rhost, unsigned short rport)
{
int r = 0;
struct ipt_entry * e;
struct ipt_entry * tmp;
struct ipt_entry_match *match = NULL;
struct ipt_entry_target *target = NULL;
e = calloc(1, sizeof(struct ipt_entry));
if(!e) {
syslog(LOG_ERR, "%s: calloc(%d) error", "addpeerdscprule",
(int)sizeof(struct ipt_entry));
return -1;
}
e->ip.proto = proto;
/* TODO: Fill port matches and SNAT */
if(proto == IPPROTO_TCP) {
match = get_tcp_match(rport, iport);
} else {
match = get_udp_match(rport, iport);
}
e->nfcache = NFC_IP_DST_PT | NFC_IP_SRC_PT;
target = get_dscp_target(dscp);
e->nfcache |= NFC_UNKNOWN;
tmp = realloc(e, sizeof(struct ipt_entry)
+ match->u.match_size
+ target->u.target_size);
if(!tmp) {
syslog(LOG_ERR, "%s: realloc(%d) error", "addpeerdscprule",
(int)(sizeof(struct ipt_entry) + match->u.match_size + target->u.target_size));
free(e);
free(match);
free(target);
return -1;
}
e = tmp;
memcpy(e->elems, match, match->u.match_size);
memcpy(e->elems + match->u.match_size, target, target->u.target_size);
e->target_offset = sizeof(struct ipt_entry)
+ match->u.match_size;
e->next_offset = sizeof(struct ipt_entry)
+ match->u.match_size
+ target->u.target_size;
/* internal host */
if(iaddr && (iaddr[0] != '\0') && (0 != strcmp(iaddr, "*")))
{
e->ip.src.s_addr = inet_addr(iaddr);
e->ip.smsk.s_addr = INADDR_NONE;
}
/* remote host */
if(rhost && (rhost[0] != '\0') && (0 != strcmp(rhost, "*")))
{
e->ip.dst.s_addr = inet_addr(rhost);
e->ip.dmsk.s_addr = INADDR_NONE;
}
r = iptc_init_verify_and_append("mangle", miniupnpd_nat_chain, e,
"addpeerDSCPrule()");
free(target);
free(match);
free(e);
return r;
}
/* ================================= */
static struct ipt_entry_target *
get_accept_target(void)
{
struct ipt_entry_target * target = NULL;
size_t size;
size = IPT_ALIGN(sizeof(struct ipt_entry_target))
+ IPT_ALIGN(sizeof(int));
target = calloc(1, size);
target->u.user.target_size = size;
strncpy(target->u.user.name, "ACCEPT", sizeof(target->u.user.name));
return target;
}
/* add_filter_rule()
* */
static int
add_filter_rule(int proto, const char * rhost,
const char * iaddr, unsigned short iport)
{
int r = 0;
struct ipt_entry * e;
struct ipt_entry * tmp;
struct ipt_entry_match *match = NULL;
struct ipt_entry_target *target = NULL;
e = calloc(1, sizeof(struct ipt_entry));
if(!e) {
syslog(LOG_ERR, "%s: calloc(%d) error", "add_filter_rule",
(int)sizeof(struct ipt_entry));
return -1;
}
e->ip.proto = proto;
if(proto == IPPROTO_TCP) {
match = get_tcp_match(iport,0);
} else {
match = get_udp_match(iport,0);
}
e->nfcache = NFC_IP_DST_PT;
e->ip.dst.s_addr = inet_addr(iaddr);
e->ip.dmsk.s_addr = INADDR_NONE;
target = get_accept_target();
e->nfcache |= NFC_UNKNOWN;
tmp = realloc(e, sizeof(struct ipt_entry)
+ match->u.match_size
+ target->u.target_size);
if(!tmp) {
syslog(LOG_ERR, "%s: realloc(%d) error", "add_filter_rule",
(int)(sizeof(struct ipt_entry) + match->u.match_size + target->u.target_size));
free(e);
free(match);
free(target);
return -1;
}
e = tmp;
memcpy(e->elems, match, match->u.match_size);
memcpy(e->elems + match->u.match_size, target, target->u.target_size);
e->target_offset = sizeof(struct ipt_entry)
+ match->u.match_size;
e->next_offset = sizeof(struct ipt_entry)
+ match->u.match_size
+ target->u.target_size;
/* remote host */
if(rhost && (rhost[0] != '\0') && (0 != strcmp(rhost, "*")))
{
e->ip.src.s_addr = inet_addr(rhost);
e->ip.smsk.s_addr = INADDR_NONE;
}
r = iptc_init_verify_and_append("filter", miniupnpd_forward_chain, e, "add_filter_rule()");
free(target);
free(match);
free(e);
return r;
}
/* return an (malloc'ed) array of "external" port for which there is
* a port mapping. number is the size of the array */
unsigned short *
get_portmappings_in_range(unsigned short startport, unsigned short endport,
int proto, unsigned int * number)
{
unsigned short * array;
unsigned int capacity;
unsigned short eport;
IPTC_HANDLE h;
const struct ipt_entry * e;
const struct ipt_entry_match *match;
*number = 0;
capacity = 128;
array = calloc(capacity, sizeof(unsigned short));
if(!array)
{
syslog(LOG_ERR, "get_portmappings_in_range() : calloc error");
return NULL;
}
h = iptc_init("nat");
if(!h)
{
syslog(LOG_ERR, "get_redirect_rule_by_index() : "
"iptc_init() failed : %s",
iptc_strerror(errno));
free(array);
return NULL;
}
if(!iptc_is_chain(miniupnpd_nat_chain, h))
{
syslog(LOG_ERR, "chain %s not found", miniupnpd_nat_chain);
free(array);
array = NULL;
}
else
{
#ifdef IPTABLES_143
for(e = iptc_first_rule(miniupnpd_nat_chain, h);
e;
e = iptc_next_rule(e, h))
#else
for(e = iptc_first_rule(miniupnpd_nat_chain, &h);
e;
e = iptc_next_rule(e, &h))
#endif
{
if(proto == e->ip.proto)
{
match = (const struct ipt_entry_match *)&e->elems;
if(0 == strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN))
{
const struct ipt_tcp * info;
info = (const struct ipt_tcp *)match->data;
eport = info->dpts[0];
}
else
{
const struct ipt_udp * info;
info = (const struct ipt_udp *)match->data;
eport = info->dpts[0];
}
if(startport <= eport && eport <= endport)
{
if(*number >= capacity)
{
unsigned short * tmp;
/* need to increase the capacity of the array */
tmp = realloc(array, sizeof(unsigned short)*capacity);
if(!tmp)
{
syslog(LOG_ERR, "get_portmappings_in_range() : realloc(%u) error",
(unsigned)sizeof(unsigned short)*capacity);
*number = 0;
free(array);
array = NULL;
break;
}
array = tmp;
}
array[*number] = eport;
(*number)++;
}
}
}
}
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
return array;
}
/* ================================ */
#ifdef DEBUG
static int
print_match(const struct ipt_entry_match *match)
{
printf("match %s\n", match->u.user.name);
if(0 == strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN))
{
struct ipt_tcp * tcpinfo;
tcpinfo = (struct ipt_tcp *)match->data;
printf("srcport = %hu:%hu dstport = %hu:%hu\n",
tcpinfo->spts[0], tcpinfo->spts[1],
tcpinfo->dpts[0], tcpinfo->dpts[1]);
}
else if(0 == strncmp(match->u.user.name, "udp", IPT_FUNCTION_MAXNAMELEN))
{
struct ipt_udp * udpinfo;
udpinfo = (struct ipt_udp *)match->data;
printf("srcport = %hu:%hu dstport = %hu:%hu\n",
udpinfo->spts[0], udpinfo->spts[1],
udpinfo->dpts[0], udpinfo->dpts[1]);
}
return 0;
}
static void
print_iface(const char * iface, const unsigned char * mask, int invert)
{
unsigned i;
if(mask[0] == 0)
return;
if(invert)
printf("! ");
for(i=0; i<IFNAMSIZ; i++)
{
if(mask[i])
{
if(iface[i])
putchar(iface[i]);
}
else
{
if(iface[i-1])
putchar('+');
break;
}
}
}
static void
printip(uint32_t ip)
{
printf("%u.%u.%u.%u", ip >> 24, (ip >> 16) & 0xff,
(ip >> 8) & 0xff, ip & 0xff);
}
/* for debug */
/* read the "filter" and "nat" tables */
int
list_redirect_rule(const char * ifname)
{
IPTC_HANDLE h;
const struct ipt_entry * e;
const struct ipt_entry_target * target;
const struct ip_nat_multi_range * mr;
const char * target_str;
char addr[16], mask[16];
(void)ifname;
h = iptc_init("nat");
if(!h)
{
printf("iptc_init() error : %s\n", iptc_strerror(errno));
return -1;
}
if(!iptc_is_chain(miniupnpd_nat_chain, h))
{
printf("chain %s not found\n", miniupnpd_nat_chain);
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
return -1;
}
#ifdef IPTABLES_143
for(e = iptc_first_rule(miniupnpd_nat_chain, h);
e;
e = iptc_next_rule(e, h))
{
target_str = iptc_get_target(e, h);
#else
for(e = iptc_first_rule(miniupnpd_nat_chain, &h);
e;
e = iptc_next_rule(e, &h))
{
target_str = iptc_get_target(e, &h);
#endif
printf("===\n");
inet_ntop(AF_INET, &e->ip.src, addr, sizeof(addr));
inet_ntop(AF_INET, &e->ip.smsk, mask, sizeof(mask));
printf("src = %s%s/%s\n", (e->ip.invflags & IPT_INV_SRCIP)?"! ":"",
/*inet_ntoa(e->ip.src), inet_ntoa(e->ip.smsk)*/
addr, mask);
inet_ntop(AF_INET, &e->ip.dst, addr, sizeof(addr));
inet_ntop(AF_INET, &e->ip.dmsk, mask, sizeof(mask));
printf("dst = %s%s/%s\n", (e->ip.invflags & IPT_INV_DSTIP)?"! ":"",
/*inet_ntoa(e->ip.dst), inet_ntoa(e->ip.dmsk)*/
addr, mask);
/*printf("in_if = %s out_if = %s\n", e->ip.iniface, e->ip.outiface);*/
printf("in_if = ");
print_iface(e->ip.iniface, e->ip.iniface_mask,
e->ip.invflags & IPT_INV_VIA_IN);
printf(" out_if = ");
print_iface(e->ip.outiface, e->ip.outiface_mask,
e->ip.invflags & IPT_INV_VIA_OUT);
printf("\n");
printf("ip.proto = %s%d\n", (e->ip.invflags & IPT_INV_PROTO)?"! ":"",
e->ip.proto);
/* display matches stuff */
if(e->target_offset)
{
IPT_MATCH_ITERATE(e, print_match);
/*printf("\n");*/
}
printf("target = %s\n", target_str);
target = (void *)e + e->target_offset;
mr = (const struct ip_nat_multi_range *)&target->data[0];
printf("ips ");
printip(ntohl(mr->range[0].min_ip));
printf(" ");
printip(ntohl(mr->range[0].max_ip));
printf("\nports %hu %hu\n", ntohs(mr->range[0].min.all),
ntohs(mr->range[0].max.all));
printf("flags = %x\n", mr->range[0].flags);
}
if(h)
#ifdef IPTABLES_143
iptc_free(h);
#else
iptc_free(&h);
#endif
return 0;
}
#endif
| gpl-2.0 |
kero99/mangos | src/game/BattleGroundMgr.cpp | 1 | 99831 | /*
* Copyright (C) 2005-2011 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 "SharedDefines.h"
#include "Player.h"
#include "BattleGroundMgr.h"
#include "BattleGroundAV.h"
#include "BattleGroundAB.h"
#include "BattleGroundEY.h"
#include "BattleGroundWS.h"
#include "BattleGroundNA.h"
#include "BattleGroundBE.h"
#include "BattleGroundAA.h"
#include "BattleGroundRL.h"
#include "BattleGroundSA.h"
#include "BattleGroundDS.h"
#include "BattleGroundRV.h"
#include "BattleGroundIC.h"
#include "BattleGroundRB.h"
#include "MapManager.h"
#include "Map.h"
#include "ObjectMgr.h"
#include "ProgressBar.h"
#include "Chat.h"
#include "ArenaTeam.h"
#include "World.h"
#include "WorldPacket.h"
#include "GameEventMgr.h"
#include "Formulas.h"
#include "Policies/SingletonImp.h"
INSTANTIATE_SINGLETON_1( BattleGroundMgr );
/*********************************************************/
/*** BATTLEGROUND QUEUE SYSTEM ***/
/*********************************************************/
BattleGroundQueue::BattleGroundQueue()
{
for(uint32 i = 0; i < BG_TEAMS_COUNT; ++i)
{
for(uint32 j = 0; j < MAX_BATTLEGROUND_BRACKETS; ++j)
{
m_SumOfWaitTimes[i][j] = 0;
m_WaitTimeLastPlayer[i][j] = 0;
for(uint32 k = 0; k < COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME; ++k)
m_WaitTimes[i][j][k] = 0;
}
}
}
BattleGroundQueue::~BattleGroundQueue()
{
m_QueuedPlayers.clear();
for (int i = 0; i < MAX_BATTLEGROUND_BRACKETS; ++i)
{
for(uint32 j = 0; j < BG_QUEUE_GROUP_TYPES_COUNT; ++j)
{
for(GroupsQueueType::iterator itr = m_QueuedGroups[i][j].begin(); itr!= m_QueuedGroups[i][j].end(); ++itr)
delete (*itr);
m_QueuedGroups[i][j].clear();
}
}
}
/*********************************************************/
/*** BATTLEGROUND QUEUE SELECTION POOLS ***/
/*********************************************************/
// selection pool initialization, used to clean up from prev selection
void BattleGroundQueue::SelectionPool::Init()
{
SelectedGroups.clear();
PlayerCount = 0;
}
// remove group info from selection pool
// returns true when we need to try to add new group to selection pool
// returns false when selection pool is ok or when we kicked smaller group than we need to kick
// sometimes it can be called on empty selection pool
bool BattleGroundQueue::SelectionPool::KickGroup(uint32 size)
{
//find maxgroup or LAST group with size == size and kick it
bool found = false;
GroupsQueueType::iterator groupToKick = SelectedGroups.begin();
for (GroupsQueueType::iterator itr = groupToKick; itr != SelectedGroups.end(); ++itr)
{
if (abs((int32)((*itr)->Players.size() - size)) <= 1)
{
groupToKick = itr;
found = true;
}
else if (!found && (*itr)->Players.size() >= (*groupToKick)->Players.size())
groupToKick = itr;
}
//if pool is empty, do nothing
if (GetPlayerCount())
{
//update player count
GroupQueueInfo* ginfo = (*groupToKick);
SelectedGroups.erase(groupToKick);
PlayerCount -= ginfo->Players.size();
//return false if we kicked smaller group or there are enough players in selection pool
if (ginfo->Players.size() <= size + 1)
return false;
}
return true;
}
// add group to selection pool
// used when building selection pools
// returns true if we can invite more players, or when we added group to selection pool
// returns false when selection pool is full
bool BattleGroundQueue::SelectionPool::AddGroup(GroupQueueInfo *ginfo, uint32 desiredCount)
{
//if group is larger than desired count - don't allow to add it to pool
if (!ginfo->IsInvitedToBGInstanceGUID && desiredCount >= PlayerCount + ginfo->Players.size())
{
SelectedGroups.push_back(ginfo);
// increase selected players count
PlayerCount += ginfo->Players.size();
return true;
}
if (PlayerCount < desiredCount)
return true;
return false;
}
/*********************************************************/
/*** BATTLEGROUND QUEUES ***/
/*********************************************************/
// add group or player (grp == NULL) to bg queue with the given leader and bg specifications
GroupQueueInfo * BattleGroundQueue::AddGroup(Player *leader, Group* grp, BattleGroundTypeId BgTypeId, PvPDifficultyEntry const* bracketEntry, ArenaType arenaType, bool isRated, bool isPremade, uint32 arenaRating, uint32 arenateamid)
{
BattleGroundBracketId bracketId = bracketEntry->GetBracketId();
// create new ginfo
GroupQueueInfo* ginfo = new GroupQueueInfo;
ginfo->BgTypeId = BgTypeId;
ginfo->arenaType = arenaType;
ginfo->ArenaTeamId = arenateamid;
ginfo->IsRated = isRated;
ginfo->IsInvitedToBGInstanceGUID = 0;
ginfo->JoinTime = WorldTimer::getMSTime();
ginfo->RemoveInviteTime = 0;
ginfo->GroupTeam = leader->GetTeam();
ginfo->ArenaTeamRating = arenaRating;
ginfo->OpponentsTeamRating = 0;
ginfo->Players.clear();
//compute index (if group is premade or joined a rated match) to queues
uint32 index = 0;
if (!isRated && !isPremade)
index += BG_TEAMS_COUNT; // BG_QUEUE_PREMADE_* -> BG_QUEUE_NORMAL_*
if (ginfo->GroupTeam == HORDE)
index++; // BG_QUEUE_*_ALLIANCE -> BG_QUEUE_*_HORDE
DEBUG_LOG("Adding Group to BattleGroundQueue bgTypeId : %u, bracket_id : %u, index : %u", BgTypeId, bracketId, index);
uint32 lastOnlineTime = WorldTimer::getMSTime();
//announce world (this don't need mutex)
if (isRated && sWorld.getConfig(CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_JOIN))
{
sWorld.SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_JOIN, ginfo->arenaType, ginfo->arenaType, ginfo->ArenaTeamRating);
}
//add players from group to ginfo
{
//ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_Lock);
if (grp)
{
for(GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player *member = itr->getSource();
if(!member)
continue; // this should never happen
PlayerQueueInfo& pl_info = m_QueuedPlayers[member->GetObjectGuid()];
pl_info.LastOnlineTime = lastOnlineTime;
pl_info.GroupInfo = ginfo;
// add the pinfo to ginfo's list
ginfo->Players[member->GetObjectGuid()] = &pl_info;
}
}
else
{
PlayerQueueInfo& pl_info = m_QueuedPlayers[leader->GetObjectGuid()];
pl_info.LastOnlineTime = lastOnlineTime;
pl_info.GroupInfo = ginfo;
ginfo->Players[leader->GetObjectGuid()] = &pl_info;
}
//add GroupInfo to m_QueuedGroups
m_QueuedGroups[bracketId][index].push_back(ginfo);
//announce to world, this code needs mutex
if (arenaType == ARENA_TYPE_NONE && !isRated && !isPremade && sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_QUEUE_ANNOUNCER_JOIN))
{
if (BattleGround* bg = sBattleGroundMgr.GetBattleGroundTemplate(ginfo->BgTypeId))
{
char const* bgName = bg->GetName();
uint32 MinPlayers = bg->GetMinPlayersPerTeam();
uint32 qHorde = 0;
uint32 qAlliance = 0;
uint32 q_min_level = bracketEntry->minLevel;
uint32 q_max_level = bracketEntry->maxLevel;
GroupsQueueType::const_iterator itr;
for(itr = m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_ALLIANCE].begin(); itr != m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_ALLIANCE].end(); ++itr)
if (!(*itr)->IsInvitedToBGInstanceGUID)
qAlliance += (*itr)->Players.size();
for(itr = m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_HORDE].begin(); itr != m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_HORDE].end(); ++itr)
if (!(*itr)->IsInvitedToBGInstanceGUID)
qHorde += (*itr)->Players.size();
// Show queue status to player only (when joining queue)
if (sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_QUEUE_ANNOUNCER_JOIN)==1)
{
ChatHandler(leader).PSendSysMessage(LANG_BG_QUEUE_ANNOUNCE_SELF, bgName, q_min_level, q_max_level,
qAlliance, (MinPlayers > qAlliance) ? MinPlayers - qAlliance : (uint32)0, qHorde, (MinPlayers > qHorde) ? MinPlayers - qHorde : (uint32)0);
}
// System message
else
{
sWorld.SendWorldText(LANG_BG_QUEUE_ANNOUNCE_WORLD, bgName, q_min_level, q_max_level,
qAlliance, (MinPlayers > qAlliance) ? MinPlayers - qAlliance : (uint32)0, qHorde, (MinPlayers > qHorde) ? MinPlayers - qHorde : (uint32)0);
}
}
}
//release mutex
}
return ginfo;
}
void BattleGroundQueue::PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo* ginfo, BattleGroundBracketId bracket_id)
{
uint32 timeInQueue = WorldTimer::getMSTimeDiff(ginfo->JoinTime, WorldTimer::getMSTime());
uint8 team_index = BG_TEAM_ALLIANCE; //default set to BG_TEAM_ALLIANCE - or non rated arenas!
if (ginfo->arenaType == ARENA_TYPE_NONE)
{
if (ginfo->GroupTeam == HORDE)
team_index = BG_TEAM_HORDE;
}
else
{
if (ginfo->IsRated)
team_index = BG_TEAM_HORDE; //for rated arenas use BG_TEAM_HORDE
}
//store pointer to arrayindex of player that was added first
uint32* lastPlayerAddedPointer = &(m_WaitTimeLastPlayer[team_index][bracket_id]);
//remove his time from sum
m_SumOfWaitTimes[team_index][bracket_id] -= m_WaitTimes[team_index][bracket_id][(*lastPlayerAddedPointer)];
//set average time to new
m_WaitTimes[team_index][bracket_id][(*lastPlayerAddedPointer)] = timeInQueue;
//add new time to sum
m_SumOfWaitTimes[team_index][bracket_id] += timeInQueue;
//set index of last player added to next one
(*lastPlayerAddedPointer)++;
(*lastPlayerAddedPointer) %= COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME;
}
uint32 BattleGroundQueue::GetAverageQueueWaitTime(GroupQueueInfo* ginfo, BattleGroundBracketId bracket_id)
{
uint8 team_index = BG_TEAM_ALLIANCE; //default set to BG_TEAM_ALLIANCE - or non rated arenas!
if (ginfo->arenaType == ARENA_TYPE_NONE)
{
if (ginfo->GroupTeam == HORDE)
team_index = BG_TEAM_HORDE;
}
else
{
if (ginfo->IsRated)
team_index = BG_TEAM_HORDE; //for rated arenas use BG_TEAM_HORDE
}
//check if there is enought values(we always add values > 0)
if (m_WaitTimes[team_index][bracket_id][COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME - 1] )
return (m_SumOfWaitTimes[team_index][bracket_id] / COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME);
else
//if there aren't enough values return 0 - not available
return 0;
}
//remove player from queue and from group info, if group info is empty then remove it too
void BattleGroundQueue::RemovePlayer(ObjectGuid guid, bool decreaseInvitedCount)
{
//Player *plr = sObjectMgr.GetPlayer(guid);
//ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_Lock);
int32 bracket_id = -1; // signed for proper for-loop finish
QueuedPlayersMap::iterator itr;
//remove player from map, if he's there
itr = m_QueuedPlayers.find(guid);
if (itr == m_QueuedPlayers.end())
{
sLog.outError("BattleGroundQueue: couldn't find for remove: %s", guid.GetString().c_str());
return;
}
GroupQueueInfo* group = itr->second.GroupInfo;
GroupsQueueType::iterator group_itr, group_itr_tmp;
// mostly people with the highest levels are in battlegrounds, thats why
// we count from MAX_BATTLEGROUND_QUEUES - 1 to 0
// variable index removes useless searching in other team's queue
uint32 index = BattleGround::GetTeamIndexByTeamId(group->GroupTeam);
for (int32 bracket_id_tmp = MAX_BATTLEGROUND_BRACKETS - 1; bracket_id_tmp >= 0 && bracket_id == -1; --bracket_id_tmp)
{
//we must check premade and normal team's queue - because when players from premade are joining bg,
//they leave groupinfo so we can't use its players size to find out index
for (uint32 j = index; j < BG_QUEUE_GROUP_TYPES_COUNT; j += BG_QUEUE_NORMAL_ALLIANCE)
{
for(group_itr_tmp = m_QueuedGroups[bracket_id_tmp][j].begin(); group_itr_tmp != m_QueuedGroups[bracket_id_tmp][j].end(); ++group_itr_tmp)
{
if ((*group_itr_tmp) == group)
{
bracket_id = bracket_id_tmp;
group_itr = group_itr_tmp;
//we must store index to be able to erase iterator
index = j;
break;
}
}
}
}
//player can't be in queue without group, but just in case
if (bracket_id == -1)
{
sLog.outError("BattleGroundQueue: ERROR Cannot find groupinfo for %s", guid.GetString().c_str());
return;
}
DEBUG_LOG("BattleGroundQueue: Removing %s, from bracket_id %u", guid.GetString().c_str(), (uint32)bracket_id);
// ALL variables are correctly set
// We can ignore leveling up in queue - it should not cause crash
// remove player from group
// if only one player there, remove group
// remove player queue info from group queue info
GroupQueueInfoPlayers::iterator pitr = group->Players.find(guid);
if (pitr != group->Players.end())
group->Players.erase(pitr);
// if invited to bg, and should decrease invited count, then do it
if (decreaseInvitedCount && group->IsInvitedToBGInstanceGUID)
{
BattleGround* bg = sBattleGroundMgr.GetBattleGround(group->IsInvitedToBGInstanceGUID, group->BgTypeId);
if (bg)
bg->DecreaseInvitedCount(group->GroupTeam);
}
// remove player queue info
m_QueuedPlayers.erase(itr);
// announce to world if arena team left queue for rated match, show only once
if (group->arenaType != ARENA_TYPE_NONE && group->IsRated && group->Players.empty() && sWorld.getConfig(CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_EXIT))
sWorld.SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_EXIT, group->arenaType, group->arenaType, group->ArenaTeamRating);
//if player leaves queue and he is invited to rated arena match, then he have to loose
if (group->IsInvitedToBGInstanceGUID && group->IsRated && decreaseInvitedCount)
{
ArenaTeam * at = sObjectMgr.GetArenaTeamById(group->ArenaTeamId);
if (at)
{
DEBUG_LOG("UPDATING memberLost's personal arena rating for %s by opponents rating: %u", guid.GetString().c_str(), group->OpponentsTeamRating);
Player *plr = sObjectMgr.GetPlayer(guid);
if (plr)
at->MemberLost(plr, group->OpponentsTeamRating);
else
at->OfflineMemberLost(guid, group->OpponentsTeamRating);
at->SaveToDB();
}
}
// remove group queue info if needed
if (group->Players.empty())
{
m_QueuedGroups[bracket_id][index].erase(group_itr);
delete group;
}
// if group wasn't empty, so it wasn't deleted, and player have left a rated
// queue -> everyone from the group should leave too
// don't remove recursively if already invited to bg!
else if (!group->IsInvitedToBGInstanceGUID && group->IsRated)
{
// remove next player, this is recursive
// first send removal information
if (Player *plr2 = sObjectMgr.GetPlayer(group->Players.begin()->first))
{
BattleGround * bg = sBattleGroundMgr.GetBattleGroundTemplate(group->BgTypeId);
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(group->BgTypeId, group->arenaType);
uint32 queueSlot = plr2->GetBattleGroundQueueIndex(bgQueueTypeId);
plr2->RemoveBattleGroundQueueId(bgQueueTypeId); // must be called this way, because if you move this call to
// queue->removeplayer, it causes bugs
WorldPacket data;
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, ARENA_TYPE_NONE);
plr2->GetSession()->SendPacket(&data);
}
// then actually delete, this may delete the group as well!
RemovePlayer(group->Players.begin()->first, decreaseInvitedCount);
}
}
//returns true when player pl_guid is in queue and is invited to bgInstanceGuid
bool BattleGroundQueue::IsPlayerInvited(ObjectGuid pl_guid, const uint32 bgInstanceGuid, const uint32 removeTime)
{
//ACE_Guard<ACE_Recursive_Thread_Mutex> g(m_Lock);
QueuedPlayersMap::const_iterator qItr = m_QueuedPlayers.find(pl_guid);
return ( qItr != m_QueuedPlayers.end()
&& qItr->second.GroupInfo->IsInvitedToBGInstanceGUID == bgInstanceGuid
&& qItr->second.GroupInfo->RemoveInviteTime == removeTime );
}
bool BattleGroundQueue::GetPlayerGroupInfoData(ObjectGuid guid, GroupQueueInfo* ginfo)
{
//ACE_Guard<ACE_Recursive_Thread_Mutex> g(m_Lock);
QueuedPlayersMap::const_iterator qItr = m_QueuedPlayers.find(guid);
if (qItr == m_QueuedPlayers.end())
return false;
*ginfo = *(qItr->second.GroupInfo);
return true;
}
bool BattleGroundQueue::InviteGroupToBG(GroupQueueInfo * ginfo, BattleGround * bg, Team side)
{
// set side if needed
if (side)
ginfo->GroupTeam = side;
if (!ginfo->IsInvitedToBGInstanceGUID)
{
// not yet invited
// set invitation
ginfo->IsInvitedToBGInstanceGUID = bg->GetInstanceID();
BattleGroundTypeId bgTypeId = bg->GetTypeID();
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bgTypeId, bg->GetArenaType());
BattleGroundBracketId bracket_id = bg->GetBracketId();
// set ArenaTeamId for rated matches
if (bg->isArena() && bg->isRated())
bg->SetArenaTeamIdForTeam(ginfo->GroupTeam, ginfo->ArenaTeamId);
ginfo->RemoveInviteTime = WorldTimer::getMSTime() + INVITE_ACCEPT_WAIT_TIME;
// loop through the players
for(GroupQueueInfoPlayers::iterator itr = ginfo->Players.begin(); itr != ginfo->Players.end(); ++itr)
{
// get the player
Player* plr = sObjectMgr.GetPlayer(itr->first);
// if offline, skip him, this should not happen - player is removed from queue when he logs out
if (!plr)
continue;
// invite the player
PlayerInvitedToBGUpdateAverageWaitTime(ginfo, bracket_id);
//sBattleGroundMgr.InvitePlayer(plr, bg, ginfo->Team);
// set invited player counters
bg->IncreaseInvitedCount(ginfo->GroupTeam);
plr->SetInviteForBattleGroundQueueType(bgQueueTypeId, ginfo->IsInvitedToBGInstanceGUID);
// create remind invite events
BGQueueInviteEvent* inviteEvent = new BGQueueInviteEvent(plr->GetObjectGuid(), ginfo->IsInvitedToBGInstanceGUID, bgTypeId, ginfo->arenaType, ginfo->RemoveInviteTime);
plr->m_Events.AddEvent(inviteEvent, plr->m_Events.CalculateTime(INVITATION_REMIND_TIME));
// create automatic remove events
BGQueueRemoveEvent* removeEvent = new BGQueueRemoveEvent(plr->GetGUID(), ginfo->IsInvitedToBGInstanceGUID, bgTypeId, bgQueueTypeId, ginfo->RemoveInviteTime);
plr->m_Events.AddEvent(removeEvent, plr->m_Events.CalculateTime(INVITE_ACCEPT_WAIT_TIME));
WorldPacket data;
uint32 queueSlot = plr->GetBattleGroundQueueIndex(bgQueueTypeId);
DEBUG_LOG("Battleground: invited %s to BG instance %u queueindex %u bgtype %u, I can't help it if they don't press the enter battle button.",
plr->GetGuidStr().c_str(), bg->GetInstanceID(), queueSlot, bg->GetTypeID());
// send status packet
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME, 0, ginfo->arenaType);
plr->GetSession()->SendPacket(&data);
}
return true;
}
return false;
}
/*
This function is inviting players to already running battlegrounds
Invitation type is based on config file
large groups are disadvantageous, because they will be kicked first if invitation type = 1
*/
void BattleGroundQueue::FillPlayersToBG(BattleGround* bg, BattleGroundBracketId bracket_id)
{
int32 hordeFree = bg->GetFreeSlotsForTeam(HORDE);
int32 aliFree = bg->GetFreeSlotsForTeam(ALLIANCE);
//iterator for iterating through bg queue
GroupsQueueType::const_iterator Ali_itr = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].begin();
//count of groups in queue - used to stop cycles
uint32 aliCount = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].size();
//index to queue which group is current
uint32 aliIndex = 0;
for (; aliIndex < aliCount && m_SelectionPools[BG_TEAM_ALLIANCE].AddGroup((*Ali_itr), aliFree); aliIndex++)
++Ali_itr;
//the same thing for horde
GroupsQueueType::const_iterator Horde_itr = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].begin();
uint32 hordeCount = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].size();
uint32 hordeIndex = 0;
for (; hordeIndex < hordeCount && m_SelectionPools[BG_TEAM_HORDE].AddGroup((*Horde_itr), hordeFree); hordeIndex++)
++Horde_itr;
//if ofc like BG queue invitation is set in config, then we are happy
if (sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_INVITATION_TYPE) == 0)
return;
/*
if we reached this code, then we have to solve NP - complete problem called Subset sum problem
So one solution is to check all possible invitation subgroups, or we can use these conditions:
1. Last time when BattleGroundQueue::Update was executed we invited all possible players - so there is only small possibility
that we will invite now whole queue, because only 1 change has been made to queues from the last BattleGroundQueue::Update call
2. Other thing we should consider is group order in queue
*/
// At first we need to compare free space in bg and our selection pool
int32 diffAli = aliFree - int32(m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount());
int32 diffHorde = hordeFree - int32(m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount());
while( abs(diffAli - diffHorde) > 1 && (m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount() > 0 || m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount() > 0) )
{
//each cycle execution we need to kick at least 1 group
if (diffAli < diffHorde)
{
//kick alliance group, add to pool new group if needed
if (m_SelectionPools[BG_TEAM_ALLIANCE].KickGroup(diffHorde - diffAli))
{
for (; aliIndex < aliCount && m_SelectionPools[BG_TEAM_ALLIANCE].AddGroup((*Ali_itr), (aliFree >= diffHorde) ? aliFree - diffHorde : 0); aliIndex++)
++Ali_itr;
}
//if ali selection is already empty, then kick horde group, but if there are less horde than ali in bg - break;
if (!m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount())
{
if (aliFree <= diffHorde + 1)
break;
m_SelectionPools[BG_TEAM_HORDE].KickGroup(diffHorde - diffAli);
}
}
else
{
//kick horde group, add to pool new group if needed
if (m_SelectionPools[BG_TEAM_HORDE].KickGroup(diffAli - diffHorde))
{
for (; hordeIndex < hordeCount && m_SelectionPools[BG_TEAM_HORDE].AddGroup((*Horde_itr), (hordeFree >= diffAli) ? hordeFree - diffAli : 0); hordeIndex++)
++Horde_itr;
}
if (!m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount())
{
if (hordeFree <= diffAli + 1)
break;
m_SelectionPools[BG_TEAM_ALLIANCE].KickGroup(diffAli - diffHorde);
}
}
//count diffs after small update
diffAli = aliFree - int32(m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount());
diffHorde = hordeFree - int32(m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount());
}
}
// this method checks if premade versus premade battleground is possible
// then after 30 mins (default) in queue it moves premade group to normal queue
// it tries to invite as much players as it can - to MaxPlayersPerTeam, because premade groups have more than MinPlayersPerTeam players
bool BattleGroundQueue::CheckPremadeMatch(BattleGroundBracketId bracket_id, uint32 MinPlayersPerTeam, uint32 MaxPlayersPerTeam)
{
//check match
if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty() && !m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].empty())
{
//start premade match
//if groups aren't invited
GroupsQueueType::const_iterator ali_group, horde_group;
for( ali_group = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].begin(); ali_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].end(); ++ali_group)
if (!(*ali_group)->IsInvitedToBGInstanceGUID)
break;
for( horde_group = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].begin(); horde_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].end(); ++horde_group)
if (!(*horde_group)->IsInvitedToBGInstanceGUID)
break;
if (ali_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].end() && horde_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].end())
{
m_SelectionPools[BG_TEAM_ALLIANCE].AddGroup((*ali_group), MaxPlayersPerTeam);
m_SelectionPools[BG_TEAM_HORDE].AddGroup((*horde_group), MaxPlayersPerTeam);
//add groups/players from normal queue to size of bigger group
uint32 maxPlayers = std::max(m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount(), m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount());
GroupsQueueType::const_iterator itr;
for(uint32 i = 0; i < BG_TEAMS_COUNT; i++)
{
for(itr = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].begin(); itr != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].end(); ++itr)
{
//if itr can join BG and player count is less that maxPlayers, then add group to selectionpool
if (!(*itr)->IsInvitedToBGInstanceGUID && !m_SelectionPools[i].AddGroup((*itr), maxPlayers))
break;
}
}
//premade selection pools are set
return true;
}
}
// now check if we can move group from Premade queue to normal queue (timer has expired) or group size lowered!!
// this could be 2 cycles but i'm checking only first team in queue - it can cause problem -
// if first is invited to BG and seconds timer expired, but we can ignore it, because players have only 80 seconds to click to enter bg
// and when they click or after 80 seconds the queue info is removed from queue
uint32 time_before = WorldTimer::getMSTime() - sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH);
for(uint32 i = 0; i < BG_TEAMS_COUNT; i++)
{
if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE + i].empty())
{
GroupsQueueType::iterator itr = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE + i].begin();
if (!(*itr)->IsInvitedToBGInstanceGUID && ((*itr)->JoinTime < time_before || (*itr)->Players.size() < MinPlayersPerTeam))
{
//we must insert group to normal queue and erase pointer from premade queue
m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].push_front((*itr));
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE + i].erase(itr);
}
}
}
//selection pools are not set
return false;
}
// this method tries to create battleground or arena with MinPlayersPerTeam against MinPlayersPerTeam
bool BattleGroundQueue::CheckNormalMatch(BattleGround* bg_template, BattleGroundBracketId bracket_id, uint32 minPlayers, uint32 maxPlayers)
{
GroupsQueueType::const_iterator itr_team[BG_TEAMS_COUNT];
for(uint32 i = 0; i < BG_TEAMS_COUNT; i++)
{
itr_team[i] = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].begin();
for(; itr_team[i] != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].end(); ++(itr_team[i]))
{
if (!(*(itr_team[i]))->IsInvitedToBGInstanceGUID)
{
m_SelectionPools[i].AddGroup(*(itr_team[i]), maxPlayers);
if (m_SelectionPools[i].GetPlayerCount() >= minPlayers)
break;
}
}
}
//try to invite same number of players - this cycle may cause longer wait time even if there are enough players in queue, but we want ballanced bg
uint32 j = BG_TEAM_ALLIANCE;
if (m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount() < m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount())
j = BG_TEAM_HORDE;
if( sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_INVITATION_TYPE) != 0
&& m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount() >= minPlayers && m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount() >= minPlayers )
{
//we will try to invite more groups to team with less players indexed by j
++(itr_team[j]); //this will not cause a crash, because for cycle above reached break;
for(; itr_team[j] != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + j].end(); ++(itr_team[j]))
{
if (!(*(itr_team[j]))->IsInvitedToBGInstanceGUID)
if (!m_SelectionPools[j].AddGroup(*(itr_team[j]), m_SelectionPools[(j + 1) % BG_TEAMS_COUNT].GetPlayerCount()))
break;
}
// do not allow to start bg with more than 2 players more on 1 faction
if (abs((int32)(m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount() - m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount())) > 2)
return false;
}
//allow 1v0 if debug bg
if (sBattleGroundMgr.isTesting() && bg_template->isBattleGround() && (m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount() || m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount()))
return true;
//return true if there are enough players in selection pools - enable to work .debug bg command correctly
return m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount() >= minPlayers;
}
// this method will check if we can invite players to same faction skirmish match
bool BattleGroundQueue::CheckSkirmishForSameFaction(BattleGroundBracketId bracket_id, uint32 minPlayersPerTeam)
{
if (m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount() < minPlayersPerTeam && m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount() < minPlayersPerTeam)
return false;
BattleGroundTeamIndex teamIdx = BG_TEAM_ALLIANCE;
BattleGroundTeamIndex otherTeamIdx = BG_TEAM_HORDE;
Team otherTeamId = HORDE;
if (m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount() == minPlayersPerTeam )
{
teamIdx = BG_TEAM_HORDE;
otherTeamIdx = BG_TEAM_ALLIANCE;
otherTeamId = ALLIANCE;
}
//clear other team's selection
m_SelectionPools[otherTeamIdx].Init();
//store last ginfo pointer
GroupQueueInfo* ginfo = m_SelectionPools[teamIdx].SelectedGroups.back();
//set itr_team to group that was added to selection pool latest
GroupsQueueType::iterator itr_team = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].begin();
for(; itr_team != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end(); ++itr_team)
if (ginfo == *itr_team)
break;
if (itr_team == m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end())
return false;
GroupsQueueType::iterator itr_team2 = itr_team;
++itr_team2;
//invite players to other selection pool
for(; itr_team2 != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end(); ++itr_team2)
{
//if selection pool is full then break;
if (!(*itr_team2)->IsInvitedToBGInstanceGUID && !m_SelectionPools[otherTeamIdx].AddGroup(*itr_team2, minPlayersPerTeam))
break;
}
if (m_SelectionPools[otherTeamIdx].GetPlayerCount() != minPlayersPerTeam)
return false;
//here we have correct 2 selections and we need to change one teams team and move selection pool teams to other team's queue
for(GroupsQueueType::iterator itr = m_SelectionPools[otherTeamIdx].SelectedGroups.begin(); itr != m_SelectionPools[otherTeamIdx].SelectedGroups.end(); ++itr)
{
//set correct team
(*itr)->GroupTeam = otherTeamId;
//add team to other queue
m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + otherTeamIdx].push_front(*itr);
//remove team from old queue
GroupsQueueType::iterator itr2 = itr_team;
++itr2;
for(; itr2 != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end(); ++itr2)
{
if (*itr2 == *itr)
{
m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].erase(itr2);
break;
}
}
}
return true;
}
/*
this method is called when group is inserted, or player / group is removed from BG Queue - there is only one player's status changed, so we don't use while(true) cycles to invite whole queue
it must be called after fully adding the members of a group to ensure group joining
should be called from BattleGround::RemovePlayer function in some cases
*/
void BattleGroundQueue::Update(BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id, ArenaType arenaType, bool isRated, uint32 arenaRating)
{
//ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_Lock);
//if no players in queue - do nothing
if( m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty() &&
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].empty() &&
m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].empty() &&
m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].empty() )
return;
//battleground with free slot for player should be always in the beggining of the queue
// maybe it would be better to create bgfreeslotqueue for each bracket_id
BGFreeSlotQueueType::iterator itr, next;
for (itr = sBattleGroundMgr.BGFreeSlotQueue[bgTypeId].begin(); itr != sBattleGroundMgr.BGFreeSlotQueue[bgTypeId].end(); itr = next)
{
next = itr;
++next;
// DO NOT allow queue manager to invite new player to arena
if( (*itr)->isBattleGround() && (*itr)->GetTypeID() == bgTypeId && (*itr)->GetBracketId() == bracket_id &&
(*itr)->GetStatus() > STATUS_WAIT_QUEUE && (*itr)->GetStatus() < STATUS_WAIT_LEAVE )
{
BattleGround* bg = *itr; //we have to store battleground pointer here, because when battleground is full, it is removed from free queue (not yet implemented!!)
// and iterator is invalid
// clear selection pools
m_SelectionPools[BG_TEAM_ALLIANCE].Init();
m_SelectionPools[BG_TEAM_HORDE].Init();
// call a function that does the job for us
FillPlayersToBG(bg, bracket_id);
// now everything is set, invite players
for(GroupsQueueType::const_iterator citr = m_SelectionPools[BG_TEAM_ALLIANCE].SelectedGroups.begin(); citr != m_SelectionPools[BG_TEAM_ALLIANCE].SelectedGroups.end(); ++citr)
InviteGroupToBG((*citr), bg, (*citr)->GroupTeam);
for(GroupsQueueType::const_iterator citr = m_SelectionPools[BG_TEAM_HORDE].SelectedGroups.begin(); citr != m_SelectionPools[BG_TEAM_HORDE].SelectedGroups.end(); ++citr)
InviteGroupToBG((*citr), bg, (*citr)->GroupTeam);
if (!bg->HasFreeSlots())
{
// remove BG from BGFreeSlotQueue
bg->RemoveFromBGFreeSlotQueue();
}
}
}
// finished iterating through the bgs with free slots, maybe we need to create a new bg
BattleGround * bg_template = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
if (!bg_template)
{
sLog.outError("Battleground: Update: bg template not found for %u", bgTypeId);
return;
}
PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketById(bg_template->GetMapId(),bracket_id);
if (!bracketEntry)
{
sLog.outError("Battleground: Update: bg bracket entry not found for map %u bracket id %u", bg_template->GetMapId(), bracket_id);
return;
}
// get the min. players per team, properly for larger arenas as well. (must have full teams for arena matches!)
uint32 MinPlayersPerTeam = bg_template->GetMinPlayersPerTeam();
uint32 MaxPlayersPerTeam = bg_template->GetMaxPlayersPerTeam();
if (sBattleGroundMgr.isTesting())
MinPlayersPerTeam = 1;
if (bg_template->isArena())
{
if (sBattleGroundMgr.isArenaTesting())
{
MaxPlayersPerTeam = 1;
MinPlayersPerTeam = 1;
}
else
{
//this switch can be much shorter
MaxPlayersPerTeam = arenaType;
MinPlayersPerTeam = arenaType;
/*switch(arenaType)
{
case ARENA_TYPE_2v2:
MaxPlayersPerTeam = 2;
MinPlayersPerTeam = 2;
break;
case ARENA_TYPE_3v3:
MaxPlayersPerTeam = 3;
MinPlayersPerTeam = 3;
break;
case ARENA_TYPE_5v5:
MaxPlayersPerTeam = 5;
MinPlayersPerTeam = 5;
break;
}*/
}
}
m_SelectionPools[BG_TEAM_ALLIANCE].Init();
m_SelectionPools[BG_TEAM_HORDE].Init();
if (bg_template->isBattleGround())
{
//check if there is premade against premade match
if (CheckPremadeMatch(bracket_id, MinPlayersPerTeam, MaxPlayersPerTeam))
{
//create new battleground
BattleGround * bg2 = sBattleGroundMgr.CreateNewBattleGround(bgTypeId, bracketEntry, ARENA_TYPE_NONE, false);
if (!bg2)
{
sLog.outError("BattleGroundQueue::Update - Cannot create battleground: %u", bgTypeId);
return;
}
//invite those selection pools
for(uint32 i = 0; i < BG_TEAMS_COUNT; i++)
for(GroupsQueueType::const_iterator citr = m_SelectionPools[BG_TEAM_ALLIANCE + i].SelectedGroups.begin(); citr != m_SelectionPools[BG_TEAM_ALLIANCE + i].SelectedGroups.end(); ++citr)
InviteGroupToBG((*citr), bg2, (*citr)->GroupTeam);
//start bg
bg2->StartBattleGround();
//clear structures
m_SelectionPools[BG_TEAM_ALLIANCE].Init();
m_SelectionPools[BG_TEAM_HORDE].Init();
}
}
// now check if there are in queues enough players to start new game of (normal battleground, or non-rated arena)
if (!isRated)
{
// if there are enough players in pools, start new battleground or non rated arena
if (CheckNormalMatch(bg_template, bracket_id, MinPlayersPerTeam, MaxPlayersPerTeam)
|| (bg_template->isArena() && CheckSkirmishForSameFaction(bracket_id, MinPlayersPerTeam)) )
{
// we successfully created a pool
BattleGround * bg2 = sBattleGroundMgr.CreateNewBattleGround(bgTypeId, bracketEntry, arenaType, false);
if (!bg2)
{
sLog.outError("BattleGroundQueue::Update - Cannot create battleground: %u", bgTypeId);
return;
}
// invite those selection pools
for(uint32 i = 0; i < BG_TEAMS_COUNT; i++)
for(GroupsQueueType::const_iterator citr = m_SelectionPools[BG_TEAM_ALLIANCE + i].SelectedGroups.begin(); citr != m_SelectionPools[BG_TEAM_ALLIANCE + i].SelectedGroups.end(); ++citr)
InviteGroupToBG((*citr), bg2, (*citr)->GroupTeam);
// start bg
bg2->StartBattleGround();
}
}
else if (bg_template->isArena())
{
// found out the minimum and maximum ratings the newly added team should battle against
// arenaRating is the rating of the latest joined team, or 0
// 0 is on (automatic update call) and we must set it to team's with longest wait time
if (!arenaRating )
{
GroupQueueInfo* front1 = NULL;
GroupQueueInfo* front2 = NULL;
if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty())
{
front1 = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].front();
arenaRating = front1->ArenaTeamRating;
}
if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].empty())
{
front2 = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].front();
arenaRating = front2->ArenaTeamRating;
}
if (front1 && front2)
{
if (front1->JoinTime < front2->JoinTime)
arenaRating = front1->ArenaTeamRating;
}
else if (!front1 && !front2)
return; //queues are empty
}
//set rating range
uint32 arenaMinRating = (arenaRating <= sBattleGroundMgr.GetMaxRatingDifference()) ? 0 : arenaRating - sBattleGroundMgr.GetMaxRatingDifference();
uint32 arenaMaxRating = arenaRating + sBattleGroundMgr.GetMaxRatingDifference();
// if max rating difference is set and the time past since server startup is greater than the rating discard time
// (after what time the ratings aren't taken into account when making teams) then
// the discard time is current_time - time_to_discard, teams that joined after that, will have their ratings taken into account
// else leave the discard time on 0, this way all ratings will be discarded
uint32 discardTime = WorldTimer::getMSTime() - sBattleGroundMgr.GetRatingDiscardTimer();
// we need to find 2 teams which will play next game
GroupsQueueType::iterator itr_team[BG_TEAMS_COUNT];
//optimalization : --- we dont need to use selection_pools - each update we select max 2 groups
uint32 teamId = 0;
for(uint32 i = BG_QUEUE_PREMADE_ALLIANCE; i < BG_QUEUE_NORMAL_ALLIANCE; i++)
{
// take the group that joined first
itr_team[i] = m_QueuedGroups[bracket_id][i].begin();
for(; itr_team[i] != m_QueuedGroups[bracket_id][i].end(); ++(itr_team[i]))
{
// if group match conditions, then add it to pool
if( !(*itr_team[i])->IsInvitedToBGInstanceGUID
&& (((*itr_team[i])->ArenaTeamRating >= arenaMinRating && (*itr_team[i])->ArenaTeamRating <= arenaMaxRating)
|| (*itr_team[i])->JoinTime < discardTime) )
{
m_SelectionPools[i].AddGroup((*itr_team[i]), MaxPlayersPerTeam);
// break for cycle to be able to start selecting another group from same faction queue
break;
}
}
}
// now we are done if we have 2 groups - ali vs horde!
// if we don't have, we must try to continue search in same queue
// tmp variables are correctly set
// this code isn't much userfriendly - but it is supposed to continue search for mathing group in HORDE queue
if (m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount() == 0 && m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount())
{
itr_team[BG_TEAM_ALLIANCE] = itr_team[BG_TEAM_HORDE];
++itr_team[BG_TEAM_ALLIANCE];
for(; itr_team[BG_TEAM_ALLIANCE] != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].end(); ++(itr_team[BG_TEAM_ALLIANCE]))
{
if( !(*itr_team[BG_TEAM_ALLIANCE])->IsInvitedToBGInstanceGUID
&& (((*itr_team[BG_TEAM_ALLIANCE])->ArenaTeamRating >= arenaMinRating && (*itr_team[BG_TEAM_ALLIANCE])->ArenaTeamRating <= arenaMaxRating)
|| (*itr_team[BG_TEAM_ALLIANCE])->JoinTime < discardTime) )
{
if((*itr_team[BG_TEAM_ALLIANCE])->ArenaTeamId != teamId)
{
m_SelectionPools[BG_TEAM_ALLIANCE].AddGroup((*itr_team[BG_TEAM_ALLIANCE]), MaxPlayersPerTeam);
break;
}
}
}
}
// this code isn't much userfriendly - but it is supposed to continue search for mathing group in ALLIANCE queue
if (m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount() == 0 && m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount())
{
itr_team[BG_TEAM_HORDE] = itr_team[BG_TEAM_ALLIANCE];
++itr_team[BG_TEAM_HORDE];
for(; itr_team[BG_TEAM_HORDE] != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].end(); ++(itr_team[BG_TEAM_HORDE]))
{
if( !(*itr_team[BG_TEAM_HORDE])->IsInvitedToBGInstanceGUID
&& (((*itr_team[BG_TEAM_HORDE])->ArenaTeamRating >= arenaMinRating && (*itr_team[BG_TEAM_HORDE])->ArenaTeamRating <= arenaMaxRating)
|| (*itr_team[BG_TEAM_HORDE])->JoinTime < discardTime) )
{
if((*itr_team[BG_TEAM_HORDE])->ArenaTeamId != teamId)
{
m_SelectionPools[BG_TEAM_HORDE].AddGroup((*itr_team[BG_TEAM_HORDE]), MaxPlayersPerTeam);
break;
}
}
}
}
//if we have 2 teams, then start new arena and invite players!
if (m_SelectionPools[BG_TEAM_ALLIANCE].GetPlayerCount() && m_SelectionPools[BG_TEAM_HORDE].GetPlayerCount())
{
BattleGround* arena = sBattleGroundMgr.CreateNewBattleGround(bgTypeId, bracketEntry, arenaType, true);
if (!arena)
{
sLog.outError("BattlegroundQueue::Update couldn't create arena instance for rated arena match!");
return;
}
(*(itr_team[BG_TEAM_ALLIANCE]))->OpponentsTeamRating = (*(itr_team[BG_TEAM_HORDE]))->ArenaTeamRating;
DEBUG_LOG("setting oposite teamrating for team %u to %u", (*(itr_team[BG_TEAM_ALLIANCE]))->ArenaTeamId, (*(itr_team[BG_TEAM_ALLIANCE]))->OpponentsTeamRating);
(*(itr_team[BG_TEAM_HORDE]))->OpponentsTeamRating = (*(itr_team[BG_TEAM_ALLIANCE]))->ArenaTeamRating;
DEBUG_LOG("setting oposite teamrating for team %u to %u", (*(itr_team[BG_TEAM_HORDE]))->ArenaTeamId, (*(itr_team[BG_TEAM_HORDE]))->OpponentsTeamRating);
// now we must move team if we changed its faction to another faction queue, because then we will spam log by errors in Queue::RemovePlayer
if ((*(itr_team[BG_TEAM_ALLIANCE]))->GroupTeam != ALLIANCE)
{
// add to alliance queue
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].push_front(*(itr_team[BG_TEAM_ALLIANCE]));
// erase from horde queue
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].erase(itr_team[BG_TEAM_ALLIANCE]);
itr_team[BG_TEAM_ALLIANCE] = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].begin();
}
if ((*(itr_team[BG_TEAM_HORDE]))->GroupTeam != HORDE)
{
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].push_front(*(itr_team[BG_TEAM_HORDE]));
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].erase(itr_team[BG_TEAM_HORDE]);
itr_team[BG_TEAM_HORDE] = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].begin();
}
InviteGroupToBG(*(itr_team[BG_TEAM_ALLIANCE]), arena, ALLIANCE);
InviteGroupToBG(*(itr_team[BG_TEAM_HORDE]), arena, HORDE);
DEBUG_LOG("Starting rated arena match!");
arena->StartBattleGround();
}
}
}
/*********************************************************/
/*** BATTLEGROUND QUEUE EVENTS ***/
/*********************************************************/
bool BGQueueInviteEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
{
Player* plr = sObjectMgr.GetPlayer( m_PlayerGuid );
// player logged off (we should do nothing, he is correctly removed from queue in another procedure)
if (!plr)
return true;
BattleGround* bg = sBattleGroundMgr.GetBattleGround(m_BgInstanceGUID, m_BgTypeId);
//if battleground ended and its instance deleted - do nothing
if (!bg)
return true;
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bg->GetTypeID(), bg->GetArenaType());
uint32 queueSlot = plr->GetBattleGroundQueueIndex(bgQueueTypeId);
if (queueSlot < PLAYER_MAX_BATTLEGROUND_QUEUES) // player is in queue or in battleground
{
// check if player is invited to this bg
BattleGroundQueue &bgQueue = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId];
if (bgQueue.IsPlayerInvited(m_PlayerGuid, m_BgInstanceGUID, m_RemoveTime))
{
WorldPacket data;
//we must send remaining time in queue
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME - INVITATION_REMIND_TIME, 0, m_ArenaType);
plr->GetSession()->SendPacket(&data);
}
}
return true; //event will be deleted
}
void BGQueueInviteEvent::Abort(uint64 /*e_time*/)
{
//do nothing
}
/*
this event has many possibilities when it is executed:
1. player is in battleground ( he clicked enter on invitation window )
2. player left battleground queue and he isn't there any more
3. player left battleground queue and he joined it again and IsInvitedToBGInstanceGUID = 0
4. player left queue and he joined again and he has been invited to same battleground again -> we should not remove him from queue yet
5. player is invited to bg and he didn't choose what to do and timer expired - only in this condition we should call queue::RemovePlayer
we must remove player in the 5. case even if battleground object doesn't exist!
*/
bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
{
Player* plr = sObjectMgr.GetPlayer( m_PlayerGuid );
if (!plr)
// player logged off (we should do nothing, he is correctly removed from queue in another procedure)
return true;
BattleGround* bg = sBattleGroundMgr.GetBattleGround(m_BgInstanceGUID, m_BgTypeId);
//battleground can be deleted already when we are removing queue info
//bg pointer can be NULL! so use it carefully!
uint32 queueSlot = plr->GetBattleGroundQueueIndex(m_BgQueueTypeId);
if (queueSlot < PLAYER_MAX_BATTLEGROUND_QUEUES) // player is in queue, or in Battleground
{
// check if player is in queue for this BG and if we are removing his invite event
BattleGroundQueue &bgQueue = sBattleGroundMgr.m_BattleGroundQueues[m_BgQueueTypeId];
if (bgQueue.IsPlayerInvited(m_PlayerGuid, m_BgInstanceGUID, m_RemoveTime))
{
DEBUG_LOG("Battleground: removing player %u from bg queue for instance %u because of not pressing enter battle in time.",plr->GetGUIDLow(),m_BgInstanceGUID);
plr->RemoveBattleGroundQueueId(m_BgQueueTypeId);
bgQueue.RemovePlayer(m_PlayerGuid, true);
//update queues if battleground isn't ended
if (bg && bg->isBattleGround() && bg->GetStatus() != STATUS_WAIT_LEAVE)
sBattleGroundMgr.ScheduleQueueUpdate(0, ARENA_TYPE_NONE, m_BgQueueTypeId, m_BgTypeId, bg->GetBracketId());
WorldPacket data;
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, ARENA_TYPE_NONE);
plr->GetSession()->SendPacket(&data);
}
}
//event will be deleted
return true;
}
void BGQueueRemoveEvent::Abort(uint64 /*e_time*/)
{
//do nothing
}
/*********************************************************/
/*** BATTLEGROUND MANAGER ***/
/*********************************************************/
BattleGroundMgr::BattleGroundMgr() : m_AutoDistributionTimeChecker(0), m_ArenaTesting(false)
{
for(uint32 i = BATTLEGROUND_TYPE_NONE; i < MAX_BATTLEGROUND_TYPE_ID; i++)
m_BattleGrounds[i].clear();
m_NextRatingDiscardUpdate = sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER);
m_Testing=false;
}
BattleGroundMgr::~BattleGroundMgr()
{
DeleteAllBattleGrounds();
}
void BattleGroundMgr::DeleteAllBattleGrounds()
{
// will also delete template bgs:
for(uint32 i = BATTLEGROUND_TYPE_NONE; i < MAX_BATTLEGROUND_TYPE_ID; i++)
{
for(BattleGroundSet::iterator itr = m_BattleGrounds[i].begin(); itr != m_BattleGrounds[i].end();)
{
BattleGround * bg = itr->second;
itr++;
delete bg;
}
}
}
// used to update running battlegrounds, and delete finished ones
void BattleGroundMgr::Update(uint32 diff)
{
// update scheduled queues
if (!m_QueueUpdateScheduler.empty())
{
std::vector<uint64> scheduled;
{
//create mutex
//ACE_Guard<ACE_Thread_Mutex> guard(SchedulerLock);
//copy vector and clear the other
scheduled = std::vector<uint64>(m_QueueUpdateScheduler);
m_QueueUpdateScheduler.clear();
//release lock
}
for (uint8 i = 0; i < scheduled.size(); i++)
{
uint32 arenaRating = scheduled[i] >> 32;
ArenaType arenaType = ArenaType(scheduled[i] >> 24 & 255);
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundQueueTypeId(scheduled[i] >> 16 & 255);
BattleGroundTypeId bgTypeId = BattleGroundTypeId((scheduled[i] >> 8) & 255);
BattleGroundBracketId bracket_id = BattleGroundBracketId(scheduled[i] & 255);
m_BattleGroundQueues[bgQueueTypeId].Update(bgTypeId, bracket_id, arenaType, arenaRating > 0, arenaRating);
}
}
// if rating difference counts, maybe force-update queues
if (sWorld.getConfig(CONFIG_UINT32_ARENA_MAX_RATING_DIFFERENCE) && sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER))
{
// it's time to force update
if (m_NextRatingDiscardUpdate < diff)
{
// forced update for rated arenas (scan all, but skipped non rated)
DEBUG_LOG("BattleGroundMgr: UPDATING ARENA QUEUES");
for(int qtype = BATTLEGROUND_QUEUE_2v2; qtype <= BATTLEGROUND_QUEUE_5v5; ++qtype)
for(int bracket = BG_BRACKET_ID_FIRST; bracket < MAX_BATTLEGROUND_BRACKETS; ++bracket)
m_BattleGroundQueues[qtype].Update(
BATTLEGROUND_AA, BattleGroundBracketId(bracket),
BattleGroundMgr::BGArenaType(BattleGroundQueueTypeId(qtype)), true, 0);
m_NextRatingDiscardUpdate = sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER);
}
else
m_NextRatingDiscardUpdate -= diff;
}
if (sWorld.getConfig(CONFIG_BOOL_ARENA_AUTO_DISTRIBUTE_POINTS))
{
if (m_AutoDistributionTimeChecker < diff)
{
if (sWorld.GetGameTime() > m_NextAutoDistributionTime)
{
DistributeArenaPoints();
m_NextAutoDistributionTime = time_t(sWorld.GetGameTime() + BATTLEGROUND_ARENA_POINT_DISTRIBUTION_DAY * sWorld.getConfig(CONFIG_UINT32_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS));
CharacterDatabase.PExecute("UPDATE saved_variables SET NextArenaPointDistributionTime = '"UI64FMTD"'", uint64(m_NextAutoDistributionTime));
}
m_AutoDistributionTimeChecker = 600000; // check 10 minutes
}
else
m_AutoDistributionTimeChecker -= diff;
}
}
void BattleGroundMgr::BuildBattleGroundStatusPacket(WorldPacket *data, BattleGround *bg, uint8 QueueSlot, uint8 StatusID, uint32 Time1, uint32 Time2, ArenaType arenatype)
{
// we can be in 2 queues in same time...
if (StatusID == 0 || !bg)
{
data->Initialize(SMSG_BATTLEFIELD_STATUS, 4+8);
*data << uint32(QueueSlot); // queue id (0...1)
*data << uint64(0);
return;
}
data->Initialize(SMSG_BATTLEFIELD_STATUS, (4+8+1+1+4+1+4+4+4));
*data << uint32(QueueSlot); // queue id (0...1) - player can be in 2 queues in time
// uint64 in client
*data << uint64( uint64(arenatype) | (uint64(0x0D) << 8) | (uint64(bg->GetTypeID()) << 16) | (uint64(0x1F90) << 48) );
*data << uint8(0); // 3.3.0, some level, only saw 80...
*data << uint8(0); // 3.3.0, some level, only saw 80...
*data << uint32(bg->GetClientInstanceID());
// alliance/horde for BG and skirmish/rated for Arenas
// following displays the minimap-icon 0 = faction icon 1 = arenaicon
*data << uint8(bg->isRated());
*data << uint32(StatusID); // status
switch(StatusID)
{
case STATUS_WAIT_QUEUE: // status_in_queue
*data << uint32(Time1); // average wait time, milliseconds
*data << uint32(Time2); // time in queue, updated every minute!, milliseconds
break;
case STATUS_WAIT_JOIN: // status_invite
*data << uint32(bg->GetMapId()); // map id
*data << uint64(0); // 3.3.5, unknown
*data << uint32(Time1); // time to remove from queue, milliseconds
break;
case STATUS_IN_PROGRESS: // status_in_progress
*data << uint32(bg->GetMapId()); // map id
*data << uint64(0); // 3.3.5, unknown
*data << uint32(Time1); // time to bg auto leave, 0 at bg start, 120000 after bg end, milliseconds
*data << uint32(Time2); // time from bg start, milliseconds
*data << uint8(0x1); // Lua_GetBattlefieldArenaFaction (bool)
break;
default:
sLog.outError("Unknown BG status!");
break;
}
}
void BattleGroundMgr::BuildPvpLogDataPacket(WorldPacket *data, BattleGround *bg)
{
uint8 type = (bg->isArena() ? 1 : 0);
// last check on 3.0.3
data->Initialize(MSG_PVP_LOG_DATA, (1+1+4+40*bg->GetPlayerScoresSize()));
*data << uint8(type); // type (battleground=0/arena=1)
if(type) // arena
{
// it seems this must be according to BG_WINNER_A/H and _NOT_ BG_TEAM_A/H
for(int i = 1; i >= 0; --i)
{
uint32 pointsLost = bg->m_ArenaTeamRatingChanges[i] < 0 ? abs(bg->m_ArenaTeamRatingChanges[i]) : 0;
uint32 pointsGained = bg->m_ArenaTeamRatingChanges[i] > 0 ? bg->m_ArenaTeamRatingChanges[i] : 0;
*data << uint32(pointsLost); // Rating Lost
*data << uint32(pointsGained); // Rating gained
*data << uint32(0); // Matchmaking Value
DEBUG_LOG("rating change: %d", bg->m_ArenaTeamRatingChanges[i]);
}
for(int i = 1; i >= 0; --i)
{
uint32 at_id = bg->m_ArenaTeamIds[i];
ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id);
if (at)
*data << at->GetName();
else
*data << (uint8)0;
}
}
if (bg->GetStatus() != STATUS_WAIT_LEAVE)
{
*data << uint8(0); // bg not ended
}
else
{
*data << uint8(1); // bg ended
*data << uint8(bg->GetWinner()); // who win
}
*data << (int32)(bg->GetPlayerScoresSize());
for(BattleGround::BattleGroundScoreMap::const_iterator itr = bg->GetPlayerScoresBegin(); itr != bg->GetPlayerScoresEnd(); ++itr)
{
*data << ObjectGuid(itr->first);
*data << (int32)itr->second->KillingBlows;
if (type == 0)
{
*data << (int32)itr->second->HonorableKills;
*data << (int32)itr->second->Deaths;
*data << (int32)(itr->second->BonusHonor);
}
else
{
Player *plr = sObjectMgr.GetPlayer(itr->first);
Team team = bg->GetPlayerTeam(itr->first);
if (!team && plr)
team = plr->GetTeam();
if (( bg->GetWinner()==0 && team == ALLIANCE ) || ( bg->GetWinner()==1 && team==HORDE ))
*data << uint8(1);
else
*data << uint8(0);
}
*data << (int32)itr->second->DamageDone; // damage done
*data << (int32)itr->second->HealingDone; // healing done
switch(bg->GetTypeID(true)) // battleground specific things
{
case BATTLEGROUND_AV:
*data << (uint32)0x00000005; // count of next fields
*data << (uint32)((BattleGroundAVScore*)itr->second)->GraveyardsAssaulted; // GraveyardsAssaulted
*data << (uint32)((BattleGroundAVScore*)itr->second)->GraveyardsDefended; // GraveyardsDefended
*data << (uint32)((BattleGroundAVScore*)itr->second)->TowersAssaulted; // TowersAssaulted
*data << (uint32)((BattleGroundAVScore*)itr->second)->TowersDefended; // TowersDefended
*data << (uint32)((BattleGroundAVScore*)itr->second)->SecondaryObjectives; // SecondaryObjectives - free some of the Lieutnants
break;
case BATTLEGROUND_WS:
*data << (uint32)0x00000002; // count of next fields
*data << (uint32)((BattleGroundWGScore*)itr->second)->FlagCaptures; // flag captures
*data << (uint32)((BattleGroundWGScore*)itr->second)->FlagReturns; // flag returns
break;
case BATTLEGROUND_AB:
*data << (uint32)0x00000002; // count of next fields
*data << (uint32)((BattleGroundABScore*)itr->second)->BasesAssaulted; // bases asssulted
*data << (uint32)((BattleGroundABScore*)itr->second)->BasesDefended; // bases defended
break;
case BATTLEGROUND_EY:
*data << (uint32)0x00000001; // count of next fields
*data << (uint32)((BattleGroundEYScore*)itr->second)->FlagCaptures; // flag captures
break;
case BATTLEGROUND_SA:
*data << (uint32)0x00000002; // count of next fields
*data << (uint32)((BattleGroundSAScore*)itr->second)->DemolishersDestroyed; // demolishers destroyed
*data << (uint32)((BattleGroundSAScore*)itr->second)->GatesDestroyed; // gates destroyed
break;
case BATTLEGROUND_NA:
case BATTLEGROUND_BE:
case BATTLEGROUND_AA:
case BATTLEGROUND_RL:
case BATTLEGROUND_DS: // wotlk
case BATTLEGROUND_RV: // wotlk
case BATTLEGROUND_IC: // wotlk
case BATTLEGROUND_RB: // wotlk
*data << (int32)0; // 0
break;
default:
sLog.outDebug("Unhandled MSG_PVP_LOG_DATA for BG id %u", bg->GetTypeID(true));
*data << (int32)0;
break;
}
}
}
void BattleGroundMgr::BuildGroupJoinedBattlegroundPacket(WorldPacket *data, GroupJoinBattlegroundResult result)
{
data->Initialize(SMSG_GROUP_JOINED_BATTLEGROUND, 4);
*data << int32(result);
if(result == ERR_BATTLEGROUND_JOIN_TIMED_OUT || result == ERR_BATTLEGROUND_JOIN_FAILED)
*data << uint64(0); // player guid
}
void BattleGroundMgr::BuildUpdateWorldStatePacket(WorldPacket *data, uint32 field, uint32 value)
{
data->Initialize(SMSG_UPDATE_WORLD_STATE, 4+4);
*data << uint32(field);
*data << uint32(value);
}
void BattleGroundMgr::BuildPlaySoundPacket(WorldPacket *data, uint32 soundid)
{
data->Initialize(SMSG_PLAY_SOUND, 4);
*data << uint32(soundid);
}
void BattleGroundMgr::BuildPlayerLeftBattleGroundPacket(WorldPacket *data, ObjectGuid guid)
{
data->Initialize(SMSG_BATTLEGROUND_PLAYER_LEFT, 8);
*data << ObjectGuid(guid);
}
void BattleGroundMgr::BuildPlayerJoinedBattleGroundPacket(WorldPacket *data, Player *plr)
{
data->Initialize(SMSG_BATTLEGROUND_PLAYER_JOINED, 8);
*data << plr->GetObjectGuid();
}
BattleGround * BattleGroundMgr::GetBattleGroundThroughClientInstance(uint32 instanceId, BattleGroundTypeId bgTypeId)
{
//cause at HandleBattleGroundJoinOpcode the clients sends the instanceid he gets from
//SMSG_BATTLEFIELD_LIST we need to find the battleground with this clientinstance-id
BattleGround* bg = GetBattleGroundTemplate(bgTypeId);
if (!bg)
return NULL;
if (bg->isArena())
return GetBattleGround(instanceId, bgTypeId);
for(BattleGroundSet::iterator itr = m_BattleGrounds[bgTypeId].begin(); itr != m_BattleGrounds[bgTypeId].end(); ++itr)
{
if (itr->second->GetClientInstanceID() == instanceId)
return itr->second;
}
return NULL;
}
BattleGround * BattleGroundMgr::GetBattleGround(uint32 InstanceID, BattleGroundTypeId bgTypeId)
{
//search if needed
BattleGroundSet::iterator itr;
if (bgTypeId == BATTLEGROUND_TYPE_NONE)
{
for(uint32 i = BATTLEGROUND_AV; i < MAX_BATTLEGROUND_TYPE_ID; i++)
{
itr = m_BattleGrounds[i].find(InstanceID);
if (itr != m_BattleGrounds[i].end())
return itr->second;
}
return NULL;
}
itr = m_BattleGrounds[bgTypeId].find(InstanceID);
return ( (itr != m_BattleGrounds[bgTypeId].end()) ? itr->second : NULL );
}
BattleGround * BattleGroundMgr::GetBattleGroundTemplate(BattleGroundTypeId bgTypeId)
{
//map is sorted and we can be sure that lowest instance id has only BG template
return m_BattleGrounds[bgTypeId].empty() ? NULL : m_BattleGrounds[bgTypeId].begin()->second;
}
uint32 BattleGroundMgr::CreateClientVisibleInstanceId(BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id)
{
if (IsArenaType(bgTypeId))
return 0; //arenas don't have client-instanceids
// we create here an instanceid, which is just for
// displaying this to the client and without any other use..
// the client-instanceIds are unique for each battleground-type
// the instance-id just needs to be as low as possible, beginning with 1
// the following works, because std::set is default ordered with "<"
// the optimalization would be to use as bitmask std::vector<uint32> - but that would only make code unreadable
uint32 lastId = 0;
for(std::set<uint32>::iterator itr = m_ClientBattleGroundIds[bgTypeId][bracket_id].begin(); itr != m_ClientBattleGroundIds[bgTypeId][bracket_id].end();)
{
if( (++lastId) != *itr) //if there is a gap between the ids, we will break..
break;
lastId = *itr;
}
m_ClientBattleGroundIds[bgTypeId][bracket_id].insert(lastId + 1);
return lastId + 1;
}
// create a new battleground that will really be used to play
BattleGround * BattleGroundMgr::CreateNewBattleGround(BattleGroundTypeId bgTypeId, PvPDifficultyEntry const* bracketEntry, ArenaType arenaType, bool isRated)
{
// get the template BG
BattleGround *bg_template = GetBattleGroundTemplate(bgTypeId);
if (!bg_template)
{
sLog.outError("BattleGround: CreateNewBattleGround - bg template not found for %u", bgTypeId);
return NULL;
}
//for arenas there is random map used
if (bg_template->isArena())
{
BattleGroundTypeId arenas[] = {BATTLEGROUND_NA, BATTLEGROUND_BE, BATTLEGROUND_RL, BATTLEGROUND_DS, BATTLEGROUND_RV};
uint32 arena_num = urand(0,4);
bgTypeId = arenas[arena_num];
bg_template = GetBattleGroundTemplate(bgTypeId);
if (!bg_template)
{
sLog.outError("BattleGround: CreateNewBattleGround - bg template not found for %u", bgTypeId);
return NULL;
}
}
bool isRandom = false;
if(bgTypeId==BATTLEGROUND_RB)
{
BattleGroundTypeId random_bgs[] = {BATTLEGROUND_AV, BATTLEGROUND_WS, BATTLEGROUND_AB, BATTLEGROUND_EY/*, BATTLEGROUND_SA*/ /*,BATTLEGROUND_IC*/};
uint32 bg_num = urand(0, sizeof(random_bgs)/sizeof(BattleGroundTypeId)-1);
bgTypeId = random_bgs[bg_num];
bg_template = GetBattleGroundTemplate(bgTypeId);
if (!bg_template)
{
sLog.outError("BattleGround: CreateNewBattleGround - bg template not found for %u", bgTypeId);
return NULL;
}
isRandom = true;
}
BattleGround *bg = NULL;
// create a copy of the BG template
switch(bgTypeId)
{
case BATTLEGROUND_AV:
bg = new BattleGroundAV(*(BattleGroundAV*)bg_template);
break;
case BATTLEGROUND_WS:
bg = new BattleGroundWS(*(BattleGroundWS*)bg_template);
break;
case BATTLEGROUND_AB:
bg = new BattleGroundAB(*(BattleGroundAB*)bg_template);
break;
case BATTLEGROUND_NA:
bg = new BattleGroundNA(*(BattleGroundNA*)bg_template);
break;
case BATTLEGROUND_BE:
bg = new BattleGroundBE(*(BattleGroundBE*)bg_template);
break;
case BATTLEGROUND_AA:
bg = new BattleGroundAA(*(BattleGroundAA*)bg_template);
break;
case BATTLEGROUND_EY:
bg = new BattleGroundEY(*(BattleGroundEY*)bg_template);
break;
case BATTLEGROUND_RL:
bg = new BattleGroundRL(*(BattleGroundRL*)bg_template);
break;
case BATTLEGROUND_SA:
bg = new BattleGroundSA(*(BattleGroundSA*)bg_template);
break;
case BATTLEGROUND_DS:
bg = new BattleGroundDS(*(BattleGroundDS*)bg_template);
break;
case BATTLEGROUND_RV:
bg = new BattleGroundRV(*(BattleGroundRV*)bg_template);
break;
case BATTLEGROUND_IC:
bg = new BattleGroundIC(*(BattleGroundIC*)bg_template);
break;
case BATTLEGROUND_RB:
bg = new BattleGroundRB(*(BattleGroundRB*)bg_template);
break;
default:
//error, but it is handled few lines above
return 0;
}
// set before Map creating for let use proper difficulty
bg->SetBracket(bracketEntry);
// will also set m_bgMap, instanceid
sMapMgr.CreateBgMap(bg->GetMapId(), bg);
bg->SetClientInstanceID(CreateClientVisibleInstanceId(isRandom ? BATTLEGROUND_RB : bgTypeId, bracketEntry->GetBracketId()));
// reset the new bg (set status to status_wait_queue from status_none)
bg->Reset();
// start the joining of the bg
bg->SetStatus(STATUS_WAIT_JOIN);
bg->SetArenaType(arenaType);
bg->SetRated(isRated);
bg->SetRandom(isRandom);
bg->SetTypeID(isRandom ? BATTLEGROUND_RB : bgTypeId);
bg->SetRandomTypeID(bgTypeId);
return bg;
}
// used to create the BG templates
uint32 BattleGroundMgr::CreateBattleGround(BattleGroundTypeId bgTypeId, bool IsArena, uint32 MinPlayersPerTeam, uint32 MaxPlayersPerTeam, uint32 LevelMin, uint32 LevelMax, char const* BattleGroundName, uint32 MapID, float Team1StartLocX, float Team1StartLocY, float Team1StartLocZ, float Team1StartLocO, float Team2StartLocX, float Team2StartLocY, float Team2StartLocZ, float Team2StartLocO)
{
// Create the BG
BattleGround *bg = NULL;
switch(bgTypeId)
{
case BATTLEGROUND_AV: bg = new BattleGroundAV; break;
case BATTLEGROUND_WS: bg = new BattleGroundWS; break;
case BATTLEGROUND_AB: bg = new BattleGroundAB; break;
case BATTLEGROUND_NA: bg = new BattleGroundNA; break;
case BATTLEGROUND_BE: bg = new BattleGroundBE; break;
case BATTLEGROUND_AA: bg = new BattleGroundAA; break;
case BATTLEGROUND_EY: bg = new BattleGroundEY; break;
case BATTLEGROUND_RL: bg = new BattleGroundRL; break;
case BATTLEGROUND_SA: bg = new BattleGroundSA; break;
case BATTLEGROUND_DS: bg = new BattleGroundDS; break;
case BATTLEGROUND_RV: bg = new BattleGroundRV; break;
case BATTLEGROUND_IC: bg = new BattleGroundIC; break;
case BATTLEGROUND_RB: bg = new BattleGroundRB; break;
default:bg = new BattleGround; break; // placeholder for non implemented BG
}
bg->SetMapId(MapID);
bg->SetTypeID(bgTypeId);
bg->SetArenaorBGType(IsArena);
bg->SetMinPlayersPerTeam(MinPlayersPerTeam);
bg->SetMaxPlayersPerTeam(MaxPlayersPerTeam);
bg->SetMinPlayers(MinPlayersPerTeam * 2);
bg->SetMaxPlayers(MaxPlayersPerTeam * 2);
bg->SetName(BattleGroundName);
bg->SetTeamStartLoc(ALLIANCE, Team1StartLocX, Team1StartLocY, Team1StartLocZ, Team1StartLocO);
bg->SetTeamStartLoc(HORDE, Team2StartLocX, Team2StartLocY, Team2StartLocZ, Team2StartLocO);
bg->SetLevelRange(LevelMin, LevelMax);
// add bg to update list
AddBattleGround(bg->GetInstanceID(), bg->GetTypeID(), bg);
// return some not-null value, bgTypeId is good enough for me
return bgTypeId;
}
void BattleGroundMgr::CreateInitialBattleGrounds()
{
uint32 count = 0;
// 0 1 2 3 4 5 6
QueryResult *result = WorldDatabase.Query("SELECT id, MinPlayersPerTeam,MaxPlayersPerTeam,AllianceStartLoc,AllianceStartO,HordeStartLoc,HordeStartO FROM battleground_template");
if (!result)
{
barGoLink bar(1);
bar.step();
sLog.outString();
sLog.outErrorDb(">> Loaded 0 battlegrounds. DB table `battleground_template` is empty.");
return;
}
barGoLink bar((int)result->GetRowCount());
do
{
Field *fields = result->Fetch();
bar.step();
uint32 bgTypeID_ = fields[0].GetUInt32();
// can be overwrite by values from DB
BattlemasterListEntry const *bl = sBattlemasterListStore.LookupEntry(bgTypeID_);
if (!bl)
{
sLog.outError("Battleground ID %u not found in BattlemasterList.dbc. Battleground not created.", bgTypeID_);
continue;
}
BattleGroundTypeId bgTypeID = BattleGroundTypeId(bgTypeID_);
bool IsArena = (bl->type == TYPE_ARENA);
uint32 MinPlayersPerTeam = fields[1].GetUInt32();
uint32 MaxPlayersPerTeam = fields[2].GetUInt32();
//check values from DB
if (MaxPlayersPerTeam == 0 || MinPlayersPerTeam == 0)
{
sLog.outErrorDb("Table `battleground_template` for id %u have wrong min/max players per team settings. BG not created.", bgTypeID);
continue;
}
if (MinPlayersPerTeam > MaxPlayersPerTeam)
MinPlayersPerTeam = MaxPlayersPerTeam;
float AStartLoc[4];
float HStartLoc[4];
uint32 start1 = fields[3].GetUInt32();
WorldSafeLocsEntry const *start = sWorldSafeLocsStore.LookupEntry(start1);
if (start)
{
AStartLoc[0] = start->x;
AStartLoc[1] = start->y;
AStartLoc[2] = start->z;
AStartLoc[3] = fields[4].GetFloat();
}
else if (bgTypeID == BATTLEGROUND_AA || bgTypeID == BATTLEGROUND_RB)
{
AStartLoc[0] = 0;
AStartLoc[1] = 0;
AStartLoc[2] = 0;
AStartLoc[3] = fields[4].GetFloat();
}
else
{
sLog.outErrorDb("Table `battleground_template` for id %u have nonexistent WorldSafeLocs.dbc id %u in field `AllianceStartLoc`. BG not created.", bgTypeID, start1);
continue;
}
uint32 start2 = fields[5].GetUInt32();
start = sWorldSafeLocsStore.LookupEntry(start2);
if (start)
{
HStartLoc[0] = start->x;
HStartLoc[1] = start->y;
HStartLoc[2] = start->z;
HStartLoc[3] = fields[6].GetFloat();
}
else if (bgTypeID == BATTLEGROUND_AA || bgTypeID == BATTLEGROUND_RB)
{
HStartLoc[0] = 0;
HStartLoc[1] = 0;
HStartLoc[2] = 0;
HStartLoc[3] = fields[6].GetFloat();
}
else
{
sLog.outErrorDb("Table `battleground_template` for id %u have nonexistent WorldSafeLocs.dbc id %u in field `HordeStartLoc`. BG not created.", bgTypeID, start2);
continue;
}
//sLog.outDetail("Creating battleground %s, %u-%u", bl->name[sWorld.GetDBClang()], MinLvl, MaxLvl);
if (!CreateBattleGround(bgTypeID, IsArena, MinPlayersPerTeam, MaxPlayersPerTeam, bl->minLevel, bl->maxLevel, bl->name[sWorld.GetDefaultDbcLocale()], bl->mapid[0], AStartLoc[0], AStartLoc[1], AStartLoc[2], AStartLoc[3], HStartLoc[0], HStartLoc[1], HStartLoc[2], HStartLoc[3]))
continue;
++count;
} while (result->NextRow());
delete result;
sLog.outString();
sLog.outString( ">> Loaded %u battlegrounds", count );
}
void BattleGroundMgr::InitAutomaticArenaPointDistribution()
{
if (sWorld.getConfig(CONFIG_BOOL_ARENA_AUTO_DISTRIBUTE_POINTS))
{
DEBUG_LOG("Initializing Automatic Arena Point Distribution");
QueryResult * result = CharacterDatabase.Query("SELECT NextArenaPointDistributionTime FROM saved_variables");
if (!result)
{
DEBUG_LOG("Battleground: Next arena point distribution time not found in SavedVariables, reseting it now.");
m_NextAutoDistributionTime = time_t(sWorld.GetGameTime() + BATTLEGROUND_ARENA_POINT_DISTRIBUTION_DAY * sWorld.getConfig(CONFIG_UINT32_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS));
CharacterDatabase.PExecute("INSERT INTO saved_variables (NextArenaPointDistributionTime) VALUES ('"UI64FMTD"')", uint64(m_NextAutoDistributionTime));
}
else
{
m_NextAutoDistributionTime = time_t((*result)[0].GetUInt64());
delete result;
}
DEBUG_LOG("Automatic Arena Point Distribution initialized.");
}
}
void BattleGroundMgr::DistributeArenaPoints()
{
// used to distribute arena points based on last week's stats
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_START);
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_ONLINE_START);
//temporary structure for storing maximum points to add values for all players
std::map<uint32, uint32> PlayerPoints;
//at first update all points for all team members
for(ObjectMgr::ArenaTeamMap::iterator team_itr = sObjectMgr.GetArenaTeamMapBegin(); team_itr != sObjectMgr.GetArenaTeamMapEnd(); ++team_itr)
{
if (ArenaTeam * at = team_itr->second)
{
at->UpdateArenaPointsHelper(PlayerPoints);
}
}
//cycle that gives points to all players
for (std::map<uint32, uint32>::iterator plr_itr = PlayerPoints.begin(); plr_itr != PlayerPoints.end(); ++plr_itr)
{
//update to database
CharacterDatabase.PExecute("UPDATE characters SET arenaPoints = arenaPoints + '%u' WHERE guid = '%u'", plr_itr->second, plr_itr->first);
//add points if player is online
if (Player* pl = sObjectMgr.GetPlayer(ObjectGuid(HIGHGUID_PLAYER, plr_itr->first)))
pl->ModifyArenaPoints(plr_itr->second);
}
PlayerPoints.clear();
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_ONLINE_END);
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_TEAM_START);
for(ObjectMgr::ArenaTeamMap::iterator titr = sObjectMgr.GetArenaTeamMapBegin(); titr != sObjectMgr.GetArenaTeamMapEnd(); ++titr)
{
if (ArenaTeam * at = titr->second)
{
at->FinishWeek(); // set played this week etc values to 0 in memory, too
at->SaveToDB(); // save changes
at->NotifyStatsChanged(); // notify the players of the changes
}
}
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_TEAM_END);
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_END);
}
void BattleGroundMgr::BuildBattleGroundListPacket(WorldPacket *data, ObjectGuid guid, Player* plr, BattleGroundTypeId bgTypeId, uint8 fromWhere)
{
if (!plr)
return;
uint32 win_kills = plr->GetRandomWinner() ? BG_REWARD_WINNER_HONOR_LAST : BG_REWARD_WINNER_HONOR_FIRST;
uint32 win_arena = plr->GetRandomWinner() ? BG_REWARD_WINNER_ARENA_LAST : BG_REWARD_WINNER_ARENA_FIRST;
uint32 loos_kills = plr->GetRandomWinner() ? BG_REWARD_LOOSER_HONOR_LAST : BG_REWARD_LOOSER_HONOR_FIRST;
win_kills = (uint32)MaNGOS::Honor::hk_honor_at_level(plr->getLevel(), win_kills*4);
loos_kills = (uint32)MaNGOS::Honor::hk_honor_at_level(plr->getLevel(), loos_kills*4);
data->Initialize(SMSG_BATTLEFIELD_LIST);
*data << guid; // battlemaster guid
*data << uint8(fromWhere); // from where you joined
*data << uint32(bgTypeId); // battleground id
*data << uint8(0); // unk
*data << uint8(0); // unk
// Rewards
*data << uint8( plr->GetRandomWinner() ); // 3.3.3 hasWin
*data << uint32( win_kills ); // 3.3.3 winHonor
*data << uint32( win_arena ); // 3.3.3 winArena
*data << uint32( loos_kills ); // 3.3.3 lossHonor
uint8 isRandom = bgTypeId == BATTLEGROUND_RB;
*data << uint8(isRandom); // 3.3.3 isRandom
if(isRandom)
{
// Rewards (random)
*data << uint8( plr->GetRandomWinner() ); // 3.3.3 hasWin_Random
*data << uint32( win_kills ); // 3.3.3 winHonor_Random
*data << uint32( win_arena ); // 3.3.3 winArena_Random
*data << uint32( loos_kills ); // 3.3.3 lossHonor_Random
}
if(bgTypeId == BATTLEGROUND_AA) // arena
{
*data << uint32(0); // arena - no instances showed
}
else // battleground
{
size_t count_pos = data->wpos();
uint32 count = 0;
*data << uint32(0); // number of bg instances
if(BattleGround* bgTemplate = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId))
{
// expected bracket entry
if(PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bgTemplate->GetMapId(),plr->getLevel()))
{
BattleGroundBracketId bracketId = bracketEntry->GetBracketId();
for(std::set<uint32>::iterator itr = m_ClientBattleGroundIds[bgTypeId][bracketId].begin(); itr != m_ClientBattleGroundIds[bgTypeId][bracketId].end();++itr)
{
*data << uint32(*itr);
++count;
}
data->put<uint32>( count_pos , count);
}
}
}
}
void BattleGroundMgr::SendToBattleGround(Player *pl, uint32 instanceId, BattleGroundTypeId bgTypeId)
{
BattleGround *bg = GetBattleGround(instanceId, bgTypeId);
if (bg)
{
uint32 mapid = bg->GetMapId();
float x, y, z, O;
Team team = pl->GetBGTeam();
if (team==0)
team = pl->GetTeam();
bg->GetTeamStartLoc(team, x, y, z, O);
DETAIL_LOG("BATTLEGROUND: Sending %s to map %u, X %f, Y %f, Z %f, O %f", pl->GetName(), mapid, x, y, z, O);
pl->TeleportTo(mapid, x, y, z, O);
}
else
{
sLog.outError("player %u trying to port to nonexistent bg instance %u",pl->GetGUIDLow(), instanceId);
}
}
bool BattleGroundMgr::IsArenaType(BattleGroundTypeId bgTypeId)
{
return ( bgTypeId == BATTLEGROUND_AA ||
bgTypeId == BATTLEGROUND_BE ||
bgTypeId == BATTLEGROUND_NA ||
bgTypeId == BATTLEGROUND_RL ||
bgTypeId == BATTLEGROUND_DS ||
bgTypeId == BATTLEGROUND_RV );
}
BattleGroundQueueTypeId BattleGroundMgr::BGQueueTypeId(BattleGroundTypeId bgTypeId, ArenaType arenaType)
{
switch(bgTypeId)
{
case BATTLEGROUND_WS:
return BATTLEGROUND_QUEUE_WS;
case BATTLEGROUND_AB:
return BATTLEGROUND_QUEUE_AB;
case BATTLEGROUND_AV:
return BATTLEGROUND_QUEUE_AV;
case BATTLEGROUND_EY:
return BATTLEGROUND_QUEUE_EY;
case BATTLEGROUND_SA:
return BATTLEGROUND_QUEUE_SA;
case BATTLEGROUND_IC:
return BATTLEGROUND_QUEUE_IC;
case BATTLEGROUND_RB:
return BATTLEGROUND_QUEUE_RB;
case BATTLEGROUND_AA:
case BATTLEGROUND_NA:
case BATTLEGROUND_RL:
case BATTLEGROUND_BE:
case BATTLEGROUND_DS:
case BATTLEGROUND_RV:
switch(arenaType)
{
case ARENA_TYPE_2v2:
return BATTLEGROUND_QUEUE_2v2;
case ARENA_TYPE_3v3:
return BATTLEGROUND_QUEUE_3v3;
case ARENA_TYPE_5v5:
return BATTLEGROUND_QUEUE_5v5;
default:
return BATTLEGROUND_QUEUE_NONE;
}
default:
return BATTLEGROUND_QUEUE_NONE;
}
}
BattleGroundTypeId BattleGroundMgr::BGTemplateId(BattleGroundQueueTypeId bgQueueTypeId)
{
switch(bgQueueTypeId)
{
case BATTLEGROUND_QUEUE_WS:
return BATTLEGROUND_WS;
case BATTLEGROUND_QUEUE_AB:
return BATTLEGROUND_AB;
case BATTLEGROUND_QUEUE_AV:
return BATTLEGROUND_AV;
case BATTLEGROUND_QUEUE_EY:
return BATTLEGROUND_EY;
case BATTLEGROUND_QUEUE_SA:
return BATTLEGROUND_SA;
case BATTLEGROUND_QUEUE_IC:
return BATTLEGROUND_IC;
case BATTLEGROUND_QUEUE_RB:
return BATTLEGROUND_RB;
case BATTLEGROUND_QUEUE_2v2:
case BATTLEGROUND_QUEUE_3v3:
case BATTLEGROUND_QUEUE_5v5:
return BATTLEGROUND_AA;
default:
return BattleGroundTypeId(0); // used for unknown template (it exist and do nothing)
}
}
ArenaType BattleGroundMgr::BGArenaType(BattleGroundQueueTypeId bgQueueTypeId)
{
switch(bgQueueTypeId)
{
case BATTLEGROUND_QUEUE_2v2:
return ARENA_TYPE_2v2;
case BATTLEGROUND_QUEUE_3v3:
return ARENA_TYPE_3v3;
case BATTLEGROUND_QUEUE_5v5:
return ARENA_TYPE_5v5;
default:
return ARENA_TYPE_NONE;
}
}
void BattleGroundMgr::ToggleTesting()
{
m_Testing = !m_Testing;
if (m_Testing)
sWorld.SendWorldText(LANG_DEBUG_BG_ON);
else
sWorld.SendWorldText(LANG_DEBUG_BG_OFF);
}
void BattleGroundMgr::ToggleArenaTesting()
{
m_ArenaTesting = !m_ArenaTesting;
if (m_ArenaTesting)
sWorld.SendWorldText(LANG_DEBUG_ARENA_ON);
else
sWorld.SendWorldText(LANG_DEBUG_ARENA_OFF);
}
void BattleGroundMgr::ScheduleQueueUpdate(uint32 arenaRating, ArenaType arenaType, BattleGroundQueueTypeId bgQueueTypeId, BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id)
{
//ACE_Guard<ACE_Thread_Mutex> guard(SchedulerLock);
//we will use only 1 number created of bgTypeId and bracket_id
uint64 schedule_id = ((uint64)arenaRating << 32) | (arenaType << 24) | (bgQueueTypeId << 16) | (bgTypeId << 8) | bracket_id;
bool found = false;
for (uint8 i = 0; i < m_QueueUpdateScheduler.size(); i++)
{
if (m_QueueUpdateScheduler[i] == schedule_id)
{
found = true;
break;
}
}
if (!found)
m_QueueUpdateScheduler.push_back(schedule_id);
}
uint32 BattleGroundMgr::GetMaxRatingDifference() const
{
// this is for stupid people who can't use brain and set max rating difference to 0
uint32 diff = sWorld.getConfig(CONFIG_UINT32_ARENA_MAX_RATING_DIFFERENCE);
if (diff == 0)
diff = 5000;
return diff;
}
uint32 BattleGroundMgr::GetRatingDiscardTimer() const
{
return sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER);
}
uint32 BattleGroundMgr::GetPrematureFinishTime() const
{
return sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_PREMATURE_FINISH_TIMER);
}
void BattleGroundMgr::LoadBattleMastersEntry()
{
mBattleMastersMap.clear(); // need for reload case
QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
uint32 count = 0;
if (!result)
{
barGoLink bar( 1 );
bar.step();
sLog.outString();
sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
return;
}
barGoLink bar( (int)result->GetRowCount() );
do
{
++count;
bar.step();
Field *fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
uint32 bgTypeId = fields[1].GetUInt32();
if (!sBattlemasterListStore.LookupEntry(bgTypeId))
{
sLog.outErrorDb("Table `battlemaster_entry` contain entry %u for nonexistent battleground type %u, ignored.",entry,bgTypeId);
continue;
}
mBattleMastersMap[entry] = BattleGroundTypeId(bgTypeId);
} while( result->NextRow() );
delete result;
sLog.outString();
sLog.outString( ">> Loaded %u battlemaster entries", count );
}
HolidayIds BattleGroundMgr::BGTypeToWeekendHolidayId(BattleGroundTypeId bgTypeId)
{
switch (bgTypeId)
{
case BATTLEGROUND_AV: return HOLIDAY_CALL_TO_ARMS_AV;
case BATTLEGROUND_EY: return HOLIDAY_CALL_TO_ARMS_EY;
case BATTLEGROUND_WS: return HOLIDAY_CALL_TO_ARMS_WS;
case BATTLEGROUND_SA: return HOLIDAY_CALL_TO_ARMS_SA;
case BATTLEGROUND_AB: return HOLIDAY_CALL_TO_ARMS_AB;
default: return HOLIDAY_NONE;
}
}
BattleGroundTypeId BattleGroundMgr::WeekendHolidayIdToBGType(HolidayIds holiday)
{
switch (holiday)
{
case HOLIDAY_CALL_TO_ARMS_AV: return BATTLEGROUND_AV;
case HOLIDAY_CALL_TO_ARMS_EY: return BATTLEGROUND_EY;
case HOLIDAY_CALL_TO_ARMS_WS: return BATTLEGROUND_WS;
case HOLIDAY_CALL_TO_ARMS_SA: return BATTLEGROUND_SA;
case HOLIDAY_CALL_TO_ARMS_AB: return BATTLEGROUND_AB;
default: return BATTLEGROUND_TYPE_NONE;
}
}
bool BattleGroundMgr::IsBGWeekend(BattleGroundTypeId bgTypeId)
{
return sGameEventMgr.IsActiveHoliday(BGTypeToWeekendHolidayId(bgTypeId));
}
void BattleGroundMgr::LoadBattleEventIndexes()
{
BattleGroundEventIdx events;
events.event1 = BG_EVENT_NONE;
events.event2 = BG_EVENT_NONE;
m_GameObjectBattleEventIndexMap.clear(); // need for reload case
m_GameObjectBattleEventIndexMap[-1] = events;
m_CreatureBattleEventIndexMap.clear(); // need for reload case
m_CreatureBattleEventIndexMap[-1] = events;
uint32 count = 0;
QueryResult *result =
// 0 1 2 3 4 5 6
WorldDatabase.Query( "SELECT data.typ, data.guid1, data.ev1 AS ev1, data.ev2 AS ev2, data.map AS m, data.guid2, description.map, "
// 7 8 9
"description.event1, description.event2, description.description "
"FROM "
"(SELECT '1' AS typ, a.guid AS guid1, a.event1 AS ev1, a.event2 AS ev2, b.map AS map, b.guid AS guid2 "
"FROM gameobject_battleground AS a "
"LEFT OUTER JOIN gameobject AS b ON a.guid = b.guid "
"UNION "
"SELECT '2' AS typ, a.guid AS guid1, a.event1 AS ev1, a.event2 AS ev2, b.map AS map, b.guid AS guid2 "
"FROM creature_battleground AS a "
"LEFT OUTER JOIN creature AS b ON a.guid = b.guid "
") data "
"RIGHT OUTER JOIN battleground_events AS description ON data.map = description.map "
"AND data.ev1 = description.event1 AND data.ev2 = description.event2 "
// full outer join doesn't work in mysql :-/ so just UNION-select the same again and add a left outer join
"UNION "
"SELECT data.typ, data.guid1, data.ev1, data.ev2, data.map, data.guid2, description.map, "
"description.event1, description.event2, description.description "
"FROM "
"(SELECT '1' AS typ, a.guid AS guid1, a.event1 AS ev1, a.event2 AS ev2, b.map AS map, b.guid AS guid2 "
"FROM gameobject_battleground AS a "
"LEFT OUTER JOIN gameobject AS b ON a.guid = b.guid "
"UNION "
"SELECT '2' AS typ, a.guid AS guid1, a.event1 AS ev1, a.event2 AS ev2, b.map AS map, b.guid AS guid2 "
"FROM creature_battleground AS a "
"LEFT OUTER JOIN creature AS b ON a.guid = b.guid "
") data "
"LEFT OUTER JOIN battleground_events AS description ON data.map = description.map "
"AND data.ev1 = description.event1 AND data.ev2 = description.event2 "
"ORDER BY m, ev1, ev2" );
if(!result)
{
barGoLink bar(1);
bar.step();
sLog.outString();
sLog.outErrorDb(">> Loaded 0 battleground eventindexes.");
return;
}
barGoLink bar((int)result->GetRowCount());
do
{
bar.step();
Field *fields = result->Fetch();
if (fields[2].GetUInt8() == BG_EVENT_NONE || fields[3].GetUInt8() == BG_EVENT_NONE)
continue; // we don't need to add those to the eventmap
bool gameobject = (fields[0].GetUInt8() == 1);
uint32 dbTableGuidLow = fields[1].GetUInt32();
events.event1 = fields[2].GetUInt8();
events.event2 = fields[3].GetUInt8();
uint32 map = fields[4].GetUInt32();
uint32 desc_map = fields[6].GetUInt32();
uint8 desc_event1 = fields[7].GetUInt8();
uint8 desc_event2 = fields[8].GetUInt8();
const char *description = fields[9].GetString();
// checking for NULL - through right outer join this will mean following:
if (fields[5].GetUInt32() != dbTableGuidLow)
{
sLog.outErrorDb("BattleGroundEvent: %s with nonexistent guid %u for event: map:%u, event1:%u, event2:%u (\"%s\")",
(gameobject) ? "gameobject" : "creature", dbTableGuidLow, map, events.event1, events.event2, description);
continue;
}
// checking for NULL - through full outer join this can mean 2 things:
if (desc_map != map)
{
// there is an event missing
if (dbTableGuidLow == 0)
{
sLog.outErrorDb("BattleGroundEvent: missing db-data for map:%u, event1:%u, event2:%u (\"%s\")", desc_map, desc_event1, desc_event2, description);
continue;
}
// we have an event which shouldn't exist
else
{
sLog.outErrorDb("BattleGroundEvent: %s with guid %u is registered, for a nonexistent event: map:%u, event1:%u, event2:%u",
(gameobject) ? "gameobject" : "creature", dbTableGuidLow, map, events.event1, events.event2);
continue;
}
}
if (gameobject)
m_GameObjectBattleEventIndexMap[dbTableGuidLow] = events;
else
m_CreatureBattleEventIndexMap[dbTableGuidLow] = events;
++count;
} while(result->NextRow());
sLog.outString();
sLog.outString( ">> Loaded %u battleground eventindexes", count);
delete result;
} | gpl-2.0 |
realtsiry/rockbox4linux | firmware/target/arm/s3c2440/adc-s3c2440.c | 1 | 3753 | /***************************************************************************
* __________ __ ___.
* Open \______ \ ____ ____ | | _\_ |__ _______ ___
* Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
* Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
* Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
* \/ \/ \/ \/ \/
* $Id: adc-s3c2440.c 27188 2010-06-30 02:02:46Z jethead71 $
*
* Copyright (C) 2006 by Wade Brown
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
****************************************************************************/
#include "cpu.h"
#include "system.h"
#include "adc.h"
#include "adc-target.h"
#include "kernel.h"
#ifdef MINI2440
#include "touchscreen-target.h"
#endif
static unsigned short adc_readings[NUM_ADC_CHANNELS];
/* prototypes */
static unsigned short __adc_read(int channel);
static void adc_tick(void);
void adc_init(void)
{
int i;
/* Turn on the ADC PCLK */
bitset32(&CLKCON, 1<<15);
/* Set channel 0, normal mode, disable "start by read" */
ADCCON &= ~(0x3F);
/* No start delay. Use normal conversion mode. */
ADCDLY = 0x1;
/* Set and enable the prescaler */
ADCCON = (ADCCON & ~(0xff<<6)) | (0x19<<6);
ADCCON |= (1<<14);
/* prefill the adc channels */
for (i = 0; i < NUM_ADC_CHANNELS; i++)
{
adc_readings[i] = __adc_read(i);
}
/* start at zero so when the tick starts it is at zero */
adc_readings[0] = __adc_read(0);
/* attach the adc reading to the tick */
tick_add_task(adc_tick);
}
/* Called to get the recent ADC reading */
inline unsigned short adc_read(int channel)
{
return adc_readings[channel];
}
/**
* Read the ADC by polling
* @param channel The ADC channel to read
* @return 10bit reading from ADC channel or ADC_READ_ERROR if timeout
*/
static unsigned short __adc_read(int channel)
{
int i;
/* Set the channel */
ADCCON = (ADCCON & ~(0x7<<3)) | (channel<<3);
/* Start the conversion process */
ADCCON |= 0x1;
/* Wait for a low Enable_start */
for (i = 20000;;)
{
if(0 == (ADCCON & 0x1))
{
break;
}
else
{
i--;
if (0 == i)
{
/* Ran out of time */
return ADC_READ_ERROR;
}
}
}
/* Wait for high End_of_Conversion */
for(i = 20000;;)
{
if(ADCCON & (1<<15))
{
break;
}
else
{
i--;
if(0 == i)
{
/* Ran out of time */
return ADC_READ_ERROR;
}
}
}
return (ADCDAT0 & 0x3ff);
}
/* add this to the tick so that the ADC converts are done in the background */
static void adc_tick(void)
{
static unsigned channel=0;
/* Check if the End Of Conversion is set */
if (ADCCON & (1<<15))
{
adc_readings[channel] = (ADCDAT0 & 0x3FF);
if (++channel >= NUM_ADC_CHANNELS)
{
channel = 0;
}
#ifdef MINI2440
/* interleave a touchscreen read if neccessary */
touchscreen_scan_device();
#endif
/* setup the next conversion and start it*/
ADCCON = (ADCCON & ~(0x7<<3)) | (channel<<3) | 0x01;
}
}
| gpl-2.0 |
kraj/gcc | gcc/testsuite/gcc.target/i386/pr92645-3.c | 1 | 1106 | /* { dg-do compile } */
/* { dg-options "-O2 -mavx2 -fdump-tree-cddce1" } */
typedef int v8si __attribute__((vector_size(32)));
typedef float v4sf __attribute__((vector_size(16)));
void low (v4sf *dst, v8si *srcp)
{
v8si src = *srcp;
*dst = (v4sf) { src[0], src[1], src[2], src[3] };
}
void high (v4sf *dst, v8si *srcp)
{
v8si src = *srcp;
*dst = (v4sf) { src[4], src[5], src[6], src[7] };
}
void even (v4sf *dst, v8si *srcp)
{
v8si src = *srcp;
*dst = (v4sf) { src[0], src[2], src[4], src[6] };
}
void odd (v4sf *dst, v8si *srcp)
{
v8si src = *srcp;
*dst = (v4sf) { src[1], src[3], src[5], src[7] };
}
/* { dg-final { scan-tree-dump-times "BIT_FIELD_REF" 4 "cddce1" } } */
/* Four conversions, on the smaller vector type, to not convert excess
elements. */
/* { dg-final { scan-tree-dump-times " = \\\(vector\\\(4\\\) float\\\)" 4 "cddce1" } } */
/* { dg-final { scan-tree-dump-times "VEC_PERM_EXPR" 3 "cddce1" { xfail *-*-* } } } */
/* Ideally highpart extraction would elide the VEC_PERM_EXPR as well. */
/* { dg-final { scan-tree-dump-times "VEC_PERM_EXPR" 2 "cddce1" } } */
| gpl-2.0 |
chuukai/ponyo-kernel-nAa | arch/arm/mach-msm/sdio_cmux.c | 1 | 22316 | /* 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.
*/
#define DEBUG
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/workqueue.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/termios.h>
#include <linux/debugfs.h>
#include <mach/sdio_al.h>
#include <mach/sdio_cmux.h>
#include "modem_notifier.h"
#define MAX_WRITE_RETRY 5
#define MAGIC_NO_V1 0x33FC
static int msm_sdio_cmux_debug_mask;
module_param_named(debug_mask, msm_sdio_cmux_debug_mask,
int, S_IRUGO | S_IWUSR | S_IWGRP);
enum cmd_type {
DATA = 0,
OPEN,
CLOSE,
STATUS,
NUM_CMDS
};
#define DSR_POS 0x1
#define CTS_POS 0x2
#define RI_POS 0x4
#define CD_POS 0x8
struct sdio_cmux_ch {
int lc_id;
struct mutex lc_lock;
wait_queue_head_t open_wait_queue;
int is_remote_open;
int is_local_open;
int is_channel_reset;
char local_status;
char remote_status;
struct mutex tx_lock;
struct list_head tx_list;
void *priv;
void (*receive_cb)(void *, int, void *);
void (*write_done)(void *, int, void *);
void (*status_callback)(int, void *);
} logical_ch[SDIO_CMUX_NUM_CHANNELS];
struct sdio_cmux_hdr {
uint16_t magic_no;
uint8_t status; /* This field is reserved for commands other
* than STATUS */
uint8_t cmd;
uint8_t pad_bytes;
uint8_t lc_id;
uint16_t pkt_len;
};
struct sdio_cmux_pkt {
struct sdio_cmux_hdr *hdr;
void *data;
};
struct sdio_cmux_list_elem {
struct list_head list;
struct sdio_cmux_pkt cmux_pkt;
};
#define logical_ch_is_local_open(x) \
(logical_ch[(x)].is_local_open)
#define logical_ch_is_remote_open(x) \
(logical_ch[(x)].is_remote_open)
static void sdio_cdemux_fn(struct work_struct *work);
static DECLARE_WORK(sdio_cdemux_work, sdio_cdemux_fn);
static struct workqueue_struct *sdio_cdemux_wq;
static DEFINE_MUTEX(write_lock);
static uint32_t bytes_to_write;
static DEFINE_MUTEX(temp_rx_lock);
static LIST_HEAD(temp_rx_list);
static void sdio_cmux_fn(struct work_struct *work);
static DECLARE_WORK(sdio_cmux_work, sdio_cmux_fn);
static struct workqueue_struct *sdio_cmux_wq;
static struct sdio_channel *sdio_qmi_chl;
static uint32_t sdio_cmux_inited;
static uint32_t abort_tx;
static DEFINE_MUTEX(modem_reset_lock);
static DEFINE_MUTEX(probe_lock);
enum {
MSM_SDIO_CMUX_DEBUG = 1U << 0,
MSM_SDIO_CMUX_DUMP_BUFFER = 1U << 1,
};
static struct platform_device sdio_ctl_dev = {
.name = "SDIO_CTL",
.id = -1,
};
#if defined(DEBUG)
#define D_DUMP_BUFFER(prestr, cnt, buf) \
do { \
if (msm_sdio_cmux_debug_mask & MSM_SDIO_CMUX_DUMP_BUFFER) { \
int i; \
pr_debug("%s", prestr); \
for (i = 0; i < cnt; i++) \
pr_info("%.2x", buf[i]); \
pr_debug("\n"); \
} \
} while (0)
#define D(x...) \
do { \
if (msm_sdio_cmux_debug_mask & MSM_SDIO_CMUX_DEBUG) \
pr_debug(x); \
} while (0)
#else
#define D_DUMP_BUFFER(prestr, cnt, buf) do {} while (0)
#define D(x...) do {} while (0)
#endif
static int sdio_cmux_ch_alloc(int id)
{
if (id < 0 || id >= SDIO_CMUX_NUM_CHANNELS) {
pr_err("%s: Invalid lc_id - %d\n", __func__, id);
return -EINVAL;
}
logical_ch[id].lc_id = id;
mutex_init(&logical_ch[id].lc_lock);
init_waitqueue_head(&logical_ch[id].open_wait_queue);
logical_ch[id].is_remote_open = 0;
logical_ch[id].is_local_open = 0;
logical_ch[id].is_channel_reset = 0;
INIT_LIST_HEAD(&logical_ch[id].tx_list);
mutex_init(&logical_ch[id].tx_lock);
logical_ch[id].priv = NULL;
logical_ch[id].receive_cb = NULL;
logical_ch[id].write_done = NULL;
return 0;
}
static int sdio_cmux_ch_clear_and_signal(int id)
{
struct sdio_cmux_list_elem *list_elem;
if (id < 0 || id >= SDIO_CMUX_NUM_CHANNELS) {
pr_err("%s: Invalid lc_id - %d\n", __func__, id);
return -EINVAL;
}
mutex_lock(&logical_ch[id].lc_lock);
logical_ch[id].is_remote_open = 0;
mutex_lock(&logical_ch[id].tx_lock);
while (!list_empty(&logical_ch[id].tx_list)) {
list_elem = list_first_entry(&logical_ch[id].tx_list,
struct sdio_cmux_list_elem,
list);
list_del(&list_elem->list);
kfree(list_elem->cmux_pkt.hdr);
kfree(list_elem);
}
mutex_unlock(&logical_ch[id].tx_lock);
if (logical_ch[id].receive_cb)
logical_ch[id].receive_cb(NULL, 0, logical_ch[id].priv);
if (logical_ch[id].write_done)
logical_ch[id].write_done(NULL, 0, logical_ch[id].priv);
mutex_unlock(&logical_ch[id].lc_lock);
wake_up(&logical_ch[id].open_wait_queue);
return 0;
}
static int sdio_cmux_write_cmd(const int id, enum cmd_type type)
{
int write_size = 0;
void *write_data = NULL;
struct sdio_cmux_list_elem *list_elem;
if (id < 0 || id >= SDIO_CMUX_NUM_CHANNELS) {
pr_err("%s: Invalid lc_id - %d\n", __func__, id);
return -EINVAL;
}
if (type < 0 || type > NUM_CMDS) {
pr_err("%s: Invalid cmd - %d\n", __func__, type);
return -EINVAL;
}
write_size = sizeof(struct sdio_cmux_hdr);
list_elem = kmalloc(sizeof(struct sdio_cmux_list_elem), GFP_KERNEL);
if (!list_elem) {
pr_err("%s: list_elem alloc failed\n", __func__);
return -ENOMEM;
}
write_data = kmalloc(write_size, GFP_KERNEL);
if (!write_data) {
pr_err("%s: write_data alloc failed\n", __func__);
kfree(list_elem);
return -ENOMEM;
}
list_elem->cmux_pkt.hdr = (struct sdio_cmux_hdr *)write_data;
list_elem->cmux_pkt.data = NULL;
list_elem->cmux_pkt.hdr->lc_id = (uint8_t)id;
list_elem->cmux_pkt.hdr->pkt_len = (uint16_t)0;
list_elem->cmux_pkt.hdr->cmd = (uint8_t)type;
list_elem->cmux_pkt.hdr->status = (uint8_t)0;
if (type == STATUS)
list_elem->cmux_pkt.hdr->status = logical_ch[id].local_status;
list_elem->cmux_pkt.hdr->pad_bytes = (uint8_t)0;
list_elem->cmux_pkt.hdr->magic_no = (uint16_t)MAGIC_NO_V1;
mutex_lock(&logical_ch[id].tx_lock);
list_add_tail(&list_elem->list, &logical_ch[id].tx_list);
mutex_unlock(&logical_ch[id].tx_lock);
mutex_lock(&write_lock);
bytes_to_write += write_size;
mutex_unlock(&write_lock);
queue_work(sdio_cmux_wq, &sdio_cmux_work);
return 0;
}
int sdio_cmux_open(const int id,
void (*receive_cb)(void *, int, void *),
void (*write_done)(void *, int, void *),
void (*status_callback)(int, void *),
void *priv)
{
int r;
struct sdio_cmux_list_elem *list_elem, *list_elem_tmp;
if (!sdio_cmux_inited)
return -ENODEV;
if (id < 0 || id >= SDIO_CMUX_NUM_CHANNELS) {
pr_err("%s: Invalid id - %d\n", __func__, id);
return -EINVAL;
}
r = wait_event_timeout(logical_ch[id].open_wait_queue,
logical_ch[id].is_remote_open, (1 * HZ));
if (r < 0) {
pr_err("ERROR %s: wait_event_timeout() failed for"
" ch%d with rc %d\n", __func__, id, r);
return r;
}
if (r == 0) {
pr_err("ERROR %s: Wait Timed Out for ch%d\n", __func__, id);
return -ETIMEDOUT;
}
mutex_lock(&logical_ch[id].lc_lock);
if (!logical_ch[id].is_remote_open) {
pr_err("%s: Remote ch%d not opened\n", __func__, id);
mutex_unlock(&logical_ch[id].lc_lock);
return -EINVAL;
}
if (logical_ch[id].is_local_open) {
mutex_unlock(&logical_ch[id].lc_lock);
return 0;
}
logical_ch[id].is_local_open = 1;
logical_ch[id].priv = priv;
logical_ch[id].receive_cb = receive_cb;
logical_ch[id].write_done = write_done;
logical_ch[id].status_callback = status_callback;
if (logical_ch[id].receive_cb) {
mutex_lock(&temp_rx_lock);
list_for_each_entry_safe(list_elem, list_elem_tmp,
&temp_rx_list, list) {
if ((int)list_elem->cmux_pkt.hdr->lc_id == id) {
logical_ch[id].receive_cb(
list_elem->cmux_pkt.data,
(int)list_elem->cmux_pkt.hdr->pkt_len,
logical_ch[id].priv);
list_del(&list_elem->list);
kfree(list_elem->cmux_pkt.hdr);
kfree(list_elem);
}
}
mutex_unlock(&temp_rx_lock);
}
mutex_unlock(&logical_ch[id].lc_lock);
sdio_cmux_write_cmd(id, OPEN);
return 0;
}
EXPORT_SYMBOL(sdio_cmux_open);
int sdio_cmux_close(int id)
{
struct sdio_cmux_ch *ch;
if (!sdio_cmux_inited)
return -ENODEV;
if (id < 0 || id >= SDIO_CMUX_NUM_CHANNELS) {
pr_err("%s: Invalid channel close\n", __func__);
return -EINVAL;
}
ch = &logical_ch[id];
mutex_lock(&ch->lc_lock);
ch->is_local_open = 0;
ch->priv = NULL;
ch->receive_cb = NULL;
ch->write_done = NULL;
mutex_unlock(&ch->lc_lock);
sdio_cmux_write_cmd(ch->lc_id, CLOSE);
return 0;
}
EXPORT_SYMBOL(sdio_cmux_close);
int sdio_cmux_write_avail(int id)
{
int write_avail;
mutex_lock(&logical_ch[id].lc_lock);
if (logical_ch[id].is_channel_reset) {
mutex_unlock(&logical_ch[id].lc_lock);
return -ENETRESET;
}
mutex_unlock(&logical_ch[id].lc_lock);
write_avail = sdio_write_avail(sdio_qmi_chl);
return write_avail - bytes_to_write;
}
EXPORT_SYMBOL(sdio_cmux_write_avail);
int sdio_cmux_write(int id, void *data, int len)
{
struct sdio_cmux_list_elem *list_elem;
uint32_t write_size;
void *write_data = NULL;
struct sdio_cmux_ch *ch;
int ret;
if (!sdio_cmux_inited)
return -ENODEV;
if (id < 0 || id >= SDIO_CMUX_NUM_CHANNELS) {
pr_err("%s: Invalid channel id %d\n", __func__, id);
return -ENODEV;
}
ch = &logical_ch[id];
if (len <= 0) {
pr_err("%s: Invalid len %d bytes to write\n",
__func__, len);
return -EINVAL;
}
write_size = sizeof(struct sdio_cmux_hdr) + len;
list_elem = kmalloc(sizeof(struct sdio_cmux_list_elem), GFP_KERNEL);
if (!list_elem) {
pr_err("%s: list_elem alloc failed\n", __func__);
return -ENOMEM;
}
write_data = kmalloc(write_size, GFP_KERNEL);
if (!write_data) {
pr_err("%s: write_data alloc failed\n", __func__);
kfree(list_elem);
return -ENOMEM;
}
list_elem->cmux_pkt.hdr = (struct sdio_cmux_hdr *)write_data;
list_elem->cmux_pkt.data = (void *)((char *)write_data +
sizeof(struct sdio_cmux_hdr));
memcpy(list_elem->cmux_pkt.data, data, len);
list_elem->cmux_pkt.hdr->lc_id = (uint8_t)ch->lc_id;
list_elem->cmux_pkt.hdr->pkt_len = (uint16_t)len;
list_elem->cmux_pkt.hdr->cmd = (uint8_t)DATA;
list_elem->cmux_pkt.hdr->status = (uint8_t)0;
list_elem->cmux_pkt.hdr->pad_bytes = (uint8_t)0;
list_elem->cmux_pkt.hdr->magic_no = (uint16_t)MAGIC_NO_V1;
mutex_lock(&ch->lc_lock);
if (!ch->is_remote_open || !ch->is_local_open) {
pr_err("%s: Local ch%d sending data before sending/receiving"
" OPEN command\n", __func__, ch->lc_id);
if (ch->is_channel_reset)
ret = -ENETRESET;
else
ret = -ENODEV;
mutex_unlock(&ch->lc_lock);
kfree(write_data);
kfree(list_elem);
return ret;
}
mutex_lock(&ch->tx_lock);
list_add_tail(&list_elem->list, &ch->tx_list);
mutex_unlock(&ch->tx_lock);
mutex_unlock(&ch->lc_lock);
mutex_lock(&write_lock);
bytes_to_write += write_size;
mutex_unlock(&write_lock);
queue_work(sdio_cmux_wq, &sdio_cmux_work);
return len;
}
EXPORT_SYMBOL(sdio_cmux_write);
int is_remote_open(int id)
{
if (id < 0 || id >= SDIO_CMUX_NUM_CHANNELS)
return -ENODEV;
return logical_ch_is_remote_open(id);
}
EXPORT_SYMBOL(is_remote_open);
int sdio_cmux_is_channel_reset(int id)
{
int ret;
if (id < 0 || id >= SDIO_CMUX_NUM_CHANNELS)
return -ENODEV;
mutex_lock(&logical_ch[id].lc_lock);
ret = logical_ch[id].is_channel_reset;
mutex_unlock(&logical_ch[id].lc_lock);
return ret;
}
EXPORT_SYMBOL(sdio_cmux_is_channel_reset);
int sdio_cmux_tiocmget(int id)
{
int ret = (logical_ch[id].remote_status & DSR_POS ? TIOCM_DSR : 0) |
(logical_ch[id].remote_status & CTS_POS ? TIOCM_CTS : 0) |
(logical_ch[id].remote_status & CD_POS ? TIOCM_CD : 0) |
(logical_ch[id].remote_status & RI_POS ? TIOCM_RI : 0) |
(logical_ch[id].local_status & CTS_POS ? TIOCM_RTS : 0) |
(logical_ch[id].local_status & DSR_POS ? TIOCM_DTR : 0);
return ret;
}
EXPORT_SYMBOL(sdio_cmux_tiocmget);
int sdio_cmux_tiocmset(int id, unsigned int set, unsigned int clear)
{
if (set & TIOCM_DTR)
logical_ch[id].local_status |= DSR_POS;
if (set & TIOCM_RTS)
logical_ch[id].local_status |= CTS_POS;
if (clear & TIOCM_DTR)
logical_ch[id].local_status &= ~DSR_POS;
if (clear & TIOCM_RTS)
logical_ch[id].local_status &= ~CTS_POS;
sdio_cmux_write_cmd(id, STATUS);
return 0;
}
EXPORT_SYMBOL(sdio_cmux_tiocmset);
static int copy_packet(void *pkt, int size)
{
struct sdio_cmux_list_elem *list_elem = NULL;
void *temp_pkt = NULL;
list_elem = kmalloc(sizeof(struct sdio_cmux_list_elem), GFP_KERNEL);
if (!list_elem) {
pr_err("%s: list_elem alloc failed\n", __func__);
return -ENOMEM;
}
temp_pkt = kmalloc(size, GFP_KERNEL);
if (!temp_pkt) {
pr_err("%s: temp_pkt alloc failed\n", __func__);
kfree(list_elem);
return -ENOMEM;
}
memcpy(temp_pkt, pkt, size);
list_elem->cmux_pkt.hdr = temp_pkt;
list_elem->cmux_pkt.data = (void *)((char *)temp_pkt +
sizeof(struct sdio_cmux_hdr));
mutex_lock(&temp_rx_lock);
list_add_tail(&list_elem->list, &temp_rx_list);
mutex_unlock(&temp_rx_lock);
return 0;
}
static int process_cmux_pkt(void *pkt, int size)
{
struct sdio_cmux_hdr *mux_hdr;
uint32_t id, data_size;
void *data;
char *dump_buf = (char *)pkt;
D_DUMP_BUFFER("process_cmux_pkt:", size, dump_buf);
mux_hdr = (struct sdio_cmux_hdr *)pkt;
switch (mux_hdr->cmd) {
case OPEN:
id = (uint32_t)(mux_hdr->lc_id);
D("%s: Received OPEN command for ch%d\n", __func__, id);
mutex_lock(&logical_ch[id].lc_lock);
logical_ch[id].is_remote_open = 1;
logical_ch[id].is_channel_reset = 0;
mutex_unlock(&logical_ch[id].lc_lock);
wake_up(&logical_ch[id].open_wait_queue);
break;
case CLOSE:
id = (uint32_t)(mux_hdr->lc_id);
D("%s: Received CLOSE command for ch%d\n", __func__, id);
sdio_cmux_ch_clear_and_signal(id);
break;
case DATA:
id = (uint32_t)(mux_hdr->lc_id);
D("%s: Received DATA for ch%d\n", __func__, id);
/*Channel is not locally open & if single packet received
then drop it*/
mutex_lock(&logical_ch[id].lc_lock);
if (!logical_ch[id].is_remote_open) {
mutex_unlock(&logical_ch[id].lc_lock);
pr_err("%s: Remote Ch%d sent data before sending/"
"receiving OPEN command\n", __func__, id);
return -ENODEV;
}
data = (void *)((char *)pkt + sizeof(struct sdio_cmux_hdr));
data_size = (int)(((struct sdio_cmux_hdr *)pkt)->pkt_len);
if (logical_ch[id].receive_cb)
logical_ch[id].receive_cb(data, data_size,
logical_ch[id].priv);
else
copy_packet(pkt, size);
mutex_unlock(&logical_ch[id].lc_lock);
break;
case STATUS:
id = (uint32_t)(mux_hdr->lc_id);
D("%s: Received STATUS command for ch%d\n", __func__, id);
if (logical_ch[id].remote_status != mux_hdr->status) {
mutex_lock(&logical_ch[id].lc_lock);
logical_ch[id].remote_status = mux_hdr->status;
mutex_unlock(&logical_ch[id].lc_lock);
if (logical_ch[id].status_callback)
logical_ch[id].status_callback(
sdio_cmux_tiocmget(id),
logical_ch[id].priv);
}
break;
}
return 0;
}
static void parse_cmux_data(void *data, int size)
{
int data_parsed = 0, pkt_size;
char *temp_ptr;
D("Entered %s\n", __func__);
temp_ptr = (char *)data;
while (data_parsed < size) {
pkt_size = sizeof(struct sdio_cmux_hdr) +
(int)(((struct sdio_cmux_hdr *)temp_ptr)->pkt_len);
D("Parsed %d bytes, Current Pkt Size %d bytes,"
" Total size %d bytes\n", data_parsed, pkt_size, size);
process_cmux_pkt((void *)temp_ptr, pkt_size);
data_parsed += pkt_size;
temp_ptr += pkt_size;
}
kfree(data);
}
static void sdio_cdemux_fn(struct work_struct *work)
{
int r = 0, read_avail = 0;
void *cmux_data;
while (1) {
read_avail = sdio_read_avail(sdio_qmi_chl);
if (read_avail < 0) {
pr_err("%s: sdio_read_avail failed with rc %d\n",
__func__, read_avail);
return;
}
if (read_avail == 0) {
D("%s: Nothing to read\n", __func__);
return;
}
D("%s: kmalloc %d bytes\n", __func__, read_avail);
cmux_data = kmalloc(read_avail, GFP_KERNEL);
if (!cmux_data) {
pr_err("%s: kmalloc Failed\n", __func__);
return;
}
D("%s: sdio_read %d bytes\n", __func__, read_avail);
r = sdio_read(sdio_qmi_chl, cmux_data, read_avail);
if (r < 0) {
pr_err("%s: sdio_read failed with rc %d\n",
__func__, r);
kfree(cmux_data);
return;
}
parse_cmux_data(cmux_data, read_avail);
}
return;
}
static void sdio_cmux_fn(struct work_struct *work)
{
int i, r = 0;
void *write_data;
uint32_t write_size, write_avail, write_retry = 0;
int bytes_written;
struct sdio_cmux_list_elem *list_elem = NULL;
struct sdio_cmux_ch *ch;
for (i = 0; i < SDIO_CMUX_NUM_CHANNELS; ++i) {
ch = &logical_ch[i];
bytes_written = 0;
mutex_lock(&ch->tx_lock);
while (!list_empty(&ch->tx_list)) {
list_elem = list_first_entry(&ch->tx_list,
struct sdio_cmux_list_elem,
list);
list_del(&list_elem->list);
mutex_unlock(&ch->tx_lock);
write_data = (void *)list_elem->cmux_pkt.hdr;
write_size = sizeof(struct sdio_cmux_hdr) +
(uint32_t)list_elem->cmux_pkt.hdr->pkt_len;
mutex_lock(&modem_reset_lock);
while (!(abort_tx) &&
((write_avail = sdio_write_avail(sdio_qmi_chl))
< write_size)) {
mutex_unlock(&modem_reset_lock);
pr_err("%s: sdio_write_avail %d bytes, "
"write size %d bytes. Waiting...\n",
__func__, write_avail, write_size);
msleep(250);
mutex_lock(&modem_reset_lock);
}
while (!(abort_tx) &&
((r = sdio_write(sdio_qmi_chl,
write_data, write_size)) < 0)
&& (write_retry++ < MAX_WRITE_RETRY)) {
mutex_unlock(&modem_reset_lock);
pr_err("%s: sdio_write failed with rc %d."
"Retrying...", __func__, r);
msleep(250);
mutex_lock(&modem_reset_lock);
}
if (!r && !abort_tx) {
D("%s: sdio_write_completed %dbytes\n",
__func__, write_size);
bytes_written += write_size;
}
mutex_unlock(&modem_reset_lock);
kfree(list_elem->cmux_pkt.hdr);
kfree(list_elem);
mutex_lock(&write_lock);
bytes_to_write -= write_size;
mutex_unlock(&write_lock);
mutex_lock(&ch->tx_lock);
}
if (ch->write_done)
ch->write_done(NULL, bytes_written, ch->priv);
mutex_unlock(&ch->tx_lock);
}
return;
}
static void sdio_qmi_chl_notify(void *priv, unsigned event)
{
if (event == SDIO_EVENT_DATA_READ_AVAIL) {
D("%s: Received SDIO_EVENT_DATA_READ_AVAIL\n", __func__);
queue_work(sdio_cdemux_wq, &sdio_cdemux_work);
}
}
#ifdef CONFIG_DEBUG_FS
static int debug_tbl(char *buf, int max)
{
int i = 0;
int j;
for (j = 0; j < SDIO_CMUX_NUM_CHANNELS; ++j) {
i += scnprintf(buf + i, max - i,
"ch%02d local open=%s remote open=%s\n",
j, logical_ch_is_local_open(j) ? "Y" : "N",
logical_ch_is_remote_open(j) ? "Y" : "N");
}
return i;
}
#define DEBUG_BUFMAX 4096
static char debug_buffer[DEBUG_BUFMAX];
static ssize_t debug_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
int (*fill)(char *buf, int max) = file->private_data;
int bsize = fill(debug_buffer, DEBUG_BUFMAX);
return simple_read_from_buffer(buf, count, ppos, debug_buffer, bsize);
}
static int debug_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static const struct file_operations debug_ops = {
.read = debug_read,
.open = debug_open,
};
static void debug_create(const char *name, mode_t mode,
struct dentry *dent,
int (*fill)(char *buf, int max))
{
debugfs_create_file(name, mode, dent, fill, &debug_ops);
}
#endif
static int sdio_cmux_probe(struct platform_device *pdev)
{
int i, r;
mutex_lock(&probe_lock);
D("%s Begins\n", __func__);
if (sdio_cmux_inited) {
mutex_lock(&modem_reset_lock);
r = sdio_open("SDIO_QMI", &sdio_qmi_chl, NULL,
sdio_qmi_chl_notify);
if (r < 0) {
mutex_unlock(&modem_reset_lock);
pr_err("%s: sdio_open() failed\n", __func__);
goto error0;
}
abort_tx = 0;
mutex_unlock(&modem_reset_lock);
mutex_unlock(&probe_lock);
return 0;
}
for (i = 0; i < SDIO_CMUX_NUM_CHANNELS; ++i)
sdio_cmux_ch_alloc(i);
INIT_LIST_HEAD(&temp_rx_list);
sdio_cmux_wq = create_singlethread_workqueue("sdio_cmux");
if (IS_ERR(sdio_cmux_wq)) {
pr_err("%s: create_singlethread_workqueue() ENOMEM\n",
__func__);
r = -ENOMEM;
goto error0;
}
sdio_cdemux_wq = create_singlethread_workqueue("sdio_cdemux");
if (IS_ERR(sdio_cdemux_wq)) {
pr_err("%s: create_singlethread_workqueue() ENOMEM\n",
__func__);
r = -ENOMEM;
goto error1;
}
r = sdio_open("SDIO_QMI", &sdio_qmi_chl, NULL, sdio_qmi_chl_notify);
if (r < 0) {
pr_err("%s: sdio_open() failed\n", __func__);
goto error2;
}
platform_device_register(&sdio_ctl_dev);
sdio_cmux_inited = 1;
D("SDIO Control MUX Driver Initialized.\n");
mutex_unlock(&probe_lock);
return 0;
error2:
destroy_workqueue(sdio_cdemux_wq);
error1:
destroy_workqueue(sdio_cmux_wq);
error0:
mutex_unlock(&probe_lock);
return r;
}
static int sdio_cmux_remove(struct platform_device *pdev)
{
int i;
mutex_lock(&modem_reset_lock);
abort_tx = 1;
for (i = 0; i < SDIO_CMUX_NUM_CHANNELS; ++i) {
mutex_lock(&logical_ch[i].lc_lock);
logical_ch[i].is_channel_reset = 1;
mutex_unlock(&logical_ch[i].lc_lock);
sdio_cmux_ch_clear_and_signal(i);
}
sdio_qmi_chl = NULL;
mutex_unlock(&modem_reset_lock);
return 0;
}
static struct platform_driver sdio_cmux_driver = {
.probe = sdio_cmux_probe,
.remove = sdio_cmux_remove,
.driver = {
.name = "SDIO_QMI",
.owner = THIS_MODULE,
},
};
static int __init sdio_cmux_init(void)
{
#ifdef CONFIG_DEBUG_FS
struct dentry *dent;
dent = debugfs_create_dir("sdio_cmux", 0);
if (!IS_ERR(dent))
debug_create("tbl", 0444, dent, debug_tbl);
#endif
msm_sdio_cmux_debug_mask = 0;
return platform_driver_register(&sdio_cmux_driver);
}
module_init(sdio_cmux_init);
MODULE_DESCRIPTION("MSM SDIO Control MUX");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
feld/xymon | lib/tree.c | 1 | 13299 | /*----------------------------------------------------------------------------*/
/* Xymon monitor library. */
/* */
/* This is a library module, part of libxymon. */
/* It contains routines for tree-based record storage. */
/* */
/* Copyright (C) 2011-2011 Henrik Storner <henrik@storner.dk> */
/* */
/* This program is released under the GNU General Public License (GPL), */
/* version 2. See the file "COPYING" for details. */
/* */
/*----------------------------------------------------------------------------*/
static char rcsid[] = "$Id$";
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include "config.h"
#include "tree.h"
#ifdef HAVE_BINARY_TREE
#include <search.h>
typedef struct treerec_t {
char *key;
void *userdata;
int (*compare)(const char *a, const char *b);
struct treerec_t *link;
} treerec_t;
typedef struct xtree_t {
void *root;
int (*compare)(const char *a, const char *b);
} xtree_t;
static treerec_t *i_curr = NULL;
static int xtree_i_compare(const void *pa, const void *pb)
{
const treerec_t *reca = pa, *recb = pb;
return (reca->compare)(reca->key, recb->key);
}
void *xtreeNew(int(*xtreeCompare)(const char *a, const char *b))
{
xtree_t *newtree;
newtree = (xtree_t *)calloc(1, sizeof(xtree_t));
newtree->compare = xtreeCompare;
newtree->root = NULL;
return newtree;
}
void xtreeDestroy(void *treehandle)
{
free(treehandle);
}
xtreeStatus_t xtreeAdd(void *treehandle, char *key, void *userdata)
{
xtree_t *tree = treehandle;
treerec_t *rec, **erec;
if (!tree) return XTREE_STATUS_NOTREE;
rec = (treerec_t *)calloc(1, sizeof(treerec_t));
rec->key = key;
rec->userdata = userdata;
rec->compare = tree->compare;
erec = tsearch(rec, &tree->root, xtree_i_compare);
if (erec == NULL) {
free(rec);
return XTREE_STATUS_MEM_EXHAUSTED;
}
if (*erec != rec) {
/* Was already there */
free(rec);
return XTREE_STATUS_DUPLICATE_KEY;
}
return XTREE_STATUS_OK;
}
void *xtreeDelete(void *treehandle, char *key)
{
xtree_t *tree = treehandle;
treerec_t **result, *zombie, rec;
void *userdata;
if (!tree) return NULL;
rec.key = key;
rec.userdata = NULL;
rec.compare = tree->compare;
result = tfind(&rec, &tree->root, xtree_i_compare);
if (result == NULL) {
/* Not found */
return NULL;
}
userdata = (*result)->userdata;
zombie = (*result);
tdelete(&rec, &tree->root, xtree_i_compare);
free(zombie);
return userdata;
}
xtreePos_t xtreeFind(void *treehandle, char *key)
{
xtree_t *tree = treehandle;
treerec_t **result, rec;
if (!tree) return NULL;
rec.key = key;
rec.userdata = NULL;
rec.compare = tree->compare;
result = tfind(&rec, &tree->root, xtree_i_compare);
return (result ? *result : NULL);
}
static void xtree_i_action(const void *nodep, const VISIT which, const int depth)
{
treerec_t *rec = NULL;
switch (which) {
case preorder:
break;
case postorder:
rec = *(treerec_t **) nodep;
break;
case endorder:
break;
case leaf:
rec = *(treerec_t **) nodep;
break;
}
if (rec) {
/*
* Each time here, we have rec pointing to the next record in the tree, and i_curr is then
* pointing to the previous record. So build a linked list of the records going backwards
* as we move through the tree.
*
* R0 <- R1:link <- R2:link <- R3:link
* ^
* i_curr
*
* becomes
*
* R0 <- R1:link <- R2:link <- R3:link <- rec:link
* ^
* i_curr
*/
rec->link = i_curr;
i_curr = rec;
}
}
xtreePos_t xtreeFirst(void *treehandle)
{
xtree_t *tree = treehandle;
treerec_t *walk, *right, *left;
if (!tree) return NULL;
i_curr = NULL;
twalk(tree->root, xtree_i_action);
if (!i_curr) return NULL;
/*
* We have walked the tree and created a reverse-linked list of the records.
* Now reverse the list so we get the records in the right sequence.
* i_curr points to the last entry.
*
* R1 <- R2 <- R3 <- R4
* ^
* i_curr
*
* must be reversed to
*
* R1 -> R2 -> R3 -> R4
*/
walk = i_curr;
right = NULL;
while (walk->link) {
left = walk->link;
walk->link = right;
right = walk;
walk = left;
}
walk->link = right;
i_curr = NULL;
return walk;
}
xtreePos_t xtreeNext(void *treehandle, xtreePos_t pos)
{
return pos ? ((treerec_t *)pos)->link : NULL;
}
char *xtreeKey(void *treehandle, xtreePos_t pos)
{
return pos ? ((treerec_t *)pos)->key : NULL;
}
void *xtreeData(void *treehandle, xtreePos_t pos)
{
return pos ? ((treerec_t *)pos)->userdata : NULL;
}
#else
typedef struct treerec_t {
char *key;
void *userdata;
int deleted;
} treerec_t;
typedef struct xtree_t {
treerec_t *entries;
xtreePos_t treesz;
int (*compare)(const char *a, const char *b);
} xtree_t;
static xtreePos_t binsearch(xtree_t *mytree, char *key)
{
xtreePos_t uplim, lowlim, n;
if (!key) return -1;
/* Do a binary search */
lowlim = 0; uplim = mytree->treesz-1;
do {
xtreePos_t res;
n = (uplim + lowlim) / 2;
res = mytree->compare(key, mytree->entries[n].key);
if (res == 0) {
/* Found it! */
uplim = -1; /* To exit loop */
}
else if (res > 0) {
/* Higher up */
lowlim = n+1;
}
else {
/* Further down */
uplim = n-1;
}
} while ((uplim >= 0) && (lowlim <= uplim));
return n;
}
void *xtreeNew(int(*xtreeCompare)(const char *a, const char *b))
{
xtree_t *newtree = (xtree_t *)calloc(1, sizeof(xtree_t));
newtree->compare = xtreeCompare;
return newtree;
}
void xtreeDestroy(void *treehandle)
{
xtree_t *mytree = (xtree_t *)treehandle;
xtreePos_t i;
if (treehandle == NULL) return;
/* Must delete our privately held keys in the deleted records */
for (i = 0; (i < mytree->treesz); i++) {
if (mytree->entries[i].deleted) free(mytree->entries[i].key);
}
free(mytree->entries);
free(mytree);
}
xtreePos_t xtreeFind(void *treehandle, char *key)
{
xtree_t *mytree = (xtree_t *)treehandle;
xtreePos_t n;
/* Does tree exist ? Is it empty? */
if ((treehandle == NULL) || (mytree->treesz == 0)) return -1;
n = binsearch(mytree, key);
if ((n >= 0) && (n < mytree->treesz) && (mytree->entries[n].deleted == 0) && (mytree->compare(key, mytree->entries[n].key) == 0))
return n;
return -1;
}
xtreePos_t xtreeFirst(void *treehandle)
{
xtree_t *mytree = (xtree_t *)treehandle;
/* Does tree exist ? Is it empty? */
if ((treehandle == NULL) || (mytree->treesz == 0)) return -1;
return 0;
}
xtreePos_t xtreeNext(void *treehandle, xtreePos_t pos)
{
xtree_t *mytree = (xtree_t *)treehandle;
/* Does tree exist ? Is it empty? */
if ((treehandle == NULL) || (mytree->treesz == 0) || (pos >= (mytree->treesz - 1)) || (pos < 0)) return -1;
do {
pos++;
} while (mytree->entries[pos].deleted && (pos < mytree->treesz));
return (pos < mytree->treesz) ? pos : -1;
}
char *xtreeKey(void *treehandle, xtreePos_t pos)
{
xtree_t *mytree = (xtree_t *)treehandle;
/* Does tree exist ? Is it empty? */
if ((treehandle == NULL) || (mytree->treesz == 0) || (pos >= mytree->treesz) || (pos < 0)) return NULL;
return mytree->entries[pos].key;
}
void *xtreeData(void *treehandle, xtreePos_t pos)
{
xtree_t *mytree = (xtree_t *)treehandle;
/* Does tree exist ? Is it empty? */
if ((treehandle == NULL) || (mytree->treesz == 0) || (pos >= mytree->treesz) || (pos < 0)) return NULL;
return mytree->entries[pos].userdata;
}
xtreeStatus_t xtreeAdd(void *treehandle, char *key, void *userdata)
{
xtree_t *mytree = (xtree_t *)treehandle;
xtreePos_t n;
if (treehandle == NULL) return XTREE_STATUS_NOTREE;
if (mytree->treesz == 0) {
/* Empty tree, just add record */
mytree->entries = (treerec_t *)calloc(1, sizeof(treerec_t));
mytree->entries[0].key = key;
mytree->entries[0].userdata = userdata;
mytree->entries[0].deleted = 0;
}
else {
n = binsearch(mytree, key);
if ((n >= 0) && (n < mytree->treesz) && (mytree->compare(key, mytree->entries[n].key) == 0)) {
/* Record already exists */
if (mytree->entries[n].deleted != 0) {
/* Revive the old record. Note that we can now discard our privately held key */
free(mytree->entries[n].key);
mytree->entries[n].key = key;
mytree->entries[n].deleted = 0;
mytree->entries[n].userdata = userdata;
return XTREE_STATUS_OK;
}
else {
/* Error */
return XTREE_STATUS_DUPLICATE_KEY;
}
}
/* Must create new record */
if (mytree->compare(key, mytree->entries[mytree->treesz - 1].key) > 0) {
/* Add after all the others */
mytree->entries = (treerec_t *)realloc(mytree->entries, (1 + mytree->treesz)*sizeof(treerec_t));
mytree->entries[mytree->treesz].key = key;
mytree->entries[mytree->treesz].userdata = userdata;
mytree->entries[mytree->treesz].deleted = 0;
}
else if (mytree->compare(key, mytree->entries[0].key) < 0) {
/* Add before all the others */
treerec_t *newents = (treerec_t *)malloc((1 + mytree->treesz)*sizeof(treerec_t));
newents[0].key = key;
newents[0].userdata = userdata;
newents[0].deleted = 0;
memcpy(&(newents[1]), &(mytree->entries[0]), (mytree->treesz * sizeof(treerec_t)));
free(mytree->entries);
mytree->entries = newents;
}
else {
treerec_t *newents;
n = binsearch(mytree, key);
if (mytree->compare(mytree->entries[n].key, key) < 0) n++;
/*
* n now points to the record AFTER where we will insert data in the current list.
* So in the new list, the new record will be in position n.
* Check if this is a deleted record, if it is then we won't have to move anything.
*/
if (mytree->entries[n].deleted != 0) {
/* Deleted record, let's re-use it. */
free(mytree->entries[n].key);
mytree->entries[n].key = key;
mytree->entries[n].userdata = userdata;
mytree->entries[n].deleted = 0;
return XTREE_STATUS_OK;
}
/* Ok, must create a new list and copy entries there */
newents = (treerec_t *)malloc((1 + mytree->treesz)*sizeof(treerec_t));
/* Copy record 0..(n-1), i.e. n records */
memcpy(&(newents[0]), &(mytree->entries[0]), n*sizeof(treerec_t));
/* New record is the n'th record */
newents[n].key = key;
newents[n].userdata = userdata;
newents[n].deleted = 0;
/* Finally, copy records n..(treesz-1) from the old list to position (n+1) onwards in the new list */
memcpy(&(newents[n+1]), &(mytree->entries[n]), (mytree->treesz - n)*sizeof(treerec_t));
free(mytree->entries);
mytree->entries = newents;
}
}
mytree->treesz += 1;
return XTREE_STATUS_OK;
}
void *xtreeDelete(void *treehandle, char *key)
{
xtree_t *mytree = (xtree_t *)treehandle;
xtreePos_t n;
if (treehandle == NULL) return NULL;
if (mytree->treesz == 0) return NULL; /* Empty tree */
n = binsearch(mytree, key);
if ((n >= 0) && (n < mytree->treesz) && (mytree->entries[n].deleted == 0) && (mytree->compare(key, mytree->entries[n].key) == 0)) {
mytree->entries[n].key = strdup(mytree->entries[n].key); /* Must dup the key, since user may discard it */
mytree->entries[n].deleted = 1;
return mytree->entries[n].userdata;
}
return NULL;
}
#endif
#ifdef STANDALONE
int main(int argc, char **argv)
{
char buf[1024], key[1024], data[1024];
void *th = NULL;
xtreePos_t n;
xtreeStatus_t stat;
char *rec, *p;
do {
printf("New, Add, Find, Delete, dUmp, deStroy : "); fflush(stdout);
if (fgets(buf, sizeof(buf), stdin) == NULL) return 0;
switch (*buf) {
case 'N': case 'n':
th = xtreeNew(strcasecmp);
break;
case 'A': case 'a':
printf("Key:");fflush(stdout); fgets(key, sizeof(key), stdin);
p = strchr(key, '\n'); if (p) *p = '\0';
printf("Data:");fflush(stdout); fgets(data, sizeof(data), stdin);
p = strchr(data, '\n'); if (p) *p = '\0';
stat = xtreeAdd(th, strdup(key), strdup(data));
printf("Result: %d\n", stat);
break;
case 'D': case 'd':
printf("Key:");fflush(stdout); fgets(key, sizeof(key), stdin);
p = strchr(key, '\n'); if (p) *p = '\0';
rec = xtreeDelete(th, key);
if (rec) {
printf("Existing record deleted: Data was '%s'\n", rec);
}
else {
printf("No record\n");
}
break;
case 'F': case 'f':
printf("Key:");fflush(stdout); fgets(key, sizeof(key), stdin);
p = strchr(key, '\n'); if (p) *p = '\0';
n = xtreeFind(th, key);
if (n != xtreeEnd(th)) {
printf("Found record: Data was '%s'\n", (char *)xtreeData(th, n));
}
else {
printf("No record\n");
}
break;
case 'U': case 'u':
n = xtreeFirst(th);
while (n != xtreeEnd(th)) {
printf("Key '%s', data '%s'\n", (char *)xtreeKey(th, n), (char *)xtreeData(th, n));
n = xtreeNext(th, n);
}
break;
case 'S': case 's':
xtreeDestroy(th);
th = NULL;
break;
}
} while (1);
return 0;
}
#endif
| gpl-2.0 |
MicroTrustRepos/microkernel | src/l4/pkg/uclibc/lib/contrib/uclibc/libc/misc/internals/tempname.c | 1 | 6740 | /* Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with the GNU C Library; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
/* March 11, 2002 Manuel Novoa III
*
* Modify code to remove dependency on libgcc long long arith support funcs.
*/
/* June 6, 2004 Erik Andersen
*
* Don't use brain damaged getpid() based randomness.
*/
/* April 15, 2005 Mike Frysinger
*
* Use brain damaged getpid() if real random fails.
*/
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include "tempname.h"
/* Return nonzero if DIR is an existent directory. */
static int direxists (const char *dir)
{
struct stat buf;
return stat(dir, &buf) == 0 && S_ISDIR (buf.st_mode);
}
/* Path search algorithm, for tmpnam, tmpfile, etc. If DIR is
non-null and exists, uses it; otherwise uses the first of $TMPDIR,
P_tmpdir, /tmp that exists. Copies into TMPL a template suitable
for use with mk[s]temp. Will fail (-1) if DIR is non-null and
doesn't exist, none of the searched dirs exists, or there's not
enough space in TMPL. */
int attribute_hidden ___path_search (char *tmpl, size_t tmpl_len, const char *dir,
const char *pfx /*, int try_tmpdir*/)
{
/*const char *d; */
size_t dlen, plen;
if (!pfx || !pfx[0])
{
pfx = "file";
plen = 4;
}
else
{
plen = strlen (pfx);
if (plen > 5)
plen = 5;
}
/* Disable support for $TMPDIR */
#if 0
if (try_tmpdir)
{
d = __secure_getenv ("TMPDIR");
if (d != NULL && direxists (d))
dir = d;
else if (dir != NULL && direxists (dir))
/* nothing */ ;
else
dir = NULL;
}
#endif
if (dir == NULL)
{
if (direxists (P_tmpdir))
dir = P_tmpdir;
else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
dir = "/tmp";
else
{
__set_errno (ENOENT);
return -1;
}
}
dlen = strlen (dir);
while (dlen > 1 && dir[dlen - 1] == '/')
dlen--; /* remove trailing slashes */
/* check we have room for "${dir}/${pfx}XXXXXX\0" */
if (tmpl_len < dlen + 1 + plen + 6 + 1)
{
__set_errno (EINVAL);
return -1;
}
sprintf (tmpl, "%.*s/%.*sXXXXXX", (int)dlen, dir, (int)plen, pfx);
return 0;
}
/* These are the characters used in temporary filenames. */
static const char letters[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
#define NUM_LETTERS (62)
static unsigned int fillrand(unsigned char *buf, unsigned int len)
{
int fd;
unsigned int result = -1;
fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) {
fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
}
if (fd >= 0) {
result = read(fd, buf, len);
close(fd);
}
return result;
}
static void brain_damaged_fillrand(unsigned char *buf, unsigned int len)
{
unsigned int i, k;
struct timeval tv;
uint32_t high, low, rh;
static uint64_t value;
gettimeofday(&tv, NULL);
value += ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec ^ getpid();
low = value & UINT32_MAX;
high = value >> 32;
for (i = 0; i < len; ++i) {
rh = high % NUM_LETTERS;
high /= NUM_LETTERS;
#define L ((UINT32_MAX % NUM_LETTERS + 1) % NUM_LETTERS)
k = (low % NUM_LETTERS) + (L * rh);
#undef L
#define H ((UINT32_MAX / NUM_LETTERS) + ((UINT32_MAX % NUM_LETTERS + 1) / NUM_LETTERS))
low = (low / NUM_LETTERS) + (H * rh) + (k / NUM_LETTERS);
#undef H
k %= NUM_LETTERS;
buf[i] = letters[k];
}
}
/* Generate a temporary file name based on TMPL. TMPL must match the
rules for mk[s]temp (i.e. end in "XXXXXX"). The name constructed
does not exist at the time of the call to __gen_tempname. TMPL is
overwritten with the result.
KIND may be one of:
__GT_NOCREATE: simply verify that the name does not exist
at the time of the call. mode argument is ignored.
__GT_FILE: create the file using open(O_CREAT|O_EXCL)
and return a read-write fd with given mode.
__GT_BIGFILE: same as __GT_FILE but use open64().
__GT_DIR: create a directory with given mode.
*/
int __gen_tempname (char *tmpl, int kind, mode_t mode)
{
char *XXXXXX;
unsigned int i;
int fd, save_errno = errno;
unsigned char randomness[6];
size_t len;
len = strlen (tmpl);
/* This is where the Xs start. */
XXXXXX = tmpl + len - 6;
if (len < 6 || strcmp (XXXXXX, "XXXXXX"))
{
__set_errno (EINVAL);
return -1;
}
for (i = 0; i < TMP_MAX; ++i) {
int j;
/* Get some random data. */
if (fillrand(randomness, sizeof(randomness)) != sizeof(randomness)) {
/* if random device nodes failed us, lets use the braindamaged ver */
brain_damaged_fillrand(randomness, sizeof(randomness));
}
for (j = 0; j < sizeof(randomness); ++j)
XXXXXX[j] = letters[randomness[j] % NUM_LETTERS];
switch (kind) {
case __GT_NOCREATE:
{
struct stat st;
if (stat (tmpl, &st) < 0) {
if (errno == ENOENT) {
fd = 0;
goto restore_and_ret;
} else
/* Give up now. */
return -1;
} else
fd = 0;
}
case __GT_FILE:
fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL, mode);
break;
#if defined __UCLIBC_HAS_LFS__
case __GT_BIGFILE:
fd = open64 (tmpl, O_RDWR | O_CREAT | O_EXCL, mode);
break;
#endif
case __GT_DIR:
fd = mkdir (tmpl, mode);
break;
default:
fd = -1;
assert (! "invalid KIND in __gen_tempname");
}
if (fd >= 0) {
restore_and_ret:
__set_errno (save_errno);
return fd;
}
else if (errno != EEXIST)
/* Any other error will apply also to other names we might
try, and there are 2^32 or so of them, so give up now. */
return -1;
}
/* We got out of the loop because we ran out of combinations to try. */
__set_errno (EEXIST);
return -1;
}
| gpl-2.0 |
eckucukoglu/sober-kernel | arch/arm/mach-omap2/board-omap4panda.c | 1 | 17889 | /*
* Chipsee pandaboard-es expansion set
* edition by Emre Can Kucukoglu <eckucukoglu@gmail.com>
*
* Board support file for OMAP4430 based PandaBoard.
*
* Copyright (C) 2010 Texas Instruments
*
* Author: David Anders <x0132446@ti.com>
*
* Based on mach-omap2/board-4430sdp.c
*
* Author: Santosh Shilimkar <santosh.shilimkar@ti.com>
*
* Based on mach-omap2/board-3430sdp.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/clk.h>
#include <linux/io.h>
#include <linux/leds.h>
#include <linux/gpio.h>
#include <linux/usb/otg.h>
#include <linux/i2c/twl.h>
#include <linux/mfd/twl6040.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/fixed.h>
#include <linux/ti_wilink_st.h>
#include <linux/usb/musb.h>
#include <linux/usb/phy.h>
#include <linux/usb/nop-usb-xceiv.h>
#include <linux/wl12xx.h>
#include <linux/irqchip/arm-gic.h>
#include <linux/platform_data/omap-abe-twl6040.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <linux/spi/ads7846.h>
#include <linux/spi/spi.h>
#include "id.h"
#include "common.h"
#include "soc.h"
#include "mmc.h"
#include "hsmmc.h"
#include "control.h"
#include "mux.h"
#include "common-board-devices.h"
#include "dss-common.h"
#define GPIO_HUB_POWER 1
#define GPIO_HUB_NRESET 62
#define GPIO_WIFI_PMENA 43
#define GPIO_WIFI_IRQ 53
/* wl127x BT, FM, GPS connectivity chip */
static struct ti_st_plat_data wilink_platform_data = {
.nshutdown_gpio = 46,
.dev_name = "/dev/ttyO1",
.flow_cntrl = 1,
.baud_rate = 3000000,
.chip_enable = NULL,
.suspend = NULL,
.resume = NULL,
};
static struct platform_device wl1271_device = {
.name = "kim",
.id = -1,
.dev = {
.platform_data = &wilink_platform_data,
},
};
static struct gpio_led gpio_leds[] = {
{
.name = "pandaboard::status1",
.default_trigger = "heartbeat",
.gpio = 7,
},
{
.name = "pandaboard::status2",
.default_trigger = "mmc0",
.gpio = 8,
},
};
static struct gpio_led_platform_data gpio_led_info = {
.leds = gpio_leds,
.num_leds = ARRAY_SIZE(gpio_leds),
};
static struct platform_device leds_gpio = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &gpio_led_info,
},
};
static struct omap_abe_twl6040_data panda_abe_audio_data = {
/* Audio out */
.has_hs = ABE_TWL6040_LEFT | ABE_TWL6040_RIGHT,
/* HandsFree through expansion connector */
.has_hf = ABE_TWL6040_LEFT | ABE_TWL6040_RIGHT,
/* PandaBoard: FM TX, PandaBoardES: can be connected to audio out */
.has_aux = ABE_TWL6040_LEFT | ABE_TWL6040_RIGHT,
/* PandaBoard: FM RX, PandaBoardES: audio in */
.has_afm = ABE_TWL6040_LEFT | ABE_TWL6040_RIGHT,
/* No jack detection. */
.jack_detection = 0,
/* MCLK input is 38.4MHz */
.mclk_freq = 38400000,
};
static struct platform_device panda_abe_audio = {
.name = "omap-abe-twl6040",
.id = -1,
.dev = {
.platform_data = &panda_abe_audio_data,
},
};
static struct platform_device panda_hdmi_audio_codec = {
.name = "hdmi-audio-codec",
.id = -1,
};
static struct platform_device btwilink_device = {
.name = "btwilink",
.id = -1,
};
/* PHY device on HS USB Port 1 i.e. nop_usb_xceiv.1 */
static struct nop_usb_xceiv_platform_data hsusb1_phy_data = {
/* FREF_CLK3 provides the 19.2 MHz reference clock to the PHY */
.clk_rate = 19200000,
};
static struct usbhs_phy_data phy_data[] __initdata = {
{
.port = 1,
.reset_gpio = GPIO_HUB_NRESET,
.vcc_gpio = GPIO_HUB_POWER,
.vcc_polarity = 1,
.platform_data = &hsusb1_phy_data,
},
};
static struct platform_device *panda_devices[] __initdata = {
&leds_gpio,
&wl1271_device,
&panda_abe_audio,
&panda_hdmi_audio_codec,
&btwilink_device,
};
static struct usbhs_omap_platform_data usbhs_bdata __initdata = {
.port_mode[0] = OMAP_EHCI_PORT_MODE_PHY,
};
static void __init omap4_ehci_init(void)
{
int ret;
/* FREF_CLK3 provides the 19.2 MHz reference clock to the PHY */
ret = clk_add_alias("main_clk", "nop_usb_xceiv.1", "auxclk3_ck", NULL);
if (ret)
pr_err("Failed to add main_clk alias to auxclk3_ck\n");
usbhs_init_phys(phy_data, ARRAY_SIZE(phy_data));
usbhs_init(&usbhs_bdata);
}
static struct omap_musb_board_data musb_board_data = {
.interface_type = MUSB_INTERFACE_UTMI,
.mode = MUSB_OTG,
.power = 100,
};
static struct omap2_hsmmc_info mmc[] = {
{
.mmc = 1,
.caps = MMC_CAP_4_BIT_DATA | MMC_CAP_8_BIT_DATA,
.gpio_wp = -EINVAL,
.gpio_cd = -EINVAL,
},
{
.name = "wl1271",
.mmc = 5,
.caps = MMC_CAP_4_BIT_DATA | MMC_CAP_POWER_OFF_CARD,
.gpio_wp = -EINVAL,
.gpio_cd = -EINVAL,
.ocr_mask = MMC_VDD_165_195,
.nonremovable = true,
},
{} /* Terminator */
};
static struct regulator_consumer_supply omap4_panda_vmmc5_supply[] = {
REGULATOR_SUPPLY("vmmc", "omap_hsmmc.4"),
};
static struct regulator_init_data panda_vmmc5 = {
.constraints = {
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(omap4_panda_vmmc5_supply),
.consumer_supplies = omap4_panda_vmmc5_supply,
};
static struct fixed_voltage_config panda_vwlan = {
.supply_name = "vwl1271",
.microvolts = 1800000, /* 1.8V */
.gpio = GPIO_WIFI_PMENA,
.startup_delay = 70000, /* 70msec */
.enable_high = 1,
.enabled_at_boot = 0,
.init_data = &panda_vmmc5,
};
static struct platform_device omap_vwlan_device = {
.name = "reg-fixed-voltage",
.id = 1,
.dev = {
.platform_data = &panda_vwlan,
},
};
static struct wl12xx_platform_data omap_panda_wlan_data __initdata = {
.board_ref_clock = WL12XX_REFCLOCK_38, /* 38.4 MHz */
};
static struct twl6040_codec_data twl6040_codec = {
/* single-step ramp for headset and handsfree */
.hs_left_step = 0x0f,
.hs_right_step = 0x0f,
.hf_left_step = 0x1d,
.hf_right_step = 0x1d,
};
static struct twl6040_platform_data twl6040_data = {
.codec = &twl6040_codec,
.audpwron_gpio = 127,
};
static struct i2c_board_info __initdata panda_i2c_1_boardinfo[] = {
{
I2C_BOARD_INFO("twl6040", 0x4b),
/* OMAP44XX_IRQ_GIC_START = 32 */
.irq = 119 + OMAP44XX_IRQ_GIC_START,
.platform_data = &twl6040_data,
},
};
/* Panda board uses the common PMIC configuration */
static struct twl4030_platform_data omap4_panda_twldata;
/*
* Display monitor features are burnt in their EEPROM as EDID data. The EEPROM
* is connected as I2C slave device, and can be accessed at address 0x50
*/
static struct i2c_board_info __initdata panda_i2c_eeprom[] = {
{
I2C_BOARD_INFO("eeprom", 0x50),
},
};
/* ft5x06 touchscreen device is not used in pandaboard-es-exp set */
/*
static struct i2c_board_info __initdata panda_i2c2_boardinfo[] = {
{
I2C_BOARD_INFO("ft5x06_ts", 0x38),
},
};
*/
static int __init omap4_panda_i2c_init(void)
{
omap4_pmic_get_config(&omap4_panda_twldata, TWL_COMMON_PDATA_USB,
TWL_COMMON_REGULATOR_VDAC |
TWL_COMMON_REGULATOR_VAUX2 |
TWL_COMMON_REGULATOR_VAUX3 |
TWL_COMMON_REGULATOR_VMMC |
TWL_COMMON_REGULATOR_VPP |
TWL_COMMON_REGULATOR_VANA |
TWL_COMMON_REGULATOR_VCXIO |
TWL_COMMON_REGULATOR_VUSB |
TWL_COMMON_REGULATOR_CLK32KG |
TWL_COMMON_REGULATOR_V1V8 |
TWL_COMMON_REGULATOR_V2V1);
omap4_pmic_init("twl6030", &omap4_panda_twldata, panda_i2c_1_boardinfo,
ARRAY_SIZE(panda_i2c_1_boardinfo));
omap_register_i2c_bus(2, 400, NULL, 0);
//panda_i2c2_boardinfo[0].irq = gpio_to_irq(34);
//omap_register_i2c_bus(2, 100, panda_i2c2_boardinfo,
// ARRAY_SIZE(panda_i2c2_boardinfo));
/*
* Bus 3 is attached to the DVI port where devices like the pico DLP
* projector don't work reliably with 400kHz
*/
omap_register_i2c_bus(3, 100, panda_i2c_eeprom,
ARRAY_SIZE(panda_i2c_eeprom));
omap_register_i2c_bus(4, 400, NULL, 0);
return 0;
}
#ifdef CONFIG_OMAP_MUX
static struct omap_board_mux board_mux[] __initdata = {
/* WLAN IRQ - GPIO 53 */
// OMAP4_MUX(GPMC_NCS3, OMAP_MUX_MODE3 | OMAP_PIN_INPUT),
/* WLAN POWER ENABLE - GPIO 43 */
// OMAP4_MUX(GPMC_A19, OMAP_MUX_MODE3 | OMAP_PIN_OUTPUT),
/* WLAN SDIO: MMC5 CMD */
OMAP4_MUX(SDMMC5_CMD, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
/* WLAN SDIO: MMC5 CLK */
OMAP4_MUX(SDMMC5_CLK, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
/* WLAN SDIO: MMC5 DAT[0-3] */
OMAP4_MUX(SDMMC5_DAT0, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
OMAP4_MUX(SDMMC5_DAT1, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
OMAP4_MUX(SDMMC5_DAT2, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
OMAP4_MUX(SDMMC5_DAT3, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
/* gpio 0 - TFP410 PD */
OMAP4_MUX(KPD_COL1, OMAP_PIN_OUTPUT | OMAP_MUX_MODE3),
/* dispc2_data23 */
OMAP4_MUX(USBB2_ULPITLL_STP, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data22 */
OMAP4_MUX(USBB2_ULPITLL_DIR, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data21 */
OMAP4_MUX(USBB2_ULPITLL_NXT, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data20 */
OMAP4_MUX(USBB2_ULPITLL_DAT0, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data19 */
OMAP4_MUX(USBB2_ULPITLL_DAT1, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data18 */
OMAP4_MUX(USBB2_ULPITLL_DAT2, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data15 */
OMAP4_MUX(USBB2_ULPITLL_DAT3, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data14 */
OMAP4_MUX(USBB2_ULPITLL_DAT4, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data13 */
OMAP4_MUX(USBB2_ULPITLL_DAT5, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data12 */
OMAP4_MUX(USBB2_ULPITLL_DAT6, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data11 */
OMAP4_MUX(USBB2_ULPITLL_DAT7, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data10 */
OMAP4_MUX(DPM_EMU3, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data9 */
OMAP4_MUX(DPM_EMU4, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data16 */
OMAP4_MUX(DPM_EMU5, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data17 */
OMAP4_MUX(DPM_EMU6, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_hsync */
OMAP4_MUX(DPM_EMU7, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_pclk */
OMAP4_MUX(DPM_EMU8, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_vsync */
OMAP4_MUX(DPM_EMU9, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_de */
OMAP4_MUX(DPM_EMU10, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data8 */
OMAP4_MUX(DPM_EMU11, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data7 */
OMAP4_MUX(DPM_EMU12, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data6 */
OMAP4_MUX(DPM_EMU13, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data5 */
OMAP4_MUX(DPM_EMU14, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data4 */
OMAP4_MUX(DPM_EMU15, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data3 */
OMAP4_MUX(DPM_EMU16, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data2 */
OMAP4_MUX(DPM_EMU17, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data1 */
OMAP4_MUX(DPM_EMU18, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data0 */
OMAP4_MUX(DPM_EMU19, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* NIRQ2 for twl6040 */
// OMAP4_MUX(SYS_NIRQ2, OMAP_MUX_MODE0 |
// OMAP_PIN_INPUT_PULLUP | OMAP_PIN_OFF_WAKEUPENABLE),
/* GPIO_127 for twl6040 */
// OMAP4_MUX(HDQ_SIO, OMAP_MUX_MODE3 | OMAP_PIN_OUTPUT),
/* McPDM */
// OMAP4_MUX(ABE_PDM_UL_DATA, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLDOWN),
// OMAP4_MUX(ABE_PDM_DL_DATA, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLDOWN),
// OMAP4_MUX(ABE_PDM_FRAME, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
// OMAP4_MUX(ABE_PDM_LB_CLK, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLDOWN),
// OMAP4_MUX(ABE_CLKS, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLDOWN),
/* McBSP1 */
// OMAP4_MUX(ABE_MCBSP1_CLKX, OMAP_MUX_MODE0 | OMAP_PIN_INPUT),
// OMAP4_MUX(ABE_MCBSP1_DR, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLDOWN),
// OMAP4_MUX(ABE_MCBSP1_DX, OMAP_MUX_MODE0 | OMAP_PIN_OUTPUT |
// OMAP_PULL_ENA),
// OMAP4_MUX(ABE_MCBSP1_FSX, OMAP_MUX_MODE0 | OMAP_PIN_INPUT),
/* UART2 - BT/FM/GPS shared transport */
// OMAP4_MUX(UART2_CTS, OMAP_PIN_INPUT | OMAP_MUX_MODE0),
// OMAP4_MUX(UART2_RTS, OMAP_PIN_OUTPUT | OMAP_MUX_MODE0),
// OMAP4_MUX(UART2_RX, OMAP_PIN_INPUT | OMAP_MUX_MODE0),
// OMAP4_MUX(UART2_TX, OMAP_PIN_OUTPUT | OMAP_MUX_MODE0),
/* TOUCHSCREEN IRQ */
OMAP4_MUX(GPMC_AD15, OMAP_MUX_MODE3 | OMAP_PIN_INPUT | OMAP_PIN_OFF_WAKEUPENABLE),
/* LCD Backlight - GPIO 50 */
OMAP4_MUX(GPMC_NCS0, OMAP_MUX_MODE3 | OMAP_PIN_OUTPUT),
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
/*
* Since generic board serial initialization can
* handle chipsee expansion properties, no need
* to set explicitly these settings:
*/
/*
static struct omap_device_pad serial2_pads[] __initdata = {
OMAP_MUX_STATIC("uart2_cts.uart2_cts",
OMAP_PIN_INPUT_PULLUP | OMAP_MUX_MODE0),
OMAP_MUX_STATIC("uart2_rts.uart2_rts",
OMAP_PIN_OUTPUT | OMAP_MUX_MODE0),
OMAP_MUX_STATIC("uart2_rx.uart2_rx",
OMAP_PIN_INPUT_PULLUP | OMAP_MUX_MODE0),
OMAP_MUX_STATIC("uart2_tx.uart2_tx",
OMAP_PIN_OUTPUT | OMAP_MUX_MODE0),
};
static struct omap_device_pad serial3_pads[] __initdata = {
OMAP_MUX_STATIC("uart3_cts_rctx.uart3_cts_rctx",
OMAP_PIN_INPUT_PULLUP | OMAP_MUX_MODE0),
OMAP_MUX_STATIC("uart3_rts_sd.uart3_rts_sd",
OMAP_PIN_OUTPUT | OMAP_MUX_MODE0),
OMAP_MUX_STATIC("uart3_rx_irrx.uart3_rx_irrx",
OMAP_PIN_INPUT | OMAP_MUX_MODE0),
OMAP_MUX_STATIC("uart3_tx_irtx.uart3_tx_irtx",
OMAP_PIN_OUTPUT | OMAP_MUX_MODE0),
};
static struct omap_device_pad serial4_pads[] __initdata = {
OMAP_MUX_STATIC("uart4_rx.uart4_rx",
OMAP_PIN_INPUT | OMAP_MUX_MODE0),
OMAP_MUX_STATIC("uart4_tx.uart4_tx",
OMAP_PIN_OUTPUT | OMAP_MUX_MODE0),
};
static struct omap_board_data serial2_data __initdata = {
.id = 1,
.pads = serial2_pads,
.pads_cnt = ARRAY_SIZE(serial2_pads),
};
static struct omap_board_data serial3_data __initdata = {
.id = 2,
.pads = serial3_pads,
.pads_cnt = ARRAY_SIZE(serial3_pads),
};
static struct omap_board_data serial4_data __initdata = {
.id = 3,
.pads = serial4_pads,
.pads_cnt = ARRAY_SIZE(serial4_pads),
};
static inline void board_serial_init(void)
{
struct omap_board_data bdata;
bdata.flags = 0;
bdata.pads = NULL;
bdata.pads_cnt = 0;
bdata.id = 0;
// pass dummy data for UART1
omap_serial_init_port(&bdata, NULL);
omap_serial_init_port(&serial2_data, NULL);
omap_serial_init_port(&serial3_data, NULL);
omap_serial_init_port(&serial4_data, NULL);
}
*/
#else
#define board_mux NULL
#endif
#define PANDABOARD_TS_GPIO 39
#include <linux/platform_data/spi-omap2-mcspi.h>
static struct omap2_mcspi_device_config ads7846_mcspi_config = {
.turbo_mode = 0,
};
static int ads7846_get_pendown_state(void)
{
return !gpio_get_value(PANDABOARD_TS_GPIO);
}
struct ads7846_platform_data ads7846_config = {
.x_max = 0xFFF,
.y_max = 0xFFF,
.x_plate_ohms = 180,
.pressure_max = 255,
.debounce_max = 10,
.debounce_tol = 3,
.debounce_rep = 1,
.get_pendown_state = ads7846_get_pendown_state,
.keep_vref_on = 1,
.wakeup = true,
};
struct spi_board_info pandaboard_spi_board_info[] = {
[0] = {
.modalias = "ads7846",
.bus_num = 1,
.chip_select = 0,
.max_speed_hz = 1500000,
.controller_data = &ads7846_mcspi_config,
.platform_data = &ads7846_config,
},
};
static void ads7846_dev_init(void)
{
int r;
printk("Initialize ads7846 touch screen controller\n");
if (gpio_request(PANDABOARD_TS_GPIO, "ADS7846 pendown") < 0)
printk(KERN_ERR "can't get ads7846 pen down GPIO\n");
r = gpio_direction_input(PANDABOARD_TS_GPIO);
printk("MMIS: ads7846_dev_init:gpio_direction_input: %d\n", r);
gpio_set_debounce(PANDABOARD_TS_GPIO, 1);
}
static void omap4_panda_init_rev(void)
{
if (cpu_is_omap443x()) {
/* PandaBoard 4430 */
/* ASoC audio configuration */
panda_abe_audio_data.card_name = "PandaBoard";
panda_abe_audio_data.has_hsmic = 1;
} else {
/* PandaBoard ES */
/* ASoC audio configuration */
panda_abe_audio_data.card_name = "PandaBoardES";
}
}
static void __init omap4_panda_init(void)
{
int package = OMAP_PACKAGE_CBS;
int ret;
if (omap_rev() == OMAP4430_REV_ES1_0)
package = OMAP_PACKAGE_CBL;
omap4_mux_init(board_mux, NULL, package);
omap_panda_wlan_data.irq = gpio_to_irq(GPIO_WIFI_IRQ);
ret = wl12xx_set_platform_data(&omap_panda_wlan_data);
if (ret)
pr_err("error setting wl12xx data: %d\n", ret);
omap4_panda_init_rev();
omap4_panda_i2c_init();
pandaboard_spi_board_info[0].irq = gpio_to_irq(PANDABOARD_TS_GPIO);
spi_register_board_info(pandaboard_spi_board_info, ARRAY_SIZE(pandaboard_spi_board_info));
ads7846_dev_init();
platform_add_devices(panda_devices, ARRAY_SIZE(panda_devices));
platform_device_register(&omap_vwlan_device);
/* Generic board serial initialization can handle expansion properties */
// board_serial_init();
omap_serial_init();
omap_sdrc_init(NULL, NULL);
omap4_twl6030_hsmmc_init(mmc);
omap4_ehci_init();
usb_bind_phy("musb-hdrc.2.auto", 0, "omap-usb2.3.auto");
usb_musb_init(&musb_board_data);
omap4_panda_display_init();
}
static const char *omap4_panda_match[] __initdata = {
"ti,omap4-panda",
NULL,
};
MACHINE_START(OMAP4_PANDA, "OMAP4 Panda board")
/* Maintainer: David Anders - Texas Instruments Inc */
.atag_offset = 0x100,
.smp = smp_ops(omap4_smp_ops),
.reserve = omap_reserve,
.map_io = omap4_map_io,
.init_early = omap4430_init_early,
.init_irq = gic_init_irq,
.init_machine = omap4_panda_init,
.init_late = omap4430_init_late,
.init_time = omap4_local_timer_init,
.restart = omap44xx_restart,
.dt_compat = omap4_panda_match,
MACHINE_END
| gpl-2.0 |
morynicz/pyroshark | wiretap/logcat_text_brief.c | 1 | 12068 | /* logcat_text_brief.c
*
* Copyright 2014, Michal Orynicz for Tieto 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include <string.h>
#include <time.h>
#include "wtap-int.h"
#include "file_wrappers.h"
#include "buffer.h"
#include "logcat_text_brief.h"
enum dump_type_t {
DUMP_BINARY,
DUMP_BRIEF,
DUMP_PROCESS,
DUMP_TAG,
DUMP_TIME,
DUMP_THREAD,
DUMP_THREADTIME,
DUMP_LONG
};
struct dumper_t {
enum dump_type_t type;
};
static gchar get_priority(const guint8 *priority) {
static gchar priorities[] = "??VDIWEFS";
if (*priority >= (guint8) sizeof(priorities))
return '?';
return priorities[(int) *priority];
}
static gchar *logcat_text_brief_log(const struct dumper_t *dumper, guint32 seconds,
gint microseconds, gint pid, gint tid, gchar priority, const gchar *tag,
const gchar *log)
{
gchar time_buffer[15];
time_t datetime;
datetime = (time_t) seconds;
switch (dumper->type) {
case DUMP_BRIEF:
return g_strdup_printf("%c/%s(%5i): %s\n",
priority, tag, pid, log);
case DUMP_PROCESS:
return g_strdup_printf("%c(%5i) %s (%s)\n",
priority, pid, log, tag);
case DUMP_TAG:
return g_strdup_printf("%c/%s: %s\n",
priority, tag, log);
case DUMP_THREAD:
return g_strdup_printf("%c(%5i:%5i) %s\n",
priority, pid, tid, log);
case DUMP_TIME:
strftime(time_buffer, sizeof(time_buffer), "%m-%d %H:%M:%S",
gmtime(&datetime));
return g_strdup_printf("%s.%03i %c/%s(%5i): %s\n",
time_buffer, microseconds, priority, tag, pid, log);
case DUMP_THREADTIME:
strftime(time_buffer, sizeof(time_buffer), "%m-%d %H:%M:%S",
gmtime(&datetime));
return g_strdup_printf("%s.%03i %5i:%5i %c %s: %s\n",
time_buffer, microseconds, pid, tid, priority, tag, log);
case DUMP_LONG:
strftime(time_buffer, sizeof(time_buffer), "%m-%d %H:%M:%S",
gmtime(&datetime));
return g_strdup_printf("[ %s.%03i %5i:%5i %c/%s ]\n%s\n\n",
time_buffer, microseconds, pid, tid, priority, tag, log);
default:
return NULL;
}
}
static gboolean logcat_text_brief_read_packet(struct logcat_phdr *logcat, FILE_T fh,
struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info)
{
gint8 *pd;
gchar cbuff[WTAP_MAX_PACKET_SIZE];
if(file_eof(fh)) {
return FALSE;
}
file_gets(cbuff,WTAP_MAX_PACKET_SIZE,fh);
buffer_assure_space(buf, strlen(cbuff)+1);
pd = buffer_start_ptr(buf);
memcpy(pd,cbuff,strlen(cbuff)+1);
phdr->presence_flags = 0;
phdr->ts.secs = (time_t) 0;
phdr->ts.nsecs = (int) 0;
phdr->caplen = strlen(cbuff);
phdr->len = strlen(cbuff);
/* phdr->pseudo_header.logcat.version = logcat->version; */
return TRUE;
}
static gboolean logcat_text_brief_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
*data_offset = file_tell(wth->fh);
return logcat_text_brief_read_packet((struct logcat_phdr *) wth->priv, wth->fh,
&wth->phdr, wth->frame_buffer, err, err_info);
}
static gboolean logcat_text_brief_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
if (!logcat_text_brief_read_packet((struct logcat_phdr *) wth->priv, wth->random_fh,
phdr, buf, err, err_info)) {
if (*err == 0)
*err = WTAP_ERR_SHORT_READ;
return FALSE;
}
return TRUE;
}
int logcat_text_brief_open(wtap *wth, int *err, gchar **err_info)
{
gchar cbuff[WTAP_MAX_PACKET_SIZE];
if (file_seek(wth->fh, 0, SEEK_SET, err) == -1)
return -1;
do {
file_gets(cbuff,WTAP_MAX_PACKET_SIZE, wth->fh);
}while (g_regex_match_simple("[-]+\\sbeginning\\sof\\s\\/",cbuff,0,0));
if(!g_regex_match_simple("[IVDWE]/.*\\(\\s*[0-9]*\\):\\s.*",cbuff,0,0)) {
return -1;
}
if (file_seek(wth->fh, 0, SEEK_SET, err) == -1)
return -1;
wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_LOGCAT_BRIEF;
wth->file_encap = WTAP_ENCAP_LOGCAT_BRIEF;
wth->snapshot_length = 0;
wth->subtype_read = logcat_text_brief_read;
wth->subtype_seek_read = logcat_text_brief_seek_read;
wth->tsprecision = WTAP_FILE_TSPREC_USEC;
fprintf(stderr,"go\n");
return 1;
}
int logcat_text_brief_dump_can_write_encap(int encap)
{
if (encap == WTAP_ENCAP_PER_PACKET)
return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
if (encap != WTAP_ENCAP_LOGCAT)
return WTAP_ERR_UNSUPPORTED_ENCAP;
return 0;
}
static gboolean logcat_text_brief_binary_dump(wtap_dumper *wdh,
const struct wtap_pkthdr *phdr,
const guint8 *pd, int *err)
{
if (!wtap_dump_file_write(wdh, pd, phdr->caplen, err))
return FALSE;
wdh->bytes_dumped += phdr->caplen;
return TRUE;
}
gboolean logcat_text_brief_binary_dump_open(wtap_dumper *wdh, int *err)
{
wdh->subtype_write = logcat_text_brief_binary_dump;
wdh->subtype_close = NULL;
switch (wdh->file_type_subtype) {
case WTAP_FILE_TYPE_SUBTYPE_LOGCAT:
wdh->tsprecision = WTAP_FILE_TSPREC_USEC;
break;
default:
*err = WTAP_ERR_UNSUPPORTED_FILE_TYPE;
return FALSE;
}
return TRUE;
}
static gboolean logcat_text_brief_dump_text(wtap_dumper *wdh,
const struct wtap_pkthdr *phdr,
const guint8 *pd, int *err)
{
gchar *buf;
gint length;
gchar priority;
const gchar *tag;
const gint *pid;
const gint *tid;
const gchar *log;
gchar *log_part;
const gchar *str_begin;
const gchar *str_end;
const guint32 *datetime;
const guint32 *nanoseconds;
const union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
const struct dumper_t *dumper = (const struct dumper_t *) wdh->priv;
if (pseudo_header->logcat.version == 1) {
pid = (const gint *) (pd + 4);
tid = (const gint *) (pd + 2 * 4);
datetime = (const guint32 *) (pd + 3 * 4);
nanoseconds = (const guint32 *) (pd + 4 * 4);
priority = get_priority((const guint8 *) (pd + 5 * 4));
tag = (const gchar *) (pd + 5 * 4 + 1);
log = tag + strlen(tag) + 1;
} else if (pseudo_header->logcat.version == 2) {
pid = (const gint *) (pd + 4);
tid = (const gint *) (pd + 2 * 4);
datetime = (const guint32 *) (pd + 3 * 4);
nanoseconds = (const guint32 *) (pd + 4 * 4);
priority = get_priority((const guint8 *) (pd + 6 * 4));
tag = (const char *) (pd + 6 * 4 + 1);
log = tag + strlen(tag) + 1;
} else {
*err = WTAP_ERR_UNSUPPORTED;
return FALSE;
}
str_begin = str_end = log;
while (dumper->type != DUMP_LONG && (str_end = strchr(str_begin, '\n'))) {
log_part = (gchar *) g_malloc(str_end - str_begin + 1);
g_strlcpy(log_part, str_begin, str_end - str_begin);
log_part[str_end - str_begin] = '\0';
str_begin = str_end + 1;
buf = logcat_text_brief_log(dumper, *datetime, *nanoseconds / 1000000, *pid, *tid,
priority, tag, log_part);
if (!buf) {
g_free(log_part);
return FALSE;
}
g_free(log_part);
length = (guint32)strlen(buf);
if (!wtap_dump_file_write(wdh, buf, length, err)) {
g_free(buf);
return FALSE;
}
wdh->bytes_dumped += length;
g_free(buf);
}
if (*str_begin != '\0') {
log_part = (gchar *) g_malloc(strlen(str_begin) + 1);
g_strlcpy(log_part, str_begin, strlen(str_begin));
log_part[strlen(str_begin)] = '\0';
buf = logcat_text_brief_log(dumper, *datetime, *nanoseconds / 1000000, *pid, *tid,
priority, tag, log_part);
if (!buf) {
g_free(log_part);
return FALSE;
}
g_free(log_part);
length = (guint32)strlen(buf);
if (!wtap_dump_file_write(wdh, buf, length, err)) {
g_free(buf);
return FALSE;
}
wdh->bytes_dumped += length;
g_free(buf);
}
return TRUE;
}
gboolean logcat_text_brief_text_brief_dump_open(wtap_dumper *wdh, int *err _U_)
{
struct dumper_t *dumper;
dumper = (struct dumper_t *) g_malloc(sizeof(struct dumper_t));
dumper->type = DUMP_BRIEF;
wdh->priv = dumper;
wdh->subtype_write = logcat_text_brief_dump_text;
wdh->subtype_close = NULL;
return TRUE;
}
gboolean logcat_text_brief_text_process_dump_open(wtap_dumper *wdh, int *err _U_)
{
struct dumper_t *dumper;
dumper = (struct dumper_t *) g_malloc(sizeof(struct dumper_t));
dumper->type = DUMP_PROCESS;
wdh->priv = dumper;
wdh->subtype_write = logcat_text_brief_dump_text;
wdh->subtype_close = NULL;
return TRUE;
}
gboolean logcat_text_brief_text_tag_dump_open(wtap_dumper *wdh, int *err _U_)
{
struct dumper_t *dumper;
dumper = (struct dumper_t *) g_malloc(sizeof(struct dumper_t));
dumper->type = DUMP_TAG;
wdh->priv = dumper;
wdh->subtype_write = logcat_text_brief_dump_text;
wdh->subtype_close = NULL;
return TRUE;
}
gboolean logcat_text_brief_text_time_dump_open(wtap_dumper *wdh, int *err _U_)
{
struct dumper_t *dumper;
dumper = (struct dumper_t *) g_malloc(sizeof(struct dumper_t));
dumper->type = DUMP_TIME;
wdh->priv = dumper;
wdh->subtype_write = logcat_text_brief_dump_text;
wdh->subtype_close = NULL;
return TRUE;
}
gboolean logcat_text_brief_text_thread_dump_open(wtap_dumper *wdh, int *err _U_)
{
struct dumper_t *dumper;
dumper = (struct dumper_t *) g_malloc(sizeof(struct dumper_t));
dumper->type = DUMP_THREAD;
wdh->priv = dumper;
wdh->subtype_write = logcat_text_brief_dump_text;
wdh->subtype_close = NULL;
return TRUE;
}
gboolean logcat_text_brief_text_threadtime_dump_open(wtap_dumper *wdh, int *err _U_)
{
struct dumper_t *dumper;
dumper = (struct dumper_t *) g_malloc(sizeof(struct dumper_t));
dumper->type = DUMP_THREADTIME;
wdh->priv = dumper;
wdh->subtype_write = logcat_text_brief_dump_text;
wdh->subtype_close = NULL;
return TRUE;
}
gboolean logcat_text_brief_text_long_dump_open(wtap_dumper *wdh, int *err _U_)
{
struct dumper_t *dumper;
dumper = (struct dumper_t *) g_malloc(sizeof(struct dumper_t));
dumper->type = DUMP_LONG;
wdh->priv = dumper;
wdh->subtype_write = logcat_text_brief_dump_text;
wdh->subtype_close = NULL;
return TRUE;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| gpl-2.0 |
zhangjinke/WiFi_access_control_system | bsp/stm32f10x/Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_sdio.c | 1 | 28143 | /**
******************************************************************************
* @file stm32f10x_sdio.c
* @author MCD Application Team
* @version V3.5.0
* @date 11-March-2011
* @brief This file provides all the SDIO firmware functions.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x_sdio.h"
#include "stm32f10x_rcc.h"
/** @addtogroup STM32F10x_StdPeriph_Driver
* @{
*/
/** @defgroup SDIO
* @brief SDIO driver modules
* @{
*/
/** @defgroup SDIO_Private_TypesDefinitions
* @{
*/
/* ------------ SDIO registers bit address in the alias region ----------- */
#define SDIO_OFFSET (SDIO_BASE - PERIPH_BASE)
/* --- CLKCR Register ---*/
/* Alias word address of CLKEN bit */
#define CLKCR_OFFSET (SDIO_OFFSET + 0x04)
#define CLKEN_BitNumber 0x08
#define CLKCR_CLKEN_BB (PERIPH_BB_BASE + (CLKCR_OFFSET * 32) + (CLKEN_BitNumber * 4))
/* --- CMD Register ---*/
/* Alias word address of SDIOSUSPEND bit */
#define CMD_OFFSET (SDIO_OFFSET + 0x0C)
#define SDIOSUSPEND_BitNumber 0x0B
#define CMD_SDIOSUSPEND_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (SDIOSUSPEND_BitNumber * 4))
/* Alias word address of ENCMDCOMPL bit */
#define ENCMDCOMPL_BitNumber 0x0C
#define CMD_ENCMDCOMPL_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ENCMDCOMPL_BitNumber * 4))
/* Alias word address of NIEN bit */
#define NIEN_BitNumber 0x0D
#define CMD_NIEN_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (NIEN_BitNumber * 4))
/* Alias word address of ATACMD bit */
#define ATACMD_BitNumber 0x0E
#define CMD_ATACMD_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ATACMD_BitNumber * 4))
/* --- DCTRL Register ---*/
/* Alias word address of DMAEN bit */
#define DCTRL_OFFSET (SDIO_OFFSET + 0x2C)
#define DMAEN_BitNumber 0x03
#define DCTRL_DMAEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (DMAEN_BitNumber * 4))
/* Alias word address of RWSTART bit */
#define RWSTART_BitNumber 0x08
#define DCTRL_RWSTART_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTART_BitNumber * 4))
/* Alias word address of RWSTOP bit */
#define RWSTOP_BitNumber 0x09
#define DCTRL_RWSTOP_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTOP_BitNumber * 4))
/* Alias word address of RWMOD bit */
#define RWMOD_BitNumber 0x0A
#define DCTRL_RWMOD_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWMOD_BitNumber * 4))
/* Alias word address of SDIOEN bit */
#define SDIOEN_BitNumber 0x0B
#define DCTRL_SDIOEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (SDIOEN_BitNumber * 4))
/* ---------------------- SDIO registers bit mask ------------------------ */
/* --- CLKCR Register ---*/
/* CLKCR register clear mask */
#define CLKCR_CLEAR_MASK ((uint32_t)0xFFFF8100)
/* --- PWRCTRL Register ---*/
/* SDIO PWRCTRL Mask */
#define PWR_PWRCTRL_MASK ((uint32_t)0xFFFFFFFC)
/* --- DCTRL Register ---*/
/* SDIO DCTRL Clear Mask */
#define DCTRL_CLEAR_MASK ((uint32_t)0xFFFFFF08)
/* --- CMD Register ---*/
/* CMD Register clear mask */
#define CMD_CLEAR_MASK ((uint32_t)0xFFFFF800)
/* SDIO RESP Registers Address */
#define SDIO_RESP_ADDR ((uint32_t)(SDIO_BASE + 0x14))
/**
* @}
*/
/** @defgroup SDIO_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup SDIO_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup SDIO_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup SDIO_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup SDIO_Private_Functions
* @{
*/
/**
* @brief Deinitializes the SDIO peripheral registers to their default reset values.
* @param None
* @retval None
*/
void SDIO_DeInit(void)
{
SDIO->POWER = 0x00000000;
SDIO->CLKCR = 0x00000000;
SDIO->ARG = 0x00000000;
SDIO->CMD = 0x00000000;
SDIO->DTIMER = 0x00000000;
SDIO->DLEN = 0x00000000;
SDIO->DCTRL = 0x00000000;
SDIO->ICR = 0x00C007FF;
SDIO->MASK = 0x00000000;
}
/**
* @brief Initializes the SDIO peripheral according to the specified
* parameters in the SDIO_InitStruct.
* @param SDIO_InitStruct : pointer to a SDIO_InitTypeDef structure
* that contains the configuration information for the SDIO peripheral.
* @retval None
*/
void SDIO_Init(SDIO_InitTypeDef* SDIO_InitStruct)
{
uint32_t tmpreg = 0;
/* Check the parameters */
assert_param(IS_SDIO_CLOCK_EDGE(SDIO_InitStruct->SDIO_ClockEdge));
assert_param(IS_SDIO_CLOCK_BYPASS(SDIO_InitStruct->SDIO_ClockBypass));
assert_param(IS_SDIO_CLOCK_POWER_SAVE(SDIO_InitStruct->SDIO_ClockPowerSave));
assert_param(IS_SDIO_BUS_WIDE(SDIO_InitStruct->SDIO_BusWide));
assert_param(IS_SDIO_HARDWARE_FLOW_CONTROL(SDIO_InitStruct->SDIO_HardwareFlowControl));
/*---------------------------- SDIO CLKCR Configuration ------------------------*/
/* Get the SDIO CLKCR value */
tmpreg = SDIO->CLKCR;
/* Clear CLKDIV, PWRSAV, BYPASS, WIDBUS, NEGEDGE, HWFC_EN bits */
tmpreg &= CLKCR_CLEAR_MASK;
/* Set CLKDIV bits according to SDIO_ClockDiv value */
/* Set PWRSAV bit according to SDIO_ClockPowerSave value */
/* Set BYPASS bit according to SDIO_ClockBypass value */
/* Set WIDBUS bits according to SDIO_BusWide value */
/* Set NEGEDGE bits according to SDIO_ClockEdge value */
/* Set HWFC_EN bits according to SDIO_HardwareFlowControl value */
tmpreg |= (SDIO_InitStruct->SDIO_ClockDiv | SDIO_InitStruct->SDIO_ClockPowerSave |
SDIO_InitStruct->SDIO_ClockBypass | SDIO_InitStruct->SDIO_BusWide |
SDIO_InitStruct->SDIO_ClockEdge | SDIO_InitStruct->SDIO_HardwareFlowControl);
/* Write to SDIO CLKCR */
SDIO->CLKCR = tmpreg;
}
/**
* @brief Fills each SDIO_InitStruct member with its default value.
* @param SDIO_InitStruct: pointer to an SDIO_InitTypeDef structure which
* will be initialized.
* @retval None
*/
void SDIO_StructInit(SDIO_InitTypeDef* SDIO_InitStruct)
{
/* SDIO_InitStruct members default value */
SDIO_InitStruct->SDIO_ClockDiv = 0x00;
SDIO_InitStruct->SDIO_ClockEdge = SDIO_ClockEdge_Rising;
SDIO_InitStruct->SDIO_ClockBypass = SDIO_ClockBypass_Disable;
SDIO_InitStruct->SDIO_ClockPowerSave = SDIO_ClockPowerSave_Disable;
SDIO_InitStruct->SDIO_BusWide = SDIO_BusWide_1b;
SDIO_InitStruct->SDIO_HardwareFlowControl = SDIO_HardwareFlowControl_Disable;
}
/**
* @brief Enables or disables the SDIO Clock.
* @param NewState: new state of the SDIO Clock. This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SDIO_ClockCmd(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
*(__IO uint32_t *) CLKCR_CLKEN_BB = (uint32_t)NewState;
}
/**
* @brief Sets the power status of the controller.
* @param SDIO_PowerState: new state of the Power state.
* This parameter can be one of the following values:
* @arg SDIO_PowerState_OFF
* @arg SDIO_PowerState_ON
* @retval None
*/
void SDIO_SetPowerState(uint32_t SDIO_PowerState)
{
/* Check the parameters */
assert_param(IS_SDIO_POWER_STATE(SDIO_PowerState));
SDIO->POWER &= PWR_PWRCTRL_MASK;
SDIO->POWER |= SDIO_PowerState;
}
/**
* @brief Gets the power status of the controller.
* @param None
* @retval Power status of the controller. The returned value can
* be one of the following:
* - 0x00: Power OFF
* - 0x02: Power UP
* - 0x03: Power ON
*/
uint32_t SDIO_GetPowerState(void)
{
return (SDIO->POWER & (~PWR_PWRCTRL_MASK));
}
/**
* @brief Enables or disables the SDIO interrupts.
* @param SDIO_IT: specifies the SDIO interrupt sources to be enabled or disabled.
* This parameter can be one or a combination of the following values:
* @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt
* @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt
* @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt
* @arg SDIO_IT_DTIMEOUT: Data timeout interrupt
* @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt
* @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt
* @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt
* @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt
* @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt
* @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide
* bus mode interrupt
* @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt
* @arg SDIO_IT_CMDACT: Command transfer in progress interrupt
* @arg SDIO_IT_TXACT: Data transmit in progress interrupt
* @arg SDIO_IT_RXACT: Data receive in progress interrupt
* @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt
* @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt
* @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt
* @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt
* @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt
* @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt
* @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt
* @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt
* @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt
* @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt
* @param NewState: new state of the specified SDIO interrupts.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SDIO_ITConfig(uint32_t SDIO_IT, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_SDIO_IT(SDIO_IT));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the SDIO interrupts */
SDIO->MASK |= SDIO_IT;
}
else
{
/* Disable the SDIO interrupts */
SDIO->MASK &= ~SDIO_IT;
}
}
/**
* @brief Enables or disables the SDIO DMA request.
* @param NewState: new state of the selected SDIO DMA request.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SDIO_DMACmd(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
*(__IO uint32_t *) DCTRL_DMAEN_BB = (uint32_t)NewState;
}
/**
* @brief Initializes the SDIO Command according to the specified
* parameters in the SDIO_CmdInitStruct and send the command.
* @param SDIO_CmdInitStruct : pointer to a SDIO_CmdInitTypeDef
* structure that contains the configuration information for the SDIO command.
* @retval None
*/
void SDIO_SendCommand(SDIO_CmdInitTypeDef *SDIO_CmdInitStruct)
{
uint32_t tmpreg = 0;
/* Check the parameters */
assert_param(IS_SDIO_CMD_INDEX(SDIO_CmdInitStruct->SDIO_CmdIndex));
assert_param(IS_SDIO_RESPONSE(SDIO_CmdInitStruct->SDIO_Response));
assert_param(IS_SDIO_WAIT(SDIO_CmdInitStruct->SDIO_Wait));
assert_param(IS_SDIO_CPSM(SDIO_CmdInitStruct->SDIO_CPSM));
/*---------------------------- SDIO ARG Configuration ------------------------*/
/* Set the SDIO Argument value */
SDIO->ARG = SDIO_CmdInitStruct->SDIO_Argument;
/*---------------------------- SDIO CMD Configuration ------------------------*/
/* Get the SDIO CMD value */
tmpreg = SDIO->CMD;
/* Clear CMDINDEX, WAITRESP, WAITINT, WAITPEND, CPSMEN bits */
tmpreg &= CMD_CLEAR_MASK;
/* Set CMDINDEX bits according to SDIO_CmdIndex value */
/* Set WAITRESP bits according to SDIO_Response value */
/* Set WAITINT and WAITPEND bits according to SDIO_Wait value */
/* Set CPSMEN bits according to SDIO_CPSM value */
tmpreg |= (uint32_t)SDIO_CmdInitStruct->SDIO_CmdIndex | SDIO_CmdInitStruct->SDIO_Response
| SDIO_CmdInitStruct->SDIO_Wait | SDIO_CmdInitStruct->SDIO_CPSM;
/* Write to SDIO CMD */
SDIO->CMD = tmpreg;
}
/**
* @brief Fills each SDIO_CmdInitStruct member with its default value.
* @param SDIO_CmdInitStruct: pointer to an SDIO_CmdInitTypeDef
* structure which will be initialized.
* @retval None
*/
void SDIO_CmdStructInit(SDIO_CmdInitTypeDef* SDIO_CmdInitStruct)
{
/* SDIO_CmdInitStruct members default value */
SDIO_CmdInitStruct->SDIO_Argument = 0x00;
SDIO_CmdInitStruct->SDIO_CmdIndex = 0x00;
SDIO_CmdInitStruct->SDIO_Response = SDIO_Response_No;
SDIO_CmdInitStruct->SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStruct->SDIO_CPSM = SDIO_CPSM_Disable;
}
/**
* @brief Returns command index of last command for which response received.
* @param None
* @retval Returns the command index of the last command response received.
*/
uint8_t SDIO_GetCommandResponse(void)
{
return (uint8_t)(SDIO->RESPCMD);
}
/**
* @brief Returns response received from the card for the last command.
* @param SDIO_RESP: Specifies the SDIO response register.
* This parameter can be one of the following values:
* @arg SDIO_RESP1: Response Register 1
* @arg SDIO_RESP2: Response Register 2
* @arg SDIO_RESP3: Response Register 3
* @arg SDIO_RESP4: Response Register 4
* @retval The Corresponding response register value.
*/
uint32_t SDIO_GetResponse(uint32_t SDIO_RESP)
{
__IO uint32_t tmp = 0;
/* Check the parameters */
assert_param(IS_SDIO_RESP(SDIO_RESP));
tmp = SDIO_RESP_ADDR + SDIO_RESP;
return (*(__IO uint32_t *) tmp);
}
/**
* @brief Initializes the SDIO data path according to the specified
* parameters in the SDIO_DataInitStruct.
* @param SDIO_DataInitStruct : pointer to a SDIO_DataInitTypeDef structure that
* contains the configuration information for the SDIO command.
* @retval None
*/
void SDIO_DataConfig(SDIO_DataInitTypeDef* SDIO_DataInitStruct)
{
uint32_t tmpreg = 0;
/* Check the parameters */
assert_param(IS_SDIO_DATA_LENGTH(SDIO_DataInitStruct->SDIO_DataLength));
assert_param(IS_SDIO_BLOCK_SIZE(SDIO_DataInitStruct->SDIO_DataBlockSize));
assert_param(IS_SDIO_TRANSFER_DIR(SDIO_DataInitStruct->SDIO_TransferDir));
assert_param(IS_SDIO_TRANSFER_MODE(SDIO_DataInitStruct->SDIO_TransferMode));
assert_param(IS_SDIO_DPSM(SDIO_DataInitStruct->SDIO_DPSM));
/*---------------------------- SDIO DTIMER Configuration ---------------------*/
/* Set the SDIO Data TimeOut value */
SDIO->DTIMER = SDIO_DataInitStruct->SDIO_DataTimeOut;
/*---------------------------- SDIO DLEN Configuration -----------------------*/
/* Set the SDIO DataLength value */
SDIO->DLEN = SDIO_DataInitStruct->SDIO_DataLength;
/*---------------------------- SDIO DCTRL Configuration ----------------------*/
/* Get the SDIO DCTRL value */
tmpreg = SDIO->DCTRL;
/* Clear DEN, DTMODE, DTDIR and DBCKSIZE bits */
tmpreg &= DCTRL_CLEAR_MASK;
/* Set DEN bit according to SDIO_DPSM value */
/* Set DTMODE bit according to SDIO_TransferMode value */
/* Set DTDIR bit according to SDIO_TransferDir value */
/* Set DBCKSIZE bits according to SDIO_DataBlockSize value */
tmpreg |= (uint32_t)SDIO_DataInitStruct->SDIO_DataBlockSize | SDIO_DataInitStruct->SDIO_TransferDir
| SDIO_DataInitStruct->SDIO_TransferMode | SDIO_DataInitStruct->SDIO_DPSM;
/* Write to SDIO DCTRL */
SDIO->DCTRL = tmpreg;
}
/**
* @brief Fills each SDIO_DataInitStruct member with its default value.
* @param SDIO_DataInitStruct: pointer to an SDIO_DataInitTypeDef structure which
* will be initialized.
* @retval None
*/
void SDIO_DataStructInit(SDIO_DataInitTypeDef* SDIO_DataInitStruct)
{
/* SDIO_DataInitStruct members default value */
SDIO_DataInitStruct->SDIO_DataTimeOut = 0xFFFFFFFF;
SDIO_DataInitStruct->SDIO_DataLength = 0x00;
SDIO_DataInitStruct->SDIO_DataBlockSize = SDIO_DataBlockSize_1b;
SDIO_DataInitStruct->SDIO_TransferDir = SDIO_TransferDir_ToCard;
SDIO_DataInitStruct->SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStruct->SDIO_DPSM = SDIO_DPSM_Disable;
}
/**
* @brief Returns number of remaining data bytes to be transferred.
* @param None
* @retval Number of remaining data bytes to be transferred
*/
uint32_t SDIO_GetDataCounter(void)
{
return SDIO->DCOUNT;
}
/**
* @brief Read one data word from Rx FIFO.
* @param None
* @retval Data received
*/
uint32_t SDIO_ReadData(void)
{
return SDIO->FIFO;
}
/**
* @brief Write one data word to Tx FIFO.
* @param Data: 32-bit data word to write.
* @retval None
*/
void SDIO_WriteData(uint32_t Data)
{
SDIO->FIFO = Data;
}
/**
* @brief Returns the number of words left to be written to or read from FIFO.
* @param None
* @retval Remaining number of words.
*/
uint32_t SDIO_GetFIFOCount(void)
{
return SDIO->FIFOCNT;
}
/**
* @brief Starts the SD I/O Read Wait operation.
* @param NewState: new state of the Start SDIO Read Wait operation.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SDIO_StartSDIOReadWait(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
*(__IO uint32_t *) DCTRL_RWSTART_BB = (uint32_t) NewState;
}
/**
* @brief Stops the SD I/O Read Wait operation.
* @param NewState: new state of the Stop SDIO Read Wait operation.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SDIO_StopSDIOReadWait(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
*(__IO uint32_t *) DCTRL_RWSTOP_BB = (uint32_t) NewState;
}
/**
* @brief Sets one of the two options of inserting read wait interval.
* @param SDIO_ReadWaitMode: SD I/O Read Wait operation mode.
* This parameter can be:
* @arg SDIO_ReadWaitMode_CLK: Read Wait control by stopping SDIOCLK
* @arg SDIO_ReadWaitMode_DATA2: Read Wait control using SDIO_DATA2
* @retval None
*/
void SDIO_SetSDIOReadWaitMode(uint32_t SDIO_ReadWaitMode)
{
/* Check the parameters */
assert_param(IS_SDIO_READWAIT_MODE(SDIO_ReadWaitMode));
*(__IO uint32_t *) DCTRL_RWMOD_BB = SDIO_ReadWaitMode;
}
/**
* @brief Enables or disables the SD I/O Mode Operation.
* @param NewState: new state of SDIO specific operation.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SDIO_SetSDIOOperation(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
*(__IO uint32_t *) DCTRL_SDIOEN_BB = (uint32_t)NewState;
}
/**
* @brief Enables or disables the SD I/O Mode suspend command sending.
* @param NewState: new state of the SD I/O Mode suspend command.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SDIO_SendSDIOSuspendCmd(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = (uint32_t)NewState;
}
/**
* @brief Enables or disables the command completion signal.
* @param NewState: new state of command completion signal.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SDIO_CommandCompletionCmd(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = (uint32_t)NewState;
}
/**
* @brief Enables or disables the CE-ATA interrupt.
* @param NewState: new state of CE-ATA interrupt. This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SDIO_CEATAITCmd(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)((~((uint32_t)NewState)) & ((uint32_t)0x1));
}
/**
* @brief Sends CE-ATA command (CMD61).
* @param NewState: new state of CE-ATA command. This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SDIO_SendCEATACmd(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
*(__IO uint32_t *) CMD_ATACMD_BB = (uint32_t)NewState;
}
/**
* @brief Checks whether the specified SDIO flag is set or not.
* @param SDIO_FLAG: specifies the flag to check.
* This parameter can be one of the following values:
* @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed)
* @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed)
* @arg SDIO_FLAG_CTIMEOUT: Command response timeout
* @arg SDIO_FLAG_DTIMEOUT: Data timeout
* @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error
* @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error
* @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed)
* @arg SDIO_FLAG_CMDSENT: Command sent (no response required)
* @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero)
* @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide
* bus mode.
* @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed)
* @arg SDIO_FLAG_CMDACT: Command transfer in progress
* @arg SDIO_FLAG_TXACT: Data transmit in progress
* @arg SDIO_FLAG_RXACT: Data receive in progress
* @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty
* @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full
* @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full
* @arg SDIO_FLAG_RXFIFOF: Receive FIFO full
* @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty
* @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty
* @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO
* @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO
* @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received
* @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61
* @retval The new state of SDIO_FLAG (SET or RESET).
*/
FlagStatus SDIO_GetFlagStatus(uint32_t SDIO_FLAG)
{
FlagStatus bitstatus = RESET;
/* Check the parameters */
assert_param(IS_SDIO_FLAG(SDIO_FLAG));
if ((SDIO->STA & SDIO_FLAG) != (uint32_t)RESET)
{
bitstatus = SET;
}
else
{
bitstatus = RESET;
}
return bitstatus;
}
/**
* @brief Clears the SDIO's pending flags.
* @param SDIO_FLAG: specifies the flag to clear.
* This parameter can be one or a combination of the following values:
* @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed)
* @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed)
* @arg SDIO_FLAG_CTIMEOUT: Command response timeout
* @arg SDIO_FLAG_DTIMEOUT: Data timeout
* @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error
* @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error
* @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed)
* @arg SDIO_FLAG_CMDSENT: Command sent (no response required)
* @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero)
* @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide
* bus mode
* @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed)
* @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received
* @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61
* @retval None
*/
void SDIO_ClearFlag(uint32_t SDIO_FLAG)
{
/* Check the parameters */
assert_param(IS_SDIO_CLEAR_FLAG(SDIO_FLAG));
SDIO->ICR = SDIO_FLAG;
}
/**
* @brief Checks whether the specified SDIO interrupt has occurred or not.
* @param SDIO_IT: specifies the SDIO interrupt source to check.
* This parameter can be one of the following values:
* @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt
* @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt
* @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt
* @arg SDIO_IT_DTIMEOUT: Data timeout interrupt
* @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt
* @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt
* @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt
* @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt
* @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt
* @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide
* bus mode interrupt
* @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt
* @arg SDIO_IT_CMDACT: Command transfer in progress interrupt
* @arg SDIO_IT_TXACT: Data transmit in progress interrupt
* @arg SDIO_IT_RXACT: Data receive in progress interrupt
* @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt
* @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt
* @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt
* @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt
* @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt
* @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt
* @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt
* @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt
* @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt
* @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt
* @retval The new state of SDIO_IT (SET or RESET).
*/
ITStatus SDIO_GetITStatus(uint32_t SDIO_IT)
{
ITStatus bitstatus = RESET;
/* Check the parameters */
assert_param(IS_SDIO_GET_IT(SDIO_IT));
if ((SDIO->STA & SDIO_IT) != (uint32_t)RESET)
{
bitstatus = SET;
}
else
{
bitstatus = RESET;
}
return bitstatus;
}
/**
* @brief Clears the SDIO's interrupt pending bits.
* @param SDIO_IT: specifies the interrupt pending bit to clear.
* This parameter can be one or a combination of the following values:
* @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt
* @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt
* @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt
* @arg SDIO_IT_DTIMEOUT: Data timeout interrupt
* @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt
* @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt
* @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt
* @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt
* @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt
* @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide
* bus mode interrupt
* @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt
* @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61
* @retval None
*/
void SDIO_ClearITPendingBit(uint32_t SDIO_IT)
{
/* Check the parameters */
assert_param(IS_SDIO_CLEAR_IT(SDIO_IT));
SDIO->ICR = SDIO_IT;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
| gpl-2.0 |
moqi88/bmybbs | ythtlib/strlib.c | 1 | 4465 | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
* Authors: Jeffrey Stedfast <fejj@ximian.com>
*
* Copyright 2001 Ximain, Inc. (www.ximian.com)
*
*/
#include "ythtlib.h"
#define lowercase(c) (isupper ((int) (c)) ? tolower ((int) (c)) : (int) (c))
#define bm_index(c, icase) ((icase) ? lowercase (c) : (int) (c))
#define bm_equal(c1, c2, icase) ((icase) ? lowercase (c1) == lowercase (c2) : (c1) == (c2))
/* FIXME: this is just a guess... should really do some performace tests to get an accurate measure */
#define bm_optimal(hlen, nlen) (((hlen) ? (hlen) > 20 : 1) && (nlen) > 10 ? 1 : 0)
static unsigned char *
__boyer_moore(const unsigned char *haystack, size_t haystacklen,
const unsigned char *needle, size_t needlelen, int icase)
{
register unsigned char *hc_ptr, *nc_ptr;
unsigned char *he_ptr, *ne_ptr, *h_ptr;
size_t skiptable[256], n;
register int i;
#ifdef BOYER_MOORE_CHECKS
/* we don't need to do these checks since memmem/strstr/etc do it already */
/* if the haystack is shorter than the needle then we can't possibly match */
if (haystacklen < needlelen)
return NULL;
/* instant match if the pattern buffer is 0-length */
if (needlelen == 0)
return (unsigned char *) haystack;
#endif /* BOYER_MOORE_CHECKS */
/* set a pointer at the end of each string */
ne_ptr = (unsigned char *) needle + needlelen - 1;
he_ptr = (unsigned char *) haystack + haystacklen - 1;
/* create our skip table */
for (i = 0; i < 256; i++)
skiptable[i] = needlelen;
for (nc_ptr = (unsigned char *) needle; nc_ptr < ne_ptr; nc_ptr++)
skiptable[bm_index(*nc_ptr, icase)] =
(size_t) (ne_ptr - nc_ptr);
h_ptr = (unsigned char *) haystack;
while (haystacklen >= needlelen) {
hc_ptr = h_ptr + needlelen - 1; /* set the haystack compare pointer */
nc_ptr = ne_ptr; /* set the needle compare pointer */
/* work our way backwards till they don't match */
for (i = 0; nc_ptr > (unsigned char *) needle;
nc_ptr--, hc_ptr--, i++)
if (!bm_equal(*nc_ptr, *hc_ptr, icase))
break;
if (!bm_equal(*nc_ptr, *hc_ptr, icase)) {
n = skiptable[bm_index(*hc_ptr, icase)];
if (n == needlelen && i)
if (bm_equal
(*ne_ptr, ((unsigned char *) needle)[0],
icase)) n--;
h_ptr += n;
haystacklen -= n;
} else
return (unsigned char *) h_ptr;
}
return NULL;
}
/**
* strnstr:
* @haystack: string to search
* @needle: substring to search for
* @haystacklen: length of the haystack to search
*
* Finds the first occurence of the substring @needle within the
* bounds of string @haystack.
*
* Returns a pointer to the beginning of the substring match within
* @haystack, or NULL if the substring is not found.
**/
char *
strnstr(const char *haystack, const char *needle, size_t haystacklen)
{
register unsigned char *h, *n, *hc, *nc;
size_t needlelen;
needlelen = strlen(needle);
if (haystacklen < needlelen) {
return NULL;
} else if (needlelen == 0) {
return (char *) haystack;
} else if (needlelen == 1) {
return memchr(haystack, (int) ((unsigned char *) needle)[0],
haystacklen);
} else if (bm_optimal(haystacklen, needlelen)) {
return (char *) __boyer_moore((const unsigned char *) haystack,
haystacklen,
(const unsigned char *) needle,
needlelen, 0);
}
h = (unsigned char *) haystack;
n = (unsigned char *) needle;
while (haystacklen >= needlelen) {
if (*h == *n) {
for (hc = h + 1, nc = n + 1; *nc; hc++, nc++)
if (*hc != *nc)
break;
if (!*nc)
return (char *) h;
}
haystacklen--;
h++;
}
return NULL;
}
char *
strncasestr(const char *haystack, const char *needle, size_t haystacklen)
{
register unsigned char *h, *n, *hc, *nc;
size_t needlelen;
needlelen = strlen(needle);
if (haystacklen < needlelen) {
return NULL;
} else if (needlelen == 0) {
return (char *) haystack;
} else if (bm_optimal(haystacklen, needlelen)) {
return (char *) __boyer_moore((const unsigned char *) haystack,
haystacklen,
(const unsigned char *) needle,
needlelen, 1);
}
h = (unsigned char *) haystack;
n = (unsigned char *) needle;
while (haystacklen >= needlelen) {
if (lowercase(*h) == lowercase(*n)) {
for (hc = h + 1, nc = n + 1; *nc; hc++, nc++)
if (lowercase(*hc) != lowercase(*nc))
break;
if (!*nc)
return (char *) h;
}
haystacklen--;
h++;
}
return NULL;
}
| gpl-2.0 |
DOOMer/qbspinfo | src/core/entityitem.cpp | 1 | 2098 | /***************************************************************************
* Copyright (C) 2013 by Artem 'DOOMer' Galichkin *
* doomer3d@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., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "entityitem.h"
EntityItem::EntityItem(const QVector< QByteArray >& data, Entity::itemType type, EntityItem* parent)
{
_parent = parent;
_itemData = data;
_type = type;
}
EntityItem::~EntityItem()
{
qDeleteAll(_childList);
}
/*!
* Add pointer to child item.
*/
void EntityItem::addChild(EntityItem* child)
{
_childList.append(child);
}
/*!
* Return pointer to child item by row.
*/
EntityItem* EntityItem::child(int row)
{
return _childList.value(row);
}
/*!
* Return pointer to pareint item.
*/
EntityItem* EntityItem::parent()
{
return _parent;
}
/*!
* Return data form selected EntityItem.
*/
QVariant EntityItem::data(int colum) const
{
return QVariant(_itemData.value(colum));
}
/*!
* Return count of cjld items for paren of selected item.
* \return int Cound of childs.
*/
int EntityItem::row() const
{
if (_parent)
{
return _parent->_childList.indexOf(const_cast<EntityItem*>(this));
}
return 0;
}
int EntityItem::columnCount() const
{
return _itemData.count();
}
/*!
* Retun count of child utems for selected item.
*/
int EntityItem::childCount() const
{
_childList.count();
}
| gpl-2.0 |
luckasfb/OT_903D-kernel-2.6.35.7 | kernel/drivers/staging/rt2860/sta/wpa.c | 1 | 9729 |
#include "../rt_config.h"
void inc_byte_array(u8 * counter, int len);
void RTMPReportMicError(struct rt_rtmp_adapter *pAd, struct rt_cipher_key *pWpaKey)
{
unsigned long Now;
u8 unicastKey = (pWpaKey->Type == PAIRWISE_KEY ? 1 : 0);
/* Record Last MIC error time and count */
NdisGetSystemUpTime(&Now);
if (pAd->StaCfg.MicErrCnt == 0) {
pAd->StaCfg.MicErrCnt++;
pAd->StaCfg.LastMicErrorTime = Now;
NdisZeroMemory(pAd->StaCfg.ReplayCounter, 8);
} else if (pAd->StaCfg.MicErrCnt == 1) {
if ((pAd->StaCfg.LastMicErrorTime + (60 * OS_HZ)) < Now) {
/* Update Last MIC error time, this did not violate two MIC errors within 60 seconds */
pAd->StaCfg.LastMicErrorTime = Now;
} else {
if (pAd->CommonCfg.bWirelessEvent)
RTMPSendWirelessEvent(pAd,
IW_COUNTER_MEASURES_EVENT_FLAG,
pAd->MacTab.
Content[BSSID_WCID].Addr,
BSS0, 0);
pAd->StaCfg.LastMicErrorTime = Now;
/* Violate MIC error counts, MIC countermeasures kicks in */
pAd->StaCfg.MicErrCnt++;
/* We shall block all reception */
/* We shall clean all Tx ring and disassoicate from AP after next EAPOL frame */
/* */
/* No necessary to clean all Tx ring, on RTMPHardTransmit will stop sending non-802.1X EAPOL packets */
/* if pAd->StaCfg.MicErrCnt greater than 2. */
/* */
/* RTMPRingCleanUp(pAd, QID_AC_BK); */
/* RTMPRingCleanUp(pAd, QID_AC_BE); */
/* RTMPRingCleanUp(pAd, QID_AC_VI); */
/* RTMPRingCleanUp(pAd, QID_AC_VO); */
/* RTMPRingCleanUp(pAd, QID_HCCA); */
}
} else {
/* MIC error count >= 2 */
/* This should not happen */
;
}
MlmeEnqueue(pAd,
MLME_CNTL_STATE_MACHINE,
OID_802_11_MIC_FAILURE_REPORT_FRAME, 1, &unicastKey);
if (pAd->StaCfg.MicErrCnt == 2) {
RTMPSetTimer(&pAd->StaCfg.WpaDisassocAndBlockAssocTimer, 100);
}
}
#define LENGTH_EAP_H 4
/* If the received frame is EAP-Packet ,find out its EAP-Code (Request(0x01), Response(0x02), Success(0x03), Failure(0x04)). */
int WpaCheckEapCode(struct rt_rtmp_adapter *pAd,
u8 *pFrame, u16 FrameLen, u16 OffSet)
{
u8 *pData;
int result = 0;
if (FrameLen < OffSet + LENGTH_EAPOL_H + LENGTH_EAP_H)
return result;
pData = pFrame + OffSet; /* skip offset bytes */
if (*(pData + 1) == EAPPacket) /* 802.1x header - Packet Type */
{
result = *(pData + 4); /* EAP header - Code */
}
return result;
}
void WpaSendMicFailureToWpaSupplicant(struct rt_rtmp_adapter *pAd, IN BOOLEAN bUnicast)
{
char custom[IW_CUSTOM_MAX] = { 0 };
sprintf(custom, "MLME-MICHAELMICFAILURE.indication");
if (bUnicast)
sprintf(custom, "%s unicast", custom);
RtmpOSWrielessEventSend(pAd, IWEVCUSTOM, -1, NULL, (u8 *)custom,
strlen(custom));
return;
}
void WpaMicFailureReportFrame(struct rt_rtmp_adapter *pAd, struct rt_mlme_queue_elem *Elem)
{
u8 *pOutBuffer = NULL;
u8 Header802_3[14];
unsigned long FrameLen = 0;
struct rt_eapol_packet Packet;
u8 Mic[16];
BOOLEAN bUnicast;
DBGPRINT(RT_DEBUG_TRACE, ("WpaMicFailureReportFrame ----->\n"));
bUnicast = (Elem->Msg[0] == 1 ? TRUE : FALSE);
pAd->Sequence = ((pAd->Sequence) + 1) & (MAX_SEQ_NUMBER);
/* init 802.3 header and Fill Packet */
MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid,
pAd->CurrentAddress, EAPOL);
NdisZeroMemory(&Packet, sizeof(Packet));
Packet.ProVer = EAPOL_VER;
Packet.ProType = EAPOLKey;
Packet.KeyDesc.Type = WPA1_KEY_DESC;
/* Request field presented */
Packet.KeyDesc.KeyInfo.Request = 1;
if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled) {
Packet.KeyDesc.KeyInfo.KeyDescVer = 2;
} else /* TKIP */
{
Packet.KeyDesc.KeyInfo.KeyDescVer = 1;
}
Packet.KeyDesc.KeyInfo.KeyType = (bUnicast ? PAIRWISEKEY : GROUPKEY);
/* KeyMic field presented */
Packet.KeyDesc.KeyInfo.KeyMic = 1;
/* Error field presented */
Packet.KeyDesc.KeyInfo.Error = 1;
/* Update packet length after decide Key data payload */
SET_u16_TO_ARRARY(Packet.Body_Len, LEN_EAPOL_KEY_MSG)
/* Key Replay Count */
NdisMoveMemory(Packet.KeyDesc.ReplayCounter,
pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);
inc_byte_array(pAd->StaCfg.ReplayCounter, 8);
/* Convert to little-endian format. */
*((u16 *) & Packet.KeyDesc.KeyInfo) =
cpu2le16(*((u16 *) & Packet.KeyDesc.KeyInfo));
MlmeAllocateMemory(pAd, (u8 **) & pOutBuffer); /* allocate memory */
if (pOutBuffer == NULL) {
return;
}
/* Prepare EAPOL frame for MIC calculation */
/* Be careful, only EAPOL frame is counted for MIC calculation */
MakeOutgoingFrame(pOutBuffer, &FrameLen,
CONV_ARRARY_TO_u16(Packet.Body_Len) + 4, &Packet,
END_OF_ARGS);
/* Prepare and Fill MIC value */
NdisZeroMemory(Mic, sizeof(Mic));
if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled) { /* AES */
u8 digest[20] = { 0 };
HMAC_SHA1(pAd->StaCfg.PTK, LEN_EAP_MICK, pOutBuffer, FrameLen,
digest, SHA1_DIGEST_SIZE);
NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
} else { /* TKIP */
HMAC_MD5(pAd->StaCfg.PTK, LEN_EAP_MICK, pOutBuffer, FrameLen,
Mic, MD5_DIGEST_SIZE);
}
NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
/* copy frame to Tx ring and send MIC failure report frame to authenticator */
RTMPToWirelessSta(pAd, &pAd->MacTab.Content[BSSID_WCID],
Header802_3, LENGTH_802_3,
(u8 *)& Packet,
CONV_ARRARY_TO_u16(Packet.Body_Len) + 4, FALSE);
MlmeFreeMemory(pAd, (u8 *)pOutBuffer);
DBGPRINT(RT_DEBUG_TRACE, ("WpaMicFailureReportFrame <-----\n"));
}
void inc_byte_array(u8 * counter, int len)
{
int pos = len - 1;
while (pos >= 0) {
counter[pos]++;
if (counter[pos] != 0)
break;
pos--;
}
}
void WpaDisassocApAndBlockAssoc(void *SystemSpecific1,
void *FunctionContext,
void *SystemSpecific2,
void *SystemSpecific3)
{
struct rt_rtmp_adapter *pAd = (struct rt_rtmp_adapter *)FunctionContext;
struct rt_mlme_disassoc_req DisassocReq;
/* disassoc from current AP first */
DBGPRINT(RT_DEBUG_TRACE,
("RTMPReportMicError - disassociate with current AP after sending second continuous EAPOL frame\n"));
DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid,
REASON_MIC_FAILURE);
MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
sizeof(struct rt_mlme_disassoc_req), &DisassocReq);
pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
pAd->StaCfg.bBlockAssoc = TRUE;
}
void WpaStaPairwiseKeySetting(struct rt_rtmp_adapter *pAd)
{
struct rt_cipher_key *pSharedKey;
struct rt_mac_table_entry *pEntry;
pEntry = &pAd->MacTab.Content[BSSID_WCID];
/* Pairwise key shall use key#0 */
pSharedKey = &pAd->SharedKey[BSS0][0];
NdisMoveMemory(pAd->StaCfg.PTK, pEntry->PTK, LEN_PTK);
/* Prepare pair-wise key information into shared key table */
NdisZeroMemory(pSharedKey, sizeof(struct rt_cipher_key));
pSharedKey->KeyLen = LEN_TKIP_EK;
NdisMoveMemory(pSharedKey->Key, &pAd->StaCfg.PTK[32], LEN_TKIP_EK);
NdisMoveMemory(pSharedKey->RxMic, &pAd->StaCfg.PTK[48],
LEN_TKIP_RXMICK);
NdisMoveMemory(pSharedKey->TxMic,
&pAd->StaCfg.PTK[48 + LEN_TKIP_RXMICK], LEN_TKIP_TXMICK);
/* Decide its ChiperAlg */
if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
pSharedKey->CipherAlg = CIPHER_TKIP;
else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
pSharedKey->CipherAlg = CIPHER_AES;
else
pSharedKey->CipherAlg = CIPHER_NONE;
/* Update these related information to struct rt_mac_table_entry */
NdisMoveMemory(pEntry->PairwiseKey.Key, &pAd->StaCfg.PTK[32],
LEN_TKIP_EK);
NdisMoveMemory(pEntry->PairwiseKey.RxMic, &pAd->StaCfg.PTK[48],
LEN_TKIP_RXMICK);
NdisMoveMemory(pEntry->PairwiseKey.TxMic,
&pAd->StaCfg.PTK[48 + LEN_TKIP_RXMICK], LEN_TKIP_TXMICK);
pEntry->PairwiseKey.CipherAlg = pSharedKey->CipherAlg;
/* Update pairwise key information to ASIC Shared Key Table */
AsicAddSharedKeyEntry(pAd,
BSS0,
0,
pSharedKey->CipherAlg,
pSharedKey->Key,
pSharedKey->TxMic, pSharedKey->RxMic);
/* Update ASIC WCID attribute table and IVEIV table */
RTMPAddWcidAttributeEntry(pAd, BSS0, 0, pSharedKey->CipherAlg, pEntry);
STA_PORT_SECURED(pAd);
pAd->IndicateMediaState = NdisMediaStateConnected;
DBGPRINT(RT_DEBUG_TRACE,
("%s : AID(%d) port secured\n", __func__, pEntry->Aid));
}
void WpaStaGroupKeySetting(struct rt_rtmp_adapter *pAd)
{
struct rt_cipher_key *pSharedKey;
pSharedKey = &pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId];
/* Prepare pair-wise key information into shared key table */
NdisZeroMemory(pSharedKey, sizeof(struct rt_cipher_key));
pSharedKey->KeyLen = LEN_TKIP_EK;
NdisMoveMemory(pSharedKey->Key, pAd->StaCfg.GTK, LEN_TKIP_EK);
NdisMoveMemory(pSharedKey->RxMic, &pAd->StaCfg.GTK[16],
LEN_TKIP_RXMICK);
NdisMoveMemory(pSharedKey->TxMic, &pAd->StaCfg.GTK[24],
LEN_TKIP_TXMICK);
/* Update Shared Key CipherAlg */
pSharedKey->CipherAlg = CIPHER_NONE;
if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
pSharedKey->CipherAlg = CIPHER_TKIP;
else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
pSharedKey->CipherAlg = CIPHER_AES;
else if (pAd->StaCfg.GroupCipher == Ndis802_11GroupWEP40Enabled)
pSharedKey->CipherAlg = CIPHER_WEP64;
else if (pAd->StaCfg.GroupCipher == Ndis802_11GroupWEP104Enabled)
pSharedKey->CipherAlg = CIPHER_WEP128;
/* Update group key information to ASIC Shared Key Table */
AsicAddSharedKeyEntry(pAd,
BSS0,
pAd->StaCfg.DefaultKeyId,
pSharedKey->CipherAlg,
pSharedKey->Key,
pSharedKey->TxMic, pSharedKey->RxMic);
/* Update ASIC WCID attribute table and IVEIV table */
RTMPAddWcidAttributeEntry(pAd,
BSS0,
pAd->StaCfg.DefaultKeyId,
pSharedKey->CipherAlg, NULL);
}
| gpl-2.0 |
blackjack/kdevplatform | plugins/testview/testview.cpp | 1 | 13992 | /* This file is part of KDevelop
Copyright 2012 Miha Čančula <miha@noughmad.eu>
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; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "testview.h"
#include "testviewplugin.h"
#include "testviewdebug.h"
#include <interfaces/icore.h>
#include <interfaces/iproject.h>
#include <interfaces/iprojectcontroller.h>
#include <interfaces/itestcontroller.h>
#include <interfaces/itestsuite.h>
#include <interfaces/iruncontroller.h>
#include <interfaces/idocumentcontroller.h>
#include <interfaces/isession.h>
#include <util/executecompositejob.h>
#include <language/duchain/indexeddeclaration.h>
#include <language/duchain/duchainlock.h>
#include <language/duchain/duchain.h>
#include <language/duchain/declaration.h>
#include <KActionCollection>
#include <KLocalizedString>
#include <KJob>
#include <KRecursiveFilterProxyModel>
#include <KLineEdit>
#include <KConfigGroup>
#include <QAction>
#include <QIcon>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QHeaderView>
#include <QVBoxLayout>
using namespace KDevelop;
enum CustomRoles {
ProjectRole = Qt::UserRole + 1,
SuiteRole,
CaseRole
};
//BEGIN TestViewFilterAction
TestViewFilterAction::TestViewFilterAction( const QString &initialFilter, QObject* parent )
: QAction( parent )
, m_intialFilter(initialFilter)
{
setIcon(QIcon::fromTheme("view-filter"));
setText(i18n("Filter..."));
setToolTip(i18n("Insert wildcard patterns to filter the test view"
" for matching test suites and cases."));
}
QWidget* TestViewFilterAction::createWidget( QWidget* parent )
{
KLineEdit* edit = new KLineEdit(parent);
edit->setClickMessage(i18n("Filter..."));
edit->setClearButtonShown(true);
connect(edit, SIGNAL(textChanged(QString)), this, SIGNAL(filterChanged(QString)));
if (!m_intialFilter.isEmpty()) {
edit->setText(m_intialFilter);
}
return edit;
}
//END TestViwFilterAction
static const char* sessionConfigGroup = "TestView";
static const char* filterConfigKey = "filter";
TestView::TestView(TestViewPlugin* plugin, QWidget* parent)
: QWidget(parent)
, m_plugin(plugin)
, m_tree(new QTreeView(this))
, m_filter(new KRecursiveFilterProxyModel(this))
{
setWindowIcon(QIcon::fromTheme("preflight-verifier"));
setWindowTitle(i18n("Unit Tests"));
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
layout->addWidget(m_tree);
m_tree->setSortingEnabled(true);
m_tree->header()->hide();
m_tree->setIndentation(10);
m_tree->setEditTriggers(QTreeView::NoEditTriggers);
m_tree->setSelectionBehavior(QTreeView::SelectRows);
m_tree->setSelectionMode(QTreeView::SingleSelection);
m_tree->setExpandsOnDoubleClick(false);
m_tree->sortByColumn(0, Qt::AscendingOrder);
connect(m_tree, SIGNAL(activated(QModelIndex)), SLOT(doubleClicked(QModelIndex)));
m_model = new QStandardItemModel(this);
m_filter->setSourceModel(m_model);
m_tree->setModel(m_filter);
QAction* showSource = new QAction( QIcon::fromTheme("code-context"), i18n("Show Source"), this );
connect (showSource, SIGNAL(triggered(bool)), SLOT(showSource()));
m_contextMenuActions << showSource;
QAction* runSelected = new QAction( QIcon::fromTheme("system-run"), i18n("Run Selected Tests"), this );
connect (runSelected, SIGNAL(triggered(bool)), SLOT(runSelectedTests()));
m_contextMenuActions << runSelected;
addAction(plugin->actionCollection()->action("run_all_tests"));
addAction(plugin->actionCollection()->action("stop_running_tests"));
QString filterText;
KConfigGroup config(ICore::self()->activeSession()->config(), sessionConfigGroup);
if (config.hasKey(filterConfigKey))
{
filterText = config.readEntry(filterConfigKey, QString());
}
TestViewFilterAction* filterAction = new TestViewFilterAction(filterText, this);
connect(filterAction, SIGNAL(filterChanged(QString)),
m_filter, SLOT(setFilterFixedString(QString)));
addAction(filterAction);
IProjectController* pc = ICore::self()->projectController();
connect (pc, SIGNAL(projectClosed(KDevelop::IProject*)), SLOT(removeProject(KDevelop::IProject*)));
ITestController* tc = ICore::self()->testController();
connect (tc, SIGNAL(testSuiteAdded(KDevelop::ITestSuite*)),
SLOT(addTestSuite(KDevelop::ITestSuite*)));
connect (tc, SIGNAL(testSuiteRemoved(KDevelop::ITestSuite*)),
SLOT(removeTestSuite(KDevelop::ITestSuite*)));
connect (tc, SIGNAL(testRunFinished(KDevelop::ITestSuite*, KDevelop::TestResult)),
SLOT(updateTestSuite(KDevelop::ITestSuite*, KDevelop::TestResult)));
connect (tc, SIGNAL(testRunStarted(KDevelop::ITestSuite*, QStringList)),
SLOT(notifyTestCaseStarted(KDevelop::ITestSuite*, QStringList)));
foreach (ITestSuite* suite, tc->testSuites())
{
addTestSuite(suite);
}
}
TestView::~TestView()
{
}
void TestView::updateTestSuite(ITestSuite* suite, const TestResult& result)
{
QStandardItem* item = itemForSuite(suite);
if (!item)
{
return;
}
debug() << "Updating test suite" << suite->name();
item->setIcon(iconForTestResult(result.suiteResult));
for (int i = 0; i < item->rowCount(); ++i)
{
debug() << "Found a test case" << item->child(i)->text();
QStandardItem* caseItem = item->child(i);
if (result.testCaseResults.contains(caseItem->text()))
{
TestResult::TestCaseResult caseResult = result.testCaseResults.value(caseItem->text(), TestResult::NotRun);
caseItem->setIcon(iconForTestResult(caseResult));
}
}
}
void TestView::notifyTestCaseStarted(ITestSuite* suite, const QStringList& test_cases)
{
QStandardItem* item = itemForSuite(suite);
if (!item)
{
return;
}
debug() << "Notify a test of the suite " << suite->name() << " has started";
// Global test suite icon
item->setIcon(QIcon::fromTheme("process-idle"));
for (int i = 0; i < item->rowCount(); ++i)
{
debug() << "Found a test case" << item->child(i)->text();
QStandardItem* caseItem = item->child(i);
if (test_cases.contains(caseItem->text()))
{
// Each test case icon
caseItem->setIcon(QIcon::fromTheme("process-idle"));
}
}
}
QIcon TestView::iconForTestResult(TestResult::TestCaseResult result)
{
switch (result)
{
case TestResult::NotRun:
return QIcon::fromTheme("code-function");
case TestResult::Skipped:
return QIcon::fromTheme("task-delegate");
case TestResult::Passed:
return QIcon::fromTheme("dialog-ok-apply");
case TestResult::UnexpectedPass:
// This is a very rare occurrence, so the icon should stand out
return QIcon::fromTheme("dialog-warning");
case TestResult::Failed:
return QIcon::fromTheme("edit-delete");
case TestResult::ExpectedFail:
return QIcon::fromTheme("dialog-ok");
case TestResult::Error:
return QIcon::fromTheme("dialog-cancel");
default:
return QIcon::fromTheme("");
}
}
QStandardItem* TestView::itemForSuite(ITestSuite* suite)
{
foreach (QStandardItem* item, m_model->findItems(suite->name(), Qt::MatchRecursive))
{
if (item->parent() && item->parent()->text() == suite->project()->name()
&& !item->parent()->parent())
{
return item;
}
}
return 0;
}
QStandardItem* TestView::itemForProject(IProject* project)
{
foreach (QStandardItem* item, m_model->findItems(project->name()))
{
return item;
}
return addProject(project);
}
void TestView::runSelectedTests()
{
QModelIndexList indexes = m_tree->selectionModel()->selectedIndexes();
if (indexes.isEmpty())
{
return;
}
QList<KJob*> jobs;
ITestController* tc = ICore::self()->testController();
/*
* NOTE: If a test suite or a single test case was selected,
* the job is launched in Verbose mode with raised output window.
* If a project is selected, it is launched silently.
*
* This is the somewhat-intuitive approach. Maybe a configuration should be offered.
*/
foreach (const QModelIndex& idx, indexes)
{
QModelIndex index = m_filter->mapToSource(idx);
if (index.parent().isValid() && indexes.contains(index.parent()))
{
continue;
}
QStandardItem* item = m_model->itemFromIndex(index);
if (item->parent() == 0)
{
// A project was selected
IProject* project = ICore::self()->projectController()->findProjectByName(item->data(ProjectRole).toString());
foreach (ITestSuite* suite, tc->testSuitesForProject(project))
{
jobs << suite->launchAllCases(ITestSuite::Silent);
}
}
else if (item->parent()->parent() == 0)
{
// A suite was selected
IProject* project = ICore::self()->projectController()->findProjectByName(item->parent()->data(ProjectRole).toString());
ITestSuite* suite = tc->findTestSuite(project, item->data(SuiteRole).toString());
jobs << suite->launchAllCases(ITestSuite::Verbose);
}
else
{
// This was a single test case
IProject* project = ICore::self()->projectController()->findProjectByName(item->parent()->parent()->data(ProjectRole).toString());
ITestSuite* suite = tc->findTestSuite(project, item->parent()->data(SuiteRole).toString());
const QString testCase = item->data(CaseRole).toString();
jobs << suite->launchCase(testCase, ITestSuite::Verbose);
}
}
if (!jobs.isEmpty())
{
KDevelop::ExecuteCompositeJob* compositeJob = new KDevelop::ExecuteCompositeJob(this, jobs);
compositeJob->setObjectName(i18np("Run 1 test", "Run %1 tests", jobs.size()));
compositeJob->setProperty("test_job", true);
ICore::self()->runController()->registerJob(compositeJob);
}
}
void TestView::showSource()
{
QModelIndexList indexes = m_tree->selectionModel()->selectedIndexes();
if (indexes.isEmpty())
{
return;
}
IndexedDeclaration declaration;
ITestController* tc = ICore::self()->testController();
QModelIndex index = m_filter->mapToSource(indexes.first());
QStandardItem* item = m_model->itemFromIndex(index);
if (item->parent() == 0)
{
// No sense in finding source code for projects.
return;
}
else if (item->parent()->parent() == 0)
{
IProject* project = ICore::self()->projectController()->findProjectByName(item->parent()->data(ProjectRole).toString());
ITestSuite* suite = tc->findTestSuite(project, item->data(SuiteRole).toString());
declaration = suite->declaration();
}
else
{
IProject* project = ICore::self()->projectController()->findProjectByName(item->parent()->parent()->data(ProjectRole).toString());
ITestSuite* suite = tc->findTestSuite(project, item->parent()->data(SuiteRole).toString());
declaration = suite->caseDeclaration(item->data(CaseRole).toString());
}
DUChainReadLocker locker(DUChain::lock());
Declaration* d = declaration.data();
if (!d)
{
return;
}
KUrl url = d->url().toUrl();
KTextEditor::Cursor cursor = d->rangeInCurrentRevision().start();
locker.unlock();
IDocumentController* dc = ICore::self()->documentController();
debug() << "Activating declaration in" << url;
dc->openDocument(url, cursor);
}
void TestView::addTestSuite(ITestSuite* suite)
{
QStandardItem* projectItem = itemForProject(suite->project());
Q_ASSERT(projectItem);
QStandardItem* suiteItem = new QStandardItem(QIcon::fromTheme("view-list-tree"), suite->name());
suiteItem->setData(suite->name(), SuiteRole);
foreach (QString caseName, suite->cases())
{
QStandardItem* caseItem = new QStandardItem(iconForTestResult(TestResult::NotRun), caseName);
caseItem->setData(caseName, CaseRole);
suiteItem->appendRow(caseItem);
}
projectItem->appendRow(suiteItem);
}
void TestView::removeTestSuite(ITestSuite* suite)
{
QStandardItem* item = itemForSuite(suite);
item->parent()->removeRow(item->row());
}
QStandardItem* TestView::addProject(IProject* project)
{
QStandardItem* projectItem = new QStandardItem(QIcon::fromTheme("project-development"), project->name());
projectItem->setData(project->name(), ProjectRole);
m_model->appendRow(projectItem);
return projectItem;
}
void TestView::removeProject(IProject* project)
{
QStandardItem* projectItem = itemForProject(project);
m_model->removeRow(projectItem->row());
}
void TestView::doubleClicked(const QModelIndex& index)
{
m_tree->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
runSelectedTests();
}
QList< QAction* > TestView::contextMenuActions()
{
return m_contextMenuActions;
}
| gpl-2.0 |
kvinodhbabu/linux | fs/overlayfs/copy_up.c | 513 | 9400 | /*
*
* Copyright (C) 2011 Novell 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.
*/
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/file.h>
#include <linux/splice.h>
#include <linux/xattr.h>
#include <linux/security.h>
#include <linux/uaccess.h>
#include <linux/sched.h>
#include <linux/namei.h>
#include "overlayfs.h"
#define OVL_COPY_UP_CHUNK_SIZE (1 << 20)
int ovl_copy_xattr(struct dentry *old, struct dentry *new)
{
ssize_t list_size, size;
char *buf, *name, *value;
int error;
if (!old->d_inode->i_op->getxattr ||
!new->d_inode->i_op->getxattr)
return 0;
list_size = vfs_listxattr(old, NULL, 0);
if (list_size <= 0) {
if (list_size == -EOPNOTSUPP)
return 0;
return list_size;
}
buf = kzalloc(list_size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
error = -ENOMEM;
value = kmalloc(XATTR_SIZE_MAX, GFP_KERNEL);
if (!value)
goto out;
list_size = vfs_listxattr(old, buf, list_size);
if (list_size <= 0) {
error = list_size;
goto out_free_value;
}
for (name = buf; name < (buf + list_size); name += strlen(name) + 1) {
size = vfs_getxattr(old, name, value, XATTR_SIZE_MAX);
if (size <= 0) {
error = size;
goto out_free_value;
}
error = vfs_setxattr(new, name, value, size, 0);
if (error)
goto out_free_value;
}
out_free_value:
kfree(value);
out:
kfree(buf);
return error;
}
static int ovl_copy_up_data(struct path *old, struct path *new, loff_t len)
{
struct file *old_file;
struct file *new_file;
loff_t old_pos = 0;
loff_t new_pos = 0;
int error = 0;
if (len == 0)
return 0;
old_file = ovl_path_open(old, O_RDONLY);
if (IS_ERR(old_file))
return PTR_ERR(old_file);
new_file = ovl_path_open(new, O_WRONLY);
if (IS_ERR(new_file)) {
error = PTR_ERR(new_file);
goto out_fput;
}
/* FIXME: copy up sparse files efficiently */
while (len) {
size_t this_len = OVL_COPY_UP_CHUNK_SIZE;
long bytes;
if (len < this_len)
this_len = len;
if (signal_pending_state(TASK_KILLABLE, current)) {
error = -EINTR;
break;
}
bytes = do_splice_direct(old_file, &old_pos,
new_file, &new_pos,
this_len, SPLICE_F_MOVE);
if (bytes <= 0) {
error = bytes;
break;
}
WARN_ON(old_pos != new_pos);
len -= bytes;
}
fput(new_file);
out_fput:
fput(old_file);
return error;
}
static char *ovl_read_symlink(struct dentry *realdentry)
{
int res;
char *buf;
struct inode *inode = realdentry->d_inode;
mm_segment_t old_fs;
res = -EINVAL;
if (!inode->i_op->readlink)
goto err;
res = -ENOMEM;
buf = (char *) __get_free_page(GFP_KERNEL);
if (!buf)
goto err;
old_fs = get_fs();
set_fs(get_ds());
/* The cast to a user pointer is valid due to the set_fs() */
res = inode->i_op->readlink(realdentry,
(char __user *)buf, PAGE_SIZE - 1);
set_fs(old_fs);
if (res < 0) {
free_page((unsigned long) buf);
goto err;
}
buf[res] = '\0';
return buf;
err:
return ERR_PTR(res);
}
static int ovl_set_timestamps(struct dentry *upperdentry, struct kstat *stat)
{
struct iattr attr = {
.ia_valid =
ATTR_ATIME | ATTR_MTIME | ATTR_ATIME_SET | ATTR_MTIME_SET,
.ia_atime = stat->atime,
.ia_mtime = stat->mtime,
};
return notify_change(upperdentry, &attr, NULL);
}
int ovl_set_attr(struct dentry *upperdentry, struct kstat *stat)
{
int err = 0;
if (!S_ISLNK(stat->mode)) {
struct iattr attr = {
.ia_valid = ATTR_MODE,
.ia_mode = stat->mode,
};
err = notify_change(upperdentry, &attr, NULL);
}
if (!err) {
struct iattr attr = {
.ia_valid = ATTR_UID | ATTR_GID,
.ia_uid = stat->uid,
.ia_gid = stat->gid,
};
err = notify_change(upperdentry, &attr, NULL);
}
if (!err)
ovl_set_timestamps(upperdentry, stat);
return err;
}
static int ovl_copy_up_locked(struct dentry *workdir, struct dentry *upperdir,
struct dentry *dentry, struct path *lowerpath,
struct kstat *stat, struct iattr *attr,
const char *link)
{
struct inode *wdir = workdir->d_inode;
struct inode *udir = upperdir->d_inode;
struct dentry *newdentry = NULL;
struct dentry *upper = NULL;
umode_t mode = stat->mode;
int err;
newdentry = ovl_lookup_temp(workdir, dentry);
err = PTR_ERR(newdentry);
if (IS_ERR(newdentry))
goto out;
upper = lookup_one_len(dentry->d_name.name, upperdir,
dentry->d_name.len);
err = PTR_ERR(upper);
if (IS_ERR(upper))
goto out1;
/* Can't properly set mode on creation because of the umask */
stat->mode &= S_IFMT;
err = ovl_create_real(wdir, newdentry, stat, link, NULL, true);
stat->mode = mode;
if (err)
goto out2;
if (S_ISREG(stat->mode)) {
struct path upperpath;
ovl_path_upper(dentry, &upperpath);
BUG_ON(upperpath.dentry != NULL);
upperpath.dentry = newdentry;
err = ovl_copy_up_data(lowerpath, &upperpath, stat->size);
if (err)
goto out_cleanup;
}
err = ovl_copy_xattr(lowerpath->dentry, newdentry);
if (err)
goto out_cleanup;
mutex_lock(&newdentry->d_inode->i_mutex);
err = ovl_set_attr(newdentry, stat);
if (!err && attr)
err = notify_change(newdentry, attr, NULL);
mutex_unlock(&newdentry->d_inode->i_mutex);
if (err)
goto out_cleanup;
err = ovl_do_rename(wdir, newdentry, udir, upper, 0);
if (err)
goto out_cleanup;
ovl_dentry_update(dentry, newdentry);
newdentry = NULL;
/*
* Non-directores become opaque when copied up.
*/
if (!S_ISDIR(stat->mode))
ovl_dentry_set_opaque(dentry, true);
out2:
dput(upper);
out1:
dput(newdentry);
out:
return err;
out_cleanup:
ovl_cleanup(wdir, newdentry);
goto out;
}
/*
* Copy up a single dentry
*
* Directory renames only allowed on "pure upper" (already created on
* upper filesystem, never copied up). Directories which are on lower or
* are merged may not be renamed. For these -EXDEV is returned and
* userspace has to deal with it. This means, when copying up a
* directory we can rely on it and ancestors being stable.
*
* Non-directory renames start with copy up of source if necessary. The
* actual rename will only proceed once the copy up was successful. Copy
* up uses upper parent i_mutex for exclusion. Since rename can change
* d_parent it is possible that the copy up will lock the old parent. At
* that point the file will have already been copied up anyway.
*/
int ovl_copy_up_one(struct dentry *parent, struct dentry *dentry,
struct path *lowerpath, struct kstat *stat,
struct iattr *attr)
{
struct dentry *workdir = ovl_workdir(dentry);
int err;
struct kstat pstat;
struct path parentpath;
struct dentry *upperdir;
struct dentry *upperdentry;
const struct cred *old_cred;
struct cred *override_cred;
char *link = NULL;
if (WARN_ON(!workdir))
return -EROFS;
ovl_path_upper(parent, &parentpath);
upperdir = parentpath.dentry;
err = vfs_getattr(&parentpath, &pstat);
if (err)
return err;
if (S_ISLNK(stat->mode)) {
link = ovl_read_symlink(lowerpath->dentry);
if (IS_ERR(link))
return PTR_ERR(link);
}
err = -ENOMEM;
override_cred = prepare_creds();
if (!override_cred)
goto out_free_link;
override_cred->fsuid = stat->uid;
override_cred->fsgid = stat->gid;
/*
* CAP_SYS_ADMIN for copying up extended attributes
* CAP_DAC_OVERRIDE for create
* CAP_FOWNER for chmod, timestamp update
* CAP_FSETID for chmod
* CAP_CHOWN for chown
* CAP_MKNOD for mknod
*/
cap_raise(override_cred->cap_effective, CAP_SYS_ADMIN);
cap_raise(override_cred->cap_effective, CAP_DAC_OVERRIDE);
cap_raise(override_cred->cap_effective, CAP_FOWNER);
cap_raise(override_cred->cap_effective, CAP_FSETID);
cap_raise(override_cred->cap_effective, CAP_CHOWN);
cap_raise(override_cred->cap_effective, CAP_MKNOD);
old_cred = override_creds(override_cred);
err = -EIO;
if (lock_rename(workdir, upperdir) != NULL) {
pr_err("overlayfs: failed to lock workdir+upperdir\n");
goto out_unlock;
}
upperdentry = ovl_dentry_upper(dentry);
if (upperdentry) {
unlock_rename(workdir, upperdir);
err = 0;
/* Raced with another copy-up? Do the setattr here */
if (attr) {
mutex_lock(&upperdentry->d_inode->i_mutex);
err = notify_change(upperdentry, attr, NULL);
mutex_unlock(&upperdentry->d_inode->i_mutex);
}
goto out_put_cred;
}
err = ovl_copy_up_locked(workdir, upperdir, dentry, lowerpath,
stat, attr, link);
if (!err) {
/* Restore timestamps on parent (best effort) */
ovl_set_timestamps(upperdir, &pstat);
}
out_unlock:
unlock_rename(workdir, upperdir);
out_put_cred:
revert_creds(old_cred);
put_cred(override_cred);
out_free_link:
if (link)
free_page((unsigned long) link);
return err;
}
int ovl_copy_up(struct dentry *dentry)
{
int err;
err = 0;
while (!err) {
struct dentry *next;
struct dentry *parent;
struct path lowerpath;
struct kstat stat;
enum ovl_path_type type = ovl_path_type(dentry);
if (OVL_TYPE_UPPER(type))
break;
next = dget(dentry);
/* find the topmost dentry not yet copied up */
for (;;) {
parent = dget_parent(next);
type = ovl_path_type(parent);
if (OVL_TYPE_UPPER(type))
break;
dput(next);
next = parent;
}
ovl_path_lower(next, &lowerpath);
err = vfs_getattr(&lowerpath, &stat);
if (!err)
err = ovl_copy_up_one(parent, next, &lowerpath, &stat, NULL);
dput(parent);
dput(next);
}
return err;
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.