code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
// Copyright 2010 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include <fstream>
#include <string>
#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
#include "Common/StringUtil.h"
#include "VideoBackends/D3D/D3DBase.h"
#include "VideoBackends/D3D/D3DShader.h"
#include "VideoCommon/VideoConfig.h"
namespace DX11
{
namespace D3D
{
// bytecode->shader
ID3D11VertexShader* CreateVertexShaderFromByteCode(const void* bytecode, size_t len)
{
ID3D11VertexShader* v_shader;
HRESULT hr = D3D::device->CreateVertexShader(bytecode, len, nullptr, &v_shader);
if (FAILED(hr))
return nullptr;
return v_shader;
}
// code->bytecode
bool CompileVertexShader(const std::string& code, D3DBlob** blob)
{
ID3D10Blob* shaderBuffer = nullptr;
ID3D10Blob* errorBuffer = nullptr;
#if defined(_DEBUG) || defined(DEBUGFAST)
UINT flags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY | D3D10_SHADER_DEBUG;
#else
UINT flags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY | D3D10_SHADER_OPTIMIZATION_LEVEL3 |
D3D10_SHADER_SKIP_VALIDATION;
#endif
HRESULT hr = PD3DCompile(code.c_str(), code.length(), nullptr, nullptr, nullptr, "main",
D3D::VertexShaderVersionString(), flags, 0, &shaderBuffer, &errorBuffer);
if (errorBuffer)
{
INFO_LOG(VIDEO, "Vertex shader compiler messages:\n%s",
(const char*)errorBuffer->GetBufferPointer());
}
if (FAILED(hr))
{
static int num_failures = 0;
std::string filename = StringFromFormat("%sbad_vs_%04i.txt",
File::GetUserPath(D_DUMP_IDX).c_str(), num_failures++);
std::ofstream file;
File::OpenFStream(file, filename, std::ios_base::out);
file << code;
file.close();
PanicAlert("Failed to compile vertex shader: %s\nDebug info (%s):\n%s", filename.c_str(),
D3D::VertexShaderVersionString(), (const char*)errorBuffer->GetBufferPointer());
*blob = nullptr;
errorBuffer->Release();
}
else
{
*blob = new D3DBlob(shaderBuffer);
shaderBuffer->Release();
}
return SUCCEEDED(hr);
}
// bytecode->shader
ID3D11GeometryShader* CreateGeometryShaderFromByteCode(const void* bytecode, size_t len)
{
ID3D11GeometryShader* g_shader;
HRESULT hr = D3D::device->CreateGeometryShader(bytecode, len, nullptr, &g_shader);
if (FAILED(hr))
return nullptr;
return g_shader;
}
// code->bytecode
bool CompileGeometryShader(const std::string& code, D3DBlob** blob,
const D3D_SHADER_MACRO* pDefines)
{
ID3D10Blob* shaderBuffer = nullptr;
ID3D10Blob* errorBuffer = nullptr;
#if defined(_DEBUG) || defined(DEBUGFAST)
UINT flags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY | D3D10_SHADER_DEBUG;
#else
UINT flags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY | D3D10_SHADER_OPTIMIZATION_LEVEL3 |
D3D10_SHADER_SKIP_VALIDATION;
#endif
HRESULT hr =
PD3DCompile(code.c_str(), code.length(), nullptr, pDefines, nullptr, "main",
D3D::GeometryShaderVersionString(), flags, 0, &shaderBuffer, &errorBuffer);
if (errorBuffer)
{
INFO_LOG(VIDEO, "Geometry shader compiler messages:\n%s",
(const char*)errorBuffer->GetBufferPointer());
}
if (FAILED(hr))
{
static int num_failures = 0;
std::string filename = StringFromFormat("%sbad_gs_%04i.txt",
File::GetUserPath(D_DUMP_IDX).c_str(), num_failures++);
std::ofstream file;
File::OpenFStream(file, filename, std::ios_base::out);
file << code;
file.close();
PanicAlert("Failed to compile geometry shader: %s\nDebug info (%s):\n%s", filename.c_str(),
D3D::GeometryShaderVersionString(), (const char*)errorBuffer->GetBufferPointer());
*blob = nullptr;
errorBuffer->Release();
}
else
{
*blob = new D3DBlob(shaderBuffer);
shaderBuffer->Release();
}
return SUCCEEDED(hr);
}
// bytecode->shader
ID3D11PixelShader* CreatePixelShaderFromByteCode(const void* bytecode, size_t len)
{
ID3D11PixelShader* p_shader;
HRESULT hr = D3D::device->CreatePixelShader(bytecode, len, nullptr, &p_shader);
if (FAILED(hr))
{
PanicAlert("CreatePixelShaderFromByteCode failed at %s %d\n", __FILE__, __LINE__);
p_shader = nullptr;
}
return p_shader;
}
// code->bytecode
bool CompilePixelShader(const std::string& code, D3DBlob** blob, const D3D_SHADER_MACRO* pDefines)
{
ID3D10Blob* shaderBuffer = nullptr;
ID3D10Blob* errorBuffer = nullptr;
#if defined(_DEBUG) || defined(DEBUGFAST)
UINT flags = D3D10_SHADER_DEBUG;
#else
UINT flags = D3D10_SHADER_OPTIMIZATION_LEVEL3;
#endif
HRESULT hr = PD3DCompile(code.c_str(), code.length(), nullptr, pDefines, nullptr, "main",
D3D::PixelShaderVersionString(), flags, 0, &shaderBuffer, &errorBuffer);
if (errorBuffer)
{
INFO_LOG(VIDEO, "Pixel shader compiler messages:\n%s",
(const char*)errorBuffer->GetBufferPointer());
}
if (FAILED(hr))
{
static int num_failures = 0;
std::string filename = StringFromFormat("%sbad_ps_%04i.txt",
File::GetUserPath(D_DUMP_IDX).c_str(), num_failures++);
std::ofstream file;
File::OpenFStream(file, filename, std::ios_base::out);
file << code;
file.close();
PanicAlert("Failed to compile pixel shader: %s\nDebug info (%s):\n%s", filename.c_str(),
D3D::PixelShaderVersionString(), (const char*)errorBuffer->GetBufferPointer());
*blob = nullptr;
errorBuffer->Release();
}
else
{
*blob = new D3DBlob(shaderBuffer);
shaderBuffer->Release();
}
return SUCCEEDED(hr);
}
ID3D11VertexShader* CompileAndCreateVertexShader(const std::string& code)
{
D3DBlob* blob = nullptr;
if (CompileVertexShader(code, &blob))
{
ID3D11VertexShader* v_shader = CreateVertexShaderFromByteCode(blob);
blob->Release();
return v_shader;
}
return nullptr;
}
ID3D11GeometryShader* CompileAndCreateGeometryShader(const std::string& code,
const D3D_SHADER_MACRO* pDefines)
{
D3DBlob* blob = nullptr;
if (CompileGeometryShader(code, &blob, pDefines))
{
ID3D11GeometryShader* g_shader = CreateGeometryShaderFromByteCode(blob);
blob->Release();
return g_shader;
}
return nullptr;
}
ID3D11PixelShader* CompileAndCreatePixelShader(const std::string& code)
{
D3DBlob* blob = nullptr;
CompilePixelShader(code, &blob);
if (blob)
{
ID3D11PixelShader* p_shader = CreatePixelShaderFromByteCode(blob);
blob->Release();
return p_shader;
}
return nullptr;
}
} // namespace
} // namespace DX11
| ligfx/dolphin | Source/Core/VideoBackends/D3D/D3DShader.cpp | C++ | gpl-2.0 | 6,767 |
//==========================================================================
//
// mpc555_serial_with_ints.c
//
// PowerPC 5xx MPC555 Serial I/O Interface Module (interrupt driven)
//
//==========================================================================
// ####ECOSGPLCOPYRIGHTBEGIN####
// -------------------------------------------
// This file is part of eCos, the Embedded Configurable Operating System.
// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
//
// eCos 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.
//
// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// As a special exception, if other files instantiate templates or use
// macros or inline functions from this file, or you compile this file
// and link it with other works to produce a work based on this file,
// this file does not by itself cause the resulting work to be covered by
// the GNU General Public License. However the source code for this file
// must still be made available in accordance with section (3) of the GNU
// General Public License v2.
//
// This exception does not invalidate any other reasons why a work based
// on this file might be covered by the GNU General Public License.
// -------------------------------------------
// ####ECOSGPLCOPYRIGHTEND####
//==========================================================================
//#####DESCRIPTIONBEGIN####
//
// Author(s): Bob Koninckx
// Contributors:
// Date: 2002-04-25
// Purpose: MPC555 Serial I/O module (interrupt driven version)
// Description:
//
//
//####DESCRIPTIONEND####
//==========================================================================
//----------------------------------
// Includes and forward declarations
//----------------------------------
#include <pkgconf/io_serial.h>
#include <pkgconf/io.h>
#include <cyg/io/io.h>
#include <cyg/hal/hal_intr.h>
#include <cyg/hal/hal_arbiter.h>
#include <cyg/io/devtab.h>
#include <cyg/infra/diag.h>
#include <cyg/io/serial.h>
// Only build this driver for the MPC555 based boards
#if defined (CYGPKG_IO_SERIAL_POWERPC_MPC555) && \
(defined (CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_A) || \
defined (CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_B))
#include "mpc555_serial.h"
//---------------------------------------------------------------------------
// Type definitions
//---------------------------------------------------------------------------
#define MPC555_SCI_RX_BUFF_SIZE 256
typedef struct st_sci_circbuf {
cyg_uint8 buf[MPC555_SCI_RX_BUFF_SIZE];
cyg_uint16 scsr[MPC555_SCI_RX_BUFF_SIZE];
cyg_uint8 fill_pos;
cyg_uint8 read_pos;
} mpc555_sci_circbuf_t;
typedef struct mpc555_serial_info {
CYG_ADDRWORD base; // The base address of the serial port
CYG_WORD tx_interrupt_num; // trivial
CYG_WORD rx_interrupt_num; // trivial
cyg_priority_t tx_interrupt_priority;// trivial
cyg_priority_t rx_interrupt_priority;// trivial
bool tx_interrupt_enable; // can the tx interrupt be re-enabled?
mpc555_sci_circbuf_t* rx_circbuf; // rx buff for ISR to DSR data exchange
bool use_queue; // Use the queue when available?
CYG_WORD rx_last_queue_pointer;// Keep track where queue read is upto
CYG_WORD rx_interrupt_idle_line_num; // trivial
CYG_WORD tx_interrupt_queue_top_empty_num; // trivial
CYG_WORD tx_interrupt_queue_bot_empty_num; // trivial
CYG_WORD rx_interrupt_queue_top_full_num; // trivial
CYG_WORD rx_interrupt_queue_bot_full_num; // trivial
cyg_priority_t rx_interrupt_idle_line_priority; // trivial
cyg_priority_t tx_interrupt_queue_top_empty_priority; // trivial
cyg_priority_t tx_interrupt_queue_bot_empty_priority; // trivial
cyg_priority_t rx_interrupt_queue_top_full_priority; // trivial
cyg_priority_t rx_interrupt_queue_bot_full_priority; // trivial
cyg_interrupt tx_interrupt; // the tx interrupt object
cyg_handle_t tx_interrupt_handle; // the tx interrupt handle
cyg_interrupt rx_interrupt; // the rx interrupt object
cyg_handle_t rx_interrupt_handle; // the rx interrupt handle
cyg_interrupt rx_idle_interrupt; // the rx idle line isr object
cyg_handle_t rx_idle_interrupt_handle; // the rx idle line isr handle
cyg_interrupt tx_queue_top_interrupt; // the tx interrupt object
cyg_handle_t tx_queue_top_interrupt_handle;// the tx interrupt handle
cyg_interrupt tx_queue_bot_interrupt; // the tx interrupt object
cyg_handle_t tx_queue_bot_interrupt_handle;// the tx interrupt handle
cyg_interrupt rx_queue_top_interrupt; // the tx interrupt object
cyg_handle_t rx_queue_top_interrupt_handle;// the tx interrupt handle
cyg_interrupt rx_queue_bot_interrupt; // the tx interrupt object
cyg_handle_t rx_queue_bot_interrupt_handle;// the tx interrupt handle
} mpc555_serial_info;
//--------------------
// Function prototypes
//--------------------
static bool mpc555_serial_putc(serial_channel * chan, unsigned char c);
static unsigned char mpc555_serial_getc(serial_channel *chan);
static Cyg_ErrNo mpc555_serial_set_config(serial_channel *chan, cyg_uint32 key,
const void *xbuf, cyg_uint32 *len);
static void mpc555_serial_start_xmit(serial_channel *chan);
static void mpc555_serial_stop_xmit(serial_channel *chan);
static Cyg_ErrNo mpc555_serial_lookup(struct cyg_devtab_entry ** tab,
struct cyg_devtab_entry * sub_tab,
const char * name);
static bool mpc555_serial_init(struct cyg_devtab_entry * tab);
// The interrupt servers
static cyg_uint32 mpc555_serial_tx_ISR(cyg_vector_t vector, cyg_addrword_t data);
static cyg_uint32 mpc555_serial_rx_ISR(cyg_vector_t vector, cyg_addrword_t data);
static void mpc555_serial_tx_DSR(cyg_vector_t vector,
cyg_ucount32 count,
cyg_addrword_t data);
static void mpc555_serial_rx_DSR(cyg_vector_t vector,
cyg_ucount32 count,
cyg_addrword_t data);
#ifdef CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_A
static cyg_uint32 mpc555_serial_tx_queue_top_ISR(cyg_vector_t vector,
cyg_addrword_t data);
static cyg_uint32 mpc555_serial_tx_queue_bot_ISR(cyg_vector_t vector,
cyg_addrword_t data);
static cyg_uint32 mpc555_serial_rx_queue_top_ISR(cyg_vector_t vector,
cyg_addrword_t data);
static cyg_uint32 mpc555_serial_rx_queue_bot_ISR(cyg_vector_t vector,
cyg_addrword_t data);
static cyg_uint32 mpc555_serial_rx_idle_line_ISR(cyg_vector_t vector,
cyg_addrword_t data);
static void mpc555_serial_tx_queue_DSR(cyg_vector_t vector,
cyg_ucount32 count,
cyg_addrword_t data);
static void mpc555_serial_rx_queue_DSR(cyg_vector_t vector,
cyg_ucount32 count,
cyg_addrword_t data);
static int mpc555_serial_read_queue(serial_channel* chan, int start, int end);
#endif
//------------------------------------------------------------------------------
// Register the device driver with the kernel
//------------------------------------------------------------------------------
static SERIAL_FUNS(mpc555_serial_funs,
mpc555_serial_putc,
mpc555_serial_getc,
mpc555_serial_set_config,
mpc555_serial_start_xmit,
mpc555_serial_stop_xmit);
//------------------------------------------------------------------------------
// Device driver data
//------------------------------------------------------------------------------
#ifdef CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_A
#ifdef CYGDAT_IO_SERIAL_POWERPC_MPC555_SERIAL_A_USE_HWARE_QUEUE
//static mpc555_sci_circbuf_t mpc555_serial_isr_to_dsr_buf0;
static mpc555_serial_info mpc555_serial_info0 = {
MPC555_SERIAL_BASE_A,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TX,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RX,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TX_PRIORITY,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RX_PRIORITY,
false,
NULL, // Don't need software buffer
true, // Use queue
0, // init queue pointer
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_IDLE,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TXQTHE,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TXQBHE,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RXQTHF,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RXQBHF,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_IDLE_PRIORITY,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TXQTHE_PRIORITY,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TXQBHE_PRIORITY,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RXQTHF_PRIORITY,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RXQBHF_PRIORITY};
static unsigned char mpc555_serial_out_buf0[CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_A_BUFSIZE];
static unsigned char mpc555_serial_in_buf0[CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_A_BUFSIZE];
static SERIAL_CHANNEL_USING_INTERRUPTS(
mpc555_serial_channel0,
mpc555_serial_funs,
mpc555_serial_info0,
CYG_SERIAL_BAUD_RATE(CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_A_BAUD),
CYG_SERIAL_STOP_DEFAULT,
CYG_SERIAL_PARITY_DEFAULT,
CYG_SERIAL_WORD_LENGTH_DEFAULT,
CYG_SERIAL_FLAGS_DEFAULT,
&mpc555_serial_out_buf0[0],
sizeof(mpc555_serial_out_buf0),
&mpc555_serial_in_buf0[0],
sizeof(mpc555_serial_in_buf0));
#elif CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_A_BUFSIZE > 0
static mpc555_sci_circbuf_t mpc555_serial_isr_to_dsr_buf0;
static mpc555_serial_info mpc555_serial_info0 = {
MPC555_SERIAL_BASE_A,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TX,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RX,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TX_PRIORITY,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RX_PRIORITY,
false,
&mpc555_serial_isr_to_dsr_buf0,
false};
static unsigned char mpc555_serial_out_buf0[CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_A_BUFSIZE];
static unsigned char mpc555_serial_in_buf0[CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_A_BUFSIZE];
static SERIAL_CHANNEL_USING_INTERRUPTS(
mpc555_serial_channel0,
mpc555_serial_funs,
mpc555_serial_info0,
CYG_SERIAL_BAUD_RATE(CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_A_BAUD),
CYG_SERIAL_STOP_DEFAULT,
CYG_SERIAL_PARITY_DEFAULT,
CYG_SERIAL_WORD_LENGTH_DEFAULT,
CYG_SERIAL_FLAGS_DEFAULT,
&mpc555_serial_out_buf0[0],
sizeof(mpc555_serial_out_buf0),
&mpc555_serial_in_buf0[0],
sizeof(mpc555_serial_in_buf0));
#else
static mpc555_serial_info mpc555_serial_info0 = {
MPC555_SERIAL_BASE_A,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TX,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RX,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TX_PRIORITY,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RX_PRIORITY,
false,
NULL,
false};
static SERIAL_CHANNEL(
mpc555_serial_channel0,
mpc555_serial_funs,
mpc555_serial_info0,
CYG_SERIAL_BAUD_RATE(CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_A_BAUD),
CYG_SERIAL_STOP_DEFAULT,
CYG_SERIAL_PARITY_DEFAULT,
CYG_SERIAL_WORD_LENGTH_DEFAULT,
CYG_SERIAL_FLAGS_DEFAULT);
#endif
DEVTAB_ENTRY(mpc555_serial_io0,
CYGDAT_IO_SERIAL_POWERPC_MPC555_SERIAL_A_NAME,
0, // does not depend on a lower level device driver
&cyg_io_serial_devio,
mpc555_serial_init,
mpc555_serial_lookup,
&mpc555_serial_channel0);
#endif // ifdef CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_A
#ifdef CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_B
#if CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_B_BUFSIZE > 0
static mpc555_sci_circbuf_t mpc555_serial_isr_to_dsr_buf1;
static mpc555_serial_info mpc555_serial_info1 = {
MPC555_SERIAL_BASE_B,
CYGNUM_HAL_INTERRUPT_IMB3_SCI2_TX,
CYGNUM_HAL_INTERRUPT_IMB3_SCI2_RX,
CYGNUM_HAL_INTERRUPT_IMB3_SCI2_TX_PRIORITY,
CYGNUM_HAL_INTERRUPT_IMB3_SCI2_RX_PRIORITY,
false,
&mpc555_serial_isr_to_dsr_buf1,
false};
static unsigned char mpc555_serial_out_buf1[CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_B_BUFSIZE];
static unsigned char mpc555_serial_in_buf1[CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_B_BUFSIZE];
static SERIAL_CHANNEL_USING_INTERRUPTS(
mpc555_serial_channel1,
mpc555_serial_funs,
mpc555_serial_info1,
CYG_SERIAL_BAUD_RATE(CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_B_BAUD),
CYG_SERIAL_STOP_DEFAULT,
CYG_SERIAL_PARITY_DEFAULT,
CYG_SERIAL_WORD_LENGTH_DEFAULT,
CYG_SERIAL_FLAGS_DEFAULT,
&mpc555_serial_out_buf1[0],
sizeof(mpc555_serial_out_buf1),
&mpc555_serial_in_buf1[0],
sizeof(mpc555_serial_in_buf1));
#else
static mpc555_serial_info mpc555_serial_info1 = {
MPC555_SERIAL_BASE_B,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TX,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RX,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TX_PRIORITY,
CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RX_PRIORITY,
false,
NULL,
false};
static SERIAL_CHANNEL(
mpc555_serial_channel1,
mpc555_serial_funs,
mpc555_serial_info1,
CYG_SERIAL_BAUD_RATE(CYGNUM_IO_SERIAL_POWERPC_MPC555_SERIAL_B_BAUD),
CYG_SERIAL_STOP_DEFAULT,
CYG_SERIAL_PARITY_DEFAULT,
CYG_SERIAL_WORD_LENGTH_DEFAULT,
CYG_SERIAL_FLAGS_DEFAULT);
#endif
DEVTAB_ENTRY(mpc555_serial_io1,
CYGDAT_IO_SERIAL_POWERPC_MPC555_SERIAL_B_NAME,
0, // does not depend on a lower level device driver
&cyg_io_serial_devio,
mpc555_serial_init,
mpc555_serial_lookup,
&mpc555_serial_channel1);
#endif // ifdef CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_B
//------------------------------------------------------------------------------
// Device driver implementation
//------------------------------------------------------------------------------
// The arbitration isr.
// I think this is the best place to implement it.
// The device driver is the only place in the code where the knowledge is
// present about how the hardware is used.
//
// Always check receive interrupts.
// Some rom monitor might be waiting for CTRL-C
static cyg_uint32 hal_arbitration_isr_qsci(CYG_ADDRWORD a_vector,
CYG_ADDRWORD a_data)
{
cyg_uint16 status;
cyg_uint16 control;
HAL_READ_UINT16(CYGARC_REG_IMM_SC1SR, status);
HAL_READ_UINT16(CYGARC_REG_IMM_SCC1R1, control);
if((status & CYGARC_REG_IMM_SCxSR_RDRF) &&
(control & CYGARC_REG_IMM_SCCxR1_RIE))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RX);
// Do not waist time on unused hardware
#ifdef CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_A
#ifdef CYGDAT_IO_SERIAL_POWERPC_MPC555_SERIAL_A_USE_HWARE_QUEUE
// Only one port supports queue mode
if((status & CYGARC_REG_IMM_SCxSR_IDLE) &&
(control & CYGARC_REG_IMM_SCCxR1_ILIE))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI1_IDLE);
HAL_READ_UINT16(CYGARC_REG_IMM_QSCI1SR, status);
HAL_READ_UINT16(CYGARC_REG_IMM_QSCI1CR, control);
if((status & CYGARC_REG_IMM_QSCI1SR_QTHF) &&
(control & CYGARC_REG_IMM_QSCI1CR_QTHFI))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RXQTHF);
if((status & CYGARC_REG_IMM_QSCI1SR_QBHF) &&
(control & CYGARC_REG_IMM_QSCI1CR_QBHFI))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI1_RXQBHF);
if((status & CYGARC_REG_IMM_QSCI1SR_QTHE) &&
(control & CYGARC_REG_IMM_QSCI1CR_QTHEI))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TXQTHE);
if((status & CYGARC_REG_IMM_QSCI1SR_QBHE) &&
(control & CYGARC_REG_IMM_QSCI1CR_QBHEI))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TXQBHE);
// Only for SPI, leave fo future reference
#if 0
HAL_READ_UINT16(CYGARC_REG_IMM_SPSR, status);
HAL_READ_UINT16(CYGARC_REG_IMM_SPCR2, control);
if((status & CYGARC_REG_IMM_SPSR_SPIF) &&
(control & CYGARC_REG_IMM_SPCR2_SPIFIE))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SPI_FI);
HAL_READ_UINT16(CYGARC_REG_IMM_SPCR3, control);
if((status & CYGARC_REG_IMM_SPSR_MODF) &&
(control & CYGARC_REG_IMM_SPCR3_HMIE))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SPI_MODF);
if((status & CYGARC_REG_IMM_SPSR_HALTA) &&
(control & CYGARC_REG_IMM_SPCR3_HMIE))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SPI_HALTA);
#endif
#else //No HW Queue
if((status & CYGARC_REG_IMM_SCxSR_TDRE) &&
(control & CYGARC_REG_IMM_SCCxR1_TIE))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TX);
// Don't waist time on unused interrupts
// Transmit complete interrupt enabled (not used)
// if((status & CYGARC_REG_IMM_SCxSR_TC) && (control & CYGARC_REG_IMM_SCCxR1_TCIE))
// return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI1_TXC);
// Don't waist time on unused interrupts
// Idle-line interrupt enabled (not used)
// if((status & CYGARC_REG_IMM_SCxSR_IDLE) && (control & CYGARC_REG_IMM_SCCxR1_ILIE))
// return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI1_IDLE);
#endif // HW_QUEUE
#endif // SERIAL_A
HAL_READ_UINT16(CYGARC_REG_IMM_SC2SR, status);
HAL_READ_UINT16(CYGARC_REG_IMM_SCC2R1, control);
if((status & CYGARC_REG_IMM_SCxSR_RDRF) &&
(control & CYGARC_REG_IMM_SCCxR1_RIE))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI2_RX);
// Do not waist time on unused hardware
#ifdef CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_B
if((status & CYGARC_REG_IMM_SCxSR_TDRE) &&
(control & CYGARC_REG_IMM_SCCxR1_TIE))
return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI2_TX);
// Don't waist time on unused interrupts
// Transmit complete interrupt enabled (not used)
// if((status & CYGARC_REG_IMM_SCxSR_TC) && (control & CYGARC_REG_IMM_SCCxR1_TCIE))
// return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI2_TXC);
// Don't waist time on unused interrupts
// Idle-line interrupt enabled (not used)
// if((status & CYGARC_REG_IMM_SCxSR_IDLE) && (control & CYGARC_REG_IMM_SCCxR1_ILIE))
// return hal_call_isr(CYGNUM_HAL_INTERRUPT_IMB3_SCI2_IDLE);
#endif
return 0;
}
//------------------------------------------------------------------------------
// Internal function to configure the hardware to desired baud rate, etc.
//------------------------------------------------------------------------------
static bool mpc555_serial_config_port(serial_channel * chan,
cyg_serial_info_t * new_config,
bool init)
{
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)(chan->dev_priv);
cyg_addrword_t port = mpc555_chan->base;
cyg_uint16 baud_rate = select_baud[new_config->baud];
unsigned char frame_length = 1; // The start bit
cyg_uint16 old_isrstate;
cyg_uint16 sccxr;
if(!baud_rate)
return false; // Invalid baud rate selected
if((new_config->word_length != CYGNUM_SERIAL_WORD_LENGTH_7) &&
(new_config->word_length != CYGNUM_SERIAL_WORD_LENGTH_8))
return false; // Invalid word length selected
if((new_config->parity != CYGNUM_SERIAL_PARITY_NONE) &&
(new_config->parity != CYGNUM_SERIAL_PARITY_EVEN) &&
(new_config->parity != CYGNUM_SERIAL_PARITY_ODD))
return false; // Invalid parity selected
if((new_config->stop != CYGNUM_SERIAL_STOP_1) &&
(new_config->stop != CYGNUM_SERIAL_STOP_2))
return false; // Invalid stop bits selected
frame_length += select_word_length[new_config->word_length -
CYGNUM_SERIAL_WORD_LENGTH_5];
frame_length += select_stop_bits[new_config->stop];
frame_length += select_parity[new_config->parity];
if((frame_length != 10) && (frame_length != 11))
return false; // Invalid frame format selected
// Disable port interrupts while changing hardware
HAL_READ_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
old_isrstate = sccxr;
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_LOOPS);
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_WOMS);
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_ILT);
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_PT);
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_PE);
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_M);
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_WAKE);
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_TE);
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_RE);
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_RWU);
old_isrstate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_SBK);
sccxr &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_TIE);
sccxr &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_TCIE);
sccxr &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_RIE);
sccxr &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_ILIE);
HAL_WRITE_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
#ifdef CYGDAT_IO_SERIAL_POWERPC_MPC555_SERIAL_A_USE_HWARE_QUEUE
cyg_uint16 qsci1cr = 0;
if(mpc555_chan->use_queue){
HAL_READ_UINT16( CYGARC_REG_IMM_QSCI1SR, qsci1cr);
// disable queue
qsci1cr &= ~((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QTE);
qsci1cr &= ~((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QRE);
// disable queue interrupts
qsci1cr &= ~((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QTHFI);
qsci1cr &= ~((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QBHFI);
qsci1cr &= ~((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QTHEI);
qsci1cr &= ~((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QBHEI);
HAL_WRITE_UINT16( CYGARC_REG_IMM_QSCI1SR, qsci1cr);
}
#endif
// Set databits, stopbits and parity.
HAL_READ_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
if(frame_length == 11)
sccxr |= (cyg_uint16)MPC555_SERIAL_SCCxR1_M;
else
sccxr &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_M);
switch(new_config->parity){
case CYGNUM_SERIAL_PARITY_NONE:
sccxr &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_PE);
break;
case CYGNUM_SERIAL_PARITY_EVEN:
sccxr |= (cyg_uint16)MPC555_SERIAL_SCCxR1_PE;
sccxr &= ~((cyg_uint16)MPC555_SERIAL_SCCxR1_PT);
break;
case CYGNUM_SERIAL_PARITY_ODD:
sccxr |= (cyg_uint16)MPC555_SERIAL_SCCxR1_PE;
sccxr |= (cyg_uint16)MPC555_SERIAL_SCCxR1_PT;
break;
default:
break;
}
HAL_WRITE_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
// Set baud rate.
baud_rate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR0_OTHR);
baud_rate &= ~((cyg_uint16)MPC555_SERIAL_SCCxR0_LINKBD);
HAL_READ_UINT16(port + MPC555_SERIAL_SCCxR0, sccxr);
sccxr &= ~(MPC555_SERIAL_SCCxR0_SCxBR);
sccxr |= baud_rate;
HAL_WRITE_UINT16(port + MPC555_SERIAL_SCCxR0, sccxr);
// Enable the device
HAL_READ_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
sccxr |= MPC555_SERIAL_SCCxR1_TE;
sccxr |= MPC555_SERIAL_SCCxR1_RE;
HAL_WRITE_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
if(init){
#ifdef CYGDAT_IO_SERIAL_POWERPC_MPC555_SERIAL_A_USE_HWARE_QUEUE
HAL_READ_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
if(mpc555_chan->use_queue){
cyg_uint16 qsci1sr;
// enable read queue
qsci1cr |= ((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QRE);
// enable receive queue interrupts
qsci1cr |= ((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QTHFI);
qsci1cr |= ((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QBHFI);
HAL_WRITE_UINT16( CYGARC_REG_IMM_QSCI1CR, qsci1cr);
// also enable idle line detect interrupt
sccxr |= MPC555_SERIAL_SCxSR_IDLE;
HAL_READ_UINT16( CYGARC_REG_IMM_QSCI1SR, qsci1sr);
qsci1sr &= ~((cyg_uint16)CYGARC_REG_IMM_QSCI1SR_QBHF);
qsci1sr &= ~((cyg_uint16)CYGARC_REG_IMM_QSCI1SR_QTHF);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1SR, qsci1sr);
}
else {
// enable the receiver interrupt
sccxr |= MPC555_SERIAL_SCCxR1_RIE;
}
HAL_WRITE_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
#else
// enable the receiver interrupt
HAL_READ_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
sccxr |= MPC555_SERIAL_SCCxR1_RIE;
HAL_WRITE_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
#endif
}
else {// Restore the old interrupt state
HAL_READ_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
sccxr |= old_isrstate;
HAL_WRITE_UINT16(port + MPC555_SERIAL_SCCxR1, sccxr);
}
if(new_config != &chan->config)
chan->config = *new_config;
return true;
}
//------------------------------------------------------------------------------
// Function to initialize the device. Called at bootstrap time.
//------------------------------------------------------------------------------
static hal_mpc5xx_arbitration_data arbiter;
static bool mpc555_serial_init(struct cyg_devtab_entry * tab){
serial_channel * chan = (serial_channel *)tab->priv;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
if(!mpc555_serial_config_port(chan, &chan->config, true))
return false;
// Really only required for interrupt driven devices
(chan->callbacks->serial_init)(chan);
if(chan->out_cbuf.len != 0){
arbiter.priority = CYGNUM_HAL_ISR_SOURCE_PRIORITY_QSCI;
arbiter.data = 0;
arbiter.arbiter = hal_arbitration_isr_qsci;
// Install the arbitration isr, Make sure that is is not installed twice
hal_mpc5xx_remove_arbitration_isr(CYGNUM_HAL_ISR_SOURCE_PRIORITY_QSCI);
hal_mpc5xx_install_arbitration_isr(&arbiter);
// if !(Chan_B && using queue)
if(!mpc555_chan->use_queue){
mpc555_chan->rx_circbuf->fill_pos = 0;
mpc555_chan->rx_circbuf->read_pos = 0;
// Create the Tx interrupt, do not enable it yet
cyg_drv_interrupt_create(mpc555_chan->tx_interrupt_num,
mpc555_chan->tx_interrupt_priority,
(cyg_addrword_t)chan,//Data item passed to isr
mpc555_serial_tx_ISR,
mpc555_serial_tx_DSR,
&mpc555_chan->tx_interrupt_handle,
&mpc555_chan->tx_interrupt);
cyg_drv_interrupt_attach(mpc555_chan->tx_interrupt_handle);
// Create the Rx interrupt, this can be safely unmasked now
cyg_drv_interrupt_create(mpc555_chan->rx_interrupt_num,
mpc555_chan->rx_interrupt_priority,
(cyg_addrword_t)chan,
mpc555_serial_rx_ISR,
mpc555_serial_rx_DSR,
&mpc555_chan->rx_interrupt_handle,
&mpc555_chan->rx_interrupt);
cyg_drv_interrupt_attach(mpc555_chan->rx_interrupt_handle);
cyg_drv_interrupt_unmask(mpc555_chan->rx_interrupt_num);
}
#ifdef CYGDAT_IO_SERIAL_POWERPC_MPC555_SERIAL_A_USE_HWARE_QUEUE
else {// Use HW queue
// Create the Tx interrupt, do not enable it yet
cyg_drv_interrupt_create(mpc555_chan->tx_interrupt_queue_top_empty_num,
mpc555_chan->tx_interrupt_queue_top_empty_priority,
(cyg_addrword_t)chan,//Data item passed to isr
mpc555_serial_tx_queue_top_ISR,
mpc555_serial_tx_queue_DSR,
&mpc555_chan->tx_queue_top_interrupt_handle,
&mpc555_chan->tx_queue_top_interrupt);
cyg_drv_interrupt_attach(mpc555_chan->tx_queue_top_interrupt_handle);
cyg_drv_interrupt_create(mpc555_chan->tx_interrupt_queue_bot_empty_num,
mpc555_chan->tx_interrupt_queue_bot_empty_priority,
(cyg_addrword_t)chan,//Data passed to isr
mpc555_serial_tx_queue_bot_ISR,
mpc555_serial_tx_queue_DSR,
&mpc555_chan->tx_queue_bot_interrupt_handle,
&mpc555_chan->tx_queue_bot_interrupt);
cyg_drv_interrupt_attach(mpc555_chan->tx_queue_bot_interrupt_handle);
// Rx queue interrupts
cyg_drv_interrupt_create(mpc555_chan->rx_interrupt_queue_top_full_num,
mpc555_chan->rx_interrupt_queue_top_full_priority,
(cyg_addrword_t)chan,//Data item passed to isr
mpc555_serial_rx_queue_top_ISR,
mpc555_serial_rx_queue_DSR,
&mpc555_chan->rx_queue_top_interrupt_handle,
&mpc555_chan->rx_queue_top_interrupt);
cyg_drv_interrupt_attach(mpc555_chan->rx_queue_top_interrupt_handle);
cyg_drv_interrupt_create(mpc555_chan->rx_interrupt_queue_bot_full_num,
mpc555_chan->rx_interrupt_queue_bot_full_priority,
(cyg_addrword_t)chan,//Data item passed to isr
mpc555_serial_rx_queue_bot_ISR,
mpc555_serial_rx_queue_DSR,
&mpc555_chan->rx_queue_bot_interrupt_handle,
&mpc555_chan->rx_queue_bot_interrupt);
cyg_drv_interrupt_attach(mpc555_chan->rx_queue_bot_interrupt_handle);
cyg_drv_interrupt_create(mpc555_chan->rx_interrupt_idle_line_num,
mpc555_chan->rx_interrupt_idle_line_priority,
(cyg_addrword_t)chan,//Data item passed to isr
mpc555_serial_rx_idle_line_ISR,
mpc555_serial_rx_queue_DSR,
&mpc555_chan->rx_idle_interrupt_handle,
&mpc555_chan->rx_idle_interrupt);
cyg_drv_interrupt_attach(mpc555_chan->rx_idle_interrupt_handle);
}
#endif // use queue
}
return true;
}
//----------------------------------------------------------------------------
// This routine is called when the device is "looked" up (i.e. attached)
//----------------------------------------------------------------------------
static Cyg_ErrNo mpc555_serial_lookup(struct cyg_devtab_entry ** tab,
struct cyg_devtab_entry * sub_tab,
const char * name)
{
serial_channel * chan = (serial_channel *)(*tab)->priv;
//Really only required for interrupt driven devices
(chan->callbacks->serial_init)(chan);
return ENOERR;
}
//----------------------------------------------------------------------------
// Send a character to the device output buffer.
// Return 'true' if character is sent to device
//----------------------------------------------------------------------------
static bool mpc555_serial_putc(serial_channel * chan, unsigned char c){
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
cyg_addrword_t port = mpc555_chan->base;
cyg_uint16 scsr;
cyg_uint16 scdr;
HAL_READ_UINT16(port + MPC555_SERIAL_SCxSR, scsr);
if(scsr & MPC555_SERIAL_SCxSR_TDRE){
// Ok, we have space, write the character and return success
scdr = (cyg_uint16)c;
HAL_WRITE_UINT16(port + MPC555_SERIAL_SCxDR, scdr);
return true;
}
else
// We cannot write to the transmitter, return failure
return false;
}
//----------------------------------------------------------------------------
// Fetch a character from the device input buffer, waiting if necessary
//----------------------------------------------------------------------------
static unsigned char mpc555_serial_getc(serial_channel * chan){
unsigned char c;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
cyg_addrword_t port = mpc555_chan->base;
cyg_uint16 scsr;
cyg_uint16 scdr;
do {
HAL_READ_UINT16(port + MPC555_SERIAL_SCxSR, scsr);
} while(!(scsr & MPC555_SERIAL_SCxSR_RDRF));
// Ok, data is received, read it out and return
HAL_READ_UINT16(port + MPC555_SERIAL_SCxDR, scdr);
c = (unsigned char)scdr;
return c;
}
//----------------------------------------------------------------------------
// Set up the device characteristics; baud rate, etc.
//----------------------------------------------------------------------------
static bool mpc555_serial_set_config(serial_channel * chan, cyg_uint32 key,
const void *xbuf, cyg_uint32 * len)
{
switch(key){
case CYG_IO_SET_CONFIG_SERIAL_INFO:{
cyg_serial_info_t *config = (cyg_serial_info_t *)xbuf;
if(*len < sizeof(cyg_serial_info_t)){
return -EINVAL;
}
*len = sizeof(cyg_serial_info_t);
if(true != mpc555_serial_config_port(chan, config, false))
return -EINVAL;
}
break;
default:
return -EINVAL;
}
return ENOERR;
}
//------------------------------------------------------------------------------
// Enable the transmitter on the device
//------------------------------------------------------------------------------
static void mpc555_serial_start_xmit(serial_channel * chan)
{
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
#ifdef CYGDAT_IO_SERIAL_POWERPC_MPC555_SERIAL_A_USE_HWARE_QUEUE
cyg_addrword_t port = mpc555_chan->base;
if(mpc555_chan->use_queue){
cyg_uint16 qscicr;
cyg_uint16 qscisr;
cyg_uint16 scsr;
int chars_avail;
unsigned char* chars;
int block_index = 0;
cyg_addrword_t i;
cyg_uint16 queue_transfer;
if(!(mpc555_chan->tx_interrupt_enable) &&
(chan->callbacks->data_xmt_req)(chan, 32, &chars_avail, &chars)
== CYG_XMT_OK){
queue_transfer = (chars_avail > 16) ? 16 : chars_avail;
HAL_READ_UINT16( CYGARC_REG_IMM_QSCI1CR, qscicr);
// Write QTSZ for first pass through the queue
qscicr &= ~(CYGARC_REG_IMM_QSCI1CR_QTSZ);
qscicr |= (CYGARC_REG_IMM_QSCI1CR_QTSZ & (queue_transfer - 1));
HAL_WRITE_UINT16( CYGARC_REG_IMM_QSCI1CR, qscicr);
// Read SC1SR to clear TC bit when followed by a write of sctq
HAL_READ_UINT16(port + MPC555_SERIAL_SCxSR, scsr);
for(i=0; i < queue_transfer; i++){
HAL_WRITE_UINT16(CYGARC_REG_IMM_SCTQ + (i * 2), chars[block_index]);
++block_index;
}
chan->callbacks->data_xmt_done(chan, queue_transfer);
// clear QTHE and QBHE
HAL_READ_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
qscisr &= ~(CYGARC_REG_IMM_QSCI1SR_QTHE);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
if(queue_transfer > 8){
qscisr &= ~(CYGARC_REG_IMM_QSCI1SR_QBHE);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
}
mpc555_chan->tx_interrupt_enable = true;
cyg_drv_interrupt_unmask(mpc555_chan->tx_interrupt_queue_top_empty_num);
if(queue_transfer > 8){
cyg_drv_interrupt_unmask(mpc555_chan->tx_interrupt_queue_bot_empty_num);
}
HAL_READ_UINT16( CYGARC_REG_IMM_QSCI1CR, qscicr);
qscicr |= ((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QTE);
HAL_WRITE_UINT16( CYGARC_REG_IMM_QSCI1CR, qscicr);
}
}
else { // no queue
mpc555_chan->tx_interrupt_enable = true;
cyg_drv_interrupt_unmask(mpc555_chan->tx_interrupt_num);
// No need to call xmt_char, this will generate an interrupt immediately.
}
#else // No queue
mpc555_chan->tx_interrupt_enable = true;
cyg_drv_interrupt_unmask(mpc555_chan->tx_interrupt_num);
// No need to call xmt_char, this will generate an interrupt immediately.
#endif
}
//----------------------------------------------------------------------------
// Disable the transmitter on the device
//----------------------------------------------------------------------------
static void mpc555_serial_stop_xmit(serial_channel * chan){
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
if(!mpc555_chan->use_queue){
cyg_drv_dsr_lock();
mpc555_chan->tx_interrupt_enable = false;
cyg_drv_interrupt_mask(mpc555_chan->tx_interrupt_num);
cyg_drv_dsr_unlock();
}
}
//----------------------------------------------------------------------------
// The low level transmit interrupt handler
//----------------------------------------------------------------------------
static cyg_uint32 mpc555_serial_tx_ISR(cyg_vector_t vector,
cyg_addrword_t data){
serial_channel * chan = (serial_channel *)data;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
cyg_drv_interrupt_mask(mpc555_chan->tx_interrupt_num);
cyg_drv_interrupt_acknowledge(mpc555_chan->tx_interrupt_num);
return CYG_ISR_CALL_DSR; // cause the DSR to run
}
//----------------------------------------------------------------------------
// The low level receive interrupt handler
//----------------------------------------------------------------------------
static cyg_uint32 mpc555_serial_rx_ISR(cyg_vector_t vector,
cyg_addrword_t data){
serial_channel * chan = (serial_channel *)data;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
cyg_drv_interrupt_mask(mpc555_chan->rx_interrupt_num);
cyg_drv_interrupt_acknowledge(mpc555_chan->rx_interrupt_num);
cyg_addrword_t port = mpc555_chan->base;
cyg_uint16 scdr;
cyg_uint16 scsr;
HAL_READ_UINT16(port + MPC555_SERIAL_SCxSR, scsr);
// Always read out the received character, in order to clear receiver flags
HAL_READ_UINT16(port + MPC555_SERIAL_SCxDR, scdr);
mpc555_chan->rx_circbuf->scsr[mpc555_chan->rx_circbuf->fill_pos] = scsr;
mpc555_chan->rx_circbuf->buf[mpc555_chan->rx_circbuf->fill_pos] = (cyg_uint8)scdr;
if(mpc555_chan->rx_circbuf->fill_pos < MPC555_SCI_RX_BUFF_SIZE - 1){
mpc555_chan->rx_circbuf->fill_pos = mpc555_chan->rx_circbuf->fill_pos + 1;
}
else {
mpc555_chan->rx_circbuf->fill_pos = 0;
}
cyg_drv_interrupt_unmask(mpc555_chan->rx_interrupt_num);
return CYG_ISR_CALL_DSR; // cause the DSR to run
}
#ifdef CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_A
//----------------------------------------------------------------------------
// The low level queued receive interrupt handlers
//----------------------------------------------------------------------------
static cyg_uint32 mpc555_serial_rx_queue_top_ISR(cyg_vector_t vector,
cyg_addrword_t data){
serial_channel * chan = (serial_channel *)data;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
cyg_drv_interrupt_mask(mpc555_chan->rx_interrupt_queue_top_full_num);
cyg_drv_interrupt_acknowledge(mpc555_chan->rx_interrupt_queue_top_full_num);
return CYG_ISR_CALL_DSR; // cause the DSR to run
}
static cyg_uint32 mpc555_serial_rx_queue_bot_ISR(cyg_vector_t vector,
cyg_addrword_t data){
serial_channel* chan = (serial_channel *)data;
mpc555_serial_info* mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
cyg_drv_interrupt_mask(mpc555_chan->rx_interrupt_queue_bot_full_num);
cyg_drv_interrupt_acknowledge(mpc555_chan->rx_interrupt_queue_bot_full_num);
return CYG_ISR_CALL_DSR; // cause the DSR to run
}
// This is used to flush the queue when the line falls idle
static cyg_uint32 mpc555_serial_rx_idle_line_ISR(cyg_vector_t vector,
cyg_addrword_t data){
serial_channel* chan = (serial_channel *)data;
mpc555_serial_info* mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
cyg_drv_interrupt_mask(mpc555_chan->rx_interrupt_idle_line_num);
cyg_drv_interrupt_acknowledge(mpc555_chan->rx_interrupt_idle_line_num);
return CYG_ISR_CALL_DSR; // cause the DSR to run
}
//----------------------------------------------------------------------------
// The low level queued transmit interrupt handlers
//----------------------------------------------------------------------------
static cyg_uint32 mpc555_serial_tx_queue_top_ISR(cyg_vector_t vector,
cyg_addrword_t data){
serial_channel * chan = (serial_channel *)data;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
cyg_drv_interrupt_mask(mpc555_chan->tx_interrupt_queue_top_empty_num);
cyg_drv_interrupt_acknowledge(mpc555_chan->tx_interrupt_queue_top_empty_num);
return CYG_ISR_CALL_DSR; // cause the DSR to run
}
static cyg_uint32 mpc555_serial_tx_queue_bot_ISR(cyg_vector_t vector,
cyg_addrword_t data){
serial_channel * chan = (serial_channel *)data;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
cyg_drv_interrupt_mask(mpc555_chan->tx_interrupt_queue_bot_empty_num);
cyg_drv_interrupt_acknowledge(mpc555_chan->tx_interrupt_queue_bot_empty_num);
return CYG_ISR_CALL_DSR; // cause the DSR to run
}
#endif // SERIAL_A
//----------------------------------------------------------------------------
// The high level transmit interrupt handler
//----------------------------------------------------------------------------
static void mpc555_serial_tx_DSR(cyg_vector_t vector, cyg_ucount32 count,
cyg_addrword_t data){
serial_channel * chan = (serial_channel *)data;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
(chan->callbacks->xmt_char)(chan);
if(mpc555_chan->tx_interrupt_enable)
cyg_drv_interrupt_unmask(mpc555_chan->tx_interrupt_num);
}
//----------------------------------------------------------------------------
// The high level receive interrupt handler
//----------------------------------------------------------------------------
#define MPC555_SERIAL_SCxSR_ERRORS (MPC555_SERIAL_SCxSR_OR | \
MPC555_SERIAL_SCxSR_NF | \
MPC555_SERIAL_SCxSR_FE | \
MPC555_SERIAL_SCxSR_PF)
static void mpc555_serial_rx_DSR(cyg_vector_t vector, cyg_ucount32 count,
cyg_addrword_t data){
serial_channel * chan = (serial_channel *)data;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
// cyg_addrword_t port = mpc555_chan->base;
// cyg_uint16 scdr;
cyg_uint16 scsr;
#ifdef CYGOPT_IO_SERIAL_SUPPORT_LINE_STATUS
cyg_serial_line_status_t stat;
#endif
int i = mpc555_chan->rx_circbuf->read_pos;
while (i < mpc555_chan->rx_circbuf->fill_pos){
scsr = mpc555_chan->rx_circbuf->scsr[i];
if(scsr & (cyg_uint16)MPC555_SERIAL_SCxSR_ERRORS){
#ifdef CYGOPT_IO_SERIAL_SUPPORT_LINE_STATUS
if(scsr & MPC555_SERIAL_SCxSR_OR){
stat.which = CYGNUM_SERIAL_STATUS_OVERRUNERR;
(chan->callbacks->indicate_status)(chan, &stat);
// The current byte is still valid when OR is set
(chan->callbacks->rcv_char)(chan, mpc555_chan->rx_circbuf->buf[i]);
}
else { // OR is never set with any other error bits
if(scsr & MPC555_SERIAL_SCxSR_NF){
stat.which = CYGNUM_SERIAL_STATUS_NOISEERR;
(chan->callbacks->indicate_status)(chan, &stat);
}
if(scsr & MPC555_SERIAL_SCxSR_FE){
stat.which = CYGNUM_SERIAL_STATUS_FRAMEERR;
(chan->callbacks->indicate_status)(chan, &stat);
}
if(scsr & MPC555_SERIAL_SCxSR_PF){
stat.which = CYGNUM_SERIAL_STATUS_PARITYERR;
(chan->callbacks->indicate_status)(chan, &stat);
}
}
#endif
}
else {
(chan->callbacks->rcv_char)(chan, mpc555_chan->rx_circbuf->buf[i]);
}
++i;
}
cyg_drv_isr_lock();
mpc555_chan->rx_circbuf->fill_pos = 0;
mpc555_chan->rx_circbuf->read_pos = 0;
cyg_drv_isr_unlock();
}
#ifdef CYGPKG_IO_SERIAL_POWERPC_MPC555_SERIAL_A
//----------------------------------------------------------------------------
// The high level queued transmit interrupt handler
//----------------------------------------------------------------------------
static void mpc555_serial_tx_queue_DSR(cyg_vector_t vector, cyg_ucount32 count,
cyg_addrword_t data){
serial_channel * chan = (serial_channel *)data;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
bool QTHE = false;
bool QBHE = false;
cyg_uint16 qscisr;
cyg_uint16 qscicr;
HAL_READ_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
QTHE = (qscisr & CYGARC_REG_IMM_QSCI1SR_QTHE) ? true : false;
QBHE = (qscisr & CYGARC_REG_IMM_QSCI1SR_QBHE) ? true : false;
CYG_ASSERT(QTHE || QBHE,"In tx queue DSR for no reason");
HAL_READ_UINT16(CYGARC_REG_IMM_QSCI1CR, qscicr);
int chars_avail;
unsigned char* chars;
int block_index = 0;
cyg_addrword_t i;
cyg_uint16 queue_transfer;
xmt_req_reply_t result = (chan->callbacks->data_xmt_req)(chan, 24, &chars_avail, &chars);
if(CYG_XMT_OK == result){
queue_transfer = (chars_avail > 8) ? 8 : chars_avail;
if(QTHE){
for(i=0; i < queue_transfer; i++){
HAL_WRITE_UINT16(CYGARC_REG_IMM_SCTQ + (i * 2), chars[block_index]);
++block_index;
}
chan->callbacks->data_xmt_done(chan, queue_transfer);
// Clear QTHE
qscisr &= ~(CYGARC_REG_IMM_QSCI1SR_QTHE);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
// Re-enable wrap QTWE
HAL_READ_UINT16(CYGARC_REG_IMM_QSCI1CR, qscicr);
qscicr |= ((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QTWE);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1CR, qscicr);
HAL_READ_UINT16(CYGARC_REG_IMM_QSCI1CR, qscicr);
// load QTSZ with how many chars *after* the next wrap
cyg_uint16 next_time = (chars_avail) > 16 ? 15 : chars_avail -1;
qscicr &= ~(CYGARC_REG_IMM_QSCI1CR_QTSZ);
qscicr |= (CYGARC_REG_IMM_QSCI1CR_QTSZ & next_time);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1CR, qscicr);
cyg_drv_interrupt_unmask(mpc555_chan->tx_interrupt_queue_top_empty_num);
}
else if(QBHE){
for(i=8; i < queue_transfer + 8; i++){
HAL_WRITE_UINT16(CYGARC_REG_IMM_SCTQ + (i * 2), chars[block_index]);
++block_index;
}
chan->callbacks->data_xmt_done(chan, queue_transfer);
// Clear QBHE
qscisr &= ~(CYGARC_REG_IMM_QSCI1SR_QBHE);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
cyg_drv_interrupt_unmask(mpc555_chan->tx_interrupt_queue_bot_empty_num);
}
}
else if(CYG_XMT_EMPTY== result){
// No more data
cyg_drv_interrupt_mask(mpc555_chan->tx_interrupt_queue_top_empty_num);
cyg_drv_interrupt_mask(mpc555_chan->tx_interrupt_queue_bot_empty_num);
mpc555_chan->tx_interrupt_enable = false;
// Clear QTHE
HAL_READ_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
qscisr &= ~(CYGARC_REG_IMM_QSCI1SR_QTHE);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
}
}
//----------------------------------------------------------------------------
// The high level queued receive interrupt handler
//----------------------------------------------------------------------------
static void mpc555_serial_rx_queue_DSR(cyg_vector_t vector,
cyg_ucount32 count, cyg_addrword_t data){
serial_channel * chan = (serial_channel *)data;
mpc555_serial_info * mpc555_chan = (mpc555_serial_info *)chan->dev_priv;
cyg_addrword_t port = mpc555_chan->base;
cyg_uint16 scrq;
cyg_uint16 qscisr;
cyg_uint16 scsr;
cyg_uint16 scdr;
bool QTHF = false;
bool QBHF = false;
bool idle = false;
// Read status reg before reading any data otherwise NE flag will be lost
HAL_READ_UINT16(port + MPC555_SERIAL_SCxSR, scsr);
HAL_READ_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
QTHF = (qscisr & CYGARC_REG_IMM_QSCI1SR_QTHF) ? true : false;
QBHF = (qscisr & CYGARC_REG_IMM_QSCI1SR_QBHF) ? true : false;
idle = (scsr & CYGARC_REG_IMM_SCxSR_IDLE)? true : false;
// The queue pointer is the next place to be filled by incomming data
cyg_uint16 queue_pointer = (qscisr & CYGARC_REG_IMM_QSCI1SR_QRPNT) >> 4;
int start;
int space_req = 0;
// Idle needs to be handled first as the IDLE bit will be cleared by a read of
// scsr followed by a read of scrq[0:16]
if(queue_pointer > mpc555_chan->rx_last_queue_pointer){
start = mpc555_chan->rx_last_queue_pointer;
space_req = mpc555_serial_read_queue(chan, start, queue_pointer - 1);
}
else {// Its wrapped around
if(mpc555_chan->rx_last_queue_pointer > queue_pointer){
space_req = mpc555_serial_read_queue(chan, mpc555_chan->rx_last_queue_pointer,15);
if(queue_pointer != 0){
mpc555_serial_read_queue(chan, 0,queue_pointer -1);
}
}
else // No new data to read, do nothing here
{
}
}
mpc555_chan->rx_last_queue_pointer = queue_pointer;
if(CYGARC_REG_IMM_QSCI1SR_QOR & qscisr){
// Need to re-enable the queue
cyg_uint16 qscicr;
HAL_READ_UINT16( CYGARC_REG_IMM_QSCI1CR, qscicr);
qscicr |= ((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QRE);
HAL_WRITE_UINT16( CYGARC_REG_IMM_QSCI1CR, qscicr);
// Queue has overrun but data might not have been lost yet
if(scsr & MPC555_SERIAL_SCxSR_OR){
#ifdef CYGOPT_IO_SERIAL_SUPPORT_LINE_STATUS
cyg_serial_line_status_t stat;
stat.which = CYGNUM_SERIAL_STATUS_OVERRUNERR;
(chan->callbacks->indicate_status)(chan, &stat);
#endif
}
}
if(scsr & (cyg_uint16)MPC555_SERIAL_SCxSR_ERRORS){
// Special case for queue overrun handled above.
// Only data without FE or PF is allowed into the queue.
// Data with NE is allowed into the queue.
// If FE or PF have occured then the queue is disabled
// until they are cleared (by reading scsr then scdr).
#ifdef CYGOPT_IO_SERIAL_SUPPORT_LINE_STATUS
cyg_serial_line_status_t stat;
if(scsr & MPC555_SERIAL_SCxSR_NF){
// Note if there is more than one frame in the queue
// it is not possible to tell which frame
// in the queue caused the noise error.
// The error has already been cleared by reading
// srsr then scrq[n], so no action is required here.
stat.which = CYGNUM_SERIAL_STATUS_NOISEERR;
(chan->callbacks->indicate_status)(chan, &stat);
}
#endif
if(scsr & (MPC555_SERIAL_SCxSR_FE | MPC555_SERIAL_SCxSR_PF)){
// This action needs to be taken clear the status bits so that
// the queue can be re-enabled.
HAL_READ_UINT16(port + MPC555_SERIAL_SCxDR, scdr);
// Need to re-enable the queue
cyg_uint16 qscicr;
HAL_READ_UINT16(CYGARC_REG_IMM_QSCI1CR, qscicr);
qscicr |= ((cyg_uint16)CYGARC_REG_IMM_QSCI1CR_QRE);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1CR, qscicr);
#ifdef CYGOPT_IO_SERIAL_SUPPORT_LINE_STATUS
if(scsr & MPC555_SERIAL_SCxSR_FE){
stat.which = CYGNUM_SERIAL_STATUS_FRAMEERR;
(chan->callbacks->indicate_status)(chan, &stat);
}
if(scsr & MPC555_SERIAL_SCxSR_PF){
stat.which = CYGNUM_SERIAL_STATUS_PARITYERR;
(chan->callbacks->indicate_status)(chan, &stat);
}
#endif
}
}
if(QTHF){
qscisr &= ~((cyg_uint16)CYGARC_REG_IMM_QSCI1SR_QTHF);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
//cyg_drv_interrupt_unmask(mpc555_chan->rx_interrupt_queue_top_full_num);
}
if(QBHF){
qscisr &= ~((cyg_uint16)CYGARC_REG_IMM_QSCI1SR_QBHF);
HAL_WRITE_UINT16(CYGARC_REG_IMM_QSCI1SR, qscisr);
//cyg_drv_interrupt_unmask(mpc555_chan->rx_interrupt_queue_bot_full_num);
}
if(idle){
if(idle && !space_req){
// The IDLE flag can be set sometimes when RE is set
// so a read of scrq is needed to clear it.
// If this occurs there should be no new data yet otherwise the
// condition is impossible to detect
HAL_READ_UINT16(CYGARC_REG_IMM_SCRQ, scrq);
}
HAL_READ_UINT16(CYGARC_REG_IMM_SCRQ, scrq);
//cyg_drv_interrupt_unmask(mpc555_chan->rx_interrupt_idle_line_num);
}
// A bit lasy, but we don't know or care what the original ISR source
// was so to cover all bases re-enble them all
cyg_drv_interrupt_unmask(mpc555_chan->rx_interrupt_queue_top_full_num);
cyg_drv_interrupt_unmask(mpc555_chan->rx_interrupt_queue_bot_full_num);
cyg_drv_interrupt_unmask(mpc555_chan->rx_interrupt_idle_line_num);
}
static int mpc555_serial_read_queue(serial_channel* chan, int start, int end)
{
int block_index = 0;
cyg_uint16 scrq;
cyg_addrword_t i;
unsigned char* space;
int space_avail = 0;
int space_req = end - start + 1;
if((space_req > 0) &&
((chan->callbacks->data_rcv_req)
(chan, space_req, &space_avail, &space) == CYG_RCV_OK)) {
CYG_ASSERT((start >= 0) && (start < 16),"rx queue read start point out of range");
CYG_ASSERT(start <= end,"rx queue read start and end points reversed");
for(i=start ;i < (start + space_avail); i++){
CYG_ASSERT((i >= 0) && (i < 16),"rx queue read out of range");
HAL_READ_UINT16(CYGARC_REG_IMM_SCRQ + (i * 2), scrq);
space[block_index] = scrq;
++block_index;
}
(chan->callbacks->data_rcv_done)(chan,space_avail);
#ifdef CYGOPT_IO_SERIAL_SUPPORT_LINE_STATUS
// If there's not enough room data will be lost.
// There's no point calling rcv_char because the reader is blocked by this DSR.
if(space_avail < space_req){
cyg_serial_line_status_t stat;
stat.which = CYGNUM_SERIAL_STATUS_OVERRUNERR;
(chan->callbacks->indicate_status)(chan, &stat);
}
#endif
}
return space_req;
}
#endif // SERIAL_A
#endif // CYGPKG_IO_SERIAL_POWERPC_MPC555
// EOF mpc555_serial_with_ints.c
| reille/proj_ecos | src/ecos/packages/devs/serial/powerpc/mpc555/current/src/mpc555_serial_with_ints.c | C | gpl-2.0 | 54,302 |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014- QLogic Corporation.
* All rights reserved
* www.qlogic.com
*
* Linux driver for QLogic BR-series Fibre Channel Host Bus Adapter.
*/
/*
* rport.c Remote port implementation.
*/
#include "bfad_drv.h"
#include "bfad_im.h"
#include "bfa_fcs.h"
#include "bfa_fcbuild.h"
BFA_TRC_FILE(FCS, RPORT);
static u32
bfa_fcs_rport_del_timeout = BFA_FCS_RPORT_DEF_DEL_TIMEOUT * 1000;
/* In millisecs */
/*
* bfa_fcs_rport_max_logins is max count of bfa_fcs_rports
* whereas DEF_CFG_NUM_RPORTS is max count of bfa_rports
*/
static u32 bfa_fcs_rport_max_logins = BFA_FCS_MAX_RPORT_LOGINS;
/*
* forward declarations
*/
static struct bfa_fcs_rport_s *bfa_fcs_rport_alloc(
struct bfa_fcs_lport_s *port, wwn_t pwwn, u32 rpid);
static void bfa_fcs_rport_free(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_hal_online(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_fcs_online_action(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_hal_online_action(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_fcs_offline_action(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_hal_offline_action(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_update(struct bfa_fcs_rport_s *rport,
struct fc_logi_s *plogi);
static void bfa_fcs_rport_timeout(void *arg);
static void bfa_fcs_rport_send_plogi(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_send_plogiacc(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_plogi_response(void *fcsarg,
struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_send_adisc(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_adisc_response(void *fcsarg,
struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_send_nsdisc(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_gidpn_response(void *fcsarg,
struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_gpnid_response(void *fcsarg,
struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_send_logo(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_send_logo_acc(void *rport_cbarg);
static void bfa_fcs_rport_process_prli(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len);
static void bfa_fcs_rport_send_ls_rjt(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u8 reason_code,
u8 reason_code_expl);
static void bfa_fcs_rport_process_adisc(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len);
static void bfa_fcs_rport_send_prlo_acc(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_hal_offline(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_sm_uninit(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogi_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogiacc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogi_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogi(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_fcs_online(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hal_online(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_online(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsquery_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsquery(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_adisc_online_sending(
struct bfa_fcs_rport_s *rport, enum rport_event event);
static void bfa_fcs_rport_sm_adisc_online(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_adisc_offline_sending(struct bfa_fcs_rport_s
*rport, enum rport_event event);
static void bfa_fcs_rport_sm_adisc_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hcb_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hcb_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hcb_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_logo_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_sent(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_sent(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_off_delete(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_delete_pending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static struct bfa_sm_table_s rport_sm_table[] = {
{BFA_SM(bfa_fcs_rport_sm_uninit), BFA_RPORT_UNINIT},
{BFA_SM(bfa_fcs_rport_sm_plogi_sending), BFA_RPORT_PLOGI},
{BFA_SM(bfa_fcs_rport_sm_plogiacc_sending), BFA_RPORT_ONLINE},
{BFA_SM(bfa_fcs_rport_sm_plogi_retry), BFA_RPORT_PLOGI_RETRY},
{BFA_SM(bfa_fcs_rport_sm_plogi), BFA_RPORT_PLOGI},
{BFA_SM(bfa_fcs_rport_sm_fc4_fcs_online), BFA_RPORT_ONLINE},
{BFA_SM(bfa_fcs_rport_sm_hal_online), BFA_RPORT_ONLINE},
{BFA_SM(bfa_fcs_rport_sm_online), BFA_RPORT_ONLINE},
{BFA_SM(bfa_fcs_rport_sm_nsquery_sending), BFA_RPORT_NSQUERY},
{BFA_SM(bfa_fcs_rport_sm_nsquery), BFA_RPORT_NSQUERY},
{BFA_SM(bfa_fcs_rport_sm_adisc_online_sending), BFA_RPORT_ADISC},
{BFA_SM(bfa_fcs_rport_sm_adisc_online), BFA_RPORT_ADISC},
{BFA_SM(bfa_fcs_rport_sm_adisc_offline_sending), BFA_RPORT_ADISC},
{BFA_SM(bfa_fcs_rport_sm_adisc_offline), BFA_RPORT_ADISC},
{BFA_SM(bfa_fcs_rport_sm_fc4_logorcv), BFA_RPORT_LOGORCV},
{BFA_SM(bfa_fcs_rport_sm_fc4_logosend), BFA_RPORT_LOGO},
{BFA_SM(bfa_fcs_rport_sm_fc4_offline), BFA_RPORT_OFFLINE},
{BFA_SM(bfa_fcs_rport_sm_hcb_offline), BFA_RPORT_OFFLINE},
{BFA_SM(bfa_fcs_rport_sm_hcb_logorcv), BFA_RPORT_LOGORCV},
{BFA_SM(bfa_fcs_rport_sm_hcb_logosend), BFA_RPORT_LOGO},
{BFA_SM(bfa_fcs_rport_sm_logo_sending), BFA_RPORT_LOGO},
{BFA_SM(bfa_fcs_rport_sm_offline), BFA_RPORT_OFFLINE},
{BFA_SM(bfa_fcs_rport_sm_nsdisc_sending), BFA_RPORT_NSDISC},
{BFA_SM(bfa_fcs_rport_sm_nsdisc_retry), BFA_RPORT_NSDISC},
{BFA_SM(bfa_fcs_rport_sm_nsdisc_sent), BFA_RPORT_NSDISC},
};
/*
* Beginning state.
*/
static void
bfa_fcs_rport_sm_uninit(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_PLOGI_SEND:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
rport->plogi_retries = 0;
bfa_fcs_rport_send_plogi(rport, NULL);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcs_rport_hal_online(rport);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_ADDRESS_DISC:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* PLOGI is being sent.
*/
static void
bfa_fcs_rport_sm_plogi_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_SCN_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_FAB_SCN:
/* query the NS */
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
WARN_ON(!(bfa_fcport_get_topology(rport->port->fcs->bfa) !=
BFA_PORT_TOPOLOGY_LOOP));
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* PLOGI is being sent.
*/
static void
bfa_fcs_rport_sm_plogiacc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_fcs_online);
bfa_fcs_rport_fcs_online_action(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_PLOGI_COMP:
case RPSM_EVENT_FAB_SCN:
/*
* Ignore, SCN is possibly online notification.
*/
break;
case RPSM_EVENT_SCN_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_HCB_OFFLINE:
/*
* Ignore BFA callback, on a PLOGI receive we call bfa offline.
*/
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* PLOGI is sent.
*/
static void
bfa_fcs_rport_sm_plogi_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_TIMEOUT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
bfa_fcs_rport_send_plogi(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_LOGO_RCVD:
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_SCN_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_stop(&rport->timer);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_FAB_SCN:
bfa_timer_stop(&rport->timer);
WARN_ON(!(bfa_fcport_get_topology(rport->port->fcs->bfa) !=
BFA_PORT_TOPOLOGY_LOOP));
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_stop(&rport->timer);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_fcs_online);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_fcs_online_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* PLOGI is sent.
*/
static void
bfa_fcs_rport_sm_plogi(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_fcs_online);
rport->plogi_retries = 0;
bfa_fcs_rport_fcs_online_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_fcs_rport_send_logo_acc(rport);
/* fall through */
case RPSM_EVENT_PRLO_RCVD:
if (rport->prlo == BFA_TRUE)
bfa_fcs_rport_send_prlo_acc(rport);
bfa_fcxp_discard(rport->fcxp);
/* fall through */
case RPSM_EVENT_FAILED:
if (rport->plogi_retries < BFA_FCS_RPORT_MAX_RETRIES) {
rport->plogi_retries++;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_retry);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
BFA_FCS_RETRY_TIMEOUT);
} else {
bfa_stats(rport->port, rport_del_max_plogi_retry);
rport->old_pid = rport->pid;
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
}
break;
case RPSM_EVENT_SCN_ONLINE:
break;
case RPSM_EVENT_SCN_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PLOGI_RETRY:
rport->plogi_retries = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_retry);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
(FC_RA_TOV * 1000));
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_FAB_SCN:
bfa_fcxp_discard(rport->fcxp);
WARN_ON(!(bfa_fcport_get_topology(rport->port->fcs->bfa) !=
BFA_PORT_TOPOLOGY_LOOP));
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_fcs_online);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_fcs_online_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* PLOGI is done. Await bfa_fcs_itnim to ascertain the scsi function
*/
static void
bfa_fcs_rport_sm_fc4_fcs_online(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_FCS_ONLINE:
if (rport->scsi_function == BFA_RPORT_INITIATOR) {
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_rport_online(rport);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_online);
break;
}
if (!rport->bfa_rport)
rport->bfa_rport =
bfa_rport_create(rport->fcs->bfa, rport);
if (rport->bfa_rport) {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcs_rport_hal_online(rport);
} else {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcs_rport_fcs_offline_action(rport);
}
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
rport->plogi_pending = BFA_TRUE;
bfa_fcs_rport_fcs_offline_action(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_FAB_SCN:
case RPSM_EVENT_SCN_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_fcs_offline_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcs_rport_fcs_offline_action(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcs_rport_fcs_offline_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
break;
}
}
/*
* PLOGI is complete. Awaiting BFA rport online callback. FC-4s
* are offline.
*/
static void
bfa_fcs_rport_sm_hal_online(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_ONLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_online);
bfa_fcs_rport_hal_online_action(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
break;
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_LOGO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcs_rport_fcs_offline_action(rport);
break;
case RPSM_EVENT_FAB_SCN:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_SCN_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_fcs_offline_action(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
rport->plogi_pending = BFA_TRUE;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_fcs_offline_action(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcs_rport_fcs_offline_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is ONLINE. FC-4s active.
*/
static void
bfa_fcs_rport_sm_online(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FAB_SCN:
if (bfa_fcs_fabric_is_switched(rport->port->fabric)) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsquery_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
} else {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_adisc_online_sending);
bfa_fcs_rport_send_adisc(rport, NULL);
}
break;
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_SCN_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_SCN_ONLINE:
case RPSM_EVENT_PLOGI_COMP:
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* An SCN event is received in ONLINE state. NS query is being sent
* prior to ADISC authentication with rport. FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_nsquery_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsquery);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_FAB_SCN:
/*
* ignore SCN, wait for response to query itself
*/
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_hal_offline_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* An SCN event is received in ONLINE state. NS query is sent to rport.
* FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_nsquery(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_adisc_online_sending);
bfa_fcs_rport_send_adisc(rport, NULL);
break;
case RPSM_EVENT_FAILED:
rport->ns_retries++;
if (rport->ns_retries < BFA_FCS_RPORT_MAX_RETRIES) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsquery_sending);
bfa_fcs_rport_send_nsdisc(rport, NULL);
} else {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_hal_offline_action(rport);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_FAB_SCN:
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_hal_offline_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* An SCN event is received in ONLINE state. ADISC is being sent for
* authenticating with rport. FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_adisc_online_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_adisc_online);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_FAB_SCN:
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_hal_offline_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* An SCN event is received in ONLINE state. ADISC is to rport.
* FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_adisc_online(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_online);
break;
case RPSM_EVENT_PLOGI_RCVD:
/*
* Too complex to cleanup FC-4 & rport and then acc to PLOGI.
* At least go offline when a PLOGI is received.
*/
bfa_fcxp_discard(rport->fcxp);
/* fall through */
case RPSM_EVENT_FAILED:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_FAB_SCN:
/*
* already processing RSCN
*/
break;
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_hal_offline_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_hal_offline_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* ADISC is being sent for authenticating with rport
* Already did offline actions.
*/
static void
bfa_fcs_rport_sm_adisc_offline_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_adisc_offline);
break;
case RPSM_EVENT_DELETE:
case RPSM_EVENT_SCN_OFFLINE:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa,
&rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* ADISC to rport
* Already did offline actions
*/
static void
bfa_fcs_rport_sm_adisc_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcs_rport_hal_online(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_FAILED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_DELETE:
case RPSM_EVENT_SCN_OFFLINE:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport has sent LOGO. Awaiting FC-4 offline completion callback.
*/
static void
bfa_fcs_rport_sm_fc4_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logorcv);
bfa_fcs_rport_hal_offline(rport);
break;
case RPSM_EVENT_DELETE:
if (rport->pid && (rport->prlo == BFA_TRUE))
bfa_fcs_rport_send_prlo_acc(rport);
if (rport->pid && (rport->prlo == BFA_FALSE))
bfa_fcs_rport_send_logo_acc(rport);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_off_delete);
break;
case RPSM_EVENT_SCN_ONLINE:
case RPSM_EVENT_SCN_OFFLINE:
case RPSM_EVENT_HCB_ONLINE:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_ADDRESS_CHANGE:
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* LOGO needs to be sent to rport. Awaiting FC-4 offline completion
* callback.
*/
static void
bfa_fcs_rport_sm_fc4_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logosend);
bfa_fcs_rport_hal_offline(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_fcs_rport_send_logo_acc(rport);
/* fall through */
case RPSM_EVENT_PRLO_RCVD:
if (rport->prlo == BFA_TRUE)
bfa_fcs_rport_send_prlo_acc(rport);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_off_delete);
break;
case RPSM_EVENT_HCB_ONLINE:
case RPSM_EVENT_DELETE:
/* Rport is being deleted */
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is going offline. Awaiting FC-4 offline completion callback.
*/
static void
bfa_fcs_rport_sm_fc4_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_offline);
bfa_fcs_rport_hal_offline(rport);
break;
case RPSM_EVENT_SCN_ONLINE:
break;
case RPSM_EVENT_LOGO_RCVD:
/*
* Rport is going offline. Just ack the logo
*/
bfa_fcs_rport_send_logo_acc(rport);
break;
case RPSM_EVENT_PRLO_RCVD:
bfa_fcs_rport_send_prlo_acc(rport);
break;
case RPSM_EVENT_SCN_OFFLINE:
case RPSM_EVENT_HCB_ONLINE:
case RPSM_EVENT_FAB_SCN:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
/*
* rport is already going offline.
* SCN - ignore and wait till transitioning to offline state
*/
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is offline. FC-4s are offline. Awaiting BFA rport offline
* callback.
*/
static void
bfa_fcs_rport_sm_hcb_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_OFFLINE:
if (bfa_fcs_lport_is_online(rport->port) &&
(rport->plogi_pending)) {
rport->plogi_pending = BFA_FALSE;
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
}
/* fall through */
case RPSM_EVENT_ADDRESS_CHANGE:
if (!bfa_fcs_lport_is_online(rport->port)) {
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
}
if (bfa_fcs_fabric_is_switched(rport->port->fabric)) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
} else if (bfa_fcport_get_topology(rport->port->fcs->bfa) ==
BFA_PORT_TOPOLOGY_LOOP) {
if (rport->scn_online) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_adisc_offline_sending);
bfa_fcs_rport_send_adisc(rport, NULL);
} else {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
}
} else {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
rport->plogi_retries = 0;
bfa_fcs_rport_send_plogi(rport, NULL);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_SCN_ONLINE:
case RPSM_EVENT_SCN_OFFLINE:
case RPSM_EVENT_FAB_SCN:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_LOGO_IMP:
/*
* Ignore, already offline.
*/
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is offline. FC-4s are offline. Awaiting BFA rport offline
* callback to send LOGO accept.
*/
static void
bfa_fcs_rport_sm_hcb_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_OFFLINE:
case RPSM_EVENT_ADDRESS_CHANGE:
if (rport->pid && (rport->prlo == BFA_TRUE))
bfa_fcs_rport_send_prlo_acc(rport);
if (rport->pid && (rport->prlo == BFA_FALSE))
bfa_fcs_rport_send_logo_acc(rport);
/*
* If the lport is online and if the rport is not a well
* known address port,
* we try to re-discover the r-port.
*/
if (bfa_fcs_lport_is_online(rport->port) &&
(!BFA_FCS_PID_IS_WKA(rport->pid))) {
if (bfa_fcs_fabric_is_switched(rport->port->fabric)) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
} else {
/* For N2N Direct Attach, try to re-login */
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_plogi_sending);
rport->plogi_retries = 0;
bfa_fcs_rport_send_plogi(rport, NULL);
}
} else {
/*
* if it is not a well known address, reset the
* pid to 0.
*/
if (!BFA_FCS_PID_IS_WKA(rport->pid))
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_delete_pending);
if (rport->pid && (rport->prlo == BFA_TRUE))
bfa_fcs_rport_send_prlo_acc(rport);
if (rport->pid && (rport->prlo == BFA_FALSE))
bfa_fcs_rport_send_logo_acc(rport);
break;
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_offline);
break;
case RPSM_EVENT_SCN_ONLINE:
case RPSM_EVENT_SCN_OFFLINE:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
/*
* Ignore - already processing a LOGO.
*/
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is being deleted. FC-4s are offline.
* Awaiting BFA rport offline
* callback to send LOGO.
*/
static void
bfa_fcs_rport_sm_hcb_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_logo_sending);
bfa_fcs_rport_send_logo(rport, NULL);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_fcs_rport_send_logo_acc(rport);
/* fall through */
case RPSM_EVENT_PRLO_RCVD:
if (rport->prlo == BFA_TRUE)
bfa_fcs_rport_send_prlo_acc(rport);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_delete_pending);
break;
case RPSM_EVENT_SCN_ONLINE:
case RPSM_EVENT_SCN_OFFLINE:
case RPSM_EVENT_ADDRESS_CHANGE:
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is being deleted. FC-4s are offline. LOGO is being sent.
*/
static void
bfa_fcs_rport_sm_logo_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
/* Once LOGO is sent, we donot wait for the response */
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_SCN_ONLINE:
case RPSM_EVENT_SCN_OFFLINE:
case RPSM_EVENT_FAB_SCN:
case RPSM_EVENT_ADDRESS_CHANGE:
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_fcs_rport_send_logo_acc(rport);
/* fall through */
case RPSM_EVENT_PRLO_RCVD:
if (rport->prlo == BFA_TRUE)
bfa_fcs_rport_send_prlo_acc(rport);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is offline. FC-4s are offline. BFA rport is offline.
* Timer active to delete stale rport.
*/
static void
bfa_fcs_rport_sm_offline(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_TIMEOUT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_FAB_SCN:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_timer_stop(&rport->timer);
WARN_ON(!(bfa_fcport_get_topology(rport->port->fcs->bfa) !=
BFA_PORT_TOPOLOGY_LOOP));
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_SCN_OFFLINE:
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_fcs_online);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_fcs_online_action(rport);
break;
case RPSM_EVENT_SCN_ONLINE:
bfa_timer_stop(&rport->timer);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
bfa_fcs_rport_send_plogi(rport, NULL);
break;
case RPSM_EVENT_PLOGI_SEND:
bfa_timer_stop(&rport->timer);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
rport->plogi_retries = 0;
bfa_fcs_rport_send_plogi(rport, NULL);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport address has changed. Nameserver discovery request is being sent.
*/
static void
bfa_fcs_rport_sm_nsdisc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sent);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_FAB_SCN:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_PLOGI_SEND:
break;
case RPSM_EVENT_ADDRESS_CHANGE:
rport->ns_retries = 0; /* reset the retry count */
break;
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_fcs_online);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_fcs_online_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Nameserver discovery failed. Waiting for timeout to retry.
*/
static void
bfa_fcs_rport_sm_nsdisc_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_TIMEOUT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_FAB_SCN:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
bfa_timer_stop(&rport->timer);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_stop(&rport->timer);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_fcs_rport_send_logo_acc(rport);
break;
case RPSM_EVENT_PRLO_RCVD:
bfa_fcs_rport_send_prlo_acc(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_fcs_online);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_fcs_online_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport address has changed. Nameserver discovery request is sent.
*/
static void
bfa_fcs_rport_sm_nsdisc_sent(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
case RPSM_EVENT_ADDRESS_CHANGE:
if (rport->pid) {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
bfa_fcs_rport_send_plogi(rport, NULL);
} else {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
}
break;
case RPSM_EVENT_FAILED:
rport->ns_retries++;
if (rport->ns_retries < BFA_FCS_RPORT_MAX_RETRIES) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
bfa_fcs_rport_send_nsdisc(rport, NULL);
} else {
rport->old_pid = rport->pid;
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PRLO_RCVD:
bfa_fcs_rport_send_prlo_acc(rport);
break;
case RPSM_EVENT_FAB_SCN:
/*
* ignore, wait for NS query response
*/
break;
case RPSM_EVENT_LOGO_RCVD:
/*
* Not logged-in yet. Accept LOGO.
*/
bfa_fcs_rport_send_logo_acc(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_fcs_online);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_fcs_online_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport needs to be deleted
* waiting for ITNIM clean up to finish
*/
static void
bfa_fcs_rport_sm_fc4_off_delete(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_delete_pending);
bfa_fcs_rport_hal_offline(rport);
break;
case RPSM_EVENT_DELETE:
case RPSM_EVENT_PLOGI_RCVD:
/* Ignore these events */
break;
default:
bfa_sm_fault(rport->fcs, event);
break;
}
}
/*
* RPort needs to be deleted
* waiting for BFA/FW to finish current processing
*/
static void
bfa_fcs_rport_sm_delete_pending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_DELETE:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_PLOGI_RCVD:
/* Ignore these events */
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* fcs_rport_private FCS RPORT provate functions
*/
static void
bfa_fcs_rport_send_plogi(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
fcxp = fcxp_alloced ? fcxp_alloced :
bfa_fcs_fcxp_alloc(port->fcs, BFA_TRUE);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_plogi, rport, BFA_TRUE);
return;
}
rport->fcxp = fcxp;
len = fc_plogi_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_lport_get_fcid(port), 0,
port->port_cfg.pwwn, port->port_cfg.nwwn,
bfa_fcport_get_maxfrsize(port->fcs->bfa),
bfa_fcport_get_rx_bbcredit(port->fcs->bfa));
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, bfa_fcs_rport_plogi_response,
(void *)rport, FC_MAX_PDUSZ, FC_ELS_TOV);
rport->stats.plogis++;
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_plogi_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
struct fc_logi_s *plogi_rsp;
struct fc_ls_rjt_s *ls_rjt;
struct bfa_fcs_rport_s *twin;
struct list_head *qe;
bfa_trc(rport->fcs, rport->pwwn);
/*
* Sanity Checks
*/
if (req_status != BFA_STATUS_OK) {
bfa_trc(rport->fcs, req_status);
rport->stats.plogi_failed++;
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
return;
}
plogi_rsp = (struct fc_logi_s *) BFA_FCXP_RSP_PLD(fcxp);
/*
* Check for failure first.
*/
if (plogi_rsp->els_cmd.els_code != FC_ELS_ACC) {
ls_rjt = (struct fc_ls_rjt_s *) BFA_FCXP_RSP_PLD(fcxp);
bfa_trc(rport->fcs, ls_rjt->reason_code);
bfa_trc(rport->fcs, ls_rjt->reason_code_expl);
if ((ls_rjt->reason_code == FC_LS_RJT_RSN_UNABLE_TO_PERF_CMD) &&
(ls_rjt->reason_code_expl == FC_LS_RJT_EXP_INSUFF_RES)) {
rport->stats.rjt_insuff_res++;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_RETRY);
return;
}
rport->stats.plogi_rejects++;
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
return;
}
/*
* PLOGI is complete. Make sure this device is not one of the known
* device with a new FC port address.
*/
list_for_each(qe, &rport->port->rport_q) {
twin = (struct bfa_fcs_rport_s *) qe;
if (twin == rport)
continue;
if (!rport->pwwn && (plogi_rsp->port_name == twin->pwwn)) {
bfa_trc(rport->fcs, twin->pid);
bfa_trc(rport->fcs, rport->pid);
/* Update plogi stats in twin */
twin->stats.plogis += rport->stats.plogis;
twin->stats.plogi_rejects +=
rport->stats.plogi_rejects;
twin->stats.plogi_timeouts +=
rport->stats.plogi_timeouts;
twin->stats.plogi_failed +=
rport->stats.plogi_failed;
twin->stats.plogi_rcvd += rport->stats.plogi_rcvd;
twin->stats.plogi_accs++;
bfa_sm_send_event(rport, RPSM_EVENT_DELETE);
bfa_fcs_rport_update(twin, plogi_rsp);
twin->pid = rsp_fchs->s_id;
bfa_sm_send_event(twin, RPSM_EVENT_PLOGI_COMP);
return;
}
}
/*
* Normal login path -- no evil twins.
*/
rport->stats.plogi_accs++;
bfa_fcs_rport_update(rport, plogi_rsp);
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
}
static void
bfa_fcs_rport_send_plogiacc(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->reply_oxid);
fcxp = fcxp_alloced ? fcxp_alloced :
bfa_fcs_fcxp_alloc(port->fcs, BFA_FALSE);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_plogiacc, rport, BFA_FALSE);
return;
}
rport->fcxp = fcxp;
len = fc_plogi_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rport->pid, bfa_fcs_lport_get_fcid(port),
rport->reply_oxid, port->port_cfg.pwwn,
port->port_cfg.nwwn,
bfa_fcport_get_maxfrsize(port->fcs->bfa),
bfa_fcport_get_rx_bbcredit(port->fcs->bfa));
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_send_adisc(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
fcxp = fcxp_alloced ? fcxp_alloced :
bfa_fcs_fcxp_alloc(port->fcs, BFA_TRUE);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_adisc, rport, BFA_TRUE);
return;
}
rport->fcxp = fcxp;
len = fc_adisc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_lport_get_fcid(port), 0,
port->port_cfg.pwwn, port->port_cfg.nwwn);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, bfa_fcs_rport_adisc_response,
rport, FC_MAX_PDUSZ, FC_ELS_TOV);
rport->stats.adisc_sent++;
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_adisc_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
void *pld = bfa_fcxp_get_rspbuf(fcxp);
struct fc_ls_rjt_s *ls_rjt;
if (req_status != BFA_STATUS_OK) {
bfa_trc(rport->fcs, req_status);
rport->stats.adisc_failed++;
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
return;
}
if (fc_adisc_rsp_parse((struct fc_adisc_s *)pld, rsp_len, rport->pwwn,
rport->nwwn) == FC_PARSE_OK) {
rport->stats.adisc_accs++;
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
return;
}
rport->stats.adisc_rejects++;
ls_rjt = pld;
bfa_trc(rport->fcs, ls_rjt->els_cmd.els_code);
bfa_trc(rport->fcs, ls_rjt->reason_code);
bfa_trc(rport->fcs, ls_rjt->reason_code_expl);
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
}
static void
bfa_fcs_rport_send_nsdisc(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
int len;
bfa_cb_fcxp_send_t cbfn;
bfa_trc(rport->fcs, rport->pid);
fcxp = fcxp_alloced ? fcxp_alloced :
bfa_fcs_fcxp_alloc(port->fcs, BFA_TRUE);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_nsdisc, rport, BFA_TRUE);
return;
}
rport->fcxp = fcxp;
if (rport->pwwn) {
len = fc_gidpn_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
bfa_fcs_lport_get_fcid(port), 0, rport->pwwn);
cbfn = bfa_fcs_rport_gidpn_response;
} else {
len = fc_gpnid_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
bfa_fcs_lport_get_fcid(port), 0, rport->pid);
cbfn = bfa_fcs_rport_gpnid_response;
}
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, cbfn,
(void *)rport, FC_MAX_PDUSZ, FC_FCCT_TOV);
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_gidpn_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
struct ct_hdr_s *cthdr;
struct fcgs_gidpn_resp_s *gidpn_rsp;
struct bfa_fcs_rport_s *twin;
struct list_head *qe;
bfa_trc(rport->fcs, rport->pwwn);
cthdr = (struct ct_hdr_s *) BFA_FCXP_RSP_PLD(fcxp);
cthdr->cmd_rsp_code = be16_to_cpu(cthdr->cmd_rsp_code);
if (cthdr->cmd_rsp_code == CT_RSP_ACCEPT) {
/* Check if the pid is the same as before. */
gidpn_rsp = (struct fcgs_gidpn_resp_s *) (cthdr + 1);
if (gidpn_rsp->dap == rport->pid) {
/* Device is online */
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
} else {
/*
* Device's PID has changed. We need to cleanup
* and re-login. If there is another device with
* the the newly discovered pid, send an scn notice
* so that its new pid can be discovered.
*/
list_for_each(qe, &rport->port->rport_q) {
twin = (struct bfa_fcs_rport_s *) qe;
if (twin == rport)
continue;
if (gidpn_rsp->dap == twin->pid) {
bfa_trc(rport->fcs, twin->pid);
bfa_trc(rport->fcs, rport->pid);
twin->pid = 0;
bfa_sm_send_event(twin,
RPSM_EVENT_ADDRESS_CHANGE);
}
}
rport->pid = gidpn_rsp->dap;
bfa_sm_send_event(rport, RPSM_EVENT_ADDRESS_CHANGE);
}
return;
}
/*
* Reject Response
*/
switch (cthdr->reason_code) {
case CT_RSN_LOGICAL_BUSY:
/*
* Need to retry
*/
bfa_sm_send_event(rport, RPSM_EVENT_TIMEOUT);
break;
case CT_RSN_UNABLE_TO_PERF:
/*
* device doesn't exist : Start timer to cleanup this later.
*/
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
break;
default:
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
break;
}
}
static void
bfa_fcs_rport_gpnid_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
struct ct_hdr_s *cthdr;
bfa_trc(rport->fcs, rport->pwwn);
cthdr = (struct ct_hdr_s *) BFA_FCXP_RSP_PLD(fcxp);
cthdr->cmd_rsp_code = be16_to_cpu(cthdr->cmd_rsp_code);
if (cthdr->cmd_rsp_code == CT_RSP_ACCEPT) {
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
return;
}
/*
* Reject Response
*/
switch (cthdr->reason_code) {
case CT_RSN_LOGICAL_BUSY:
/*
* Need to retry
*/
bfa_sm_send_event(rport, RPSM_EVENT_TIMEOUT);
break;
case CT_RSN_UNABLE_TO_PERF:
/*
* device doesn't exist : Start timer to cleanup this later.
*/
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
break;
default:
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
break;
}
}
/*
* Called to send a logout to the rport.
*/
static void
bfa_fcs_rport_send_logo(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
u16 len;
bfa_trc(rport->fcs, rport->pid);
port = rport->port;
fcxp = fcxp_alloced ? fcxp_alloced :
bfa_fcs_fcxp_alloc(port->fcs, BFA_FALSE);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_logo, rport, BFA_FALSE);
return;
}
rport->fcxp = fcxp;
len = fc_logo_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_lport_get_fcid(port), 0,
bfa_fcs_lport_get_pwwn(port));
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL,
rport, FC_MAX_PDUSZ, FC_ELS_TOV);
rport->stats.logos++;
bfa_fcxp_discard(rport->fcxp);
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
/*
* Send ACC for a LOGO received.
*/
static void
bfa_fcs_rport_send_logo_acc(void *rport_cbarg)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
u16 len;
bfa_trc(rport->fcs, rport->pid);
port = rport->port;
fcxp = bfa_fcs_fcxp_alloc(port->fcs, BFA_FALSE);
if (!fcxp)
return;
rport->stats.logo_rcvd++;
len = fc_logo_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rport->pid, bfa_fcs_lport_get_fcid(port),
rport->reply_oxid);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
}
/*
* brief
* This routine will be called by bfa_timer on timer timeouts.
*
* param[in] rport - pointer to bfa_fcs_lport_ns_t.
* param[out] rport_status - pointer to return vport status in
*
* return
* void
*
* Special Considerations:
*
* note
*/
static void
bfa_fcs_rport_timeout(void *arg)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) arg;
rport->stats.plogi_timeouts++;
bfa_stats(rport->port, rport_plogi_timeouts);
bfa_sm_send_event(rport, RPSM_EVENT_TIMEOUT);
}
static void
bfa_fcs_rport_process_prli(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len)
{
struct bfa_fcxp_s *fcxp;
struct fchs_s fchs;
struct bfa_fcs_lport_s *port = rport->port;
struct fc_prli_s *prli;
bfa_trc(port->fcs, rx_fchs->s_id);
bfa_trc(port->fcs, rx_fchs->d_id);
rport->stats.prli_rcvd++;
/*
* We are in Initiator Mode
*/
prli = (struct fc_prli_s *) (rx_fchs + 1);
if (prli->parampage.servparams.target) {
/*
* PRLI from a target ?
* Send the Acc.
* PRLI sent by us will be used to transition the IT nexus,
* once the response is received from the target.
*/
bfa_trc(port->fcs, rx_fchs->s_id);
rport->scsi_function = BFA_RPORT_TARGET;
} else {
bfa_trc(rport->fcs, prli->parampage.type);
rport->scsi_function = BFA_RPORT_INITIATOR;
bfa_fcs_itnim_is_initiator(rport->itnim);
}
fcxp = bfa_fcs_fcxp_alloc(port->fcs, BFA_FALSE);
if (!fcxp)
return;
len = fc_prli_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rx_fchs->s_id, bfa_fcs_lport_get_fcid(port),
rx_fchs->ox_id, port->port_cfg.roles);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
}
static void
bfa_fcs_rport_process_rpsc(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len)
{
struct bfa_fcxp_s *fcxp;
struct fchs_s fchs;
struct bfa_fcs_lport_s *port = rport->port;
struct fc_rpsc_speed_info_s speeds;
struct bfa_port_attr_s pport_attr;
bfa_trc(port->fcs, rx_fchs->s_id);
bfa_trc(port->fcs, rx_fchs->d_id);
rport->stats.rpsc_rcvd++;
speeds.port_speed_cap =
RPSC_SPEED_CAP_1G | RPSC_SPEED_CAP_2G | RPSC_SPEED_CAP_4G |
RPSC_SPEED_CAP_8G;
/*
* get curent speed from pport attributes from BFA
*/
bfa_fcport_get_attr(port->fcs->bfa, &pport_attr);
speeds.port_op_speed = fc_bfa_speed_to_rpsc_operspeed(pport_attr.speed);
fcxp = bfa_fcs_fcxp_alloc(port->fcs, BFA_FALSE);
if (!fcxp)
return;
len = fc_rpsc_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rx_fchs->s_id, bfa_fcs_lport_get_fcid(port),
rx_fchs->ox_id, &speeds);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
}
static void
bfa_fcs_rport_process_adisc(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len)
{
struct bfa_fcxp_s *fcxp;
struct fchs_s fchs;
struct bfa_fcs_lport_s *port = rport->port;
bfa_trc(port->fcs, rx_fchs->s_id);
bfa_trc(port->fcs, rx_fchs->d_id);
rport->stats.adisc_rcvd++;
/*
* Accept if the itnim for this rport is online.
* Else reject the ADISC.
*/
if (bfa_fcs_itnim_get_online_state(rport->itnim) == BFA_STATUS_OK) {
fcxp = bfa_fcs_fcxp_alloc(port->fcs, BFA_FALSE);
if (!fcxp)
return;
len = fc_adisc_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rx_fchs->s_id, bfa_fcs_lport_get_fcid(port),
rx_fchs->ox_id, port->port_cfg.pwwn,
port->port_cfg.nwwn);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag,
BFA_FALSE, FC_CLASS_3, len, &fchs, NULL, NULL,
FC_MAX_PDUSZ, 0);
} else {
rport->stats.adisc_rejected++;
bfa_fcs_rport_send_ls_rjt(rport, rx_fchs,
FC_LS_RJT_RSN_UNABLE_TO_PERF_CMD,
FC_LS_RJT_EXP_LOGIN_REQUIRED);
}
}
static void
bfa_fcs_rport_hal_online(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_lport_s *port = rport->port;
struct bfa_rport_info_s rport_info;
rport_info.pid = rport->pid;
rport_info.local_pid = port->pid;
rport_info.lp_tag = port->lp_tag;
rport_info.vf_id = port->fabric->vf_id;
rport_info.vf_en = port->fabric->is_vf;
rport_info.fc_class = rport->fc_cos;
rport_info.cisc = rport->cisc;
rport_info.max_frmsz = rport->maxfrsize;
bfa_rport_online(rport->bfa_rport, &rport_info);
}
static void
bfa_fcs_rport_hal_offline(struct bfa_fcs_rport_s *rport)
{
if (rport->bfa_rport)
bfa_sm_send_event(rport->bfa_rport, BFA_RPORT_SM_OFFLINE);
else
bfa_cb_rport_offline(rport);
}
static struct bfa_fcs_rport_s *
bfa_fcs_rport_alloc(struct bfa_fcs_lport_s *port, wwn_t pwwn, u32 rpid)
{
struct bfa_fcs_s *fcs = port->fcs;
struct bfa_fcs_rport_s *rport;
struct bfad_rport_s *rport_drv;
/*
* allocate rport
*/
if (fcs->num_rport_logins >= bfa_fcs_rport_max_logins) {
bfa_trc(fcs, rpid);
return NULL;
}
if (bfa_fcb_rport_alloc(fcs->bfad, &rport, &rport_drv)
!= BFA_STATUS_OK) {
bfa_trc(fcs, rpid);
return NULL;
}
/*
* Initialize r-port
*/
rport->port = port;
rport->fcs = fcs;
rport->rp_drv = rport_drv;
rport->pid = rpid;
rport->pwwn = pwwn;
rport->old_pid = 0;
rport->bfa_rport = NULL;
/*
* allocate FC-4s
*/
WARN_ON(!bfa_fcs_lport_is_initiator(port));
if (bfa_fcs_lport_is_initiator(port)) {
rport->itnim = bfa_fcs_itnim_create(rport);
if (!rport->itnim) {
bfa_trc(fcs, rpid);
kfree(rport_drv);
return NULL;
}
}
bfa_fcs_lport_add_rport(port, rport);
fcs->num_rport_logins++;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
/* Initialize the Rport Features(RPF) Sub Module */
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_init(rport);
return rport;
}
static void
bfa_fcs_rport_free(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_lport_s *port = rport->port;
struct bfa_fcs_s *fcs = port->fcs;
/*
* - delete FC-4s
* - delete BFA rport
* - remove from queue of rports
*/
rport->plogi_pending = BFA_FALSE;
if (bfa_fcs_lport_is_initiator(port)) {
bfa_fcs_itnim_delete(rport->itnim);
if (rport->pid != 0 && !BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_rport_offline(rport);
}
if (rport->bfa_rport) {
bfa_sm_send_event(rport->bfa_rport, BFA_RPORT_SM_DELETE);
rport->bfa_rport = NULL;
}
bfa_fcs_lport_del_rport(port, rport);
fcs->num_rport_logins--;
kfree(rport->rp_drv);
}
static void
bfa_fcs_rport_aen_post(struct bfa_fcs_rport_s *rport,
enum bfa_rport_aen_event event,
struct bfa_rport_aen_data_s *data)
{
struct bfa_fcs_lport_s *port = rport->port;
struct bfad_s *bfad = (struct bfad_s *)port->fcs->bfad;
struct bfa_aen_entry_s *aen_entry;
bfad_get_aen_entry(bfad, aen_entry);
if (!aen_entry)
return;
if (event == BFA_RPORT_AEN_QOS_PRIO)
aen_entry->aen_data.rport.priv.qos = data->priv.qos;
else if (event == BFA_RPORT_AEN_QOS_FLOWID)
aen_entry->aen_data.rport.priv.qos = data->priv.qos;
aen_entry->aen_data.rport.vf_id = rport->port->fabric->vf_id;
aen_entry->aen_data.rport.ppwwn = bfa_fcs_lport_get_pwwn(
bfa_fcs_get_base_port(rport->fcs));
aen_entry->aen_data.rport.lpwwn = bfa_fcs_lport_get_pwwn(rport->port);
aen_entry->aen_data.rport.rpwwn = rport->pwwn;
/* Send the AEN notification */
bfad_im_post_vendor_event(aen_entry, bfad, ++rport->fcs->fcs_aen_seq,
BFA_AEN_CAT_RPORT, event);
}
static void
bfa_fcs_rport_fcs_online_action(struct bfa_fcs_rport_s *rport)
{
if ((!rport->pid) || (!rport->pwwn)) {
bfa_trc(rport->fcs, rport->pid);
bfa_sm_fault(rport->fcs, rport->pid);
}
bfa_sm_send_event(rport->itnim, BFA_FCS_ITNIM_SM_FCS_ONLINE);
}
static void
bfa_fcs_rport_hal_online_action(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_lport_s *port = rport->port;
struct bfad_s *bfad = (struct bfad_s *)port->fcs->bfad;
char lpwwn_buf[BFA_STRING_32];
char rpwwn_buf[BFA_STRING_32];
rport->stats.onlines++;
if ((!rport->pid) || (!rport->pwwn)) {
bfa_trc(rport->fcs, rport->pid);
bfa_sm_fault(rport->fcs, rport->pid);
}
if (bfa_fcs_lport_is_initiator(port)) {
bfa_fcs_itnim_brp_online(rport->itnim);
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_rport_online(rport);
}
wwn2str(lpwwn_buf, bfa_fcs_lport_get_pwwn(port));
wwn2str(rpwwn_buf, rport->pwwn);
if (!BFA_FCS_PID_IS_WKA(rport->pid)) {
BFA_LOG(KERN_INFO, bfad, bfa_log_level,
"Remote port (WWN = %s) online for logical port (WWN = %s)\n",
rpwwn_buf, lpwwn_buf);
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_ONLINE, NULL);
}
}
static void
bfa_fcs_rport_fcs_offline_action(struct bfa_fcs_rport_s *rport)
{
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_rport_offline(rport);
bfa_fcs_itnim_rport_offline(rport->itnim);
}
static void
bfa_fcs_rport_hal_offline_action(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_lport_s *port = rport->port;
struct bfad_s *bfad = (struct bfad_s *)port->fcs->bfad;
char lpwwn_buf[BFA_STRING_32];
char rpwwn_buf[BFA_STRING_32];
if (!rport->bfa_rport) {
bfa_fcs_rport_fcs_offline_action(rport);
return;
}
rport->stats.offlines++;
wwn2str(lpwwn_buf, bfa_fcs_lport_get_pwwn(port));
wwn2str(rpwwn_buf, rport->pwwn);
if (!BFA_FCS_PID_IS_WKA(rport->pid)) {
if (bfa_fcs_lport_is_online(rport->port) == BFA_TRUE) {
BFA_LOG(KERN_ERR, bfad, bfa_log_level,
"Remote port (WWN = %s) connectivity lost for "
"logical port (WWN = %s)\n",
rpwwn_buf, lpwwn_buf);
bfa_fcs_rport_aen_post(rport,
BFA_RPORT_AEN_DISCONNECT, NULL);
} else {
BFA_LOG(KERN_INFO, bfad, bfa_log_level,
"Remote port (WWN = %s) offlined by "
"logical port (WWN = %s)\n",
rpwwn_buf, lpwwn_buf);
bfa_fcs_rport_aen_post(rport,
BFA_RPORT_AEN_OFFLINE, NULL);
}
}
if (bfa_fcs_lport_is_initiator(port)) {
bfa_fcs_itnim_rport_offline(rport->itnim);
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_rport_offline(rport);
}
}
/*
* Update rport parameters from PLOGI or PLOGI accept.
*/
static void
bfa_fcs_rport_update(struct bfa_fcs_rport_s *rport, struct fc_logi_s *plogi)
{
bfa_fcs_lport_t *port = rport->port;
/*
* - port name
* - node name
*/
rport->pwwn = plogi->port_name;
rport->nwwn = plogi->node_name;
/*
* - class of service
*/
rport->fc_cos = 0;
if (plogi->class3.class_valid)
rport->fc_cos = FC_CLASS_3;
if (plogi->class2.class_valid)
rport->fc_cos |= FC_CLASS_2;
/*
* - CISC
* - MAX receive frame size
*/
rport->cisc = plogi->csp.cisc;
if (be16_to_cpu(plogi->class3.rxsz) < be16_to_cpu(plogi->csp.rxsz))
rport->maxfrsize = be16_to_cpu(plogi->class3.rxsz);
else
rport->maxfrsize = be16_to_cpu(plogi->csp.rxsz);
bfa_trc(port->fcs, be16_to_cpu(plogi->csp.bbcred));
bfa_trc(port->fcs, port->fabric->bb_credit);
/*
* Direct Attach P2P mode :
* This is to handle a bug (233476) in IBM targets in Direct Attach
* Mode. Basically, in FLOGI Accept the target would have
* erroneously set the BB Credit to the value used in the FLOGI
* sent by the HBA. It uses the correct value (its own BB credit)
* in PLOGI.
*/
if ((!bfa_fcs_fabric_is_switched(port->fabric)) &&
(be16_to_cpu(plogi->csp.bbcred) < port->fabric->bb_credit)) {
bfa_trc(port->fcs, be16_to_cpu(plogi->csp.bbcred));
bfa_trc(port->fcs, port->fabric->bb_credit);
port->fabric->bb_credit = be16_to_cpu(plogi->csp.bbcred);
bfa_fcport_set_tx_bbcredit(port->fcs->bfa,
port->fabric->bb_credit);
}
}
/*
* Called to handle LOGO received from an existing remote port.
*/
static void
bfa_fcs_rport_process_logo(struct bfa_fcs_rport_s *rport, struct fchs_s *fchs)
{
rport->reply_oxid = fchs->ox_id;
bfa_trc(rport->fcs, rport->reply_oxid);
rport->prlo = BFA_FALSE;
rport->stats.logo_rcvd++;
bfa_sm_send_event(rport, RPSM_EVENT_LOGO_RCVD);
}
/*
* fcs_rport_public FCS rport public interfaces
*/
/*
* Called by bport/vport to create a remote port instance for a discovered
* remote device.
*
* @param[in] port - base port or vport
* @param[in] rpid - remote port ID
*
* @return None
*/
struct bfa_fcs_rport_s *
bfa_fcs_rport_create(struct bfa_fcs_lport_s *port, u32 rpid)
{
struct bfa_fcs_rport_s *rport;
bfa_trc(port->fcs, rpid);
rport = bfa_fcs_rport_alloc(port, WWN_NULL, rpid);
if (!rport)
return NULL;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_SEND);
return rport;
}
/*
* Called to create a rport for which only the wwn is known.
*
* @param[in] port - base port
* @param[in] rpwwn - remote port wwn
*
* @return None
*/
struct bfa_fcs_rport_s *
bfa_fcs_rport_create_by_wwn(struct bfa_fcs_lport_s *port, wwn_t rpwwn)
{
struct bfa_fcs_rport_s *rport;
bfa_trc(port->fcs, rpwwn);
rport = bfa_fcs_rport_alloc(port, rpwwn, 0);
if (!rport)
return NULL;
bfa_sm_send_event(rport, RPSM_EVENT_ADDRESS_DISC);
return rport;
}
/*
* Called by bport in private loop topology to indicate that a
* rport has been discovered and plogi has been completed.
*
* @param[in] port - base port or vport
* @param[in] rpid - remote port ID
*/
void
bfa_fcs_rport_start(struct bfa_fcs_lport_s *port, struct fchs_s *fchs,
struct fc_logi_s *plogi)
{
struct bfa_fcs_rport_s *rport;
rport = bfa_fcs_rport_alloc(port, WWN_NULL, fchs->s_id);
if (!rport)
return;
bfa_fcs_rport_update(rport, plogi);
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_COMP);
}
/*
* Called by bport/vport to handle PLOGI received from a new remote port.
* If an existing rport does a plogi, it will be handled separately.
*/
void
bfa_fcs_rport_plogi_create(struct bfa_fcs_lport_s *port, struct fchs_s *fchs,
struct fc_logi_s *plogi)
{
struct bfa_fcs_rport_s *rport;
rport = bfa_fcs_rport_alloc(port, plogi->port_name, fchs->s_id);
if (!rport)
return;
bfa_fcs_rport_update(rport, plogi);
rport->reply_oxid = fchs->ox_id;
bfa_trc(rport->fcs, rport->reply_oxid);
rport->stats.plogi_rcvd++;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_RCVD);
}
/*
* Called by bport/vport to handle PLOGI received from an existing
* remote port.
*/
void
bfa_fcs_rport_plogi(struct bfa_fcs_rport_s *rport, struct fchs_s *rx_fchs,
struct fc_logi_s *plogi)
{
/*
* @todo Handle P2P and initiator-initiator.
*/
bfa_fcs_rport_update(rport, plogi);
rport->reply_oxid = rx_fchs->ox_id;
bfa_trc(rport->fcs, rport->reply_oxid);
rport->pid = rx_fchs->s_id;
bfa_trc(rport->fcs, rport->pid);
rport->stats.plogi_rcvd++;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_RCVD);
}
/*
* Called by bport/vport to notify SCN for the remote port
*/
void
bfa_fcs_rport_scn(struct bfa_fcs_rport_s *rport)
{
rport->stats.rscns++;
bfa_sm_send_event(rport, RPSM_EVENT_FAB_SCN);
}
/*
* brief
* This routine BFA callback for bfa_rport_online() call.
*
* param[in] cb_arg - rport struct.
*
* return
* void
*
* Special Considerations:
*
* note
*/
void
bfa_cb_rport_online(void *cbarg)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
bfa_trc(rport->fcs, rport->pwwn);
bfa_sm_send_event(rport, RPSM_EVENT_HCB_ONLINE);
}
/*
* brief
* This routine BFA callback for bfa_rport_offline() call.
*
* param[in] rport -
*
* return
* void
*
* Special Considerations:
*
* note
*/
void
bfa_cb_rport_offline(void *cbarg)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
bfa_trc(rport->fcs, rport->pwwn);
bfa_sm_send_event(rport, RPSM_EVENT_HCB_OFFLINE);
}
/*
* brief
* This routine is a static BFA callback when there is a QoS flow_id
* change notification
*
* param[in] rport -
*
* return
* void
*
* Special Considerations:
*
* note
*/
void
bfa_cb_rport_qos_scn_flowid(void *cbarg,
struct bfa_rport_qos_attr_s old_qos_attr,
struct bfa_rport_qos_attr_s new_qos_attr)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
struct bfa_rport_aen_data_s aen_data;
bfa_trc(rport->fcs, rport->pwwn);
aen_data.priv.qos = new_qos_attr;
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_QOS_FLOWID, &aen_data);
}
void
bfa_cb_rport_scn_online(struct bfa_s *bfa)
{
struct bfa_fcs_s *fcs = &((struct bfad_s *)bfa->bfad)->bfa_fcs;
struct bfa_fcs_lport_s *port = bfa_fcs_get_base_port(fcs);
struct bfa_fcs_rport_s *rp;
struct list_head *qe;
list_for_each(qe, &port->rport_q) {
rp = (struct bfa_fcs_rport_s *) qe;
bfa_sm_send_event(rp, RPSM_EVENT_SCN_ONLINE);
rp->scn_online = BFA_TRUE;
}
if (bfa_fcs_lport_is_online(port))
bfa_fcs_lport_lip_scn_online(port);
}
void
bfa_cb_rport_scn_no_dev(void *rport)
{
struct bfa_fcs_rport_s *rp = rport;
bfa_sm_send_event(rp, RPSM_EVENT_SCN_OFFLINE);
rp->scn_online = BFA_FALSE;
}
void
bfa_cb_rport_scn_offline(struct bfa_s *bfa)
{
struct bfa_fcs_s *fcs = &((struct bfad_s *)bfa->bfad)->bfa_fcs;
struct bfa_fcs_lport_s *port = bfa_fcs_get_base_port(fcs);
struct bfa_fcs_rport_s *rp;
struct list_head *qe;
list_for_each(qe, &port->rport_q) {
rp = (struct bfa_fcs_rport_s *) qe;
bfa_sm_send_event(rp, RPSM_EVENT_SCN_OFFLINE);
rp->scn_online = BFA_FALSE;
}
}
/*
* brief
* This routine is a static BFA callback when there is a QoS priority
* change notification
*
* param[in] rport -
*
* return
* void
*
* Special Considerations:
*
* note
*/
void
bfa_cb_rport_qos_scn_prio(void *cbarg,
struct bfa_rport_qos_attr_s old_qos_attr,
struct bfa_rport_qos_attr_s new_qos_attr)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
struct bfa_rport_aen_data_s aen_data;
bfa_trc(rport->fcs, rport->pwwn);
aen_data.priv.qos = new_qos_attr;
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_QOS_PRIO, &aen_data);
}
/*
* Called to process any unsolicted frames from this remote port
*/
void
bfa_fcs_rport_uf_recv(struct bfa_fcs_rport_s *rport,
struct fchs_s *fchs, u16 len)
{
struct bfa_fcs_lport_s *port = rport->port;
struct fc_els_cmd_s *els_cmd;
bfa_trc(rport->fcs, fchs->s_id);
bfa_trc(rport->fcs, fchs->d_id);
bfa_trc(rport->fcs, fchs->type);
if (fchs->type != FC_TYPE_ELS)
return;
els_cmd = (struct fc_els_cmd_s *) (fchs + 1);
bfa_trc(rport->fcs, els_cmd->els_code);
switch (els_cmd->els_code) {
case FC_ELS_LOGO:
bfa_stats(port, plogi_rcvd);
bfa_fcs_rport_process_logo(rport, fchs);
break;
case FC_ELS_ADISC:
bfa_stats(port, adisc_rcvd);
bfa_fcs_rport_process_adisc(rport, fchs, len);
break;
case FC_ELS_PRLO:
bfa_stats(port, prlo_rcvd);
if (bfa_fcs_lport_is_initiator(port))
bfa_fcs_fcpim_uf_recv(rport->itnim, fchs, len);
break;
case FC_ELS_PRLI:
bfa_stats(port, prli_rcvd);
bfa_fcs_rport_process_prli(rport, fchs, len);
break;
case FC_ELS_RPSC:
bfa_stats(port, rpsc_rcvd);
bfa_fcs_rport_process_rpsc(rport, fchs, len);
break;
default:
bfa_stats(port, un_handled_els_rcvd);
bfa_fcs_rport_send_ls_rjt(rport, fchs,
FC_LS_RJT_RSN_CMD_NOT_SUPP,
FC_LS_RJT_EXP_NO_ADDL_INFO);
break;
}
}
/* send best case acc to prlo */
static void
bfa_fcs_rport_send_prlo_acc(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
int len;
bfa_trc(rport->fcs, rport->pid);
fcxp = bfa_fcs_fcxp_alloc(port->fcs, BFA_FALSE);
if (!fcxp)
return;
len = fc_prlo_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rport->pid, bfa_fcs_lport_get_fcid(port),
rport->reply_oxid, 0);
bfa_fcxp_send(fcxp, rport->bfa_rport, port->fabric->vf_id,
port->lp_tag, BFA_FALSE, FC_CLASS_3, len, &fchs,
NULL, NULL, FC_MAX_PDUSZ, 0);
}
/*
* Send a LS reject
*/
static void
bfa_fcs_rport_send_ls_rjt(struct bfa_fcs_rport_s *rport, struct fchs_s *rx_fchs,
u8 reason_code, u8 reason_code_expl)
{
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
int len;
bfa_trc(rport->fcs, rx_fchs->s_id);
fcxp = bfa_fcs_fcxp_alloc(rport->fcs, BFA_FALSE);
if (!fcxp)
return;
len = fc_ls_rjt_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rx_fchs->s_id, bfa_fcs_lport_get_fcid(port),
rx_fchs->ox_id, reason_code, reason_code_expl);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag,
BFA_FALSE, FC_CLASS_3, len, &fchs, NULL, NULL,
FC_MAX_PDUSZ, 0);
}
/*
* Return state of rport.
*/
int
bfa_fcs_rport_get_state(struct bfa_fcs_rport_s *rport)
{
return bfa_sm_to_state(rport_sm_table, rport->sm);
}
/*
* brief
* Called by the Driver to set rport delete/ageout timeout
*
* param[in] rport timeout value in seconds.
*
* return None
*/
void
bfa_fcs_rport_set_del_timeout(u8 rport_tmo)
{
/* convert to Millisecs */
if (rport_tmo > 0)
bfa_fcs_rport_del_timeout = rport_tmo * 1000;
}
void
bfa_fcs_rport_prlo(struct bfa_fcs_rport_s *rport, __be16 ox_id)
{
bfa_trc(rport->fcs, rport->pid);
rport->prlo = BFA_TRUE;
rport->reply_oxid = ox_id;
bfa_sm_send_event(rport, RPSM_EVENT_PRLO_RCVD);
}
/*
* Called by BFAD to set the max limit on number of bfa_fcs_rport allocation
* which limits number of concurrent logins to remote ports
*/
void
bfa_fcs_rport_set_max_logins(u32 max_logins)
{
if (max_logins > 0)
bfa_fcs_rport_max_logins = max_logins;
}
void
bfa_fcs_rport_get_attr(struct bfa_fcs_rport_s *rport,
struct bfa_rport_attr_s *rport_attr)
{
struct bfa_rport_qos_attr_s qos_attr;
struct bfa_fcs_lport_s *port = rport->port;
bfa_port_speed_t rport_speed = rport->rpf.rpsc_speed;
struct bfa_port_attr_s port_attr;
bfa_fcport_get_attr(rport->fcs->bfa, &port_attr);
memset(rport_attr, 0, sizeof(struct bfa_rport_attr_s));
memset(&qos_attr, 0, sizeof(struct bfa_rport_qos_attr_s));
rport_attr->pid = rport->pid;
rport_attr->pwwn = rport->pwwn;
rport_attr->nwwn = rport->nwwn;
rport_attr->cos_supported = rport->fc_cos;
rport_attr->df_sz = rport->maxfrsize;
rport_attr->state = bfa_fcs_rport_get_state(rport);
rport_attr->fc_cos = rport->fc_cos;
rport_attr->cisc = rport->cisc;
rport_attr->scsi_function = rport->scsi_function;
rport_attr->curr_speed = rport->rpf.rpsc_speed;
rport_attr->assigned_speed = rport->rpf.assigned_speed;
if (rport->bfa_rport) {
qos_attr.qos_priority = rport->bfa_rport->qos_attr.qos_priority;
qos_attr.qos_flow_id =
cpu_to_be32(rport->bfa_rport->qos_attr.qos_flow_id);
}
rport_attr->qos_attr = qos_attr;
rport_attr->trl_enforced = BFA_FALSE;
if (bfa_fcport_is_ratelim(port->fcs->bfa) &&
(rport->scsi_function == BFA_RPORT_TARGET)) {
if (rport_speed == BFA_PORT_SPEED_UNKNOWN)
rport_speed =
bfa_fcport_get_ratelim_speed(rport->fcs->bfa);
if ((bfa_fcs_lport_get_rport_max_speed(port) !=
BFA_PORT_SPEED_UNKNOWN) && (rport_speed < port_attr.speed))
rport_attr->trl_enforced = BFA_TRUE;
}
}
/*
* Remote port implementation.
*/
/*
* fcs_rport_api FCS rport API.
*/
struct bfa_fcs_rport_s *
bfa_fcs_rport_lookup(struct bfa_fcs_lport_s *port, wwn_t rpwwn)
{
struct bfa_fcs_rport_s *rport;
rport = bfa_fcs_lport_get_rport_by_pwwn(port, rpwwn);
if (rport == NULL) {
/*
* TBD Error handling
*/
}
return rport;
}
struct bfa_fcs_rport_s *
bfa_fcs_rport_lookup_by_nwwn(struct bfa_fcs_lport_s *port, wwn_t rnwwn)
{
struct bfa_fcs_rport_s *rport;
rport = bfa_fcs_lport_get_rport_by_nwwn(port, rnwwn);
if (rport == NULL) {
/*
* TBD Error handling
*/
}
return rport;
}
/*
* Remote port features (RPF) implementation.
*/
#define BFA_FCS_RPF_RETRIES (3)
#define BFA_FCS_RPF_RETRY_TIMEOUT (1000) /* 1 sec (In millisecs) */
static void bfa_fcs_rpf_send_rpsc2(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rpf_rpsc2_response(void *fcsarg,
struct bfa_fcxp_s *fcxp,
void *cbarg,
bfa_status_t req_status,
u32 rsp_len,
u32 resid_len,
struct fchs_s *rsp_fchs);
static void bfa_fcs_rpf_timeout(void *arg);
/*
* fcs_rport_ftrs_sm FCS rport state machine events
*/
enum rpf_event {
RPFSM_EVENT_RPORT_OFFLINE = 1, /* Rport offline */
RPFSM_EVENT_RPORT_ONLINE = 2, /* Rport online */
RPFSM_EVENT_FCXP_SENT = 3, /* Frame from has been sent */
RPFSM_EVENT_TIMEOUT = 4, /* Rport SM timeout event */
RPFSM_EVENT_RPSC_COMP = 5,
RPFSM_EVENT_RPSC_FAIL = 6,
RPFSM_EVENT_RPSC_ERROR = 7,
};
static void bfa_fcs_rpf_sm_uninit(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void bfa_fcs_rpf_sm_rpsc_sending(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void bfa_fcs_rpf_sm_rpsc(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void bfa_fcs_rpf_sm_rpsc_retry(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void bfa_fcs_rpf_sm_offline(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void bfa_fcs_rpf_sm_online(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void
bfa_fcs_rpf_sm_uninit(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
struct bfa_fcs_fabric_s *fabric = &rport->fcs->fabric;
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_RPORT_ONLINE:
/* Send RPSC2 to a Brocade fabric only. */
if ((!BFA_FCS_PID_IS_WKA(rport->pid)) &&
((rport->port->fabric->lps->brcd_switch) ||
(bfa_fcs_fabric_get_switch_oui(fabric) ==
BFA_FCS_BRCD_SWITCH_OUI))) {
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_rpsc_sending);
rpf->rpsc_retries = 0;
bfa_fcs_rpf_send_rpsc2(rpf, NULL);
}
break;
case RPFSM_EVENT_RPORT_OFFLINE:
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
static void
bfa_fcs_rpf_sm_rpsc_sending(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_rpsc);
break;
case RPFSM_EVENT_RPORT_OFFLINE:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rpf->fcxp_wqe);
rpf->rpsc_retries = 0;
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
static void
bfa_fcs_rpf_sm_rpsc(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_RPSC_COMP:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_online);
/* Update speed info in f/w via BFA */
if (rpf->rpsc_speed != BFA_PORT_SPEED_UNKNOWN)
bfa_rport_speed(rport->bfa_rport, rpf->rpsc_speed);
else if (rpf->assigned_speed != BFA_PORT_SPEED_UNKNOWN)
bfa_rport_speed(rport->bfa_rport, rpf->assigned_speed);
break;
case RPFSM_EVENT_RPSC_FAIL:
/* RPSC not supported by rport */
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_online);
break;
case RPFSM_EVENT_RPSC_ERROR:
/* need to retry...delayed a bit. */
if (rpf->rpsc_retries++ < BFA_FCS_RPF_RETRIES) {
bfa_timer_start(rport->fcs->bfa, &rpf->timer,
bfa_fcs_rpf_timeout, rpf,
BFA_FCS_RPF_RETRY_TIMEOUT);
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_rpsc_retry);
} else {
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_online);
}
break;
case RPFSM_EVENT_RPORT_OFFLINE:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_offline);
bfa_fcxp_discard(rpf->fcxp);
rpf->rpsc_retries = 0;
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
static void
bfa_fcs_rpf_sm_rpsc_retry(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_TIMEOUT:
/* re-send the RPSC */
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_rpsc_sending);
bfa_fcs_rpf_send_rpsc2(rpf, NULL);
break;
case RPFSM_EVENT_RPORT_OFFLINE:
bfa_timer_stop(&rpf->timer);
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_offline);
rpf->rpsc_retries = 0;
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
static void
bfa_fcs_rpf_sm_online(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_RPORT_OFFLINE:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_offline);
rpf->rpsc_retries = 0;
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
static void
bfa_fcs_rpf_sm_offline(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_RPORT_ONLINE:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_rpsc_sending);
bfa_fcs_rpf_send_rpsc2(rpf, NULL);
break;
case RPFSM_EVENT_RPORT_OFFLINE:
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Called when Rport is created.
*/
void
bfa_fcs_rpf_init(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_rpf_s *rpf = &rport->rpf;
bfa_trc(rport->fcs, rport->pid);
rpf->rport = rport;
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_uninit);
}
/*
* Called when Rport becomes online
*/
void
bfa_fcs_rpf_rport_online(struct bfa_fcs_rport_s *rport)
{
bfa_trc(rport->fcs, rport->pid);
if (__fcs_min_cfg(rport->port->fcs))
return;
if (bfa_fcs_fabric_is_switched(rport->port->fabric))
bfa_sm_send_event(&rport->rpf, RPFSM_EVENT_RPORT_ONLINE);
}
/*
* Called when Rport becomes offline
*/
void
bfa_fcs_rpf_rport_offline(struct bfa_fcs_rport_s *rport)
{
bfa_trc(rport->fcs, rport->pid);
if (__fcs_min_cfg(rport->port->fcs))
return;
rport->rpf.rpsc_speed = 0;
bfa_sm_send_event(&rport->rpf, RPFSM_EVENT_RPORT_OFFLINE);
}
static void
bfa_fcs_rpf_timeout(void *arg)
{
struct bfa_fcs_rpf_s *rpf = (struct bfa_fcs_rpf_s *) arg;
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, rport->pid);
bfa_sm_send_event(rpf, RPFSM_EVENT_TIMEOUT);
}
static void
bfa_fcs_rpf_send_rpsc2(void *rpf_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rpf_s *rpf = (struct bfa_fcs_rpf_s *)rpf_cbarg;
struct bfa_fcs_rport_s *rport = rpf->rport;
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
fcxp = fcxp_alloced ? fcxp_alloced :
bfa_fcs_fcxp_alloc(port->fcs, BFA_TRUE);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rpf->fcxp_wqe,
bfa_fcs_rpf_send_rpsc2, rpf, BFA_TRUE);
return;
}
rpf->fcxp = fcxp;
len = fc_rpsc2_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_lport_get_fcid(port), &rport->pid, 1);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, bfa_fcs_rpf_rpsc2_response,
rpf, FC_MAX_PDUSZ, FC_ELS_TOV);
rport->stats.rpsc_sent++;
bfa_sm_send_event(rpf, RPFSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rpf_rpsc2_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rpf_s *rpf = (struct bfa_fcs_rpf_s *) cbarg;
struct bfa_fcs_rport_s *rport = rpf->rport;
struct fc_ls_rjt_s *ls_rjt;
struct fc_rpsc2_acc_s *rpsc2_acc;
u16 num_ents;
bfa_trc(rport->fcs, req_status);
if (req_status != BFA_STATUS_OK) {
bfa_trc(rport->fcs, req_status);
if (req_status == BFA_STATUS_ETIMER)
rport->stats.rpsc_failed++;
bfa_sm_send_event(rpf, RPFSM_EVENT_RPSC_ERROR);
return;
}
rpsc2_acc = (struct fc_rpsc2_acc_s *) BFA_FCXP_RSP_PLD(fcxp);
if (rpsc2_acc->els_cmd == FC_ELS_ACC) {
rport->stats.rpsc_accs++;
num_ents = be16_to_cpu(rpsc2_acc->num_pids);
bfa_trc(rport->fcs, num_ents);
if (num_ents > 0) {
WARN_ON(be32_to_cpu(rpsc2_acc->port_info[0].pid) !=
bfa_ntoh3b(rport->pid));
bfa_trc(rport->fcs,
be32_to_cpu(rpsc2_acc->port_info[0].pid));
bfa_trc(rport->fcs,
be16_to_cpu(rpsc2_acc->port_info[0].speed));
bfa_trc(rport->fcs,
be16_to_cpu(rpsc2_acc->port_info[0].index));
bfa_trc(rport->fcs,
rpsc2_acc->port_info[0].type);
if (rpsc2_acc->port_info[0].speed == 0) {
bfa_sm_send_event(rpf, RPFSM_EVENT_RPSC_ERROR);
return;
}
rpf->rpsc_speed = fc_rpsc_operspeed_to_bfa_speed(
be16_to_cpu(rpsc2_acc->port_info[0].speed));
bfa_sm_send_event(rpf, RPFSM_EVENT_RPSC_COMP);
}
} else {
ls_rjt = (struct fc_ls_rjt_s *) BFA_FCXP_RSP_PLD(fcxp);
bfa_trc(rport->fcs, ls_rjt->reason_code);
bfa_trc(rport->fcs, ls_rjt->reason_code_expl);
rport->stats.rpsc_rejects++;
if (ls_rjt->reason_code == FC_LS_RJT_RSN_CMD_NOT_SUPP)
bfa_sm_send_event(rpf, RPFSM_EVENT_RPSC_FAIL);
else
bfa_sm_send_event(rpf, RPFSM_EVENT_RPSC_ERROR);
}
}
| penberg/linux | drivers/scsi/bfa/bfa_fcs_rport.c | C | gpl-2.0 | 89,903 |
<?php
$magicWords = array();
$magicWords['en'] = array(
'systemtest_tagextension' => array( 0, 'systemtest_tagextension' ),
);
| elevati0n/batPhoneWiki | vendor/mediawiki/parser-hooks/tests/system/TagHookTest.i18n.php | PHP | gpl-2.0 | 130 |
/*
* kernel/power/suspend.c - Suspend to RAM and standby functionality.
*
* Copyright (c) 2003 Patrick Mochel
* Copyright (c) 2003 Open Source Development Lab
* Copyright (c) 2009 Rafael J. Wysocki <[email protected]>, Novell Inc.
*
* This file is released under the GPLv2.
*/
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/cpu.h>
#include <linux/cpuidle.h>
#include <linux/syscalls.h>
#include <linux/gfp.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/suspend.h>
#include <linux/syscore_ops.h>
#include <linux/ftrace.h>
#include <trace/events/power.h>
#include <linux/compiler.h>
#include "power.h"
const char *pm_labels[] = { "mem", "standby", "freeze", NULL };
const char *pm_states[PM_SUSPEND_MAX];
static const struct platform_suspend_ops *suspend_ops;
static const struct platform_freeze_ops *freeze_ops;
static DECLARE_WAIT_QUEUE_HEAD(suspend_freeze_wait_head);
static bool suspend_freeze_wake;
void freeze_set_ops(const struct platform_freeze_ops *ops)
{
lock_system_sleep();
freeze_ops = ops;
unlock_system_sleep();
}
static void freeze_begin(void)
{
suspend_freeze_wake = false;
}
static void freeze_enter(void)
{
cpuidle_use_deepest_state(true);
cpuidle_resume();
wait_event(suspend_freeze_wait_head, suspend_freeze_wake);
cpuidle_pause();
cpuidle_use_deepest_state(false);
}
void freeze_wake(void)
{
suspend_freeze_wake = true;
wake_up(&suspend_freeze_wait_head);
}
EXPORT_SYMBOL_GPL(freeze_wake);
static bool valid_state(suspend_state_t state)
{
/*
* PM_SUSPEND_STANDBY and PM_SUSPEND_MEM states need low level
* support and need to be valid to the low level
* implementation, no valid callback implies that none are valid.
*/
return suspend_ops && suspend_ops->valid && suspend_ops->valid(state);
}
/*
* If this is set, the "mem" label always corresponds to the deepest sleep state
* available, the "standby" label corresponds to the second deepest sleep state
* available (if any), and the "freeze" label corresponds to the remaining
* available sleep state (if there is one).
*/
static bool relative_states;
static int __init sleep_states_setup(char *str)
{
relative_states = !strncmp(str, "1", 1);
pm_states[PM_SUSPEND_FREEZE] = pm_labels[relative_states ? 0 : 2];
return 1;
}
__setup("relative_sleep_states=", sleep_states_setup);
/**
* suspend_set_ops - Set the global suspend method table.
* @ops: Suspend operations to use.
*/
void suspend_set_ops(const struct platform_suspend_ops *ops)
{
suspend_state_t i;
int j = 0;
lock_system_sleep();
suspend_ops = ops;
for (i = PM_SUSPEND_MEM; i >= PM_SUSPEND_STANDBY; i--)
if (valid_state(i)) {
pm_states[i] = pm_labels[j++];
} else if (!relative_states) {
pm_states[i] = NULL;
j++;
}
pm_states[PM_SUSPEND_FREEZE] = pm_labels[j];
unlock_system_sleep();
}
EXPORT_SYMBOL_GPL(suspend_set_ops);
/**
* suspend_valid_only_mem - Generic memory-only valid callback.
*
* Platform drivers that implement mem suspend only and only need to check for
* that in their .valid() callback can use this instead of rolling their own
* .valid() callback.
*/
int suspend_valid_only_mem(suspend_state_t state)
{
return state == PM_SUSPEND_MEM;
}
EXPORT_SYMBOL_GPL(suspend_valid_only_mem);
static bool sleep_state_supported(suspend_state_t state)
{
return state == PM_SUSPEND_FREEZE || (suspend_ops && suspend_ops->enter);
}
static int platform_suspend_prepare(suspend_state_t state)
{
return state != PM_SUSPEND_FREEZE && suspend_ops->prepare ?
suspend_ops->prepare() : 0;
}
static int platform_suspend_prepare_late(suspend_state_t state)
{
return state == PM_SUSPEND_FREEZE && freeze_ops && freeze_ops->prepare ?
freeze_ops->prepare() : 0;
}
static int platform_suspend_prepare_noirq(suspend_state_t state)
{
return state != PM_SUSPEND_FREEZE && suspend_ops->prepare_late ?
suspend_ops->prepare_late() : 0;
}
static void platform_resume_noirq(suspend_state_t state)
{
if (state != PM_SUSPEND_FREEZE && suspend_ops->wake)
suspend_ops->wake();
}
static void platform_resume_early(suspend_state_t state)
{
if (state == PM_SUSPEND_FREEZE && freeze_ops && freeze_ops->restore)
freeze_ops->restore();
}
static void platform_resume_finish(suspend_state_t state)
{
if (state != PM_SUSPEND_FREEZE && suspend_ops->finish)
suspend_ops->finish();
}
static int platform_suspend_begin(suspend_state_t state)
{
if (state == PM_SUSPEND_FREEZE && freeze_ops && freeze_ops->begin)
return freeze_ops->begin();
else if (suspend_ops->begin)
return suspend_ops->begin(state);
else
return 0;
}
static void platform_resume_end(suspend_state_t state)
{
if (state == PM_SUSPEND_FREEZE && freeze_ops && freeze_ops->end)
freeze_ops->end();
else if (suspend_ops->end)
suspend_ops->end();
}
static void platform_recover(suspend_state_t state)
{
if (state != PM_SUSPEND_FREEZE && suspend_ops->recover)
suspend_ops->recover();
}
static bool platform_suspend_again(suspend_state_t state)
{
return state != PM_SUSPEND_FREEZE && suspend_ops->suspend_again ?
suspend_ops->suspend_again() : false;
}
static int suspend_test(int level)
{
#ifdef CONFIG_PM_DEBUG
if (pm_test_level == level) {
printk(KERN_INFO "suspend debug: Waiting for 5 seconds.\n");
mdelay(5000);
return 1;
}
#endif /* !CONFIG_PM_DEBUG */
return 0;
}
/**
* suspend_prepare - Prepare for entering system sleep state.
*
* Common code run for every system sleep state that can be entered (except for
* hibernation). Run suspend notifiers, allocate the "suspend" console and
* freeze processes.
*/
static int suspend_prepare(suspend_state_t state)
{
int error;
if (!sleep_state_supported(state))
return -EPERM;
pm_prepare_console();
error = pm_notifier_call_chain(PM_SUSPEND_PREPARE);
if (error)
goto Finish;
trace_suspend_resume(TPS("freeze_processes"), 0, true);
error = suspend_freeze_processes();
trace_suspend_resume(TPS("freeze_processes"), 0, false);
if (!error)
return 0;
suspend_stats.failed_freeze++;
dpm_save_failed_step(SUSPEND_FREEZE);
Finish:
pm_notifier_call_chain(PM_POST_SUSPEND);
pm_restore_console();
return error;
}
/* default implementation */
void __weak arch_suspend_disable_irqs(void)
{
local_irq_disable();
}
/* default implementation */
void __weak arch_suspend_enable_irqs(void)
{
local_irq_enable();
}
/**
* suspend_enter - Make the system enter the given sleep state.
* @state: System sleep state to enter.
* @wakeup: Returns information that the sleep state should not be re-entered.
*
* This function should be called after devices have been suspended.
*/
static int suspend_enter(suspend_state_t state, bool *wakeup)
{
int error;
error = platform_suspend_prepare(state);
if (error)
goto Platform_finish;
error = dpm_suspend_late(PMSG_SUSPEND);
if (error) {
printk(KERN_ERR "PM: late suspend of devices failed\n");
goto Platform_finish;
}
error = platform_suspend_prepare_late(state);
if (error)
goto Devices_early_resume;
error = dpm_suspend_noirq(PMSG_SUSPEND);
if (error) {
printk(KERN_ERR "PM: noirq suspend of devices failed\n");
goto Platform_early_resume;
}
error = platform_suspend_prepare_noirq(state);
if (error)
goto Platform_wake;
if (suspend_test(TEST_PLATFORM))
goto Platform_wake;
/*
* PM_SUSPEND_FREEZE equals
* frozen processes + suspended devices + idle processors.
* Thus we should invoke freeze_enter() soon after
* all the devices are suspended.
*/
if (state == PM_SUSPEND_FREEZE) {
trace_suspend_resume(TPS("machine_suspend"), state, true);
freeze_enter();
trace_suspend_resume(TPS("machine_suspend"), state, false);
goto Platform_wake;
}
error = disable_nonboot_cpus();
if (error || suspend_test(TEST_CPUS))
goto Enable_cpus;
arch_suspend_disable_irqs();
BUG_ON(!irqs_disabled());
system_state = SYSTEM_SUSPEND;
error = syscore_suspend();
if (!error) {
*wakeup = pm_wakeup_pending();
if (!(suspend_test(TEST_CORE) || *wakeup)) {
trace_suspend_resume(TPS("machine_suspend"),
state, true);
error = suspend_ops->enter(state);
trace_suspend_resume(TPS("machine_suspend"),
state, false);
events_check_enabled = false;
}
syscore_resume();
}
system_state = SYSTEM_RUNNING;
arch_suspend_enable_irqs();
BUG_ON(irqs_disabled());
Enable_cpus:
enable_nonboot_cpus();
Platform_wake:
platform_resume_noirq(state);
dpm_resume_noirq(PMSG_RESUME);
Platform_early_resume:
platform_resume_early(state);
Devices_early_resume:
dpm_resume_early(PMSG_RESUME);
Platform_finish:
platform_resume_finish(state);
return error;
}
/**
* suspend_devices_and_enter - Suspend devices and enter system sleep state.
* @state: System sleep state to enter.
*/
int suspend_devices_and_enter(suspend_state_t state)
{
int error;
bool wakeup = false;
if (!sleep_state_supported(state))
return -ENOSYS;
error = platform_suspend_begin(state);
if (error)
goto Close;
suspend_console();
suspend_test_start();
error = dpm_suspend_start(PMSG_SUSPEND);
if (error) {
pr_err("PM: Some devices failed to suspend, or early wake event detected\n");
goto Recover_platform;
}
suspend_test_finish("suspend devices");
if (suspend_test(TEST_DEVICES))
goto Recover_platform;
do {
error = suspend_enter(state, &wakeup);
} while (!error && !wakeup && platform_suspend_again(state));
Resume_devices:
suspend_test_start();
dpm_resume_end(PMSG_RESUME);
suspend_test_finish("resume devices");
trace_suspend_resume(TPS("resume_console"), state, true);
resume_console();
trace_suspend_resume(TPS("resume_console"), state, false);
Close:
platform_resume_end(state);
return error;
Recover_platform:
platform_recover(state);
goto Resume_devices;
}
/**
* suspend_finish - Clean up before finishing the suspend sequence.
*
* Call platform code to clean up, restart processes, and free the console that
* we've allocated. This routine is not called for hibernation.
*/
static void suspend_finish(void)
{
suspend_thaw_processes();
pm_notifier_call_chain(PM_POST_SUSPEND);
pm_restore_console();
}
/**
* enter_state - Do common work needed to enter system sleep state.
* @state: System sleep state to enter.
*
* Make sure that no one else is trying to put the system into a sleep state.
* Fail if that's not the case. Otherwise, prepare for system suspend, make the
* system enter the given sleep state and clean up after wakeup.
*/
static int enter_state(suspend_state_t state)
{
int error;
trace_suspend_resume(TPS("suspend_enter"), state, true);
if (state == PM_SUSPEND_FREEZE) {
#ifdef CONFIG_PM_DEBUG
if (pm_test_level != TEST_NONE && pm_test_level <= TEST_CPUS) {
pr_warning("PM: Unsupported test mode for freeze state,"
"please choose none/freezer/devices/platform.\n");
return -EAGAIN;
}
#endif
} else if (!valid_state(state)) {
return -EINVAL;
}
if (!mutex_trylock(&pm_mutex))
return -EBUSY;
if (state == PM_SUSPEND_FREEZE)
freeze_begin();
trace_suspend_resume(TPS("sync_filesystems"), 0, true);
printk(KERN_INFO "PM: Syncing filesystems ... ");
sys_sync();
printk("done.\n");
trace_suspend_resume(TPS("sync_filesystems"), 0, false);
pr_debug("PM: Preparing system for %s sleep\n", pm_states[state]);
error = suspend_prepare(state);
if (error)
goto Unlock;
if (suspend_test(TEST_FREEZER))
goto Finish;
trace_suspend_resume(TPS("suspend_enter"), state, false);
pr_debug("PM: Entering %s sleep\n", pm_states[state]);
pm_restrict_gfp_mask();
error = suspend_devices_and_enter(state);
pm_restore_gfp_mask();
Finish:
pr_debug("PM: Finishing wakeup.\n");
suspend_finish();
Unlock:
mutex_unlock(&pm_mutex);
return error;
}
/**
* pm_suspend - Externally visible function for suspending the system.
* @state: System sleep state to enter.
*
* Check if the value of @state represents one of the supported states,
* execute enter_state() and update system suspend statistics.
*/
int pm_suspend(suspend_state_t state)
{
int error;
if (state <= PM_SUSPEND_ON || state >= PM_SUSPEND_MAX)
return -EINVAL;
error = enter_state(state);
if (error) {
suspend_stats.fail++;
dpm_save_failed_errno(error);
} else {
suspend_stats.success++;
}
return error;
}
EXPORT_SYMBOL(pm_suspend);
| dtuchsch/linux-preempt_rt | kernel/power/suspend.c | C | gpl-2.0 | 12,389 |
package teammates.test.cases.datatransfer;
import static teammates.common.util.Const.EOL;
import org.testng.annotations.Test;
import teammates.common.datatransfer.InstructorPrivileges;
import teammates.common.datatransfer.attributes.InstructorAttributes;
import teammates.common.util.Const;
import teammates.common.util.FieldValidator;
import teammates.common.util.StringHelper;
import teammates.storage.entity.Instructor;
/**
* SUT: {@link InstructorAttributes}.
*/
public class InstructorAttributesTest extends BaseAttributesTest {
private static final String DEFAULT_ROLE_NAME = Const.InstructorPermissionRoleNames
.INSTRUCTOR_PERMISSION_ROLE_COOWNER;
private static final String DEFAULT_DISPLAYED_NAME = InstructorAttributes.DEFAULT_DISPLAY_NAME;
private static final InstructorPrivileges DEFAULT_PRIVILEGES =
new InstructorPrivileges(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER);
@Test
public void testBuilderWithDefaultOptionalValues() {
InstructorAttributes instructor = InstructorAttributes
.builder("valid.google.id", "valid-course-id", "valid name", "[email protected]")
.build();
// Check default values for optional params
assertEquals(DEFAULT_ROLE_NAME, instructor.role);
assertEquals(DEFAULT_DISPLAYED_NAME, instructor.displayedName);
assertEquals(DEFAULT_PRIVILEGES, instructor.privileges);
assertFalse(instructor.isArchived);
assertTrue(instructor.isDisplayedToStudents);
}
@Test
public void testBuilderWithNullArguments() {
InstructorAttributes instructorWithNullValues = InstructorAttributes
.builder(null, null, null, null)
.withRole(null)
.withDisplayedName(null)
.withIsArchived(null)
.withPrivileges((InstructorPrivileges) null)
.build();
// No default values for required params
assertNull(instructorWithNullValues.googleId);
assertNull(instructorWithNullValues.courseId);
assertNull(instructorWithNullValues.name);
assertNull(instructorWithNullValues.email);
// Check default values for optional params
assertEquals(DEFAULT_ROLE_NAME, instructorWithNullValues.role);
assertEquals(DEFAULT_DISPLAYED_NAME, instructorWithNullValues.displayedName);
assertEquals(DEFAULT_PRIVILEGES, instructorWithNullValues.privileges);
assertFalse(instructorWithNullValues.isArchived);
}
@Test
public void testBuilderCopy() {
InstructorAttributes instructor = InstructorAttributes
.builder("valid.google.id", "valid-course-id", "valid name", "[email protected]")
.withDisplayedName("Original instructor")
.build();
InstructorAttributes instructorCopy = InstructorAttributes
.builder(instructor.googleId, instructor.courseId, instructor.name, instructor.email)
.withDisplayedName(instructor.displayedName)
.build();
assertEquals(instructor.googleId, instructorCopy.googleId);
assertEquals(instructor.courseId, instructorCopy.courseId);
assertEquals(instructor.name, instructorCopy.name);
assertEquals(instructor.email, instructorCopy.email);
assertEquals(instructor.displayedName, instructorCopy.displayedName);
assertEquals(instructor.role, instructorCopy.role);
assertEquals(instructor.privileges, instructorCopy.privileges);
assertEquals(instructor.key, instructorCopy.key);
assertEquals(instructor.isArchived, instructorCopy.isArchived);
assertEquals(instructor.isDisplayedToStudents, instructorCopy.isDisplayedToStudents);
}
@Test
public void testValueOf() {
InstructorPrivileges privileges =
new InstructorPrivileges(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER);
InstructorAttributes instructor = InstructorAttributes
.builder("valid.google.id", "valid-course-id", "valid name", "[email protected]")
.withDisplayedName(InstructorAttributes.DEFAULT_DISPLAY_NAME)
.withRole(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER)
.withPrivileges(privileges)
.build();
Instructor entity = instructor.toEntity();
InstructorAttributes instructor1 = InstructorAttributes.valueOf(entity);
assertEquals(instructor.googleId, instructor1.googleId);
assertEquals(instructor.courseId, instructor1.courseId);
assertEquals(instructor.name, instructor1.name);
assertEquals(instructor.email, instructor1.email);
assertEquals(instructor.role, instructor1.role);
assertEquals(instructor.displayedName, instructor1.displayedName);
assertEquals(instructor.privileges, instructor1.privileges);
entity.setRole(null);
entity.setDisplayedName(null);
entity.setInstructorPrivilegeAsText(null);
InstructorAttributes instructor2 = InstructorAttributes.valueOf(entity);
assertEquals(instructor.googleId, instructor2.googleId);
assertEquals(instructor.courseId, instructor2.courseId);
assertEquals(instructor.name, instructor2.name);
assertEquals(instructor.email, instructor2.email);
// default values for these
assertEquals(instructor.role, instructor2.role);
assertEquals(instructor.displayedName, instructor2.displayedName);
assertEquals(instructor.privileges, instructor2.privileges);
}
@Test
public void testIsRegistered() {
@SuppressWarnings("deprecation")
InstructorAttributes instructor = InstructorAttributes
.builder("valid.google.id", "valid-course-id", "valid name", "[email protected]")
.build();
assertTrue(instructor.isRegistered());
instructor.googleId = null;
assertFalse(instructor.isRegistered());
}
@Override
@Test
public void testToEntity() {
String googleId = "valid.googleId";
String courseId = "courseId";
String name = "name";
String email = "[email protected]";
String roleName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER;
String displayedName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER;
InstructorPrivileges privileges =
new InstructorPrivileges(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER);
InstructorAttributes instructor = InstructorAttributes.builder(googleId, courseId, name, email)
.withRole(roleName)
.withDisplayedName(displayedName).withPrivileges(privileges)
.build();
String key = "randomKey";
instructor.key = key;
Instructor entity = instructor.toEntity();
assertEquals(key, entity.getRegistrationKey());
}
@Test
public void testGetInvalidityInfo() throws Exception {
@SuppressWarnings("deprecation")
InstructorAttributes i = InstructorAttributes
.builder("valid.google.id", "valid-course-id", "valid name", "[email protected]")
.build();
assertTrue(i.isValid());
i.googleId = "invalid@google@id";
i.name = "";
i.email = "invalid email";
i.courseId = "";
i.role = "invalidRole";
assertFalse("invalid value", i.isValid());
String errorMessage =
getPopulatedErrorMessage(
FieldValidator.GOOGLE_ID_ERROR_MESSAGE, i.googleId,
FieldValidator.GOOGLE_ID_FIELD_NAME, FieldValidator.REASON_INCORRECT_FORMAT,
FieldValidator.GOOGLE_ID_MAX_LENGTH) + EOL
+ getPopulatedEmptyStringErrorMessage(
FieldValidator.COURSE_ID_ERROR_MESSAGE_EMPTY_STRING,
FieldValidator.COURSE_ID_FIELD_NAME, FieldValidator.COURSE_ID_MAX_LENGTH) + EOL
+ getPopulatedEmptyStringErrorMessage(
FieldValidator.SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE_EMPTY_STRING,
FieldValidator.PERSON_NAME_FIELD_NAME, FieldValidator.PERSON_NAME_MAX_LENGTH) + EOL
+ getPopulatedErrorMessage(
FieldValidator.EMAIL_ERROR_MESSAGE, i.email,
FieldValidator.EMAIL_FIELD_NAME, FieldValidator.REASON_INCORRECT_FORMAT,
FieldValidator.EMAIL_MAX_LENGTH) + EOL
+ String.format(FieldValidator.ROLE_ERROR_MESSAGE, i.role);
assertEquals("invalid value", errorMessage, StringHelper.toString(i.getInvalidityInfo()));
i.googleId = null;
assertFalse("invalid value", i.isValid());
errorMessage =
getPopulatedEmptyStringErrorMessage(
FieldValidator.COURSE_ID_ERROR_MESSAGE_EMPTY_STRING,
FieldValidator.COURSE_ID_FIELD_NAME, FieldValidator.COURSE_ID_MAX_LENGTH) + EOL
+ getPopulatedEmptyStringErrorMessage(
FieldValidator.SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE_EMPTY_STRING,
FieldValidator.PERSON_NAME_FIELD_NAME, FieldValidator.PERSON_NAME_MAX_LENGTH) + EOL
+ getPopulatedErrorMessage(
FieldValidator.EMAIL_ERROR_MESSAGE, i.email,
FieldValidator.EMAIL_FIELD_NAME, FieldValidator.REASON_INCORRECT_FORMAT,
FieldValidator.EMAIL_MAX_LENGTH) + EOL
+ String.format(FieldValidator.ROLE_ERROR_MESSAGE, i.role);
assertEquals("invalid value", errorMessage, StringHelper.toString(i.getInvalidityInfo()));
}
@Test
public void testSanitizeForSaving() {
String googleId = "valid.googleId";
String courseId = "courseId";
String name = "name";
String email = "[email protected]";
String roleName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER;
String displayedName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER;
InstructorPrivileges privileges =
new InstructorPrivileges(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER);
InstructorAttributes instructor = InstructorAttributes.builder(googleId, courseId, name, email)
.withRole(roleName)
.withDisplayedName(displayedName).withPrivileges(privileges)
.build();
instructor.sanitizeForSaving();
assertEquals(privileges, instructor.privileges);
instructor.role = null;
instructor.displayedName = null;
instructor.privileges = null;
instructor.sanitizeForSaving();
assertEquals(privileges, instructor.privileges);
}
@Test
public void testIsAllowedForPrivilege() {
String googleId = "valid.googleId";
String courseId = "courseId";
String name = "name";
String email = "[email protected]";
String roleName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER;
String displayedName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER;
InstructorPrivileges privileges =
new InstructorPrivileges(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_MANAGER);
InstructorAttributes instructor = InstructorAttributes.builder(googleId, courseId, name, email)
.withRole(roleName)
.withDisplayedName(displayedName).withPrivileges(privileges)
.build();
assertFalse(instructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE));
instructor.privileges = null;
assertTrue(instructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE));
String sectionId = "sectionId";
String sessionId = "sessionId";
assertTrue(instructor.isAllowedForPrivilege(sectionId, sessionId,
Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION_COMMENT_IN_SECTIONS));
instructor.privileges = null;
assertTrue(instructor.isAllowedForPrivilege(sectionId, sessionId,
Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION_COMMENT_IN_SECTIONS));
}
@Test
public void testIsEqualToAnotherInstructor() {
String googleId = "valid.googleId";
String courseId = "courseId";
String name = "name";
String email = "[email protected]";
String roleName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER;
String displayedName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER;
InstructorPrivileges privileges =
new InstructorPrivileges(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_MANAGER);
InstructorAttributes instructor = InstructorAttributes.builder(googleId, courseId, name, email)
.withRole(roleName)
.withDisplayedName(displayedName).withPrivileges(privileges)
.build();
InstructorPrivileges privileges2 =
new InstructorPrivileges(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_MANAGER);
InstructorAttributes instructor2 = InstructorAttributes.builder(googleId, courseId, name, email)
.withRole(roleName)
.withDisplayedName(displayedName)
.withPrivileges(privileges2)
.build();
assertTrue(instructor.isEqualToAnotherInstructor(instructor2));
instructor2.privileges.updatePrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE, true);
assertFalse(instructor.isEqualToAnotherInstructor(instructor2));
instructor2.privileges.updatePrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE, false);
assertTrue(instructor.isEqualToAnotherInstructor(instructor2));
// TODO: find ways to test this method more thoroughly
}
}
| HirdayGupta/teammates | src/test/java/teammates/test/cases/datatransfer/InstructorAttributesTest.java | Java | gpl-2.0 | 14,279 |
/*
* Copyright (C) 2007-2009 ENAC, Pascal Brisset, Antoine Drouin
*
* This file is part of paparazzi.
*
* paparazzi 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.
*
* paparazzi 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 paparazzi; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* @file subsystems/navigation/snav.h
*
* Smooth navigation to wp_a along an arc (around wp_cd),
* a segment (from wp_rd to wp_ta) and a second arc (around wp_ca).
*/
#ifndef SNAV_H
#define SNAV_H
#include "std.h"
extern float snav_desired_tow; /* time of week, s */
bool_t snav_init(uint8_t wp_a, float desired_course_rad, float radius);
bool_t snav_circle1(void);
bool_t snav_route(void);
bool_t snav_circle2(void);
bool_t snav_on_time(float radius);
#endif // SNAV_H
| arbuzarbuz/paparazzi | sw/airborne/subsystems/navigation/snav.h | C | gpl-2.0 | 1,309 |
/*
* This file is part of the coreboot project.
*
* Copyright (C) 2014 Edward O'Callaghan <[email protected]>
*
* 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.
*/
#ifndef SUPERIO_FINTEK_F71869AD_INTERNAL_H
#define SUPERIO_FINTEK_F71869AD_INTERNAL_H
#include <arch/io.h>
#include <device/pnp.h>
void f71869ad_multifunc_init(struct device *dev);
void f71869ad_hwm_init(struct device *dev);
#endif /* SUPERIO_FINTEK_F71869AD_INTERNAL_H */
| latelee/coreboot | src/superio/fintek/f71869ad/fintek_internal.h | C | gpl-2.0 | 909 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="nl_NL">
<context>
<name>design/admin/content/search</name>
<message>
<source>Search</source>
<translation>Zoeken</translation>
</message>
<message>
<source>All content</source>
<translation>Alle inhoud</translation>
</message>
<message>
<source>The same location</source>
<translation>Dezelfde locatie</translation>
</message>
<message>
<source>For more options try the %1Advanced search%2.</source>
<comment>The parameters are link start and end tags.</comment>
<translation>Probeer %1Geavanceerd zoeken%2 voor meer opties.</translation>
</message>
<message>
<source>The following words were excluded from the search</source>
<translation>De volgende woorden zijn weggelaten uit de zoekopdracht</translation>
</message>
<message>
<source>No results were found while searching for <%1></source>
<translation>Geen resultaten gevonden bij het zoeken naar <%1></translation>
</message>
<message>
<source>Search tips</source>
<translation>Zoektips</translation>
</message>
<message>
<source>Check spelling of keywords.</source>
<translation>Controleer de spelling van de woorden.</translation>
</message>
<message>
<source>Try changing some keywords e.g. &quot;car&quot; instead of &quot;cars&quot;.</source>
<translation>Probeer woorden te veranderen, bijvoorbeeld &quot;fiets&quot; in plaats van &quot;fietsen&quot;.</translation>
</message>
<message>
<source>Try more general keywords.</source>
<translation>Probeer meer algemene woorden.</translation>
</message>
<message>
<source>Fewer keywords result in more matches. Try reducing keywords until you get a result.</source>
<translation>Minder woorden leidt tot meer resultaten. Probeer het aantal woorden te verminderen tot u resultaat krijgt.</translation>
</message>
<message>
<source>Search for <%1> returned %2 matches</source>
<translation>Het zoeken naar <%1> leverde %2 resultaten op</translation>
</message>
</context>
<context>
<name>design/admin/node/view/full</name>
<message>
<source>Show 10 items per page.</source>
<translation>10 items per pagina tonen.</translation>
</message>
<message>
<source>Show 50 items per page.</source>
<translation>50 items per pagina tonen.</translation>
</message>
<message>
<source>Show 25 items per page.</source>
<translation>25 items per pagina tonen.</translation>
</message>
</context>
<context>
<name>design/admin/pagelayout</name>
<message>
<source>Search in all content</source>
<translation>Alle inhoud doorzoeken</translation>
</message>
<message>
<source>Search</source>
<translation>Zoeken</translation>
</message>
<message>
<source>Advanced</source>
<translation>Geavanceerd</translation>
</message>
<message>
<source>Search in '%node'</source>
<translation>Zoeken in '%node'</translation>
</message>
<message>
<source>Advanced search.</source>
<translation>Geavanceerd zoeken.</translation>
</message>
</context>
<context>
<name>design/base</name>
<message>
<source>The following words were excluded from the search</source>
<translation>De volgende woorden zijn weggelaten uit de zoekopdracht</translation>
</message>
<message>
<source>Search</source>
<translation>Zoeken</translation>
</message>
<message>
<source>For more options try the %1Advanced search%2</source>
<comment>The parameters are link start and end tags.</comment>
<translation>Probeer %1Geavanceerd zoeken%2 voor meer opties</translation>
</message>
<message>
<source>No results were found when searching for "%1"</source>
<translation>Geen resultaten gevonden bij het zoeken naar "<%1>"</translation>
</message>
<message>
<source>Search tips</source>
<translation>Zoektips</translation>
</message>
<message>
<source>Check spelling of keywords.</source>
<translation>Controleer de spelling van de woorden.</translation>
</message>
<message>
<source>Try changing some keywords eg. car instead of cars.</source>
<translation>Probeer woorden te veranderen, bijvoorbeeld &quot;fiets&quot; in plaats van &quot;fietsen&quot;.</translation>
</message>
<message>
<source>Try more general keywords.</source>
<translation>Probeer meer algemene woorden.</translation>
</message>
<message>
<source>Fewer keywords gives more results, try reducing keywords until you get a result.</source>
<translation>Minder woorden leidt tot meer resultaten. Probeer het aantal woorden te verminderen tot u resultaat krijgt.</translation>
</message>
<message>
<source>Search for "%1" returned %2 matches</source>
<translation>Het zoeken naar "<%1>" leverde %2 resultaten op</translation>
</message>
</context>
<context>
<name>design/ezfind/search</name>
<message>
<source>Spell check suggestion: did you mean</source>
<translation>Spellingssuggesties: bedoelde u</translation>
</message>
<message>
<source>The search is case insensitive. Upper and lower case characters may be used.</source>
<translation>Het zoeken is niet hoofdlettergevoelig. Zowel hoofdletters als kleine letters kunnen worden gebruikt.</translation>
</message>
<message>
<source>The search result contains all search terms.</source>
<translation>Het zoekresultaat bevat alle zoektermen.</translation>
</message>
<message>
<source>Phrase search can be achieved by using quotes, example: "Quick brown fox jumps over the lazy dog"</source>
<translation>Het zoeken op zinnen kan worden gedaan door aanhalingstekens te gebruiken, bijvoorbeeld: "Blaffende honden bijten niet"</translation>
</message>
<message>
<source>Words may be excluded by using a minus ( - ) character, example: lazy -dog</source>
<translation>Woorden kunnen worden uitgesloten door het minteken ( - ) te gebruiken, bijvoorbeeld: "blaffende -honden"</translation>
</message>
</context>
<context>
<name>design/ezflow/block/search</name>
<message>
<source>Search</source>
<translation>Zoeken</translation>
</message>
</context>
<context>
<name>design/ezwebin/content/search</name>
<message>
<source>Search</source>
<translation>Zoeken</translation>
</message>
<message>
<source>For more options try the %1Advanced search%2</source>
<comment>The parameters are link start and end tags.</comment>
<translation>Probeer %1Geavanceerd zoeken%2 voor meer opties</translation>
</message>
<message>
<source>No results were found when searching for "%1".</source>
<translation>Geen resultaten gevonden bij het zoeken naar "<%1>".</translation>
</message>
<message>
<source>Search tips</source>
<translation>Zoektips</translation>
</message>
<message>
<source>Check spelling of keywords.</source>
<translation>Controleer de spelling van de woorden.</translation>
</message>
<message>
<source>Try changing some keywords (eg, "car" instead of "cars").</source>
<translation>Probeer woorden te veranderen, bijvoorbeeld &quot;fiets&quot; in plaats van &quot;fietsen&quot;.</translation>
</message>
<message>
<source>Try searching with less specific keywords.</source>
<translation>Probeer te zoeken met minder specifieke woorden.</translation>
</message>
<message>
<source>Reduce number of keywords to get more results.</source>
<translation>Verminder het aantal woorden om meer resultaten te krijgen.</translation>
</message>
<message>
<source>Search for "%1" returned %2 matches</source>
<translation>Het zoeken naar "<%1>" leverde %2 resultaten op</translation>
</message>
<message>
<source>Help</source>
<translation>Help</translation>
</message>
<message>
<source>Refine your search</source>
<translation>Resultaat verfijnen</translation>
</message>
</context>
<context>
<name>design/ezwebin/full/article</name>
<message>
<source>Comments</source>
<translation>Reacties</translation>
</message>
<message>
<source>New comment</source>
<translation>Nieuwe reactie</translation>
</message>
<message>
<source>%login_link_startLog in%login_link_end or %create_link_startcreate a user account%create_link_end to comment.</source>
<translation>%login_link_startLog in%login_link_end of %create_link_startmaak een gebruikersaccount aan%create_link_end om te reageren.</translation>
</message>
<message>
<source>Tip a friend</source>
<translation>Tip doorsturen</translation>
</message>
<message>
<source>Related content</source>
<translation>Gerelateerde inhoud</translation>
</message>
</context>
<context>
<name>design/ezwebin/pagelayout</name>
<message>
<source>Search text:</source>
<translation>Zoekterm:</translation>
</message>
<message>
<source>Search</source>
<translation>Zoeken</translation>
</message>
</context>
<context>
<name>design/standard/content/search</name>
<message>
<source>Last day</source>
<translation>Afgelopen dag</translation>
</message>
<message>
<source>Last week</source>
<translation>Afgelopen week</translation>
</message>
<message>
<source>Last month</source>
<translation>Afgelopen maand</translation>
</message>
<message>
<source>Last three months</source>
<translation>Afgelopen drie maanden</translation>
</message>
<message>
<source>Last year</source>
<translation>Afgelopen jaar</translation>
</message>
<message>
<source>Advanced search</source>
<translation>Geavanceerd zoeken</translation>
</message>
<message>
<source>Search all the words</source>
<translation>Zoeken naar alle woorden</translation>
</message>
<message>
<source>Search the exact phrase</source>
<translation>Zoeken naar de exacte zin</translation>
</message>
<message>
<source>Search with at least one of the words</source>
<translation>Zoeken met tenminste één van de woorden</translation>
</message>
<message>
<source>Class</source>
<translation>Type</translation>
</message>
<message>
<source>Any class</source>
<translation>Alle typen</translation>
</message>
<message>
<source>Class attribute</source>
<translation>Type-attribuut</translation>
</message>
<message>
<source>Any attribute</source>
<translation>Alle attributen</translation>
</message>
<message>
<source>Update attributes</source>
<translation>Attributen actualiseren</translation>
</message>
<message>
<source>In</source>
<translation>In</translation>
</message>
<message>
<source>Any section</source>
<translation>Alle secties</translation>
</message>
<message>
<source>Published</source>
<translation>Gepubliceerd</translation>
</message>
<message>
<source>Any time</source>
<translation>Op elk gewenst moment</translation>
</message>
<message>
<source>Display per page</source>
<translation>Per pagina tonen</translation>
</message>
<message>
<source>5 items</source>
<translation>5 items</translation>
</message>
<message>
<source>10 items</source>
<translation>10 items</translation>
</message>
<message>
<source>20 items</source>
<translation>20 items</translation>
</message>
<message>
<source>30 items</source>
<translation>30 items</translation>
</message>
<message>
<source>50 items</source>
<translation>50 items</translation>
</message>
<message>
<source>Search</source>
<translation>Zoeken</translation>
</message>
<message>
<source>No results were found when searching for "%1"</source>
<translation>Geen resultaten gevonden bij het zoeken naar "<%1>"</translation>
</message>
<message>
<source>Search for "%1" returned %2 matches</source>
<translation>Het zoeken naar "<%1>" leverde %2 resultaten op</translation>
</message>
<message>
<source>Score</source>
<translation>Relevantie</translation>
</message>
<message>
<source>Name</source>
<translation>Naam</translation>
</message>
</context>
<context>
<name>extension/ezfind</name>
<message>
<source>eZFind</source>
<translation type="unfinished">eZFind</translation>
</message>
<message>
<source>Elevation</source>
<translation type="unfinished">Elevatie</translation>
</message>
<message>
<source>Remove Elevation</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>extension/ezfind/ajax-search</name>
<message>
<source>No search results...</source>
<translation>Geen zoekresultaten...</translation>
</message>
<message>
<source>Did you mean</source>
<translation>Bedoelde u</translation>
</message>
<message>
<source>Refine with facets</source>
<translation>Met facetten verfijnen</translation>
</message>
</context>
<context>
<name>extension/ezfind/backoffice_left_menu</name>
<message>
<source>eZFind</source>
<translation>eZFind</translation>
</message>
<message>
<source>Elevation</source>
<translation>Elevatie</translation>
</message>
<message>
<source>Boost</source>
<translation>Boosten</translation>
</message>
<message>
<source>Facets</source>
<translation>Facetten</translation>
</message>
</context>
<context>
<name>extension/ezfind/elevate</name>
<message>
<source>Hide preview of existing elevate configurations.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Preview existing configurations</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show preview of existing elevate configurations.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Elevation</source>
<translation type="unfinished">Elevatie</translation>
</message>
<message>
<source>Please enter a search query.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Please choose a valid object.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Missing language information.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Successful creation of the following Elevate configuration</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Details</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Successful synchronization of the local Elevate configuration with Solr's.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Synchronise Elevate configuration with Solr</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Synchronise</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Synchronise the Elevate configuration with Solr.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Elevate an object</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>"Elevating an object" for a given search query means that this object will be returned among the very first search results when a search is triggered using this search query.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Search query</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Search query to elevate the object for.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Elevate object</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Browse for the object to associate elevation to.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Elevate %objectlink with &nbsp; %searchquery &nbsp; for language:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>All</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Elevate</source>
<translation type="unfinished">Eleveren</translation>
</message>
<message>
<source>Store elevation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cancel</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cancel elevation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Search for elevated objects</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>By search query</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Language</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select a translation to narrow down the search.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Fuzzy match</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Fuzzy match on the search query.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Filter</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Find elevate configurations matching the search query entered.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>By object</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Browse</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Objects elevated by "%search_query"</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>fuzzy match</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Existing configurations</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No existing Elevate configuration.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Content object</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Actions</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>See elevate configuration details for '%objectName'</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove elevation by '%searchQuery' for '%objectName'.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>See all objects elevated by '%searchQuery'</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Trash</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Elevation detail for object %objectName</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Missing content object.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Elevate %objectName</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Elevate %objectlink with:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>for language:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Existing configurations for %objectName</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>in %selectedLanguage</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>containing '%searchQuery'</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Search query to filter the result set on.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Filter configurations by language</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Removal confirmed ( for %objectName ) :</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Confirm removal of the following Elevate configuration ( for %objectName ) :</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Back</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Confirm removal of the elevate configuration</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cancel removal of the elevate configuration</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Error while generating the configuration XML</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>An unknown error occured in updating Solr's elevate configuration.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>extension/ezfind/facets</name>
<message>
<source>Creation time</source>
<translation>Aangemaakt</translation>
</message>
<message>
<source>Clear all</source>
<translation>Alles wissen</translation>
</message>
<message>
<source>Content type</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Author</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Keywords</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Publication Year</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>extension/ezfind/popupmenu</name>
<message>
<source>eZ Find</source>
<translation>eZ Find</translation>
</message>
<message>
<source>Elevate</source>
<translation>Eleveren</translation>
</message>
<message>
<source>Elevation detail</source>
<translation>Elevatiedetails</translation>
</message>
</context>
<context>
<name>ezfind</name>
<message>
<source>Search took: %1 msecs, using </source>
<translation>Zoeken duurde %1 milliseconden met</translation>
</message>
<message>
<source>Core search time: %1 msecs</source>
<translation>Core zoektijd: %1 milliseconden</translation>
</message>
<message>
<source>N/A</source>
<translation>N/B</translation>
</message>
<message>
<source>eZ Find %version search plugin &copy; 1999-2012 eZ Systems AS, powered by Apache Solr 3.1</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| amirkoklan/hollywood | extension/ezfind/translations/dut-NL/translation.ts | TypeScript | gpl-2.0 | 25,921 |
/*****************************************************************************
* playlist_fetcher.h:
*****************************************************************************
* Copyright (C) 1999-2008 VLC authors and VideoLAN
* $Id$
*
* Authors: Samuel Hocevar <[email protected]>
* Clément Stenac <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef _PLAYLIST_FETCHER_H
#define _PLAYLIST_FETCHER_H 1
#include <vlc_input_item.h>
/**
* Fetcher opaque structure.
*
* The fetcher object will retrieve the art album data for any given input
* item in an asynchronous way.
*/
typedef struct playlist_fetcher_t playlist_fetcher_t;
/**
* This function creates the fetcher object and thread.
*/
playlist_fetcher_t *playlist_fetcher_New( vlc_object_t * );
/**
* This function enqueues the provided item to be art fetched.
*
* The input item is retained until the art fetching is done or until the
* fetcher object is destroyed.
*/
void playlist_fetcher_Push( playlist_fetcher_t *, input_item_t *,
input_item_meta_request_option_t );
/**
* This function destroys the fetcher object and thread.
*
* All pending input items will be released.
*/
void playlist_fetcher_Delete( playlist_fetcher_t * );
#endif
| qenter/vlc-android | vlc/src/playlist/fetcher.h | C | gpl-2.0 | 2,061 |
var serviceUrl = 'http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/' +
'Petroleum/KSFields/FeatureServer/';
var layer = '0';
var esrijsonFormat = new ol.format.EsriJSON();
var styleCache = {
'ABANDONED': [
new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(225, 225, 225, 255)'
}),
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 255)',
width: 0.4
})
})
],
'GAS': [
new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 0, 0, 255)'
}),
stroke: new ol.style.Stroke({
color: 'rgba(110, 110, 110, 255)',
width: 0.4
})
})
],
'OIL': [
new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(56, 168, 0, 255)'
}),
stroke: new ol.style.Stroke({
color: 'rgba(110, 110, 110, 255)',
width: 0
})
})
],
'OILGAS': [
new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(168, 112, 0, 255)'
}),
stroke: new ol.style.Stroke({
color: 'rgba(110, 110, 110, 255)',
width: 0.4
})
})
]
};
var vectorSource = new ol.source.Vector({
loader: function(extent, resolution, projection) {
var url = serviceUrl + layer + '/query/?f=json&' +
'returnGeometry=true&spatialRel=esriSpatialRelIntersects&geometry=' +
encodeURIComponent('{"xmin":' + extent[0] + ',"ymin":' +
extent[1] + ',"xmax":' + extent[2] + ',"ymax":' + extent[3] +
',"spatialReference":{"wkid":102100}}') +
'&geometryType=esriGeometryEnvelope&inSR=102100&outFields=*' +
'&outSR=102100';
$.ajax({url: url, dataType: 'jsonp', success: function(response) {
if (response.error) {
alert(response.error.message + '\n' +
response.error.details.join('\n'));
} else {
// dataProjection will be read from document
var features = esrijsonFormat.readFeatures(response, {
featureProjection: projection
});
if (features.length > 0) {
vectorSource.addFeatures(features);
}
}
}});
},
strategy: ol.loadingstrategy.tile(ol.tilegrid.createXYZ({
tileSize: 512
}))
});
var vector = new ol.layer.Vector({
source: vectorSource,
style: function(feature, resolution) {
var classify = feature.get('activeprod');
return styleCache[classify];
}
});
var attribution = new ol.Attribution({
html: 'Tiles © <a href="http://services.arcgisonline.com/ArcGIS/' +
'rest/services/World_Topo_Map/MapServer">ArcGIS</a>'
});
var raster = new ol.layer.Tile({
source: new ol.source.XYZ({
attributions: [attribution],
url: 'http://server.arcgisonline.com/ArcGIS/rest/services/' +
'World_Topo_Map/MapServer/tile/{z}/{y}/{x}'
})
});
var map = new ol.Map({
layers: [raster, vector],
target: document.getElementById('map'),
view: new ol.View({
center: ol.proj.transform([-97.6114, 38.8403], 'EPSG:4326', 'EPSG:3857'),
zoom: 7
})
});
var displayFeatureInfo = function(pixel) {
var features = [];
map.forEachFeatureAtPixel(pixel, function(feature, layer) {
features.push(feature);
});
if (features.length > 0) {
var info = [];
var i, ii;
for (i = 0, ii = features.length; i < ii; ++i) {
info.push(features[i].get('field_name'));
}
document.getElementById('info').innerHTML = info.join(', ') || '(unknown)';
map.getTarget().style.cursor = 'pointer';
} else {
document.getElementById('info').innerHTML = ' ';
map.getTarget().style.cursor = '';
}
};
map.on('pointermove', function(evt) {
if (evt.dragging) {
return;
}
var pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel);
});
map.on('click', function(evt) {
displayFeatureInfo(evt.pixel);
});
| NROER/drupal-intranet | sites/all/libraries/openlayers3/examples/vector-esri.js | JavaScript | gpl-2.0 | 3,862 |
/* Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2015 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "KalmanFilter1d.hpp"
KalmanFilter1d::KalmanFilter1d(const fixed var_x_accel)
:var_x_accel_(var_x_accel)
{
Reset();
}
KalmanFilter1d::KalmanFilter1d()
:var_x_accel_(fixed(1))
{
Reset();
}
void
KalmanFilter1d::Reset()
{
Reset(fixed(0), fixed(0));
}
void
KalmanFilter1d::Reset(const fixed x_abs_value)
{
Reset(x_abs_value, fixed(0));
}
void
KalmanFilter1d::Reset(const fixed x_abs_value, const fixed x_vel_value)
{
x_abs_ = x_abs_value;
x_vel_ = x_vel_value;
p_abs_abs_ = fixed(1.e6);
p_abs_vel_ = fixed(0);
p_vel_vel_ = var_x_accel_;
}
void
KalmanFilter1d::Update(const fixed z_abs, const fixed var_z_abs,
const fixed dt)
{
// Some abbreviated constants to make the code line up nicely:
static constexpr fixed F1 = fixed(1);
// Validity checks. TODO: more?
assert(positive(dt));
// Note: math is not optimized by hand. Let the compiler sort it out.
// Predict step.
// Update state estimate.
x_abs_ += x_vel_ * dt;
// Update state covariance. The last term mixes in acceleration noise.
const fixed dt2 = sqr(dt);
const fixed dt3 = dt * dt2;
const fixed dt4 = sqr(dt2);
p_abs_abs_ += Double(dt*p_abs_vel_) + dt2 * p_vel_vel_ + Quarter(var_x_accel_ * dt4);
p_abs_vel_ += dt * p_vel_vel_ + Half(var_x_accel_ * dt3);
p_vel_vel_ += var_x_accel_ * dt2;
// Update step.
const fixed y = z_abs - x_abs_; // Innovation.
const fixed s_inv = F1 / (p_abs_abs_ + var_z_abs); // Innovation precision.
const fixed k_abs = p_abs_abs_*s_inv; // Kalman gain
const fixed k_vel = p_abs_vel_*s_inv;
// Update state estimate.
x_abs_ += k_abs * y;
x_vel_ += k_vel * y;
// Update state covariance.
p_vel_vel_ -= p_abs_vel_*k_vel;
p_abs_vel_ -= p_abs_vel_*k_abs;
p_abs_abs_ -= p_abs_abs_*k_abs;
}
| turbhrus/XCSoar | src/Math/KalmanFilter1d.cpp | C++ | gpl-2.0 | 2,690 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Sales
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Flat sales order invoice item resource
*
* @category Mage
* @package Mage_Sales
* @author Magento Core Team <[email protected]>
*/
class Mage_Sales_Model_Mysql4_Order_Invoice_Item extends Mage_Sales_Model_Resource_Order_Invoice_Item
{
}
| keegan2149/magento | sites/default/app/code/core/Mage/Sales/Model/Mysql4/Order/Invoice/Item.php | PHP | gpl-2.0 | 1,231 |
/*
* Copyright (c) 2012-2017 The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/*
* This file was originally distributed by Qualcomm Atheros, Inc.
* under proprietary terms before Copyright ownership was assigned
* to the Linux Foundation.
*/
/*===========================================================================
@file vos_memory.c
@brief Virtual Operating System Services Memory API
===========================================================================*/
/*===========================================================================
EDIT HISTORY FOR FILE
This section contains comments describing changes made to the module.
Notice that changes are listed in reverse chronological order.
$Header:$ $DateTime: $ $Author: $
when who what, where, why
-------- --- --------------------------------------------------------
===========================================================================*/
/*---------------------------------------------------------------------------
* Include Files
* ------------------------------------------------------------------------*/
#include "vos_memory.h"
#include "vos_trace.h"
#include "vos_api.h"
#include <vmalloc.h>
#ifdef CONFIG_WCNSS_MEM_PRE_ALLOC
#include <linux/wcnss_wlan.h>
#define WCNSS_PRE_ALLOC_GET_THRESHOLD (4*1024)
#endif
#define VOS_GET_MEMORY_TIME_THRESHOLD 300
#ifdef MEMORY_DEBUG
#include "wlan_hdd_dp_utils.h"
hdd_list_t vosMemList;
static v_U8_t WLAN_MEM_HEADER[] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68 };
static v_U8_t WLAN_MEM_TAIL[] = {0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87};
static int memory_dbug_flag;
struct s_vos_mem_struct
{
hdd_list_node_t pNode;
char* fileName;
unsigned int lineNum;
unsigned int size;
v_U8_t header[8];
};
#endif
/*---------------------------------------------------------------------------
* Preprocessor Definitions and Constants
* ------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
* Type Declarations
* ------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
* Data definitions
* ------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
* External Function implementation
* ------------------------------------------------------------------------*/
#ifdef MEMORY_DEBUG
void vos_mem_init()
{
/* Initalizing the list with maximum size of 60000 */
hdd_list_init(&vosMemList, 60000);
memory_dbug_flag = 1;
return;
}
void vos_mem_clean()
{
v_SIZE_t listSize;
hdd_list_size(&vosMemList, &listSize);
if(listSize)
{
hdd_list_node_t* pNode;
VOS_STATUS vosStatus;
struct s_vos_mem_struct* memStruct;
char* prev_mleak_file = "";
unsigned int prev_mleak_lineNum = 0;
unsigned int prev_mleak_sz = 0;
unsigned int mleak_cnt = 0;
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s: List is not Empty. listSize %d ", __func__, (int)listSize);
do
{
spin_lock(&vosMemList.lock);
vosStatus = hdd_list_remove_front(&vosMemList, &pNode);
spin_unlock(&vosMemList.lock);
if(VOS_STATUS_SUCCESS == vosStatus)
{
memStruct = (struct s_vos_mem_struct*)pNode;
/* Take care to log only once multiple memory leaks from
* the same place */
if(strcmp(prev_mleak_file, memStruct->fileName) ||
(prev_mleak_lineNum != memStruct->lineNum) ||
(prev_mleak_sz != memStruct->size))
{
if(mleak_cnt != 0)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"%d Time Memory Leak@ File %s, @Line %d, size %d",
mleak_cnt, prev_mleak_file, prev_mleak_lineNum,
prev_mleak_sz);
}
prev_mleak_file = memStruct->fileName;
prev_mleak_lineNum = memStruct->lineNum;
prev_mleak_sz = memStruct->size;
mleak_cnt = 0;
}
mleak_cnt++;
kfree((v_VOID_t*)memStruct);
}
}while(vosStatus == VOS_STATUS_SUCCESS);
/* Print last memory leak from the module */
if(mleak_cnt)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"%d Time memory Leak@ File %s, @Line %d, size %d",
mleak_cnt, prev_mleak_file, prev_mleak_lineNum,
prev_mleak_sz);
}
#ifdef CONFIG_HALT_KMEMLEAK
BUG_ON(0);
#endif
}
}
void vos_mem_exit()
{
if (memory_dbug_flag)
{
vos_mem_clean();
hdd_list_destroy(&vosMemList);
}
}
v_VOID_t * vos_mem_malloc_debug( v_SIZE_t size, char* fileName, v_U32_t lineNum)
{
struct s_vos_mem_struct* memStruct;
v_VOID_t* memPtr = NULL;
v_SIZE_t new_size;
int flags = GFP_KERNEL;
unsigned long IrqFlags;
unsigned long time_before_kmalloc;
if (size > (1024*1024) || size == 0)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s: called with invalid arg %u !!!", __func__, size);
return NULL;
}
if (in_interrupt() || irqs_disabled() || in_atomic())
{
flags = GFP_ATOMIC;
}
if (!memory_dbug_flag)
{
#ifdef CONFIG_WCNSS_MEM_PRE_ALLOC
v_VOID_t* pmem;
if (size > WCNSS_PRE_ALLOC_GET_THRESHOLD)
{
pmem = wcnss_prealloc_get(size);
if (NULL != pmem)
return pmem;
}
#endif
time_before_kmalloc = vos_timer_get_system_time();
memPtr = kmalloc(size, flags);
/* If time taken by kmalloc is greater than VOS_GET_MEMORY_TIME_THRESHOLD
* msec */
if (vos_timer_get_system_time() - time_before_kmalloc >=
VOS_GET_MEMORY_TIME_THRESHOLD)
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s: kmalloc took %lu msec for size %d called from %pS at line %d",
__func__,
vos_timer_get_system_time() - time_before_kmalloc,
size, (void *)_RET_IP_, lineNum);
if ((flags != GFP_ATOMIC) && (NULL == memPtr))
{
WARN_ON(1);
vos_fatal_event_logs_req(WLAN_LOG_TYPE_FATAL,
WLAN_LOG_INDICATOR_HOST_ONLY,
WLAN_LOG_REASON_MALLOC_FAIL,
false, true);
}
return memPtr;
}
new_size = size + sizeof(struct s_vos_mem_struct) + 8;
time_before_kmalloc = vos_timer_get_system_time();
memStruct = (struct s_vos_mem_struct*)kmalloc(new_size, flags);
/* If time taken by kmalloc is greater than VOS_GET_MEMORY_TIME_THRESHOLD
* msec */
if (vos_timer_get_system_time() - time_before_kmalloc >=
VOS_GET_MEMORY_TIME_THRESHOLD)
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s: kmalloc took %lu msec for size %d called from %pS at line %d",
__func__,
vos_timer_get_system_time() - time_before_kmalloc,
size, (void *)_RET_IP_, lineNum);
if(memStruct != NULL)
{
VOS_STATUS vosStatus;
memStruct->fileName = fileName;
memStruct->lineNum = lineNum;
memStruct->size = size;
vos_mem_copy(&memStruct->header[0], &WLAN_MEM_HEADER[0], sizeof(WLAN_MEM_HEADER));
vos_mem_copy( (v_U8_t*)(memStruct + 1) + size, &WLAN_MEM_TAIL[0], sizeof(WLAN_MEM_TAIL));
spin_lock_irqsave(&vosMemList.lock, IrqFlags);
vosStatus = hdd_list_insert_front(&vosMemList, &memStruct->pNode);
spin_unlock_irqrestore(&vosMemList.lock, IrqFlags);
if(VOS_STATUS_SUCCESS != vosStatus)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s: Unable to insert node into List vosStatus %d", __func__, vosStatus);
}
memPtr = (v_VOID_t*)(memStruct + 1);
}
if ((flags != GFP_ATOMIC) && (NULL == memStruct))
{
WARN_ON(1);
vos_fatal_event_logs_req(WLAN_LOG_TYPE_FATAL,
WLAN_LOG_INDICATOR_HOST_ONLY,
WLAN_LOG_REASON_MALLOC_FAIL,
false, true);
}
return memPtr;
}
v_VOID_t vos_mem_free( v_VOID_t *ptr )
{
unsigned long IrqFlags;
if (ptr == NULL)
return;
if (!memory_dbug_flag)
{
#ifdef CONFIG_WCNSS_MEM_PRE_ALLOC
if (wcnss_prealloc_put(ptr))
return;
#endif
kfree(ptr);
}
else
{
VOS_STATUS vosStatus;
struct s_vos_mem_struct* memStruct = ((struct s_vos_mem_struct*)ptr) - 1;
spin_lock_irqsave(&vosMemList.lock, IrqFlags);
vosStatus = hdd_list_remove_node(&vosMemList, &memStruct->pNode);
spin_unlock_irqrestore(&vosMemList.lock, IrqFlags);
if(VOS_STATUS_SUCCESS == vosStatus)
{
if(0 == vos_mem_compare(memStruct->header, &WLAN_MEM_HEADER[0], sizeof(WLAN_MEM_HEADER)) )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"Memory Header is corrupted. MemInfo: Filename %s, LineNum %d",
memStruct->fileName, (int)memStruct->lineNum);
}
if(0 == vos_mem_compare( (v_U8_t*)ptr + memStruct->size, &WLAN_MEM_TAIL[0], sizeof(WLAN_MEM_TAIL ) ) )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"Memory Trailer is corrupted. MemInfo: Filename %s, LineNum %d",
memStruct->fileName, (int)memStruct->lineNum);
}
kfree((v_VOID_t*)memStruct);
}
else
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"%s: Unallocated memory (double free?)", __func__);
VOS_BUG(0);
}
}
}
#else
v_VOID_t * vos_mem_malloc( v_SIZE_t size )
{
int flags = GFP_KERNEL;
v_VOID_t* memPtr = NULL;
#ifdef CONFIG_WCNSS_MEM_PRE_ALLOC
v_VOID_t* pmem;
#endif
unsigned long time_before_kmalloc;
if (size > (1024*1024) || size == 0)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s: called with invalid arg %u !!!", __func__, size);
return NULL;
}
if (in_interrupt() || irqs_disabled() || in_atomic())
{
flags = GFP_ATOMIC;
}
#ifdef CONFIG_WCNSS_MEM_PRE_ALLOC
if(size > WCNSS_PRE_ALLOC_GET_THRESHOLD)
{
pmem = wcnss_prealloc_get(size);
if(NULL != pmem)
return pmem;
}
#endif
time_before_kmalloc = vos_timer_get_system_time();
memPtr = kmalloc(size, flags);
/* If time taken by kmalloc is greater than VOS_GET_MEMORY_TIME_THRESHOLD
* msec */
if (vos_timer_get_system_time() - time_before_kmalloc >=
VOS_GET_MEMORY_TIME_THRESHOLD)
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s: kmalloc took %lu msec for size %d from %pS",
__func__,
vos_timer_get_system_time() - time_before_kmalloc,
size, (void *)_RET_IP_);
if ((flags != GFP_ATOMIC) && (NULL == memPtr))
{
WARN_ON(1);
vos_fatal_event_logs_req(WLAN_LOG_TYPE_FATAL,
WLAN_LOG_INDICATOR_HOST_ONLY,
WLAN_LOG_REASON_MALLOC_FAIL,
false, true);
}
return memPtr;
}
v_VOID_t vos_mem_free( v_VOID_t *ptr )
{
if (ptr == NULL)
return;
#ifdef CONFIG_WCNSS_MEM_PRE_ALLOC
if(wcnss_prealloc_put(ptr))
return;
#endif
kfree(ptr);
}
#endif
v_VOID_t * vos_mem_vmalloc(v_SIZE_t size)
{
v_VOID_t* memPtr = NULL;
unsigned long time_before_vmalloc;
if (size == 0 || size >= (1024*1024))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s invalid size: %u", __func__, size);
return NULL;
}
time_before_vmalloc = vos_timer_get_system_time();
memPtr = vmalloc(size);
/* If time taken by vmalloc is greater than VOS_GET_MEMORY_TIME_THRESHOLD
* msec
*/
if (vos_timer_get_system_time() - time_before_vmalloc >=
VOS_GET_MEMORY_TIME_THRESHOLD)
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s: vmalloc took %lu msec for size %d from %pS",
__func__,
vos_timer_get_system_time() - time_before_vmalloc,
size, (void *)_RET_IP_);
return memPtr;
}
v_VOID_t vos_mem_vfree(void *addr)
{
if (addr == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s NULL address passed to free", __func__);
return;
}
vfree(addr);
return;
}
v_VOID_t vos_mem_set( v_VOID_t *ptr, v_SIZE_t numBytes, v_BYTE_t value )
{
if (ptr == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR, "%s called with NULL parameter ptr", __func__);
return;
}
memset(ptr, value, numBytes);
}
void vos_buff_to_hl_buff (tANI_U8 *buffer, int size)
{
int *val, i;
if (size % 4 != 0)
VOS_TRACE(VOS_MODULE_ID_PE,VOS_TRACE_LEVEL_ERROR,
"%s: size should be multiple of 4, size %d",
__func__, size);
val = (int *)buffer;
for (i=0; i<(size/4); i++)
*(val+i) = vos_htonl ((unsigned long)(*(val+i)));
}
v_VOID_t vos_mem_zero( v_VOID_t *ptr, v_SIZE_t numBytes )
{
if (0 == numBytes)
{
// special case where ptr can be NULL
return;
}
if (ptr == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR, "%s called with NULL parameter ptr", __func__);
return;
}
memset(ptr, 0, numBytes);
}
v_VOID_t vos_mem_copy( v_VOID_t *pDst, const v_VOID_t *pSrc, v_SIZE_t numBytes )
{
if (0 == numBytes)
{
// special case where pDst or pSrc can be NULL
return;
}
if ((pDst == NULL) || (pSrc==NULL))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s called with NULL parameter, source:%pK destination:%pK",
__func__, pSrc, pDst);
VOS_ASSERT(0);
return;
}
memcpy(pDst, pSrc, numBytes);
}
v_VOID_t vos_mem_move( v_VOID_t *pDst, const v_VOID_t *pSrc, v_SIZE_t numBytes )
{
if (0 == numBytes)
{
// special case where pDst or pSrc can be NULL
return;
}
if ((pDst == NULL) || (pSrc==NULL))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s called with NULL parameter, source:%pK destination:%pK",
__func__, pSrc, pDst);
VOS_ASSERT(0);
return;
}
memmove(pDst, pSrc, numBytes);
}
v_BOOL_t vos_mem_compare(
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,18,0))
const v_VOID_t *pMemory1,
#else
v_VOID_t *pMemory1,
#endif
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,18,0))
const v_VOID_t *pMemory2,
#else
v_VOID_t *pMemory2,
#endif
v_U32_t numBytes )
{
if (0 == numBytes)
{
// special case where pMemory1 or pMemory2 can be NULL
return VOS_TRUE;
}
if ((pMemory1 == NULL) || (pMemory2==NULL))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s called with NULL parameter, p1:%pK p2:%pK",
__func__, pMemory1, pMemory2);
VOS_ASSERT(0);
return VOS_FALSE;
}
return (memcmp(pMemory1, pMemory2, numBytes)?VOS_FALSE:VOS_TRUE);
}
v_SINT_t vos_mem_compare2( v_VOID_t *pMemory1, v_VOID_t *pMemory2, v_U32_t numBytes )
{
return( (v_SINT_t) memcmp( pMemory1, pMemory2, numBytes ) );
}
/*----------------------------------------------------------------------------
\brief vos_mem_dma_malloc() - vOSS DMA Memory Allocation
This function will dynamicallly allocate the specified number of bytes of
memory. This memory will have special attributes making it DMA friendly i.e.
it will exist in contiguous, 32-byte aligned uncached memory. A normal
vos_mem_malloc does not yield memory with these attributes.
NOTE: the special DMA friendly memory is very scarce and this API must be
used sparingly
On WM, there is nothing special about this memory. SDHC allocates the
DMA friendly buffer and copies the data into it
\param size - the number of bytes of memory to allocate.
\return Upon successful allocate, returns a non-NULL pointer to the
allocated memory. If this function is unable to allocate the amount of
memory specified (for any reason) it returns NULL.
\sa
--------------------------------------------------------------------------*/
#ifdef MEMORY_DEBUG
v_VOID_t * vos_mem_dma_malloc_debug( v_SIZE_t size, char* fileName, v_U32_t lineNum)
{
struct s_vos_mem_struct* memStruct;
v_VOID_t* memPtr = NULL;
v_SIZE_t new_size;
if (in_interrupt())
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR, "%s cannot be called from interrupt context!!!", __func__);
return NULL;
}
if (!memory_dbug_flag)
return kmalloc(size, GFP_KERNEL);
new_size = size + sizeof(struct s_vos_mem_struct) + 8;
memStruct = (struct s_vos_mem_struct*)kmalloc(new_size,GFP_KERNEL);
if(memStruct != NULL)
{
VOS_STATUS vosStatus;
memStruct->fileName = fileName;
memStruct->lineNum = lineNum;
memStruct->size = size;
vos_mem_copy(&memStruct->header[0], &WLAN_MEM_HEADER[0], sizeof(WLAN_MEM_HEADER));
vos_mem_copy( (v_U8_t*)(memStruct + 1) + size, &WLAN_MEM_TAIL[0], sizeof(WLAN_MEM_TAIL));
spin_lock(&vosMemList.lock);
vosStatus = hdd_list_insert_front(&vosMemList, &memStruct->pNode);
spin_unlock(&vosMemList.lock);
if(VOS_STATUS_SUCCESS != vosStatus)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR,
"%s: Unable to insert node into List vosStatus %d", __func__, vosStatus);
}
memPtr = (v_VOID_t*)(memStruct + 1);
}
return memPtr;
}
v_VOID_t vos_mem_dma_free( v_VOID_t *ptr )
{
if (ptr == NULL)
return;
if (memory_dbug_flag)
{
VOS_STATUS vosStatus;
struct s_vos_mem_struct* memStruct = ((struct s_vos_mem_struct*)ptr) - 1;
spin_lock(&vosMemList.lock);
vosStatus = hdd_list_remove_node(&vosMemList, &memStruct->pNode);
spin_unlock(&vosMemList.lock);
if(VOS_STATUS_SUCCESS == vosStatus)
{
if(0 == vos_mem_compare(memStruct->header, &WLAN_MEM_HEADER[0], sizeof(WLAN_MEM_HEADER)) )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"Memory Header is corrupted. MemInfo: Filename %s, LineNum %d",
memStruct->fileName, (int)memStruct->lineNum);
}
if(0 == vos_mem_compare( (v_U8_t*)ptr + memStruct->size, &WLAN_MEM_TAIL[0], sizeof(WLAN_MEM_TAIL ) ) )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_FATAL,
"Memory Trailer is corrupted. MemInfo: Filename %s, LineNum %d",
memStruct->fileName, (int)memStruct->lineNum);
}
kfree((v_VOID_t*)memStruct);
}
}
else
kfree(ptr);
}
#else
v_VOID_t* vos_mem_dma_malloc( v_SIZE_t size )
{
if (in_interrupt())
{
VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR, "%s cannot be called from interrupt context!!!", __func__);
return NULL;
}
return kmalloc(size, GFP_KERNEL);
}
/*----------------------------------------------------------------------------
\brief vos_mem_dma_free() - vOSS DMA Free Memory
This function will free special DMA friendly memory pointed to by 'ptr'.
On WM, there is nothing special about the memory being free'd. SDHC will
take care of free'ing the DMA friendly buffer
\param ptr - pointer to the starting address of the memory to be
free'd.
\return Nothing
\sa
--------------------------------------------------------------------------*/
v_VOID_t vos_mem_dma_free( v_VOID_t *ptr )
{
if (ptr == NULL)
return;
kfree(ptr);
}
#endif
| M8s-dev/kernel_htc_msm8939 | drivers/staging/prima/CORE/VOSS/src/vos_memory.c | C | gpl-2.0 | 21,342 |
/*
* gnc-tree-model-selection.c -- GtkTreeModel which supports a
* selectable column.
*
* Copyright (C) 2003 Jan Arne Petersen
* Author: Jan Arne Petersen <[email protected]>
*
* 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, contact:
*
* Free Software Foundation Voice: +1-617-542-5942
* 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652
* Boston, MA 02110-1301, USA [email protected]
*/
#include "config.h"
#include <gtk/gtk.h>
#include "gnc-tree-model-selection.h"
static void gnc_tree_model_selection_class_init (GncTreeModelSelectionClass *klass);
static void gnc_tree_model_selection_init (GncTreeModelSelection *model);
static void gnc_tree_model_selection_finalize (GObject *object);
static void gnc_tree_model_selection_tree_model_init (GtkTreeModelIface *iface);
static GtkTreeModelFlags gnc_tree_model_selection_get_flags (GtkTreeModel *tree_model);
static int gnc_tree_model_selection_get_n_columns (GtkTreeModel *tree_model);
static GType gnc_tree_model_selection_get_column_type (GtkTreeModel *tree_model,
int index);
static gboolean gnc_tree_model_selection_get_iter (GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreePath *path);
static GtkTreePath *gnc_tree_model_selection_get_path (GtkTreeModel *tree_model,
GtkTreeIter *iter);
static void gnc_tree_model_selection_get_value (GtkTreeModel *tree_model,
GtkTreeIter *iter,
int column,
GValue *value);
static gboolean gnc_tree_model_selection_iter_next (GtkTreeModel *tree_model,
GtkTreeIter *iter);
static gboolean gnc_tree_model_selection_iter_children (GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent);
static gboolean gnc_tree_model_selection_iter_has_child (GtkTreeModel *tree_model,
GtkTreeIter *iter);
static int gnc_tree_model_selection_iter_n_children (GtkTreeModel *tree_model,
GtkTreeIter *iter);
static gboolean gnc_tree_model_selection_iter_nth_child (GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent,
int n);
static gboolean gnc_tree_model_selection_iter_parent (GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *child);
static void gnc_tree_model_selection_row_changed (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
GncTreeModelSelection *selection_model);
static void gnc_tree_model_selection_row_inserted (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
GncTreeModelSelection *selection_model);
static void gnc_tree_model_selection_row_has_child_toggled (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
GncTreeModelSelection *selection_model);
static void gnc_tree_model_selection_row_deleted (GtkTreeModel *tree_model,
GtkTreePath *path,
GncTreeModelSelection *selection_model);
static void gnc_tree_model_selection_rows_reordered (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
gint *new_order,
GncTreeModelSelection *selection_model);
static void gnc_tree_model_selection_toggled (GtkCellRendererToggle *toggle,
gchar *path,
GncTreeModelSelection *model);
typedef struct GncTreeModelSelectionPrivate
{
GtkTreeModel *child_model;
GHashTable *selections;
} GncTreeModelSelectionPrivate;
#define GNC_TREE_MODEL_SELECTION_GET_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), GNC_TYPE_TREE_MODEL_SELECTION, GncTreeModelSelectionPrivate))
static GObjectClass *parent_class = NULL;
GType
gnc_tree_model_selection_get_type (void)
{
static GType gnc_tree_model_selection_type = 0;
if (gnc_tree_model_selection_type == 0)
{
static const GTypeInfo our_info =
{
sizeof (GncTreeModelSelectionClass),
NULL,
NULL,
(GClassInitFunc) gnc_tree_model_selection_class_init,
NULL,
NULL,
sizeof (GncTreeModelSelection),
0,
(GInstanceInitFunc) gnc_tree_model_selection_init
};
static const GInterfaceInfo tree_model_info =
{
(GInterfaceInitFunc) gnc_tree_model_selection_tree_model_init,
NULL,
NULL
};
gnc_tree_model_selection_type = g_type_register_static (G_TYPE_OBJECT,
"GncTreeModelSelection",
&our_info, 0);
g_type_add_interface_static (gnc_tree_model_selection_type,
GTK_TYPE_TREE_MODEL,
&tree_model_info);
}
return gnc_tree_model_selection_type;
}
static void
gnc_tree_model_selection_class_init (GncTreeModelSelectionClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
parent_class = g_type_class_peek_parent (klass);
object_class->finalize = gnc_tree_model_selection_finalize;
g_type_class_add_private(klass, sizeof(GncTreeModelSelectionPrivate));
}
static void
gnc_tree_model_selection_init (GncTreeModelSelection *model)
{
GncTreeModelSelectionPrivate *priv;
while (model->stamp == 0)
{
model->stamp = g_random_int ();
}
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
priv->selections = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
}
static void
gnc_tree_model_selection_finalize (GObject *object)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
g_return_if_fail (object != NULL);
g_return_if_fail (GNC_IS_TREE_MODEL_SELECTION (object));
model = GNC_TREE_MODEL_SELECTION (object);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
g_object_unref (priv->child_model);
g_hash_table_destroy (priv->selections);
G_OBJECT_CLASS (parent_class)->finalize (object);
}
GtkTreeModel *
gnc_tree_model_selection_new (GtkTreeModel *child_model)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
model = g_object_new (GNC_TYPE_TREE_MODEL_SELECTION, NULL);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
priv->child_model = child_model;
g_object_ref (child_model);
g_signal_connect (G_OBJECT (child_model), "row_changed",
G_CALLBACK (gnc_tree_model_selection_row_changed), model);
g_signal_connect (G_OBJECT (child_model), "row_inserted",
G_CALLBACK (gnc_tree_model_selection_row_inserted), model);
g_signal_connect (G_OBJECT (child_model), "row_has_child_toggled",
G_CALLBACK (gnc_tree_model_selection_row_has_child_toggled), model);
g_signal_connect (G_OBJECT (child_model), "row_deleted",
G_CALLBACK (gnc_tree_model_selection_row_deleted), model);
g_signal_connect (G_OBJECT (child_model), "rows_reordered",
G_CALLBACK (gnc_tree_model_selection_rows_reordered), model);
return GTK_TREE_MODEL (model);
}
void
gnc_tree_model_selection_convert_child_iter_to_iter (GncTreeModelSelection *model,
GtkTreeIter *selection_iter,
GtkTreeIter *child_iter)
{
g_return_if_fail (GNC_IS_TREE_MODEL_SELECTION (model));
g_return_if_fail (child_iter != NULL);
g_return_if_fail (selection_iter != NULL);
selection_iter->stamp = model->stamp;
selection_iter->user_data = gtk_tree_iter_copy (child_iter);
}
void
gnc_tree_model_selection_convert_iter_to_child_iter (GncTreeModelSelection *model,
GtkTreeIter *child_iter,
GtkTreeIter *selection_iter)
{
g_return_if_fail (GNC_IS_TREE_MODEL_SELECTION (model));
g_return_if_fail (selection_iter != NULL);
g_return_if_fail (GNC_TREE_MODEL_SELECTION (model)->stamp == selection_iter->stamp);
g_return_if_fail (selection_iter->user_data != NULL);
g_return_if_fail (child_iter != NULL);
child_iter->stamp = ((GtkTreeIter *) selection_iter->user_data)->stamp;
child_iter->user_data = ((GtkTreeIter *) selection_iter->user_data)->user_data;
child_iter->user_data2 = ((GtkTreeIter *) selection_iter->user_data)->user_data2;
child_iter->user_data3 = ((GtkTreeIter *) selection_iter->user_data)->user_data3;
}
void
gnc_tree_model_selection_set_selected (GncTreeModelSelection *model,
GtkTreeIter *iter,
gboolean selected)
{
GncTreeModelSelectionPrivate *priv;
gchar *path_string;
GtkTreePath *path;
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
path_string = gtk_tree_model_get_string_from_iter (GTK_TREE_MODEL (model), iter);
if (selected == (g_hash_table_lookup (priv->selections, path_string) != NULL))
{
g_free (path_string);
return;
}
if (selected)
{
g_hash_table_insert (priv->selections, g_strdup (path_string), GINT_TO_POINTER (1));
}
else
{
g_hash_table_remove (priv->selections, path_string);
}
path = gtk_tree_path_new_from_string (path_string);
gtk_tree_model_row_changed (GTK_TREE_MODEL (model), path, iter);
gtk_tree_path_free (path);
g_free (path_string);
}
static void
gnc_tree_model_selection_tree_model_init (GtkTreeModelIface *iface)
{
iface->get_flags = gnc_tree_model_selection_get_flags;
iface->get_n_columns = gnc_tree_model_selection_get_n_columns;
iface->get_column_type = gnc_tree_model_selection_get_column_type;
iface->get_iter = gnc_tree_model_selection_get_iter;
iface->get_path = gnc_tree_model_selection_get_path;
iface->get_value = gnc_tree_model_selection_get_value;
iface->iter_next = gnc_tree_model_selection_iter_next;
iface->iter_children = gnc_tree_model_selection_iter_children;
iface->iter_has_child = gnc_tree_model_selection_iter_has_child;
iface->iter_n_children = gnc_tree_model_selection_iter_n_children;
iface->iter_nth_child = gnc_tree_model_selection_iter_nth_child;
iface->iter_parent = gnc_tree_model_selection_iter_parent;
}
static GtkTreeModelFlags
gnc_tree_model_selection_get_flags (GtkTreeModel *tree_model)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), 0);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
return gtk_tree_model_get_flags (priv->child_model);
}
static int
gnc_tree_model_selection_get_n_columns (GtkTreeModel *tree_model)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), 0);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
return gtk_tree_model_get_n_columns (priv->child_model) + 1;
}
static GType
gnc_tree_model_selection_get_column_type (GtkTreeModel *tree_model,
int index)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
gint columns = gnc_tree_model_selection_get_n_columns (tree_model);
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), G_TYPE_INVALID);
g_return_val_if_fail ((index >= 0) && (index < columns), G_TYPE_INVALID);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
if (index < columns - 1)
{
return gtk_tree_model_get_column_type (priv->child_model, index);
}
else
{
return G_TYPE_BOOLEAN;
}
}
static gboolean
gnc_tree_model_selection_get_iter (GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreePath *path)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
GtkTreeIter child_iter;
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), FALSE);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
if (!gtk_tree_model_get_iter (priv->child_model, &child_iter, path))
{
return FALSE;
}
gnc_tree_model_selection_convert_child_iter_to_iter (model, iter, &child_iter);
return TRUE;
}
static GtkTreePath *
gnc_tree_model_selection_get_path (GtkTreeModel *tree_model,
GtkTreeIter *iter)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
GtkTreeIter child_iter;
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), NULL);
g_return_val_if_fail (iter != NULL, NULL);
g_return_val_if_fail (iter->stamp == GNC_TREE_MODEL_SELECTION (tree_model)->stamp, NULL);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
gnc_tree_model_selection_convert_iter_to_child_iter (model, &child_iter, iter);
return gtk_tree_model_get_path (priv->child_model, &child_iter);
}
static void
gnc_tree_model_selection_get_value (GtkTreeModel *tree_model,
GtkTreeIter *iter,
int column,
GValue *value)
{
gint columns = gnc_tree_model_selection_get_n_columns (tree_model);
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
GtkTreeIter child_iter;
gchar *path;
g_return_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model));
g_return_if_fail ((column >= 0) && (column < columns));
g_return_if_fail (iter != NULL);
g_return_if_fail (iter->stamp == GNC_TREE_MODEL_SELECTION (tree_model)->stamp);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
gnc_tree_model_selection_convert_iter_to_child_iter (model, &child_iter, iter);
if (column < columns - 1)
{
gtk_tree_model_get_value (priv->child_model, &child_iter, column, value);
}
else
{
g_value_init (value, G_TYPE_BOOLEAN);
path = gtk_tree_model_get_string_from_iter (priv->child_model, &child_iter);
g_value_set_boolean (value, g_hash_table_lookup (priv->selections, path) != NULL);
g_free (path);
}
}
static gboolean
gnc_tree_model_selection_iter_next (GtkTreeModel *tree_model,
GtkTreeIter *iter)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
GtkTreeIter child_iter;
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), FALSE);
g_return_val_if_fail (iter != NULL, FALSE);
g_return_val_if_fail (iter->stamp == GNC_TREE_MODEL_SELECTION (tree_model)->stamp, FALSE);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
gnc_tree_model_selection_convert_iter_to_child_iter (model, &child_iter, iter);
if (!gtk_tree_model_iter_next (priv->child_model, &child_iter))
{
return FALSE;
}
else
{
gnc_tree_model_selection_convert_child_iter_to_iter (model, iter, &child_iter);
return TRUE;
}
}
static gboolean
gnc_tree_model_selection_iter_children (GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
GtkTreeIter child_iter;
GtkTreeIter child_parent;
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), FALSE);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
if (parent == NULL)
{
if (!gtk_tree_model_iter_children (priv->child_model, &child_iter, NULL))
return FALSE;
}
else
{
g_return_val_if_fail (parent != NULL, FALSE);
g_return_val_if_fail (parent->stamp == model->stamp, FALSE);
gnc_tree_model_selection_convert_iter_to_child_iter (model, &child_parent, parent);
if (!gtk_tree_model_iter_children (priv->child_model, &child_iter, &child_parent))
return FALSE;
}
gnc_tree_model_selection_convert_child_iter_to_iter (model, iter, &child_iter);
return TRUE;
}
static gboolean
gnc_tree_model_selection_iter_has_child (GtkTreeModel *tree_model,
GtkTreeIter *iter)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
GtkTreeIter child_iter;
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), FALSE);
g_return_val_if_fail (iter != NULL, FALSE);
g_return_val_if_fail (iter->stamp == GNC_TREE_MODEL_SELECTION (tree_model)->stamp, FALSE);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
gnc_tree_model_selection_convert_iter_to_child_iter (model, &child_iter, iter);
return gtk_tree_model_iter_has_child (priv->child_model, &child_iter);
}
static int
gnc_tree_model_selection_iter_n_children (GtkTreeModel *tree_model,
GtkTreeIter *iter)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
GtkTreeIter child_iter;
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), 0);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
if (iter == NULL)
{
return gtk_tree_model_iter_n_children (priv->child_model, NULL);
}
else
{
g_return_val_if_fail (iter != NULL, 0);
g_return_val_if_fail (iter->stamp == model->stamp, 0);
gnc_tree_model_selection_convert_iter_to_child_iter (model, &child_iter, iter);
return gtk_tree_model_iter_n_children (priv->child_model, &child_iter);
}
}
static gboolean
gnc_tree_model_selection_iter_nth_child (GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent,
int n)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
GtkTreeIter child_iter;
GtkTreeIter child_parent;
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), FALSE);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
if (parent == NULL)
{
if (!gtk_tree_model_iter_nth_child (priv->child_model, &child_iter, NULL, n))
return FALSE;
}
else
{
g_return_val_if_fail (iter != NULL, FALSE);
g_return_val_if_fail (iter->stamp == model->stamp, FALSE);
gnc_tree_model_selection_convert_iter_to_child_iter (model, &child_parent, parent);
if (!gtk_tree_model_iter_nth_child (priv->child_model, &child_iter, &child_parent, n))
return FALSE;
}
gnc_tree_model_selection_convert_child_iter_to_iter (model, iter, &child_iter);
return TRUE;
}
static gboolean
gnc_tree_model_selection_iter_parent (GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *child)
{
GncTreeModelSelection *model;
GncTreeModelSelectionPrivate *priv;
GtkTreeIter child_child;
GtkTreeIter child_iter;
g_return_val_if_fail (GNC_IS_TREE_MODEL_SELECTION (tree_model), FALSE);
g_return_val_if_fail (child != NULL, FALSE);
g_return_val_if_fail (child->stamp == GNC_TREE_MODEL_SELECTION (tree_model)->stamp, FALSE);
model = GNC_TREE_MODEL_SELECTION (tree_model);
priv = GNC_TREE_MODEL_SELECTION_GET_PRIVATE(model);
gnc_tree_model_selection_convert_iter_to_child_iter (model, &child_child, child);
if (!gtk_tree_model_iter_parent (priv->child_model, &child_iter, &child_child))
{
return FALSE;
}
else
{
gnc_tree_model_selection_convert_child_iter_to_iter (model, iter, &child_iter);
return TRUE;
}
}
static void
gnc_tree_model_selection_row_changed (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
GncTreeModelSelection *selection_model)
{
GtkTreeIter selection_iter;
gnc_tree_model_selection_convert_child_iter_to_iter (selection_model, &selection_iter, iter);
gtk_tree_model_row_changed (GTK_TREE_MODEL (selection_model), path, &selection_iter);
}
static void
gnc_tree_model_selection_row_inserted (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
GncTreeModelSelection *selection_model)
{
GtkTreeIter selection_iter;
gnc_tree_model_selection_convert_child_iter_to_iter (selection_model, &selection_iter, iter);
gtk_tree_model_row_inserted (GTK_TREE_MODEL (selection_model), path, &selection_iter);
}
static void
gnc_tree_model_selection_row_has_child_toggled (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
GncTreeModelSelection *selection_model)
{
GtkTreeIter selection_iter;
gnc_tree_model_selection_convert_child_iter_to_iter (selection_model, &selection_iter, iter);
gtk_tree_model_row_has_child_toggled (GTK_TREE_MODEL (selection_model), path, &selection_iter);
}
static void
gnc_tree_model_selection_row_deleted (GtkTreeModel *tree_model,
GtkTreePath *path,
GncTreeModelSelection *selection_model)
{
gtk_tree_model_row_deleted (GTK_TREE_MODEL (selection_model), path);
}
static void
gnc_tree_model_selection_rows_reordered (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
gint *new_order,
GncTreeModelSelection *selection_model)
{
GtkTreeIter selection_iter;
gnc_tree_model_selection_convert_child_iter_to_iter (selection_model, &selection_iter, iter);
gtk_tree_model_rows_reordered (GTK_TREE_MODEL (selection_model), path, &selection_iter, new_order);
}
static void
gnc_tree_model_selection_toggled (GtkCellRendererToggle *toggle,
gchar *path,
GncTreeModelSelection *model)
{
GtkTreeIter iter;
if (gtk_tree_model_get_iter_from_string (GTK_TREE_MODEL (model), &iter, path))
{
gnc_tree_model_selection_set_selected (model, &iter, !gtk_cell_renderer_toggle_get_active (toggle));
}
}
| dimbeni/Gnucash | src/gnome-utils/gnc-tree-model-selection.c | C | gpl-2.0 | 23,011 |
/*
* net/sched/sch_generic.c Generic packet scheduler routines.
*
* 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.
*
* Authors: Alexey Kuznetsov, <[email protected]>
* Jamal Hadi Salim, <[email protected]> 990601
* - Ingress support
*/
#include <linux/bitops.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/rtnetlink.h>
#include <linux/init.h>
#include <linux/rcupdate.h>
#include <linux/list.h>
#include <net/pkt_sched.h>
#include <net/dst.h>
/* Main transmission queue. */
/* Modifications to data participating in scheduling must be protected with
* qdisc_lock(qdisc) spinlock.
*
* The idea is the following:
* - enqueue, dequeue are serialized via qdisc root lock
* - ingress filtering is also serialized via qdisc root lock
* - updates to tree and tree walking are only done under the rtnl mutex.
*/
static inline int dev_requeue_skb(struct sk_buff *skb, struct Qdisc *q)
{
skb_dst_force(skb);
q->gso_skb = skb;
q->qstats.requeues++;
q->q.qlen++; /* it's still part of the queue */
__netif_schedule(q);
return 0;
}
static inline struct sk_buff *dequeue_skb(struct Qdisc *q)
{
struct sk_buff *skb = q->gso_skb;
if (unlikely(skb)) {
struct net_device *dev = qdisc_dev(q);
struct netdev_queue *txq;
/* check the reason of requeuing without tx lock first */
txq = netdev_get_tx_queue(dev, skb_get_queue_mapping(skb));
if (!netif_tx_queue_stopped(txq) &&
!netif_tx_queue_frozen(txq)) {
q->gso_skb = NULL;
q->q.qlen--;
} else
skb = NULL;
} else {
skb = q->dequeue(q);
}
return skb;
}
static inline int handle_dev_cpu_collision(struct sk_buff *skb,
struct netdev_queue *dev_queue,
struct Qdisc *q)
{
int ret;
if (unlikely(dev_queue->xmit_lock_owner == smp_processor_id())) {
/*
* Same CPU holding the lock. It may be a transient
* configuration error, when hard_start_xmit() recurses. We
* detect it by checking xmit owner and drop the packet when
* deadloop is detected. Return OK to try the next skb.
*/
kfree_skb(skb);
if (net_ratelimit())
printk(KERN_WARNING "Dead loop on netdevice %s, "
"fix it urgently!\n", dev_queue->dev->name);
ret = qdisc_qlen(q);
} else {
/*
* Another cpu is holding lock, requeue & delay xmits for
* some time.
*/
__get_cpu_var(netdev_rx_stat).cpu_collision++;
ret = dev_requeue_skb(skb, q);
}
return ret;
}
/*
* Transmit one skb, and handle the return status as required. Holding the
* __QDISC_STATE_RUNNING bit guarantees that only one CPU can execute this
* function.
*
* Returns to the caller:
* 0 - queue is empty or throttled.
* >0 - queue is not empty.
*/
int sch_direct_xmit(struct sk_buff *skb, struct Qdisc *q,
struct net_device *dev, struct netdev_queue *txq,
spinlock_t *root_lock)
{
int ret = NETDEV_TX_BUSY;
/* And release qdisc */
spin_unlock(root_lock);
HARD_TX_LOCK(dev, txq, smp_processor_id());
if (!netif_tx_queue_stopped(txq) &&
!netif_tx_queue_frozen(txq))
ret = dev_hard_start_xmit(skb, dev, txq);
HARD_TX_UNLOCK(dev, txq);
spin_lock(root_lock);
switch (ret) {
case NETDEV_TX_OK:
/* Driver sent out skb successfully */
ret = qdisc_qlen(q);
break;
case NETDEV_TX_LOCKED:
/* Driver try lock failed */
ret = handle_dev_cpu_collision(skb, txq, q);
break;
default:
/* Driver returned NETDEV_TX_BUSY - requeue skb */
if (unlikely (ret != NETDEV_TX_BUSY && net_ratelimit()))
printk(KERN_WARNING "BUG %s code %d qlen %d\n",
dev->name, ret, q->q.qlen);
ret = dev_requeue_skb(skb, q);
break;
}
if (ret && (netif_tx_queue_stopped(txq) ||
netif_tx_queue_frozen(txq)))
ret = 0;
return ret;
}
/*
* NOTE: Called under qdisc_lock(q) with locally disabled BH.
*
* __QDISC_STATE_RUNNING guarantees only one CPU can process
* this qdisc at a time. qdisc_lock(q) serializes queue accesses for
* this queue.
*
* netif_tx_lock serializes accesses to device driver.
*
* qdisc_lock(q) and netif_tx_lock are mutually exclusive,
* if one is grabbed, another must be free.
*
* Note, that this procedure can be called by a watchdog timer
*
* Returns to the caller:
* 0 - queue is empty or throttled.
* >0 - queue is not empty.
*
*/
static inline int qdisc_restart(struct Qdisc *q)
{
struct netdev_queue *txq;
struct net_device *dev;
spinlock_t *root_lock;
struct sk_buff *skb;
/* Dequeue packet */
skb = dequeue_skb(q);
if (unlikely(!skb))
return 0;
WARN_ON_ONCE(skb_dst_is_noref(skb));
root_lock = qdisc_lock(q);
dev = qdisc_dev(q);
txq = netdev_get_tx_queue(dev, skb_get_queue_mapping(skb));
return sch_direct_xmit(skb, q, dev, txq, root_lock);
}
void __qdisc_run(struct Qdisc *q)
{
unsigned long start_time = jiffies;
while (qdisc_restart(q)) {
/*
* Postpone processing if
* 1. another process needs the CPU;
* 2. we've been doing it for too long.
*/
if (need_resched() || jiffies != start_time) {
__netif_schedule(q);
break;
}
}
clear_bit(__QDISC_STATE_RUNNING, &q->state);
}
unsigned long dev_trans_start(struct net_device *dev)
{
unsigned long val, res = dev->trans_start;
unsigned int i;
for (i = 0; i < dev->num_tx_queues; i++) {
val = netdev_get_tx_queue(dev, i)->trans_start;
if (val && time_after(val, res))
res = val;
}
dev->trans_start = res;
return res;
}
EXPORT_SYMBOL(dev_trans_start);
static void dev_watchdog(unsigned long arg)
{
struct net_device *dev = (struct net_device *)arg;
netif_tx_lock(dev);
if (!qdisc_tx_is_noop(dev)) {
if (netif_device_present(dev) &&
netif_running(dev) &&
netif_carrier_ok(dev)) {
int some_queue_timedout = 0;
unsigned int i;
unsigned long trans_start;
for (i = 0; i < dev->num_tx_queues; i++) {
struct netdev_queue *txq;
txq = netdev_get_tx_queue(dev, i);
/*
* old device drivers set dev->trans_start
*/
trans_start = txq->trans_start ? : dev->trans_start;
if (netif_tx_queue_stopped(txq) &&
time_after(jiffies, (trans_start +
dev->watchdog_timeo))) {
some_queue_timedout = 1;
break;
}
}
if (some_queue_timedout) {
char drivername[64];
WARN_ONCE(1, KERN_INFO "NETDEV WATCHDOG: %s (%s): transmit queue %u timed out\n",
dev->name, netdev_drivername(dev, drivername, 64), i);
dev->netdev_ops->ndo_tx_timeout(dev);
}
if (!mod_timer(&dev->watchdog_timer,
round_jiffies(jiffies +
dev->watchdog_timeo)))
dev_hold(dev);
}
}
netif_tx_unlock(dev);
dev_put(dev);
}
void __netdev_watchdog_up(struct net_device *dev)
{
if (dev->netdev_ops->ndo_tx_timeout) {
if (dev->watchdog_timeo <= 0)
dev->watchdog_timeo = 5*HZ;
if (!mod_timer(&dev->watchdog_timer,
round_jiffies(jiffies + dev->watchdog_timeo)))
dev_hold(dev);
}
}
static void dev_watchdog_up(struct net_device *dev)
{
__netdev_watchdog_up(dev);
}
static void dev_watchdog_down(struct net_device *dev)
{
netif_tx_lock_bh(dev);
if (del_timer(&dev->watchdog_timer))
dev_put(dev);
netif_tx_unlock_bh(dev);
}
/**
* netif_carrier_on - set carrier
* @dev: network device
*
* Device has detected that carrier.
*/
void netif_carrier_on(struct net_device *dev)
{
if (test_and_clear_bit(__LINK_STATE_NOCARRIER, &dev->state)) {
if (dev->reg_state == NETREG_UNINITIALIZED)
return;
linkwatch_fire_event(dev);
if (netif_running(dev))
__netdev_watchdog_up(dev);
}
}
EXPORT_SYMBOL(netif_carrier_on);
/**
* netif_carrier_off - clear carrier
* @dev: network device
*
* Device has detected loss of carrier.
*/
void netif_carrier_off(struct net_device *dev)
{
if (!test_and_set_bit(__LINK_STATE_NOCARRIER, &dev->state)) {
if (dev->reg_state == NETREG_UNINITIALIZED)
return;
linkwatch_fire_event(dev);
}
}
EXPORT_SYMBOL(netif_carrier_off);
/* "NOOP" scheduler: the best scheduler, recommended for all interfaces
under all circumstances. It is difficult to invent anything faster or
cheaper.
*/
static int noop_enqueue(struct sk_buff *skb, struct Qdisc * qdisc)
{
kfree_skb(skb);
return NET_XMIT_CN;
}
static struct sk_buff *noop_dequeue(struct Qdisc * qdisc)
{
return NULL;
}
struct Qdisc_ops noop_qdisc_ops __read_mostly = {
.id = "noop",
.priv_size = 0,
.enqueue = noop_enqueue,
.dequeue = noop_dequeue,
.peek = noop_dequeue,
.owner = THIS_MODULE,
};
static struct netdev_queue noop_netdev_queue = {
.qdisc = &noop_qdisc,
.qdisc_sleeping = &noop_qdisc,
};
struct Qdisc noop_qdisc = {
.enqueue = noop_enqueue,
.dequeue = noop_dequeue,
.flags = TCQ_F_BUILTIN,
.ops = &noop_qdisc_ops,
.list = LIST_HEAD_INIT(noop_qdisc.list),
.q.lock = __SPIN_LOCK_UNLOCKED(noop_qdisc.q.lock),
.dev_queue = &noop_netdev_queue,
};
EXPORT_SYMBOL(noop_qdisc);
static struct Qdisc_ops noqueue_qdisc_ops __read_mostly = {
.id = "noqueue",
.priv_size = 0,
.enqueue = noop_enqueue,
.dequeue = noop_dequeue,
.peek = noop_dequeue,
.owner = THIS_MODULE,
};
static struct Qdisc noqueue_qdisc;
static struct netdev_queue noqueue_netdev_queue = {
.qdisc = &noqueue_qdisc,
.qdisc_sleeping = &noqueue_qdisc,
};
static struct Qdisc noqueue_qdisc = {
.enqueue = NULL,
.dequeue = noop_dequeue,
.flags = TCQ_F_BUILTIN,
.ops = &noqueue_qdisc_ops,
.list = LIST_HEAD_INIT(noqueue_qdisc.list),
.q.lock = __SPIN_LOCK_UNLOCKED(noqueue_qdisc.q.lock),
.dev_queue = &noqueue_netdev_queue,
};
static const u8 prio2band[TC_PRIO_MAX+1] =
{ 1, 2, 2, 2, 1, 2, 0, 0 , 1, 1, 1, 1, 1, 1, 1, 1 };
/* 3-band FIFO queue: old style, but should be a bit faster than
generic prio+fifo combination.
*/
#define PFIFO_FAST_BANDS 3
/*
* Private data for a pfifo_fast scheduler containing:
* - queues for the three band
* - bitmap indicating which of the bands contain skbs
*/
struct pfifo_fast_priv {
u32 bitmap;
struct sk_buff_head q[PFIFO_FAST_BANDS];
};
/*
* Convert a bitmap to the first band number where an skb is queued, where:
* bitmap=0 means there are no skbs on any band.
* bitmap=1 means there is an skb on band 0.
* bitmap=7 means there are skbs on all 3 bands, etc.
*/
static const int bitmap2band[] = {-1, 0, 1, 0, 2, 0, 1, 0};
static inline struct sk_buff_head *band2list(struct pfifo_fast_priv *priv,
int band)
{
return priv->q + band;
}
static int pfifo_fast_enqueue(struct sk_buff *skb, struct Qdisc* qdisc)
{
if (skb_queue_len(&qdisc->q) < qdisc_dev(qdisc)->tx_queue_len) {
int band = prio2band[skb->priority & TC_PRIO_MAX];
struct pfifo_fast_priv *priv = qdisc_priv(qdisc);
struct sk_buff_head *list = band2list(priv, band);
priv->bitmap |= (1 << band);
qdisc->q.qlen++;
return __qdisc_enqueue_tail(skb, qdisc, list);
}
return qdisc_drop(skb, qdisc);
}
static struct sk_buff *pfifo_fast_dequeue(struct Qdisc* qdisc)
{
struct pfifo_fast_priv *priv = qdisc_priv(qdisc);
int band = bitmap2band[priv->bitmap];
if (likely(band >= 0)) {
struct sk_buff_head *list = band2list(priv, band);
struct sk_buff *skb = __qdisc_dequeue_head(qdisc, list);
qdisc->q.qlen--;
if (skb_queue_empty(list))
priv->bitmap &= ~(1 << band);
return skb;
}
return NULL;
}
static struct sk_buff *pfifo_fast_peek(struct Qdisc* qdisc)
{
struct pfifo_fast_priv *priv = qdisc_priv(qdisc);
int band = bitmap2band[priv->bitmap];
if (band >= 0) {
struct sk_buff_head *list = band2list(priv, band);
return skb_peek(list);
}
return NULL;
}
static void pfifo_fast_reset(struct Qdisc* qdisc)
{
int prio;
struct pfifo_fast_priv *priv = qdisc_priv(qdisc);
for (prio = 0; prio < PFIFO_FAST_BANDS; prio++)
__qdisc_reset_queue(qdisc, band2list(priv, prio));
priv->bitmap = 0;
qdisc->qstats.backlog = 0;
qdisc->q.qlen = 0;
}
static int pfifo_fast_dump(struct Qdisc *qdisc, struct sk_buff *skb)
{
struct tc_prio_qopt opt = { .bands = PFIFO_FAST_BANDS };
memcpy(&opt.priomap, prio2band, TC_PRIO_MAX+1);
NLA_PUT(skb, TCA_OPTIONS, sizeof(opt), &opt);
return skb->len;
nla_put_failure:
return -1;
}
static int pfifo_fast_init(struct Qdisc *qdisc, struct nlattr *opt)
{
int prio;
struct pfifo_fast_priv *priv = qdisc_priv(qdisc);
for (prio = 0; prio < PFIFO_FAST_BANDS; prio++)
skb_queue_head_init(band2list(priv, prio));
return 0;
}
struct Qdisc_ops pfifo_fast_ops __read_mostly = {
.id = "pfifo_fast",
.priv_size = sizeof(struct pfifo_fast_priv),
.enqueue = pfifo_fast_enqueue,
.dequeue = pfifo_fast_dequeue,
.peek = pfifo_fast_peek,
.init = pfifo_fast_init,
.reset = pfifo_fast_reset,
.dump = pfifo_fast_dump,
.owner = THIS_MODULE,
};
struct Qdisc *qdisc_alloc(struct netdev_queue *dev_queue,
struct Qdisc_ops *ops)
{
void *p;
struct Qdisc *sch;
unsigned int size;
int err = -ENOBUFS;
/* ensure that the Qdisc and the private data are 32-byte aligned */
size = QDISC_ALIGN(sizeof(*sch));
size += ops->priv_size + (QDISC_ALIGNTO - 1);
p = kzalloc(size, GFP_KERNEL);
if (!p)
goto errout;
sch = (struct Qdisc *) QDISC_ALIGN((unsigned long) p);
sch->padded = (char *) sch - (char *) p;
INIT_LIST_HEAD(&sch->list);
skb_queue_head_init(&sch->q);
sch->ops = ops;
sch->enqueue = ops->enqueue;
sch->dequeue = ops->dequeue;
sch->dev_queue = dev_queue;
dev_hold(qdisc_dev(sch));
atomic_set(&sch->refcnt, 1);
return sch;
errout:
return ERR_PTR(err);
}
struct Qdisc * qdisc_create_dflt(struct net_device *dev,
struct netdev_queue *dev_queue,
struct Qdisc_ops *ops,
unsigned int parentid)
{
struct Qdisc *sch;
sch = qdisc_alloc(dev_queue, ops);
if (IS_ERR(sch))
goto errout;
sch->parent = parentid;
if (!ops->init || ops->init(sch, NULL) == 0)
return sch;
qdisc_destroy(sch);
errout:
return NULL;
}
EXPORT_SYMBOL(qdisc_create_dflt);
/* Under qdisc_lock(qdisc) and BH! */
void qdisc_reset(struct Qdisc *qdisc)
{
const struct Qdisc_ops *ops = qdisc->ops;
if (ops->reset)
ops->reset(qdisc);
if (qdisc->gso_skb) {
kfree_skb(qdisc->gso_skb);
qdisc->gso_skb = NULL;
qdisc->q.qlen = 0;
}
}
EXPORT_SYMBOL(qdisc_reset);
void qdisc_destroy(struct Qdisc *qdisc)
{
const struct Qdisc_ops *ops = qdisc->ops;
if (qdisc->flags & TCQ_F_BUILTIN ||
!atomic_dec_and_test(&qdisc->refcnt))
return;
#ifdef CONFIG_NET_SCHED
qdisc_list_del(qdisc);
qdisc_put_stab(qdisc->stab);
#endif
gen_kill_estimator(&qdisc->bstats, &qdisc->rate_est);
if (ops->reset)
ops->reset(qdisc);
if (ops->destroy)
ops->destroy(qdisc);
module_put(ops->owner);
dev_put(qdisc_dev(qdisc));
kfree_skb(qdisc->gso_skb);
kfree((char *) qdisc - qdisc->padded);
}
EXPORT_SYMBOL(qdisc_destroy);
/* Attach toplevel qdisc to device queue. */
struct Qdisc *dev_graft_qdisc(struct netdev_queue *dev_queue,
struct Qdisc *qdisc)
{
struct Qdisc *oqdisc = dev_queue->qdisc_sleeping;
spinlock_t *root_lock;
root_lock = qdisc_lock(oqdisc);
spin_lock_bh(root_lock);
/* Prune old scheduler */
if (oqdisc && atomic_read(&oqdisc->refcnt) <= 1)
qdisc_reset(oqdisc);
/* ... and graft new one */
if (qdisc == NULL)
qdisc = &noop_qdisc;
dev_queue->qdisc_sleeping = qdisc;
rcu_assign_pointer(dev_queue->qdisc, &noop_qdisc);
spin_unlock_bh(root_lock);
return oqdisc;
}
static void attach_one_default_qdisc(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_unused)
{
struct Qdisc *qdisc;
if (dev->tx_queue_len) {
qdisc = qdisc_create_dflt(dev, dev_queue,
&pfifo_fast_ops, TC_H_ROOT);
if (!qdisc) {
printk(KERN_INFO "%s: activation failed\n", dev->name);
return;
}
/* Can by-pass the queue discipline for default qdisc */
qdisc->flags |= TCQ_F_CAN_BYPASS;
} else {
qdisc = &noqueue_qdisc;
}
dev_queue->qdisc_sleeping = qdisc;
}
static void attach_default_qdiscs(struct net_device *dev)
{
struct netdev_queue *txq;
struct Qdisc *qdisc;
txq = netdev_get_tx_queue(dev, 0);
if (!netif_is_multiqueue(dev) || dev->tx_queue_len == 0) {
netdev_for_each_tx_queue(dev, attach_one_default_qdisc, NULL);
dev->qdisc = txq->qdisc_sleeping;
atomic_inc(&dev->qdisc->refcnt);
} else {
qdisc = qdisc_create_dflt(dev, txq, &mq_qdisc_ops, TC_H_ROOT);
if (qdisc) {
qdisc->ops->attach(qdisc);
dev->qdisc = qdisc;
}
}
}
static void transition_one_qdisc(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_need_watchdog)
{
struct Qdisc *new_qdisc = dev_queue->qdisc_sleeping;
int *need_watchdog_p = _need_watchdog;
if (!(new_qdisc->flags & TCQ_F_BUILTIN))
clear_bit(__QDISC_STATE_DEACTIVATED, &new_qdisc->state);
rcu_assign_pointer(dev_queue->qdisc, new_qdisc);
if (need_watchdog_p && new_qdisc != &noqueue_qdisc) {
dev_queue->trans_start = 0;
*need_watchdog_p = 1;
}
}
void dev_activate(struct net_device *dev)
{
int need_watchdog;
/* No queueing discipline is attached to device;
create default one i.e. pfifo_fast for devices,
which need queueing and noqueue_qdisc for
virtual interfaces
*/
if (dev->qdisc == &noop_qdisc)
attach_default_qdiscs(dev);
if (!netif_carrier_ok(dev))
/* Delay activation until next carrier-on event */
return;
need_watchdog = 0;
netdev_for_each_tx_queue(dev, transition_one_qdisc, &need_watchdog);
transition_one_qdisc(dev, &dev->rx_queue, NULL);
if (need_watchdog) {
dev->trans_start = jiffies;
dev_watchdog_up(dev);
}
}
static void dev_deactivate_queue(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_qdisc_default)
{
struct Qdisc *qdisc_default = _qdisc_default;
struct Qdisc *qdisc;
qdisc = dev_queue->qdisc;
if (qdisc) {
spin_lock_bh(qdisc_lock(qdisc));
if (!(qdisc->flags & TCQ_F_BUILTIN))
set_bit(__QDISC_STATE_DEACTIVATED, &qdisc->state);
rcu_assign_pointer(dev_queue->qdisc, qdisc_default);
qdisc_reset(qdisc);
spin_unlock_bh(qdisc_lock(qdisc));
}
}
static bool some_qdisc_is_busy(struct net_device *dev)
{
unsigned int i;
for (i = 0; i < dev->num_tx_queues; i++) {
struct netdev_queue *dev_queue;
spinlock_t *root_lock;
struct Qdisc *q;
int val;
dev_queue = netdev_get_tx_queue(dev, i);
q = dev_queue->qdisc_sleeping;
root_lock = qdisc_lock(q);
spin_lock_bh(root_lock);
val = (test_bit(__QDISC_STATE_RUNNING, &q->state) ||
test_bit(__QDISC_STATE_SCHED, &q->state));
spin_unlock_bh(root_lock);
if (val)
return true;
}
return false;
}
void dev_deactivate(struct net_device *dev)
{
netdev_for_each_tx_queue(dev, dev_deactivate_queue, &noop_qdisc);
dev_deactivate_queue(dev, &dev->rx_queue, &noop_qdisc);
dev_watchdog_down(dev);
/* Wait for outstanding qdisc-less dev_queue_xmit calls. */
synchronize_rcu();
/* Wait for outstanding qdisc_run calls. */
while (some_qdisc_is_busy(dev))
yield();
}
static void dev_init_scheduler_queue(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_qdisc)
{
struct Qdisc *qdisc = _qdisc;
dev_queue->qdisc = qdisc;
dev_queue->qdisc_sleeping = qdisc;
}
void dev_init_scheduler(struct net_device *dev)
{
dev->qdisc = &noop_qdisc;
netdev_for_each_tx_queue(dev, dev_init_scheduler_queue, &noop_qdisc);
dev_init_scheduler_queue(dev, &dev->rx_queue, &noop_qdisc);
setup_timer(&dev->watchdog_timer, dev_watchdog, (unsigned long)dev);
}
static void shutdown_scheduler_queue(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_qdisc_default)
{
struct Qdisc *qdisc = dev_queue->qdisc_sleeping;
struct Qdisc *qdisc_default = _qdisc_default;
if (qdisc) {
rcu_assign_pointer(dev_queue->qdisc, qdisc_default);
dev_queue->qdisc_sleeping = qdisc_default;
qdisc_destroy(qdisc);
}
}
void dev_shutdown(struct net_device *dev)
{
netdev_for_each_tx_queue(dev, shutdown_scheduler_queue, &noop_qdisc);
shutdown_scheduler_queue(dev, &dev->rx_queue, &noop_qdisc);
qdisc_destroy(dev->qdisc);
dev->qdisc = &noop_qdisc;
WARN_ON(timer_pending(&dev->watchdog_timer));
}
| faux123/kernel-moto-atrix4g | net/sched/sch_generic.c | C | gpl-2.0 | 20,160 |
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <common.h>
#include <io.h>
#include <init.h>
#include <linux/sizes.h>
#include <mach/generic.h>
#include <mach/omap4-mux.h>
#include <mach/omap4-silicon.h>
#include <mach/omap4-generic.h>
#include <mach/omap4-clock.h>
#include <mach/syslib.h>
#include <asm/barebox-arm.h>
#include <asm/barebox-arm-head.h>
#include "mux.h"
#define TPS62361_VSEL0_GPIO 7
static const struct ddr_regs ddr_regs_400_mhz_2cs = {
.tim1 = 0x10EB0662,
.tim2 = 0x20370DD2,
.tim3 = 0x00B1C33F,
.phy_ctrl_1 = 0x849FF408,
.ref_ctrl = 0x00000618,
.config_init = 0x80000EB9,
.config_final = 0x80001AB9,
.zq_config = 0xD00B3215,
.mr1 = 0x83,
.mr2 = 0x4
};
static noinline void archosg9_init_lowlevel(void)
{
struct dpll_param core = OMAP4_CORE_DPLL_PARAM_19M2_DDR400;
struct dpll_param mpu = OMAP4_MPU_DPLL_PARAM_19M2_MPU1200;
struct dpll_param iva = OMAP4_IVA_DPLL_PARAM_19M2;
struct dpll_param per = OMAP4_PER_DPLL_PARAM_19M2;
struct dpll_param abe = OMAP4_ABE_DPLL_PARAM_19M2;
struct dpll_param usb = OMAP4_USB_DPLL_PARAM_19M2;
set_muxconf_regs();
omap4460_scale_vcores(TPS62361_VSEL0_GPIO, 1380);
/* Enable all clocks */
omap4_enable_all_clocks();
writel(CM_SYS_CLKSEL_19M2, CM_SYS_CLKSEL);
/* Configure all DPLL's at 100% OPP */
omap4_configure_mpu_dpll(&mpu);
omap4_configure_iva_dpll(&iva);
omap4_configure_per_dpll(&per);
omap4_configure_abe_dpll(&abe);
omap4_configure_usb_dpll(&usb);
omap4_ddr_init(&ddr_regs_400_mhz_2cs, &core);
}
void __naked __bare_init barebox_arm_reset_vector(uint32_t *data)
{
omap4_save_bootinfo(data);
arm_cpu_lowlevel_init();
if (get_pc() > 0x80000000)
goto out;
arm_setup_stack(0x4030d000);
archosg9_init_lowlevel();
out:
barebox_arm_entry(0x80000000, SZ_1G, NULL);
}
| zhang3/barebox | arch/arm/boards/archosg9/lowlevel.c | C | gpl-2.0 | 2,295 |
/*
* This file is part of the bayou project.
*
* Copyright (C) 2008 Advanced Micro Devices, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc.
*/
#include <libpayload.h>
#include <curses.h>
#include "bayou.h"
#define SCREEN_X 80
#define SCREEN_Y 25
static int menu_width = 0;
static struct payload *mpayloads[BAYOU_MAX_ENTRIES];
static int m_entries = 0;
static unsigned int selected = 0;
static WINDOW *menuwin, *status;
void create_menu(void)
{
int i;
for (i = 0; i < bayoucfg.n_entries; i++) {
struct payload *p = &(bayoucfg.entries[i]);
char *name;
if ((p->pentry.parent != 0) ||
(p->pentry.flags & BPT_FLAG_NOSHOW))
continue;
mpayloads[m_entries++] = p;
name = payload_get_name(p);
if (strlen(name) > menu_width)
menu_width = strlen(name);
}
menu_width += 4;
if (menu_width < 30)
menu_width = 30;
menuwin = newwin(m_entries + 3, menu_width,
(SCREEN_Y - (m_entries + 3)) / 2,
(SCREEN_X - menu_width) / 2);
}
void draw_menu(void)
{
struct payload *s;
int i;
wattrset(menuwin, COLOR_PAIR(3));
wclear(menuwin);
wborder(menuwin, ACS_VLINE, ACS_VLINE, ACS_HLINE, ACS_HLINE,
ACS_ULCORNER, ACS_URCORNER, ACS_LLCORNER, ACS_LRCORNER);
wattrset(menuwin, COLOR_PAIR(4) | A_BOLD);
mvwprintw(menuwin, 0, (menu_width - 17) / 2, " Payload Chooser ");
wattrset(menuwin, COLOR_PAIR(3));
for (i = 0; i < m_entries; i++) {
char *name = payload_get_name(mpayloads[i]);
int col = (menu_width - (2 + strlen(name))) / 2;
if (i == selected)
wattrset(menuwin, COLOR_PAIR(5) | A_BOLD);
else
wattrset(menuwin, COLOR_PAIR(3));
mvwprintw(menuwin, 2 + i, col, name);
}
s = mpayloads[selected];
wclear(status);
if (s->params[BAYOU_PARAM_DESC] != NULL) {
char buf[66];
int len = strnlen(s->params[BAYOU_PARAM_DESC], 65);
snprintf(buf, 65, s->params[BAYOU_PARAM_DESC]);
buf[65] = 0;
mvwprintw(status, 0, (80 - len) / 2, buf);
}
wrefresh(menuwin);
wrefresh(status);
}
void loop(void)
{
int key;
while (1) {
key = getch();
if (key == ERR)
continue;
if (key == KEY_DOWN)
selected = (selected + 1) % m_entries;
else if (key == KEY_UP)
selected = (selected - 1) % m_entries;
else if (key == KEY_ENTER) {
run_payload(mpayloads[selected]);
clear();
refresh();
} else
continue;
draw_menu();
}
}
void menu(void)
{
initscr();
init_pair(1, COLOR_WHITE, COLOR_RED);
init_pair(2, COLOR_BLACK, COLOR_WHITE);
init_pair(3, COLOR_BLACK, COLOR_WHITE);
init_pair(4, COLOR_CYAN, COLOR_WHITE);
init_pair(5, COLOR_WHITE, COLOR_RED);
wattrset(stdscr, COLOR_PAIR(1));
wclear(stdscr);
status = newwin(1, 80, 24, 0);
wattrset(status, COLOR_PAIR(2));
wclear(status);
refresh();
create_menu();
draw_menu();
loop();
}
| BTDC/coreboot | payloads/bayou/menu.c | C | gpl-2.0 | 3,286 |
using MediaBrowser.Controller.Persistence;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Controller.Providers
{
public interface IProviderRepository : IRepository
{
/// <summary>
/// Gets the metadata status.
/// </summary>
/// <param name="itemId">The item identifier.</param>
/// <returns>MetadataStatus.</returns>
MetadataStatus GetMetadataStatus(Guid itemId);
/// <summary>
/// Saves the metadata status.
/// </summary>
/// <param name="status">The status.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task SaveMetadataStatus(MetadataStatus status, CancellationToken cancellationToken);
/// <summary>
/// Initializes this instance.
/// </summary>
/// <returns>Task.</returns>
Task Initialize();
}
}
| TomGillen/MediaBrowser | MediaBrowser.Controller/Providers/IProviderRepository.cs | C# | gpl-2.0 | 1,004 |
/*
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2014, SAP AG. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef OS_CPU_AIX_OJDKPPC_VM_ATOMIC_AIX_PPC_INLINE_HPP
#define OS_CPU_AIX_OJDKPPC_VM_ATOMIC_AIX_PPC_INLINE_HPP
#include "runtime/atomic.hpp"
#include "runtime/os.hpp"
#ifndef _LP64
#error "Atomic currently only impleneted for PPC64"
#endif
// Implementation of class atomic
inline void Atomic::store (jbyte store_value, jbyte* dest) { *dest = store_value; }
inline void Atomic::store (jshort store_value, jshort* dest) { *dest = store_value; }
inline void Atomic::store (jint store_value, jint* dest) { *dest = store_value; }
inline void Atomic::store (jlong store_value, jlong* dest) { *dest = store_value; }
inline void Atomic::store_ptr(intptr_t store_value, intptr_t* dest) { *dest = store_value; }
inline void Atomic::store_ptr(void* store_value, void* dest) { *(void**)dest = store_value; }
inline void Atomic::store (jbyte store_value, volatile jbyte* dest) { *dest = store_value; }
inline void Atomic::store (jshort store_value, volatile jshort* dest) { *dest = store_value; }
inline void Atomic::store (jint store_value, volatile jint* dest) { *dest = store_value; }
inline void Atomic::store (jlong store_value, volatile jlong* dest) { *dest = store_value; }
inline void Atomic::store_ptr(intptr_t store_value, volatile intptr_t* dest) { *dest = store_value; }
inline void Atomic::store_ptr(void* store_value, volatile void* dest) { *(void* volatile *)dest = store_value; }
inline jlong Atomic::load(volatile jlong* src) { return *src; }
//
// machine barrier instructions:
//
// - ppc_sync two-way memory barrier, aka fence
// - ppc_lwsync orders Store|Store,
// Load|Store,
// Load|Load,
// but not Store|Load
// - ppc_eieio orders memory accesses for device memory (only)
// - ppc_isync invalidates speculatively executed instructions
// From the POWER ISA 2.06 documentation:
// "[...] an isync instruction prevents the execution of
// instructions following the isync until instructions
// preceding the isync have completed, [...]"
// From IBM's AIX assembler reference:
// "The isync [...] instructions causes the processor to
// refetch any instructions that might have been fetched
// prior to the isync instruction. The instruction isync
// causes the processor to wait for all previous instructions
// to complete. Then any instructions already fetched are
// discarded and instruction processing continues in the
// environment established by the previous instructions."
//
// semantic barrier instructions:
// (as defined in orderAccess.hpp)
//
// - ppc_release orders Store|Store, (maps to ppc_lwsync)
// Load|Store
// - ppc_acquire orders Load|Store, (maps to ppc_lwsync)
// Load|Load
// - ppc_fence orders Store|Store, (maps to ppc_sync)
// Load|Store,
// Load|Load,
// Store|Load
//
#define strasm_sync "\n sync \n"
#define strasm_lwsync "\n lwsync \n"
#define strasm_isync "\n isync \n"
#define strasm_release strasm_lwsync
#define strasm_acquire strasm_lwsync
#define strasm_fence strasm_sync
#define strasm_nobarrier ""
#define strasm_nobarrier_clobber_memory ""
inline jint Atomic::add (jint add_value, volatile jint* dest) {
unsigned int result;
__asm__ __volatile__ (
strasm_lwsync
"1: lwarx %0, 0, %2 \n"
" add %0, %0, %1 \n"
" stwcx. %0, 0, %2 \n"
" bne- 1b \n"
strasm_isync
: /*%0*/"=&r" (result)
: /*%1*/"r" (add_value), /*%2*/"r" (dest)
: "cc", "memory" );
return (jint) result;
}
inline intptr_t Atomic::add_ptr(intptr_t add_value, volatile intptr_t* dest) {
long result;
__asm__ __volatile__ (
strasm_lwsync
"1: ldarx %0, 0, %2 \n"
" add %0, %0, %1 \n"
" stdcx. %0, 0, %2 \n"
" bne- 1b \n"
strasm_isync
: /*%0*/"=&r" (result)
: /*%1*/"r" (add_value), /*%2*/"r" (dest)
: "cc", "memory" );
return (intptr_t) result;
}
inline void* Atomic::add_ptr(intptr_t add_value, volatile void* dest) {
return (void*)add_ptr(add_value, (volatile intptr_t*)dest);
}
inline void Atomic::inc (volatile jint* dest) {
unsigned int temp;
__asm__ __volatile__ (
strasm_nobarrier
"1: lwarx %0, 0, %2 \n"
" addic %0, %0, 1 \n"
" stwcx. %0, 0, %2 \n"
" bne- 1b \n"
strasm_nobarrier
: /*%0*/"=&r" (temp), "=m" (*dest)
: /*%2*/"r" (dest), "m" (*dest)
: "cc" strasm_nobarrier_clobber_memory);
}
inline void Atomic::inc_ptr(volatile intptr_t* dest) {
long temp;
__asm__ __volatile__ (
strasm_nobarrier
"1: ldarx %0, 0, %2 \n"
" addic %0, %0, 1 \n"
" stdcx. %0, 0, %2 \n"
" bne- 1b \n"
strasm_nobarrier
: /*%0*/"=&r" (temp), "=m" (*dest)
: /*%2*/"r" (dest), "m" (*dest)
: "cc" strasm_nobarrier_clobber_memory);
}
inline void Atomic::inc_ptr(volatile void* dest) {
inc_ptr((volatile intptr_t*)dest);
}
inline void Atomic::dec (volatile jint* dest) {
unsigned int temp;
__asm__ __volatile__ (
strasm_nobarrier
"1: lwarx %0, 0, %2 \n"
" addic %0, %0, -1 \n"
" stwcx. %0, 0, %2 \n"
" bne- 1b \n"
strasm_nobarrier
: /*%0*/"=&r" (temp), "=m" (*dest)
: /*%2*/"r" (dest), "m" (*dest)
: "cc" strasm_nobarrier_clobber_memory);
}
inline void Atomic::dec_ptr(volatile intptr_t* dest) {
long temp;
__asm__ __volatile__ (
strasm_nobarrier
"1: ldarx %0, 0, %2 \n"
" addic %0, %0, -1 \n"
" stdcx. %0, 0, %2 \n"
" bne- 1b \n"
strasm_nobarrier
: /*%0*/"=&r" (temp), "=m" (*dest)
: /*%2*/"r" (dest), "m" (*dest)
: "cc" strasm_nobarrier_clobber_memory);
}
inline void Atomic::dec_ptr(volatile void* dest) {
dec_ptr((volatile intptr_t*)dest);
}
inline jint Atomic::xchg(jint exchange_value, volatile jint* dest) {
// Note that xchg_ptr doesn't necessarily do an acquire
// (see synchronizer.cpp).
unsigned int old_value;
const uint64_t zero = 0;
__asm__ __volatile__ (
/* lwsync */
strasm_lwsync
/* atomic loop */
"1: \n"
" lwarx %[old_value], %[dest], %[zero] \n"
" stwcx. %[exchange_value], %[dest], %[zero] \n"
" bne- 1b \n"
/* isync */
strasm_sync
/* exit */
"2: \n"
/* out */
: [old_value] "=&r" (old_value),
"=m" (*dest)
/* in */
: [dest] "b" (dest),
[zero] "r" (zero),
[exchange_value] "r" (exchange_value),
"m" (*dest)
/* clobber */
: "cc",
"memory"
);
return (jint) old_value;
}
inline intptr_t Atomic::xchg_ptr(intptr_t exchange_value, volatile intptr_t* dest) {
// Note that xchg_ptr doesn't necessarily do an acquire
// (see synchronizer.cpp).
long old_value;
const uint64_t zero = 0;
__asm__ __volatile__ (
/* lwsync */
strasm_lwsync
/* atomic loop */
"1: \n"
" ldarx %[old_value], %[dest], %[zero] \n"
" stdcx. %[exchange_value], %[dest], %[zero] \n"
" bne- 1b \n"
/* isync */
strasm_sync
/* exit */
"2: \n"
/* out */
: [old_value] "=&r" (old_value),
"=m" (*dest)
/* in */
: [dest] "b" (dest),
[zero] "r" (zero),
[exchange_value] "r" (exchange_value),
"m" (*dest)
/* clobber */
: "cc",
"memory"
);
return (intptr_t) old_value;
}
inline void* Atomic::xchg_ptr(void* exchange_value, volatile void* dest) {
return (void*)xchg_ptr((intptr_t)exchange_value, (volatile intptr_t*)dest);
}
inline jint Atomic::cmpxchg(jint exchange_value, volatile jint* dest, jint compare_value) {
// Note that cmpxchg guarantees a two-way memory barrier across
// the cmpxchg, so it's really a a 'fence_cmpxchg_acquire'
// (see atomic.hpp).
unsigned int old_value;
const uint64_t zero = 0;
__asm__ __volatile__ (
/* fence */
strasm_sync
/* simple guard */
" lwz %[old_value], 0(%[dest]) \n"
" cmpw %[compare_value], %[old_value] \n"
" bne- 2f \n"
/* atomic loop */
"1: \n"
" lwarx %[old_value], %[dest], %[zero] \n"
" cmpw %[compare_value], %[old_value] \n"
" bne- 2f \n"
" stwcx. %[exchange_value], %[dest], %[zero] \n"
" bne- 1b \n"
/* acquire */
strasm_sync
/* exit */
"2: \n"
/* out */
: [old_value] "=&r" (old_value),
"=m" (*dest)
/* in */
: [dest] "b" (dest),
[zero] "r" (zero),
[compare_value] "r" (compare_value),
[exchange_value] "r" (exchange_value),
"m" (*dest)
/* clobber */
: "cc",
"memory"
);
return (jint) old_value;
}
inline jlong Atomic::cmpxchg(jlong exchange_value, volatile jlong* dest, jlong compare_value) {
// Note that cmpxchg guarantees a two-way memory barrier across
// the cmpxchg, so it's really a a 'fence_cmpxchg_acquire'
// (see atomic.hpp).
long old_value;
const uint64_t zero = 0;
__asm__ __volatile__ (
/* fence */
strasm_sync
/* simple guard */
" ld %[old_value], 0(%[dest]) \n"
" cmpd %[compare_value], %[old_value] \n"
" bne- 2f \n"
/* atomic loop */
"1: \n"
" ldarx %[old_value], %[dest], %[zero] \n"
" cmpd %[compare_value], %[old_value] \n"
" bne- 2f \n"
" stdcx. %[exchange_value], %[dest], %[zero] \n"
" bne- 1b \n"
/* acquire */
strasm_sync
/* exit */
"2: \n"
/* out */
: [old_value] "=&r" (old_value),
"=m" (*dest)
/* in */
: [dest] "b" (dest),
[zero] "r" (zero),
[compare_value] "r" (compare_value),
[exchange_value] "r" (exchange_value),
"m" (*dest)
/* clobber */
: "cc",
"memory"
);
return (jlong) old_value;
}
inline intptr_t Atomic::cmpxchg_ptr(intptr_t exchange_value, volatile intptr_t* dest, intptr_t compare_value) {
return (intptr_t)cmpxchg((jlong)exchange_value, (volatile jlong*)dest, (jlong)compare_value);
}
inline void* Atomic::cmpxchg_ptr(void* exchange_value, volatile void* dest, void* compare_value) {
return (void*)cmpxchg((jlong)exchange_value, (volatile jlong*)dest, (jlong)compare_value);
}
#undef strasm_sync
#undef strasm_lwsync
#undef strasm_isync
#undef strasm_release
#undef strasm_acquire
#undef strasm_fence
#undef strasm_nobarrier
#undef strasm_nobarrier_clobber_memory
#endif // OS_CPU_AIX_OJDKPPC_VM_ATOMIC_AIX_PPC_INLINE_HPP
| benbenolson/hotspot_9_mc | src/os_cpu/aix_ppc/vm/atomic_aix_ppc.inline.hpp | C++ | gpl-2.0 | 13,545 |
/* APPLE LOCAL file CW asm blocks */
/* Test function calls in asm functions. */
/* { dg-do run { target powerpc*-*-darwin* } } */
/* { dg-options "-fasm-blocks -O2" } */
/* { dg-require-effective-target ilp32 } */
void abort(void);
int glob = 0;
int other ();
int stubfn ();
int localfn () { return other (); }
asm void foo(int arg)
{
nofralloc
mflr r0
stmw r30,-8(r1)
stw r0,8(r1)
stwu r1,-80(r1)
bl stubfn
/* bl L_stubfn$stub */
lwz r0,88(r1)
addi r1,r1,80
mtlr r0
lmw r30,-8(r1)
b localfn
}
void bar (int arg)
{
stubfn ();
localfn ();
}
int stubfn () { return other(); }
int other () { return ++glob; }
int main ()
{
bar(34);
foo(92);
if (glob != 4)
abort ();
return 0;
}
| aosm/llvmgcc42 | gcc/testsuite/gcc.apple/asm-function-5.c | C | gpl-2.0 | 729 |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_yuv_sw_c_h_
#define SDL_yuv_sw_c_h_
#include "../SDL_internal.h"
#include "SDL_video.h"
/* This is the software implementation of the YUV texture support */
struct SDL_SW_YUVTexture
{
Uint32 format;
Uint32 target_format;
int w, h;
Uint8 *pixels;
/* These are just so we don't have to allocate them separately */
Uint16 pitches[3];
Uint8 *planes[3];
/* This is a temporary surface in case we have to stretch copy */
SDL_Surface *stretch;
SDL_Surface *display;
};
typedef struct SDL_SW_YUVTexture SDL_SW_YUVTexture;
SDL_SW_YUVTexture *SDL_SW_CreateYUVTexture(Uint32 format, int w, int h);
int SDL_SW_QueryYUVTexturePixels(SDL_SW_YUVTexture * swdata, void **pixels,
int *pitch);
int SDL_SW_UpdateYUVTexture(SDL_SW_YUVTexture * swdata, const SDL_Rect * rect,
const void *pixels, int pitch);
int SDL_SW_UpdateYUVTexturePlanar(SDL_SW_YUVTexture * swdata, const SDL_Rect * rect,
const Uint8 *Yplane, int Ypitch,
const Uint8 *Uplane, int Upitch,
const Uint8 *Vplane, int Vpitch);
int SDL_SW_LockYUVTexture(SDL_SW_YUVTexture * swdata, const SDL_Rect * rect,
void **pixels, int *pitch);
void SDL_SW_UnlockYUVTexture(SDL_SW_YUVTexture * swdata);
int SDL_SW_CopyYUVToRGB(SDL_SW_YUVTexture * swdata, const SDL_Rect * srcrect,
Uint32 target_format, int w, int h, void *pixels,
int pitch);
void SDL_SW_DestroyYUVTexture(SDL_SW_YUVTexture * swdata);
/* FIXME: This breaks on various versions of GCC and should be rewritten using intrinsics */
#if 0 /* (__GNUC__ > 2) && defined(__i386__) && __OPTIMIZE__ && SDL_ASSEMBLY_ROUTINES && !defined(__clang__) */
#define USE_MMX_ASSEMBLY 1
#endif
#endif /* SDL_yuv_sw_c_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| joncampbell123/dosbox-rewrite | vs2015/sdl2/src/render/SDL_yuv_sw_c.h | C | gpl-2.0 | 2,877 |
/*
* (C) Copyright 2002
* Wolfgang Denk, DENX Software Engineering, [email protected].
*
* See file CREDITS for list of people who contributed to this
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* I2C test
*
* For verifying the I2C bus, a full I2C bus scanning is performed.
*
* #ifdef CONFIG_SYS_POST_I2C_ADDRS
* The test is considered as passed if all the devices and only the devices
* in the list are found.
* #ifdef CONFIG_SYS_POST_I2C_IGNORES
* Ignore devices listed in CONFIG_SYS_POST_I2C_IGNORES. These devices
* are optional or not vital to board functionality.
* #endif
* #else [ ! CONFIG_SYS_POST_I2C_ADDRS ]
* The test is considered as passed if any I2C device is found.
* #endif
*/
#include <common.h>
#include <post.h>
#include <i2c.h>
#if CONFIG_POST & CONFIG_SYS_POST_I2C
#ifdef CONFIG_POST_AML
#include <aml_i2c.h>
extern struct aml_i2c_device aml_i2c_devices;
//=============================================================================
static int i2c_xfer(unsigned int addr)
{
unsigned char cmd = 0x0;
struct i2c_msg msgs[] = {
{
.addr = addr,
.flags = 0,
.len = 1,
.buf = &cmd,
}
};
if(aml_i2c_xfer(msgs, 1) < 0)
return -1;
return 0;
}
//=============================================================================
int i2c_post_test(int flags)
{
int i, ret;
struct i2c_board_info *ptests = aml_i2c_devices.aml_i2c_boards;
struct i2c_board_info *ptest = NULL;
int num = aml_i2c_devices.dev_num;
ret = 0;
for(i=0; i<num; i++){
ptest = ptests+i;
if(ptest->device_init)
ptest->device_init();
if(i2c_xfer(ptest->addr) < 0){
post_log("<%d>%s:%d: I2C[board: %s addr: 0x%x]: test fail.\n", SYSTEST_INFO_L2, __FUNCTION__, __LINE__, ptest->type, ptest->addr);
ret = -1;
}
else{
post_log("<%d>%s:%d: I2C[board: %s addr: 0x%x]: test pass.\n", SYSTEST_INFO_L2, __FUNCTION__, __LINE__, ptest->type, ptest->addr);
}
if(ptest->device_uninit)
ptest->device_uninit();
}
return ret;
}
//=============================================================================
#else
static int i2c_ignore_device(unsigned int chip)
{
#ifdef CONFIG_SYS_POST_I2C_IGNORES
const unsigned char i2c_ignore_list[] = CONFIG_SYS_POST_I2C_IGNORES;
int i;
for (i = 0; i < sizeof(i2c_ignore_list); i++)
if (i2c_ignore_list[i] == chip)
return 1;
#endif
return 0;
}
int i2c_post_test (int flags)
{
unsigned int i;
#ifndef CONFIG_SYS_POST_I2C_ADDRS
/* Start at address 1, address 0 is the general call address */
for (i = 1; i < 128; i++) {
if (i2c_ignore_device(i))
continue;
if (i2c_probe (i) == 0)
return 0;
}
/* No devices found */
return -1;
#else
unsigned int ret = 0;
int j;
unsigned char i2c_addr_list[] = CONFIG_SYS_POST_I2C_ADDRS;
/* Start at address 1, address 0 is the general call address */
for (i = 1; i < 128; i++) {
if (i2c_ignore_device(i))
continue;
if (i2c_probe(i) != 0)
continue;
for (j = 0; j < sizeof(i2c_addr_list); ++j) {
if (i == i2c_addr_list[j]) {
i2c_addr_list[j] = 0xff;
break;
}
}
if (j == sizeof(i2c_addr_list)) {
ret = -1;
post_log("I2C: addr %02x not expected\n", i);
}
}
for (i = 0; i < sizeof(i2c_addr_list); ++i) {
if (i2c_addr_list[i] == 0xff)
continue;
post_log("I2C: addr %02x did not respond\n", i2c_addr_list[i]);
ret = -1;
}
return ret;
#endif
}
#endif /*CONFIG_POST_AML*/
#endif /* CONFIG_POST & CONFIG_SYS_POST_I2C */
| InternetBowser/plutos | u-boot-s805/post/drivers/i2c.c | C | gpl-2.0 | 4,200 |
/* ______ ___ ___
* /\ _ \ /\_ \ /\_ \
* \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___
* \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\
* \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \
* \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
* \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
* /\____/
* \_/__/
*
* DirectDraw video mode setting.
*
* By Stefan Schimanski.
*
* Unified setup code and refresh rate support by Eric Botcazou.
*
* Graphics mode list fetching code by Henrik Stokseth.
*
* See readme.txt for copyright information.
*/
#include "wddraw.h"
#define PREFIX_I "al-wddmode INFO: "
#define PREFIX_W "al-wddmode WARNING: "
#define PREFIX_E "al-wddmode ERROR: "
int _win_desktop_depth;
RGB_MAP _win_desktop_rgb_map; /* for 8-bit desktops */
int mode_supported;
static int pixel_realdepth[] = {8, 15, 15, 16, 16, 24, 24, 32, 32, 0};
static DDPIXELFORMAT pixel_format[] = {
/* 8-bit */
{sizeof(DDPIXELFORMAT), DDPF_RGB | DDPF_PALETTEINDEXED8, 0, {8}, {0}, {0}, {0}, {0}},
/* 16-bit RGB 5:5:5 */
{sizeof(DDPIXELFORMAT), DDPF_RGB, 0, {16}, {0x7C00}, {0x03e0}, {0x001F}, {0}},
/* 16-bit BGR 5:5:5 */
{sizeof(DDPIXELFORMAT), DDPF_RGB, 0, {16}, {0x001F}, {0x03e0}, {0x7C00}, {0}},
/* 16-bit RGB 5:6:5 */
{sizeof(DDPIXELFORMAT), DDPF_RGB, 0, {16}, {0xF800}, {0x07e0}, {0x001F}, {0}},
/* 16-bit BGR 5:6:5 */
{sizeof(DDPIXELFORMAT), DDPF_RGB, 0, {16}, {0x001F}, {0x07e0}, {0xF800}, {0}},
/* 24-bit RGB */
{sizeof(DDPIXELFORMAT), DDPF_RGB, 0, {24}, {0xFF0000}, {0x00FF00}, {0x0000FF}, {0}},
/* 24-bit BGR */
{sizeof(DDPIXELFORMAT), DDPF_RGB, 0, {24}, {0x0000FF}, {0x00FF00}, {0xFF0000}, {0}},
/* 32-bit RGB */
{sizeof(DDPIXELFORMAT), DDPF_RGB, 0, {32}, {0xFF0000}, {0x00FF00}, {0x0000FF}, {0}},
/* 32-bit BGR */
{sizeof(DDPIXELFORMAT), DDPF_RGB, 0, {32}, {0x0000FF}, {0x00FF00}, {0xFF0000}, {0}}
};
/* window thread callback parameters */
static int _wnd_width, _wnd_height, _wnd_depth, _wnd_refresh_rate, _wnd_flags;
/* wnd_set_video_mode:
* Called by window thread to set a gfx mode; this is needed because DirectDraw can only
* change the mode in the thread that handles the window.
*/
static int wnd_set_video_mode(void)
{
HRESULT hr;
HWND allegro_wnd = win_get_window();
/* set the cooperative level to allow fullscreen access */
hr = IDirectDraw2_SetCooperativeLevel(directdraw, allegro_wnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
if (FAILED(hr)) {
_TRACE(PREFIX_E "SetCooperativeLevel() failed (%x)\n", hr);
return -1;
}
/* switch to fullscreen mode */
hr = IDirectDraw2_SetDisplayMode(directdraw, _wnd_width, _wnd_height, _wnd_depth,
_wnd_refresh_rate, _wnd_flags);
if (FAILED(hr)) {
_TRACE(PREFIX_E "SetDisplayMode(%u, %u, %u, %u, %u) failed (%x)\n", _wnd_width, _wnd_height, _wnd_depth,
_wnd_refresh_rate, _wnd_flags, hr);
return -1;
}
return 0;
}
/* shift_gamma:
* Helper function for changing a 8-bit gamma value into
* a fake 6-bit gamma value (shifted 5-bit gamma value).
*/
static INLINE int shift_gamma(int gamma)
{
if (gamma<128)
return (gamma+7)>>2;
else
return (gamma-7)>>2;
}
/* build_desktop_rgb_map:
* Builds the RGB map corresponding to the desktop palette.
*/
void build_desktop_rgb_map(void)
{
PALETTE pal;
PALETTEENTRY system_palette[PAL_SIZE];
HDC dc;
int i;
/* retrieve Windows system palette */
dc = GetDC(NULL);
GetSystemPaletteEntries(dc, 0, PAL_SIZE, system_palette);
ReleaseDC(NULL, dc);
for (i=0; i<PAL_SIZE; i++) {
pal[i].r = shift_gamma(system_palette[i].peRed);
pal[i].g = shift_gamma(system_palette[i].peGreen);
pal[i].b = shift_gamma(system_palette[i].peBlue);
}
create_rgb_table(&_win_desktop_rgb_map, pal, NULL);
/* create_rgb_table() never maps RGB triplets to index 0 */
_win_desktop_rgb_map.data[pal[0].r>>1][pal[0].g>>1][pal[0].b>>1] = 0;
}
/* get_color_shift:
* Returns shift value for color mask.
*/
static int get_color_shift(int mask)
{
int n;
for (n = 0; ((mask & 1) == 0) && (mask != 0); n++)
mask >>= 1;
return n;
}
/* get_color_bits:
* Returns used bits in color mask.
*/
static int get_color_bits(int mask)
{
int n;
int num = 0;
for (n = 0; n < 32; n++) {
num += (mask & 1);
mask >>= 1;
}
return num;
}
/* gfx_directx_compare_color_depth:
* Compares the requested color depth with the desktop depth and find
* the best pixel format for color conversion if they don't match.
* Returns 0 if the depths match, -1 if they don't.
*/
int gfx_directx_compare_color_depth(int color_depth)
{
DDSURFACEDESC surf_desc;
HRESULT hr;
int i;
/* get current video mode */
surf_desc.dwSize = sizeof(surf_desc);
hr = IDirectDraw2_GetDisplayMode(directdraw, &surf_desc);
if (FAILED(hr)) {
_TRACE(PREFIX_E "Can't get color format.\n");
return -1;
}
/* get the *real* color depth of the desktop */
_win_desktop_depth = surf_desc.ddpfPixelFormat.dwRGBBitCount;
if (_win_desktop_depth == 16) /* sure? */
_win_desktop_depth = get_color_bits(surf_desc.ddpfPixelFormat.dwRBitMask) +
get_color_bits(surf_desc.ddpfPixelFormat.dwGBitMask) +
get_color_bits(surf_desc.ddpfPixelFormat.dwBBitMask);
if (color_depth == _win_desktop_depth) {
ddpixel_format = NULL;
return 0;
}
else {
/* test for the same depth and RGB order */
for (i=0 ; pixel_realdepth[i] ; i++) {
if ((pixel_realdepth[i] == color_depth) &&
((surf_desc.ddpfPixelFormat.dwRBitMask & pixel_format[i].dwRBitMask) ||
(surf_desc.ddpfPixelFormat.dwBBitMask & pixel_format[i].dwBBitMask) ||
(_win_desktop_depth == 8) || (color_depth == 8))) {
ddpixel_format = &pixel_format[i];
break;
}
}
return -1;
}
}
/* gfx_directx_update_color_format:
* Sets the _rgb* variables for correct color format.
*/
int gfx_directx_update_color_format(DDRAW_SURFACE *surf, int color_depth)
{
DDPIXELFORMAT pixel_format;
HRESULT hr;
int shift_r, shift_g, shift_b;
/* get pixel format */
pixel_format.dwSize = sizeof(DDPIXELFORMAT);
hr = IDirectDrawSurface2_GetPixelFormat(surf->id, &pixel_format);
if (FAILED(hr)) {
_TRACE(PREFIX_E "Can't get color format.\n");
return -1;
}
/* pass color format */
shift_r = get_color_shift(pixel_format.dwRBitMask);
shift_g = get_color_shift(pixel_format.dwGBitMask);
shift_b = get_color_shift(pixel_format.dwBBitMask);
/* set correct shift values */
switch (color_depth) {
case 15:
_rgb_r_shift_15 = shift_r;
_rgb_g_shift_15 = shift_g;
_rgb_b_shift_15 = shift_b;
break;
case 16:
_rgb_r_shift_16 = shift_r;
_rgb_g_shift_16 = shift_g;
_rgb_b_shift_16 = shift_b;
break;
case 24:
_rgb_r_shift_24 = shift_r;
_rgb_g_shift_24 = shift_g;
_rgb_b_shift_24 = shift_b;
break;
case 32:
_rgb_r_shift_32 = shift_r;
_rgb_g_shift_32 = shift_g;
_rgb_b_shift_32 = shift_b;
break;
}
return 0;
}
/* EnumModesCallback:
* Callback function for enumerating the graphics modes.
*/
static HRESULT CALLBACK EnumModesCallback(LPDDSURFACEDESC lpDDSurfaceDesc, LPVOID gfx_mode_list_ptr)
{
GFX_MODE_LIST *gfx_mode_list = (GFX_MODE_LIST *)gfx_mode_list_ptr;
/* build gfx mode-list */
gfx_mode_list->mode = _al_sane_realloc(gfx_mode_list->mode, sizeof(GFX_MODE) * (gfx_mode_list->num_modes + 1));
if (!gfx_mode_list->mode)
return DDENUMRET_CANCEL;
gfx_mode_list->mode[gfx_mode_list->num_modes].width = lpDDSurfaceDesc->dwWidth;
gfx_mode_list->mode[gfx_mode_list->num_modes].height = lpDDSurfaceDesc->dwHeight;
gfx_mode_list->mode[gfx_mode_list->num_modes].bpp = lpDDSurfaceDesc->ddpfPixelFormat.dwRGBBitCount;
/* check if 16 bpp mode is 16 bpp or 15 bpp */
if (gfx_mode_list->mode[gfx_mode_list->num_modes].bpp == 16) {
gfx_mode_list->mode[gfx_mode_list->num_modes].bpp =
get_color_bits(lpDDSurfaceDesc->ddpfPixelFormat.dwRBitMask) +
get_color_bits(lpDDSurfaceDesc->ddpfPixelFormat.dwGBitMask) +
get_color_bits(lpDDSurfaceDesc->ddpfPixelFormat.dwBBitMask);
}
gfx_mode_list->num_modes++;
return DDENUMRET_OK;
}
/* gfx_directx_fetch_mode_list:
* Creates a list of available video modes.
* Returns the list on success, NULL on failure.
*/
GFX_MODE_LIST *gfx_directx_fetch_mode_list(void)
{
GFX_MODE_LIST *gfx_mode_list;
int enum_flags, dx_was_off;
HRESULT hr;
/* enumerate VGA Mode 13h under DirectX 5 or greater */
if (_dx_ver >= 0x500)
enum_flags = DDEDM_STANDARDVGAMODES;
else
enum_flags = 0;
if (!directdraw) {
init_directx();
dx_was_off = TRUE;
}
else {
dx_was_off = FALSE;
}
/* start enumeration */
gfx_mode_list = _AL_MALLOC(sizeof(GFX_MODE_LIST));
if (!gfx_mode_list)
goto Error;
gfx_mode_list->num_modes = 0;
gfx_mode_list->mode = NULL;
hr = IDirectDraw2_EnumDisplayModes(directdraw, enum_flags, NULL, gfx_mode_list, EnumModesCallback);
if (FAILED(hr)) {
_AL_FREE(gfx_mode_list);
goto Error;
}
/* terminate mode list */
gfx_mode_list->mode = _al_sane_realloc(gfx_mode_list->mode, sizeof(GFX_MODE) * (gfx_mode_list->num_modes + 1));
if (!gfx_mode_list->mode)
goto Error;
gfx_mode_list->mode[gfx_mode_list->num_modes].width = 0;
gfx_mode_list->mode[gfx_mode_list->num_modes].height = 0;
gfx_mode_list->mode[gfx_mode_list->num_modes].bpp = 0;
if (dx_was_off)
exit_directx();
return gfx_mode_list;
Error:
if (dx_was_off)
exit_directx();
return NULL;
}
/* set_video_mode:
* Sets the requested fullscreen video mode.
*/
int set_video_mode(int w, int h, int v_w, int v_h, int color_depth)
{
HWND allegro_wnd = win_get_window();
_wnd_width = w;
_wnd_height = h;
_wnd_depth = (color_depth == 15 ? 16 : color_depth);
_wnd_refresh_rate = _refresh_rate_request;
/* use VGA Mode 13h under DirectX 5 or greater */
if ((w == 320) && (h == 200) && (color_depth == 8) && (_dx_ver >= 0x500))
_wnd_flags = DDSDM_STANDARDVGAMODE;
else
_wnd_flags = 0;
while (TRUE) {
/* let the window thread do the hard work */
_TRACE(PREFIX_I "setting display mode(%u, %u, %u, %u)\n",
_wnd_width, _wnd_height, _wnd_depth, _wnd_refresh_rate);
if (wnd_call_proc(wnd_set_video_mode) == 0) {
/* check that the requested mode was properly set by the driver */
if (gfx_directx_compare_color_depth(color_depth) == 0)
goto Done;
}
/* try with no refresh rate request */
if (_wnd_refresh_rate > 0)
_wnd_refresh_rate = 0;
else
break;
}
_TRACE(PREFIX_E "Unable to set any display mode.\n");
return -1;
Done:
/* remove the window controls */
SetWindowLong(allegro_wnd, GWL_STYLE, WS_POPUP);
/* maximize the window */
ShowWindow(allegro_wnd, SW_MAXIMIZE);
/* put it in the foreground */
SetForegroundWindow(allegro_wnd);
return 0;
}
| aseprite-gpl/aseprite | src/allegro/src/win/wddmode.c | C | gpl-2.0 | 11,668 |
<?php
/**
* Provides PHP support for simple use of the WPMUDEV plugin UI.
*
* @package WPMUDEV_UI
*/
if ( ! class_exists( 'WDEV_Plugin_Ui' ) ) {
/**
* UI class that encapsulates all module functions.
*/
class WDEV_Plugin_Ui {
/**
* Current module version.
*/
const VERSION = '1.1';
/**
* Internal translation container.
*
* @var array
*/
static protected $i10n = array();
/**
* Internal storage that holds additional classes for body tag.
*
* @var array
*/
static protected $body_class = '';
/**
* URL to this module (directory). Used to enqueue the css/js files.
*
* @var string
*/
static protected $module_url = '';
/**
* Initializes all UI components.
*
* @since 1.0.0
* @internal
*/
static public function reset() {
self::$i10n = array(
'empty_search' => __( 'Nothing found', 'wpmudev' ),
'default_msg_ok' => __( 'Okay, we saved your changes!', 'wpmudev' ),
'default_msg_err' => __( 'Oops, we could not do this...', 'wpmudev' ),
);
}
/**
* Enqueues the CSS and JS files needed for plugin UI
*
* @since 1.0.0
* @api Call this function before/in `admin_head`.
* @param string $module_url URL to this module (directory).
* @param string $body_class List of additional classes for the body tag.
*/
static public function load( $module_url, $body_class = '' ) {
self::$module_url = trailingslashit( $module_url );
self::$body_class = trim( $body_class );
add_filter(
'admin_body_class',
array( __CLASS__, 'admin_body_class' )
);
if ( ! did_action( 'admin_enqueue_scripts' ) ) {
add_action(
'admin_enqueue_scripts',
array( __CLASS__, 'enqueue' )
);
} else {
self::enqueue();
}
}
/**
* Enqueues the CSS and JS files.
*
* @since 1.0.0
* @internal Do not call this method manually. It's called by `load()`!
*/
static public function enqueue() {
wp_enqueue_style(
'wdev-plugin-google_fonts',
'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700|Roboto:400,500,300,300italic',
false,
self::VERSION
);
wp_enqueue_style(
'wdev-plugin-ui',
self::$module_url . 'wdev-ui.css',
array( 'wdev-plugin-google_fonts' ),
self::VERSION
);
wp_enqueue_script(
'wdev-plugin-ui',
self::$module_url . 'wdev-ui.js',
array( 'jquery' ),
self::VERSION
);
}
/**
* Adds the page-specific class to the admin page body tag.
*
* @since 1.0.0
* @internal Action hook
* @param string $classes List of CSS classes of the body tag.
* @return string Updated list of CSS classes.
*/
static public function admin_body_class( $classes ) {
$classes .= ' wpmud';
if ( self::$body_class ) {
$classes .= ' ' . self::$body_class;
}
$classes .= ' ';
return $classes;
}
/**
* Sets a translation from javascript.
*
* @since 1.0.0
* @api Use this before calling `output_header()`.
* @param string $key The translation key (used in javascript).
* @param string $value Human readable text.
*/
static public function translate( $key, $value ) {
self::$i10n[ $key ] = (string) $value;
}
/**
* Outputs code in the page header.
*
* This function must be called by the plugin!
* It's not important if it's in the header or in the footer of the page,
* but in top/header is recommended.
*
* @since 1.0.0
* @api Call this function somewhere after output started.
* @param array $commands Optinal list of additional JS commands that
* are executed when page loaded.
*/
static public function output( $commands = array() ) {
$data = array();
$data[] = 'window.WDP = window.WDP || {}';
$data[] = 'WDP.data = WDP.data || {}';
$data[] = 'WDP.data.site_url = ' . json_encode( get_site_url() );
$data[] = 'WDP.lang = ' . json_encode( self::$i10n );
// Add custom JS commands to the init-code.
if ( is_array( $commands ) ) {
$data = array_merge( $data, $commands );
}
/**
* Display a custom success message on the WPMU Dashboard pages.
*
* @var string|array The message to display.
* Array options:
* 'type' => [ok|err] (default: 'ok')
* 'delay' => 3000 (default: 3000ms)
* 'message' => '...' (required!)
*/
$notice = apply_filters( 'wpmudev-admin-notice', false );
if ( $notice ) {
$command = 'WDP';
if ( is_array( $notice ) && ! empty( $notice['type'] ) ) {
$command .= sprintf( '.showMessage("type", "%s")', esc_attr( $notice['type'] ) );
}
if ( is_array( $notice ) && ! empty( $notice['delay'] ) ) {
$command .= sprintf( '.showMessage("delay", %s)', intval( $notice['delay'] ) );
}
if ( is_array( $notice ) && ! empty( $notice['message'] ) ) {
$command .= sprintf( '.showMessage("message", "%s")', esc_html( $notice['message'] ) );
} elseif ( is_string( $notice ) ) {
$command .= sprintf( '.showMessage("message", "%s")', esc_html( $notice ) );
}
$command .= '.showMessage("show")';
$data[] = $command;
}
foreach ( $data as $item ) {
printf(
"<script>;jQuery(function(){%s;});</script>\n",
// @codingStandardsIgnoreStart: This is javascript code, no escaping!
$item
// @codingStandardsIgnoreEnd
);
}
}
/**
* Output the HTML code to display the notification.
*
* @since 1.0.0
* @param string $module_url URL to this module (directory).
* @param array $msg The message details.
* id .. Required, can be any valid class-name.
* content .. Required, can contain HTML.
* dismissed .. Optional. If true then no message is output.
* can_dismiss .. Optional. If true a Dismiss button is added.
* cta .. Optional. Can be HTML code of a button/link.
*/
static public function render_dev_notification( $module_url, $msg ) {
if ( ! is_array( $msg ) ) { return; }
if ( ! isset( $msg['id'] ) ) { return; }
if ( empty( $msg['content'] ) ) { return; }
if ( $msg['dismissed'] ) { return; }
$css_url = $module_url . 'notice.css';
$js_url = $module_url . 'notice.js';
if ( empty( $msg['id'] ) ) {
$msg_dismiss = '';
} else {
$msg_dismiss = __( 'Saving', 'wpmudev' );
}
$show_actions = $msg['can_dismiss'] || $msg['cta'];
$allowed = array(
'a' => array( 'href' => array(), 'title' => array(), 'target' => array(), 'class' => array() ),
'br' => array(),
'hr' => array(),
'em' => array(),
'i' => array(),
'strong' => array(),
'b' => array(),
);
?>
<link rel="stylesheet" type="text/css" href="<?php echo esc_url( $css_url ); ?>" />
<div class="notice frash-notice" style="display:none">
<input type="hidden" name="msg_id" value="<?php echo esc_attr( $msg['id'] ); ?>" />
<div class="frash-notice-logo"><span></span></div>
<div class="frash-notice-message">
<?php echo wp_kses( $msg['content'], $allowed ); ?>
</div>
<?php if ( $show_actions ) : ?>
<div class="frash-notice-cta">
<?php echo wp_kses( $msg['cta'], $allowed ); ?>
<?php if ( $msg['can_dismiss'] ) : ?>
<button class="frash-notice-dismiss" data-msg="<?php echo esc_attr( $msg_dismiss ); ?>">
<?php esc_html_e( 'Dismiss', 'wpmudev' ); ?>
</button>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
<script src="<?php echo esc_url( $js_url ); ?>"></script>
<?php
}
};
// Initialize the UI.
WDEV_Plugin_Ui::reset();
}
| ankitdds/liwts | wp-content/plugins/wp-smushit/assets/shared-ui/plugin-ui.php | PHP | gpl-2.0 | 7,624 |
#!/usr/bin/python
# From issue #1 of Ryan Hileman
from unicorn import *
import regress
CODE = b"\x90\x91\x92"
class DeadLock(regress.RegressTest):
def runTest(self):
mu = Uc(UC_ARCH_X86, UC_MODE_64)
mu.mem_map(0x100000, 4 * 1024)
mu.mem_write(0x100000, CODE)
with self.assertRaises(UcError):
mu.emu_start(0x100000, 0x1000 + len(CODE))
if __name__ == '__main__':
regress.main()
| pkooiman/unicorn | tests/regress/deadlock_1.py | Python | gpl-2.0 | 435 |
/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
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 "VMSignal.hpp"
#include <string.h>
Signal::Signal(){
memset(&header, 0, sizeof(header));
memset(theData, 0, sizeof(theData));
}
void
Signal::garbage_register()
{
int i;
theData[0] = 0x13579135;
header.theLength = 0x13579135;
header.theSendersBlockRef = 0x13579135;
for (i = 1; i < 24; i++)
theData[i] = 0x13579135;
}
| ottok/mariadb-galera-10.0 | storage/ndb/src/kernel/vm/VMSignal.cpp | C++ | gpl-2.0 | 1,047 |
<?php
/**
* @file
* Contains \Drupal\Tests\views\Unit\Plugin\pager\PagerPluginBaseTest.
*/
namespace Drupal\Tests\views\Unit\Plugin\pager;
use Drupal\Tests\UnitTestCase;
use Drupal\Core\Database\StatementInterface;
use Drupal\Core\Database\Query\Select;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\pager\PagerPluginBase
* @group views
*/
class PagerPluginBaseTest extends UnitTestCase {
/**
* The mock pager plugin instance.
*
* @var \Drupal\views\Plugin\views\pager\PagerPluginBase|\PHPUnit\Framework\MockObject\MockObject
*/
protected $pager;
protected function setUp(): void {
$this->pager = $this->getMockBuilder('Drupal\views\Plugin\views\pager\PagerPluginBase')
->disableOriginalConstructor()
->getMockForAbstractClass();
$view = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$options = [
'items_per_page' => 5,
'offset' => 1,
];
$this->pager->init($view, $display, $options);
$this->pager->current_page = 1;
}
/**
* Tests the getItemsPerPage() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getItemsPerPage()
*/
public function testGetItemsPerPage() {
$this->assertEquals(5, $this->pager->getItemsPerPage());
}
/**
* Tests the setItemsPerPage() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::setItemsPerPage()
*/
public function testSetItemsPerPage() {
$this->pager->setItemsPerPage(6);
$this->assertEquals(6, $this->pager->getItemsPerPage());
}
/**
* Tests the getOffset() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getOffset()
*/
public function testGetOffset() {
$this->assertEquals(1, $this->pager->getOffset());
}
/**
* Tests the setOffset() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::setOffset()
*/
public function testSetOffset() {
$this->pager->setOffset(2);
$this->assertEquals(2, $this->pager->getOffset());
}
/**
* Tests the getCurrentPage() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getCurrentPage()
*/
public function testGetCurrentPage() {
$this->assertEquals(1, $this->pager->getCurrentPage());
}
/**
* Tests the setCurrentPage() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::setCurrentPage()
*/
public function testSetCurrentPage() {
$this->pager->setCurrentPage(2);
$this->assertEquals(2, $this->pager->getCurrentPage());
// A non numeric number or number below 0 should return 0.
$this->pager->setCurrentPage('two');
$this->assertEquals(0, $this->pager->getCurrentPage());
$this->pager->setCurrentPage(-2);
$this->assertEquals(0, $this->pager->getCurrentPage());
}
/**
* Tests the getTotalItems() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getTotalItems()
*/
public function testGetTotalItems() {
// Should return 0 by default.
$this->assertEquals(0, $this->pager->getTotalItems());
$this->pager->total_items = 10;
$this->assertEquals(10, $this->pager->getTotalItems());
}
/**
* Tests the getPagerId() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getPagerId()
*/
public function testGetPagerId() {
// Should return 0 if 'id' is not set.
$this->assertEquals(0, $this->pager->getPagerId());
$this->pager->options['id'] = 1;
$this->assertEquals(1, $this->pager->getPagerId());
}
/**
* Tests the usePager() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::usePager()
*/
public function testUsePager() {
$this->assertTrue($this->pager->usePager());
}
/**
* Tests the useCountQuery() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::useCountQuery()
*/
public function testUseCountQuery() {
$this->assertTrue($this->pager->useCountQuery());
}
/**
* Tests the usesExposed() method.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::usedExposed()
*/
public function testUsesExposed() {
$this->assertFalse($this->pager->usesExposed());
}
/**
* Tests the hasMoreRecords() method.
*
* @dataProvider providerTestHasMoreRecords
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::hasMoreRecords()
*/
public function testHasMoreRecords($items_per_page, $total_items, $current_page, $has_more_records) {
$this->pager->setItemsPerPage($items_per_page);
$this->pager->total_items = $total_items;
$this->pager->setCurrentPage($current_page);
$this->assertEquals($has_more_records, $this->pager->hasMoreRecords());
}
/**
* Provides test data for the hasMoreRecord method test.
*
* @see self::testHasMoreRecords
*/
public function providerTestHasMoreRecords() {
return [
// No items per page, so there can't be more available records.
[0, 0, 0, FALSE],
[0, 10, 0, FALSE],
// The amount of total items equals the items per page, so there is no
// next page available.
[5, 5, 0, FALSE],
// There is one more item, and we are at the first page.
[5, 6, 0, TRUE],
// Now we are on the second page, which has just a single one left.
[5, 6, 1, FALSE],
// Increase the total items, so we have some available on the third page.
[5, 12, 1, TRUE],
];
}
/**
* Tests the executeCountQuery method without a set offset.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::executeCountQuery()
*/
public function testExecuteCountQueryWithoutOffset() {
$statement = $this->createMock('\Drupal\Tests\views\Unit\Plugin\pager\TestStatementInterface');
$statement->expects($this->once())
->method('fetchField')
->will($this->returnValue(3));
$query = $this->getMockBuilder('\Drupal\Core\Database\Query\Select')
->disableOriginalConstructor()
->getMock();
$query->expects($this->once())
->method('execute')
->will($this->returnValue($statement));
$this->pager->setOffset(0);
$this->assertEquals(3, $this->pager->executeCountQuery($query));
}
/**
* Tests the executeCountQuery method with a set offset.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::executeCountQuery()
*/
public function testExecuteCountQueryWithOffset() {
$statement = $this->createMock('\Drupal\Tests\views\Unit\Plugin\pager\TestStatementInterface');
$statement->expects($this->once())
->method('fetchField')
->will($this->returnValue(3));
$query = $this->getMockBuilder('\Drupal\Core\Database\Query\Select')
->disableOriginalConstructor()
->getMock();
$query->expects($this->once())
->method('execute')
->will($this->returnValue($statement));
$this->pager->setOffset(2);
$this->assertEquals(1, $this->pager->executeCountQuery($query));
}
/**
* Tests the executeCountQuery method with an offset larger than result count.
*
* @see \Drupal\views\Plugin\views\pager\PagerPluginBase::executeCountQuery()
*/
public function testExecuteCountQueryWithOffsetLargerThanResult() {
$statement = $this->createMock(TestStatementInterface::class);
$statement->expects($this->once())
->method('fetchField')
->will($this->returnValue(2));
$query = $this->getMockBuilder(Select::class)
->disableOriginalConstructor()
->getMock();
$query->expects($this->once())
->method('execute')
->will($this->returnValue($statement));
$this->pager->setOffset(3);
$this->assertEquals(0, $this->pager->executeCountQuery($query));
}
}
/**
* As StatementInterface extends \Traversable, which though always needs
* an additional interface. The Statement class itself can't be mocked because
* of its __wakeup function.
*/
interface TestStatementInterface extends StatementInterface, \Iterator {}
| tobiasbuhrer/tobiasb | web/core/modules/views/tests/src/Unit/Plugin/pager/PagerPluginBaseTest.php | PHP | gpl-2.0 | 8,174 |
/* { dg-skip-if "Incompatible float ABI" { *-*-* } { "-mfloat-abi=soft" } {""} } */
/* { dg-require-effective-target arm_v8_1m_mve_ok } */
/* { dg-add-options arm_v8_1m_mve } */
/* { dg-additional-options "-O2" } */
#include "arm_mve.h"
int8x16_t
foo (int8_t a, int8x16_t b)
{
return vsetq_lane_s8 (a, b, 0);
}
/* { dg-final { scan-assembler "vmov.8" } } */
| Gurgel100/gcc | gcc/testsuite/gcc.target/arm/mve/intrinsics/vsetq_lane_s8.c | C | gpl-2.0 | 368 |
<?php
namespace Drupal\Tests\language\Kernel\Migrate\d7;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests the migration of language negotiation.
*
* @group migrate_drupal_7
*/
class MigrateLanguageNegotiationSettingsTest extends MigrateDrupal7TestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['language'];
/**
* Tests migration of language types variables to language.types.yml.
*/
public function testLanguageTypes() {
$this->executeMigrations([
'language',
'd7_language_negotiation_settings',
'd7_language_types',
]);
$config = $this->config('language.types');
$this->assertSame(['language_content', 'language_url', 'language_interface'], $config->get('all'));
$this->assertSame(['language_content', 'language_interface'], $config->get('configurable'));
$this->assertSame(['enabled' => ['language-interface' => 0]], $config->get('negotiation.language_content'));
$this->assertSame(['enabled' => ['language-url' => 0, 'language-url-fallback' => 1]], $config->get('negotiation.language_url'));
$expected_language_interface = [
'enabled' => [
'language-url' => -9,
'language-user' => -10,
'language-selected' => -6,
],
'method_weights' => [
'language-url' => -9,
'language-session' => -8,
'language-user' => -10,
'language-browser' => -7,
'language-selected' => -6,
],
];
$this->assertSame($expected_language_interface, $config->get('negotiation.language_interface'));
}
/**
* Tests the migration with prefix negotiation.
*/
public function testLanguageNegotiationWithPrefix() {
$this->sourceDatabase->update('languages')
->fields(['domain' => ''])
->execute();
$this->executeMigrations([
'language',
'd7_language_negotiation_settings',
'language_prefixes_and_domains',
]);
$config = $this->config('language.negotiation');
$this->assertSame('language', $config->get('session.parameter'));
$this->assertSame(LanguageNegotiationUrl::CONFIG_PATH_PREFIX, $config->get('url.source'));
$this->assertSame('site_default', $config->get('selected_langcode'));
$expected_prefixes = [
'en' => '',
'fr' => 'fr',
'is' => 'is',
];
$this->assertSame($expected_prefixes, $config->get('url.prefixes'));
// If prefix negotiation is used, make sure that no domains are migrated.
// Otherwise there will be validation errors when trying to save URL
// language detection configuration from the UI.
$expected_domains = [
'en' => '',
'fr' => '',
'is' => '',
];
$this->assertSame($expected_domains, $config->get('url.domains'));
}
/**
* Tests the migration with domain negotiation.
*/
public function testLanguageNegotiationWithDomain() {
$this->sourceDatabase->update('variable')
->fields(['value' => serialize(1)])
->condition('name', 'locale_language_negotiation_url_part')
->execute();
$this->executeMigrations([
'language',
'd7_language_negotiation_settings',
'language_prefixes_and_domains',
]);
global $base_url;
$config = $this->config('language.negotiation');
$this->assertSame('language', $config->get('session.parameter'));
$this->assertSame(LanguageNegotiationUrl::CONFIG_DOMAIN, $config->get('url.source'));
$this->assertSame('site_default', $config->get('selected_langcode'));
$expected_domains = [
'en' => parse_url($base_url, PHP_URL_HOST),
'fr' => 'fr.drupal.org',
'is' => 'is.drupal.org',
];
$this->assertSame($expected_domains, $config->get('url.domains'));
}
/**
* Tests the migration with non-existent variables.
*/
public function testLanguageNegotiationWithNonExistentVariables() {
$this->sourceDatabase->delete('variable')
->condition('name', ['local_language_negotiation_url_part', 'local_language_negotiation_session_param'], 'IN')
->execute();
$this->executeMigrations([
'language',
'd6_language_negotiation_settings',
'language_prefixes_and_domains',
]);
$config = $this->config('language.negotiation');
$this->assertSame('language', $config->get('session.parameter'));
$this->assertSame(LanguageNegotiationUrl::CONFIG_PATH_PREFIX, $config->get('url.source'));
$this->assertSame('site_default', $config->get('selected_langcode'));
$expected_prefixes = [
'en' => '',
'fr' => 'fr',
'is' => 'is',
];
$this->assertSame($expected_prefixes, $config->get('url.prefixes'));
}
}
| tobiasbuhrer/tobiasb | web/core/modules/language/tests/src/Kernel/Migrate/d7/MigrateLanguageNegotiationSettingsTest.php | PHP | gpl-2.0 | 4,727 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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.
*/
/*
* Based on OPL emulation code of DOSBox
* Copyright (C) 2002-2009 The DOSBox Team
* Licensed under GPLv2+
* http://www.dosbox.com
*/
#ifndef AUDIO_SOFTSYNTH_OPL_DOSBOX_H
#define AUDIO_SOFTSYNTH_OPL_DOSBOX_H
#ifndef DISABLE_DOSBOX_OPL
#include "audio/fmopl.h"
namespace OPL {
namespace DOSBox {
struct Timer {
double startTime;
double delay;
bool enabled, overflow, masked;
uint8 counter;
Timer();
//Call update before making any further changes
void update(double time);
//On a reset make sure the start is in sync with the next cycle
void reset(double time);
void stop();
void start(double time, int scale);
};
struct Chip {
//Last selected register
Timer timer[2];
//Check for it being a write to the timer
bool write(uint32 addr, uint8 val);
//Read the current timer state, will use current double
uint8 read();
};
namespace DBOPL {
struct Chip;
} // end of namespace DBOPL
class OPL : public ::OPL::OPL {
private:
Config::OplType _type;
uint _rate;
DBOPL::Chip *_emulator;
Chip _chip[2];
union {
uint16 normal;
uint8 dual[2];
} _reg;
void free();
void dualWrite(uint8 index, uint8 reg, uint8 val);
public:
OPL(Config::OplType type);
~OPL();
bool init(int rate);
void reset();
void write(int a, int v);
byte read(int a);
void writeReg(int r, int v);
void readBuffer(int16 *buffer, int length);
bool isStereo() const { return _type != Config::kOpl2; }
};
} // End of namespace DOSBox
} // End of namespace OPL
#endif // !DISABLE_DOSBOX_OPL
#endif
| MaddTheSane/scummvm | audio/softsynth/opl/dosbox.h | C | gpl-2.0 | 2,464 |
/***************************************************************************
qgsspatialitedataitems.cpp
---------------------
begin : October 2011
copyright : (C) 2011 by Martin Dobias
email : wonder dot sk at gmail dot 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 "qgsspatialitedataitems.h"
#include "qgsspatialiteprovider.h"
#include "qgsspatialiteconnection.h"
#ifdef HAVE_GUI
#include "qgsspatialitesourceselect.h"
#endif
#include "qgslogger.h"
#include "qgsmimedatautils.h"
#include "qgsvectorlayerexporter.h"
#include "qgsmessageoutput.h"
#include "qgsvectorlayer.h"
#include "qgssettings.h"
#include <QAction>
#include <QFileDialog>
#include <QMessageBox>
QGISEXTERN bool deleteLayer( const QString &dbPath, const QString &tableName, QString &errCause );
QgsSLLayerItem::QgsSLLayerItem( QgsDataItem *parent, const QString &name, const QString &path, const QString &uri, LayerType layerType )
: QgsLayerItem( parent, name, path, uri, layerType, QStringLiteral( "spatialite" ) )
{
setState( Populated ); // no children are expected
}
#ifdef HAVE_GUI
QList<QAction *> QgsSLLayerItem::actions( QWidget *parent )
{
QList<QAction *> lst;
QAction *actionDeleteLayer = new QAction( tr( "Delete Layer" ), parent );
connect( actionDeleteLayer, &QAction::triggered, this, &QgsSLLayerItem::deleteLayer );
lst.append( actionDeleteLayer );
return lst;
}
void QgsSLLayerItem::deleteLayer()
{
if ( QMessageBox::question( nullptr, QObject::tr( "Delete Object" ),
QObject::tr( "Are you sure you want to delete %1?" ).arg( mName ),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) != QMessageBox::Yes )
return;
QgsDataSourceUri uri( mUri );
QString errCause;
bool res = ::deleteLayer( uri.database(), uri.table(), errCause );
if ( !res )
{
QMessageBox::warning( nullptr, tr( "Delete Layer" ), errCause );
}
else
{
QMessageBox::information( nullptr, tr( "Delete Layer" ), tr( "Layer deleted successfully." ) );
mParent->refresh();
}
}
#endif
// ------
QgsSLConnectionItem::QgsSLConnectionItem( QgsDataItem *parent, const QString &name, const QString &path )
: QgsDataCollectionItem( parent, name, path )
{
mDbPath = QgsSpatiaLiteConnection::connectionPath( name );
mToolTip = mDbPath;
mCapabilities |= Collapse;
}
static QgsLayerItem::LayerType _layerTypeFromDb( const QString &dbType )
{
if ( dbType == QLatin1String( "POINT" ) || dbType == QLatin1String( "MULTIPOINT" ) )
{
return QgsLayerItem::Point;
}
else if ( dbType == QLatin1String( "LINESTRING" ) || dbType == QLatin1String( "MULTILINESTRING" ) )
{
return QgsLayerItem::Line;
}
else if ( dbType == QLatin1String( "POLYGON" ) || dbType == QLatin1String( "MULTIPOLYGON" ) )
{
return QgsLayerItem::Polygon;
}
else if ( dbType == QLatin1String( "qgis_table" ) )
{
return QgsLayerItem::Table;
}
else
{
return QgsLayerItem::NoType;
}
}
QVector<QgsDataItem *> QgsSLConnectionItem::createChildren()
{
QVector<QgsDataItem *> children;
QgsSpatiaLiteConnection connection( mName );
QgsSpatiaLiteConnection::Error err = connection.fetchTables( true );
if ( err != QgsSpatiaLiteConnection::NoError )
{
QString msg;
switch ( err )
{
case QgsSpatiaLiteConnection::NotExists:
msg = tr( "Database does not exist" );
break;
case QgsSpatiaLiteConnection::FailedToOpen:
msg = tr( "Failed to open database" );
break;
case QgsSpatiaLiteConnection::FailedToCheckMetadata:
msg = tr( "Failed to check metadata" );
break;
case QgsSpatiaLiteConnection::FailedToGetTables:
msg = tr( "Failed to get list of tables" );
break;
default:
msg = tr( "Unknown error" );
break;
}
QString msgDetails = connection.errorMessage();
if ( !msgDetails.isEmpty() )
msg = QStringLiteral( "%1 (%2)" ).arg( msg, msgDetails );
children.append( new QgsErrorItem( this, msg, mPath + "/error" ) );
return children;
}
QString connectionInfo = QStringLiteral( "dbname='%1'" ).arg( QString( connection.path() ).replace( '\'', QLatin1String( "\\'" ) ) );
QgsDataSourceUri uri( connectionInfo );
Q_FOREACH ( const QgsSpatiaLiteConnection::TableEntry &entry, connection.tables() )
{
uri.setDataSource( QString(), entry.tableName, entry.column, QString(), QString() );
QgsSLLayerItem *layer = new QgsSLLayerItem( this, entry.tableName, mPath + '/' + entry.tableName, uri.uri(), _layerTypeFromDb( entry.type ) );
children.append( layer );
}
return children;
}
bool QgsSLConnectionItem::equal( const QgsDataItem *other )
{
if ( type() != other->type() )
{
return false;
}
const QgsSLConnectionItem *o = dynamic_cast<const QgsSLConnectionItem *>( other );
return o && mPath == o->mPath && mName == o->mName;
}
#ifdef HAVE_GUI
QList<QAction *> QgsSLConnectionItem::actions( QWidget *parent )
{
QList<QAction *> lst;
//QAction* actionEdit = new QAction( tr( "Edit…" ), parent );
//connect( actionEdit, SIGNAL( triggered() ), this, SLOT( editConnection() ) );
//lst.append( actionEdit );
QAction *actionDelete = new QAction( tr( "Delete" ), parent );
connect( actionDelete, &QAction::triggered, this, &QgsSLConnectionItem::deleteConnection );
lst.append( actionDelete );
return lst;
}
void QgsSLConnectionItem::editConnection()
{
}
void QgsSLConnectionItem::deleteConnection()
{
if ( QMessageBox::question( nullptr, QObject::tr( "Delete Connection" ),
QObject::tr( "Are you sure you want to delete the connection to %1?" ).arg( mName ),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) != QMessageBox::Yes )
return;
QgsSpatiaLiteConnection::deleteConnection( mName );
// the parent should be updated
mParent->refreshConnections();
}
#endif
bool QgsSLConnectionItem::handleDrop( const QMimeData *data, Qt::DropAction )
{
if ( !QgsMimeDataUtils::isUriList( data ) )
return false;
// TODO: probably should show a GUI with settings etc
QgsDataSourceUri destUri;
destUri.setDatabase( mDbPath );
QStringList importResults;
bool hasError = false;
QgsMimeDataUtils::UriList lst = QgsMimeDataUtils::decodeUriList( data );
Q_FOREACH ( const QgsMimeDataUtils::Uri &u, lst )
{
// open the source layer
bool owner;
QString error;
QgsVectorLayer *srcLayer = u.vectorLayer( owner, error );
if ( !srcLayer )
{
importResults.append( tr( "%1: %2" ).arg( u.name, error ) );
hasError = true;
continue;
}
if ( srcLayer->isValid() )
{
destUri.setDataSource( QString(), u.name, srcLayer->geometryType() != QgsWkbTypes::NullGeometry ? QStringLiteral( "geom" ) : QString() );
QgsDebugMsg( "URI " + destUri.uri() );
std::unique_ptr< QgsVectorLayerExporterTask > exportTask( new QgsVectorLayerExporterTask( srcLayer, destUri.uri(), QStringLiteral( "spatialite" ), srcLayer->crs(), QVariantMap(), owner ) );
// when export is successful:
connect( exportTask.get(), &QgsVectorLayerExporterTask::exportComplete, this, [ = ]()
{
// this is gross - TODO - find a way to get access to messageBar from data items
QMessageBox::information( nullptr, tr( "Import to SpatiaLite database" ), tr( "Import was successful." ) );
refresh();
} );
// when an error occurs:
connect( exportTask.get(), &QgsVectorLayerExporterTask::errorOccurred, this, [ = ]( int error, const QString & errorMessage )
{
if ( error != QgsVectorLayerExporter::ErrUserCanceled )
{
QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
output->setTitle( tr( "Import to SpatiaLite database" ) );
output->setMessage( tr( "Failed to import layer!\n\n" ) + errorMessage, QgsMessageOutput::MessageText );
output->showMessage();
}
refresh();
} );
QgsApplication::taskManager()->addTask( exportTask.release() );
}
else
{
importResults.append( tr( "%1: Not a valid layer!" ).arg( u.name ) );
hasError = true;
}
}
if ( hasError )
{
QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
output->setTitle( tr( "Import to SpatiaLite database" ) );
output->setMessage( tr( "Failed to import some layers!\n\n" ) + importResults.join( QStringLiteral( "\n" ) ), QgsMessageOutput::MessageText );
output->showMessage();
}
return true;
}
// ---------------------------------------------------------------------------
QgsSLRootItem::QgsSLRootItem( QgsDataItem *parent, const QString &name, const QString &path )
: QgsDataCollectionItem( parent, name, path )
{
mCapabilities |= Fast;
mIconName = QStringLiteral( "mIconSpatialite.svg" );
populate();
}
QVector<QgsDataItem *> QgsSLRootItem::createChildren()
{
QVector<QgsDataItem *> connections;
Q_FOREACH ( const QString &connName, QgsSpatiaLiteConnection::connectionList() )
{
QgsDataItem *conn = new QgsSLConnectionItem( this, connName, mPath + '/' + connName );
connections.push_back( conn );
}
return connections;
}
#ifdef HAVE_GUI
QList<QAction *> QgsSLRootItem::actions( QWidget *parent )
{
QList<QAction *> lst;
QAction *actionNew = new QAction( tr( "New Connection…" ), parent );
connect( actionNew, &QAction::triggered, this, &QgsSLRootItem::newConnection );
lst.append( actionNew );
QAction *actionCreateDatabase = new QAction( tr( "Create Database…" ), parent );
connect( actionCreateDatabase, &QAction::triggered, this, &QgsSLRootItem::createDatabase );
lst.append( actionCreateDatabase );
return lst;
}
QWidget *QgsSLRootItem::paramWidget()
{
QgsSpatiaLiteSourceSelect *select = new QgsSpatiaLiteSourceSelect( nullptr, nullptr, QgsProviderRegistry::WidgetMode::Manager );
connect( select, &QgsSpatiaLiteSourceSelect::connectionsChanged, this, &QgsSLRootItem::onConnectionsChanged );
return select;
}
void QgsSLRootItem::onConnectionsChanged()
{
refresh();
}
void QgsSLRootItem::newConnection()
{
if ( QgsSpatiaLiteSourceSelect::newConnection( nullptr ) )
{
refreshConnections();
}
}
#endif
QGISEXTERN bool createDb( const QString &dbPath, QString &errCause );
void QgsSLRootItem::createDatabase()
{
QgsSettings settings;
QString lastUsedDir = settings.value( QStringLiteral( "UI/lastSpatiaLiteDir" ), QDir::homePath() ).toString();
QString filename = QFileDialog::getSaveFileName( nullptr, tr( "New SpatiaLite Database File" ),
lastUsedDir,
tr( "SpatiaLite" ) + " (*.sqlite *.db *.sqlite3 *.db3 *.s3db)" );
if ( filename.isEmpty() )
return;
QString errCause;
if ( ::createDb( filename, errCause ) )
{
// add connection
settings.setValue( "/SpatiaLite/connections/" + QFileInfo( filename ).fileName() + "/sqlitepath", filename );
refresh();
}
else
{
QMessageBox::critical( nullptr, tr( "Create SpatiaLite database" ), tr( "Failed to create the database:\n" ) + errCause );
}
}
// ---------------------------------------------------------------------------
#ifdef HAVE_GUI
QGISEXTERN QgsSpatiaLiteSourceSelect *selectWidget( QWidget *parent, Qt::WindowFlags fl, QgsProviderRegistry::WidgetMode widgetMode )
{
// TODO: this should be somewhere else
return new QgsSpatiaLiteSourceSelect( parent, fl, widgetMode );
}
#endif
QGISEXTERN int dataCapabilities()
{
return QgsDataProvider::Database;
}
QGISEXTERN QgsDataItem *dataItem( QString path, QgsDataItem *parentItem )
{
Q_UNUSED( path );
return new QgsSLRootItem( parentItem, QStringLiteral( "SpatiaLite" ), QStringLiteral( "spatialite:" ) );
}
| dwadler/QGIS | src/providers/spatialite/qgsspatialitedataitems.cpp | C++ | gpl-2.0 | 12,401 |
/*
* Copyright 2011 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef INCLUDE_LIBYUV_PLANAR_FUNCTIONS_H_
#define INCLUDE_LIBYUV_PLANAR_FUNCTIONS_H_
#include "libyuv/basic_types.h"
// TODO(fbarchard): Remove the following headers includes.
#include "libyuv/convert.h"
#include "libyuv/convert_argb.h"
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// Copy a plane of data.
LIBYUV_API
void CopyPlane(const uint8* src_y,
int src_stride_y,
uint8* dst_y,
int dst_stride_y,
int width,
int height);
LIBYUV_API
void CopyPlane_16(const uint16* src_y,
int src_stride_y,
uint16* dst_y,
int dst_stride_y,
int width,
int height);
// Set a plane of data to a 32 bit value.
LIBYUV_API
void SetPlane(uint8* dst_y,
int dst_stride_y,
int width,
int height,
uint32 value);
// Split interleaved UV plane into separate U and V planes.
LIBYUV_API
void SplitUVPlane(const uint8* src_uv,
int src_stride_uv,
uint8* dst_u,
int dst_stride_u,
uint8* dst_v,
int dst_stride_v,
int width,
int height);
// Merge separate U and V planes into one interleaved UV plane.
LIBYUV_API
void MergeUVPlane(const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_uv,
int dst_stride_uv,
int width,
int height);
// Copy I400. Supports inverting.
LIBYUV_API
int I400ToI400(const uint8* src_y,
int src_stride_y,
uint8* dst_y,
int dst_stride_y,
int width,
int height);
#define J400ToJ400 I400ToI400
// Copy I422 to I422.
#define I422ToI422 I422Copy
LIBYUV_API
int I422Copy(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_y,
int dst_stride_y,
uint8* dst_u,
int dst_stride_u,
uint8* dst_v,
int dst_stride_v,
int width,
int height);
// Copy I444 to I444.
#define I444ToI444 I444Copy
LIBYUV_API
int I444Copy(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_y,
int dst_stride_y,
uint8* dst_u,
int dst_stride_u,
uint8* dst_v,
int dst_stride_v,
int width,
int height);
// Convert YUY2 to I422.
LIBYUV_API
int YUY2ToI422(const uint8* src_yuy2,
int src_stride_yuy2,
uint8* dst_y,
int dst_stride_y,
uint8* dst_u,
int dst_stride_u,
uint8* dst_v,
int dst_stride_v,
int width,
int height);
// Convert UYVY to I422.
LIBYUV_API
int UYVYToI422(const uint8* src_uyvy,
int src_stride_uyvy,
uint8* dst_y,
int dst_stride_y,
uint8* dst_u,
int dst_stride_u,
uint8* dst_v,
int dst_stride_v,
int width,
int height);
LIBYUV_API
int YUY2ToNV12(const uint8* src_yuy2,
int src_stride_yuy2,
uint8* dst_y,
int dst_stride_y,
uint8* dst_uv,
int dst_stride_uv,
int width,
int height);
LIBYUV_API
int UYVYToNV12(const uint8* src_uyvy,
int src_stride_uyvy,
uint8* dst_y,
int dst_stride_y,
uint8* dst_uv,
int dst_stride_uv,
int width,
int height);
LIBYUV_API
int YUY2ToY(const uint8* src_yuy2,
int src_stride_yuy2,
uint8* dst_y,
int dst_stride_y,
int width,
int height);
// Convert I420 to I400. (calls CopyPlane ignoring u/v).
LIBYUV_API
int I420ToI400(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_y,
int dst_stride_y,
int width,
int height);
// Alias
#define J420ToJ400 I420ToI400
#define I420ToI420Mirror I420Mirror
// I420 mirror.
LIBYUV_API
int I420Mirror(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_y,
int dst_stride_y,
uint8* dst_u,
int dst_stride_u,
uint8* dst_v,
int dst_stride_v,
int width,
int height);
// Alias
#define I400ToI400Mirror I400Mirror
// I400 mirror. A single plane is mirrored horizontally.
// Pass negative height to achieve 180 degree rotation.
LIBYUV_API
int I400Mirror(const uint8* src_y,
int src_stride_y,
uint8* dst_y,
int dst_stride_y,
int width,
int height);
// Alias
#define ARGBToARGBMirror ARGBMirror
// ARGB mirror.
LIBYUV_API
int ARGBMirror(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Convert NV12 to RGB565.
LIBYUV_API
int NV12ToRGB565(const uint8* src_y,
int src_stride_y,
const uint8* src_uv,
int src_stride_uv,
uint8* dst_rgb565,
int dst_stride_rgb565,
int width,
int height);
// I422ToARGB is in convert_argb.h
// Convert I422 to BGRA.
LIBYUV_API
int I422ToBGRA(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_bgra,
int dst_stride_bgra,
int width,
int height);
// Convert I422 to ABGR.
LIBYUV_API
int I422ToABGR(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_abgr,
int dst_stride_abgr,
int width,
int height);
// Convert I422 to RGBA.
LIBYUV_API
int I422ToRGBA(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_rgba,
int dst_stride_rgba,
int width,
int height);
// Alias
#define RGB24ToRAW RAWToRGB24
LIBYUV_API
int RAWToRGB24(const uint8* src_raw,
int src_stride_raw,
uint8* dst_rgb24,
int dst_stride_rgb24,
int width,
int height);
// Draw a rectangle into I420.
LIBYUV_API
int I420Rect(uint8* dst_y,
int dst_stride_y,
uint8* dst_u,
int dst_stride_u,
uint8* dst_v,
int dst_stride_v,
int x,
int y,
int width,
int height,
int value_y,
int value_u,
int value_v);
// Draw a rectangle into ARGB.
LIBYUV_API
int ARGBRect(uint8* dst_argb,
int dst_stride_argb,
int x,
int y,
int width,
int height,
uint32 value);
// Convert ARGB to gray scale ARGB.
LIBYUV_API
int ARGBGrayTo(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Make a rectangle of ARGB gray scale.
LIBYUV_API
int ARGBGray(uint8* dst_argb,
int dst_stride_argb,
int x,
int y,
int width,
int height);
// Make a rectangle of ARGB Sepia tone.
LIBYUV_API
int ARGBSepia(uint8* dst_argb,
int dst_stride_argb,
int x,
int y,
int width,
int height);
// Apply a matrix rotation to each ARGB pixel.
// matrix_argb is 4 signed ARGB values. -128 to 127 representing -2 to 2.
// The first 4 coefficients apply to B, G, R, A and produce B of the output.
// The next 4 coefficients apply to B, G, R, A and produce G of the output.
// The next 4 coefficients apply to B, G, R, A and produce R of the output.
// The last 4 coefficients apply to B, G, R, A and produce A of the output.
LIBYUV_API
int ARGBColorMatrix(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
const int8* matrix_argb,
int width,
int height);
// Deprecated. Use ARGBColorMatrix instead.
// Apply a matrix rotation to each ARGB pixel.
// matrix_argb is 3 signed ARGB values. -128 to 127 representing -1 to 1.
// The first 4 coefficients apply to B, G, R, A and produce B of the output.
// The next 4 coefficients apply to B, G, R, A and produce G of the output.
// The last 4 coefficients apply to B, G, R, A and produce R of the output.
LIBYUV_API
int RGBColorMatrix(uint8* dst_argb,
int dst_stride_argb,
const int8* matrix_rgb,
int x,
int y,
int width,
int height);
// Apply a color table each ARGB pixel.
// Table contains 256 ARGB values.
LIBYUV_API
int ARGBColorTable(uint8* dst_argb,
int dst_stride_argb,
const uint8* table_argb,
int x,
int y,
int width,
int height);
// Apply a color table each ARGB pixel but preserve destination alpha.
// Table contains 256 ARGB values.
LIBYUV_API
int RGBColorTable(uint8* dst_argb,
int dst_stride_argb,
const uint8* table_argb,
int x,
int y,
int width,
int height);
// Apply a luma/color table each ARGB pixel but preserve destination alpha.
// Table contains 32768 values indexed by [Y][C] where 7 it 7 bit luma from
// RGB (YJ style) and C is an 8 bit color component (R, G or B).
LIBYUV_API
int ARGBLumaColorTable(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
const uint8* luma_rgb_table,
int width,
int height);
// Apply a 3 term polynomial to ARGB values.
// poly points to a 4x4 matrix. The first row is constants. The 2nd row is
// coefficients for b, g, r and a. The 3rd row is coefficients for b squared,
// g squared, r squared and a squared. The 4rd row is coefficients for b to
// the 3, g to the 3, r to the 3 and a to the 3. The values are summed and
// result clamped to 0 to 255.
// A polynomial approximation can be dirived using software such as 'R'.
LIBYUV_API
int ARGBPolynomial(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
const float* poly,
int width,
int height);
// Convert plane of 16 bit shorts to half floats.
// Source values are multiplied by scale before storing as half float.
LIBYUV_API
int HalfFloatPlane(const uint16* src_y,
int src_stride_y,
uint16* dst_y,
int dst_stride_y,
float scale,
int width,
int height);
// Quantize a rectangle of ARGB. Alpha unaffected.
// scale is a 16 bit fractional fixed point scaler between 0 and 65535.
// interval_size should be a value between 1 and 255.
// interval_offset should be a value between 0 and 255.
LIBYUV_API
int ARGBQuantize(uint8* dst_argb,
int dst_stride_argb,
int scale,
int interval_size,
int interval_offset,
int x,
int y,
int width,
int height);
// Copy ARGB to ARGB.
LIBYUV_API
int ARGBCopy(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Copy Alpha channel of ARGB to alpha of ARGB.
LIBYUV_API
int ARGBCopyAlpha(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Extract the alpha channel from ARGB.
LIBYUV_API
int ARGBExtractAlpha(const uint8* src_argb,
int src_stride_argb,
uint8* dst_a,
int dst_stride_a,
int width,
int height);
// Copy Y channel to Alpha of ARGB.
LIBYUV_API
int ARGBCopyYToAlpha(const uint8* src_y,
int src_stride_y,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
typedef void (*ARGBBlendRow)(const uint8* src_argb0,
const uint8* src_argb1,
uint8* dst_argb,
int width);
// Get function to Alpha Blend ARGB pixels and store to destination.
LIBYUV_API
ARGBBlendRow GetARGBBlend();
// Alpha Blend ARGB images and store to destination.
// Source is pre-multiplied by alpha using ARGBAttenuate.
// Alpha of destination is set to 255.
LIBYUV_API
int ARGBBlend(const uint8* src_argb0,
int src_stride_argb0,
const uint8* src_argb1,
int src_stride_argb1,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Alpha Blend plane and store to destination.
// Source is not pre-multiplied by alpha.
LIBYUV_API
int BlendPlane(const uint8* src_y0,
int src_stride_y0,
const uint8* src_y1,
int src_stride_y1,
const uint8* alpha,
int alpha_stride,
uint8* dst_y,
int dst_stride_y,
int width,
int height);
// Alpha Blend YUV images and store to destination.
// Source is not pre-multiplied by alpha.
// Alpha is full width x height and subsampled to half size to apply to UV.
LIBYUV_API
int I420Blend(const uint8* src_y0,
int src_stride_y0,
const uint8* src_u0,
int src_stride_u0,
const uint8* src_v0,
int src_stride_v0,
const uint8* src_y1,
int src_stride_y1,
const uint8* src_u1,
int src_stride_u1,
const uint8* src_v1,
int src_stride_v1,
const uint8* alpha,
int alpha_stride,
uint8* dst_y,
int dst_stride_y,
uint8* dst_u,
int dst_stride_u,
uint8* dst_v,
int dst_stride_v,
int width,
int height);
// Multiply ARGB image by ARGB image. Shifted down by 8. Saturates to 255.
LIBYUV_API
int ARGBMultiply(const uint8* src_argb0,
int src_stride_argb0,
const uint8* src_argb1,
int src_stride_argb1,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Add ARGB image with ARGB image. Saturates to 255.
LIBYUV_API
int ARGBAdd(const uint8* src_argb0,
int src_stride_argb0,
const uint8* src_argb1,
int src_stride_argb1,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Subtract ARGB image (argb1) from ARGB image (argb0). Saturates to 0.
LIBYUV_API
int ARGBSubtract(const uint8* src_argb0,
int src_stride_argb0,
const uint8* src_argb1,
int src_stride_argb1,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Convert I422 to YUY2.
LIBYUV_API
int I422ToYUY2(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_frame,
int dst_stride_frame,
int width,
int height);
// Convert I422 to UYVY.
LIBYUV_API
int I422ToUYVY(const uint8* src_y,
int src_stride_y,
const uint8* src_u,
int src_stride_u,
const uint8* src_v,
int src_stride_v,
uint8* dst_frame,
int dst_stride_frame,
int width,
int height);
// Convert unattentuated ARGB to preattenuated ARGB.
LIBYUV_API
int ARGBAttenuate(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Convert preattentuated ARGB to unattenuated ARGB.
LIBYUV_API
int ARGBUnattenuate(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Internal function - do not call directly.
// Computes table of cumulative sum for image where the value is the sum
// of all values above and to the left of the entry. Used by ARGBBlur.
LIBYUV_API
int ARGBComputeCumulativeSum(const uint8* src_argb,
int src_stride_argb,
int32* dst_cumsum,
int dst_stride32_cumsum,
int width,
int height);
// Blur ARGB image.
// dst_cumsum table of width * (height + 1) * 16 bytes aligned to
// 16 byte boundary.
// dst_stride32_cumsum is number of ints in a row (width * 4).
// radius is number of pixels around the center. e.g. 1 = 3x3. 2=5x5.
// Blur is optimized for radius of 5 (11x11) or less.
LIBYUV_API
int ARGBBlur(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int32* dst_cumsum,
int dst_stride32_cumsum,
int width,
int height,
int radius);
// Multiply ARGB image by ARGB value.
LIBYUV_API
int ARGBShade(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height,
uint32 value);
// Interpolate between two images using specified amount of interpolation
// (0 to 255) and store to destination.
// 'interpolation' is specified as 8 bit fraction where 0 means 100% src0
// and 255 means 1% src0 and 99% src1.
LIBYUV_API
int InterpolatePlane(const uint8* src0,
int src_stride0,
const uint8* src1,
int src_stride1,
uint8* dst,
int dst_stride,
int width,
int height,
int interpolation);
// Interpolate between two ARGB images using specified amount of interpolation
// Internally calls InterpolatePlane with width * 4 (bpp).
LIBYUV_API
int ARGBInterpolate(const uint8* src_argb0,
int src_stride_argb0,
const uint8* src_argb1,
int src_stride_argb1,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height,
int interpolation);
// Interpolate between two YUV images using specified amount of interpolation
// Internally calls InterpolatePlane on each plane where the U and V planes
// are half width and half height.
LIBYUV_API
int I420Interpolate(const uint8* src0_y,
int src0_stride_y,
const uint8* src0_u,
int src0_stride_u,
const uint8* src0_v,
int src0_stride_v,
const uint8* src1_y,
int src1_stride_y,
const uint8* src1_u,
int src1_stride_u,
const uint8* src1_v,
int src1_stride_v,
uint8* dst_y,
int dst_stride_y,
uint8* dst_u,
int dst_stride_u,
uint8* dst_v,
int dst_stride_v,
int width,
int height,
int interpolation);
#if defined(__pnacl__) || defined(__CLR_VER) || \
(defined(__i386__) && !defined(__SSE2__))
#define LIBYUV_DISABLE_X86
#endif
// MemorySanitizer does not support assembly code yet. http://crbug.com/344505
#if defined(__has_feature)
#if __has_feature(memory_sanitizer)
#define LIBYUV_DISABLE_X86
#endif
#endif
// The following are available on all x86 platforms:
#if !defined(LIBYUV_DISABLE_X86) && \
(defined(_M_IX86) || defined(__x86_64__) || defined(__i386__))
#define HAS_ARGBAFFINEROW_SSE2
#endif
// Row function for copying pixels from a source with a slope to a row
// of destination. Useful for scaling, rotation, mirror, texture mapping.
LIBYUV_API
void ARGBAffineRow_C(const uint8* src_argb,
int src_argb_stride,
uint8* dst_argb,
const float* uv_dudv,
int width);
LIBYUV_API
void ARGBAffineRow_SSE2(const uint8* src_argb,
int src_argb_stride,
uint8* dst_argb,
const float* uv_dudv,
int width);
// Shuffle ARGB channel order. e.g. BGRA to ARGB.
// shuffler is 16 bytes and must be aligned.
LIBYUV_API
int ARGBShuffle(const uint8* src_bgra,
int src_stride_bgra,
uint8* dst_argb,
int dst_stride_argb,
const uint8* shuffler,
int width,
int height);
// Sobel ARGB effect with planar output.
LIBYUV_API
int ARGBSobelToPlane(const uint8* src_argb,
int src_stride_argb,
uint8* dst_y,
int dst_stride_y,
int width,
int height);
// Sobel ARGB effect.
LIBYUV_API
int ARGBSobel(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
// Sobel ARGB effect w/ Sobel X, Sobel, Sobel Y in ARGB.
LIBYUV_API
int ARGBSobelXY(const uint8* src_argb,
int src_stride_argb,
uint8* dst_argb,
int dst_stride_argb,
int width,
int height);
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
#endif // INCLUDE_LIBYUV_PLANAR_FUNCTIONS_H_
| svn2github/pjsip | third_party/yuv/include/libyuv/planar_functions.h | C | gpl-2.0 | 24,568 |
// SPDX-License-Identifier: GPL-2.0-only
/*
*
* Copyright 2010-2011 Paul Mackerras, IBM Corp. <[email protected]>
*/
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kvm.h>
#include <linux/kvm_host.h>
#include <linux/hugetlb.h>
#include <linux/module.h>
#include <linux/log2.h>
#include <linux/sizes.h>
#include <asm/trace.h>
#include <asm/kvm_ppc.h>
#include <asm/kvm_book3s.h>
#include <asm/book3s/64/mmu-hash.h>
#include <asm/hvcall.h>
#include <asm/synch.h>
#include <asm/ppc-opcode.h>
#include <asm/pte-walk.h>
/* Translate address of a vmalloc'd thing to a linear map address */
static void *real_vmalloc_addr(void *x)
{
unsigned long addr = (unsigned long) x;
pte_t *p;
/*
* assume we don't have huge pages in vmalloc space...
* So don't worry about THP collapse/split. Called
* Only in realmode with MSR_EE = 0, hence won't need irq_save/restore.
*/
p = find_init_mm_pte(addr, NULL);
if (!p || !pte_present(*p))
return NULL;
addr = (pte_pfn(*p) << PAGE_SHIFT) | (addr & ~PAGE_MASK);
return __va(addr);
}
/* Return 1 if we need to do a global tlbie, 0 if we can use tlbiel */
static int global_invalidates(struct kvm *kvm)
{
int global;
int cpu;
/*
* If there is only one vcore, and it's currently running,
* as indicated by local_paca->kvm_hstate.kvm_vcpu being set,
* we can use tlbiel as long as we mark all other physical
* cores as potentially having stale TLB entries for this lpid.
* Otherwise, don't use tlbiel.
*/
if (kvm->arch.online_vcores == 1 && local_paca->kvm_hstate.kvm_vcpu)
global = 0;
else
global = 1;
if (!global) {
/* any other core might now have stale TLB entries... */
smp_wmb();
cpumask_setall(&kvm->arch.need_tlb_flush);
cpu = local_paca->kvm_hstate.kvm_vcore->pcpu;
/*
* On POWER9, threads are independent but the TLB is shared,
* so use the bit for the first thread to represent the core.
*/
if (cpu_has_feature(CPU_FTR_ARCH_300))
cpu = cpu_first_thread_sibling(cpu);
cpumask_clear_cpu(cpu, &kvm->arch.need_tlb_flush);
}
return global;
}
/*
* Add this HPTE into the chain for the real page.
* Must be called with the chain locked; it unlocks the chain.
*/
void kvmppc_add_revmap_chain(struct kvm *kvm, struct revmap_entry *rev,
unsigned long *rmap, long pte_index, int realmode)
{
struct revmap_entry *head, *tail;
unsigned long i;
if (*rmap & KVMPPC_RMAP_PRESENT) {
i = *rmap & KVMPPC_RMAP_INDEX;
head = &kvm->arch.hpt.rev[i];
if (realmode)
head = real_vmalloc_addr(head);
tail = &kvm->arch.hpt.rev[head->back];
if (realmode)
tail = real_vmalloc_addr(tail);
rev->forw = i;
rev->back = head->back;
tail->forw = pte_index;
head->back = pte_index;
} else {
rev->forw = rev->back = pte_index;
*rmap = (*rmap & ~KVMPPC_RMAP_INDEX) |
pte_index | KVMPPC_RMAP_PRESENT | KVMPPC_RMAP_HPT;
}
unlock_rmap(rmap);
}
EXPORT_SYMBOL_GPL(kvmppc_add_revmap_chain);
/* Update the dirty bitmap of a memslot */
void kvmppc_update_dirty_map(const struct kvm_memory_slot *memslot,
unsigned long gfn, unsigned long psize)
{
unsigned long npages;
if (!psize || !memslot->dirty_bitmap)
return;
npages = (psize + PAGE_SIZE - 1) / PAGE_SIZE;
gfn -= memslot->base_gfn;
set_dirty_bits_atomic(memslot->dirty_bitmap, gfn, npages);
}
EXPORT_SYMBOL_GPL(kvmppc_update_dirty_map);
static void kvmppc_set_dirty_from_hpte(struct kvm *kvm,
unsigned long hpte_v, unsigned long hpte_gr)
{
struct kvm_memory_slot *memslot;
unsigned long gfn;
unsigned long psize;
psize = kvmppc_actual_pgsz(hpte_v, hpte_gr);
gfn = hpte_rpn(hpte_gr, psize);
memslot = __gfn_to_memslot(kvm_memslots_raw(kvm), gfn);
if (memslot && memslot->dirty_bitmap)
kvmppc_update_dirty_map(memslot, gfn, psize);
}
/* Returns a pointer to the revmap entry for the page mapped by a HPTE */
static unsigned long *revmap_for_hpte(struct kvm *kvm, unsigned long hpte_v,
unsigned long hpte_gr,
struct kvm_memory_slot **memslotp,
unsigned long *gfnp)
{
struct kvm_memory_slot *memslot;
unsigned long *rmap;
unsigned long gfn;
gfn = hpte_rpn(hpte_gr, kvmppc_actual_pgsz(hpte_v, hpte_gr));
memslot = __gfn_to_memslot(kvm_memslots_raw(kvm), gfn);
if (memslotp)
*memslotp = memslot;
if (gfnp)
*gfnp = gfn;
if (!memslot)
return NULL;
rmap = real_vmalloc_addr(&memslot->arch.rmap[gfn - memslot->base_gfn]);
return rmap;
}
/* Remove this HPTE from the chain for a real page */
static void remove_revmap_chain(struct kvm *kvm, long pte_index,
struct revmap_entry *rev,
unsigned long hpte_v, unsigned long hpte_r)
{
struct revmap_entry *next, *prev;
unsigned long ptel, head;
unsigned long *rmap;
unsigned long rcbits;
struct kvm_memory_slot *memslot;
unsigned long gfn;
rcbits = hpte_r & (HPTE_R_R | HPTE_R_C);
ptel = rev->guest_rpte |= rcbits;
rmap = revmap_for_hpte(kvm, hpte_v, ptel, &memslot, &gfn);
if (!rmap)
return;
lock_rmap(rmap);
head = *rmap & KVMPPC_RMAP_INDEX;
next = real_vmalloc_addr(&kvm->arch.hpt.rev[rev->forw]);
prev = real_vmalloc_addr(&kvm->arch.hpt.rev[rev->back]);
next->back = rev->back;
prev->forw = rev->forw;
if (head == pte_index) {
head = rev->forw;
if (head == pte_index)
*rmap &= ~(KVMPPC_RMAP_PRESENT | KVMPPC_RMAP_INDEX);
else
*rmap = (*rmap & ~KVMPPC_RMAP_INDEX) | head;
}
*rmap |= rcbits << KVMPPC_RMAP_RC_SHIFT;
if (rcbits & HPTE_R_C)
kvmppc_update_dirty_map(memslot, gfn,
kvmppc_actual_pgsz(hpte_v, hpte_r));
unlock_rmap(rmap);
}
long kvmppc_do_h_enter(struct kvm *kvm, unsigned long flags,
long pte_index, unsigned long pteh, unsigned long ptel,
pgd_t *pgdir, bool realmode, unsigned long *pte_idx_ret)
{
unsigned long i, pa, gpa, gfn, psize;
unsigned long slot_fn, hva;
__be64 *hpte;
struct revmap_entry *rev;
unsigned long g_ptel;
struct kvm_memory_slot *memslot;
unsigned hpage_shift;
bool is_ci;
unsigned long *rmap;
pte_t *ptep;
unsigned int writing;
unsigned long mmu_seq;
unsigned long rcbits;
if (kvm_is_radix(kvm))
return H_FUNCTION;
psize = kvmppc_actual_pgsz(pteh, ptel);
if (!psize)
return H_PARAMETER;
writing = hpte_is_writable(ptel);
pteh &= ~(HPTE_V_HVLOCK | HPTE_V_ABSENT | HPTE_V_VALID);
ptel &= ~HPTE_GR_RESERVED;
g_ptel = ptel;
/* used later to detect if we might have been invalidated */
mmu_seq = kvm->mmu_notifier_seq;
smp_rmb();
/* Find the memslot (if any) for this address */
gpa = (ptel & HPTE_R_RPN) & ~(psize - 1);
gfn = gpa >> PAGE_SHIFT;
memslot = __gfn_to_memslot(kvm_memslots_raw(kvm), gfn);
pa = 0;
is_ci = false;
rmap = NULL;
if (!(memslot && !(memslot->flags & KVM_MEMSLOT_INVALID))) {
/* Emulated MMIO - mark this with key=31 */
pteh |= HPTE_V_ABSENT;
ptel |= HPTE_R_KEY_HI | HPTE_R_KEY_LO;
goto do_insert;
}
/* Check if the requested page fits entirely in the memslot. */
if (!slot_is_aligned(memslot, psize))
return H_PARAMETER;
slot_fn = gfn - memslot->base_gfn;
rmap = &memslot->arch.rmap[slot_fn];
/* Translate to host virtual address */
hva = __gfn_to_hva_memslot(memslot, gfn);
arch_spin_lock(&kvm->mmu_lock.rlock.raw_lock);
ptep = find_kvm_host_pte(kvm, mmu_seq, hva, &hpage_shift);
if (ptep) {
pte_t pte;
unsigned int host_pte_size;
if (hpage_shift)
host_pte_size = 1ul << hpage_shift;
else
host_pte_size = PAGE_SIZE;
/*
* We should always find the guest page size
* to <= host page size, if host is using hugepage
*/
if (host_pte_size < psize) {
arch_spin_unlock(&kvm->mmu_lock.rlock.raw_lock);
return H_PARAMETER;
}
pte = kvmppc_read_update_linux_pte(ptep, writing);
if (pte_present(pte) && !pte_protnone(pte)) {
if (writing && !__pte_write(pte))
/* make the actual HPTE be read-only */
ptel = hpte_make_readonly(ptel);
is_ci = pte_ci(pte);
pa = pte_pfn(pte) << PAGE_SHIFT;
pa |= hva & (host_pte_size - 1);
pa |= gpa & ~PAGE_MASK;
}
}
arch_spin_unlock(&kvm->mmu_lock.rlock.raw_lock);
ptel &= HPTE_R_KEY | HPTE_R_PP0 | (psize-1);
ptel |= pa;
if (pa)
pteh |= HPTE_V_VALID;
else {
pteh |= HPTE_V_ABSENT;
ptel &= ~(HPTE_R_KEY_HI | HPTE_R_KEY_LO);
}
/*If we had host pte mapping then Check WIMG */
if (ptep && !hpte_cache_flags_ok(ptel, is_ci)) {
if (is_ci)
return H_PARAMETER;
/*
* Allow guest to map emulated device memory as
* uncacheable, but actually make it cacheable.
*/
ptel &= ~(HPTE_R_W|HPTE_R_I|HPTE_R_G);
ptel |= HPTE_R_M;
}
/* Find and lock the HPTEG slot to use */
do_insert:
if (pte_index >= kvmppc_hpt_npte(&kvm->arch.hpt))
return H_PARAMETER;
if (likely((flags & H_EXACT) == 0)) {
pte_index &= ~7UL;
hpte = (__be64 *)(kvm->arch.hpt.virt + (pte_index << 4));
for (i = 0; i < 8; ++i) {
if ((be64_to_cpu(*hpte) & HPTE_V_VALID) == 0 &&
try_lock_hpte(hpte, HPTE_V_HVLOCK | HPTE_V_VALID |
HPTE_V_ABSENT))
break;
hpte += 2;
}
if (i == 8) {
/*
* Since try_lock_hpte doesn't retry (not even stdcx.
* failures), it could be that there is a free slot
* but we transiently failed to lock it. Try again,
* actually locking each slot and checking it.
*/
hpte -= 16;
for (i = 0; i < 8; ++i) {
u64 pte;
while (!try_lock_hpte(hpte, HPTE_V_HVLOCK))
cpu_relax();
pte = be64_to_cpu(hpte[0]);
if (!(pte & (HPTE_V_VALID | HPTE_V_ABSENT)))
break;
__unlock_hpte(hpte, pte);
hpte += 2;
}
if (i == 8)
return H_PTEG_FULL;
}
pte_index += i;
} else {
hpte = (__be64 *)(kvm->arch.hpt.virt + (pte_index << 4));
if (!try_lock_hpte(hpte, HPTE_V_HVLOCK | HPTE_V_VALID |
HPTE_V_ABSENT)) {
/* Lock the slot and check again */
u64 pte;
while (!try_lock_hpte(hpte, HPTE_V_HVLOCK))
cpu_relax();
pte = be64_to_cpu(hpte[0]);
if (pte & (HPTE_V_VALID | HPTE_V_ABSENT)) {
__unlock_hpte(hpte, pte);
return H_PTEG_FULL;
}
}
}
/* Save away the guest's idea of the second HPTE dword */
rev = &kvm->arch.hpt.rev[pte_index];
if (realmode)
rev = real_vmalloc_addr(rev);
if (rev) {
rev->guest_rpte = g_ptel;
note_hpte_modification(kvm, rev);
}
/* Link HPTE into reverse-map chain */
if (pteh & HPTE_V_VALID) {
if (realmode)
rmap = real_vmalloc_addr(rmap);
lock_rmap(rmap);
/* Check for pending invalidations under the rmap chain lock */
if (mmu_notifier_retry(kvm, mmu_seq)) {
/* inval in progress, write a non-present HPTE */
pteh |= HPTE_V_ABSENT;
pteh &= ~HPTE_V_VALID;
ptel &= ~(HPTE_R_KEY_HI | HPTE_R_KEY_LO);
unlock_rmap(rmap);
} else {
kvmppc_add_revmap_chain(kvm, rev, rmap, pte_index,
realmode);
/* Only set R/C in real HPTE if already set in *rmap */
rcbits = *rmap >> KVMPPC_RMAP_RC_SHIFT;
ptel &= rcbits | ~(HPTE_R_R | HPTE_R_C);
}
}
/* Convert to new format on P9 */
if (cpu_has_feature(CPU_FTR_ARCH_300)) {
ptel = hpte_old_to_new_r(pteh, ptel);
pteh = hpte_old_to_new_v(pteh);
}
hpte[1] = cpu_to_be64(ptel);
/* Write the first HPTE dword, unlocking the HPTE and making it valid */
eieio();
__unlock_hpte(hpte, pteh);
asm volatile("ptesync" : : : "memory");
*pte_idx_ret = pte_index;
return H_SUCCESS;
}
EXPORT_SYMBOL_GPL(kvmppc_do_h_enter);
long kvmppc_h_enter(struct kvm_vcpu *vcpu, unsigned long flags,
long pte_index, unsigned long pteh, unsigned long ptel)
{
return kvmppc_do_h_enter(vcpu->kvm, flags, pte_index, pteh, ptel,
vcpu->arch.pgdir, true,
&vcpu->arch.regs.gpr[4]);
}
#ifdef __BIG_ENDIAN__
#define LOCK_TOKEN (*(u32 *)(&get_paca()->lock_token))
#else
#define LOCK_TOKEN (*(u32 *)(&get_paca()->paca_index))
#endif
static inline int is_mmio_hpte(unsigned long v, unsigned long r)
{
return ((v & HPTE_V_ABSENT) &&
(r & (HPTE_R_KEY_HI | HPTE_R_KEY_LO)) ==
(HPTE_R_KEY_HI | HPTE_R_KEY_LO));
}
static inline void fixup_tlbie_lpid(unsigned long rb_value, unsigned long lpid)
{
if (cpu_has_feature(CPU_FTR_P9_TLBIE_ERAT_BUG)) {
/* Radix flush for a hash guest */
unsigned long rb,rs,prs,r,ric;
rb = PPC_BIT(52); /* IS = 2 */
rs = 0; /* lpid = 0 */
prs = 0; /* partition scoped */
r = 1; /* radix format */
ric = 0; /* RIC_FLSUH_TLB */
/*
* Need the extra ptesync to make sure we don't
* re-order the tlbie
*/
asm volatile("ptesync": : :"memory");
asm volatile(PPC_TLBIE_5(%0, %4, %3, %2, %1)
: : "r"(rb), "i"(r), "i"(prs),
"i"(ric), "r"(rs) : "memory");
}
if (cpu_has_feature(CPU_FTR_P9_TLBIE_STQ_BUG)) {
asm volatile("ptesync": : :"memory");
asm volatile(PPC_TLBIE_5(%0,%1,0,0,0) : :
"r" (rb_value), "r" (lpid));
}
}
static void do_tlbies(struct kvm *kvm, unsigned long *rbvalues,
long npages, int global, bool need_sync)
{
long i;
/*
* We use the POWER9 5-operand versions of tlbie and tlbiel here.
* Since we are using RIC=0 PRS=0 R=0, and P7/P8 tlbiel ignores
* the RS field, this is backwards-compatible with P7 and P8.
*/
if (global) {
if (need_sync)
asm volatile("ptesync" : : : "memory");
for (i = 0; i < npages; ++i) {
asm volatile(PPC_TLBIE_5(%0,%1,0,0,0) : :
"r" (rbvalues[i]), "r" (kvm->arch.lpid));
}
fixup_tlbie_lpid(rbvalues[i - 1], kvm->arch.lpid);
asm volatile("eieio; tlbsync; ptesync" : : : "memory");
} else {
if (need_sync)
asm volatile("ptesync" : : : "memory");
for (i = 0; i < npages; ++i) {
asm volatile(PPC_TLBIEL(%0,%1,0,0,0) : :
"r" (rbvalues[i]), "r" (0));
}
asm volatile("ptesync" : : : "memory");
}
}
long kvmppc_do_h_remove(struct kvm *kvm, unsigned long flags,
unsigned long pte_index, unsigned long avpn,
unsigned long *hpret)
{
__be64 *hpte;
unsigned long v, r, rb;
struct revmap_entry *rev;
u64 pte, orig_pte, pte_r;
if (kvm_is_radix(kvm))
return H_FUNCTION;
if (pte_index >= kvmppc_hpt_npte(&kvm->arch.hpt))
return H_PARAMETER;
hpte = (__be64 *)(kvm->arch.hpt.virt + (pte_index << 4));
while (!try_lock_hpte(hpte, HPTE_V_HVLOCK))
cpu_relax();
pte = orig_pte = be64_to_cpu(hpte[0]);
pte_r = be64_to_cpu(hpte[1]);
if (cpu_has_feature(CPU_FTR_ARCH_300)) {
pte = hpte_new_to_old_v(pte, pte_r);
pte_r = hpte_new_to_old_r(pte_r);
}
if ((pte & (HPTE_V_ABSENT | HPTE_V_VALID)) == 0 ||
((flags & H_AVPN) && (pte & ~0x7fUL) != avpn) ||
((flags & H_ANDCOND) && (pte & avpn) != 0)) {
__unlock_hpte(hpte, orig_pte);
return H_NOT_FOUND;
}
rev = real_vmalloc_addr(&kvm->arch.hpt.rev[pte_index]);
v = pte & ~HPTE_V_HVLOCK;
if (v & HPTE_V_VALID) {
hpte[0] &= ~cpu_to_be64(HPTE_V_VALID);
rb = compute_tlbie_rb(v, pte_r, pte_index);
do_tlbies(kvm, &rb, 1, global_invalidates(kvm), true);
/*
* The reference (R) and change (C) bits in a HPT
* entry can be set by hardware at any time up until
* the HPTE is invalidated and the TLB invalidation
* sequence has completed. This means that when
* removing a HPTE, we need to re-read the HPTE after
* the invalidation sequence has completed in order to
* obtain reliable values of R and C.
*/
remove_revmap_chain(kvm, pte_index, rev, v,
be64_to_cpu(hpte[1]));
}
r = rev->guest_rpte & ~HPTE_GR_RESERVED;
note_hpte_modification(kvm, rev);
unlock_hpte(hpte, 0);
if (is_mmio_hpte(v, pte_r))
atomic64_inc(&kvm->arch.mmio_update);
if (v & HPTE_V_ABSENT)
v = (v & ~HPTE_V_ABSENT) | HPTE_V_VALID;
hpret[0] = v;
hpret[1] = r;
return H_SUCCESS;
}
EXPORT_SYMBOL_GPL(kvmppc_do_h_remove);
long kvmppc_h_remove(struct kvm_vcpu *vcpu, unsigned long flags,
unsigned long pte_index, unsigned long avpn)
{
return kvmppc_do_h_remove(vcpu->kvm, flags, pte_index, avpn,
&vcpu->arch.regs.gpr[4]);
}
long kvmppc_h_bulk_remove(struct kvm_vcpu *vcpu)
{
struct kvm *kvm = vcpu->kvm;
unsigned long *args = &vcpu->arch.regs.gpr[4];
__be64 *hp, *hptes[4];
unsigned long tlbrb[4];
long int i, j, k, n, found, indexes[4];
unsigned long flags, req, pte_index, rcbits;
int global;
long int ret = H_SUCCESS;
struct revmap_entry *rev, *revs[4];
u64 hp0, hp1;
if (kvm_is_radix(kvm))
return H_FUNCTION;
global = global_invalidates(kvm);
for (i = 0; i < 4 && ret == H_SUCCESS; ) {
n = 0;
for (; i < 4; ++i) {
j = i * 2;
pte_index = args[j];
flags = pte_index >> 56;
pte_index &= ((1ul << 56) - 1);
req = flags >> 6;
flags &= 3;
if (req == 3) { /* no more requests */
i = 4;
break;
}
if (req != 1 || flags == 3 ||
pte_index >= kvmppc_hpt_npte(&kvm->arch.hpt)) {
/* parameter error */
args[j] = ((0xa0 | flags) << 56) + pte_index;
ret = H_PARAMETER;
break;
}
hp = (__be64 *) (kvm->arch.hpt.virt + (pte_index << 4));
/* to avoid deadlock, don't spin except for first */
if (!try_lock_hpte(hp, HPTE_V_HVLOCK)) {
if (n)
break;
while (!try_lock_hpte(hp, HPTE_V_HVLOCK))
cpu_relax();
}
found = 0;
hp0 = be64_to_cpu(hp[0]);
hp1 = be64_to_cpu(hp[1]);
if (cpu_has_feature(CPU_FTR_ARCH_300)) {
hp0 = hpte_new_to_old_v(hp0, hp1);
hp1 = hpte_new_to_old_r(hp1);
}
if (hp0 & (HPTE_V_ABSENT | HPTE_V_VALID)) {
switch (flags & 3) {
case 0: /* absolute */
found = 1;
break;
case 1: /* andcond */
if (!(hp0 & args[j + 1]))
found = 1;
break;
case 2: /* AVPN */
if ((hp0 & ~0x7fUL) == args[j + 1])
found = 1;
break;
}
}
if (!found) {
hp[0] &= ~cpu_to_be64(HPTE_V_HVLOCK);
args[j] = ((0x90 | flags) << 56) + pte_index;
continue;
}
args[j] = ((0x80 | flags) << 56) + pte_index;
rev = real_vmalloc_addr(&kvm->arch.hpt.rev[pte_index]);
note_hpte_modification(kvm, rev);
if (!(hp0 & HPTE_V_VALID)) {
/* insert R and C bits from PTE */
rcbits = rev->guest_rpte & (HPTE_R_R|HPTE_R_C);
args[j] |= rcbits << (56 - 5);
hp[0] = 0;
if (is_mmio_hpte(hp0, hp1))
atomic64_inc(&kvm->arch.mmio_update);
continue;
}
/* leave it locked */
hp[0] &= ~cpu_to_be64(HPTE_V_VALID);
tlbrb[n] = compute_tlbie_rb(hp0, hp1, pte_index);
indexes[n] = j;
hptes[n] = hp;
revs[n] = rev;
++n;
}
if (!n)
break;
/* Now that we've collected a batch, do the tlbies */
do_tlbies(kvm, tlbrb, n, global, true);
/* Read PTE low words after tlbie to get final R/C values */
for (k = 0; k < n; ++k) {
j = indexes[k];
pte_index = args[j] & ((1ul << 56) - 1);
hp = hptes[k];
rev = revs[k];
remove_revmap_chain(kvm, pte_index, rev,
be64_to_cpu(hp[0]), be64_to_cpu(hp[1]));
rcbits = rev->guest_rpte & (HPTE_R_R|HPTE_R_C);
args[j] |= rcbits << (56 - 5);
__unlock_hpte(hp, 0);
}
}
return ret;
}
long kvmppc_h_protect(struct kvm_vcpu *vcpu, unsigned long flags,
unsigned long pte_index, unsigned long avpn)
{
struct kvm *kvm = vcpu->kvm;
__be64 *hpte;
struct revmap_entry *rev;
unsigned long v, r, rb, mask, bits;
u64 pte_v, pte_r;
if (kvm_is_radix(kvm))
return H_FUNCTION;
if (pte_index >= kvmppc_hpt_npte(&kvm->arch.hpt))
return H_PARAMETER;
hpte = (__be64 *)(kvm->arch.hpt.virt + (pte_index << 4));
while (!try_lock_hpte(hpte, HPTE_V_HVLOCK))
cpu_relax();
v = pte_v = be64_to_cpu(hpte[0]);
if (cpu_has_feature(CPU_FTR_ARCH_300))
v = hpte_new_to_old_v(v, be64_to_cpu(hpte[1]));
if ((v & (HPTE_V_ABSENT | HPTE_V_VALID)) == 0 ||
((flags & H_AVPN) && (v & ~0x7fUL) != avpn)) {
__unlock_hpte(hpte, pte_v);
return H_NOT_FOUND;
}
pte_r = be64_to_cpu(hpte[1]);
bits = (flags << 55) & HPTE_R_PP0;
bits |= (flags << 48) & HPTE_R_KEY_HI;
bits |= flags & (HPTE_R_PP | HPTE_R_N | HPTE_R_KEY_LO);
/* Update guest view of 2nd HPTE dword */
mask = HPTE_R_PP0 | HPTE_R_PP | HPTE_R_N |
HPTE_R_KEY_HI | HPTE_R_KEY_LO;
rev = real_vmalloc_addr(&kvm->arch.hpt.rev[pte_index]);
if (rev) {
r = (rev->guest_rpte & ~mask) | bits;
rev->guest_rpte = r;
note_hpte_modification(kvm, rev);
}
/* Update HPTE */
if (v & HPTE_V_VALID) {
/*
* If the page is valid, don't let it transition from
* readonly to writable. If it should be writable, we'll
* take a trap and let the page fault code sort it out.
*/
r = (pte_r & ~mask) | bits;
if (hpte_is_writable(r) && !hpte_is_writable(pte_r))
r = hpte_make_readonly(r);
/* If the PTE is changing, invalidate it first */
if (r != pte_r) {
rb = compute_tlbie_rb(v, r, pte_index);
hpte[0] = cpu_to_be64((pte_v & ~HPTE_V_VALID) |
HPTE_V_ABSENT);
do_tlbies(kvm, &rb, 1, global_invalidates(kvm), true);
/* Don't lose R/C bit updates done by hardware */
r |= be64_to_cpu(hpte[1]) & (HPTE_R_R | HPTE_R_C);
hpte[1] = cpu_to_be64(r);
}
}
unlock_hpte(hpte, pte_v & ~HPTE_V_HVLOCK);
asm volatile("ptesync" : : : "memory");
if (is_mmio_hpte(v, pte_r))
atomic64_inc(&kvm->arch.mmio_update);
return H_SUCCESS;
}
long kvmppc_h_read(struct kvm_vcpu *vcpu, unsigned long flags,
unsigned long pte_index)
{
struct kvm *kvm = vcpu->kvm;
__be64 *hpte;
unsigned long v, r;
int i, n = 1;
struct revmap_entry *rev = NULL;
if (kvm_is_radix(kvm))
return H_FUNCTION;
if (pte_index >= kvmppc_hpt_npte(&kvm->arch.hpt))
return H_PARAMETER;
if (flags & H_READ_4) {
pte_index &= ~3;
n = 4;
}
rev = real_vmalloc_addr(&kvm->arch.hpt.rev[pte_index]);
for (i = 0; i < n; ++i, ++pte_index) {
hpte = (__be64 *)(kvm->arch.hpt.virt + (pte_index << 4));
v = be64_to_cpu(hpte[0]) & ~HPTE_V_HVLOCK;
r = be64_to_cpu(hpte[1]);
if (cpu_has_feature(CPU_FTR_ARCH_300)) {
v = hpte_new_to_old_v(v, r);
r = hpte_new_to_old_r(r);
}
if (v & HPTE_V_ABSENT) {
v &= ~HPTE_V_ABSENT;
v |= HPTE_V_VALID;
}
if (v & HPTE_V_VALID) {
r = rev[i].guest_rpte | (r & (HPTE_R_R | HPTE_R_C));
r &= ~HPTE_GR_RESERVED;
}
vcpu->arch.regs.gpr[4 + i * 2] = v;
vcpu->arch.regs.gpr[5 + i * 2] = r;
}
return H_SUCCESS;
}
long kvmppc_h_clear_ref(struct kvm_vcpu *vcpu, unsigned long flags,
unsigned long pte_index)
{
struct kvm *kvm = vcpu->kvm;
__be64 *hpte;
unsigned long v, r, gr;
struct revmap_entry *rev;
unsigned long *rmap;
long ret = H_NOT_FOUND;
if (kvm_is_radix(kvm))
return H_FUNCTION;
if (pte_index >= kvmppc_hpt_npte(&kvm->arch.hpt))
return H_PARAMETER;
rev = real_vmalloc_addr(&kvm->arch.hpt.rev[pte_index]);
hpte = (__be64 *)(kvm->arch.hpt.virt + (pte_index << 4));
while (!try_lock_hpte(hpte, HPTE_V_HVLOCK))
cpu_relax();
v = be64_to_cpu(hpte[0]);
r = be64_to_cpu(hpte[1]);
if (!(v & (HPTE_V_VALID | HPTE_V_ABSENT)))
goto out;
gr = rev->guest_rpte;
if (rev->guest_rpte & HPTE_R_R) {
rev->guest_rpte &= ~HPTE_R_R;
note_hpte_modification(kvm, rev);
}
if (v & HPTE_V_VALID) {
gr |= r & (HPTE_R_R | HPTE_R_C);
if (r & HPTE_R_R) {
kvmppc_clear_ref_hpte(kvm, hpte, pte_index);
rmap = revmap_for_hpte(kvm, v, gr, NULL, NULL);
if (rmap) {
lock_rmap(rmap);
*rmap |= KVMPPC_RMAP_REFERENCED;
unlock_rmap(rmap);
}
}
}
vcpu->arch.regs.gpr[4] = gr;
ret = H_SUCCESS;
out:
unlock_hpte(hpte, v & ~HPTE_V_HVLOCK);
return ret;
}
long kvmppc_h_clear_mod(struct kvm_vcpu *vcpu, unsigned long flags,
unsigned long pte_index)
{
struct kvm *kvm = vcpu->kvm;
__be64 *hpte;
unsigned long v, r, gr;
struct revmap_entry *rev;
long ret = H_NOT_FOUND;
if (kvm_is_radix(kvm))
return H_FUNCTION;
if (pte_index >= kvmppc_hpt_npte(&kvm->arch.hpt))
return H_PARAMETER;
rev = real_vmalloc_addr(&kvm->arch.hpt.rev[pte_index]);
hpte = (__be64 *)(kvm->arch.hpt.virt + (pte_index << 4));
while (!try_lock_hpte(hpte, HPTE_V_HVLOCK))
cpu_relax();
v = be64_to_cpu(hpte[0]);
r = be64_to_cpu(hpte[1]);
if (!(v & (HPTE_V_VALID | HPTE_V_ABSENT)))
goto out;
gr = rev->guest_rpte;
if (gr & HPTE_R_C) {
rev->guest_rpte &= ~HPTE_R_C;
note_hpte_modification(kvm, rev);
}
if (v & HPTE_V_VALID) {
/* need to make it temporarily absent so C is stable */
hpte[0] |= cpu_to_be64(HPTE_V_ABSENT);
kvmppc_invalidate_hpte(kvm, hpte, pte_index);
r = be64_to_cpu(hpte[1]);
gr |= r & (HPTE_R_R | HPTE_R_C);
if (r & HPTE_R_C) {
hpte[1] = cpu_to_be64(r & ~HPTE_R_C);
eieio();
kvmppc_set_dirty_from_hpte(kvm, v, gr);
}
}
vcpu->arch.regs.gpr[4] = gr;
ret = H_SUCCESS;
out:
unlock_hpte(hpte, v & ~HPTE_V_HVLOCK);
return ret;
}
static int kvmppc_get_hpa(struct kvm_vcpu *vcpu, unsigned long mmu_seq,
unsigned long gpa, int writing, unsigned long *hpa,
struct kvm_memory_slot **memslot_p)
{
struct kvm *kvm = vcpu->kvm;
struct kvm_memory_slot *memslot;
unsigned long gfn, hva, pa, psize = PAGE_SHIFT;
unsigned int shift;
pte_t *ptep, pte;
/* Find the memslot for this address */
gfn = gpa >> PAGE_SHIFT;
memslot = __gfn_to_memslot(kvm_memslots_raw(kvm), gfn);
if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
return H_PARAMETER;
/* Translate to host virtual address */
hva = __gfn_to_hva_memslot(memslot, gfn);
/* Try to find the host pte for that virtual address */
ptep = find_kvm_host_pte(kvm, mmu_seq, hva, &shift);
if (!ptep)
return H_TOO_HARD;
pte = kvmppc_read_update_linux_pte(ptep, writing);
if (!pte_present(pte))
return H_TOO_HARD;
/* Convert to a physical address */
if (shift)
psize = 1UL << shift;
pa = pte_pfn(pte) << PAGE_SHIFT;
pa |= hva & (psize - 1);
pa |= gpa & ~PAGE_MASK;
if (hpa)
*hpa = pa;
if (memslot_p)
*memslot_p = memslot;
return H_SUCCESS;
}
static long kvmppc_do_h_page_init_zero(struct kvm_vcpu *vcpu,
unsigned long dest)
{
struct kvm_memory_slot *memslot;
struct kvm *kvm = vcpu->kvm;
unsigned long pa, mmu_seq;
long ret = H_SUCCESS;
int i;
/* Used later to detect if we might have been invalidated */
mmu_seq = kvm->mmu_notifier_seq;
smp_rmb();
arch_spin_lock(&kvm->mmu_lock.rlock.raw_lock);
ret = kvmppc_get_hpa(vcpu, mmu_seq, dest, 1, &pa, &memslot);
if (ret != H_SUCCESS)
goto out_unlock;
/* Zero the page */
for (i = 0; i < SZ_4K; i += L1_CACHE_BYTES, pa += L1_CACHE_BYTES)
dcbz((void *)pa);
kvmppc_update_dirty_map(memslot, dest >> PAGE_SHIFT, PAGE_SIZE);
out_unlock:
arch_spin_unlock(&kvm->mmu_lock.rlock.raw_lock);
return ret;
}
static long kvmppc_do_h_page_init_copy(struct kvm_vcpu *vcpu,
unsigned long dest, unsigned long src)
{
unsigned long dest_pa, src_pa, mmu_seq;
struct kvm_memory_slot *dest_memslot;
struct kvm *kvm = vcpu->kvm;
long ret = H_SUCCESS;
/* Used later to detect if we might have been invalidated */
mmu_seq = kvm->mmu_notifier_seq;
smp_rmb();
arch_spin_lock(&kvm->mmu_lock.rlock.raw_lock);
ret = kvmppc_get_hpa(vcpu, mmu_seq, dest, 1, &dest_pa, &dest_memslot);
if (ret != H_SUCCESS)
goto out_unlock;
ret = kvmppc_get_hpa(vcpu, mmu_seq, src, 0, &src_pa, NULL);
if (ret != H_SUCCESS)
goto out_unlock;
/* Copy the page */
memcpy((void *)dest_pa, (void *)src_pa, SZ_4K);
kvmppc_update_dirty_map(dest_memslot, dest >> PAGE_SHIFT, PAGE_SIZE);
out_unlock:
arch_spin_unlock(&kvm->mmu_lock.rlock.raw_lock);
return ret;
}
long kvmppc_rm_h_page_init(struct kvm_vcpu *vcpu, unsigned long flags,
unsigned long dest, unsigned long src)
{
struct kvm *kvm = vcpu->kvm;
u64 pg_mask = SZ_4K - 1; /* 4K page size */
long ret = H_SUCCESS;
/* Don't handle radix mode here, go up to the virtual mode handler */
if (kvm_is_radix(kvm))
return H_TOO_HARD;
/* Check for invalid flags (H_PAGE_SET_LOANED covers all CMO flags) */
if (flags & ~(H_ICACHE_INVALIDATE | H_ICACHE_SYNCHRONIZE |
H_ZERO_PAGE | H_COPY_PAGE | H_PAGE_SET_LOANED))
return H_PARAMETER;
/* dest (and src if copy_page flag set) must be page aligned */
if ((dest & pg_mask) || ((flags & H_COPY_PAGE) && (src & pg_mask)))
return H_PARAMETER;
/* zero and/or copy the page as determined by the flags */
if (flags & H_COPY_PAGE)
ret = kvmppc_do_h_page_init_copy(vcpu, dest, src);
else if (flags & H_ZERO_PAGE)
ret = kvmppc_do_h_page_init_zero(vcpu, dest);
/* We can ignore the other flags */
return ret;
}
void kvmppc_invalidate_hpte(struct kvm *kvm, __be64 *hptep,
unsigned long pte_index)
{
unsigned long rb;
u64 hp0, hp1;
hptep[0] &= ~cpu_to_be64(HPTE_V_VALID);
hp0 = be64_to_cpu(hptep[0]);
hp1 = be64_to_cpu(hptep[1]);
if (cpu_has_feature(CPU_FTR_ARCH_300)) {
hp0 = hpte_new_to_old_v(hp0, hp1);
hp1 = hpte_new_to_old_r(hp1);
}
rb = compute_tlbie_rb(hp0, hp1, pte_index);
do_tlbies(kvm, &rb, 1, 1, true);
}
EXPORT_SYMBOL_GPL(kvmppc_invalidate_hpte);
void kvmppc_clear_ref_hpte(struct kvm *kvm, __be64 *hptep,
unsigned long pte_index)
{
unsigned long rb;
unsigned char rbyte;
u64 hp0, hp1;
hp0 = be64_to_cpu(hptep[0]);
hp1 = be64_to_cpu(hptep[1]);
if (cpu_has_feature(CPU_FTR_ARCH_300)) {
hp0 = hpte_new_to_old_v(hp0, hp1);
hp1 = hpte_new_to_old_r(hp1);
}
rb = compute_tlbie_rb(hp0, hp1, pte_index);
rbyte = (be64_to_cpu(hptep[1]) & ~HPTE_R_R) >> 8;
/* modify only the second-last byte, which contains the ref bit */
*((char *)hptep + 14) = rbyte;
do_tlbies(kvm, &rb, 1, 1, false);
}
EXPORT_SYMBOL_GPL(kvmppc_clear_ref_hpte);
static int slb_base_page_shift[4] = {
24, /* 16M */
16, /* 64k */
34, /* 16G */
20, /* 1M, unsupported */
};
static struct mmio_hpte_cache_entry *mmio_cache_search(struct kvm_vcpu *vcpu,
unsigned long eaddr, unsigned long slb_v, long mmio_update)
{
struct mmio_hpte_cache_entry *entry = NULL;
unsigned int pshift;
unsigned int i;
for (i = 0; i < MMIO_HPTE_CACHE_SIZE; i++) {
entry = &vcpu->arch.mmio_cache.entry[i];
if (entry->mmio_update == mmio_update) {
pshift = entry->slb_base_pshift;
if ((entry->eaddr >> pshift) == (eaddr >> pshift) &&
entry->slb_v == slb_v)
return entry;
}
}
return NULL;
}
static struct mmio_hpte_cache_entry *
next_mmio_cache_entry(struct kvm_vcpu *vcpu)
{
unsigned int index = vcpu->arch.mmio_cache.index;
vcpu->arch.mmio_cache.index++;
if (vcpu->arch.mmio_cache.index == MMIO_HPTE_CACHE_SIZE)
vcpu->arch.mmio_cache.index = 0;
return &vcpu->arch.mmio_cache.entry[index];
}
/* When called from virtmode, this func should be protected by
* preempt_disable(), otherwise, the holding of HPTE_V_HVLOCK
* can trigger deadlock issue.
*/
long kvmppc_hv_find_lock_hpte(struct kvm *kvm, gva_t eaddr, unsigned long slb_v,
unsigned long valid)
{
unsigned int i;
unsigned int pshift;
unsigned long somask;
unsigned long vsid, hash;
unsigned long avpn;
__be64 *hpte;
unsigned long mask, val;
unsigned long v, r, orig_v;
/* Get page shift, work out hash and AVPN etc. */
mask = SLB_VSID_B | HPTE_V_AVPN | HPTE_V_SECONDARY;
val = 0;
pshift = 12;
if (slb_v & SLB_VSID_L) {
mask |= HPTE_V_LARGE;
val |= HPTE_V_LARGE;
pshift = slb_base_page_shift[(slb_v & SLB_VSID_LP) >> 4];
}
if (slb_v & SLB_VSID_B_1T) {
somask = (1UL << 40) - 1;
vsid = (slb_v & ~SLB_VSID_B) >> SLB_VSID_SHIFT_1T;
vsid ^= vsid << 25;
} else {
somask = (1UL << 28) - 1;
vsid = (slb_v & ~SLB_VSID_B) >> SLB_VSID_SHIFT;
}
hash = (vsid ^ ((eaddr & somask) >> pshift)) & kvmppc_hpt_mask(&kvm->arch.hpt);
avpn = slb_v & ~(somask >> 16); /* also includes B */
avpn |= (eaddr & somask) >> 16;
if (pshift >= 24)
avpn &= ~((1UL << (pshift - 16)) - 1);
else
avpn &= ~0x7fUL;
val |= avpn;
for (;;) {
hpte = (__be64 *)(kvm->arch.hpt.virt + (hash << 7));
for (i = 0; i < 16; i += 2) {
/* Read the PTE racily */
v = be64_to_cpu(hpte[i]) & ~HPTE_V_HVLOCK;
if (cpu_has_feature(CPU_FTR_ARCH_300))
v = hpte_new_to_old_v(v, be64_to_cpu(hpte[i+1]));
/* Check valid/absent, hash, segment size and AVPN */
if (!(v & valid) || (v & mask) != val)
continue;
/* Lock the PTE and read it under the lock */
while (!try_lock_hpte(&hpte[i], HPTE_V_HVLOCK))
cpu_relax();
v = orig_v = be64_to_cpu(hpte[i]) & ~HPTE_V_HVLOCK;
r = be64_to_cpu(hpte[i+1]);
if (cpu_has_feature(CPU_FTR_ARCH_300)) {
v = hpte_new_to_old_v(v, r);
r = hpte_new_to_old_r(r);
}
/*
* Check the HPTE again, including base page size
*/
if ((v & valid) && (v & mask) == val &&
kvmppc_hpte_base_page_shift(v, r) == pshift)
/* Return with the HPTE still locked */
return (hash << 3) + (i >> 1);
__unlock_hpte(&hpte[i], orig_v);
}
if (val & HPTE_V_SECONDARY)
break;
val |= HPTE_V_SECONDARY;
hash = hash ^ kvmppc_hpt_mask(&kvm->arch.hpt);
}
return -1;
}
EXPORT_SYMBOL(kvmppc_hv_find_lock_hpte);
/*
* Called in real mode to check whether an HPTE not found fault
* is due to accessing a paged-out page or an emulated MMIO page,
* or if a protection fault is due to accessing a page that the
* guest wanted read/write access to but which we made read-only.
* Returns a possibly modified status (DSISR) value if not
* (i.e. pass the interrupt to the guest),
* -1 to pass the fault up to host kernel mode code, -2 to do that
* and also load the instruction word (for MMIO emulation),
* or 0 if we should make the guest retry the access.
*/
long kvmppc_hpte_hv_fault(struct kvm_vcpu *vcpu, unsigned long addr,
unsigned long slb_v, unsigned int status, bool data)
{
struct kvm *kvm = vcpu->kvm;
long int index;
unsigned long v, r, gr, orig_v;
__be64 *hpte;
unsigned long valid;
struct revmap_entry *rev;
unsigned long pp, key;
struct mmio_hpte_cache_entry *cache_entry = NULL;
long mmio_update = 0;
/* For protection fault, expect to find a valid HPTE */
valid = HPTE_V_VALID;
if (status & DSISR_NOHPTE) {
valid |= HPTE_V_ABSENT;
mmio_update = atomic64_read(&kvm->arch.mmio_update);
cache_entry = mmio_cache_search(vcpu, addr, slb_v, mmio_update);
}
if (cache_entry) {
index = cache_entry->pte_index;
v = cache_entry->hpte_v;
r = cache_entry->hpte_r;
gr = cache_entry->rpte;
} else {
index = kvmppc_hv_find_lock_hpte(kvm, addr, slb_v, valid);
if (index < 0) {
if (status & DSISR_NOHPTE)
return status; /* there really was no HPTE */
return 0; /* for prot fault, HPTE disappeared */
}
hpte = (__be64 *)(kvm->arch.hpt.virt + (index << 4));
v = orig_v = be64_to_cpu(hpte[0]) & ~HPTE_V_HVLOCK;
r = be64_to_cpu(hpte[1]);
if (cpu_has_feature(CPU_FTR_ARCH_300)) {
v = hpte_new_to_old_v(v, r);
r = hpte_new_to_old_r(r);
}
rev = real_vmalloc_addr(&kvm->arch.hpt.rev[index]);
gr = rev->guest_rpte;
unlock_hpte(hpte, orig_v);
}
/* For not found, if the HPTE is valid by now, retry the instruction */
if ((status & DSISR_NOHPTE) && (v & HPTE_V_VALID))
return 0;
/* Check access permissions to the page */
pp = gr & (HPTE_R_PP0 | HPTE_R_PP);
key = (vcpu->arch.shregs.msr & MSR_PR) ? SLB_VSID_KP : SLB_VSID_KS;
status &= ~DSISR_NOHPTE; /* DSISR_NOHPTE == SRR1_ISI_NOPT */
if (!data) {
if (gr & (HPTE_R_N | HPTE_R_G))
return status | SRR1_ISI_N_G_OR_CIP;
if (!hpte_read_permission(pp, slb_v & key))
return status | SRR1_ISI_PROT;
} else if (status & DSISR_ISSTORE) {
/* check write permission */
if (!hpte_write_permission(pp, slb_v & key))
return status | DSISR_PROTFAULT;
} else {
if (!hpte_read_permission(pp, slb_v & key))
return status | DSISR_PROTFAULT;
}
/* Check storage key, if applicable */
if (data && (vcpu->arch.shregs.msr & MSR_DR)) {
unsigned int perm = hpte_get_skey_perm(gr, vcpu->arch.amr);
if (status & DSISR_ISSTORE)
perm >>= 1;
if (perm & 1)
return status | DSISR_KEYFAULT;
}
/* Save HPTE info for virtual-mode handler */
vcpu->arch.pgfault_addr = addr;
vcpu->arch.pgfault_index = index;
vcpu->arch.pgfault_hpte[0] = v;
vcpu->arch.pgfault_hpte[1] = r;
vcpu->arch.pgfault_cache = cache_entry;
/* Check the storage key to see if it is possibly emulated MMIO */
if ((r & (HPTE_R_KEY_HI | HPTE_R_KEY_LO)) ==
(HPTE_R_KEY_HI | HPTE_R_KEY_LO)) {
if (!cache_entry) {
unsigned int pshift = 12;
unsigned int pshift_index;
if (slb_v & SLB_VSID_L) {
pshift_index = ((slb_v & SLB_VSID_LP) >> 4);
pshift = slb_base_page_shift[pshift_index];
}
cache_entry = next_mmio_cache_entry(vcpu);
cache_entry->eaddr = addr;
cache_entry->slb_base_pshift = pshift;
cache_entry->pte_index = index;
cache_entry->hpte_v = v;
cache_entry->hpte_r = r;
cache_entry->rpte = gr;
cache_entry->slb_v = slb_v;
cache_entry->mmio_update = mmio_update;
}
if (data && (vcpu->arch.shregs.msr & MSR_IR))
return -2; /* MMIO emulation - load instr word */
}
return -1; /* send fault up to host kernel mode */
}
| rperier/linux-rockchip | arch/powerpc/kvm/book3s_hv_rm_mmu.c | C | gpl-2.0 | 36,079 |
/*
* This source file is public domain, as it is not based on the original tcpflow.
*
* Author: Michael Shick <[email protected]>
*/
#ifndef LEGEND_VIEW_H
#define LEGEND_VIEW_H
#include "plot_view.h"
class legend_view {
public:
// legend_view::entry to everyone else
class entry_t {
public:
entry_t(plot_view::rgb_t color_, std::string label_, uint16_t port_) :
color(color_), label(label_), port(port_) {}
plot_view::rgb_t color;
std::string label;
uint16_t port;
};
typedef std::vector<entry_t> entries_t;
legend_view(entries_t entries_) :
entries(entries_) {}
void render(cairo_t *cr, const plot_view::bounds_t &bounds) const;
static const std::string empty_legend_label;
static const double base_font_size;
static const double chip_length;
static const double chip_label_space;
static const double inter_item_space;
static const double padding;
static const double border_width;
static const plot_view::rgb_t border_color;
private:
const entries_t entries;
};
inline bool operator<(const legend_view::entry_t &a, const legend_view::entry_t &b)
{
return a.port < b.port;
}
#endif
| dougburks/tcpflow | src/netviz/legend_view.h | C | gpl-3.0 | 1,211 |
/*
Copyright © 2014-2015 by The qTox Project
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre 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.
qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#include "groupwidget.h"
#include "maskablepixmapwidget.h"
#include "contentdialog.h"
#include "src/grouplist.h"
#include "src/group.h"
#include "src/persistence/settings.h"
#include "form/groupchatform.h"
#include "src/widget/style.h"
#include "src/core/core.h"
#include "tool/croppinglabel.h"
#include "src/widget/translator.h"
#include <QPalette>
#include <QMenu>
#include <QContextMenuEvent>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QApplication>
#include <QDrag>
GroupWidget::GroupWidget(int GroupId, QString Name)
: groupId{GroupId}
{
avatar->setPixmap(Style::scaleSvgImage(":img/group.svg", avatar->width(), avatar->height()));
statusPic.setPixmap(QPixmap(":img/status/dot_online.svg"));
statusPic.setMargin(3);
nameLabel->setText(Name);
onUserListChanged();
setAcceptDrops(true);
connect(nameLabel, &CroppingLabel::editFinished, [this](const QString &newName)
{
if (!newName.isEmpty())
{
Group* g = GroupList::findGroup(groupId);
emit renameRequested(this, newName);
emit g->getChatForm()->groupTitleChanged(groupId, newName.left(128));
}
});
Translator::registerHandler(std::bind(&GroupWidget::retranslateUi, this), this);
}
GroupWidget::~GroupWidget()
{
Translator::unregister(this);
}
void GroupWidget::contextMenuEvent(QContextMenuEvent* event)
{
if (!active)
setBackgroundRole(QPalette::Highlight);
installEventFilter(this); // Disable leave event.
QMenu menu(this);
QAction* openChatWindow = nullptr;
QAction* removeChatWindow = nullptr;
ContentDialog* contentDialog = ContentDialog::getGroupDialog(groupId);
bool notAlone = contentDialog != nullptr && contentDialog->chatroomWidgetCount() > 1;
if (contentDialog == nullptr || notAlone)
openChatWindow = menu.addAction(tr("Open chat in new window"));
if (contentDialog && contentDialog->hasGroupWidget(groupId, this))
removeChatWindow = menu.addAction(tr("Remove chat from this window"));
menu.addSeparator();
QAction* setTitle = menu.addAction(tr("Set title..."));
QAction* quitGroup = menu.addAction(tr("Quit group", "Menu to quit a groupchat"));
QAction* selectedItem = menu.exec(event->globalPos());
removeEventFilter(this);
if (!active)
setBackgroundRole(QPalette::Window);
if (selectedItem)
{
if (selectedItem == quitGroup)
{
emit removeGroup(groupId);
}
else if (selectedItem == openChatWindow)
{
emit chatroomWidgetClicked(this, true);
return;
}
else if (selectedItem == removeChatWindow)
{
ContentDialog* contentDialog = ContentDialog::getGroupDialog(groupId);
contentDialog->removeGroup(groupId);
return;
}
else if (selectedItem == setTitle)
{
editName();
}
}
}
void GroupWidget::mousePressEvent(QMouseEvent *ev)
{
if (ev->button() == Qt::LeftButton)
dragStartPos = ev->pos();
GenericChatroomWidget::mousePressEvent(ev);
}
void GroupWidget::mouseMoveEvent(QMouseEvent *ev)
{
if (!(ev->buttons() & Qt::LeftButton))
return;
if ((dragStartPos - ev->pos()).manhattanLength() > QApplication::startDragDistance())
{
QDrag* drag = new QDrag(this);
QMimeData* mdata = new QMimeData;
mdata->setData("group", QString::number(groupId).toLatin1());
drag->setMimeData(mdata);
drag->setPixmap(avatar->getPixmap());
drag->exec(Qt::CopyAction | Qt::MoveAction);
}
}
void GroupWidget::onUserListChanged()
{
Group* g = GroupList::findGroup(groupId);
if (g)
{
int peersCount = g->getPeersCount();
if (peersCount == 1)
statusMessageLabel->setText(tr("1 user in chat"));
else
statusMessageLabel->setText(tr("%1 users in chat").arg(peersCount));
}
}
void GroupWidget::setAsActiveChatroom()
{
setActive(true);
avatar->setPixmap(Style::scaleSvgImage(":img/group_dark.svg", avatar->width(), avatar->height()));
}
void GroupWidget::setAsInactiveChatroom()
{
setActive(false);
avatar->setPixmap(Style::scaleSvgImage(":img/group.svg", avatar->width(), avatar->height()));
}
void GroupWidget::updateStatusLight()
{
Group *g = GroupList::findGroup(groupId);
if (!g->getEventFlag())
{
statusPic.setPixmap(QPixmap(":img/status/dot_online.svg"));
statusPic.setMargin(3);
}
else
{
statusPic.setPixmap(QPixmap(":img/status/dot_online_notification.svg"));
statusPic.setMargin(0);
}
}
QString GroupWidget::getStatusString() const
{
Group *g = GroupList::findGroup(groupId);
if (!g->getEventFlag())
return "Online";
else
return "New Message";
}
void GroupWidget::editName()
{
nameLabel->editBegin();
}
Group* GroupWidget::getGroup() const
{
return GroupList::findGroup(groupId);
}
bool GroupWidget::chatFormIsSet(bool focus) const
{
(void)focus;
Group* g = GroupList::findGroup(groupId);
return ContentDialog::existsGroupWidget(groupId, focus) || g->getChatForm()->isVisible();
}
void GroupWidget::setChatForm(ContentLayout* contentLayout)
{
Group* g = GroupList::findGroup(groupId);
g->getChatForm()->show(contentLayout);
}
void GroupWidget::resetEventFlags()
{
Group* g = GroupList::findGroup(groupId);
g->setEventFlag(false);
g->setMentionedFlag(false);
}
void GroupWidget::dragEnterEvent(QDragEnterEvent *ev)
{
if (ev->mimeData()->hasFormat("friend"))
ev->acceptProposedAction();
if (!active)
setBackgroundRole(QPalette::Highlight);
}
void GroupWidget::dragLeaveEvent(QDragLeaveEvent *)
{
if (!active)
setBackgroundRole(QPalette::Window);
}
void GroupWidget::dropEvent(QDropEvent *ev)
{
if (ev->mimeData()->hasFormat("friend"))
{
int friendId = ev->mimeData()->data("friend").toInt();
Core::getInstance()->groupInviteFriend(friendId, groupId);
if (!active)
setBackgroundRole(QPalette::Window);
}
}
void GroupWidget::setName(const QString& name)
{
nameLabel->setText(name);
}
void GroupWidget::retranslateUi()
{
Group* g = GroupList::findGroup(groupId);
if (g)
{
int peersCount = g->getPeersCount();
if (peersCount == 1)
statusMessageLabel->setText(tr("1 user in chat"));
else
statusMessageLabel->setText(tr("%1 users in chat").arg(peersCount));
}
}
| ovalseven8/qTox | src/widget/groupwidget.cpp | C++ | gpl-3.0 | 7,345 |
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.webkit;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.provider.Browser;
import android.util.Log;
import java.io.File;
import java.util.HashMap;
import java.util.Vector;
/**
* Functions for manipulating the icon database used by WebView.
* These functions require that a WebView be constructed before being invoked
* and WebView.getIconDatabase() will return a WebIconDatabase object. This
* WebIconDatabase object is a single instance and all methods operate on that
* single object.
*/
public final class WebIconDatabase {
private static final String LOGTAG = "WebIconDatabase";
// Global instance of a WebIconDatabase
private static WebIconDatabase sIconDatabase;
// EventHandler for handling messages before and after the WebCore thread is
// ready.
private final EventHandler mEventHandler = new EventHandler();
// Class to handle messages before WebCore is ready
private static class EventHandler extends Handler {
// Message ids
static final int OPEN = 0;
static final int CLOSE = 1;
static final int REMOVE_ALL = 2;
static final int REQUEST_ICON = 3;
static final int RETAIN_ICON = 4;
static final int RELEASE_ICON = 5;
static final int BULK_REQUEST_ICON = 6;
// Message for dispatching icon request results
private static final int ICON_RESULT = 10;
// Actual handler that runs in WebCore thread
private Handler mHandler;
// Vector of messages before the WebCore thread is ready
private Vector<Message> mMessages = new Vector<Message>();
// Class to handle a result dispatch
private class IconResult {
private final String mUrl;
private final Bitmap mIcon;
private final IconListener mListener;
IconResult(String url, Bitmap icon, IconListener l) {
mUrl = url;
mIcon = icon;
mListener = l;
}
void dispatch() {
mListener.onReceivedIcon(mUrl, mIcon);
}
}
@Override
public void handleMessage(Message msg) {
// Note: This is the message handler for the UI thread.
switch (msg.what) {
case ICON_RESULT:
((IconResult) msg.obj).dispatch();
break;
}
}
// Called by WebCore thread to create the actual handler
private synchronized void createHandler() {
if (mHandler == null) {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Note: This is the message handler for the WebCore
// thread.
switch (msg.what) {
case OPEN:
nativeOpen((String) msg.obj);
break;
case CLOSE:
nativeClose();
break;
case REMOVE_ALL:
nativeRemoveAllIcons();
break;
case REQUEST_ICON:
IconListener l = (IconListener) msg.obj;
String url = msg.getData().getString("url");
requestIconAndSendResult(url, l);
break;
case BULK_REQUEST_ICON:
bulkRequestIcons(msg);
break;
case RETAIN_ICON:
nativeRetainIconForPageUrl((String) msg.obj);
break;
case RELEASE_ICON:
nativeReleaseIconForPageUrl((String) msg.obj);
break;
}
}
};
// Transfer all pending messages
for (int size = mMessages.size(); size > 0; size--) {
mHandler.sendMessage(mMessages.remove(0));
}
mMessages = null;
}
}
private synchronized boolean hasHandler() {
return mHandler != null;
}
private synchronized void postMessage(Message msg) {
if (mMessages != null) {
mMessages.add(msg);
} else {
mHandler.sendMessage(msg);
}
}
private void bulkRequestIcons(Message msg) {
HashMap map = (HashMap) msg.obj;
IconListener listener = (IconListener) map.get("listener");
ContentResolver cr = (ContentResolver) map.get("contentResolver");
String where = (String) map.get("where");
Cursor c = null;
try {
c = cr.query(
Browser.BOOKMARKS_URI,
new String[] { Browser.BookmarkColumns.URL },
where, null, null);
if (c.moveToFirst()) {
do {
String url = c.getString(0);
requestIconAndSendResult(url, listener);
} while (c.moveToNext());
}
} catch (IllegalStateException e) {
Log.e(LOGTAG, "BulkRequestIcons", e);
} finally {
if (c != null) c.close();
}
}
private void requestIconAndSendResult(String url, IconListener listener) {
Bitmap icon = nativeIconForPageUrl(url);
if (icon != null) {
sendMessage(obtainMessage(ICON_RESULT,
new IconResult(url, icon, listener)));
}
}
}
/**
* Interface for receiving icons from the database.
*/
public interface IconListener {
/**
* Called when the icon has been retrieved from the database and the
* result is non-null.
* @param url The url passed in the request.
* @param icon The favicon for the given url.
*/
public void onReceivedIcon(String url, Bitmap icon);
}
/**
* Open a the icon database and store the icons in the given path.
* @param path The directory path where the icon database will be stored.
*/
public void open(String path) {
if (path != null) {
// Make the directories and parents if they don't exist
File db = new File(path);
if (!db.exists()) {
db.mkdirs();
}
mEventHandler.postMessage(
Message.obtain(null, EventHandler.OPEN, db.getAbsolutePath()));
}
}
/**
* Close the shared instance of the icon database.
*/
public void close() {
mEventHandler.postMessage(
Message.obtain(null, EventHandler.CLOSE));
}
/**
* Removes all the icons in the database.
*/
public void removeAllIcons() {
mEventHandler.postMessage(
Message.obtain(null, EventHandler.REMOVE_ALL));
}
/**
* Request the Bitmap representing the icon for the given page
* url. If the icon exists, the listener will be called with the result.
* @param url The page's url.
* @param listener An implementation on IconListener to receive the result.
*/
public void requestIconForPageUrl(String url, IconListener listener) {
if (listener == null || url == null) {
return;
}
Message msg = Message.obtain(null, EventHandler.REQUEST_ICON, listener);
msg.getData().putString("url", url);
mEventHandler.postMessage(msg);
}
/** {@hide}
*/
public void bulkRequestIconForPageUrl(ContentResolver cr, String where,
IconListener listener) {
if (listener == null) {
return;
}
// Special case situation: we don't want to add this message to the
// queue if there is no handler because we may never have a real
// handler to service the messages and the cursor will never get
// closed.
if (mEventHandler.hasHandler()) {
// Don't use Bundle as it is parcelable.
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("contentResolver", cr);
map.put("where", where);
map.put("listener", listener);
Message msg =
Message.obtain(null, EventHandler.BULK_REQUEST_ICON, map);
mEventHandler.postMessage(msg);
}
}
/**
* Retain the icon for the given page url.
* @param url The page's url.
*/
public void retainIconForPageUrl(String url) {
if (url != null) {
mEventHandler.postMessage(
Message.obtain(null, EventHandler.RETAIN_ICON, url));
}
}
/**
* Release the icon for the given page url.
* @param url The page's url.
*/
public void releaseIconForPageUrl(String url) {
if (url != null) {
mEventHandler.postMessage(
Message.obtain(null, EventHandler.RELEASE_ICON, url));
}
}
/**
* Get the global instance of WebIconDatabase.
* @return A single instance of WebIconDatabase. It will be the same
* instance for the current process each time this method is
* called.
*/
public static WebIconDatabase getInstance() {
// XXX: Must be created in the UI thread.
if (sIconDatabase == null) {
sIconDatabase = new WebIconDatabase();
}
return sIconDatabase;
}
/**
* Create the internal handler and transfer all pending messages.
* XXX: Called by WebCore thread only!
*/
/*package*/ void createHandler() {
mEventHandler.createHandler();
}
/**
* Private constructor to avoid anyone else creating an instance.
*/
private WebIconDatabase() {}
// Native functions
private static native void nativeOpen(String path);
private static native void nativeClose();
private static native void nativeRemoveAllIcons();
private static native Bitmap nativeIconForPageUrl(String url);
private static native void nativeRetainIconForPageUrl(String url);
private static native void nativeReleaseIconForPageUrl(String url);
}
| mateor/PDroidHistory | frameworks/base/core/java/android/webkit/WebIconDatabase.java | Java | gpl-3.0 | 11,435 |
--
-- Type: VIEW; Owner: SEARCHAPP; Name: SEARCH_TAXONOMY_LEVEL3
--
CREATE OR REPLACE FORCE VIEW "SEARCHAPP"."SEARCH_TAXONOMY_LEVEL3" ("TERM_ID", "TERM_NAME", "CATEGORY_NAME") AS
SELECT st.term_id,
st.term_name,
stl2.category_name
FROM searchapp.search_taxonomy_rels str,
search_taxonomy st,
search_taxonomy_level2 stl2
WHERE ((str.parent_id = stl2.term_id) AND (str.child_id = st.term_id));
| JanKanis/transmart-data | ddl/oracle/searchapp/views/search_taxonomy_level3.sql | SQL | gpl-3.0 | 408 |
<?php
namespace Sabre\VObject\Recur\EventIterator;
use Sabre\VObject\Recur;
use Sabre\VObject\Reader;
class FifthTuesdayProblemTest extends \PHPUnit_Framework_TestCase {
/**
* A pretty slow test. Had to be marked as 'medium' for phpunit to not die
* after 1 second. Would be good to optimize later.
*
* @medium
*/
function testGetDTEnd() {
$ics = <<<ICS
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Apple Inc.//iCal 4.0.4//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
TRANSP:OPAQUE
DTEND;TZID=America/New_York:20070925T170000
UID:uuid
DTSTAMP:19700101T000000Z
LOCATION:
DESCRIPTION:
STATUS:CONFIRMED
SEQUENCE:18
SUMMARY:Stuff
DTSTART;TZID=America/New_York:20070925T160000
CREATED:20071004T144642Z
RRULE:FREQ=MONTHLY;INTERVAL=1;UNTIL=20071030T035959Z;BYDAY=5TU
END:VEVENT
END:VCALENDAR
ICS;
$vObject = Reader::read($ics);
$it = new Recur\EventIterator($vObject, (string)$vObject->VEVENT->UID);
while ($it->valid()) {
$it->next();
}
// If we got here, it means we were successful. The bug that was in the
// system before would fail on the 5th tuesday of the month, if the 5th
// tuesday did not exist.
$this->assertTrue(true);
}
}
| bridystone/baikal | vendor/sabre/vobject/tests/VObject/Recur/EventIterator/FifthTuesdayProblemTest.php | PHP | gpl-3.0 | 1,244 |
<html>
<head>
<title>Network GWT documentation</title>
<link rel='stylesheet' href='default.css' type='text/css'>
<link href="prettify/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="prettify/prettify.js"></script>
</head>
<body onload="prettyPrint();">
<h1>Network GWT documentation</h1>
<p>
There is a GWT wrapper available to use the Network inside Google Web
Toolkit (GWT).
This documentation assumes you have Eclipse installed, and have GWT
installed in Eclipse.
</p>
<h2>Short guide</h2>
<p>
To use the GWT version of the Network, create a GWT project. Put a copy of the
modules <b><a href="http://almende.github.com/chap-links-library/downloads.html">gwt-links-network.jar</a></b> and
<b><a href="http://code.google.com/p/gwt-google-apis/downloads/" target="_blank">gwt-visualization.jar</a></b>
in a subfolder of your project (for example lib),
and add both jar-modules to your project via "Build path", "Configure Build Path...", "Add JARs...".
Then, add the following lines to the module file YourProject.gwt.xml:
</p>
<pre class="prettyprint lang-html"><!-- Other module inherits -->
<inherits name='com.google.gwt.visualization.Visualization'/>
<inherits name='com.chap.links.Network'/>
</pre>
<p>
Thats all, now you can use the Network visualization.
</p>
<p>
Open the main HTML file of your project, located in the directory war
(typically war/YourProject.html). In there, create a DIV the id "mynetwork".
</p>
<pre class="prettyprint lang-html">
<html>
<head>
...
</head>
<body>
...
<div id="mynetwork"></div>
...
</body>
</html> </pre>
<p>
Open the entry point java file of your project (typically YourProject.java),
and add code to create a datatable with nodes, create a datatable with links,
specify some options, and create a Network widget.
</p>
<pre class="prettyprint lang-java">
package com.yourproject.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.chap.links.client.Network;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class YourProject implements EntryPoint {
Network network = null;
/**
* This is the entry point method.
*/
public void onModuleLoad() {
// Create a callback to be called when the visualization API
// has been loaded.
Runnable onLoadCallback = new Runnable() {
public void run() {
// Create nodes table with some data
DataTable nodes = DataTable.create();
nodes.addColumn(DataTable.ColumnType.NUMBER, "id");
nodes.addColumn(DataTable.ColumnType.STRING, "text");
nodes.addRow();
int i = 0;
nodes.setValue(i, 0, 1);
nodes.setValue(i, 1, "Node 1");
nodes.addRow();
i++;
nodes.setValue(i, 0, 2);
nodes.setValue(i, 1, "Node 2");
nodes.addRow();
i++;
nodes.setValue(i, 0, 3);
nodes.setValue(i, 1, "Node 3");
// Create links table with some data
DataTable links = DataTable.create();
links.addColumn(DataTable.ColumnType.NUMBER, "from");
links.addColumn(DataTable.ColumnType.NUMBER, "to");
links.addRow();
i = 0;
links.setValue(i, 0, 1);
links.setValue(i, 1, 2);
links.addRow();
i++;
links.setValue(i, 0, 1);
links.setValue(i, 1, 3);
links.addRow();
i++;
links.setValue(i, 0, 2);
links.setValue(i, 1, 3);
// Create options
Network.Options options = Network.Options.create();
options.setWidth("300px");
options.setHeight("300px");
// create the visualization, with data and options
network = new Network(nodes, links, options);
RootPanel.get("mynetwork").add(network);
}
};
// Load the visualization api, passing the onLoadCallback to be called
// when loading is done.
VisualizationUtils.loadVisualizationApi(onLoadCallback);
}
}</pre>
<h2>Documentation</h2>
<p>
At the moment there is no documentation available for the GWT version of the
Network.
Please use the javascript documentation, which describes the
available methods, data format, options, events, and styles.
</p>
<p>
<a href="http://links.sf.net/network/js/doc">Javascript documentation</a>
</p>
<h2>Reference sites</h2>
<p><a href="http://code.google.com/p/gwt-google-apis/wiki/VisualizationGettingStarted" target="_blank">http://code.google.com/p/gwt-google-apis/wiki/VisualizationGettingStarted</a></p>
<div style="height:50px;"></div>
</body>
</html>
| say2joe/fedkit | js/graphing/chap-links-library/gwt/src/Network/doc/index.html | HTML | gpl-3.0 | 5,196 |
// Copyright (c) Athena Dev Teams - Licensed under GNU GPL
// For more information, see LICENCE in the main folder
#include "../common/cbasetypes.h"
#include "../common/timer.h"
#include "../common/nullpo.h"
#include "../common/malloc.h"
#include "../common/showmsg.h"
#include "../common/strlib.h"
#include "../common/utils.h"
#include "../common/ers.h"
#include "../common/db.h"
#include "map.h"
#include "log.h"
#include "clif.h"
#include "intif.h"
#include "pc.h"
#include "pet.h"
#include "instance.h"
#include "chat.h"
#include <stdlib.h>
#include <errno.h>
struct npc_data* fake_nd;
// linked list of npc source files
struct npc_src_list {
struct npc_src_list* next;
char name[4]; // dynamic array, the structure is allocated with extra bytes (string length)
};
static struct npc_src_list* npc_src_files = NULL;
static int npc_id=START_NPC_NUM;
static int npc_warp=0;
static int npc_shop=0;
static int npc_script=0;
static int npc_mob=0;
static int npc_delay_mob=0;
static int npc_cache_mob=0;
// Market Shop
#if PACKETVER >= 20131223
struct s_npc_market {
struct npc_item_list *list;
char exname[NAME_LENGTH+1];
uint16 count;
};
static DBMap *NPCMarketDB; /// Stock persistency! Temporary market stocks from `market` table. struct s_npc_market, key: NPC exname
static void npc_market_checkall(void);
static void npc_market_fromsql(void);
#define npc_market_delfromsql(exname,nameid) (npc_market_delfromsql_((exname), (nameid), false))
#define npc_market_clearfromsql(exname) (npc_market_delfromsql_((exname), 0, true))
#endif
/// Returns a new npc id that isn't being used in id_db.
/// Fatal error if nothing is available.
int npc_get_new_npc_id(void) {
if( npc_id >= START_NPC_NUM && !map_blid_exists(npc_id) )
return npc_id++;// available
else {// find next id
int base_id = npc_id;
while( base_id != ++npc_id ) {
if( npc_id < START_NPC_NUM )
npc_id = START_NPC_NUM;
if( !map_blid_exists(npc_id) )
return npc_id++;// available
}
// full loop, nothing available
ShowFatalError("npc_get_new_npc_id: All ids are taken. Exiting...");
exit(1);
}
}
static DBMap* ev_db; // const char* event_name -> struct event_data*
static DBMap* npcname_db; // const char* npc_name -> struct npc_data*
struct event_data {
struct npc_data *nd;
int pos;
};
static struct eri *timer_event_ers; //For the npc timer data. [Skotlex]
/* hello */
static char *npc_last_path;
static char *npc_last_ref;
struct npc_path_data {
char* path;
unsigned short references;
};
struct npc_path_data *npc_last_npd;
static DBMap *npc_path_db;
//For holding the view data of npc classes. [Skotlex]
static struct view_data npc_viewdb[MAX_NPC_CLASS];
static struct view_data npc_viewdb2[MAX_NPC_CLASS2_END-MAX_NPC_CLASS2_START];
static struct script_event_s
{ //Holds pointers to the commonly executed scripts for speedup. [Skotlex]
struct event_data *event[UCHAR_MAX];
const char *event_name[UCHAR_MAX];
uint8 event_count;
} script_event[NPCE_MAX];
struct view_data* npc_get_viewdata(int class_)
{ //Returns the viewdata for normal npc classes.
if( class_ == INVISIBLE_CLASS )
return &npc_viewdb[0];
if (npcdb_checkid(class_) || class_ == WARP_CLASS){
if( class_ > MAX_NPC_CLASS2_START ){
return &npc_viewdb2[class_-MAX_NPC_CLASS2_START];
}else{
return &npc_viewdb[class_];
}
}
return NULL;
}
int npc_isnear_sub(struct block_list* bl, va_list args) {
struct npc_data *nd = (struct npc_data*)bl;
int skill_id = va_arg(args, int);
if (skill_id > 0) { //If skill_id > 0 that means is used for INF2_NO_NEARNPC [Cydh]
uint16 idx = skill_get_index(skill_id);
if (idx > 0 && skill_db[idx]->unit_nonearnpc_type) {
while (1) {
if (skill_db[idx]->unit_nonearnpc_type&1 && nd->subtype == NPCTYPE_WARP) break;
if (skill_db[idx]->unit_nonearnpc_type&2 && nd->subtype == NPCTYPE_SHOP) break;
if (skill_db[idx]->unit_nonearnpc_type&4 && nd->subtype == NPCTYPE_SCRIPT) break;
if (skill_db[idx]->unit_nonearnpc_type&8 && nd->subtype == NPCTYPE_TOMB) break;
return 0;
}
}
}
if( nd->sc.option & (OPTION_HIDE|OPTION_INVISIBLE) )
return 0;
return 1;
}
bool npc_isnear(struct block_list * bl) {
if( battle_config.min_npc_vendchat_distance > 0 &&
map_foreachinrange(npc_isnear_sub,bl, battle_config.min_npc_vendchat_distance, BL_NPC, 0) )
return true;
return false;
}
int npc_ontouch_event(struct map_session_data *sd, struct npc_data *nd)
{
char name[EVENT_NAME_LENGTH];
if( nd->touching_id )
return 0; // Attached a player already. Can't trigger on anyone else.
if( pc_ishiding(sd) )
return 1; // Can't trigger 'OnTouch_'. try 'OnTouch' later.
snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_name);
return npc_event(sd,name,1);
}
int npc_ontouch2_event(struct map_session_data *sd, struct npc_data *nd)
{
char name[EVENT_NAME_LENGTH];
if( sd->areanpc_id == nd->bl.id )
return 0;
snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch2_name);
return npc_event(sd,name,2);
}
/*==========================================
* Sub-function of npc_enable, runs OnTouch event when enabled
*------------------------------------------*/
int npc_enable_sub(struct block_list *bl, va_list ap)
{
struct npc_data *nd;
nullpo_ret(bl);
nullpo_ret(nd=va_arg(ap,struct npc_data *));
if(bl->type == BL_PC)
{
TBL_PC *sd = (TBL_PC*)bl;
if (nd->sc.option&OPTION_INVISIBLE)
return 1;
if( npc_ontouch_event(sd,nd) > 0 && npc_ontouch2_event(sd,nd) > 0 )
{ // failed to run OnTouch event, so just click the npc
if (sd->npc_id != 0)
return 0;
pc_stop_walking(sd,1);
npc_click(sd,nd);
}
}
return 0;
}
/*==========================================
* Disable / Enable NPC
*------------------------------------------*/
int npc_enable(const char* name, int flag)
{
struct npc_data* nd = npc_name2id(name);
if (nd==NULL)
{
ShowError("npc_enable: Attempted to %s a non-existing NPC '%s' (flag=%d).\n", (flag&3) ? "show" : "hide", name, flag);
return 0;
}
if (flag&1) {
nd->sc.option&=~OPTION_INVISIBLE;
clif_spawn(&nd->bl);
} else if (flag&2)
nd->sc.option&=~OPTION_HIDE;
else if (flag&4)
nd->sc.option|= OPTION_HIDE;
else { //Can't change the view_data to invisible class because the view_data for all npcs is shared! [Skotlex]
nd->sc.option|= OPTION_INVISIBLE;
clif_clearunit_area(&nd->bl,CLR_OUTSIGHT); // Hack to trick maya purple card [Xazax]
}
if (nd->class_ == WARP_CLASS || nd->class_ == FLAG_CLASS)
{ //Client won't display option changes for these classes [Toms]
if (nd->sc.option&(OPTION_HIDE|OPTION_INVISIBLE))
clif_clearunit_area(&nd->bl, CLR_OUTSIGHT);
else
clif_spawn(&nd->bl);
} else
clif_changeoption(&nd->bl);
if( flag&3 && (nd->u.scr.xs >= 0 || nd->u.scr.ys >= 0) ) //check if player standing on a OnTouchArea
map_foreachinarea( npc_enable_sub, nd->bl.m, nd->bl.x-nd->u.scr.xs, nd->bl.y-nd->u.scr.ys, nd->bl.x+nd->u.scr.xs, nd->bl.y+nd->u.scr.ys, BL_PC, nd );
return 0;
}
/*==========================================
* NPC lookup (get npc_data through npcname)
*------------------------------------------*/
struct npc_data* npc_name2id(const char* name)
{
return (struct npc_data *) strdb_get(npcname_db, name);
}
/**
* For the Secure NPC Timeout option (check config/Secure.h) [RR]
**/
#ifdef SECURE_NPCTIMEOUT
/**
* Timer to check for idle time and timeout the dialog if necessary
**/
int npc_rr_secure_timeout_timer(int tid, unsigned int tick, int id, intptr_t data) {
struct map_session_data* sd = NULL;
unsigned int timeout = NPC_SECURE_TIMEOUT_NEXT;
int cur_tick = gettick(); //ensure we are on last tick
if( (sd = map_id2sd(id)) == NULL || !sd->npc_id ) {
if( sd ) sd->npc_idle_timer = INVALID_TIMER;
return 0;//Not logged in anymore OR no longer attached to a npc
}
switch( sd->npc_idle_type ) {
case NPCT_INPUT:
timeout = NPC_SECURE_TIMEOUT_INPUT;
break;
case NPCT_MENU:
timeout = NPC_SECURE_TIMEOUT_MENU;
break;
//case NPCT_WAIT: var starts with this value
}
if( DIFF_TICK(cur_tick,sd->npc_idle_tick) > (timeout*1000) ) {
pc_close_npc(sd,1);
} else if(sd->st && (sd->st->state == END || sd->st->state == CLOSE)){
sd->npc_idle_timer = INVALID_TIMER; //stop timer the script is already ending
} else { //Create a new instance of ourselves to continue
sd->npc_idle_timer = add_timer(cur_tick + (SECURE_NPCTIMEOUT_INTERVAL*1000),npc_rr_secure_timeout_timer,sd->bl.id,0);
}
return 0;
}
#endif
/*==========================================
* Dequeue event and add timer for execution (100ms)
*------------------------------------------*/
int npc_event_dequeue(struct map_session_data* sd)
{
nullpo_ret(sd);
if(sd->npc_id)
{ //Current script is aborted.
if(sd->state.using_fake_npc){
clif_clearunit_single(sd->npc_id, CLR_OUTSIGHT, sd->fd);
sd->state.using_fake_npc = 0;
}
if (sd->st) {
script_free_state(sd->st);
sd->st = NULL;
}
sd->npc_id = 0;
}
if (!sd->eventqueue[0][0])
return 0; //Nothing to dequeue
if (!pc_addeventtimer(sd,100,sd->eventqueue[0]))
{ //Failed to dequeue, couldn't set a timer.
ShowWarning("npc_event_dequeue: event timer is full !\n");
return 0;
}
//Event dequeued successfully, shift other elements.
memmove(sd->eventqueue[0], sd->eventqueue[1], (MAX_EVENTQUEUE-1)*sizeof(sd->eventqueue[0]));
sd->eventqueue[MAX_EVENTQUEUE-1][0]=0;
return 1;
}
/*==========================================
* exports a npc event label
* called from npc_parse_script
*------------------------------------------*/
static int npc_event_export(struct npc_data *nd, int i)
{
char* lname = nd->u.scr.label_list[i].name;
int pos = nd->u.scr.label_list[i].pos;
if ((lname[0] == 'O' || lname[0] == 'o') && (lname[1] == 'N' || lname[1] == 'n')) {
struct event_data *ev;
char buf[EVENT_NAME_LENGTH];
snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, lname);
// generate the data and insert it
CREATE(ev, struct event_data, 1);
ev->nd = nd;
ev->pos = pos;
if (strdb_put(ev_db, buf, ev)) // There was already another event of the same name?
return 1;
}
return 0;
}
int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname); //[Lance]
/**
* Exec name (NPC events) on player or global
* Do on all NPC when called with foreach
* @see DBApply
*/
int npc_event_doall_sub(DBKey key, DBData *data, va_list ap)
{
const char* p = key.str;
struct event_data* ev;
int* c;
const char* name;
int rid;
nullpo_ret(ev = db_data2ptr(data));
nullpo_ret(c = va_arg(ap, int *));
nullpo_ret(name = va_arg(ap, const char *));
rid = va_arg(ap, int);
p = strchr(p, ':'); // match only the event name
if( p && strcmpi(name, p) == 0 /* && !ev->nd->src_id */ ) // Do not run on duplicates. [Paradox924X]
{
if(rid) // a player may only have 1 script running at the same time
npc_event_sub(map_id2sd(rid),ev,key.str);
else
run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
(*c)++;
}
return 0;
}
/**
* @see DBApply
*/
static int npc_event_do_sub(DBKey key, DBData *data, va_list ap)
{
const char* p = key.str;
struct event_data* ev;
int* c, rid;
const char* name;
nullpo_ret(ev = db_data2ptr(data));
nullpo_ret(c = va_arg(ap, int *));
nullpo_ret(name = va_arg(ap, const char *));
rid = va_arg(ap, int);
if( p && strcmpi(name, p) == 0 )
{
run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
(*c)++;
}
return 0;
}
int npc_event_do_id(const char* name, int rid) {
int c = 0;
if( name[0] == ':' && name[1] == ':' )
ev_db->foreach(ev_db,npc_event_doall_sub,&c,name,0,rid);
else
ev_db->foreach(ev_db,npc_event_do_sub,&c,name,rid);
return c;
}
// runs the specified event (supports both single-npc and global events)
int npc_event_do(const char* name) {
return npc_event_do_id(name, 0);
}
// runs the specified event (global only)
int npc_event_doall(const char* name)
{
return npc_event_doall_id(name, 0);
}
// runs the specified event, with a RID attached (global only)
int npc_event_doall_id(const char* name, int rid)
{
int c = 0;
char buf[64];
safesnprintf(buf, sizeof(buf), "::%s", name);
ev_db->foreach(ev_db,npc_event_doall_sub,&c,buf,rid);
return c;
}
/*==========================================
* Clock event execution
* OnMinute/OnClock/OnHour/OnDay/OnDDHHMM
*------------------------------------------*/
int npc_event_do_clock(int tid, unsigned int tick, int id, intptr_t data)
{
static struct tm ev_tm_b; // tracks previous execution time
time_t timer;
struct tm* t;
char buf[64];
int c = 0;
timer = time(NULL);
t = localtime(&timer);
if (t->tm_min != ev_tm_b.tm_min ) {
char* day;
switch (t->tm_wday) {
case 0: day = "Sun"; break;
case 1: day = "Mon"; break;
case 2: day = "Tue"; break;
case 3: day = "Wed"; break;
case 4: day = "Thu"; break;
case 5: day = "Fri"; break;
case 6: day = "Sat"; break;
default:day = ""; break;
}
sprintf(buf,"OnMinute%02d",t->tm_min);
c += npc_event_doall(buf);
sprintf(buf,"OnClock%02d%02d",t->tm_hour,t->tm_min);
c += npc_event_doall(buf);
sprintf(buf,"On%s%02d%02d",day,t->tm_hour,t->tm_min);
c += npc_event_doall(buf);
}
if (t->tm_hour != ev_tm_b.tm_hour) {
sprintf(buf,"OnHour%02d",t->tm_hour);
c += npc_event_doall(buf);
}
if (t->tm_mday != ev_tm_b.tm_mday) {
sprintf(buf,"OnDay%02d%02d",t->tm_mon+1,t->tm_mday);
c += npc_event_doall(buf);
}
memcpy(&ev_tm_b,t,sizeof(ev_tm_b));
return c;
}
/*==========================================
* OnInit Event execution (the start of the event and watch)
*------------------------------------------*/
void npc_event_do_oninit(void)
{
ShowStatus("Event '"CL_WHITE"OnInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs."CL_CLL"\n", npc_event_doall("OnInit"));
add_timer_interval(gettick()+100,npc_event_do_clock,0,0,1000);
}
/*==========================================
* Incorporation of the label for the timer event
* called from npc_parse_script
*------------------------------------------*/
int npc_timerevent_export(struct npc_data *nd, int i)
{
int t = 0, k = 0;
char *lname = nd->u.scr.label_list[i].name;
int pos = nd->u.scr.label_list[i].pos;
if (sscanf(lname, "OnTimer%d%n", &t, &k) == 1 && lname[k] == '\0') {
// Timer event
struct npc_timerevent_list *te = nd->u.scr.timer_event;
int j, k2 = nd->u.scr.timeramount;
if (te == NULL)
te = (struct npc_timerevent_list *)aMalloc(sizeof(struct npc_timerevent_list));
else
te = (struct npc_timerevent_list *)aRealloc( te, sizeof(struct npc_timerevent_list) * (k2+1) );
for (j = 0; j < k2; j++) {
if (te[j].timer > t) {
memmove(te+j+1, te+j, sizeof(struct npc_timerevent_list)*(k2-j));
break;
}
}
te[j].timer = t;
te[j].pos = pos;
nd->u.scr.timer_event = te;
nd->u.scr.timeramount++;
}
return 0;
}
struct timer_event_data {
int rid; //Attached player for this timer.
int next; //timer index (starts with 0, then goes up to nd->u.scr.timeramount)
int time; //holds total time elapsed for the script from when timer was started to when last time the event triggered.
};
/*==========================================
* triger 'OnTimerXXXX' events
*------------------------------------------*/
int npc_timerevent(int tid, unsigned int tick, int id, intptr_t data)
{
int old_rid, old_timer;
unsigned int old_tick;
struct npc_data* nd=(struct npc_data *)map_id2bl(id);
struct npc_timerevent_list *te;
struct timer_event_data *ted = (struct timer_event_data*)data;
struct map_session_data *sd=NULL;
if( nd == NULL )
{
ShowError("npc_timerevent: NPC not found??\n");
return 0;
}
if( ted->rid && !(sd = map_id2sd(ted->rid)) )
{
ShowError("npc_timerevent: Attached player not found.\n");
ers_free(timer_event_ers, ted);
return 0;
}
// These stuffs might need to be restored.
old_rid = nd->u.scr.rid;
old_tick = nd->u.scr.timertick;
old_timer = nd->u.scr.timer;
// Set the values of the timer
nd->u.scr.rid = sd?sd->bl.id:0; //attached rid
nd->u.scr.timertick = tick; //current time tick
nd->u.scr.timer = ted->time; //total time from beginning to now
// Locate the event
te = nd->u.scr.timer_event + ted->next;
// Arrange for the next event
ted->next++;
if( nd->u.scr.timeramount > ted->next )
{
int next;
next = nd->u.scr.timer_event[ ted->next ].timer - nd->u.scr.timer_event[ ted->next - 1 ].timer;
ted->time += next;
if( sd )
sd->npc_timer_id = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
else
nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
}
else
{
if( sd )
sd->npc_timer_id = INVALID_TIMER;
else
nd->u.scr.timerid = INVALID_TIMER;
ers_free(timer_event_ers, ted);
}
// Run the script
run_script(nd->u.scr.script,te->pos,nd->u.scr.rid,nd->bl.id);
nd->u.scr.rid = old_rid; // Attached-rid should be restored anyway.
if( sd )
{ // Restore previous data, only if this timer is a player-attached one.
nd->u.scr.timer = old_timer;
nd->u.scr.timertick = old_tick;
}
return 0;
}
/*==========================================
* Start/Resume NPC timer
*------------------------------------------*/
int npc_timerevent_start(struct npc_data* nd, int rid)
{
int j;
unsigned int tick = gettick();
struct map_session_data *sd = NULL; //Player to whom script is attached.
nullpo_ret(nd);
// Check if there is an OnTimer Event
ARR_FIND( 0, nd->u.scr.timeramount, j, nd->u.scr.timer_event[j].timer > nd->u.scr.timer );
if( nd->u.scr.rid > 0 && !(sd = map_id2sd(nd->u.scr.rid)) )
{ // Failed to attach timer to this player.
ShowError("npc_timerevent_start: Attached player not found!\n");
return 1;
}
// Check if timer is already started.
if( sd )
{
if( sd->npc_timer_id != INVALID_TIMER )
return 0;
}
else if( nd->u.scr.timerid != INVALID_TIMER || nd->u.scr.timertick )
return 0;
if (j < nd->u.scr.timeramount)
{
int next;
struct timer_event_data *ted;
// Arrange for the next event
ted = ers_alloc(timer_event_ers, struct timer_event_data);
ted->next = j; // Set event index
ted->time = nd->u.scr.timer_event[j].timer;
next = nd->u.scr.timer_event[j].timer - nd->u.scr.timer;
if( sd )
{
ted->rid = sd->bl.id; // Attach only the player if attachplayerrid was used.
sd->npc_timer_id = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
}
else
{
ted->rid = 0;
nd->u.scr.timertick = tick; // Set when timer is started
nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
}
}
else if (!sd)
{
nd->u.scr.timertick = tick;
}
return 0;
}
/*==========================================
* Stop NPC timer
*------------------------------------------*/
int npc_timerevent_stop(struct npc_data* nd)
{
struct map_session_data *sd = NULL;
int *tid;
nullpo_ret(nd);
if( nd->u.scr.rid && !(sd = map_id2sd(nd->u.scr.rid)) )
{
ShowError("npc_timerevent_stop: Attached player not found!\n");
return 1;
}
tid = sd?&sd->npc_timer_id:&nd->u.scr.timerid;
if( *tid == INVALID_TIMER && (sd || !nd->u.scr.timertick) ) // Nothing to stop
return 0;
// Delete timer
if ( *tid != INVALID_TIMER )
{
const struct TimerData *td = NULL;
td = get_timer(*tid);
if( td && td->data )
ers_free(timer_event_ers, (void*)td->data);
delete_timer(*tid,npc_timerevent);
*tid = INVALID_TIMER;
}
if( !sd && nd->u.scr.timertick )
{
nd->u.scr.timer += DIFF_TICK(gettick(),nd->u.scr.timertick); // Set 'timer' to the time that has passed since the beginning of the timers
nd->u.scr.timertick = 0; // Set 'tick' to zero so that we know it's off.
}
return 0;
}
/*==========================================
* Aborts a running NPC timer that is attached to a player.
*------------------------------------------*/
void npc_timerevent_quit(struct map_session_data* sd)
{
const struct TimerData *td;
struct npc_data* nd;
struct timer_event_data *ted;
// Check timer existance
if( sd->npc_timer_id == INVALID_TIMER )
return;
if( !(td = get_timer(sd->npc_timer_id)) )
{
sd->npc_timer_id = INVALID_TIMER;
return;
}
// Delete timer
nd = (struct npc_data *)map_id2bl(td->id);
ted = (struct timer_event_data*)td->data;
delete_timer(sd->npc_timer_id, npc_timerevent);
sd->npc_timer_id = INVALID_TIMER;
// Execute OnTimerQuit
if( nd && nd->bl.type == BL_NPC )
{
char buf[EVENT_NAME_LENGTH];
struct event_data *ev;
snprintf(buf, ARRAYLENGTH(buf), "%s::OnTimerQuit", nd->exname);
ev = (struct event_data*)strdb_get(ev_db, buf);
if( ev && ev->nd != nd )
{
ShowWarning("npc_timerevent_quit: Unable to execute \"OnTimerQuit\", two NPCs have the same event name [%s]!\n",buf);
ev = NULL;
}
if( ev )
{
int old_rid,old_timer;
unsigned int old_tick;
//Set timer related info.
old_rid = (nd->u.scr.rid == sd->bl.id ? 0 : nd->u.scr.rid); // Detach rid if the last attached player logged off.
old_tick = nd->u.scr.timertick;
old_timer = nd->u.scr.timer;
nd->u.scr.rid = sd->bl.id;
nd->u.scr.timertick = gettick();
nd->u.scr.timer = ted->time;
//Execute label
run_script(nd->u.scr.script,ev->pos,sd->bl.id,nd->bl.id);
//Restore previous data.
nd->u.scr.rid = old_rid;
nd->u.scr.timer = old_timer;
nd->u.scr.timertick = old_tick;
}
}
ers_free(timer_event_ers, ted);
}
/*==========================================
* Get the tick value of an NPC timer
* If it's stopped, return stopped time
*------------------------------------------*/
int npc_gettimerevent_tick(struct npc_data* nd)
{
int tick;
nullpo_ret(nd);
// TODO: Get player attached timer's tick. Now we can just get it by using 'getnpctimer' inside OnTimer event.
tick = nd->u.scr.timer; // The last time it's active(start, stop or event trigger)
if( nd->u.scr.timertick ) // It's a running timer
tick += DIFF_TICK(gettick(), nd->u.scr.timertick);
return tick;
}
/*==========================================
* Set tick for running and stopped timer
*------------------------------------------*/
int npc_settimerevent_tick(struct npc_data* nd, int newtimer)
{
bool flag;
int old_rid;
//struct map_session_data *sd = NULL;
nullpo_ret(nd);
// TODO: Set player attached timer's tick.
old_rid = nd->u.scr.rid;
nd->u.scr.rid = 0;
// Check if timer is started
flag = (nd->u.scr.timerid != INVALID_TIMER);
if( flag ) npc_timerevent_stop(nd);
nd->u.scr.timer = newtimer;
if( flag ) npc_timerevent_start(nd, -1);
nd->u.scr.rid = old_rid;
return 0;
}
int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname)
{
if ( sd->npc_id != 0 )
{
//Enqueue the event trigger.
int i;
ARR_FIND( 0, MAX_EVENTQUEUE, i, sd->eventqueue[i][0] == '\0' );
if( i < MAX_EVENTQUEUE )
{
safestrncpy(sd->eventqueue[i],eventname,50); //Event enqueued.
return 0;
}
ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
return 1;
}
if( ev->nd->sc.option&OPTION_INVISIBLE )
{
//Disabled npc, shouldn't trigger event.
npc_event_dequeue(sd);
return 2;
}
run_script(ev->nd->u.scr.script,ev->pos,sd->bl.id,ev->nd->bl.id);
return 0;
}
/*==========================================
* NPC processing event type
*------------------------------------------*/
int npc_event(struct map_session_data* sd, const char* eventname, int ontouch)
{
struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
struct npc_data *nd;
nullpo_ret(sd);
if( ev == NULL || (nd = ev->nd) == NULL )
{
if( !ontouch )
ShowError("npc_event: event not found [%s]\n", eventname);
return ontouch;
}
switch(ontouch)
{
case 1:
nd->touching_id = sd->bl.id;
sd->touching_id = nd->bl.id;
break;
case 2:
sd->areanpc_id = nd->bl.id;
break;
}
return npc_event_sub(sd,ev,eventname);
}
/*==========================================
* Sub chk then execute area event type
*------------------------------------------*/
int npc_touch_areanpc_sub(struct block_list *bl, va_list ap)
{
struct map_session_data *sd;
int pc_id;
char *name;
nullpo_ret(bl);
nullpo_ret((sd = map_id2sd(bl->id)));
pc_id = va_arg(ap,int);
name = va_arg(ap,char*);
if( sd->state.warping )
return 0;
if( pc_ishiding(sd) )
return 0;
if( pc_id == sd->bl.id )
return 0;
npc_event(sd,name,1);
return 1;
}
/*==========================================
* Chk if sd is still touching his assigned npc.
* If not, it unsets it and searches for another player in range.
*------------------------------------------*/
int npc_touchnext_areanpc(struct map_session_data* sd, bool leavemap)
{
struct npc_data *nd = map_id2nd(sd->touching_id);
short xs, ys;
if( !nd || nd->touching_id != sd->bl.id )
return 1;
xs = nd->u.scr.xs;
ys = nd->u.scr.ys;
if( sd->bl.m != nd->bl.m ||
sd->bl.x < nd->bl.x - xs || sd->bl.x > nd->bl.x + xs ||
sd->bl.y < nd->bl.y - ys || sd->bl.y > nd->bl.y + ys ||
pc_ishiding(sd) || leavemap )
{
char name[EVENT_NAME_LENGTH];
nd->touching_id = sd->touching_id = 0;
snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_name);
map_forcountinarea(npc_touch_areanpc_sub,nd->bl.m,nd->bl.x - xs,nd->bl.y - ys,nd->bl.x + xs,nd->bl.y + ys,1,BL_PC,sd->bl.id,name);
}
return 0;
}
/*==========================================
* Exec OnTouch for player if in range of area event
*------------------------------------------*/
int npc_touch_areanpc(struct map_session_data* sd, int16 m, int16 x, int16 y)
{
int xs,ys;
int f = 1;
int i;
int j, found_warp = 0;
nullpo_retr(1, sd);
// Why not enqueue it? [Inkfish]
//if(sd->npc_id)
// return 1;
for(i=0;i<map[m].npc_num;i++)
{
if (map[m].npc[i]->sc.option&OPTION_INVISIBLE) {
f=0; // a npc was found, but it is disabled; don't print warning
continue;
}
switch(map[m].npc[i]->subtype) {
case NPCTYPE_WARP:
xs=map[m].npc[i]->u.warp.xs;
ys=map[m].npc[i]->u.warp.ys;
break;
case NPCTYPE_SCRIPT:
xs=map[m].npc[i]->u.scr.xs;
ys=map[m].npc[i]->u.scr.ys;
break;
default:
continue;
}
if( x >= map[m].npc[i]->bl.x-xs && x <= map[m].npc[i]->bl.x+xs
&& y >= map[m].npc[i]->bl.y-ys && y <= map[m].npc[i]->bl.y+ys )
break;
}
if( i == map[m].npc_num )
{
if( f == 1 ) // no npc found
ShowError("npc_touch_areanpc : stray NPC cell/NPC not found in the block on coordinates '%s',%d,%d\n", map[m].name, x, y);
return 1;
}
switch(map[m].npc[i]->subtype) {
case NPCTYPE_WARP:
if (pc_ishiding(sd) || (sd->sc.count && sd->sc.data[SC_CAMOUFLAGE]) || pc_isdead(sd))
break; // hidden or dead chars cannot use warps
if(sd->count_rewarp > 10){
ShowWarning("Prevented infinite warp loop for player (%d:%d). Please fix NPC: '%s', path: '%s'\n", sd->status.account_id, sd->status.char_id, map[m].npc[i]->exname, map[m].npc[i]->path);
sd->count_rewarp=0;
break;
}
pc_setpos(sd,map[m].npc[i]->u.warp.mapindex,map[m].npc[i]->u.warp.x,map[m].npc[i]->u.warp.y,CLR_OUTSIGHT);
break;
case NPCTYPE_SCRIPT:
for (j = i; j < map[m].npc_num; j++) {
if (map[m].npc[j]->subtype != NPCTYPE_WARP) {
continue;
}
if ((sd->bl.x >= (map[m].npc[j]->bl.x - map[m].npc[j]->u.warp.xs) && sd->bl.x <= (map[m].npc[j]->bl.x + map[m].npc[j]->u.warp.xs)) &&
(sd->bl.y >= (map[m].npc[j]->bl.y - map[m].npc[j]->u.warp.ys) && sd->bl.y <= (map[m].npc[j]->bl.y + map[m].npc[j]->u.warp.ys))) {
if( pc_ishiding(sd) || (sd->sc.count && sd->sc.data[SC_CAMOUFLAGE]) || pc_isdead(sd) )
break; // hidden or dead chars cannot use warps
pc_setpos(sd,map[m].npc[j]->u.warp.mapindex,map[m].npc[j]->u.warp.x,map[m].npc[j]->u.warp.y,CLR_OUTSIGHT);
found_warp = 1;
break;
}
}
if (found_warp > 0) {
break;
}
if( npc_ontouch_event(sd,map[m].npc[i]) > 0 && npc_ontouch2_event(sd,map[m].npc[i]) > 0 )
{ // failed to run OnTouch event, so just click the npc
struct unit_data *ud = unit_bl2ud(&sd->bl);
if( ud && ud->walkpath.path_pos < ud->walkpath.path_len )
{ // Since walktimer always == INVALID_TIMER at this time, we stop walking manually. [Inkfish]
clif_fixpos(&sd->bl);
ud->walkpath.path_pos = ud->walkpath.path_len;
}
sd->areanpc_id = map[m].npc[i]->bl.id;
npc_click(sd,map[m].npc[i]);
}
break;
}
return 0;
}
// OnTouch NPC or Warp for Mobs
// Return 1 if Warped
int npc_touch_areanpc2(struct mob_data *md)
{
int i, m = md->bl.m, x = md->bl.x, y = md->bl.y, id;
char eventname[EVENT_NAME_LENGTH];
struct event_data* ev;
int xs, ys;
for( i = 0; i < map[m].npc_num; i++ )
{
if( map[m].npc[i]->sc.option&OPTION_INVISIBLE )
continue;
switch( map[m].npc[i]->subtype )
{
case NPCTYPE_WARP:
if( !( battle_config.mob_warp&1 ) )
continue;
xs = map[m].npc[i]->u.warp.xs;
ys = map[m].npc[i]->u.warp.ys;
break;
case NPCTYPE_SCRIPT:
xs = map[m].npc[i]->u.scr.xs;
ys = map[m].npc[i]->u.scr.ys;
break;
default:
continue; // Keep Searching
}
if( x >= map[m].npc[i]->bl.x-xs && x <= map[m].npc[i]->bl.x+xs && y >= map[m].npc[i]->bl.y-ys && y <= map[m].npc[i]->bl.y+ys )
{ // In the npc touch area
switch( map[m].npc[i]->subtype )
{
case NPCTYPE_WARP:
xs = map_mapindex2mapid(map[m].npc[i]->u.warp.mapindex);
if( m < 0 )
break; // Cannot Warp between map servers
if( unit_warp(&md->bl, xs, map[m].npc[i]->u.warp.x, map[m].npc[i]->u.warp.y, CLR_OUTSIGHT) == 0 )
return 1; // Warped
break;
case NPCTYPE_SCRIPT:
if( map[m].npc[i]->bl.id == md->areanpc_id )
break; // Already touch this NPC
snprintf(eventname, ARRAYLENGTH(eventname), "%s::OnTouchNPC", map[m].npc[i]->exname);
if( (ev = (struct event_data*)strdb_get(ev_db, eventname)) == NULL || ev->nd == NULL )
break; // No OnTouchNPC Event
md->areanpc_id = map[m].npc[i]->bl.id;
id = md->bl.id; // Stores Unique ID
run_script(ev->nd->u.scr.script, ev->pos, md->bl.id, ev->nd->bl.id);
if( map_id2md(id) == NULL ) return 1; // Not Warped, but killed
break;
}
return 0;
}
}
return 0;
}
/**
* Checks if there are any NPC on-touch objects on the given range.
* @param flag : Flag determines the type of object to check for
* &1: NPC Warps
* &2: NPCs with on-touch events.
* @param m : mapindex
* @param x : x coord
* @param y : y coord
* @param range : range to check
* @return 0: no npc on target cells, x: npc_id
*/
int npc_check_areanpc(int flag, int16 m, int16 x, int16 y, int16 range)
{
int i;
int x0,y0,x1,y1;
int xs,ys;
if (range < 0) return 0;
x0 = max(x-range, 0);
y0 = max(y-range, 0);
x1 = min(x+range, map[m].xs-1);
y1 = min(y+range, map[m].ys-1);
//First check for npc_cells on the range given
i = 0;
for (ys = y0; ys <= y1 && !i; ys++) {
for(xs = x0; xs <= x1 && !i; xs++){
if (map_getcell(m,xs,ys,CELL_CHKNPC))
i = 1;
}
}
if (!i) return 0; //No NPC_CELLs.
//Now check for the actual NPC on said range.
for(i=0;i<map[m].npc_num;i++)
{
if (map[m].npc[i]->sc.option&OPTION_INVISIBLE)
continue;
switch(map[m].npc[i]->subtype)
{
case NPCTYPE_WARP:
if (!(flag&1))
continue;
xs=map[m].npc[i]->u.warp.xs;
ys=map[m].npc[i]->u.warp.ys;
break;
case NPCTYPE_SCRIPT:
if (!(flag&2))
continue;
xs=map[m].npc[i]->u.scr.xs;
ys=map[m].npc[i]->u.scr.ys;
break;
default:
continue;
}
if( x1 >= map[m].npc[i]->bl.x-xs && x0 <= map[m].npc[i]->bl.x+xs
&& y1 >= map[m].npc[i]->bl.y-ys && y0 <= map[m].npc[i]->bl.y+ys )
break; // found a npc
}
if (i==map[m].npc_num)
return 0;
return (map[m].npc[i]->bl.id);
}
/*==========================================
* Chk if player not too far to access the npc.
* Returns npc_data (success) or NULL (fail).
*------------------------------------------*/
struct npc_data* npc_checknear(struct map_session_data* sd, struct block_list* bl)
{
struct npc_data *nd;
nullpo_retr(NULL, sd);
if(bl == NULL) return NULL;
if(bl->type != BL_NPC) return NULL;
nd = (TBL_NPC*)bl;
if(sd->state.using_fake_npc && sd->npc_id == bl->id)
return nd;
if (nd->class_<0) //Class-less npc, enable click from anywhere.
return nd;
if (bl->m!=sd->bl.m ||
bl->x<sd->bl.x-AREA_SIZE-1 || bl->x>sd->bl.x+AREA_SIZE+1 ||
bl->y<sd->bl.y-AREA_SIZE-1 || bl->y>sd->bl.y+AREA_SIZE+1)
return NULL;
return nd;
}
/*==========================================
* Make NPC talk in global chat (like npctalk)
*------------------------------------------*/
int npc_globalmessage(const char* name, const char* mes)
{
struct npc_data* nd = npc_name2id(name);
char temp[100];
if (!nd)
return 0;
snprintf(temp, sizeof(temp), "%s : %s", name, mes);
clif_GlobalMessage(&nd->bl,temp,ALL_CLIENT);
return 0;
}
// MvP tomb [GreenBox]
void run_tomb(struct map_session_data* sd, struct npc_data* nd)
{
char buffer[200];
char time[10];
strftime(time, sizeof(time), "%H:%M", localtime(&nd->u.tomb.kill_time));
// TODO: Find exact color?
snprintf(buffer, sizeof(buffer), msg_txt(sd,657), nd->u.tomb.md->db->name);
clif_scriptmes(sd, nd->bl.id, buffer);
clif_scriptmes(sd, nd->bl.id, msg_txt(sd,658));
snprintf(buffer, sizeof(buffer), msg_txt(sd,659), time);
clif_scriptmes(sd, nd->bl.id, buffer);
clif_scriptmes(sd, nd->bl.id, msg_txt(sd,660));
snprintf(buffer, sizeof(buffer), msg_txt(sd,661), nd->u.tomb.killer_name[0] ? nd->u.tomb.killer_name : "Unknown");
clif_scriptmes(sd, nd->bl.id, buffer);
clif_scriptclose(sd, nd->bl.id);
}
/*==========================================
* NPC 1st call when clicking on npc
* Do specific action for NPC type (openshop, run scripts...)
*------------------------------------------*/
int npc_click(struct map_session_data* sd, struct npc_data* nd)
{
nullpo_retr(1, sd);
if (sd->npc_id != 0) {
ShowError("npc_click: npc_id != 0\n");
return 1;
}
if(!nd) return 1;
if ((nd = npc_checknear(sd,&nd->bl)) == NULL)
return 1;
//Hidden/Disabled npc.
if (nd->class_ < 0 || nd->sc.option&(OPTION_INVISIBLE|OPTION_HIDE))
return 1;
switch(nd->subtype) {
case NPCTYPE_SHOP:
case NPCTYPE_ITEMSHOP:
case NPCTYPE_POINTSHOP:
clif_npcbuysell(sd,nd->bl.id);
break;
case NPCTYPE_CASHSHOP:
clif_cashshop_show(sd,nd);
break;
case NPCTYPE_MARKETSHOP:
#if PACKETVER >= 20131223
{
unsigned short i;
for (i = 0; i < nd->u.shop.count; i++) {
if (nd->u.shop.shop_item[i].qty)
break;
}
if (i == nd->u.shop.count) {
clif_colormes(sd, color_table[COLOR_RED], msg_txt(sd, 534));
return false;
}
sd->npc_shopid = nd->bl.id;
clif_npc_market_open(sd, nd);
}
#endif
break;
case NPCTYPE_SCRIPT:
run_script(nd->u.scr.script,0,sd->bl.id,nd->bl.id);
break;
case NPCTYPE_TOMB:
run_tomb(sd,nd);
break;
}
return 0;
}
/*==========================================
*
*------------------------------------------*/
int npc_scriptcont(struct map_session_data* sd, int id, bool closing)
{
nullpo_retr(1, sd);
if( id != sd->npc_id ){
TBL_NPC* nd_sd=(TBL_NPC*)map_id2bl(sd->npc_id);
TBL_NPC* nd=(TBL_NPC*)map_id2bl(id);
ShowDebug("npc_scriptcont: %s (sd->npc_id=%d) is not %s (id=%d).\n",
nd_sd?(char*)nd_sd->name:"'Unknown NPC'", (int)sd->npc_id,
nd?(char*)nd->name:"'Unknown NPC'", (int)id);
return 1;
}
if(id != fake_nd->bl.id) { // Not item script
if ((npc_checknear(sd,map_id2bl(id))) == NULL){
ShowWarning("npc_scriptcont: failed npc_checknear test.\n");
return 1;
}
}
#ifdef SECURE_NPCTIMEOUT
sd->npc_idle_tick = gettick(); //Update the last NPC iteration
#endif
/**
* WPE can get to this point with a progressbar; we deny it.
**/
if( sd->progressbar.npc_id && DIFF_TICK(sd->progressbar.timeout,gettick()) > 0 )
return 1;
if( closing && sd->st && sd->st->state == CLOSE )
sd->st->state = END;
run_script_main(sd->st);
return 0;
}
/*==========================================
* Chk if valid call then open buy or selling list
*------------------------------------------*/
int npc_buysellsel(struct map_session_data* sd, int id, int type)
{
struct npc_data *nd;
nullpo_retr(1, sd);
if ((nd = npc_checknear(sd,map_id2bl(id))) == NULL)
return 1;
if (nd->subtype != NPCTYPE_SHOP && nd->subtype != NPCTYPE_ITEMSHOP && nd->subtype != NPCTYPE_POINTSHOP) {
ShowError("no such shop npc : %d\n",id);
if (sd->npc_id == id)
sd->npc_id=0;
return 1;
}
if (nd->sc.option & OPTION_INVISIBLE) // can't buy if npc is not visible (hack?)
return 1;
if( nd->class_ < 0 && !sd->state.callshop ) {// not called through a script and is not a visible NPC so an invalid call
return 1;
}
if (nd->subtype == NPCTYPE_ITEMSHOP) {
char output[CHAT_SIZE_MAX];
struct item_data *itd = itemdb_exists(nd->u.shop.itemshop_nameid);
memset(output,'\0',sizeof(output));
if (itd) {
sprintf(output,msg_txt(sd,714),itd->jname,itd->nameid); // Item Shop List: %s (%hu)
clif_broadcast(&sd->bl,output,strlen(output) + 1,BC_BLUE,SELF);
}
} else if (nd->subtype == NPCTYPE_POINTSHOP) {
char output[CHAT_SIZE_MAX];
memset(output,'\0',sizeof(output));
sprintf(output,msg_txt(sd,715),nd->u.shop.pointshop_str); // Point Shop List: '%s'
clif_broadcast(&sd->bl,output,strlen(output) + 1,BC_BLUE,SELF);
}
// reset the callshop state for future calls
sd->state.callshop = 0;
sd->npc_shopid = id;
if (type == 0) {
clif_buylist(sd,nd);
} else {
clif_selllist(sd);
}
return 0;
}
/*==========================================
* Cash Shop Buy List
*------------------------------------------*/
int npc_cashshop_buylist(struct map_session_data *sd, int points, int count, unsigned short* item_list)
{
int i, j, amount, new_, w, vt;
unsigned short nameid;
struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
if( !nd || nd->subtype != NPCTYPE_CASHSHOP )
return 1;
if( sd->state.trading )
return 4;
new_ = 0;
w = 0;
vt = 0; // Global Value
// Validating Process ----------------------------------------------------
for( i = 0; i < count; i++ )
{
nameid = item_list[i*2+1];
amount = item_list[i*2+0];
if( !itemdb_exists(nameid) || amount <= 0 )
return 5;
ARR_FIND(0,nd->u.shop.count,j,nd->u.shop.shop_item[j].nameid == nameid || itemdb_viewid(nd->u.shop.shop_item[j].nameid) == nameid);
if( j == nd->u.shop.count || nd->u.shop.shop_item[j].value <= 0 )
return 5;
nameid = item_list[i*2+1] = nd->u.shop.shop_item[j].nameid; //item_avail replacement
if( !itemdb_isstackable(nameid) && amount > 1 )
{
ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %hu!\n", sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
amount = item_list[i*2+0] = 1;
}
switch( pc_checkadditem(sd,nameid,amount) )
{
case CHKADDITEM_NEW:
new_++;
break;
case CHKADDITEM_OVERAMOUNT:
return 3;
}
vt += nd->u.shop.shop_item[j].value * amount;
w += itemdb_weight(nameid) * amount;
}
if( w + sd->weight > sd->max_weight )
return 3;
if( pc_inventoryblank(sd) < new_ )
return 3;
if( points > vt ) points = vt;
// Payment Process ----------------------------------------------------
if( sd->kafraPoints < points || sd->cashPoints < (vt - points) )
return 6;
pc_paycash(sd,vt,points, LOG_TYPE_NPC);
// Delivery Process ----------------------------------------------------
for( i = 0; i < count; i++ )
{
struct item item_tmp;
nameid = item_list[i*2+1];
amount = item_list[i*2+0];
memset(&item_tmp,0,sizeof(item_tmp));
if( !pet_create_egg(sd,nameid) )
{
item_tmp.nameid = nameid;
item_tmp.identify = 1;
pc_additem(sd,&item_tmp,amount,LOG_TYPE_NPC);
}
}
return 0;
}
/**
* npc_buylist for script-controlled shops.
* @param sd Player who bought
* @param n Number of item
* @param item_list List of item
* @param nd Attached NPC
**/
static int npc_buylist_sub(struct map_session_data* sd, uint16 n, struct s_npc_buy_list *item_list, struct npc_data* nd) {
char npc_ev[EVENT_NAME_LENGTH];
int i;
int key_nameid = 0;
int key_amount = 0;
// discard old contents
script_cleararray_pc(sd, "@bought_nameid", (void*)0);
script_cleararray_pc(sd, "@bought_quantity", (void*)0);
// save list of bought items
for (i = 0; i < n; i++) {
script_setarray_pc(sd, "@bought_nameid", i, (void*)(intptr_t)item_list[i].nameid, &key_nameid);
script_setarray_pc(sd, "@bought_quantity", i, (void*)(intptr_t)item_list[i].qty, &key_amount);
}
// invoke event
snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::OnBuyItem", nd->exname);
npc_event(sd, npc_ev, 0);
return 0;
}
/*==========================================
* Cash Shop Buy
*------------------------------------------*/
int npc_cashshop_buy(struct map_session_data *sd, unsigned short nameid, int amount, int points)
{
struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
struct item_data *item;
int i, price, w;
if( amount <= 0 )
return 5;
if( points < 0 )
return 6;
if( !nd || nd->subtype != NPCTYPE_CASHSHOP )
return 1;
if( sd->state.trading )
return 4;
if( (item = itemdb_exists(nameid)) == NULL )
return 5; // Invalid Item
ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid || itemdb_viewid(nd->u.shop.shop_item[i].nameid) == nameid);
if( i == nd->u.shop.count )
return 5;
if( nd->u.shop.shop_item[i].value <= 0 )
return 5;
nameid = nd->u.shop.shop_item[i].nameid; //item_avail replacement
if(!itemdb_isstackable(nameid) && amount > 1)
{
ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %hu!\n",
sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
amount = 1;
}
switch( pc_checkadditem(sd, nameid, amount) )
{
case CHKADDITEM_NEW:
if( pc_inventoryblank(sd) == 0 )
return 3;
break;
case CHKADDITEM_OVERAMOUNT:
return 3;
}
w = item->weight * amount;
if( w + sd->weight > sd->max_weight )
return 3;
if( (double)nd->u.shop.shop_item[i].value * amount > INT_MAX )
{
ShowWarning("npc_cashshop_buy: Item '%s' (%hu) price overflow attempt!\n", item->name, nameid);
ShowDebug("(NPC:'%s' (%s,%d,%d), player:'%s' (%d/%d), value:%d, amount:%d)\n",
nd->exname, map[nd->bl.m].name, nd->bl.x, nd->bl.y, sd->status.name, sd->status.account_id, sd->status.char_id, nd->u.shop.shop_item[i].value, amount);
return 5;
}
price = nd->u.shop.shop_item[i].value * amount;
if( points > price )
points = price;
if( (sd->kafraPoints < points) || (sd->cashPoints < price - points) )
return 6;
pc_paycash(sd, price, points, LOG_TYPE_NPC);
if( !pet_create_egg(sd, nameid) )
{
struct item item_tmp;
memset(&item_tmp, 0, sizeof(struct item));
item_tmp.nameid = nameid;
item_tmp.identify = 1;
pc_additem(sd,&item_tmp, amount, LOG_TYPE_NPC);
}
return 0;
}
/**
* Shop buylist
* @param sd Player who attempt to buy
* @param n Number of item will be bought
* @param *item_list List of item will be bought
* @return result code for clif_parse_NpcBuyListSend/clif_npc_market_purchase_ack
**/
uint8 npc_buylist(struct map_session_data* sd, uint16 n, struct s_npc_buy_list *item_list) {
struct npc_data* nd;
struct npc_item_list *shop = NULL;
double z;
int i,j,k,w,skill,new_,count = 0;
char output[CHAT_SIZE_MAX];
uint8 market_index[MAX_INVENTORY];
nullpo_retr(3, sd);
nullpo_retr(3, item_list);
nd = npc_checknear(sd,map_id2bl(sd->npc_shopid));
if( nd == NULL )
return 3;
if( nd->subtype != NPCTYPE_SHOP && nd->subtype != NPCTYPE_ITEMSHOP && nd->subtype != NPCTYPE_POINTSHOP && nd->subtype != NPCTYPE_MARKETSHOP )
return 3;
if (!item_list || !n)
return 3;
z = 0;
w = 0;
new_ = 0;
shop = nd->u.shop.shop_item;
memset(market_index, 0, sizeof(market_index));
// process entries in buy list, one by one
for( i = 0; i < n; ++i ) {
unsigned short nameid, amount;
int value;
// find this entry in the shop's sell list
ARR_FIND( 0, nd->u.shop.count, j,
item_list[i].nameid == shop[j].nameid || //Normal items
item_list[i].nameid == itemdb_viewid(shop[j].nameid) //item_avail replacement
);
if( j == nd->u.shop.count )
return 3; // no such item in shop
#if PACKETVER >= 20131223
if (nd->subtype == NPCTYPE_MARKETSHOP) {
if (item_list[i].qty > shop[j].qty)
return 3;
market_index[i] = j;
}
#endif
amount = item_list[i].qty;
nameid = item_list[i].nameid = shop[j].nameid; //item_avail replacement
value = shop[j].value;
if( !itemdb_exists(nameid) )
return 3; // item no longer in itemdb
if( !itemdb_isstackable(nameid) && amount > 1 ) { //Exploit? You can't buy more than 1 of equipment types o.O
ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %hu!\n",
sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
amount = item_list[i].qty = 1;
}
if( nd->master_nd ) { // Script-controlled shops decide by themselves, what can be bought and for what price.
continue;
}
switch( pc_checkadditem(sd,nameid,amount) ) {
case CHKADDITEM_EXIST:
break;
case CHKADDITEM_NEW:
new_++;
break;
case CHKADDITEM_OVERAMOUNT:
return 2;
}
if (npc_shop_discount(nd->subtype,nd->u.shop.discount))
value = pc_modifybuyvalue(sd,value);
z += (double)value * amount;
w += itemdb_weight(nameid) * amount;
}
if (nd->master_nd) //Script-based shops.
return npc_buylist_sub(sd,n,item_list,nd->master_nd);
switch(nd->subtype) {
case NPCTYPE_SHOP:
case NPCTYPE_MARKETSHOP:
if (z > (double)sd->status.zeny)
return 1; // Not enough Zeny
break;
case NPCTYPE_ITEMSHOP:
for (k = 0; k < MAX_INVENTORY; k++) {
if (sd->status.inventory[k].nameid == nd->u.shop.itemshop_nameid)
count += sd->status.inventory[k].amount;
}
if (z > (double)count) {
struct item_data *id = itemdb_exists(nd->u.shop.itemshop_nameid);
sprintf(output,msg_txt(sd,712),id->jname,id->nameid); // You do not have enough %s %d.
clif_colormes(sd,color_table[COLOR_RED],output);
return 1;
}
break;
case NPCTYPE_POINTSHOP:
count = pc_readreg2(sd, nd->u.shop.pointshop_str);
if (z > (double)count) {
sprintf(output,msg_txt(sd,713),nd->u.shop.pointshop_str); // You do not have enough '%s'.
clif_colormes(sd,color_table[COLOR_RED],output);
return 1;
}
break;
}
if( w + sd->weight > sd->max_weight )
return 2; // Too heavy
if( pc_inventoryblank(sd) < new_ )
return 3; // Not enough space to store items
switch(nd->subtype) {
case NPCTYPE_SHOP:
case NPCTYPE_MARKETSHOP:
pc_payzeny(sd, (int)z, LOG_TYPE_NPC, NULL);
break;
case NPCTYPE_ITEMSHOP:
pc_delitem(sd, pc_search_inventory(sd, nd->u.shop.itemshop_nameid), (int)z, 0, 0, LOG_TYPE_NPC);
break;
case NPCTYPE_POINTSHOP:
pc_setreg2(sd, nd->u.shop.pointshop_str, count - (int)z);
break;
}
for( i = 0; i < n; ++i ) {
unsigned short nameid = item_list[i].nameid;
unsigned short amount = item_list[i].qty;
struct item item_tmp;
#if PACKETVER >= 20131223
if (nd->subtype == NPCTYPE_MARKETSHOP) {
j = market_index[i];
if (amount > shop[j].qty)
return 1;
shop[j].qty -= amount;
npc_market_tosql(nd->exname, &shop[j]);
}
#endif
if (itemdb_type(nameid) == IT_PETEGG)
pet_create_egg(sd, nameid);
else {
memset(&item_tmp,0,sizeof(item_tmp));
item_tmp.nameid = nameid;
item_tmp.identify = 1;
pc_additem(sd,&item_tmp,amount,LOG_TYPE_NPC);
}
}
// custom merchant shop exp bonus
if( battle_config.shop_exp > 0 && z > 0 && (skill = pc_checkskill(sd,MC_DISCOUNT)) > 0 ) {
uint16 sk_idx = skill_get_index(MC_DISCOUNT);
if( sd->status.skill[sk_idx].flag >= SKILL_FLAG_REPLACED_LV_0 )
skill = sd->status.skill[sk_idx].flag - SKILL_FLAG_REPLACED_LV_0;
if( skill > 0 ) {
z = z * (double)skill * (double)battle_config.shop_exp/10000.;
if( z < 1 )
z = 1;
pc_gainexp(sd,NULL,0,(int)z, false);
}
}
if (nd->subtype == NPCTYPE_POINTSHOP) {
sprintf(output,msg_txt(sd,716),nd->u.shop.pointshop_str,count - (int)z); // Your '%s' now: %d
clif_disp_onlyself(sd,output,strlen(output)+1);
}
return 0;
}
/// npc_selllist for script-controlled shops
static int npc_selllist_sub(struct map_session_data* sd, int n, unsigned short* item_list, struct npc_data* nd)
{
char npc_ev[EVENT_NAME_LENGTH];
char card_slot[NAME_LENGTH];
int i, j;
int key_nameid = 0;
int key_amount = 0;
int key_refine = 0;
int key_attribute = 0;
int key_identify = 0;
int key_card[MAX_SLOTS];
// discard old contents
script_cleararray_pc(sd, "@sold_nameid", (void*)0);
script_cleararray_pc(sd, "@sold_quantity", (void*)0);
script_cleararray_pc(sd, "@sold_refine", (void*)0);
script_cleararray_pc(sd, "@sold_attribute", (void*)0);
script_cleararray_pc(sd, "@sold_identify", (void*)0);
for( j = 0; j < MAX_SLOTS; j++ )
{// clear each of the card slot entries
key_card[j] = 0;
snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
script_cleararray_pc(sd, card_slot, (void*)0);
}
// save list of to be sold items
for( i = 0; i < n; i++ )
{
int idx;
idx = item_list[i*2]-2;
script_setarray_pc(sd, "@sold_nameid", i, (void*)(intptr_t)sd->status.inventory[idx].nameid, &key_nameid);
script_setarray_pc(sd, "@sold_quantity", i, (void*)(intptr_t)item_list[i*2+1], &key_amount);
if( itemdb_isequip(sd->status.inventory[idx].nameid) )
{// process equipment based information into the arrays
script_setarray_pc(sd, "@sold_refine", i, (void*)(intptr_t)sd->status.inventory[idx].refine, &key_refine);
script_setarray_pc(sd, "@sold_attribute", i, (void*)(intptr_t)sd->status.inventory[idx].attribute, &key_attribute);
script_setarray_pc(sd, "@sold_identify", i, (void*)(intptr_t)sd->status.inventory[idx].identify, &key_identify);
for( j = 0; j < MAX_SLOTS; j++ )
{// store each of the cards from the equipment in the array
snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
script_setarray_pc(sd, card_slot, i, (void*)(intptr_t)sd->status.inventory[idx].card[j], &key_card[j]);
}
}
}
// invoke event
snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::OnSellItem", nd->exname);
npc_event(sd, npc_ev, 0);
return 0;
}
/// Player item selling to npc shop.
///
/// @param item_list 'n' pairs <index,amount>
/// @return result code for clif_parse_NpcSellListSend
uint8 npc_selllist(struct map_session_data* sd, int n, unsigned short *item_list)
{
double z;
int i,skill;
struct npc_data *nd;
nullpo_retr(1, sd);
nullpo_retr(1, item_list);
if( ( nd = npc_checknear(sd, map_id2bl(sd->npc_shopid)) ) == NULL
|| ( nd->subtype != NPCTYPE_SHOP && nd->subtype != NPCTYPE_ITEMSHOP && nd->subtype != NPCTYPE_POINTSHOP ) )
{
return 1;
}
z = 0;
// verify the sell list
for( i = 0; i < n; i++ )
{
unsigned short nameid;
int amount, idx, value;
idx = item_list[i*2]-2;
amount = item_list[i*2+1];
if( idx >= MAX_INVENTORY || idx < 0 || amount < 0 )
{
return 1;
}
nameid = sd->status.inventory[idx].nameid;
if( !nameid || !sd->inventory_data[idx] || sd->status.inventory[idx].amount < amount )
{
return 1;
}
if( nd->master_nd )
{// Script-controlled shops decide by themselves, what can be sold and at what price.
continue;
}
value = pc_modifysellvalue(sd, sd->inventory_data[idx]->value_sell);
z+= (double)value*amount;
}
if( nd->master_nd )
{// Script-controlled shops
return npc_selllist_sub(sd, n, item_list, nd->master_nd);
}
// delete items
for( i = 0; i < n; i++ )
{
int amount, idx;
idx = item_list[i*2]-2;
amount = item_list[i*2+1];
if( sd->inventory_data[idx]->type == IT_PETEGG && sd->status.inventory[idx].card[0] == CARD0_PET )
{
if( search_petDB_index(sd->status.inventory[idx].nameid, PET_EGG) >= 0 )
{
intif_delete_petdata(MakeDWord(sd->status.inventory[idx].card[1], sd->status.inventory[idx].card[2]));
}
}
pc_delitem(sd, idx, amount, 0, 6, LOG_TYPE_NPC);
}
if( z > MAX_ZENY )
z = MAX_ZENY;
pc_getzeny(sd, (int)z, LOG_TYPE_NPC, NULL);
// custom merchant shop exp bonus
if( battle_config.shop_exp > 0 && z > 0 && ( skill = pc_checkskill(sd,MC_OVERCHARGE) ) > 0)
{
uint16 sk_idx = skill_get_index(MC_OVERCHARGE);
if( sd->status.skill[sk_idx].flag >= SKILL_FLAG_REPLACED_LV_0 )
skill = sd->status.skill[sk_idx].flag - SKILL_FLAG_REPLACED_LV_0;
if( skill > 0 )
{
z = z * (double)skill * (double)battle_config.shop_exp/10000.;
if( z < 1 )
z = 1;
pc_gainexp(sd, NULL, 0, (int)z, false);
}
}
return 0;
}
//Atempt to remove an npc from a map
//This doesn't remove it from map_db
int npc_remove_map(struct npc_data* nd)
{
int16 m,i;
nullpo_retr(1, nd);
if(nd->bl.prev == NULL || nd->bl.m < 0)
return 1; //Not assigned to a map.
m = nd->bl.m;
if (nd->subtype == NPCTYPE_SCRIPT)
skill_clear_unitgroup(&nd->bl);
clif_clearunit_area(&nd->bl,CLR_RESPAWN);
npc_unsetcells(nd);
map_delblock(&nd->bl);
//Remove npc from map[].npc list. [Skotlex]
ARR_FIND( 0, map[m].npc_num, i, map[m].npc[i] == nd );
if( i == map[m].npc_num ) return 2; //failed to find it?
map[m].npc_num--;
map[m].npc[i] = map[m].npc[map[m].npc_num];
map[m].npc[map[m].npc_num] = NULL;
return 0;
}
/**
* @see DBApply
*/
static int npc_unload_ev(DBKey key, DBData *data, va_list ap)
{
struct event_data* ev = db_data2ptr(data);
char* npcname = va_arg(ap, char *);
if(strcmp(ev->nd->exname,npcname)==0){
db_remove(ev_db, key);
return 1;
}
return 0;
}
//Chk if npc matches src_id, then unload.
//Sub-function used to find duplicates.
static int npc_unload_dup_sub(struct npc_data* nd, va_list args)
{
int src_id;
src_id = va_arg(args, int);
if (nd->src_id == src_id)
npc_unload(nd, true);
return 0;
}
//Removes all npcs that are duplicates of the passed one. [Skotlex]
void npc_unload_duplicates(struct npc_data* nd)
{
map_foreachnpc(npc_unload_dup_sub,nd->bl.id);
}
//Removes an npc from map and db.
//Single is to free name (for duplicates).
int npc_unload(struct npc_data* nd, bool single) {
nullpo_ret(nd);
npc_remove_map(nd);
map_deliddb(&nd->bl);
if( single )
strdb_remove(npcname_db, nd->exname);
if (nd->chat_id) // remove npc chatroom object and kick users
chat_deletenpcchat(nd);
#ifdef PCRE_SUPPORT
npc_chat_finalize(nd); // deallocate npc PCRE data structures
#endif
if( single && nd->path ) {
struct npc_path_data* npd = NULL;
if( nd->path && nd->path != npc_last_ref ) {
npd = strdb_get(npc_path_db, nd->path);
}
if( npd && --npd->references == 0 ) {
strdb_remove(npc_path_db, nd->path);/* remove from db */
aFree(nd->path);/* remove now that no other instances exist */
}
}
if( single && nd->bl.m != -1 )
map_remove_questinfo(nd->bl.m, nd);
if( (nd->subtype == NPCTYPE_SHOP || nd->subtype == NPCTYPE_CASHSHOP || nd->subtype == NPCTYPE_ITEMSHOP || nd->subtype == NPCTYPE_POINTSHOP || nd->subtype == NPCTYPE_MARKETSHOP) && nd->src_id == 0) //src check for duplicate shops [Orcao]
aFree(nd->u.shop.shop_item);
else if( nd->subtype == NPCTYPE_SCRIPT ) {
struct s_mapiterator* iter;
struct block_list* bl;
if( single )
ev_db->foreach(ev_db,npc_unload_ev,nd->exname); //Clean up all events related
iter = mapit_geteachpc();
for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) ) {
struct map_session_data *sd = ((TBL_PC*)bl);
if( sd && sd->npc_timer_id != INVALID_TIMER ) {
const struct TimerData *td = get_timer(sd->npc_timer_id);
if( td && td->id != nd->bl.id )
continue;
if( td && td->data )
ers_free(timer_event_ers, (void*)td->data);
delete_timer(sd->npc_timer_id, npc_timerevent);
sd->npc_timer_id = INVALID_TIMER;
}
}
mapit_free(iter);
if (nd->u.scr.timerid != INVALID_TIMER) {
const struct TimerData *td;
td = get_timer(nd->u.scr.timerid);
if (td && td->data)
ers_free(timer_event_ers, (void*)td->data);
delete_timer(nd->u.scr.timerid, npc_timerevent);
}
if (nd->u.scr.timer_event)
aFree(nd->u.scr.timer_event);
if (nd->src_id == 0) {
if(nd->u.scr.script) {
script_free_code(nd->u.scr.script);
nd->u.scr.script = NULL;
}
if (nd->u.scr.label_list) {
aFree(nd->u.scr.label_list);
nd->u.scr.label_list = NULL;
nd->u.scr.label_list_num = 0;
}
}
if( nd->u.scr.guild_id )
guild_flag_remove(nd);
}
script_stop_sleeptimers(nd->bl.id);
aFree(nd);
return 0;
}
//
// NPC Source Files
//
/// Clears the npc source file list
static void npc_clearsrcfile(void)
{
struct npc_src_list* file = npc_src_files;
while( file != NULL ) {
struct npc_src_list* file_tofree = file;
file = file->next;
aFree(file_tofree);
}
npc_src_files = NULL;
}
/**
* Adds a npc source file (or removes all)
* @param name : file to add
* @return 0=error, 1=sucess
*/
int npc_addsrcfile(const char* name)
{
struct npc_src_list* file;
struct npc_src_list* file_prev = NULL;
if( strcmpi(name, "clear") == 0 )
{
npc_clearsrcfile();
return 1;
}
if(check_filepath(name)!=2) return 0; //this is not a file
// prevent multiple insert of source files
file = npc_src_files;
while( file != NULL )
{
if( strcmp(name, file->name) == 0 )
return 0;// found the file, no need to insert it again
file_prev = file;
file = file->next;
}
file = (struct npc_src_list*)aMalloc(sizeof(struct npc_src_list) + strlen(name));
file->next = NULL;
safestrncpy(file->name, name, strlen(name) + 1);
if( file_prev == NULL )
npc_src_files = file;
else
file_prev->next = file;
return 1;
}
/// Removes a npc source file (or all)
void npc_delsrcfile(const char* name)
{
struct npc_src_list* file = npc_src_files;
struct npc_src_list* file_prev = NULL;
if( strcmpi(name, "all") == 0 )
{
npc_clearsrcfile();
return;
}
while( file != NULL )
{
if( strcmp(file->name, name) == 0 )
{
if( npc_src_files == file )
npc_src_files = file->next;
else
file_prev->next = file->next;
aFree(file);
break;
}
file_prev = file;
file = file->next;
}
}
/// Parses and sets the name and exname of a npc.
/// Assumes that m, x and y are already set in nd.
static void npc_parsename(struct npc_data* nd, const char* name, const char* start, const char* buffer, const char* filepath)
{
const char* p;
struct npc_data* dnd;// duplicate npc
char newname[NAME_LENGTH];
// parse name
p = strstr(name,"::");
if( p ) { // <Display name>::<Unique name>
size_t len = p-name;
if( len > NAME_LENGTH ) {
ShowWarning("npc_parsename: Display name of '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NAME_LENGTH);
safestrncpy(nd->name, name, sizeof(nd->name));
} else {
memcpy(nd->name, name, len);
memset(nd->name+len, 0, sizeof(nd->name)-len);
}
len = strlen(p+2);
if( len > NAME_LENGTH )
ShowWarning("npc_parsename: Unique name of '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NAME_LENGTH);
safestrncpy(nd->exname, p+2, sizeof(nd->exname));
} else {// <Display name>
size_t len = strlen(name);
if( len > NAME_LENGTH )
ShowWarning("npc_parsename: Name '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NAME_LENGTH);
safestrncpy(nd->name, name, sizeof(nd->name));
safestrncpy(nd->exname, name, sizeof(nd->exname));
}
if( *nd->exname == '\0' || strstr(nd->exname,"::") != NULL ) {// invalid
snprintf(newname, ARRAYLENGTH(newname), "0_%d_%d_%d", nd->bl.m, nd->bl.x, nd->bl.y);
ShowWarning("npc_parsename: Invalid unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
safestrncpy(nd->exname, newname, sizeof(nd->exname));
}
if( (dnd=npc_name2id(nd->exname)) != NULL ) {// duplicate unique name, generate new one
char this_mapname[32];
char other_mapname[32];
int i = 0;
do {
++i;
snprintf(newname, ARRAYLENGTH(newname), "%d_%d_%d_%d", i, nd->bl.m, nd->bl.x, nd->bl.y);
} while( npc_name2id(newname) != NULL );
strcpy(this_mapname, (nd->bl.m==-1?"(not on a map)":mapindex_id2name(map[nd->bl.m].index)));
strcpy(other_mapname, (dnd->bl.m==-1?"(not on a map)":mapindex_id2name(map[dnd->bl.m].index)));
ShowWarning("npc_parsename: Duplicate unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
ShowDebug("this npc:\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n", nd->name, nd->exname, this_mapname, nd->bl.x, nd->bl.y);
ShowDebug("other npc in '%s' :\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n",dnd->path, dnd->name, dnd->exname, other_mapname, dnd->bl.x, dnd->bl.y);
safestrncpy(nd->exname, newname, sizeof(nd->exname));
}
if( npc_last_path != filepath ) {
struct npc_path_data * npd = NULL;
if( !(npd = strdb_get(npc_path_db,filepath) ) ) {
CREATE(npd, struct npc_path_data, 1);
strdb_put(npc_path_db, filepath, npd);
CREATE(npd->path, char, strlen(filepath)+1);
safestrncpy(npd->path, filepath, strlen(filepath)+1);
npd->references = 0;
}
nd->path = npd->path;
npd->references++;
npc_last_npd = npd;
npc_last_ref = npd->path;
npc_last_path = (char*) filepath;
} else {
nd->path = npc_last_ref;
if( npc_last_npd )
npc_last_npd->references++;
}
}
/**
* Parses NPC view.
* Support for using Constants in place of NPC View IDs.
*/
int npc_parseview(const char* w4, const char* start, const char* buffer, const char* filepath) {
int val = -1, i = 0;
char viewid[1024]; // Max size of name from const.txt, see read_constdb.
// Extract view ID / constant
while (w4[i] != '\0') {
if (ISSPACE(w4[i]) || w4[i] == '/' || w4[i] == ',')
break;
i++;
}
safestrncpy(viewid, w4, i+=1);
// Check if view id is not an ID (only numbers).
if(!npc_viewisid(viewid)) {
// Check if constant exists and get its value.
if(!script_get_constant(viewid, &val)) {
ShowWarning("npc_parseview: Invalid NPC constant '%s' specified in file '%s', line'%d'. Defaulting to INVISIBLE_CLASS. \n", viewid, filepath, strline(buffer,start-buffer));
val = INVISIBLE_CLASS;
}
} else {
// NPC has an ID specified for view id.
val = atoi(w4);
}
return val;
}
/**
* Checks if given view is an ID or constant.
*/
bool npc_viewisid(const char * viewid)
{
if(atoi(viewid) != -1) {
// Loop through view, looking for non-numeric character.
while (*viewid) {
if (ISDIGIT(*viewid++) == 0) return false;
}
}
return true;
}
/**
* Add then display an npc warp on map
* @param name : warp unique name
* @param from_mapid : mapid to warp from
* @param from_x : x coordinate of warp
* @param from_y : y coordinate of warp
* @param xs : x lenght of warp (for trigger activation)
* @param ys : y lenght of warp (for trigger activation)
* @param to_mapindex : mapid to warp to
* @param to_x : x coordinate to warp to
* @param to_y : y coordinate to warp to
* @return NULL:failed creation, npc_data* new warp
*/
struct npc_data* npc_add_warp(char* name, short from_mapid, short from_x, short from_y, short xs, short ys, unsigned short to_mapindex, short to_x, short to_y)
{
int i, flag = 0;
struct npc_data *nd;
CREATE(nd, struct npc_data, 1);
nd->bl.id = npc_get_new_npc_id();
map_addnpc(from_mapid, nd);
nd->bl.prev = nd->bl.next = NULL;
nd->bl.m = from_mapid;
nd->bl.x = from_x;
nd->bl.y = from_y;
safestrncpy(nd->exname, name, ARRAYLENGTH(nd->exname));
if (npc_name2id(nd->exname) != NULL)
flag = 1;
if (flag == 1)
snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp_%d_%d_%d", from_mapid, from_x, from_y);
for( i = 0; npc_name2id(nd->exname) != NULL; ++i )
snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp%d_%d_%d_%d", i, from_mapid, from_x, from_y);
safestrncpy(nd->name, nd->exname, ARRAYLENGTH(nd->name));
if( battle_config.warp_point_debug )
nd->class_ = WARP_DEBUG_CLASS;
else
nd->class_ = WARP_CLASS;
nd->speed = 200;
nd->u.warp.mapindex = to_mapindex;
nd->u.warp.x = to_x;
nd->u.warp.y = to_y;
nd->u.warp.xs = xs;
nd->u.warp.ys = xs;
nd->bl.type = BL_NPC;
nd->subtype = NPCTYPE_WARP;
npc_setcells(nd);
if(map_addblock(&nd->bl))
return NULL;
status_set_viewdata(&nd->bl, nd->class_);
status_change_init(&nd->bl);
unit_dataset(&nd->bl);
if( map[nd->bl.m].users )
clif_spawn(&nd->bl);
strdb_put(npcname_db, nd->exname, nd);
return nd;
}
/**
* Parses a warp npc.
* Line definition <from mapname>,<fromX>,<fromY>,<facing>%TAB%warp%TAB%<warp name>%TAB%<spanx>,<spany>,<to mapname>,<toX>,<toY>
* @param w1 : word 1 before tab (<from map name>,<fromX>,<fromY>,<facing>)
* @param w2 : word 2 before tab (warp), keyword that sent us in this parsing
* @param w3 : word 3 before tab (<warp name>)
* @param w4 : word 4 before tab (<spanx>,<spany>,<to mapname>,<toX>,<toY>)
* @param start : index to start parsing
* @param buffer : lines to parses
* @param filepath : filename with path wich we are parsing
* @return new index for next parsing
*/
static const char* npc_parse_warp(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
{
int x, y, xs, ys, to_x, to_y, m;
unsigned short i;
char mapname[32], to_mapname[32];
struct npc_data *nd;
// w1=<from map name>,<fromX>,<fromY>,<facing>
// w4=<spanx>,<spany>,<to map name>,<toX>,<toY>
if( sscanf(w1, "%31[^,],%d,%d", mapname, &x, &y) != 3
|| sscanf(w4, "%d,%d,%31[^,],%d,%d", &xs, &ys, to_mapname, &to_x, &to_y) != 5 )
{
ShowError("npc_parse_warp: Invalid warp definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return strchr(start,'\n');// skip and continue
}
m = map_mapname2mapid(mapname);
i = mapindex_name2id(to_mapname);
if( i == 0 )
{
ShowError("npc_parse_warp: Unknown destination map in file '%s', line '%d' : %s\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), to_mapname, w1, w2, w3, w4);
return strchr(start,'\n');// skip and continue
}
if( m != -1 && ( x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys ) ) {
ShowWarning("npc_parse_warp: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, map[m].name, map[m].xs, map[m].ys,filepath,strline(buffer,start-buffer));
}
CREATE(nd, struct npc_data, 1);
nd->bl.id = npc_get_new_npc_id();
map_addnpc(m, nd);
nd->bl.prev = nd->bl.next = NULL;
nd->bl.m = m;
nd->bl.x = x;
nd->bl.y = y;
npc_parsename(nd, w3, start, buffer, filepath);
if (!battle_config.warp_point_debug)
nd->class_ = WARP_CLASS;
else
nd->class_ = WARP_DEBUG_CLASS;
nd->speed = 200;
nd->u.warp.mapindex = i;
nd->u.warp.x = to_x;
nd->u.warp.y = to_y;
nd->u.warp.xs = xs;
nd->u.warp.ys = ys;
npc_warp++;
nd->bl.type = BL_NPC;
nd->subtype = NPCTYPE_WARP;
npc_setcells(nd);
if(map_addblock(&nd->bl)) //couldn't add on map
return strchr(start,'\n');
status_set_viewdata(&nd->bl, nd->class_);
status_change_init(&nd->bl);
unit_dataset(&nd->bl);
if( map[nd->bl.m].users )
clif_spawn(&nd->bl);
strdb_put(npcname_db, nd->exname, nd);
return strchr(start,'\n');// continue
}
/**
* Parses a shop/cashshop npc.
* Line definition :
* <map name>,<x>,<y>,<facing>%TAB%shop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>{,<itemid>:<price>...}
* <map name>,<x>,<y>,<facing>%TAB%cashshop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>{,<itemid>:<price>...}
* <map name>,<x>,<y>,<facing>%TAB%itemshop%TAB%<NPC Name>%TAB%<sprite id>,<costitemid>{:<discount>},<itemid>:<price>{,<itemid>:<price>...}
* <map name>,<x>,<y>,<facing>%TAB%pointshop%TAB%<NPC Name>%TAB%<sprite id>,<costvariable>{:<discount>},<itemid>:<price>{,<itemid>:<price>...}
* <map name>,<x>,<y>,<facing>%TAB%marketshop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>:<quantity>{,<itemid>:<price>:<quantity>...}
* @param w1 : word 1 before tab (<from map name>,<x>,<y>,<facing>)
* @param w2 : word 2 before tab (shop|cashshop|itemshop|pointshop|marketshop), keyword that sent us in this parsing
* @param w3 : word 3 before tab (<NPC Name>)
* @param w4 : word 4 before tab (<sprited id>,<shop definition...>)
* @param start : index to start parsing
* @param buffer : lines to parses
* @param filepath : filename with path wich we are parsing
* @return new index for next parsing
*/
static const char* npc_parse_shop(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
{
char *p, point_str[32];
int x, y, dir, m, is_discount = 0;
unsigned short nameid = 0;
struct npc_data *nd;
enum npc_subtype type;
if( strcmp(w1,"-") == 0 )
{// 'floating' shop?
x = y = dir = 0;
m = -1;
}
else
{// w1=<map name>,<x>,<y>,<facing>
char mapname[32];
if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4
|| strchr(w4, ',') == NULL )
{
ShowError("npc_parse_shop: Invalid shop definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return strchr(start,'\n');// skip and continue
}
m = map_mapname2mapid(mapname);
}
if( m != -1 && ( x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys ) ) {
ShowWarning("npc_parse_shop: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, map[m].name, map[m].xs, map[m].ys,filepath,strline(buffer,start-buffer));
}
if( !strcasecmp(w2,"cashshop") )
type = NPCTYPE_CASHSHOP;
else if( !strcasecmp(w2,"itemshop") )
type = NPCTYPE_ITEMSHOP;
else if( !strcasecmp(w2,"pointshop") )
type = NPCTYPE_POINTSHOP;
else if( !strcasecmp(w2, "marketshop") )
type = NPCTYPE_MARKETSHOP;
else
type = NPCTYPE_SHOP;
p = strchr(w4,',');
memset(point_str,'\0',sizeof(point_str));
switch(type) {
case NPCTYPE_ITEMSHOP: {
if (sscanf(p,",%hu:%d,",&nameid,&is_discount) < 1) {
ShowError("npc_parse_shop: Invalid item cost definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return strchr(start,'\n'); // skip and continue
}
if (itemdb_exists(nameid) == NULL) {
ShowWarning("npc_parse_shop: Invalid item ID cost in file '%s', line '%d' (id '%hu').\n", filepath, strline(buffer,start-buffer), nameid);
return strchr(start,'\n'); // skip and continue
}
p = strchr(p+1,',');
break;
}
case NPCTYPE_POINTSHOP: {
if (sscanf(p, ",%32[^,:]:%d,",point_str,&is_discount) < 1) {
ShowError("npc_parse_shop: Invalid item cost definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return strchr(start,'\n'); // skip and continue
}
switch(point_str[0]) {
case '$':
case '.':
case '\'':
ShowWarning("npc_parse_shop: Invalid item cost variable type (must be permanent character or account based) in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return strchr(start,'\n'); // skip and continue
break;
}
if (point_str[strlen(point_str) - 1] == '$') {
ShowWarning("npc_parse_shop: Invalid item cost variable type (must be integer) in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return strchr(start,'\n'); // skip and continue
}
p = strchr(p+1,',');
break;
}
case NPCTYPE_MARKETSHOP:
#if PACKETVER < 20131223
ShowError("npc_parse_shop: (MARKETSHOP) Feature is disabled, need client 20131223 or newer. Ignoring file '%s', line '%d\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
return strchr(start, '\n'); // skip and continue
#else
is_discount = 0;
break;
#endif
default:
is_discount = 1;
break;
}
CREATE(nd, struct npc_data, 1);
nd->u.shop.count = 0;
while ( p ) {
unsigned short nameid2, qty = 0;
int value;
struct item_data* id;
bool skip = false;
if( p == NULL )
break;
switch(type) {
case NPCTYPE_MARKETSHOP:
#if PACKETVER >= 20131223
if (sscanf(p, ",%hu:%d:%hu", &nameid2, &value, &qty) != 3) {
ShowError("npc_parse_shop: (MARKETSHOP) Invalid item definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
skip = true;
}
#endif
break;
default:
if (sscanf(p, ",%hu:%d", &nameid2, &value) != 2) {
ShowError("npc_parse_shop: Invalid item definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
skip = true;
}
break;
}
if (skip)
break;
if( (id = itemdb_exists(nameid2)) == NULL ) {
ShowWarning("npc_parse_shop: Invalid sell item in file '%s', line '%d' (id '%hu').\n", filepath, strline(buffer,start-buffer), nameid2);
p = strchr(p+1,',');
continue;
}
if( value < 0 ) {
if (type == NPCTYPE_SHOP || type == NPCTYPE_MARKETSHOP) value = id->value_buy;
else value = 0; // Cashshop doesn't have a "buy price" in the item_db
}
if (value == 0 && (type == NPCTYPE_SHOP || type == NPCTYPE_ITEMSHOP || type == NPCTYPE_POINTSHOP || type == NPCTYPE_MARKETSHOP)) { // NPC selling items for free!
ShowWarning("npc_parse_shop: Item %s [%hu] is being sold for FREE in file '%s', line '%d'.\n",
id->name, nameid2, filepath, strline(buffer,start-buffer));
}
if( type == NPCTYPE_SHOP && value*0.75 < id->value_sell*1.24 ) { // Exploit possible: you can buy and sell back with profit
ShowWarning("npc_parse_shop: Item %s [%hu] discounted buying price (%d->%d) is less than overcharged selling price (%d->%d) at file '%s', line '%d'.\n",
id->name, nameid2, value, (int)(value*0.75), id->value_sell, (int)(id->value_sell*1.24), filepath, strline(buffer,start-buffer));
}
if (type == NPCTYPE_MARKETSHOP && (!qty || qty > UINT16_MAX)) {
ShowWarning("npc_parse_shop: Item %s [%hu] is stocked with invalid value %d, changed to 1. File '%s', line '%d'.\n",
id->name, nameid2, filepath, strline(buffer,start-buffer));
qty = 1;
}
//for logs filters, atcommands and iteminfo script command
if( id->maxchance == 0 )
id->maxchance = -1; // -1 would show that the item's sold in NPC Shop
#if PACKETVER >= 20131223
if (nd->u.shop.count && type == NPCTYPE_MARKETSHOP) {
uint16 i;
// Duplicate entry? Replace the value
ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid);
if (i != nd->u.shop.count) {
nd->u.shop.shop_item[i].qty = qty;
nd->u.shop.shop_item[i].value = value;
p = strchr(p+1,',');
continue;
}
}
#endif
RECREATE(nd->u.shop.shop_item, struct npc_item_list,nd->u.shop.count+1);
nd->u.shop.shop_item[nd->u.shop.count].nameid = nameid2;
nd->u.shop.shop_item[nd->u.shop.count].value = value;
#if PACKETVER >= 20131223
nd->u.shop.shop_item[nd->u.shop.count].flag = 0;
if (type == NPCTYPE_MARKETSHOP)
nd->u.shop.shop_item[nd->u.shop.count].qty = qty;
#endif
nd->u.shop.count++;
p = strchr(p+1,',');
}
if( nd->u.shop.count == 0 ) {
ShowWarning("npc_parse_shop: Ignoring empty shop in file '%s', line '%d'.\n", filepath, strline(buffer,start-buffer));
aFree(nd);
return strchr(start,'\n');// continue
}
if (type != NPCTYPE_SHOP) {
if (type == NPCTYPE_ITEMSHOP) nd->u.shop.itemshop_nameid = nameid; // Item shop currency
else if (type == NPCTYPE_POINTSHOP) safestrncpy(nd->u.shop.pointshop_str,point_str,strlen(point_str)+1); // Point shop currency
nd->u.shop.discount = is_discount;
}
nd->bl.prev = nd->bl.next = NULL;
nd->bl.m = m;
nd->bl.x = x;
nd->bl.y = y;
nd->bl.id = npc_get_new_npc_id();
npc_parsename(nd, w3, start, buffer, filepath);
nd->class_ = m == -1 ? -1 : npc_parseview(w4, start, buffer, filepath);
nd->speed = 200;
++npc_shop;
nd->bl.type = BL_NPC;
nd->subtype = type;
#if PACKETVER >= 20131223
// Insert market data to table
if (nd->subtype == NPCTYPE_MARKETSHOP) {
uint16 i;
for (i = 0; i < nd->u.shop.count; i++)
npc_market_tosql(nd->exname, &nd->u.shop.shop_item[i]);
}
#endif
if( m >= 0 )
{// normal shop npc
map_addnpc(m,nd);
if(map_addblock(&nd->bl))
return strchr(start,'\n');
status_set_viewdata(&nd->bl, nd->class_);
status_change_init(&nd->bl);
unit_dataset(&nd->bl);
nd->ud.dir = dir;
if( map[nd->bl.m].users )
clif_spawn(&nd->bl);
} else
{// 'floating' shop?
map_addiddb(&nd->bl);
}
strdb_put(npcname_db, nd->exname, nd);
return strchr(start,'\n');// continue
}
/** [Cydh]
* Check if the shop is affected by discount or not
* @param type Type of NPC shop (enum npc_subtype)
* @param discount Discount flag of NPC shop
* @return bool 'true' is discountable, 'false' otherwise
*/
bool npc_shop_discount(enum npc_subtype type, bool discount) {
if (type == NPCTYPE_SHOP || (type != NPCTYPE_SHOP && discount))
return true;
if( (type == NPCTYPE_ITEMSHOP && battle_config.discount_item_point_shop&1) ||
(type == NPCTYPE_POINTSHOP && battle_config.discount_item_point_shop&2) )
return true;
return false;
}
/**
* NPC other label
* Not sure, seem to add label in a chainlink
* @see DBApply
*/
int npc_convertlabel_db(DBKey key, DBData *data, va_list ap)
{
const char* lname = (const char*)key.str;
int lpos = db_data2i(data);
struct npc_label_list** label_list;
int* label_list_num;
const char* filepath;
struct npc_label_list* label;
const char *p;
int len;
nullpo_ret(label_list = va_arg(ap,struct npc_label_list**));
nullpo_ret(label_list_num = va_arg(ap,int*));
nullpo_ret(filepath = va_arg(ap,const char*));
// In case of labels not terminated with ':', for user defined function support
p = lname;
while( ISALNUM(*p) || *p == '_' )
++p;
len = p-lname;
// here we check if the label fit into the buffer
if( len > 23 )
{
ShowError("npc_parse_script: label name longer than 23 chars! '%s'\n (%s)", lname, filepath);
return 0;
}
if( *label_list == NULL )
{
*label_list = (struct npc_label_list *) aCalloc (1, sizeof(struct npc_label_list));
*label_list_num = 0;
} else
*label_list = (struct npc_label_list *) aRealloc (*label_list, sizeof(struct npc_label_list)*(*label_list_num+1));
label = *label_list+*label_list_num;
safestrncpy(label->name, lname, sizeof(label->name));
label->pos = lpos;
++(*label_list_num);
return 0;
}
// Skip the contents of a script.
static const char* npc_skip_script(const char* start, const char* buffer, const char* filepath)
{
const char* p;
int curly_count;
if( start == NULL )
return NULL;// nothing to skip
// initial bracket (assumes the previous part is ok)
p = strchr(start,'{');
if( p == NULL )
{
ShowError("npc_skip_script: Missing left curly in file '%s', line'%d'.", filepath, strline(buffer,start-buffer));
return NULL;// can't continue
}
// skip everything
for( curly_count = 1; curly_count > 0 ; )
{
p = skip_space(p+1) ;
if( *p == '}' )
{// right curly
--curly_count;
}
else if( *p == '{' )
{// left curly
++curly_count;
}
else if( *p == '"' )
{// string
for( ++p; *p != '"' ; ++p )
{
if( *p == '\\' && (unsigned char)p[-1] <= 0x7e )
++p;// escape sequence (not part of a multibyte character)
else if( *p == '\0' )
{
script_error(buffer, filepath, 0, "Unexpected end of string.", p);
return NULL;// can't continue
}
else if( *p == '\n' )
{
script_error(buffer, filepath, 0, "Unexpected newline at string.", p);
return NULL;// can't continue
}
}
}
else if( *p == '\0' )
{// end of buffer
ShowError("Missing %d right curlys at file '%s', line '%d'.\n", curly_count, filepath, strline(buffer,p-buffer));
return NULL;// can't continue
}
}
return p+1;// return after the last '}'
}
/**
* Parses a npc script.
* Line definition :
* <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,{<code>}
* <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>,{<code>} * @TODO missing cashshop line definition
* @param w1 : word 1 before tab (<from map name>,<x>,<y>,<facing>)
* @param w2 : word 2 before tab (script), keyword that sent us in this parsing
* @param w3 : word 3 before tab (<NPC Name>)
* @param w4 : word 4 before tab (<sprited id>,<code>)
* @param start : index to start parsing
* @param buffer : lines to parses
* @param filepath : filename with path wich we are parsing
* @return new index for next parsing
*/
static const char* npc_parse_script(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath, bool runOnInit) {
int x, y, dir = 0, m, xs = 0, ys = 0; // [Valaris] thanks to fov
struct script_code *script;
int i;
const char* end;
const char* script_start;
struct npc_label_list* label_list;
int label_list_num;
struct npc_data* nd;
if( strcmp(w1, "-") == 0 )
{// floating npc
x = 0;
y = 0;
m = -1;
}
else
{// npc in a map
char mapname[32];
if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4 )
{
ShowError("npc_parse_script: Invalid placement format for a script in file '%s', line '%d'. Skipping the rest of file...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return NULL;// unknown format, don't continue
}
m = map_mapname2mapid(mapname);
}
script_start = strstr(start,",{");
end = strchr(start,'\n');
if( strstr(w4,",{") == NULL || script_start == NULL || (end != NULL && script_start > end) )
{
ShowError("npc_parse_script: Missing left curly ',{' in file '%s', line '%d'. Skipping the rest of the file.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return NULL;// can't continue
}
++script_start;
end = npc_skip_script(script_start, buffer, filepath);
if( end == NULL )
return NULL;// (simple) parse error, don't continue
script = parse_script(script_start, filepath, strline(buffer,script_start-buffer), SCRIPT_USE_LABEL_DB);
label_list = NULL;
label_list_num = 0;
if( script )
{
DBMap* label_db = script_get_label_db();
label_db->foreach(label_db, npc_convertlabel_db, &label_list, &label_list_num, filepath);
db_clear(label_db); // not needed anymore, so clear the db
}
CREATE(nd, struct npc_data, 1);
if( sscanf(w4, "%*[^,],%d,%d", &xs, &ys) == 2 )
{// OnTouch area defined
nd->u.scr.xs = xs;
nd->u.scr.ys = ys;
}
else
{// no OnTouch area
nd->u.scr.xs = -1;
nd->u.scr.ys = -1;
}
nd->bl.prev = nd->bl.next = NULL;
nd->bl.m = m;
nd->bl.x = x;
nd->bl.y = y;
npc_parsename(nd, w3, start, buffer, filepath);
nd->bl.id = npc_get_new_npc_id();
nd->class_ = m == -1 ? -1 : npc_parseview(w4, start, buffer, filepath);
nd->speed = 200;
nd->u.scr.script = script;
nd->u.scr.label_list = label_list;
nd->u.scr.label_list_num = label_list_num;
++npc_script;
nd->bl.type = BL_NPC;
nd->subtype = NPCTYPE_SCRIPT;
if( m >= 0 )
{
map_addnpc(m, nd);
status_change_init(&nd->bl);
unit_dataset(&nd->bl);
nd->ud.dir = dir;
npc_setcells(nd);
if(map_addblock(&nd->bl))
return NULL;
if( nd->class_ >= 0 )
{
status_set_viewdata(&nd->bl, nd->class_);
if( map[nd->bl.m].users )
clif_spawn(&nd->bl);
}
}
else
{
// we skip map_addnpc, but still add it to the list of ID's
map_addiddb(&nd->bl);
}
strdb_put(npcname_db, nd->exname, nd);
//-----------------------------------------
// Loop through labels to export them as necessary
for (i = 0; i < nd->u.scr.label_list_num; i++) {
if (npc_event_export(nd, i)) {
ShowWarning("npc_parse_script : duplicate event %s::%s (%s)\n",
nd->exname, nd->u.scr.label_list[i].name, filepath);
}
npc_timerevent_export(nd, i);
}
nd->u.scr.timerid = INVALID_TIMER;
if( runOnInit ) {
char evname[EVENT_NAME_LENGTH];
struct event_data *ev;
snprintf(evname, ARRAYLENGTH(evname), "%s::OnInit", nd->exname);
if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) ) {
//Execute OnInit
run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
}
}
return end;
}
/// Duplicate a warp, shop, cashshop or script. [Orcao]
/// warp: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<spanx>,<spany>
/// shop/cashshop/npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
/// shop/cashshop/npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
/// npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
/// npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
const char* npc_parse_duplicate(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
{
int x, y, dir, m, xs = -1, ys = -1;
char srcname[128];
int i;
const char* end;
size_t length;
int src_id;
int type;
struct npc_data* nd;
struct npc_data* dnd;
end = strchr(start,'\n');
length = strlen(w2);
// get the npc being duplicated
if( w2[length-1] != ')' || length <= 11 || length-11 >= sizeof(srcname) )
{// does not match 'duplicate(%127s)', name is empty or too long
ShowError("npc_parse_script: bad duplicate name in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), w2);
return end;// next line, try to continue
}
safestrncpy(srcname, w2+10, length-10);
dnd = npc_name2id(srcname);
if( dnd == NULL) {
ShowError("npc_parse_script: original npc not found for duplicate in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), srcname);
return end;// next line, try to continue
}
src_id = dnd->bl.id;
type = dnd->subtype;
// get placement
if ((type == NPCTYPE_SHOP || type == NPCTYPE_CASHSHOP || type == NPCTYPE_ITEMSHOP || type == NPCTYPE_POINTSHOP || type == NPCTYPE_SCRIPT || type == NPCTYPE_MARKETSHOP) && strcmp(w1, "-") == 0) {// floating shop/chashshop/itemshop/pointshop/script
x = y = dir = 0;
m = -1;
} else {
char mapname[32];
if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4 ) { // <map name>,<x>,<y>,<facing>
ShowError("npc_parse_duplicate: Invalid placement format for duplicate in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return end;// next line, try to continue
}
m = map_mapname2mapid(mapname);
}
if( m != -1 && ( x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys ) ) {
ShowError("npc_parse_duplicate: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, map[m].name, map[m].xs, map[m].ys,filepath,strline(buffer,start-buffer));
}
if( type == NPCTYPE_WARP && sscanf(w4, "%d,%d", &xs, &ys) == 2 );// <spanx>,<spany>
else if( type == NPCTYPE_SCRIPT && sscanf(w4, "%*[^,],%d,%d", &xs, &ys) == 2);// <sprite id>,<triggerX>,<triggerY>
else if( type == NPCTYPE_WARP ) {
ShowError("npc_parse_duplicate: Invalid span format for duplicate warp in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return end;// next line, try to continue
}
CREATE(nd, struct npc_data, 1);
nd->bl.prev = nd->bl.next = NULL;
nd->bl.m = m;
nd->bl.x = x;
nd->bl.y = y;
npc_parsename(nd, w3, start, buffer, filepath);
nd->bl.id = npc_get_new_npc_id();
nd->class_ = m == -1 ? -1 : npc_parseview(w4, start, buffer, filepath);
nd->speed = 200;
nd->src_id = src_id;
nd->bl.type = BL_NPC;
nd->subtype = (enum npc_subtype)type;
switch( type ) {
case NPCTYPE_SCRIPT:
++npc_script;
nd->u.scr.xs = xs;
nd->u.scr.ys = ys;
nd->u.scr.script = dnd->u.scr.script;
nd->u.scr.label_list = dnd->u.scr.label_list;
nd->u.scr.label_list_num = dnd->u.scr.label_list_num;
break;
case NPCTYPE_SHOP:
case NPCTYPE_CASHSHOP:
case NPCTYPE_ITEMSHOP:
case NPCTYPE_POINTSHOP:
case NPCTYPE_MARKETSHOP:
++npc_shop;
nd->u.shop.shop_item = dnd->u.shop.shop_item;
nd->u.shop.count = dnd->u.shop.count;
break;
case NPCTYPE_WARP:
++npc_warp;
if( !battle_config.warp_point_debug )
nd->class_ = WARP_CLASS;
else
nd->class_ = WARP_DEBUG_CLASS;
nd->u.warp.xs = xs;
nd->u.warp.ys = ys;
nd->u.warp.mapindex = dnd->u.warp.mapindex;
nd->u.warp.x = dnd->u.warp.x;
nd->u.warp.y = dnd->u.warp.y;
break;
}
//Add the npc to its location
if( m >= 0 ) {
map_addnpc(m, nd);
status_change_init(&nd->bl);
unit_dataset(&nd->bl);
nd->ud.dir = dir;
npc_setcells(nd);
if(map_addblock(&nd->bl))
return end;
if( nd->class_ >= 0 ) {
status_set_viewdata(&nd->bl, nd->class_);
if( map[nd->bl.m].users )
clif_spawn(&nd->bl);
}
} else {
// we skip map_addnpc, but still add it to the list of ID's
map_addiddb(&nd->bl);
}
strdb_put(npcname_db, nd->exname, nd);
if( type != NPCTYPE_SCRIPT )
return end;
//-----------------------------------------
// Loop through labels to export them as necessary
for (i = 0; i < nd->u.scr.label_list_num; i++) {
if (npc_event_export(nd, i)) {
ShowWarning("npc_parse_duplicate : duplicate event %s::%s (%s)\n",
nd->exname, nd->u.scr.label_list[i].name, filepath);
}
npc_timerevent_export(nd, i);
}
if(!strcmp(filepath,"INSTANCING")) //Instance NPCs will use this for commands
nd->instance_id = map[m].instance_id;
nd->u.scr.timerid = INVALID_TIMER;
return end;
}
int npc_duplicate4instance(struct npc_data *snd, int16 m) {
char newname[NAME_LENGTH];
if( map[m].instance_id == 0 )
return 1;
snprintf(newname, ARRAYLENGTH(newname), "dup_%d_%d", map[m].instance_id, snd->bl.id);
if( npc_name2id(newname) != NULL ) { // Name already in use
ShowError("npc_duplicate4instance: the npcname (%s) is already in use while trying to duplicate npc %s in instance %d.\n", newname, snd->exname, map[m].instance_id);
return 1;
}
if( snd->subtype == NPCTYPE_WARP ) { // Adjust destination, if instanced
struct npc_data *wnd = NULL; // New NPC
struct instance_data *im = &instance_data[map[m].instance_id];
int dm = map_mapindex2mapid(snd->u.warp.mapindex), imap = 0, i;
if( dm < 0 ) return 1;
for(i = 0; i < MAX_MAP_PER_INSTANCE; i++)
if(im->map[i].m && map_mapname2mapid(map[im->map[i].src_m].name) == dm) {
imap = map_mapname2mapid(map[m].name);
break; // Instance map matches destination, update to instance map
}
if(!imap)
imap = map_mapname2mapid(map[dm].name);
if( imap == -1 ) {
ShowError("npc_duplicate4instance: warp (%s) leading to instanced map (%s), but instance map is not attached to current instance.\n", map[dm].name, snd->exname);
return 1;
}
CREATE(wnd, struct npc_data, 1);
wnd->bl.id = npc_get_new_npc_id();
map_addnpc(m, wnd);
wnd->bl.prev = wnd->bl.next = NULL;
wnd->bl.m = m;
wnd->bl.x = snd->bl.x;
wnd->bl.y = snd->bl.y;
safestrncpy(wnd->name, "", ARRAYLENGTH(wnd->name));
safestrncpy(wnd->exname, newname, ARRAYLENGTH(wnd->exname));
wnd->class_ = WARP_CLASS;
wnd->speed = 200;
wnd->u.warp.mapindex = map_id2index(imap);
wnd->u.warp.x = snd->u.warp.x;
wnd->u.warp.y = snd->u.warp.y;
wnd->u.warp.xs = snd->u.warp.xs;
wnd->u.warp.ys = snd->u.warp.ys;
wnd->bl.type = BL_NPC;
wnd->subtype = NPCTYPE_WARP;
npc_setcells(wnd);
if(map_addblock(&wnd->bl))
return 1;
status_set_viewdata(&wnd->bl, wnd->class_);
status_change_init(&wnd->bl);
unit_dataset(&wnd->bl);
if( map[wnd->bl.m].users )
clif_spawn(&wnd->bl);
strdb_put(npcname_db, wnd->exname, wnd);
} else {
static char w1[50], w2[50], w3[50], w4[50];
const char* stat_buf = "- call from instancing subsystem -\n";
snprintf(w1, sizeof(w1), "%s,%d,%d,%d", map[m].name, snd->bl.x, snd->bl.y, snd->ud.dir);
snprintf(w2, sizeof(w2), "duplicate(%s)", snd->exname);
snprintf(w3, sizeof(w3), "%s::%s", snd->name, newname);
if( snd->u.scr.xs >= 0 && snd->u.scr.ys >= 0 )
snprintf(w4, sizeof(w4), "%d,%d,%d", snd->class_, snd->u.scr.xs, snd->u.scr.ys); // Touch Area
else
snprintf(w4, sizeof(w4), "%d", snd->class_);
npc_parse_duplicate(w1, w2, w3, w4, stat_buf, stat_buf, "INSTANCING");
}
return 0;
}
int npc_instanceinit(struct npc_data* nd)
{
struct event_data *ev;
char evname[EVENT_NAME_LENGTH];
snprintf(evname, ARRAYLENGTH(evname), "%s::OnInstanceInit", nd->exname);
if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) )
run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
return 0;
}
#if PACKETVER >= 20131223
/**
* Saves persistent NPC Market Data into SQL
* @param exname NPC exname
* @param nameid Item ID
* @param qty Stock
**/
void npc_market_tosql(const char *exname, struct npc_item_list *list) {
SqlStmt* stmt = SqlStmt_Malloc(mmysql_handle);
if (SQL_ERROR == SqlStmt_Prepare(stmt, "REPLACE INTO `%s` (`name`,`nameid`,`price`,`amount`,`flag`) VALUES ('%s','%hu','%d','%hu','%"PRIu8"')",
market_table, exname, list->nameid, list->value, list->qty, list->flag) ||
SQL_ERROR == SqlStmt_Execute(stmt))
SqlStmt_ShowDebug(stmt);
SqlStmt_Free(stmt);
}
/**
* Removes persistent NPC Market Data from SQL
* @param exname NPC exname
* @param nameid Item ID
* @param clear True: will removes all records related with the NPC
**/
void npc_market_delfromsql_(const char *exname, unsigned short nameid, bool clear) {
SqlStmt* stmt = SqlStmt_Malloc(mmysql_handle);
if (clear) {
if( SQL_ERROR == SqlStmt_Prepare(stmt, "DELETE FROM `%s` WHERE `name`='%s'", market_table, exname) ||
SQL_ERROR == SqlStmt_Execute(stmt))
SqlStmt_ShowDebug(stmt);
} else {
if (SQL_ERROR == SqlStmt_Prepare(stmt, "DELETE FROM `%s` WHERE `name`='%s' AND `nameid`='%d' LIMIT 1", market_table, exname, nameid) ||
SQL_ERROR == SqlStmt_Execute(stmt))
SqlStmt_ShowDebug(stmt);
}
SqlStmt_Free(stmt);
}
/**
* Check NPC Market Shop for each entry
**/
static int npc_market_checkall_sub(DBKey key, DBData *data, va_list ap) {
struct s_npc_market *market = (struct s_npc_market *)db_data2ptr(data);
struct npc_data *nd = NULL;
uint16 i;
if (!market)
return 1;
nd = npc_name2id(market->exname);
if (!nd) {
ShowInfo("npc_market_checkall_sub: NPC '%s' not found, removing...\n", market->exname);
npc_market_clearfromsql(market->exname);
return 1;
}
else if (nd->subtype != NPCTYPE_MARKETSHOP || !nd->u.shop.shop_item || !nd->u.shop.count ) {
ShowError("npc_market_checkall_sub: NPC '%s' is not proper for market, removing...\n", nd->exname);
npc_market_clearfromsql(nd->exname);
return 1;
}
if (!market->count || !market->list)
return 1;
for (i = 0; i < market->count; i++) {
struct npc_item_list *list = &market->list[i];
uint16 j;
if (!list->nameid || !itemdb_exists(list->nameid)) {
ShowError("npc_market_checkall_sub: NPC '%s' sells invalid item '%hu', deleting...\n", nd->exname, list->nameid);
npc_market_delfromsql(nd->exname, list->nameid);
continue;
}
// Reloading stock from `market` table
ARR_FIND(0, nd->u.shop.count, j, nd->u.shop.shop_item[j].nameid == list->nameid);
if (j != nd->u.shop.count) {
nd->u.shop.shop_item[j].value = list->value;
nd->u.shop.shop_item[j].qty = list->qty;
nd->u.shop.shop_item[j].flag = list->flag;
npc_market_tosql(nd->exname, &nd->u.shop.shop_item[j]);
continue;
}
if (list->flag&1) { // Item added by npcshopitem/npcshopadditem, add new entry
RECREATE(nd->u.shop.shop_item, struct npc_item_list, nd->u.shop.count+1);
nd->u.shop.shop_item[j].nameid = list->nameid;
nd->u.shop.shop_item[j].value = list->value;
nd->u.shop.shop_item[j].qty = list->qty;
nd->u.shop.shop_item[j].flag = list->flag;
nd->u.shop.count++;
npc_market_tosql(nd->exname, &nd->u.shop.shop_item[j]);
}
else { // Removing "out-of-date" entry
ShowError("npc_market_checkall_sub: NPC '%s' does not sell item %hu (qty %hu), deleting...\n", nd->exname, list->nameid, list->qty);
npc_market_delfromsql(nd->exname, list->nameid);
}
}
return 0;
}
/**
* Clear NPC market single entry
**/
static int npc_market_free(DBKey key, DBData *data, va_list ap) {
struct s_npc_market *market = (struct s_npc_market *)db_data2ptr(data);
if (!market)
return 0;
if (market->list) {
aFree(market->list);
market->list = NULL;
}
aFree(market);
return 1;
}
/**
* Check all existing NPC Market Shop after first loading map-server or after reloading scripts.
* Overwrite stocks from NPC by using stock entries from `market` table.
**/
static void npc_market_checkall(void) {
if (!db_size(NPCMarketDB))
return;
else {
ShowInfo("Checking '"CL_WHITE"%d"CL_RESET"' NPC Markets...\n", db_size(NPCMarketDB));
NPCMarketDB->foreach(NPCMarketDB, npc_market_checkall_sub);
ShowStatus("Done checking '"CL_WHITE"%d"CL_RESET"' NPC Markets.\n", db_size(NPCMarketDB));
NPCMarketDB->clear(NPCMarketDB, npc_market_free);
}
}
/**
* Loads persistent NPC Market Data from SQL, use the records after NPCs init'd to reuse the stock values.
**/
static void npc_market_fromsql(void) {
uint32 count = 0;
if (SQL_ERROR == Sql_Query(mmysql_handle, "SELECT `name`,`nameid`,`price`,`amount`,`flag` FROM `%s` ORDER BY `name`", market_table)) {
Sql_ShowDebug(mmysql_handle);
return;
}
while (SQL_SUCCESS == Sql_NextRow(mmysql_handle)) {
char *data;
struct s_npc_market *market;
struct npc_item_list list;
Sql_GetData(mmysql_handle, 0, &data, NULL);
if (!(market = (struct s_npc_market *)strdb_get(NPCMarketDB,data))) {
CREATE(market, struct s_npc_market, 1);
market->count = 0;
safestrncpy(market->exname, data, strlen(data)+1);
strdb_put(NPCMarketDB, market->exname, market);
}
Sql_GetData(mmysql_handle, 1, &data, NULL); list.nameid = atoi(data);
Sql_GetData(mmysql_handle, 2, &data, NULL); list.value = atoi(data);
Sql_GetData(mmysql_handle, 3, &data, NULL); list.qty = atoi(data);
Sql_GetData(mmysql_handle, 4, &data, NULL); list.flag = atoi(data);
RECREATE(market->list, struct npc_item_list, market->count+1);
market->list[market->count++] = list;
count++;
}
Sql_FreeResult(mmysql_handle);
ShowStatus("Done loading '"CL_WHITE"%d"CL_RESET"' entries for '"CL_WHITE"%d"CL_RESET"' NPC Markets from '"CL_WHITE"%s"CL_RESET"' table.\n", count, db_size(NPCMarketDB), market_table);
}
#endif
//Set mapcell CELL_NPC to trigger event later
void npc_setcells(struct npc_data* nd)
{
int16 m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
int i,j;
switch(nd->subtype)
{
case NPCTYPE_WARP:
xs = nd->u.warp.xs;
ys = nd->u.warp.ys;
break;
case NPCTYPE_SCRIPT:
xs = nd->u.scr.xs;
ys = nd->u.scr.ys;
break;
default:
return; // Other types doesn't have touch area
}
if (m < 0 || xs < 0 || ys < 0) //invalid range or map
return;
for (i = y-ys; i <= y+ys; i++) {
for (j = x-xs; j <= x+xs; j++) {
if (map_getcell(m, j, i, CELL_CHKNOPASS))
continue;
map_setcell(m, j, i, CELL_NPC, true);
}
}
}
int npc_unsetcells_sub(struct block_list* bl, va_list ap)
{
struct npc_data *nd = (struct npc_data*)bl;
int id = va_arg(ap,int);
if (nd->bl.id == id) return 0;
npc_setcells(nd);
return 1;
}
void npc_unsetcells(struct npc_data* nd)
{
int16 m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
int i,j, x0, x1, y0, y1;
if (nd->subtype == NPCTYPE_WARP) {
xs = nd->u.warp.xs;
ys = nd->u.warp.ys;
} else {
xs = nd->u.scr.xs;
ys = nd->u.scr.ys;
}
if (m < 0 || xs < 0 || ys < 0)
return;
//Locate max range on which we can locate npc cells
//FIXME: does this really do what it's supposed to do? [ultramage]
for(x0 = x-xs; x0 > 0 && map_getcell(m, x0, y, CELL_CHKNPC); x0--);
for(x1 = x+xs; x1 < map[m].xs-1 && map_getcell(m, x1, y, CELL_CHKNPC); x1++);
for(y0 = y-ys; y0 > 0 && map_getcell(m, x, y0, CELL_CHKNPC); y0--);
for(y1 = y+ys; y1 < map[m].ys-1 && map_getcell(m, x, y1, CELL_CHKNPC); y1++);
//Erase this npc's cells
for (i = y-ys; i <= y+ys; i++)
for (j = x-xs; j <= x+xs; j++)
map_setcell(m, j, i, CELL_NPC, false);
//Re-deploy NPC cells for other nearby npcs.
map_foreachinarea( npc_unsetcells_sub, m, x0, y0, x1, y1, BL_NPC, nd->bl.id );
}
void npc_movenpc(struct npc_data* nd, int16 x, int16 y)
{
const int16 m = nd->bl.m;
if (m < 0 || nd->bl.prev == NULL) return; //Not on a map.
x = cap_value(x, 0, map[m].xs-1);
y = cap_value(y, 0, map[m].ys-1);
map_foreachinrange(clif_outsight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
map_moveblock(&nd->bl, x, y, gettick());
map_foreachinrange(clif_insight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
}
/// Changes the display name of the npc.
///
/// @param nd Target npc
/// @param newname New display name
void npc_setdisplayname(struct npc_data* nd, const char* newname)
{
nullpo_retv(nd);
safestrncpy(nd->name, newname, sizeof(nd->name));
if( map[nd->bl.m].users )
clif_charnameack(0, &nd->bl);
}
/// Changes the display class of the npc.
///
/// @param nd Target npc
/// @param class_ New display class
void npc_setclass(struct npc_data* nd, short class_)
{
nullpo_retv(nd);
if( nd->class_ == class_ )
return;
if( map[nd->bl.m].users )
clif_clearunit_area(&nd->bl, CLR_OUTSIGHT);// fade out
nd->class_ = class_;
status_set_viewdata(&nd->bl, class_);
if( map[nd->bl.m].users )
clif_spawn(&nd->bl);// fade in
}
// @commands (script based)
int npc_do_atcmd_event(struct map_session_data* sd, const char* command, const char* message, const char* eventname)
{
struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
struct npc_data *nd;
struct script_state *st;
int i = 0, j = 0, k = 0;
char *temp;
nullpo_ret(sd);
if( ev == NULL || (nd = ev->nd) == NULL ) {
ShowError("npc_event: event not found [%s]\n", eventname);
return 0;
}
if( sd->npc_id != 0 ) { // Enqueue the event trigger.
int l;
ARR_FIND( 0, MAX_EVENTQUEUE, l, sd->eventqueue[l][0] == '\0' );
if( l < MAX_EVENTQUEUE ) {
safestrncpy(sd->eventqueue[l],eventname,50); //Event enqueued.
return 0;
}
ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
return 1;
}
if( ev->nd->sc.option&OPTION_INVISIBLE ) { // Disabled npc, shouldn't trigger event.
npc_event_dequeue(sd);
return 2;
}
st = script_alloc_state(ev->nd->u.scr.script, ev->pos, sd->bl.id, ev->nd->bl.id);
setd_sub(st, NULL, ".@atcmd_command$", 0, (void *)command, NULL);
// split atcmd parameters based on spaces
temp = (char*)aMalloc(strlen(message) + 1);
for( i = 0; i < ( strlen( message ) + 1 ) && k < 127; i ++ ) {
if( message[i] == ' ' || message[i] == '\0' ) {
if( message[ ( i - 1 ) ] == ' ' ) {
continue; // To prevent "@atcmd [space][space]" and .@atcmd_numparameters return 1 without any parameter.
}
temp[k] = '\0';
k = 0;
if( temp[0] != '\0' ) {
setd_sub( st, NULL, ".@atcmd_parameters$", j++, (void *)temp, NULL );
}
} else {
temp[k] = message[i];
k++;
}
}
setd_sub(st, NULL, ".@atcmd_numparameters", 0, (void *)__64BPRTSIZE(j), NULL);
aFree(temp);
run_script_main(st);
return 0;
}
/// Parses a function.
/// function%TAB%script%TAB%<function name>%TAB%{<code>}
static const char* npc_parse_function(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
{
DBMap* func_db;
DBData old_data;
struct script_code *script;
const char* end;
const char* script_start;
script_start = strstr(start,"\t{");
end = strchr(start,'\n');
if( *w4 != '{' || script_start == NULL || (end != NULL && script_start > end) )
{
ShowError("npc_parse_function: Missing left curly '%%TAB%%{' in file '%s', line '%d'. Skipping the rest of the file.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return NULL;// can't continue
}
++script_start;
end = npc_skip_script(script_start,buffer,filepath);
if( end == NULL )
return NULL;// (simple) parse error, don't continue
script = parse_script(script_start, filepath, strline(buffer,start-buffer), SCRIPT_RETURN_EMPTY_SCRIPT);
if( script == NULL )// parse error, continue
return end;
func_db = script_get_userfunc_db();
if (func_db->put(func_db, db_str2key(w3), db_ptr2data(script), &old_data))
{
struct script_code *oldscript = (struct script_code*)db_data2ptr(&old_data);
ShowInfo("npc_parse_function: Overwriting user function [%s] (%s:%d)\n", w3, filepath, strline(buffer,start-buffer));
script_free_vars(oldscript->script_vars);
aFree(oldscript->script_buf);
aFree(oldscript);
}
return end;
}
/*==========================================
* Parse Mob 1 - Parse mob list into each map
* Parse Mob 2 - Actually Spawns Mob
* [Wizputer]
*------------------------------------------*/
void npc_parse_mob2(struct spawn_data* mob)
{
int i;
for( i = mob->active; i < mob->num; ++i )
{
struct mob_data* md = mob_spawn_dataset(mob);
md->spawn = mob;
md->spawn->active++;
mob_spawn(md);
}
}
static const char* npc_parse_mob(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
{
int num, class_, m,x,y,xs,ys, i,j;
int mob_lv = -1, ai = -1, size = -1;
char mapname[32], mobname[NAME_LENGTH];
struct spawn_data mob, *data;
struct mob_db* db;
memset(&mob, 0, sizeof(struct spawn_data));
mob.state.boss = !strcmpi(w2,"boss_monster");
// w1=<map name>,<x>,<y>,<xs>,<ys>
// w3=<mob name>{,<mob level>}
// w4=<mob id>,<amount>,<delay1>,<delay2>,<event>{,<mob size>,<mob ai>}
if( sscanf(w1, "%31[^,],%d,%d,%d,%d", mapname, &x, &y, &xs, &ys) < 3
|| sscanf(w3, "%23[^,],%d", mobname, &mob_lv) < 1
|| sscanf(w4, "%d,%d,%u,%u,%127[^,],%d,%d[^\t\r\n]", &class_, &num, &mob.delay1, &mob.delay2, mob.eventname, &size, &ai) < 2 )
{
ShowError("npc_parse_mob: Invalid mob definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return strchr(start,'\n');// skip and continue
}
if( mapindex_name2id(mapname) == 0 )
{
ShowError("npc_parse_mob: Unknown map '%s' in file '%s', line '%d'.\n", mapname, filepath, strline(buffer,start-buffer));
return strchr(start,'\n');// skip and continue
}
m = map_mapname2mapid(mapname);
if( m < 0 )//Not loaded on this map-server instance.
return strchr(start,'\n');// skip and continue
mob.m = (unsigned short)m;
if( x < 0 || x >= map[mob.m].xs || y < 0 || y >= map[mob.m].ys )
{
ShowError("npc_parse_mob: Spawn coordinates out of range: %s (%d,%d), map size is (%d,%d) - %s %s (file '%s', line '%d').\n", map[mob.m].name, x, y, (map[mob.m].xs-1), (map[mob.m].ys-1), w1, w3, filepath, strline(buffer,start-buffer));
return strchr(start,'\n');// skip and continue
}
// check monster ID if exists!
if( mobdb_checkid(class_) == 0 )
{
ShowError("npc_parse_mob: Unknown mob ID %d (file '%s', line '%d').\n", class_, filepath, strline(buffer,start-buffer));
return strchr(start,'\n');// skip and continue
}
if( num < 1 || num > 1000 )
{
ShowError("npc_parse_mob: Invalid number of monsters %d, must be inside the range [1,1000] (file '%s', line '%d').\n", num, filepath, strline(buffer,start-buffer));
return strchr(start,'\n');// skip and continue
}
if( mob.state.size > 2 && size != -1 )
{
ShowError("npc_parse_mob: Invalid size number %d for mob ID %d (file '%s', line '%d').\n", mob.state.size, class_, filepath, strline(buffer, start - buffer));
return strchr(start, '\n');
}
if( (mob.state.ai < AI_NONE || mob.state.ai >= AI_MAX) && ai != -1 )
{
ShowError("npc_parse_mob: Invalid ai %d for mob ID %d (file '%s', line '%d').\n", mob.state.ai, class_, filepath, strline(buffer, start - buffer));
return strchr(start, '\n');
}
if( (mob_lv == 0 || mob_lv > MAX_LEVEL) && mob_lv != -1 )
{
ShowError("npc_parse_mob: Invalid level %d for mob ID %d (file '%s', line '%d').\n", mob_lv, class_, filepath, strline(buffer, start - buffer));
return strchr(start, '\n');
}
mob.num = (unsigned short)num;
mob.active = 0;
mob.id = (short) class_;
mob.x = (unsigned short)x;
mob.y = (unsigned short)y;
mob.xs = (signed short)xs;
mob.ys = (signed short)ys;
if (mob_lv > 0 && mob_lv <= MAX_LEVEL)
mob.level = mob_lv;
if (size > 0 && size <= 2)
mob.state.size = size;
if (ai > AI_NONE && ai <= AI_MAX)
mob.state.ai = ai;
if (mob.num > 1 && battle_config.mob_count_rate != 100) {
if ((mob.num = mob.num * battle_config.mob_count_rate / 100) < 1)
mob.num = 1;
}
if (battle_config.force_random_spawn || (mob.x == 0 && mob.y == 0))
{ //Force a random spawn anywhere on the map.
mob.x = mob.y = 0;
mob.xs = mob.ys = -1;
}
if(mob.delay1>0xfffffff || mob.delay2>0xfffffff) {
ShowError("npc_parse_mob: Invalid spawn delays %u %u (file '%s', line '%d').\n", mob.delay1, mob.delay2, filepath, strline(buffer,start-buffer));
return strchr(start,'\n');// skip and continue
}
//Use db names instead of the spawn file ones.
if(battle_config.override_mob_names==1)
strcpy(mob.name,"--en--");
else if (battle_config.override_mob_names==2)
strcpy(mob.name,"--ja--");
else
safestrncpy(mob.name, mobname, sizeof(mob.name));
//Verify dataset.
if( !mob_parse_dataset(&mob) )
{
ShowError("npc_parse_mob: Invalid dataset for monster ID %d (file '%s', line '%d').\n", class_, filepath, strline(buffer,start-buffer));
return strchr(start,'\n');// skip and continue
}
//Update mob spawn lookup database
db = mob_db(class_);
for( i = 0; i < ARRAYLENGTH(db->spawn); ++i )
{
if (map[mob.m].index == db->spawn[i].mapindex)
{ //Update total
db->spawn[i].qty += mob.num;
//Re-sort list
for( j = i; j > 0 && db->spawn[j-1].qty < db->spawn[i].qty; --j );
if( j != i )
{
xs = db->spawn[i].mapindex;
ys = db->spawn[i].qty;
memmove(&db->spawn[j+1], &db->spawn[j], (i-j)*sizeof(db->spawn[0]));
db->spawn[j].mapindex = xs;
db->spawn[j].qty = ys;
}
break;
}
if (mob.num > db->spawn[i].qty)
{ //Insert into list
memmove(&db->spawn[i+1], &db->spawn[i], sizeof(db->spawn) -(i+1)*sizeof(db->spawn[0]));
db->spawn[i].mapindex = map[mob.m].index;
db->spawn[i].qty = mob.num;
break;
}
}
//Now that all has been validated. We allocate the actual memory that the re-spawn data will use.
data = (struct spawn_data*)aMalloc(sizeof(struct spawn_data));
memcpy(data, &mob, sizeof(struct spawn_data));
// spawn / cache the new mobs
if( battle_config.dynamic_mobs && map_addmobtolist(data->m, data) >= 0 )
{
data->state.dynamic = true;
npc_cache_mob += data->num;
// check if target map has players
// (usually shouldn't occur when map server is just starting,
// but not the case when we do @reloadscript
if( map[data->m].users > 0 )
npc_parse_mob2(data);
}
else
{
data->state.dynamic = false;
npc_parse_mob2(data);
npc_delay_mob += data->num;
}
npc_mob++;
return strchr(start,'\n');// continue
}
/*==========================================
* Set or disable mapflag on map
* eg : bat_c01 mapflag battleground 2
* also chking if mapflag conflict with another
*------------------------------------------*/
static const char* npc_parse_mapflag(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
{
int16 m;
char mapname[32];
int state = 1;
// w1=<mapname>
if( sscanf(w1, "%31[^,]", mapname) != 1 )
{
ShowError("npc_parse_mapflag: Invalid mapflag definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return strchr(start,'\n');// skip and continue
}
m = map_mapname2mapid(mapname);
if( m < 0 )
{
ShowWarning("npc_parse_mapflag: Unknown map in file '%s', line '%d' : %s\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", mapname, filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
return strchr(start,'\n');// skip and continue
}
if (w4 && !strcmpi(w4, "off"))
state = 0; //Disable mapflag rather than enable it. [Skotlex]
if (!strcmpi(w3, "nosave")) {
char savemap[32];
int savex, savey;
if (state == 0)
; //Map flag disabled.
else if (!strcmpi(w4, "SavePoint")) {
map[m].save.map = 0;
map[m].save.x = -1;
map[m].save.y = -1;
} else if (sscanf(w4, "%31[^,],%d,%d", savemap, &savex, &savey) == 3) {
map[m].save.map = mapindex_name2id(savemap);
map[m].save.x = savex;
map[m].save.y = savey;
if (!map[m].save.map) {
ShowWarning("npc_parse_mapflag: Specified save point map '%s' for mapflag 'nosave' not found (file '%s', line '%d'), using 'SavePoint'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", savemap, filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
map[m].save.x = -1;
map[m].save.y = -1;
}
}
map[m].flag.nosave = state;
}
else if (!strcmpi(w3,"autotrade"))
map[m].flag.autotrade=state;
else if (!strcmpi(w3,"allowks"))
map[m].flag.allowks=state; // [Kill Steal Protection]
else if (!strcmpi(w3,"town"))
map[m].flag.town=state;
else if (!strcmpi(w3,"nomemo"))
map[m].flag.nomemo=state;
else if (!strcmpi(w3,"noteleport"))
map[m].flag.noteleport=state;
else if (!strcmpi(w3,"nowarp"))
map[m].flag.nowarp=state;
else if (!strcmpi(w3,"nowarpto"))
map[m].flag.nowarpto=state;
else if (!strcmpi(w3,"noreturn"))
map[m].flag.noreturn=state;
else if (!strcmpi(w3,"monster_noteleport"))
map[m].flag.monster_noteleport=state;
else if (!strcmpi(w3,"nobranch"))
map[m].flag.nobranch=state;
else if (!strcmpi(w3,"nopenalty")) {
map[m].flag.noexppenalty=state;
map[m].flag.nozenypenalty=state;
}
else if (!strcmpi(w3,"pvp")) {
map[m].flag.pvp = state;
if( state && (map[m].flag.gvg || map[m].flag.gvg_dungeon || map[m].flag.gvg_castle) ) {
map[m].flag.gvg = 0;
map[m].flag.gvg_dungeon = 0;
map[m].flag.gvg_castle = 0;
ShowWarning("npc_parse_mapflag: You can't set PvP and GvG flags for the same map! Removing GvG flags from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
}
if( state && map[m].flag.battleground ) {
map[m].flag.battleground = 0;
ShowWarning("npc_parse_mapflag: You can't set PvP and BattleGround flags for the same map! Removing BattleGround flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
}
}
else if (!strcmpi(w3,"pvp_noparty"))
map[m].flag.pvp_noparty=state;
else if (!strcmpi(w3,"pvp_noguild"))
map[m].flag.pvp_noguild=state;
else if (!strcmpi(w3, "pvp_nightmaredrop")) {
char drop_arg1[16], drop_arg2[16];
int drop_per = 0;
if (sscanf(w4, "%15[^,],%15[^,],%d", drop_arg1, drop_arg2, &drop_per) == 3) {
int drop_id = 0, drop_type = 0;
if (!strcmpi(drop_arg1, "random"))
drop_id = -1;
else if (itemdb_exists((drop_id = atoi(drop_arg1))) == NULL)
drop_id = 0;
if (!strcmpi(drop_arg2, "inventory"))
drop_type = 1;
else if (!strcmpi(drop_arg2,"equip"))
drop_type = 2;
else if (!strcmpi(drop_arg2,"all"))
drop_type = 3;
if (drop_id != 0){
int i;
for (i = 0; i < MAX_DROP_PER_MAP; i++) {
if (map[m].drop_list[i].drop_id == 0){
map[m].drop_list[i].drop_id = drop_id;
map[m].drop_list[i].drop_type = drop_type;
map[m].drop_list[i].drop_per = drop_per;
break;
}
}
map[m].flag.pvp_nightmaredrop = 1;
}
} else if (!state) //Disable
map[m].flag.pvp_nightmaredrop = 0;
}
else if (!strcmpi(w3,"pvp_nocalcrank"))
map[m].flag.pvp_nocalcrank=state;
else if (!strcmpi(w3,"gvg")) {
map[m].flag.gvg = state;
if( state && map[m].flag.pvp ) {
map[m].flag.pvp = 0;
ShowWarning("npc_parse_mapflag: You can't set PvP and GvG flags for the same map! Removing PvP flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
}
if( state && map[m].flag.battleground ) {
map[m].flag.battleground = 0;
ShowWarning("npc_parse_mapflag: You can't set GvG and BattleGround flags for the same map! Removing BattleGround flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
}
}
else if (!strcmpi(w3,"gvg_noparty"))
map[m].flag.gvg_noparty=state;
else if (!strcmpi(w3,"gvg_dungeon")) {
map[m].flag.gvg_dungeon=state;
if (state) map[m].flag.pvp=0;
}
else if (!strcmpi(w3,"gvg_castle")) {
map[m].flag.gvg_castle=state;
if (state) map[m].flag.pvp=0;
}
else if (!strcmpi(w3,"battleground")) {
if( state ) {
if( sscanf(w4, "%d", &state) == 1 )
map[m].flag.battleground = state;
else
map[m].flag.battleground = 1; // Default value
} else
map[m].flag.battleground = 0;
if( map[m].flag.battleground && map[m].flag.pvp ) {
map[m].flag.pvp = 0;
ShowWarning("npc_parse_mapflag: You can't set PvP and BattleGround flags for the same map! Removing PvP flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
}
if( map[m].flag.battleground && (map[m].flag.gvg || map[m].flag.gvg_dungeon || map[m].flag.gvg_castle) ) {
map[m].flag.gvg = 0;
map[m].flag.gvg_dungeon = 0;
map[m].flag.gvg_castle = 0;
ShowWarning("npc_parse_mapflag: You can't set GvG and BattleGround flags for the same map! Removing GvG flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
}
}
else if (!strcmpi(w3,"noexppenalty"))
map[m].flag.noexppenalty=state;
else if (!strcmpi(w3,"nozenypenalty"))
map[m].flag.nozenypenalty=state;
else if (!strcmpi(w3,"notrade"))
map[m].flag.notrade=state;
else if (!strcmpi(w3,"novending"))
map[m].flag.novending=state;
else if (!strcmpi(w3,"nodrop"))
map[m].flag.nodrop=state;
else if (!strcmpi(w3,"noskill"))
map[m].flag.noskill=state;
else if (!strcmpi(w3,"noicewall"))
map[m].flag.noicewall=state;
else if (!strcmpi(w3,"snow"))
map[m].flag.snow=state;
else if (!strcmpi(w3,"clouds"))
map[m].flag.clouds=state;
else if (!strcmpi(w3,"clouds2"))
map[m].flag.clouds2=state;
else if (!strcmpi(w3,"fog"))
map[m].flag.fog=state;
else if (!strcmpi(w3,"fireworks"))
map[m].flag.fireworks=state;
else if (!strcmpi(w3,"sakura"))
map[m].flag.sakura=state;
else if (!strcmpi(w3,"leaves"))
map[m].flag.leaves=state;
else if (!strcmpi(w3,"nightenabled"))
map[m].flag.nightenabled=state;
else if (!strcmpi(w3,"nogo"))
map[m].flag.nogo=state;
else if (!strcmpi(w3,"noexp")) {
map[m].flag.nobaseexp=state;
map[m].flag.nojobexp=state;
}
else if (!strcmpi(w3,"nobaseexp"))
map[m].flag.nobaseexp=state;
else if (!strcmpi(w3,"nojobexp"))
map[m].flag.nojobexp=state;
else if (!strcmpi(w3,"noloot")) {
map[m].flag.nomobloot=state;
map[m].flag.nomvploot=state;
}
else if (!strcmpi(w3,"nomobloot"))
map[m].flag.nomobloot=state;
else if (!strcmpi(w3,"nomvploot"))
map[m].flag.nomvploot=state;
else if (!strcmpi(w3,"nocommand")) {
if (state) {
if (sscanf(w4, "%d", &state) == 1)
map[m].nocommand =state;
else //No level specified, block everyone.
map[m].nocommand =100;
} else
map[m].nocommand=0;
}
else if (!strcmpi(w3,"restricted")) {
if (state) {
map[m].flag.restricted=1;
sscanf(w4, "%d", &state);
map[m].zone |= 1<<(state+1);
} else {
map[m].flag.restricted=0;
map[m].zone = 0;
}
}
else if (!strcmpi(w3,"jexp")) {
map[m].adjust.jexp = (state) ? atoi(w4) : 100;
if( map[m].adjust.jexp < 0 ) map[m].adjust.jexp = 100;
map[m].flag.nojobexp = (map[m].adjust.jexp==0)?1:0;
}
else if (!strcmpi(w3,"bexp")) {
map[m].adjust.bexp = (state) ? atoi(w4) : 100;
if( map[m].adjust.bexp < 0 ) map[m].adjust.bexp = 100;
map[m].flag.nobaseexp = (map[m].adjust.bexp==0)?1:0;
}
else if (!strcmpi(w3,"loadevent"))
map[m].flag.loadevent=state;
else if (!strcmpi(w3,"nochat"))
map[m].flag.nochat=state;
else if (!strcmpi(w3,"partylock"))
map[m].flag.partylock=state;
else if (!strcmpi(w3,"guildlock"))
map[m].flag.guildlock=state;
else if (!strcmpi(w3,"reset"))
map[m].flag.reset=state;
else if (!strcmpi(w3,"nomapchannelautojoin"))
map[m].flag.chmautojoin = state;
else if (!strcmpi(w3,"nousecart"))
map[m].flag.nousecart = state;
else if (!strcmpi(w3,"noitemconsumption"))
map[m].flag.noitemconsumption = state;
else if (!strcmpi(w3,"summonstarmiracle"))
map[m].flag.nosumstarmiracle = state;
else if (!strcmpi(w3,"nomineeffect"))
map[m].flag.nomineeffect = state;
else if (!strcmpi(w3,"nolockon"))
map[m].flag.nolockon = state;
else if (!strcmpi(w3,"notomb"))
map[m].flag.notomb = state;
else if (!strcmpi(w3,"skill_damage")) {
#ifdef ADJUST_SKILL_DAMAGE
char skill[SKILL_NAME_LENGTH];
int pc = 0, mob = 0, boss = 0, other = 0, caster = 0;
memset(skill, 0, sizeof(skill));
map[m].flag.skill_damage = state; // Set the mapflag
if (!state) {
memset(&map[m].adjust.damage, 0, sizeof(map[m].adjust.damage));
if (map[m].skill_damage.count)
map_skill_damage_free(&map[m]);
}
else {
if (sscanf(w4, "%30[^,],%d,%d,%d,%d,%d[^\n]", skill, &caster, &pc, &mob, &boss, &other) >= 3) {
caster = (!caster) ? SDC_ALL : caster;
pc = cap_value(pc, -100, INT_MAX);
mob = cap_value(mob, -100, INT_MAX);
boss = cap_value(boss, -100, INT_MAX);
other = cap_value(other, -100, INT_MAX);
if (strcmp(skill,"all") == 0) { // Adjust damages for all skills
map[m].adjust.damage.caster = caster;
map[m].adjust.damage.pc = pc;
map[m].adjust.damage.mob = mob;
map[m].adjust.damage.boss = boss;
map[m].adjust.damage.other = other;
}
else if (skill_name2id(skill) <= 0)
ShowWarning("npc_parse_mapflag: skill_damage: Invalid skill name '%s'. Skipping (file '%s', line '%d')\n", skill, filepath, strline(buffer,start-buffer));
else //Damages for specified skill
map_skill_damage_add(&map[m], skill_name2id(skill), pc, mob, boss, other, caster);
}
}
#else
ShowInfo("npc_parse_mapflag: skill_damage: ADJUST_SKILL_DAMAGE is inactive (core.h). Skipping this mapflag..\n");
#endif
}
else
ShowError("npc_parse_mapflag: unrecognized mapflag '%s' (file '%s', line '%d').\n", w3, filepath, strline(buffer,start-buffer));
return strchr(start,'\n');// continue
}
/**
* Read file and create npc/func/mapflag/monster... accordingly.
* @param filepath : Relative path of file from map-serv bin
* @param runOnInit : should we exec OnInit when it's done ?
* @return 0:error, 1:success
*/
int npc_parsesrcfile(const char* filepath, bool runOnInit)
{
int16 m, x, y;
int lines = 0;
FILE* fp;
size_t len;
char* buffer;
const char* p;
if(check_filepath(filepath)!=2) { //this is not a file
ShowDebug("npc_parsesrcfile: Path doesn't seem to be a file skipping it : '%s'.\n", filepath);
return 0;
}
// read whole file to buffer
fp = fopen(filepath, "rb");
if( fp == NULL )
{
ShowError("npc_parsesrcfile: File not found '%s'.\n", filepath);
return 0;
}
fseek(fp, 0, SEEK_END);
len = ftell(fp);
buffer = (char*)aMalloc(len+1);
fseek(fp, 0, SEEK_SET);
len = fread(buffer, 1, len, fp);
buffer[len] = '\0';
if( ferror(fp) )
{
ShowError("npc_parsesrcfile: Failed to read file '%s' - %s\n", filepath, strerror(errno));
aFree(buffer);
fclose(fp);
return 0;
}
fclose(fp);
if ((unsigned char)buffer[0] == 0xEF && (unsigned char)buffer[1] == 0xBB && (unsigned char)buffer[2] == 0xBF) {
// UTF-8 BOM. This is most likely an error on the user's part, because:
// - BOM is discouraged in UTF-8, and the only place where you see it is Notepad and such.
// - It's unlikely that the user wants to use UTF-8 data here, since we don't really support it, nor does the client by default.
// - If the user really wants to use UTF-8 (instead of latin1, EUC-KR, SJIS, etc), then they can still do it <without BOM>.
// More info at http://unicode.org/faq/utf_bom.html#bom5 and http://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
ShowError("npc_parsesrcfile: Detected unsupported UTF-8 BOM in file '%s'. Stopping (please consider using another character set).\n", filepath);
aFree(buffer);
return 0;
}
// parse buffer
for( p = skip_space(buffer); p && *p ; p = skip_space(p) )
{
int pos[9];
char w1[2048], w2[2048], w3[2048], w4[2048];
int i, count;
lines++;
// w1<TAB>w2<TAB>w3<TAB>w4
count = sv_parse(p, len+buffer-p, 0, '\t', pos, ARRAYLENGTH(pos), (e_svopt)(SV_TERMINATE_LF|SV_TERMINATE_CRLF));
if( count < 0 )
{
ShowError("npc_parsesrcfile: Parse error in file '%s', line '%d'. Stopping...\n", filepath, strline(buffer,p-buffer));
break;
}
// fill w1
if( pos[3]-pos[2] > ARRAYLENGTH(w1)-1 )
ShowWarning("npc_parsesrcfile: w1 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[3]-pos[2], filepath, strline(buffer,p-buffer));
i = min(pos[3]-pos[2], ARRAYLENGTH(w1)-1);
memcpy(w1, p+pos[2], i*sizeof(char));
w1[i] = '\0';
// fill w2
if( pos[5]-pos[4] > ARRAYLENGTH(w2)-1 )
ShowWarning("npc_parsesrcfile: w2 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[5]-pos[4], filepath, strline(buffer,p-buffer));
i = min(pos[5]-pos[4], ARRAYLENGTH(w2)-1);
memcpy(w2, p+pos[4], i*sizeof(char));
w2[i] = '\0';
// fill w3
if( pos[7]-pos[6] > ARRAYLENGTH(w3)-1 )
ShowWarning("npc_parsesrcfile: w3 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[7]-pos[6], filepath, strline(buffer,p-buffer));
i = min(pos[7]-pos[6], ARRAYLENGTH(w3)-1);
memcpy(w3, p+pos[6], i*sizeof(char));
w3[i] = '\0';
// fill w4 (to end of line)
if( pos[1]-pos[8] > ARRAYLENGTH(w4)-1 )
ShowWarning("npc_parsesrcfile: w4 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[1]-pos[8], filepath, strline(buffer,p-buffer));
if( pos[8] != -1 )
{
i = min(pos[1]-pos[8], ARRAYLENGTH(w4)-1);
memcpy(w4, p+pos[8], i*sizeof(char));
w4[i] = '\0';
}
else
w4[0] = '\0';
if( count < 3 )
{// Unknown syntax
ShowError("npc_parsesrcfile: Unknown syntax in file '%s', line '%d'. Stopping...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
break;
}
if( strcmp(w1,"-") !=0 && strcasecmp(w1,"function") != 0 )
{// w1 = <map name>,<x>,<y>,<facing>
char mapname[MAP_NAME_LENGTH*2];
x = y = 0;
sscanf(w1,"%23[^,],%hd,%hd[^,]",mapname,&x,&y);
if( !mapindex_name2id(mapname) )
{// Incorrect map, we must skip the script info...
ShowError("npc_parsesrcfile: Unknown map '%s' in file '%s', line '%d'. Skipping line...\n", mapname, filepath, strline(buffer,p-buffer));
if( strcasecmp(w2,"script") == 0 && count > 3 )
{
if((p = npc_skip_script(p,buffer,filepath)) == NULL)
{
break;
}
}
p = strchr(p,'\n');// next line
continue;
}
m = map_mapname2mapid(mapname);
if( m < 0 )
{// "mapname" is not assigned to this server, we must skip the script info...
if( strcasecmp(w2,"script") == 0 && count > 3 )
{
if((p = npc_skip_script(p,buffer,filepath)) == NULL)
{
break;
}
}
p = strchr(p,'\n');// next line
continue;
}
if (x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys) {
ShowError("npc_parsesrcfile: Unknown coordinates ('%d', '%d') for map '%s' in file '%s', line '%d'. Skipping line...\n", x, y, mapname, filepath, strline(buffer,p-buffer));
if( strcasecmp(w2,"script") == 0 && count > 3 )
{
if((p = npc_skip_script(p,buffer,filepath)) == NULL)
{
break;
}
}
p = strchr(p,'\n');// next line
continue;
}
}
if( strcasecmp(w2,"warp") == 0 && count > 3 )
p = npc_parse_warp(w1,w2,w3,w4, p, buffer, filepath);
else if( (!strcasecmp(w2,"shop") || !strcasecmp(w2,"cashshop") || !strcasecmp(w2,"itemshop") || !strcasecmp(w2,"pointshop") || !strcasecmp(w2,"marketshop") ) && count > 3 )
p = npc_parse_shop(w1,w2,w3,w4, p, buffer, filepath);
else if( strcasecmp(w2,"script") == 0 && count > 3 ) {
if( strcasecmp(w1,"function") == 0 )
p = npc_parse_function(w1, w2, w3, w4, p, buffer, filepath);
else
p = npc_parse_script(w1,w2,w3,w4, p, buffer, filepath,runOnInit);
}
else if( (i=0, sscanf(w2,"duplicate%n",&i), (i > 0 && w2[i] == '(')) && count > 3 )
p = npc_parse_duplicate(w1,w2,w3,w4, p, buffer, filepath);
else if( (strcmpi(w2,"monster") == 0 || strcmpi(w2,"boss_monster") == 0) && count > 3 )
p = npc_parse_mob(w1, w2, w3, w4, p, buffer, filepath);
else if( strcmpi(w2,"mapflag") == 0 && count >= 3 )
p = npc_parse_mapflag(w1, w2, trim(w3), trim(w4), p, buffer, filepath);
else {
ShowError("npc_parsesrcfile: Unable to parse, probably a missing or extra TAB in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
p = strchr(p,'\n');// skip and continue
}
}
aFree(buffer);
return 1;
}
int npc_script_event(struct map_session_data* sd, enum npce_event type)
{
int i;
if (type == NPCE_MAX)
return 0;
if (!sd) {
ShowError("npc_script_event: NULL sd. Event Type %d\n", type);
return 0;
}
for (i = 0; i<script_event[type].event_count; i++)
npc_event_sub(sd,script_event[type].event[i],script_event[type].event_name[i]);
return i;
}
void npc_read_event_script(void)
{
int i;
struct {
char *name;
const char *event_name;
} config[] = {
{"Login Event",script_config.login_event_name},
{"Logout Event",script_config.logout_event_name},
{"Load Map Event",script_config.loadmap_event_name},
{"Base LV Up Event",script_config.baselvup_event_name},
{"Job LV Up Event",script_config.joblvup_event_name},
{"Die Event",script_config.die_event_name},
{"Kill PC Event",script_config.kill_pc_event_name},
{"Kill NPC Event",script_config.kill_mob_event_name},
{"Stat Calc Event",script_config.stat_calc_event_name},
};
for (i = 0; i < NPCE_MAX; i++)
{
DBIterator* iter;
DBKey key;
DBData *data;
char name[64]="::";
safestrncpy(name+2,config[i].event_name,62);
script_event[i].event_count = 0;
iter = db_iterator(ev_db);
for( data = iter->first(iter,&key); iter->exists(iter); data = iter->next(iter,&key) )
{
const char* p = key.str;
struct event_data* ed = db_data2ptr(data);
unsigned char count = script_event[i].event_count;
if( count >= ARRAYLENGTH(script_event[i].event) )
{
ShowWarning("npc_read_event_script: too many occurences of event '%s'!\n", config[i].event_name);
break;
}
if( (p=strchr(p,':')) && p && strcmpi(name,p)==0 )
{
script_event[i].event[count] = ed;
script_event[i].event_name[count] = key.str;
script_event[i].event_count++;
}
}
dbi_destroy(iter);
}
if (battle_config.etc_log) {
//Print summary.
for (i = 0; i < NPCE_MAX; i++)
ShowInfo("%s: %d '%s' events.\n", config[i].name, script_event[i].event_count, config[i].event_name);
}
}
void npc_clear_pathlist(void) {
struct npc_path_data *npd = NULL;
DBIterator *path_list = db_iterator(npc_path_db);
/* free all npc_path_data filepaths */
for( npd = dbi_first(path_list); dbi_exists(path_list); npd = dbi_next(path_list) ) {
if( npd->path )
aFree(npd->path);
}
dbi_destroy(path_list);
}
//Clear then reload npcs files
int npc_reload(void) {
struct npc_src_list *nsl;
int16 m, i;
int npc_new_min = npc_id;
struct s_mapiterator* iter;
struct block_list* bl;
/* clear guild flag cache */
guild_flags_clear();
npc_clear_pathlist();
db_clear(npc_path_db);
db_clear(npcname_db);
db_clear(ev_db);
//Remove all npcs/mobs. [Skotlex]
#if PACKETVER >= 20131223
npc_market_fromsql();
#endif
iter = mapit_geteachiddb();
for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) ) {
switch(bl->type) {
case BL_NPC:
if( bl->id != fake_nd->bl.id )// don't remove fake_nd
npc_unload((struct npc_data *)bl, false);
break;
case BL_MOB:
unit_free(bl,CLR_OUTSIGHT);
break;
}
}
mapit_free(iter);
if(battle_config.dynamic_mobs)
{// dynamic check by [random]
for (m = 0; m < map_num; m++) {
for (i = 0; i < MAX_MOB_LIST_PER_MAP; i++) {
if (map[m].moblist[i] != NULL) {
aFree(map[m].moblist[i]);
map[m].moblist[i] = NULL;
}
if( map[m].mob_delete_timer != INVALID_TIMER )
{ // Mobs were removed anyway,so delete the timer [Inkfish]
delete_timer(map[m].mob_delete_timer, map_removemobs_timer);
map[m].mob_delete_timer = INVALID_TIMER;
}
}
}
if (map[m].npc_num > 0)
ShowWarning("npc_reload: %d npcs weren't removed at map %s!\n", map[m].npc_num, map[m].name);
}
// clear mob spawn lookup index
mob_clear_spawninfo();
npc_warp = npc_shop = npc_script = 0;
npc_mob = npc_cache_mob = npc_delay_mob = 0;
// reset mapflags
map_flags_init();
//TODO: the following code is copy-pasted from do_init_npc(); clean it up
// Reloading npcs now
for (nsl = npc_src_files; nsl; nsl = nsl->next) {
ShowStatus("Loading NPC file: %s"CL_CLL"\r", nsl->name);
npc_parsesrcfile(nsl->name,false);
}
ShowInfo ("Done loading '"CL_WHITE"%d"CL_RESET"' NPCs:"CL_CLL"\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Warps\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Shops\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Scripts\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Spawn sets\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Mobs Cached\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Mobs Not Cached\n",
npc_id - npc_new_min, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
//Re-read the NPC Script Events cache.
npc_read_event_script();
/* refresh guild castle flags on both woe setups */
npc_event_doall("OnAgitInit");
npc_event_doall("OnAgitInit2");
//Execute the OnInit event for freshly loaded npcs. [Skotlex]
ShowStatus("Event '"CL_WHITE"OnInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n",npc_event_doall("OnInit"));
do_reload_instance();
// Execute rest of the startup events if connected to char-server. [Lance]
if(!CheckForCharServer()){
ShowStatus("Event '"CL_WHITE"OnInterIfInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n", npc_event_doall("OnInterIfInit"));
}
#if PACKETVER >= 20131223
npc_market_checkall();
#endif
return 0;
}
//Unload all npc in the given file
bool npc_unloadfile( const char* path ) {
DBIterator * iter = db_iterator(npcname_db);
struct npc_data* nd = NULL;
bool found = false;
for( nd = dbi_first(iter); dbi_exists(iter); nd = dbi_next(iter) ) {
if( nd->path && strcasecmp(nd->path,path) == 0 ) {
found = true;
npc_unload_duplicates(nd);/* unload any npcs which could duplicate this but be in a different file */
npc_unload(nd, true);
}
}
dbi_destroy(iter);
if( found ) /* refresh event cache */
npc_read_event_script();
npc_delsrcfile(path);
return found;
}
void do_clear_npc(void) {
db_clear(npcname_db);
db_clear(ev_db);
}
/*==========================================
* Destructor
*------------------------------------------*/
void do_final_npc(void) {
npc_clear_pathlist();
ev_db->destroy(ev_db, NULL);
npcname_db->destroy(npcname_db, NULL);
npc_path_db->destroy(npc_path_db, NULL);
#if PACKETVER >= 20131223
NPCMarketDB->destroy(NPCMarketDB, npc_market_free);
#endif
ers_destroy(timer_event_ers);
npc_clearsrcfile();
}
static void npc_debug_warps_sub(struct npc_data* nd)
{
int16 m;
if (nd->bl.type != BL_NPC || nd->subtype != NPCTYPE_WARP || nd->bl.m < 0)
return;
m = map_mapindex2mapid(nd->u.warp.mapindex);
if (m < 0) return; //Warps to another map, nothing to do about it.
if (nd->u.warp.x == 0 && nd->u.warp.y == 0) return; // random warp
if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNPC)) {
ShowWarning("Warp %s at %s(%d,%d) warps directly on top of an area npc at %s(%d,%d)\n",
nd->name,
map[nd->bl.m].name, nd->bl.x, nd->bl.y,
map[m].name, nd->u.warp.x, nd->u.warp.y
);
}
if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNOPASS)) {
ShowWarning("Warp %s at %s(%d,%d) warps to a non-walkable tile at %s(%d,%d)\n",
nd->name,
map[nd->bl.m].name, nd->bl.x, nd->bl.y,
map[m].name, nd->u.warp.x, nd->u.warp.y
);
}
}
static void npc_debug_warps(void)
{
int16 m, i;
for (m = 0; m < map_num; m++)
for (i = 0; i < map[m].npc_num; i++)
npc_debug_warps_sub(map[m].npc[i]);
}
/*==========================================
* npc initialization
*------------------------------------------*/
void do_init_npc(void){
struct npc_src_list *file;
int i;
//Stock view data for normal npcs.
memset(&npc_viewdb, 0, sizeof(npc_viewdb));
npc_viewdb[0].class_ = INVISIBLE_CLASS; //Invisible class is stored here.
for( i = 1; i < MAX_NPC_CLASS; i++ )
npc_viewdb[i].class_ = i;
for( i = MAX_NPC_CLASS2_START; i < MAX_NPC_CLASS2_END; i++ )
npc_viewdb2[i - MAX_NPC_CLASS2_START].class_ = i;
ev_db = strdb_alloc((DBOptions)(DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA),2*NAME_LENGTH+2+1);
npcname_db = strdb_alloc(DB_OPT_BASE,NAME_LENGTH);
npc_path_db = strdb_alloc(DB_OPT_BASE|DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA,80);
#if PACKETVER >= 20131223
NPCMarketDB = strdb_alloc(DB_OPT_BASE, NAME_LENGTH+1);
npc_market_fromsql();
#endif
timer_event_ers = ers_new(sizeof(struct timer_event_data),"clif.c::timer_event_ers",ERS_OPT_NONE);
// process all npc files
ShowStatus("Loading NPCs...\r");
for( file = npc_src_files; file != NULL; file = file->next ) {
ShowStatus("Loading NPC file: %s"CL_CLL"\r", file->name);
npc_parsesrcfile(file->name,false);
}
ShowInfo ("Done loading '"CL_WHITE"%d"CL_RESET"' NPCs:"CL_CLL"\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Warps\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Shops\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Scripts\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Spawn sets\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Mobs Cached\n"
"\t-'"CL_WHITE"%d"CL_RESET"' Mobs Not Cached\n",
npc_id - START_NPC_NUM, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
// set up the events cache
memset(script_event, 0, sizeof(script_event));
npc_read_event_script();
#if PACKETVER >= 20131223
npc_market_checkall();
#endif
//Debug function to locate all endless loop warps.
if (battle_config.warp_point_debug)
npc_debug_warps();
add_timer_func_list(npc_event_do_clock,"npc_event_do_clock");
add_timer_func_list(npc_timerevent,"npc_timerevent");
// Init dummy NPC
fake_nd = (struct npc_data *)aCalloc(1,sizeof(struct npc_data));
fake_nd->bl.m = -1;
fake_nd->bl.id = npc_get_new_npc_id();
fake_nd->class_ = -1;
fake_nd->speed = 200;
strcpy(fake_nd->name,"FAKE_NPC");
memcpy(fake_nd->exname, fake_nd->name, 9);
npc_script++;
fake_nd->bl.type = BL_NPC;
fake_nd->subtype = NPCTYPE_SCRIPT;
strdb_put(npcname_db, fake_nd->exname, fake_nd);
fake_nd->u.scr.timerid = INVALID_TIMER;
map_addiddb(&fake_nd->bl);
// End of initialization
}
| saprobes/rathena | src/map/npc.c | C | gpl-3.0 | 138,888 |
//
// NuINT09 Conference, Benchmark Calculations (GENIE contribution)
//
// 1PI.2:
// 1pi+ cross section at E_nu= 1.0 and 1.5 GeV as a function of pi kinetic energy.
//
// Inputs:
// - sample id: 0 (nu_mu+C12), 1 (nu_mu+O16), 2 (nu_mu+Fe56)
// - single pion source: 0 (all), 1 (P33(1232) resonance only), 2 (resonances only)
// - stage: 0 -> primary Xpi+, 1 -> final state Xpi+
//
// Costas Andreopoulos, STFC / Rutherford Appleton Laboratory
//
#include <iomanip>
//
// consts
//
const int kNSamples = 3;
const int kNWCur = 1;
const int kNEnergies = 2;
const int kNRunsPerCase = 5;
const int kNEvtPerRun = 100000;
const char * kLabel[kNSamples] =
{
// available samples
/* 0 */ "nu_mu_C12",
/* 1 */ "nu_mu_O16",
/* 2 */ "nu_mu_Fe56"
};
const int kRunNu1PI2[kNSamples][kNWCur][kNEnergies][kNRunsPerCase] =
{
/* indices : sample ; cc/nc ; energy */
{
/* 0,0,0 (nu_mu C12, CC, 1.0 GeV) */ { {900200, 900201, 900202, 900203, 900204},
/* 0,0,1 (nu_mu C12, CC, 1.5 GeV) */ {900300, 900301, 900302, 900303, 900304} }
},
{
/* 1,0,0 (nu_mu O16, CC, 1.0 GeV) */ { {910200, 910201, 910202, 910203, 910204},
/* 1,0,1 (nu_mu O16, CC, 1.5 GeV) */ {910300, 910301, 910302, 910303, 910304} }
},
{
/* 2,0,0 (nu_mu Fe56, CC, 1.0 GeV) */ { {920200, 920201, 920202, 920203, 920204},
/* 2,0,1 (nu_mu Fe56, CC, 1.5 GeV) */ {920300, 920301, 920302, 920303, 920304} }
}
};
void nuint09_1pi2(int isample, int single_pion_sources=0, int stage=1)
{
cout << " ***** running: 1PI.2" << endl;
if(isample<0 || isample >= kNSamples) return;
if(single_pion_sources<0 || single_pion_sources>2) return;
const char * label = kLabel[isample];
// get cross section graph
TFile fsig("./cc1pip_tmp.root","read"); // generated at [1PI.1]
TGraph * sig_graph_cc1pip = (TGraph*) fsig.Get("CC1pip");
// range & spacing
const int nKEpip = 60;
const double KEpipmin = 0.00;
const double KEpipmax = 1.50;
// create output stream
ostringstream out_filename;
out_filename << label;
if (single_pion_sources==0) out_filename << ".1pi_2a.";
else if (single_pion_sources==1) out_filename << ".1pi_2b.";
else if (single_pion_sources==2) out_filename << ".1pi_2c.";
if(stage==0) out_filename << "no_FSI.";
out_filename << label << "dsig1pi_dKEpi.data";
ofstream out_stream(out_filename.str().c_str(), ios::out);
// write out txt file
out_stream << "# [" << label << "]" << endl;
out_stream << "# " << endl;
out_stream << "# [1PI.2]:" << endl;
out_stream << "# 1pi+ cross section at E_nu= 1.0 and 1.5 GeV as a function of the pi+ kinetic energy" << endl;
if(stage==0) {
out_stream << "# ***** NO FSI: The {X pi+} state is a primary hadronic state" << endl;
}
if(single_pion_sources==0) {
out_stream << "# 1pi sources: All" << endl;
}
else if(single_pion_sources==1) {
out_stream << "# 1pi sources: P33(1232) resonance only" << endl;
}
else if(single_pion_sources==2) {
out_stream << "# 1pi sources: All resonances only" << endl;
}
out_stream << "# " << endl;
out_stream << "# Note:" << endl;
out_stream << "# - pi+ kinetic energy KE in GeV, linear spacing between KEmin = " << KEpipmin << " GeV, KEmax = " << KEpipmax << " GeV " << endl;
out_stream << "# - cross sections in 1E-38 cm^2 / GeV" << endl;
out_stream << "# - quoted cross section is nuclear cross section divided with number of nucleons A" << endl;
out_stream << "# Columns:" << endl;
out_stream << "# | KE(pi+) | dsig(numu A -> mu- 1pi+ X; Enu = 1.0 GeV) | dsig(numu A -> mu- 1pi+ X; Enu = 1.5 GeV) | " << endl;
out_stream << setiosflags(ios::fixed) << setprecision(6);
//
// load event data
//
TChain * chain = new TChain("gst");
// loop over CC/NC cases
for(int iwkcur=0; iwkcur<kNWCur; iwkcur++) {
// loop over energies
for(int ie=0; ie<kNEnergies; ie++) {
// loop over runs for current case
for(int ir=0; ir<kNRunsPerCase; ir++) {
// build filename
ostringstream filename;
int run_number = kRunNu1PI2[isample][iwkcur][ie][ir];
filename << "../gst/gntp." << run_number << ".gst.root";
// add to chain
cout << "Adding " << filename.str() << " to event chain" << endl;
chain->Add(filename.str().c_str());
}
}
}
//
// get CC1pi+ cross sections at given energies for normalization purposes
//
double sig_cc1pip_1000MeV = sig_graph_cc1pip -> Eval (1.0);
double sig_cc1pip_1500MeV = sig_graph_cc1pip -> Eval (1.5);
//
// book histograms
//
TH1D * hst_dsig_dKEpip_1000MeV = new TH1D("hst_dsig_dKEpip_1000MeV","dsig/dKEpi+, numu A -> mu- 1pi+ X, Enu=1.0 GeV", nKEpip, KEpipmin, KEpipmax);
TH1D * hst_dsig_dKEpip_1500MeV = new TH1D("hst_dsig_dKEpip_1500MeV","dsig/dKEpi+, numu A -> mu- 1pi+ X, Enu=1.5 GeV", nKEpip, KEpipmin, KEpipmax);
//
// fill histograms
//
if(stage==1) {
if(single_pion_sources==0) {
// all sources
chain->Draw("(Ef-0.139)>>hst_dsig_dKEpip_1000MeV","cc&&Ev>0.99&&Ev<1.01&&pdgf==211&&nfpip==1&&nfpim==0&&nfpi0==0","GOFF");
chain->Draw("(Ef-0.139)>>hst_dsig_dKEpip_1500MeV","cc&&Ev>1.49&&Ev<1.51&&pdgf==211&&nfpip==1&&nfpim==0&&nfpi0==0","GOFF");
}
else if(single_pion_sources==1) {
// P33(1232) only
chain->Draw("(Ef-0.139)>>hst_dsig_dKEpip_1000MeV","cc&&resid==0&&res&&Ev>0.99&&Ev<1.01&&pdgf==211&&nfpip==1&&nfpim==0&&nfpi0==0","GOFF");
chain->Draw("(Ef-0.139)>>hst_dsig_dKEpip_1500MeV","cc&&resid==0&&res&&Ev>1.49&&Ev<1.51&&pdgf==211&&nfpip==1&&nfpim==0&&nfpi0==0","GOFF");
}
else if(single_pion_sources==2) {
// all resonances only
chain->Draw("(Ef-0.139)>>hst_dsig_dKEpip_1000MeV","cc&&res&&Ev>0.99&&Ev<1.01&&pdgf==211&&nfpip==1&&nfpim==0&&nfpi0==0","GOFF");
chain->Draw("(Ef-0.139)>>hst_dsig_dKEpip_1500MeV","cc&&res&&Ev>1.49&&Ev<1.51&&pdgf==211&&nfpip==1&&nfpim==0&&nfpi0==0","GOFF");
}
}
else if(stage==0) {
if(single_pion_sources==0) {
// all sources
chain->Draw("(Ei-0.139)>>hst_dsig_dKEpip_1000MeV","cc&&Ev>0.99&&Ev<1.01&&pdgi==211&&nipip==1&&nipim==0&&nipi0==0","GOFF");
chain->Draw("(Ei-0.139)>>hst_dsig_dKEpip_1500MeV","cc&&Ev>1.49&&Ev<1.51&&pdgi==211&&nipip==1&&nipim==0&&nipi0==0","GOFF");
}
else if(single_pion_sources==1) {
// P33(1232) only
chain->Draw("(Ei-0.139)>>hst_dsig_dKEpip_1000MeV","cc&&resid==0&&res&&Ev>0.99&&Ev<1.01&&pdgi==211&&nipip==1&&nipim==0&&nipi0==0","GOFF");
chain->Draw("(Ei-0.139)>>hst_dsig_dKEpip_1500MeV","cc&&resid==0&&res&&Ev>1.49&&Ev<1.51&&pdgi==211&&nipip==1&&nipim==0&&nipi0==0","GOFF");
}
else if(single_pion_sources==2) {
// all resonances only
chain->Draw("(Ei-0.139)>>hst_dsig_dKEpip_1000MeV","cc&&res&&Ev>0.99&&Ev<1.01&&pdgi==211&&nipip==1&&nipim==0&&nipi0==0","GOFF");
chain->Draw("(Ei-0.139)>>hst_dsig_dKEpip_1500MeV","cc&&res&&Ev>1.49&&Ev<1.51&&pdgi==211&&nipip==1&&nipim==0&&nipi0==0","GOFF");
}
}
//
// normalize
//
double norm_cc1pip_1000MeV = hst_dsig_dKEpip_1000MeV -> Integral("width") / sig_cc1pip_1000MeV;
double norm_cc1pip_1500MeV = hst_dsig_dKEpip_1500MeV -> Integral("width") / sig_cc1pip_1500MeV;
if (norm_cc1pip_1000MeV > 0) hst_dsig_dKEpip_1000MeV -> Scale(1./norm_cc1pip_1000MeV);
if (norm_cc1pip_1500MeV > 0) hst_dsig_dKEpip_1500MeV -> Scale(1./norm_cc1pip_1500MeV);
for(int i=1; i <= hst_dsig_dKEpip_1000MeV->GetNbinsX(); i++) {
double KEpip = hst_dsig_dKEpip_1000MeV -> GetBinCenter(i);
double dsig_dKEpip_1000MeV = hst_dsig_dKEpip_1000MeV -> GetBinContent(i);
double dsig_dKEpip_1500MeV = hst_dsig_dKEpip_1500MeV -> GetBinContent(i);
dsig_dKEpip_1000MeV = TMath::Max(0., dsig_dKEpip_1000MeV);
dsig_dKEpip_1500MeV = TMath::Max(0., dsig_dKEpip_1500MeV);
out_stream << setw(15) << KEpip
<< setw(15) << dsig_dKEpip_1000MeV
<< setw(15) << dsig_dKEpip_1500MeV
<< endl;
}
out_stream.close();
// visual inspection
//TCanvas * c1 = new TCanvas("c1","",20,20,500,500);
//...
//c1->Update();
delete chain;
fsig.Close();
}
| rishimouland/GENIE_NCGamma | src/contrib/nuint09/nuint09_1pi2.C | C++ | gpl-3.0 | 8,228 |
/*
* This file is part of the libopencm3 project.
*
* Copyright (C) 2018 Karl Palsson <[email protected]>
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/lm4f/gpio.h>
#include <libopencm3/lm4f/rcc.h>
#include <libopencm3/lm4f/systemcontrol.h>
#include <stdio.h>
#include "delay.h"
#include "usb-gadget0.h"
#define ER_DEBUG
#ifdef ER_DEBUG
#define ER_DPRINTF(fmt, ...) \
do { printf(fmt, ## __VA_ARGS__); } while (0)
#else
#define ER_DPRINTF(fmt, ...) \
do { } while (0)
#endif
/* FIXME - implement delay functionality for better test coverage */
void delay_setup(void) {
}
void delay_us(uint16_t us) {
(void)us;
}
int main(void)
{
gpio_enable_ahb_aperture();
#define PLL_DIV_80MHZ 5
rcc_sysclk_config(OSCSRC_MOSC, XTAL_16M, PLL_DIV_80MHZ);
periph_clock_enable(RCC_GPIOD);
gpio_mode_setup(GPIOD, GPIO_MODE_ANALOG, GPIO_PUPD_NONE, GPIO4 | GPIO5);
/* blue LED on board */
periph_clock_enable(RCC_GPIOF);
gpio_mode_setup(GPIOF, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO2);
gpio_set_output_config(GPIOF, GPIO_OTYPE_PP, GPIO_DRIVE_2MA, GPIO2);
usbd_device *usbd_dev = gadget0_init(&lm4f_usb_driver, "tilm4f120xl");
ER_DPRINTF("bootup complete\n");
while (1) {
gpio_set(GPIOF, GPIO2);
gadget0_run(usbd_dev);
gpio_clear(GPIOF, GPIO2);
}
}
| devanlai/libopencm3 | tests/gadget-zero/main-tilm4f120xl.c | C | gpl-3.0 | 1,962 |
#!/bin/sh -e
#
# Copyright (C) 2008-2011 Intel
#
# install.sh [device_name] [rootfs_name] [video_mode] [vga_mode]
#
PATH=/sbin:/bin:/usr/sbin:/usr/bin
boot_device="__TARGET_DEVICE__"
list_devices() {
# copied from poky
# Get a list of hard drives
hdnamelist=""
live_dev_name=${1%%/*}
live_dev_name=${live_dev_name%%[0-9]*}
echo "Searching for hard drives ..."
for device in `ls /sys/block/`; do
case $device in
loop*)
# skip loop device
;;
sr*)
# skip CDROM device
;;
ram*)
# skip ram device
;;
*)
# skip the device LiveOS is on
# Add valid hard drive name to the list
if [ "$device" != "$live_dev_name" -a -e /dev/$device ]; then
hdnamelist="$hdnamelist $device"
fi
;;
esac
done
for hdname in $hdnamelist; do
# Display found hard drives and their basic info
echo "-------------------------------"
echo /dev/$hdname
if [ -r /sys/block/$hdname/device/vendor ]; then
echo -n "VENDOR="
cat /sys/block/$hdname/device/vendor
fi
if [ -r /sys/block/$hdname/device/model ]; then
echo -n "MODEL="
cat /sys/block/$hdname/device/model
fi
if [ -r /sys/block/$hdname/device/uevent ]; then
echo -n "UEVENT="
cat /sys/block/$hdname/device/uevent
fi
echo
done
}
### install scripts following ###
| umatomba/meta-caros | recipes-core/initrdscripts/files/init-install.sh | Shell | mpl-2.0 | 1,320 |
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by referrer-policy/generic/tools/generate.py using referrer-policy/generic/template/test.release.html.template. -->
<html>
<head>
<title>Referrer-Policy: Referrer Policy is set to 'no-referrer-when-downgrade'</title>
<meta name="description" content="Check that non a priori insecure subresource gets the full Referrer URL. A priori insecure subresource gets no referrer information.">
<meta http-equiv="Content-Security-Policy" content="referrer no-referrer-when-downgrade">
<link rel="author" title="Kristijan Burnik" href="[email protected]">
<link rel="help" href="https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-no-referrer-when-downgrade">
<meta name="assert" content="The referrer URL is stripped-referrer when a
document served over http requires an https
sub-resource via img-tag using the meta-csp
delivery method with swap-origin-redirect and when
the target request is cross-origin.">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<!-- TODO(kristijanburnik): Minify and merge both: -->
<script src="/referrer-policy/generic/common.js"></script>
<script src="/referrer-policy/generic/referrer-policy-test-case.js?pipe=sub"></script>
</head>
<body>
<script>
ReferrerPolicyTestCase(
{
"referrer_policy": "no-referrer-when-downgrade",
"delivery_method": "meta-csp",
"redirection": "swap-origin-redirect",
"origin": "cross-origin",
"source_protocol": "http",
"target_protocol": "https",
"subresource": "img-tag",
"subresource_path": "/referrer-policy/generic/subresource/image.py",
"referrer_url": "stripped-referrer"
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html>
| Nashenas88/servo | tests/wpt/web-platform-tests/referrer-policy/no-referrer-when-downgrade/meta-csp/cross-origin/http-https/img-tag/upgrade-protocol.swap-origin-redirect.http.html | HTML | mpl-2.0 | 2,114 |
package module
import (
"bufio"
"bytes"
"fmt"
"path/filepath"
"strings"
"sync"
"github.com/hashicorp/go-getter"
"github.com/hashicorp/terraform/config"
)
// RootName is the name of the root tree.
const RootName = "root"
// Tree represents the module import tree of configurations.
//
// This Tree structure can be used to get (download) new modules, load
// all the modules without getting, flatten the tree into something
// Terraform can use, etc.
type Tree struct {
name string
config *config.Config
children map[string]*Tree
path []string
lock sync.RWMutex
}
// NewTree returns a new Tree for the given config structure.
func NewTree(name string, c *config.Config) *Tree {
return &Tree{config: c, name: name}
}
// NewEmptyTree returns a new tree that is empty (contains no configuration).
func NewEmptyTree() *Tree {
t := &Tree{config: &config.Config{}}
// We do this dummy load so that the tree is marked as "loaded". It
// should never fail because this is just about a no-op. If it does fail
// we panic so we can know its a bug.
if err := t.Load(nil, GetModeGet); err != nil {
panic(err)
}
return t
}
// NewTreeModule is like NewTree except it parses the configuration in
// the directory and gives it a specific name. Use a blank name "" to specify
// the root module.
func NewTreeModule(name, dir string) (*Tree, error) {
c, err := config.LoadDir(dir)
if err != nil {
return nil, err
}
return NewTree(name, c), nil
}
// Config returns the configuration for this module.
func (t *Tree) Config() *config.Config {
return t.config
}
// Child returns the child with the given path (by name).
func (t *Tree) Child(path []string) *Tree {
if len(path) == 0 {
return t
}
c := t.Children()[path[0]]
if c == nil {
return nil
}
return c.Child(path[1:])
}
// Children returns the children of this tree (the modules that are
// imported by this root).
//
// This will only return a non-nil value after Load is called.
func (t *Tree) Children() map[string]*Tree {
t.lock.RLock()
defer t.lock.RUnlock()
return t.children
}
// Loaded says whether or not this tree has been loaded or not yet.
func (t *Tree) Loaded() bool {
t.lock.RLock()
defer t.lock.RUnlock()
return t.children != nil
}
// Modules returns the list of modules that this tree imports.
//
// This is only the imports of _this_ level of the tree. To retrieve the
// full nested imports, you'll have to traverse the tree.
func (t *Tree) Modules() []*Module {
result := make([]*Module, len(t.config.Modules))
for i, m := range t.config.Modules {
result[i] = &Module{
Name: m.Name,
Source: m.Source,
}
}
return result
}
// Name returns the name of the tree. This will be "<root>" for the root
// tree and then the module name given for any children.
func (t *Tree) Name() string {
if t.name == "" {
return RootName
}
return t.name
}
// Load loads the configuration of the entire tree.
//
// The parameters are used to tell the tree where to find modules and
// whether it can download/update modules along the way.
//
// Calling this multiple times will reload the tree.
//
// Various semantic-like checks are made along the way of loading since
// module trees inherently require the configuration to be in a reasonably
// sane state: no circular dependencies, proper module sources, etc. A full
// suite of validations can be done by running Validate (after loading).
func (t *Tree) Load(s getter.Storage, mode GetMode) error {
t.lock.Lock()
defer t.lock.Unlock()
// Reset the children if we have any
t.children = nil
modules := t.Modules()
children := make(map[string]*Tree)
// Go through all the modules and get the directory for them.
for _, m := range modules {
if _, ok := children[m.Name]; ok {
return fmt.Errorf(
"module %s: duplicated. module names must be unique", m.Name)
}
// Determine the path to this child
path := make([]string, len(t.path), len(t.path)+1)
copy(path, t.path)
path = append(path, m.Name)
// Split out the subdir if we have one
source, subDir := getter.SourceDirSubdir(m.Source)
source, err := getter.Detect(source, t.config.Dir, getter.Detectors)
if err != nil {
return fmt.Errorf("module %s: %s", m.Name, err)
}
// Check if the detector introduced something new.
source, subDir2 := getter.SourceDirSubdir(source)
if subDir2 != "" {
subDir = filepath.Join(subDir2, subDir)
}
// Get the directory where this module is so we can load it
key := strings.Join(path, ".")
key = fmt.Sprintf("root.%s-%s", key, source)
dir, ok, err := getStorage(s, key, source, mode)
if err != nil {
return err
}
if !ok {
return fmt.Errorf(
"module %s: not found, may need to be downloaded using 'terraform get'", m.Name)
}
// If we have a subdirectory, then merge that in
if subDir != "" {
dir = filepath.Join(dir, subDir)
}
// Load the configurations.Dir(source)
children[m.Name], err = NewTreeModule(m.Name, dir)
if err != nil {
return fmt.Errorf(
"module %s: %s", m.Name, err)
}
// Set the path of this child
children[m.Name].path = path
}
// Go through all the children and load them.
for _, c := range children {
if err := c.Load(s, mode); err != nil {
return err
}
}
// Set our tree up
t.children = children
return nil
}
// Path is the full path to this tree.
func (t *Tree) Path() []string {
return t.path
}
// String gives a nice output to describe the tree.
func (t *Tree) String() string {
var result bytes.Buffer
path := strings.Join(t.path, ", ")
if path != "" {
path = fmt.Sprintf(" (path: %s)", path)
}
result.WriteString(t.Name() + path + "\n")
cs := t.Children()
if cs == nil {
result.WriteString(" not loaded")
} else {
// Go through each child and get its string value, then indent it
// by two.
for _, c := range cs {
r := strings.NewReader(c.String())
scanner := bufio.NewScanner(r)
for scanner.Scan() {
result.WriteString(" ")
result.WriteString(scanner.Text())
result.WriteString("\n")
}
}
}
return result.String()
}
// Validate does semantic checks on the entire tree of configurations.
//
// This will call the respective config.Config.Validate() functions as well
// as verifying things such as parameters/outputs between the various modules.
//
// Load must be called prior to calling Validate or an error will be returned.
func (t *Tree) Validate() error {
if !t.Loaded() {
return fmt.Errorf("tree must be loaded before calling Validate")
}
// If something goes wrong, here is our error template
newErr := &TreeError{Name: []string{t.Name()}}
// Validate our configuration first.
if err := t.config.Validate(); err != nil {
newErr.Err = err
return newErr
}
// Get the child trees
children := t.Children()
// Validate all our children
for _, c := range children {
err := c.Validate()
if err == nil {
continue
}
verr, ok := err.(*TreeError)
if !ok {
// Unknown error, just return...
return err
}
// Append ourselves to the error and then return
verr.Name = append(verr.Name, t.Name())
return verr
}
// Go over all the modules and verify that any parameters are valid
// variables into the module in question.
for _, m := range t.config.Modules {
tree, ok := children[m.Name]
if !ok {
// This should never happen because Load watches us
panic("module not found in children: " + m.Name)
}
// Build the variables that the module defines
requiredMap := make(map[string]struct{})
varMap := make(map[string]struct{})
for _, v := range tree.config.Variables {
varMap[v.Name] = struct{}{}
if v.Required() {
requiredMap[v.Name] = struct{}{}
}
}
// Compare to the keys in our raw config for the module
for k, _ := range m.RawConfig.Raw {
if _, ok := varMap[k]; !ok {
newErr.Err = fmt.Errorf(
"module %s: %s is not a valid parameter",
m.Name, k)
return newErr
}
// Remove the required
delete(requiredMap, k)
}
// If we have any required left over, they aren't set.
for k, _ := range requiredMap {
newErr.Err = fmt.Errorf(
"module %s: required variable %s not set",
m.Name, k)
return newErr
}
}
// Go over all the variables used and make sure that any module
// variables represent outputs properly.
for source, vs := range t.config.InterpolatedVariables() {
for _, v := range vs {
mv, ok := v.(*config.ModuleVariable)
if !ok {
continue
}
tree, ok := children[mv.Name]
if !ok {
// This should never happen because Load watches us
panic("module not found in children: " + mv.Name)
}
found := false
for _, o := range tree.config.Outputs {
if o.Name == mv.Field {
found = true
break
}
}
if !found {
newErr.Err = fmt.Errorf(
"%s: %s is not a valid output for module %s",
source, mv.Field, mv.Name)
return newErr
}
}
}
return nil
}
// TreeError is an error returned by Tree.Validate if an error occurs
// with validation.
type TreeError struct {
Name []string
Err error
}
func (e *TreeError) Error() string {
// Build up the name
var buf bytes.Buffer
for _, n := range e.Name {
buf.WriteString(n)
buf.WriteString(".")
}
buf.Truncate(buf.Len() - 1)
// Format the value
return fmt.Sprintf("module %s: %s", buf.String(), e.Err)
}
| daveadams/terraform | config/module/tree.go | GO | mpl-2.0 | 9,350 |
from django_future.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_POST
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import reverse
from django.http import HttpResponse
import json
import logging
import re
from courseware.courses import get_course_with_access
from edxmako.shortcuts import render_to_response
from . import cohorts
log = logging.getLogger(__name__)
def json_http_response(data):
"""
Return an HttpResponse with the data json-serialized and the right content
type header.
"""
return HttpResponse(json.dumps(data), content_type="application/json")
def split_by_comma_and_whitespace(s):
"""
Split a string both by commas and whitespice. Returns a list.
"""
return re.split(r'[\s,]+', s)
@ensure_csrf_cookie
def list_cohorts(request, course_id):
"""
Return json dump of dict:
{'success': True,
'cohorts': [{'name': name, 'id': id}, ...]}
"""
get_course_with_access(request.user, course_id, 'staff')
all_cohorts = [{'name': c.name, 'id': c.id}
for c in cohorts.get_course_cohorts(course_id)]
return json_http_response({'success': True,
'cohorts': all_cohorts})
@ensure_csrf_cookie
@require_POST
def add_cohort(request, course_id):
"""
Return json of dict:
{'success': True,
'cohort': {'id': id,
'name': name}}
or
{'success': False,
'msg': error_msg} if there's an error
"""
get_course_with_access(request.user, course_id, 'staff')
name = request.POST.get("name")
if not name:
return json_http_response({'success': False,
'msg': "No name specified"})
try:
cohort = cohorts.add_cohort(course_id, name)
except ValueError as err:
return json_http_response({'success': False,
'msg': str(err)})
return json_http_response({'success': 'True',
'cohort': {
'id': cohort.id,
'name': cohort.name
}})
@ensure_csrf_cookie
def users_in_cohort(request, course_id, cohort_id):
"""
Return users in the cohort. Show up to 100 per page, and page
using the 'page' GET attribute in the call. Format:
Returns:
Json dump of dictionary in the following format:
{'success': True,
'page': page,
'num_pages': paginator.num_pages,
'users': [{'username': ..., 'email': ..., 'name': ...}]
}
"""
get_course_with_access(request.user, course_id, 'staff')
# this will error if called with a non-int cohort_id. That's ok--it
# shoudn't happen for valid clients.
cohort = cohorts.get_cohort_by_id(course_id, int(cohort_id))
paginator = Paginator(cohort.users.all(), 100)
page = request.GET.get('page')
try:
users = paginator.page(page)
except PageNotAnInteger:
# return the first page
page = 1
users = paginator.page(page)
except EmptyPage:
# Page is out of range. Return last page
page = paginator.num_pages
contacts = paginator.page(page)
user_info = [{'username': u.username,
'email': u.email,
'name': '{0} {1}'.format(u.first_name, u.last_name)}
for u in users]
return json_http_response({'success': True,
'page': page,
'num_pages': paginator.num_pages,
'users': user_info})
@ensure_csrf_cookie
@require_POST
def add_users_to_cohort(request, course_id, cohort_id):
"""
Return json dict of:
{'success': True,
'added': [{'username': ...,
'name': ...,
'email': ...}, ...],
'changed': [{'username': ...,
'name': ...,
'email': ...,
'previous_cohort': ...}, ...],
'present': [str1, str2, ...], # already there
'unknown': [str1, str2, ...]}
"""
get_course_with_access(request.user, course_id, 'staff')
cohort = cohorts.get_cohort_by_id(course_id, cohort_id)
users = request.POST.get('users', '')
added = []
changed = []
present = []
unknown = []
for username_or_email in split_by_comma_and_whitespace(users):
if not username_or_email:
continue
try:
(user, previous_cohort) = cohorts.add_user_to_cohort(cohort, username_or_email)
info = {
'username': user.username,
'name': user.profile.name,
'email': user.email,
}
if previous_cohort:
info['previous_cohort'] = previous_cohort
changed.append(info)
else:
added.append(info)
except ValueError:
present.append(username_or_email)
except User.DoesNotExist:
unknown.append(username_or_email)
return json_http_response({'success': True,
'added': added,
'changed': changed,
'present': present,
'unknown': unknown})
@ensure_csrf_cookie
@require_POST
def remove_user_from_cohort(request, course_id, cohort_id):
"""
Expects 'username': username in POST data.
Return json dict of:
{'success': True} or
{'success': False,
'msg': error_msg}
"""
get_course_with_access(request.user, course_id, 'staff')
username = request.POST.get('username')
if username is None:
return json_http_response({'success': False,
'msg': 'No username specified'})
cohort = cohorts.get_cohort_by_id(course_id, cohort_id)
try:
user = User.objects.get(username=username)
cohort.users.remove(user)
return json_http_response({'success': True})
except User.DoesNotExist:
log.debug('no user')
return json_http_response({'success': False,
'msg': "No user '{0}'".format(username)})
def debug_cohort_mgmt(request, course_id):
"""
Debugging view for dev.
"""
# add staff check to make sure it's safe if it's accidentally deployed.
get_course_with_access(request.user, course_id, 'staff')
context = {'cohorts_ajax_url': reverse('cohorts',
kwargs={'course_id': course_id})}
return render_to_response('/course_groups/debug.html', context)
| yokose-ks/edx-platform | common/djangoapps/course_groups/views.py | Python | agpl-3.0 | 6,739 |
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ejb.security.runas.ejb2mdb;
import javax.annotation.Resource;
import javax.annotation.security.RunAs;
import javax.annotation.security.PermitAll;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import org.jboss.logging.Logger;
/**
* MDB with RunAs annotation. Takes data from in queue and replies to reply queue.
*
* @author Ondrej Chaloupka
*/
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "java:jboss/exported/queue/TestQueue"),
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "maxSession", propertyValue = "1")})
@RunAs("INTERNAL_ROLE")
@PermitAll // needed for access not being denied, see WFLY-8560
public class HelloMDB implements MessageListener {
private static final Logger log = Logger.getLogger(HowdyBean.class);
@EJB
Howdy howdy;
@Resource(mappedName = "java:/ConnectionFactory")
private QueueConnectionFactory qFactory;
@Resource(lookup = "java:global/runasmdbejb-ejb2/GoodBye!org.jboss.as.test.integration.ejb.security.runas.ejb2mdb.GoodByeLocalHome")
GoodByeLocalHome goodByeHome;
public void onMessage(Message message) {
try {
GoodByeLocal goodBye = goodByeHome.create();
String messageToReply = String.format("%s! %s.", howdy.sayHowdy(), goodBye.sayGoodBye());
sendReply(messageToReply, (Queue) message.getJMSReplyTo(), message.getJMSMessageID());
} catch (Exception e) {
log.errorf(e, "Can't process message '%s'", message);
}
}
private void sendReply(String msg, Queue destination, String messageID) throws JMSException {
QueueConnection conn = qFactory.createQueueConnection("guest", "guest");
try {
QueueSession session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
conn.start();
QueueSender sender = session.createSender(destination);
TextMessage message = session.createTextMessage(msg);
message.setJMSCorrelationID(messageID);
sender.send(message, DeliveryMode.NON_PERSISTENT, 4, 500);
} finally {
conn.close();
}
}
}
| xasx/wildfly | testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/security/runas/ejb2mdb/HelloMDB.java | Java | lgpl-2.1 | 3,813 |
/*
* nwfilter_ebiptables_driver.h: ebtables/iptables driver support
*
* Copyright (C) 2010 IBM Corporation
* Copyright (C) 2010 Stefan Berger
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "nwfilter_tech_driver.h"
#define MAX_CHAINNAME_LENGTH 32 /* see linux/netfilter_bridge/ebtables.h */
extern virNWFilterTechDriver ebiptables_driver;
#define EBIPTABLES_DRIVER_ID "ebiptables"
#define IPTABLES_MAX_COMMENT_LENGTH 256
| eskultety/libvirt | src/nwfilter/nwfilter_ebiptables_driver.h | C | lgpl-2.1 | 1,086 |
class TagCloudPortlet < Cms::Portlet
description "Generates a Tag cloud by based the tags used on content blocks."
def self.default_sizes
(0..4).map{|n| "size-#{n}" }.join(" ")
end
def render
@sizes = self.sizes.blank? ? self.class.default_sizes : self.sizes
@limit = self.limit.blank? ? 50 : self.limit
@cloud = Cms::Tag.cloud(:sizes => @sizes.size, :limit => @limit)
end
end
| bill-ricksteves/browsercms | app/portlets/tag_cloud_portlet.rb | Ruby | lgpl-3.0 | 413 |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<link rel="stylesheet" type="text/css" href="../stylesheets/style.css">
<title>TarFileSet Type</title>
</head>
<body>
<h2><a name="fileset">TarFileSet</a></h2>
<p><em>TarFileSet</em> has been added as a stand-alone type in Apache Ant
1.7.</p>
<p>A <code><tarfileset></code> is a special form of a <code><<a
href="fileset.html">fileset</a>></code> which can behave in 2
different ways : <br>
</p>
<ul>
<li>When the <span style="font-style: italic;">src</span> attribute
is used - or a nested resource collection has been specified, the
tarfileset is populated with tar entries found in the file <span
style="font-style: italic;">src</span>.<br>
</li>
<li>When the <span style="font-style: italic;">dir</span> attribute
is used, the tarfileset is populated with filesystem files found under <span
style="font-style: italic;">dir</span>.<br>
</li>
</ul>
<p><code><tarfileset></code> supports all attributes of <code><<a
href="fileset.html">fileset</a>></code>
in addition to those listed below. Note that tar archives in general
don't contain entries with leading slashes so you shouldn't use
include/exclude patterns that start with slashes either.
</p>
<p>A tarfileset can be defined with the <span style="font-style:
italic;">id </span>attribute and referred to with the <span
style="font-style: italic;">refid</span> attribute. This is also true
for tarfileset which has been added in Ant 1.7.<br>
</p>
<h3>Parameters</h3>
<table border="1" cellpadding="2" cellspacing="0">
<tbody>
<tr>
<td valign="top"><b>Attribute</b></td>
<td valign="top"><b>Description</b></td>
<td valign="top" align="center"><b>Required</b></td>
</tr>
<tr>
<td valign="top">prefix</td>
<td valign="top">all files in the fileset are prefixed with that
path in the archive.</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">fullpath</td>
<td valign="top">the file described by the fileset is placed at
that exact location in the archive.</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">src</td>
<td valign="top">may be used in place of the <i>dir</i> attribute
to specify a tar file whose contents will be extracted and included
in the archive.</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">filemode</td>
<td valign="top">A 3 digit octal string, specify the user, group
and other modes in the standard Unix fashion. Only applies to
plain files. Default is 644.</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">dirmode</td>
<td valign="top">A 3 digit octal string, specify the user, group
and other modes in the standard Unix fashion. Only applies to
directories. Default is 755.</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">username</td>
<td valign="top">The username for the tar entry. This is not the same as the UID.
</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">group</td>
<td valign="top">The groupname for the tar entry. This is not the same as the GID.
</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">uid</td>
<td valign="top">The user identifier (UID) for the tar entry. This is an integer value
and is not the same as the username.
</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">gid</td>
<td valign="top">The group identifier (GID) for the tar entry.
</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">erroronmissingarchive</td>
<td valign="top">
Specify what happens if the archive does not exist.
If true, a build error will happen; if false, the fileset
will be ignored/empty.
Defaults to true.
<em>Since Ant 1.8.0</em>
</td>
<td valign="top" align="center">No</td>
</tr>
<tr>
<td valign="top">encoding</td>
<td valign="top">The character encoding to use for filenames
inside the zip file. For a list of possible values see the <a
href="http://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html">Supported Encodings</a>.
Defaults to the platform's default character encoding.
<em>Since Ant 1.9.5</em>
<td align="center" valign="top">No</td>
</tr>
</tbody>
</table>
<p>The <i>fullpath</i> attribute can only be set for filesets that
represent a single file. The <i>prefix</i> and <i>fullpath</i>
attributes cannot both be set on the same fileset.</p>
<p>When using the <i>src</i> attribute, include and exclude patterns
may be used to specify a subset of the archive for inclusion in the
archive as with the <i>dir</i> attribute.</p>
<p>Please note that currently only the <a
href="../Tasks/tar.html">tar</a> task uses the permission and
ownership attributes.</p>
<h3>Parameters specified as nested elements</h3>
<h4>any <a href="resources.html">resource</a> or single element
resource collection</h4>
<p>The specified resource will be used as src.</p>
<h4>Examples</h4>
<blockquote>
<pre>
<copy todir="some-dir">
<tarfileset includes="lib/**">
<bzip2resource>
<url url="http://example.org/dist/some-archive.tar.bz2"/>
</bzip2resource>
</tarfileset>
</copy>
</pre></blockquote>
<p>downloads the archive some-archive.tar.bz2, uncompresses and
extracts it on the fly, copies the contents of the lib directory into
some-dir and discards the rest of the archive. File timestamps will
be compared between the archive's entries and files inside the target
directory, no files get overwritten unless they are out-of-date.</p>
</body>
</html>
| mntamim/vending-machine-kata | vending-machine-kata/apache-ant-1.9.7/manual/Types/tarfileset.html | HTML | unlicense | 6,885 |
module.exports = require("core-js-pure/features/weak-set"); | BigBoss424/portfolio | v8/development/node_modules/@babel/runtime-corejs3/core-js/weak-set.js | JavaScript | apache-2.0 | 59 |
/*
* Copyright 2012-2018 the original author or authors.
*
* 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.
*/
package org.springframework.boot.context.properties.bind.validation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.springframework.boot.context.properties.source.ConfigurationProperty;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName.Form;
import org.springframework.boot.origin.Origin;
import org.springframework.boot.origin.OriginProvider;
import org.springframework.util.Assert;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
/**
* A collection of {@link ObjectError ObjectErrors} caused by bind validation failures.
* Where possible, included {@link FieldError FieldErrors} will be OriginProvider.
*
* @author Phillip Webb
* @author Madhura Bhave
* @since 2.0.0
*/
public class ValidationErrors implements Iterable<ObjectError> {
private final ConfigurationPropertyName name;
private final Set<ConfigurationProperty> boundProperties;
private final List<ObjectError> errors;
ValidationErrors(ConfigurationPropertyName name,
Set<ConfigurationProperty> boundProperties, List<ObjectError> errors) {
Assert.notNull(name, "Name must not be null");
Assert.notNull(boundProperties, "BoundProperties must not be null");
Assert.notNull(errors, "Errors must not be null");
this.name = name;
this.boundProperties = Collections.unmodifiableSet(boundProperties);
this.errors = convertErrors(name, boundProperties, errors);
}
private List<ObjectError> convertErrors(ConfigurationPropertyName name,
Set<ConfigurationProperty> boundProperties, List<ObjectError> errors) {
List<ObjectError> converted = new ArrayList<>(errors.size());
for (ObjectError error : errors) {
converted.add(convertError(name, boundProperties, error));
}
return Collections.unmodifiableList(converted);
}
private ObjectError convertError(ConfigurationPropertyName name,
Set<ConfigurationProperty> boundProperties, ObjectError error) {
if (error instanceof FieldError) {
return convertFieldError(name, boundProperties, (FieldError) error);
}
return error;
}
private FieldError convertFieldError(ConfigurationPropertyName name,
Set<ConfigurationProperty> boundProperties, FieldError error) {
if (error instanceof OriginProvider) {
return error;
}
return OriginTrackedFieldError.of(error,
findFieldErrorOrigin(name, boundProperties, error));
}
private Origin findFieldErrorOrigin(ConfigurationPropertyName name,
Set<ConfigurationProperty> boundProperties, FieldError error) {
for (ConfigurationProperty boundProperty : boundProperties) {
if (isForError(name, boundProperty.getName(), error)) {
return Origin.from(boundProperty);
}
}
return null;
}
private boolean isForError(ConfigurationPropertyName name,
ConfigurationPropertyName boundPropertyName, FieldError error) {
return name.isParentOf(boundPropertyName) && boundPropertyName
.getLastElement(Form.UNIFORM).equalsIgnoreCase(error.getField());
}
/**
* Return the name of the item that was being validated.
* @return the name of the item
*/
public ConfigurationPropertyName getName() {
return this.name;
}
/**
* Return the properties that were bound before validation failed.
* @return the boundProperties
*/
public Set<ConfigurationProperty> getBoundProperties() {
return this.boundProperties;
}
public boolean hasErrors() {
return !this.errors.isEmpty();
}
/**
* Return the list of all validation errors.
* @return the errors
*/
public List<ObjectError> getAllErrors() {
return this.errors;
}
@Override
public Iterator<ObjectError> iterator() {
return this.errors.iterator();
}
}
| bclozel/spring-boot | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationErrors.java | Java | apache-2.0 | 4,455 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../includes/main.css" type="text/css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<title>Apache CloudStack | The Power Behind Your Cloud</title>
</head>
<body>
<div id="insidetopbg">
<div id="inside_wrapper">
<div class="uppermenu_panel">
<div class="uppermenu_box"></div>
</div>
<div id="main_master">
<div id="inside_header">
<div class="header_top">
<a class="cloud_logo" href="http://cloudstack.org"></a>
<div class="mainemenu_panel"></div>
</div>
</div>
<div id="main_content">
<div class="inside_apileftpanel">
<div class="inside_contentpanel" style="width:930px;">
<div class="api_titlebox">
<div class="api_titlebox_left">
<span>
Apache CloudStack 4.0.0-incubating User API Reference
</span>
<p></p>
<h1>createProject</h1>
<p>Creates a project</p>
</div>
<div class="api_titlebox_right">
<a class="api_backbutton" href="../TOC_User.html"></a>
</div>
</div>
<div class="api_tablepanel">
<h2>Request parameters</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td>
</tr>
<tr>
<td style="width:200px;"><strong>displaytext</strong></td><td style="width:500px;"><strong>display text of the project</strong></td><td style="width:180px;"><strong>true</strong></td>
</tr>
<tr>
<td style="width:200px;"><strong>name</strong></td><td style="width:500px;"><strong>name of the project</strong></td><td style="width:180px;"><strong>true</strong></td>
</tr>
<tr>
<td style="width:200px;"><i>account</i></td><td style="width:500px;"><i>account who will be Admin for the project</i></td><td style="width:180px;"><i>false</i></td>
</tr>
<tr>
<td style="width:200px;"><i>domainid</i></td><td style="width:500px;"><i>domain ID of the account owning a project</i></td><td style="width:180px;"><i>false</i></td>
</tr>
</table>
</div>
<div class="api_tablepanel">
<h2>Response Tags</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td>
</tr>
<tr>
<td style="width:200px;"><strong>id</strong></td><td style="width:500px;">the id of the project</td>
</tr>
<tr>
<td style="width:200px;"><strong>account</strong></td><td style="width:500px;">the account name of the project's owner</td>
</tr>
<tr>
<td style="width:200px;"><strong>displaytext</strong></td><td style="width:500px;">the displaytext of the project</td>
</tr>
<tr>
<td style="width:200px;"><strong>domain</strong></td><td style="width:500px;">the domain name where the project belongs to</td>
</tr>
<tr>
<td style="width:200px;"><strong>domainid</strong></td><td style="width:500px;">the domain id the project belongs to</td>
</tr>
<tr>
<td style="width:200px;"><strong>name</strong></td><td style="width:500px;">the name of the project</td>
</tr>
<tr>
<td style="width:200px;"><strong>state</strong></td><td style="width:500px;">the state of the project</td>
</tr>
<tr>
<td style="width:200px;"><strong>tags(*)</strong></td><td style="width:500px;">the list of resource tags associated with vm</td>
<tr>
<td style="width:180px; padding-left:25px;"><strong>account</strong></td><td style="width:500px;">the account associated with the tag</td>
</tr>
<tr>
<td style="width:180px; padding-left:25px;"><strong>customer</strong></td><td style="width:500px;">customer associated with the tag</td>
</tr>
<tr>
<td style="width:180px; padding-left:25px;"><strong>domain</strong></td><td style="width:500px;">the domain associated with the tag</td>
</tr>
<tr>
<td style="width:180px; padding-left:25px;"><strong>domainid</strong></td><td style="width:500px;">the ID of the domain associated with the tag</td>
</tr>
<tr>
<td style="width:180px; padding-left:25px;"><strong>key</strong></td><td style="width:500px;">tag key name</td>
</tr>
<tr>
<td style="width:180px; padding-left:25px;"><strong>project</strong></td><td style="width:500px;">the project name where tag belongs to</td>
</tr>
<tr>
<td style="width:180px; padding-left:25px;"><strong>projectid</strong></td><td style="width:500px;">the project id the tag belongs to</td>
</tr>
<tr>
<td style="width:180px; padding-left:25px;"><strong>resourceid</strong></td><td style="width:500px;">id of the resource</td>
</tr>
<tr>
<td style="width:180px; padding-left:25px;"><strong>resourcetype</strong></td><td style="width:500px;">resource type</td>
</tr>
<tr>
<td style="width:180px; padding-left:25px;"><strong>value</strong></td><td style="width:500px;">tag value</td>
</tr>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer_mainmaster">
<p>Copyright © 2012 The Apache Software Foundation, Licensed under the
<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a>
<br>
Apache and the Apache feather logo are trademarks of The Apache Software Foundation.</p>
</div>
</div>
</div>
</div>
</body>
</html>
| resmo/cloudstack-www | source/api/apidocs-4.0.0/user/createProject.html | HTML | apache-2.0 | 5,250 |
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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 "tensorflow/core/kernels/cwise_ops_common.h"
namespace tensorflow {
REGISTER2(BinaryOp, CPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, CPU, "Polygamma", functor::polygamma, float, double);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER2(BinaryOp, GPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, GPU, "Polygamma", functor::polygamma, float, double);
#endif
#endif
} // namespace tensorflow
| tensorflow/tensorflow | tensorflow/core/kernels/cwise_op_zeta.cc | C++ | apache-2.0 | 1,156 |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
"""pytree-related utilities.
This module collects various utilities related to the parse trees produced by
the lib2to3 library.
NodeName(): produces a string name for pytree nodes.
ParseCodeToTree(): convenience wrapper around lib2to3 interfaces to parse
a given string with code to a pytree.
InsertNodeBefore(): insert a node before another in a pytree.
InsertNodeAfter(): insert a node after another in a pytree.
{Get,Set}NodeAnnotation(): manage custom annotations on pytree nodes.
"""
import ast
from lib2to3 import pygram
from lib2to3 import pytree
from lib2to3.pgen2 import driver
from lib2to3.pgen2 import parse
from lib2to3.pgen2 import token
# TODO(eliben): We may want to get rid of this filtering at some point once we
# have a better understanding of what information we need from the tree. Then,
# these tokens may be filtered out from the tree before the tree gets to the
# unwrapper.
NONSEMANTIC_TOKENS = frozenset(['DEDENT', 'INDENT', 'NEWLINE', 'ENDMARKER'])
OPENING_BRACKETS = frozenset({'(', '[', '{'})
CLOSING_BRACKETS = frozenset({')', ']', '}'})
class Annotation(object):
"""Annotation names associated with pytrees."""
CHILD_INDENT = 'child_indent'
NEWLINES = 'newlines'
MUST_SPLIT = 'must_split'
SPLIT_PENALTY = 'split_penalty'
SUBTYPE = 'subtype'
def NodeName(node):
"""Produce a string name for a given node.
For a Leaf this is the token name, and for a Node this is the type.
Arguments:
node: a tree node
Returns:
Name as a string.
"""
# Nodes with values < 256 are tokens. Values >= 256 are grammar symbols.
if node.type < 256:
return token.tok_name[node.type]
else:
return pygram.python_grammar.number2symbol[node.type]
# lib2to3 thoughtfully provides pygram.python_grammar_no_print_statement for
# parsing Python 3 code that wouldn't parse otherwise (when 'print' is used in a
# context where a keyword is disallowed).
# It forgets to do the same for 'exec' though. Luckily, Python is amenable to
# monkey-patching.
_GRAMMAR_FOR_PY3 = pygram.python_grammar_no_print_statement.copy()
del _GRAMMAR_FOR_PY3.keywords['exec']
_GRAMMAR_FOR_PY2 = pygram.python_grammar.copy()
def ParseCodeToTree(code):
"""Parse the given code to a lib2to3 pytree.
Arguments:
code: a string with the code to parse.
Raises:
SyntaxError if the code is invalid syntax.
parse.ParseError if some other parsing failure.
Returns:
The root node of the parsed tree.
"""
# This function is tiny, but the incantation for invoking the parser correctly
# is sufficiently magical to be worth abstracting away.
try:
# Try to parse using a Python 3 grammar, which is more permissive (print and
# exec are not keywords).
parser_driver = driver.Driver(_GRAMMAR_FOR_PY3, convert=pytree.convert)
tree = parser_driver.parse_string(code, debug=False)
except parse.ParseError:
# Now try to parse using a Python 2 grammar; If this fails, then
# there's something else wrong with the code.
try:
parser_driver = driver.Driver(_GRAMMAR_FOR_PY2, convert=pytree.convert)
tree = parser_driver.parse_string(code, debug=False)
except parse.ParseError:
# Raise a syntax error if the code is invalid python syntax.
try:
ast.parse(code)
except SyntaxError as e:
raise e
else:
raise
return _WrapEndMarker(tree)
def _WrapEndMarker(tree):
"""Wrap a single ENDMARKER token in a "file_input" node.
Arguments:
tree: (pytree.Node) The root node of the parsed tree.
Returns:
The root node of the parsed tree. If the tree is a single ENDMARKER node,
then that node is wrapped in a "file_input" node. That will ensure we don't
skip comments attached to that node.
"""
if isinstance(tree, pytree.Leaf) and tree.type == token.ENDMARKER:
return pytree.Node(pygram.python_symbols.file_input, [tree])
return tree
def InsertNodesBefore(new_nodes, target):
"""Insert new_nodes before the given target location in the tree.
Arguments:
new_nodes: a sequence of new nodes to insert (the nodes should not be in the
tree).
target: the target node before which the new node node will be inserted.
Raises:
RuntimeError: if the tree is corrupted, or the insertion would corrupt it.
"""
for node in new_nodes:
_InsertNodeAt(node, target, after=False)
def InsertNodesAfter(new_nodes, target):
"""Insert new_nodes after the given target location in the tree.
Arguments:
new_nodes: a sequence of new nodes to insert (the nodes should not be in the
tree).
target: the target node after which the new node node will be inserted.
Raises:
RuntimeError: if the tree is corrupted, or the insertion would corrupt it.
"""
for node in reversed(new_nodes):
_InsertNodeAt(node, target, after=True)
def _InsertNodeAt(new_node, target, after=False):
"""Underlying implementation for node insertion.
Arguments:
new_node: a new node to insert (this node should not be in the tree).
target: the target node.
after: if True, new_node is inserted after target. Otherwise, it's inserted
before target.
Returns:
nothing
Raises:
RuntimeError: if the tree is corrupted, or the insertion would corrupt it.
"""
# Protect against attempts to insert nodes which already belong to some tree.
if new_node.parent is not None:
raise RuntimeError('inserting node which already has a parent',
(new_node, new_node.parent))
# The code here is based on pytree.Base.next_sibling
parent_of_target = target.parent
if parent_of_target is None:
raise RuntimeError('expected target node to have a parent', (target,))
for i, child in enumerate(parent_of_target.children):
if child is target:
insertion_index = i + 1 if after else i
parent_of_target.insert_child(insertion_index, new_node)
return
raise RuntimeError('unable to find insertion point for target node',
(target,))
# The following constant and functions implement a simple custom annotation
# mechanism for pytree nodes. We attach new attributes to nodes. Each attribute
# is prefixed with _NODE_ANNOTATION_PREFIX. These annotations should only be
# managed through GetNodeAnnotation and SetNodeAnnotation.
_NODE_ANNOTATION_PREFIX = '_yapf_annotation_'
def GetNodeAnnotation(node, annotation, default=None):
"""Get annotation value from a node.
Arguments:
node: the node.
annotation: annotation name - a string.
default: the default value to return if there's no annotation.
Returns:
Value of the annotation in the given node. If the node doesn't have this
particular annotation name yet, returns default.
"""
return getattr(node, _NODE_ANNOTATION_PREFIX + annotation, default)
def SetNodeAnnotation(node, annotation, value):
"""Set annotation value on a node.
Arguments:
node: the node.
annotation: annotation name - a string.
value: annotation value to set.
"""
setattr(node, _NODE_ANNOTATION_PREFIX + annotation, value)
def AppendNodeAnnotation(node, annotation, value):
"""Appends an annotation value to a list of annotations on the node.
Arguments:
node: the node.
annotation: annotation name - a string.
value: annotation value to set.
"""
attr = GetNodeAnnotation(node, annotation, set())
attr.add(value)
SetNodeAnnotation(node, annotation, attr)
def RemoveSubtypeAnnotation(node, value):
"""Removes an annotation value from the subtype annotations on the node.
Arguments:
node: the node.
value: annotation value to remove.
"""
attr = GetNodeAnnotation(node, Annotation.SUBTYPE)
if attr and value in attr:
attr.remove(value)
SetNodeAnnotation(node, Annotation.SUBTYPE, attr)
def DumpNodeToString(node):
"""Dump a string representation of the given node. For debugging.
Arguments:
node: the node.
Returns:
The string representation.
"""
if isinstance(node, pytree.Leaf):
fmt = '{name}({value}) [lineno={lineno}, column={column}, prefix={prefix}]'
return fmt.format(name=NodeName(node),
value=repr(node),
lineno=node.lineno,
column=node.column,
prefix=repr(node.prefix))
else:
fmt = '{node} [{len} children] [child_indent="{indent}"]'
return fmt.format(node=NodeName(node),
len=len(node.children),
indent=GetNodeAnnotation(node, Annotation.CHILD_INDENT))
def IsCommentStatement(node):
return (NodeName(node) == 'simple_stmt' and
NodeName(node.children[0]) == 'COMMENT')
| lucius-feng/yapf | yapf/yapflib/pytree_utils.py | Python | apache-2.0 | 9,295 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.arrow.vector.ipc.message;
import com.google.flatbuffers.FlatBufferBuilder;
/**
* Interface for serializing to FlatBuffers.
*/
public interface FBSerializable {
/**
* Returns the number of bytes taken to serialize the data in builder after writing to it.
*/
int writeTo(FlatBufferBuilder builder);
}
| renesugar/arrow | java/vector/src/main/java/org/apache/arrow/vector/ipc/message/FBSerializable.java | Java | apache-2.0 | 1,134 |
<div class="x_panel">
<div class="x_title">
<ol class="breadcrumb pull-left">
<li class="active">Divisions</li>
</ol>
<button class="btn btn-primary pull-right" ng-click="createDivision()">New</button>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br>
<table id="divisionsTable" class="table responsive-utilities jambo_table">
<thead>
<tr class="headings">
<th>name</th>
</tr>
</thead>
<tbody>
<tr ng-click="editDivision(division.id)" ng-repeat="division in divisions">
<td>{{division.name}}</td>
</tr>
</tbody>
</table>
</div>
</div>
| smalenfant/traffic_control | traffic_ops/experimental/ui/app/src/common/modules/table/divisions/table.divisions.tpl.html | HTML | apache-2.0 | 763 |
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
*/
/**
* @fileoverview Factory for amp-user-notification
*/
import {getElementService} from './custom-element';
/**
* @param {!Window} window
* @return {!Promise<!UserNotificationManager>}
*/
export function userNotificationManagerFor(window) {
return getElementService(window, 'userNotificationManager',
'amp-user-notification');
}
| simplereach/amphtml | src/user-notification.js | JavaScript | apache-2.0 | 975 |
/*******************************************************************************
* Copyright (c) 2005, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.bpel.ui.properties;
import org.eclipse.bpel.common.ui.flatui.FlatFormAttachment;
import org.eclipse.bpel.common.ui.flatui.FlatFormData;
import org.eclipse.bpel.ui.Messages;
import org.eclipse.bpel.ui.util.MultiObjectAdapter;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
/**
* Details section for the CatchAll
*/
public class CatchAllSection extends BPELPropertySection {
@Override
protected void createClient(Composite parent) {
Composite composite = createFlatFormComposite(parent);
FlatFormData ffdata;
Label nameLabel = fWidgetFactory.createLabel(composite, Messages.CatchAllDetails_0);
ffdata = new FlatFormData();
ffdata.left = new FlatFormAttachment(0, 0);
ffdata.top = new FlatFormAttachment(0, 0);
ffdata.right = new FlatFormAttachment(100, 0);
nameLabel.setLayoutData(ffdata);
}
@Override
protected MultiObjectAdapter[] createAdapters() {
return new MultiObjectAdapter[0];
}
@Override
public Object getUserContext() {
// TODO Auto-generated method stub
return null;
}
@Override
public void restoreUserContext(Object userContext) {
// TODO Auto-generated method stub
}
}
| Drifftr/devstudio-tooling-bps | plugins/org.eclipse.bpel.ui.noEmbeddedEditors/src/org/eclipse/bpel/ui/properties/CatchAllSection.java | Java | apache-2.0 | 1,729 |
package clusterresourceoverride
import (
"fmt"
"io"
"strings"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/admission"
kapi "k8s.io/kubernetes/pkg/api"
kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
informers "k8s.io/kubernetes/pkg/client/informers/informers_generated/internalversion"
kadmission "k8s.io/kubernetes/pkg/kubeapiserver/admission"
"k8s.io/kubernetes/plugin/pkg/admission/limitranger"
oadmission "github.com/openshift/origin/pkg/cmd/server/admission"
configlatest "github.com/openshift/origin/pkg/cmd/server/api/latest"
"github.com/openshift/origin/pkg/project/cache"
"github.com/openshift/origin/pkg/project/registry/projectrequest/delegated"
"github.com/openshift/origin/pkg/quota/admission/clusterresourceoverride/api"
"github.com/openshift/origin/pkg/quota/admission/clusterresourceoverride/api/validation"
)
const (
clusterResourceOverrideAnnotation = "quota.openshift.io/cluster-resource-override-enabled"
cpuBaseScaleFactor = 1000.0 / (1024.0 * 1024.0 * 1024.0) // 1000 milliCores per 1GiB
)
var (
cpuFloor = resource.MustParse("1m")
memFloor = resource.MustParse("1Mi")
)
func Register(plugins *admission.Plugins) {
plugins.Register(api.PluginName,
func(config io.Reader) (admission.Interface, error) {
pluginConfig, err := ReadConfig(config)
if err != nil {
return nil, err
}
if pluginConfig == nil {
glog.Infof("Admission plugin %q is not configured so it will be disabled.", api.PluginName)
return nil, nil
}
return newClusterResourceOverride(pluginConfig)
})
}
type internalConfig struct {
limitCPUToMemoryRatio float64
cpuRequestToLimitRatio float64
memoryRequestToLimitRatio float64
}
type clusterResourceOverridePlugin struct {
*admission.Handler
config *internalConfig
ProjectCache *cache.ProjectCache
LimitRanger admission.Interface
}
type limitRangerActions struct{}
var _ = oadmission.WantsProjectCache(&clusterResourceOverridePlugin{})
var _ = limitranger.LimitRangerActions(&limitRangerActions{})
var _ = kadmission.WantsInternalKubeInformerFactory(&clusterResourceOverridePlugin{})
var _ = kadmission.WantsInternalKubeClientSet(&clusterResourceOverridePlugin{})
// newClusterResourceOverride returns an admission controller for containers that
// configurably overrides container resource request/limits
func newClusterResourceOverride(config *api.ClusterResourceOverrideConfig) (admission.Interface, error) {
glog.V(2).Infof("%s admission controller loaded with config: %v", api.PluginName, config)
var internal *internalConfig
if config != nil {
internal = &internalConfig{
limitCPUToMemoryRatio: float64(config.LimitCPUToMemoryPercent) / 100,
cpuRequestToLimitRatio: float64(config.CPURequestToLimitPercent) / 100,
memoryRequestToLimitRatio: float64(config.MemoryRequestToLimitPercent) / 100,
}
}
limitRanger, err := limitranger.NewLimitRanger(nil)
if err != nil {
return nil, err
}
return &clusterResourceOverridePlugin{
Handler: admission.NewHandler(admission.Create),
config: internal,
LimitRanger: limitRanger,
}, nil
}
func (d *clusterResourceOverridePlugin) SetInternalKubeInformerFactory(i informers.SharedInformerFactory) {
d.LimitRanger.(kadmission.WantsInternalKubeInformerFactory).SetInternalKubeInformerFactory(i)
}
func (d *clusterResourceOverridePlugin) SetInternalKubeClientSet(c kclientset.Interface) {
d.LimitRanger.(kadmission.WantsInternalKubeClientSet).SetInternalKubeClientSet(c)
}
// these serve to satisfy the interface so that our kept LimitRanger limits nothing and only provides defaults.
func (d *limitRangerActions) SupportsAttributes(a admission.Attributes) bool {
return true
}
func (d *limitRangerActions) SupportsLimit(limitRange *kapi.LimitRange) bool {
return true
}
func (d *limitRangerActions) Limit(limitRange *kapi.LimitRange, resourceName string, obj runtime.Object) error {
return nil
}
func (a *clusterResourceOverridePlugin) SetProjectCache(projectCache *cache.ProjectCache) {
a.ProjectCache = projectCache
}
func ReadConfig(configFile io.Reader) (*api.ClusterResourceOverrideConfig, error) {
obj, err := configlatest.ReadYAML(configFile)
if err != nil {
glog.V(5).Infof("%s error reading config: %v", api.PluginName, err)
return nil, err
}
if obj == nil {
return nil, nil
}
config, ok := obj.(*api.ClusterResourceOverrideConfig)
if !ok {
return nil, fmt.Errorf("unexpected config object: %#v", obj)
}
glog.V(5).Infof("%s config is: %v", api.PluginName, config)
if errs := validation.Validate(config); len(errs) > 0 {
return nil, errs.ToAggregate()
}
return config, nil
}
func (a *clusterResourceOverridePlugin) Validate() error {
if a.ProjectCache == nil {
return fmt.Errorf("%s did not get a project cache", api.PluginName)
}
v, ok := a.LimitRanger.(admission.Validator)
if !ok {
return fmt.Errorf("LimitRanger does not implement kadmission.Validator")
}
return v.Validate()
}
func isExemptedNamespace(name string) bool {
for _, s := range delegated.ForbiddenNames {
if name == s {
return true
}
}
for _, s := range delegated.ForbiddenPrefixes {
if strings.HasPrefix(name, s) {
return true
}
}
return false
}
// TODO this will need to update when we have pod requests/limits
func (a *clusterResourceOverridePlugin) Admit(attr admission.Attributes) error {
glog.V(6).Infof("%s admission controller is invoked", api.PluginName)
if a.config == nil || attr.GetResource().GroupResource() != kapi.Resource("pods") || attr.GetSubresource() != "" {
return nil // not applicable
}
pod, ok := attr.GetObject().(*kapi.Pod)
if !ok {
return admission.NewForbidden(attr, fmt.Errorf("unexpected object: %#v", attr.GetObject()))
}
glog.V(5).Infof("%s is looking at creating pod %s in project %s", api.PluginName, pod.Name, attr.GetNamespace())
// allow annotations on project to override
ns, err := a.ProjectCache.GetNamespace(attr.GetNamespace())
if err != nil {
glog.Warningf("%s got an error retrieving namespace: %v", api.PluginName, err)
return admission.NewForbidden(attr, err) // this should not happen though
}
projectEnabledPlugin, exists := ns.Annotations[clusterResourceOverrideAnnotation]
if exists && projectEnabledPlugin != "true" {
glog.V(5).Infof("%s is disabled for project %s", api.PluginName, attr.GetNamespace())
return nil // disabled for this project, do nothing
}
if isExemptedNamespace(ns.Name) {
glog.V(5).Infof("%s is skipping exempted project %s", api.PluginName, attr.GetNamespace())
return nil // project is exempted, do nothing
}
// Reuse LimitRanger logic to apply limit/req defaults from the project. Ignore validation
// errors, assume that LimitRanger will run after this plugin to validate.
glog.V(5).Infof("%s: initial pod limits are: %#v", api.PluginName, pod.Spec)
if err := a.LimitRanger.Admit(attr); err != nil {
glog.V(5).Infof("%s: error from LimitRanger: %#v", api.PluginName, err)
}
glog.V(5).Infof("%s: pod limits after LimitRanger: %#v", api.PluginName, pod.Spec)
for i := range pod.Spec.InitContainers {
updateContainerResources(a.config, &pod.Spec.InitContainers[i])
}
for i := range pod.Spec.Containers {
updateContainerResources(a.config, &pod.Spec.Containers[i])
}
glog.V(5).Infof("%s: pod limits after overrides are: %#v", api.PluginName, pod.Spec)
return nil
}
func updateContainerResources(config *internalConfig, container *kapi.Container) {
resources := container.Resources
memLimit, memFound := resources.Limits[kapi.ResourceMemory]
if memFound && config.memoryRequestToLimitRatio != 0 {
// memory is measured in whole bytes.
// the plugin rounds down to the nearest MiB rather than bytes to improve ease of use for end-users.
amount := memLimit.Value() * int64(config.memoryRequestToLimitRatio*100) / 100
// TODO: move into resource.Quantity
var mod int64
switch memLimit.Format {
case resource.BinarySI:
mod = 1024 * 1024
default:
mod = 1000 * 1000
}
if rem := amount % mod; rem != 0 {
amount = amount - rem
}
q := resource.NewQuantity(int64(amount), memLimit.Format)
if memFloor.Cmp(*q) > 0 {
q = memFloor.Copy()
}
resources.Requests[kapi.ResourceMemory] = *q
}
if memFound && config.limitCPUToMemoryRatio != 0 {
amount := float64(memLimit.Value()) * config.limitCPUToMemoryRatio * cpuBaseScaleFactor
q := resource.NewMilliQuantity(int64(amount), resource.DecimalSI)
if cpuFloor.Cmp(*q) > 0 {
q = cpuFloor.Copy()
}
resources.Limits[kapi.ResourceCPU] = *q
}
cpuLimit, cpuFound := resources.Limits[kapi.ResourceCPU]
if cpuFound && config.cpuRequestToLimitRatio != 0 {
amount := float64(cpuLimit.MilliValue()) * config.cpuRequestToLimitRatio
q := resource.NewMilliQuantity(int64(amount), cpuLimit.Format)
if cpuFloor.Cmp(*q) > 0 {
q = cpuFloor.Copy()
}
resources.Requests[kapi.ResourceCPU] = *q
}
}
| ashetty1/kedge | vendor/github.com/openshift/origin/pkg/quota/admission/clusterresourceoverride/admission.go | GO | apache-2.0 | 8,980 |
# encoding: utf-8
# copyright: 2018, The Authors
title 'Test all the Jenkins things'
include_controls 'jenkins_smoke'
| opscode-cookbooks/jenkins | test/integration/smoke_war_stable/controls/smoke_war_stable.rb | Ruby | apache-2.0 | 120 |
/*
* Copyright 2012-2017 the original author or authors.
*
* 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.
*/
package org.springframework.boot.test.json;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.ResolvableType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link JsonContent}.
*
* @author Phillip Webb
*/
public class JsonContentTests {
private static final String JSON = "{\"name\":\"spring\", \"age\":100}";
private static final ResolvableType TYPE = ResolvableType
.forClass(ExampleObject.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void createWhenResourceLoadClassIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ResourceLoadClass must not be null");
new JsonContent<ExampleObject>(null, TYPE, JSON);
}
@Test
public void createWhenJsonIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("JSON must not be null");
new JsonContent<ExampleObject>(getClass(), TYPE, null);
}
@Test
public void createWhenTypeIsNullShouldCreateContent() throws Exception {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), null, JSON);
assertThat(content).isNotNull();
}
@Test
public void assertThatShouldReturnJsonContentAssert() throws Exception {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), TYPE, JSON);
assertThat(content.assertThat()).isInstanceOf(JsonContentAssert.class);
}
@Test
public void getJsonShouldReturnJson() throws Exception {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), TYPE, JSON);
assertThat(content.getJson()).isEqualTo(JSON);
}
@Test
public void toStringWhenHasTypeShouldReturnString() throws Exception {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), TYPE, JSON);
assertThat(content.toString())
.isEqualTo("JsonContent " + JSON + " created from " + TYPE);
}
@Test
public void toStringWhenHasNoTypeShouldReturnString() throws Exception {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), null, JSON);
assertThat(content.toString()).isEqualTo("JsonContent " + JSON);
}
}
| olivergierke/spring-boot | spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java | Java | apache-2.0 | 2,872 |
/*
* cgeTiltshiftAdjust.h
*
* Created on: 2014-1-24
* Author: Wang Yang
* Mail: [email protected]
*/
#ifndef _CGETILTSHIFT_H_
#define _CGETILTSHIFT_H_
#include "cgeGLFunctions.h"
#include "cgeSharpenBlurAdjust.h"
namespace CGE
{
class CGETiltshiftVectorFilter : public CGEImageFilterInterface
{
public:
CGETiltshiftVectorFilter() : m_texture(0), m_samplerScale(0) {}
~CGETiltshiftVectorFilter() { glDeleteTextures(1, &m_texture); }
virtual bool init();
//Both the real size about the image.
//eg: 100, 100. This means blurring from "start" and gradual changing in "gradient".
void setBlurGradient(GLfloat start, GLfloat gradient);
//Real pixels. This means the position the blur line would pass by.
void setBlurPassPos(GLfloat x, GLfloat y);
//range: both [0, 1]. This means the direction of the blur line.
void setBlurNormal(GLfloat x, GLfloat y);
//range: [0, π/2]. This means the angle of the blur normal.
//Note: You can choose one of "setBlurNormal" and "setRotation" as you like. The two functions did the same thing.
void setRotation(GLfloat angle);
//range: [0, 50]. This means the intensity of the blurring.
void setBlurRadiusScale(int radius);
//range: > 1. This defines the max true radius of the blurring.
//You should know that the sampling would be very slow in OpenGL ES2.0+ on your device if the sampling-radius is too large. The radius you set by "setBlurRadiusScale" simply provides a sampling radius scale whose true radius is less than the "limit" set by this function.
//This should be called before setBlurRadiusScale
void setBlurRadiusLimit(int limit);
void render2Texture(CGEImageHandlerInterface* handler, GLuint srcTexture, GLuint vertexBufferID);
void flush();
protected:
GLuint m_texture;
CGEBlurFastFilter m_blurProc;
static CGEConstString paramGradientName;
static CGEConstString paramBlurPassPosName;
static CGEConstString paramBlurNormalName;
private:
int m_samplerScale;
};
class CGETiltshiftEllipseFilter : public CGEImageFilterInterface
{
public:
CGETiltshiftEllipseFilter() : m_texture(0), m_samplerScale(0) {}
~CGETiltshiftEllipseFilter() { glDeleteTextures(1, &m_texture); }
virtual bool init();
//gradient > 1. The gradient is defined as the multiples of "RadiusStart".And ("BlurGradient" - "RadiusStart") is the gradual changing zone.
void setBlurGradient(GLfloat gradient);
//Real Pixels. The "centralX" and "centralY" sets the center of the ellipse.
void setBlurCentralPos(GLfloat centralX, GLfloat centralY);
//Real Pixels.
//The "radiusX" and "randiusY" sets the radius of the ellipse.
void setRadiusStart(GLfloat radiusX, GLfloat radiusY);
//range: [0, 50]. This means the intensity of the blurring.
void setBlurRadiusScale(int radius);
//This function is the same as "CGETiltshiftVectorFilter::setBlurRadiusLimit", see the discription above.
//This should be called before setBlurRadiusScale
void setBlurRadiusLimit(int limit);
//range: [0, π/2]. This means the rotation of the ellipse.
void setRotation(GLfloat rot);
void render2Texture(CGEImageHandlerInterface* handler, GLuint srcTexture, GLuint vertexBufferID);
void flush();
protected:
GLuint m_texture;
CGEBlurFastFilter m_blurProc;
static CGEConstString paramRotationName;
static CGEConstString paramGradientName;
static CGEConstString paramCentralPosName;
static CGEConstString paramRadiusStartName;
private:
int m_samplerScale;
};
//////////////////////////////////////////////////////////////////////////
class CGETiltshiftVectorWithFixedBlurRadiusFilter : public CGETiltshiftVectorFilter
{
public:
bool init();
};
class CGETiltshiftEllipseWithFixedBlurRadiusFilter : public CGETiltshiftEllipseFilter
{
public:
bool init();
};
}
#endif | qwertyezi/Test | text/library/gpuimageplus/src/main/jni/include/filters/cgeTiltshiftAdjust.h | C | apache-2.0 | 3,832 |
/* Copyright 2007-2015 QReal Research Group
*
* 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 "borderChecker.h"
#include "editor/nodeElement.h"
using namespace qReal::gui::editor;
BorderChecker::BorderChecker(const NodeElement* const node)
: mNode(node), mBorderValues(node->borderValues())
, mXHor(mBorderValues[0])
, mYHor(mBorderValues[1])
, mXVert(mBorderValues[2])
, mYVert(mBorderValues[3])
{
}
bool BorderChecker::checkLowerBorder(const QPointF &point) const
{
const qreal checkingPointX = point.x();
const qreal checkingPointY = point.y();
const QRectF rc = mNode->boundingRect();
return (checkingPointX >= rc.x() + mXHor) && (checkingPointX <= rc.x() + rc.width() - mXHor)
&& (checkingPointY >= rc.y() + rc.height() - mYHor)
&& (checkingPointY <= rc.y() + rc.height() + mYHor);
}
bool BorderChecker::checkUpperBorder(const QPointF &point) const
{
const qreal checkingPointX = point.x();
const qreal checkingPointY = point.y();
const QRectF rc = mNode->boundingRect();
return (checkingPointX >= rc.x() + mXHor) && (checkingPointX <= rc.x() + rc.width() - mXHor)
&& (checkingPointY >= rc.y() - mYHor)
&& (checkingPointY <= rc.y() + mYHor);
}
bool BorderChecker::checkLeftBorder(const QPointF &point) const
{
const qreal checkingPointX = point.x();
const qreal checkingPointY = point.y();
const QRectF rc = mNode->boundingRect();
return (checkingPointX >= rc.x() - mXVert) && (checkingPointX <= rc.x() + mXVert)
&& (checkingPointY >= rc.y() + mYVert)
&& (checkingPointY <= rc.y() + rc.height() - mYVert);
}
bool BorderChecker::checkRightBorder(const QPointF &point) const
{
const qreal checkingPointX = point.x();
const qreal checkingPointY = point.y();
const QRectF rc = mNode->boundingRect();
return (checkingPointX >= rc.x() + rc.width() - mXVert) && (checkingPointX <= rc.x() + rc.width() + mXVert)
&& (checkingPointY >= rc.y() + mYVert)
&& (checkingPointY <= rc.y() + rc.height() - mYVert);
}
bool BorderChecker::checkNoBorderX(const QPointF &point, qreal y) const
{
const qreal checkingPointY = point.y();
const QRectF rc = mNode->boundingRect();
return (checkingPointY >= rc.y() + y) && (checkingPointY <= rc.y() + rc.height() - y);
}
bool BorderChecker::checkNoBorderY(const QPointF &point, qreal x) const
{
const qreal checkingPointX = point.x();
const QRectF rc = mNode->boundingRect();
return (checkingPointX >= rc.x() + x) && (checkingPointX <= rc.x() + rc.width() - x);
}
| RomanBelkov/qreal | qrgui/editor/private/borderChecker.cpp | C++ | apache-2.0 | 2,972 |
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.
*
*/
package org.wso2.carbon.apimgt.usage.client.bean;
/**
* This class is used as a bean for represent API First access time result from the DAS REST API
*/
public class FirstAccessValue {
private long first_access_time;
public long getFirst_access_time() {
return first_access_time;
}
public void setFirst_access_time(long first_access_time) {
this.first_access_time = first_access_time;
}
public FirstAccessValue(long first_access_time) {
super();
this.first_access_time = first_access_time;
}
}
| dhanuka84/carbon-apimgt | components/apimgt/org.wso2.carbon.apimgt.usage/org.wso2.carbon.apimgt.usage.client/src/main/java/org/wso2/carbon/apimgt/usage/client/bean/FirstAccessValue.java | Java | apache-2.0 | 1,216 |
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.http2;
import java.io.IOException;
import java.util.List;
import okhttp3.Protocol;
import okio.BufferedSource;
/**
* {@link Protocol#HTTP_2 HTTP/2} only. Processes server-initiated HTTP requests on the client.
* Implementations must quickly dispatch callbacks to avoid creating a bottleneck.
*
* <p>While {@link #onReset} may occur at any time, the following callbacks are expected in order,
* correlated by stream ID.
*
* <ul>
* <li>{@link #onRequest}</li> <li>{@link #onHeaders} (unless canceled)
* <li>{@link #onData} (optional sequence of data frames)
* </ul>
*
* <p>As a stream ID is scoped to a single HTTP/2 connection, implementations which target multiple
* connections should expect repetition of stream IDs.
*
* <p>Return true to request cancellation of a pushed stream. Note that this does not guarantee
* future frames won't arrive on the stream ID.
*/
public interface PushObserver {
/**
* Describes the request that the server intends to push a response for.
*
* @param streamId server-initiated stream ID: an even number.
* @param requestHeaders minimally includes {@code :method}, {@code :scheme}, {@code :authority},
* and {@code :path}.
*/
boolean onRequest(int streamId, List<Header> requestHeaders);
/**
* The response headers corresponding to a pushed request. When {@code last} is true, there are
* no data frames to follow.
*
* @param streamId server-initiated stream ID: an even number.
* @param responseHeaders minimally includes {@code :status}.
* @param last when true, there is no response data.
*/
boolean onHeaders(int streamId, List<Header> responseHeaders, boolean last);
/**
* A chunk of response data corresponding to a pushed request. This data must either be read or
* skipped.
*
* @param streamId server-initiated stream ID: an even number.
* @param source location of data corresponding with this stream ID.
* @param byteCount number of bytes to read or skip from the source.
* @param last when true, there are no data frames to follow.
*/
boolean onData(int streamId, BufferedSource source, int byteCount, boolean last)
throws IOException;
/** Indicates the reason why this stream was canceled. */
void onReset(int streamId, ErrorCode errorCode);
PushObserver CANCEL = new PushObserver() {
@Override public boolean onRequest(int streamId, List<Header> requestHeaders) {
return true;
}
@Override public boolean onHeaders(int streamId, List<Header> responseHeaders, boolean last) {
return true;
}
@Override public boolean onData(int streamId, BufferedSource source, int byteCount,
boolean last) throws IOException {
source.skip(byteCount);
return true;
}
@Override public void onReset(int streamId, ErrorCode errorCode) {
}
};
}
| mjbenedict/okhttp | okhttp/src/main/java/okhttp3/internal/http2/PushObserver.java | Java | apache-2.0 | 3,484 |
//
// ZipLocalFileHeader.cpp
//
// $Id: //poco/1.4/Zip/src/ZipLocalFileHeader.cpp#1 $
//
// Library: Zip
// Package: Zip
// Module: ZipLocalFileHeader
//
// Copyright (c) 2007, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Zip/ZipLocalFileHeader.h"
#include "Poco/Zip/ZipDataInfo.h"
#include "Poco/Zip/ParseCallback.h"
#include "Poco/Buffer.h"
#include "Poco/Exception.h"
#include "Poco/File.h"
#include <cstring>
namespace Poco {
namespace Zip {
const char ZipLocalFileHeader::HEADER[ZipCommon::HEADER_SIZE] = {'\x50', '\x4b', '\x03', '\x04'};
ZipLocalFileHeader::ZipLocalFileHeader(const Poco::Path& fileName,
const Poco::DateTime& lastModifiedAt,
ZipCommon::CompressionMethod cm,
ZipCommon::CompressionLevel cl):
_rawHeader(),
_startPos(-1),
_endPos(-1),
_fileName(),
_lastModifiedAt(),
_extraField(),
_crc32(0),
_compressedSize(0),
_uncompressedSize(0)
{
std::memcpy(_rawHeader, HEADER, ZipCommon::HEADER_SIZE);
std::memset(_rawHeader+ZipCommon::HEADER_SIZE, 0, FULLHEADER_SIZE - ZipCommon::HEADER_SIZE);
ZipCommon::HostSystem hs = ZipCommon::HS_FAT;
#if (POCO_OS == POCO_OS_CYGWIN)
hs = ZipCommon::HS_UNIX;
#endif
#if (POCO_OS == POCO_OS_VMS)
hs = ZipCommon::HS_VMS;
#endif
#if defined(POCO_OS_FAMILY_UNIX)
hs = ZipCommon::HS_UNIX;
#endif
setHostSystem(hs);
setEncryption(false);
setExtraFieldSize(0);
setLastModifiedAt(lastModifiedAt);
init(fileName, cm, cl);
}
ZipLocalFileHeader::ZipLocalFileHeader(std::istream& inp, bool assumeHeaderRead, ParseCallback& callback):
_rawHeader(),
_startPos(inp.tellg()),
_endPos(-1),
_fileName(),
_lastModifiedAt(),
_extraField(),
_crc32(0),
_compressedSize(0),
_uncompressedSize(0)
{
poco_assert_dbg( (EXTRAFIELD_POS+EXTRAFIELD_LENGTH) == FULLHEADER_SIZE);
if (assumeHeaderRead)
_startPos -= ZipCommon::HEADER_SIZE;
parse(inp, assumeHeaderRead);
bool ok = callback.handleZipEntry(inp, *this);
if (ok)
{
if (searchCRCAndSizesAfterData())
{
ZipDataInfo nfo(inp, false);
setCRC(nfo.getCRC32());
setCompressedSize(nfo.getCompressedSize());
setUncompressedSize(nfo.getUncompressedSize());
}
}
else
{
poco_assert_dbg(!searchCRCAndSizesAfterData());
ZipUtil::sync(inp);
}
_endPos = _startPos + getHeaderSize() + _compressedSize; // exclude the data block!
}
ZipLocalFileHeader::~ZipLocalFileHeader()
{
}
void ZipLocalFileHeader::parse(std::istream& inp, bool assumeHeaderRead)
{
if (!assumeHeaderRead)
{
inp.read(_rawHeader, ZipCommon::HEADER_SIZE);
}
else
{
std::memcpy(_rawHeader, HEADER, ZipCommon::HEADER_SIZE);
}
poco_assert (std::memcmp(_rawHeader, HEADER, ZipCommon::HEADER_SIZE) == 0);
// read the rest of the header
inp.read(_rawHeader + ZipCommon::HEADER_SIZE, FULLHEADER_SIZE - ZipCommon::HEADER_SIZE);
if (!(_rawHeader[VERSION_POS + 1]>= ZipCommon::HS_FAT && _rawHeader[VERSION_POS + 1] < ZipCommon::HS_UNUSED))
throw Poco::DataFormatException("bad ZIP file header", "invalid version");
if (ZipUtil::get16BitValue(_rawHeader, COMPR_METHOD_POS) >= ZipCommon::CM_UNUSED)
throw Poco::DataFormatException("bad ZIP file header", "invalid compression method");
parseDateTime();
Poco::UInt16 len = getFileNameLength();
Poco::Buffer<char> buf(len);
inp.read(buf.begin(), len);
_fileName = std::string(buf.begin(), len);
if (hasExtraField())
{
len = getExtraFieldLength();
Poco::Buffer<char> xtra(len);
inp.read(xtra.begin(), len);
_extraField = std::string(xtra.begin(), len);
}
if (!searchCRCAndSizesAfterData())
{
_crc32 = getCRCFromHeader();
_compressedSize = getCompressedSizeFromHeader();
_uncompressedSize = getUncompressedSizeFromHeader();
}
}
bool ZipLocalFileHeader::searchCRCAndSizesAfterData() const
{
if (getCompressionMethod() == ZipCommon::CM_DEFLATE)
{
// check bit 3
return ((ZipUtil::get16BitValue(_rawHeader, GENERAL_PURPOSE_POS) & 0x0008) != 0);
}
return false;
}
void ZipLocalFileHeader::setFileName(const std::string& fileName, bool isDirectory)
{
poco_assert (!fileName.empty());
Poco::Path aPath(fileName);
if (isDirectory)
{
aPath.makeDirectory();
setCRC(0);
setCompressedSize(0);
setUncompressedSize(0);
setCompressionMethod(ZipCommon::CM_STORE);
setCompressionLevel(ZipCommon::CL_NORMAL);
}
else
{
aPath.makeFile();
}
_fileName = aPath.toString(Poco::Path::PATH_UNIX);
if (_fileName[0] == '/')
_fileName = _fileName.substr(1);
if (isDirectory)
{
poco_assert_dbg (_fileName[_fileName.size()-1] == '/');
}
setFileNameLength(static_cast<Poco::UInt16>(_fileName.size()));
}
void ZipLocalFileHeader::init( const Poco::Path& fName,
ZipCommon::CompressionMethod cm,
ZipCommon::CompressionLevel cl)
{
poco_assert (_fileName.empty());
setSearchCRCAndSizesAfterData(false);
Poco::Path fileName(fName);
fileName.setDevice(""); // clear device!
setFileName(fileName.toString(Poco::Path::PATH_UNIX), fileName.isDirectory());
setRequiredVersion(2, 0);
if (fileName.isFile())
{
setCompressionMethod(cm);
setCompressionLevel(cl);
}
else
setCompressionMethod(ZipCommon::CM_STORE);
}
std::string ZipLocalFileHeader::createHeader() const
{
std::string result(_rawHeader, FULLHEADER_SIZE);
result.append(_fileName);
result.append(_extraField);
return result;
}
} } // namespace Poco::Zip
| linuxvom/macchina.io | platform/Zip/src/ZipLocalFileHeader.cpp | C++ | apache-2.0 | 5,335 |
//= require 'lib/_raphael-2.1.4.js'
//= require 'lib/_jquery.mapael-1.1.0.js'
//= require 'lib/_world_countries-1.1.0-changed.js'
//= require 'lib/_jquery.mousewheel-3.1.12.js'
//= require 'app/_contribute'
| jyotisingh/www.go.cd | source/assets/javascripts/contribute.js | JavaScript | apache-2.0 | 208 |
/*
* Copyright 2001-2013 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalatest
import SharedHelpers._
import Matchers._
class NotifierSpec extends Spec {
object `A Notifier` {
def `should fire NoteProvided event with correct message and None in payload when using apply(message)` {
class MySuite extends FunSuite {
note("update message")
}
val suite = new MySuite()
val rep = new EventRecordingReporter()
suite.run(None, Args(rep))
val noteProvidedEvents = rep.noteProvidedEventsReceived
assert(noteProvidedEvents.length === 1)
assert(noteProvidedEvents(0).message === "update message")
assert(noteProvidedEvents(0).payload === None)
}
def `should fire NoteProvided event with correct message and payload when using apply(message, payload)` {
class MySuite extends FunSuite {
note("update message", Some("a payload"))
}
val suite = new MySuite()
val rep = new EventRecordingReporter()
suite.run(None, Args(rep))
val noteProvidedEvents = rep.noteProvidedEventsReceived
assert(noteProvidedEvents.length === 1)
assert(noteProvidedEvents(0).message === "update message")
assert(noteProvidedEvents(0).payload === Some("a payload"))
}
}
}
| travisbrown/scalatest | src/test/scala/org/scalatest/NotifierSpec.scala | Scala | apache-2.0 | 1,824 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.hadoop.security;
import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.PrivilegedExceptionAction;
import java.security.Security;
import java.util.Map;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.AuthorizeCallback;
import javax.security.sasl.RealmCallback;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import javax.security.sasl.SaslServerFactory;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RetriableException;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.ipc.Server.Connection;
import org.apache.hadoop.ipc.StandbyException;
import org.apache.hadoop.security.token.SecretManager;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A utility class for dealing with SASL on RPC server
*/
@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
@InterfaceStability.Evolving
public class SaslRpcServer {
public static final Logger LOG = LoggerFactory.getLogger(SaslRpcServer.class);
public static final String SASL_DEFAULT_REALM = "default";
private static SaslServerFactory saslFactory;
public enum QualityOfProtection {
AUTHENTICATION("auth"),
INTEGRITY("auth-int"),
PRIVACY("auth-conf");
public final String saslQop;
private QualityOfProtection(String saslQop) {
this.saslQop = saslQop;
}
public String getSaslQop() {
return saslQop;
}
}
@InterfaceAudience.Private
@InterfaceStability.Unstable
public AuthMethod authMethod;
public String mechanism;
public String protocol;
public String serverId;
@InterfaceAudience.Private
@InterfaceStability.Unstable
public SaslRpcServer(AuthMethod authMethod) throws IOException {
this.authMethod = authMethod;
mechanism = authMethod.getMechanismName();
switch (authMethod) {
case SIMPLE: {
return; // no sasl for simple
}
case TOKEN: {
protocol = "";
serverId = SaslRpcServer.SASL_DEFAULT_REALM;
break;
}
case KERBEROS: {
String fullName = UserGroupInformation.getCurrentUser().getUserName();
if (LOG.isDebugEnabled())
LOG.debug("Kerberos principal name is " + fullName);
// don't use KerberosName because we don't want auth_to_local
String[] parts = fullName.split("[/@]", 3);
protocol = parts[0];
// should verify service host is present here rather than in create()
// but lazy tests are using a UGI that isn't a SPN...
serverId = (parts.length < 2) ? "" : parts[1];
break;
}
default:
// we should never be able to get here
throw new AccessControlException(
"Server does not support SASL " + authMethod);
}
}
@InterfaceAudience.Private
@InterfaceStability.Unstable
public SaslServer create(final Connection connection,
final Map<String,?> saslProperties,
SecretManager<TokenIdentifier> secretManager
) throws IOException, InterruptedException {
UserGroupInformation ugi = null;
final CallbackHandler callback;
switch (authMethod) {
case TOKEN: {
callback = new SaslDigestCallbackHandler(secretManager, connection);
break;
}
case KERBEROS: {
ugi = UserGroupInformation.getCurrentUser();
if (serverId.isEmpty()) {
throw new AccessControlException(
"Kerberos principal name does NOT have the expected "
+ "hostname part: " + ugi.getUserName());
}
callback = new SaslGssCallbackHandler();
break;
}
default:
// we should never be able to get here
throw new AccessControlException(
"Server does not support SASL " + authMethod);
}
final SaslServer saslServer;
if (ugi != null) {
saslServer = ugi.doAs(
new PrivilegedExceptionAction<SaslServer>() {
@Override
public SaslServer run() throws SaslException {
return saslFactory.createSaslServer(mechanism, protocol, serverId,
saslProperties, callback);
}
});
} else {
saslServer = saslFactory.createSaslServer(mechanism, protocol, serverId,
saslProperties, callback);
}
if (saslServer == null) {
throw new AccessControlException(
"Unable to find SASL server implementation for " + mechanism);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Created SASL server with mechanism = " + mechanism);
}
return saslServer;
}
public static void init(Configuration conf) {
if (saslFactory == null) {
Security.addProvider(new SaslPlainServer.SecurityProvider());
// passing null so factory is populated with all possibilities. the
// properties passed when instantiating a server are what really matter
saslFactory = new FastSaslServerFactory(null);
}
}
static String encodeIdentifier(byte[] identifier) {
return new String(Base64.encodeBase64(identifier), StandardCharsets.UTF_8);
}
static byte[] decodeIdentifier(String identifier) {
return Base64.decodeBase64(identifier.getBytes(StandardCharsets.UTF_8));
}
public static <T extends TokenIdentifier> T getIdentifier(String id,
SecretManager<T> secretManager) throws InvalidToken {
byte[] tokenId = decodeIdentifier(id);
T tokenIdentifier = secretManager.createIdentifier();
try {
tokenIdentifier.readFields(new DataInputStream(new ByteArrayInputStream(
tokenId)));
} catch (IOException e) {
throw (InvalidToken) new InvalidToken(
"Can't de-serialize tokenIdentifier").initCause(e);
}
return tokenIdentifier;
}
static char[] encodePassword(byte[] password) {
return new String(Base64.encodeBase64(password),
StandardCharsets.UTF_8).toCharArray();
}
/** Splitting fully qualified Kerberos name into parts */
public static String[] splitKerberosName(String fullName) {
return fullName.split("[/@]");
}
/** Authentication method */
@InterfaceStability.Evolving
public enum AuthMethod {
SIMPLE((byte) 80, ""),
KERBEROS((byte) 81, "GSSAPI"),
@Deprecated
DIGEST((byte) 82, "DIGEST-MD5"),
TOKEN((byte) 82, "DIGEST-MD5"),
PLAIN((byte) 83, "PLAIN");
/** The code for this method. */
public final byte code;
public final String mechanismName;
private AuthMethod(byte code, String mechanismName) {
this.code = code;
this.mechanismName = mechanismName;
}
private static final int FIRST_CODE = values()[0].code;
/** Return the object represented by the code. */
private static AuthMethod valueOf(byte code) {
final int i = (code & 0xff) - FIRST_CODE;
return i < 0 || i >= values().length ? null : values()[i];
}
/** Return the SASL mechanism name */
public String getMechanismName() {
return mechanismName;
}
/** Read from in */
public static AuthMethod read(DataInput in) throws IOException {
return valueOf(in.readByte());
}
/** Write to out */
public void write(DataOutput out) throws IOException {
out.write(code);
}
};
/** CallbackHandler for SASL DIGEST-MD5 mechanism */
@InterfaceStability.Evolving
public static class SaslDigestCallbackHandler implements CallbackHandler {
private SecretManager<TokenIdentifier> secretManager;
private Server.Connection connection;
public SaslDigestCallbackHandler(
SecretManager<TokenIdentifier> secretManager,
Server.Connection connection) {
this.secretManager = secretManager;
this.connection = connection;
}
private char[] getPassword(TokenIdentifier tokenid) throws InvalidToken,
StandbyException, RetriableException, IOException {
return encodePassword(secretManager.retriableRetrievePassword(tokenid));
}
@Override
public void handle(Callback[] callbacks) throws InvalidToken,
UnsupportedCallbackException, StandbyException, RetriableException,
IOException {
NameCallback nc = null;
PasswordCallback pc = null;
AuthorizeCallback ac = null;
for (Callback callback : callbacks) {
if (callback instanceof AuthorizeCallback) {
ac = (AuthorizeCallback) callback;
} else if (callback instanceof NameCallback) {
nc = (NameCallback) callback;
} else if (callback instanceof PasswordCallback) {
pc = (PasswordCallback) callback;
} else if (callback instanceof RealmCallback) {
continue; // realm is ignored
} else {
throw new UnsupportedCallbackException(callback,
"Unrecognized SASL DIGEST-MD5 Callback");
}
}
if (pc != null) {
TokenIdentifier tokenIdentifier = getIdentifier(nc.getDefaultName(),
secretManager);
char[] password = getPassword(tokenIdentifier);
UserGroupInformation user = null;
user = tokenIdentifier.getUser(); // may throw exception
connection.attemptingUser = user;
if (LOG.isDebugEnabled()) {
LOG.debug("SASL server DIGEST-MD5 callback: setting password "
+ "for client: " + tokenIdentifier.getUser());
}
pc.setPassword(password);
}
if (ac != null) {
String authid = ac.getAuthenticationID();
String authzid = ac.getAuthorizationID();
if (authid.equals(authzid)) {
ac.setAuthorized(true);
} else {
ac.setAuthorized(false);
}
if (ac.isAuthorized()) {
if (LOG.isDebugEnabled()) {
UserGroupInformation logUser =
getIdentifier(authzid, secretManager).getUser();
String username = logUser == null ? null : logUser.getUserName();
LOG.debug("SASL server DIGEST-MD5 callback: setting "
+ "canonicalized client ID: " + username);
}
ac.setAuthorizedID(authzid);
}
}
}
}
/** CallbackHandler for SASL GSSAPI Kerberos mechanism */
@InterfaceStability.Evolving
public static class SaslGssCallbackHandler implements CallbackHandler {
@Override
public void handle(Callback[] callbacks) throws
UnsupportedCallbackException {
AuthorizeCallback ac = null;
for (Callback callback : callbacks) {
if (callback instanceof AuthorizeCallback) {
ac = (AuthorizeCallback) callback;
} else {
throw new UnsupportedCallbackException(callback,
"Unrecognized SASL GSSAPI Callback");
}
}
if (ac != null) {
String authid = ac.getAuthenticationID();
String authzid = ac.getAuthorizationID();
if (authid.equals(authzid)) {
ac.setAuthorized(true);
} else {
ac.setAuthorized(false);
}
if (ac.isAuthorized()) {
if (LOG.isDebugEnabled())
LOG.debug("SASL server GSSAPI callback: setting "
+ "canonicalized client ID: " + authzid);
ac.setAuthorizedID(authzid);
}
}
}
}
}
| apurtell/hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/SaslRpcServer.java | Java | apache-2.0 | 12,745 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>org.apache.jmeter.modifiers.gui Class Hierarchy (Apache JMeter API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.jmeter.modifiers.gui Class Hierarchy (Apache JMeter API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Apache JMeter</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/jmeter/modifiers/package-tree.html">Prev</a></li>
<li><a href="../../../../../org/apache/jmeter/monitor/model/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/jmeter/modifiers/gui/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.apache.jmeter.modifiers.gui</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="strong">Object</span></a>
<ul>
<li type="circle">java.awt.<a href="http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html?is-external=true" title="class or interface in java.awt"><span class="strong">Component</span></a> (implements java.awt.image.<a href="http://docs.oracle.com/javase/7/docs/api/java/awt/image/ImageObserver.html?is-external=true" title="class or interface in java.awt.image">ImageObserver</a>, java.awt.<a href="http://docs.oracle.com/javase/7/docs/api/java/awt/MenuContainer.html?is-external=true" title="class or interface in java.awt">MenuContainer</a>, java.io.<a href="http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>)
<ul>
<li type="circle">java.awt.<a href="http://docs.oracle.com/javase/7/docs/api/java/awt/Container.html?is-external=true" title="class or interface in java.awt"><span class="strong">Container</span></a>
<ul>
<li type="circle">javax.swing.<a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html?is-external=true" title="class or interface in javax.swing"><span class="strong">JComponent</span></a> (implements java.io.<a href="http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>)
<ul>
<li type="circle">javax.swing.<a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JPanel.html?is-external=true" title="class or interface in javax.swing"><span class="strong">JPanel</span></a> (implements javax.accessibility.<a href="http://docs.oracle.com/javase/7/docs/api/javax/accessibility/Accessible.html?is-external=true" title="class or interface in javax.accessibility">Accessible</a>)
<ul>
<li type="circle">org.apache.jmeter.gui.<a href="../../../../../org/apache/jmeter/gui/AbstractJMeterGuiComponent.html" title="class in org.apache.jmeter.gui"><span class="strong">AbstractJMeterGuiComponent</span></a> (implements org.apache.jmeter.gui.<a href="../../../../../org/apache/jmeter/gui/JMeterGUIComponent.html" title="interface in org.apache.jmeter.gui">JMeterGUIComponent</a>, org.apache.jmeter.visualizers.<a href="../../../../../org/apache/jmeter/visualizers/Printable.html" title="interface in org.apache.jmeter.visualizers">Printable</a>)
<ul>
<li type="circle">org.apache.jmeter.config.gui.<a href="../../../../../org/apache/jmeter/config/gui/AbstractConfigGui.html" title="class in org.apache.jmeter.config.gui"><span class="strong">AbstractConfigGui</span></a>
<ul>
<li type="circle">org.apache.jmeter.modifiers.gui.<a href="../../../../../org/apache/jmeter/modifiers/gui/CounterConfigGui.html" title="class in org.apache.jmeter.modifiers.gui"><span class="strong">CounterConfigGui</span></a> (implements java.awt.event.<a href="http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html?is-external=true" title="class or interface in java.awt.event">ActionListener</a>)</li>
</ul>
</li>
<li type="circle">org.apache.jmeter.processor.gui.<a href="../../../../../org/apache/jmeter/processor/gui/AbstractPreProcessorGui.html" title="class in org.apache.jmeter.processor.gui"><span class="strong">AbstractPreProcessorGui</span></a>
<ul>
<li type="circle">org.apache.jmeter.modifiers.gui.<a href="../../../../../org/apache/jmeter/modifiers/gui/SampleTimeoutGui.html" title="class in org.apache.jmeter.modifiers.gui"><span class="strong">SampleTimeoutGui</span></a></li>
<li type="circle">org.apache.jmeter.modifiers.gui.<a href="../../../../../org/apache/jmeter/modifiers/gui/UserParametersGui.html" title="class in org.apache.jmeter.modifiers.gui"><span class="strong">UserParametersGui</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Apache JMeter</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/jmeter/modifiers/package-tree.html">Prev</a></li>
<li><a href="../../../../../org/apache/jmeter/monitor/model/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/jmeter/modifiers/gui/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 1998-2016 Apache Software Foundation. All Rights Reserved.</small></p>
</body>
</html>
| shareactorIO/pipeline | oreilly.ml/high-performance-tensorflow/apache-jmeter-3.1/docs/api/org/apache/jmeter/modifiers/gui/package-tree.html | HTML | apache-2.0 | 8,298 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.qa.sql.nosecurity;
import org.elasticsearch.xpack.qa.sql.cli.SelectTestCase;
public class CliSelectIT extends SelectTestCase {
}
| gfyoung/elasticsearch | x-pack/qa/sql/no-security/src/test/java/org/elasticsearch/xpack/qa/sql/nosecurity/CliSelectIT.java | Java | apache-2.0 | 405 |
/****************************************************************************
*
* Copyright 2016 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
/// @file tc_libc_pthread.c
/// @brief Test Case Example for Libc Pthread API
/****************************************************************************
* Included Files
****************************************************************************/
#include <tinyara/config.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <sched.h>
#include <string.h>
#include <sys/types.h>
#include <tinyara/pthread.h>
#include "tc_internal.h"
/****************************************************************************
* Definitions
****************************************************************************/
#define STACKSIZE PTHREAD_STACK_DEFAULT
#define PRIORITY PTHREAD_DEFAULT_PRIORITY
#define POLICY PTHREAD_DEFAULT_POLICY
#define INHERITSCHED PTHREAD_EXPLICIT_SCHED
#define PTHREAD_PRIO_INVALID -1
/****************************************************************************
* Global Variables
****************************************************************************/
struct race_cond_s {
sem_t *sem1;
sem_t *sem2;
pthread_rwlock_t *rw_lock;
};
/****************************************************************************
* Public Functions
**************************************************************************/
static int g_race_cond_thread_pos;
/****************************************************************************
* Private Functions
****************************************************************************/
/**
* @fn :tc_libc_pthread_pthread_attr_init
* @brief :This tc tests pthread_attr_init()
* @Scenario :If pthread_attr is NULL, ENOMEM is returned.
* Else, it return OK and pthread_attr is set to default value
* @API'scovered :pthread_attr_init
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_attr_init(void)
{
pthread_attr_t attr;
int ret_chk;
ret_chk = pthread_attr_init(NULL);
TC_ASSERT_EQ("pthread_attr_init", ret_chk, ENOMEM);
ret_chk = pthread_attr_init(&attr);
TC_ASSERT_EQ("pthread_attr_init", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_init", attr.stacksize, PTHREAD_STACK_DEFAULT);
TC_ASSERT_EQ("pthread_attr_init", attr.priority, PTHREAD_DEFAULT_PRIORITY);
TC_ASSERT_EQ("pthread_attr_init", attr.policy, PTHREAD_DEFAULT_POLICY);
TC_ASSERT_EQ("pthread_attr_init", attr.inheritsched, PTHREAD_EXPLICIT_SCHED);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_attr_destroy
* @brief :This tc tests pthread_attr_destroy()
* @Scenario :If pthread_attr is NULL, EINVAL is returned.
* Else, it return OK and pthread_attr is set to zero
* @API'scovered :pthread_attr_destroy
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_attr_destroy(void)
{
pthread_attr_t attr;
pthread_attr_t destroyed_attr;
int ret_chk;
memset(&destroyed_attr, 0, sizeof(pthread_attr_t));
ret_chk = pthread_attr_destroy(NULL);
TC_ASSERT_EQ("pthread_attr_destroy", ret_chk, EINVAL);
ret_chk = pthread_attr_destroy(&attr);
TC_ASSERT_EQ("pthread_attr_destroy", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_destroy", memcmp(&attr, &destroyed_attr, sizeof(pthread_attr_t)), 0);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_attr_getstacksize
* @brief :This tc tests pthread_attr_getstacksize()
* @Scenario :If pthread_attr or stacksize parameter is NULL, EINVAL is returned.
* Else, it return OK and stacksize is set to the stack size of pthread_attr
* @API'scovered :pthread_attr_getstacksize
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_attr_getstacksize(void)
{
pthread_attr_t attr;
long stacksize;
int ret_chk;
attr.stacksize = STACKSIZE;
ret_chk = pthread_attr_getstacksize(NULL, &stacksize);
TC_ASSERT_EQ("pthread_attr_getstacksize", ret_chk, EINVAL);
ret_chk = pthread_attr_getstacksize(&attr, NULL);
TC_ASSERT_EQ("pthread_attr_getstacksize", ret_chk, EINVAL);
ret_chk = pthread_attr_getstacksize(&attr, &stacksize);
TC_ASSERT_EQ("pthread_attr_getstacksize", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_getstacksize", stacksize, attr.stacksize);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_attr_setstacksize
* @brief :This tc tests pthread_attr_setstacksize()
* @Scenario :If pthread_attr is NULL or stacksize is under PTHREAD_STACK_MIN , EINVAL is returned.
* Else, it return OK and stacksize of pthread_attr is set to stacksize parameter.
* @API'scovered :pthread_attr_setstacksize
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_attr_setstacksize(void)
{
pthread_attr_t attr;
long stacksize = STACKSIZE;
int ret_chk;
ret_chk = pthread_attr_setstacksize(NULL, stacksize);
TC_ASSERT_EQ("pthread_attr_setstacksize", ret_chk, EINVAL);
ret_chk = pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN - 1);
TC_ASSERT_EQ("pthread_attr_setstacksize", ret_chk, EINVAL);
ret_chk = pthread_attr_setstacksize(&attr, stacksize);
TC_ASSERT_EQ("pthread_attr_setstacksize", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_setstacksize", attr.stacksize, stacksize);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_attr_getschedparam
* @brief :This tc tests pthread_attr_getschedparam()
* @Scenario :If pthread_attr or sched_param parameter is NULL, EINVAL is returned.
* Else, it return OK and sched_priority of sched_param is set to the priority of pthread_attr
* @API'scovered :pthread_attr_getschedparam
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_attr_getschedparam(void)
{
pthread_attr_t attr;
struct sched_param param;
int ret_chk;
attr.priority = PRIORITY;
ret_chk = pthread_attr_getschedparam(NULL, ¶m);
TC_ASSERT_EQ("pthread_attr_getschedparam", ret_chk, EINVAL);
ret_chk = pthread_attr_getschedparam(&attr, NULL);
TC_ASSERT_EQ("pthread_attr_getschedparam", ret_chk, EINVAL);
ret_chk = pthread_attr_getschedparam(&attr, ¶m);
TC_ASSERT_EQ("pthread_attr_getschedparam", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_getschedparam", param.sched_priority, attr.priority);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_attr_setschedparam
* @brief :This tc tests pthread_attr_setschedparam()
* @Scenario :If pthread_attr or sched_param parameter is NULL, EINVAL is returned.
* Else, it return OK and sched_priority of sched_param is set to the priority of pthread_attr
* @API'scovered :pthread_attr_setschedparam
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_attr_setschedparam(void)
{
pthread_attr_t attr;
struct sched_param param;
int ret_chk;
param.sched_priority = PRIORITY;
ret_chk = pthread_attr_setschedparam(NULL, ¶m);
TC_ASSERT_EQ("pthread_attr_setschedparam", ret_chk, EINVAL);
ret_chk = pthread_attr_setschedparam(&attr, NULL);
TC_ASSERT_EQ("pthread_attr_setschedparam", ret_chk, EINVAL);
ret_chk = pthread_attr_setschedparam(&attr, ¶m);
TC_ASSERT_EQ("pthread_attr_setschedparam", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_setschedparam", attr.priority, param.sched_priority);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_attr_getschedpolicy
* @brief :This tc tests pthread_attr_getschedpolicy()
* @Scenario :If pthread_attr or policy is NULL, EINVAL is returned.
* Else, it return OK and policy is set to policy of pthread_attr_t
* @API'scovered :pthread_attr_getschedpolicy
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_attr_getschedpolicy(void)
{
pthread_attr_t attr;
int policy;
int ret_chk;
attr.policy = POLICY;
ret_chk = pthread_attr_getschedpolicy(NULL, &policy);
TC_ASSERT_EQ("pthread_attr_getschedpolicy", ret_chk, EINVAL);
ret_chk = pthread_attr_getschedpolicy(&attr, NULL);
TC_ASSERT_EQ("pthread_attr_getschedpolicy", ret_chk, EINVAL);
ret_chk = pthread_attr_getschedpolicy(&attr, &policy);
TC_ASSERT_EQ("pthread_attr_getschedpolicy", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_getschedpolicy", policy, attr.policy);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_attr_setschedpolicy
* @brief :This tc tests pthread_attr_setschedpolicy()
* @Scenario :If pthread_attr is NULL or policy parameter is invalid, EINVAL is returned.
* Else, it return OK and inheritsched of pthread_attr is set to inheritsched
* @API'scovered :pthread_attr_setschedpolicy
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_attr_setschedpolicy(void)
{
pthread_attr_t attr;
int policy;
int ret_chk;
policy = SCHED_FIFO;
ret_chk = pthread_attr_setschedpolicy(NULL, policy);
TC_ASSERT_EQ("pthread_attr_setschedpolicy", ret_chk, EINVAL);
policy = -1;
ret_chk = pthread_attr_setschedpolicy(&attr, policy);
TC_ASSERT_EQ("pthread_attr_setschedpolicy", ret_chk, EINVAL);
policy = SCHED_FIFO;
ret_chk = pthread_attr_setschedpolicy(&attr, policy);
TC_ASSERT_EQ("pthread_attr_setschedpolicy", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_setschedpolicy", attr.policy, policy);
policy = SCHED_RR;
ret_chk = pthread_attr_setschedpolicy(&attr, policy);
#if CONFIG_RR_INTERVAL > 0
TC_ASSERT_EQ("pthread_attr_setschedpolicy", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_setschedpolicy", attr.policy, policy);
#else
TC_ASSERT_EQ("pthread_attr_setschedpolicy", ret_chk, EINVAL);
#endif
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_attr_getinheritsched
* @brief :This tc tests pthread_attr_getinheritsched()
* @Scenario :If pthread_attr or inheritsched is NULL, EINVAL is returned.
* Else, it return OK and inheritsched is set to inheritsched of pthread_attr_t
* @API'scovered :pthread_attr_getinheritsched
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_attr_getinheritsched(void)
{
pthread_attr_t attr;
int inheritsched;
int ret_chk;
attr.inheritsched = INHERITSCHED;
ret_chk = pthread_attr_getinheritsched(NULL, &inheritsched);
TC_ASSERT_EQ("pthread_attr_getinheritsched", ret_chk, EINVAL);
ret_chk = pthread_attr_getinheritsched(&attr, NULL);
TC_ASSERT_EQ("pthread_attr_getinheritsched", ret_chk, EINVAL);
ret_chk = pthread_attr_getinheritsched(&attr, &inheritsched);
TC_ASSERT_EQ("pthread_attr_getinheritsched", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_getinheritsched", inheritsched, attr.inheritsched);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_attr_setinheritsched
* @brief :This tc tests pthread_attr_setinheritsched()
* @Scenario :If pthread_attr is NULL or inheritsched parameter is invalid, EINVAL is returned.
* Else, it return OK and inheritsched of pthread_attr is set to inheritsched
* @API'scovered :pthread_attr_setinheritsched
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_attr_setinheritsched(void)
{
pthread_attr_t attr;
int inheritsched;
int ret_chk;
inheritsched = PTHREAD_INHERIT_SCHED;
ret_chk = pthread_attr_setinheritsched(NULL, inheritsched);
TC_ASSERT_EQ("pthread_attr_setschedparam", ret_chk, EINVAL);
inheritsched = -1;
ret_chk = pthread_attr_setinheritsched(&attr, inheritsched);
TC_ASSERT_EQ("pthread_attr_setschedparam", ret_chk, EINVAL);
inheritsched = PTHREAD_INHERIT_SCHED;
ret_chk = pthread_attr_setinheritsched(&attr, inheritsched);
TC_ASSERT_EQ("pthread_attr_setschedparam", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_setschedparam", attr.inheritsched, inheritsched);
inheritsched = PTHREAD_EXPLICIT_SCHED;
ret_chk = pthread_attr_setinheritsched(&attr, inheritsched);
TC_ASSERT_EQ("pthread_attr_setschedparam", ret_chk, OK);
TC_ASSERT_EQ("pthread_attr_setschedparam", attr.inheritsched, inheritsched);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_barrierattr_init
* @brief :This tc tests pthread_barrierattr_init()
* @Scenario :If pthread_barrierattr is NULL, EINVAL is returned.
* Else, it return OK and pthread_barrierattr is set to default value
* @API'scovered :pthread_barrierattr_init
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_barrierattr_init(void)
{
pthread_barrierattr_t attr;
int ret_chk;
ret_chk = pthread_barrierattr_init(NULL);
TC_ASSERT_EQ("pthread_barrierattr_init", ret_chk, EINVAL);
ret_chk = pthread_barrierattr_init(&attr);
TC_ASSERT_EQ("pthread_barrierattr_init", ret_chk, OK);
TC_ASSERT_EQ("pthread_barrierattr_init", attr.pshared, PTHREAD_PROCESS_PRIVATE);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_barrierattr_destroy
* @brief :This tc tests pthread_barrierattr_destroy()
* @Scenario :If pthread_barrierattr_destroy is NULL, EINVAL is returned.
* Else, it return OK and pthread_barrierattr is set to default value
* @API'scovered :pthread_barrierattr_destroy
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_barrierattr_destroy(void)
{
pthread_barrierattr_t attr;
int ret_chk;
ret_chk = pthread_barrierattr_destroy(NULL);
TC_ASSERT_EQ("pthread_barrierattr_destroy", ret_chk, EINVAL);
ret_chk = pthread_barrierattr_destroy(&attr);
TC_ASSERT_EQ("pthread_barrierattr_destroy", ret_chk, OK);
TC_ASSERT_EQ("pthread_barrierattr_destroy", attr.pshared, PTHREAD_PROCESS_PRIVATE);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_barrierattr_getpshared
* @brief :This tc tests pthread_barrierattr_getpshared()
* @Scenario :If pthread_barrierattr or psahred is NULL, EINVAL is returned.
* Else, it return OK and pshared is set to psahred of pthread_barrierattr
* @API'scovered :pthread_barrierattr_getpshared
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_barrierattr_getpshared(void)
{
pthread_barrierattr_t attr;
int pshared;
int ret_chk;
ret_chk = pthread_barrierattr_getpshared(NULL, &pshared);
TC_ASSERT_EQ("pthread_barrierattr_getpshared", ret_chk, EINVAL);
ret_chk = pthread_barrierattr_getpshared(&attr, NULL);
TC_ASSERT_EQ("pthread_barrierattr_getpshared", ret_chk, EINVAL);
attr.pshared = PTHREAD_PROCESS_PRIVATE;
ret_chk = pthread_barrierattr_getpshared(&attr, &pshared);
TC_ASSERT_EQ("pthread_barrierattr_getpshared", ret_chk, OK);
TC_ASSERT_EQ("pthread_barrierattr_getpshared", pshared, attr.pshared);
attr.pshared = PTHREAD_PROCESS_SHARED;
ret_chk = pthread_barrierattr_getpshared(&attr, &pshared);
TC_ASSERT_EQ("pthread_barrierattr_getpshared", ret_chk, OK);
TC_ASSERT_EQ("pthread_barrierattr_getpshared", pshared, attr.pshared);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_barrierattr_setpshared
* @brief :This tc tests pthread_attr_setinheritsched()
* @Scenario :If pthread_attr is NULL or inheritsched parameter is invalid, EINVAL is returned.
* Else, it return OK and pshared of pthread_barrierattr is set to pshared.
* @API'scovered :pthread_barrierattr_setpshared
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_barrierattr_setpshared(void)
{
pthread_barrierattr_t attr;
int pshared;
int ret_chk;
pshared = PTHREAD_PROCESS_PRIVATE;
ret_chk = pthread_barrierattr_setpshared(NULL, pshared);
TC_ASSERT_EQ("pthread_barrierattr_setpshared", ret_chk, EINVAL);
pshared = -1;
ret_chk = pthread_barrierattr_setpshared(&attr, pshared);
TC_ASSERT_EQ("pthread_barrierattr_setpshared", ret_chk, EINVAL);
pshared = PTHREAD_PROCESS_PRIVATE;
ret_chk = pthread_barrierattr_setpshared(&attr, pshared);
TC_ASSERT_EQ("pthread_barrierattr_setpshared", ret_chk, OK);
TC_ASSERT_EQ("pthread_barrierattr_setpshared", attr.pshared, pshared);
pshared = PTHREAD_PROCESS_SHARED;
ret_chk = pthread_barrierattr_setpshared(&attr, pshared);
TC_ASSERT_EQ("pthread_barrierattr_setpshared", ret_chk, OK);
TC_ASSERT_EQ("pthread_barrierattr_setpshared", attr.pshared, pshared);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_condattr_init
* @brief :This tc tests pthread_condattr_init()
* @Scenario :If pthread_condattr is NULL, EINVAL is returned.
* Else, it return OK and pthread_condattr is set to 0 value
* @API'scovered :pthread_condattr_init
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_condattr_init(void)
{
pthread_condattr_t attr;
int ret_chk;
ret_chk = pthread_condattr_init(NULL);
TC_ASSERT_EQ("pthread_condattr_init", ret_chk, EINVAL);
ret_chk = pthread_condattr_init(&attr);
TC_ASSERT_EQ("pthread_condattr_init", ret_chk, OK);
TC_ASSERT_EQ("pthread_condattr_init", attr, 0);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_condattr_destroy
* @brief :This tc tests pthread_condattr_destroy()
* @Scenario :If pthread_condattr_destroy is NULL, EINVAL is returned.
* Else, it return OK
* @API'scovered :pthread_condattr_destroy
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_condattr_destroy(void)
{
pthread_condattr_t attr;
int ret_chk;
ret_chk = pthread_condattr_destroy(NULL);
TC_ASSERT_EQ("pthread_condattr_destroy", ret_chk, EINVAL);
ret_chk = pthread_condattr_destroy(&attr);
TC_ASSERT_EQ("pthread_condattr_destroy", ret_chk, OK);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_mutexattr_init
* @brief :This tc tests pthread_mutexattr_init()
* @Scenario :If pthread_mutexattr is NULL, EINVAL is returned.
* Else, it return OK and pthread_mutexattr is set to default value
* @API'scovered :pthread_mutexattr_init
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_mutexattr_init(void)
{
pthread_mutexattr_t attr;
int ret_chk;
ret_chk = pthread_mutexattr_init(NULL);
TC_ASSERT_EQ("pthread_mutexattr_init", ret_chk, EINVAL);
ret_chk = pthread_mutexattr_init(&attr);
TC_ASSERT_EQ("pthread_mutexattr_init", ret_chk, OK);
TC_ASSERT_EQ("pthread_mutexattr_init", attr.pshared, 0);
#ifdef CONFIG_PTHREAD_MUTEX_TYPES
TC_ASSERT_EQ("pthread_mutexattr_init", attr.type, PTHREAD_MUTEX_DEFAULT);
#endif
#ifdef CONFIG_PTHREAD_MUTEX_BOTH
#ifdef CONFIG_PTHREAD_MUTEX_DEFAULT_UNSAFE
TC_ASSERT_EQ("pthread_mutexattr_init", attr.robust, PTHREAD_MUTEX_STALLED);
#else
TC_ASSERT_EQ("pthread_mutexattr_init", attr.robust, PTHREAD_MUTEX_ROBUST);
#endif
#endif
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_mutexattr_destroy
* @brief :This tc tests pthread_mutexattr_destroy()
* @Scenario :If pthread_condattr_destroy is NULL, EINVAL is returned.
* Else, it return OK
* @API'scovered :pthread_mutexattr_destroy
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_mutexattr_destroy(void)
{
pthread_mutexattr_t attr;
int ret_chk;
ret_chk = pthread_mutexattr_destroy(NULL);
TC_ASSERT_EQ("pthread_mutexattr_destroy", ret_chk, EINVAL);
ret_chk = pthread_mutexattr_destroy(&attr);
TC_ASSERT_EQ("pthread_mutexattr_destroy", ret_chk, OK);
TC_ASSERT_EQ("pthread_mutexattr_destroy", attr.pshared, 0);
TC_SUCCESS_RESULT();
return;
}
/**
* @fn :tc_libc_pthread_pthread_mutexattr_getpshared
* @brief :This tc tests pthread_mutexattr_getpshared()
* @Scenario :Get and check the pthread_mutexattr's pshared value
* with proper and not-proper parameter
* @API'scovered :pthread_mutexattr_getpshared
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_mutexattr_getpshared(void)
{
int ret_chk;
pthread_mutexattr_t attr;
int mutexattr_pshared;
ret_chk = pthread_mutexattr_init(&attr);
TC_ASSERT_EQ("pthread_mutexattr_init", ret_chk, OK);
ret_chk = pthread_mutexattr_getpshared(NULL, 0);
TC_ASSERT_EQ("pthread_mutexattr_getpshared", ret_chk, EINVAL);
ret_chk = pthread_mutexattr_getpshared(&attr, &mutexattr_pshared);
TC_ASSERT_EQ("pthread_mutexattr_getpshared", ret_chk, OK);
TC_ASSERT_EQ("pthread_mutexattr_getpshared", mutexattr_pshared, 0);
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_mutexattr_setpshared
* @brief :This tc tests pthread_mutexattr_setpshared()
* @Scenario :Set and check the pthread_mutexattr's pshared value
* with proper and not-proper parameter
* @API'scovered :pthread_mutexattr_setpshared
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_mutexattr_setpshared(void)
{
int ret_chk;
pthread_mutexattr_t attr;
ret_chk = pthread_mutexattr_setpshared(NULL, 0);
TC_ASSERT_EQ("pthread_mutexattr_setpshared", ret_chk, EINVAL);
ret_chk = pthread_mutexattr_setpshared(&attr, 1);
TC_ASSERT_EQ("pthread_mutexattr_setpshared", ret_chk, OK);
TC_ASSERT_EQ("pthread_mutexattr_setpshared", attr.pshared, 1);
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_mutexattr_gettype
* @brief :This tc tests pthread_mutexattr_gettype()
* @Scenario :Get and check the pthread_mutexattr's type value
* with proper and not-proper parameter
* @API'scovered :pthread_mutexattr_gettype
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_mutexattr_gettype(void)
{
int ret_chk;
pthread_mutexattr_t attr;
int mutexattr_type;
ret_chk = pthread_mutexattr_init(&attr);
TC_ASSERT_EQ("pthread_mutexattr_init", ret_chk, OK);
ret_chk = pthread_mutexattr_gettype(NULL, &mutexattr_type);
TC_ASSERT_EQ("pthread_mutexattr_gettype", ret_chk, EINVAL);
ret_chk = pthread_mutexattr_gettype(&attr, &mutexattr_type);
TC_ASSERT_EQ("pthread_mutexattr_gettype", ret_chk, 0);
#ifdef CONFIG_PTHREAD_MUTEX_TYPES
TC_ASSERT_EQ("pthread_mutexattr_gettype", mutexattr_type, attr.type);
#else
TC_ASSERT_EQ("pthread_mutexattr_gettype", mutexattr_type, PTHREAD_MUTEX_NORMAL);
#endif
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_mutexattr_settype
* @brief :This tc tests pthread_mutexattr_settype()
* @Scenario :Set and check the pthread_mutexattr's type value
* with proper and not-proper parameter
* @API'scovered :pthread_mutexattr_settype
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_mutexattr_settype(void)
{
int ret_chk;
pthread_mutexattr_t attr;
ret_chk = pthread_mutexattr_settype(NULL, PTHREAD_MUTEX_NORMAL);
TC_ASSERT_EQ("pthread_mutexattr_settype", ret_chk, EINVAL);
ret_chk = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
TC_ASSERT_EQ("pthread_mutexattr_segttype", ret_chk, OK);
#ifdef CONFIG_PTHREAD_MUTEX_TYPES
TC_ASSERT_EQ("pthread_mutexattr_settype", attr.type, PTHREAD_MUTEX_NORMAL);
#else
ret_chk = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
TC_ASSERT_EQ("pthread_mutexattr_settype", ret_chk, ENOSYS);
#endif
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_mutexattr_getprotocol
* @brief :This tc tests pthread_mutexattr_getprotocol()
* @Scenario :Get and check the pthread_mutexattr's proto value
* with proper and not-proper parameter
* @API'scovered :pthread_mutexattr_getprotocol
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_mutexattr_getprotocol(void)
{
int ret_chk;
pthread_mutexattr_t attr;
int mutexattr_protocol;
ret_chk = pthread_mutexattr_init(&attr);
TC_ASSERT_EQ("pthread_mutexattr_init", ret_chk, OK);
#ifdef CONFIG_PRIORITY_INHERITANCE
attr.proto = PTHREAD_PRIO_INHERIT;
ret_chk = pthread_mutexattr_getprotocol(&attr, &mutexattr_protocol);
TC_ASSERT_EQ("pthread_mutexattr_getprotocol", ret_chk, OK);
TC_ASSERT_EQ("pthread_mutexattr_getprotocol", mutexattr_protocol, attr.proto);
#else
ret_chk = pthread_mutexattr_getprotocol(&attr, &mutexattr_protocol);
TC_ASSERT_EQ("pthread_mutexattr_getprotocol", ret_chk, OK);
#endif
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_mutexattr_setprotocol
* @brief :This tc tests pthread_mutexattr_setprotocol()
* @Scenario :Set and check the pthread_mutexattr's proto value
* with proper and not-proper parameter
* @API'scovered :pthread_mutexattr_settype
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_mutexattr_setprotocol(void)
{
int ret_chk;
pthread_mutexattr_t attr;
#ifdef CONFIG_PRIORITY_INHERITANCE
ret_chk = pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INVALID);
TC_ASSERT_EQ("pthread_mutexattr_setprotocol", ret_chk, EINVAL);
ret_chk = pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_NONE);
TC_ASSERT_EQ("pthread_mutexattr_setprotocol", ret_chk, OK);
TC_ASSERT_EQ("pthread_mutexattr_setprotocol", attr.proto, PTHREAD_PRIO_NONE);
#else
ret_chk = pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INVALID);
TC_ASSERT_EQ("pthread_mutexattr_setprotocol", ret_chk, ENOSYS);
ret_chk = pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_NONE);
TC_ASSERT_EQ("pthread_mutexattr_setprotocol", ret_chk, OK);
#endif
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_mutexattr_getrobust
* @brief :This tc tests pthread_mutexattr_getrobust()
* @Scenario :Get and check the pthread_mutexattr's robust value
* with proper and not-proper parameter
* @API'scovered :pthread_mutexattr_getrobust
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_mutexattr_getrobust(void)
{
int ret_chk;
pthread_mutexattr_t attr;
int mutexattr_robust;
ret_chk = pthread_mutexattr_init(&attr);
TC_ASSERT_EQ("pthread_mutexattr_init", ret_chk, OK);
ret_chk = pthread_mutexattr_getrobust(&attr, NULL);
TC_ASSERT_EQ("pthread_mutexattr_getrobust", ret_chk, EINVAL);
ret_chk = pthread_mutexattr_getrobust(&attr, &mutexattr_robust);
#if defined(CONFIG_PTHREAD_MUTEX_UNSAFE) || defined(CONFIG_PTHREAD_MUTEX_DEFAULT_UNSAFE)
TC_ASSERT_EQ("pthread_mutexattr_getrobust", mutexattr_robust, PTHREAD_MUTEX_STALLED);
#else
TC_ASSERT_EQ("pthread_mutexattr_getrobust", mutexattr_robust, PTHREAD_MUTEX_ROBUST);
#endif
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_mutexattr_setrobust
* @brief :This tc tests pthread_mutexattr_setrobust()
* @Scenario :Set and check the pthread_mutexattr's robust value
* with proper and not-proper parameter
* @API'scovered :pthread_mutexattr_setrobust
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_mutexattr_setrobust(void)
{
int ret_chk;
pthread_mutexattr_t attr;
ret_chk = pthread_mutexattr_setrobust(NULL, PTHREAD_MUTEX_STALLED);
TC_ASSERT_EQ("pthread_mutexattr_setrobust", ret_chk, EINVAL);
#ifdef CONFIG_PTHREAD_MUTEX_UNSAFE
ret_chk = pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_STALLED);
TC_ASSERT_EQ("pthread_mutexattr_setrobust", ret_chk, OK);
#elif defined(CONFIG_PTHREAD_MUTEX_BOTH)
ret_chk = pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_STALLED);
TC_ASSERT_EQ("pthread_mutexattr_setrobust", attr.robust, PTHREAD_MUTEX_STALLED);
#else
ret_chk = pthread_mutexattr_setrobust(&attr, _PTHREAD_MFLAGS_ROBUST);
TC_ASSERT_EQ("pthread_mutexattr_setrobust", ret_chk, OK);
#endif
TC_SUCCESS_RESULT();
}
/****************************************************************************
* Name: Test Case API's for libc_pthread_rwlock
****************************************************************************/
static void *race_cond_thread1(void *data)
{
// Runs 1st
int status;
struct race_cond_s *rc = (struct race_cond_s *)data;
TC_ASSERT_EQ_RETURN("race_cond_thread1", g_race_cond_thread_pos++, OK, NULL);
status = pthread_rwlock_wrlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_wrlock", status, OK, NULL);
sem_post(rc->sem2);
sem_wait(rc->sem1);
// Context Switch -> Runs 3rd
TC_ASSERT_EQ_RETURN("race_cond_thread1", g_race_cond_thread_pos++, 2, NULL);
status = pthread_rwlock_unlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_unlock", status, OK, NULL);
status = pthread_rwlock_rdlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_rdlock", status, OK, NULL);
sem_wait(rc->sem1);
// Context Switch - Runs 5th
TC_ASSERT_EQ_RETURN("race_cond_thread1", g_race_cond_thread_pos++, 4, NULL);
status = pthread_rwlock_unlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_unlock", status, OK, NULL);
status = pthread_rwlock_rdlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_rdlock", status, OK, NULL);
sem_post(rc->sem2);
sem_wait(rc->sem1);
/* Context switch - Runs 7th */
TC_ASSERT_EQ_RETURN("race_cond_thread1", g_race_cond_thread_pos++, 6, NULL);
status = pthread_rwlock_unlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_unlock", status, OK, NULL);
return NULL;
}
static void *race_cond_thread2(void *data)
{
int status;
struct race_cond_s *rc = (struct race_cond_s *)data;
status = sem_wait(rc->sem2);
// Runs 2nd
TC_ASSERT_EQ_RETURN("sem_wait", status, OK, NULL);
TC_ASSERT_EQ_RETURN("race_cond_thread2", g_race_cond_thread_pos++, 1, NULL);
status = pthread_rwlock_tryrdlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_tryrdlock", status, EBUSY, NULL);
status = pthread_rwlock_trywrlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_trywrlock", status, EBUSY, NULL);
sem_post(rc->sem1);
status = pthread_rwlock_rdlock(rc->rw_lock);
// Context - Switch Runs 4th
TC_ASSERT_EQ_RETURN("pthread_rwlock_rdlock", status, OK, NULL);
TC_ASSERT_EQ_RETURN("race_cond_thread2", g_race_cond_thread_pos++, 3, NULL);
status = pthread_rwlock_unlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_unlock", status, OK, NULL);
sem_post(rc->sem1);
sem_wait(rc->sem2);
/* Context switch Runs 6th */
TC_ASSERT_EQ_RETURN("race_cond_thread2", g_race_cond_thread_pos++, 5, NULL);
sem_post(rc->sem1);
status = pthread_rwlock_wrlock(rc->rw_lock);
/* Context switch runs 8th */
TC_ASSERT_EQ_RETURN("pthread_rwlock_wrlock", status, OK, NULL);
TC_ASSERT_EQ_RETURN("race_cond_thread2", g_race_cond_thread_pos++, 7, NULL);
status = pthread_rwlock_unlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_unlock", status, OK, NULL);
return NULL;
}
static void test_two_threads(void)
{
pthread_t thread1;
pthread_t thread2;
int status;
pthread_rwlock_t rw_lock;
sem_t sem1;
sem_t sem2;
struct race_cond_s rc;
status = pthread_rwlock_init(&rw_lock, NULL);
TC_ASSERT_EQ("pthread_rwlock_init", status, OK);
status = sem_init(&sem1, 0, 0);
TC_ASSERT_EQ("sem_init", status, OK);
status = sem_init(&sem2, 0, 0);
TC_ASSERT_EQ("sem_init", status, OK);
rc.sem1 = &sem1;
rc.sem2 = &sem2;
rc.rw_lock = &rw_lock;
g_race_cond_thread_pos = 0;
status = pthread_create(&thread1, NULL, race_cond_thread1, &rc);
status = pthread_create(&thread2, NULL, race_cond_thread2, &rc);
(void)pthread_join(thread1, NULL);
(void)pthread_join(thread2, NULL);
}
static void *timeout_thread1(FAR void *data)
{
FAR struct race_cond_s *rc = (FAR struct race_cond_s *)data;
int status;
status = pthread_rwlock_wrlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_wrlock", status, OK, NULL);
sem_wait(rc->sem1);
status = pthread_rwlock_unlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_unlock", status, OK, NULL);
return NULL;
}
static void *timeout_thread2(FAR void *data)
{
FAR struct race_cond_s *rc = (FAR struct race_cond_s *)data;
struct timespec time;
int status;
status = clock_gettime(CLOCK_REALTIME, &time);
time.tv_sec += 2;
status = pthread_rwlock_timedwrlock(rc->rw_lock, &time);
TC_ASSERT_EQ_RETURN("pthread_rwlock_timedwrlock", status, ETIMEDOUT, NULL);
status = clock_gettime(CLOCK_REALTIME, &time);
time.tv_sec += 2;
status = pthread_rwlock_timedrdlock(rc->rw_lock, &time);
TC_ASSERT_EQ_RETURN("pthread_rwlock_timedrdlock", status, ETIMEDOUT, NULL);
status = clock_gettime(CLOCK_REALTIME, &time);
time.tv_sec += 2;
sem_post(rc->sem1);
status = pthread_rwlock_timedrdlock(rc->rw_lock, &time);
TC_ASSERT_EQ_RETURN("pthread_rwlock_timedrdlock", status, OK, NULL);
status = pthread_rwlock_unlock(rc->rw_lock);
TC_ASSERT_EQ_RETURN("pthread_rwlock_unlock", status, OK, NULL);
return NULL;
}
/**
* @fn :tc_libc_pthread_pthread_rwlock_rdlock_wrlock
* @Description :creates and initializes a new read-write lock object with specified attributes and \
* creates two threads using pthread_create and tries acquiring read & write locks referenced rwlock \
* destroys the read-write lock object referenced by rwlock and release any resources used by the lock started with pthread_rwlock_init.
* API's covered :pthread_rwlock_init, pthread_rwlock_wrlock, pthread_rwlock_rdlock, pthread_rwlock_trywrlock, pthread_rwlock_tryrdlock, pthread_rwlock_unlock
* Preconditions :none
* Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_rwlock_rdlock_wrlock(void)
{
int status;
pthread_rwlock_t rw_lock;
status = pthread_rwlock_init(&rw_lock, NULL);
TC_ASSERT_EQ("pthread_rwlock_init", status, OK);
status = pthread_rwlock_trywrlock(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_trywrlock", status, OK);
status = pthread_rwlock_trywrlock(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_trywrlock", status, EBUSY);
status = pthread_rwlock_tryrdlock(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_tryrdlock", status, EBUSY);
status = pthread_rwlock_unlock(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_unlock", status, OK);
test_two_threads();
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_rwlock_timedwrlock_timedrdlock
* @Description :creates and initializes a new read-write lock object with specified attributes and \
* tries acquiring timed read & write lock referenced rwlock multple times and checks whether it times out correctly \
* destroys the read-write lock object referenced by rwlock and release any resources used by the lock started with pthread_rwlock_init.
* API's covered :pthread_rwlock_init, pthread_rwlock_timedwrlock, pthread_rwlock_timedrdlock, pthread_rwlock_unlock
* Preconditions :none
* Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_rwlock_timedwrlock_timedrdlock(void)
{
pthread_rwlock_t rw_lock;
struct race_cond_s rc;
pthread_t thread1;
pthread_t thread2;
int status;
sem_t sem1;
sem_t sem2;
status = pthread_rwlock_init(&rw_lock, NULL);
TC_ASSERT_EQ("pthread_rwlock_init", status, OK);
status = sem_init(&sem1, 0, 0);
TC_ASSERT_EQ("sem_init", status, OK);
status = sem_init(&sem2, 0, 0);
TC_ASSERT_EQ("sem_init", status, OK);
rc.sem1 = &sem1;
rc.sem2 = &sem2;
rc.rw_lock = &rw_lock;
status = pthread_create(&thread1, NULL, timeout_thread1, &rc);
status = pthread_create(&thread2, NULL, timeout_thread2, &rc);
(void)pthread_join(thread1, NULL);
(void)pthread_join(thread2, NULL);
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_rwlock_init_unlock_destroy
* @Description :creates and initializes a new read-write lock object with specified attributes and \
* unlock releases the lock held on the read-write lock object referenced by rwlock and then \
* destroys the read-write lock object referenced by rwlock and release any resources used by the lock started with pthread_rwlock_init.
* API's covered :pthread_rwlock_init, pthread_rwlock_wrlock, pthread_rwlock_unlock, pthread_rwlock_destroy
* Preconditions :none
* Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_rwlock_init_unlock_destroy(void)
{
int status;
pthread_rwlock_t rw_lock;
pthread_rwlockattr_t attr;
status = pthread_rwlock_init(NULL, &attr);
TC_ASSERT_EQ("pthread_rwlock_init", status, EINVAL);
status = pthread_rwlock_init(&rw_lock, NULL);
TC_ASSERT_EQ("pthread_rwlock_init", status, OK);
status = pthread_rwlock_wrlock(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_wrlock", status, OK);
status = pthread_rwlock_unlock(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_unlock", status, OK);
status = pthread_rwlock_destroy(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_destroy", status, OK);
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_rwlock_tryrdlock
* @Description :creates and initializes a new read-write lock object with specified attributes and \
* pthread_rwlock_tryrdlock applies a timed read lock to the read-write lock referenced by rwlock \
* The calling thread acquires the read lock if a writer does not hold the lock and there are no writers blocked on the lock and then \
* unlocks & destroys the rw lock object referenced by rwlock & release any resources used by the lock started with pthread_rwlock_init.
* API's covered :pthread_rwlock_init, pthread_rwlock_tryrdlock, pthread_rwlock_unlock, pthread_rwlock_destroy
* Preconditions :none
* Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_rwlock_tryrdlock(void)
{
int status;
pthread_rwlock_t rw_lock;
status = pthread_rwlock_init(&rw_lock, NULL);
TC_ASSERT_EQ("pthread_rwlock_init", status, OK);
status = pthread_rwlock_tryrdlock(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_tryrdlock", status, OK);
status = pthread_rwlock_unlock(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_unlock", status, OK);
status = pthread_rwlock_destroy(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_destroy", status, OK);
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_rwlock_trywrlock
* @Description :creates and initializes a new read-write lock object with specified attributes and \
* pthread_rwlock_trywrlock applies a timed write lock to the read-write lock referenced by rwlock \
* If the lock cannot be acquired without waiting for other threads to unlock the lock \
* this wait shall be terminated when the specified timeout expires and then \
* unlocks & destroys the read-write lock object referenced by rwlock and release any resources used by the lock started with pthread_rwlock_init.
* API's covered :pthread_rwlock_init, pthread_rwlock_trywrlock, pthread_rwlock_unlock, pthread_rwlock_destroy
* Preconditions :none
* Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_rwlock_trywrlock(void)
{
int status;
pthread_rwlock_t rw_lock;
status = pthread_rwlock_init(&rw_lock, NULL);
TC_ASSERT_EQ("pthread_rwlock_init", status, OK);
status = pthread_rwlock_trywrlock(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_trywrlock", status, OK);
status = pthread_rwlock_unlock(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_unlock", status, OK);
status = pthread_rwlock_destroy(&rw_lock);
TC_ASSERT_EQ("pthread_rwlock_destroy", status, OK);
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_setcancelstate
* @brief :This tc tests pthread_setcancelstate()
* @Scenario :The function shall atomically both set the calling thread's cancelability state to the indicated state
* and return the previous cancelability state at the location referenced by oldstate
* If successful pthread_setcancelstate() function shall return zero;
* otherwise, an error number shall be returned to indicate the error.
* @API'scovered :pthread_setcancelstate
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
static void tc_libc_pthread_pthread_setcancelstate(void)
{
int state;
int oldstate;
int ret_chk;
state = PTHREAD_CANCEL_ENABLE;
ret_chk = pthread_setcancelstate(state, &oldstate);
TC_ASSERT_EQ("pthread_setcancelstate", ret_chk, OK);
state = PTHREAD_CANCEL_DISABLE;
ret_chk = pthread_setcancelstate(state, &oldstate);
TC_ASSERT_EQ("pthread_setcancelstate", ret_chk, OK);
TC_ASSERT_EQ("pthread_setcancelstate", oldstate, PTHREAD_CANCEL_ENABLE);
TC_SUCCESS_RESULT();
}
/**
* @fn :tc_libc_pthread_pthread_setcanceltype
* @brief :This tc tests pthread_setcanceltype()
* @Scenario :The function shall atomically both set the calling thread's cancelability type to the indicated type
* and return the previous cancelability type at the location referenced by oldtype
* If successful pthread_setcanceltype() function shall return zero;
* otherwise, an error number shall be returned to indicate the error.
* @API'scovered :pthread_setcanceltype
* @Preconditions :none
* @Postconditions :none
* @return :void
*/
#ifndef CONFIG_CANCELLATION_POINTS
static void tc_libc_pthread_pthread_setcanceltype(void)
{
int type;
int oldtype;
int ret_chk;
type = PTHREAD_CANCEL_ASYNCHRONOUS;
ret_chk = pthread_setcanceltype(type, &oldtype);
TC_ASSERT_EQ("pthread_setcanceltype", ret_chk, OK);
type = PTHREAD_CANCEL_DEFERRED;
ret_chk = pthread_setcanceltype(type, &oldtype);
TC_ASSERT_EQ("pthread_setcanceltype", ret_chk, ENOSYS);
TC_ASSERT_EQ("pthread_setcanceltype", oldtype, PTHREAD_CANCEL_ASYNCHRONOUS);
TC_SUCCESS_RESULT();
}
#endif
/****************************************************************************
* Name: libc_pthread
****************************************************************************/
int libc_pthread_main(void)
{
tc_libc_pthread_pthread_attr_init();
tc_libc_pthread_pthread_attr_destroy();
tc_libc_pthread_pthread_attr_getstacksize();
tc_libc_pthread_pthread_attr_setstacksize();
tc_libc_pthread_pthread_attr_getschedparam();
tc_libc_pthread_pthread_attr_setschedparam();
tc_libc_pthread_pthread_attr_getschedpolicy();
tc_libc_pthread_pthread_attr_setschedpolicy();
tc_libc_pthread_pthread_attr_getinheritsched();
tc_libc_pthread_pthread_attr_setinheritsched();
tc_libc_pthread_pthread_barrierattr_init();
tc_libc_pthread_pthread_barrierattr_destroy();
tc_libc_pthread_pthread_barrierattr_getpshared();
tc_libc_pthread_pthread_barrierattr_setpshared();
tc_libc_pthread_pthread_condattr_init();
tc_libc_pthread_pthread_condattr_destroy();
tc_libc_pthread_pthread_mutexattr_init();
tc_libc_pthread_pthread_mutexattr_destroy();
tc_libc_pthread_pthread_mutexattr_getpshared();
tc_libc_pthread_pthread_mutexattr_setpshared();
tc_libc_pthread_pthread_mutexattr_gettype();
tc_libc_pthread_pthread_mutexattr_settype();
tc_libc_pthread_pthread_mutexattr_getprotocol();
tc_libc_pthread_pthread_mutexattr_setprotocol();
tc_libc_pthread_pthread_mutexattr_getrobust();
tc_libc_pthread_pthread_mutexattr_setrobust();
tc_libc_pthread_pthread_rwlock_init_unlock_destroy();
tc_libc_pthread_pthread_rwlock_tryrdlock();
tc_libc_pthread_pthread_rwlock_trywrlock();
tc_libc_pthread_pthread_rwlock_rdlock_wrlock();
tc_libc_pthread_pthread_rwlock_timedwrlock_timedrdlock();
tc_libc_pthread_pthread_setcancelstate();
#ifndef CONFIG_CANCELLATION_POINTS
tc_libc_pthread_pthread_setcanceltype();
#endif
return 0;
}
| jsdosa/TizenRT | apps/examples/testcase/le_tc/kernel/tc_libc_pthread.c | C | apache-2.0 | 46,422 |
//
// Copyright (c) 2000-2002
// Joerg Walter, Mathias Koch
//
// 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 authors gratefully acknowledge the support of
// GeNeSys mbH & Co. KG in producing this work.
//
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/io.hpp>
int main () {
using namespace boost::numeric::ublas;
matrix<double> m (3, 3);
vector<double> v (3);
for (unsigned i = 0; i < (std::min) (m.size1 (), v.size ()); ++ i) {
for (unsigned j = 0; j <= i; ++ j)
m (i, j) = 3 * i + j + 1;
v (i) = i;
}
std::cout << solve (m, v, lower_tag ()) << std::endl;
std::cout << solve (v, m, lower_tag ()) << std::endl;
}
| flingone/frameworks_base_cmds_remoted | libs/boost/libs/numeric/ublas/doc/samples/matrix_vector_solve.cpp | C++ | apache-2.0 | 859 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.ignite.internal.processors.cache;
import org.apache.ignite.testframework.MvccFeatureChecker;
import org.junit.Before;
import org.junit.Test;
/**
* Tests peek modes with near tx cache.
*/
public class IgniteCacheTxNearPeekModesTest extends IgniteCacheTxPeekModesTest {
/** */
@Before
public void beforeIgniteCacheTxNearPeekModesTest() {
MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.NEAR_CACHE);
}
/** {@inheritDoc} */
@Override protected boolean hasNearCache() {
return true;
}
/** {@inheritDoc} */
@Test
@Override public void testLocalPeek() throws Exception {
// TODO: uncomment and re-open ticket if fails.
// fail("https://issues.apache.org/jira/browse/IGNITE-1824");
super.testLocalPeek();
}
}
| ascherbakoff/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheTxNearPeekModesTest.java | Java | apache-2.0 | 1,631 |
package org.zstack.simulator;
import org.zstack.core.GlobalProperty;
import org.zstack.core.GlobalPropertyDefinition;
/**
*/
@GlobalPropertyDefinition
public class SimulatorGlobalProperty {
@GlobalProperty(name="Simulator.notCacheAgentCommand", defaultValue = "false")
public static boolean NOT_CACHE_AGENT_COMMAND;
}
| SoftwareKing/zstack | simulator/simulatorImpl/src/main/java/org/zstack/simulator/SimulatorGlobalProperty.java | Java | apache-2.0 | 341 |
/*
* Copyright 2012 Amadeus s.a.s.
* 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.
*/
var Aria = require("../Aria");
var ariaTemplatesIFlowCtrl = require("./IFlowCtrl");
require("../utils/String");
var ariaTemplatesPublicWrapper = require("./PublicWrapper");
/**
* Base class for flow controllers.
* @class aria.templates.FlowCtrl
*/
module.exports = Aria.classDefinition({
$classpath : 'aria.templates.FlowCtrl',
$extends : ariaTemplatesPublicWrapper,
$implements : [ariaTemplatesIFlowCtrl],
$constructor : function () {
this.$PublicWrapper.constructor.call(this);
},
$destructor : function () {
this.moduleCtrl = null;
this.data = null;
this.$PublicWrapper.$destructor.call(this);
},
$prototype : {
/**
* Classpath of the interface to be used as the public interface of this flow controller.
* @protected
* @type {String}
*/
$publicInterfaceName : 'aria.templates.IFlowCtrl',
/**
* Called when the flow controller is initialized, to set the module controller associated to this flow
* controller. Note that this is before the module controller init method has been called.
* @param {Object} moduleCtrl Public interface of the flow controller.
*/
setModuleCtrl : function (moduleCtrl) {
this.moduleCtrl = moduleCtrl;
},
/**
* Interceptor on the callback of the init method of the module controller. It is used to set the data property
* on the flow controller.
*/
oninitCallback : function (param) {
this.data = this.moduleCtrl.getData();
}
}
});
| fbasso/ariatemplates | src/aria/templates/FlowCtrl.js | JavaScript | apache-2.0 | 2,218 |
// RUN: %clang_cc1 -fsyntax-only -Wsigned-enum-bitfield -verify %s --std=c++11
// Enums used in bitfields with no explicitly specified underlying type.
void test0() {
enum E { E1, E2 };
enum F { F1, F2 };
struct { E e1 : 1; E e2; F f1 : 1; F f2; } s;
s.e1 = E1; // expected-warning {{enums in the Microsoft ABI are signed integers by default; consider giving the enum 'E' an unsigned underlying type to make this code portable}}
s.f1 = F1; // expected-warning {{enums in the Microsoft ABI are signed integers by default; consider giving the enum 'F' an unsigned underlying type to make this code portable}}
s.e2 = E2;
s.f2 = F2;
}
// Enums used in bitfields with an explicit signed underlying type.
void test1() {
enum E : signed { E1, E2 };
enum F : long { F1, F2 };
struct { E e1 : 1; E e2; F f1 : 1; F f2; } s;
s.e1 = E1;
s.f1 = F1;
s.e2 = E2;
s.f2 = F2;
}
// Enums used in bitfields with an explicitly unsigned underlying type.
void test3() {
enum E : unsigned { E1, E2 };
enum F : unsigned long { F1, F2 };
struct { E e1 : 1; E e2; F f1 : 1; F f2; } s;
s.e1 = E1;
s.f1 = F1;
s.e2 = E2;
s.f2 = F2;
}
| google/llvm-propeller | clang/test/SemaCXX/warn-msvc-enum-bitfield.cpp | C++ | apache-2.0 | 1,155 |
/* Copyright (c) Mark J. Kilgard, 1996. */
/* This program is freely distributable without licensing fees
and is provided without guarantee or warrantee expressed or
implied. This program is -not- in the public domain. */
#include <stdlib.h>
#if !defined(_WIN32) && !defined(__BEOS__)
#include <GL/glx.h>
#endif
#ifdef __sgi
#include <dlfcn.h>
#endif
#include "glutint.h"
/* Grumble. The IRIX 6.3 and early IRIX 6.4 OpenGL headers
support the video resize extension, but failed to define
GLX_SGIX_video_resize. */
#ifdef GLX_SYNC_FRAME_SGIX
#define GLX_SGIX_video_resize 1
#endif
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_video_resize)
static int canVideoResize = -1;
static int videoResizeChannel;
#else
static int canVideoResize = 0;
#endif
static int videoResizeInUse = 0;
static int dx = -1, dy = -1, dw = -1, dh = -1;
/* XXX Note that IRIX 6.2, 6.3, and some 6.4 versions have a
bug where programs seg-fault when they attempt video
resizing from an indirect OpenGL context (either local or
over a network). */
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_video_resize)
static volatile int errorCaught;
/* ARGSUSED */
static
catchXSGIvcErrors(Display * dpy, XErrorEvent * event)
{
errorCaught = 1;
return 0;
}
#endif
/* CENTRY */
int APIENTRY
glutVideoResizeGet(GLenum param)
{
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_video_resize)
if (canVideoResize < 0) {
canVideoResize = __glutIsSupportedByGLX("GLX_SGIX_video_resize");
if (canVideoResize) {
#if __sgi
/* This is a hack because IRIX 6.2, 6.3, and some 6.4
versions were released with GLX_SGIX_video_resize
being advertised by the X server though the video
resize extension is not actually supported. We try to
determine if the libGL.so we are using actually has a
video resize entrypoint before we try to use the
feature. */
void (*func) (void);
void *glxDso = dlopen("libGL.so", RTLD_LAZY);
func = (void (*)(void)) dlsym(glxDso, "glXQueryChannelDeltasSGIX");
if (!func) {
canVideoResize = 0;
} else
#endif
{
char *channelString;
int (*handler) (Display *, XErrorEvent *);
channelString = getenv("GLUT_VIDEO_RESIZE_CHANNEL");
videoResizeChannel = channelString ? atoi(channelString) : 0;
/* Work around another annoying problem with SGI's
GLX_SGIX_video_resize implementation. Early IRIX
6.4 OpenGL's advertise the extension and have the
video resize API, but an XSGIvc X protocol errors
result trying to use the API. Set up an error
handler to intercept what would otherwise be a fatal
error. If an error was recieved, do not report that
video resize is possible. */
handler = XSetErrorHandler(catchXSGIvcErrors);
errorCaught = 0;
glXQueryChannelDeltasSGIX(__glutDisplay, __glutScreen,
videoResizeChannel, &dx, &dy, &dw, &dh);
/* glXQueryChannelDeltasSGIX is an inherent X server
round-trip so we know we will have gotten either the
correct reply or and error by this time. */
XSetErrorHandler(handler);
/* Still yet another work around. In IRIX 6.4 betas,
glXQueryChannelDeltasSGIX will return as if it
succeeded, but the values are filled with junk.
Watch to make sure the delta variables really make
sense. */
if (errorCaught ||
dx < 0 || dy < 0 || dw < 0 || dh < 0 ||
dx > 2048 || dy > 2048 || dw > 2048 || dh > 2048) {
canVideoResize = 0;
}
}
}
}
#endif /* GLX_SGIX_video_resize */
switch (param) {
case GLUT_VIDEO_RESIZE_POSSIBLE:
return canVideoResize;
case GLUT_VIDEO_RESIZE_IN_USE:
return videoResizeInUse;
case GLUT_VIDEO_RESIZE_X_DELTA:
return dx;
case GLUT_VIDEO_RESIZE_Y_DELTA:
return dy;
case GLUT_VIDEO_RESIZE_WIDTH_DELTA:
return dw;
case GLUT_VIDEO_RESIZE_HEIGHT_DELTA:
return dh;
case GLUT_VIDEO_RESIZE_X:
case GLUT_VIDEO_RESIZE_Y:
case GLUT_VIDEO_RESIZE_WIDTH:
case GLUT_VIDEO_RESIZE_HEIGHT:
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_video_resize)
if (videoResizeInUse) {
int x, y, width, height;
glXQueryChannelRectSGIX(__glutDisplay, __glutScreen,
videoResizeChannel, &x, &y, &width, &height);
switch (param) {
case GLUT_VIDEO_RESIZE_X:
return x;
case GLUT_VIDEO_RESIZE_Y:
return y;
case GLUT_VIDEO_RESIZE_WIDTH:
return width;
case GLUT_VIDEO_RESIZE_HEIGHT:
return height;
}
}
#endif
return -1;
default:
__glutWarning("invalid glutVideoResizeGet parameter: %d", param);
return -1;
}
}
void APIENTRY
glutSetupVideoResizing(void)
{
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_video_resize)
if (glutVideoResizeGet(GLUT_VIDEO_RESIZE_POSSIBLE)) {
glXBindChannelToWindowSGIX(__glutDisplay, __glutScreen,
videoResizeChannel, __glutCurrentWindow->win);
videoResizeInUse = 1;
} else
#endif
__glutFatalError("glutEstablishVideoResizing: video resizing not possible.\n");
}
void APIENTRY
glutStopVideoResizing(void)
{
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_video_resize)
if (glutVideoResizeGet(GLUT_VIDEO_RESIZE_POSSIBLE)) {
if (videoResizeInUse) {
glXBindChannelToWindowSGIX(__glutDisplay, __glutScreen,
videoResizeChannel, None);
videoResizeInUse = 0;
}
}
#endif
}
/* ARGSUSED */
void APIENTRY
glutVideoResize(int x, int y, int width, int height)
{
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_video_resize)
if (videoResizeInUse) {
#ifdef GLX_SYNC_SWAP_SGIX
/* glXChannelRectSyncSGIX introduced in a patch to IRIX
6.2; the original unpatched IRIX 6.2 behavior is always
GLX_SYNC_SWAP_SGIX. */
glXChannelRectSyncSGIX(__glutDisplay, __glutScreen,
videoResizeChannel, GLX_SYNC_SWAP_SGIX);
#endif
glXChannelRectSGIX(__glutDisplay, __glutScreen,
videoResizeChannel, x, y, width, height);
}
#endif
}
/* ARGSUSED */
void APIENTRY
glutVideoPan(int x, int y, int width, int height)
{
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_video_resize)
if (videoResizeInUse) {
#ifdef GLX_SYNC_FRAME_SGIX
/* glXChannelRectSyncSGIX introduced in a patch to IRIX
6.2; the original unpatched IRIX 6.2 behavior is always
GLX_SYNC_SWAP_SGIX. We just ignore that we cannot
accomplish GLX_SYNC_FRAME_SGIX on IRIX unpatched 6.2;
this means you'd need a glutSwapBuffers to actually
realize the video resize. */
glXChannelRectSyncSGIX(__glutDisplay, __glutScreen,
videoResizeChannel, GLX_SYNC_FRAME_SGIX);
#endif
glXChannelRectSGIX(__glutDisplay, __glutScreen,
videoResizeChannel, x, y, width, height);
}
#endif
}
/* ENDCENTRY */
| execunix/vinos | xsrc/external/mit/MesaGLUT/dist/src/glut/beos/glut_vidresize.c | C | apache-2.0 | 6,916 |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.
*/
package org.keycloak.adapters.springsecurity.client;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.OidcKeycloakAccount;
import org.keycloak.adapters.springsecurity.account.KeycloakRole;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import java.util.Collections;
import java.util.UUID;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* Keycloak client request factory tests.
*/
public class KeycloakClientRequestFactoryTest {
@Spy
private KeycloakClientRequestFactory factory;
@Mock
private OidcKeycloakAccount account;
@Mock
private KeycloakAuthenticationToken keycloakAuthenticationToken;
@Mock
private KeycloakSecurityContext keycloakSecurityContext;
@Mock
private HttpUriRequest request;
private String bearerTokenString;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
bearerTokenString = UUID.randomUUID().toString();
SecurityContextHolder.getContext().setAuthentication(keycloakAuthenticationToken);
when(keycloakAuthenticationToken.getAccount()).thenReturn(account);
when(account.getKeycloakSecurityContext()).thenReturn(keycloakSecurityContext);
when(keycloakSecurityContext.getTokenString()).thenReturn(bearerTokenString);
}
@Test
public void testPostProcessHttpRequest() throws Exception {
factory.postProcessHttpRequest(request);
verify(factory).getKeycloakSecurityContext();
verify(request).setHeader(eq(KeycloakClientRequestFactory.AUTHORIZATION_HEADER), eq("Bearer " + bearerTokenString));
}
@Test
public void testGetKeycloakSecurityContext() throws Exception {
KeycloakSecurityContext context = factory.getKeycloakSecurityContext();
assertNotNull(context);
assertEquals(keycloakSecurityContext, context);
}
@Test(expected = IllegalStateException.class)
public void testGetKeycloakSecurityContextInvalidAuthentication() throws Exception {
SecurityContextHolder.getContext().setAuthentication(
new PreAuthenticatedAuthenticationToken("foo", "bar", Collections.singleton(new KeycloakRole("baz"))));
factory.getKeycloakSecurityContext();
}
@Test(expected = IllegalStateException.class)
public void testGetKeycloakSecurityContextNullAuthentication() throws Exception {
SecurityContextHolder.clearContext();
factory.getKeycloakSecurityContext();
}
}
| jean-merelis/keycloak | adapters/oidc/spring-security/src/test/java/org/keycloak/adapters/springsecurity/client/KeycloakClientRequestFactoryTest.java | Java | apache-2.0 | 3,586 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace FlickrSearch
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string searchTerm = (string)e.Parameter;
if (string.IsNullOrEmpty(searchTerm.Trim()))
{
searchTerm = "flowers";
}
SearchFlickr(searchTerm);
}
async void SearchFlickr(string searchTerm)
{
List<FlickrPhotoResult> results = await FlickrSearcher.SearchAsync(searchTerm);
this.DataContext = results;
UpdateTile(results.Take(5));
SendToast(results.First());
}
void UpdateTile(IEnumerable<FlickrPhotoResult> results)
{
TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
tileUpdater.EnableNotificationQueue(true);
foreach (FlickrPhotoResult result in results)
{
XmlDocument xmlTileContent = TileUpdateManager.GetTemplateContent(
TileTemplateType.TileWide310x150ImageAndText01);
TemplateUtility.CompleteTemplate(
xmlTileContent,
new string[] { result.Title },
new string[] { result.ImageUrl });
TileNotification notification = new TileNotification(xmlTileContent);
tileUpdater.Update(notification);
}
}
void SendToast(FlickrPhotoResult flickrPhotoResult)
{
ToastNotifier toastNotifier = ToastNotificationManager.CreateToastNotifier();
XmlDocument xmlToastContent = ToastNotificationManager.GetTemplateContent(
ToastTemplateType.ToastImageAndText01);
TemplateUtility.CompleteTemplate(
xmlToastContent,
new string[] { flickrPhotoResult.Title },
new string[] { flickrPhotoResult.ImageUrl },
"ms-winsoundevent:Notification.Mail");
// TODO: change delivery time
ScheduledToastNotification toastNotification = new ScheduledToastNotification(xmlToastContent,
(new DateTimeOffset(DateTime.Now) + TimeSpan.FromSeconds(10)));
// TODO: change identifier
toastNotification.Id = "Fred";
toastNotifier.AddToSchedule(toastNotification);
}
}
}
| William-Wen/TrainingContent | O3654/O3654-W Overview of universal Windows App development/1 - Demo1 Flickr Search/End/FlickrSearch/FlickrSearch/FlickrSearch.Shared/MainPage.xaml.cs | C# | apache-2.0 | 3,104 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.stdlib;
import com.intellij.openapi.diagnostic.Logger;
import com.jetbrains.python.PythonHelpersLocator;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* @author vlan
*/
public final class PyStdlibUtil {
@Nullable private static final Set<String> PACKAGES = loadStdlibPackagesList();
private PyStdlibUtil() {
}
@Nullable
public static Collection<String> getPackages() {
return PACKAGES;
}
@Nullable
private static Set<String> loadStdlibPackagesList() {
final Logger log = Logger.getInstance(PyStdlibUtil.class.getName());
final String helperPath = PythonHelpersLocator.getHelperPath("/tools/stdlib_packages.txt");
try {
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(helperPath), StandardCharsets.UTF_8));
try {
final Set<String> result = new HashSet<>();
String line;
while ((line = reader.readLine()) != null) {
result.add(line);
}
return result;
}
finally {
reader.close();
}
}
catch (IOException e) {
log.error("Cannot read list of standard library packages: " + e.getMessage());
}
return null;
}
}
| siosio/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibUtil.java | Java | apache-2.0 | 1,625 |
# Examples
This directory contains example configurations for a number of popular tools.
Here is how you start them with Curl:
curl -i -H 'Content-Type: application/json' -d @<filename.json> localhost:8080/v2/apps
If you want to contribute your own config, please send us a pull request!
| EvanKrall/marathon | examples/README.md | Markdown | apache-2.0 | 295 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0) on Mon Mar 07 09:03:16 PST 2016 -->
<title>CheckedSupplier (Quarks v0.4.0)</title>
<meta name="date" content="2016-03-07">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="CheckedSupplier (Quarks v0.4.0)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div role="navigation" title ="TOP_Navigation" aria-label ="Top Navigation Bar"/>
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/CheckedSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../quarks/connectors/jdbc/CheckedFunction.html" title="interface in quarks.connectors.jdbc"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../quarks/connectors/jdbc/JdbcStreams.html" title="class in quarks.connectors.jdbc"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?quarks/connectors/jdbc/CheckedSupplier.html" target="_top">Frames</a></li>
<li><a href="CheckedSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div role="main" title ="CheckedSupplier" aria-labelledby ="Header1"/>
<div class="header">
<div class="subTitle">quarks.connectors.jdbc</div>
<h2 title="Interface CheckedSupplier" class="title" id="Header1">Interface CheckedSupplier<T></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt><span class="paramLabel">Type Parameters:</span></dt>
<dd><code>T</code> - stream tuple type</dd>
</dl>
<dl>
<dt>Functional Interface:</dt>
<dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd>
</dl>
<hr>
<br>
<pre>@FunctionalInterface
public interface <span class="typeNameLabel">CheckedSupplier<T></span></pre>
<div class="block">Function that supplies a result and may throw an Exception.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../quarks/connectors/jdbc/CheckedSupplier.html" title="type parameter in CheckedSupplier">T</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../quarks/connectors/jdbc/CheckedSupplier.html#get--">get</a></span>()</code>
<div class="block">Get a result.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="get--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>get</h4>
<pre><a href="../../../quarks/connectors/jdbc/CheckedSupplier.html" title="type parameter in CheckedSupplier">T</a> get()
throws java.lang.Exception</pre>
<div class="block">Get a result.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the result</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.Exception</code> - if there are errors</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div role="navigation" title ="Bottom_NAVIGATION" aria-label ="Bottom Navigation Bar"/>
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/CheckedSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><a href="http://quarks-edge.github.io">quarks-edge community @ github.com</a></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../quarks/connectors/jdbc/CheckedFunction.html" title="interface in quarks.connectors.jdbc"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../quarks/connectors/jdbc/JdbcStreams.html" title="class in quarks.connectors.jdbc"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?quarks/connectors/jdbc/CheckedSupplier.html" target="_top">Frames</a></li>
<li><a href="CheckedSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<div role="contentinfo" title ="contentinfo_title" aria-label ="Contains footer note"/>
<p class="legalCopy"><small>Copyright IBM 2015,2016 - 2f6ad0e-20160307-0902</small></p>
</body>
</html>
| queeniema/incubator-edgent-website | site/javadoc/r0.4.0/quarks/connectors/jdbc/CheckedSupplier.html | HTML | apache-2.0 | 8,875 |
# Enforce Exclusive Access to Memory
* Proposal: [SE-0176](0176-enforce-exclusive-access-to-memory.md)
* Author: [John McCall](https://github.com/rjmccall)
* Review Manager: [Ben Cohen](https://github.com/airspeedswift)
* Status: **Implemented (Swift 4)**
* Previous Revision: [1](https://github.com/apple/swift-evolution/blob/7e6816c22a29b0ba9bdf63ff92b380f9e963860a/proposals/0176-enforce-exclusive-access-to-memory.md)
* Previous Discussion: [Email Thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170501/036308.html)
## Introduction
In Swift 3, it is possible to modify a variable while it's being used or
modified by another part of the program. This can lead to unexpected and
confusing results. It also forces a great deal of conservatism onto the
implementation of the compiler and the standard libraries, which must
generally ensure the basic soundness of the program (no crashes or
undefined behavior) even in unusual circumstances.
We propose that Swift should instead enforce a general rule that potential
modifications of variables must be exclusive with any other access to that
variable.
This proposal is a core part of the Ownership feature, which was described
in the [ownership manifesto](https://github.com/apple/swift/blob/master/docs/OwnershipManifesto.md).
That document presents the high-level objectives of Ownership, develops
a more rigorous theory of memory access in Swift, and applies it in detail
to a variety of different language features. In that document, the rule
we're proposing here is called the Law of Exclusivity. We will not be
going into that level of detail in this proposal. Instead, we will
lay out the basic rule, how it will be enforced, and the implications for
programming in Swift. It should be possible to understand this proposal
without actually having read the ownership manifesto at all. That said,
if you are interested in the technical details, that document is probably
the right place to turn.
## Motivation
### Instantaneous and non-instantaneous accesses
On a basic level, Swift is an imperative language which allows programmers
to directly access mutable memory.
Many of the language features that access memory, like simply loading
from or assigning to a variable, are "instantaneous". This means that,
from the perspective of the current thread, the operation completes
without any other code being able to interfere. For example, when you
assign to a stored property, the current value is just replaced with
the new value. Because arbitrary other code can't run during an
instantaneous access, it's never possible for two instantaneous accesses
to overlap each other (without introducing concurrency, which we'll
talk about later). That makes them very easy to reason about.
However, not all accesses are instantaneous. For example, when you
call a ``mutating`` method on a stored property, it's really one long
access to the property: ``self`` just becomes another way of referring
to the property's storage. This access isn't instantaneous because
all of the code in the method executes during it, so if that code
manages to access the same property again, the accesses will overlap.
There are several language features like this already in Swift, and
Ownership will add a few more.
### Examples of problems due to overlap
Here's an example:
```swift
// These are simple global variables.
var global: Int = 0
var total: Int = 0
extension Int {
// Mutating methods access the variable they were called on
// for the duration of the method.
mutating func increaseByGlobal() {
// Any accesses they do will overlap the access to that variable.
total += self // Might access 'total' through both 'total' and 'self'
self += global // Might access 'global' through both 'global' and 'self'
}
}
```
If ``self`` is ``total`` or ``global``, the low-level semantics of this
method don't change, but the programmer's high-level understanding
of it almost certainly does. A line that superficially seems to not
change 'global' might suddenly start doubling it! And the data dependencies
between the two lines instantly go from simple to very complex. That's very
important information for someone maintaining this method, who might be
tempted to re-arrange the code in ways that seem equivalent. That kind of
maintenance can get very frustrating because of overlap like this.
The same considerations apply to the language implementation.
The possibility of overlap means the language has to make
pessimistic assumptions about the loads and stores in this method.
For example, the following code avoids a seemingly-redundant load,
but it's not actually equivalent because of overlap:
```swift
let value = self
total += value
self = value + global
```
Because these variables just have type ``Int``, the cost of this pessimism
is only an extra load. If the types were more complex, like ``String``,
it might mean doing extra copies of the ``String`` value, which would
translate to extra retains and releases of the string's buffer; in a more
complex example, that could even lead to the underlying data being copied
unnecessarily.
In the above examples, we've made the potentially-overlapping accesses
obvious, but they don't have to be. For example, here is another method
that takes a closure as an argument:
```swift
extension Array {
mutating func modifyElements(_ closure: (inout Element) -> ()) {
var i = startIndex
while i != endIndex {
closure(&self[i])
i = index(after: i)
}
}
}
```
This method's implementation seems straightforwardly correct, but
unfortunately it doesn't account for overlap. Absolutely nothing
prevents the closure from modifying ``self`` during the iteration,
which means that ``i`` can suddenly become an invalid index, which
could lead to all sorts of unwanted behavior. Even if this never
happen in reality, the fact that it's *possible* means that the
implementation is blocked from pursuing all sorts of important
optimizations.
For example, the compiler has an optimization that "hoists" the
uniqueness check on a copy-on-write collection from the inside of
a loop (where it's run on each iteration) to the outside (so that
it's only checked once, before the loop begins). But that optimization
can't be applied in this example because the closure might change or
copy ``self``. The only realistic way to tell the compiler that
that can't happen is to enforce exclusivity on ``self``.
The same considerations that apply to ``self`` in a ``mutating``
method also apply to ``inout`` parameters. For example:
```swift
open class Person {
open var title: String
}
func collectTitles(people: [Person], into set: inout Set<String>) {
for person in people {
set.insert(person.title)
}
}
```
This function mutates a set of strings, but it also repeatedly
calls a class method. The compiler cannot know how this method
is implemented, because it is ``open`` and therefore overridable
from an arbitrary module. Therefore, because of overlap, the
compiler must pessimistically assume that each of these method
calls might somehow find a way to modify the original variable
that ``set`` was bound to. (And if the method did manage to do
so, the resulting strange behavior would probably be seen as a bug
by the caller of ``collectTitles``.)
### Eliminating non-instantaneous accesses?
If non-instantaneous accesses create all of these problems with
overlapping accesses, should we just eliminate non-instantaneous
accesses completely? Well, no, and there's two big reasons why not.
In order to make something like a ``mutating`` method not access
the original storage of ``self`` for the duration of the method,
we would need to make it access a temporary copy instead, which
we would assign back to the storage after the method is complete.
That is, suppose we had the following Swift code:
```swift
var numbers = [Int]()
numbers.appendABunchOfStuff()
```
Currently, behind the scenes, this is implemented somewhat like
the following C code:
```c
struct Array numbers = _Array_init();
_Array_appendABunchOfStuff(&numbers);
```
You can see clearly how ``_Array_appendABunchOfStuff`` will be working
directly with the storage of ``numbers``, creating the abstract
possibility of overlapping accesses to that variable. To prevent
this in general, we would need to pass a temporary copy instead:
```c
struct Array numbers = _Array_init();
struct Array temp = _Array_copy(numbers);
_Array_appendABunchOfStuff(&temp);
_Array_assign(&numbers, temp);
```
Like we said, there's two big problems with this.
The first problem is that it's awful for performance. Even for a
normal type, doing extra copies is wasteful, but doing it with ``Array``
is even worse because it's a copy-on-write type. The extra copy here
means that there will be multiple references to the buffer, which
means that ``_Array_appendABunchOfStuff`` will be forced to copy the
buffer instead of modifying it in place. Removing these kinds of
copies, and making it easier to reason about when they happen, is a
large part of the goal of the Ownership feature.
The second problem is that it doesn't even eliminate the potential
confusion. Suppose that ``_Array_appendABunchOfStuff`` somehow
reads or writes to ``numbers`` (perhaps because ``numbers`` is
captured in a closure, or it's actually a global variable or a class
property or something else that can be potentially accessed from
anywhere). Because the method is now modifying the copy in ``temp``,
any reads it makes from ``numbers`` won't see any of the changes
it's made to ``temp``, and any changes it makes to ``numbers`` will
be silently lost when it returns and the caller unconditionally
overwrites ``numbers`` with ``temp``.
### Consequences of non-instantaneous accesses
So we have to accept that accesses can be non-instantaneous. That
means programmers can write code that would naturally cause overlapping
accesses to the same variable. We currently allow this to happen
and make a best effort to live with the consequences. The costs,
in general, are a lot of complexity and lost performance.
For example, the ``Array`` type has an optimization in its ``subscript``
operator which allows callers to directly access the storage of array
elements. This is a very important optimization which, among other
things, allows arrays to efficiently hold values of copy-on-write types.
However, because the caller can execute arbitrary code while they're
working with the array element storage, and that code might do something
like assign a new value to the original array variable and therefore drop
the last reference to the array buffer, this optimization has to create a
new strong reference to the buffer until the caller is done with the element,
which itself causes a whole raft of complexity.
Similarly, when the compiler is optimizing a ``mutating`` method, it has
to assume that an arbitrary call might completely rewrite ``self``.
This makes it very difficult to perform any meaningful optimization
at all, especially in generic code. It also means that the compiler
must generally emit a large number of conservative copies just in case
things are modified in unexpected ways.
Furthermore, the possibility of overlapping accesses has a continued
impact on language evolution. Many of the features laid out in the
Ownership manifesto rely on static guarantees that Swift simply cannot
make without stronger rules about when a variable can be modified.
Therefore we think it best to simply disallow overlapping accesses
as best as we can.
## Proposed solution
We should add a rule to Swift that two accesses to the same variable
are not allowed to overlap unless both accesses are reads. By
"variable", we mean any kind of mutable memory: global variables,
local variables, class and struct properties, and so on.
This rule should be enforced as strongly as possible, depending on
what sort of variable it is:
* Local variables, inout parameters, and struct properties can
generally enforce the rule statically. The compiler can analyze
all the accesses to the variable and emit an error if it sees
any conflicts.
* Class properties and global variables will have to enforce the
rule dynamically. The runtime can keep track of what accesses
are underway and report any conflicts. Local variables will
sometimes have to use dynamic enforcement when they are
captured in closures.
* Unsafe pointers will not use any active enforcement; it is the
programmer's responsibility to follow the rule.
* No enforcement is required for immutable memory, like a ``let``
binding or property, because all accesses must be reads.
Examples:
```swift
var x = 0, y = 0
// NOT A CONFLICT. These two accesses to 'x' are both reads.
// Each completes instantaneously, so the accesses do not overlap and
// therefore do not conflict. Even if they were not instantaneous, they
// are both reads and therefore do no conflict.
let z = x + x
// NOT A CONFLICT. The right-hand side of the assignment is a read of
// 'x' which completes instantaneously. The assignment is a write to 'x'
// which completes instantaneously. The accesses do not overlap and
// therefore do not conflict.
x = x
// NOT A CONFLICT. The right-hand side is a read of 'x' which completes
// instantaneously. Calling the operator involves passing 'x' as an inout
// argument; this is a write access for the duration of the call, but it does
// not begin until immediately before the call, after the right-hand side is
// fully evaluated. Therefore the accesses do not overlap and do not conflict.
x += x
// CONFLICT. Passing 'x' as an inout argument is a write access for the
// duration of the call. Passing the same variable twice means performing
// two overlapping write accesses to that variable, which therefore conflict.
swap(&x, &x)
extension Int {
mutating func assignResultOf(_ function: () -> Int) {
self = function()
}
}
// CONFLICT. Calling a mutating method on a value type is a write access
// that lasts for the duration of the method. The read of 'x' in the closure
// is evaluated while the method is executing, which means it overlaps
// the method's formal access to 'x'. Therefore these accesses conflict.
x.assignResultOf { x + 1 }
```
## Detailed design
### Concurrency
Swift has always considered read/write and write/write races on the same
variable to be undefined behavior. It is the programmer's responsibility
to avoid such races in their code by using appropriate thread-safe
programming techniques.
We do not propose changing that. Dynamic enforcement is not required to
detect concurrent conflicting accesses, and we propose that by default
it should not make any effort to do so. This should allow the dynamic
bookkeeping to avoid synchronizing between threads; for example, it
can track accesses in a thread-local data structure instead of a global
one protected by locks. Our hope is that this will make dynamic
access-tracking cheap enough to enable by default in all programs.
The implementation should still be *permitted* to detect concurrent
conflicting accesses, of course. Some programmers may wish to use an
opt-in thread-safe enforcement mechanism instead, at least in some
build configurations.
Any future concurrency design in Swift will have the elimination
of such races as a primary goal. To the extent that it succeeds,
it will also define away any specific problems for exclusivity.
### Value types
Calling a method on a value type is an access to the entire value:
a write if it's a ``mutating`` method, a read otherwise. This is
because we have to assume that a method might read or write an
arbitrary part of the value. Trying to formalize rules like
"this method only uses these properties" would massively complicate
the language.
For similar reasons, using a computed property or subscript on a
value type generally has to be treated as an access to the entire
value. Whether the access is a read or write depends on how the
property/subscript is used and whether either the getter or the setter
is ``mutating``.
Accesses to different stored properties of a ``struct`` or different
elements of a tuple are allowed to overlap. However, note that
modifying part of a value type still requires exclusive access to
the entire value, and that acquiring that access might itself prevent
overlapping accesses. For example:
```swift
struct Pair {
var x: Int
var y: Int
}
class Paired {
var pair = Pair(x: 0, y: 0)
}
let object = Paired()
swap(&object.pair.x, &object.pair.y)
```
Here, initiating the write-access to ``object.pair`` for the first
argument will prevent the write-access to ``object.pair`` for the
second argument from succeeding because of the dynamic enforcement
used for the property. Attempting to make dynamic enforcement
aware of the fact that these accesses are modifying different
sub-components of the property would be prohibitive, both in terms
of the additional performance cost and in terms of the complexity
of the implementation.
However, this limitation can be worked around by binding
``object.pair`` to an ``inout`` parameter:
```swift
func modifying<T>(_ value: inout T, _ function: (inout T) -> ()) {
function(&value)
}
modifying(&object.pair) { pair in swap(&pair.x, &pair.y) }
```
This works because now there is only a single access to
``object.pair`` and because, once the the ``inout`` parameter is
bound to that storage, accesses to the parameter within the
function can use purely static enforcement.
We expect that workarounds like this will only rarely be required.
Note that two different properties can only be assumed to not
conflict when they are both known to be stored. This means that,
for example, it will not be allowed to have overlapping accesses
to different properties of a resilient value type. This is not
expected to be a significant problem for programmers.
### Arrays
Collections do not receive any special treatment in this proposal.
For example, ``Array``'s indexed subscript is an ordinary computed
subscript on a value type. Accordingly, mutating an element of an
array will require exclusive access to the entire array, and
therefore will disallow any other simultaneous accesses to the
array, even to different elements. For example:
```swift
var array = [[1,2], [3,4,5]]
// NOT A CONFLICT. These accesses to the elements of 'array' each
// complete instantaneously and do not overlap each other. Even if they
// did overlap for some reason, they are both reads and therefore
// do not conflict.
print(array[0] + array[1])
// NOT A CONFLICT. The access done to read 'array[1]' completes
// before the modifying access to 'array[0]' begins. Therefore, these
// accesses do not conflict.
array[0] += array[1]
// CONFLICT. Passing 'array[i]' as an inout argument performs a
// write access to it, and therefore to 'array', for the duration of
// the call. This call makes two such accesses to the same array variable,
// which therefore conflict.
swap(&array[0], &array[1])
// CONFLICT. Calling a non-mutating method on 'array[0]' performs a
// read access to it, and thus to 'array', for the duration of the method.
// Calling a mutating method on 'array[1]' performs a write access to it,
// and thus to 'array', for the duration of the method. These accesses
// therefore conflict.
array[0].forEach { array[1].append($0) }
```
It's always been somewhat fraught to do simultaneous accesses to
an array because of copy-on-write. The fact that you should not
create an array and then fork off a bunch of threads that assign
into different elements concurrently has been independently
rediscovered by a number of different programmers. (Under this
proposal, we will still not be reliably detecting this problem
by default, because it is a race condition; see the section on
concurrency.) The main new limitation here is that some idioms
which did work on a single thread are going to be forbidden.
This may just be a cost of progress, but there are things we
can do to mitigate the problem.
In the long term, the API of ``Array`` and other collections
should be extended to ensure that there are good ways of achieving
the tasks that exclusivity enforcement has made difficult.
It will take experience living with exclusivity in order to
understand the problems and propose the right API additions.
In the short term, these problems can be worked around with
``withUnsafeMutableBufferPointer``.
We do know that swapping two array elements will be problematic,
and accordingly we are (separately proposing)[https://github.com/apple/swift-evolution/blob/master/proposals/0173-swap-indices.md] to add a
``swapAt`` method to ``MutableCollection`` that takes two indices
rather than two ``inout`` arguments. The Swift 3 compatibility
mode should recognize the swap-of-elements pattern and automatically
translate it to use ``swapAt``, and the 3-to-4 migrator should
perform this rewrite automatically.
### Class properties
Unlike value types, calling a method on a class doesn't formally access
the entire class instance. In fact, we never try to enforce exclusivity
of access on the whole object at all; we only enforce it for individual
stored properties. Among other things, this means that an access to a
class property never conflicts with an access to a different property.
There are two major reasons for this difference between value
and reference types.
The first reason is that it's important to allow overlapping method
calls to a single class instance. It's quite common for an object
to have methods called on it concurrently from different threads.
These methods may access different properties, or they may synchronize
their accesses to the same properties using locks, dispatch queues,
or some other thread-safe technique. Regardless, it's a widespread
pattern.
The second reason is that there's no benefit to trying to enforce
exclusivity of access to the entire class instance. For a value
type to be mutated, it has to be held in a variable, and it's
often possible to reason quite strongly about how that variable
is used. That means that the exclusivity rule that we're proposing
here allows us to make some very strong guarantees for value types,
generally making them an even tighter, lower-cost abstraction.
In contrast, it's inherent to the nature of reference types that
references can be copied pretty arbitrarily throughout a program.
The assumptions we want to make about value types depend on having
unique access to the variable holding the value; there's no way
to make a similar assumption about reference types without knowing
that we have a unique reference to the object, which would
radically change the programming model of classes and make them
unacceptable for the concurrent patterns described above.
### Disabling dynamic enforcement.
We could add an attribute which allows dynamic enforcement to
be downgraded to an unsafe-pointer-style undefined-behavior rule
on a variable-by-variable basis. This would allow programmers to
opt out of the expense of dynamic enforcement when it is known
to be unnecessary (e.g. because exclusivity is checked at some
higher level) or when the performance burden is simply too great.
There is some concern that adding this attribute might lead to
over-use and that we should only support it if we are certain
that the overheads cannot be reduced in some better way.
Since the rule still applies, and it's merely no longer being checked,
it makes sense to borrow the "checked" and "unchecked" terminology
from the optimizer settings.
```swift
class TreeNode {
@exclusivity(unchecked) var left: TreeNode?
@exclusivity(unchecked) var right: TreeNode?
}
```
### Closures
A closure (including both local function declarations and closure
expressions, whether explicit or autoclosure) is either "escaping" or
"non-escaping". Currently, a closure is considered non-escaping
only if it is:
- a closure expression which is immediately called,
- a closure expression which is passed as a non-escaping function
argument, or
- a local function which captures something that is not allowed
to escape, like an ``inout`` parameter.
It is likely that this definition will be broadened over time.
A variable is said to be escaping if it is captured in an escaping
closure; otherwise, it is non-escaping.
Escaping variables generally require dynamic enforcement instead of
static enforcement. This is because Swift cannot reason about when
an escaping closure will be called and thus when the variable will
be accessed. There are some circumstances where static enforcement
may still be allowed, for example when Swift can reason about how
the variable will be used after it is escaped, but this is only
possible as a best-effort improvement for special cases, not as a
general rule.
In contrast, non-escaping variables can always use static enforcement.
(In order to achieve this, we must impose a new restriction on
recursive uses of non-escaping closures; see below.) This guarantee
aligns a number of related semantic and performance goals. For
example, a non-escaping variable does not need to be allocated
on the heap; by also promising to only use static enforcement for
the variable, we are essentially able to guarantee that the variable
will have C-like performance, which can be important for some kinds
of program. This guarantee also ensures that only static enforcement
is needed for ``inout`` parameters, which cannot be captured in
escaping closures; this substantially simplifies the implementation
model for capturing ``inout`` parameters.
### Diagnosing dynamic enforcement violations statically
In general, Swift is permitted to upgrade dynamic enforcement to
static enforcement when it can prove that two accesses either
always or never conflict. This is analogous to Swift's rules
about integer overflow.
For example, if Swift can prove that two accesses to a global
variable will always conflict, then it can report that error
statically, even though global variables use dynamic enforcement:
```swift
var global: Int
swap(&global, &global) // Two overlapping modifications to 'global'
```
Swift is not required to prove that both accesses will actually
be executed dynamically in order to report a violation statically.
It is sufficient to prove that one of the accesses cannot ever
be executed without causing a conflict. For example, in the
following example, Swift does not need to prove that ``mutate``
actually calls its argument function:
```swift
// The inout access lasts for the duration of the call.
global.mutate { return global + 1 }
```
When a closure is passed as a non-escaping function argument
or captured in a closure that is passed as a non-escaping function
argument, Swift may assume that any accesses made by the closure
will be executed during the call, potentially conflicting with
accesses that overlap the call.
### Restrictions on recursive uses of non-escaping closures
In order to achieve the goal of guaranteeing the use of static
enforcement for variables that are captured only by non-escaping
closures, we do need to impose an additional restriction on
the use of such closures. This rule is as follows:
> A non-escaping closure ``A`` may not be recursively invoked
> during the execution of a non-escaping closure ``B`` which
> captures the same local variable or ``inout`` parameter unless:
>
> - ``A`` is defined within ``B`` or
>
> - ``A`` is a local function declaration which is referenced
> directly by ``B``.
For clarity, we will call this rule the Non-Escaping Recursion
Restriction, or NRR. The NRR is sufficient to prove that
non-escaping variables captured by ``B`` will not be interfered
with unless ``B`` delegates to something which is locally known by
``B`` to have access to those variables. This, together with the
fact that the uses of ``B`` itself can be statically analyzed by
its defining function, is sufficient to allow static enforcement
for the non-escaping variables it captures. (It also enables some
powerful analyses of captured variables within non-escaping
closures; we do not need to get into that here.)
Because of the tight restrictions on how non-escaping closures
can be used in Swift today, it's already quite difficult to
violate the NRR. The following user-level restrictions are
sufficient to ensure that the NRR is obeyed:
- A function may not call a non-escaping function parameter
passing a non-escaping function parameter as an argument.
For the purposes of this rule, a closure which captures
a non-escaping function parameter is treated the same as
the parameter.
We will call this rule the Non-Escaping Parameter Call
Restriction, or NPCR.
- Programmers using ``withoutActuallyEscaping`` should take
care not to allow the result to be recursively invoked.
The NPCR is a conservative over-approximation: that is, there
is code which does not violate the NRR which will be considered
ill-formed under the NPCR. This is unfortunate but inevitable.
Here is an example of the sort of code that will be disallowed
under the NPCR:
```swift
func recurse(fn: (() -> ()) -> ()) {
// Invoke the closure, passing a closure which, if invoked,
// will invoke the closure again.
fn { fn { } }
}
func apply<T>(argProvider: () -> T, fn: (() -> T) -> T) {
// Pass the first argument function to the second.
fn(argProvider)
}
```
Note that it's quite easy to come up with ways to use these
functions that wouldn't violate the NRR. For example, if
either argument to ``apply`` is not a closure, the call
cannot possibly violate the NRR. Nonetheless, we feel that
the NPCR is a reasonable restriction:
- Functions like ``recurse`` that apply a function to itself are
pretty much just of theoretical interest. Recursion is an
important programming tool, but nobody writes it like this
because it's just unnecessarily more difficult to reason about.
- Functions like ``apply`` that take two closures are not uncommon,
but they're likely to either invoke the closures sequentially,
which would not violate the NPCR, or else be some sort of
higher-order combinator, which would require the closures to be
``@escaping`` and thus also not violate the NPCR.
Note that passing two non-escaping functions as arguments to the
same call does not violate the NPCR. This is because the NPCR
will be enforced, recursively, in the callee. (Imported C
functions which take non-escaping block parameters can, of
course, easily violate the NPCR. They can also easily allow
the block to escape. We do not believe there are any existing
functions or methods on our target platforms that directly
violate the NPCR.)
In general, programmers who find the NPCR an unnecessarily
overbearing restriction can simply declare their function parameter
to be ``@escaping`` or, if they are certain that their code will
not violate the NRR, use ``withoutActuallyEscaping`` to disable
the NPCR check.
## Source compatibility
In order to gain the performance and language-design benefits of
exclusivity, we will have to enforce it in all language modes.
Therefore, exclusivity will eventually demand a source break.
We can mitigate some of the impact of this break by implicitly migrating
code matching certain patterns to use different patterns that are known
to satisfy the exclusivity rule. For example, it would be straightforward
to automatically translate calls like ``swap(&array[i], &array[j])`` to
``array.swapAt(i, j)``. Whether this makes sense for any particular
migration remains to be seen; for example, ``swap`` does not appear to be
used very often in practice outside of specific collection algorithms.
Overall, we do not expect that a significant amount of code will violate
exclusivity. This has been borne out so far by our testing. Often the
examples that do violate exclusivity can easily be rewritten to avoid
conflicts. In some of these cases, it may make sense to do the rewrite
automatically to avoid source-compatibility problems.
## Effect on ABI stability and resilience
In order to gain the performance and language-desing benefits of
exclusivity, we must be able to assume that it is followed faithfully
in various places throughout the ABI. Therefore, exclusivity must be
enforced before we commit to a stable ABI, or else we'll be stuck with
the current conservatism around ``inout`` and ``mutating`` methods
forever.
| rballard/swift-evolution | proposals/0176-enforce-exclusive-access-to-memory.md | Markdown | apache-2.0 | 32,557 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You 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.
*/
package org.apache.geode.internal.cache;
/**
* This class is an event that just holds an EventID. Unlike other EntryEventImpls this class does
* not need to be released since its values are never off-heap.
*/
public class EventIDHolder extends EntryEventImpl {
/*
* This constructor is used to create a bridge event in server-side command classes. Events
* created with this are not intended to be used in cache operations.
*
* @param id the identity of the client's event
*/
public EventIDHolder(EventID id) {
setEventId(id);
disallowOffHeapValues();
}
}
| smgoller/geode | geode-core/src/main/java/org/apache/geode/internal/cache/EventIDHolder.java | Java | apache-2.0 | 1,379 |
// Load required modules
var http = require("http"); // http server core module
var express = require("express"); // web framework external module
var io = require("socket.io"); // web socket external module
var easyrtc = require("easyrtc"); // EasyRTC external module
// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var httpApp = express();
httpApp.use(express.static(__dirname + "/static/"));
// Start Express http server on port 8080
var webServer = http.createServer(httpApp).listen(8080);
// Start Socket.io so it attaches itself to Express server
var socketServer = io.listen(webServer, {"log level":1});
// Start EasyRTC server
var rtc = easyrtc.listen(httpApp, socketServer);
| udayshankar3/nodeapp | server_example/server.js | JavaScript | bsd-2-clause | 806 |
/*
* Copyright (C) Yichun Zhang (agentzh)
*/
#ifndef DDEBUG
#define DDEBUG 0
#endif
#include "ddebug.h"
#include "ngx_http_lua_phase.h"
#include "ngx_http_lua_util.h"
#include "ngx_http_lua_ctx.h"
static int ngx_http_lua_ngx_get_phase(lua_State *L);
static int
ngx_http_lua_ngx_get_phase(lua_State *L)
{
ngx_http_request_t *r;
ngx_http_lua_ctx_t *ctx;
r = ngx_http_lua_get_req(L);
/* If we have no request object, assume we are called from the "init"
* phase. */
if (r == NULL) {
lua_pushlstring(L, (char *) "init", sizeof("init") - 1);
return 1;
}
ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module);
if (ctx == NULL) {
return luaL_error(L, "no request ctx found");
}
switch (ctx->context) {
case NGX_HTTP_LUA_CONTEXT_SET:
lua_pushliteral(L, "set");
break;
case NGX_HTTP_LUA_CONTEXT_REWRITE:
lua_pushliteral(L, "rewrite");
break;
case NGX_HTTP_LUA_CONTEXT_ACCESS:
lua_pushliteral(L, "access");
break;
case NGX_HTTP_LUA_CONTEXT_CONTENT:
lua_pushliteral(L, "content");
break;
case NGX_HTTP_LUA_CONTEXT_LOG:
lua_pushliteral(L, "log");
break;
case NGX_HTTP_LUA_CONTEXT_HEADER_FILTER:
lua_pushliteral(L, "header_filter");
break;
case NGX_HTTP_LUA_CONTEXT_BODY_FILTER:
lua_pushliteral(L, "body_filter");
break;
case NGX_HTTP_LUA_CONTEXT_TIMER:
lua_pushliteral(L, "timer");
break;
default:
return luaL_error(L, "unknown phase: %d", (int) ctx->context);
}
return 1;
}
void
ngx_http_lua_inject_phase_api(lua_State *L)
{
lua_pushcfunction(L, ngx_http_lua_ngx_get_phase);
lua_setfield(L, -2, "get_phase");
}
/* vi:set ft=c ts=4 sw=4 et fdm=marker: */
| miurahr/nginx-resty-ppa | debian/modules/ngx_lua-0.9.0/src/ngx_http_lua_phase.c | C | bsd-2-clause | 1,846 |
class NotationalVelocity < Cask
url 'http://notational.net/NotationalVelocity.zip'
homepage 'http://notational.net'
version 'latest'
no_checksum
link 'Notational Velocity.app'
end
| meduz/homebrew-cask | Casks/notational-velocity.rb | Ruby | bsd-2-clause | 190 |
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _TRAVERSE_H
#define _TRAVERSE_H
#pragma ident "%Z%%M% %I% %E% SMI"
/*
* Routines used to traverse tdesc trees, invoking user-supplied callbacks
* as the tree is traversed.
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "ctftools.h"
typedef int (*tdtrav_cb_f)(tdesc_t *, tdesc_t **, void *);
typedef struct tdtrav_data {
int vgen;
tdtrav_cb_f *firstops;
tdtrav_cb_f *preops;
tdtrav_cb_f *postops;
void *private;
} tdtrav_data_t;
void tdtrav_init(tdtrav_data_t *, int *, tdtrav_cb_f *, tdtrav_cb_f *,
tdtrav_cb_f *, void *);
int tdtraverse(tdesc_t *, tdesc_t **, tdtrav_data_t *);
int iitraverse(iidesc_t *, int *, tdtrav_cb_f *, tdtrav_cb_f *, tdtrav_cb_f *,
void *);
int iitraverse_hash(hash_t *, int *, tdtrav_cb_f *, tdtrav_cb_f *,
tdtrav_cb_f *, void *);
int iitraverse_td(void *, void *);
int tdtrav_assert(tdesc_t *, tdesc_t **, void *);
#ifdef __cplusplus
}
#endif
#endif /* _TRAVERSE_H */
| dplbsd/zcaplib | head/cddl/contrib/opensolaris/tools/ctf/cvt/traverse.h | C | bsd-2-clause | 1,890 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\PointLog */
$this->title = Yii::t('app', 'Create ') . Yii::t('app', 'Point Log');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Point Logs'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="point-log-create">
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| webwlsong/funshop | backend/views/point-log/create.php | PHP | bsd-3-clause | 428 |
Es troben disponibles els següents paràmetres:
<dl>
<dt><b>Taula</b>
<dd>La taula sobre la qual s'apliquen aquests permisos. <p>
<dt><b>Usuari</b>
<dd>L'usuari a qui es concedeixen els permisos.
Aquest usuari ja ha d'existir a la taula de <tt>Permisos d'Usuari</tt>. <p>
<dt><b>Hosts</b>
<dd>Els hosts des dels quals l'usuari pot accedir aquesta taula. <p>
<dt><b>Permisos de la taula</b>
<dd>Els permisos concedits a l'usuari sobre totes les columnes de la taula. <p>
<dt><b>Permisos de la Columna</b>
<dd>Els permisos màxims que es poden concedir a aquest usuari per
qualsevol columna de la taula a la pàgina <tt>Permisos de Columna</tt>. <p>
</dl>
| rcuvgd/Webmin22.01.2016 | mysql/help/tpriv.ca.html | HTML | bsd-3-clause | 660 |
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file recorderTable.h
* @author drose
* @date 2004-01-27
*/
#ifndef RECORDERTABLE_H
#define RECORDERTABLE_H
#include "pandabase.h"
#include "recorderBase.h"
#include "pointerTo.h"
#include "pmap.h"
#include "typedWritable.h"
class BamWriter;
class BamReader;
class FactoryParams;
/**
* This object is used by the RecorderController to write (and read) a record
* of the set of recorders in use to the bam file. Do not attempt to use it
* directly.
*/
class EXPCL_PANDA_RECORDER RecorderTable : public TypedWritable {
public:
INLINE RecorderTable();
INLINE RecorderTable(const RecorderTable ©);
INLINE void operator = (const RecorderTable ©);
~RecorderTable();
void merge_from(const RecorderTable &other);
INLINE void add_recorder(const std::string &name, RecorderBase *recorder);
INLINE RecorderBase *get_recorder(const std::string &name) const;
INLINE bool remove_recorder(const std::string &name);
void record_frame(BamWriter *manager, Datagram &dg);
void play_frame(DatagramIterator &scan, BamReader *manager);
void set_flags(short flags);
void clear_flags(short flags);
void write(std::ostream &out, int indent_level) const;
// RecorderBase itself doesn't inherit from ReferenceCount, so we can't put
// a PT() around it. Instead, we manage the reference count using calls to
// ref() and unref().
typedef pmap<std::string, RecorderBase*> Recorders;
Recorders _recorders;
bool _error;
public:
static void register_with_read_factory();
virtual void write_datagram(BamWriter *manager, Datagram &dg);
protected:
static TypedWritable *make_from_bam(const FactoryParams ¶ms);
void fillin(DatagramIterator &scan, BamReader *manager);
public:
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
TypedWritable::init_type();
register_type(_type_handle, "RecorderTable",
TypedWritable::get_class_type());
}
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
private:
static TypeHandle _type_handle;
};
#include "recorderTable.I"
#endif
| chandler14362/panda3d | panda/src/recorder/recorderTable.h | C | bsd-3-clause | 2,479 |
<h1><?php echo CHtml::encode($model->name); ?></h1>
<?php echo CHtml::image($model->file, $model->name, array('width' => 500, 'height' => 500)); ?>
<br/><br/>
<p><?php echo CHtml::encode($model->description);?></p>
<br/>
<?php $this->widget('application.modules.comment.widgets.CommentsListWidget', array('model' => $model, 'modelId' => $model->id)); ?>
<br/>
<?php if (Yii::app()->user->isAuthenticated()): ?>
<h3>Оставить комментарий</h3>
<?php $this->widget('application.modules.comment.widgets.CommentFormWidget', array('redirectTo' => $this->createUrl('/gallery/gallery/foto', array('id' => $model->id)), 'model' => $model, 'modelId' => $model->id)); ?>
<?php else: ?>
Для комментирования, пожалуйста, <?php echo CHtml::link('авторизуйтесь', array('/user/account/login')); ?>...
<?php endif; ?> | itrustam/cupon | protected/www/protected/modules/gallery/views/gallery/foto.php | PHP | bsd-3-clause | 875 |
<h3>Introducció a NFS</h3>
NFS és el protocol estàndard de compartició de fitxers dels sistemes Unix.
NFS permet que un sistema exporti un directori a través de la xarxa a un
o més hosts, cosa que permet els usuaris i programes d'aquests hosts
d'accedir aquests fitxers exportats com si fossin locals. <p>
Un servidor NFS és un sistema que exporta un o més directoris, mentre que
un client NFS és un sistema que munta un o més directoris des d'un servidor.
Un host pot ser al mateix temps un servidor NFS i un client d'un altre
servidor .<p>
Un servidor controla quins clients poden muntar un directori exportat
comprovant l'adreça IP del client contra una llista de hosts permesos
per al directori en qüestió. El servidor també pot establir que una
exportació sigui només lectura, o només lectura per a certs clients. <p>
Contràriament a altres sistemes de fitxers de xarxa. un client NFS no ha
de subministrar la contrasenya al servidor per muntar un directori exportat.
El servidor confia que els usuaris ja són autenticats pel client, i
subministra l'ID de l'usuari actual quan aquest accedeix als fitxers
exportats. Així doncs, és convenient que només els hosts client fiables
puguin muntar els directoris exportats. <p>
| rcuvgd/Webmin22.01.2016 | dfsadmin/help/nfs.ca.html | HTML | bsd-3-clause | 1,232 |
// Copyright 2014 The Chromium 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 "content/common/input/web_touch_event_traits.h"
#include "base/logging.h"
using blink::WebInputEvent;
using blink::WebTouchEvent;
using blink::WebTouchPoint;
namespace content {
bool WebTouchEventTraits::AllTouchPointsHaveState(
const WebTouchEvent& event,
blink::WebTouchPoint::State state) {
if (!event.touchesLength)
return false;
for (size_t i = 0; i < event.touchesLength; ++i) {
if (event.touches[i].state != state)
return false;
}
return true;
}
bool WebTouchEventTraits::IsTouchSequenceStart(const WebTouchEvent& event) {
DCHECK(event.touchesLength);
if (event.type != WebInputEvent::TouchStart)
return false;
return AllTouchPointsHaveState(event, blink::WebTouchPoint::StatePressed);
}
void WebTouchEventTraits::ResetType(WebInputEvent::Type type,
double timestamp_sec,
WebTouchEvent* event) {
DCHECK(WebInputEvent::isTouchEventType(type));
event->type = type;
event->cancelable = (type != WebInputEvent::TouchCancel);
event->timeStampSeconds = timestamp_sec;
}
void WebTouchEventTraits::ResetTypeAndTouchStates(WebInputEvent::Type type,
double timestamp_sec,
WebTouchEvent* event) {
ResetType(type, timestamp_sec, event);
WebTouchPoint::State newState = WebTouchPoint::StateUndefined;
switch (event->type) {
case WebInputEvent::TouchStart:
newState = WebTouchPoint::StatePressed;
break;
case WebInputEvent::TouchMove:
newState = WebTouchPoint::StateMoved;
break;
case WebInputEvent::TouchEnd:
newState = WebTouchPoint::StateReleased;
break;
case WebInputEvent::TouchCancel:
newState = WebTouchPoint::StateCancelled;
break;
default:
NOTREACHED();
break;
}
for (size_t i = 0; i < event->touchesLength; ++i)
event->touches[i].state = newState;
}
} // namespace content
| TeamEOS/external_chromium_org | content/common/input/web_touch_event_traits.cc | C++ | bsd-3-clause | 2,175 |
/*
**********************************************************************
* Copyright (C) 1999-2012, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Date Name Description
* 12/09/99 aliu Ported from Java.
**********************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "thcoll.h"
#include "unicode/utypes.h"
#include "unicode/coll.h"
#include "unicode/localpointer.h"
#include "unicode/sortkey.h"
#include "unicode/ustring.h"
#include "cstring.h"
#include "filestrm.h"
#include "textfile.h"
/**
* The TestDictionary test expects a file of this name, with this
* encoding, to be present in the directory $ICU/source/test/testdata.
*/
//#define TEST_FILE "th18057.txt"
/**
* This is the most failures we show in TestDictionary. If this number
* is < 0, we show all failures.
*/
#define MAX_FAILURES_TO_SHOW -1
CollationThaiTest::CollationThaiTest() {
UErrorCode status = U_ZERO_ERROR;
coll = Collator::createInstance(Locale("th", "TH", ""), status);
if (coll && U_SUCCESS(status)) {
//coll->setStrength(Collator::TERTIARY);
} else {
delete coll;
coll = 0;
}
}
CollationThaiTest::~CollationThaiTest() {
delete coll;
}
void CollationThaiTest::runIndexedTest(int32_t index, UBool exec, const char* &name,
char* /*par*/) {
if((!coll) && exec) {
dataerrln(__FILE__ " cannot test - failed to create collator.");
name = "some test";
return;
}
switch (index) {
TESTCASE(0,TestDictionary);
TESTCASE(1,TestCornerCases);
TESTCASE(2,TestNamesList);
TESTCASE(3,TestInvalidThai);
TESTCASE(4,TestReordering);
default: name = ""; break;
}
}
/**
* Read the external names list, and confirms that the collator
* gets the same results when comparing lines one to another
* using regular and iterative comparison.
*/
void CollationThaiTest::TestNamesList(void) {
if (coll == 0) {
errln("Error: could not construct Thai collator");
return;
}
UErrorCode ec = U_ZERO_ERROR;
TextFile names("TestNames_Thai.txt", "UTF16LE", ec);
if (U_FAILURE(ec)) {
logln("Can't open TestNames_Thai.txt: %s; skipping test",
u_errorName(ec));
return;
}
//
// Loop through each word in the dictionary and compare it to the previous
// word. They should be in sorted order.
//
UnicodeString lastWord, word;
//int32_t failed = 0;
int32_t wordCount = 0;
while (names.readLineSkippingComments(word, ec, FALSE) && U_SUCCESS(ec)) {
// Show the first 8 words being compared, so we can see what's happening
++wordCount;
if (wordCount <= 8) {
UnicodeString str;
logln((UnicodeString)"Word " + wordCount + ": " + IntlTest::prettify(word, str));
}
if (lastWord.length() > 0) {
Collator::EComparisonResult result = coll->compare(lastWord, word);
doTest(coll, lastWord, word, result);
}
lastWord = word;
}
assertSuccess("readLine", ec);
logln((UnicodeString)"Words checked: " + wordCount);
}
/**
* Read the external dictionary file, which is already in proper
* sorted order, and confirm that the collator compares each line as
* preceding the following line.
*/
void CollationThaiTest::TestDictionary(void) {
if (coll == 0) {
errln("Error: could not construct Thai collator");
return;
}
UErrorCode ec = U_ZERO_ERROR;
TextFile riwords("riwords.txt", "UTF8", ec);
if (U_FAILURE(ec)) {
logln("Can't open riwords.txt: %s; skipping test",
u_errorName(ec));
return;
}
//
// Loop through each word in the dictionary and compare it to the previous
// word. They should be in sorted order.
//
UnicodeString lastWord, word;
int32_t failed = 0;
int32_t wordCount = 0;
while (riwords.readLineSkippingComments(word, ec, FALSE) && U_SUCCESS(ec)) {
// Show the first 8 words being compared, so we can see what's happening
++wordCount;
if (wordCount <= 8) {
UnicodeString str;
logln((UnicodeString)"Word " + wordCount + ": " + IntlTest::prettify(word, str));
}
if (lastWord.length() > 0) {
int32_t result = coll->compare(lastWord, word);
if (result > 0) {
failed++;
if (MAX_FAILURES_TO_SHOW < 0 || failed <= MAX_FAILURES_TO_SHOW) {
UnicodeString str;
UnicodeString msg =
UnicodeString("--------------------------------------------\n")
+ riwords.getLineNumber()
+ " compare(" + IntlTest::prettify(lastWord, str);
msg += UnicodeString(", ")
+ IntlTest::prettify(word, str) + ") returned " + result
+ ", expected -1\n";
UErrorCode status = U_ZERO_ERROR;
CollationKey k1, k2;
coll->getCollationKey(lastWord, k1, status);
coll->getCollationKey(word, k2, status);
if (U_FAILURE(status)) {
errln((UnicodeString)"Fail: getCollationKey returned " + u_errorName(status));
return;
}
msg.append("key1: ").append(prettify(k1, str)).append("\n");
msg.append("key2: ").append(prettify(k2, str));
errln(msg);
}
}
}
lastWord = word;
}
assertSuccess("readLine", ec);
if (failed != 0) {
if (failed > MAX_FAILURES_TO_SHOW) {
errln((UnicodeString)"Too many failures; only the first " +
MAX_FAILURES_TO_SHOW + " failures were shown");
}
errln((UnicodeString)"Summary: " + failed + " of " + (riwords.getLineNumber() - 1) +
" comparisons failed");
}
logln((UnicodeString)"Words checked: " + wordCount);
}
/**
* Odd corner conditions taken from "How to Sort Thai Without Rewriting Sort",
* by Doug Cooper, http://seasrc.th.net/paper/thaisort.zip
*/
void CollationThaiTest::TestCornerCases(void) {
const char* TESTS[] = {
// Shorter words precede longer
"\\u0e01", "<", "\\u0e01\\u0e01",
// Tone marks are considered after letters (i.e. are primary ignorable)
"\\u0e01\\u0e32", "<", "\\u0e01\\u0e49\\u0e32",
// ditto for other over-marks
"\\u0e01\\u0e32", "<", "\\u0e01\\u0e32\\u0e4c",
// commonly used mark-in-context order.
// In effect, marks are sorted after each syllable.
"\\u0e01\\u0e32\\u0e01\\u0e49\\u0e32", "<", "\\u0e01\\u0e48\\u0e32\\u0e01\\u0e49\\u0e32",
// Hyphens and other punctuation follow whitespace but come before letters
"\\u0e01\\u0e32", "=", "\\u0e01\\u0e32-",
"\\u0e01\\u0e32-", "<", "\\u0e01\\u0e32\\u0e01\\u0e32",
// Doubler follows an indentical word without the doubler
"\\u0e01\\u0e32", "=", "\\u0e01\\u0e32\\u0e46",
"\\u0e01\\u0e32\\u0e46", "<", "\\u0e01\\u0e32\\u0e01\\u0e32",
// \\u0e45 after either \\u0e24 or \\u0e26 is treated as a single
// combining character, similar to "c < ch" in traditional spanish.
// TODO: beef up this case
"\\u0e24\\u0e29\\u0e35", "<", "\\u0e24\\u0e45\\u0e29\\u0e35",
"\\u0e26\\u0e29\\u0e35", "<", "\\u0e26\\u0e45\\u0e29\\u0e35",
// Vowels reorder, should compare \\u0e2d and \\u0e34
"\\u0e40\\u0e01\\u0e2d", "<", "\\u0e40\\u0e01\\u0e34",
// Tones are compared after the rest of the word (e.g. primary ignorable)
"\\u0e01\\u0e32\\u0e01\\u0e48\\u0e32", "<", "\\u0e01\\u0e49\\u0e32\\u0e01\\u0e32",
// Periods are ignored entirely
"\\u0e01.\\u0e01.", "<", "\\u0e01\\u0e32",
};
const int32_t TESTS_length = (int32_t)(sizeof(TESTS)/sizeof(TESTS[0]));
if (coll == 0) {
errln("Error: could not construct Thai collator");
return;
}
compareArray(*coll, TESTS, TESTS_length);
}
//------------------------------------------------------------------------
// Internal utilities
//------------------------------------------------------------------------
void CollationThaiTest::compareArray(Collator& c, const char* tests[],
int32_t testsLength) {
for (int32_t i = 0; i < testsLength; i += 3) {
Collator::EComparisonResult expect;
if (tests[i+1][0] == '<') {
expect = Collator::LESS;
} else if (tests[i+1][0] == '>') {
expect = Collator::GREATER;
} else if (tests[i+1][0] == '=') {
expect = Collator::EQUAL;
} else {
// expect = Integer.decode(tests[i+1]).intValue();
errln((UnicodeString)"Error: unknown operator " + tests[i+1]);
return;
}
UnicodeString s1, s2;
parseChars(s1, tests[i]);
parseChars(s2, tests[i+2]);
doTest(&c, s1, s2, expect);
#if 0
UErrorCode status = U_ZERO_ERROR;
int32_t result = c.compare(s1, s2);
if (sign(result) != sign(expect))
{
UnicodeString t1, t2;
errln(UnicodeString("") +
i/3 + ": compare(" + IntlTest::prettify(s1, t1)
+ " , " + IntlTest::prettify(s2, t2)
+ ") got " + result + "; expected " + expect);
CollationKey k1, k2;
c.getCollationKey(s1, k1, status);
c.getCollationKey(s2, k2, status);
if (U_FAILURE(status)) {
errln((UnicodeString)"Fail: getCollationKey returned " + u_errorName(status));
return;
}
errln((UnicodeString)" key1: " + prettify(k1, t1) );
errln((UnicodeString)" key2: " + prettify(k2, t2) );
}
else
{
// Collator.compare worked OK; now try the collation keys
CollationKey k1, k2;
c.getCollationKey(s1, k1, status);
c.getCollationKey(s2, k2, status);
if (U_FAILURE(status)) {
errln((UnicodeString)"Fail: getCollationKey returned " + u_errorName(status));
return;
}
result = k1.compareTo(k2);
if (sign(result) != sign(expect)) {
UnicodeString t1, t2;
errln(UnicodeString("") +
i/3 + ": key(" + IntlTest::prettify(s1, t1)
+ ").compareTo(key(" + IntlTest::prettify(s2, t2)
+ ")) got " + result + "; expected " + expect);
errln((UnicodeString)" " + prettify(k1, t1) + " vs. " + prettify(k2, t2));
}
}
#endif
}
}
int8_t CollationThaiTest::sign(int32_t i) {
if (i < 0) return -1;
if (i > 0) return 1;
return 0;
}
/**
* Set a UnicodeString corresponding to the given string. Use
* UnicodeString and the default converter, unless we see the sequence
* "\\u", in which case we interpret the subsequent escape.
*/
UnicodeString& CollationThaiTest::parseChars(UnicodeString& result,
const char* chars) {
return result = CharsToUnicodeString(chars);
}
UCollator *thaiColl = NULL;
U_CDECL_BEGIN
static int U_CALLCONV
StrCmp(const void *p1, const void *p2) {
return ucol_strcoll(thaiColl, *(UChar **) p1, -1, *(UChar **)p2, -1);
}
U_CDECL_END
#define LINES 6
void CollationThaiTest::TestInvalidThai(void) {
const char *tests[LINES] = {
"\\u0E44\\u0E01\\u0E44\\u0E01",
"\\u0E44\\u0E01\\u0E01\\u0E44",
"\\u0E01\\u0E44\\u0E01\\u0E44",
"\\u0E01\\u0E01\\u0E44\\u0E44",
"\\u0E44\\u0E44\\u0E01\\u0E01",
"\\u0E01\\u0E44\\u0E44\\u0E01",
};
UChar strings[LINES][20];
UChar *toSort[LINES];
int32_t i = 0, j = 0, len = 0;
UErrorCode coll_status = U_ZERO_ERROR;
UnicodeString iteratorText;
thaiColl = ucol_open ("th_TH", &coll_status);
if (U_FAILURE(coll_status)) {
errln("Error opening Thai collator: %s", u_errorName(coll_status));
return;
}
CollationElementIterator* c = ((RuleBasedCollator *)coll)->createCollationElementIterator( iteratorText );
for(i = 0; i < (int32_t)(sizeof(tests)/sizeof(tests[0])); i++) {
len = u_unescape(tests[i], strings[i], 20);
strings[i][len] = 0;
toSort[i] = strings[i];
}
qsort (toSort, LINES, sizeof (UChar *), StrCmp);
for (i=0; i < LINES; i++)
{
logln("%i", i);
for (j=i+1; j < LINES; j++) {
if (ucol_strcoll (thaiColl, toSort[i], -1, toSort[j], -1) == UCOL_GREATER)
{
// inconsistency ordering found!
errln("Inconsistent ordering between strings %i and %i", i, j);
}
}
iteratorText.setTo(toSort[i]);
c->setText(iteratorText, coll_status);
backAndForth(*c);
}
ucol_close(thaiColl);
delete c;
}
void CollationThaiTest::TestReordering(void) {
// Until UCA 4.1, the collation code swapped Thai/Lao prevowels with the following consonants,
// resulting in consonant+prevowel == prevowel+consonant.
// From UCA 5.0 on, there are order-reversing contractions for prevowel+consonant.
// From UCA 5.0 until UCA 6.1, there was a tertiary difference between
// consonant+prevowel and prevowel+consonant.
// In UCA 6.2, they compare equal again.
// The test was modified to using a collator with strength=secondary,
// ignoring possible tertiary differences.
const char *tests[] = {
"\\u0E41c\\u0301", "=", "\\u0E41\\u0107", // composition
"\\u0E41\\U0001D7CE", "<", "\\u0E41\\U0001D7CF", // supplementaries
"\\u0E41\\U0001D15F", "=", "\\u0E41\\U0001D158\\U0001D165", // supplementary composition decomps to supplementary
"\\u0E41\\U0002F802", "=", "\\u0E41\\u4E41", // supplementary composition decomps to BMP
"\\u0E41\\u0301", "=", "\\u0E41\\u0301", // unsafe (just checking backwards iteration)
"\\u0E41\\u0301\\u0316", "=", "\\u0E41\\u0316\\u0301",
"\\u0e24\\u0e41", "=", "\\u0e41\\u0e24", // exiting contraction bug
"\\u0e3f\\u0e3f\\u0e24\\u0e41", "=", "\\u0e3f\\u0e3f\\u0e41\\u0e24",
"abc\\u0E41c\\u0301", "=", "abc\\u0E41\\u0107", // composition
"abc\\u0E41\\U0001D000", "<", "abc\\u0E41\\U0001D001", // supplementaries
"abc\\u0E41\\U0001D15F", "=", "abc\\u0E41\\U0001D158\\U0001D165", // supplementary composition decomps to supplementary
"abc\\u0E41\\U0002F802", "=", "abc\\u0E41\\u4E41", // supplementary composition decomps to BMP
"abc\\u0E41\\u0301", "=", "abc\\u0E41\\u0301", // unsafe (just checking backwards iteration)
"abc\\u0E41\\u0301\\u0316", "=", "abc\\u0E41\\u0316\\u0301",
"\\u0E41c\\u0301abc", "=", "\\u0E41\\u0107abc", // composition
"\\u0E41\\U0001D000abc", "<", "\\u0E41\\U0001D001abc", // supplementaries
"\\u0E41\\U0001D15Fabc", "=", "\\u0E41\\U0001D158\\U0001D165abc", // supplementary composition decomps to supplementary
"\\u0E41\\U0002F802abc", "=", "\\u0E41\\u4E41abc", // supplementary composition decomps to BMP
"\\u0E41\\u0301abc", "=", "\\u0E41\\u0301abc", // unsafe (just checking backwards iteration)
"\\u0E41\\u0301\\u0316abc", "=", "\\u0E41\\u0316\\u0301abc",
"abc\\u0E41c\\u0301abc", "=", "abc\\u0E41\\u0107abc", // composition
"abc\\u0E41\\U0001D000abc", "<", "abc\\u0E41\\U0001D001abc", // supplementaries
"abc\\u0E41\\U0001D15Fabc", "=", "abc\\u0E41\\U0001D158\\U0001D165abc", // supplementary composition decomps to supplementary
"abc\\u0E41\\U0002F802abc", "=", "abc\\u0E41\\u4E41abc", // supplementary composition decomps to BMP
"abc\\u0E41\\u0301abc", "=", "abc\\u0E41\\u0301abc", // unsafe (just checking backwards iteration)
"abc\\u0E41\\u0301\\u0316abc", "=", "abc\\u0E41\\u0316\\u0301abc",
};
LocalPointer<Collator> coll2(coll->clone());
UErrorCode status = U_ZERO_ERROR;
coll2->setAttribute(UCOL_STRENGTH, UCOL_SECONDARY, status);
if(U_FAILURE(status)) {
errln("Unable to set the Thai collator clone to secondary strength");
return;
}
compareArray(*coll2, tests, sizeof(tests)/sizeof(tests[0]));
const char *rule = "& c < ab";
const char *testcontraction[] = { "\\u0E41ab", ">", "\\u0E41c"}; // After UCA 4.1 Thai are normal so won't break a contraction
UnicodeString rules;
parseChars(rules, rule);
LocalPointer<RuleBasedCollator> rcoll(new RuleBasedCollator(rules, status));
if(U_SUCCESS(status)) {
compareArray(*rcoll, testcontraction, 3);
} else {
errln("Couldn't instantiate collator from rules");
}
}
#endif /* #if !UCONFIG_NO_COLLATION */
| mxOBS/deb-pkg_trusty_chromium-browser | third_party/icu/source/test/intltest/thcoll.cpp | C++ | bsd-3-clause | 17,321 |
#!/usr/bin/env python
import clean_json_attrs
import json
import os
import shutil
import tempfile
import unittest
class CleanJsonAttrs(unittest.TestCase):
def setUp(self):
self._start_dir = tempfile.mkdtemp(dir=os.path.dirname(__file__))
self._kwargs = {
'file_pattern': 'package\.json',
'attr_pattern': '^_',
'start_dir': self._start_dir
}
def tearDown(self):
assert self._start_dir
shutil.rmtree(self._start_dir)
def _read_temp_file(self, filename):
return json.loads(open(os.path.join(self._start_dir, filename)).read())
def _write_temp_file(self, filename, json_dict):
with open(os.path.join(self._start_dir, filename), 'w') as f:
f.write(json.dumps(json_dict))
def testAttrPattern(self):
self._write_temp_file('package.json', {
'delete_me': True,
'ignore_me': True,
'version': '2.3.4',
})
args = self._kwargs.copy()
args['attr_pattern'] = '^delete'
self.assertTrue(clean_json_attrs.Clean(**args))
json_dict = self._read_temp_file('package.json')
self.assertEquals(['ignore_me', 'version'], sorted(json_dict.keys()))
def testFilePattern(self):
self._write_temp_file('clean_me.json', {'_where': '/a/b/c'})
self._write_temp_file('ignore_me.json', {'_args': ['/a/b/c']})
args = self._kwargs.copy()
args['file_pattern'] = '^clean_'
self.assertTrue(clean_json_attrs.Clean(**args))
self.assertEquals([], self._read_temp_file('clean_me.json').keys())
self.assertEquals(['_args'], self._read_temp_file('ignore_me.json').keys())
def testNestedKeys(self):
self._write_temp_file('package.json', {
'_args': ['/some/path/'],
'nested': {
'_keys': [],
'also': {
'_get': 'scanned',
},
},
'_where': '/some/path',
'version': '2.0.0'
})
self.assertTrue(clean_json_attrs.Clean(**self._kwargs))
json_dict = self._read_temp_file('package.json')
self.assertEquals(['nested', 'version'], sorted(json_dict.keys()))
self.assertEquals(['also'], json_dict['nested'].keys())
self.assertEquals([], json_dict['nested']['also'].keys())
def testNothingToRemove(self):
self._write_temp_file('package.json', {'version': '2.0.0'})
self.assertFalse(clean_json_attrs.Clean(**self._kwargs))
self.assertEquals(['version'], self._read_temp_file('package.json').keys())
def testSimple(self):
self._write_temp_file('package.json', {
'_args': ['/some/path/'],
'version': '2.0.0',
'_where': '/some/path'
})
self.assertTrue(clean_json_attrs.Clean(**self._kwargs))
self.assertEquals(['version'], self._read_temp_file('package.json').keys())
if __name__ == '__main__':
unittest.main()
| nwjs/chromium.src | third_party/node/clean_json_attrs_test.py | Python | bsd-3-clause | 2,783 |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.mediafilter;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.textmining.extraction.TextExtractor;
import org.textmining.extraction.word.WordTextExtractorFactory;
/*
*
* to do: helpful error messages - can't find mediafilter.cfg - can't
* instantiate filter - bitstream format doesn't exist
*
*/
public class WordFilter extends MediaFilter
{
private static Logger log = Logger.getLogger(WordFilter.class);
public String getFilteredName(String oldFilename)
{
return oldFilename + ".txt";
}
/**
* @return String bundle name
*
*/
public String getBundleName()
{
return "TEXT";
}
/**
* @return String bitstreamformat
*/
public String getFormatString()
{
return "Text";
}
/**
* @return String description
*/
public String getDescription()
{
return "Extracted text";
}
/**
* @param source
* source input stream
*
* @return InputStream the resulting input stream
*/
public InputStream getDestinationStream(InputStream source)
throws Exception
{
// get input stream from bitstream
// pass to filter, get string back
try
{
WordTextExtractorFactory factory = new WordTextExtractorFactory();
TextExtractor e = factory.textExtractor(source);
String extractedText = e.getText();
// if verbose flag is set, print out extracted text
// to STDOUT
if (MediaFilterManager.isVerbose)
{
System.out.println(extractedText);
}
// generate an input stream with the extracted text
byte[] textBytes = extractedText.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(textBytes);
return bais; // will this work? or will the byte array be out of scope?
}
catch (IOException ioe)
{
System.out.println("Invalid Word Format");
log.error("Error detected - Word File format not recognized: " + ioe.getMessage(), ioe);
}
return null;
}
}
| jamie-dryad/dryad-repo | dspace-api/src/main/java/org/dspace/app/mediafilter/WordFilter.java | Java | bsd-3-clause | 2,525 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.