repo_name
string
path
string
copies
string
size
string
content
string
license
string
0x0all/ROOT
interpreter/llvm/src/tools/clang/test/CodeGen/aarch64-neon-vget-hilo.c
15
4685
// REQUIRES: aarch64-registered-target // RUN: %clang_cc1 -triple arm64-none-linux-gnu -target-feature +neon \ // RUN: -ffp-contract=fast -S -O3 -o - %s | FileCheck %s --check-prefix CHECK-COMMON --check-prefix CHECK-ARM64 // Test new aarch64 intrinsics and types #include <arm_neon.h> int8x8_t test_vget_high_s8(int8x16_t a) { // CHECK-COMMON-LABEL: test_vget_high_s8: return vget_high_s8(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } int16x4_t test_vget_high_s16(int16x8_t a) { // CHECK-COMMON-LABEL: test_vget_high_s16: return vget_high_s16(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } int32x2_t test_vget_high_s32(int32x4_t a) { // CHECK-COMMON-LABEL: test_vget_high_s32: return vget_high_s32(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } int64x1_t test_vget_high_s64(int64x2_t a) { // CHECK-COMMON-LABEL: test_vget_high_s64: return vget_high_s64(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } uint8x8_t test_vget_high_u8(uint8x16_t a) { // CHECK-COMMON-LABEL: test_vget_high_u8: return vget_high_u8(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } uint16x4_t test_vget_high_u16(uint16x8_t a) { // CHECK-COMMON-LABEL: test_vget_high_u16: return vget_high_u16(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } uint32x2_t test_vget_high_u32(uint32x4_t a) { // CHECK-COMMON-LABEL: test_vget_high_u32: return vget_high_u32(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } uint64x1_t test_vget_high_u64(uint64x2_t a) { // CHECK-COMMON-LABEL: test_vget_high_u64: return vget_high_u64(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } poly64x1_t test_vget_high_p64(poly64x2_t a) { // CHECK-COMMON-LABEL: test_vget_high_p64: return vget_high_p64(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } float16x4_t test_vget_high_f16(float16x8_t a) { // CHECK-COMMON-LABEL: test_vget_high_f16: return vget_high_f16(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } float32x2_t test_vget_high_f32(float32x4_t a) { // CHECK-COMMON-LABEL: test_vget_high_f32: return vget_high_f32(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } poly8x8_t test_vget_high_p8(poly8x16_t a) { // CHECK-COMMON-LABEL: test_vget_high_p8: return vget_high_p8(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } poly16x4_t test_vget_high_p16(poly16x8_t a) { // CHECK-COMMON-LABEL: test_vget_high_p16 return vget_high_p16(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } float64x1_t test_vget_high_f64(float64x2_t a) { // CHECK-COMMON-LABEL: test_vget_high_f64 return vget_high_f64(a); // CHECK-ARM64: ext v0.16b, v0.16b, v0.16b, #8 } int8x8_t test_vget_low_s8(int8x16_t a) { // CHECK-COMMON-LABEL: test_vget_low_s8: return vget_low_s8(a); // CHECK-COMMON-NEXT: ret } int16x4_t test_vget_low_s16(int16x8_t a) { // CHECK-COMMON-LABEL: test_vget_low_s16: return vget_low_s16(a); // CHECK-COMMON-NEXT: ret } int32x2_t test_vget_low_s32(int32x4_t a) { // CHECK-COMMON-LABEL: test_vget_low_s32: return vget_low_s32(a); // CHECK-COMMON-NEXT: ret } int64x1_t test_vget_low_s64(int64x2_t a) { // CHECK-COMMON-LABEL: test_vget_low_s64: return vget_low_s64(a); // CHECK-COMMON-NEXT: ret } uint8x8_t test_vget_low_u8(uint8x16_t a) { // CHECK-COMMON-LABEL: test_vget_low_u8: return vget_low_u8(a); // CHECK-COMMON-NEXT: ret } uint16x4_t test_vget_low_u16(uint16x8_t a) { // CHECK-COMMON-LABEL: test_vget_low_u16: return vget_low_u16(a); // CHECK-COMMON-NEXT: ret } uint32x2_t test_vget_low_u32(uint32x4_t a) { // CHECK-COMMON-LABEL: test_vget_low_u32: return vget_low_u32(a); // CHECK-COMMON-NEXT: ret } uint64x1_t test_vget_low_u64(uint64x2_t a) { // CHECK-COMMON-LABEL: test_vget_low_u64: return vget_low_u64(a); // CHECK-COMMON-NEXT: ret } poly64x1_t test_vget_low_p64(poly64x2_t a) { // CHECK-COMMON-LABEL: test_vget_low_p64: return vget_low_p64(a); // CHECK-COMMON-NEXT: ret } float16x4_t test_vget_low_f16(float16x8_t a) { // CHECK-COMMON-LABEL: test_vget_low_f16: return vget_low_f16(a); // CHECK-COMMON-NEXT: ret } float32x2_t test_vget_low_f32(float32x4_t a) { // CHECK-COMMON-LABEL: test_vget_low_f32: return vget_low_f32(a); // CHECK-COMMON-NEXT: ret } poly8x8_t test_vget_low_p8(poly8x16_t a) { // CHECK-COMMON-LABEL: test_vget_low_p8: return vget_low_p8(a); // CHECK-COMMON-NEXT: ret } poly16x4_t test_vget_low_p16(poly16x8_t a) { // CHECK-COMMON-LABEL: test_vget_low_p16: return vget_low_p16(a); // CHECK-COMMON-NEXT: ret } float64x1_t test_vget_low_f64(float64x2_t a) { // CHECK-COMMON-LABEL: test_vget_low_f64: return vget_low_f64(a); // CHECK-COMMON-NEXT: ret }
lgpl-2.1
foxban/libvirt-0.9.12-centos5
gnulib/tests/test-stdint.c
16
11390
/* Test of <stdint.h> substitute. Copyright (C) 2006-2012 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Written by Bruno Haible <bruno@clisp.org>, 2006. */ #include <config.h> /* Whether to enable pedantic checks. */ #define DO_PEDANTIC 0 #include <stdint.h> #include "verify.h" #include "intprops.h" #if __GNUC__ >= 2 && DO_PEDANTIC # define verify_same_types(expr1,expr2) \ extern void _verify_func(__LINE__) (__typeof__ (expr1) *); \ extern void _verify_func(__LINE__) (__typeof__ (expr2) *); # define _verify_func(line) _verify_func2(line) # define _verify_func2(line) verify_func_ ## line #else # define verify_same_types(expr1,expr2) extern void verify_func (int) #endif /* 7.18.1.1. Exact-width integer types */ /* 7.18.2.1. Limits of exact-width integer types */ int8_t a1[3] = { INT8_C (17), INT8_MIN, INT8_MAX }; verify (TYPE_MINIMUM (int8_t) == INT8_MIN); verify (TYPE_MAXIMUM (int8_t) == INT8_MAX); verify_same_types (INT8_MIN, (int8_t) 0 + 0); verify_same_types (INT8_MAX, (int8_t) 0 + 0); int16_t a2[3] = { INT16_C (17), INT16_MIN, INT16_MAX }; verify (TYPE_MINIMUM (int16_t) == INT16_MIN); verify (TYPE_MAXIMUM (int16_t) == INT16_MAX); verify_same_types (INT16_MIN, (int16_t) 0 + 0); verify_same_types (INT16_MAX, (int16_t) 0 + 0); int32_t a3[3] = { INT32_C (17), INT32_MIN, INT32_MAX }; verify (TYPE_MINIMUM (int32_t) == INT32_MIN); verify (TYPE_MAXIMUM (int32_t) == INT32_MAX); verify_same_types (INT32_MIN, (int32_t) 0 + 0); verify_same_types (INT32_MAX, (int32_t) 0 + 0); #ifdef INT64_MAX int64_t a4[3] = { INT64_C (17), INT64_MIN, INT64_MAX }; verify (TYPE_MINIMUM (int64_t) == INT64_MIN); verify (TYPE_MAXIMUM (int64_t) == INT64_MAX); verify_same_types (INT64_MIN, (int64_t) 0 + 0); verify_same_types (INT64_MAX, (int64_t) 0 + 0); #endif uint8_t b1[2] = { UINT8_C (17), UINT8_MAX }; verify (TYPE_MAXIMUM (uint8_t) == UINT8_MAX); verify_same_types (UINT8_MAX, (uint8_t) 0 + 0); uint16_t b2[2] = { UINT16_C (17), UINT16_MAX }; verify (TYPE_MAXIMUM (uint16_t) == UINT16_MAX); verify_same_types (UINT16_MAX, (uint16_t) 0 + 0); uint32_t b3[2] = { UINT32_C (17), UINT32_MAX }; verify (TYPE_MAXIMUM (uint32_t) == UINT32_MAX); verify_same_types (UINT32_MAX, (uint32_t) 0 + 0); #ifdef UINT64_MAX uint64_t b4[2] = { UINT64_C (17), UINT64_MAX }; verify (TYPE_MAXIMUM (uint64_t) == UINT64_MAX); verify_same_types (UINT64_MAX, (uint64_t) 0 + 0); #endif #if INT8_MIN && INT8_MAX && INT16_MIN && INT16_MAX && INT32_MIN && INT32_MAX /* ok */ #else err or; #endif #if UINT8_MAX && UINT16_MAX && UINT32_MAX /* ok */ #else err or; #endif /* 7.18.1.2. Minimum-width integer types */ /* 7.18.2.2. Limits of minimum-width integer types */ int_least8_t c1[3] = { 17, INT_LEAST8_MIN, INT_LEAST8_MAX }; verify (TYPE_MINIMUM (int_least8_t) == INT_LEAST8_MIN); verify (TYPE_MAXIMUM (int_least8_t) == INT_LEAST8_MAX); verify_same_types (INT_LEAST8_MIN, (int_least8_t) 0 + 0); verify_same_types (INT_LEAST8_MAX, (int_least8_t) 0 + 0); int_least16_t c2[3] = { 17, INT_LEAST16_MIN, INT_LEAST16_MAX }; verify (TYPE_MINIMUM (int_least16_t) == INT_LEAST16_MIN); verify (TYPE_MAXIMUM (int_least16_t) == INT_LEAST16_MAX); verify_same_types (INT_LEAST16_MIN, (int_least16_t) 0 + 0); verify_same_types (INT_LEAST16_MAX, (int_least16_t) 0 + 0); int_least32_t c3[3] = { 17, INT_LEAST32_MIN, INT_LEAST32_MAX }; verify (TYPE_MINIMUM (int_least32_t) == INT_LEAST32_MIN); verify (TYPE_MAXIMUM (int_least32_t) == INT_LEAST32_MAX); verify_same_types (INT_LEAST32_MIN, (int_least32_t) 0 + 0); verify_same_types (INT_LEAST32_MAX, (int_least32_t) 0 + 0); #ifdef INT_LEAST64_MAX int_least64_t c4[3] = { 17, INT_LEAST64_MIN, INT_LEAST64_MAX }; verify (TYPE_MINIMUM (int_least64_t) == INT_LEAST64_MIN); verify (TYPE_MAXIMUM (int_least64_t) == INT_LEAST64_MAX); verify_same_types (INT_LEAST64_MIN, (int_least64_t) 0 + 0); verify_same_types (INT_LEAST64_MAX, (int_least64_t) 0 + 0); #endif uint_least8_t d1[2] = { 17, UINT_LEAST8_MAX }; verify (TYPE_MAXIMUM (uint_least8_t) == UINT_LEAST8_MAX); verify_same_types (UINT_LEAST8_MAX, (uint_least8_t) 0 + 0); uint_least16_t d2[2] = { 17, UINT_LEAST16_MAX }; verify (TYPE_MAXIMUM (uint_least16_t) == UINT_LEAST16_MAX); verify_same_types (UINT_LEAST16_MAX, (uint_least16_t) 0 + 0); uint_least32_t d3[2] = { 17, UINT_LEAST32_MAX }; verify (TYPE_MAXIMUM (uint_least32_t) == UINT_LEAST32_MAX); verify_same_types (UINT_LEAST32_MAX, (uint_least32_t) 0 + 0); #ifdef UINT_LEAST64_MAX uint_least64_t d4[2] = { 17, UINT_LEAST64_MAX }; verify (TYPE_MAXIMUM (uint_least64_t) == UINT_LEAST64_MAX); verify_same_types (UINT_LEAST64_MAX, (uint_least64_t) 0 + 0); #endif #if INT_LEAST8_MIN && INT_LEAST8_MAX && INT_LEAST16_MIN && INT_LEAST16_MAX && INT_LEAST32_MIN && INT_LEAST32_MAX /* ok */ #else err or; #endif #if UINT_LEAST8_MAX && UINT_LEAST16_MAX && UINT_LEAST32_MAX /* ok */ #else err or; #endif /* 7.18.1.3. Fastest minimum-width integer types */ /* 7.18.2.3. Limits of fastest minimum-width integer types */ int_fast8_t e1[3] = { 17, INT_FAST8_MIN, INT_FAST8_MAX }; verify (TYPE_MINIMUM (int_fast8_t) == INT_FAST8_MIN); verify (TYPE_MAXIMUM (int_fast8_t) == INT_FAST8_MAX); verify_same_types (INT_FAST8_MIN, (int_fast8_t) 0 + 0); verify_same_types (INT_FAST8_MAX, (int_fast8_t) 0 + 0); int_fast16_t e2[3] = { 17, INT_FAST16_MIN, INT_FAST16_MAX }; verify (TYPE_MINIMUM (int_fast16_t) == INT_FAST16_MIN); verify (TYPE_MAXIMUM (int_fast16_t) == INT_FAST16_MAX); verify_same_types (INT_FAST16_MIN, (int_fast16_t) 0 + 0); verify_same_types (INT_FAST16_MAX, (int_fast16_t) 0 + 0); int_fast32_t e3[3] = { 17, INT_FAST32_MIN, INT_FAST32_MAX }; verify (TYPE_MINIMUM (int_fast32_t) == INT_FAST32_MIN); verify (TYPE_MAXIMUM (int_fast32_t) == INT_FAST32_MAX); verify_same_types (INT_FAST32_MIN, (int_fast32_t) 0 + 0); verify_same_types (INT_FAST32_MAX, (int_fast32_t) 0 + 0); #ifdef INT_FAST64_MAX int_fast64_t e4[3] = { 17, INT_FAST64_MIN, INT_FAST64_MAX }; verify (TYPE_MINIMUM (int_fast64_t) == INT_FAST64_MIN); verify (TYPE_MAXIMUM (int_fast64_t) == INT_FAST64_MAX); verify_same_types (INT_FAST64_MIN, (int_fast64_t) 0 + 0); verify_same_types (INT_FAST64_MAX, (int_fast64_t) 0 + 0); #endif uint_fast8_t f1[2] = { 17, UINT_FAST8_MAX }; verify (TYPE_MAXIMUM (uint_fast8_t) == UINT_FAST8_MAX); verify_same_types (UINT_FAST8_MAX, (uint_fast8_t) 0 + 0); uint_fast16_t f2[2] = { 17, UINT_FAST16_MAX }; verify (TYPE_MAXIMUM (uint_fast16_t) == UINT_FAST16_MAX); verify_same_types (UINT_FAST16_MAX, (uint_fast16_t) 0 + 0); uint_fast32_t f3[2] = { 17, UINT_FAST32_MAX }; verify (TYPE_MAXIMUM (uint_fast32_t) == UINT_FAST32_MAX); verify_same_types (UINT_FAST32_MAX, (uint_fast32_t) 0 + 0); #ifdef UINT_FAST64_MAX uint_fast64_t f4[2] = { 17, UINT_FAST64_MAX }; verify (TYPE_MAXIMUM (uint_fast64_t) == UINT_FAST64_MAX); verify_same_types (UINT_FAST64_MAX, (uint_fast64_t) 0 + 0); #endif #if INT_FAST8_MIN && INT_FAST8_MAX && INT_FAST16_MIN && INT_FAST16_MAX && INT_FAST32_MIN && INT_FAST32_MAX /* ok */ #else err or; #endif #if UINT_FAST8_MAX && UINT_FAST16_MAX && UINT_FAST32_MAX /* ok */ #else err or; #endif /* 7.18.1.4. Integer types capable of holding object pointers */ /* 7.18.2.4. Limits of integer types capable of holding object pointers */ intptr_t g[3] = { 17, INTPTR_MIN, INTPTR_MAX }; verify (TYPE_MINIMUM (intptr_t) == INTPTR_MIN); verify (TYPE_MAXIMUM (intptr_t) == INTPTR_MAX); verify_same_types (INTPTR_MIN, (intptr_t) 0 + 0); verify_same_types (INTPTR_MAX, (intptr_t) 0 + 0); uintptr_t h[2] = { 17, UINTPTR_MAX }; verify (TYPE_MAXIMUM (uintptr_t) == UINTPTR_MAX); verify_same_types (UINTPTR_MAX, (uintptr_t) 0 + 0); #if INTPTR_MIN && INTPTR_MAX && UINTPTR_MAX /* ok */ #else err or; #endif /* 7.18.1.5. Greatest-width integer types */ /* 7.18.2.5. Limits of greatest-width integer types */ intmax_t i[3] = { INTMAX_C (17), INTMAX_MIN, INTMAX_MAX }; verify (TYPE_MINIMUM (intmax_t) == INTMAX_MIN); verify (TYPE_MAXIMUM (intmax_t) == INTMAX_MAX); verify_same_types (INTMAX_MIN, (intmax_t) 0 + 0); verify_same_types (INTMAX_MAX, (intmax_t) 0 + 0); uintmax_t j[2] = { UINTMAX_C (17), UINTMAX_MAX }; verify (TYPE_MAXIMUM (uintmax_t) == UINTMAX_MAX); verify_same_types (UINTMAX_MAX, (uintmax_t) 0 + 0); /* As of 2007, Sun C and HP-UX 10.20 cc don't support 'long long' constants in the preprocessor. */ #if !(defined __SUNPRO_C || (defined __hpux && !defined __GNUC__)) #if INTMAX_MIN && INTMAX_MAX && UINTMAX_MAX /* ok */ #else err or; #endif #endif /* 7.18.3. Limits of other integer types */ #include <stddef.h> verify (TYPE_MINIMUM (ptrdiff_t) == PTRDIFF_MIN); verify (TYPE_MAXIMUM (ptrdiff_t) == PTRDIFF_MAX); verify_same_types (PTRDIFF_MIN, (ptrdiff_t) 0 + 0); verify_same_types (PTRDIFF_MAX, (ptrdiff_t) 0 + 0); #if PTRDIFF_MIN && PTRDIFF_MAX /* ok */ #else err or; #endif #include <signal.h> verify (TYPE_MINIMUM (sig_atomic_t) == SIG_ATOMIC_MIN); verify (TYPE_MAXIMUM (sig_atomic_t) == SIG_ATOMIC_MAX); verify_same_types (SIG_ATOMIC_MIN, (sig_atomic_t) 0 + 0); verify_same_types (SIG_ATOMIC_MAX, (sig_atomic_t) 0 + 0); #if SIG_ATOMIC_MIN != 17 && SIG_ATOMIC_MAX /* ok */ #else err or; #endif verify (TYPE_MAXIMUM (size_t) == SIZE_MAX); verify_same_types (SIZE_MAX, (size_t) 0 + 0); #if SIZE_MAX /* ok */ #else err or; #endif #if HAVE_WCHAR_T verify (TYPE_MINIMUM (wchar_t) == WCHAR_MIN); verify (TYPE_MAXIMUM (wchar_t) == WCHAR_MAX); verify_same_types (WCHAR_MIN, (wchar_t) 0 + 0); verify_same_types (WCHAR_MAX, (wchar_t) 0 + 0); # if WCHAR_MIN != 17 && WCHAR_MAX /* ok */ # else err or; # endif #endif #if HAVE_WINT_T # include <wchar.h> verify (TYPE_MINIMUM (wint_t) == WINT_MIN); verify (TYPE_MAXIMUM (wint_t) == WINT_MAX); verify_same_types (WINT_MIN, (wint_t) 0 + 0); verify_same_types (WINT_MAX, (wint_t) 0 + 0); # if WINT_MIN != 17 && WINT_MAX /* ok */ # else err or; # endif #endif /* 7.18.4. Macros for integer constants */ verify (INT8_C (17) == 17); verify_same_types (INT8_C (17), (int_least8_t)0 + 0); verify (UINT8_C (17) == 17); verify_same_types (UINT8_C (17), (uint_least8_t)0 + 0); verify (INT16_C (17) == 17); verify_same_types (INT16_C (17), (int_least16_t)0 + 0); verify (UINT16_C (17) == 17); verify_same_types (UINT16_C (17), (uint_least16_t)0 + 0); verify (INT32_C (17) == 17); verify_same_types (INT32_C (17), (int_least32_t)0 + 0); verify (UINT32_C (17) == 17); verify_same_types (UINT32_C (17), (uint_least32_t)0 + 0); #ifdef INT64_C verify (INT64_C (17) == 17); verify_same_types (INT64_C (17), (int_least64_t)0 + 0); #endif #ifdef UINT64_C verify (UINT64_C (17) == 17); verify_same_types (UINT64_C (17), (uint_least64_t)0 + 0); #endif verify (INTMAX_C (17) == 17); verify_same_types (INTMAX_C (17), (intmax_t)0 + 0); verify (UINTMAX_C (17) == 17); verify_same_types (UINTMAX_C (17), (uintmax_t)0 + 0); int main (void) { return 0; }
lgpl-2.1
jasonatran/RIOT
drivers/saul/init_devs/auto_init_ad7746.c
16
2366
/* * Copyright (C) 2019 HAW Hamburg * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. * */ /** * @ingroup sys_auto_init_saul * @{ * * @file * @brief Auto initialization of AD7746 * * @author Leandro Lanzieri <leandro.lanzieri@haw-hamburg.de> * * @} */ #include "assert.h" #include "log.h" #include "saul_reg.h" #include "ad7746.h" #include "ad7746_params.h" /** * @brief Define the number of configured sensors */ #define AD7746_NUM ARRAY_SIZE(ad7746_params) /** * @brief Allocate memory for the device descriptors. */ static ad7746_t ad7746_devs[AD7746_NUM]; /** * @brief Memory for the SAUL registry entries. Each device provides * 3 SAUL entries (capacitance, temperature and voltage) */ static saul_reg_t saul_entries[AD7746_NUM * 3]; /** * @brief Define the number of saul info */ #define AD7746_INFO_NUM ARRAY_SIZE(ad7746_saul_info) /** * @brief Reference the driver structs * @{ */ extern saul_driver_t ad7746_saul_driver_cap; extern saul_driver_t ad7746_saul_driver_temp; extern saul_driver_t ad7746_saul_driver_volt; /** @} */ void auto_init_ad7746(void) { assert(AD7746_INFO_NUM == AD7746_NUM); for (unsigned i = 0; i < AD7746_NUM; i++) { LOG_DEBUG("[auto_init_saul] initializing ad7746 #%d\n", i); if (ad7746_init(&ad7746_devs[i], &ad7746_params[i]) < 0) { LOG_ERROR("[auto_init_saul] error initializing ad7746 #%d\n", i); continue; } /* add capacitance driver */ saul_entries[i].dev = &(ad7746_devs[i]); saul_entries[i].name = ad7746_saul_info[i].name; saul_entries[i].driver = &ad7746_saul_driver_cap; saul_reg_add(&(saul_entries[i])); /* add temperature driver */ saul_entries[i + 1].dev = &(ad7746_devs[i]); saul_entries[i + 1].name = ad7746_saul_info[i].name; saul_entries[i + 1].driver = &ad7746_saul_driver_temp; saul_reg_add(&(saul_entries[i + 1])); /* add voltage driver */ saul_entries[i + 2].dev = &(ad7746_devs[i]); saul_entries[i + 2].name = ad7746_saul_info[i].name; saul_entries[i + 2].driver = &ad7746_saul_driver_volt; saul_reg_add(&(saul_entries[i + 2])); } }
lgpl-2.1
elgambitero/FreeCAD_sf_master
src/Mod/Mesh/Gui/ViewProviderMeshFaceSet.cpp
17
8015
/*************************************************************************** * Copyright (c) 2006 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <algorithm> # include <Inventor/SoPickedPoint.h> # include <Inventor/details/SoFaceDetail.h> # include <Inventor/nodes/SoBaseColor.h> # include <Inventor/nodes/SoCoordinate3.h> # include <Inventor/nodes/SoDrawStyle.h> # include <Inventor/nodes/SoIndexedLineSet.h> # include <Inventor/nodes/SoMaterial.h> # include <Inventor/nodes/SoMaterialBinding.h> # include <Inventor/nodes/SoPolygonOffset.h> # include <Inventor/nodes/SoShapeHints.h> # include <Inventor/nodes/SoOrthographicCamera.h> # include <Inventor/nodes/SoTransform.h> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/events/SoMouseButtonEvent.h> # include <QAction> # include <QMenu> #endif /// Here the FreeCAD includes sorted by Base,App,Gui...... #include <Base/Console.h> #include <Base/Exception.h> #include <Base/Sequencer.h> #include <Base/Tools2D.h> #include <Base/ViewProj.h> #include <App/Document.h> #include <App/PropertyLinks.h> #include <Gui/Application.h> #include <Gui/Command.h> #include <Gui/Document.h> #include <Gui/SoFCSelection.h> #include <Gui/MainWindow.h> #include <Gui/Selection.h> #include <Gui/WaitCursor.h> #include <Gui/Window.h> #include <Gui/Flag.h> #include <Gui/View3DInventor.h> #include <Gui/View3DInventorViewer.h> #include <Mod/Mesh/App/Core/Algorithm.h> #include <Mod/Mesh/App/Core/Evaluation.h> #include <Mod/Mesh/App/Core/Grid.h> #include <Mod/Mesh/App/Core/Iterator.h> #include <Mod/Mesh/App/Core/MeshIO.h> #include <Mod/Mesh/App/Core/MeshKernel.h> #include <Mod/Mesh/App/Core/Triangulation.h> #include <Mod/Mesh/App/Core/Visitor.h> #include <Mod/Mesh/App/Mesh.h> #include <Mod/Mesh/App/MeshFeature.h> #include <Mod/Mesh/App/MeshProperties.h> #include "ViewProviderMeshFaceSet.h" #include "SoFCMeshObject.h" #include "SoFCIndexedFaceSet.h" using namespace MeshGui; PROPERTY_SOURCE(MeshGui::ViewProviderMeshFaceSet, MeshGui::ViewProviderMesh) ViewProviderMeshFaceSet::ViewProviderMeshFaceSet() { directRendering = false; triangleCount = 2500000; pcMeshNode = new SoFCMeshObjectNode; pcMeshNode->ref(); pcMeshShape = new SoFCMeshObjectShape; pcMeshShape->ref(); pcMeshCoord = new SoCoordinate3; pcMeshCoord->ref(); pcMeshFaces = new SoFCIndexedFaceSet; pcMeshFaces->ref(); } ViewProviderMeshFaceSet::~ViewProviderMeshFaceSet() { pcMeshNode->unref(); pcMeshShape->unref(); pcMeshCoord->unref(); pcMeshFaces->unref(); } void ViewProviderMeshFaceSet::attach(App::DocumentObject *pcFeat) { ViewProviderMesh::attach(pcFeat); pcHighlight->addChild(pcMeshCoord); pcHighlight->addChild(pcMeshFaces); // read the threshold from the preferences Base::Reference<ParameterGrp> hGrp = Gui::WindowParameter::getDefaultParameter()->GetGroup("Mod/Mesh"); int size = hGrp->GetInt("RenderTriangleLimit", -1); if (size > 0) { pcMeshShape->renderTriangleLimit = (unsigned int)(pow(10.0f,size)); static_cast<SoFCIndexedFaceSet*>(pcMeshFaces)->renderTriangleLimit = (unsigned int)(pow(10.0f,size)); } } void ViewProviderMeshFaceSet::updateData(const App::Property* prop) { Gui::ViewProviderGeometryObject::updateData(prop); if (prop->getTypeId() == Mesh::PropertyMeshKernel::getClassTypeId()) { const Mesh::MeshObject* mesh = static_cast<const Mesh::PropertyMeshKernel*>(prop)->getValuePtr(); bool direct = (mesh->countFacets() > this->triangleCount); if (direct) { this->pcMeshNode->mesh.setValue(mesh); // Needs to update internal bounding box caches this->pcMeshShape->touch(); pcMeshCoord->point.setNum(0); pcMeshFaces->coordIndex.setNum(0); } else { ViewProviderMeshBuilder builder; builder.createMesh(prop, pcMeshCoord, pcMeshFaces); } if (direct != directRendering) { directRendering = direct; pcHighlight->removeAllChildren(); if (directRendering) { pcHighlight->addChild(pcMeshNode); pcHighlight->addChild(pcMeshShape); } else { pcHighlight->addChild(pcMeshCoord); pcHighlight->addChild(pcMeshFaces); } } showOpenEdges(OpenEdges.getValue()); std::vector<unsigned long> selection; mesh->getFacetsFromSelection(selection); if (selection.empty()) unhighlightSelection(); else highlightSelection(); } } void ViewProviderMeshFaceSet::showOpenEdges(bool show) { if (pcOpenEdge) { // remove the node and destroy the data pcRoot->removeChild(pcOpenEdge); pcOpenEdge = 0; } if (show) { pcOpenEdge = new SoSeparator(); pcOpenEdge->addChild(pcLineStyle); pcOpenEdge->addChild(pOpenColor); if (directRendering) { pcOpenEdge->addChild(pcMeshNode); pcOpenEdge->addChild(new SoFCMeshObjectBoundary); } else { pcOpenEdge->addChild(pcMeshCoord); SoIndexedLineSet* lines = new SoIndexedLineSet; pcOpenEdge->addChild(lines); // Build up the lines with indices to the list of vertices 'pcMeshCoord' int index=0; const MeshCore::MeshKernel& rMesh = static_cast<Mesh::Feature*>(pcObject)->Mesh.getValue().getKernel(); const MeshCore::MeshFacetArray& rFaces = rMesh.GetFacets(); for (MeshCore::MeshFacetArray::_TConstIterator it = rFaces.begin(); it != rFaces.end(); ++it) { for (int i=0; i<3; i++) { if (it->_aulNeighbours[i] == ULONG_MAX) { lines->coordIndex.set1Value(index++,it->_aulPoints[i]); lines->coordIndex.set1Value(index++,it->_aulPoints[(i+1)%3]); lines->coordIndex.set1Value(index++,SO_END_LINE_INDEX); } } } } // add to the highlight node pcRoot->addChild(pcOpenEdge); } } SoShape* ViewProviderMeshFaceSet::getShapeNode() const { if (directRendering) return this->pcMeshShape; return this->pcMeshFaces; } SoNode* ViewProviderMeshFaceSet::getCoordNode() const { if (directRendering) return this->pcMeshNode; return this->pcMeshCoord; }
lgpl-2.1
droozynuu/doom-android
project/sdl/sdl-1.3/src/thread/nds/SDL_syscond.c
21
6200
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2010 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifdef SAVE_RCSID static char rcsid = "@(#) $Id: SDL_syscond.c,v 1.2 2001/04/26 16:50:18 hercules Exp $"; #endif /* An implementation of condition variables using semaphores and mutexes */ /* This implementation borrows heavily from the BeOS condition variable implementation, written by Christopher Tate and Owen Smith. Thanks! */ #include <stdio.h> #include <stdlib.h> #include "SDL_error.h" #include "SDL_thread.h" struct SDL_cond { SDL_mutex *lock; int waiting; int signals; SDL_sem *wait_sem; SDL_sem *wait_done; }; /* Create a condition variable */ SDL_cond * SDL_CreateCond(void) { SDL_cond *cond; cond = (SDL_cond *) malloc(sizeof(SDL_cond)); if (cond) { cond->lock = SDL_CreateMutex(); cond->wait_sem = SDL_CreateSemaphore(0); cond->wait_done = SDL_CreateSemaphore(0); cond->waiting = cond->signals = 0; if (!cond->lock || !cond->wait_sem || !cond->wait_done) { SDL_DestroyCond(cond); cond = NULL; } } else { SDL_OutOfMemory(); } return (cond); } /* Destroy a condition variable */ void SDL_DestroyCond(SDL_cond * cond) { if (cond) { if (cond->wait_sem) { SDL_DestroySemaphore(cond->wait_sem); } if (cond->wait_done) { SDL_DestroySemaphore(cond->wait_done); } if (cond->lock) { SDL_DestroyMutex(cond->lock); } free(cond); } } /* Restart one of the threads that are waiting on the condition variable */ int SDL_CondSignal(SDL_cond * cond) { if (!cond) { SDL_SetError("Passed a NULL condition variable"); return -1; } /* If there are waiting threads not already signalled, then signal the condition and wait for the thread to respond. */ SDL_LockMutex(cond->lock); if (cond->waiting > cond->signals) { ++cond->signals; SDL_SemPost(cond->wait_sem); SDL_UnlockMutex(cond->lock); SDL_SemWait(cond->wait_done); } else { SDL_UnlockMutex(cond->lock); } return 0; } /* Restart all threads that are waiting on the condition variable */ int SDL_CondBroadcast(SDL_cond * cond) { if (!cond) { SDL_SetError("Passed a NULL condition variable"); return -1; } /* If there are waiting threads not already signalled, then signal the condition and wait for the thread to respond. */ SDL_LockMutex(cond->lock); if (cond->waiting > cond->signals) { int i, num_waiting; num_waiting = (cond->waiting - cond->signals); cond->signals = cond->waiting; for (i = 0; i < num_waiting; ++i) { SDL_SemPost(cond->wait_sem); } /* Now all released threads are blocked here, waiting for us. Collect them all (and win fabulous prizes!) :-) */ SDL_UnlockMutex(cond->lock); for (i = 0; i < num_waiting; ++i) { SDL_SemWait(cond->wait_done); } } else { SDL_UnlockMutex(cond->lock); } return 0; } /* Wait on the condition variable for at most 'ms' milliseconds. The mutex must be locked before entering this function! The mutex is unlocked during the wait, and locked again after the wait. Typical use: Thread A: SDL_LockMutex(lock); while ( ! condition ) { SDL_CondWait(cond); } SDL_UnlockMutex(lock); Thread B: SDL_LockMutex(lock); ... condition = true; ... SDL_UnlockMutex(lock); */ int SDL_CondWaitTimeout(SDL_cond * cond, SDL_mutex * mutex, Uint32 ms) { int retval; if (!cond) { SDL_SetError("Passed a NULL condition variable"); return -1; } /* Obtain the protection mutex, and increment the number of waiters. This allows the signal mechanism to only perform a signal if there are waiting threads. */ SDL_LockMutex(cond->lock); ++cond->waiting; SDL_UnlockMutex(cond->lock); /* Unlock the mutex, as is required by condition variable semantics */ SDL_UnlockMutex(mutex); /* Wait for a signal */ if (ms == SDL_MUTEX_MAXWAIT) { retval = SDL_SemWait(cond->wait_sem); } else { retval = SDL_SemWaitTimeout(cond->wait_sem, ms); } /* Let the signaler know we have completed the wait, otherwise the signaler can race ahead and get the condition semaphore if we are stopped between the mutex unlock and semaphore wait, giving a deadlock. See the following URL for details: http://www-classic.be.com/aboutbe/benewsletter/volume_III/Issue40.html */ SDL_LockMutex(cond->lock); if (cond->signals > 0) { /* If we timed out, we need to eat a condition signal */ if (retval > 0) { SDL_SemWait(cond->wait_sem); } /* We always notify the signal thread that we are done */ SDL_SemPost(cond->wait_done); /* Signal handshake complete */ --cond->signals; } --cond->waiting; SDL_UnlockMutex(cond->lock); /* Lock the mutex, as is required by condition variable semantics */ SDL_LockMutex(mutex); return retval; } /* Wait on the condition variable forever */ int SDL_CondWait(SDL_cond * cond, SDL_mutex * mutex) { return SDL_CondWaitTimeout(cond, mutex, SDL_MUTEX_MAXWAIT); }
lgpl-2.1
GrokImageCompression/gst-plugins-good
gst/multifile/test-splitmuxpartreader.c
22
2591
#include <gst/gst.h> #include "gstsplitmuxpartreader.h" #include "gstsplitmuxsrc.h" GST_DEBUG_CATEGORY_EXTERN (splitmux_debug); static const gchar *const path = "out001.mp4"; typedef struct _CustomData { GstSplitMuxPartReader *reader; GMainLoop *main_loop; GstBus *bus; } CustomData; static void part_prepared (GstSplitMuxPartReader * reader) { g_print ("Part prepared\n"); } static gboolean handle_message (GstBus * bus, GstMessage * msg, CustomData * data) { GError *err; gchar *debug_info; switch (GST_MESSAGE_TYPE (msg)) { case GST_MESSAGE_ERROR: gst_message_parse_error (msg, &err, &debug_info); g_print ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message); g_print ("Debugging information: %s\n", debug_info ? debug_info : "none"); g_clear_error (&err); g_free (debug_info); g_main_loop_quit (data->main_loop); break; case GST_MESSAGE_EOS: g_print ("End-Of-Stream reached.\n"); g_main_loop_quit (data->main_loop); break; default: break; } return TRUE; } static gboolean start_reader (CustomData * data) { g_print ("Preparing part reader for %s\n", path); gst_splitmux_part_reader_prepare (data->reader); return FALSE; } static GstPad * handle_get_pad (GstSplitMuxPartReader * reader, GstPad * src_pad, CustomData * data) { /* Create a dummy target pad for the reader */ GstPad *new_pad = g_object_new (SPLITMUX_TYPE_SRC_PAD, "name", GST_PAD_NAME (src_pad), "direction", GST_PAD_SRC, NULL); g_print ("Creating new dummy pad %s\n", GST_PAD_NAME (src_pad)); return new_pad; } int main (int argc, char **argv) { CustomData data; gst_init (&argc, &argv); data.main_loop = g_main_loop_new (NULL, FALSE); data.reader = g_object_new (GST_TYPE_SPLITMUX_PART_READER, NULL); data.bus = gst_element_get_bus (GST_ELEMENT_CAST (data.reader)); /* Listen for bus messages */ gst_bus_add_watch (data.bus, (GstBusFunc) handle_message, &data); gst_splitmux_part_reader_set_location (data.reader, path); /* Connect to prepare signal */ g_signal_connect (data.reader, "prepared", (GCallback) part_prepared, &data); gst_splitmux_part_reader_set_callbacks (data.reader, &data, (GstSplitMuxPartReaderPadCb) handle_get_pad); g_idle_add ((GSourceFunc) start_reader, &data); /* Run mainloop */ g_main_loop_run (data.main_loop); gst_splitmux_part_reader_unprepare (data.reader); g_main_loop_unref (data.main_loop); gst_object_unref (data.bus); g_object_unref (data.reader); return 0; }
lgpl-2.1
BerserkerTroll/root
interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Haiku.cpp
23
1135
//===--- Haiku.cpp - Haiku ToolChain Implementations ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Haiku.h" #include "CommonArgs.h" using namespace clang::driver; using namespace clang::driver::toolchains; using namespace clang; using namespace llvm::opt; /// Haiku - Haiku tool chain which can call as(1) and ld(1) directly. Haiku::Haiku(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) : Generic_ELF(D, Triple, Args) { } std::string Haiku::findLibCxxIncludePath() const { return getDriver().SysRoot + "/system/develop/headers/c++/v1"; } void Haiku::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const { addLibStdCXXIncludePaths(getDriver().SysRoot, "/system/develop/headers/c++", getTriple().str(), "", "", "", DriverArgs, CC1Args); }
lgpl-2.1
artoolkit/osg
src/osgWrappers/deprecated-dotosg/osgFX/IO_Effect.cpp
26
1682
#include <osgFX/Effect> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> bool Effect_readLocalData(osg::Object &obj, osgDB::Input &fr); bool Effect_writeLocalData(const osg::Object &obj, osgDB::Output &fw); REGISTER_DOTOSGWRAPPER(Effect_Proxy) ( 0, "osgFX::Effect", "Object Node Group osgFX::Effect", Effect_readLocalData, Effect_writeLocalData ); bool Effect_readLocalData(osg::Object &obj, osgDB::Input &fr) { osgFX::Effect &myobj = static_cast<osgFX::Effect &>(obj); bool itAdvanced = false; if (fr[0].matchWord("enabled")) { if (fr[1].matchWord("FALSE")) { myobj.setEnabled(false); } else { myobj.setEnabled(true); } fr += 2; itAdvanced = true; } if (fr[0].matchWord("selectedTechnique")) { if (fr[1].matchWord("AUTO_DETECT")) { myobj.selectTechnique(osgFX::Effect::AUTO_DETECT); fr += 2; itAdvanced = true; } else { int i; if (fr[1].getInt(i)) { myobj.selectTechnique(i); fr += 2; itAdvanced = true; } } } return itAdvanced; } bool Effect_writeLocalData(const osg::Object &obj, osgDB::Output &fw) { const osgFX::Effect &myobj = static_cast<const osgFX::Effect &>(obj); fw.indent() << "enabled " << (myobj.getEnabled() ? "TRUE" : "FALSE") << "\n"; fw.indent() << "selectedTechnique "; if (myobj.getSelectedTechnique() == osgFX::Effect::AUTO_DETECT) { fw << "AUTO_DETECT\n"; } else { fw << myobj.getSelectedTechnique() << "\n"; } return true; }
lgpl-2.1
vukasinmilosevic/root
interpreter/llvm/src/lib/Target/NVPTX/NVPTXImageOptimizer.cpp
30
5766
//===-- NVPTXImageOptimizer.cpp - Image optimization pass -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass implements IR-level optimizations of image access code, // including: // // 1. Eliminate istypep intrinsics when image access qualifier is known // //===----------------------------------------------------------------------===// #include "NVPTX.h" #include "NVPTXUtilities.h" #include "llvm/Analysis/ConstantFolding.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" using namespace llvm; namespace { class NVPTXImageOptimizer : public FunctionPass { private: static char ID; SmallVector<Instruction*, 4> InstrToDelete; public: NVPTXImageOptimizer(); bool runOnFunction(Function &F) override; private: bool replaceIsTypePSampler(Instruction &I); bool replaceIsTypePSurface(Instruction &I); bool replaceIsTypePTexture(Instruction &I); Value *cleanupValue(Value *V); void replaceWith(Instruction *From, ConstantInt *To); }; } char NVPTXImageOptimizer::ID = 0; NVPTXImageOptimizer::NVPTXImageOptimizer() : FunctionPass(ID) {} bool NVPTXImageOptimizer::runOnFunction(Function &F) { bool Changed = false; InstrToDelete.clear(); // Look for call instructions in the function for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) { for (BasicBlock::iterator I = (*BI).begin(), E = (*BI).end(); I != E; ++I) { Instruction &Instr = *I; if (CallInst *CI = dyn_cast<CallInst>(I)) { Function *CalledF = CI->getCalledFunction(); if (CalledF && CalledF->isIntrinsic()) { // This is an intrinsic function call, check if its an istypep switch (CalledF->getIntrinsicID()) { default: break; case Intrinsic::nvvm_istypep_sampler: Changed |= replaceIsTypePSampler(Instr); break; case Intrinsic::nvvm_istypep_surface: Changed |= replaceIsTypePSurface(Instr); break; case Intrinsic::nvvm_istypep_texture: Changed |= replaceIsTypePTexture(Instr); break; } } } } } // Delete any istypep instances we replaced in the IR for (unsigned i = 0, e = InstrToDelete.size(); i != e; ++i) InstrToDelete[i]->eraseFromParent(); return Changed; } bool NVPTXImageOptimizer::replaceIsTypePSampler(Instruction &I) { Value *TexHandle = cleanupValue(I.getOperand(0)); if (isSampler(*TexHandle)) { // This is an OpenCL sampler, so it must be a samplerref replaceWith(&I, ConstantInt::getTrue(I.getContext())); return true; } else if (isImageWriteOnly(*TexHandle) || isImageReadWrite(*TexHandle) || isImageReadOnly(*TexHandle)) { // This is an OpenCL image, so it cannot be a samplerref replaceWith(&I, ConstantInt::getFalse(I.getContext())); return true; } else { // The image type is unknown, so we cannot eliminate the intrinsic return false; } } bool NVPTXImageOptimizer::replaceIsTypePSurface(Instruction &I) { Value *TexHandle = cleanupValue(I.getOperand(0)); if (isImageReadWrite(*TexHandle) || isImageWriteOnly(*TexHandle)) { // This is an OpenCL read-only/read-write image, so it must be a surfref replaceWith(&I, ConstantInt::getTrue(I.getContext())); return true; } else if (isImageReadOnly(*TexHandle) || isSampler(*TexHandle)) { // This is an OpenCL read-only/ imageor sampler, so it cannot be // a surfref replaceWith(&I, ConstantInt::getFalse(I.getContext())); return true; } else { // The image type is unknown, so we cannot eliminate the intrinsic return false; } } bool NVPTXImageOptimizer::replaceIsTypePTexture(Instruction &I) { Value *TexHandle = cleanupValue(I.getOperand(0)); if (isImageReadOnly(*TexHandle)) { // This is an OpenCL read-only image, so it must be a texref replaceWith(&I, ConstantInt::getTrue(I.getContext())); return true; } else if (isImageWriteOnly(*TexHandle) || isImageReadWrite(*TexHandle) || isSampler(*TexHandle)) { // This is an OpenCL read-write/write-only image or a sampler, so it // cannot be a texref replaceWith(&I, ConstantInt::getFalse(I.getContext())); return true; } else { // The image type is unknown, so we cannot eliminate the intrinsic return false; } } void NVPTXImageOptimizer::replaceWith(Instruction *From, ConstantInt *To) { // We implement "poor man's DCE" here to make sure any code that is no longer // live is actually unreachable and can be trivially eliminated by the // unreachable block elimination pass. for (CallInst::use_iterator UI = From->use_begin(), UE = From->use_end(); UI != UE; ++UI) { if (BranchInst *BI = dyn_cast<BranchInst>(*UI)) { if (BI->isUnconditional()) continue; BasicBlock *Dest; if (To->isZero()) // Get false block Dest = BI->getSuccessor(1); else // Get true block Dest = BI->getSuccessor(0); BranchInst::Create(Dest, BI); InstrToDelete.push_back(BI); } } From->replaceAllUsesWith(To); InstrToDelete.push_back(From); } Value *NVPTXImageOptimizer::cleanupValue(Value *V) { if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) { return cleanupValue(EVI->getAggregateOperand()); } return V; } FunctionPass *llvm::createNVPTXImageOptimizerPass() { return new NVPTXImageOptimizer(); }
lgpl-2.1
DarkLotus/OakCore
libraries/RF24/examples_RPi/gettingstarted_call_response.cpp
30
6432
/* TMRh20 2014 - Updated to work with optimized RF24 Arduino library */ /** * Example for efficient call-response using ack-payloads * * This example continues to make use of all the normal functionality of the radios including * the auto-ack and auto-retry features, but allows ack-payloads to be written optionlly as well. * This allows very fast call-response communication, with the responding radio never having to * switch out of Primary Receiver mode to send back a payload, but having the option to switch to * primary transmitter if wanting to initiate communication instead of respond to a commmunication. */ #include <cstdlib> #include <iostream> #include <sstream> #include <string> #include <unistd.h> #include <RF24/RF24.h> using namespace std; // // Hardware configuration // Configure the appropriate pins for your connections /****************** Raspberry Pi ***********************/ // Radio CE Pin, CSN Pin, SPI Speed // See http://www.airspayce.com/mikem/bcm2835/group__constants.html#ga63c029bd6500167152db4e57736d0939 and the related enumerations for pin information. // Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 4Mhz //RF24 radio(RPI_V2_GPIO_P1_22, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_4MHZ); // NEW: Setup for RPi B+ //RF24 radio(RPI_BPLUS_GPIO_J8_15,RPI_BPLUS_GPIO_J8_24, BCM2835_SPI_SPEED_8MHZ); // Setup for GPIO 15 CE and CE0 CSN with SPI Speed @ 8Mhz RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ); /*** RPi Alternate ***/ //Note: Specify SPI BUS 0 or 1 instead of CS pin number. // See http://tmrh20.github.io/RF24/RPi.html for more information on usage //RPi Alternate, with MRAA //RF24 radio(15,0); //RPi Alternate, with SPIDEV - Note: Edit RF24/arch/BBB/spi.cpp and set 'this->device = "/dev/spidev0.0";;' or as listed in /dev //RF24 radio(22,0); /****************** Linux (BBB,x86,etc) ***********************/ // See http://tmrh20.github.io/RF24/pages.html for more information on usage // See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA // See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV // Setup for ARM(Linux) devices like BBB using spidev (default is "/dev/spidev1.0" ) //RF24 radio(115,0); //BBB Alternate, with mraa // CE pin = (Header P9, Pin 13) = 59 = 13 + 46 //Note: Specify SPI BUS 0 or 1 instead of CS pin number. //RF24 radio(59,0); /********** User Config *********/ // Assign a unique identifier for this node, 0 or 1. Arduino example uses radioNumber 0 by default. bool radioNumber = 1; /********************************/ // Radio pipe addresses for the 2 nodes to communicate. const uint8_t addresses[][6] = {"1Node","2Node"}; bool role_ping_out = 1, role_pong_back = 0, role = 0; uint8_t counter = 1; // A single byte to keep track of the data being sent back and forth int main(int argc, char** argv){ cout << "RPi/RF24/examples/gettingstarted_call_response\n"; radio.begin(); radio.enableAckPayload(); // Allow optional ack payloads radio.enableDynamicPayloads(); radio.printDetails(); // Dump the configuration of the rf unit for debugging /********* Role chooser ***********/ printf("\n ************ Role Setup ***********\n"); string input = ""; char myChar = {0}; cout << "Choose a role: Enter 0 for pong_back, 1 for ping_out (CTRL+C to exit)\n>"; getline(cin,input); if(input.length() == 1) { myChar = input[0]; if(myChar == '0'){ cout << "Role: Pong Back, awaiting transmission " << endl << endl; }else{ cout << "Role: Ping Out, starting transmission " << endl << endl; role = role_ping_out; } } /***********************************/ // This opens two pipes for these two nodes to communicate // back and forth. if ( !radioNumber ) { radio.openWritingPipe(addresses[0]); radio.openReadingPipe(1,addresses[1]); }else{ radio.openWritingPipe(addresses[1]); radio.openReadingPipe(1,addresses[0]); } radio.startListening(); radio.writeAckPayload(1,&counter,1); // forever loop while (1){ /****************** Ping Out Role ***************************/ if (role == role_ping_out){ // Radio is in ping mode uint8_t gotByte; // Initialize a variable for the incoming response radio.stopListening(); // First, stop listening so we can talk. printf("Now sending %d as payload. ",counter); // Use a simple byte counter as payload unsigned long time = millis(); // Record the current microsecond count if ( radio.write(&counter,1) ){ // Send the counter variable to the other radio if(!radio.available()){ // If nothing in the buffer, we got an ack but it is blank printf("Got blank response. round-trip delay: %lu ms\n\r",millis()-time); }else{ while(radio.available() ){ // If an ack with payload was received radio.read( &gotByte, 1 ); // Read it, and display the response time printf("Got response %d, round-trip delay: %lu ms\n\r",gotByte,millis()-time); counter++; // Increment the counter variable } } }else{ printf("Sending failed.\n\r"); } // If no ack response, sending failed sleep(1); // Try again later } /****************** Pong Back Role ***************************/ if ( role == role_pong_back ) { uint8_t pipeNo, gotByte; // Declare variables for the pipe and the byte received if( radio.available(&pipeNo)){ // Read all available payloads radio.read( &gotByte, 1 ); // Since this is a call-response. Respond directly with an ack payload. gotByte += 1; // Ack payloads are much more efficient than switching to transmit mode to respond to a call radio.writeAckPayload(pipeNo,&gotByte, 1 ); // This can be commented out to send empty payloads. printf("Loaded next response %d \n\r", gotByte); delay(900); //Delay after a response to minimize CPU usage on RPi //Expects a payload every second } } } //while 1 } //main
lgpl-2.1
permcody/libmesh
contrib/exodusii/5.22b/exodus/cbind/test/testrd_ss.c
30
11463
/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * testrd_ss - read exodus file test.exo created by testwt_ss * * author - Sandia National Laboratories * Larry A. Schoof - Original * * * environment - UNIX * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * * revision history - * * Original L. A. Schoof * *****************************************************************************/ #include <stdlib.h> #include <stdio.h> #include "netcdf.h" #include "exodusII.h" int main (int argc, char **argv) { int exoid, num_dim, num_nodes, num_elem, num_elem_blk, num_node_sets; int num_side_sets, error; int i, j, k, node_ctr; int *connect, *node_list, *node_ctr_list, *elem_list, *side_list; int *ids; int *num_elem_per_set; int *num_df_per_set; int *elem_ind, *df_ind; int *num_elem_in_block, *num_nodes_per_elem, *num_attr; int num_elem_in_set; int num_sides_in_set, num_df_in_set; int elem_list_len = 0; int node_list_len = 0; int df_list_len = 0; int CPU_word_size,IO_word_size; int idum; float *dist_fact; float version, fdum; char title[MAX_LINE_LENGTH+1], elem_type[MAX_STR_LENGTH+1]; char *cdum = 0; CPU_word_size = 0; /* sizeof(float) */ IO_word_size = 0; /* use what is stored in file */ ex_opts (EX_VERBOSE | EX_ABORT ); /* open EXODUS II files */ exoid = ex_open ("test.exo", /* filename path */ EX_READ, /* access mode = READ */ &CPU_word_size, /* CPU word size */ &IO_word_size, /* IO word size */ &version); /* ExodusII library version */ printf ("\nafter ex_open\n"); if (exoid < 0) exit(1); printf ("test.exo is an EXODUSII file; version %4.2f\n", version); /* printf (" CPU word size %1d\n",CPU_word_size); */ printf (" I/O word size %1d\n",IO_word_size); ex_inquire(exoid,EX_INQ_API_VERS, &idum, &version, cdum); printf ("EXODUSII API; version %4.2f\n", version); /* ncopts = NC_VERBOSE; */ /* read database parameters */ error = ex_get_init (exoid, title, &num_dim, &num_nodes, &num_elem, &num_elem_blk, &num_node_sets, &num_side_sets); printf ("after ex_get_init, error = %3d\n", error); printf ("database parameters:\n"); printf ("title = '%s'\n",title); printf ("num_dim = %3d\n",num_dim); printf ("num_nodes = %3d\n",num_nodes); printf ("num_elem = %3d\n",num_elem); printf ("num_elem_blk = %3d\n",num_elem_blk); printf ("num_node_sets = %3d\n",num_node_sets); printf ("num_side_sets = %3d\n",num_side_sets); /* read element block parameters */ ids = (int *) calloc(num_elem_blk, sizeof(int)); num_elem_in_block = (int *) calloc(num_elem_blk, sizeof(int)); num_nodes_per_elem = (int *) calloc(num_elem_blk, sizeof(int)); num_attr = (int *) calloc(num_elem_blk, sizeof(int)); error = ex_get_elem_blk_ids (exoid, ids); printf ("\nafter ex_get_elem_blk_ids, error = %3d\n", error); for (i=0; i<num_elem_blk; i++) { error = ex_get_elem_block (exoid, ids[i], elem_type, &(num_elem_in_block[i]), &(num_nodes_per_elem[i]), &(num_attr[i])); printf ("\nafter ex_get_elem_block, error = %d\n", error); printf ("element block id = %2d\n",ids[i]); printf ("element type = '%s'\n", elem_type); printf ("num_elem_in_block = %2d\n",num_elem_in_block[i]); printf ("num_nodes_per_elem = %2d\n",num_nodes_per_elem[i]); printf ("num_attr = %2d\n",num_attr[i]); } /* read element connectivity */ for (i=0; i<num_elem_blk; i++) { connect = (int *) calloc((num_nodes_per_elem[i] * num_elem_in_block[i]), sizeof(int)); error = ex_get_elem_conn (exoid, ids[i], connect); printf ("\nafter ex_get_elem_conn, error = %d\n", error); printf ("connect array for elem block %2d\n", ids[i]); for (j=0; j<num_nodes_per_elem[i]; j++) { printf ("%3d\n", connect[j]); } free (connect); } free(ids); free(num_elem_in_block); free(num_nodes_per_elem); free(num_attr); /* read individual side sets */ ids = (int *) calloc(num_side_sets, sizeof(int)); error = ex_get_side_set_ids (exoid, ids); printf ("\nafter ex_get_side_set_ids, error = %3d\n", error); for (i=0; i<num_side_sets; i++) { error = ex_get_side_set_param (exoid, ids[i], &num_sides_in_set, &num_df_in_set); printf ("\nafter ex_get_side_set_param, error = %3d\n", error); printf ("side set %2d parameters:\n",ids[i]); printf ("num_sides = %3d\n",num_sides_in_set); printf ("num_dist_factors = %3d\n", num_df_in_set); /* Note: The # of elements is same as # of sides! */ num_elem_in_set = num_sides_in_set; elem_list = (int *) calloc(num_elem_in_set, sizeof(int)); side_list = (int *) calloc(num_sides_in_set, sizeof(int)); node_ctr_list = (int *) calloc(num_elem_in_set, sizeof(int)); node_list = (int *) calloc(num_elem_in_set*21, sizeof(int)); dist_fact = (float *) calloc(num_df_in_set, sizeof(float)); error = ex_get_side_set (exoid, ids[i], elem_list, side_list); printf ("\nafter ex_get_side_set, error = %3d\n", error); error = ex_get_side_set_node_list (exoid, ids[i], node_ctr_list, node_list); printf ("\nafter ex_get_side_set_node_list, error = %3d\n", error); if (num_df_in_set > 0) { error = ex_get_side_set_dist_fact (exoid, ids[i], dist_fact); printf ("\nafter ex_get_side_set_dist_fact, error = %3d\n", error); } printf ("element list for side set %2d\n", ids[i]); for (j=0; j<num_elem_in_set; j++) { printf ("%3d\n", elem_list[j]); } printf ("side list for side set %2d\n", ids[i]); for (j=0; j<num_sides_in_set; j++) { printf ("%3d\n", side_list[j]); } node_ctr = 0; printf ("node list for side set %2d\n", ids[i]); for (k=0; k<num_elem_in_set; k++) { printf ("%3d nodes for side %3d\n", node_ctr_list[k], k); for (j=0; j<node_ctr_list[k]; j++) { printf ("%3d\n", node_list[node_ctr+j]); } node_ctr += node_ctr_list[k]; } if (num_df_in_set > 0) { printf ("dist factors for side set %2d\n", ids[i]); for (j=0; j<num_df_in_set; j++) { printf ("%5.3f\n", dist_fact[j]); } } else printf ("no dist factors for side set %2d\n", ids[i]); free (elem_list); free (side_list); free (node_ctr_list); free (node_list); free (dist_fact); } free(ids); if (num_side_sets > 0) { error = ex_inquire(exoid, EX_INQ_SS_ELEM_LEN, &elem_list_len, &fdum, cdum); printf ("\nafter ex_inquire: EX_INQ_SS_ELEM_LEN = %d, error = %d\n", elem_list_len, error); error = ex_inquire(exoid, EX_INQ_SS_NODE_LEN, &node_list_len, &fdum, cdum); printf ("\nafter ex_inquire: EX_INQ_SS_NODE_LEN = %d, error = %d\n", node_list_len, error); error = ex_inquire(exoid, EX_INQ_SS_DF_LEN, &df_list_len, &fdum, cdum); printf ("\nafter ex_inquire: EX_INQ_SS_DF_LEN = %d, error = %d\n", df_list_len, error); } /* read concatenated side sets; this produces the same information as * the above code which reads individual side sets */ /* concatenated side set read */ ids = (int *) calloc(num_side_sets, sizeof(int)); num_elem_per_set = (int *) calloc(num_side_sets, sizeof(int)); num_df_per_set = (int *) calloc(num_side_sets, sizeof(int)); elem_ind = (int *) calloc(num_side_sets, sizeof(int)); df_ind = (int *) calloc(num_side_sets, sizeof(int)); elem_list = (int *) calloc(elem_list_len, sizeof(int)); side_list = (int *) calloc(elem_list_len, sizeof(int)); dist_fact = (float *) calloc(df_list_len, sizeof(float)); error = ex_get_concat_side_sets (exoid, ids, num_elem_per_set, num_df_per_set, elem_ind, df_ind, elem_list, side_list, dist_fact); printf ("\nafter ex_get_concat_side_sets, error = %3d\n", error); printf ("concatenated side set info\n"); printf ("ids = \n"); for (i=0; i<num_side_sets; i++) printf ("%3d\n", ids[i]); printf ("num_elem_per_set = \n"); for (i=0; i<num_side_sets; i++) printf ("%3d\n", num_elem_per_set[i]); printf ("num_dist_per_set = \n"); for (i=0; i<num_side_sets; i++) printf ("%3d\n", num_df_per_set[i]); printf ("elem_ind = \n"); for (i=0; i<num_side_sets; i++) printf ("%3d\n", elem_ind[i]); printf ("dist_ind = \n"); for (i=0; i<num_side_sets; i++) printf ("%3d\n", df_ind[i]); printf ("elem_list = \n"); for (i=0; i<elem_list_len; i++) printf ("%3d\n", elem_list[i]); printf ("side_list = \n"); for (i=0; i<elem_list_len; i++) printf ("%3d\n", side_list[i]); printf ("dist_fact = \n"); for (i=0; i<df_list_len; i++) printf ("%5.3f\n", dist_fact[i]); free (ids); free (num_elem_per_set); free (num_df_per_set); free (df_ind); free (elem_ind); free (elem_list); free (side_list); free (dist_fact); /* end of concatenated side set read */ error = ex_close (exoid); printf ("\nafter ex_close, error = %3d\n", error); return 0; }
lgpl-2.1
paulthulstrup/moose
libmesh/contrib/qhull/2012.1/src/qhulltest/QhullPoint_test.cpp
31
10363
/**************************************************************************** ** ** Copyright (c) 2008-2012 C.B. Barber. All rights reserved. ** $Id: //main/2011/qhull/src/qhulltest/QhullPoint_test.cpp#4 $$Change: 1490 $ ** $DateTime: 2012/02/19 20:27:01 $$Author: bbarber $ ** ****************************************************************************/ //pre-compiled headers #include <iostream> #include "RoadTest.h" #include "QhullPoint.h" #include "Coordinates.h" #include "RboxPoints.h" #include "QhullError.h" #include "QhullFacet.h" #include "QhullPoint.h" #include "Qhull.h" #include <numeric> using std::cout; using std::endl; using std::ostringstream; using std::ostream; using std::string; namespace orgQhull { class QhullPoint_test : public RoadTest { Q_OBJECT #//Test slots private slots: void cleanup(); void t_construct(); void t_convert(); void t_readonly(); void t_define(); void t_operator(); void t_iterator(); void t_const_iterator(); void t_qhullpoint_iterator(); void t_io(); };//QhullPoint_test void add_QhullPoint_test() { new QhullPoint_test(); } //Executed after each test void QhullPoint_test:: cleanup() { UsingLibQhull::checkQhullMemoryEmpty(); RoadTest::cleanup(); } void QhullPoint_test:: t_construct() { // Qhull.runQhull() constructs QhullFacets as facetT QhullPoint p; QVERIFY(!p.isDefined()); QCOMPARE(p.dimension(),0); QCOMPARE(p.coordinates(),static_cast<double *>(0)); RboxPoints rcube("c"); Qhull q(rcube,"Qt QR0"); // triangulation of rotated unit cube QhullVertex v2(q.beginVertex()); QhullPoint p2(v2.point()); QVERIFY(p2.isDefined()); QCOMPARE(p2.dimension(),3); // p= p2; // copy assignment disabled, ambiguous QhullPoint p3(p2.dimension(), p2.coordinates()); QCOMPARE(p2, p3); Coordinates c; c << 0.0 << 0.0 << 0.0; QhullPoint p6(c); QCOMPARE(p6, q.origin()); QhullPoint p5= p2; // copy constructor QVERIFY(p5==p2); }//t_construct void QhullPoint_test:: t_convert() { RboxPoints rcube("c"); Qhull q(rcube,"Qt QR0"); // triangulation of rotated unit cube QhullVertex v= q.firstVertex(); QhullPoint p= v.point(); std::vector<double> vs= p.toStdVector(); QCOMPARE(vs.size(), 3u); for(int k=3; k--; ){ QCOMPARE(vs[k], p[k]); } QList<double> qs= p.toQList(); QCOMPARE(qs.size(), 3); for(int k=3; k--; ){ QCOMPARE(qs[k], p[k]); } }//t_convert void QhullPoint_test:: t_readonly() { RboxPoints rcube("c"); { Qhull q(rcube,"Qt QR0"); // triangulation of rotated unit cube QhullVertexList vs= q.vertexList(); QhullVertexListIterator i(vs); while(i.hasNext()){ QhullPoint p= i.next().point(); int id= p.id(q.runId()); cout << "p" << id << endl; QVERIFY(p.isDefined()); QCOMPARE(p.dimension(),3); QCOMPARE(id, p.id()); QVERIFY(p.id()>=0 && p.id()<9); const coordT *c= p.coordinates(); coordT *c2= p.coordinates(); QCOMPARE(c, c2); QCOMPARE(p.dimension(), 3); } QhullPoint p2= vs.first().point(); QhullPoint p3= vs.last().point(); QVERIFY(p2!=p3); QVERIFY(p3.coordinates()!=p2.coordinates()); } }//t_readonly void QhullPoint_test:: t_define() { RboxPoints rcube("c"); { Qhull q(rcube,"Qt QR0"); // triangulation of rotated unit cube QhullVertexList vs= q.vertexList(); QhullPoint p= vs.first().point(); QhullPoint p2= p; QVERIFY(p==p2); QhullPoint p3= vs.last().point(); QVERIFY(p2!=p3); int idx= (p3.coordinates()-p2.coordinates())/p2.dimension(); QVERIFY(idx>-8 && idx<8); p2.advancePoint(idx); QVERIFY(p2==p3); p2.advancePoint(-idx); QVERIFY(p2==p); p2.advancePoint(0); QVERIFY(p2==p); QhullPoint p4= p3; p4.defineAs(p2); QVERIFY(p2==p4); QhullPoint p5= p3; p5.defineAs(p2.dimension(), p2.coordinates()); QVERIFY(p2==p5); QhullPoint p6= p3; p6.setCoordinates(p2.coordinates()); QCOMPARE(p2.coordinates(), p6.coordinates()); QVERIFY(p2==p6); p6.setDimension(2); QCOMPARE(p6.dimension(), 2); QVERIFY(p2!=p6); } }//t_define void QhullPoint_test:: t_operator() { RboxPoints rcube("c"); Qhull q(rcube,"Qt QR0"); // triangulation of rotated unit cube const QhullPoint p= q.firstVertex().point(); //operator== and operator!= tested elsewhere const coordT *c= p.coordinates(); for(int k=p.dimension(); k--; ){ QCOMPARE(c[k], p[k]); } //p[0]= 10.0; // compiler error, const QhullPoint p2= q.firstVertex().point(); p2[0]= 10.0; // Overwrites point coordinate QCOMPARE(p2[0], 10.0); }//t_operator void QhullPoint_test:: t_iterator() { RboxPoints rcube("c"); { QhullPoint p2; QCOMPARE(p2.begin(), p2.end()); Qhull q(rcube,"QR0"); // rotated unit cube QhullPoint p= q.firstVertex().point(); QhullPoint::Iterator i= p.begin(); QhullPoint::iterator i2= p.begin(); QVERIFY(i==i2); QVERIFY(i>=i2); QVERIFY(i<=i2); i= p.begin(); QVERIFY(i==i2); i2= p.end(); QVERIFY(i!=i2); double d3= *i; i2--; double d2= *i2; QCOMPARE(d3, p[0]); QCOMPARE(d2, p[2]); QhullPoint::Iterator i3(i2); QCOMPARE(*i2, *i3); (i3= i)++; QCOMPARE((*i3), p[1]); QVERIFY(i==i); QVERIFY(i!=i2); QVERIFY(i<i2); QVERIFY(i<=i2); QVERIFY(i2>i); QVERIFY(i2>=i); QhullPoint::ConstIterator i4= p.begin(); QVERIFY(i==i4); // iterator COMP const_iterator QVERIFY(i<=i4); QVERIFY(i>=i4); QVERIFY(i4==i); // const_iterator COMP iterator QVERIFY(i4<=i); QVERIFY(i4>=i); QVERIFY(i>=i4); QVERIFY(i4<=i); QVERIFY(i2!=i4); QVERIFY(i2>i4); QVERIFY(i2>=i4); QVERIFY(i4!=i2); QVERIFY(i4<i2); QVERIFY(i4<=i2); ++i4; QVERIFY(i<i4); QVERIFY(i<=i4); QVERIFY(i4>i); QVERIFY(i4>=i); i= p.begin(); i2= p.begin(); QCOMPARE(i, i2++); QCOMPARE(*i2, p[1]); QCOMPARE(++i, i2); QCOMPARE(i, i2--); QCOMPARE(i2, p.begin()); QCOMPARE(--i, i2); QCOMPARE(i2 += 3, p.end()); QCOMPARE(i2 -= 3, p.begin()); QCOMPARE(i2+0, p.begin()); QCOMPARE(i2+3, p.end()); i2 += 3; i= i2-0; QCOMPARE(i, i2); i= i2-3; QCOMPARE(i, p.begin()); QCOMPARE(i2-i, 3); //p.begin end tested above // QhullPoint is const-only } }//t_iterator void QhullPoint_test:: t_const_iterator() { RboxPoints rcube("c"); { Qhull q(rcube,"QR0"); // rotated unit cube QhullPoint p= q.firstVertex().point(); QhullPoint::ConstIterator i= p.begin(); QhullPoint::const_iterator i2= p.begin(); QVERIFY(i==i2); QVERIFY(i>=i2); QVERIFY(i<=i2); i= p.begin(); QVERIFY(i==i2); i2= p.end(); QVERIFY(i!=i2); double d3= *i; i2--; double d2= *i2; QCOMPARE(d3, p[0]); QCOMPARE(d2, p[2]); QhullPoint::ConstIterator i3(i2); QCOMPARE(*i2, *i3); (i3= i)++; QCOMPARE((*i3), p[1]); QVERIFY(i==i); QVERIFY(i!=i2); QVERIFY(i<i2); QVERIFY(i<=i2); QVERIFY(i2>i); QVERIFY(i2>=i); // See t_iterator for const_iterator COMP iterator i= p.begin(); i2= p.constBegin(); QCOMPARE(i, i2++); QCOMPARE(*i2, p[1]); QCOMPARE(++i, i2); QCOMPARE(i, i2--); QCOMPARE(i2, p.constBegin()); QCOMPARE(--i, i2); QCOMPARE(i2+=3, p.constEnd()); QCOMPARE(i2-=3, p.constBegin()); QCOMPARE(i2+0, p.constBegin()); QCOMPARE(i2+3, p.constEnd()); i2 += 3; i= i2-0; QCOMPARE(i, i2); i= i2-3; QCOMPARE(i, p.constBegin()); QCOMPARE(i2-i, 3); // QhullPoint is const-only } }//t_const_iterator void QhullPoint_test:: t_qhullpoint_iterator() { QhullPoint p2; QhullPointIterator i= p2; QCOMPARE(p2.dimension(), 0); QVERIFY(!i.hasNext()); QVERIFY(!i.hasPrevious()); i.toBack(); QVERIFY(!i.hasNext()); QVERIFY(!i.hasPrevious()); RboxPoints rcube("c"); Qhull q(rcube,"QR0"); // rotated unit cube QhullPoint p = q.firstVertex().point(); QhullPointIterator i2(p); QCOMPARE(p.dimension(), 3); i= p; QVERIFY(i2.hasNext()); QVERIFY(!i2.hasPrevious()); QVERIFY(i.hasNext()); QVERIFY(!i.hasPrevious()); i2.toBack(); i.toFront(); QVERIFY(!i2.hasNext()); QVERIFY(i2.hasPrevious()); QVERIFY(i.hasNext()); QVERIFY(!i.hasPrevious()); // i at front, i2 at end/back, 3 coordinates QCOMPARE(i.peekNext(), p[0]); QCOMPARE(i2.peekPrevious(), p[2]); QCOMPARE(i2.previous(), p[2]); QCOMPARE(i2.previous(), p[1]); QCOMPARE(i2.previous(), p[0]); QVERIFY(!i2.hasPrevious()); QCOMPARE(i.peekNext(), p[0]); // i.peekNext()= 1.0; // compiler error, i is const QCOMPARE(i.next(), p[0]); QCOMPARE(i.peekNext(), p[1]); QCOMPARE(i.next(), p[1]); QCOMPARE(i.next(), p[2]); QVERIFY(!i.hasNext()); i.toFront(); QCOMPARE(i.next(), p[0]); }//t_qhullpoint_iterator void QhullPoint_test:: t_io() { RboxPoints rcube("c"); { Qhull q(rcube, ""); QhullPoint p= q.beginVertex().point(); ostringstream os; os << "Point w/o runId:\n"; os << p; os << "Point w/ runId:\n"; os << p.print(q.runId()) << p.print(q.runId(), " and a message "); os << p.printWithIdentifier(q.runId(), " Point with id and a message "); cout << os.str(); QString s= QString::fromStdString(os.str()); QCOMPARE(s.count("p"), 3); // QCOMPARE(s.count(QRegExp("f\\d")), 3*7 + 13*3*2); } }//t_io }//orgQhull #include "moc/QhullPoint_test.moc"
lgpl-2.1
CodeDJ/qt5-hidpi
qt/qtdeclarative/examples/qml/referenceexamples/properties/person.cpp
32
2312
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "person.h" Person::Person(QObject *parent) : QObject(parent), m_shoeSize(0) { } QString Person::name() const { return m_name; } void Person::setName(const QString &n) { m_name = n; } int Person::shoeSize() const { return m_shoeSize; } void Person::setShoeSize(int s) { m_shoeSize = s; }
lgpl-2.1
derek57/sdl-test
src/video/x11/SDL_x11video.c
34
45534
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #include "SDL_config.h" /* X11 based SDL video driver implementation. Note: This implementation does not currently need X11 thread locking, since the event thread uses a separate X connection and any additional locking necessary is handled internally. However, if full locking is neccessary, take a look at XInitThreads(). */ #include <unistd.h> #include <sys/ioctl.h> #ifdef MTRR_SUPPORT #include <asm/mtrr.h> #include <sys/fcntl.h> #endif #include "SDL_endian.h" #include "SDL_timer.h" #include "SDL_thread.h" #include "SDL_video.h" #include "SDL_mouse.h" #include "../SDL_sysvideo.h" #include "../SDL_pixels_c.h" #include "../../events/SDL_events_c.h" #include "SDL_x11video.h" #include "SDL_x11wm_c.h" #include "SDL_x11mouse_c.h" #include "SDL_x11events_c.h" #include "SDL_x11modes_c.h" #include "SDL_x11image_c.h" #include "SDL_x11yuv_c.h" #include "SDL_x11gl_c.h" #include "SDL_x11gamma_c.h" #include "../blank_cursor.h" #ifdef X_HAVE_UTF8_STRING #include <locale.h> #endif /* Initialization/Query functions */ static int X11_VideoInit(_THIS, SDL_PixelFormat *vformat); static SDL_Surface *X11_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); static int X11_ToggleFullScreen(_THIS, int on); static void X11_UpdateMouse(_THIS); static int X11_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); static int X11_SetGammaRamp(_THIS, Uint16 *ramp); static void X11_VideoQuit(_THIS); /* X11 driver bootstrap functions */ static int X11_Available(void) { Display *display = NULL; if ( SDL_X11_LoadSymbols() ) { display = XOpenDisplay(NULL); if ( display != NULL ) { XCloseDisplay(display); } SDL_X11_UnloadSymbols(); } return(display != NULL); } static void X11_DeleteDevice(SDL_VideoDevice *device) { if ( device ) { if ( device->hidden ) { SDL_free(device->hidden); } if ( device->gl_data ) { SDL_free(device->gl_data); } SDL_free(device); SDL_X11_UnloadSymbols(); } } static SDL_VideoDevice *X11_CreateDevice(int devindex) { SDL_VideoDevice *device = NULL; if ( SDL_X11_LoadSymbols() ) { /* Initialize all variables that we clean on shutdown */ device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); if ( device ) { SDL_memset(device, 0, (sizeof *device)); device->hidden = (struct SDL_PrivateVideoData *) SDL_malloc((sizeof *device->hidden)); device->gl_data = (struct SDL_PrivateGLData *) SDL_malloc((sizeof *device->gl_data)); } if ( (device == NULL) || (device->hidden == NULL) || (device->gl_data == NULL) ) { SDL_OutOfMemory(); X11_DeleteDevice(device); /* calls SDL_X11_UnloadSymbols(). */ return(0); } SDL_memset(device->hidden, 0, (sizeof *device->hidden)); SDL_memset(device->gl_data, 0, (sizeof *device->gl_data)); #if SDL_VIDEO_OPENGL_GLX device->gl_data->swap_interval = -1; #endif /* Set the driver flags */ device->handles_any_size = 1; /* Set the function pointers */ device->VideoInit = X11_VideoInit; device->ListModes = X11_ListModes; device->SetVideoMode = X11_SetVideoMode; device->ToggleFullScreen = X11_ToggleFullScreen; device->UpdateMouse = X11_UpdateMouse; #if SDL_VIDEO_DRIVER_X11_XV device->CreateYUVOverlay = X11_CreateYUVOverlay; #endif device->SetColors = X11_SetColors; device->UpdateRects = NULL; device->VideoQuit = X11_VideoQuit; device->AllocHWSurface = X11_AllocHWSurface; device->CheckHWBlit = NULL; device->FillHWRect = NULL; device->SetHWColorKey = NULL; device->SetHWAlpha = NULL; device->LockHWSurface = X11_LockHWSurface; device->UnlockHWSurface = X11_UnlockHWSurface; device->FlipHWSurface = X11_FlipHWSurface; device->FreeHWSurface = X11_FreeHWSurface; device->SetGamma = X11_SetVidModeGamma; device->GetGamma = X11_GetVidModeGamma; device->SetGammaRamp = X11_SetGammaRamp; device->GetGammaRamp = NULL; #if SDL_VIDEO_OPENGL_GLX device->GL_LoadLibrary = X11_GL_LoadLibrary; device->GL_GetProcAddress = X11_GL_GetProcAddress; device->GL_GetAttribute = X11_GL_GetAttribute; device->GL_MakeCurrent = X11_GL_MakeCurrent; device->GL_SwapBuffers = X11_GL_SwapBuffers; #endif device->SetCaption = X11_SetCaption; device->SetIcon = X11_SetIcon; device->IconifyWindow = X11_IconifyWindow; device->GrabInput = X11_GrabInput; device->GetWMInfo = X11_GetWMInfo; device->FreeWMCursor = X11_FreeWMCursor; device->CreateWMCursor = X11_CreateWMCursor; device->ShowWMCursor = X11_ShowWMCursor; device->WarpWMCursor = X11_WarpWMCursor; device->CheckMouseMode = X11_CheckMouseMode; device->InitOSKeymap = X11_InitOSKeymap; device->PumpEvents = X11_PumpEvents; device->free = X11_DeleteDevice; } return device; } VideoBootStrap X11_bootstrap = { "x11", "X Window System", X11_Available, X11_CreateDevice }; /* Normal X11 error handler routine */ static int (*X_handler)(Display *, XErrorEvent *) = NULL; static int x_errhandler(Display *d, XErrorEvent *e) { #if SDL_VIDEO_DRIVER_X11_VIDMODE extern int vm_error; #endif #if SDL_VIDEO_DRIVER_X11_DGAMOUSE extern int dga_error; #endif #if SDL_VIDEO_DRIVER_X11_VIDMODE /* VidMode errors are non-fatal. :) */ /* Are the errors offset by one from the error base? e.g. the error base is 143, the code is 148, and the actual error is XF86VidModeExtensionDisabled (4) ? */ if ( (vm_error >= 0) && (((e->error_code == BadRequest)&&(e->request_code == vm_error)) || ((e->error_code > vm_error) && (e->error_code <= (vm_error+XF86VidModeNumberErrors)))) ) { #ifdef X11_DEBUG { char errmsg[1024]; XGetErrorText(d, e->error_code, errmsg, sizeof(errmsg)); printf("VidMode error: %s\n", errmsg); } #endif return(0); } #endif /* SDL_VIDEO_DRIVER_X11_VIDMODE */ #if SDL_VIDEO_DRIVER_X11_DGAMOUSE /* DGA errors can be non-fatal. :) */ if ( (dga_error >= 0) && ((e->error_code > dga_error) && (e->error_code <= (dga_error+XF86DGANumberErrors))) ) { #ifdef X11_DEBUG { char errmsg[1024]; XGetErrorText(d, e->error_code, errmsg, sizeof(errmsg)); printf("DGA error: %s\n", errmsg); } #endif return(0); } #endif /* SDL_VIDEO_DRIVER_X11_DGAMOUSE */ return(X_handler(d,e)); } /* X11 I/O error handler routine */ static int (*XIO_handler)(Display *) = NULL; static int xio_errhandler(Display *d) { /* Ack! Lost X11 connection! */ /* We will crash if we try to clean up our display */ if ( SDL_VideoSurface && current_video->hidden->Ximage ) { SDL_VideoSurface->pixels = NULL; } current_video->hidden->X11_Display = NULL; /* Continue with the standard X11 error handler */ return(XIO_handler(d)); } static int (*Xext_handler)(Display *, _Xconst char *, _Xconst char *) = NULL; static int xext_errhandler(Display *d, _Xconst char *ext, _Xconst char *reason) { #ifdef X11_DEBUG printf("Xext error inside SDL (may be harmless):\n"); printf(" Extension \"%s\" %s on display \"%s\".\n", ext, reason, XDisplayString(d)); #endif if (SDL_strcmp(reason, "missing") == 0) { /* * Since the query itself, elsewhere, can handle a missing extension * and the default behaviour in Xlib is to write to stderr, which * generates unnecessary bug reports, we just ignore these. */ return 0; } /* Everything else goes to the default handler... */ return Xext_handler(d, ext, reason); } /* Find out what class name we should use */ static char *get_classname(char *classname, int maxlen) { char *spot; #if defined(__LINUX__) || defined(__FREEBSD__) char procfile[1024]; char linkfile[1024]; int linksize; #endif /* First allow environment variable override */ spot = SDL_getenv("SDL_VIDEO_X11_WMCLASS"); if ( spot ) { SDL_strlcpy(classname, spot, maxlen); return classname; } /* Next look at the application's executable name */ #if defined(__LINUX__) || defined(__FREEBSD__) #if defined(__LINUX__) SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/exe", getpid()); #elif defined(__FREEBSD__) SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/file", getpid()); #else #error Where can we find the executable name? #endif linksize = readlink(procfile, linkfile, sizeof(linkfile)-1); if ( linksize > 0 ) { linkfile[linksize] = '\0'; spot = SDL_strrchr(linkfile, '/'); if ( spot ) { SDL_strlcpy(classname, spot+1, maxlen); } else { SDL_strlcpy(classname, linkfile, maxlen); } return classname; } #endif /* __LINUX__ */ /* Finally use the default we've used forever */ SDL_strlcpy(classname, "SDL_App", maxlen); return classname; } /* Create auxiliary (toplevel) windows with the current visual */ static void create_aux_windows(_THIS) { int x = 0, y = 0; char classname[1024]; XSetWindowAttributes xattr; XWMHints *hints; unsigned long app_event_mask; int def_vis = (SDL_Visual == DefaultVisual(SDL_Display, SDL_Screen)); /* Look up some useful Atoms */ WM_DELETE_WINDOW = XInternAtom(SDL_Display, "WM_DELETE_WINDOW", False); /* Don't create any extra windows if we are being managed */ if ( SDL_windowid ) { FSwindow = 0; WMwindow = SDL_strtol(SDL_windowid, NULL, 0); return; } if(FSwindow) XDestroyWindow(SDL_Display, FSwindow); #if SDL_VIDEO_DRIVER_X11_XINERAMA if ( use_xinerama ) { x = xinerama_info.x_org; y = xinerama_info.y_org; } #endif xattr.override_redirect = True; xattr.background_pixel = def_vis ? BlackPixel(SDL_Display, SDL_Screen) : 0; xattr.border_pixel = 0; xattr.colormap = SDL_XColorMap; FSwindow = XCreateWindow(SDL_Display, SDL_Root, x, y, 32, 32, 0, this->hidden->depth, InputOutput, SDL_Visual, CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWColormap, &xattr); XSelectInput(SDL_Display, FSwindow, StructureNotifyMask); /* Tell KDE to keep the fullscreen window on top */ { XEvent ev; long mask; SDL_memset(&ev, 0, sizeof(ev)); ev.xclient.type = ClientMessage; ev.xclient.window = SDL_Root; ev.xclient.message_type = XInternAtom(SDL_Display, "KWM_KEEP_ON_TOP", False); ev.xclient.format = 32; ev.xclient.data.l[0] = FSwindow; ev.xclient.data.l[1] = CurrentTime; mask = SubstructureRedirectMask; XSendEvent(SDL_Display, SDL_Root, False, mask, &ev); } hints = NULL; if(WMwindow) { /* All window attributes must survive the recreation */ hints = XGetWMHints(SDL_Display, WMwindow); XDestroyWindow(SDL_Display, WMwindow); } /* Create the window for windowed management */ /* (reusing the xattr structure above) */ WMwindow = XCreateWindow(SDL_Display, SDL_Root, x, y, 32, 32, 0, this->hidden->depth, InputOutput, SDL_Visual, CWBackPixel | CWBorderPixel | CWColormap, &xattr); /* Set the input hints so we get keyboard input */ if(!hints) { hints = XAllocWMHints(); hints->input = True; hints->flags = InputHint; } XSetWMHints(SDL_Display, WMwindow, hints); XFree(hints); X11_SetCaptionNoLock(this, this->wm_title, this->wm_icon); app_event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask | PropertyChangeMask | StructureNotifyMask | KeymapStateMask; XSelectInput(SDL_Display, WMwindow, app_event_mask); /* Set the class hints so we can get an icon (AfterStep) */ get_classname(classname, sizeof(classname)); { XClassHint *classhints; classhints = XAllocClassHint(); if(classhints != NULL) { classhints->res_name = classname; classhints->res_class = classname; XSetClassHint(SDL_Display, WMwindow, classhints); XFree(classhints); } } { pid_t pid = getpid(); char hostname[256]; if (pid > 0 && gethostname(hostname, sizeof(hostname)) > -1) { Atom _NET_WM_PID = XInternAtom(SDL_Display, "_NET_WM_PID", False); Atom WM_CLIENT_MACHINE = XInternAtom(SDL_Display, "WM_CLIENT_MACHINE", False); hostname[sizeof(hostname)-1] = '\0'; XChangeProperty(SDL_Display, WMwindow, _NET_WM_PID, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1); XChangeProperty(SDL_Display, WMwindow, WM_CLIENT_MACHINE, XA_STRING, 8, PropModeReplace, (unsigned char *)hostname, SDL_strlen(hostname)); } } /* Setup the communication with the IM server */ /* create_aux_windows may be called several times against the same Display. We should reuse the SDL_IM if one has been opened for the Display, so we should not simply reset SDL_IM here. */ #ifdef X_HAVE_UTF8_STRING if (SDL_X11_HAVE_UTF8) { /* Discard obsolete resources if any. */ if (SDL_IM != NULL && SDL_Display != XDisplayOfIM(SDL_IM)) { /* Just a double check. I don't think this code is ever executed. */ SDL_SetError("display has changed while an IM is kept"); if (SDL_IC) { XUnsetICFocus(SDL_IC); XDestroyIC(SDL_IC); SDL_IC = NULL; } XCloseIM(SDL_IM); SDL_IM = NULL; } /* Open an input method. */ if (SDL_IM == NULL) { char *old_locale = NULL, *old_modifiers = NULL; const char *p; size_t n; /* I'm not comfortable to do locale setup here. However, we need C library locale (and xlib modifiers) to be set based on the user's preference to use XIM, and many existing game programs doesn't take care of users' locale preferences, so someone other than the game program should do it. Moreover, ones say that some game programs heavily rely on the C locale behaviour, e.g., strcol()'s, and we can't change the C library locale. Given the situation, I couldn't find better place to do the job... */ /* Save the current (application program's) locale settings. */ p = setlocale(LC_ALL, NULL); if ( p ) { n = SDL_strlen(p)+1; old_locale = SDL_stack_alloc(char, n); if ( old_locale ) { SDL_strlcpy(old_locale, p, n); } } p = XSetLocaleModifiers(NULL); if ( p ) { n = SDL_strlen(p)+1; old_modifiers = SDL_stack_alloc(char, n); if ( old_modifiers ) { SDL_strlcpy(old_modifiers, p, n); } } /* Fetch the user's preferences and open the input method with them. */ setlocale(LC_ALL, ""); XSetLocaleModifiers(""); SDL_IM = XOpenIM(SDL_Display, NULL, classname, classname); /* Restore the application's locale settings so that we don't break the application's expected behaviour. */ if ( old_locale ) { /* We need to restore the C library locale first, since the interpretation of the X modifier may depend on it. */ setlocale(LC_ALL, old_locale); SDL_stack_free(old_locale); } if ( old_modifiers ) { XSetLocaleModifiers(old_modifiers); SDL_stack_free(old_modifiers); } } /* Create a new input context for the new window just created. */ if (SDL_IM == NULL) { SDL_SetError("no input method could be opened"); } else { if (SDL_IC != NULL) { /* Discard the old IC before creating new one. */ XUnsetICFocus(SDL_IC); XDestroyIC(SDL_IC); } /* Theoretically we should check the current IM supports PreeditNothing+StatusNothing style (i.e., root window method) before creating the IC. However, it is the bottom line method, and we supports any other options. If the IM didn't support root window method, the following call fails, and SDL falls back to pre-XIM keyboard handling. */ SDL_IC = pXCreateIC(SDL_IM, XNClientWindow, WMwindow, XNFocusWindow, WMwindow, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNResourceName, classname, XNResourceClass, classname, NULL); if (SDL_IC == NULL) { SDL_SetError("no input context could be created"); XCloseIM(SDL_IM); SDL_IM = NULL; } else { /* We need to receive X events that an IM wants and to pass them to the IM through XFilterEvent. The set of events may vary depending on the IM implementation and the options specified through various routes. Although unlikely, the xlib specification allows IM to change the event requirement with its own circumstances, it is safe to call SelectInput whenever we re-create an IC. */ unsigned long mask = 0; char *ret = pXGetICValues(SDL_IC, XNFilterEvents, &mask, NULL); if (ret != NULL) { XUnsetICFocus(SDL_IC); XDestroyIC(SDL_IC); SDL_IC = NULL; SDL_SetError("no input context could be created"); XCloseIM(SDL_IM); SDL_IM = NULL; } else { XSelectInput(SDL_Display, WMwindow, app_event_mask | mask); XSetICFocus(SDL_IC); } } } } #endif /* Allow the window to be deleted by the window manager */ XSetWMProtocols(SDL_Display, WMwindow, &WM_DELETE_WINDOW, 1); } static int X11_VideoInit(_THIS, SDL_PixelFormat *vformat) { const char *env; char *display; int i; /* Open the X11 display */ display = NULL; /* Get it from DISPLAY environment variable */ if ( (SDL_strncmp(XDisplayName(display), ":", 1) == 0) || (SDL_strncmp(XDisplayName(display), "unix:", 5) == 0) ) { local_X11 = 1; } else { local_X11 = 0; } SDL_Display = XOpenDisplay(display); #if defined(__osf__) && defined(SDL_VIDEO_DRIVER_X11_DYNAMIC) /* On Tru64 if linking without -lX11, it fails and you get following message. * Xlib: connection to ":0.0" refused by server * Xlib: XDM authorization key matches an existing client! * * It succeeds if retrying 1 second later * or if running xhost +localhost on shell. * */ if ( SDL_Display == NULL ) { SDL_Delay(1000); SDL_Display = XOpenDisplay(display); } #endif if ( SDL_Display == NULL ) { SDL_SetError("Couldn't open X11 display"); return(-1); } #ifdef X11_DEBUG XSynchronize(SDL_Display, True); #endif /* Create an alternate X display for graphics updates -- allows us to do graphics updates in a separate thread from event handling. Thread-safe X11 doesn't seem to exist. */ GFX_Display = XOpenDisplay(display); if ( GFX_Display == NULL ) { XCloseDisplay(SDL_Display); SDL_Display = NULL; SDL_SetError("Couldn't open X11 display"); return(-1); } /* Set the normal X error handler */ X_handler = XSetErrorHandler(x_errhandler); /* Set the error handler if we lose the X display */ XIO_handler = XSetIOErrorHandler(xio_errhandler); /* Set the X extension error handler */ Xext_handler = XSetExtensionErrorHandler(xext_errhandler); /* use default screen (from $DISPLAY) */ SDL_Screen = DefaultScreen(SDL_Display); #ifndef NO_SHARED_MEMORY /* Check for MIT shared memory extension */ use_mitshm = 0; if ( local_X11 ) { use_mitshm = XShmQueryExtension(SDL_Display); } #endif /* NO_SHARED_MEMORY */ /* Get the available video modes */ if(X11_GetVideoModes(this) < 0) { XCloseDisplay(GFX_Display); GFX_Display = NULL; XCloseDisplay(SDL_Display); SDL_Display = NULL; return -1; } /* Determine the current screen size */ this->info.current_w = DisplayWidth(SDL_Display, SDL_Screen); this->info.current_h = DisplayHeight(SDL_Display, SDL_Screen); /* Determine the default screen depth: Use the default visual (or at least one with the same depth) */ SDL_DisplayColormap = DefaultColormap(SDL_Display, SDL_Screen); for(i = 0; i < this->hidden->nvisuals; i++) if(this->hidden->visuals[i].depth == DefaultDepth(SDL_Display, SDL_Screen)) break; if(i == this->hidden->nvisuals) { /* default visual was useless, take the deepest one instead */ i = 0; } SDL_Visual = this->hidden->visuals[i].visual; if ( SDL_Visual == DefaultVisual(SDL_Display, SDL_Screen) ) { SDL_XColorMap = SDL_DisplayColormap; } else { SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root, SDL_Visual, AllocNone); } this->hidden->depth = this->hidden->visuals[i].depth; vformat->BitsPerPixel = this->hidden->visuals[i].bpp; if ( vformat->BitsPerPixel > 8 ) { vformat->Rmask = SDL_Visual->red_mask; vformat->Gmask = SDL_Visual->green_mask; vformat->Bmask = SDL_Visual->blue_mask; } if ( this->hidden->depth == 32 ) { vformat->Amask = (0xFFFFFFFF & ~(vformat->Rmask|vformat->Gmask|vformat->Bmask)); } X11_SaveVidModeGamma(this); /* Allow environment override of screensaver disable. */ env = SDL_getenv("SDL_VIDEO_ALLOW_SCREENSAVER"); if ( env ) { allow_screensaver = SDL_atoi(env); } else { #ifdef SDL_VIDEO_DISABLE_SCREENSAVER allow_screensaver = 0; #else allow_screensaver = 1; #endif } /* See if we have been passed a window to use */ SDL_windowid = SDL_getenv("SDL_WINDOWID"); /* Create the fullscreen and managed windows */ create_aux_windows(this); /* Create the blank cursor */ SDL_BlankCursor = this->CreateWMCursor(this, blank_cdata, blank_cmask, BLANK_CWIDTH, BLANK_CHEIGHT, BLANK_CHOTX, BLANK_CHOTY); /* Fill in some window manager capabilities */ this->info.wm_available = 1; /* We're done! */ XFlush(SDL_Display); return(0); } static void X11_DestroyWindow(_THIS, SDL_Surface *screen) { /* Clean up OpenGL */ if ( screen ) { screen->flags &= ~(SDL_OPENGL|SDL_OPENGLBLIT); } X11_GL_Shutdown(this); if ( ! SDL_windowid ) { /* Hide the managed window */ if ( WMwindow ) { XUnmapWindow(SDL_Display, WMwindow); } if ( screen && (screen->flags & SDL_FULLSCREEN) ) { screen->flags &= ~SDL_FULLSCREEN; X11_LeaveFullScreen(this); } /* Destroy the output window */ if ( SDL_Window ) { XDestroyWindow(SDL_Display, SDL_Window); } /* Free the colormap entries */ if ( SDL_XPixels ) { int numcolors; unsigned long pixel; numcolors = SDL_Visual->map_entries; for ( pixel=0; pixel<numcolors; ++pixel ) { while ( SDL_XPixels[pixel] > 0 ) { XFreeColors(GFX_Display, SDL_DisplayColormap,&pixel,1,0); --SDL_XPixels[pixel]; } } SDL_free(SDL_XPixels); SDL_XPixels = NULL; } /* Free the graphics context */ if ( SDL_GC ) { XFreeGC(SDL_Display, SDL_GC); SDL_GC = 0; } } } static SDL_bool X11_WindowPosition(_THIS, int *x, int *y, int w, int h) { const char *window = SDL_getenv("SDL_VIDEO_WINDOW_POS"); const char *center = SDL_getenv("SDL_VIDEO_CENTERED"); if ( window ) { if ( SDL_sscanf(window, "%d,%d", x, y) == 2 ) { return SDL_TRUE; } if ( SDL_strcmp(window, "center") == 0 ) { center = window; } } if ( center ) { *x = (DisplayWidth(SDL_Display, SDL_Screen) - w)/2; *y = (DisplayHeight(SDL_Display, SDL_Screen) - h)/2; return SDL_TRUE; } return SDL_FALSE; } static void X11_SetSizeHints(_THIS, int w, int h, Uint32 flags) { XSizeHints *hints; hints = XAllocSizeHints(); if ( hints ) { if (!(flags & SDL_RESIZABLE)) { hints->min_width = hints->max_width = w; hints->min_height = hints->max_height = h; hints->flags = PMaxSize | PMinSize; } if ( flags & SDL_FULLSCREEN ) { hints->x = 0; hints->y = 0; hints->flags |= USPosition; } else /* Center it, if desired */ if ( X11_WindowPosition(this, &hints->x, &hints->y, w, h) ) { hints->flags |= USPosition; /* Hints must be set before moving the window, otherwise an unwanted ConfigureNotify event will be issued */ XSetWMNormalHints(SDL_Display, WMwindow, hints); XMoveWindow(SDL_Display, WMwindow, hints->x, hints->y); /* Flush the resize event so we don't catch it later */ XSync(SDL_Display, True); } XSetWMNormalHints(SDL_Display, WMwindow, hints); XFree(hints); } /* Respect the window caption style */ if ( flags & SDL_NOFRAME ) { SDL_bool set; Atom WM_HINTS; /* We haven't modified the window manager hints yet */ set = SDL_FALSE; /* First try to set MWM hints */ WM_HINTS = XInternAtom(SDL_Display, "_MOTIF_WM_HINTS", True); if ( WM_HINTS != None ) { /* Hints used by Motif compliant window managers */ struct { unsigned long flags; unsigned long functions; unsigned long decorations; long input_mode; unsigned long status; } MWMHints = { (1L << 1), 0, 0, 0, 0 }; XChangeProperty(SDL_Display, WMwindow, WM_HINTS, WM_HINTS, 32, PropModeReplace, (unsigned char *)&MWMHints, sizeof(MWMHints)/sizeof(long)); set = SDL_TRUE; } /* Now try to set KWM hints */ WM_HINTS = XInternAtom(SDL_Display, "KWM_WIN_DECORATION", True); if ( WM_HINTS != None ) { long KWMHints = 0; XChangeProperty(SDL_Display, WMwindow, WM_HINTS, WM_HINTS, 32, PropModeReplace, (unsigned char *)&KWMHints, sizeof(KWMHints)/sizeof(long)); set = SDL_TRUE; } /* Now try to set GNOME hints */ WM_HINTS = XInternAtom(SDL_Display, "_WIN_HINTS", True); if ( WM_HINTS != None ) { long GNOMEHints = 0; XChangeProperty(SDL_Display, WMwindow, WM_HINTS, WM_HINTS, 32, PropModeReplace, (unsigned char *)&GNOMEHints, sizeof(GNOMEHints)/sizeof(long)); set = SDL_TRUE; } /* Finally set the transient hints if necessary */ if ( ! set ) { XSetTransientForHint(SDL_Display, WMwindow, SDL_Root); } } else { SDL_bool set; Atom WM_HINTS; /* We haven't modified the window manager hints yet */ set = SDL_FALSE; /* First try to unset MWM hints */ WM_HINTS = XInternAtom(SDL_Display, "_MOTIF_WM_HINTS", True); if ( WM_HINTS != None ) { XDeleteProperty(SDL_Display, WMwindow, WM_HINTS); set = SDL_TRUE; } /* Now try to unset KWM hints */ WM_HINTS = XInternAtom(SDL_Display, "KWM_WIN_DECORATION", True); if ( WM_HINTS != None ) { XDeleteProperty(SDL_Display, WMwindow, WM_HINTS); set = SDL_TRUE; } /* Now try to unset GNOME hints */ WM_HINTS = XInternAtom(SDL_Display, "_WIN_HINTS", True); if ( WM_HINTS != None ) { XDeleteProperty(SDL_Display, WMwindow, WM_HINTS); set = SDL_TRUE; } /* Finally unset the transient hints if necessary */ if ( ! set ) { XDeleteProperty(SDL_Display, WMwindow, XA_WM_TRANSIENT_FOR); } } } static int X11_CreateWindow(_THIS, SDL_Surface *screen, int w, int h, int bpp, Uint32 flags) { int i, depth; Visual *vis; int vis_change; Uint32 Amask; /* If a window is already present, destroy it and start fresh */ if ( SDL_Window ) { X11_DestroyWindow(this, screen); switch_waiting = 0; /* Prevent jump back to now-meaningless state. */ } /* See if we have been given a window id */ if ( SDL_windowid ) { SDL_Window = SDL_strtol(SDL_windowid, NULL, 0); } else { SDL_Window = 0; } /* find out which visual we are going to use */ if ( flags & SDL_OPENGL ) { XVisualInfo *vi; vi = X11_GL_GetVisual(this); if( !vi ) { return -1; } vis = vi->visual; depth = vi->depth; } else if ( SDL_windowid ) { XWindowAttributes a; XGetWindowAttributes(SDL_Display, SDL_Window, &a); vis = a.visual; depth = a.depth; } else { for ( i = 0; i < this->hidden->nvisuals; i++ ) { if ( this->hidden->visuals[i].bpp == bpp ) break; } if ( i == this->hidden->nvisuals ) { SDL_SetError("No matching visual for requested depth"); return -1; /* should never happen */ } vis = this->hidden->visuals[i].visual; depth = this->hidden->visuals[i].depth; } #ifdef X11_DEBUG printf("Choosing %s visual at %d bpp - %d colormap entries\n", vis->class == PseudoColor ? "PseudoColor" : (vis->class == TrueColor ? "TrueColor" : (vis->class == DirectColor ? "DirectColor" : "Unknown")), depth, vis->map_entries); #endif vis_change = (vis != SDL_Visual); SDL_Visual = vis; this->hidden->depth = depth; /* Allocate the new pixel format for this video mode */ if ( this->hidden->depth == 32 ) { Amask = (0xFFFFFFFF & ~(vis->red_mask|vis->green_mask|vis->blue_mask)); } else { Amask = 0; } if ( ! SDL_ReallocFormat(screen, bpp, vis->red_mask, vis->green_mask, vis->blue_mask, Amask) ) { return -1; } /* Create the appropriate colormap */ if ( SDL_XColorMap != SDL_DisplayColormap ) { XFreeColormap(SDL_Display, SDL_XColorMap); } if ( SDL_Visual->class == PseudoColor ) { int ncolors; /* Allocate the pixel flags */ ncolors = SDL_Visual->map_entries; SDL_XPixels = SDL_malloc(ncolors * sizeof(int)); if(SDL_XPixels == NULL) { SDL_OutOfMemory(); return -1; } SDL_memset(SDL_XPixels, 0, ncolors * sizeof(*SDL_XPixels)); /* always allocate a private colormap on non-default visuals */ if ( SDL_Visual != DefaultVisual(SDL_Display, SDL_Screen) ) { flags |= SDL_HWPALETTE; } if ( flags & SDL_HWPALETTE ) { screen->flags |= SDL_HWPALETTE; SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root, SDL_Visual, AllocAll); } else { SDL_XColorMap = SDL_DisplayColormap; } } else if ( SDL_Visual->class == DirectColor ) { /* Create a colormap which we can manipulate for gamma */ SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root, SDL_Visual, AllocAll); XSync(SDL_Display, False); /* Initialize the colormap to the identity mapping */ SDL_GetGammaRamp(0, 0, 0); this->screen = screen; X11_SetGammaRamp(this, this->gamma); this->screen = NULL; } else { /* Create a read-only colormap for our window */ SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root, SDL_Visual, AllocNone); } /* Recreate the auxiliary windows, if needed (required for GL) */ if ( vis_change ) create_aux_windows(this); if(screen->flags & SDL_HWPALETTE) { /* Since the full-screen window might have got a nonzero background colour (0 is white on some displays), we should reset the background to 0 here since that is what the user expects with a private colormap */ XSetWindowBackground(SDL_Display, FSwindow, 0); XClearWindow(SDL_Display, FSwindow); } /* resize the (possibly new) window manager window */ if( !SDL_windowid ) { X11_SetSizeHints(this, w, h, flags); window_w = w; window_h = h; XResizeWindow(SDL_Display, WMwindow, w, h); } /* Create (or use) the X11 display window */ if ( !SDL_windowid ) { if ( flags & SDL_OPENGL ) { if ( X11_GL_CreateWindow(this, w, h) < 0 ) { return(-1); } } else { XSetWindowAttributes swa; swa.background_pixel = 0; swa.border_pixel = 0; swa.colormap = SDL_XColorMap; SDL_Window = XCreateWindow(SDL_Display, WMwindow, 0, 0, w, h, 0, depth, InputOutput, SDL_Visual, CWBackPixel | CWBorderPixel | CWColormap, &swa); } /* Only manage our input if we own the window */ XSelectInput(SDL_Display, SDL_Window, ( EnterWindowMask | LeaveWindowMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | ExposureMask )); } /* Create the graphics context here, once we have a window */ if ( flags & SDL_OPENGL ) { if ( X11_GL_CreateContext(this) < 0 ) { return(-1); } else { screen->flags |= SDL_OPENGL; } } else { XGCValues gcv; gcv.graphics_exposures = False; SDL_GC = XCreateGC(SDL_Display, SDL_Window, GCGraphicsExposures, &gcv); if ( ! SDL_GC ) { SDL_SetError("Couldn't create graphics context"); return(-1); } } /* Set our colormaps when not setting a GL mode */ if ( ! (flags & SDL_OPENGL) ) { XSetWindowColormap(SDL_Display, SDL_Window, SDL_XColorMap); if( !SDL_windowid ) { XSetWindowColormap(SDL_Display, FSwindow, SDL_XColorMap); XSetWindowColormap(SDL_Display, WMwindow, SDL_XColorMap); } } #if 0 /* This is an experiment - are the graphics faster now? - nope. */ if ( SDL_getenv("SDL_VIDEO_X11_BACKINGSTORE") ) #endif /* Cache the window in the server, when possible */ { Screen *xscreen; XSetWindowAttributes a; xscreen = ScreenOfDisplay(SDL_Display, SDL_Screen); a.backing_store = DoesBackingStore(xscreen); if ( a.backing_store != NotUseful ) { XChangeWindowAttributes(SDL_Display, SDL_Window, CWBackingStore, &a); } } /* Map them both and go fullscreen, if requested */ if ( ! SDL_windowid ) { XMapWindow(SDL_Display, SDL_Window); XMapWindow(SDL_Display, WMwindow); X11_WaitMapped(this, WMwindow); if ( flags & SDL_FULLSCREEN ) { screen->flags |= SDL_FULLSCREEN; X11_EnterFullScreen(this); } else { screen->flags &= ~SDL_FULLSCREEN; } } return(0); } static int X11_ResizeWindow(_THIS, SDL_Surface *screen, int w, int h, Uint32 flags) { if ( ! SDL_windowid ) { /* Resize the window manager window */ X11_SetSizeHints(this, w, h, flags); window_w = w; window_h = h; XResizeWindow(SDL_Display, WMwindow, w, h); /* Resize the fullscreen and display windows */ if ( flags & SDL_FULLSCREEN ) { if ( screen->flags & SDL_FULLSCREEN ) { X11_ResizeFullScreen(this); } else { screen->flags |= SDL_FULLSCREEN; X11_EnterFullScreen(this); } } else { if ( screen->flags & SDL_FULLSCREEN ) { screen->flags &= ~SDL_FULLSCREEN; X11_LeaveFullScreen(this); } } XResizeWindow(SDL_Display, SDL_Window, w, h); } return(0); } SDL_Surface *X11_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags) { Uint32 saved_flags; /* Lock the event thread, in multi-threading environments */ SDL_Lock_EventThread(); /* Check the combination of flags we were passed */ if ( flags & SDL_FULLSCREEN ) { /* Clear fullscreen flag if not supported */ if ( SDL_windowid ) { flags &= ~SDL_FULLSCREEN; } } /* Flush any delayed updates */ XSync(GFX_Display, False); /* Set up the X11 window */ saved_flags = current->flags; if ( (SDL_Window) && ((saved_flags&SDL_OPENGL) == (flags&SDL_OPENGL)) && (bpp == current->format->BitsPerPixel) && ((saved_flags&SDL_NOFRAME) == (flags&SDL_NOFRAME)) ) { if (X11_ResizeWindow(this, current, width, height, flags) < 0) { current = NULL; goto done; } X11_PendingConfigureNotifyWidth = width; X11_PendingConfigureNotifyHeight = height; } else { if (X11_CreateWindow(this,current,width,height,bpp,flags) < 0) { current = NULL; goto done; } } /* Update the internal keyboard state */ X11_SetKeyboardState(SDL_Display, NULL); /* When the window is first mapped, ignore non-modifier keys */ if ( !current->w && !current->h ) { Uint8 *keys = SDL_GetKeyState(NULL); int i; for ( i = 0; i < SDLK_LAST; ++i ) { switch (i) { case SDLK_NUMLOCK: case SDLK_CAPSLOCK: case SDLK_LCTRL: case SDLK_RCTRL: case SDLK_LSHIFT: case SDLK_RSHIFT: case SDLK_LALT: case SDLK_RALT: case SDLK_LMETA: case SDLK_RMETA: case SDLK_MODE: break; default: keys[i] = SDL_RELEASED; break; } } } /* Set up the new mode framebuffer */ if ( ((current->w != width) || (current->h != height)) || ((saved_flags&SDL_OPENGL) != (flags&SDL_OPENGL)) ) { current->w = width; current->h = height; current->pitch = SDL_CalculatePitch(current); if (X11_ResizeImage(this, current, flags) < 0) { current = NULL; goto done; } } /* Clear these flags and set them only if they are in the new set. */ current->flags &= ~(SDL_RESIZABLE|SDL_NOFRAME); current->flags |= (flags&(SDL_RESIZABLE|SDL_NOFRAME)); done: /* Release the event thread */ XSync(SDL_Display, False); SDL_Unlock_EventThread(); /* We're done! */ return(current); } static int X11_ToggleFullScreen(_THIS, int on) { Uint32 event_thread; /* Don't switch if we don't own the window */ if ( SDL_windowid ) { return(0); } /* Don't lock if we are the event thread */ event_thread = SDL_EventThreadID(); if ( event_thread && (SDL_ThreadID() == event_thread) ) { event_thread = 0; } if ( event_thread ) { SDL_Lock_EventThread(); } if ( on ) { this->screen->flags |= SDL_FULLSCREEN; X11_EnterFullScreen(this); } else { this->screen->flags &= ~SDL_FULLSCREEN; X11_LeaveFullScreen(this); } X11_RefreshDisplay(this); if ( event_thread ) { SDL_Unlock_EventThread(); } SDL_ResetKeyboard(); return(1); } /* Update the current mouse state and position */ static void X11_UpdateMouse(_THIS) { Window u1; int u2; Window current_win; int x, y; unsigned int mask; /* Lock the event thread, in multi-threading environments */ SDL_Lock_EventThread(); if ( XQueryPointer(SDL_Display, SDL_Window, &u1, &current_win, &u2, &u2, &x, &y, &mask) ) { if ( (x >= 0) && (x < SDL_VideoSurface->w) && (y >= 0) && (y < SDL_VideoSurface->h) ) { SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); SDL_PrivateMouseMotion(0, 0, x, y); } else { SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); } } SDL_Unlock_EventThread(); } /* simple colour distance metric. Supposed to be better than a plain Euclidian distance anyway. */ #define COLOUR_FACTOR 3 #define LIGHT_FACTOR 1 #define COLOUR_DIST(r1, g1, b1, r2, g2, b2) \ (COLOUR_FACTOR * (abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2)) \ + LIGHT_FACTOR * abs(r1 + g1 + b1 - (r2 + g2 + b2))) static void allocate_nearest(_THIS, SDL_Color *colors, SDL_Color *want, int nwant) { /* * There is no way to know which ones to choose from, so we retrieve * the entire colormap and try the nearest possible, until we find one * that is shared. */ XColor all[256]; int i; for(i = 0; i < 256; i++) all[i].pixel = i; /* * XQueryColors sets the flags in the XColor struct, so we use * that to keep track of which colours are available */ XQueryColors(GFX_Display, SDL_XColorMap, all, 256); for(i = 0; i < nwant; i++) { XColor *c; int j; int best = 0; int mindist = 0x7fffffff; int ri = want[i].r; int gi = want[i].g; int bi = want[i].b; for(j = 0; j < 256; j++) { int rj, gj, bj, d2; if(!all[j].flags) continue; /* unavailable colour cell */ rj = all[j].red >> 8; gj = all[j].green >> 8; bj = all[j].blue >> 8; d2 = COLOUR_DIST(ri, gi, bi, rj, gj, bj); if(d2 < mindist) { mindist = d2; best = j; } } if(SDL_XPixels[best]) continue; /* already allocated, waste no more time */ c = all + best; if(XAllocColor(GFX_Display, SDL_XColorMap, c)) { /* got it */ colors[c->pixel].r = c->red >> 8; colors[c->pixel].g = c->green >> 8; colors[c->pixel].b = c->blue >> 8; ++SDL_XPixels[c->pixel]; } else { /* * The colour couldn't be allocated, probably being * owned as a r/w cell by another client. Flag it as * unavailable and try again. The termination of the * loop is guaranteed since at least black and white * are always there. */ c->flags = 0; i--; } } } int X11_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) { int nrej = 0; /* Check to make sure we have a colormap allocated */ if ( SDL_XPixels == NULL ) { return(0); } if ( (this->screen->flags & SDL_HWPALETTE) == SDL_HWPALETTE ) { /* private writable colormap: just set the colours we need */ XColor *xcmap; int i; xcmap = SDL_stack_alloc(XColor, ncolors); if(xcmap == NULL) return 0; for ( i=0; i<ncolors; ++i ) { xcmap[i].pixel = i + firstcolor; xcmap[i].red = (colors[i].r<<8)|colors[i].r; xcmap[i].green = (colors[i].g<<8)|colors[i].g; xcmap[i].blue = (colors[i].b<<8)|colors[i].b; xcmap[i].flags = (DoRed|DoGreen|DoBlue); } XStoreColors(GFX_Display, SDL_XColorMap, xcmap, ncolors); XSync(GFX_Display, False); SDL_stack_free(xcmap); } else { /* * Shared colormap: We only allocate read-only cells, which * increases the likelyhood of colour sharing with other * clients. The pixel values will almost certainly be * different from the requested ones, so the user has to * walk the colormap and see which index got what colour. * * We can work directly with the logical palette since it * has already been set when we get here. */ SDL_Color *want, *reject; unsigned long *freelist; int i; int nfree = 0; int nc = this->screen->format->palette->ncolors; colors = this->screen->format->palette->colors; freelist = SDL_stack_alloc(unsigned long, nc); /* make sure multiple allocations of the same cell are freed */ for(i = 0; i < ncolors; i++) { int pixel = firstcolor + i; while(SDL_XPixels[pixel]) { freelist[nfree++] = pixel; --SDL_XPixels[pixel]; } } XFreeColors(GFX_Display, SDL_XColorMap, freelist, nfree, 0); SDL_stack_free(freelist); want = SDL_stack_alloc(SDL_Color, ncolors); reject = SDL_stack_alloc(SDL_Color, ncolors); SDL_memcpy(want, colors + firstcolor, ncolors * sizeof(SDL_Color)); /* make sure the user isn't fooled by her own wishes (black is safe, always available in the default colormap) */ SDL_memset(colors + firstcolor, 0, ncolors * sizeof(SDL_Color)); /* now try to allocate the colours */ for(i = 0; i < ncolors; i++) { XColor col; col.red = want[i].r << 8; col.green = want[i].g << 8; col.blue = want[i].b << 8; col.flags = DoRed | DoGreen | DoBlue; if(XAllocColor(GFX_Display, SDL_XColorMap, &col)) { /* We got the colour, or at least the nearest the hardware could get. */ colors[col.pixel].r = col.red >> 8; colors[col.pixel].g = col.green >> 8; colors[col.pixel].b = col.blue >> 8; ++SDL_XPixels[col.pixel]; } else { /* * no more free cells, add it to the list * of rejected colours */ reject[nrej++] = want[i]; } } if(nrej) allocate_nearest(this, colors, reject, nrej); SDL_stack_free(reject); SDL_stack_free(want); } return nrej == 0; } int X11_SetGammaRamp(_THIS, Uint16 *ramp) { int i, ncolors; XColor xcmap[256]; /* See if actually setting the gamma is supported */ if ( SDL_Visual->class != DirectColor ) { SDL_SetError("Gamma correction not supported on this visual"); return(-1); } /* Calculate the appropriate palette for the given gamma ramp */ ncolors = SDL_Visual->map_entries; for ( i=0; i<ncolors; ++i ) { Uint8 c = (256 * i / ncolors); xcmap[i].pixel = SDL_MapRGB(this->screen->format, c, c, c); xcmap[i].red = ramp[0*256+c]; xcmap[i].green = ramp[1*256+c]; xcmap[i].blue = ramp[2*256+c]; xcmap[i].flags = (DoRed|DoGreen|DoBlue); } XStoreColors(GFX_Display, SDL_XColorMap, xcmap, ncolors); XSync(GFX_Display, False); return(0); } /* Note: If we are terminated, this could be called in the middle of another SDL video routine -- notably UpdateRects. */ void X11_VideoQuit(_THIS) { /* Shutdown everything that's still up */ /* The event thread should be done, so we can touch SDL_Display */ if ( SDL_Display != NULL ) { /* Flush any delayed updates */ XSync(GFX_Display, False); /* Close the connection with the IM server */ #ifdef X_HAVE_UTF8_STRING if (SDL_IC != NULL) { XUnsetICFocus(SDL_IC); XDestroyIC(SDL_IC); SDL_IC = NULL; } if (SDL_IM != NULL) { XCloseIM(SDL_IM); SDL_IM = NULL; } #endif /* Start shutting down the windows */ X11_DestroyImage(this, this->screen); X11_DestroyWindow(this, this->screen); X11_FreeVideoModes(this); if ( SDL_XColorMap != SDL_DisplayColormap ) { XFreeColormap(SDL_Display, SDL_XColorMap); } if ( SDL_iconcolors ) { unsigned long pixel; Colormap dcmap = DefaultColormap(SDL_Display, SDL_Screen); for(pixel = 0; pixel < 256; ++pixel) { while(SDL_iconcolors[pixel] > 0) { XFreeColors(GFX_Display, dcmap, &pixel, 1, 0); --SDL_iconcolors[pixel]; } } SDL_free(SDL_iconcolors); SDL_iconcolors = NULL; } /* Restore gamma settings if they've changed */ if ( SDL_GetAppState() & SDL_APPACTIVE ) { X11_SwapVidModeGamma(this); } /* Free that blank cursor */ if ( SDL_BlankCursor != NULL ) { this->FreeWMCursor(this, SDL_BlankCursor); SDL_BlankCursor = NULL; } /* Close the X11 graphics connection */ if ( GFX_Display != NULL ) { XCloseDisplay(GFX_Display); GFX_Display = NULL; } /* Close the X11 display connection */ XCloseDisplay(SDL_Display); SDL_Display = NULL; /* Reset the X11 error handlers */ if ( XIO_handler ) { XSetIOErrorHandler(XIO_handler); } if ( X_handler ) { XSetErrorHandler(X_handler); } /* Unload GL library after X11 shuts down */ X11_GL_UnloadLibrary(this); } if ( this->screen && (this->screen->flags & SDL_HWSURFACE) ) { /* Direct screen access, no memory buffer */ this->screen->pixels = NULL; } #if SDL_VIDEO_DRIVER_X11_XME XiGMiscDestroy(); #endif }
lgpl-2.1
brammittendorff/PF_RING
linux-3.16.7-ckt9/arch/parisc/kernel/firmware.c
2101
42879
/* * arch/parisc/kernel/firmware.c - safe PDC access routines * * PDC == Processor Dependent Code * * See http://www.parisc-linux.org/documentation/index.html * for documentation describing the entry points and calling * conventions defined below. * * Copyright 1999 SuSE GmbH Nuernberg (Philipp Rumpf, prumpf@tux.org) * Copyright 1999 The Puffin Group, (Alex deVries, David Kennedy) * Copyright 2003 Grant Grundler <grundler parisc-linux org> * Copyright 2003,2004 Ryan Bradetich <rbrad@parisc-linux.org> * Copyright 2004,2006 Thibaut VARENE <varenet@parisc-linux.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * */ /* I think it would be in everyone's best interest to follow this * guidelines when writing PDC wrappers: * * - the name of the pdc wrapper should match one of the macros * used for the first two arguments * - don't use caps for random parts of the name * - use the static PDC result buffers and "copyout" to structs * supplied by the caller to encapsulate alignment restrictions * - hold pdc_lock while in PDC or using static result buffers * - use __pa() to convert virtual (kernel) pointers to physical * ones. * - the name of the struct used for pdc return values should equal * one of the macros used for the first two arguments to the * corresponding PDC call * - keep the order of arguments * - don't be smart (setting trailing NUL bytes for strings, return * something useful even if the call failed) unless you are sure * it's not going to affect functionality or performance * * Example: * int pdc_cache_info(struct pdc_cache_info *cache_info ) * { * int retval; * * spin_lock_irq(&pdc_lock); * retval = mem_pdc_call(PDC_CACHE,PDC_CACHE_INFO,__pa(cache_info),0); * convert_to_wide(pdc_result); * memcpy(cache_info, pdc_result, sizeof(*cache_info)); * spin_unlock_irq(&pdc_lock); * * return retval; * } * prumpf 991016 */ #include <stdarg.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/string.h> #include <linux/spinlock.h> #include <asm/page.h> #include <asm/pdc.h> #include <asm/pdcpat.h> #include <asm/processor.h> /* for boot_cpu_data */ static DEFINE_SPINLOCK(pdc_lock); extern unsigned long pdc_result[NUM_PDC_RESULT]; extern unsigned long pdc_result2[NUM_PDC_RESULT]; #ifdef CONFIG_64BIT #define WIDE_FIRMWARE 0x1 #define NARROW_FIRMWARE 0x2 /* Firmware needs to be initially set to narrow to determine the * actual firmware width. */ int parisc_narrow_firmware __read_mostly = 1; #endif /* On most currently-supported platforms, IODC I/O calls are 32-bit calls * and MEM_PDC calls are always the same width as the OS. * Some PAT boxes may have 64-bit IODC I/O. * * Ryan Bradetich added the now obsolete CONFIG_PDC_NARROW to allow * 64-bit kernels to run on systems with 32-bit MEM_PDC calls. * This allowed wide kernels to run on Cxxx boxes. * We now detect 32-bit-only PDC and dynamically switch to 32-bit mode * when running a 64-bit kernel on such boxes (e.g. C200 or C360). */ #ifdef CONFIG_64BIT long real64_call(unsigned long function, ...); #endif long real32_call(unsigned long function, ...); #ifdef CONFIG_64BIT # define MEM_PDC (unsigned long)(PAGE0->mem_pdc_hi) << 32 | PAGE0->mem_pdc # define mem_pdc_call(args...) unlikely(parisc_narrow_firmware) ? real32_call(MEM_PDC, args) : real64_call(MEM_PDC, args) #else # define MEM_PDC (unsigned long)PAGE0->mem_pdc # define mem_pdc_call(args...) real32_call(MEM_PDC, args) #endif /** * f_extend - Convert PDC addresses to kernel addresses. * @address: Address returned from PDC. * * This function is used to convert PDC addresses into kernel addresses * when the PDC address size and kernel address size are different. */ static unsigned long f_extend(unsigned long address) { #ifdef CONFIG_64BIT if(unlikely(parisc_narrow_firmware)) { if((address & 0xff000000) == 0xf0000000) return 0xf0f0f0f000000000UL | (u32)address; if((address & 0xf0000000) == 0xf0000000) return 0xffffffff00000000UL | (u32)address; } #endif return address; } /** * convert_to_wide - Convert the return buffer addresses into kernel addresses. * @address: The return buffer from PDC. * * This function is used to convert the return buffer addresses retrieved from PDC * into kernel addresses when the PDC address size and kernel address size are * different. */ static void convert_to_wide(unsigned long *addr) { #ifdef CONFIG_64BIT int i; unsigned int *p = (unsigned int *)addr; if(unlikely(parisc_narrow_firmware)) { for(i = 31; i >= 0; --i) addr[i] = p[i]; } #endif } #ifdef CONFIG_64BIT void set_firmware_width_unlocked(void) { int ret; ret = mem_pdc_call(PDC_MODEL, PDC_MODEL_CAPABILITIES, __pa(pdc_result), 0); convert_to_wide(pdc_result); if (pdc_result[0] != NARROW_FIRMWARE) parisc_narrow_firmware = 0; } /** * set_firmware_width - Determine if the firmware is wide or narrow. * * This function must be called before any pdc_* function that uses the * convert_to_wide function. */ void set_firmware_width(void) { unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); set_firmware_width_unlocked(); spin_unlock_irqrestore(&pdc_lock, flags); } #else void set_firmware_width_unlocked(void) { return; } void set_firmware_width(void) { return; } #endif /*CONFIG_64BIT*/ /** * pdc_emergency_unlock - Unlock the linux pdc lock * * This call unlocks the linux pdc lock in case we need some PDC functions * (like pdc_add_valid) during kernel stack dump. */ void pdc_emergency_unlock(void) { /* Spinlock DEBUG code freaks out if we unconditionally unlock */ if (spin_is_locked(&pdc_lock)) spin_unlock(&pdc_lock); } /** * pdc_add_valid - Verify address can be accessed without causing a HPMC. * @address: Address to be verified. * * This PDC call attempts to read from the specified address and verifies * if the address is valid. * * The return value is PDC_OK (0) in case accessing this address is valid. */ int pdc_add_valid(unsigned long address) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_ADD_VALID, PDC_ADD_VALID_VERIFY, address); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } EXPORT_SYMBOL(pdc_add_valid); /** * pdc_chassis_info - Return chassis information. * @result: The return buffer. * @chassis_info: The memory buffer address. * @len: The size of the memory buffer address. * * An HVERSION dependent call for returning the chassis information. */ int __init pdc_chassis_info(struct pdc_chassis_info *chassis_info, void *led_info, unsigned long len) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); memcpy(&pdc_result, chassis_info, sizeof(*chassis_info)); memcpy(&pdc_result2, led_info, len); retval = mem_pdc_call(PDC_CHASSIS, PDC_RETURN_CHASSIS_INFO, __pa(pdc_result), __pa(pdc_result2), len); memcpy(chassis_info, pdc_result, sizeof(*chassis_info)); memcpy(led_info, pdc_result2, len); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_pat_chassis_send_log - Sends a PDC PAT CHASSIS log message. * @retval: -1 on error, 0 on success. Other value are PDC errors * * Must be correctly formatted or expect system crash */ #ifdef CONFIG_64BIT int pdc_pat_chassis_send_log(unsigned long state, unsigned long data) { int retval = 0; unsigned long flags; if (!is_pdc_pat()) return -1; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_PAT_CHASSIS_LOG, PDC_PAT_CHASSIS_WRITE_LOG, __pa(&state), __pa(&data)); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } #endif /** * pdc_chassis_disp - Updates chassis code * @retval: -1 on error, 0 on success */ int pdc_chassis_disp(unsigned long disp) { int retval = 0; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_CHASSIS, PDC_CHASSIS_DISP, disp); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_chassis_warn - Fetches chassis warnings * @retval: -1 on error, 0 on success */ int pdc_chassis_warn(unsigned long *warn) { int retval = 0; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_CHASSIS, PDC_CHASSIS_WARN, __pa(pdc_result)); *warn = pdc_result[0]; spin_unlock_irqrestore(&pdc_lock, flags); return retval; } int pdc_coproc_cfg_unlocked(struct pdc_coproc_cfg *pdc_coproc_info) { int ret; ret = mem_pdc_call(PDC_COPROC, PDC_COPROC_CFG, __pa(pdc_result)); convert_to_wide(pdc_result); pdc_coproc_info->ccr_functional = pdc_result[0]; pdc_coproc_info->ccr_present = pdc_result[1]; pdc_coproc_info->revision = pdc_result[17]; pdc_coproc_info->model = pdc_result[18]; return ret; } /** * pdc_coproc_cfg - To identify coprocessors attached to the processor. * @pdc_coproc_info: Return buffer address. * * This PDC call returns the presence and status of all the coprocessors * attached to the processor. */ int pdc_coproc_cfg(struct pdc_coproc_cfg *pdc_coproc_info) { int ret; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); ret = pdc_coproc_cfg_unlocked(pdc_coproc_info); spin_unlock_irqrestore(&pdc_lock, flags); return ret; } /** * pdc_iodc_read - Read data from the modules IODC. * @actcnt: The actual number of bytes. * @hpa: The HPA of the module for the iodc read. * @index: The iodc entry point. * @iodc_data: A buffer memory for the iodc options. * @iodc_data_size: Size of the memory buffer. * * This PDC call reads from the IODC of the module specified by the hpa * argument. */ int pdc_iodc_read(unsigned long *actcnt, unsigned long hpa, unsigned int index, void *iodc_data, unsigned int iodc_data_size) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_IODC, PDC_IODC_READ, __pa(pdc_result), hpa, index, __pa(pdc_result2), iodc_data_size); convert_to_wide(pdc_result); *actcnt = pdc_result[0]; memcpy(iodc_data, pdc_result2, iodc_data_size); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } EXPORT_SYMBOL(pdc_iodc_read); /** * pdc_system_map_find_mods - Locate unarchitected modules. * @pdc_mod_info: Return buffer address. * @mod_path: pointer to dev path structure. * @mod_index: fixed address module index. * * To locate and identify modules which reside at fixed I/O addresses, which * do not self-identify via architected bus walks. */ int pdc_system_map_find_mods(struct pdc_system_map_mod_info *pdc_mod_info, struct pdc_module_path *mod_path, long mod_index) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_SYSTEM_MAP, PDC_FIND_MODULE, __pa(pdc_result), __pa(pdc_result2), mod_index); convert_to_wide(pdc_result); memcpy(pdc_mod_info, pdc_result, sizeof(*pdc_mod_info)); memcpy(mod_path, pdc_result2, sizeof(*mod_path)); spin_unlock_irqrestore(&pdc_lock, flags); pdc_mod_info->mod_addr = f_extend(pdc_mod_info->mod_addr); return retval; } /** * pdc_system_map_find_addrs - Retrieve additional address ranges. * @pdc_addr_info: Return buffer address. * @mod_index: Fixed address module index. * @addr_index: Address range index. * * Retrieve additional information about subsequent address ranges for modules * with multiple address ranges. */ int pdc_system_map_find_addrs(struct pdc_system_map_addr_info *pdc_addr_info, long mod_index, long addr_index) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_SYSTEM_MAP, PDC_FIND_ADDRESS, __pa(pdc_result), mod_index, addr_index); convert_to_wide(pdc_result); memcpy(pdc_addr_info, pdc_result, sizeof(*pdc_addr_info)); spin_unlock_irqrestore(&pdc_lock, flags); pdc_addr_info->mod_addr = f_extend(pdc_addr_info->mod_addr); return retval; } /** * pdc_model_info - Return model information about the processor. * @model: The return buffer. * * Returns the version numbers, identifiers, and capabilities from the processor module. */ int pdc_model_info(struct pdc_model *model) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_MODEL, PDC_MODEL_INFO, __pa(pdc_result), 0); convert_to_wide(pdc_result); memcpy(model, pdc_result, sizeof(*model)); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_model_sysmodel - Get the system model name. * @name: A char array of at least 81 characters. * * Get system model name from PDC ROM (e.g. 9000/715 or 9000/778/B160L). * Using OS_ID_HPUX will return the equivalent of the 'modelname' command * on HP/UX. */ int pdc_model_sysmodel(char *name) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_MODEL, PDC_MODEL_SYSMODEL, __pa(pdc_result), OS_ID_HPUX, __pa(name)); convert_to_wide(pdc_result); if (retval == PDC_OK) { name[pdc_result[0]] = '\0'; /* add trailing '\0' */ } else { name[0] = 0; } spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_model_versions - Identify the version number of each processor. * @cpu_id: The return buffer. * @id: The id of the processor to check. * * Returns the version number for each processor component. * * This comment was here before, but I do not know what it means :( -RB * id: 0 = cpu revision, 1 = boot-rom-version */ int pdc_model_versions(unsigned long *versions, int id) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_MODEL, PDC_MODEL_VERSIONS, __pa(pdc_result), id); convert_to_wide(pdc_result); *versions = pdc_result[0]; spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_model_cpuid - Returns the CPU_ID. * @cpu_id: The return buffer. * * Returns the CPU_ID value which uniquely identifies the cpu portion of * the processor module. */ int pdc_model_cpuid(unsigned long *cpu_id) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); pdc_result[0] = 0; /* preset zero (call may not be implemented!) */ retval = mem_pdc_call(PDC_MODEL, PDC_MODEL_CPU_ID, __pa(pdc_result), 0); convert_to_wide(pdc_result); *cpu_id = pdc_result[0]; spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_model_capabilities - Returns the platform capabilities. * @capabilities: The return buffer. * * Returns information about platform support for 32- and/or 64-bit * OSes, IO-PDIR coherency, and virtual aliasing. */ int pdc_model_capabilities(unsigned long *capabilities) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); pdc_result[0] = 0; /* preset zero (call may not be implemented!) */ retval = mem_pdc_call(PDC_MODEL, PDC_MODEL_CAPABILITIES, __pa(pdc_result), 0); convert_to_wide(pdc_result); if (retval == PDC_OK) { *capabilities = pdc_result[0]; } else { *capabilities = PDC_MODEL_OS32; } spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_cache_info - Return cache and TLB information. * @cache_info: The return buffer. * * Returns information about the processor's cache and TLB. */ int pdc_cache_info(struct pdc_cache_info *cache_info) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_CACHE, PDC_CACHE_INFO, __pa(pdc_result), 0); convert_to_wide(pdc_result); memcpy(cache_info, pdc_result, sizeof(*cache_info)); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_spaceid_bits - Return whether Space ID hashing is turned on. * @space_bits: Should be 0, if not, bad mojo! * * Returns information about Space ID hashing. */ int pdc_spaceid_bits(unsigned long *space_bits) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); pdc_result[0] = 0; retval = mem_pdc_call(PDC_CACHE, PDC_CACHE_RET_SPID, __pa(pdc_result), 0); convert_to_wide(pdc_result); *space_bits = pdc_result[0]; spin_unlock_irqrestore(&pdc_lock, flags); return retval; } #ifndef CONFIG_PA20 /** * pdc_btlb_info - Return block TLB information. * @btlb: The return buffer. * * Returns information about the hardware Block TLB. */ int pdc_btlb_info(struct pdc_btlb_info *btlb) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_BLOCK_TLB, PDC_BTLB_INFO, __pa(pdc_result), 0); memcpy(btlb, pdc_result, sizeof(*btlb)); spin_unlock_irqrestore(&pdc_lock, flags); if(retval < 0) { btlb->max_size = 0; } return retval; } /** * pdc_mem_map_hpa - Find fixed module information. * @address: The return buffer * @mod_path: pointer to dev path structure. * * This call was developed for S700 workstations to allow the kernel to find * the I/O devices (Core I/O). In the future (Kittyhawk and beyond) this * call will be replaced (on workstations) by the architected PDC_SYSTEM_MAP * call. * * This call is supported by all existing S700 workstations (up to Gecko). */ int pdc_mem_map_hpa(struct pdc_memory_map *address, struct pdc_module_path *mod_path) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); memcpy(pdc_result2, mod_path, sizeof(*mod_path)); retval = mem_pdc_call(PDC_MEM_MAP, PDC_MEM_MAP_HPA, __pa(pdc_result), __pa(pdc_result2)); memcpy(address, pdc_result, sizeof(*address)); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } #endif /* !CONFIG_PA20 */ /** * pdc_lan_station_id - Get the LAN address. * @lan_addr: The return buffer. * @hpa: The network device HPA. * * Get the LAN station address when it is not directly available from the LAN hardware. */ int pdc_lan_station_id(char *lan_addr, unsigned long hpa) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_LAN_STATION_ID, PDC_LAN_STATION_ID_READ, __pa(pdc_result), hpa); if (retval < 0) { /* FIXME: else read MAC from NVRAM */ memset(lan_addr, 0, PDC_LAN_STATION_ID_SIZE); } else { memcpy(lan_addr, pdc_result, PDC_LAN_STATION_ID_SIZE); } spin_unlock_irqrestore(&pdc_lock, flags); return retval; } EXPORT_SYMBOL(pdc_lan_station_id); /** * pdc_stable_read - Read data from Stable Storage. * @staddr: Stable Storage address to access. * @memaddr: The memory address where Stable Storage data shall be copied. * @count: number of bytes to transfer. count is multiple of 4. * * This PDC call reads from the Stable Storage address supplied in staddr * and copies count bytes to the memory address memaddr. * The call will fail if staddr+count > PDC_STABLE size. */ int pdc_stable_read(unsigned long staddr, void *memaddr, unsigned long count) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_STABLE, PDC_STABLE_READ, staddr, __pa(pdc_result), count); convert_to_wide(pdc_result); memcpy(memaddr, pdc_result, count); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } EXPORT_SYMBOL(pdc_stable_read); /** * pdc_stable_write - Write data to Stable Storage. * @staddr: Stable Storage address to access. * @memaddr: The memory address where Stable Storage data shall be read from. * @count: number of bytes to transfer. count is multiple of 4. * * This PDC call reads count bytes from the supplied memaddr address, * and copies count bytes to the Stable Storage address staddr. * The call will fail if staddr+count > PDC_STABLE size. */ int pdc_stable_write(unsigned long staddr, void *memaddr, unsigned long count) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); memcpy(pdc_result, memaddr, count); convert_to_wide(pdc_result); retval = mem_pdc_call(PDC_STABLE, PDC_STABLE_WRITE, staddr, __pa(pdc_result), count); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } EXPORT_SYMBOL(pdc_stable_write); /** * pdc_stable_get_size - Get Stable Storage size in bytes. * @size: pointer where the size will be stored. * * This PDC call returns the number of bytes in the processor's Stable * Storage, which is the number of contiguous bytes implemented in Stable * Storage starting from staddr=0. size in an unsigned 64-bit integer * which is a multiple of four. */ int pdc_stable_get_size(unsigned long *size) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_STABLE, PDC_STABLE_RETURN_SIZE, __pa(pdc_result)); *size = pdc_result[0]; spin_unlock_irqrestore(&pdc_lock, flags); return retval; } EXPORT_SYMBOL(pdc_stable_get_size); /** * pdc_stable_verify_contents - Checks that Stable Storage contents are valid. * * This PDC call is meant to be used to check the integrity of the current * contents of Stable Storage. */ int pdc_stable_verify_contents(void) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_STABLE, PDC_STABLE_VERIFY_CONTENTS); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } EXPORT_SYMBOL(pdc_stable_verify_contents); /** * pdc_stable_initialize - Sets Stable Storage contents to zero and initialize * the validity indicator. * * This PDC call will erase all contents of Stable Storage. Use with care! */ int pdc_stable_initialize(void) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_STABLE, PDC_STABLE_INITIALIZE); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } EXPORT_SYMBOL(pdc_stable_initialize); /** * pdc_get_initiator - Get the SCSI Interface Card params (SCSI ID, SDTR, SE or LVD) * @hwpath: fully bc.mod style path to the device. * @initiator: the array to return the result into * * Get the SCSI operational parameters from PDC. * Needed since HPUX never used BIOS or symbios card NVRAM. * Most ncr/sym cards won't have an entry and just use whatever * capabilities of the card are (eg Ultra, LVD). But there are * several cases where it's useful: * o set SCSI id for Multi-initiator clusters, * o cable too long (ie SE scsi 10Mhz won't support 6m length), * o bus width exported is less than what the interface chip supports. */ int pdc_get_initiator(struct hardware_path *hwpath, struct pdc_initiator *initiator) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); /* BCJ-XXXX series boxes. E.G. "9000/785/C3000" */ #define IS_SPROCKETS() (strlen(boot_cpu_data.pdc.sys_model_name) == 14 && \ strncmp(boot_cpu_data.pdc.sys_model_name, "9000/785", 8) == 0) retval = mem_pdc_call(PDC_INITIATOR, PDC_GET_INITIATOR, __pa(pdc_result), __pa(hwpath)); if (retval < PDC_OK) goto out; if (pdc_result[0] < 16) { initiator->host_id = pdc_result[0]; } else { initiator->host_id = -1; } /* * Sprockets and Piranha return 20 or 40 (MT/s). Prelude returns * 1, 2, 5 or 10 for 5, 10, 20 or 40 MT/s, respectively */ switch (pdc_result[1]) { case 1: initiator->factor = 50; break; case 2: initiator->factor = 25; break; case 5: initiator->factor = 12; break; case 25: initiator->factor = 10; break; case 20: initiator->factor = 12; break; case 40: initiator->factor = 10; break; default: initiator->factor = -1; break; } if (IS_SPROCKETS()) { initiator->width = pdc_result[4]; initiator->mode = pdc_result[5]; } else { initiator->width = -1; initiator->mode = -1; } out: spin_unlock_irqrestore(&pdc_lock, flags); return (retval >= PDC_OK); } EXPORT_SYMBOL(pdc_get_initiator); /** * pdc_pci_irt_size - Get the number of entries in the interrupt routing table. * @num_entries: The return value. * @hpa: The HPA for the device. * * This PDC function returns the number of entries in the specified cell's * interrupt table. * Similar to PDC_PAT stuff - but added for Forte/Allegro boxes */ int pdc_pci_irt_size(unsigned long *num_entries, unsigned long hpa) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_PCI_INDEX, PDC_PCI_GET_INT_TBL_SIZE, __pa(pdc_result), hpa); convert_to_wide(pdc_result); *num_entries = pdc_result[0]; spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_pci_irt - Get the PCI interrupt routing table. * @num_entries: The number of entries in the table. * @hpa: The Hard Physical Address of the device. * @tbl: * * Get the PCI interrupt routing table for the device at the given HPA. * Similar to PDC_PAT stuff - but added for Forte/Allegro boxes */ int pdc_pci_irt(unsigned long num_entries, unsigned long hpa, void *tbl) { int retval; unsigned long flags; BUG_ON((unsigned long)tbl & 0x7); spin_lock_irqsave(&pdc_lock, flags); pdc_result[0] = num_entries; retval = mem_pdc_call(PDC_PCI_INDEX, PDC_PCI_GET_INT_TBL, __pa(pdc_result), hpa, __pa(tbl)); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } #if 0 /* UNTEST CODE - left here in case someone needs it */ /** * pdc_pci_config_read - read PCI config space. * @hpa token from PDC to indicate which PCI device * @pci_addr configuration space address to read from * * Read PCI Configuration space *before* linux PCI subsystem is running. */ unsigned int pdc_pci_config_read(void *hpa, unsigned long cfg_addr) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); pdc_result[0] = 0; pdc_result[1] = 0; retval = mem_pdc_call(PDC_PCI_INDEX, PDC_PCI_READ_CONFIG, __pa(pdc_result), hpa, cfg_addr&~3UL, 4UL); spin_unlock_irqrestore(&pdc_lock, flags); return retval ? ~0 : (unsigned int) pdc_result[0]; } /** * pdc_pci_config_write - read PCI config space. * @hpa token from PDC to indicate which PCI device * @pci_addr configuration space address to write * @val value we want in the 32-bit register * * Write PCI Configuration space *before* linux PCI subsystem is running. */ void pdc_pci_config_write(void *hpa, unsigned long cfg_addr, unsigned int val) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); pdc_result[0] = 0; retval = mem_pdc_call(PDC_PCI_INDEX, PDC_PCI_WRITE_CONFIG, __pa(pdc_result), hpa, cfg_addr&~3UL, 4UL, (unsigned long) val); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } #endif /* UNTESTED CODE */ /** * pdc_tod_read - Read the Time-Of-Day clock. * @tod: The return buffer: * * Read the Time-Of-Day clock */ int pdc_tod_read(struct pdc_tod *tod) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_TOD, PDC_TOD_READ, __pa(pdc_result), 0); convert_to_wide(pdc_result); memcpy(tod, pdc_result, sizeof(*tod)); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } EXPORT_SYMBOL(pdc_tod_read); /** * pdc_tod_set - Set the Time-Of-Day clock. * @sec: The number of seconds since epoch. * @usec: The number of micro seconds. * * Set the Time-Of-Day clock. */ int pdc_tod_set(unsigned long sec, unsigned long usec) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_TOD, PDC_TOD_WRITE, sec, usec); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } EXPORT_SYMBOL(pdc_tod_set); #ifdef CONFIG_64BIT int pdc_mem_mem_table(struct pdc_memory_table_raddr *r_addr, struct pdc_memory_table *tbl, unsigned long entries) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_MEM, PDC_MEM_TABLE, __pa(pdc_result), __pa(pdc_result2), entries); convert_to_wide(pdc_result); memcpy(r_addr, pdc_result, sizeof(*r_addr)); memcpy(tbl, pdc_result2, entries * sizeof(*tbl)); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } #endif /* CONFIG_64BIT */ /* FIXME: Is this pdc used? I could not find type reference to ftc_bitmap * so I guessed at unsigned long. Someone who knows what this does, can fix * it later. :) */ int pdc_do_firm_test_reset(unsigned long ftc_bitmap) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_BROADCAST_RESET, PDC_DO_FIRM_TEST_RESET, PDC_FIRM_TEST_MAGIC, ftc_bitmap); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /* * pdc_do_reset - Reset the system. * * Reset the system. */ int pdc_do_reset(void) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_BROADCAST_RESET, PDC_DO_RESET); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /* * pdc_soft_power_info - Enable soft power switch. * @power_reg: address of soft power register * * Return the absolute address of the soft power switch register */ int __init pdc_soft_power_info(unsigned long *power_reg) { int retval; unsigned long flags; *power_reg = (unsigned long) (-1); spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_SOFT_POWER, PDC_SOFT_POWER_INFO, __pa(pdc_result), 0); if (retval == PDC_OK) { convert_to_wide(pdc_result); *power_reg = f_extend(pdc_result[0]); } spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /* * pdc_soft_power_button - Control the soft power button behaviour * @sw_control: 0 for hardware control, 1 for software control * * * This PDC function places the soft power button under software or * hardware control. * Under software control the OS may control to when to allow to shut * down the system. Under hardware control pressing the power button * powers off the system immediately. */ int pdc_soft_power_button(int sw_control) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_SOFT_POWER, PDC_SOFT_POWER_ENABLE, __pa(pdc_result), sw_control); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /* * pdc_io_reset - Hack to avoid overlapping range registers of Bridges devices. * Primarily a problem on T600 (which parisc-linux doesn't support) but * who knows what other platform firmware might do with this OS "hook". */ void pdc_io_reset(void) { unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); mem_pdc_call(PDC_IO, PDC_IO_RESET, 0); spin_unlock_irqrestore(&pdc_lock, flags); } /* * pdc_io_reset_devices - Hack to Stop USB controller * * If PDC used the usb controller, the usb controller * is still running and will crash the machines during iommu * setup, because of still running DMA. This PDC call * stops the USB controller. * Normally called after calling pdc_io_reset(). */ void pdc_io_reset_devices(void) { unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); mem_pdc_call(PDC_IO, PDC_IO_RESET_DEVICES, 0); spin_unlock_irqrestore(&pdc_lock, flags); } /* locked by pdc_console_lock */ static int __attribute__((aligned(8))) iodc_retbuf[32]; static char __attribute__((aligned(64))) iodc_dbuf[4096]; /** * pdc_iodc_print - Console print using IODC. * @str: the string to output. * @count: length of str * * Note that only these special chars are architected for console IODC io: * BEL, BS, CR, and LF. Others are passed through. * Since the HP console requires CR+LF to perform a 'newline', we translate * "\n" to "\r\n". */ int pdc_iodc_print(const unsigned char *str, unsigned count) { unsigned int i; unsigned long flags; for (i = 0; i < count;) { switch(str[i]) { case '\n': iodc_dbuf[i+0] = '\r'; iodc_dbuf[i+1] = '\n'; i += 2; goto print; default: iodc_dbuf[i] = str[i]; i++; break; } } print: spin_lock_irqsave(&pdc_lock, flags); real32_call(PAGE0->mem_cons.iodc_io, (unsigned long)PAGE0->mem_cons.hpa, ENTRY_IO_COUT, PAGE0->mem_cons.spa, __pa(PAGE0->mem_cons.dp.layers), __pa(iodc_retbuf), 0, __pa(iodc_dbuf), i, 0); spin_unlock_irqrestore(&pdc_lock, flags); return i; } /** * pdc_iodc_getc - Read a character (non-blocking) from the PDC console. * * Read a character (non-blocking) from the PDC console, returns -1 if * key is not present. */ int pdc_iodc_getc(void) { int ch; int status; unsigned long flags; /* Bail if no console input device. */ if (!PAGE0->mem_kbd.iodc_io) return 0; /* wait for a keyboard (rs232)-input */ spin_lock_irqsave(&pdc_lock, flags); real32_call(PAGE0->mem_kbd.iodc_io, (unsigned long)PAGE0->mem_kbd.hpa, ENTRY_IO_CIN, PAGE0->mem_kbd.spa, __pa(PAGE0->mem_kbd.dp.layers), __pa(iodc_retbuf), 0, __pa(iodc_dbuf), 1, 0); ch = *iodc_dbuf; status = *iodc_retbuf; spin_unlock_irqrestore(&pdc_lock, flags); if (status == 0) return -1; return ch; } int pdc_sti_call(unsigned long func, unsigned long flags, unsigned long inptr, unsigned long outputr, unsigned long glob_cfg) { int retval; unsigned long irqflags; spin_lock_irqsave(&pdc_lock, irqflags); retval = real32_call(func, flags, inptr, outputr, glob_cfg); spin_unlock_irqrestore(&pdc_lock, irqflags); return retval; } EXPORT_SYMBOL(pdc_sti_call); #ifdef CONFIG_64BIT /** * pdc_pat_cell_get_number - Returns the cell number. * @cell_info: The return buffer. * * This PDC call returns the cell number of the cell from which the call * is made. */ int pdc_pat_cell_get_number(struct pdc_pat_cell_num *cell_info) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_PAT_CELL, PDC_PAT_CELL_GET_NUMBER, __pa(pdc_result)); memcpy(cell_info, pdc_result, sizeof(*cell_info)); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_pat_cell_module - Retrieve the cell's module information. * @actcnt: The number of bytes written to mem_addr. * @ploc: The physical location. * @mod: The module index. * @view_type: The view of the address type. * @mem_addr: The return buffer. * * This PDC call returns information about each module attached to the cell * at the specified location. */ int pdc_pat_cell_module(unsigned long *actcnt, unsigned long ploc, unsigned long mod, unsigned long view_type, void *mem_addr) { int retval; unsigned long flags; static struct pdc_pat_cell_mod_maddr_block result __attribute__ ((aligned (8))); spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_PAT_CELL, PDC_PAT_CELL_MODULE, __pa(pdc_result), ploc, mod, view_type, __pa(&result)); if(!retval) { *actcnt = pdc_result[0]; memcpy(mem_addr, &result, *actcnt); } spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_pat_cpu_get_number - Retrieve the cpu number. * @cpu_info: The return buffer. * @hpa: The Hard Physical Address of the CPU. * * Retrieve the cpu number for the cpu at the specified HPA. */ int pdc_pat_cpu_get_number(struct pdc_pat_cpu_num *cpu_info, void *hpa) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_PAT_CPU, PDC_PAT_CPU_GET_NUMBER, __pa(&pdc_result), hpa); memcpy(cpu_info, pdc_result, sizeof(*cpu_info)); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_pat_get_irt_size - Retrieve the number of entries in the cell's interrupt table. * @num_entries: The return value. * @cell_num: The target cell. * * This PDC function returns the number of entries in the specified cell's * interrupt table. */ int pdc_pat_get_irt_size(unsigned long *num_entries, unsigned long cell_num) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_PAT_IO, PDC_PAT_IO_GET_PCI_ROUTING_TABLE_SIZE, __pa(pdc_result), cell_num); *num_entries = pdc_result[0]; spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_pat_get_irt - Retrieve the cell's interrupt table. * @r_addr: The return buffer. * @cell_num: The target cell. * * This PDC function returns the actual interrupt table for the specified cell. */ int pdc_pat_get_irt(void *r_addr, unsigned long cell_num) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_PAT_IO, PDC_PAT_IO_GET_PCI_ROUTING_TABLE, __pa(r_addr), cell_num); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_pat_pd_get_addr_map - Retrieve information about memory address ranges. * @actlen: The return buffer. * @mem_addr: Pointer to the memory buffer. * @count: The number of bytes to read from the buffer. * @offset: The offset with respect to the beginning of the buffer. * */ int pdc_pat_pd_get_addr_map(unsigned long *actual_len, void *mem_addr, unsigned long count, unsigned long offset) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_PAT_PD, PDC_PAT_PD_GET_ADDR_MAP, __pa(pdc_result), __pa(pdc_result2), count, offset); *actual_len = pdc_result[0]; memcpy(mem_addr, pdc_result2, *actual_len); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_pat_io_pci_cfg_read - Read PCI configuration space. * @pci_addr: PCI configuration space address for which the read request is being made. * @pci_size: Size of read in bytes. Valid values are 1, 2, and 4. * @mem_addr: Pointer to return memory buffer. * */ int pdc_pat_io_pci_cfg_read(unsigned long pci_addr, int pci_size, u32 *mem_addr) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_PAT_IO, PDC_PAT_IO_PCI_CONFIG_READ, __pa(pdc_result), pci_addr, pci_size); switch(pci_size) { case 1: *(u8 *) mem_addr = (u8) pdc_result[0]; case 2: *(u16 *)mem_addr = (u16) pdc_result[0]; case 4: *(u32 *)mem_addr = (u32) pdc_result[0]; } spin_unlock_irqrestore(&pdc_lock, flags); return retval; } /** * pdc_pat_io_pci_cfg_write - Retrieve information about memory address ranges. * @pci_addr: PCI configuration space address for which the write request is being made. * @pci_size: Size of write in bytes. Valid values are 1, 2, and 4. * @value: Pointer to 1, 2, or 4 byte value in low order end of argument to be * written to PCI Config space. * */ int pdc_pat_io_pci_cfg_write(unsigned long pci_addr, int pci_size, u32 val) { int retval; unsigned long flags; spin_lock_irqsave(&pdc_lock, flags); retval = mem_pdc_call(PDC_PAT_IO, PDC_PAT_IO_PCI_CONFIG_WRITE, pci_addr, pci_size, val); spin_unlock_irqrestore(&pdc_lock, flags); return retval; } #endif /* CONFIG_64BIT */ /***************** 32-bit real-mode calls ***********/ /* The struct below is used * to overlay real_stack (real2.S), preparing a 32-bit call frame. * real32_call_asm() then uses this stack in narrow real mode */ struct narrow_stack { /* use int, not long which is 64 bits */ unsigned int arg13; unsigned int arg12; unsigned int arg11; unsigned int arg10; unsigned int arg9; unsigned int arg8; unsigned int arg7; unsigned int arg6; unsigned int arg5; unsigned int arg4; unsigned int arg3; unsigned int arg2; unsigned int arg1; unsigned int arg0; unsigned int frame_marker[8]; unsigned int sp; /* in reality, there's nearly 8k of stack after this */ }; long real32_call(unsigned long fn, ...) { va_list args; extern struct narrow_stack real_stack; extern unsigned long real32_call_asm(unsigned int *, unsigned int *, unsigned int); va_start(args, fn); real_stack.arg0 = va_arg(args, unsigned int); real_stack.arg1 = va_arg(args, unsigned int); real_stack.arg2 = va_arg(args, unsigned int); real_stack.arg3 = va_arg(args, unsigned int); real_stack.arg4 = va_arg(args, unsigned int); real_stack.arg5 = va_arg(args, unsigned int); real_stack.arg6 = va_arg(args, unsigned int); real_stack.arg7 = va_arg(args, unsigned int); real_stack.arg8 = va_arg(args, unsigned int); real_stack.arg9 = va_arg(args, unsigned int); real_stack.arg10 = va_arg(args, unsigned int); real_stack.arg11 = va_arg(args, unsigned int); real_stack.arg12 = va_arg(args, unsigned int); real_stack.arg13 = va_arg(args, unsigned int); va_end(args); return real32_call_asm(&real_stack.sp, &real_stack.arg0, fn); } #ifdef CONFIG_64BIT /***************** 64-bit real-mode calls ***********/ struct wide_stack { unsigned long arg0; unsigned long arg1; unsigned long arg2; unsigned long arg3; unsigned long arg4; unsigned long arg5; unsigned long arg6; unsigned long arg7; unsigned long arg8; unsigned long arg9; unsigned long arg10; unsigned long arg11; unsigned long arg12; unsigned long arg13; unsigned long frame_marker[2]; /* rp, previous sp */ unsigned long sp; /* in reality, there's nearly 8k of stack after this */ }; long real64_call(unsigned long fn, ...) { va_list args; extern struct wide_stack real64_stack; extern unsigned long real64_call_asm(unsigned long *, unsigned long *, unsigned long); va_start(args, fn); real64_stack.arg0 = va_arg(args, unsigned long); real64_stack.arg1 = va_arg(args, unsigned long); real64_stack.arg2 = va_arg(args, unsigned long); real64_stack.arg3 = va_arg(args, unsigned long); real64_stack.arg4 = va_arg(args, unsigned long); real64_stack.arg5 = va_arg(args, unsigned long); real64_stack.arg6 = va_arg(args, unsigned long); real64_stack.arg7 = va_arg(args, unsigned long); real64_stack.arg8 = va_arg(args, unsigned long); real64_stack.arg9 = va_arg(args, unsigned long); real64_stack.arg10 = va_arg(args, unsigned long); real64_stack.arg11 = va_arg(args, unsigned long); real64_stack.arg12 = va_arg(args, unsigned long); real64_stack.arg13 = va_arg(args, unsigned long); va_end(args); return real64_call_asm(&real64_stack.sp, &real64_stack.arg0, fn); } #endif /* CONFIG_64BIT */
lgpl-2.1
nadult/mpg123
src/libmpg123/dct64_altivec.c
72
8298
/* dct64_altivec.c: Discrete Cosine Tansform (DCT) for Altivec copyright ?-2006 by the mpg123 project - free software under the terms of the LGPL 2.1 see COPYING and AUTHORS files in distribution or http://mpg123.org initially written by Michael Hipp altivec optimization by tmkk */ /* * Discrete Cosine Tansform (DCT) for subband synthesis * * -funroll-loops (for gcc) will remove the loops for better performance * using loops in the source-code enhances readabillity * * * TODO: write an optimized version for the down-sampling modes * (in these modes the bands 16-31 (2:1) or 8-31 (4:1) are zero */ #include "mpg123lib_intern.h" #ifndef __APPLE__ #include <altivec.h> #endif void dct64_altivec(real *out0,real *out1,real *samples) { ALIGNED(16) real bufs[32]; { register real *b1,*costab; vector unsigned char vinvert,vperm1,vperm2,vperm3,vperm4; vector float v1,v2,v3,v4,v5,v6,v7,v8; vector float vbs1,vbs2,vbs3,vbs4,vbs5,vbs6,vbs7,vbs8; vector float vbs9,vbs10,vbs11,vbs12,vbs13,vbs14,vbs15,vbs16; vector float vzero; b1 = samples; costab = pnts[0]; vzero = vec_xor(vzero,vzero); #ifdef __APPLE__ vinvert = (vector unsigned char)(12,13,14,15,8,9,10,11,4,5,6,7,0,1,2,3); #else vinvert = (vector unsigned char){12,13,14,15,8,9,10,11,4,5,6,7,0,1,2,3}; #endif vperm1 = vec_lvsl(0,b1); vperm2 = vec_perm(vperm1,vperm1,vinvert); v1 = vec_ld(0,b1); v2 = vec_ld(16,b1); v3 = vec_ld(112,b1); v4 = vec_ld(127,b1); v5 = vec_perm(v1,v2,vperm1); /* b1[0,1,2,3] */ v6 = vec_perm(v3,v4,vperm2); /* b1[31,30,29,28] */ vbs1 = vec_add(v5,v6); vbs8 = vec_sub(v5,v6); v1 = vec_ld(32,b1); v4 = vec_ld(96,b1); v5 = vec_perm(v2,v1,vperm1); /* b1[4,5,6,7] */ v6 = vec_perm(v4,v3,vperm2); /* b1[27,26,25,24] */ vbs2 = vec_add(v5,v6); vbs7 = vec_sub(v5,v6); v2 = vec_ld(48,b1); v3 = vec_ld(80,b1); v5 = vec_perm(v1,v2,vperm1); /* b1[8,9,10,11] */ v6 = vec_perm(v3,v4,vperm2); /* b1[23,22,21,20] */ vbs3 = vec_add(v5,v6); vbs6 = vec_sub(v5,v6); v1 = vec_ld(64,b1); v5 = vec_perm(v2,v1,vperm1); /* b1[12,13,14,15] */ v6 = vec_perm(v1,v3,vperm2); /* b1[19,18,17,16] */ vbs4 = vec_add(v5,v6); vbs5 = vec_sub(v5,v6); v1 = vec_ld(0,costab); vbs8 = vec_madd(vbs8,v1,vzero); v2 = vec_ld(16,costab); vbs7 = vec_madd(vbs7,v2,vzero); v3 = vec_ld(32,costab); vbs6 = vec_madd(vbs6,v3,vzero); v4 = vec_ld(48,costab); vbs5 = vec_madd(vbs5,v4,vzero); vbs6 = vec_perm(vbs6,vbs6,vinvert); vbs5 = vec_perm(vbs5,vbs5,vinvert); costab = pnts[1]; v1 = vec_perm(vbs4,vbs4,vinvert); vbs9 = vec_add(vbs1,v1); v3 = vec_sub(vbs1,v1); v5 = vec_ld(0,costab); v2 = vec_perm(vbs3,vbs3,vinvert); vbs10 = vec_add(vbs2,v2); v4 = vec_sub(vbs2,v2); v6 = vec_ld(16,costab); vbs12 = vec_madd(v3,v5,vzero); vbs11 = vec_madd(v4,v6,vzero); v7 = vec_sub(vbs7,vbs6); v8 = vec_sub(vbs8,vbs5); vbs13 = vec_add(vbs5,vbs8); vbs14 = vec_add(vbs6,vbs7); vbs15 = vec_madd(v7,v6,vzero); vbs16 = vec_madd(v8,v5,vzero); costab = pnts[2]; v1 = vec_perm(vbs10,vbs10,vinvert); v5 = vec_perm(vbs14,vbs14,vinvert); vbs1 = vec_add(v1,vbs9); vbs5 = vec_add(v5,vbs13); v2 = vec_sub(vbs9,v1); v6 = vec_sub(vbs13,v5); v3 = vec_ld(0,costab); vbs11 = vec_perm(vbs11,vbs11,vinvert); vbs15 = vec_perm(vbs15,vbs15,vinvert); vbs3 = vec_add(vbs11,vbs12); vbs7 = vec_add(vbs15,vbs16); v4 = vec_sub(vbs12,vbs11); v7 = vec_sub(vbs16,vbs15); vbs2 = vec_madd(v2,v3,vzero); vbs4 = vec_madd(v4,v3,vzero); vbs6 = vec_madd(v6,v3,vzero); vbs8 = vec_madd(v7,v3,vzero); vbs2 = vec_perm(vbs2,vbs2,vinvert); vbs4 = vec_perm(vbs4,vbs4,vinvert); vbs6 = vec_perm(vbs6,vbs6,vinvert); vbs8 = vec_perm(vbs8,vbs8,vinvert); costab = pnts[3]; #ifdef __APPLE__ vperm1 = (vector unsigned char)(0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); vperm2 = (vector unsigned char)(12,13,14,15,8,9,10,11,28,29,30,31,24,25,26,27); vperm3 = (vector unsigned char)(0,1,2,3,4,5,6,7,20,21,22,23,16,17,18,19); #else vperm1 = (vector unsigned char){0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23}; vperm2 = (vector unsigned char){12,13,14,15,8,9,10,11,28,29,30,31,24,25,26,27}; vperm3 = (vector unsigned char){0,1,2,3,4,5,6,7,20,21,22,23,16,17,18,19}; #endif vperm4 = vec_add(vperm3,vec_splat_u8(8)); v1 = vec_ld(0,costab); v2 = vec_splat(v1,0); v3 = vec_splat(v1,1); v1 = vec_mergeh(v2,v3); v2 = vec_perm(vbs1,vbs3,vperm1); v3 = vec_perm(vbs2,vbs4,vperm1); v4 = vec_perm(vbs1,vbs3,vperm2); v5 = vec_perm(vbs2,vbs4,vperm2); v6 = vec_sub(v2,v4); v7 = vec_sub(v3,v5); v2 = vec_add(v2,v4); v3 = vec_add(v3,v5); v4 = vec_madd(v6,v1,vzero); v5 = vec_nmsub(v7,v1,vzero); vbs9 = vec_perm(v2,v4,vperm3); vbs11 = vec_perm(v2,v4,vperm4); vbs10 = vec_perm(v3,v5,vperm3); vbs12 = vec_perm(v3,v5,vperm4); v2 = vec_perm(vbs5,vbs7,vperm1); v3 = vec_perm(vbs6,vbs8,vperm1); v4 = vec_perm(vbs5,vbs7,vperm2); v5 = vec_perm(vbs6,vbs8,vperm2); v6 = vec_sub(v2,v4); v7 = vec_sub(v3,v5); v2 = vec_add(v2,v4); v3 = vec_add(v3,v5); v4 = vec_madd(v6,v1,vzero); v5 = vec_nmsub(v7,v1,vzero); vbs13 = vec_perm(v2,v4,vperm3); vbs15 = vec_perm(v2,v4,vperm4); vbs14 = vec_perm(v3,v5,vperm3); vbs16 = vec_perm(v3,v5,vperm4); costab = pnts[4]; v1 = vec_lde(0,costab); #ifdef __APPLE__ v2 = (vector float)(1.0f,-1.0f,1.0f,-1.0f); #else v2 = (vector float){1.0f,-1.0f,1.0f,-1.0f}; #endif v3 = vec_splat(v1,0); v1 = vec_madd(v2,v3,vzero); v2 = vec_mergeh(vbs9,vbs10); v3 = vec_mergel(vbs9,vbs10); v4 = vec_mergeh(vbs11,vbs12); v5 = vec_mergel(vbs11,vbs12); v6 = vec_mergeh(v2,v3); v7 = vec_mergel(v2,v3); v2 = vec_mergeh(v4,v5); v3 = vec_mergel(v4,v5); v4 = vec_sub(v6,v7); v5 = vec_sub(v2,v3); v6 = vec_add(v6,v7); v7 = vec_add(v2,v3); v2 = vec_madd(v4,v1,vzero); v3 = vec_madd(v5,v1,vzero); vbs1 = vec_mergeh(v6,v2); vbs2 = vec_mergel(v6,v2); vbs3 = vec_mergeh(v7,v3); vbs4 = vec_mergel(v7,v3); v2 = vec_mergeh(vbs13,vbs14); v3 = vec_mergel(vbs13,vbs14); v4 = vec_mergeh(vbs15,vbs16); v5 = vec_mergel(vbs15,vbs16); v6 = vec_mergeh(v2,v3); v7 = vec_mergel(v2,v3); v2 = vec_mergeh(v4,v5); v3 = vec_mergel(v4,v5); v4 = vec_sub(v6,v7); v5 = vec_sub(v2,v3); v6 = vec_add(v6,v7); v7 = vec_add(v2,v3); v2 = vec_madd(v4,v1,vzero); v3 = vec_madd(v5,v1,vzero); vbs5 = vec_mergeh(v6,v2); vbs6 = vec_mergel(v6,v2); vbs7 = vec_mergeh(v7,v3); vbs8 = vec_mergel(v7,v3); vec_st(vbs1,0,bufs); vec_st(vbs2,16,bufs); vec_st(vbs3,32,bufs); vec_st(vbs4,48,bufs); vec_st(vbs5,64,bufs); vec_st(vbs6,80,bufs); vec_st(vbs7,96,bufs); vec_st(vbs8,112,bufs); } { register real *b1; register int i; for(b1=bufs,i=8;i;i--,b1+=4) b1[2] += b1[3]; for(b1=bufs,i=4;i;i--,b1+=8) { b1[4] += b1[6]; b1[6] += b1[5]; b1[5] += b1[7]; } for(b1=bufs,i=2;i;i--,b1+=16) { b1[8] += b1[12]; b1[12] += b1[10]; b1[10] += b1[14]; b1[14] += b1[9]; b1[9] += b1[13]; b1[13] += b1[11]; b1[11] += b1[15]; } } out0[0x10*16] = bufs[0]; out0[0x10*15] = bufs[16+0] + bufs[16+8]; out0[0x10*14] = bufs[8]; out0[0x10*13] = bufs[16+8] + bufs[16+4]; out0[0x10*12] = bufs[4]; out0[0x10*11] = bufs[16+4] + bufs[16+12]; out0[0x10*10] = bufs[12]; out0[0x10* 9] = bufs[16+12] + bufs[16+2]; out0[0x10* 8] = bufs[2]; out0[0x10* 7] = bufs[16+2] + bufs[16+10]; out0[0x10* 6] = bufs[10]; out0[0x10* 5] = bufs[16+10] + bufs[16+6]; out0[0x10* 4] = bufs[6]; out0[0x10* 3] = bufs[16+6] + bufs[16+14]; out0[0x10* 2] = bufs[14]; out0[0x10* 1] = bufs[16+14] + bufs[16+1]; out0[0x10* 0] = bufs[1]; out1[0x10* 0] = bufs[1]; out1[0x10* 1] = bufs[16+1] + bufs[16+9]; out1[0x10* 2] = bufs[9]; out1[0x10* 3] = bufs[16+9] + bufs[16+5]; out1[0x10* 4] = bufs[5]; out1[0x10* 5] = bufs[16+5] + bufs[16+13]; out1[0x10* 6] = bufs[13]; out1[0x10* 7] = bufs[16+13] + bufs[16+3]; out1[0x10* 8] = bufs[3]; out1[0x10* 9] = bufs[16+3] + bufs[16+11]; out1[0x10*10] = bufs[11]; out1[0x10*11] = bufs[16+11] + bufs[16+7]; out1[0x10*12] = bufs[7]; out1[0x10*13] = bufs[16+7] + bufs[16+15]; out1[0x10*14] = bufs[15]; out1[0x10*15] = bufs[16+15]; }
lgpl-2.1
saitoha/SDL1.2-SIXEL
src/audio/nas/SDL_nasaudio.c
81
11244
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org This driver was written by: Erik Inge Bolsø knan@mo.himolde.no */ #include "SDL_config.h" /* Allow access to a raw mixing buffer */ #include <signal.h> #include <unistd.h> #include "SDL_timer.h" #include "SDL_audio.h" #include "../SDL_audiomem.h" #include "../SDL_audio_c.h" #include "../SDL_audiodev_c.h" #include "SDL_nasaudio.h" #ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC #include "SDL_loadso.h" #endif /* The tag name used by artsc audio */ #define NAS_DRIVER_NAME "nas" static struct SDL_PrivateAudioData *this2 = NULL; static void (*NAS_AuCloseServer) (AuServer *); static void (*NAS_AuNextEvent) (AuServer *, AuBool, AuEvent *); static AuBool(*NAS_AuDispatchEvent) (AuServer *, AuEvent *); static AuFlowID(*NAS_AuCreateFlow) (AuServer *, AuStatus *); static void (*NAS_AuStartFlow) (AuServer *, AuFlowID, AuStatus *); static void (*NAS_AuSetElements) (AuServer *, AuFlowID, AuBool, int, AuElement *, AuStatus *); static void (*NAS_AuWriteElement) (AuServer *, AuFlowID, int, AuUint32, AuPointer, AuBool, AuStatus *); static AuServer *(*NAS_AuOpenServer) (_AuConst char *, int, _AuConst char *, int, _AuConst char *, char **); static AuEventHandlerRec *(*NAS_AuRegisterEventHandler) (AuServer *, AuMask, int, AuID, AuEventHandlerCallback, AuPointer); #ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC static const char *nas_library = SDL_AUDIO_DRIVER_NAS_DYNAMIC; static void *nas_handle = NULL; static int load_nas_sym(const char *fn, void **addr) { *addr = SDL_LoadFunction(nas_handle, fn); if (*addr == NULL) { return 0; } return 1; } /* cast funcs to char* first, to please GCC's strict aliasing rules. */ #define SDL_NAS_SYM(x) \ if (!load_nas_sym(#x, (void **) (char *) &NAS_##x)) return -1 #else #define SDL_NAS_SYM(x) NAS_##x = x #endif static int load_nas_syms(void) { SDL_NAS_SYM(AuCloseServer); SDL_NAS_SYM(AuNextEvent); SDL_NAS_SYM(AuDispatchEvent); SDL_NAS_SYM(AuCreateFlow); SDL_NAS_SYM(AuStartFlow); SDL_NAS_SYM(AuSetElements); SDL_NAS_SYM(AuWriteElement); SDL_NAS_SYM(AuOpenServer); SDL_NAS_SYM(AuRegisterEventHandler); return 0; } #undef SDL_NAS_SYM #ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC static void UnloadNASLibrary(void) { if (nas_handle != NULL) { SDL_UnloadObject(nas_handle); nas_handle = NULL; } } static int LoadNASLibrary(void) { int retval = 0; if (nas_handle == NULL) { nas_handle = SDL_LoadObject(nas_library); if (nas_handle == NULL) { /* Copy error string so we can use it in a new SDL_SetError(). */ char *origerr = SDL_GetError(); size_t len = SDL_strlen(origerr) + 1; char *err = (char *) alloca(len); SDL_strlcpy(err, origerr, len); retval = -1; SDL_SetError("NAS: SDL_LoadObject('%s') failed: %s\n", nas_library, err); } else { retval = load_nas_syms(); if (retval < 0) { UnloadNASLibrary(); } } } return retval; } #else static void UnloadNASLibrary(void) { } static int LoadNASLibrary(void) { load_nas_syms(); return 0; } #endif /* SDL_AUDIO_DRIVER_NAS_DYNAMIC */ /* Audio driver functions */ static int NAS_OpenAudio(_THIS, SDL_AudioSpec *spec); static void NAS_WaitAudio(_THIS); static void NAS_PlayAudio(_THIS); static Uint8 *NAS_GetAudioBuf(_THIS); static void NAS_CloseAudio(_THIS); /* Audio driver bootstrap functions */ static int Audio_Available(void) { if (LoadNASLibrary() == 0) { AuServer *aud = NAS_AuOpenServer("", 0, NULL, 0, NULL, NULL); if (!aud) { UnloadNASLibrary(); return 0; } NAS_AuCloseServer(aud); UnloadNASLibrary(); return 1; } return 0; } static void Audio_DeleteDevice(SDL_AudioDevice *device) { UnloadNASLibrary(); SDL_free(device->hidden); SDL_free(device); } static SDL_AudioDevice *Audio_CreateDevice(int devindex) { SDL_AudioDevice *this; if (LoadNASLibrary() < 0) { return NULL; } /* Initialize all variables that we clean on shutdown */ this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); if ( this ) { SDL_memset(this, 0, (sizeof *this)); this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); } if ( (this == NULL) || (this->hidden == NULL) ) { SDL_OutOfMemory(); if ( this ) { SDL_free(this); } return NULL; } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); /* Set the function pointers */ this->OpenAudio = NAS_OpenAudio; this->WaitAudio = NAS_WaitAudio; this->PlayAudio = NAS_PlayAudio; this->GetAudioBuf = NAS_GetAudioBuf; this->CloseAudio = NAS_CloseAudio; this->free = Audio_DeleteDevice; return this; } AudioBootStrap NAS_bootstrap = { NAS_DRIVER_NAME, "Network Audio System", Audio_Available, Audio_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ static void NAS_WaitAudio(_THIS) { while ( this->hidden->buf_free < this->hidden->mixlen ) { AuEvent ev; NAS_AuNextEvent(this->hidden->aud, AuTrue, &ev); NAS_AuDispatchEvent(this->hidden->aud, &ev); } } static void NAS_PlayAudio(_THIS) { while (this->hidden->mixlen > this->hidden->buf_free) { /* We think the buffer is full? Yikes! Ask the server for events, in the hope that some of them is LowWater events telling us more of the buffer is free now than what we think. */ AuEvent ev; NAS_AuNextEvent(this->hidden->aud, AuTrue, &ev); NAS_AuDispatchEvent(this->hidden->aud, &ev); } this->hidden->buf_free -= this->hidden->mixlen; /* Write the audio data */ NAS_AuWriteElement(this->hidden->aud, this->hidden->flow, 0, this->hidden->mixlen, this->hidden->mixbuf, AuFalse, NULL); this->hidden->written += this->hidden->mixlen; #ifdef DEBUG_AUDIO fprintf(stderr, "Wrote %d bytes of audio data\n", this->hidden->mixlen); #endif } static Uint8 *NAS_GetAudioBuf(_THIS) { return(this->hidden->mixbuf); } static void NAS_CloseAudio(_THIS) { if ( this->hidden->mixbuf != NULL ) { SDL_FreeAudioMem(this->hidden->mixbuf); this->hidden->mixbuf = NULL; } if ( this->hidden->aud ) { NAS_AuCloseServer(this->hidden->aud); this->hidden->aud = 0; } } static unsigned char sdlformat_to_auformat(unsigned int fmt) { switch (fmt) { case AUDIO_U8: return AuFormatLinearUnsigned8; case AUDIO_S8: return AuFormatLinearSigned8; case AUDIO_U16LSB: return AuFormatLinearUnsigned16LSB; case AUDIO_U16MSB: return AuFormatLinearUnsigned16MSB; case AUDIO_S16LSB: return AuFormatLinearSigned16LSB; case AUDIO_S16MSB: return AuFormatLinearSigned16MSB; } return AuNone; } static AuBool event_handler(AuServer* aud, AuEvent* ev, AuEventHandlerRec* hnd) { switch (ev->type) { case AuEventTypeElementNotify: { AuElementNotifyEvent* event = (AuElementNotifyEvent *)ev; switch (event->kind) { case AuElementNotifyKindLowWater: if (this2->buf_free >= 0) { this2->really += event->num_bytes; gettimeofday(&this2->last_tv, 0); this2->buf_free += event->num_bytes; } else { this2->buf_free = event->num_bytes; } break; case AuElementNotifyKindState: switch (event->cur_state) { case AuStatePause: if (event->reason != AuReasonUser) { if (this2->buf_free >= 0) { this2->really += event->num_bytes; gettimeofday(&this2->last_tv, 0); this2->buf_free += event->num_bytes; } else { this2->buf_free = event->num_bytes; } } break; } } } } return AuTrue; } static AuDeviceID find_device(_THIS, int nch) { /* These "Au" things are all macros, not functions... */ int i; for (i = 0; i < AuServerNumDevices(this->hidden->aud); i++) { if ((AuDeviceKind(AuServerDevice(this->hidden->aud, i)) == AuComponentKindPhysicalOutput) && AuDeviceNumTracks(AuServerDevice(this->hidden->aud, i)) == nch) { return AuDeviceIdentifier(AuServerDevice(this->hidden->aud, i)); } } return AuNone; } static int NAS_OpenAudio(_THIS, SDL_AudioSpec *spec) { AuElement elms[3]; int buffer_size; Uint16 test_format, format; this->hidden->mixbuf = NULL; /* Try for a closest match on audio format */ format = 0; for ( test_format = SDL_FirstAudioFormat(spec->format); ! format && test_format; ) { format = sdlformat_to_auformat(test_format); if (format == AuNone) { test_format = SDL_NextAudioFormat(); } } if ( format == 0 ) { SDL_SetError("Couldn't find any hardware audio formats"); return(-1); } spec->format = test_format; this->hidden->aud = NAS_AuOpenServer("", 0, NULL, 0, NULL, NULL); if (this->hidden->aud == 0) { SDL_SetError("Couldn't open connection to NAS server"); return (-1); } this->hidden->dev = find_device(this, spec->channels); if ((this->hidden->dev == AuNone) || (!(this->hidden->flow = NAS_AuCreateFlow(this->hidden->aud, NULL)))) { NAS_AuCloseServer(this->hidden->aud); this->hidden->aud = 0; SDL_SetError("Couldn't find a fitting playback device on NAS server"); return (-1); } buffer_size = spec->freq; if (buffer_size < 4096) buffer_size = 4096; if (buffer_size > 32768) buffer_size = 32768; /* So that the buffer won't get unmanageably big. */ /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(spec); this2 = this->hidden; /* These "Au" things without a NAS_ prefix are macros, not functions... */ AuMakeElementImportClient(elms, spec->freq, format, spec->channels, AuTrue, buffer_size, buffer_size / 4, 0, NULL); AuMakeElementExportDevice(elms+1, 0, this->hidden->dev, spec->freq, AuUnlimitedSamples, 0, NULL); NAS_AuSetElements(this->hidden->aud, this->hidden->flow, AuTrue, 2, elms, NULL); NAS_AuRegisterEventHandler(this->hidden->aud, AuEventHandlerIDMask, 0, this->hidden->flow, event_handler, (AuPointer) NULL); NAS_AuStartFlow(this->hidden->aud, this->hidden->flow, NULL); /* Allocate mixing buffer */ this->hidden->mixlen = spec->size; this->hidden->mixbuf = (Uint8 *)SDL_AllocAudioMem(this->hidden->mixlen); if ( this->hidden->mixbuf == NULL ) { return(-1); } SDL_memset(this->hidden->mixbuf, spec->silence, spec->size); /* Get the parent process id (we're the parent of the audio thread) */ this->hidden->parent = getpid(); /* We're ready to rock and roll. :-) */ return(0); }
lgpl-2.1
sexroute/commandergenius
project/jni/intl/src/printf-parse.c
98
21600
/* Formatted output to strings. Copyright (C) 1999-2000, 2002-2003, 2006-2008 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2, 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 Library General Public License for more details. You should have received a copy of the GNU Library 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. */ /* This file can be parametrized with the following macros: CHAR_T The element type of the format string. CHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters in the format string are ASCII. DIRECTIVE Structure denoting a format directive. Depends on CHAR_T. DIRECTIVES Structure denoting the set of format directives of a format string. Depends on CHAR_T. PRINTF_PARSE Function that parses a format string. Depends on CHAR_T. STATIC Set to 'static' to declare the function static. ENABLE_UNISTDIO Set to 1 to enable the unistdio extensions. */ #ifndef PRINTF_PARSE # include <config.h> #endif /* Specification. */ #ifndef PRINTF_PARSE # include "printf-parse.h" #endif /* Default parameters. */ #ifndef PRINTF_PARSE # define PRINTF_PARSE printf_parse # define CHAR_T char # define DIRECTIVE char_directive # define DIRECTIVES char_directives #endif /* Get size_t, NULL. */ #include <stddef.h> /* Get intmax_t. */ #if defined IN_LIBINTL || defined IN_LIBASPRINTF # if HAVE_STDINT_H_WITH_UINTMAX # include <stdint.h> # endif # if HAVE_INTTYPES_H_WITH_UINTMAX # include <inttypes.h> # endif #else # include <stdint.h> #endif /* malloc(), realloc(), free(). */ #include <stdlib.h> /* errno. */ #include <errno.h> /* Checked size_t computations. */ #include "xsize.h" #if CHAR_T_ONLY_ASCII /* c_isascii(). */ # include "c-ctype.h" #endif #ifdef STATIC STATIC #endif int PRINTF_PARSE (const CHAR_T *format, DIRECTIVES *d, arguments *a) { const CHAR_T *cp = format; /* pointer into format */ size_t arg_posn = 0; /* number of regular arguments consumed */ size_t d_allocated; /* allocated elements of d->dir */ size_t a_allocated; /* allocated elements of a->arg */ size_t max_width_length = 0; size_t max_precision_length = 0; d->count = 0; d_allocated = 1; d->dir = (DIRECTIVE *) malloc (d_allocated * sizeof (DIRECTIVE)); if (d->dir == NULL) /* Out of memory. */ goto out_of_memory_1; a->count = 0; a_allocated = 0; a->arg = NULL; #define REGISTER_ARG(_index_,_type_) \ { \ size_t n = (_index_); \ if (n >= a_allocated) \ { \ size_t memory_size; \ argument *memory; \ \ a_allocated = xtimes (a_allocated, 2); \ if (a_allocated <= n) \ a_allocated = xsum (n, 1); \ memory_size = xtimes (a_allocated, sizeof (argument)); \ if (size_overflow_p (memory_size)) \ /* Overflow, would lead to out of memory. */ \ goto out_of_memory; \ memory = (argument *) (a->arg \ ? realloc (a->arg, memory_size) \ : malloc (memory_size)); \ if (memory == NULL) \ /* Out of memory. */ \ goto out_of_memory; \ a->arg = memory; \ } \ while (a->count <= n) \ a->arg[a->count++].type = TYPE_NONE; \ if (a->arg[n].type == TYPE_NONE) \ a->arg[n].type = (_type_); \ else if (a->arg[n].type != (_type_)) \ /* Ambiguous type for positional argument. */ \ goto error; \ } while (*cp != '\0') { CHAR_T c = *cp++; if (c == '%') { size_t arg_index = ARG_NONE; DIRECTIVE *dp = &d->dir[d->count]; /* pointer to next directive */ /* Initialize the next directive. */ dp->dir_start = cp - 1; dp->flags = 0; dp->width_start = NULL; dp->width_end = NULL; dp->width_arg_index = ARG_NONE; dp->precision_start = NULL; dp->precision_end = NULL; dp->precision_arg_index = ARG_NONE; dp->arg_index = ARG_NONE; /* Test for positional argument. */ if (*cp >= '0' && *cp <= '9') { const CHAR_T *np; for (np = cp; *np >= '0' && *np <= '9'; np++) ; if (*np == '$') { size_t n = 0; for (np = cp; *np >= '0' && *np <= '9'; np++) n = xsum (xtimes (n, 10), *np - '0'); if (n == 0) /* Positional argument 0. */ goto error; if (size_overflow_p (n)) /* n too large, would lead to out of memory later. */ goto error; arg_index = n - 1; cp = np + 1; } } /* Read the flags. */ for (;;) { if (*cp == '\'') { dp->flags |= FLAG_GROUP; cp++; } else if (*cp == '-') { dp->flags |= FLAG_LEFT; cp++; } else if (*cp == '+') { dp->flags |= FLAG_SHOWSIGN; cp++; } else if (*cp == ' ') { dp->flags |= FLAG_SPACE; cp++; } else if (*cp == '#') { dp->flags |= FLAG_ALT; cp++; } else if (*cp == '0') { dp->flags |= FLAG_ZERO; cp++; } else break; } /* Parse the field width. */ if (*cp == '*') { dp->width_start = cp; cp++; dp->width_end = cp; if (max_width_length < 1) max_width_length = 1; /* Test for positional argument. */ if (*cp >= '0' && *cp <= '9') { const CHAR_T *np; for (np = cp; *np >= '0' && *np <= '9'; np++) ; if (*np == '$') { size_t n = 0; for (np = cp; *np >= '0' && *np <= '9'; np++) n = xsum (xtimes (n, 10), *np - '0'); if (n == 0) /* Positional argument 0. */ goto error; if (size_overflow_p (n)) /* n too large, would lead to out of memory later. */ goto error; dp->width_arg_index = n - 1; cp = np + 1; } } if (dp->width_arg_index == ARG_NONE) { dp->width_arg_index = arg_posn++; if (dp->width_arg_index == ARG_NONE) /* arg_posn wrapped around. */ goto error; } REGISTER_ARG (dp->width_arg_index, TYPE_INT); } else if (*cp >= '0' && *cp <= '9') { size_t width_length; dp->width_start = cp; for (; *cp >= '0' && *cp <= '9'; cp++) ; dp->width_end = cp; width_length = dp->width_end - dp->width_start; if (max_width_length < width_length) max_width_length = width_length; } /* Parse the precision. */ if (*cp == '.') { cp++; if (*cp == '*') { dp->precision_start = cp - 1; cp++; dp->precision_end = cp; if (max_precision_length < 2) max_precision_length = 2; /* Test for positional argument. */ if (*cp >= '0' && *cp <= '9') { const CHAR_T *np; for (np = cp; *np >= '0' && *np <= '9'; np++) ; if (*np == '$') { size_t n = 0; for (np = cp; *np >= '0' && *np <= '9'; np++) n = xsum (xtimes (n, 10), *np - '0'); if (n == 0) /* Positional argument 0. */ goto error; if (size_overflow_p (n)) /* n too large, would lead to out of memory later. */ goto error; dp->precision_arg_index = n - 1; cp = np + 1; } } if (dp->precision_arg_index == ARG_NONE) { dp->precision_arg_index = arg_posn++; if (dp->precision_arg_index == ARG_NONE) /* arg_posn wrapped around. */ goto error; } REGISTER_ARG (dp->precision_arg_index, TYPE_INT); } else { size_t precision_length; dp->precision_start = cp - 1; for (; *cp >= '0' && *cp <= '9'; cp++) ; dp->precision_end = cp; precision_length = dp->precision_end - dp->precision_start; if (max_precision_length < precision_length) max_precision_length = precision_length; } } { arg_type type; /* Parse argument type/size specifiers. */ { int flags = 0; for (;;) { if (*cp == 'h') { flags |= (1 << (flags & 1)); cp++; } else if (*cp == 'L') { flags |= 4; cp++; } else if (*cp == 'l') { flags += 8; cp++; } else if (*cp == 'j') { if (sizeof (intmax_t) > sizeof (long)) { /* intmax_t = long long */ flags += 16; } else if (sizeof (intmax_t) > sizeof (int)) { /* intmax_t = long */ flags += 8; } cp++; } else if (*cp == 'z' || *cp == 'Z') { /* 'z' is standardized in ISO C 99, but glibc uses 'Z' because the warning facility in gcc-2.95.2 understands only 'Z' (see gcc-2.95.2/gcc/c-common.c:1784). */ if (sizeof (size_t) > sizeof (long)) { /* size_t = long long */ flags += 16; } else if (sizeof (size_t) > sizeof (int)) { /* size_t = long */ flags += 8; } cp++; } else if (*cp == 't') { if (sizeof (ptrdiff_t) > sizeof (long)) { /* ptrdiff_t = long long */ flags += 16; } else if (sizeof (ptrdiff_t) > sizeof (int)) { /* ptrdiff_t = long */ flags += 8; } cp++; } #if defined __APPLE__ && defined __MACH__ /* On MacOS X 10.3, PRIdMAX is defined as "qd". We cannot change it to "lld" because PRIdMAX must also be understood by the system's printf routines. */ else if (*cp == 'q') { if (64 / 8 > sizeof (long)) { /* int64_t = long long */ flags += 16; } else { /* int64_t = long */ flags += 8; } cp++; } #endif #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ /* On native Win32, PRIdMAX is defined as "I64d". We cannot change it to "lld" because PRIdMAX must also be understood by the system's printf routines. */ else if (*cp == 'I' && cp[1] == '6' && cp[2] == '4') { if (64 / 8 > sizeof (long)) { /* __int64 = long long */ flags += 16; } else { /* __int64 = long */ flags += 8; } cp += 3; } #endif else break; } /* Read the conversion character. */ c = *cp++; switch (c) { case 'd': case 'i': #if HAVE_LONG_LONG_INT /* If 'long long' exists and is larger than 'long': */ if (flags >= 16 || (flags & 4)) type = TYPE_LONGLONGINT; else #endif /* If 'long long' exists and is the same as 'long', we parse "lld" into TYPE_LONGINT. */ if (flags >= 8) type = TYPE_LONGINT; else if (flags & 2) type = TYPE_SCHAR; else if (flags & 1) type = TYPE_SHORT; else type = TYPE_INT; break; case 'o': case 'u': case 'x': case 'X': #if HAVE_LONG_LONG_INT /* If 'long long' exists and is larger than 'long': */ if (flags >= 16 || (flags & 4)) type = TYPE_ULONGLONGINT; else #endif /* If 'unsigned long long' exists and is the same as 'unsigned long', we parse "llu" into TYPE_ULONGINT. */ if (flags >= 8) type = TYPE_ULONGINT; else if (flags & 2) type = TYPE_UCHAR; else if (flags & 1) type = TYPE_USHORT; else type = TYPE_UINT; break; case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': case 'a': case 'A': if (flags >= 16 || (flags & 4)) type = TYPE_LONGDOUBLE; else type = TYPE_DOUBLE; break; case 'c': if (flags >= 8) #if HAVE_WINT_T type = TYPE_WIDE_CHAR; #else goto error; #endif else type = TYPE_CHAR; break; #if HAVE_WINT_T case 'C': type = TYPE_WIDE_CHAR; c = 'c'; break; #endif case 's': if (flags >= 8) #if HAVE_WCHAR_T type = TYPE_WIDE_STRING; #else goto error; #endif else type = TYPE_STRING; break; #if HAVE_WCHAR_T case 'S': type = TYPE_WIDE_STRING; c = 's'; break; #endif case 'p': type = TYPE_POINTER; break; case 'n': #if HAVE_LONG_LONG_INT /* If 'long long' exists and is larger than 'long': */ if (flags >= 16 || (flags & 4)) type = TYPE_COUNT_LONGLONGINT_POINTER; else #endif /* If 'long long' exists and is the same as 'long', we parse "lln" into TYPE_COUNT_LONGINT_POINTER. */ if (flags >= 8) type = TYPE_COUNT_LONGINT_POINTER; else if (flags & 2) type = TYPE_COUNT_SCHAR_POINTER; else if (flags & 1) type = TYPE_COUNT_SHORT_POINTER; else type = TYPE_COUNT_INT_POINTER; break; #if ENABLE_UNISTDIO /* The unistdio extensions. */ case 'U': if (flags >= 16) type = TYPE_U32_STRING; else if (flags >= 8) type = TYPE_U16_STRING; else type = TYPE_U8_STRING; break; #endif case '%': type = TYPE_NONE; break; default: /* Unknown conversion character. */ goto error; } } if (type != TYPE_NONE) { dp->arg_index = arg_index; if (dp->arg_index == ARG_NONE) { dp->arg_index = arg_posn++; if (dp->arg_index == ARG_NONE) /* arg_posn wrapped around. */ goto error; } REGISTER_ARG (dp->arg_index, type); } dp->conversion = c; dp->dir_end = cp; } d->count++; if (d->count >= d_allocated) { size_t memory_size; DIRECTIVE *memory; d_allocated = xtimes (d_allocated, 2); memory_size = xtimes (d_allocated, sizeof (DIRECTIVE)); if (size_overflow_p (memory_size)) /* Overflow, would lead to out of memory. */ goto out_of_memory; memory = (DIRECTIVE *) realloc (d->dir, memory_size); if (memory == NULL) /* Out of memory. */ goto out_of_memory; d->dir = memory; } } #if CHAR_T_ONLY_ASCII else if (!c_isascii (c)) { /* Non-ASCII character. Not supported. */ goto error; } #endif } d->dir[d->count].dir_start = cp; d->max_width_length = max_width_length; d->max_precision_length = max_precision_length; return 0; error: if (a->arg) free (a->arg); if (d->dir) free (d->dir); errno = EINVAL; return -1; out_of_memory: if (a->arg) free (a->arg); if (d->dir) free (d->dir); out_of_memory_1: errno = ENOMEM; return -1; } #undef PRINTF_PARSE #undef DIRECTIVES #undef DIRECTIVE #undef CHAR_T_ONLY_ASCII #undef CHAR_T
lgpl-2.1
ogahara/Arduino
libraries/TFT/src/utility/Adafruit_GFX.cpp
173
17185
/* This is the core graphics library for all our displays, providing a common set of graphics primitives (points, lines, circles, etc.). It needs to be paired with a hardware-specific library for each display device we carry (to handle the lower-level functions). Adafruit invests time and resources providing this open source code, please support Adafruit & open-source hardware by purchasing products from Adafruit! Copyright (c) 2013 Adafruit Industries. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Adafruit_GFX.h" #include "glcdfont.c" #ifdef __AVR__ #include <avr/pgmspace.h> #else #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) #endif Adafruit_GFX::Adafruit_GFX(int16_t w, int16_t h) : WIDTH(w), HEIGHT(h) { _width = WIDTH; _height = HEIGHT; rotation = 0; cursor_y = cursor_x = 0; textsize = 1; textcolor = textbgcolor = 0xFFFF; wrap = true; } // draw a circle outline void Adafruit_GFX::drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; drawPixel(x0, y0+r, color); drawPixel(x0, y0-r, color); drawPixel(x0+r, y0, color); drawPixel(x0-r, y0, color); while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; drawPixel(x0 + x, y0 + y, color); drawPixel(x0 - x, y0 + y, color); drawPixel(x0 + x, y0 - y, color); drawPixel(x0 - x, y0 - y, color); drawPixel(x0 + y, y0 + x, color); drawPixel(x0 - y, y0 + x, color); drawPixel(x0 + y, y0 - x, color); drawPixel(x0 - y, y0 - x, color); } } void Adafruit_GFX::drawCircleHelper( int16_t x0, int16_t y0, int16_t r, uint8_t cornername, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x4) { drawPixel(x0 + x, y0 + y, color); drawPixel(x0 + y, y0 + x, color); } if (cornername & 0x2) { drawPixel(x0 + x, y0 - y, color); drawPixel(x0 + y, y0 - x, color); } if (cornername & 0x8) { drawPixel(x0 - y, y0 + x, color); drawPixel(x0 - x, y0 + y, color); } if (cornername & 0x1) { drawPixel(x0 - y, y0 - x, color); drawPixel(x0 - x, y0 - y, color); } } } void Adafruit_GFX::fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color) { drawFastVLine(x0, y0-r, 2*r+1, color); fillCircleHelper(x0, y0, r, 3, 0, color); } // used to do circles and roundrects void Adafruit_GFX::fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, int16_t delta, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x1) { drawFastVLine(x0+x, y0-y, 2*y+1+delta, color); drawFastVLine(x0+y, y0-x, 2*x+1+delta, color); } if (cornername & 0x2) { drawFastVLine(x0-x, y0-y, 2*y+1+delta, color); drawFastVLine(x0-y, y0-x, 2*x+1+delta, color); } } } // Bresenham's algorithm - thx wikpedia void Adafruit_GFX::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color) { int16_t steep = abs(y1 - y0) > abs(x1 - x0); if (steep) { swap(x0, y0); swap(x1, y1); } if (x0 > x1) { swap(x0, x1); swap(y0, y1); } int16_t dx, dy; dx = x1 - x0; dy = abs(y1 - y0); int16_t err = dx / 2; int16_t ystep; if (y0 < y1) { ystep = 1; } else { ystep = -1; } for (; x0<=x1; x0++) { if (steep) { drawPixel(y0, x0, color); } else { drawPixel(x0, y0, color); } err -= dy; if (err < 0) { y0 += ystep; err += dx; } } } // Draw a rectangle void Adafruit_GFX::drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { drawFastHLine(x, y, w, color); drawFastHLine(x, y+h-1, w, color); drawFastVLine(x, y, h, color); drawFastVLine(x+w-1, y, h, color); } void Adafruit_GFX::drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { // Update in subclasses if desired! drawLine(x, y, x, y+h-1, color); } void Adafruit_GFX::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { // Update in subclasses if desired! drawLine(x, y, x+w-1, y, color); } void Adafruit_GFX::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { // Update in subclasses if desired! for (int16_t i=x; i<x+w; i++) { drawFastVLine(i, y, h, color); } } void Adafruit_GFX::fillScreen(uint16_t color) { fillRect(0, 0, _width, _height, color); } // Draw a rounded rectangle void Adafruit_GFX::drawRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint16_t color) { // smarter version drawFastHLine(x+r , y , w-2*r, color); // Top drawFastHLine(x+r , y+h-1, w-2*r, color); // Bottom drawFastVLine(x , y+r , h-2*r, color); // Left drawFastVLine(x+w-1, y+r , h-2*r, color); // Right // draw four corners drawCircleHelper(x+r , y+r , r, 1, color); drawCircleHelper(x+w-r-1, y+r , r, 2, color); drawCircleHelper(x+w-r-1, y+h-r-1, r, 4, color); drawCircleHelper(x+r , y+h-r-1, r, 8, color); } // Fill a rounded rectangle void Adafruit_GFX::fillRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint16_t color) { // smarter version fillRect(x+r, y, w-2*r, h, color); // draw four corners fillCircleHelper(x+w-r-1, y+r, r, 1, h-2*r-1, color); fillCircleHelper(x+r , y+r, r, 2, h-2*r-1, color); } // Draw a triangle void Adafruit_GFX::drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color) { drawLine(x0, y0, x1, y1, color); drawLine(x1, y1, x2, y2, color); drawLine(x2, y2, x0, y0, color); } // Fill a triangle void Adafruit_GFX::fillTriangle ( int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color) { int16_t a, b, y, last; // Sort coordinates by Y order (y2 >= y1 >= y0) if (y0 > y1) { swap(y0, y1); swap(x0, x1); } if (y1 > y2) { swap(y2, y1); swap(x2, x1); } if (y0 > y1) { swap(y0, y1); swap(x0, x1); } if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing a = b = x0; if(x1 < a) a = x1; else if(x1 > b) b = x1; if(x2 < a) a = x2; else if(x2 > b) b = x2; drawFastHLine(a, y0, b-a+1, color); return; } int16_t dx01 = x1 - x0, dy01 = y1 - y0, dx02 = x2 - x0, dy02 = y2 - y0, dx12 = x2 - x1, dy12 = y2 - y1, sa = 0, sb = 0; // For upper part of triangle, find scanline crossings for segments // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 // is included here (and second loop will be skipped, avoiding a /0 // error there), otherwise scanline y1 is skipped here and handled // in the second loop...which also avoids a /0 error here if y0=y1 // (flat-topped triangle). if(y1 == y2) last = y1; // Include y1 scanline else last = y1-1; // Skip it for(y=y0; y<=last; y++) { a = x0 + sa / dy01; b = x0 + sb / dy02; sa += dx01; sb += dx02; /* longhand: a = x0 + (x1 - x0) * (y - y0) / (y1 - y0); b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); */ if(a > b) swap(a,b); drawFastHLine(a, y, b-a+1, color); } // For lower part of triangle, find scanline crossings for segments // 0-2 and 1-2. This loop is skipped if y1=y2. sa = dx12 * (y - y1); sb = dx02 * (y - y0); for(; y<=y2; y++) { a = x1 + sa / dy12; b = x0 + sb / dy02; sa += dx12; sb += dx02; /* longhand: a = x1 + (x2 - x1) * (y - y1) / (y2 - y1); b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); */ if(a > b) swap(a,b); drawFastHLine(a, y, b-a+1, color); } } void Adafruit_GFX::drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color) { int16_t i, j, byteWidth = (w + 7) / 8; for(j=0; j<h; j++) { for(i=0; i<w; i++ ) { if(pgm_read_byte(bitmap + j * byteWidth + i / 8) & (128 >> (i & 7))) { drawPixel(x+i, y+j, color); } } } } #if ARDUINO >= 100 size_t Adafruit_GFX::write(uint8_t c) { #else void Adafruit_GFX::write(uint8_t c) { #endif if (c == '\n') { cursor_y += textsize*8; cursor_x = 0; } else if (c == '\r') { // skip em } else { drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); cursor_x += textsize*6; if (wrap && (cursor_x > (_width - textsize*6))) { cursor_y += textsize*8; cursor_x = 0; } } #if ARDUINO >= 100 return 1; #endif } // draw a character void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color, uint16_t bg, uint8_t size) { if((x >= _width) || // Clip right (y >= _height) || // Clip bottom ((x + 6 * size - 1) < 0) || // Clip left ((y + 8 * size - 1) < 0)) // Clip top return; for (int8_t i=0; i<6; i++ ) { uint8_t line; if (i == 5) line = 0x0; else line = pgm_read_byte(font+(c*5)+i); for (int8_t j = 0; j<8; j++) { if (line & 0x1) { if (size == 1) // default size drawPixel(x+i, y+j, color); else { // big size fillRect(x+(i*size), y+(j*size), size, size, color); } } else if (bg != color) { if (size == 1) // default size drawPixel(x+i, y+j, bg); else { // big size fillRect(x+i*size, y+j*size, size, size, bg); } } line >>= 1; } } } void Adafruit_GFX::setCursor(int16_t x, int16_t y) { cursor_x = x; cursor_y = y; } void Adafruit_GFX::setTextSize(uint8_t s) { textsize = (s > 0) ? s : 1; } void Adafruit_GFX::setTextColor(uint16_t c) { textcolor = c; textbgcolor = c; // for 'transparent' background, we'll set the bg // to the same as fg instead of using a flag } void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) { textcolor = c; textbgcolor = b; } void Adafruit_GFX::setTextWrap(boolean w) { wrap = w; } uint8_t Adafruit_GFX::getRotation(void) { return rotation; } void Adafruit_GFX::setRotation(uint8_t x) { rotation = (x & 3); switch (x) { case 0: case 2: _width = WIDTH; _height = HEIGHT; break; case 1: case 3: _width = HEIGHT; _height = WIDTH; break; } } // return the size of the display (per current rotation) int16_t Adafruit_GFX::width(void) { return _width; } int16_t Adafruit_GFX::height(void) { return _height; } void Adafruit_GFX::invertDisplay(boolean i) { // Do nothing, must be subclassed if supported } uint16_t Adafruit_GFX::newColor(uint8_t r, uint8_t g, uint8_t b) { return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); } void Adafruit_GFX::background(uint8_t red, uint8_t green, uint8_t blue) { background(newColor(red, green, blue)); } void Adafruit_GFX::background(color c) { fillScreen(c); } void Adafruit_GFX::stroke(uint8_t red, uint8_t green, uint8_t blue) { stroke(newColor(red, green, blue)); } void Adafruit_GFX::stroke(color c) { useStroke = true; strokeColor = c; setTextColor(c); } void Adafruit_GFX::noStroke() { useStroke = false; } void Adafruit_GFX::noFill() { useFill = false; } void Adafruit_GFX::fill(uint8_t red, uint8_t green, uint8_t blue) { fill(newColor(red, green, blue)); } void Adafruit_GFX::fill(color c) { useFill = true; fillColor = c; } void Adafruit_GFX::text(const char * text, int16_t x, int16_t y) { if (!useStroke) return; setTextWrap(false); setTextColor(strokeColor); setCursor(x, y); print(text); } void Adafruit_GFX::textWrap(const char * text, int16_t x, int16_t y) { if (!useStroke) return; setTextWrap(true); setTextColor(strokeColor); setCursor(x, y); print(text); } void Adafruit_GFX::textSize(uint8_t size) { setTextSize(size); } void Adafruit_GFX::point(int16_t x, int16_t y) { if (!useStroke) return; drawPixel(x, y, strokeColor); } void Adafruit_GFX::line(int16_t x1, int16_t y1, int16_t x2, int16_t y2) { if (!useStroke) return; if (x1 == x2) { if (y1 < y2) drawFastVLine(x1, y1, y2 - y1, strokeColor); else drawFastVLine(x1, y2, y1 - y2, strokeColor); } else if (y1 == y2) { if (x1 < x2) drawFastHLine(x1, y1, x2 - x1, strokeColor); else drawFastHLine(x2, y1, x1 - x2, strokeColor); } else { drawLine(x1, y1, x2, y2, strokeColor); } } void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height) { if (useFill) { fillRect(x, y, width, height, fillColor); } if (useStroke) { drawRect(x, y, width, height, strokeColor); } } void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius) { if (radius == 0) { rect(x, y, width, height); } if (useFill) { fillRoundRect(x, y, width, height, radius, fillColor); } if (useStroke) { drawRoundRect(x, y, width, height, radius, strokeColor); } } void Adafruit_GFX::circle(int16_t x, int16_t y, int16_t r) { if (r == 0) return; if (useFill) { fillCircle(x, y, r, fillColor); } if (useStroke) { drawCircle(x, y, r, strokeColor); } } void Adafruit_GFX::triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3) { if (useFill) { fillTriangle(x1, y1, x2, y2, x3, y3, fillColor); } if (useStroke) { drawTriangle(x1, y1, x2, y2, x3, y3, strokeColor); } } #if defined(__SD_H__) // Arduino SD library #define BUFFPIXEL 20 void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { int w, h, row, col; uint8_t r, g, b; uint32_t pos = 0; uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer // Crop area to be loaded w = img._bmpWidth; h = img._bmpHeight; if((x+w-1) >= width()) w = width() - x; if((y+h-1) >= height()) h = height() - y; /* // Set TFT address window to clipped image bounds setAddrWindow(x, y, x+w-1, y+h-1); */ for (row=0; row<h; row++) { // For each scanline... // Seek to start of scan line. It might seem labor- // intensive to be doing this on every line, but this // method covers a lot of gritty details like cropping // and scanline padding. Also, the seek only takes // place if the file position actually needs to change // (avoids a lot of cluster math in SD library). if(img._flip) // Bitmap is stored bottom-to-top order (normal BMP) pos = img._bmpImageoffset + (img._bmpHeight - 1 - row) * img._rowSize; else // Bitmap is stored top-to-bottom pos = img._bmpImageoffset + row * img._rowSize; if(img._bmpFile.position() != pos) { // Need seek? img._bmpFile.seek(pos); buffidx = sizeof(sdbuffer); // Force buffer reload } for (col=0; col<w; col++) { // For each pixel... // Time to read more pixel data? if (buffidx >= sizeof(sdbuffer)) { // Indeed img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); buffidx = 0; // Set index to beginning } // Convert pixel from BMP to TFT format, push to display b = sdbuffer[buffidx++]; g = sdbuffer[buffidx++]; r = sdbuffer[buffidx++]; //pushColor(tft.Color565(r,g,b)); drawPixel(x + col, y + row, newColor(r, g, b)); } // end pixel } // end scanline } #endif
lgpl-2.1
stanxii/wr1004sjl
linux-3.4.6/drivers/media/video/adp1653.c
4784
12811
/* * drivers/media/video/adp1653.c * * Copyright (C) 2008--2011 Nokia Corporation * * Contact: Sakari Ailus <sakari.ailus@maxwell.research.nokia.com> * * Contributors: * Sakari Ailus <sakari.ailus@maxwell.research.nokia.com> * Tuukka Toivonen <tuukkat76@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * TODO: * - fault interrupt handling * - hardware strobe * - power doesn't need to be ON if all lights are off * */ #include <linux/delay.h> #include <linux/module.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/version.h> #include <media/adp1653.h> #include <media/v4l2-device.h> #define TIMEOUT_MAX 820000 #define TIMEOUT_STEP 54600 #define TIMEOUT_MIN (TIMEOUT_MAX - ADP1653_REG_CONFIG_TMR_SET_MAX \ * TIMEOUT_STEP) #define TIMEOUT_US_TO_CODE(t) ((TIMEOUT_MAX + (TIMEOUT_STEP / 2) - (t)) \ / TIMEOUT_STEP) #define TIMEOUT_CODE_TO_US(c) (TIMEOUT_MAX - (c) * TIMEOUT_STEP) /* Write values into ADP1653 registers. */ static int adp1653_update_hw(struct adp1653_flash *flash) { struct i2c_client *client = v4l2_get_subdevdata(&flash->subdev); u8 out_sel; u8 config = 0; int rval; out_sel = ADP1653_INDICATOR_INTENSITY_uA_TO_REG( flash->indicator_intensity->val) << ADP1653_REG_OUT_SEL_ILED_SHIFT; switch (flash->led_mode->val) { case V4L2_FLASH_LED_MODE_NONE: break; case V4L2_FLASH_LED_MODE_FLASH: /* Flash mode, light on with strobe, duration from timer */ config = ADP1653_REG_CONFIG_TMR_CFG; config |= TIMEOUT_US_TO_CODE(flash->flash_timeout->val) << ADP1653_REG_CONFIG_TMR_SET_SHIFT; break; case V4L2_FLASH_LED_MODE_TORCH: /* Torch mode, light immediately on, duration indefinite */ out_sel |= ADP1653_FLASH_INTENSITY_mA_TO_REG( flash->torch_intensity->val) << ADP1653_REG_OUT_SEL_HPLED_SHIFT; break; } rval = i2c_smbus_write_byte_data(client, ADP1653_REG_OUT_SEL, out_sel); if (rval < 0) return rval; rval = i2c_smbus_write_byte_data(client, ADP1653_REG_CONFIG, config); if (rval < 0) return rval; return 0; } static int adp1653_get_fault(struct adp1653_flash *flash) { struct i2c_client *client = v4l2_get_subdevdata(&flash->subdev); int fault; int rval; fault = i2c_smbus_read_byte_data(client, ADP1653_REG_FAULT); if (IS_ERR_VALUE(fault)) return fault; flash->fault |= fault; if (!flash->fault) return 0; /* Clear faults. */ rval = i2c_smbus_write_byte_data(client, ADP1653_REG_OUT_SEL, 0); if (IS_ERR_VALUE(rval)) return rval; flash->led_mode->val = V4L2_FLASH_LED_MODE_NONE; rval = adp1653_update_hw(flash); if (IS_ERR_VALUE(rval)) return rval; return flash->fault; } static int adp1653_strobe(struct adp1653_flash *flash, int enable) { struct i2c_client *client = v4l2_get_subdevdata(&flash->subdev); u8 out_sel = ADP1653_INDICATOR_INTENSITY_uA_TO_REG( flash->indicator_intensity->val) << ADP1653_REG_OUT_SEL_ILED_SHIFT; int rval; if (flash->led_mode->val != V4L2_FLASH_LED_MODE_FLASH) return -EBUSY; if (!enable) return i2c_smbus_write_byte_data(client, ADP1653_REG_OUT_SEL, out_sel); out_sel |= ADP1653_FLASH_INTENSITY_mA_TO_REG( flash->flash_intensity->val) << ADP1653_REG_OUT_SEL_HPLED_SHIFT; rval = i2c_smbus_write_byte_data(client, ADP1653_REG_OUT_SEL, out_sel); if (rval) return rval; /* Software strobe using i2c */ rval = i2c_smbus_write_byte_data(client, ADP1653_REG_SW_STROBE, ADP1653_REG_SW_STROBE_SW_STROBE); if (rval) return rval; return i2c_smbus_write_byte_data(client, ADP1653_REG_SW_STROBE, 0); } /* -------------------------------------------------------------------------- * V4L2 controls */ static int adp1653_get_ctrl(struct v4l2_ctrl *ctrl) { struct adp1653_flash *flash = container_of(ctrl->handler, struct adp1653_flash, ctrls); int rval; rval = adp1653_get_fault(flash); if (IS_ERR_VALUE(rval)) return rval; ctrl->cur.val = 0; if (flash->fault & ADP1653_REG_FAULT_FLT_SCP) ctrl->cur.val |= V4L2_FLASH_FAULT_SHORT_CIRCUIT; if (flash->fault & ADP1653_REG_FAULT_FLT_OT) ctrl->cur.val |= V4L2_FLASH_FAULT_OVER_TEMPERATURE; if (flash->fault & ADP1653_REG_FAULT_FLT_TMR) ctrl->cur.val |= V4L2_FLASH_FAULT_TIMEOUT; if (flash->fault & ADP1653_REG_FAULT_FLT_OV) ctrl->cur.val |= V4L2_FLASH_FAULT_OVER_VOLTAGE; flash->fault = 0; return 0; } static int adp1653_set_ctrl(struct v4l2_ctrl *ctrl) { struct adp1653_flash *flash = container_of(ctrl->handler, struct adp1653_flash, ctrls); int rval; rval = adp1653_get_fault(flash); if (IS_ERR_VALUE(rval)) return rval; if ((rval & (ADP1653_REG_FAULT_FLT_SCP | ADP1653_REG_FAULT_FLT_OT | ADP1653_REG_FAULT_FLT_OV)) && (ctrl->id == V4L2_CID_FLASH_STROBE || ctrl->id == V4L2_CID_FLASH_TORCH_INTENSITY || ctrl->id == V4L2_CID_FLASH_LED_MODE)) return -EBUSY; switch (ctrl->id) { case V4L2_CID_FLASH_STROBE: return adp1653_strobe(flash, 1); case V4L2_CID_FLASH_STROBE_STOP: return adp1653_strobe(flash, 0); } return adp1653_update_hw(flash); } static const struct v4l2_ctrl_ops adp1653_ctrl_ops = { .g_volatile_ctrl = adp1653_get_ctrl, .s_ctrl = adp1653_set_ctrl, }; static int adp1653_init_controls(struct adp1653_flash *flash) { struct v4l2_ctrl *fault; v4l2_ctrl_handler_init(&flash->ctrls, 9); flash->led_mode = v4l2_ctrl_new_std_menu(&flash->ctrls, &adp1653_ctrl_ops, V4L2_CID_FLASH_LED_MODE, V4L2_FLASH_LED_MODE_TORCH, ~0x7, 0); v4l2_ctrl_new_std_menu(&flash->ctrls, &adp1653_ctrl_ops, V4L2_CID_FLASH_STROBE_SOURCE, V4L2_FLASH_STROBE_SOURCE_SOFTWARE, ~0x1, 0); v4l2_ctrl_new_std(&flash->ctrls, &adp1653_ctrl_ops, V4L2_CID_FLASH_STROBE, 0, 0, 0, 0); v4l2_ctrl_new_std(&flash->ctrls, &adp1653_ctrl_ops, V4L2_CID_FLASH_STROBE_STOP, 0, 0, 0, 0); flash->flash_timeout = v4l2_ctrl_new_std(&flash->ctrls, &adp1653_ctrl_ops, V4L2_CID_FLASH_TIMEOUT, TIMEOUT_MIN, flash->platform_data->max_flash_timeout, TIMEOUT_STEP, flash->platform_data->max_flash_timeout); flash->flash_intensity = v4l2_ctrl_new_std(&flash->ctrls, &adp1653_ctrl_ops, V4L2_CID_FLASH_INTENSITY, ADP1653_FLASH_INTENSITY_MIN, flash->platform_data->max_flash_intensity, 1, flash->platform_data->max_flash_intensity); flash->torch_intensity = v4l2_ctrl_new_std(&flash->ctrls, &adp1653_ctrl_ops, V4L2_CID_FLASH_TORCH_INTENSITY, ADP1653_TORCH_INTENSITY_MIN, flash->platform_data->max_torch_intensity, ADP1653_FLASH_INTENSITY_STEP, flash->platform_data->max_torch_intensity); flash->indicator_intensity = v4l2_ctrl_new_std(&flash->ctrls, &adp1653_ctrl_ops, V4L2_CID_FLASH_INDICATOR_INTENSITY, ADP1653_INDICATOR_INTENSITY_MIN, flash->platform_data->max_indicator_intensity, ADP1653_INDICATOR_INTENSITY_STEP, ADP1653_INDICATOR_INTENSITY_MIN); fault = v4l2_ctrl_new_std(&flash->ctrls, &adp1653_ctrl_ops, V4L2_CID_FLASH_FAULT, 0, V4L2_FLASH_FAULT_OVER_VOLTAGE | V4L2_FLASH_FAULT_OVER_TEMPERATURE | V4L2_FLASH_FAULT_SHORT_CIRCUIT, 0, 0); if (flash->ctrls.error) return flash->ctrls.error; fault->flags |= V4L2_CTRL_FLAG_VOLATILE; flash->subdev.ctrl_handler = &flash->ctrls; return 0; } /* -------------------------------------------------------------------------- * V4L2 subdev operations */ static int adp1653_init_device(struct adp1653_flash *flash) { struct i2c_client *client = v4l2_get_subdevdata(&flash->subdev); int rval; /* Clear FAULT register by writing zero to OUT_SEL */ rval = i2c_smbus_write_byte_data(client, ADP1653_REG_OUT_SEL, 0); if (rval < 0) { dev_err(&client->dev, "failed writing fault register\n"); return -EIO; } mutex_lock(&flash->ctrls.lock); /* Reset faults before reading new ones. */ flash->fault = 0; rval = adp1653_get_fault(flash); mutex_unlock(&flash->ctrls.lock); if (rval > 0) { dev_err(&client->dev, "faults detected: 0x%1.1x\n", rval); return -EIO; } mutex_lock(&flash->ctrls.lock); rval = adp1653_update_hw(flash); mutex_unlock(&flash->ctrls.lock); if (rval) { dev_err(&client->dev, "adp1653_update_hw failed at %s\n", __func__); return -EIO; } return 0; } static int __adp1653_set_power(struct adp1653_flash *flash, int on) { int ret; ret = flash->platform_data->power(&flash->subdev, on); if (ret < 0) return ret; if (!on) return 0; ret = adp1653_init_device(flash); if (ret < 0) flash->platform_data->power(&flash->subdev, 0); return ret; } static int adp1653_set_power(struct v4l2_subdev *subdev, int on) { struct adp1653_flash *flash = to_adp1653_flash(subdev); int ret = 0; mutex_lock(&flash->power_lock); /* If the power count is modified from 0 to != 0 or from != 0 to 0, * update the power state. */ if (flash->power_count == !on) { ret = __adp1653_set_power(flash, !!on); if (ret < 0) goto done; } /* Update the power count. */ flash->power_count += on ? 1 : -1; WARN_ON(flash->power_count < 0); done: mutex_unlock(&flash->power_lock); return ret; } static int adp1653_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { return adp1653_set_power(sd, 1); } static int adp1653_close(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { return adp1653_set_power(sd, 0); } static const struct v4l2_subdev_core_ops adp1653_core_ops = { .s_power = adp1653_set_power, }; static const struct v4l2_subdev_ops adp1653_ops = { .core = &adp1653_core_ops, }; static const struct v4l2_subdev_internal_ops adp1653_internal_ops = { .open = adp1653_open, .close = adp1653_close, }; /* -------------------------------------------------------------------------- * I2C driver */ #ifdef CONFIG_PM static int adp1653_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct adp1653_flash *flash = to_adp1653_flash(subdev); if (!flash->power_count) return 0; return __adp1653_set_power(flash, 0); } static int adp1653_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct adp1653_flash *flash = to_adp1653_flash(subdev); if (!flash->power_count) return 0; return __adp1653_set_power(flash, 1); } #else #define adp1653_suspend NULL #define adp1653_resume NULL #endif /* CONFIG_PM */ static int adp1653_probe(struct i2c_client *client, const struct i2c_device_id *devid) { struct adp1653_flash *flash; int ret; /* we couldn't work without platform data */ if (client->dev.platform_data == NULL) return -ENODEV; flash = kzalloc(sizeof(*flash), GFP_KERNEL); if (flash == NULL) return -ENOMEM; flash->platform_data = client->dev.platform_data; mutex_init(&flash->power_lock); v4l2_i2c_subdev_init(&flash->subdev, client, &adp1653_ops); flash->subdev.internal_ops = &adp1653_internal_ops; flash->subdev.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; ret = adp1653_init_controls(flash); if (ret) goto free_and_quit; ret = media_entity_init(&flash->subdev.entity, 0, NULL, 0); if (ret < 0) goto free_and_quit; flash->subdev.entity.type = MEDIA_ENT_T_V4L2_SUBDEV_FLASH; return 0; free_and_quit: v4l2_ctrl_handler_free(&flash->ctrls); kfree(flash); return ret; } static int __exit adp1653_remove(struct i2c_client *client) { struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct adp1653_flash *flash = to_adp1653_flash(subdev); v4l2_device_unregister_subdev(&flash->subdev); v4l2_ctrl_handler_free(&flash->ctrls); media_entity_cleanup(&flash->subdev.entity); kfree(flash); return 0; } static const struct i2c_device_id adp1653_id_table[] = { { ADP1653_NAME, 0 }, { } }; MODULE_DEVICE_TABLE(i2c, adp1653_id_table); static struct dev_pm_ops adp1653_pm_ops = { .suspend = adp1653_suspend, .resume = adp1653_resume, }; static struct i2c_driver adp1653_i2c_driver = { .driver = { .name = ADP1653_NAME, .pm = &adp1653_pm_ops, }, .probe = adp1653_probe, .remove = __exit_p(adp1653_remove), .id_table = adp1653_id_table, }; module_i2c_driver(adp1653_i2c_driver); MODULE_AUTHOR("Sakari Ailus <sakari.ailus@nokia.com>"); MODULE_DESCRIPTION("Analog Devices ADP1653 LED flash driver"); MODULE_LICENSE("GPL");
lgpl-2.1
chuncky/test01
linux-2.6.35.4/arch/arm/mach-mx3/mach-mx31_3ds.c
699
11304
/* * Copyright 2008 Freescale Semiconductor, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/delay.h> #include <linux/types.h> #include <linux/init.h> #include <linux/clk.h> #include <linux/irq.h> #include <linux/gpio.h> #include <linux/smsc911x.h> #include <linux/platform_device.h> #include <linux/mfd/mc13783.h> #include <linux/spi/spi.h> #include <linux/regulator/machine.h> #include <linux/fsl_devices.h> #include <linux/input/matrix_keypad.h> #include <mach/hardware.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/time.h> #include <asm/memory.h> #include <asm/mach/map.h> #include <mach/common.h> #include <mach/board-mx31_3ds.h> #include <mach/imx-uart.h> #include <mach/iomux-mx3.h> #include <mach/mxc_nand.h> #include <mach/spi.h> #include "devices.h" /*! * @file mx31_3ds.c * * @brief This file contains the board-specific initialization routines. * * @ingroup System */ static int mx31_3ds_pins[] = { /* UART1 */ MX31_PIN_CTS1__CTS1, MX31_PIN_RTS1__RTS1, MX31_PIN_TXD1__TXD1, MX31_PIN_RXD1__RXD1, IOMUX_MODE(MX31_PIN_GPIO1_1, IOMUX_CONFIG_GPIO), /* SPI 1 */ MX31_PIN_CSPI2_SCLK__SCLK, MX31_PIN_CSPI2_MOSI__MOSI, MX31_PIN_CSPI2_MISO__MISO, MX31_PIN_CSPI2_SPI_RDY__SPI_RDY, MX31_PIN_CSPI2_SS0__SS0, MX31_PIN_CSPI2_SS2__SS2, /*CS for MC13783 */ /* MC13783 IRQ */ IOMUX_MODE(MX31_PIN_GPIO1_3, IOMUX_CONFIG_GPIO), /* USB OTG reset */ IOMUX_MODE(MX31_PIN_USB_PWR, IOMUX_CONFIG_GPIO), /* USB OTG */ MX31_PIN_USBOTG_DATA0__USBOTG_DATA0, MX31_PIN_USBOTG_DATA1__USBOTG_DATA1, MX31_PIN_USBOTG_DATA2__USBOTG_DATA2, MX31_PIN_USBOTG_DATA3__USBOTG_DATA3, MX31_PIN_USBOTG_DATA4__USBOTG_DATA4, MX31_PIN_USBOTG_DATA5__USBOTG_DATA5, MX31_PIN_USBOTG_DATA6__USBOTG_DATA6, MX31_PIN_USBOTG_DATA7__USBOTG_DATA7, MX31_PIN_USBOTG_CLK__USBOTG_CLK, MX31_PIN_USBOTG_DIR__USBOTG_DIR, MX31_PIN_USBOTG_NXT__USBOTG_NXT, MX31_PIN_USBOTG_STP__USBOTG_STP, /*Keyboard*/ MX31_PIN_KEY_ROW0_KEY_ROW0, MX31_PIN_KEY_ROW1_KEY_ROW1, MX31_PIN_KEY_ROW2_KEY_ROW2, MX31_PIN_KEY_COL0_KEY_COL0, MX31_PIN_KEY_COL1_KEY_COL1, MX31_PIN_KEY_COL2_KEY_COL2, MX31_PIN_KEY_COL3_KEY_COL3, }; /* * Matrix keyboard */ static const uint32_t mx31_3ds_keymap[] = { KEY(0, 0, KEY_UP), KEY(0, 1, KEY_DOWN), KEY(1, 0, KEY_RIGHT), KEY(1, 1, KEY_LEFT), KEY(1, 2, KEY_ENTER), KEY(2, 0, KEY_F6), KEY(2, 1, KEY_F8), KEY(2, 2, KEY_F9), KEY(2, 3, KEY_F10), }; static struct matrix_keymap_data mx31_3ds_keymap_data = { .keymap = mx31_3ds_keymap, .keymap_size = ARRAY_SIZE(mx31_3ds_keymap), }; /* Regulators */ static struct regulator_init_data pwgtx_init = { .constraints = { .boot_on = 1, .always_on = 1, }, }; static struct mc13783_regulator_init_data mx31_3ds_regulators[] = { { .id = MC13783_REGU_PWGT1SPI, /* Power Gate for ARM core. */ .init_data = &pwgtx_init, }, { .id = MC13783_REGU_PWGT2SPI, /* Power Gate for L2 Cache. */ .init_data = &pwgtx_init, }, }; /* MC13783 */ static struct mc13783_platform_data mc13783_pdata __initdata = { .regulators = mx31_3ds_regulators, .num_regulators = ARRAY_SIZE(mx31_3ds_regulators), .flags = MC13783_USE_REGULATOR, }; /* SPI */ static int spi1_internal_chipselect[] = { MXC_SPI_CS(0), MXC_SPI_CS(2), }; static struct spi_imx_master spi1_pdata = { .chipselect = spi1_internal_chipselect, .num_chipselect = ARRAY_SIZE(spi1_internal_chipselect), }; static struct spi_board_info mx31_3ds_spi_devs[] __initdata = { { .modalias = "mc13783", .max_speed_hz = 1000000, .bus_num = 1, .chip_select = 1, /* SS2 */ .platform_data = &mc13783_pdata, .irq = IOMUX_TO_IRQ(MX31_PIN_GPIO1_3), .mode = SPI_CS_HIGH, }, }; /* * NAND Flash */ static struct mxc_nand_platform_data imx31_3ds_nand_flash_pdata = { .width = 1, .hw_ecc = 1, #ifdef MACH_MX31_3DS_MXC_NAND_USE_BBT .flash_bbt = 1, #endif }; /* * USB OTG */ #define USB_PAD_CFG (PAD_CTL_DRV_MAX | PAD_CTL_SRE_FAST | PAD_CTL_HYS_CMOS | \ PAD_CTL_ODE_CMOS | PAD_CTL_100K_PU) #define USBOTG_RST_B IOMUX_TO_GPIO(MX31_PIN_USB_PWR) static void mx31_3ds_usbotg_init(void) { mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA0, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA1, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA2, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA3, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA4, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA5, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA6, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA7, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_CLK, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_DIR, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_NXT, USB_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_USBOTG_STP, USB_PAD_CFG); gpio_request(USBOTG_RST_B, "otgusb-reset"); gpio_direction_output(USBOTG_RST_B, 0); mdelay(1); gpio_set_value(USBOTG_RST_B, 1); } static struct fsl_usb2_platform_data usbotg_pdata = { .operating_mode = FSL_USB2_DR_DEVICE, .phy_mode = FSL_USB2_PHY_ULPI, }; static struct imxuart_platform_data uart_pdata = { .flags = IMXUART_HAVE_RTSCTS, }; /* * Support for the SMSC9217 on the Debug board. */ static struct smsc911x_platform_config smsc911x_config = { .irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW, .irq_type = SMSC911X_IRQ_TYPE_PUSH_PULL, .flags = SMSC911X_USE_16BIT | SMSC911X_FORCE_INTERNAL_PHY, .phy_interface = PHY_INTERFACE_MODE_MII, }; static struct resource smsc911x_resources[] = { { .start = LAN9217_BASE_ADDR, .end = LAN9217_BASE_ADDR + 0xff, .flags = IORESOURCE_MEM, }, { .start = EXPIO_INT_ENET, .end = EXPIO_INT_ENET, .flags = IORESOURCE_IRQ, }, }; static struct platform_device smsc911x_device = { .name = "smsc911x", .id = -1, .num_resources = ARRAY_SIZE(smsc911x_resources), .resource = smsc911x_resources, .dev = { .platform_data = &smsc911x_config, }, }; /* * Routines for the CPLD on the debug board. It contains a CPLD handling * LEDs, switches, interrupts for Ethernet. */ static void mx31_3ds_expio_irq_handler(uint32_t irq, struct irq_desc *desc) { uint32_t imr_val; uint32_t int_valid; uint32_t expio_irq; imr_val = __raw_readw(CPLD_INT_MASK_REG); int_valid = __raw_readw(CPLD_INT_STATUS_REG) & ~imr_val; expio_irq = MXC_EXP_IO_BASE; for (; int_valid != 0; int_valid >>= 1, expio_irq++) { if ((int_valid & 1) == 0) continue; generic_handle_irq(expio_irq); } } /* * Disable an expio pin's interrupt by setting the bit in the imr. * @param irq an expio virtual irq number */ static void expio_mask_irq(uint32_t irq) { uint16_t reg; uint32_t expio = MXC_IRQ_TO_EXPIO(irq); /* mask the interrupt */ reg = __raw_readw(CPLD_INT_MASK_REG); reg |= 1 << expio; __raw_writew(reg, CPLD_INT_MASK_REG); } /* * Acknowledge an expanded io pin's interrupt by clearing the bit in the isr. * @param irq an expanded io virtual irq number */ static void expio_ack_irq(uint32_t irq) { uint32_t expio = MXC_IRQ_TO_EXPIO(irq); /* clear the interrupt status */ __raw_writew(1 << expio, CPLD_INT_RESET_REG); __raw_writew(0, CPLD_INT_RESET_REG); /* mask the interrupt */ expio_mask_irq(irq); } /* * Enable a expio pin's interrupt by clearing the bit in the imr. * @param irq a expio virtual irq number */ static void expio_unmask_irq(uint32_t irq) { uint16_t reg; uint32_t expio = MXC_IRQ_TO_EXPIO(irq); /* unmask the interrupt */ reg = __raw_readw(CPLD_INT_MASK_REG); reg &= ~(1 << expio); __raw_writew(reg, CPLD_INT_MASK_REG); } static struct irq_chip expio_irq_chip = { .ack = expio_ack_irq, .mask = expio_mask_irq, .unmask = expio_unmask_irq, }; static int __init mx31_3ds_init_expio(void) { int i; int ret; /* Check if there's a debug board connected */ if ((__raw_readw(CPLD_MAGIC_NUMBER1_REG) != 0xAAAA) || (__raw_readw(CPLD_MAGIC_NUMBER2_REG) != 0x5555) || (__raw_readw(CPLD_MAGIC_NUMBER3_REG) != 0xCAFE)) { /* No Debug board found */ return -ENODEV; } pr_info("i.MX31 3DS Debug board detected, rev = 0x%04X\n", __raw_readw(CPLD_CODE_VER_REG)); /* * Configure INT line as GPIO input */ ret = gpio_request(IOMUX_TO_GPIO(MX31_PIN_GPIO1_1), "sms9217-irq"); if (ret) pr_warning("could not get LAN irq gpio\n"); else gpio_direction_input(IOMUX_TO_GPIO(MX31_PIN_GPIO1_1)); /* Disable the interrupts and clear the status */ __raw_writew(0, CPLD_INT_MASK_REG); __raw_writew(0xFFFF, CPLD_INT_RESET_REG); __raw_writew(0, CPLD_INT_RESET_REG); __raw_writew(0x1F, CPLD_INT_MASK_REG); for (i = MXC_EXP_IO_BASE; i < (MXC_EXP_IO_BASE + MXC_MAX_EXP_IO_LINES); i++) { set_irq_chip(i, &expio_irq_chip); set_irq_handler(i, handle_level_irq); set_irq_flags(i, IRQF_VALID); } set_irq_type(EXPIO_PARENT_INT, IRQ_TYPE_LEVEL_LOW); set_irq_chained_handler(EXPIO_PARENT_INT, mx31_3ds_expio_irq_handler); return 0; } /* * This structure defines the MX31 memory map. */ static struct map_desc mx31_3ds_io_desc[] __initdata = { { .virtual = MX31_CS5_BASE_ADDR_VIRT, .pfn = __phys_to_pfn(MX31_CS5_BASE_ADDR), .length = MX31_CS5_SIZE, .type = MT_DEVICE, }, }; /* * Set up static virtual mappings. */ static void __init mx31_3ds_map_io(void) { mx31_map_io(); iotable_init(mx31_3ds_io_desc, ARRAY_SIZE(mx31_3ds_io_desc)); } /*! * Board specific initialization. */ static void __init mxc_board_init(void) { mxc_iomux_setup_multiple_pins(mx31_3ds_pins, ARRAY_SIZE(mx31_3ds_pins), "mx31_3ds"); mxc_register_device(&mxc_uart_device0, &uart_pdata); mxc_register_device(&mxc_nand_device, &imx31_3ds_nand_flash_pdata); mxc_register_device(&mxc_spi_device1, &spi1_pdata); spi_register_board_info(mx31_3ds_spi_devs, ARRAY_SIZE(mx31_3ds_spi_devs)); mxc_register_device(&imx_kpp_device, &mx31_3ds_keymap_data); mx31_3ds_usbotg_init(); mxc_register_device(&mxc_otg_udc_device, &usbotg_pdata); if (!mx31_3ds_init_expio()) platform_device_register(&smsc911x_device); } static void __init mx31_3ds_timer_init(void) { mx31_clocks_init(26000000); } static struct sys_timer mx31_3ds_timer = { .init = mx31_3ds_timer_init, }; /* * The following uses standard kernel macros defined in arch.h in order to * initialize __mach_desc_MX31_3DS data structure. */ MACHINE_START(MX31_3DS, "Freescale MX31PDK (3DS)") /* Maintainer: Freescale Semiconductor, Inc. */ .phys_io = MX31_AIPS1_BASE_ADDR, .io_pg_offst = (MX31_AIPS1_BASE_ADDR_VIRT >> 18) & 0xfffc, .boot_params = MX3x_PHYS_OFFSET + 0x100, .map_io = mx31_3ds_map_io, .init_irq = mx31_init_irq, .init_machine = mxc_board_init, .timer = &mx31_3ds_timer, MACHINE_END
lgpl-2.1
moddevices/cc-master
server/src/base64.c
1
3324
/* This is a public domain base64 implementation written by WEI Zhicheng. */ #include <stdio.h> #include "base64.h" /* BASE 64 encode table */ static const char base64en[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; #define BASE64_PAD '=' #define BASE64DE_FIRST '+' #define BASE64DE_LAST 'z' /* ASCII order for BASE 64 decode, -1 in unused character */ static const signed char base64de[] = { /* '+', ',', '-', '.', '/', '0', '1', '2', */ 62, -1, -1, -1, 63, 52, 53, 54, /* '3', '4', '5', '6', '7', '8', '9', ':', */ 55, 56, 57, 58, 59, 60, 61, -1, /* ';', '<', '=', '>', '?', '@', 'A', 'B', */ -1, -1, -1, -1, -1, -1, 0, 1, /* 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', */ 2, 3, 4, 5, 6, 7, 8, 9, /* 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', */ 10, 11, 12, 13, 14, 15, 16, 17, /* 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', */ 18, 19, 20, 21, 22, 23, 24, 25, /* '[', '\', ']', '^', '_', '`', 'a', 'b', */ -1, -1, -1, -1, -1, -1, 26, 27, /* 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', */ 28, 29, 30, 31, 32, 33, 34, 35, /* 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', */ 36, 37, 38, 39, 40, 41, 42, 43, /* 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', */ 44, 45, 46, 47, 48, 49, 50, 51, }; int base64_encode(const unsigned char *in, unsigned int inlen, char *out) { unsigned int i, j; for (i = j = 0; i < inlen; i++) { int s = i % 3; /* from 6/gcd(6, 8) */ switch (s) { case 0: out[j++] = base64en[(in[i] >> 2) & 0x3F]; continue; case 1: out[j++] = base64en[((in[i-1] & 0x3) << 4) + ((in[i] >> 4) & 0xF)]; continue; case 2: out[j++] = base64en[((in[i-1] & 0xF) << 2) + ((in[i] >> 6) & 0x3)]; out[j++] = base64en[in[i] & 0x3F]; } } /* move back */ i -= 1; /* check the last and add padding */ if ((i % 3) == 0) { out[j++] = base64en[(in[i] & 0x3) << 4]; out[j++] = BASE64_PAD; out[j++] = BASE64_PAD; } else if ((i % 3) == 1) { out[j++] = base64en[(in[i] & 0xF) << 2]; out[j++] = BASE64_PAD; } out[j] = 0; return BASE64_OK; } int base64_decode(const char *in, unsigned int inlen, unsigned char *out) { unsigned int i, j; for (i = j = 0; i < inlen; i++) { int c; int s = i % 4; /* from 8/gcd(6, 8) */ if (in[i] == '=') return BASE64_OK; if (in[i] < BASE64DE_FIRST || in[i] > BASE64DE_LAST || (c = base64de[in[i] - BASE64DE_FIRST]) == -1) return BASE64_INVALID; switch (s) { case 0: out[j] = ((unsigned int)c << 2) & 0xFF; continue; case 1: out[j++] += ((unsigned int)c >> 4) & 0x3; /* if not last char with padding */ if (i < (inlen - 3) || in[inlen - 2] != '=') out[j] = ((unsigned int)c & 0xF) << 4; continue; case 2: out[j++] += ((unsigned int)c >> 2) & 0xF; /* if not last char with padding */ if (i < (inlen - 2) || in[inlen - 1] != '=') out[j] = ((unsigned int)c & 0x3) << 6; continue; case 3: out[j++] += (unsigned char)c; } } return BASE64_OK; }
lgpl-3.0
pcolby/libqtaws
src/nimblestudio/geteularequest.cpp
1
2702
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "geteularequest.h" #include "geteularequest_p.h" #include "geteularesponse.h" #include "nimblestudiorequest_p.h" namespace QtAws { namespace NimbleStudio { /*! * \class QtAws::NimbleStudio::GetEulaRequest * \brief The GetEulaRequest class provides an interface for NimbleStudio GetEula requests. * * \inmodule QtAwsNimbleStudio * * * \sa NimbleStudioClient::getEula */ /*! * Constructs a copy of \a other. */ GetEulaRequest::GetEulaRequest(const GetEulaRequest &other) : NimbleStudioRequest(new GetEulaRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a GetEulaRequest object. */ GetEulaRequest::GetEulaRequest() : NimbleStudioRequest(new GetEulaRequestPrivate(NimbleStudioRequest::GetEulaAction, this)) { } /*! * \reimp */ bool GetEulaRequest::isValid() const { return false; } /*! * Returns a GetEulaResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * GetEulaRequest::response(QNetworkReply * const reply) const { return new GetEulaResponse(*this, reply); } /*! * \class QtAws::NimbleStudio::GetEulaRequestPrivate * \brief The GetEulaRequestPrivate class provides private implementation for GetEulaRequest. * \internal * * \inmodule QtAwsNimbleStudio */ /*! * Constructs a GetEulaRequestPrivate object for NimbleStudio \a action, * with public implementation \a q. */ GetEulaRequestPrivate::GetEulaRequestPrivate( const NimbleStudioRequest::Action action, GetEulaRequest * const q) : NimbleStudioRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the GetEulaRequest * class' copy constructor. */ GetEulaRequestPrivate::GetEulaRequestPrivate( const GetEulaRequestPrivate &other, GetEulaRequest * const q) : NimbleStudioRequestPrivate(other, q) { } } // namespace NimbleStudio } // namespace QtAws
lgpl-3.0
Motesque/photon-firmware
hal/src/stm32f2xx/bootloader_platform_6.c
1
97004
const unsigned char bootloader_platform_6_bin[] = { 0x00, 0x00, 0x02, 0x20, 0x3d, 0x35, 0x00, 0x08, 0xdf, 0x13, 0x00, 0x08, 0xdd, 0x13, 0x00, 0x08, 0xdb, 0x13, 0x00, 0x08, 0xd9, 0x13, 0x00, 0x08, 0xd7, 0x13, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd5, 0x13, 0x00, 0x08, 0xd3, 0x13, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0xd1, 0x13, 0x00, 0x08, 0x25, 0x13, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x37, 0x35, 0x00, 0x08, 0x31, 0x35, 0x00, 0x08, 0x2b, 0x35, 0x00, 0x08, 0x25, 0x35, 0x00, 0x08, 0x1f, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0xf7, 0x34, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0xe9, 0x14, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0xc1, 0x34, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x3d, 0x15, 0x00, 0x08, 0x4d, 0x0e, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x85, 0x35, 0x00, 0x08, 0x00, 0x00, 0x00, 0x08, 0x5c, 0x3d, 0x00, 0x08, 0x00, 0x00, 0x0c, 0x00, 0x06, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x84, 0x46, 0x41, 0xea, 0x00, 0x03, 0x13, 0xf0, 0x03, 0x03, 0x49, 0xd1, 0x40, 0x3a, 0x23, 0xd3, 0x0b, 0x68, 0x03, 0x60, 0x4b, 0x68, 0x43, 0x60, 0x8b, 0x68, 0x83, 0x60, 0xcb, 0x68, 0xc3, 0x60, 0x0b, 0x69, 0x03, 0x61, 0x4b, 0x69, 0x43, 0x61, 0x8b, 0x69, 0x83, 0x61, 0xcb, 0x69, 0xc3, 0x61, 0x0b, 0x6a, 0x03, 0x62, 0x4b, 0x6a, 0x43, 0x62, 0x8b, 0x6a, 0x83, 0x62, 0xcb, 0x6a, 0xc3, 0x62, 0x0b, 0x6b, 0x03, 0x63, 0x4b, 0x6b, 0x43, 0x63, 0x8b, 0x6b, 0x83, 0x63, 0xcb, 0x6b, 0xc3, 0x63, 0x40, 0x30, 0x40, 0x31, 0x40, 0x3a, 0xdb, 0xd2, 0x30, 0x32, 0x0b, 0xd3, 0x0b, 0x68, 0x03, 0x60, 0x4b, 0x68, 0x43, 0x60, 0x8b, 0x68, 0x83, 0x60, 0xcb, 0x68, 0xc3, 0x60, 0x10, 0x30, 0x10, 0x31, 0x10, 0x3a, 0xf3, 0xd2, 0x0c, 0x32, 0x05, 0xd3, 0x51, 0xf8, 0x04, 0x3b, 0x40, 0xf8, 0x04, 0x3b, 0x04, 0x3a, 0xf9, 0xd2, 0x04, 0x32, 0x08, 0xd0, 0xd2, 0x07, 0x1c, 0xbf, 0x11, 0xf8, 0x01, 0x3b, 0x00, 0xf8, 0x01, 0x3b, 0x01, 0xd3, 0x0b, 0x88, 0x03, 0x80, 0x60, 0x46, 0x70, 0x47, 0x00, 0xbf, 0x08, 0x2a, 0x13, 0xd3, 0x8b, 0x07, 0xb1, 0xd0, 0x10, 0xf0, 0x03, 0x03, 0xae, 0xd0, 0xc3, 0xf1, 0x04, 0x03, 0xd2, 0x1a, 0xdb, 0x07, 0x1c, 0xbf, 0x11, 0xf8, 0x01, 0x3b, 0x00, 0xf8, 0x01, 0x3b, 0xa4, 0xd3, 0x31, 0xf8, 0x02, 0x3b, 0x20, 0xf8, 0x02, 0x3b, 0x9f, 0xe7, 0x04, 0x3a, 0xd9, 0xd3, 0x01, 0x3a, 0x11, 0xf8, 0x01, 0x3b, 0x00, 0xf8, 0x01, 0x3b, 0xf9, 0xd2, 0x0b, 0x78, 0x03, 0x70, 0x4b, 0x78, 0x43, 0x70, 0x8b, 0x78, 0x83, 0x70, 0x60, 0x46, 0x70, 0x47, 0x80, 0xb5, 0xac, 0x4a, 0x01, 0x24, 0x13, 0x68, 0x00, 0x26, 0x43, 0xf0, 0x10, 0x03, 0x13, 0x60, 0xa9, 0x4b, 0x4f, 0xf0, 0x80, 0x45, 0x1a, 0x6c, 0x8a, 0xb0, 0x42, 0xf0, 0x80, 0x52, 0x1a, 0x64, 0xa6, 0x4a, 0x4f, 0xf0, 0x80, 0x40, 0x14, 0x60, 0xa5, 0x4a, 0x51, 0x68, 0x41, 0xf0, 0x07, 0x01, 0x51, 0x60, 0x91, 0x68, 0x41, 0xf4, 0xc0, 0x51, 0x91, 0x60, 0xa2, 0x49, 0xca, 0x68, 0x42, 0xf0, 0x80, 0x72, 0xca, 0x60, 0xa0, 0x4a, 0x56, 0x60, 0x11, 0x68, 0x21, 0x43, 0x11, 0x60, 0x9f, 0x49, 0x02, 0xf5, 0x5d, 0x42, 0xd1, 0x60, 0x1a, 0x6b, 0x31, 0x46, 0x42, 0xf4, 0x80, 0x52, 0x1a, 0x63, 0x5a, 0x6c, 0x42, 0xf4, 0x80, 0x42, 0x5a, 0x64, 0x02, 0xf0, 0xa4, 0xfb, 0x2b, 0x8c, 0x28, 0x46, 0x23, 0xf0, 0x01, 0x03, 0x1b, 0x04, 0x1b, 0x0c, 0x2b, 0x84, 0x2b, 0x8c, 0xa9, 0x88, 0x2a, 0x8b, 0x23, 0xf0, 0x02, 0x03, 0x22, 0xf0, 0x73, 0x02, 0x1b, 0x04, 0x12, 0x04, 0x1b, 0x0c, 0x12, 0x0c, 0x89, 0xb2, 0x23, 0x43, 0xa9, 0x80, 0x2a, 0x83, 0x6e, 0x63, 0x2b, 0x84, 0x2b, 0x8b, 0x04, 0x21, 0x23, 0xf0, 0x08, 0x03, 0x1b, 0x04, 0x1b, 0x0c, 0x2b, 0x83, 0x02, 0xf0, 0xb7, 0xfa, 0x28, 0x46, 0x08, 0x21, 0x02, 0xf0, 0xb3, 0xfa, 0x28, 0x46, 0x0c, 0x21, 0x02, 0xf0, 0xaf, 0xfa, 0x28, 0x46, 0x21, 0x46, 0x02, 0xf0, 0x77, 0xfb, 0x82, 0x48, 0x82, 0x49, 0x60, 0x22, 0xff, 0xf7, 0x22, 0xff, 0x81, 0x4d, 0x03, 0x2c, 0x21, 0xdd, 0x18, 0x20, 0x60, 0x43, 0x00, 0xf6, 0xef, 0x50, 0x03, 0xf0, 0x07, 0xfa, 0x03, 0x78, 0xff, 0x2b, 0x46, 0xd0, 0x83, 0x7d, 0x03, 0xf0, 0x09, 0x03, 0x09, 0x2b, 0x41, 0xd1, 0x03, 0x46, 0x2e, 0x46, 0x00, 0xf1, 0x18, 0x07, 0x32, 0x46, 0x18, 0x68, 0x59, 0x68, 0x08, 0x33, 0x03, 0xc2, 0xbb, 0x42, 0x16, 0x46, 0xf7, 0xd1, 0x28, 0x69, 0x01, 0x21, 0x02, 0xf0, 0x51, 0xfb, 0x28, 0x69, 0xa9, 0x8a, 0x02, 0xf0, 0x81, 0xfa, 0x67, 0x4a, 0x69, 0x89, 0x13, 0x6b, 0x0b, 0x43, 0x13, 0x63, 0x2b, 0x89, 0x03, 0x22, 0x08, 0x93, 0x2b, 0x7b, 0x68, 0x68, 0x8d, 0xf8, 0x24, 0x30, 0x08, 0xa9, 0x00, 0x23, 0x8d, 0xf8, 0x26, 0x30, 0x8d, 0xf8, 0x27, 0x30, 0x8d, 0xf8, 0x25, 0x20, 0x02, 0xf0, 0x7f, 0xff, 0x2b, 0x7b, 0x02, 0x2b, 0x14, 0xd1, 0xab, 0x7b, 0xe8, 0x7b, 0xd9, 0x08, 0x03, 0xf0, 0x07, 0x02, 0x6b, 0x68, 0x92, 0x00, 0x03, 0xeb, 0x81, 0x03, 0x19, 0x6a, 0x0f, 0x26, 0x90, 0x40, 0x06, 0xfa, 0x02, 0xf2, 0x21, 0xea, 0x02, 0x02, 0x1a, 0x62, 0x19, 0x6a, 0x40, 0xea, 0x01, 0x02, 0x1a, 0x62, 0x01, 0x34, 0x08, 0x2c, 0x05, 0xf1, 0x18, 0x05, 0xa8, 0xd1, 0x00, 0x20, 0x02, 0xf0, 0x07, 0xfd, 0x55, 0x4b, 0xf3, 0x22, 0xda, 0x60, 0x40, 0xf6, 0x2f, 0x60, 0x03, 0xf0, 0xae, 0xf9, 0x03, 0x78, 0xaa, 0x2b, 0x19, 0xd1, 0x4b, 0xf6, 0xcc, 0x32, 0x03, 0x8a, 0x9b, 0xb2, 0x93, 0x42, 0x13, 0xd1, 0x03, 0x46, 0x4d, 0x4c, 0x00, 0xf1, 0x20, 0x05, 0x22, 0x46, 0x18, 0x68, 0x59, 0x68, 0x08, 0x33, 0x03, 0xc2, 0xab, 0x42, 0x14, 0x46, 0xf7, 0xd1, 0x49, 0x4b, 0x00, 0x22, 0x83, 0xf8, 0x20, 0x20, 0x01, 0x20, 0x1a, 0x86, 0x02, 0xf0, 0xe3, 0xfc, 0x01, 0xf0, 0x27, 0xf8, 0x30, 0xb1, 0x4f, 0xf0, 0x80, 0x42, 0x93, 0x89, 0x9b, 0xb2, 0x43, 0xf0, 0x02, 0x03, 0x93, 0x81, 0x41, 0x4b, 0x4f, 0xf4, 0x7a, 0x72, 0x1b, 0x68, 0xf0, 0x21, 0xb3, 0xfb, 0xf2, 0xf3, 0x3e, 0x4a, 0x01, 0x3b, 0x53, 0x60, 0x3e, 0x4b, 0x00, 0x20, 0x83, 0xf8, 0x23, 0x10, 0x07, 0x21, 0x90, 0x60, 0x11, 0x60, 0xd0, 0x22, 0x83, 0xf8, 0x23, 0x20, 0x3a, 0x4b, 0x01, 0x22, 0x1a, 0x70, 0x03, 0xf0, 0x6e, 0xf9, 0x38, 0x4a, 0x03, 0x46, 0x15, 0x46, 0x00, 0xf1, 0x20, 0x06, 0x14, 0x46, 0x18, 0x68, 0x59, 0x68, 0x08, 0x33, 0x03, 0xc4, 0xb3, 0x42, 0x22, 0x46, 0xf7, 0xd1, 0x4a, 0xf6, 0xc0, 0x43, 0x2b, 0x80, 0x41, 0xf6, 0xde, 0x23, 0x6b, 0x80, 0x1f, 0x4b, 0x6a, 0x69, 0x5b, 0x6f, 0x9a, 0x42, 0x03, 0xd0, 0x2c, 0x4a, 0x53, 0x61, 0x02, 0xf0, 0x46, 0xf9, 0xab, 0x88, 0x0c, 0x2b, 0x04, 0xd0, 0x29, 0x4b, 0x0c, 0x22, 0x9a, 0x80, 0x02, 0xf0, 0x3e, 0xf9, 0xab, 0x7c, 0x23, 0xb1, 0x25, 0x4b, 0x00, 0x22, 0x9a, 0x74, 0x02, 0xf0, 0x37, 0xf9, 0x40, 0xf6, 0xaf, 0x60, 0x03, 0xf0, 0x3f, 0xf9, 0x04, 0x46, 0xa0, 0xb1, 0x03, 0x78, 0x01, 0x2b, 0x11, 0xd1, 0x21, 0x46, 0x0b, 0x20, 0x00, 0xf0, 0x72, 0xff, 0x1d, 0x4b, 0x21, 0x46, 0x18, 0x60, 0x08, 0x20, 0x00, 0xf0, 0x6c, 0xff, 0x1b, 0x4b, 0x21, 0x46, 0x18, 0x60, 0x0a, 0x20, 0x00, 0xf0, 0x66, 0xff, 0x19, 0x4b, 0x18, 0x60, 0x19, 0x4b, 0x1a, 0x4f, 0x3b, 0x60, 0x2b, 0x89, 0x05, 0x2b, 0x33, 0xd1, 0x01, 0x22, 0x18, 0x4b, 0x39, 0xe0, 0x00, 0xbf, 0x14, 0xed, 0x00, 0xe0, 0x00, 0x38, 0x02, 0x40, 0x20, 0x00, 0x0e, 0x42, 0x00, 0x20, 0x04, 0xe0, 0xf0, 0xed, 0x00, 0xe0, 0x00, 0x10, 0x00, 0xe0, 0x00, 0x03, 0xfa, 0x05, 0x50, 0x02, 0x00, 0x20, 0x64, 0x39, 0x00, 0x08, 0x68, 0x02, 0x00, 0x20, 0x00, 0x3c, 0x02, 0x40, 0x30, 0x01, 0x00, 0x20, 0x10, 0x01, 0x00, 0x20, 0x0c, 0x01, 0x00, 0x20, 0x10, 0xe0, 0x00, 0xe0, 0x00, 0xed, 0x00, 0xe0, 0xe0, 0x01, 0x00, 0x20, 0x30, 0x02, 0x00, 0x20, 0x20, 0x00, 0x00, 0x20, 0x48, 0x00, 0x00, 0x20, 0x4c, 0x00, 0x00, 0x20, 0x00, 0x00, 0x02, 0x08, 0xdc, 0x01, 0x00, 0x20, 0xed, 0x01, 0x00, 0x20, 0x45, 0xf2, 0x55, 0x52, 0x93, 0x42, 0x05, 0xd1, 0xa9, 0x4b, 0x00, 0x22, 0x1a, 0x70, 0xa9, 0x4b, 0x01, 0x22, 0x1a, 0x70, 0x4a, 0xf6, 0xaa, 0x23, 0x4f, 0xf6, 0xff, 0x70, 0xaa, 0x89, 0x00, 0x24, 0x9a, 0x42, 0x02, 0xbf, 0xa4, 0x4b, 0x01, 0x22, 0x1a, 0x70, 0xa4, 0x4b, 0x06, 0x94, 0x06, 0x93, 0x06, 0x9b, 0x04, 0x33, 0x06, 0x93, 0x06, 0x9b, 0x1b, 0x68, 0x9b, 0xb2, 0xad, 0xf8, 0x16, 0x30, 0xbd, 0xf8, 0x16, 0x30, 0x9b, 0xb2, 0x83, 0x42, 0x47, 0xd0, 0x4e, 0xf6, 0xfa, 0x52, 0xbd, 0xf8, 0x16, 0x30, 0x9b, 0xb2, 0x93, 0x42, 0x02, 0xd1, 0x01, 0x22, 0x99, 0x4b, 0x08, 0xe0, 0x45, 0xf6, 0xfe, 0x22, 0xbd, 0xf8, 0x16, 0x30, 0x9b, 0xb2, 0x93, 0x42, 0x03, 0xd1, 0x95, 0x4b, 0x01, 0x22, 0x1a, 0x70, 0x38, 0xe0, 0x7d, 0x20, 0x02, 0xf0, 0x13, 0xfb, 0x00, 0x28, 0x35, 0xd0, 0xbd, 0xf8, 0x16, 0x30, 0x9b, 0xb2, 0x02, 0x2b, 0x09, 0xd0, 0x03, 0x2b, 0x10, 0xd0, 0x01, 0x2b, 0x11, 0xd1, 0x88, 0x4a, 0x13, 0x70, 0xbd, 0xf8, 0x16, 0x30, 0x01, 0x33, 0x06, 0xe0, 0x86, 0x4b, 0x01, 0x22, 0x1a, 0x70, 0xbd, 0xf8, 0x16, 0x30, 0xec, 0x80, 0x13, 0x44, 0x9b, 0xb2, 0x04, 0xe0, 0x84, 0x4b, 0x01, 0x22, 0x1a, 0x70, 0x4f, 0xf6, 0xff, 0x73, 0xad, 0xf8, 0x16, 0x30, 0xbd, 0xf8, 0x16, 0x00, 0x80, 0xb2, 0x02, 0xf0, 0xcf, 0xfb, 0x00, 0x23, 0x6b, 0x81, 0x02, 0xf0, 0x7b, 0xf8, 0x7e, 0x4a, 0x53, 0x6f, 0x43, 0xf0, 0x80, 0x73, 0x53, 0x67, 0x07, 0xe0, 0x01, 0x23, 0xad, 0xf8, 0x16, 0x30, 0xbd, 0xf8, 0x16, 0x00, 0x80, 0xb2, 0x02, 0xf0, 0xbd, 0xfb, 0x00, 0x20, 0x00, 0xf0, 0xfc, 0xfe, 0x40, 0xb9, 0x74, 0x4b, 0x1b, 0x78, 0x00, 0x2b, 0x6a, 0xd0, 0x01, 0x23, 0xab, 0x74, 0x02, 0xf0, 0x61, 0xf8, 0x65, 0xe0, 0x71, 0x48, 0x01, 0xf0, 0x27, 0xfa, 0x42, 0xf6, 0xe0, 0x63, 0x82, 0x46, 0x6f, 0x4e, 0x33, 0x60, 0x00, 0x20, 0x00, 0xf0, 0xe7, 0xfe, 0x00, 0x28, 0xe9, 0xd0, 0x33, 0x68, 0x00, 0x2b, 0xe6, 0xd0, 0x00, 0x20, 0x00, 0xf0, 0xc9, 0xfe, 0x42, 0xf2, 0x10, 0x73, 0x98, 0x42, 0x06, 0xd9, 0x68, 0x4b, 0x6f, 0xf0, 0x7f, 0x42, 0x1a, 0x60, 0x01, 0x23, 0xeb, 0x80, 0xe9, 0xe7, 0xdf, 0xf8, 0x74, 0x81, 0x98, 0xf8, 0x00, 0x30, 0x03, 0xf0, 0xff, 0x04, 0x7b, 0xb9, 0x20, 0x46, 0x00, 0xf0, 0xb4, 0xfe, 0x41, 0xf6, 0x64, 0x13, 0x98, 0x42, 0x08, 0xd9, 0x5d, 0x4b, 0x4f, 0xf4, 0x7f, 0x42, 0x1a, 0x60, 0x01, 0x23, 0xec, 0x80, 0x88, 0xf8, 0x00, 0x30, 0xd2, 0xe7, 0x54, 0x4c, 0x23, 0x78, 0x03, 0xf0, 0xff, 0x00, 0x7b, 0xb9, 0x00, 0xf0, 0xa0, 0xfe, 0x40, 0xf6, 0xb7, 0x33, 0x98, 0x42, 0x09, 0xd9, 0x54, 0x4b, 0x1a, 0x68, 0x52, 0x4b, 0x1a, 0x60, 0x01, 0x23, 0x23, 0x70, 0xba, 0xf1, 0x00, 0x0f, 0xbe, 0xd1, 0xac, 0xe7, 0xdf, 0xf8, 0x28, 0x91, 0x99, 0xf8, 0x00, 0x30, 0x03, 0xf0, 0xff, 0x04, 0x00, 0x2b, 0xb5, 0xd1, 0x20, 0x46, 0x00, 0xf0, 0x87, 0xfe, 0xb0, 0xf5, 0x7a, 0x7f, 0xaf, 0xd3, 0x3e, 0x4b, 0x88, 0xf8, 0x00, 0x40, 0x1c, 0x70, 0x3d, 0x4b, 0x1c, 0x70, 0x46, 0x4b, 0x1a, 0x68, 0x43, 0x4b, 0x1a, 0x60, 0x01, 0x23, 0x89, 0xf8, 0x00, 0x30, 0xa1, 0xe7, 0x37, 0x4e, 0xdf, 0xf8, 0xe4, 0x80, 0x33, 0x78, 0x01, 0x2b, 0x04, 0xd1, 0x40, 0x4b, 0x1a, 0x68, 0x3c, 0x4b, 0x1a, 0x60, 0xc4, 0xe0, 0x98, 0xf8, 0x00, 0x30, 0x43, 0xb3, 0x98, 0xf8, 0x00, 0x30, 0x01, 0x2b, 0x1f, 0xd1, 0xeb, 0x88, 0x01, 0x2b, 0x36, 0x4b, 0x0c, 0xbf, 0x6f, 0xf0, 0x7f, 0x42, 0x4f, 0xf4, 0x7f, 0x42, 0x1a, 0x60, 0x02, 0xf0, 0x11, 0xf8, 0x00, 0x28, 0x40, 0xf0, 0xb0, 0x80, 0x38, 0x68, 0x00, 0xf0, 0x35, 0xfe, 0x00, 0x28, 0x00, 0xf0, 0xaa, 0x80, 0xbf, 0xf3, 0x4f, 0x8f, 0x30, 0x49, 0x31, 0x4b, 0xca, 0x68, 0x02, 0xf4, 0xe0, 0x62, 0x13, 0x43, 0xcb, 0x60, 0xbf, 0xf3, 0x4f, 0x8f, 0xfe, 0xe7, 0x00, 0x23, 0x88, 0xf8, 0x00, 0x30, 0x01, 0xf0, 0xcb, 0xff, 0x20, 0x4b, 0x1b, 0x78, 0x00, 0x2b, 0x40, 0xf0, 0x94, 0x80, 0x40, 0xf6, 0x24, 0x30, 0x02, 0xf0, 0xc6, 0xff, 0x00, 0xf1, 0x28, 0x04, 0x00, 0xf1, 0x78, 0x0a, 0x4a, 0xf6, 0xcd, 0x33, 0x34, 0xf8, 0x14, 0x2c, 0x9a, 0x42, 0x52, 0xd1, 0x01, 0x23, 0x33, 0x70, 0x1d, 0x4b, 0xa4, 0xf1, 0x14, 0x09, 0x1a, 0x68, 0x18, 0x4b, 0x1a, 0x60, 0x54, 0xf8, 0x08, 0x3c, 0x14, 0xf8, 0x11, 0x2c, 0x14, 0xf8, 0x12, 0x0c, 0x00, 0x93, 0x14, 0xf8, 0x03, 0x3c, 0x01, 0x93, 0x14, 0xf8, 0x04, 0x3c, 0x02, 0x93, 0x54, 0xf8, 0x10, 0x1c, 0x54, 0xf8, 0x0c, 0x3c, 0x01, 0xf0, 0x87, 0xf9, 0x02, 0xf0, 0x0f, 0xfe, 0xa1, 0x45, 0x24, 0xd0, 0x48, 0x46, 0x00, 0x21, 0x02, 0xf0, 0xad, 0xfd, 0x09, 0xf1, 0x04, 0x09, 0xf6, 0xe7, 0xed, 0x01, 0x00, 0x20, 0xee, 0x01, 0x00, 0x20, 0xfd, 0x01, 0x00, 0x20, 0x50, 0x28, 0x00, 0x40, 0xfc, 0x01, 0x00, 0x20, 0xec, 0x01, 0x00, 0x20, 0x00, 0x38, 0x02, 0x40, 0x75, 0x25, 0x00, 0x08, 0xf4, 0x01, 0x00, 0x20, 0x14, 0x03, 0x00, 0x20, 0x4c, 0x00, 0x00, 0x20, 0x48, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x20, 0x00, 0xed, 0x00, 0xe0, 0x04, 0x00, 0xfa, 0x05, 0x4f, 0xf0, 0x00, 0x09, 0x02, 0xf0, 0xdc, 0xfd, 0x48, 0x46, 0x86, 0xf8, 0x00, 0x90, 0x02, 0xf0, 0x9d, 0xfb, 0x96, 0x4b, 0x01, 0x22, 0x83, 0xf8, 0x00, 0x90, 0x95, 0x4b, 0x1a, 0x70, 0x14, 0x34, 0x54, 0x45, 0xa3, 0xd1, 0x3c, 0x68, 0x20, 0x46, 0x00, 0xf0, 0xb4, 0xfd, 0x20, 0xb3, 0x62, 0x68, 0x90, 0x4b, 0x1a, 0x60, 0x90, 0x4b, 0x1a, 0x60, 0x22, 0x68, 0x82, 0xf3, 0x08, 0x88, 0x4d, 0xf2, 0x01, 0x02, 0xe9, 0x89, 0x91, 0x42, 0x1a, 0x46, 0x0e, 0xd1, 0x45, 0xf2, 0x55, 0x51, 0x8b, 0x4b, 0x19, 0x60, 0x06, 0x21, 0x59, 0x60, 0x40, 0xf2, 0x71, 0x21, 0x99, 0x60, 0x4a, 0xf6, 0xaa, 0x21, 0x19, 0x60, 0x4c, 0xf6, 0xcc, 0x41, 0x19, 0x60, 0x85, 0x49, 0x0b, 0x68, 0x23, 0xf0, 0x01, 0x03, 0x0b, 0x60, 0x13, 0x68, 0x98, 0x47, 0x05, 0xe0, 0x82, 0x4b, 0x4f, 0xf4, 0x7f, 0x02, 0x1a, 0x60, 0x01, 0xf0, 0x5e, 0xff, 0x80, 0x4b, 0x00, 0x24, 0x1c, 0x70, 0x80, 0x4b, 0x88, 0xf8, 0x00, 0x40, 0x1a, 0x68, 0x7c, 0x4b, 0x34, 0x70, 0x1a, 0x60, 0x7d, 0x4b, 0x7e, 0x4e, 0x01, 0x27, 0x1f, 0x70, 0x33, 0x6b, 0x7d, 0x4d, 0x43, 0xf0, 0x02, 0x03, 0x33, 0x63, 0x4f, 0xf4, 0x40, 0x43, 0x08, 0x93, 0x4f, 0xf0, 0x02, 0x08, 0x03, 0x23, 0x28, 0x46, 0x08, 0xa9, 0x8d, 0xf8, 0x25, 0x30, 0x8d, 0xf8, 0x24, 0x80, 0x02, 0xf0, 0xbf, 0xfc, 0x6b, 0x6a, 0x74, 0x4a, 0x23, 0xf0, 0x70, 0x63, 0x6b, 0x62, 0x6b, 0x6a, 0x43, 0xf0, 0x40, 0x63, 0x6b, 0x62, 0x6b, 0x6a, 0x23, 0xf0, 0x70, 0x43, 0x6b, 0x62, 0x6b, 0x6a, 0x43, 0xf0, 0x40, 0x43, 0x6b, 0x62, 0x33, 0x6b, 0x43, 0xf0, 0x00, 0x53, 0x33, 0x63, 0x6b, 0x4b, 0xc3, 0xf8, 0xc4, 0x24, 0x6b, 0x4a, 0xdc, 0x70, 0xc3, 0xf8, 0xc8, 0x24, 0x6a, 0x4a, 0xdc, 0x72, 0xc3, 0xf8, 0xcc, 0x24, 0x40, 0x22, 0x9a, 0x80, 0x0c, 0x22, 0x1a, 0x70, 0x06, 0x22, 0x5a, 0x70, 0x4f, 0xf4, 0xa0, 0x62, 0xda, 0x80, 0x64, 0x4a, 0x9f, 0x70, 0xda, 0x60, 0x02, 0xf5, 0x00, 0x62, 0x1a, 0x61, 0x02, 0xf5, 0x80, 0x72, 0x9a, 0x61, 0x02, 0xf5, 0x00, 0x72, 0x9a, 0x64, 0xa2, 0xf5, 0xf0, 0x72, 0xda, 0x61, 0x02, 0xf5, 0x00, 0x72, 0xda, 0x64, 0xa2, 0xf5, 0xf0, 0x72, 0x1a, 0x62, 0x02, 0xf5, 0x00, 0x72, 0x1a, 0x65, 0xa2, 0xf5, 0xf0, 0x72, 0x5a, 0x62, 0x02, 0xf5, 0x00, 0x72, 0x5a, 0x65, 0xa2, 0xf5, 0xf0, 0x72, 0x9a, 0x62, 0x02, 0xf5, 0x00, 0x72, 0x83, 0xf8, 0x08, 0x80, 0x9f, 0x72, 0x9a, 0x65, 0xa2, 0xf5, 0xf0, 0x72, 0xda, 0x62, 0x02, 0xf5, 0x00, 0x72, 0xda, 0x65, 0xa2, 0xf5, 0xf4, 0x62, 0x5a, 0x61, 0x40, 0x32, 0xc3, 0xf8, 0xa8, 0x20, 0x22, 0x46, 0x1c, 0x46, 0x4b, 0x4b, 0xa1, 0x18, 0x13, 0x44, 0x04, 0x32, 0xdb, 0x00, 0x30, 0x2a, 0x8b, 0x67, 0xf7, 0xd1, 0x00, 0x22, 0x02, 0xf5, 0x80, 0x11, 0xa0, 0x18, 0x01, 0xf5, 0x82, 0x71, 0x04, 0x32, 0x89, 0x02, 0x30, 0x2a, 0x3e, 0x4b, 0xc0, 0xf8, 0xac, 0x10, 0xf3, 0xd1, 0x19, 0x46, 0x41, 0x4a, 0x00, 0x20, 0xc3, 0xf8, 0xdc, 0x20, 0x01, 0x22, 0x83, 0xf8, 0xe2, 0x20, 0x83, 0xf8, 0xe4, 0x00, 0x01, 0x22, 0x81, 0xf8, 0xec, 0x00, 0xa1, 0xf8, 0xf2, 0x00, 0x01, 0x30, 0x81, 0xf8, 0xed, 0x20, 0x40, 0x25, 0x00, 0x22, 0x06, 0x28, 0x81, 0xf8, 0xef, 0x20, 0xc1, 0xf8, 0xf4, 0x50, 0xc1, 0xf8, 0xf8, 0x20, 0xc1, 0xf8, 0x00, 0x21, 0x01, 0xf1, 0x28, 0x01, 0xe9, 0xd1, 0x83, 0xf8, 0xcc, 0x22, 0xa3, 0xf8, 0xd2, 0x22, 0x01, 0x32, 0x00, 0x25, 0x40, 0x21, 0x06, 0x2a, 0x83, 0xf8, 0xcd, 0x52, 0x83, 0xf8, 0xcf, 0x52, 0xc3, 0xf8, 0xd4, 0x12, 0xc3, 0xf8, 0xd8, 0x52, 0xc3, 0xf8, 0xe0, 0x52, 0x03, 0xf1, 0x28, 0x03, 0xea, 0xd1, 0x25, 0x4a, 0x21, 0x4e, 0x93, 0x68, 0x23, 0xf0, 0x01, 0x03, 0x93, 0x60, 0x23, 0x7a, 0x01, 0x2b, 0x49, 0xd1, 0xf2, 0x68, 0x71, 0x7a, 0x93, 0x6b, 0x65, 0xf3, 0x10, 0x43, 0x09, 0xb1, 0x43, 0xf4, 0x80, 0x13, 0x93, 0x63, 0xd3, 0x68, 0x1e, 0x48, 0x6f, 0xf3, 0x86, 0x13, 0x6f, 0xf3, 0x96, 0x53, 0x6f, 0xf3, 0x51, 0x43, 0x6f, 0xf3, 0xd3, 0x43, 0xd3, 0x60, 0x02, 0xf0, 0xee, 0xfa, 0xe3, 0x78, 0x01, 0x2b, 0x46, 0xd1, 0x05, 0x23, 0x63, 0xf3, 0x44, 0x05, 0x0f, 0x4b, 0x45, 0xf0, 0x20, 0x05, 0xdb, 0x68, 0x9d, 0x60, 0x3d, 0xe0, 0x50, 0x00, 0x00, 0x20, 0x24, 0x00, 0x00, 0x20, 0xe8, 0x01, 0x00, 0x20, 0xe4, 0x01, 0x00, 0x20, 0x00, 0x30, 0x00, 0x40, 0x10, 0xe0, 0x00, 0xe0, 0x14, 0x03, 0x00, 0x20, 0xee, 0x01, 0x00, 0x20, 0x4c, 0x00, 0x00, 0x20, 0xfc, 0x01, 0x00, 0x20, 0x00, 0x38, 0x02, 0x40, 0x00, 0x04, 0x02, 0x40, 0x54, 0x00, 0x00, 0x20, 0x18, 0x14, 0x00, 0x20, 0x28, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x40, 0xa0, 0x80, 0x00, 0x08, 0x00, 0x0e, 0x04, 0x40, 0x24, 0x14, 0x00, 0x20, 0x30, 0x46, 0x50, 0xf8, 0x0c, 0x2f, 0xd3, 0x68, 0x43, 0xf0, 0x40, 0x03, 0xd3, 0x60, 0x02, 0xf0, 0xb1, 0xfa, 0x73, 0x7a, 0xe2, 0x68, 0x00, 0x2b, 0x0c, 0xbf, 0x4f, 0xf4, 0x34, 0x13, 0x4f, 0xf4, 0x74, 0x13, 0x93, 0x63, 0x44, 0xf6, 0x20, 0x60, 0x00, 0xf0, 0x8a, 0xff, 0xe3, 0x78, 0x01, 0x2b, 0x08, 0xd1, 0x83, 0x4b, 0x05, 0x22, 0xdb, 0x68, 0x9d, 0x68, 0x62, 0xf3, 0x44, 0x05, 0x45, 0xf0, 0x20, 0x05, 0x9d, 0x60, 0xe2, 0x68, 0x4c, 0xf2, 0x50, 0x30, 0xd3, 0x68, 0x7c, 0x4d, 0x6f, 0xf3, 0x5d, 0x73, 0x43, 0xf0, 0x80, 0x43, 0xd3, 0x60, 0x00, 0xf0, 0x72, 0xff, 0xd4, 0xf8, 0xdc, 0x30, 0x00, 0x21, 0x19, 0x60, 0x20, 0x69, 0x0a, 0x46, 0x03, 0x68, 0x61, 0xf3, 0xcc, 0x23, 0x03, 0x60, 0xe3, 0x7a, 0x00, 0x2b, 0x3c, 0xd1, 0x2b, 0x7a, 0x28, 0x69, 0x01, 0x2b, 0x03, 0x68, 0x14, 0xbf, 0x01, 0x25, 0x61, 0xf3, 0x01, 0x03, 0xc0, 0xf2, 0x40, 0x01, 0x18, 0xbf, 0x65, 0xf3, 0x01, 0x03, 0x03, 0x60, 0xe3, 0x68, 0x4f, 0xf4, 0x80, 0x70, 0x60, 0xf3, 0x0f, 0x01, 0x58, 0x62, 0x99, 0x62, 0x4f, 0xf4, 0xa0, 0x71, 0x61, 0xf3, 0x0f, 0x02, 0x60, 0xf3, 0x1f, 0x42, 0x4f, 0xf4, 0x10, 0x71, 0xc3, 0xf8, 0x04, 0x21, 0x61, 0xf3, 0x0f, 0x02, 0xc0, 0xf2, 0x20, 0x02, 0x4f, 0xf4, 0x18, 0x71, 0xc3, 0xf8, 0x08, 0x21, 0x61, 0xf3, 0x0f, 0x02, 0x60, 0xf3, 0x1f, 0x42, 0x4f, 0xf4, 0x58, 0x71, 0xc3, 0xf8, 0x0c, 0x21, 0x61, 0xf3, 0x0f, 0x02, 0xc0, 0xf2, 0x20, 0x02, 0x4f, 0xf4, 0x60, 0x71, 0xc3, 0xf8, 0x10, 0x21, 0x61, 0xf3, 0x0f, 0x02, 0xc0, 0xf2, 0x40, 0x02, 0xc3, 0xf8, 0x14, 0x21, 0x10, 0x20, 0x02, 0xf0, 0xbd, 0xf8, 0x00, 0x23, 0x07, 0x93, 0x07, 0x9b, 0x43, 0xf0, 0x10, 0x03, 0x07, 0x93, 0x07, 0x9b, 0xe2, 0x68, 0x13, 0x61, 0x4e, 0x4b, 0x11, 0x69, 0x01, 0x3b, 0x07, 0x91, 0x02, 0xd0, 0x07, 0x99, 0xc9, 0x06, 0xf8, 0xd4, 0x03, 0x20, 0x00, 0xf0, 0x11, 0xff, 0x22, 0x69, 0x00, 0x23, 0x13, 0x61, 0x22, 0x69, 0x4f, 0xf0, 0xff, 0x31, 0x53, 0x61, 0x91, 0x61, 0xd3, 0x61, 0x45, 0x4a, 0x61, 0x78, 0x8b, 0x42, 0x10, 0xd2, 0x10, 0x68, 0x01, 0x33, 0x01, 0x68, 0x00, 0x29, 0xac, 0xbf, 0x00, 0x21, 0x4f, 0xf0, 0x90, 0x41, 0x01, 0x60, 0x11, 0x68, 0x00, 0x20, 0x08, 0x61, 0x52, 0xf8, 0x04, 0x1b, 0xff, 0x20, 0x88, 0x60, 0xeb, 0xe7, 0x3c, 0x4b, 0x00, 0x21, 0x60, 0x78, 0x37, 0x4a, 0x81, 0x42, 0x10, 0xd2, 0x18, 0x68, 0x01, 0x31, 0x02, 0x68, 0x00, 0x2a, 0xac, 0xbf, 0x00, 0x22, 0x4f, 0xf0, 0x90, 0x42, 0x02, 0x60, 0x1a, 0x68, 0x00, 0x20, 0x10, 0x61, 0x53, 0xf8, 0x04, 0x2b, 0xff, 0x20, 0x90, 0x60, 0xea, 0xe7, 0x11, 0x69, 0x0b, 0x69, 0x43, 0xf4, 0x80, 0x73, 0x0b, 0x61, 0xd1, 0x78, 0x01, 0x29, 0x01, 0xbf, 0x2d, 0x4b, 0x40, 0x20, 0x12, 0x69, 0x60, 0xf3, 0x59, 0x43, 0x08, 0xbf, 0x13, 0x63, 0xe2, 0x68, 0x00, 0x23, 0x93, 0x61, 0x4f, 0xf0, 0xff, 0x30, 0x6f, 0xf0, 0x80, 0x43, 0x53, 0x61, 0x50, 0x60, 0xe2, 0x68, 0x00, 0x29, 0x53, 0x61, 0x25, 0x4b, 0x93, 0x61, 0x14, 0xbf, 0x4f, 0xf4, 0x00, 0x63, 0x4f, 0xf4, 0x01, 0x63, 0x43, 0xf4, 0x70, 0x13, 0x91, 0x69, 0x43, 0xf4, 0x40, 0x53, 0x43, 0xf0, 0x08, 0x03, 0x0b, 0x43, 0x93, 0x61, 0x93, 0x68, 0x43, 0xf0, 0x01, 0x03, 0x93, 0x60, 0xd4, 0xf8, 0xc8, 0x34, 0x0b, 0xb1, 0x1b, 0x68, 0x98, 0x47, 0x4d, 0x23, 0x02, 0x26, 0x00, 0x25, 0x01, 0x24, 0x08, 0xa8, 0x8d, 0xf8, 0x20, 0x30, 0x8d, 0xf8, 0x21, 0x60, 0x8d, 0xf8, 0x22, 0x50, 0x8d, 0xf8, 0x23, 0x40, 0x02, 0xf0, 0x91, 0xfb, 0x4a, 0x23, 0x08, 0xa8, 0x8d, 0xf8, 0x20, 0x30, 0x8d, 0xf8, 0x21, 0x60, 0x8d, 0xf8, 0x22, 0x50, 0x8d, 0xf8, 0x23, 0x40, 0x02, 0xf0, 0x85, 0xfb, 0x4b, 0x23, 0x08, 0xa8, 0x8d, 0xf8, 0x20, 0x30, 0x8d, 0xf8, 0x21, 0x60, 0x8d, 0xf8, 0x22, 0x50, 0x8d, 0xf8, 0x23, 0x40, 0x02, 0xf0, 0x79, 0xfb, 0xfe, 0xe7, 0x18, 0x14, 0x00, 0x20, 0x41, 0x0d, 0x03, 0x00, 0x30, 0x14, 0x00, 0x20, 0x60, 0x14, 0x00, 0x20, 0x03, 0x01, 0x01, 0x00, 0x00, 0x08, 0x00, 0x80, 0x01, 0x46, 0x58, 0xb1, 0x43, 0x78, 0xee, 0x2b, 0x08, 0xd1, 0x83, 0x88, 0x04, 0x2b, 0x05, 0xd1, 0x43, 0x88, 0x1b, 0xb9, 0x02, 0x4b, 0x03, 0x48, 0x9b, 0x68, 0x18, 0x47, 0x02, 0x20, 0x70, 0x47, 0x54, 0x00, 0x00, 0x20, 0x18, 0x14, 0x00, 0x20, 0x70, 0x47, 0x00, 0x00, 0x30, 0xb5, 0x13, 0x4b, 0x42, 0x01, 0x9c, 0x18, 0x64, 0x8a, 0xac, 0xb1, 0xc4, 0xb2, 0x03, 0xeb, 0x44, 0x14, 0x65, 0x68, 0x24, 0x89, 0x2d, 0x69, 0x2c, 0x42, 0x14, 0xbf, 0x01, 0x24, 0x00, 0x24, 0x8c, 0x42, 0x09, 0xd1, 0x99, 0x5c, 0x09, 0xb9, 0x01, 0x21, 0x99, 0x54, 0x13, 0x44, 0x1a, 0x8a, 0x0a, 0x32, 0x92, 0xb2, 0x1a, 0x82, 0x30, 0xbd, 0x9b, 0x5c, 0x43, 0xb1, 0x04, 0x4b, 0x00, 0x21, 0x99, 0x54, 0xc0, 0xb2, 0x01, 0x21, 0xbd, 0xe8, 0x30, 0x40, 0x01, 0xf0, 0xf3, 0xbc, 0x30, 0xbd, 0x10, 0x01, 0x00, 0x20, 0x38, 0xb5, 0x0a, 0x4a, 0x43, 0x01, 0xd4, 0x18, 0x65, 0x8a, 0x8d, 0x42, 0x0d, 0xd1, 0x00, 0x21, 0x21, 0x82, 0x01, 0x24, 0xd4, 0x54, 0xc0, 0xb2, 0x01, 0xf0, 0xe2, 0xfc, 0x4f, 0xf0, 0x80, 0x42, 0x93, 0x89, 0x9b, 0xb2, 0x43, 0xf0, 0x02, 0x03, 0x93, 0x81, 0x38, 0xbd, 0x10, 0x01, 0x00, 0x20, 0x2d, 0xe9, 0xf0, 0x4f, 0x94, 0x4c, 0x85, 0xb0, 0xe3, 0x68, 0x5a, 0x69, 0xd6, 0x07, 0x00, 0xf1, 0x58, 0x82, 0x5a, 0x69, 0x9f, 0x69, 0x17, 0x40, 0x00, 0xf0, 0x53, 0x82, 0xc7, 0xf3, 0x07, 0x4b, 0x1b, 0xf0, 0x08, 0x0f, 0x57, 0xd0, 0xa1, 0x46, 0x22, 0x69, 0x04, 0xf1, 0x48, 0x08, 0x93, 0x69, 0xd6, 0x69, 0x4f, 0xf0, 0x00, 0x0a, 0x1e, 0x40, 0x36, 0x0c, 0x00, 0x2e, 0x4b, 0xd0, 0xf5, 0x07, 0x41, 0xd5, 0x5f, 0xfa, 0x8a, 0xf1, 0x04, 0xeb, 0x81, 0x03, 0x9b, 0x6c, 0x9a, 0x68, 0x23, 0x69, 0x5d, 0x69, 0x15, 0x40, 0xe8, 0x07, 0x26, 0xd5, 0xd8, 0xf8, 0x00, 0x30, 0x01, 0x25, 0x9d, 0x60, 0x7d, 0x4b, 0xdb, 0x78, 0xab, 0x42, 0x01, 0xbf, 0xd8, 0xf8, 0x00, 0x30, 0x1b, 0x69, 0xc3, 0xf3, 0x12, 0x02, 0xd9, 0xf8, 0xd4, 0x32, 0x04, 0xbf, 0x9b, 0x1a, 0xc9, 0xf8, 0xe4, 0x32, 0x77, 0x4a, 0x75, 0x4b, 0x12, 0x68, 0x18, 0x46, 0x01, 0x93, 0x90, 0x47, 0xe2, 0x78, 0x01, 0x9b, 0x01, 0x2a, 0x09, 0xd1, 0xba, 0xf1, 0x00, 0x0f, 0x06, 0xd1, 0x93, 0xf8, 0xe1, 0x20, 0x05, 0x2a, 0x02, 0xd1, 0x18, 0x46, 0x02, 0xf0, 0x0b, 0xf9, 0xa9, 0x07, 0x42, 0xbf, 0xd8, 0xf8, 0x00, 0x30, 0x02, 0x25, 0x9d, 0x60, 0x2a, 0x07, 0x07, 0xd5, 0x69, 0x4b, 0x67, 0x48, 0x9b, 0x68, 0x98, 0x47, 0xd8, 0xf8, 0x00, 0x30, 0x08, 0x25, 0x9d, 0x60, 0x0a, 0xf1, 0x01, 0x0a, 0x76, 0x08, 0x08, 0xf1, 0x04, 0x08, 0x09, 0xf1, 0x28, 0x09, 0xb1, 0xe7, 0x1b, 0xf0, 0x04, 0x0f, 0x00, 0xf0, 0xc3, 0x80, 0x23, 0x69, 0xdf, 0xf8, 0x7c, 0x81, 0x9a, 0x69, 0xdb, 0x69, 0xa8, 0xf1, 0x18, 0x06, 0x02, 0xea, 0x03, 0x09, 0x1f, 0xfa, 0x89, 0xf9, 0x4f, 0xf0, 0x00, 0x0a, 0xb9, 0xf1, 0x00, 0x0f, 0x00, 0xf0, 0xb2, 0x80, 0x19, 0xf0, 0x01, 0x0f, 0x00, 0xf0, 0xa0, 0x80, 0x21, 0x69, 0x5f, 0xfa, 0x8a, 0xfb, 0x0b, 0x69, 0x4a, 0x6b, 0x04, 0xeb, 0x8b, 0x00, 0x80, 0x69, 0x22, 0xfa, 0x0b, 0xf2, 0xd2, 0x01, 0x80, 0x68, 0xd2, 0xb2, 0x42, 0xea, 0x03, 0x05, 0x05, 0x40, 0xeb, 0x07, 0xdf, 0xf8, 0x2c, 0xc1, 0x20, 0xd5, 0x4b, 0x6b, 0x01, 0x25, 0x05, 0xfa, 0x0a, 0xf2, 0x23, 0xea, 0x02, 0x03, 0x4b, 0x63, 0xd8, 0xf8, 0x00, 0x30, 0x60, 0x46, 0x9d, 0x60, 0x45, 0x4b, 0x59, 0x46, 0x5b, 0x68, 0xcd, 0xf8, 0x04, 0xc0, 0x98, 0x47, 0xdd, 0xf8, 0x04, 0xc0, 0x9c, 0xf8, 0x03, 0x30, 0xab, 0x42, 0x09, 0xd1, 0xba, 0xf1, 0x00, 0x0f, 0x06, 0xd1, 0x9c, 0xf8, 0xe1, 0x30, 0x04, 0x2b, 0x02, 0xd1, 0x60, 0x46, 0x02, 0xf0, 0xa5, 0xf8, 0x28, 0x07, 0x42, 0xbf, 0xd8, 0xf8, 0x00, 0x30, 0x08, 0x25, 0x9d, 0x60, 0xe9, 0x06, 0x42, 0xbf, 0xd8, 0xf8, 0x00, 0x30, 0x10, 0x25, 0x9d, 0x60, 0x6a, 0x06, 0x42, 0xbf, 0xd8, 0xf8, 0x00, 0x30, 0x40, 0x25, 0x9d, 0x60, 0xab, 0x07, 0x42, 0xbf, 0xd8, 0xf8, 0x00, 0x30, 0x02, 0x25, 0x9d, 0x60, 0x2d, 0x06, 0x50, 0xd5, 0xd6, 0xf8, 0x00, 0x31, 0xd6, 0xf8, 0x04, 0x21, 0x9a, 0x1a, 0xd6, 0xf8, 0xf4, 0x30, 0x93, 0x42, 0x28, 0xbf, 0x13, 0x46, 0x03, 0x33, 0x9b, 0x08, 0xd8, 0xf8, 0x00, 0x20, 0x92, 0x69, 0x92, 0xb2, 0x9a, 0x42, 0x3a, 0xd9, 0xd6, 0xf8, 0x04, 0x01, 0xd6, 0xf8, 0x00, 0x31, 0x98, 0x42, 0x34, 0xd2, 0x9b, 0xb3, 0x1b, 0x1a, 0xd6, 0xf8, 0xf4, 0x00, 0xe1, 0x78, 0x98, 0x42, 0x28, 0xbf, 0x18, 0x46, 0xc3, 0x1c, 0x9b, 0x08, 0xd6, 0xf8, 0xf8, 0xe0, 0xb9, 0xb1, 0xd6, 0xf8, 0xf8, 0x10, 0xd6, 0xf8, 0x04, 0x21, 0x01, 0x44, 0xc6, 0xf8, 0xf8, 0x10, 0xd6, 0xf8, 0x00, 0x11, 0x02, 0x44, 0x8a, 0x42, 0xc6, 0xf8, 0x04, 0x21, 0xd8, 0xd3, 0x21, 0x69, 0x96, 0xf8, 0xec, 0x00, 0x4a, 0x6b, 0x01, 0x23, 0x83, 0x40, 0x22, 0xea, 0x03, 0x03, 0x4b, 0x63, 0x0f, 0xe0, 0x0d, 0x4a, 0x85, 0xb2, 0x02, 0xeb, 0x8b, 0x02, 0x03, 0x35, 0xd2, 0xf8, 0xac, 0x20, 0x4f, 0xea, 0xa5, 0x0c, 0x61, 0x45, 0xdc, 0xd0, 0x5e, 0xf8, 0x21, 0x50, 0x01, 0x31, 0x15, 0x60, 0xf8, 0xe7, 0xd8, 0xf8, 0x00, 0x30, 0x80, 0x25, 0x9d, 0x60, 0x0a, 0xf1, 0x01, 0x0a, 0x4f, 0xea, 0x59, 0x09, 0x08, 0xf1, 0x04, 0x08, 0x28, 0x36, 0x4f, 0xe7, 0x18, 0x14, 0x00, 0x20, 0x88, 0x00, 0x00, 0x20, 0x30, 0x14, 0x00, 0x20, 0xfe, 0xb2, 0xb0, 0x07, 0x42, 0xbf, 0xe3, 0x68, 0x02, 0x22, 0x5a, 0x61, 0x00, 0x2f, 0x18, 0xda, 0xa3, 0x7a, 0x94, 0x4a, 0x43, 0xb1, 0xd2, 0xf8, 0xdc, 0x30, 0xd2, 0xf8, 0xdc, 0x20, 0x6f, 0xf3, 0x41, 0x03, 0x6f, 0xf3, 0x00, 0x03, 0x13, 0x60, 0x22, 0x69, 0x8e, 0x48, 0x53, 0x68, 0x23, 0xf0, 0x01, 0x03, 0x53, 0x60, 0x8c, 0x4b, 0x9b, 0x69, 0x98, 0x47, 0xe3, 0x68, 0x4f, 0xf0, 0x00, 0x42, 0x5a, 0x61, 0xc7, 0xf3, 0x07, 0x25, 0x29, 0x07, 0x2f, 0xd5, 0x00, 0x23, 0x8d, 0xf8, 0x0f, 0x30, 0x94, 0xf8, 0xe2, 0x30, 0xdf, 0xf8, 0x0c, 0x82, 0x8d, 0xf8, 0x0f, 0x30, 0x82, 0x4b, 0x40, 0x46, 0x5b, 0x69, 0x98, 0x47, 0xe2, 0x68, 0x23, 0x69, 0x4f, 0xf4, 0x00, 0x61, 0x9b, 0x68, 0x51, 0x61, 0xa2, 0x7a, 0xd2, 0xb1, 0xda, 0x07, 0x18, 0xd5, 0x98, 0xf8, 0xe5, 0x30, 0x01, 0x2b, 0x14, 0xd1, 0x9d, 0xf8, 0x0f, 0x30, 0x03, 0x2b, 0x10, 0xd1, 0xd8, 0xf8, 0xdc, 0x20, 0x13, 0x68, 0x43, 0xf0, 0x01, 0x03, 0x13, 0x60, 0xd8, 0xf8, 0xdc, 0x20, 0x13, 0x68, 0x43, 0xf0, 0x03, 0x03, 0x13, 0x60, 0x72, 0x4a, 0x13, 0x69, 0x43, 0xf0, 0x06, 0x03, 0x13, 0x61, 0x33, 0x07, 0x06, 0xd5, 0x6e, 0x4b, 0x6c, 0x48, 0xdb, 0x68, 0x98, 0x47, 0xe3, 0x68, 0x08, 0x22, 0x5a, 0x61, 0xf6, 0x06, 0x4b, 0xd5, 0xe2, 0x68, 0x68, 0x4e, 0x91, 0x69, 0x21, 0xf0, 0x10, 0x01, 0x91, 0x61, 0x12, 0x6a, 0xc2, 0xf3, 0x43, 0x40, 0x02, 0x28, 0x02, 0xf0, 0x0f, 0x03, 0x14, 0xd0, 0x06, 0x28, 0x37, 0xd1, 0xd6, 0xf8, 0xac, 0x00, 0xc2, 0xf3, 0x0a, 0x12, 0x01, 0x68, 0xc6, 0xf8, 0xac, 0x14, 0x01, 0x68, 0xc6, 0xf8, 0xb0, 0x14, 0x28, 0x21, 0x01, 0xfb, 0x03, 0x63, 0xd3, 0xf8, 0xe4, 0x12, 0x0a, 0x44, 0xc3, 0xf8, 0xe4, 0x22, 0x24, 0xe0, 0x47, 0xf6, 0xf0, 0x70, 0x10, 0x40, 0x00, 0xb3, 0x28, 0x20, 0x00, 0xfb, 0x03, 0x60, 0xc2, 0xf3, 0x0a, 0x12, 0xd0, 0xf8, 0xd8, 0xe2, 0xd6, 0xf8, 0xac, 0x60, 0xd0, 0x1c, 0x80, 0x10, 0x00, 0x21, 0x81, 0x42, 0x05, 0xd0, 0xd6, 0xf8, 0x00, 0xc0, 0x4e, 0xf8, 0x21, 0xc0, 0x01, 0x31, 0xf7, 0xe7, 0x28, 0x21, 0x01, 0xfb, 0x03, 0x43, 0xd3, 0xf8, 0xd8, 0x02, 0xd3, 0xf8, 0xe4, 0x12, 0x10, 0x44, 0x11, 0x44, 0xc3, 0xf8, 0xd8, 0x02, 0xc3, 0xf8, 0xe4, 0x12, 0xe2, 0x68, 0x93, 0x69, 0x43, 0xf0, 0x10, 0x03, 0x93, 0x61, 0xe8, 0x06, 0x36, 0xd5, 0x22, 0x69, 0x00, 0x26, 0x53, 0x68, 0x30, 0x46, 0x23, 0xf0, 0x01, 0x03, 0x53, 0x60, 0x01, 0xf0, 0xcb, 0xfd, 0x33, 0x46, 0x94, 0xf8, 0x01, 0xe0, 0x3e, 0x4a, 0x73, 0x45, 0x07, 0xd2, 0x52, 0xf8, 0x04, 0x0f, 0xff, 0x21, 0x81, 0x60, 0x10, 0x6b, 0x01, 0x33, 0x81, 0x60, 0xf5, 0xe7, 0x23, 0x69, 0x4f, 0xf0, 0xff, 0x32, 0x9a, 0x61, 0x01, 0x22, 0x62, 0xf3, 0x0f, 0x06, 0x62, 0xf3, 0x1f, 0x46, 0x0b, 0x22, 0xde, 0x61, 0x5a, 0x61, 0xc3, 0xf8, 0x84, 0x20, 0x1a, 0x61, 0x21, 0x69, 0x2e, 0x48, 0x4a, 0x64, 0x0b, 0x68, 0x6f, 0xf3, 0x0a, 0x13, 0x0b, 0x60, 0x01, 0xf0, 0x4f, 0xff, 0xe3, 0x68, 0x4f, 0xf4, 0x80, 0x52, 0x5a, 0x61, 0x29, 0x4b, 0x27, 0x48, 0x1b, 0x69, 0x98, 0x47, 0xa9, 0x06, 0x31, 0xd5, 0x23, 0x69, 0xa1, 0x69, 0x9a, 0x68, 0x0b, 0x68, 0xc2, 0xf3, 0x41, 0x02, 0x02, 0x2a, 0x06, 0xbf, 0x03, 0x22, 0x62, 0xf3, 0x0a, 0x03, 0x6f, 0xf3, 0x0a, 0x03, 0x0b, 0x60, 0x22, 0x69, 0x53, 0x68, 0x43, 0xf4, 0x80, 0x73, 0x53, 0x60, 0xe1, 0x68, 0x23, 0x69, 0xca, 0x68, 0x9b, 0x68, 0xc3, 0xf3, 0x41, 0x03, 0x02, 0x2b, 0x0a, 0xd0, 0x03, 0x2b, 0x08, 0xd0, 0x01, 0x2b, 0x06, 0xd0, 0x00, 0x23, 0xa3, 0x70, 0x4f, 0xf4, 0x00, 0x73, 0xa3, 0x80, 0x09, 0x23, 0x04, 0xe0, 0x01, 0x23, 0xa3, 0x70, 0x40, 0x23, 0xa3, 0x80, 0x05, 0x23, 0x63, 0xf3, 0x8d, 0x22, 0xca, 0x60, 0xe3, 0x68, 0x4f, 0xf4, 0x00, 0x52, 0x5a, 0x61, 0xc7, 0xf3, 0x07, 0x47, 0xfa, 0x06, 0x07, 0xd5, 0x0b, 0x4b, 0x09, 0x48, 0xdb, 0x69, 0x98, 0x47, 0xe3, 0x68, 0x4f, 0xf4, 0x80, 0x12, 0x5a, 0x61, 0xbb, 0x06, 0x07, 0xd5, 0x06, 0x4b, 0x04, 0x48, 0x1b, 0x6a, 0x98, 0x47, 0xe3, 0x68, 0x4f, 0xf4, 0x00, 0x12, 0x5a, 0x61, 0x05, 0xb0, 0xbd, 0xe8, 0xf0, 0x8f, 0x18, 0x14, 0x00, 0x20, 0x88, 0x00, 0x00, 0x20, 0x00, 0xed, 0x00, 0xe0, 0x2c, 0x14, 0x00, 0x20, 0x10, 0xb5, 0xef, 0xf3, 0x10, 0x83, 0x72, 0xb6, 0x1d, 0x49, 0xdb, 0x07, 0x0a, 0x68, 0x02, 0xf1, 0x01, 0x02, 0x0a, 0x60, 0x1b, 0x4a, 0x51, 0x68, 0x1b, 0x4a, 0x11, 0x60, 0x00, 0xd4, 0x62, 0xb6, 0x1a, 0x4b, 0x1a, 0x68, 0x12, 0xb1, 0x1a, 0x68, 0x01, 0x3a, 0x1a, 0x60, 0x18, 0x4b, 0x1a, 0x68, 0x1c, 0x46, 0x1a, 0xb1, 0x1a, 0x68, 0x01, 0x3a, 0x1a, 0x60, 0x16, 0xe0, 0x15, 0x4b, 0x1b, 0x78, 0x2b, 0xb9, 0x15, 0x4b, 0x1b, 0x78, 0x13, 0xb9, 0x14, 0x4b, 0x1b, 0x78, 0x1b, 0xb1, 0x01, 0xf0, 0x4b, 0xfe, 0x32, 0x23, 0x08, 0xe0, 0x12, 0x4b, 0x1b, 0x78, 0x13, 0xb9, 0x11, 0x4b, 0x1b, 0x78, 0x1b, 0xb1, 0x01, 0xf0, 0x41, 0xfe, 0x64, 0x23, 0x23, 0x60, 0x0f, 0x4a, 0x13, 0x68, 0x33, 0xb1, 0x01, 0x3b, 0x13, 0x60, 0x1b, 0xb9, 0x00, 0xf0, 0xab, 0xfd, 0x01, 0xf0, 0xe7, 0xf9, 0x10, 0xbd, 0xf0, 0x01, 0x00, 0x20, 0x00, 0x10, 0x00, 0xe0, 0x00, 0x02, 0x00, 0x20, 0xf4, 0x01, 0x00, 0x20, 0xf8, 0x01, 0x00, 0x20, 0xfd, 0x01, 0x00, 0x20, 0xee, 0x01, 0x00, 0x20, 0xed, 0x01, 0x00, 0x20, 0xec, 0x01, 0x00, 0x20, 0xfc, 0x01, 0x00, 0x20, 0x14, 0x02, 0x00, 0x20, 0x70, 0x47, 0x70, 0x47, 0x70, 0x47, 0xfe, 0xe7, 0xfe, 0xe7, 0xfe, 0xe7, 0xfe, 0xe7, 0x70, 0x47, 0x4a, 0xf6, 0xaa, 0x22, 0x01, 0x4b, 0x00, 0x20, 0x1a, 0x60, 0x70, 0x47, 0x00, 0x30, 0x00, 0x40, 0x00, 0xeb, 0x40, 0x00, 0x01, 0x30, 0x0a, 0x5c, 0x0b, 0x18, 0x5b, 0x78, 0x11, 0x01, 0x10, 0x09, 0xc9, 0xb2, 0x1b, 0x09, 0x02, 0xf0, 0x0f, 0x02, 0x0a, 0x43, 0x43, 0xea, 0x03, 0x13, 0x43, 0xea, 0x02, 0x23, 0x40, 0xea, 0x00, 0x10, 0x43, 0xea, 0x00, 0x40, 0x70, 0x47, 0x02, 0x68, 0x0d, 0x4b, 0x13, 0x40, 0xb3, 0xf1, 0x00, 0x5f, 0x14, 0xbf, 0x03, 0x46, 0x00, 0xf5, 0xc2, 0x73, 0x5b, 0xb1, 0x1a, 0x68, 0x82, 0x42, 0x0a, 0xd1, 0x5a, 0x68, 0xb2, 0xf1, 0x01, 0x6f, 0x06, 0xd8, 0x9b, 0x89, 0x06, 0x3b, 0x58, 0x42, 0x58, 0x41, 0x02, 0xe0, 0x18, 0x46, 0x00, 0xe0, 0x00, 0x20, 0xc0, 0xb2, 0x70, 0x47, 0x00, 0xbf, 0x00, 0x00, 0xf1, 0x2f, 0x03, 0x46, 0x10, 0xb5, 0x08, 0x4a, 0x02, 0xeb, 0x43, 0x11, 0x0c, 0x8a, 0xa4, 0xb2, 0x43, 0xb9, 0x53, 0x8e, 0x33, 0xb1, 0x01, 0x20, 0xff, 0xf7, 0xf3, 0xff, 0xa0, 0x42, 0x4f, 0xf0, 0x01, 0x03, 0xf0, 0xd8, 0x20, 0x46, 0x10, 0xbd, 0x00, 0xbf, 0x10, 0x01, 0x00, 0x20, 0x10, 0xb5, 0x07, 0x4b, 0x42, 0x01, 0x9c, 0x5c, 0xe4, 0xb2, 0x30, 0xb9, 0x5b, 0x8e, 0x23, 0xb1, 0x01, 0x20, 0xff, 0xf7, 0xf5, 0xff, 0x20, 0x43, 0xc4, 0xb2, 0x20, 0x46, 0x10, 0xbd, 0x00, 0xbf, 0x10, 0x01, 0x00, 0x20, 0x10, 0xb5, 0x00, 0x20, 0x0d, 0x4c, 0x01, 0x46, 0xff, 0xf7, 0x8a, 0xfc, 0x94, 0xf8, 0x3c, 0x10, 0x01, 0x20, 0xa1, 0xf1, 0x08, 0x03, 0x59, 0x42, 0x59, 0x41, 0xff, 0xf7, 0x81, 0xfc, 0x23, 0x78, 0x94, 0xf8, 0x20, 0x00, 0x18, 0x18, 0x01, 0xbf, 0x4f, 0xf0, 0x80, 0x42, 0x93, 0x89, 0x23, 0xf0, 0x02, 0x03, 0x1b, 0x04, 0x04, 0xbf, 0x1b, 0x0c, 0x93, 0x81, 0x10, 0xbd, 0x10, 0x01, 0x00, 0x20, 0x4f, 0xf0, 0x80, 0x43, 0x19, 0x8a, 0x9a, 0x89, 0x89, 0x07, 0x92, 0xb2, 0x06, 0xd5, 0x92, 0x07, 0x04, 0xd5, 0x4f, 0xf6, 0xfd, 0x72, 0x1a, 0x82, 0xff, 0xf7, 0xd2, 0xbf, 0x70, 0x47, 0x00, 0x00, 0x10, 0xb5, 0x0a, 0x4b, 0x04, 0x46, 0x1a, 0x68, 0x59, 0x69, 0x08, 0x42, 0x0c, 0xd0, 0x10, 0x42, 0x0a, 0xd0, 0x21, 0x46, 0x58, 0x61, 0x00, 0x20, 0xff, 0xf7, 0x7c, 0xfc, 0x21, 0x46, 0xbd, 0xe8, 0x10, 0x40, 0x01, 0x20, 0xff, 0xf7, 0x76, 0xbc, 0x10, 0xbd, 0x00, 0xbf, 0x00, 0x3c, 0x01, 0x40, 0x01, 0xf0, 0x2e, 0xbc, 0x10, 0xb5, 0x0f, 0x4c, 0xa3, 0x7a, 0xb3, 0xb1, 0x0e, 0x4a, 0x13, 0x68, 0x23, 0xf0, 0x06, 0x03, 0x13, 0x60, 0x01, 0xf0, 0x0b, 0xfb, 0xa3, 0x7a, 0x6b, 0xb1, 0x23, 0x69, 0x9b, 0x68, 0xdb, 0x07, 0x41, 0xbf, 0xd4, 0xf8, 0xdc, 0x30, 0xd4, 0xf8, 0xdc, 0x20, 0x6f, 0xf3, 0x41, 0x03, 0x6f, 0xf3, 0x00, 0x03, 0x48, 0xbf, 0x13, 0x60, 0x04, 0x4b, 0x4f, 0xf4, 0x80, 0x12, 0x5a, 0x61, 0x10, 0xbd, 0x18, 0x14, 0x00, 0x20, 0x10, 0xed, 0x00, 0xe0, 0x00, 0x3c, 0x01, 0x40, 0x38, 0xb5, 0x04, 0x46, 0x00, 0x29, 0x39, 0xd1, 0x90, 0xf8, 0xe1, 0x30, 0x03, 0x2b, 0x3e, 0xd1, 0xd0, 0xf8, 0xe8, 0x22, 0xd0, 0xf8, 0xd4, 0x32, 0x9a, 0x42, 0x14, 0xd9, 0xc1, 0x78, 0xd2, 0x1a, 0x01, 0x29, 0x08, 0xbf, 0xd0, 0xf8, 0xd8, 0x12, 0xc0, 0xf8, 0xe8, 0x22, 0x04, 0xbf, 0xc9, 0x18, 0xc0, 0xf8, 0xd8, 0x12, 0x9a, 0x42, 0x28, 0xbf, 0x1a, 0x46, 0xd0, 0xf8, 0xd8, 0x12, 0x92, 0xb2, 0x01, 0xf0, 0xb5, 0xfc, 0x23, 0xe0, 0xd0, 0xf8, 0xc8, 0x34, 0x9b, 0xb1, 0xdb, 0x69, 0x8b, 0xb1, 0x90, 0xf8, 0xe2, 0x20, 0x03, 0x2a, 0x0d, 0xd1, 0x08, 0x46, 0x01, 0x21, 0x98, 0x47, 0x48, 0xb1, 0xd4, 0xf8, 0xc4, 0x34, 0x1b, 0x69, 0x2b, 0xb1, 0x94, 0xf8, 0xe2, 0x20, 0x03, 0x2a, 0x01, 0xd1, 0x20, 0x46, 0x98, 0x47, 0x20, 0x46, 0x00, 0xf0, 0xa1, 0xfc, 0x08, 0xe0, 0xd0, 0xf8, 0xc4, 0x34, 0x9b, 0x69, 0x23, 0xb1, 0x90, 0xf8, 0xe2, 0x20, 0x03, 0x2a, 0x00, 0xd1, 0x98, 0x47, 0x00, 0x20, 0x38, 0xbd, 0x00, 0x00, 0xf0, 0xb5, 0x90, 0xf8, 0xaf, 0x24, 0x90, 0xf8, 0xae, 0x34, 0x90, 0xf8, 0xb1, 0x54, 0x03, 0xeb, 0x02, 0x23, 0x90, 0xf8, 0xb0, 0x24, 0x90, 0xf8, 0xb3, 0x74, 0x02, 0xeb, 0x05, 0x25, 0x90, 0xf8, 0xb2, 0x24, 0x90, 0xf8, 0xac, 0x14, 0x02, 0xeb, 0x07, 0x22, 0x01, 0x27, 0x90, 0xf8, 0xad, 0x64, 0x80, 0xf8, 0xe1, 0x70, 0x01, 0xf0, 0x1f, 0x07, 0x85, 0xb0, 0x92, 0xb2, 0x9b, 0xb2, 0xad, 0xb2, 0x01, 0x2f, 0x04, 0x46, 0x8d, 0xf8, 0x08, 0x10, 0x8d, 0xf8, 0x09, 0x60, 0xad, 0xf8, 0x0a, 0x30, 0xad, 0xf8, 0x0c, 0x50, 0xad, 0xf8, 0x0e, 0x20, 0xc0, 0xf8, 0x10, 0x21, 0x00, 0xf0, 0x73, 0x81, 0x03, 0xd3, 0x02, 0x2f, 0x00, 0xf0, 0x82, 0x81, 0xeb, 0xe1, 0x01, 0xf0, 0x60, 0x01, 0x40, 0x29, 0x16, 0xd1, 0xd0, 0xf8, 0xc8, 0x34, 0x00, 0x2b, 0x00, 0xf0, 0xe7, 0x81, 0xdb, 0x69, 0x00, 0x2b, 0x00, 0xf0, 0xe3, 0x81, 0x02, 0xa8, 0x00, 0x21, 0x98, 0x47, 0xbd, 0xf8, 0x0e, 0x30, 0x1b, 0xb9, 0x00, 0x28, 0x40, 0xf0, 0x5f, 0x81, 0xe6, 0xe0, 0x00, 0x28, 0x00, 0xf0, 0xd6, 0x81, 0x59, 0xe1, 0x09, 0x2e, 0x00, 0xf2, 0x57, 0x81, 0xdf, 0xe8, 0x16, 0xf0, 0x06, 0x01, 0x44, 0x01, 0x55, 0x01, 0x16, 0x01, 0x55, 0x01, 0xa9, 0x00, 0x0a, 0x00, 0x55, 0x01, 0xf9, 0x00, 0xc7, 0x00, 0x1a, 0x0a, 0x01, 0x3a, 0x06, 0x2a, 0x00, 0xf2, 0x46, 0x81, 0xdf, 0xe8, 0x12, 0xf0, 0x07, 0x00, 0x19, 0x00, 0x33, 0x00, 0x44, 0x01, 0x44, 0x01, 0x65, 0x00, 0x7a, 0x00, 0xd0, 0xf8, 0xcc, 0x34, 0x0d, 0xf1, 0x06, 0x01, 0x1b, 0x68, 0x80, 0x78, 0x98, 0x47, 0xbd, 0xf8, 0x0e, 0x30, 0x01, 0x46, 0x40, 0x2b, 0x03, 0xd0, 0x94, 0xf8, 0xe2, 0x30, 0x01, 0x2b, 0x6f, 0xd1, 0x08, 0x23, 0x5d, 0xe0, 0xd0, 0xf8, 0xc4, 0x24, 0x0d, 0xf1, 0x06, 0x01, 0xd8, 0xb2, 0x92, 0x6a, 0x90, 0x47, 0xa3, 0x78, 0x01, 0x46, 0x01, 0x2b, 0x09, 0xd1, 0x20, 0x7a, 0x01, 0x28, 0x06, 0xd1, 0xd4, 0xf8, 0xc4, 0x34, 0x0d, 0xf1, 0x06, 0x01, 0xdb, 0x6a, 0x98, 0x47, 0x01, 0x46, 0x02, 0x23, 0x4b, 0x70, 0xc4, 0xf8, 0xd0, 0x14, 0x53, 0xe0, 0xd9, 0xb2, 0x03, 0x29, 0x80, 0x78, 0x15, 0xd0, 0x06, 0xd8, 0x01, 0x29, 0xd4, 0xf8, 0xcc, 0x34, 0x08, 0xd0, 0x0d, 0xd8, 0x5b, 0x68, 0x06, 0xe0, 0x05, 0x29, 0x13, 0xd0, 0x0e, 0xd3, 0xee, 0x29, 0x14, 0xd0, 0x18, 0xe0, 0x9b, 0x68, 0x0d, 0xf1, 0x06, 0x01, 0x98, 0x47, 0x01, 0x46, 0x3b, 0xe0, 0xdb, 0x68, 0xf8, 0xe7, 0xd4, 0xf8, 0xcc, 0x34, 0x1b, 0x69, 0xf4, 0xe7, 0xd4, 0xf8, 0xcc, 0x34, 0x5b, 0x69, 0xf0, 0xe7, 0xd4, 0xf8, 0xcc, 0x34, 0x9b, 0x69, 0xec, 0xe7, 0xd4, 0xf8, 0xcc, 0x34, 0xdb, 0x69, 0x00, 0x2b, 0xe7, 0xd1, 0xd4, 0xf8, 0xc4, 0x34, 0x0d, 0xf1, 0x06, 0x02, 0x1b, 0x6b, 0x98, 0x47, 0xe3, 0xe7, 0x80, 0x78, 0x00, 0x28, 0x40, 0xf0, 0xdb, 0x80, 0xd4, 0xf8, 0xc4, 0x34, 0x0d, 0xf1, 0x06, 0x01, 0x9b, 0x6a, 0x98, 0x47, 0xa9, 0x49, 0x83, 0x7b, 0x0b, 0x71, 0xc3, 0x7b, 0x4b, 0x71, 0x03, 0x7c, 0x8b, 0x71, 0x0a, 0x23, 0xad, 0xf8, 0x06, 0x30, 0x0c, 0xe0, 0x80, 0x78, 0x00, 0x28, 0x40, 0xf0, 0xc6, 0x80, 0xd4, 0xf8, 0xc4, 0x34, 0x0d, 0xf1, 0x06, 0x01, 0xdb, 0x6a, 0x98, 0x47, 0x01, 0x46, 0x07, 0x23, 0x43, 0x70, 0xbd, 0xf8, 0x06, 0x30, 0x00, 0x2b, 0x00, 0xf0, 0x33, 0x81, 0xbd, 0xf8, 0x0e, 0x20, 0x00, 0x2a, 0x00, 0xf0, 0x2e, 0x81, 0x9a, 0x42, 0x28, 0xbf, 0x1a, 0x46, 0x20, 0x46, 0xad, 0xf8, 0x06, 0x20, 0x1b, 0xe1, 0x00, 0x2d, 0x40, 0xf0, 0xa9, 0x80, 0x00, 0x2a, 0x40, 0xf0, 0xa6, 0x80, 0x03, 0xf0, 0x7f, 0x05, 0x90, 0xf8, 0xe2, 0x30, 0x03, 0x2b, 0x00, 0xf0, 0x9f, 0x80, 0x01, 0x69, 0x80, 0xf8, 0xe4, 0x50, 0x0b, 0x68, 0x65, 0xf3, 0x0a, 0x12, 0x1a, 0x43, 0x0a, 0x60, 0x00, 0xf0, 0x7f, 0xfb, 0x0d, 0xb1, 0x02, 0x23, 0x00, 0xe0, 0x01, 0x23, 0x84, 0xf8, 0xe2, 0x30, 0x08, 0xe1, 0xd9, 0xb2, 0x86, 0x4d, 0x01, 0x29, 0x29, 0x70, 0x00, 0xf2, 0x88, 0x80, 0x90, 0xf8, 0xe2, 0x30, 0x02, 0x2b, 0x02, 0xd0, 0x03, 0x2b, 0x0e, 0xd0, 0x80, 0xe0, 0x41, 0xb1, 0x01, 0x21, 0x03, 0x23, 0x80, 0xf8, 0xe0, 0x10, 0x80, 0xf8, 0xe2, 0x30, 0x20, 0x46, 0x00, 0xf0, 0x11, 0xfe, 0x20, 0x46, 0x00, 0xf0, 0x5e, 0xfb, 0xed, 0xe0, 0x49, 0xb9, 0x02, 0x23, 0x80, 0xf8, 0xe2, 0x30, 0xd0, 0xf8, 0xc4, 0x34, 0x80, 0xf8, 0xe0, 0x10, 0x5b, 0x68, 0x98, 0x47, 0xf0, 0xe7, 0x90, 0xf8, 0xe0, 0x10, 0x01, 0x29, 0xec, 0xd0, 0xd0, 0xf8, 0xc4, 0x34, 0x5b, 0x68, 0x98, 0x47, 0x29, 0x78, 0x84, 0xf8, 0xe0, 0x10, 0xe1, 0xe7, 0x01, 0x2a, 0x59, 0xd1, 0x90, 0xf8, 0xe2, 0x30, 0x02, 0x2b, 0x04, 0xd0, 0x03, 0x2b, 0x53, 0xd1, 0x00, 0xf1, 0xe0, 0x01, 0xc0, 0xe0, 0x69, 0x49, 0xbe, 0xe0, 0x90, 0xf8, 0xe2, 0x30, 0x02, 0x3b, 0x01, 0x2b, 0x49, 0xd8, 0x66, 0x4b, 0x01, 0x22, 0x1a, 0x60, 0xd0, 0xf8, 0xe8, 0x20, 0x0a, 0xb1, 0x03, 0x22, 0x1a, 0x60, 0x20, 0x46, 0x62, 0x49, 0xad, 0xe0, 0x01, 0x2b, 0x08, 0xd1, 0xc4, 0xf8, 0xe8, 0x30, 0xd4, 0xf8, 0xc4, 0x34, 0x20, 0x46, 0x9b, 0x68, 0x02, 0xa9, 0x98, 0x47, 0xbc, 0xe7, 0x02, 0x2b, 0x40, 0xf0, 0xac, 0x80, 0x15, 0xf0, 0xff, 0x0f, 0x40, 0xf0, 0xa8, 0x80, 0x03, 0x69, 0x2d, 0x0a, 0x01, 0x3d, 0x5b, 0x68, 0x04, 0x2d, 0x0f, 0xd8, 0xdf, 0xe8, 0x05, 0xf0, 0x03, 0x05, 0x07, 0x09, 0x0b, 0x00, 0x01, 0x22, 0x06, 0xe0, 0x02, 0x22, 0x04, 0xe0, 0x03, 0x22, 0x02, 0xe0, 0x04, 0x22, 0x00, 0xe0, 0x05, 0x22, 0x62, 0xf3, 0x06, 0x13, 0x4e, 0x4a, 0x13, 0x60, 0x01, 0x23, 0x84, 0xf8, 0xe6, 0x30, 0x99, 0xe7, 0x90, 0xf8, 0xe2, 0x20, 0x02, 0x3a, 0x01, 0x2a, 0x0b, 0xd8, 0x01, 0x2b, 0x40, 0xf0, 0x84, 0x80, 0x00, 0x23, 0xc9, 0xe7, 0x90, 0xf8, 0xe2, 0x30, 0x03, 0x2b, 0x75, 0xd1, 0xed, 0xb2, 0x0a, 0x2d, 0x01, 0xd9, 0x20, 0x46, 0x70, 0xe0, 0xd0, 0xf8, 0xc4, 0x34, 0x02, 0xa9, 0x9b, 0x68, 0x98, 0x47, 0xbd, 0xf8, 0x0e, 0x30, 0x00, 0x2b, 0x6f, 0xd1, 0x7c, 0xe7, 0x01, 0x2e, 0xe9, 0xb2, 0x0f, 0xd0, 0x3b, 0xd3, 0x03, 0x2e, 0x68, 0xd1, 0x90, 0xf8, 0xe2, 0x20, 0x02, 0x2a, 0x3c, 0xd0, 0x03, 0x2a, 0x5a, 0xd1, 0x00, 0x2b, 0xaa, 0xd1, 0x4a, 0x06, 0xa8, 0xd0, 0x01, 0xf0, 0x5f, 0xfb, 0xa5, 0xe7, 0x90, 0xf8, 0xe2, 0x20, 0x02, 0x2a, 0x2f, 0xd0, 0x03, 0x2a, 0x4d, 0xd1, 0x00, 0x2b, 0x53, 0xd1, 0x11, 0xf0, 0x7f, 0x02, 0x3f, 0xf4, 0x5e, 0xaf, 0x28, 0x23, 0x11, 0xf0, 0x80, 0x0f, 0x15, 0xbf, 0x03, 0xfb, 0x02, 0x03, 0x03, 0xfb, 0x01, 0x03, 0xec, 0x33, 0x03, 0xf5, 0x33, 0x73, 0x00, 0x20, 0xc9, 0x09, 0x1a, 0x70, 0x98, 0x70, 0x59, 0x70, 0x04, 0xeb, 0x82, 0x02, 0x09, 0xb1, 0x91, 0x69, 0x00, 0xe0, 0x91, 0x6c, 0xdb, 0x78, 0x0a, 0x68, 0x02, 0x3b, 0x6f, 0xf3, 0x55, 0x52, 0x01, 0x2b, 0x98, 0xbf, 0x42, 0xf0, 0x80, 0x52, 0x0a, 0x60, 0x78, 0xe7, 0x90, 0xf8, 0xe2, 0x30, 0x02, 0x2b, 0x02, 0xd0, 0x03, 0x2b, 0x03, 0xd0, 0x1f, 0xe0, 0x4b, 0x06, 0x25, 0xd0, 0x22, 0xe0, 0x15, 0xf0, 0x80, 0x0f, 0x4f, 0xf0, 0x28, 0x00, 0x16, 0x4a, 0x0d, 0xd0, 0x01, 0xf0, 0x7f, 0x03, 0x00, 0xfb, 0x03, 0x41, 0x91, 0xf8, 0xee, 0x30, 0x0b, 0xb1, 0x01, 0x23, 0x00, 0xe0, 0x00, 0x23, 0x13, 0x60, 0x20, 0x46, 0x0f, 0x49, 0x04, 0xe0, 0x00, 0xfb, 0x01, 0x41, 0x91, 0xf8, 0xce, 0x32, 0xf2, 0xe7, 0x02, 0x22, 0x00, 0xf0, 0x86, 0xfa, 0x07, 0xe0, 0x02, 0xa9, 0x00, 0xf0, 0x8f, 0xfa, 0x03, 0xe0, 0x01, 0xf0, 0x80, 0x01, 0x01, 0xf0, 0x02, 0xfb, 0x00, 0x20, 0x05, 0xb0, 0xf0, 0xbd, 0xb4, 0x00, 0x00, 0x20, 0x08, 0x02, 0x00, 0x20, 0x10, 0x02, 0x00, 0x20, 0x04, 0x02, 0x00, 0x20, 0x1c, 0x02, 0x00, 0x20, 0x0c, 0x02, 0x00, 0x20, 0x78, 0x23, 0x58, 0x43, 0x07, 0x23, 0xb0, 0xfb, 0xf3, 0xf0, 0x00, 0x23, 0x01, 0x33, 0x83, 0x42, 0xfc, 0xd9, 0x70, 0x47, 0x38, 0xb5, 0x12, 0x4b, 0x05, 0x46, 0x5a, 0x69, 0x11, 0x4c, 0xd2, 0x07, 0x41, 0xbf, 0x11, 0x4a, 0x9a, 0x60, 0x02, 0xf1, 0x44, 0x32, 0x9a, 0x60, 0xf3, 0x22, 0xda, 0x60, 0x01, 0xf0, 0x40, 0xfc, 0x08, 0x28, 0x08, 0xbf, 0x20, 0x88, 0x0c, 0x4a, 0x02, 0xbf, 0x28, 0x43, 0x80, 0xb2, 0x20, 0x80, 0x13, 0x78, 0x43, 0xf0, 0x02, 0x03, 0x13, 0x70, 0x01, 0xf0, 0x32, 0xfc, 0x03, 0x4a, 0x53, 0x69, 0x43, 0xf0, 0x01, 0x03, 0x53, 0x61, 0x23, 0x88, 0x38, 0xbd, 0x00, 0xbf, 0x00, 0x3c, 0x02, 0x40, 0x16, 0x3c, 0x02, 0x40, 0x3b, 0x2a, 0x19, 0x08, 0x14, 0x3c, 0x02, 0x40, 0x1f, 0xb5, 0x04, 0x46, 0x40, 0xf6, 0x24, 0x30, 0x01, 0xf0, 0x3c, 0xfe, 0x40, 0xf6, 0xac, 0x72, 0x01, 0x88, 0x03, 0x46, 0x91, 0x42, 0x0a, 0xd1, 0xd9, 0x68, 0xda, 0x78, 0x80, 0x78, 0x00, 0x91, 0x59, 0x7c, 0x01, 0x91, 0x19, 0x7c, 0x02, 0x91, 0x59, 0x68, 0x9b, 0x68, 0x09, 0xe0, 0x4f, 0xf4, 0x00, 0x21, 0x04, 0x22, 0x0e, 0x23, 0x00, 0x20, 0x8d, 0xe8, 0x0e, 0x00, 0x02, 0x46, 0x02, 0x49, 0x02, 0x4b, 0xa0, 0x47, 0x04, 0xb0, 0x10, 0xbd, 0x00, 0x00, 0x08, 0x08, 0x00, 0x00, 0x02, 0x08, 0x2d, 0xe9, 0xf0, 0x4f, 0x89, 0xb0, 0x9d, 0xf8, 0x4c, 0x40, 0x12, 0x9e, 0x01, 0x94, 0x9d, 0xf8, 0x50, 0x40, 0x00, 0x96, 0x02, 0x94, 0x05, 0x90, 0x88, 0x46, 0x06, 0x92, 0x1d, 0x46, 0x00, 0xf0, 0x07, 0xfd, 0x07, 0x46, 0x00, 0x28, 0x00, 0xf0, 0x84, 0x80, 0x00, 0x2e, 0x00, 0xf0, 0x8b, 0x80, 0x06, 0x9b, 0x00, 0x2b, 0x7d, 0xd1, 0x28, 0x46, 0x00, 0xf0, 0xc8, 0xfd, 0x01, 0x30, 0x80, 0xb2, 0x04, 0x28, 0x95, 0xbf, 0x42, 0x4b, 0x40, 0x04, 0x53, 0xf8, 0x20, 0x40, 0x00, 0xf1, 0xff, 0x64, 0x64, 0x1b, 0xb4, 0x42, 0x28, 0xbf, 0x34, 0x46, 0xb5, 0xf1, 0x00, 0x6f, 0x04, 0xeb, 0x05, 0x0a, 0x0a, 0xf1, 0xff, 0x3b, 0x65, 0xd3, 0xbb, 0xf1, 0x01, 0x6f, 0x62, 0xd8, 0x28, 0x46, 0x00, 0xf0, 0xad, 0xfd, 0x38, 0x4b, 0x1b, 0x5c, 0x58, 0x2b, 0x04, 0x93, 0x5a, 0xd8, 0xbb, 0xf1, 0x01, 0x6f, 0x08, 0xd9, 0x01, 0xf0, 0x47, 0xfc, 0xc4, 0xf3, 0x10, 0x02, 0x63, 0x0c, 0x1a, 0xb3, 0x03, 0xf1, 0x01, 0x0b, 0x21, 0xe0, 0x01, 0x22, 0x02, 0xfa, 0x00, 0xf3, 0x1f, 0xfa, 0x83, 0xf9, 0x58, 0x46, 0x07, 0x92, 0x00, 0xf0, 0x93, 0xfd, 0xb9, 0xf1, 0x00, 0x0f, 0xea, 0xd0, 0x07, 0x9a, 0x82, 0x40, 0x52, 0x00, 0x1f, 0xfa, 0x82, 0xfb, 0x19, 0xea, 0x0b, 0x0f, 0xe2, 0xd1, 0x26, 0x49, 0x09, 0x88, 0x19, 0xea, 0x01, 0x0f, 0x02, 0xd1, 0x48, 0x46, 0xff, 0xf7, 0x44, 0xff, 0x4f, 0xea, 0x49, 0x03, 0x1f, 0xfa, 0x83, 0xf9, 0xef, 0xe7, 0x9b, 0x46, 0x20, 0x4a, 0xf3, 0x21, 0xd1, 0x60, 0x00, 0x22, 0x5a, 0x45, 0x0b, 0xd0, 0x04, 0x9b, 0x02, 0x21, 0x03, 0xeb, 0xc2, 0x00, 0x07, 0x92, 0x01, 0xf0, 0xd3, 0xfb, 0x08, 0x28, 0x1d, 0xd1, 0x07, 0x9a, 0x01, 0x32, 0xf1, 0xe7, 0x01, 0xf0, 0x02, 0xfc, 0xc3, 0x46, 0x01, 0xf0, 0x07, 0xfc, 0x04, 0xeb, 0x08, 0x09, 0xc8, 0xeb, 0x05, 0x00, 0xcb, 0x45, 0x58, 0x44, 0x04, 0xd2, 0x05, 0x9b, 0x73, 0xb9, 0xdb, 0xf8, 0x00, 0x10, 0x0c, 0xe0, 0x01, 0x25, 0x00, 0xe0, 0x00, 0x25, 0x01, 0xf0, 0xee, 0xfb, 0x1d, 0xb1, 0x36, 0x1b, 0x55, 0x46, 0xc8, 0x46, 0x7b, 0xe7, 0x00, 0x27, 0x07, 0xe0, 0x00, 0x21, 0x01, 0xf0, 0x90, 0xfb, 0x08, 0x28, 0xf0, 0xd1, 0x0b, 0xf1, 0x04, 0x0b, 0xe1, 0xe7, 0x38, 0x46, 0x09, 0xb0, 0xbd, 0xe8, 0xf0, 0x8f, 0x00, 0xbf, 0xc4, 0x39, 0x00, 0x08, 0x76, 0x3a, 0x00, 0x08, 0x16, 0x3c, 0x02, 0x40, 0x00, 0x3c, 0x02, 0x40, 0x00, 0x20, 0x70, 0x47, 0x00, 0x20, 0x70, 0x47, 0x00, 0xf1, 0x78, 0x40, 0xb0, 0xf5, 0x80, 0x1f, 0x34, 0xbf, 0x00, 0x20, 0x01, 0x20, 0x70, 0x47, 0x03, 0x46, 0x30, 0xb5, 0x1a, 0x1a, 0x8a, 0x42, 0x07, 0xd2, 0x05, 0x4d, 0x53, 0xf8, 0x04, 0x4b, 0x52, 0x59, 0xa2, 0x42, 0xf6, 0xd0, 0x01, 0x20, 0x30, 0xbd, 0x00, 0x20, 0x30, 0xbd, 0x00, 0xbf, 0x18, 0x03, 0x00, 0x20, 0x70, 0x47, 0x00, 0x20, 0x70, 0x47, 0x00, 0x20, 0x70, 0x47, 0x00, 0x00, 0x24, 0x23, 0x0b, 0x80, 0x00, 0x48, 0x70, 0x47, 0xe8, 0x00, 0x00, 0x20, 0x24, 0x23, 0x0b, 0x80, 0x00, 0x48, 0x70, 0x47, 0xbe, 0x00, 0x00, 0x20, 0x00, 0x20, 0x70, 0x47, 0x10, 0xb5, 0x08, 0x4b, 0x1a, 0x68, 0x1c, 0x46, 0x52, 0x68, 0x02, 0xb1, 0x90, 0x47, 0x63, 0x68, 0x5b, 0x68, 0x03, 0xb1, 0x98, 0x47, 0x04, 0x4a, 0x02, 0x23, 0x13, 0x70, 0x03, 0x4a, 0x00, 0x20, 0x13, 0x71, 0x10, 0xbd, 0x78, 0x01, 0x00, 0x20, 0x2c, 0x02, 0x00, 0x20, 0xf0, 0x18, 0x00, 0x20, 0x08, 0xb5, 0xd0, 0xf8, 0xc4, 0x34, 0x5b, 0x6a, 0x98, 0x47, 0x00, 0x20, 0x08, 0xbd, 0x08, 0xb5, 0xd0, 0xf8, 0xc4, 0x34, 0x1b, 0x6a, 0x98, 0x47, 0x00, 0x20, 0x08, 0xbd, 0x08, 0xb5, 0xd0, 0xf8, 0xc4, 0x34, 0xdb, 0x69, 0x03, 0xb1, 0x98, 0x47, 0x00, 0x20, 0x08, 0xbd, 0x08, 0xb5, 0x90, 0xf8, 0xe2, 0x30, 0x80, 0xf8, 0xe3, 0x30, 0x04, 0x23, 0x80, 0xf8, 0xe2, 0x30, 0xd0, 0xf8, 0xc8, 0x34, 0x0b, 0xb1, 0xdb, 0x68, 0x98, 0x47, 0x00, 0x20, 0x08, 0xbd, 0x10, 0xb5, 0xd0, 0xf8, 0xc8, 0x34, 0x04, 0x46, 0x0b, 0xb1, 0x1b, 0x69, 0x98, 0x47, 0x03, 0x23, 0x84, 0xf8, 0xe2, 0x30, 0x00, 0x20, 0x10, 0xbd, 0x00, 0x00, 0x0f, 0x29, 0x08, 0xb5, 0x08, 0xd8, 0x8b, 0x1f, 0x04, 0x49, 0x51, 0xf8, 0x23, 0x00, 0x11, 0x46, 0x01, 0xf0, 0x8e, 0xf8, 0x02, 0x48, 0x08, 0xbd, 0x00, 0x20, 0x08, 0xbd, 0xdc, 0x39, 0x00, 0x08, 0x18, 0x13, 0x00, 0x20, 0x38, 0xb5, 0x04, 0x46, 0x00, 0x29, 0x4f, 0xd1, 0x90, 0xf8, 0xe1, 0x30, 0x02, 0x2b, 0x3f, 0xd1, 0xd0, 0xf8, 0x08, 0x21, 0xd0, 0xf8, 0xf4, 0x30, 0x9a, 0x42, 0x11, 0xd9, 0xc1, 0x78, 0xd2, 0x1a, 0x01, 0x29, 0x08, 0xbf, 0xd0, 0xf8, 0xf8, 0x10, 0xc0, 0xf8, 0x08, 0x21, 0x04, 0xbf, 0x5b, 0x18, 0xc0, 0xf8, 0xf8, 0x30, 0xd4, 0xf8, 0xf8, 0x10, 0x92, 0xb2, 0x01, 0xf0, 0x87, 0xf8, 0x27, 0xe0, 0xd0, 0xf8, 0x0c, 0x21, 0xb2, 0xfb, 0xf3, 0xf5, 0x03, 0xfb, 0x15, 0x25, 0x5d, 0xb9, 0x9a, 0x42, 0x09, 0xd3, 0xd0, 0xf8, 0x10, 0x31, 0x9a, 0x42, 0x05, 0xd2, 0x2a, 0x46, 0x01, 0xf0, 0x76, 0xf8, 0xc4, 0xf8, 0x10, 0x51, 0x14, 0xe0, 0xd4, 0xf8, 0xc4, 0x34, 0xdb, 0x68, 0x2b, 0xb1, 0x94, 0xf8, 0xe2, 0x20, 0x03, 0x2a, 0x01, 0xd1, 0x20, 0x46, 0x98, 0x47, 0x05, 0x23, 0x00, 0x21, 0x84, 0xf8, 0xe1, 0x30, 0x20, 0x46, 0x0a, 0x46, 0x01, 0xf0, 0x76, 0xf8, 0x20, 0x46, 0x01, 0xf0, 0x5c, 0xf9, 0x94, 0xf8, 0xe6, 0x30, 0x01, 0x2b, 0x10, 0xd1, 0x09, 0x4a, 0x23, 0x69, 0x12, 0x68, 0x5a, 0x60, 0x00, 0x23, 0x84, 0xf8, 0xe6, 0x30, 0x08, 0xe0, 0xd0, 0xf8, 0xc4, 0x34, 0x5b, 0x69, 0x23, 0xb1, 0x90, 0xf8, 0xe2, 0x20, 0x03, 0x2a, 0x00, 0xd1, 0x98, 0x47, 0x00, 0x20, 0x38, 0xbd, 0x00, 0xbf, 0x1c, 0x02, 0x00, 0x20, 0xf8, 0xb5, 0x04, 0x46, 0x00, 0x25, 0x40, 0x27, 0x00, 0xf5, 0x33, 0x71, 0x01, 0x26, 0x80, 0xf8, 0xcc, 0x52, 0x80, 0xf8, 0xcd, 0x52, 0xc0, 0xf8, 0xd4, 0x72, 0x80, 0xf8, 0xcf, 0x52, 0x01, 0xf0, 0x52, 0xf9, 0x84, 0xf8, 0xec, 0x50, 0x84, 0xf8, 0xed, 0x60, 0xc4, 0xf8, 0xf4, 0x70, 0x84, 0xf8, 0xef, 0x50, 0xa4, 0xf8, 0xf2, 0x50, 0x20, 0x46, 0x04, 0xf1, 0xec, 0x01, 0x01, 0xf0, 0x43, 0xf9, 0xd4, 0xf8, 0xc8, 0x34, 0x84, 0xf8, 0xe2, 0x60, 0x13, 0xb1, 0x5b, 0x68, 0xa0, 0x78, 0x98, 0x47, 0x00, 0x20, 0xf8, 0xbd, 0x08, 0xb5, 0x05, 0x4b, 0x53, 0xf8, 0x20, 0x30, 0x08, 0x46, 0xdb, 0x69, 0x98, 0x47, 0x00, 0x30, 0x18, 0xbf, 0x01, 0x20, 0x08, 0xbd, 0x00, 0xbf, 0x78, 0x01, 0x00, 0x20, 0x10, 0xb5, 0x06, 0x4b, 0x1a, 0x68, 0x1c, 0x46, 0x92, 0x68, 0x02, 0xb1, 0x90, 0x47, 0x63, 0x68, 0x9b, 0x68, 0x03, 0xb1, 0x98, 0x47, 0x00, 0x20, 0x10, 0xbd, 0x00, 0xbf, 0x78, 0x01, 0x00, 0x20, 0x07, 0x4a, 0x02, 0x23, 0x10, 0xb5, 0x13, 0x70, 0x06, 0x4a, 0x00, 0x24, 0x13, 0x71, 0x06, 0x4b, 0x1c, 0x60, 0x06, 0x4b, 0x1c, 0x60, 0xff, 0xf7, 0xe3, 0xff, 0x20, 0x46, 0x10, 0xbd, 0x00, 0xbf, 0x2c, 0x02, 0x00, 0x20, 0xf0, 0x18, 0x00, 0x20, 0x20, 0x02, 0x00, 0x20, 0x18, 0x02, 0x00, 0x20, 0x10, 0xb5, 0x04, 0x46, 0x04, 0x23, 0x00, 0x21, 0x80, 0xf8, 0xe1, 0x30, 0x0a, 0x46, 0x00, 0xf0, 0xdb, 0xff, 0x20, 0x46, 0x01, 0xf0, 0xd6, 0xf8, 0x00, 0x20, 0x10, 0xbd, 0x03, 0x46, 0x10, 0xb5, 0x02, 0x24, 0xc3, 0xf8, 0x0c, 0x21, 0xc3, 0xf8, 0x08, 0x21, 0x80, 0xf8, 0xe1, 0x40, 0x00, 0xf0, 0xcb, 0xff, 0x00, 0x20, 0x10, 0xbd, 0x10, 0xb5, 0x04, 0x46, 0x80, 0x21, 0x01, 0xf0, 0x73, 0xf8, 0x20, 0x46, 0x00, 0x21, 0x01, 0xf0, 0x6f, 0xf8, 0x20, 0x46, 0xbd, 0xe8, 0x10, 0x40, 0x01, 0xf0, 0xb9, 0xb8, 0x00, 0x00, 0x2d, 0xe9, 0xf0, 0x4f, 0x60, 0x4b, 0x85, 0xb0, 0x1a, 0x78, 0x80, 0x46, 0x04, 0x2a, 0x1f, 0x46, 0x40, 0xf0, 0x9e, 0x80, 0x5d, 0x4e, 0x5e, 0x4d, 0x33, 0x68, 0x01, 0x96, 0x00, 0x2b, 0x4b, 0xd1, 0x5c, 0x4b, 0x1a, 0x78, 0x1a, 0xb9, 0x2b, 0x68, 0x01, 0x2b, 0x3a, 0xd1, 0x87, 0xe0, 0x21, 0x2a, 0x0f, 0xd1, 0x2a, 0x68, 0x05, 0x2a, 0x34, 0xd1, 0xda, 0x78, 0x99, 0x78, 0x12, 0x04, 0x02, 0xeb, 0x01, 0x21, 0x5a, 0x78, 0x1b, 0x79, 0x0a, 0x44, 0x02, 0xeb, 0x03, 0x63, 0x52, 0x4a, 0x13, 0x60, 0x75, 0xe0, 0x41, 0x2a, 0x25, 0xd1, 0x2a, 0x68, 0x05, 0x2a, 0x22, 0xd1, 0xda, 0x78, 0x9c, 0x78, 0x12, 0x04, 0x02, 0xeb, 0x04, 0x22, 0x5c, 0x78, 0x22, 0x44, 0x1c, 0x79, 0x4a, 0x4b, 0x02, 0xeb, 0x04, 0x64, 0x1c, 0x60, 0x49, 0x4b, 0x21, 0x46, 0x1e, 0x68, 0x30, 0x46, 0xff, 0xf7, 0x60, 0xff, 0x78, 0xb9, 0x04, 0xf1, 0x78, 0x43, 0xb3, 0xf5, 0x00, 0x3f, 0x0a, 0xd3, 0x01, 0x2e, 0x08, 0xd8, 0x43, 0x4b, 0x53, 0xf8, 0x26, 0x30, 0xdb, 0x68, 0x1b, 0xb1, 0x20, 0x46, 0x98, 0x47, 0x00, 0x28, 0x4d, 0xd0, 0x00, 0x23, 0x8d, 0xf8, 0x08, 0x30, 0x40, 0x46, 0x01, 0x23, 0x02, 0xa9, 0xad, 0xf8, 0x0e, 0x30, 0xff, 0xf7, 0x96, 0xff, 0x42, 0xe0, 0x01, 0x2b, 0x40, 0xd9, 0x36, 0x4a, 0x03, 0xf5, 0x7f, 0x23, 0x14, 0x68, 0x03, 0xf6, 0xfe, 0x73, 0x04, 0xeb, 0x03, 0x34, 0x33, 0x4b, 0x21, 0x46, 0x1e, 0x68, 0xd5, 0xf8, 0x00, 0xa0, 0x30, 0x46, 0xff, 0xf7, 0x32, 0xff, 0x00, 0x28, 0xe0, 0xd1, 0x04, 0xf1, 0x78, 0x43, 0xb3, 0xf5, 0x00, 0x3f, 0xdb, 0xd3, 0x01, 0x2e, 0xd9, 0xd8, 0x2c, 0x4b, 0x53, 0xf8, 0x26, 0x10, 0x99, 0x46, 0x09, 0x69, 0x00, 0x29, 0xd2, 0xd0, 0x4f, 0xf0, 0x03, 0x0b, 0x59, 0xf8, 0x26, 0x30, 0x20, 0x46, 0x1b, 0x69, 0x51, 0x46, 0x98, 0x47, 0x38, 0xb9, 0x59, 0xf8, 0x26, 0x30, 0x20, 0x46, 0x9b, 0x69, 0x51, 0x46, 0x98, 0x47, 0x50, 0xb9, 0x0f, 0xe0, 0x20, 0x4b, 0x20, 0x46, 0x53, 0xf8, 0x26, 0x30, 0x51, 0x46, 0x1b, 0x69, 0x98, 0x47, 0x00, 0x28, 0xee, 0xd0, 0xb7, 0xe7, 0x0b, 0xf1, 0xff, 0x33, 0x13, 0xf0, 0xff, 0x0b, 0xe1, 0xd1, 0xb1, 0xe7, 0x01, 0x9a, 0x00, 0x23, 0x13, 0x60, 0x17, 0x4a, 0x2b, 0x60, 0x03, 0x23, 0x3b, 0x70, 0x13, 0x71, 0x16, 0xe0, 0x07, 0x2a, 0x14, 0xd1, 0x14, 0x4a, 0x00, 0x21, 0x11, 0x60, 0x14, 0x4a, 0x52, 0x7f, 0x12, 0xf0, 0x04, 0x0f, 0x08, 0xbf, 0x08, 0x21, 0x0f, 0x4a, 0x05, 0xbf, 0x19, 0x70, 0x10, 0x4b, 0x06, 0x21, 0x11, 0x71, 0x0d, 0xbf, 0x4f, 0xf4, 0xfa, 0x72, 0x19, 0x70, 0x11, 0x71, 0x1a, 0x60, 0x00, 0x20, 0x05, 0xb0, 0xbd, 0xe8, 0xf0, 0x8f, 0x00, 0xbf, 0x2c, 0x02, 0x00, 0x20, 0x20, 0x02, 0x00, 0x20, 0x18, 0x02, 0x00, 0x20, 0x18, 0x03, 0x00, 0x20, 0xe4, 0x00, 0x00, 0x20, 0x24, 0x02, 0x00, 0x20, 0x78, 0x01, 0x00, 0x20, 0xf0, 0x18, 0x00, 0x20, 0x28, 0x02, 0x00, 0x20, 0xbe, 0x00, 0x00, 0x20, 0x14, 0x02, 0x00, 0x20, 0x4e, 0xf6, 0xc1, 0x62, 0x2d, 0xe9, 0xf0, 0x43, 0x0b, 0x88, 0x85, 0xb0, 0x93, 0x42, 0x06, 0x46, 0x0d, 0x46, 0x02, 0xd1, 0x8b, 0x88, 0x05, 0x2b, 0x05, 0xe0, 0x4e, 0xf6, 0xc0, 0x62, 0x93, 0x42, 0x1a, 0xd1, 0x8b, 0x88, 0x04, 0x2b, 0x17, 0xd1, 0xab, 0x88, 0x04, 0x2b, 0x02, 0xd1, 0x30, 0x46, 0xa6, 0x49, 0x0f, 0xe0, 0x05, 0x2b, 0x40, 0xf0, 0x83, 0x81, 0xac, 0x78, 0x1c, 0xb9, 0x30, 0x46, 0xa3, 0x49, 0xea, 0x88, 0x72, 0xe1, 0x00, 0x21, 0x01, 0xa8, 0x0a, 0x22, 0x01, 0xf0, 0x96, 0xfb, 0x30, 0x46, 0x01, 0xa9, 0xea, 0x88, 0x86, 0xe0, 0x2c, 0x78, 0x14, 0xf0, 0x60, 0x04, 0x00, 0xf0, 0x4d, 0x81, 0x20, 0x2c, 0x40, 0xf0, 0x6e, 0x81, 0x6c, 0x78, 0x06, 0x2c, 0x00, 0xf2, 0x28, 0x81, 0xdf, 0xe8, 0x14, 0xf0, 0xf7, 0x00, 0x07, 0x00, 0x30, 0x00, 0x93, 0x00, 0xcd, 0x00, 0xde, 0x00, 0xe2, 0x00, 0xea, 0x88, 0x93, 0x4b, 0xc2, 0xb1, 0x19, 0x78, 0x02, 0x29, 0x01, 0xd0, 0x05, 0x29, 0x6f, 0xd1, 0x68, 0x88, 0x90, 0x49, 0xc6, 0xf8, 0xec, 0x22, 0x08, 0x60, 0x8f, 0x49, 0xc6, 0xf8, 0xe8, 0x22, 0x0a, 0x60, 0x03, 0x21, 0x19, 0x70, 0x8d, 0x4b, 0x86, 0xf8, 0xe1, 0x10, 0x19, 0x71, 0x30, 0x46, 0x8c, 0x49, 0x00, 0xf0, 0x99, 0xfe, 0x44, 0xe1, 0x1a, 0x78, 0x05, 0x2a, 0x01, 0xd0, 0x02, 0x2a, 0x56, 0xd1, 0x88, 0x4a, 0x01, 0x21, 0x11, 0x60, 0x06, 0x22, 0x1a, 0x70, 0x84, 0x4b, 0x1a, 0x71, 0x37, 0xe1, 0xb5, 0xf8, 0x06, 0x80, 0x7e, 0x4b, 0xb8, 0xf1, 0x00, 0x0f, 0x56, 0xd0, 0x19, 0x78, 0x7d, 0x4a, 0x02, 0x29, 0xdf, 0xf8, 0xf4, 0x91, 0x01, 0xd0, 0x09, 0x29, 0x45, 0xd1, 0x6f, 0x88, 0xc9, 0xf8, 0x00, 0x80, 0x17, 0x60, 0x79, 0x4a, 0x87, 0xb9, 0xb8, 0xf1, 0x03, 0x0f, 0x78, 0x49, 0x98, 0xbf, 0x09, 0x24, 0x1c, 0x70, 0x21, 0x23, 0x14, 0x71, 0x4b, 0x70, 0x30, 0x46, 0x41, 0x23, 0x03, 0x22, 0x0f, 0x70, 0x8b, 0x70, 0xff, 0xf7, 0x7c, 0xfe, 0xce, 0xe0, 0x01, 0x2f, 0x24, 0xd0, 0x09, 0x21, 0x19, 0x70, 0x71, 0x4b, 0x07, 0xf5, 0x7f, 0x27, 0x1b, 0x68, 0x07, 0xf6, 0xfe, 0x77, 0x03, 0xeb, 0x07, 0x37, 0x6e, 0x4b, 0x11, 0x71, 0x1c, 0x68, 0x39, 0x46, 0x20, 0x46, 0xff, 0xf7, 0x24, 0xfe, 0x58, 0xb9, 0x01, 0x2c, 0x09, 0xd8, 0x6a, 0x4b, 0x53, 0xf8, 0x24, 0x30, 0x5b, 0x69, 0x23, 0xb1, 0x41, 0x46, 0x38, 0x46, 0x98, 0x47, 0x01, 0x46, 0x00, 0xe0, 0x61, 0x49, 0x30, 0x46, 0xb9, 0xf8, 0x00, 0x20, 0xff, 0xf7, 0x55, 0xfe, 0xeb, 0xe0, 0x0f, 0x21, 0x19, 0x70, 0x11, 0x71, 0x30, 0x46, 0x29, 0x46, 0xff, 0xf7, 0x5a, 0xfe, 0xe3, 0xe0, 0x00, 0x24, 0x30, 0x46, 0x29, 0x46, 0xc9, 0xf8, 0x00, 0x40, 0x14, 0x60, 0xff, 0xf7, 0x51, 0xfe, 0xdb, 0xe0, 0x02, 0x22, 0x1a, 0x70, 0x53, 0x4b, 0x44, 0x46, 0x1a, 0x71, 0xd5, 0xe0, 0x4e, 0x4b, 0x1a, 0x78, 0x06, 0x2a, 0x20, 0xd0, 0x07, 0x2a, 0x2b, 0xd0, 0x03, 0x2a, 0x2d, 0xd1, 0x4c, 0x4a, 0x11, 0x68, 0x4c, 0x4a, 0xa1, 0xb1, 0x04, 0x21, 0x19, 0x70, 0x48, 0x4b, 0x11, 0x71, 0x1a, 0x68, 0x4c, 0x49, 0x4b, 0x4b, 0x32, 0xb9, 0x48, 0x48, 0x00, 0x78, 0x41, 0x28, 0x02, 0xd1, 0x08, 0x68, 0x19, 0x68, 0x02, 0xe0, 0x08, 0x68, 0x19, 0x68, 0x01, 0x22, 0x00, 0xf0, 0x21, 0xfe, 0x14, 0xe0, 0x05, 0x21, 0x19, 0x70, 0x11, 0x71, 0x10, 0xe0, 0x40, 0x4a, 0x12, 0x68, 0x01, 0x2a, 0x03, 0xd1, 0x07, 0x22, 0x1a, 0x70, 0x05, 0x22, 0x06, 0xe0, 0x3a, 0xb9, 0x40, 0x4a, 0x52, 0x7f, 0x52, 0x07, 0x03, 0xd5, 0x02, 0x22, 0x1a, 0x70, 0x37, 0x4b, 0x1a, 0x71, 0x30, 0x46, 0x35, 0x49, 0x06, 0x22, 0xab, 0xe7, 0x31, 0x4a, 0x13, 0x78, 0x0a, 0x2b, 0x32, 0x4b, 0x05, 0xd1, 0x02, 0x21, 0x00, 0x24, 0x11, 0x70, 0x1c, 0x70, 0x19, 0x71, 0x90, 0xe0, 0x0a, 0x21, 0x11, 0x70, 0x0e, 0x22, 0x1a, 0x70, 0x19, 0x71, 0x89, 0xe0, 0x30, 0x46, 0x28, 0x49, 0x01, 0x22, 0x96, 0xe7, 0x26, 0x4b, 0x1a, 0x78, 0x91, 0x1e, 0x01, 0x29, 0x04, 0xd9, 0x51, 0x1f, 0x01, 0x29, 0x01, 0xd9, 0x09, 0x2a, 0x7b, 0xd1, 0x02, 0x22, 0x1a, 0x70, 0x23, 0x4b, 0x00, 0x24, 0x1c, 0x70, 0x1a, 0x71, 0x1f, 0x4b, 0x1c, 0x60, 0x1f, 0x4b, 0x1c, 0x60, 0x71, 0xe0, 0x1c, 0x4b, 0x1a, 0x78, 0x91, 0x1e, 0x01, 0x29, 0x04, 0xd9, 0x51, 0x1f, 0x01, 0x29, 0x01, 0xd9, 0x09, 0x2a, 0x08, 0xd1, 0x02, 0x22, 0x1a, 0x70, 0x19, 0x4b, 0x1a, 0x71, 0x16, 0x4a, 0x00, 0x23, 0x13, 0x60, 0x15, 0x4a, 0x13, 0x60, 0x1b, 0x4b, 0x9b, 0x7f, 0x03, 0xf0, 0x10, 0x03, 0x03, 0xf0, 0xff, 0x07, 0x63, 0xb1, 0x30, 0x46, 0x00, 0xf0, 0x38, 0xfe, 0x32, 0x69, 0x40, 0xf6, 0xb8, 0x30, 0x53, 0x68, 0x6f, 0xf3, 0x41, 0x03, 0x53, 0x60, 0xff, 0xf7, 0x45, 0xfb, 0x4a, 0xe0, 0x6b, 0x88, 0x4f, 0xf4, 0x7a, 0x70, 0x58, 0x43, 0xff, 0xf7, 0x3e, 0xfb, 0x3c, 0x46, 0x42, 0xe0, 0x30, 0x46, 0x29, 0x46, 0xff, 0xf7, 0xb3, 0xfd, 0x3a, 0xe0, 0x00, 0xbf, 0xe6, 0x3a, 0x00, 0x08, 0xe4, 0x39, 0x00, 0x08, 0x2c, 0x02, 0x00, 0x20, 0x20, 0x02, 0x00, 0x20, 0x18, 0x02, 0x00, 0x20, 0xf0, 0x18, 0x00, 0x20, 0x18, 0x03, 0x00, 0x20, 0x28, 0x02, 0x00, 0x20, 0xe4, 0x00, 0x00, 0x20, 0x24, 0x02, 0x00, 0x20, 0x78, 0x01, 0x00, 0x20, 0xbe, 0x00, 0x00, 0x20, 0x6b, 0x78, 0x0a, 0x2b, 0x11, 0xd0, 0x0b, 0x2b, 0x15, 0xd0, 0x06, 0x2b, 0x1d, 0xd1, 0x6b, 0x88, 0x1b, 0x0a, 0x21, 0x2b, 0x05, 0xd1, 0xea, 0x88, 0x0e, 0x49, 0x09, 0x2a, 0x28, 0xbf, 0x09, 0x22, 0x01, 0xe0, 0x21, 0x46, 0x22, 0x46, 0x30, 0x46, 0x02, 0xe0, 0x30, 0x46, 0x0a, 0x49, 0x01, 0x22, 0xff, 0xf7, 0x72, 0xfd, 0x09, 0xe0, 0xab, 0x78, 0x01, 0x2b, 0x3f, 0xf6, 0x1c, 0xaf, 0x06, 0x4a, 0x13, 0x60, 0x02, 0xe0, 0x02, 0x24, 0x00, 0xe0, 0x00, 0x24, 0x20, 0x46, 0x05, 0xb0, 0xbd, 0xe8, 0xf0, 0x83, 0x00, 0xbf, 0xd9, 0x00, 0x00, 0x20, 0x24, 0x02, 0x00, 0x20, 0x10, 0xb5, 0x04, 0x46, 0xd0, 0xf8, 0xc4, 0x34, 0x1b, 0x68, 0x98, 0x47, 0xd4, 0xf8, 0xc8, 0x34, 0x0b, 0xb1, 0x9b, 0x68, 0x98, 0x47, 0x00, 0x20, 0x10, 0xbd, 0x00, 0x00, 0xf8, 0xb5, 0x8b, 0x07, 0x07, 0x46, 0x0e, 0x46, 0x01, 0xd0, 0x0a, 0x46, 0x07, 0xe0, 0x00, 0xf0, 0xc3, 0xff, 0x12, 0x4b, 0xf3, 0x22, 0xda, 0x60, 0x08, 0x24, 0x00, 0x25, 0x12, 0xe0, 0x4f, 0xf6, 0xfc, 0x73, 0x33, 0x40, 0x04, 0x33, 0x9a, 0x42, 0xf1, 0xd2, 0x0d, 0x4b, 0xff, 0x21, 0xd1, 0x54, 0x01, 0x32, 0xf4, 0xe7, 0x08, 0x2c, 0x09, 0xd1, 0x09, 0x4b, 0xe9, 0x58, 0x00, 0xf0, 0x50, 0xff, 0x04, 0x46, 0x04, 0x35, 0xb5, 0x42, 0x05, 0xeb, 0x07, 0x00, 0xf3, 0xd3, 0x00, 0xf0, 0x9c, 0xff, 0xb4, 0xf1, 0x08, 0x00, 0x18, 0xbf, 0x01, 0x20, 0xf8, 0xbd, 0x00, 0xbf, 0x00, 0x3c, 0x02, 0x40, 0x18, 0x03, 0x00, 0x20, 0x10, 0xb5, 0x04, 0x46, 0x00, 0xf0, 0x96, 0xff, 0x0e, 0x4b, 0xf3, 0x22, 0xda, 0x60, 0x20, 0x46, 0x00, 0xf0, 0xec, 0xf8, 0x04, 0x46, 0x0c, 0x4b, 0x01, 0x20, 0xa0, 0x40, 0x1b, 0x88, 0x80, 0xb2, 0x18, 0x42, 0x01, 0xd1, 0xff, 0xf7, 0xa6, 0xfa, 0x08, 0x4b, 0x02, 0x21, 0x18, 0x5d, 0x00, 0xf0, 0x43, 0xff, 0x04, 0x46, 0x00, 0xf0, 0x76, 0xff, 0xb4, 0xf1, 0x08, 0x00, 0x18, 0xbf, 0x01, 0x20, 0x10, 0xbd, 0x00, 0xbf, 0x00, 0x3c, 0x02, 0x40, 0x16, 0x3c, 0x02, 0x40, 0x76, 0x3a, 0x00, 0x08, 0x70, 0xb5, 0x04, 0x9d, 0x9d, 0xf8, 0x18, 0x40, 0x00, 0x28, 0x71, 0xd1, 0xb1, 0xf1, 0x00, 0x6f, 0x6e, 0xd3, 0x6e, 0x1e, 0x0e, 0x44, 0xb6, 0xf1, 0x01, 0x6f, 0x69, 0xd8, 0x00, 0x2a, 0x68, 0xd1, 0xb3, 0xf1, 0x00, 0x6f, 0x64, 0xd3, 0x5a, 0x1e, 0x2a, 0x44, 0xb2, 0xf1, 0x01, 0x6f, 0x5f, 0xd8, 0x14, 0xf0, 0x0e, 0x0f, 0x01, 0xd1, 0x01, 0x20, 0x70, 0xbd, 0x08, 0x68, 0x2d, 0x4a, 0x02, 0x40, 0xb2, 0xf1, 0x00, 0x5f, 0x14, 0xbf, 0x0a, 0x46, 0x01, 0xf5, 0xc2, 0x72, 0x12, 0xb1, 0x50, 0x68, 0x12, 0x68, 0x82, 0x1a, 0x14, 0xf0, 0x0a, 0x0f, 0x02, 0xd0, 0x10, 0x1d, 0x85, 0x42, 0x47, 0xd3, 0x0d, 0x68, 0x24, 0x48, 0x28, 0x40, 0xb0, 0xf1, 0x00, 0x5f, 0x14, 0xbf, 0x08, 0x46, 0x01, 0xf5, 0xc2, 0x70, 0x85, 0x7b, 0x01, 0x2d, 0x02, 0xd0, 0x86, 0x89, 0x06, 0x2e, 0x38, 0xd1, 0x66, 0x07, 0x02, 0xd5, 0x00, 0x68, 0x98, 0x42, 0x33, 0xd1, 0x20, 0x07, 0x03, 0xd5, 0x9d, 0xf8, 0x14, 0x30, 0x9d, 0x42, 0x2d, 0xd1, 0xa3, 0x07, 0xce, 0xd5, 0x52, 0xb3, 0x50, 0x58, 0x00, 0xba, 0x16, 0x4b, 0x01, 0x24, 0x9c, 0x60, 0x22, 0xf0, 0x03, 0x04, 0x0c, 0x44, 0xa1, 0x42, 0x05, 0xd0, 0x51, 0xf8, 0x04, 0x5b, 0x95, 0xfa, 0xa5, 0xf5, 0x1d, 0x60, 0xf7, 0xe7, 0x0f, 0x4b, 0x1b, 0x68, 0x93, 0xfa, 0xa3, 0xf3, 0x02, 0xf0, 0x03, 0x02, 0x0a, 0x44, 0x91, 0x42, 0x0e, 0xd0, 0x11, 0xf8, 0x01, 0x4b, 0x63, 0x40, 0x08, 0x24, 0x13, 0xf0, 0x01, 0x0f, 0x4f, 0xea, 0x53, 0x05, 0x16, 0xbf, 0x07, 0x4b, 0x2b, 0x46, 0x6b, 0x40, 0x01, 0x3c, 0xf5, 0xd1, 0xee, 0xe7, 0xdb, 0x43, 0x98, 0x42, 0xa2, 0xd0, 0x00, 0x20, 0x70, 0xbd, 0x00, 0x00, 0xf1, 0x2f, 0x00, 0x30, 0x02, 0x40, 0x20, 0x83, 0xb8, 0xed, 0x4f, 0xf0, 0x80, 0x43, 0xd8, 0x6a, 0x01, 0x30, 0x80, 0xb2, 0x70, 0x47, 0x4f, 0xf0, 0x80, 0x43, 0x9a, 0x6b, 0x02, 0x80, 0xda, 0x6b, 0x42, 0x80, 0x1b, 0x6c, 0x83, 0x80, 0x70, 0x47, 0x00, 0x00, 0x11, 0x4a, 0x18, 0x23, 0x10, 0xb5, 0x03, 0xfb, 0x00, 0x20, 0x83, 0x7d, 0xda, 0x07, 0x19, 0xd5, 0x5b, 0x07, 0x5c, 0xbf, 0x4f, 0xf0, 0x80, 0x43, 0xdb, 0x6a, 0x02, 0x69, 0x58, 0xbf, 0x01, 0x33, 0x80, 0x8a, 0x5c, 0xbf, 0x59, 0x1a, 0x89, 0xb2, 0x08, 0xb9, 0x51, 0x63, 0x10, 0xbd, 0x04, 0x28, 0x01, 0xd1, 0x91, 0x63, 0x10, 0xbd, 0x08, 0x28, 0x01, 0xd1, 0xd1, 0x63, 0x10, 0xbd, 0x0c, 0x28, 0x08, 0xbf, 0x11, 0x64, 0x10, 0xbd, 0x00, 0xbf, 0x50, 0x02, 0x00, 0x20, 0x70, 0xb5, 0x06, 0x46, 0x0d, 0x46, 0x14, 0x46, 0x4f, 0xf0, 0x80, 0x43, 0x98, 0x63, 0xd9, 0x63, 0x06, 0x20, 0x31, 0x46, 0x1a, 0x64, 0xff, 0xf7, 0xcd, 0xff, 0x29, 0x46, 0x07, 0x20, 0xff, 0xf7, 0xc9, 0xff, 0x21, 0x46, 0xbd, 0xe8, 0x70, 0x40, 0x05, 0x20, 0xff, 0xf7, 0xc3, 0xbf, 0x00, 0x00, 0x12, 0x4b, 0x98, 0x42, 0x11, 0xd9, 0x03, 0xf5, 0x80, 0x43, 0x98, 0x42, 0x0f, 0xd9, 0x03, 0xf5, 0x80, 0x43, 0x98, 0x42, 0x0d, 0xd9, 0x03, 0xf5, 0x80, 0x43, 0x98, 0x42, 0x0b, 0xd9, 0x03, 0xf5, 0x80, 0x33, 0x98, 0x42, 0x0b, 0xd8, 0x05, 0x20, 0x06, 0xe0, 0x01, 0x20, 0x04, 0xe0, 0x02, 0x20, 0x02, 0xe0, 0x03, 0x20, 0x00, 0xe0, 0x04, 0x20, 0x01, 0x38, 0x80, 0xb2, 0x70, 0x47, 0x00, 0xf1, 0x77, 0x40, 0x00, 0xf5, 0x7e, 0x00, 0x40, 0x0c, 0x05, 0x30, 0x70, 0x47, 0xff, 0x3f, 0x00, 0x08, 0x02, 0x48, 0x00, 0x21, 0x20, 0x22, 0x01, 0xf0, 0x0e, 0xb8, 0x00, 0xbf, 0x30, 0x02, 0x00, 0x20, 0x07, 0xb5, 0x4d, 0xf2, 0x01, 0x02, 0x0f, 0x4b, 0x4f, 0xf4, 0xa0, 0x44, 0xda, 0x81, 0x1c, 0x81, 0xff, 0xf7, 0xee, 0xff, 0x00, 0x23, 0x01, 0x93, 0x0b, 0x4b, 0x0c, 0x48, 0x01, 0x93, 0x01, 0x9b, 0x28, 0x33, 0x01, 0x93, 0x01, 0x9b, 0x1c, 0x60, 0x00, 0xf0, 0x5e, 0xfc, 0xbf, 0xf3, 0x4f, 0x8f, 0x07, 0x49, 0x08, 0x4b, 0xca, 0x68, 0x02, 0xf4, 0xe0, 0x62, 0x13, 0x43, 0xcb, 0x60, 0xbf, 0xf3, 0x4f, 0x8f, 0xfe, 0xe7, 0x30, 0x02, 0x00, 0x20, 0x50, 0x28, 0x00, 0x40, 0x18, 0x14, 0x00, 0x20, 0x00, 0xed, 0x00, 0xe0, 0x04, 0x00, 0xfa, 0x05, 0x10, 0xb5, 0x0a, 0x48, 0xff, 0xf7, 0x92, 0xf9, 0x4f, 0xf6, 0xff, 0x72, 0x08, 0x4b, 0x04, 0x46, 0x9a, 0x81, 0x30, 0xb1, 0x00, 0x22, 0x5a, 0x81, 0x1a, 0x74, 0x5a, 0x22, 0x5a, 0x74, 0xff, 0xf7, 0xc3, 0xff, 0xff, 0xf7, 0xb9, 0xff, 0x20, 0x46, 0x10, 0xbd, 0x00, 0xbf, 0x45, 0x1b, 0x00, 0x08, 0x30, 0x02, 0x00, 0x20, 0xf0, 0xb5, 0x27, 0x4e, 0x40, 0x01, 0x37, 0x18, 0xbb, 0x7d, 0x4f, 0xf0, 0x0f, 0x0c, 0x03, 0xf0, 0x03, 0x04, 0x03, 0xf0, 0xfc, 0x03, 0x03, 0xf1, 0x80, 0x43, 0x03, 0xf5, 0x9c, 0x33, 0x9d, 0x68, 0xa4, 0x00, 0x0c, 0xfa, 0x04, 0xfc, 0x25, 0xea, 0x0c, 0x05, 0x97, 0xf8, 0x14, 0xe0, 0x9d, 0x60, 0x9d, 0x68, 0x0e, 0xfa, 0x04, 0xf4, 0x2c, 0x43, 0x9c, 0x60, 0x7c, 0x8a, 0x19, 0x4b, 0x5c, 0x61, 0x7d, 0x8a, 0x3c, 0x7f, 0xea, 0x43, 0x19, 0xb3, 0x19, 0x68, 0x10, 0x2c, 0x01, 0xea, 0x02, 0x01, 0x19, 0x60, 0x59, 0x68, 0x01, 0xea, 0x02, 0x01, 0x59, 0x60, 0x19, 0x68, 0x41, 0xea, 0x05, 0x01, 0x19, 0x60, 0x99, 0x68, 0x01, 0xea, 0x02, 0x01, 0x99, 0x60, 0xd9, 0x68, 0x02, 0xea, 0x01, 0x02, 0xda, 0x60, 0x06, 0xd1, 0x9a, 0x68, 0x2a, 0x43, 0x9a, 0x60, 0xda, 0x68, 0x2a, 0x43, 0xda, 0x60, 0x09, 0xe0, 0x04, 0xf1, 0x80, 0x43, 0x03, 0xf5, 0x9e, 0x33, 0x1a, 0x68, 0x2a, 0x43, 0x01, 0xe0, 0x19, 0x68, 0x0a, 0x40, 0x1a, 0x60, 0x30, 0x44, 0x42, 0x8a, 0x02, 0x4b, 0x5a, 0x61, 0xf0, 0xbd, 0x10, 0x01, 0x00, 0x20, 0x00, 0x3c, 0x01, 0x40, 0x10, 0xb5, 0x71, 0xbb, 0x03, 0x8c, 0x63, 0x4c, 0x23, 0xf0, 0x01, 0x03, 0x1b, 0x04, 0x1b, 0x0c, 0x03, 0x84, 0x03, 0x8c, 0x81, 0x88, 0x02, 0x8b, 0xa0, 0x42, 0x22, 0xf0, 0x73, 0x02, 0x4f, 0xea, 0x02, 0x42, 0x4f, 0xea, 0x12, 0x42, 0x9b, 0xb2, 0x89, 0xb2, 0x42, 0xf0, 0x60, 0x02, 0x08, 0xd0, 0x04, 0xf5, 0x80, 0x64, 0xa0, 0x42, 0x04, 0xd0, 0x23, 0xf0, 0x02, 0x03, 0x43, 0xf0, 0x03, 0x03, 0x06, 0xe0, 0x23, 0xf0, 0x0e, 0x03, 0x21, 0xf4, 0x40, 0x71, 0x43, 0xf0, 0x03, 0x03, 0x89, 0xb2, 0x81, 0x80, 0x02, 0x83, 0x00, 0x22, 0x42, 0x63, 0x03, 0x84, 0x03, 0x8b, 0x23, 0xf0, 0x08, 0x03, 0x2f, 0xe0, 0x04, 0x29, 0x31, 0xd1, 0x03, 0x8c, 0x4a, 0x4c, 0x23, 0xf0, 0x10, 0x03, 0x1b, 0x04, 0x1b, 0x0c, 0x03, 0x84, 0x03, 0x8c, 0x81, 0x88, 0x02, 0x8b, 0xa0, 0x42, 0x22, 0xf4, 0xe6, 0x42, 0x4f, 0xea, 0x02, 0x42, 0x4f, 0xea, 0x12, 0x42, 0x9b, 0xb2, 0x89, 0xb2, 0x42, 0xf4, 0xc0, 0x42, 0x08, 0xd0, 0x04, 0xf5, 0x80, 0x64, 0xa0, 0x42, 0x04, 0xd0, 0x23, 0xf0, 0x20, 0x03, 0x43, 0xf0, 0x30, 0x03, 0x06, 0xe0, 0x23, 0xf0, 0xe0, 0x03, 0x21, 0xf4, 0x40, 0x61, 0x43, 0xf0, 0x30, 0x03, 0x89, 0xb2, 0x81, 0x80, 0x02, 0x83, 0x00, 0x22, 0x82, 0x63, 0x03, 0x84, 0x03, 0x8b, 0x23, 0xf4, 0x00, 0x63, 0x1b, 0x04, 0x1b, 0x0c, 0x03, 0x83, 0x5d, 0xe0, 0x08, 0x29, 0x2e, 0xd1, 0x03, 0x8c, 0x30, 0x4c, 0x23, 0xf4, 0x80, 0x73, 0x1b, 0x04, 0x1b, 0x0c, 0x03, 0x84, 0x03, 0x8c, 0x81, 0x88, 0x82, 0x8b, 0xa0, 0x42, 0x22, 0xf0, 0x73, 0x02, 0x4f, 0xea, 0x02, 0x42, 0x4f, 0xea, 0x12, 0x42, 0x9b, 0xb2, 0x89, 0xb2, 0x42, 0xf0, 0x60, 0x02, 0x08, 0xd0, 0x04, 0xf5, 0x80, 0x64, 0xa0, 0x42, 0x04, 0xd0, 0x23, 0xf4, 0x00, 0x73, 0x43, 0xf4, 0x40, 0x73, 0x06, 0xe0, 0x23, 0xf4, 0x60, 0x63, 0x21, 0xf4, 0x40, 0x51, 0x43, 0xf4, 0x40, 0x73, 0x89, 0xb2, 0x81, 0x80, 0x82, 0x83, 0x00, 0x22, 0xc2, 0x63, 0x03, 0x84, 0x83, 0x8b, 0x23, 0xf0, 0x08, 0x03, 0x29, 0xe0, 0x0c, 0x29, 0x2a, 0xd1, 0x03, 0x8c, 0x18, 0x4c, 0x23, 0xf4, 0x80, 0x53, 0x1b, 0x04, 0x1b, 0x0c, 0x03, 0x84, 0x03, 0x8c, 0x81, 0x88, 0x82, 0x8b, 0x23, 0xf4, 0x00, 0x53, 0x22, 0xf4, 0xe6, 0x42, 0x12, 0x04, 0x1b, 0x04, 0x12, 0x0c, 0x1b, 0x0c, 0xa0, 0x42, 0x89, 0xb2, 0x42, 0xf4, 0xc0, 0x42, 0x43, 0xf4, 0x40, 0x53, 0x03, 0xd0, 0x04, 0xf5, 0x80, 0x64, 0xa0, 0x42, 0x02, 0xd1, 0x21, 0xf4, 0x80, 0x41, 0x89, 0xb2, 0x81, 0x80, 0x82, 0x83, 0x00, 0x22, 0x02, 0x64, 0x03, 0x84, 0x83, 0x8b, 0x23, 0xf4, 0x00, 0x63, 0x1b, 0x04, 0x1b, 0x0c, 0x83, 0x83, 0x03, 0x88, 0x9b, 0xb2, 0x43, 0xf0, 0x80, 0x03, 0x03, 0x80, 0x10, 0xbd, 0x00, 0xbf, 0x00, 0x00, 0x01, 0x40, 0x03, 0x88, 0x10, 0xb5, 0xdb, 0x07, 0x6d, 0xd4, 0x40, 0x4b, 0x41, 0x4c, 0x1a, 0x68, 0xa0, 0x42, 0x4f, 0xea, 0x52, 0x03, 0x07, 0xd1, 0x04, 0xf5, 0x9c, 0x34, 0x63, 0x6c, 0x43, 0xf0, 0x01, 0x03, 0x63, 0x64, 0x13, 0x46, 0x1f, 0xe0, 0xb0, 0xf1, 0x80, 0x4f, 0x04, 0xd1, 0x39, 0x4c, 0x22, 0x6c, 0x42, 0xf0, 0x01, 0x02, 0x16, 0xe0, 0x38, 0x4a, 0x90, 0x42, 0x04, 0xd1, 0x35, 0x4c, 0x22, 0x6c, 0x42, 0xf0, 0x02, 0x02, 0x0e, 0xe0, 0x35, 0x4a, 0x90, 0x42, 0x04, 0xd1, 0x31, 0x4c, 0x22, 0x6c, 0x42, 0xf0, 0x04, 0x02, 0x06, 0xe0, 0x32, 0x4a, 0x90, 0x42, 0x04, 0xd1, 0x2d, 0x4c, 0x22, 0x6c, 0x42, 0xf0, 0x08, 0x02, 0x22, 0x64, 0x2f, 0x4a, 0x29, 0x4c, 0xb3, 0xfb, 0xf2, 0xf2, 0x03, 0x88, 0x01, 0x3a, 0xa0, 0x42, 0x92, 0xb2, 0x9b, 0xb2, 0x12, 0xd0, 0x04, 0xf5, 0x80, 0x64, 0xa0, 0x42, 0x0e, 0xd0, 0xb0, 0xf1, 0x80, 0x4f, 0x0b, 0xd0, 0xa4, 0xf5, 0x80, 0x34, 0xa0, 0x42, 0x07, 0xd0, 0x04, 0xf5, 0x80, 0x64, 0xa0, 0x42, 0x03, 0xd0, 0x04, 0xf5, 0x80, 0x64, 0xa0, 0x42, 0x02, 0xd1, 0x23, 0xf0, 0x70, 0x03, 0x9b, 0xb2, 0x20, 0x4c, 0xa0, 0x42, 0x06, 0xd0, 0x04, 0xf5, 0x80, 0x64, 0xa0, 0x42, 0x1c, 0xbf, 0x23, 0xf4, 0x40, 0x73, 0x9b, 0xb2, 0x03, 0x80, 0x42, 0xf2, 0x0f, 0x73, 0xc3, 0x62, 0x13, 0x4b, 0x02, 0x85, 0x98, 0x42, 0x03, 0xd0, 0x03, 0xf5, 0x80, 0x63, 0x98, 0x42, 0x01, 0xd1, 0x00, 0x23, 0x03, 0x86, 0x01, 0x23, 0x83, 0x82, 0x03, 0x88, 0x9b, 0xb2, 0x43, 0xf0, 0x80, 0x03, 0x03, 0x80, 0x89, 0xb1, 0x03, 0x88, 0x9b, 0xb2, 0x43, 0xf0, 0x01, 0x03, 0x03, 0x80, 0x07, 0x4b, 0x98, 0x42, 0x01, 0xbf, 0xb0, 0xf8, 0x44, 0x30, 0x6f, 0xea, 0x43, 0x43, 0x6f, 0xea, 0x53, 0x43, 0x9b, 0xb2, 0x08, 0xbf, 0xa0, 0xf8, 0x44, 0x30, 0x10, 0xbd, 0x0c, 0x01, 0x00, 0x20, 0x00, 0x00, 0x01, 0x40, 0x00, 0x38, 0x02, 0x40, 0x00, 0x04, 0x00, 0x40, 0x00, 0x08, 0x00, 0x40, 0x00, 0x0c, 0x00, 0x40, 0x40, 0x42, 0x0f, 0x00, 0x00, 0x10, 0x00, 0x40, 0x2f, 0x4b, 0x00, 0x21, 0x1a, 0x68, 0x82, 0xb0, 0x42, 0xf0, 0x01, 0x02, 0x1a, 0x60, 0x99, 0x60, 0x1a, 0x68, 0x22, 0xf0, 0x84, 0x72, 0x22, 0xf4, 0x80, 0x32, 0x1a, 0x60, 0x29, 0x4a, 0x5a, 0x60, 0x1a, 0x68, 0x22, 0xf4, 0x80, 0x22, 0x1a, 0x60, 0xd9, 0x60, 0x00, 0x91, 0x01, 0x91, 0x1a, 0x68, 0x42, 0xf4, 0x80, 0x32, 0x1a, 0x60, 0x22, 0x4b, 0x1a, 0x68, 0x02, 0xf4, 0x00, 0x32, 0x01, 0x92, 0x00, 0x9a, 0x01, 0x32, 0x00, 0x92, 0x01, 0x9a, 0x1a, 0xb9, 0x00, 0x9a, 0xb2, 0xf5, 0xa0, 0x6f, 0xf1, 0xd1, 0x1b, 0x68, 0x13, 0xf4, 0x00, 0x33, 0x18, 0xbf, 0x01, 0x23, 0x01, 0x93, 0x01, 0x9b, 0x01, 0x2b, 0x05, 0xd0, 0x18, 0x4b, 0x4f, 0xf0, 0x00, 0x62, 0x9a, 0x60, 0x02, 0xb0, 0x70, 0x47, 0x13, 0x4b, 0x9a, 0x68, 0x9a, 0x60, 0x9a, 0x68, 0x42, 0xf4, 0x00, 0x42, 0x9a, 0x60, 0x9a, 0x68, 0x42, 0xf4, 0xa0, 0x52, 0x9a, 0x60, 0x11, 0x4a, 0x5a, 0x60, 0x1a, 0x68, 0x42, 0xf0, 0x80, 0x72, 0x1a, 0x60, 0x19, 0x68, 0x0a, 0x4a, 0x89, 0x01, 0xfb, 0xd5, 0x40, 0xf2, 0x03, 0x71, 0x0c, 0x4b, 0x19, 0x60, 0x93, 0x68, 0x23, 0xf0, 0x03, 0x03, 0x93, 0x60, 0x93, 0x68, 0x43, 0xf0, 0x02, 0x03, 0x93, 0x60, 0x03, 0x4b, 0x9b, 0x68, 0x03, 0xf0, 0x0c, 0x03, 0x08, 0x2b, 0xf9, 0xd1, 0xd1, 0xe7, 0x00, 0x38, 0x02, 0x40, 0x10, 0x30, 0x00, 0x24, 0x00, 0xed, 0x00, 0xe0, 0x1a, 0x3c, 0x40, 0x05, 0x00, 0x3c, 0x02, 0x40, 0x42, 0x09, 0x01, 0x2a, 0x07, 0x4b, 0x01, 0xd1, 0x1b, 0x68, 0x03, 0xe0, 0x02, 0x2a, 0x0c, 0xbf, 0x1b, 0x6f, 0x5b, 0x6f, 0x00, 0xf0, 0x1f, 0x00, 0x23, 0xfa, 0x00, 0xf0, 0x00, 0xf0, 0x01, 0x00, 0x70, 0x47, 0x00, 0xbf, 0x00, 0x38, 0x02, 0x40, 0x10, 0xb5, 0x05, 0x4b, 0x1c, 0x78, 0x05, 0x4b, 0x44, 0x43, 0xdb, 0x68, 0x00, 0x20, 0x98, 0x47, 0x60, 0x43, 0x00, 0x0c, 0x10, 0xbd, 0x00, 0xbf, 0x80, 0x01, 0x00, 0x20, 0xac, 0x01, 0x00, 0x20, 0xf7, 0xb5, 0x4f, 0x78, 0x4d, 0x69, 0x01, 0x2f, 0x3c, 0xd1, 0x86, 0x69, 0x34, 0x68, 0x33, 0x69, 0x00, 0x93, 0xda, 0xb2, 0xc3, 0xf3, 0x07, 0x43, 0x35, 0xb9, 0x65, 0xf3, 0x06, 0x02, 0x8d, 0xf8, 0x00, 0x20, 0x67, 0xf3, 0xc4, 0x03, 0x0e, 0xe0, 0x8f, 0x68, 0xbd, 0x42, 0x8c, 0xbf, 0x67, 0xf3, 0x06, 0x02, 0x65, 0xf3, 0x06, 0x02, 0x8d, 0xf8, 0x00, 0x20, 0x4f, 0xf0, 0x01, 0x02, 0x88, 0xbf, 0x4f, 0x61, 0x62, 0xf3, 0xc4, 0x03, 0x8d, 0xf8, 0x02, 0x30, 0x00, 0x9b, 0x44, 0xf0, 0x04, 0x44, 0x33, 0x61, 0xc3, 0x78, 0x01, 0x2b, 0x01, 0xbf, 0x0b, 0x78, 0x0a, 0x69, 0x00, 0xeb, 0x83, 0x03, 0x9b, 0x69, 0x08, 0xbf, 0x5a, 0x61, 0x34, 0x60, 0xc3, 0x78, 0x00, 0x2b, 0x34, 0xd1, 0x4b, 0x69, 0x00, 0x2b, 0x31, 0xd0, 0x00, 0x69, 0x09, 0x78, 0x42, 0x6b, 0x01, 0x23, 0x8b, 0x40, 0x13, 0x43, 0x43, 0x63, 0x29, 0xe0, 0x0e, 0x78, 0x8f, 0x68, 0x00, 0xeb, 0x86, 0x06, 0xb3, 0x6c, 0x1c, 0x68, 0x1b, 0x69, 0x00, 0x93, 0xda, 0xb2, 0xc3, 0xf3, 0x07, 0x43, 0x05, 0xb1, 0x4f, 0x61, 0x67, 0xf3, 0x06, 0x02, 0x8d, 0xf8, 0x00, 0x20, 0x01, 0x22, 0x62, 0xf3, 0xc4, 0x03, 0x8d, 0xf8, 0x02, 0x30, 0x00, 0x9a, 0xb3, 0x6c, 0x44, 0xf0, 0x04, 0x44, 0x1a, 0x61, 0xc3, 0x78, 0x01, 0x2b, 0x01, 0xbf, 0x0b, 0x78, 0x0a, 0x69, 0x00, 0xeb, 0x83, 0x03, 0x9b, 0x6c, 0x08, 0xbf, 0x5a, 0x61, 0x0b, 0x78, 0x00, 0xeb, 0x83, 0x00, 0x83, 0x6c, 0x1c, 0x60, 0x00, 0x20, 0x03, 0xb0, 0xf0, 0xbd, 0xb0, 0xf5, 0x80, 0x4f, 0x34, 0xbf, 0x00, 0x20, 0x01, 0x20, 0x70, 0x47, 0x00, 0x20, 0x70, 0x47, 0x00, 0x20, 0x70, 0x47, 0x00, 0xf0, 0xff, 0xbc, 0x00, 0x00, 0x08, 0xb5, 0x03, 0x46, 0x0a, 0x46, 0x04, 0x48, 0x19, 0x46, 0x00, 0xf0, 0xfe, 0xfc, 0x00, 0x30, 0x18, 0xbf, 0x01, 0x20, 0x08, 0xbd, 0x00, 0xbf, 0x18, 0x03, 0x00, 0x20, 0x10, 0xb5, 0x04, 0x4c, 0x04, 0x4b, 0x9c, 0x42, 0x03, 0xd2, 0x54, 0xf8, 0x04, 0x3b, 0x98, 0x47, 0xf8, 0xe7, 0x10, 0xbd, 0x54, 0x3b, 0x00, 0x08, 0x58, 0x3b, 0x00, 0x08, 0x07, 0xb5, 0x00, 0x23, 0x01, 0x93, 0x01, 0x9b, 0x00, 0xf0, 0x1f, 0x00, 0x43, 0xf0, 0x20, 0x03, 0x01, 0x93, 0x01, 0x9b, 0x23, 0xf4, 0xf8, 0x63, 0x43, 0xea, 0x80, 0x10, 0x09, 0x4b, 0x01, 0x90, 0xda, 0x68, 0x01, 0x9b, 0x13, 0x61, 0x08, 0x4b, 0x11, 0x69, 0x01, 0x3b, 0x01, 0x91, 0x02, 0xd0, 0x01, 0x99, 0x89, 0x06, 0xf8, 0xd4, 0x03, 0x20, 0xfe, 0xf7, 0x4a, 0xfe, 0x00, 0x20, 0x03, 0xb0, 0x5d, 0xf8, 0x04, 0xfb, 0x18, 0x14, 0x00, 0x20, 0x41, 0x0d, 0x03, 0x00, 0x82, 0xb0, 0x00, 0x23, 0x01, 0x93, 0x04, 0x4b, 0x01, 0x93, 0x01, 0x9b, 0x04, 0x33, 0x01, 0x93, 0x01, 0x9b, 0x18, 0x60, 0x02, 0xb0, 0x70, 0x47, 0x50, 0x28, 0x00, 0x40, 0x30, 0xb5, 0x05, 0x46, 0x27, 0x4c, 0x28, 0x49, 0x04, 0xeb, 0x40, 0x14, 0x0a, 0x6b, 0x60, 0x89, 0x85, 0xb0, 0x02, 0x43, 0x0a, 0x63, 0x22, 0x89, 0xa3, 0x7b, 0x02, 0x92, 0x22, 0x7b, 0x60, 0x68, 0x02, 0xa9, 0x8d, 0xf8, 0x0c, 0x20, 0x8d, 0xf8, 0x0f, 0x30, 0x00, 0xf0, 0x41, 0xfa, 0x4f, 0xf0, 0x80, 0x42, 0x93, 0x89, 0x28, 0x46, 0x23, 0xf0, 0x02, 0x03, 0x1b, 0x04, 0x1b, 0x0c, 0x93, 0x81, 0x23, 0x8b, 0x8d, 0xf8, 0x04, 0x30, 0x63, 0x8b, 0x01, 0x24, 0x8d, 0xf8, 0x05, 0x30, 0x21, 0x46, 0x00, 0x23, 0x8d, 0xf8, 0x06, 0x30, 0x8d, 0xf8, 0x07, 0x40, 0xff, 0xf7, 0xc1, 0xfc, 0x9d, 0xf8, 0x07, 0x30, 0x1b, 0xb1, 0x01, 0xa8, 0x00, 0xf0, 0xf7, 0xfa, 0x0a, 0xe0, 0x9d, 0xf8, 0x04, 0x30, 0x5a, 0x09, 0x03, 0xf0, 0x1f, 0x03, 0x9c, 0x40, 0x02, 0xf1, 0x20, 0x03, 0x0b, 0x4a, 0x42, 0xf8, 0x23, 0x40, 0x1c, 0x23, 0x8d, 0xf8, 0x04, 0x30, 0x06, 0x23, 0x8d, 0xf8, 0x05, 0x30, 0x00, 0x23, 0x8d, 0xf8, 0x06, 0x30, 0x01, 0xa8, 0x01, 0x23, 0x8d, 0xf8, 0x07, 0x30, 0x00, 0xf0, 0xdc, 0xfa, 0x05, 0xb0, 0x30, 0xbd, 0x10, 0x01, 0x00, 0x20, 0x00, 0x38, 0x02, 0x40, 0x00, 0xe1, 0x00, 0xe0, 0x10, 0xb5, 0xd0, 0xb1, 0x02, 0x46, 0x13, 0x1a, 0x12, 0xf8, 0x01, 0x4b, 0xdb, 0xb2, 0x00, 0x2c, 0xf9, 0xd1, 0x0a, 0x4a, 0x5b, 0x00, 0x02, 0x33, 0x0b, 0x80, 0x13, 0x70, 0x03, 0x23, 0x53, 0x70, 0x01, 0x38, 0x02, 0x23, 0x10, 0xf8, 0x01, 0x4f, 0x3c, 0xb1, 0x59, 0x1c, 0xd4, 0x54, 0xc9, 0xb2, 0x02, 0x33, 0x00, 0x24, 0xdb, 0xb2, 0x54, 0x54, 0xf4, 0xe7, 0x10, 0xbd, 0x18, 0x13, 0x00, 0x20, 0x10, 0xb5, 0x01, 0x24, 0x80, 0xf8, 0xed, 0x40, 0x00, 0x24, 0x80, 0xf8, 0xec, 0x40, 0xc0, 0xf8, 0xf8, 0x10, 0xc0, 0xf8, 0xfc, 0x10, 0xc0, 0xf8, 0x04, 0x41, 0xc0, 0xf8, 0x00, 0x21, 0x00, 0xf1, 0xec, 0x01, 0xff, 0xf7, 0xa9, 0xfe, 0x20, 0x46, 0x10, 0xbd, 0x10, 0xb5, 0x00, 0x23, 0xc0, 0xf8, 0xe4, 0x32, 0x80, 0xf8, 0xcd, 0x32, 0x80, 0xf8, 0xcc, 0x32, 0xc3, 0x78, 0x00, 0xf5, 0x33, 0x74, 0x01, 0x2b, 0x08, 0xbf, 0xc0, 0xf8, 0xdc, 0x12, 0xc0, 0xf8, 0xd8, 0x12, 0xc0, 0xf8, 0xe0, 0x22, 0x21, 0x46, 0xff, 0xf7, 0x91, 0xfe, 0x00, 0x20, 0x10, 0xbd, 0x00, 0x00, 0x38, 0xb5, 0x05, 0x46, 0x14, 0x46, 0xfe, 0xf7, 0xb3, 0xff, 0xd8, 0xb9, 0x01, 0x2d, 0x19, 0xd8, 0x0d, 0x49, 0x14, 0xf0, 0x01, 0x04, 0x0d, 0x4b, 0x51, 0xf8, 0x25, 0x20, 0x08, 0xd0, 0x11, 0x6a, 0xc1, 0xf3, 0x07, 0x22, 0x59, 0x70, 0xc1, 0xf3, 0x07, 0x41, 0x9a, 0x70, 0xd9, 0x70, 0x38, 0xbd, 0x52, 0x6a, 0x20, 0x46, 0xc2, 0xf3, 0x07, 0x21, 0x5a, 0x70, 0xc2, 0xf3, 0x07, 0x42, 0x99, 0x70, 0xda, 0x70, 0x38, 0xbd, 0x01, 0x20, 0x38, 0xbd, 0x78, 0x01, 0x00, 0x20, 0xf0, 0x18, 0x00, 0x20, 0x05, 0x4b, 0x00, 0x22, 0x1a, 0x82, 0x1a, 0x60, 0x5a, 0x60, 0x1a, 0x81, 0x9a, 0x72, 0x9a, 0x81, 0xda, 0x81, 0x01, 0x22, 0x9a, 0x74, 0x70, 0x47, 0xf8, 0x18, 0x00, 0x20, 0x70, 0xb5, 0x04, 0x46, 0xc0, 0xf3, 0x07, 0x40, 0xff, 0xf7, 0x42, 0xfe, 0x06, 0x46, 0xc4, 0xf3, 0x07, 0x20, 0xff, 0xf7, 0x3d, 0xfe, 0x05, 0x46, 0xe0, 0xb2, 0xff, 0xf7, 0x39, 0xfe, 0x05, 0x4b, 0x02, 0x46, 0x5c, 0x68, 0x30, 0x46, 0x29, 0x46, 0xa4, 0x46, 0xbd, 0xe8, 0x70, 0x40, 0x00, 0x23, 0x60, 0x47, 0x00, 0xbf, 0xac, 0x01, 0x00, 0x20, 0x13, 0xb5, 0x0e, 0x4b, 0x1b, 0x78, 0x0b, 0xb1, 0x0d, 0x4b, 0x00, 0xe0, 0x0d, 0x4b, 0x1c, 0x68, 0x0d, 0x4b, 0x68, 0x46, 0x9b, 0x68, 0x00, 0x21, 0x98, 0x47, 0xbd, 0xf8, 0x02, 0x20, 0xbd, 0xf8, 0x00, 0x30, 0x13, 0x43, 0xbd, 0xf8, 0x04, 0x20, 0x13, 0x43, 0x9b, 0xb2, 0x0b, 0xb1, 0x00, 0x20, 0x00, 0xe0, 0x20, 0x46, 0xff, 0xf7, 0xc8, 0xff, 0x02, 0xb0, 0x10, 0xbd, 0x10, 0x03, 0x00, 0x20, 0xec, 0x18, 0x00, 0x20, 0x14, 0x03, 0x00, 0x20, 0xac, 0x01, 0x00, 0x20, 0x02, 0x69, 0x40, 0xf6, 0xb8, 0x30, 0x53, 0x68, 0x43, 0xf0, 0x02, 0x03, 0x53, 0x60, 0xfe, 0xf7, 0x0d, 0xbd, 0xca, 0xb2, 0x12, 0xf0, 0x80, 0x0f, 0x01, 0xf0, 0x7f, 0x03, 0x10, 0xb5, 0x4f, 0xf0, 0x28, 0x04, 0x15, 0xbf, 0x04, 0xfb, 0x03, 0x01, 0x04, 0xfb, 0x01, 0x01, 0xec, 0x31, 0x01, 0xf5, 0x33, 0x71, 0xdb, 0xb2, 0x01, 0x24, 0xd2, 0x09, 0x8c, 0x70, 0x0b, 0x70, 0x4a, 0x70, 0x00, 0xeb, 0x83, 0x00, 0x32, 0xb1, 0x82, 0x69, 0x13, 0x68, 0x00, 0x2b, 0x04, 0xda, 0x43, 0xf0, 0x80, 0x43, 0x01, 0xe0, 0x82, 0x6c, 0x13, 0x68, 0x43, 0xf4, 0x00, 0x13, 0x13, 0x60, 0x00, 0x20, 0x10, 0xbd, 0x37, 0xb5, 0x05, 0x46, 0x00, 0x23, 0x11, 0x4c, 0x01, 0x93, 0x03, 0x20, 0xfe, 0xf7, 0xde, 0xfc, 0x2a, 0x68, 0x01, 0x3c, 0x13, 0x69, 0x01, 0x93, 0x14, 0xd0, 0x01, 0x9b, 0x00, 0x2b, 0xf4, 0xda, 0x01, 0x9b, 0x43, 0xf0, 0x01, 0x03, 0x01, 0x93, 0x01, 0x9b, 0x13, 0x61, 0x29, 0x68, 0x07, 0x4b, 0x0a, 0x69, 0x01, 0x3b, 0x01, 0x92, 0x02, 0xd0, 0x01, 0x9a, 0xd2, 0x07, 0xf8, 0xd4, 0x03, 0x20, 0xfe, 0xf7, 0xc4, 0xfc, 0x00, 0x20, 0x03, 0xb0, 0x30, 0xbd, 0x00, 0xbf, 0x41, 0x0d, 0x03, 0x00, 0x82, 0xb0, 0x00, 0x23, 0x00, 0x93, 0xc0, 0x23, 0x8d, 0xf8, 0x03, 0x30, 0x4f, 0xf0, 0x00, 0x03, 0x01, 0x22, 0x62, 0xf3, 0xc4, 0x03, 0x8d, 0xf8, 0x02, 0x30, 0x18, 0x23, 0x8d, 0xf8, 0x00, 0x30, 0x00, 0x9a, 0x83, 0x6c, 0x1a, 0x61, 0xc3, 0x78, 0x01, 0x2b, 0x08, 0xd1, 0x83, 0x6c, 0x00, 0xf2, 0xac, 0x42, 0x5a, 0x61, 0x83, 0x6c, 0x1a, 0x68, 0x4f, 0xf0, 0x80, 0x22, 0x1a, 0x60, 0x02, 0xb0, 0x70, 0x47, 0x30, 0xb5, 0x4c, 0x78, 0x0b, 0x78, 0x01, 0x2c, 0x15, 0xbf, 0x00, 0xeb, 0x83, 0x04, 0x00, 0xeb, 0x83, 0x05, 0xa5, 0x6c, 0xad, 0x69, 0x1c, 0xbf, 0x01, 0x24, 0x04, 0xfa, 0x03, 0xf3, 0x4f, 0xf0, 0x00, 0x02, 0x0c, 0xbf, 0x9c, 0x40, 0x63, 0xf3, 0x1f, 0x42, 0x2b, 0x68, 0x08, 0xbf, 0x64, 0xf3, 0x0f, 0x02, 0x1c, 0x04, 0x0d, 0xd4, 0x8c, 0x68, 0x64, 0xf3, 0x0a, 0x03, 0xcc, 0x78, 0x64, 0xf3, 0x93, 0x43, 0xcc, 0x88, 0x64, 0xf3, 0x99, 0x53, 0x43, 0xf0, 0x80, 0x53, 0x43, 0xf4, 0x00, 0x43, 0x2b, 0x60, 0x0b, 0x78, 0x01, 0x2b, 0x03, 0x69, 0x05, 0xd1, 0xc1, 0x7a, 0x19, 0xb9, 0xd9, 0x6b, 0x0a, 0x43, 0xda, 0x63, 0x02, 0xe0, 0xd9, 0x69, 0x0a, 0x43, 0xda, 0x61, 0x00, 0x20, 0x30, 0xbd, 0x00, 0x00, 0x0b, 0x4b, 0xda, 0x68, 0xd1, 0x03, 0x0d, 0xd4, 0xda, 0x68, 0xd2, 0x06, 0x0c, 0xd4, 0xda, 0x68, 0x12, 0xf0, 0xef, 0x0f, 0x0a, 0xd1, 0xdb, 0x68, 0x13, 0xf0, 0x02, 0x0f, 0x14, 0xbf, 0x07, 0x20, 0x08, 0x20, 0x70, 0x47, 0x01, 0x20, 0x70, 0x47, 0x05, 0x20, 0x70, 0x47, 0x06, 0x20, 0x70, 0x47, 0x00, 0x3c, 0x02, 0x40, 0x12, 0x23, 0x0b, 0x80, 0x00, 0x48, 0x70, 0x47, 0x0e, 0x3b, 0x00, 0x08, 0x04, 0x23, 0x0b, 0x80, 0x00, 0x48, 0x70, 0x47, 0xc4, 0x01, 0x00, 0x20, 0x12, 0x23, 0x0b, 0x80, 0x00, 0x48, 0x70, 0x47, 0xc8, 0x01, 0x00, 0x20, 0x08, 0xb5, 0x02, 0x48, 0xff, 0xf7, 0x58, 0xfe, 0x01, 0x48, 0x08, 0xbd, 0x20, 0x3b, 0x00, 0x08, 0x18, 0x13, 0x00, 0x20, 0x08, 0xb5, 0x02, 0x48, 0xff, 0xf7, 0x4e, 0xfe, 0x01, 0x48, 0x08, 0xbd, 0x20, 0x3b, 0x00, 0x08, 0x18, 0x13, 0x00, 0x20, 0x08, 0xb5, 0x02, 0x48, 0xff, 0xf7, 0x44, 0xfe, 0x01, 0x48, 0x08, 0xbd, 0x24, 0x3b, 0x00, 0x08, 0x18, 0x13, 0x00, 0x20, 0x08, 0xb5, 0x02, 0x48, 0xff, 0xf7, 0x3a, 0xfe, 0x01, 0x48, 0x08, 0xbd, 0x2d, 0x3b, 0x00, 0x08, 0x18, 0x13, 0x00, 0x20, 0x70, 0xb5, 0x8e, 0xb0, 0x05, 0xac, 0x21, 0x22, 0x0e, 0x46, 0x20, 0x46, 0x00, 0x21, 0x00, 0xf0, 0x29, 0xfb, 0x13, 0x4b, 0x01, 0xad, 0x93, 0xe8, 0x07, 0x00, 0x85, 0xe8, 0x07, 0x00, 0x00, 0x23, 0xea, 0x5c, 0x10, 0x09, 0x00, 0xf1, 0x30, 0x01, 0x39, 0x29, 0x88, 0xbf, 0x00, 0xf1, 0x37, 0x01, 0x02, 0xf0, 0x0f, 0x02, 0x04, 0xf8, 0x13, 0x10, 0x02, 0xf1, 0x30, 0x01, 0x39, 0x29, 0x88, 0xbf, 0x02, 0xf1, 0x37, 0x01, 0x04, 0xeb, 0x43, 0x02, 0x01, 0x33, 0x0c, 0x2b, 0x51, 0x70, 0xe7, 0xd1, 0x20, 0x46, 0x31, 0x46, 0xff, 0xf7, 0x08, 0xfe, 0x02, 0x48, 0x0e, 0xb0, 0x70, 0xbd, 0x00, 0xbf, 0x10, 0x7a, 0xff, 0x1f, 0x18, 0x13, 0x00, 0x20, 0xf0, 0xb5, 0x00, 0x22, 0x01, 0x23, 0x0c, 0x68, 0x93, 0x40, 0x1c, 0x40, 0x9c, 0x42, 0x29, 0xd1, 0x55, 0x00, 0x03, 0x23, 0xab, 0x40, 0xdb, 0x43, 0x06, 0x68, 0x1e, 0x40, 0x06, 0x60, 0x0e, 0x79, 0x07, 0x68, 0xae, 0x40, 0x3e, 0x43, 0x06, 0x60, 0x0e, 0x79, 0x01, 0x3e, 0x01, 0x2e, 0x11, 0xd8, 0x86, 0x68, 0x1e, 0x40, 0x86, 0x60, 0x4e, 0x79, 0x87, 0x68, 0xae, 0x40, 0x3e, 0x43, 0x86, 0x60, 0x46, 0x68, 0x26, 0xea, 0x04, 0x04, 0x44, 0x60, 0x8c, 0x79, 0x46, 0x68, 0x94, 0x40, 0xa4, 0xb2, 0x34, 0x43, 0x44, 0x60, 0xc4, 0x68, 0x23, 0x40, 0xc3, 0x60, 0xcb, 0x79, 0xc4, 0x68, 0xab, 0x40, 0x23, 0x43, 0xc3, 0x60, 0x01, 0x32, 0x10, 0x2a, 0xcc, 0xd1, 0xf0, 0xbd, 0x07, 0xb5, 0x08, 0x23, 0x8d, 0xf8, 0x07, 0x30, 0xff, 0xf7, 0x3c, 0xff, 0x8d, 0xf8, 0x07, 0x00, 0x9d, 0xf8, 0x07, 0x30, 0x01, 0x2b, 0xf7, 0xd0, 0x9d, 0xf8, 0x07, 0x00, 0x03, 0xb0, 0x5d, 0xf8, 0x04, 0xfb, 0x00, 0x00, 0x01, 0x4b, 0xd8, 0x60, 0x70, 0x47, 0x00, 0xbf, 0x00, 0x3c, 0x02, 0x40, 0x70, 0xb5, 0x05, 0x46, 0x0e, 0x46, 0xff, 0xf7, 0xe3, 0xff, 0x08, 0x28, 0x11, 0xd1, 0x09, 0x4c, 0x23, 0x69, 0x23, 0xf4, 0x40, 0x73, 0x23, 0x61, 0x23, 0x69, 0x23, 0x61, 0x23, 0x69, 0x43, 0xf0, 0x01, 0x03, 0x23, 0x61, 0x2e, 0x70, 0xff, 0xf7, 0xd3, 0xff, 0x23, 0x69, 0x23, 0xf0, 0x01, 0x03, 0x23, 0x61, 0x70, 0xbd, 0x00, 0x3c, 0x02, 0x40, 0x70, 0xb5, 0x05, 0x46, 0x0e, 0x46, 0xff, 0xf7, 0xc7, 0xff, 0x08, 0x28, 0x13, 0xd1, 0x0a, 0x4c, 0x23, 0x69, 0x23, 0xf4, 0x40, 0x73, 0x23, 0x61, 0x23, 0x69, 0x43, 0xf4, 0x00, 0x73, 0x23, 0x61, 0x23, 0x69, 0x43, 0xf0, 0x01, 0x03, 0x23, 0x61, 0x2e, 0x60, 0xff, 0xf7, 0xb5, 0xff, 0x23, 0x69, 0x23, 0xf0, 0x01, 0x03, 0x23, 0x61, 0x70, 0xbd, 0x00, 0x3c, 0x02, 0x40, 0x70, 0xb5, 0x06, 0x46, 0x41, 0xb1, 0x01, 0x29, 0x08, 0xd0, 0x02, 0x29, 0x0c, 0xbf, 0x4f, 0xf4, 0x00, 0x75, 0x4f, 0xf4, 0x40, 0x75, 0x03, 0xe0, 0x0d, 0x46, 0x01, 0xe0, 0x4f, 0xf4, 0x80, 0x75, 0xff, 0xf7, 0x9c, 0xff, 0x08, 0x28, 0x1e, 0xd1, 0x0f, 0x4c, 0x23, 0x69, 0x23, 0xf4, 0x40, 0x73, 0x23, 0x61, 0x21, 0x69, 0x29, 0x43, 0x21, 0x61, 0x23, 0x69, 0x23, 0xf0, 0xf8, 0x03, 0x23, 0x61, 0x23, 0x69, 0x43, 0xf0, 0x02, 0x03, 0x1e, 0x43, 0x26, 0x61, 0x23, 0x69, 0x43, 0xf4, 0x80, 0x33, 0x23, 0x61, 0xff, 0xf7, 0x83, 0xff, 0x23, 0x69, 0x23, 0xf0, 0x02, 0x03, 0x23, 0x61, 0x23, 0x69, 0x23, 0xf0, 0xf8, 0x03, 0x23, 0x61, 0x70, 0xbd, 0x00, 0x3c, 0x02, 0x40, 0x02, 0x4a, 0x13, 0x69, 0x43, 0xf0, 0x00, 0x43, 0x13, 0x61, 0x70, 0x47, 0x00, 0x3c, 0x02, 0x40, 0x04, 0x4b, 0x1a, 0x69, 0x00, 0x2a, 0xbf, 0xbf, 0x03, 0x4a, 0x5a, 0x60, 0x02, 0xf1, 0x88, 0x32, 0x5a, 0x60, 0x70, 0x47, 0x00, 0x3c, 0x02, 0x40, 0x23, 0x01, 0x67, 0x45, 0x10, 0x4b, 0xda, 0x68, 0x43, 0x78, 0xd2, 0x43, 0xc2, 0xf3, 0x02, 0x22, 0xc2, 0xf1, 0x04, 0x01, 0xc9, 0xb2, 0x8b, 0x40, 0xd9, 0xb2, 0x0f, 0x23, 0x13, 0x41, 0x82, 0x78, 0x13, 0x40, 0x0b, 0x43, 0x02, 0x78, 0x09, 0x49, 0x1b, 0x01, 0xdb, 0xb2, 0x0a, 0x44, 0x82, 0xf8, 0x00, 0x33, 0x03, 0x78, 0x01, 0x22, 0x58, 0x09, 0x03, 0xf0, 0x1f, 0x03, 0x02, 0xfa, 0x03, 0xf3, 0x41, 0xf8, 0x20, 0x30, 0x70, 0x47, 0x00, 0xbf, 0x00, 0xed, 0x00, 0xe0, 0x00, 0xe1, 0x00, 0xe0, 0x08, 0xb5, 0x4f, 0xf4, 0x80, 0x60, 0xfe, 0xf7, 0x1f, 0xf8, 0x4f, 0xf4, 0x00, 0x60, 0xfe, 0xf7, 0x1b, 0xf8, 0x4f, 0xf4, 0x80, 0x50, 0xfe, 0xf7, 0x17, 0xf8, 0x4f, 0xf4, 0x00, 0x50, 0xfe, 0xf7, 0x13, 0xf8, 0x4f, 0xf4, 0x80, 0x40, 0xfe, 0xf7, 0x0f, 0xf8, 0xbd, 0xe8, 0x08, 0x40, 0x4f, 0xf4, 0x00, 0x40, 0xfe, 0xf7, 0x09, 0xb8, 0x08, 0xb5, 0x20, 0x20, 0xfe, 0xf7, 0x05, 0xf8, 0x40, 0x20, 0xfe, 0xf7, 0x02, 0xf8, 0x80, 0x20, 0xfd, 0xf7, 0xff, 0xff, 0x4f, 0xf4, 0x80, 0x70, 0xfd, 0xf7, 0xfb, 0xff, 0xbd, 0xe8, 0x08, 0x40, 0x4f, 0xf4, 0x00, 0x70, 0xfd, 0xf7, 0xf5, 0xbf, 0x10, 0x20, 0xfd, 0xf7, 0xf2, 0xbf, 0x08, 0x20, 0xfd, 0xf7, 0xef, 0xbf, 0x04, 0x20, 0xfd, 0xf7, 0xec, 0xbf, 0x02, 0x20, 0xfd, 0xf7, 0xe9, 0xbf, 0x01, 0x20, 0xfd, 0xf7, 0xe6, 0xbf, 0x00, 0x21, 0x03, 0xe0, 0x0b, 0x4b, 0x5b, 0x58, 0x43, 0x50, 0x04, 0x31, 0x0a, 0x48, 0x0b, 0x4b, 0x42, 0x18, 0x9a, 0x42, 0xf6, 0xd3, 0x0a, 0x4a, 0x02, 0xe0, 0x00, 0x23, 0x42, 0xf8, 0x04, 0x3b, 0x08, 0x4b, 0x9a, 0x42, 0xf9, 0xd3, 0xff, 0xf7, 0x01, 0xfb, 0xfd, 0xf7, 0xe7, 0xff, 0xfc, 0xf7, 0x8d, 0xfe, 0x70, 0x47, 0x58, 0x3b, 0x00, 0x08, 0x00, 0x00, 0x00, 0x20, 0xdc, 0x01, 0x00, 0x20, 0xdc, 0x01, 0x00, 0x20, 0x0c, 0x19, 0x00, 0x20, 0xfe, 0xe7, 0x00, 0x00, 0x08, 0xb5, 0x12, 0x4b, 0x98, 0x42, 0x1a, 0x46, 0x09, 0xd1, 0x00, 0x23, 0x52, 0xf8, 0x23, 0x10, 0x01, 0x31, 0x13, 0xd1, 0x01, 0x33, 0xb3, 0xf5, 0x80, 0x5f, 0xf7, 0xd1, 0x0c, 0xe0, 0x0c, 0x4b, 0x98, 0x42, 0x1a, 0x46, 0x08, 0xd1, 0x00, 0x23, 0x52, 0xf8, 0x23, 0x10, 0x01, 0x31, 0x07, 0xd1, 0x01, 0x33, 0xb3, 0xf5, 0x80, 0x5f, 0xf7, 0xd1, 0x00, 0x20, 0x08, 0xbd, 0x08, 0x20, 0x00, 0xe0, 0x10, 0x20, 0x01, 0x46, 0x00, 0xf0, 0xf1, 0xf8, 0x08, 0xbd, 0x00, 0xbf, 0x00, 0x40, 0x00, 0x08, 0x00, 0x80, 0x00, 0x08, 0x70, 0xb5, 0xe2, 0xb0, 0x00, 0x21, 0x4f, 0xf4, 0xc2, 0x72, 0x05, 0x46, 0x01, 0xa8, 0x00, 0xf0, 0x6d, 0xf9, 0x01, 0x23, 0x18, 0x4a, 0x8d, 0xf8, 0x0d, 0x30, 0x8d, 0xf8, 0x0e, 0x30, 0x17, 0x4b, 0x04, 0x92, 0xb3, 0xf9, 0x08, 0x10, 0x1e, 0x46, 0xb1, 0xf5, 0x80, 0x7f, 0x14, 0x4c, 0x11, 0x46, 0x06, 0xd1, 0xd8, 0x68, 0x90, 0x42, 0x03, 0xd1, 0x54, 0xf8, 0x25, 0x00, 0x18, 0x44, 0x19, 0xe0, 0x10, 0x4a, 0xb2, 0xf9, 0x08, 0x30, 0xb3, 0xf5, 0x80, 0x7f, 0x06, 0xd1, 0xd3, 0x68, 0x8b, 0x42, 0x03, 0xd1, 0x54, 0xf8, 0x25, 0x00, 0x10, 0x44, 0x0c, 0xe0, 0x08, 0x20, 0x01, 0x46, 0x00, 0xf0, 0xba, 0xf8, 0x06, 0x48, 0x01, 0xa9, 0x4f, 0xf4, 0xc2, 0x72, 0x00, 0xf0, 0xcf, 0xf8, 0x54, 0xf8, 0x25, 0x30, 0xf0, 0x18, 0x62, 0xb0, 0x70, 0xbd, 0x42, 0x52, 0x43, 0x4d, 0x00, 0x40, 0x00, 0x08, 0x40, 0x3b, 0x00, 0x08, 0x00, 0x80, 0x00, 0x08, 0x2d, 0xe9, 0xf0, 0x4f, 0x81, 0x46, 0xe3, 0xb0, 0x04, 0x20, 0x17, 0x46, 0x8a, 0x46, 0xff, 0xf7, 0xb3, 0xff, 0x00, 0x21, 0x05, 0x46, 0x4f, 0xf4, 0xc2, 0x72, 0x01, 0xa8, 0x00, 0xf0, 0x22, 0xf9, 0x38, 0x4c, 0x01, 0x23, 0x8d, 0xf8, 0x0d, 0x30, 0x07, 0xeb, 0x09, 0x08, 0x36, 0x4b, 0xa0, 0x45, 0x04, 0x93, 0x5b, 0xd8, 0x05, 0xeb, 0x09, 0x00, 0x51, 0x46, 0x3a, 0x46, 0x00, 0xf0, 0xe0, 0xf8, 0x00, 0x28, 0x5b, 0xd0, 0x31, 0x4b, 0x32, 0x4e, 0xa9, 0xf5, 0xc2, 0x7b, 0xb5, 0x42, 0x08, 0xbf, 0x1e, 0x46, 0x30, 0x46, 0xff, 0xf7, 0x66, 0xff, 0x06, 0xf5, 0xc2, 0x70, 0x05, 0xf5, 0xc2, 0x71, 0x5a, 0x46, 0x00, 0xf0, 0x8f, 0xf8, 0x00, 0x28, 0x43, 0xd1, 0xb1, 0x44, 0x48, 0x46, 0x51, 0x46, 0x3a, 0x46, 0x00, 0xf0, 0x87, 0xf8, 0x00, 0x28, 0x3e, 0xd1, 0xa4, 0xf5, 0xc2, 0x74, 0xcb, 0xeb, 0x04, 0x04, 0xe2, 0x1b, 0x22, 0xd1, 0x01, 0x23, 0x8d, 0xf8, 0x0e, 0x30, 0x00, 0x23, 0x61, 0x93, 0xeb, 0x7a, 0x05, 0xf1, 0x10, 0x01, 0x50, 0x22, 0x05, 0xa8, 0x8d, 0xf8, 0x0f, 0x30, 0xfc, 0xf7, 0x4b, 0xfd, 0x05, 0xf1, 0x60, 0x01, 0x4f, 0xf4, 0x90, 0x72, 0x19, 0xa8, 0xfc, 0xf7, 0x44, 0xfd, 0x30, 0x46, 0x01, 0xa9, 0x4f, 0xf4, 0xc2, 0x72, 0x00, 0xf0, 0x64, 0xf8, 0x04, 0x46, 0x80, 0xb1, 0x30, 0x46, 0xff, 0xf7, 0x2f, 0xff, 0x6f, 0xf0, 0x04, 0x00, 0x17, 0xe0, 0x09, 0xeb, 0x07, 0x00, 0x05, 0xeb, 0x08, 0x01, 0x00, 0xf0, 0x56, 0xf8, 0x00, 0x28, 0xd4, 0xd0, 0x6f, 0xf0, 0x03, 0x00, 0x0c, 0xe0, 0x28, 0x46, 0xff, 0xf7, 0x1e, 0xff, 0x20, 0x46, 0x07, 0xe0, 0x4f, 0xf0, 0xff, 0x30, 0x04, 0xe0, 0x6f, 0xf0, 0x01, 0x00, 0x01, 0xe0, 0x6f, 0xf0, 0x02, 0x00, 0x63, 0xb0, 0xbd, 0xe8, 0xf0, 0x8f, 0x00, 0xbf, 0x00, 0x40, 0x00, 0x00, 0x42, 0x52, 0x43, 0x4d, 0x00, 0x80, 0x00, 0x08, 0x00, 0x40, 0x00, 0x08, 0x10, 0xb5, 0x04, 0x46, 0x00, 0x20, 0xff, 0xf7, 0x2d, 0xff, 0x20, 0x44, 0x10, 0xbd, 0x70, 0xb5, 0x05, 0x46, 0x14, 0x46, 0x08, 0x46, 0x0e, 0x46, 0xff, 0xf7, 0xf2, 0xff, 0x29, 0x46, 0x22, 0x46, 0x00, 0xf0, 0x26, 0xf8, 0x40, 0xb1, 0x06, 0xf5, 0xeb, 0x50, 0x29, 0x46, 0x22, 0x46, 0xbd, 0xe8, 0x70, 0x40, 0x1c, 0x30, 0xff, 0xf7, 0x5a, 0xbf, 0x70, 0xbd, 0x38, 0xb5, 0x04, 0x46, 0x0d, 0x46, 0xff, 0xf7, 0x4e, 0xfe, 0xf3, 0x20, 0xff, 0xf7, 0xcd, 0xfd, 0xfd, 0xf7, 0x0d, 0xfe, 0xac, 0x42, 0x0a, 0xd8, 0x20, 0x46, 0x02, 0x21, 0xff, 0xf7, 0x05, 0xfe, 0x08, 0x28, 0x00, 0xd0, 0xfe, 0xe7, 0xfd, 0xf7, 0x02, 0xfe, 0x08, 0x34, 0xf2, 0xe7, 0xff, 0xf7, 0x32, 0xfe, 0x00, 0x20, 0x38, 0xbd, 0x2d, 0xe9, 0xf0, 0x47, 0x81, 0x46, 0x0f, 0x46, 0x90, 0x46, 0x01, 0xeb, 0x02, 0x0a, 0xff, 0xf7, 0x2f, 0xfe, 0xf3, 0x20, 0xff, 0xf7, 0xae, 0xfd, 0x3c, 0x46, 0x4d, 0x46, 0x54, 0x45, 0x1e, 0xd2, 0xab, 0x07, 0x10, 0xd1, 0xc4, 0xeb, 0x0a, 0x03, 0x0f, 0x2b, 0x4f, 0xf0, 0x0b, 0x06, 0x0b, 0xdd, 0x28, 0x46, 0x21, 0x68, 0xff, 0xf7, 0xc0, 0xfd, 0x08, 0x28, 0x01, 0xd0, 0x01, 0x3e, 0xf7, 0xd1, 0x04, 0x35, 0x04, 0x34, 0xea, 0xe7, 0x0b, 0x26, 0x28, 0x46, 0x21, 0x78, 0xff, 0xf7, 0x98, 0xfd, 0x08, 0x28, 0x01, 0xd0, 0x01, 0x3e, 0xf7, 0xd1, 0x01, 0x35, 0x01, 0x34, 0xde, 0xe7, 0x39, 0x46, 0x42, 0x46, 0x48, 0x46, 0x00, 0xf0, 0x0a, 0xf8, 0x00, 0x28, 0x0c, 0xbf, 0x00, 0x24, 0x04, 0x24, 0xff, 0xf7, 0xf6, 0xfd, 0x20, 0x46, 0xbd, 0xe8, 0xf0, 0x87, 0x00, 0x00, 0x03, 0x2a, 0x70, 0xb4, 0x26, 0xd9, 0x40, 0xea, 0x01, 0x03, 0x9b, 0x07, 0x11, 0xd0, 0x04, 0x78, 0x0d, 0x78, 0xac, 0x42, 0x22, 0xd1, 0x02, 0x44, 0x43, 0x1c, 0x05, 0xe0, 0x13, 0xf8, 0x01, 0x4b, 0x11, 0xf8, 0x01, 0x5f, 0xac, 0x42, 0x19, 0xd1, 0x93, 0x42, 0xf7, 0xd1, 0x00, 0x20, 0x70, 0xbc, 0x70, 0x47, 0x0c, 0x46, 0x03, 0x46, 0x1e, 0x68, 0x25, 0x68, 0x18, 0x46, 0xae, 0x42, 0x21, 0x46, 0x03, 0xf1, 0x04, 0x03, 0x04, 0xf1, 0x04, 0x04, 0x04, 0xd1, 0x04, 0x3a, 0x03, 0x2a, 0x18, 0x46, 0x21, 0x46, 0xf0, 0xd8, 0x00, 0x2a, 0xda, 0xd1, 0x10, 0x46, 0xe8, 0xe7, 0x60, 0x1b, 0x70, 0xbc, 0x70, 0x47, 0x00, 0xbf, 0x70, 0xb4, 0x84, 0x07, 0x46, 0xd0, 0x54, 0x1e, 0x00, 0x2a, 0x41, 0xd0, 0xcd, 0xb2, 0x03, 0x46, 0x02, 0xe0, 0x62, 0x1e, 0xe4, 0xb3, 0x14, 0x46, 0x03, 0xf8, 0x01, 0x5b, 0x9a, 0x07, 0xf8, 0xd1, 0x03, 0x2c, 0x2e, 0xd9, 0xcd, 0xb2, 0x45, 0xea, 0x05, 0x25, 0x0f, 0x2c, 0x45, 0xea, 0x05, 0x45, 0x19, 0xd9, 0x26, 0x46, 0x03, 0xf1, 0x10, 0x02, 0x10, 0x3e, 0x0f, 0x2e, 0x42, 0xf8, 0x10, 0x5c, 0x42, 0xf8, 0x0c, 0x5c, 0x42, 0xf8, 0x08, 0x5c, 0x42, 0xf8, 0x04, 0x5c, 0x02, 0xf1, 0x10, 0x02, 0xf2, 0xd8, 0xa4, 0xf1, 0x10, 0x02, 0x22, 0xf0, 0x0f, 0x02, 0x04, 0xf0, 0x0f, 0x04, 0x10, 0x32, 0x03, 0x2c, 0x13, 0x44, 0x0d, 0xd9, 0x1e, 0x46, 0x22, 0x46, 0x04, 0x3a, 0x03, 0x2a, 0x46, 0xf8, 0x04, 0x5b, 0xfa, 0xd8, 0x22, 0x1f, 0x22, 0xf0, 0x03, 0x02, 0x04, 0x32, 0x13, 0x44, 0x04, 0xf0, 0x03, 0x04, 0x2c, 0xb1, 0xc9, 0xb2, 0x1c, 0x44, 0x03, 0xf8, 0x01, 0x1b, 0xa3, 0x42, 0xfb, 0xd1, 0x70, 0xbc, 0x70, 0x47, 0x14, 0x46, 0x03, 0x46, 0xc2, 0xe7, 0x00, 0xbf, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x40, 0x00, 0x20, 0x01, 0x00, 0x01, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x40, 0x08, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x40, 0x02, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x40, 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x40, 0x00, 0x08, 0x00, 0x80, 0x00, 0x08, 0x00, 0xc0, 0x00, 0x08, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x02, 0x08, 0x82, 0x3a, 0x00, 0x08, 0xc4, 0x3a, 0x00, 0x08, 0x92, 0x00, 0x00, 0x00, 0x00, 0x01, 0x05, 0x00, 0x01, 0x00, 0x88, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x44, 0x00, 0x65, 0x00, 0x76, 0x00, 0x69, 0x00, 0x63, 0x00, 0x65, 0x00, 0x49, 0x00, 0x6e, 0x00, 0x74, 0x00, 0x65, 0x00, 0x72, 0x00, 0x66, 0x00, 0x61, 0x00, 0x63, 0x00, 0x65, 0x00, 0x47, 0x00, 0x55, 0x00, 0x49, 0x00, 0x44, 0x00, 0x73, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x7b, 0x00, 0x33, 0x00, 0x37, 0x00, 0x66, 0x00, 0x62, 0x00, 0x35, 0x00, 0x66, 0x00, 0x39, 0x00, 0x30, 0x00, 0x2d, 0x00, 0x31, 0x00, 0x61, 0x00, 0x33, 0x00, 0x34, 0x00, 0x2d, 0x00, 0x34, 0x00, 0x39, 0x00, 0x32, 0x00, 0x39, 0x00, 0x2d, 0x00, 0x39, 0x00, 0x33, 0x00, 0x33, 0x00, 0x62, 0x00, 0x2d, 0x00, 0x38, 0x00, 0x61, 0x00, 0x32, 0x00, 0x37, 0x00, 0x65, 0x00, 0x31, 0x00, 0x38, 0x00, 0x35, 0x00, 0x30, 0x00, 0x30, 0x00, 0x33, 0x00, 0x33, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48, 0x50, 0x58, 0x40, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x20, 0x46, 0x6c, 0x61, 0x73, 0x68, 0x20, 0x20, 0x20, 0x2f, 0x30, 0x78, 0x30, 0x38, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x2f, 0x30, 0x33, 0x2a, 0x30, 0x31, 0x36, 0x4b, 0x61, 0x2c, 0x30, 0x31, 0x2a, 0x30, 0x31, 0x36, 0x4b, 0x67, 0x2c, 0x30, 0x31, 0x2a, 0x30, 0x36, 0x34, 0x4b, 0x67, 0x2c, 0x30, 0x37, 0x2a, 0x31, 0x32, 0x38, 0x4b, 0x67, 0x00, 0x40, 0x44, 0x43, 0x54, 0x20, 0x46, 0x6c, 0x61, 0x73, 0x68, 0x20, 0x20, 0x20, 0x2f, 0x30, 0x78, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x2f, 0x30, 0x31, 0x2a, 0x30, 0x31, 0x36, 0x4b, 0x67, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x57, 0x49, 0x4e, 0x55, 0x53, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x03, 0x4d, 0x00, 0x53, 0x00, 0x46, 0x00, 0x54, 0x00, 0x31, 0x00, 0x30, 0x00, 0x30, 0x00, 0xee, 0x00, 0x44, 0x46, 0x55, 0x00, 0x50, 0x61, 0x72, 0x74, 0x69, 0x63, 0x6c, 0x65, 0x00, 0x50, 0x68, 0x6f, 0x74, 0x6f, 0x6e, 0x20, 0x44, 0x46, 0x55, 0x20, 0x4d, 0x6f, 0x64, 0x65, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x1d, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00, 0x84, 0x01, 0x00, 0x00, 0x30, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb9, 0x2f, 0x00, 0x08, 0x09, 0x32, 0x00, 0x08, 0xfd, 0x31, 0x00, 0x08, 0x3d, 0x32, 0x00, 0x08, 0x51, 0x32, 0x00, 0x08, 0x65, 0x32, 0x00, 0x08, 0x29, 0x32, 0x00, 0x08, 0x15, 0x32, 0x00, 0x08, 0xf1, 0x31, 0x00, 0x08, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0xc5, 0x0d, 0x00, 0x08, 0xc5, 0x0d, 0x00, 0x08, 0xc5, 0x0d, 0x00, 0x08, 0xc5, 0x0d, 0x00, 0x08, 0xc5, 0x0d, 0x00, 0x08, 0xc5, 0x0d, 0x00, 0x08, 0xc5, 0x0d, 0x00, 0x08, 0x9d, 0x0d, 0x00, 0x08, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x63, 0x00, 0x00, 0x00, 0x09, 0x1d, 0x00, 0x08, 0x15, 0x1f, 0x00, 0x08, 0x4d, 0x21, 0x00, 0x08, 0x99, 0x1f, 0x00, 0x08, 0x05, 0x1d, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf9, 0x1c, 0x00, 0x08, 0xed, 0x1c, 0x00, 0x08, 0x9d, 0x1d, 0x00, 0x08, 0x89, 0x15, 0x00, 0x08, 0xc1, 0x1d, 0x00, 0x08, 0x1d, 0x16, 0x00, 0x08, 0x55, 0x1d, 0x00, 0x08, 0x85, 0x1e, 0x00, 0x08, 0x65, 0x1d, 0x00, 0x08, 0x83, 0x1d, 0x00, 0x08, 0x47, 0x1d, 0x00, 0x08, 0x39, 0x1d, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x06, 0x00, 0x02, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x09, 0x02, 0x24, 0x00, 0x01, 0x01, 0x02, 0xc0, 0x32, 0x09, 0x04, 0x00, 0x00, 0x00, 0xfe, 0x01, 0x02, 0x06, 0x09, 0x04, 0x00, 0x01, 0x00, 0xfe, 0x01, 0x02, 0x07, 0x09, 0x21, 0x0b, 0xff, 0x00, 0x00, 0x10, 0x1a, 0x01, 0x00, 0x00, 0x00, 0x00, 0x02, 0x08, 0x09, 0x07, 0x24, 0x00, 0x01, 0x01, 0x02, 0xc0, 0x32, 0x09, 0x04, 0x00, 0x00, 0x00, 0xfe, 0x01, 0x02, 0x06, 0x09, 0x04, 0x00, 0x01, 0x00, 0xfe, 0x01, 0x02, 0x07, 0x09, 0x21, 0x0b, 0xff, 0x00, 0x00, 0x10, 0x1a, 0x01, 0x00, 0x0e, 0x27, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x02, 0x40, 0x80, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x80, 0x00, 0x02, 0x00, 0x07, 0x00, 0x17, 0x00, 0x07, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc4, 0x3a, 0x00, 0x08, 0xa9, 0x1c, 0x00, 0x08, 0x6f, 0x2d, 0x00, 0x08, 0xa5, 0x1c, 0x00, 0x08, 0x7d, 0x2d, 0x00, 0x08, 0x77, 0x2d, 0x00, 0x08, 0x73, 0x2d, 0x00, 0x08, 0x63, 0x2d, 0x00, 0x08, 0x01, 0x00, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x84, 0x01, 0x00, 0x20, 0x50, 0x01, 0x00, 0x20, 0x60, 0x00, 0x00, 0x00, 0x82, 0x3a, 0x00, 0x08, 0xe7, 0x1c, 0x00, 0x08, 0xe3, 0x1c, 0x00, 0x08, 0x25, 0x25, 0x00, 0x08, 0xc1, 0x24, 0x00, 0x08, 0xe1, 0x1c, 0x00, 0x08, 0xbd, 0x1c, 0x00, 0x08, 0xad, 0x1c, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe1, 0x26, 0x00, 0x08, 0x81, 0x26, 0x00, 0x08, 0x75, 0x26, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x03, 0x09, 0x04, 0x12, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x40, 0x04, 0x2b, 0x06, 0xd0, 0x50, 0x02, 0x01, 0x02, 0x03, 0x01, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xc4, 0x37, 0xbb, 0x98, 0x49, 0x01, 0x53, 0x33, 0xa4, 0xe7, 0x53, 0x7b, 0xd0, 0x93, 0x5b, 0x3e, 0xcd, 0x4d, 0xe7, 0x22, 0xe1, 0x18, 0x48, 0x62, 0x0b, 0xfb, 0xa5, 0xf2, 0xd5, 0xdb, 0x99, 0x37, 0x28, 0x00, 0xc2, 0xe7, 0x39, 0x1f }; const unsigned int bootloader_platform_6_bin_len = 15712;
lgpl-3.0
aamaricci/SciFortran
src/fftpack/sint1f.f90
1
3556
subroutine sint1f ( n, inc, x, lenx, wsave, lensav, work, lenwrk, ier ) !*****************************************************************************80 ! !! SINT1F: real double precision forward sine transform, 1D. ! ! Discussion: ! ! SINT1F computes the one-dimensional Fourier transform of an odd ! sequence within a real array. This transform is referred to as the ! forward transform or Fourier analysis, transforming the sequence ! from physical to spectral space. ! ! This transform is normalized since a call to SINT1F followed ! by a call to SINT1B (or vice-versa) reproduces the original ! array within roundoff error. ! ! License: ! ! Licensed under the GNU General Public License (GPL). ! Copyright (C) 1995-2004, Scientific Computing Division, ! University Corporation for Atmospheric Research ! ! Modified: ! ! 15 November 2011 ! ! Author: ! ! Original FORTRAN77 version by Paul Swarztrauber, Richard Valent. ! FORTRAN90 version by John Burkardt. ! ! Reference: ! ! Paul Swarztrauber, ! Vectorizing the Fast Fourier Transforms, ! in Parallel Computations, ! edited by G. Rodrigue, ! Academic Press, 1982. ! ! Paul Swarztrauber, ! Fast Fourier Transform Algorithms for Vector Computers, ! Parallel Computing, pages 45-63, 1984. ! ! Parameters: ! ! Input, integer ( kind = 4 ) N, the length of the sequence to be ! transformed. The transform is most efficient when N+1 is a product of ! small primes. ! ! Input, integer ( kind = 4 ) INC, the increment between the locations, ! in array R, of two consecutive elements within the sequence. ! ! Input/output, real ( kind = 8 ) R(LENR), on input, contains the sequence ! to be transformed, and on output, the transformed sequence. ! ! Input, integer ( kind = 4 ) LENR, the dimension of the R array. ! LENR must be at least INC*(N-1)+ 1. ! ! Input, real ( kind = 8 ) WSAVE(LENSAV). WSAVE's contents must be ! initialized with a call to SINT1I before the first call to routine SINT1F ! or SINT1B for a given transform length N. WSAVE's contents may be re-used ! for subsequent calls to SINT1F and SINT1B with the same N. ! ! Input, integer ( kind = 4 ) LENSAV, the dimension of the WSAVE array. ! LENSAV must be at least N/2 + N + INT(LOG(REAL(N))) + 4. ! ! Workspace, real ( kind = 8 ) WORK(LENWRK). ! ! Input, integer ( kind = 4 ) LENWRK, the dimension of the WORK array. ! LENWRK must be at least 2*N+2. ! ! Output, integer ( kind = 4 ) IER, error flag. ! 0, successful exit; ! 1, input parameter LENR not big enough; ! 2, input parameter LENSAV not big enough; ! 3, input parameter LENWRK not big enough; ! 20, input error returned by lower level routine. ! implicit none integer ( kind = 4 ) inc integer ( kind = 4 ) lensav integer ( kind = 4 ) lenwrk integer ( kind = 4 ) ier integer ( kind = 4 ) ier1 integer ( kind = 4 ) lenx integer ( kind = 4 ) n real ( kind = 8 ) work(lenwrk) real ( kind = 8 ) wsave(lensav) real ( kind = 8 ) x(inc,*) ier = 0 if (lenx < inc*(n-1) + 1) then ier = 1 call xerfft ('sint1f', 6) return else if (lensav < n/2 + n + int(log( real ( n, kind = 8 ) ) & /log( 2.0D+00 )) +4) then ier = 2 call xerfft ('sint1f', 8) return else if (lenwrk < (2*n+2)) then ier = 3 call xerfft ('sint1f', 10) return end if call sintf1(n,inc,x,wsave,work,work(n+2),ier1) if (ier1 /= 0) then ier = 20 call xerfft ('sint1f',-5) end if return end
lgpl-3.0
PankajKataria/radare2
libr/bin/p/bin_any.c
3
1523
/* radare - LGPL - Copyright 2009-2017 - pancake, nibble */ #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_bin.h> #include <r_magic.h> static char *get_filetype(RBinFile *bf) { ut8 buf[4096] = { 0 }; char *res = NULL; RMagic *ck; if (!bf) { return NULL; } ck = r_magic_new (0); if (ck && bf && bf->buf) { const char *tmp = NULL; r_magic_load (ck, R_MAGIC_PATH); r_buf_read_at (bf->buf, 0, buf, sizeof (buf)); tmp = r_magic_buffer (ck, buf, sizeof (buf)); if (tmp) { res = strdup (tmp); } } r_magic_free (ck); return res; } static RBinInfo *info(RBinFile *bf) { RBinInfo *ret = R_NEW0 (RBinInfo); if (!ret) { return NULL; } ret->lang = ""; ret->file = bf->file? strdup (bf->file): NULL; ret->type = get_filetype (bf); ret->has_pi = 0; ret->has_canary = 0; if (R_SYS_BITS & R_SYS_BITS_64) { ret->bits = 64; } else { ret->bits = 32; } ret->big_endian = 0; ret->has_va = 0; ret->has_nx = 0; ret->dbg_info = 0; ret->dbg_info = 0; ret->dbg_info = 0; return ret; } static bool load(RBinFile *bf) { return true; } static int destroy(RBinFile *bf) { return true; } static ut64 baddr(RBinFile *bf) { return 0LL; } RBinPlugin r_bin_plugin_any = { .name = "any", .desc = "Dummy format r_bin plugin", .license = "LGPL3", .load = &load, .destroy = &destroy, .baddr = &baddr, .info = info, .minstrlen = 0, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_BIN, .data = &r_bin_plugin_any, .version = R2_VERSION }; #endif
lgpl-3.0
smessmer/cryfs
src/cryfs-cli/program_options/Parser.cpp
3
11185
#include "Parser.h" #include "utils.h" #include <iostream> #include <boost/optional.hpp> #include <cryfs/impl/config/CryConfigConsole.h> #include <cryfs/impl/CryfsException.h> #include <cryfs-cli/Environment.h> namespace po = boost::program_options; namespace bf = boost::filesystem; using namespace cryfs_cli::program_options; using cryfs::CryConfigConsole; using cryfs::CryfsException; using cryfs::ErrorCode; using std::vector; using std::cerr; using std::endl; using std::string; using boost::optional; using boost::none; using namespace cpputils::logging; Parser::Parser(int argc, const char **argv) :_options(_argsToVector(argc, argv)) { } vector<string> Parser::_argsToVector(int argc, const char **argv) { vector<string> result; for(int i = 0; i < argc; ++i) { result.push_back(argv[i]); } return result; } ProgramOptions Parser::parse(const vector<string> &supportedCiphers) const { vector<string> cryfsOptions; vector<string> fuseOptions; std::tie(cryfsOptions, fuseOptions) = splitAtDoubleDash(_options); if (fuseOptions.size() != 0) { LOG(WARN, "Passing fuse mount options after a double dash '--' is deprecated. Please pass them directly (e.g. 'cryfs basedir mountdir -o allow_other'"); } po::variables_map vm = _parseOptionsOrShowHelp(cryfsOptions, supportedCiphers); if (!vm.count("base-dir")) { _showHelpAndExit("Please specify a base directory.", ErrorCode::InvalidArguments); } if (!vm.count("mount-dir")) { _showHelpAndExit("Please specify a mount directory.", ErrorCode::InvalidArguments); } bf::path baseDir = vm["base-dir"].as<string>(); bf::path mountDir = vm["mount-dir"].as<string>(); optional<bf::path> configfile = none; if (vm.count("config")) { configfile = bf::absolute(vm["config"].as<string>()); } bool foreground = vm.count("foreground"); bool allowFilesystemUpgrade = vm.count("allow-filesystem-upgrade"); bool allowReplacedFilesystem = vm.count("allow-replaced-filesystem"); bool createMissingBasedir = vm.count("create-missing-basedir"); bool createMissingMountpoint = vm.count("create-missing-mountpoint"); optional<double> unmountAfterIdleMinutes = 0.0; // first setting to 0 and then to none is somehow needed to silence a GCC warning from -Wmaybe-uninitialized unmountAfterIdleMinutes = none; if (vm.count("unmount-idle")) { unmountAfterIdleMinutes = vm["unmount-idle"].as<double>(); } optional<bf::path> logfile = none; if (vm.count("logfile")) { logfile = bf::absolute(vm["logfile"].as<string>()); } optional<string> cipher = none; if (vm.count("cipher")) { cipher = vm["cipher"].as<string>(); _checkValidCipher(*cipher, supportedCiphers); } optional<uint32_t> blocksizeBytes = none; if (vm.count("blocksize")) { blocksizeBytes = vm["blocksize"].as<uint32_t>(); } bool allowIntegrityViolations = vm.count("allow-integrity-violations"); optional<bool> missingBlockIsIntegrityViolation = none; if (vm.count("missing-block-is-integrity-violation")) { missingBlockIsIntegrityViolation = vm["missing-block-is-integrity-violation"].as<bool>(); } if (vm.count("fuse-option")) { auto options = vm["fuse-option"].as<vector<string>>(); for (const auto& option: options) { fuseOptions.push_back("-o"); fuseOptions.push_back(option); } } return ProgramOptions(std::move(baseDir), std::move(mountDir), std::move(configfile), foreground, allowFilesystemUpgrade, allowReplacedFilesystem, createMissingBasedir, createMissingMountpoint, std::move(unmountAfterIdleMinutes), std::move(logfile), std::move(cipher), blocksizeBytes, allowIntegrityViolations, std::move(missingBlockIsIntegrityViolation), std::move(fuseOptions)); } void Parser::_checkValidCipher(const string &cipher, const vector<string> &supportedCiphers) { if (std::find(supportedCiphers.begin(), supportedCiphers.end(), cipher) == supportedCiphers.end()) { throw CryfsException("Invalid cipher: " + cipher, ErrorCode::InvalidArguments); } } po::variables_map Parser::_parseOptionsOrShowHelp(const vector<string> &options, const vector<string> &supportedCiphers) { try { return _parseOptions(options, supportedCiphers); } catch (const CryfsException& e) { // If CryfsException is thrown, we already know what's wrong. // Show usage information and pass through the exception, don't catch it. if (e.errorCode() != ErrorCode::Success) { _showHelp(); } throw; } catch(const std::exception &e) { std::cerr << e.what() << std::endl; _showHelpAndExit("Invalid arguments", ErrorCode::InvalidArguments); } } po::variables_map Parser::_parseOptions(const vector<string> &options, const vector<string> &supportedCiphers) { po::options_description desc; po::positional_options_description positional_desc; _addAllowedOptions(&desc); _addPositionalOptionForBaseDir(&desc, &positional_desc); po::variables_map vm; vector<const char*> _options = _to_const_char_vector(options); po::store(po::command_line_parser(_options.size(), _options.data()) .options(desc).positional(positional_desc).run(), vm); if (vm.count("help")) { _showHelpAndExit("", ErrorCode::Success); } if (vm.count("show-ciphers")) { _showCiphersAndExit(supportedCiphers); } if (vm.count("version")) { _showVersionAndExit(); } po::notify(vm); return vm; } vector<const char*> Parser::_to_const_char_vector(const vector<string> &options) { vector<const char*> result; result.reserve(options.size()); for (const string &option : options) { result.push_back(option.c_str()); } return result; } void Parser::_addAllowedOptions(po::options_description *desc) { po::options_description options("Allowed options"); string cipher_description = "Cipher to use for encryption. See possible values by calling cryfs with --show-ciphers. Default: "; cipher_description += CryConfigConsole::DEFAULT_CIPHER; string blocksize_description = "The block size used when storing ciphertext blocks (in bytes). Default: "; blocksize_description += std::to_string(CryConfigConsole::DEFAULT_BLOCKSIZE_BYTES); options.add_options() ("help,h", "show help message") ("config,c", po::value<string>(), "Configuration file") ("foreground,f", "Run CryFS in foreground.") ("fuse-option,o", po::value<vector<string>>(), "Add a fuse mount option. Example: atime or noatime.") ("cipher", po::value<string>(), cipher_description.c_str()) ("blocksize", po::value<uint32_t>(), blocksize_description.c_str()) ("missing-block-is-integrity-violation", po::value<bool>(), "Whether to treat a missing block as an integrity violation. This makes sure you notice if an attacker deleted some of your files, but only works in single-client mode. You will not be able to use the file system on other devices.") ("allow-integrity-violations", "Disable integrity checks. Integrity checks ensure that your file system was not manipulated or rolled back to an earlier version. Disabling them is needed if you want to load an old snapshot of your file system.") ("allow-filesystem-upgrade", "Allow upgrading the file system if it was created with an old CryFS version. After the upgrade, older CryFS versions might not be able to use the file system anymore.") ("allow-replaced-filesystem", "By default, CryFS remembers file systems it has seen in this base directory and checks that it didn't get replaced by an attacker with an entirely different file system since the last time it was loaded. However, if you do want to replace the file system with an entirely new one, you can pass in this option to disable the check.") ("create-missing-basedir", "Creates the base directory even if there is no directory currently there, skipping the normal confirmation message to create it later.") ("create-missing-mountpoint", "Creates the mountpoint even if there is no directory currently there, skipping the normal confirmation message to create it later.") ("show-ciphers", "Show list of supported ciphers.") ("unmount-idle", po::value<double>(), "Automatically unmount after specified number of idle minutes.") ("logfile", po::value<string>(), "Specify the file to write log messages to. If this is not specified, log messages will go to stdout, or syslog if CryFS is running in the background.") ("version", "Show CryFS version number") ; desc->add(options); } void Parser::_addPositionalOptionForBaseDir(po::options_description *desc, po::positional_options_description *positional) { positional->add("base-dir", 1); positional->add("mount-dir", 1); po::options_description hidden("Hidden options"); hidden.add_options() ("base-dir", po::value<string>(), "Base directory") ("mount-dir", po::value<string>(), "Mount directory") ; desc->add(hidden); } [[noreturn]] void Parser::_showCiphersAndExit(const vector<string> &supportedCiphers) { for (const auto &cipher : supportedCiphers) { std::cerr << cipher << "\n"; } throw CryfsException("", ErrorCode::Success); } void Parser::_showHelp() { cerr << "Usage: cryfs [options] baseDir mountPoint [-- [FUSE Mount Options]]\n"; po::options_description desc; _addAllowedOptions(&desc); cerr << desc << endl; cerr << "Environment variables:\n" << " " << Environment::FRONTEND_KEY << "=" << Environment::FRONTEND_NONINTERACTIVE << "\n" << "\tWork better together with tools.\n" << "\tWith this option set, CryFS won't ask anything, but use default values\n" << "\tfor options you didn't specify on command line. Furthermore, it won't\n" << "\task you to enter a new password a second time (password confirmation).\n" << " " << Environment::NOUPDATECHECK_KEY << "=true\n" << "\tBy default, CryFS connects to the internet to check for known\n" << "\tsecurity vulnerabilities and new versions. This option disables this.\n" << " " << Environment::LOCALSTATEDIR_KEY << "=[path]\n" << "\tSets the directory cryfs uses to store local state. This local state\n" << "\tis used to recognize known file systems and run integrity checks,\n" << "\ti.e. check that they haven't been modified by an attacker.\n" << "\tDefault value: " << Environment::defaultLocalStateDir().string() << "\n" << endl; } [[noreturn]] void Parser::_showHelpAndExit(const std::string& message, ErrorCode errorCode) { _showHelp(); throw CryfsException(message, errorCode); } [[noreturn]] void Parser::_showVersionAndExit() { // no need to show version because it was already shown in the CryFS header before parsing program options throw CryfsException("", ErrorCode::Success); }
lgpl-3.0
berkmancenter/metalab_rgbdemo
nestk/deps/openni/Source/OpenNI/Linux-x86/LinuxUSBDevice.cpp
3
23448
/**************************************************************************** * * * OpenNI 1.1 Alpha * * Copyright (C) 2011 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * OpenNI 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. * * * * OpenNI 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 OpenNI. If not, see <http://www.gnu.org/licenses/>. * * * ****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <XnPlatform.h> #if (XN_PLATFORM == XN_PLATFORM_LINUX_ARM) #include <XnUSBDevice.h> #include <linux/usb/gadgetfs.h> #include <asm/byteorder.h> #include <poll.h> #include <errno.h> #include <XnLog.h> #include <XnOSCpp.h> //--------------------------------------------------------------------------- // Defines //--------------------------------------------------------------------------- #define GADGET_DEVICE_DIR "/dev/gadget/" #define GADGET_DEVICE_FILE_NAME "musb_hdrc" #define GADGET_DEVICE_FILE_PATH GADGET_DEVICE_DIR GADGET_DEVICE_FILE_NAME #define USB_LANGUAGE_ENGLISH_US 0x0409 #define XN_USB_DEVICE_ENDPOINT_MAX_COUNT 16 //--------------------------------------------------------------------------- // Macros //--------------------------------------------------------------------------- #define WRITE_TO_BUF(buf, data, size) \ memcpy(buf, data, size); \ buf += size; #define WRITE_OBJ_TO_BUF(buf, obj) \ WRITE_TO_BUF(buf, &obj, sizeof(obj)); //--------------------------------------------------------------------------- // Types //--------------------------------------------------------------------------- typedef enum { /** No control message **/ XN_USB_DEVICE_CONTROL_CLEAR, /** Out control received. Wasn't read by client yet. **/ XN_USB_DEVICE_CONTROL_REQUEST_PENDING, /** Out control received and read by client **/ XN_USB_DEVICE_CONTROL_REQUEST_PROCESSING, /** In control received, but no client reply yet **/ XN_USB_DEVICE_CONTROL_REPLY_PENDING, /** Client reply received, but no in control yet **/ XN_USB_DEVICE_CONTROL_REPLY_READY, } XnUSBDeviceControlState; struct XnUSBDevice { const XnUSBDeviceDescriptorHolder* pDescriptors; int deviceFD; XnBool bShutdown; XN_THREAD_HANDLE hThread; XN_CRITICAL_SECTION_HANDLE hLock; XnBool bConnected; enum usb_device_speed speed; XnUInt32 nControlMessageMaxSize; XnUInt8 nConfigID; XnUInt8 nInterfaceID; XnUInt8 nAltInterfaceID; int endpointsFDs[XN_USB_DEVICE_ENDPOINT_MAX_COUNT]; // all control members should be accessed with a lock. They can be modified either from the user thread // or the ep0 thread. XnUSBDeviceControlState eControlState; XnUChar* pControlBuffer; XnUInt32 nControlSize; XnUSBDeviceNewControlRequestCallback pNewControlRequestCallback; void* pNewControlRequestCallbackCookie; }; //--------------------------------------------------------------------------- // Configuring GadgetFS Device //--------------------------------------------------------------------------- static XnStatus buildGadgetFSInterfaceDescriptor(const XnUSBInterfaceDescriptorHolder* pInterface, XnChar*& buf) { XnStatus nRetVal = XN_STATUS_OK; // write interface descriptor WRITE_OBJ_TO_BUF(buf, pInterface->descriptor); // now write each endpoint for (__u8 iEP = 0; iEP < pInterface->descriptor.bNumEndpoints; ++iEP) { WRITE_TO_BUF(buf, pInterface->aEndpoints[iEP], USB_DT_ENDPOINT_SIZE); } return XN_STATUS_OK; } static XnStatus buildGadgetFSConfigDescriptor(const XnUSBConfigDescriptorHolder* pConfig, XnChar*& buf) { XnStatus nRetVal = XN_STATUS_OK; struct usb_config_descriptor* pTarget = (struct usb_config_descriptor*)buf; // write configuration descriptor WRITE_OBJ_TO_BUF(buf, pConfig->descriptor); // for now, gadget FS supports a single interface if (pConfig->descriptor.bNumInterfaces > 1) { xnLogError(XN_MASK_OS, "GadgetFS does not support more than 1 interface!"); return XN_STATUS_INVALID_OPERATION; } // now write the interface buildGadgetFSInterfaceDescriptor(pConfig->aInterfaces[0], buf); pTarget->wTotalLength = buf - (XnChar*)pTarget; return XN_STATUS_OK; } static XnStatus buildGadgetFSDescriptors(const XnUSBDeviceDescriptorHolder* pDescriptors, XnChar*& buf) { XnStatus nRetVal = XN_STATUS_OK; // write format ID XnUInt32 nFormatID = 0; WRITE_OBJ_TO_BUF(buf, nFormatID); // for now, gadget FS supports a single configuration if (pDescriptors->descriptor.bNumConfigurations > 1) { xnLogError(XN_MASK_OS, "GadgetFS does not support more than 1 configuration!"); return XN_STATUS_INVALID_OPERATION; } XN_VALIDATE_INPUT_PTR(pDescriptors->aConfigurations); XN_VALIDATE_INPUT_PTR(pDescriptors->aConfigurations[0]); // we first write the full-speed one (backwards compatibility) and then the high-speed one buildGadgetFSConfigDescriptor(pDescriptors->aConfigurations[0], buf); buildGadgetFSConfigDescriptor(pDescriptors->aConfigurations[0], buf); // write device WRITE_OBJ_TO_BUF(buf, pDescriptors->descriptor); } //--------------------------------------------------------------------------- // Configuring GadgetFS Endpoints //--------------------------------------------------------------------------- static int openEndpointFile(struct usb_endpoint_descriptor* pDesc) { // build file name XnChar fileName[255]; bool bIn = (pDesc->bEndpointAddress & 0x80) != 0; sprintf(fileName, "%s%s%d%s", GADGET_DEVICE_DIR, "ep", pDesc->bEndpointAddress & 0xF, bIn ? "in" : "out"); // open it int fd = open(fileName, O_RDWR); // config it XnUChar bufConfig[1024]; XnUChar* buf = bufConfig; XnUInt32 nFormatID = 1; WRITE_OBJ_TO_BUF(buf, nFormatID); // now we should write the full-speed descriptor. Take high-speed one and reduce speed struct usb_endpoint_descriptor* pFSDesc = (struct usb_endpoint_descriptor*)buf; WRITE_TO_BUF(buf, pDesc, USB_DT_ENDPOINT_SIZE); pFSDesc->wMaxPacketSize = 64; // now write the real one (high-speed) WRITE_TO_BUF(buf, pDesc, USB_DT_ENDPOINT_SIZE); int status = write(fd, bufConfig, buf - bufConfig); if (status < 0) { // status = -errno; // fprintf (stderr, "%s config %s error %d (%s)\n", // label, name, errno, strerror (errno)); close (fd); return -1; } return fd; } static XnStatus configureEndpoints(XnUSBDevice* pDevice, int nConfigID) { // first of all, we need to close all previous open endpoints for (int i = 0; i < XN_USB_DEVICE_ENDPOINT_MAX_COUNT; ++i) { if (pDevice->endpointsFDs[i] != -1) { close(pDevice->endpointsFDs[i]); pDevice->endpointsFDs[i] = -1; } } if (nConfigID == 0) { // device is unconfigured return XN_STATUS_OK; } // open endpoint files XnUSBInterfaceDescriptorHolder* pInterface = pDevice->pDescriptors->aConfigurations[0]->aInterfaces[0]; for (int i = 0; i < pInterface->descriptor.bNumEndpoints; ++i) { __u8 nAddress = pInterface->aEndpoints[i]->bEndpointAddress & 0xF; pDevice->endpointsFDs[nAddress] = openEndpointFile(pInterface->aEndpoints[i]); if (pDevice->endpointsFDs[nAddress] == -1) { return XN_STATUS_ERROR; } } } //--------------------------------------------------------------------------- // EP0 Handling //--------------------------------------------------------------------------- static XnBool handleVendorControl(XnUSBDevice* pDevice, struct usb_ctrlrequest *setup); static inline void put_unaligned_le16(__u16 val, __u16 *cp) { __u8 *p = (__u8 *)cp; *p++ = (__u8) val; *p++ = (__u8) (val >> 8); } static int utf8_to_utf16le(const char *s, __u16 *cp, unsigned len) { int count = 0; __u8 c; __u16 uchar; /* this insists on correct encodings, though not minimal ones. * BUT it currently rejects legit 4-byte UTF-8 code points, * which need surrogate pairs. (Unicode 3.1 can use them.) */ while (len != 0 && (c = (__u8) *s++) != 0) { if (c & 0x80) { // 2-byte sequence: // 00000yyyyyxxxxxx = 110yyyyy 10xxxxxx if ((c & 0xe0) == 0xc0) { uchar = (c & 0x1f) << 6; c = (__u8) *s++; if ((c & 0xc0) != 0xc0) goto fail; c &= 0x3f; uchar |= c; // 3-byte sequence (most CJKV characters): // zzzzyyyyyyxxxxxx = 1110zzzz 10yyyyyy 10xxxxxx } else if ((c & 0xf0) == 0xe0) { uchar = (c & 0x0f) << 12; c = (__u8) *s++; if ((c & 0xc0) != 0xc0) goto fail; c &= 0x3f; uchar |= c << 6; c = (__u8) *s++; if ((c & 0xc0) != 0xc0) goto fail; c &= 0x3f; uchar |= c; /* no bogus surrogates */ if (0xd800 <= uchar && uchar <= 0xdfff) goto fail; // 4-byte sequence (surrogate pairs, currently rare): // 11101110wwwwzzzzyy + 110111yyyyxxxxxx // = 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx // (uuuuu = wwww + 1) // FIXME accept the surrogate code points (only) } else goto fail; } else uchar = c; put_unaligned_le16 (uchar, cp++); count++; len--; } return count; fail: return -1; } static XnBool handleGetStringDescriptor(XnUSBDevice* pDevice, __u16 nMaxLength, __u16 lang, __u8 nIndex) { if (nIndex != 0 && lang != USB_LANGUAGE_ENGLISH_US) { return FALSE; } XnUChar buf[256]; // descriptor 0 has the language id if (nIndex == 0) { buf [0] = 4; buf [1] = USB_DT_STRING; *(__u16*)&buf[2] = __cpu_to_le16(USB_LANGUAGE_ENGLISH_US); } else { // look for index const XnChar* strString = NULL; for (__u8 i = 0; i < pDevice->pDescriptors->nStrings; ++i) { if (pDevice->pDescriptors->aStrings[i].nID == nIndex) { strString = pDevice->pDescriptors->aStrings[i].strString; break; } } if (strString == NULL) { return FALSE; } int len = strlen(strString); len = XN_MIN(len, 126); // zero all bytes memset(buf+2, 0, 2*len); len = utf8_to_utf16le(strString, (__u16 *)&buf[2], len); if (len < 0) { return FALSE; } buf [0] = (len + 1) * 2; buf [1] = USB_DT_STRING; } XnUInt32 nReplySize = XN_MIN(buf[0], nMaxLength); int status = write(pDevice->deviceFD, buf, nReplySize); if (status < 0) { if (errno == EIDRM) fprintf (stderr, "string timeout\n"); else perror ("write string data"); } else if (status != nReplySize) { fprintf (stderr, "short string write, %d\n", status); } return TRUE; } static XnBool handleChapter9Requests(XnUSBDevice* pDevice, struct usb_ctrlrequest *setup) { __u16 value = __le16_to_cpu(setup->wValue); __u16 index = __le16_to_cpu(setup->wIndex); __u16 length = __le16_to_cpu(setup->wLength); switch (setup->bRequest) { case USB_REQ_GET_DESCRIPTOR: { if (setup->bRequestType != USB_DIR_IN) { return FALSE; } if ((value >> 8) != USB_DT_STRING) { return FALSE; } // index is language index and string index is last byte return handleGetStringDescriptor(pDevice, length, index, value & 0xFF); } break; case USB_REQ_SET_CONFIGURATION: { if (setup->bRequestType != USB_DIR_OUT) { return FALSE; } __u8 nConfigID = value; // make sure this is the only supported configuration if (nConfigID != 0 && nConfigID != pDevice->pDescriptors->aConfigurations[0]->descriptor.bConfigurationValue) { return FALSE; } if (!configureEndpoints(pDevice, value)) { return FALSE; } pDevice->nConfigID = value; // send ACK int status = read (pDevice->deviceFD, &status, 0); if (status) perror ("ack SET_CONFIGURATION"); } break; case USB_REQ_GET_INTERFACE: { if (setup->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE) || index != pDevice->nInterfaceID || length > 1) { return FALSE; } __u8 nAlt = pDevice->nAltInterfaceID; int status = write(pDevice->deviceFD, &nAlt, 1); if (status < 0) { if (errno == EIDRM) fprintf (stderr, "GET_INTERFACE timeout\n"); else perror ("write GET_INTERFACE data"); } else if (status != length) { fprintf (stderr, "short GET_INTERFACE write, %d\n", status); } } break; case USB_REQ_SET_INTERFACE: { __u16 nInt = index; __u16 nAlt = value; if (setup->bRequestType != USB_RECIP_INTERFACE) { return FALSE; } // make sure this is the only interface if (nInt != 0 || nAlt != 0) { return FALSE; } } break; default: return FALSE; } return TRUE; } static XnBool handleControl(XnUSBDevice* pDevice, struct usb_ctrlrequest *setup) { if ((setup->bRequestType & USB_TYPE_MASK) == USB_TYPE_VENDOR) { return handleVendorControl(pDevice, setup); } else { // usb 2.0 spec ch9 requests return handleChapter9Requests(pDevice, setup); } } XN_THREAD_PROC xnUSBDeviceEndPoint0Handler(XN_THREAD_PARAM pThreadParam) { XnUSBDevice* pDevice = (XnUSBDevice*)pThreadParam; int status; struct pollfd ep0_poll; ep0_poll.fd = pDevice->deviceFD; ep0_poll.events = POLLIN | POLLOUT | POLLHUP; while (!pDevice->bShutdown) { status = poll(&ep0_poll, 1, -1); if (status < 0) { xnLogError(XN_MASK_OS, "Failed polling device file! (%d)", errno); sleep(1); continue; } struct usb_gadgetfs_event event; status = read(pDevice->deviceFD, &event, sizeof(event)); if (status < 0) { if (errno != EAGAIN) { xnLogError(XN_MASK_OS, "Failed reading from device file! (%d)", errno); } sleep (1); continue; } switch (event.type) { case GADGETFS_NOP: break; case GADGETFS_CONNECT: pDevice->speed = event.u.speed; pDevice->bConnected = TRUE; break; case GADGETFS_DISCONNECT: pDevice->speed = USB_SPEED_UNKNOWN; pDevice->bConnected = FALSE; break; case GADGETFS_SUSPEND: break; case GADGETFS_SETUP: // setup stage if (!handleControl(pDevice, &event.u.setup)) { // stall is done by reading/writing in the wrong direction if ((event.u.setup.bRequestType & USB_DIR_IN) != 0) status = read (pDevice->deviceFD, &status, 0); else status = write (pDevice->deviceFD, &status, 0); if (status != -1) { //fprintf (stderr, "can't stall ep0 for %02x.%02x\n", // setup->bRequestType, setup->bRequest); } else if (errno != EL2HLT) { //perror ("ep0 stall"); } } break; default: xnLogWarning(XN_MASK_OS, "Got unknown gadgetfs event: %d", event.type); } } XN_THREAD_PROC_RETURN(XN_STATUS_OK); } //--------------------------------------------------------------------------- // Init & Shutdown //--------------------------------------------------------------------------- XN_C_API XnStatus XN_C_DECL xnUSBDeviceInit(const XnUSBDeviceDescriptorHolder* pDescriptors, XnUInt32 nControlMessageMaxSize, XnUSBDevice** ppDevice) { XnStatus nRetVal = XN_STATUS_OK; XN_VALIDATE_INPUT_PTR(pDescriptors); XN_VALIDATE_OUTPUT_PTR(ppDevice); // open device file int device_fd = open (GADGET_DEVICE_FILE_PATH, O_RDWR); if (device_fd < 0) { xnLogWarning(XN_MASK_OS, "Failed opening %s (%d)", GADGET_DEVICE_FILE_PATH, errno); return XN_STATUS_ERROR; } // build descriptors buffer XnChar bufDescriptors[4096]; XnUInt32 nBufSize = 4096; XnChar* buf = bufDescriptors; nRetVal = buildGadgetFSDescriptors(pDescriptors, buf); XN_IS_STATUS_OK(nRetVal); int status = write(device_fd, bufDescriptors, buf - bufDescriptors); if (status < 0) { xnLogWarning(XN_MASK_OS, "Failed writing descriptor to device file (%d)", errno); close (device_fd); return XN_STATUS_ERROR; } else if (status != (buf - bufDescriptors)) { xnLogWarning(XN_MASK_OS, "Failed writing descriptors to device file. Write %d, expected %d.", status, buf - bufDescriptors); close (device_fd); return XN_STATUS_ERROR; } XnUSBDevice* pDevice = (XnUSBDevice*)xnOSCalloc(1, sizeof(XnUSBDevice)); if (pDevice == NULL) { close(device_fd); return XN_STATUS_ALLOC_FAILED; } pDevice->deviceFD = device_fd; for (int i = 0; i < XN_USB_DEVICE_ENDPOINT_MAX_COUNT; ++i) { pDevice->endpointsFDs[i] = -1; } pDevice->nControlMessageMaxSize = nControlMessageMaxSize; pDevice->pDescriptors = pDescriptors; pDevice->pControlBuffer = (XnUChar*)xnOSMallocAligned(nControlMessageMaxSize, XN_DEFAULT_MEM_ALIGN); if (pDevice->pControlBuffer == NULL) { xnUSBDeviceShutdown(pDevice); return XN_STATUS_ALLOC_FAILED; } nRetVal = xnOSCreateCriticalSection(&pDevice->hLock); if (nRetVal != XN_STATUS_OK) { xnUSBDeviceShutdown(pDevice); return (nRetVal); } nRetVal = xnOSCreateThread(xnUSBDeviceEndPoint0Handler, pDevice, &pDevice->hThread); if (nRetVal != XN_STATUS_OK) { xnUSBDeviceShutdown(pDevice); return (nRetVal); } *ppDevice = pDevice; return XN_STATUS_OK; } XN_C_API void XN_C_DECL xnUSBDeviceShutdown(XnUSBDevice* pDevice) { XN_ASSERT(pDevice != NULL); pDevice->bShutdown = TRUE; if (pDevice->hThread != NULL) { xnOSWaitAndTerminateThread(&pDevice->hThread, 10000); pDevice->hThread = NULL; } if (pDevice->hLock != NULL) { xnOSCloseCriticalSection(&pDevice->hLock); pDevice->hLock = NULL; } if (pDevice->pControlBuffer != NULL) { xnOSFreeAligned(pDevice->pControlBuffer); pDevice->pControlBuffer = NULL; } if (pDevice->deviceFD != -1) { close(pDevice->deviceFD); pDevice->deviceFD = -1; } xnOSFree(pDevice); } //--------------------------------------------------------------------------- // Handling Vendor Controls //--------------------------------------------------------------------------- XN_C_API XnBool XN_C_DECL xnUSBDeviceIsControlRequestPending(XnUSBDevice* pDevice) { XN_ASSERT(pDevice != NULL); if (pDevice != NULL) return FALSE; XnAutoCSLocker locker(pDevice->hLock); return (pDevice->eControlState == XN_USB_DEVICE_CONTROL_REQUEST_PENDING); } XN_C_API XnStatus XN_C_DECL xnUSBDeviceReceiveControlRequest(XnUSBDevice* pDevice, XnUChar* pBuffer, XnUInt32* pnRequestSize) { XnStatus nRetVal = XN_STATUS_OK; XN_VALIDATE_INPUT_PTR(pDevice); XN_VALIDATE_INPUT_PTR(pBuffer); XN_VALIDATE_OUTPUT_PTR(pnRequestSize); XnAutoCSLocker locker(pDevice->hLock); if (pDevice->eControlState != XN_USB_DEVICE_CONTROL_REQUEST_PENDING) { return XN_STATUS_USB_NO_REQUEST_PENDING; } xnOSMemCopy(pBuffer, pDevice->pControlBuffer, pDevice->nControlSize); *pnRequestSize = pDevice->nControlSize; pDevice->eControlState = XN_USB_DEVICE_CONTROL_REQUEST_PROCESSING; return (XN_STATUS_OK); } XN_C_API XnStatus XN_C_DECL xnUSBDeviceSendControlReply(XnUSBDevice* pDevice, const XnUChar* pBuffer, XnUInt32 nReplySize) { XnStatus nRetVal = XN_STATUS_OK; XN_VALIDATE_INPUT_PTR(pDevice); XN_VALIDATE_INPUT_PTR(pBuffer); XnAutoCSLocker locker(pDevice->hLock); switch (pDevice->eControlState) { case XN_USB_DEVICE_CONTROL_REPLY_PENDING: { // already got in control. we can write reply directly to USB int status = write(pDevice->deviceFD, pBuffer, nReplySize); if (status < 0) { perror("failed to send control reply"); return XN_STATUS_USB_CONTROL_SEND_FAILED; } pDevice->eControlState = XN_USB_DEVICE_CONTROL_CLEAR; break; } case XN_USB_DEVICE_CONTROL_REQUEST_PROCESSING: { // no in control yet. keep the reply for later xnOSMemCopy(pDevice->pControlBuffer, pBuffer, nReplySize); pDevice->nControlSize = nReplySize; pDevice->eControlState = XN_USB_DEVICE_CONTROL_REPLY_READY; break; } default: return XN_STATUS_USB_NO_REQUEST_PENDING; } return (XN_STATUS_OK); } static XnBool handleVendorControl(XnUSBDevice* pDevice, struct usb_ctrlrequest *setup) { __u16 length = __le16_to_cpu(setup->wLength); XnBool bHostRequest = (setup->bRequestType & USB_DIR_IN) ? 0 : 1; if (bHostRequest) { // read data stage if (length == 0) { return FALSE; } if (length > pDevice->nControlMessageMaxSize) { xnLogError(XN_MASK_OS, "Got a control message bigger than max allowed size!"); return FALSE; } XnAutoCSLocker locker(pDevice->hLock); if (pDevice->eControlState != XN_USB_DEVICE_CONTROL_CLEAR) { xnLogError(XN_MASK_OS, "Got a control request before previous one was replied!"); return FALSE; } // read the data int status = read(pDevice->deviceFD, pDevice->pControlBuffer, length); if (status < 0) { //perror("failed to read control request"); return FALSE; } pDevice->nControlSize = length; pDevice->eControlState = XN_USB_DEVICE_CONTROL_REQUEST_PENDING; // raise callback if (pDevice->pNewControlRequestCallback != NULL) { pDevice->pNewControlRequestCallback(pDevice, pDevice->pNewControlRequestCallbackCookie); } } else { // host requests to read. XnAutoCSLocker locker(pDevice->hLock); switch (pDevice->eControlState) { case XN_USB_DEVICE_CONTROL_REPLY_READY: { // reply is waiting to be send. send it now int status = write(pDevice->deviceFD, pDevice->pControlBuffer, pDevice->nControlSize); if (status < 0) { return FALSE; } pDevice->eControlState = XN_USB_DEVICE_CONTROL_CLEAR; break; } case XN_USB_DEVICE_CONTROL_REQUEST_PROCESSING: { // no reply yet. mark that we got the in control pDevice->eControlState = XN_USB_DEVICE_CONTROL_REPLY_PENDING; break; } default: // bad state return FALSE; } } return TRUE; } XN_C_API XnStatus XN_C_DECL xnUSBDeviceSetNewControlRequestCallback(XnUSBDevice* pDevice, XnUSBDeviceNewControlRequestCallback pFunc, void* pCookie) { XnStatus nRetVal = XN_STATUS_OK; XN_VALIDATE_INPUT_PTR(pDevice); XnAutoCSLocker locker(pDevice->hLock); pDevice->pNewControlRequestCallback = pFunc; pDevice->pNewControlRequestCallbackCookie = pCookie; return XN_STATUS_OK; } //--------------------------------------------------------------------------- // Writing Data //--------------------------------------------------------------------------- XN_C_API XnStatus XN_C_DECL xnUSBDeviceWriteEndpoint(XnUSBDevice* pDevice, XnUInt8 nAddress, XnUChar* pData, XnUInt32 nDataSize) { XnStatus nRetVal = XN_STATUS_OK; XN_VALIDATE_INPUT_PTR(pDevice); XN_VALIDATE_INPUT_PTR(pData); __u8 nIndex = nAddress & 0xF; int status = write(pDevice->endpointsFDs[nIndex], pData, nDataSize); if (status < 0) { xnLogWarning(XN_MASK_OS, "Failed to write data! (%d)", errno); return XN_STATUS_USB_ENDPOINT_WRITE_FAILED; } return XN_STATUS_OK; } #endif // XN_PLATFORM == XN_PLATFORM_LINUX_ARM
lgpl-3.0
mfine/libswiftnav
clapack-3.2.1-CMAKE/SRC/csysvx.c
26
13700
/* csysvx.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" #include "blaswrap.h" /* Table of constant values */ static integer c__1 = 1; static integer c_n1 = -1; /* Subroutine */ int csysvx_(char *fact, char *uplo, integer *n, integer * nrhs, complex *a, integer *lda, complex *af, integer *ldaf, integer * ipiv, complex *b, integer *ldb, complex *x, integer *ldx, real *rcond, real *ferr, real *berr, complex *work, integer *lwork, real *rwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, af_dim1, af_offset, b_dim1, b_offset, x_dim1, x_offset, i__1, i__2; /* Local variables */ integer nb; extern logical lsame_(char *, char *); real anorm; extern doublereal slamch_(char *); logical nofact; extern /* Subroutine */ int clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *); extern doublereal clansy_(char *, char *, integer *, complex *, integer *, real *); extern /* Subroutine */ int csycon_(char *, integer *, complex *, integer *, integer *, real *, real *, complex *, integer *), csyrfs_(char *, integer *, integer *, complex *, integer *, complex *, integer *, integer *, complex *, integer *, complex *, integer *, real *, real *, complex *, real *, integer *), csytrf_(char *, integer *, complex *, integer *, integer *, complex *, integer *, integer *); integer lwkopt; logical lquery; extern /* Subroutine */ int csytrs_(char *, integer *, integer *, complex *, integer *, integer *, complex *, integer *, integer *); /* -- LAPACK driver routine (version 3.2) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* CSYSVX uses the diagonal pivoting factorization to compute the */ /* solution to a complex system of linear equations A * X = B, */ /* where A is an N-by-N symmetric matrix and X and B are N-by-NRHS */ /* matrices. */ /* Error bounds on the solution and a condition estimate are also */ /* provided. */ /* Description */ /* =========== */ /* The following steps are performed: */ /* 1. If FACT = 'N', the diagonal pivoting method is used to factor A. */ /* The form of the factorization is */ /* A = U * D * U**T, if UPLO = 'U', or */ /* A = L * D * L**T, if UPLO = 'L', */ /* where U (or L) is a product of permutation and unit upper (lower) */ /* triangular matrices, and D is symmetric and block diagonal with */ /* 1-by-1 and 2-by-2 diagonal blocks. */ /* 2. If some D(i,i)=0, so that D is exactly singular, then the routine */ /* returns with INFO = i. Otherwise, the factored form of A is used */ /* to estimate the condition number of the matrix A. If the */ /* reciprocal of the condition number is less than machine precision, */ /* INFO = N+1 is returned as a warning, but the routine still goes on */ /* to solve for X and compute error bounds as described below. */ /* 3. The system of equations is solved for X using the factored form */ /* of A. */ /* 4. Iterative refinement is applied to improve the computed solution */ /* matrix and calculate error bounds and backward error estimates */ /* for it. */ /* Arguments */ /* ========= */ /* FACT (input) CHARACTER*1 */ /* Specifies whether or not the factored form of A has been */ /* supplied on entry. */ /* = 'F': On entry, AF and IPIV contain the factored form */ /* of A. A, AF and IPIV will not be modified. */ /* = 'N': The matrix A will be copied to AF and factored. */ /* UPLO (input) CHARACTER*1 */ /* = 'U': Upper triangle of A is stored; */ /* = 'L': Lower triangle of A is stored. */ /* N (input) INTEGER */ /* The number of linear equations, i.e., the order of the */ /* matrix A. N >= 0. */ /* NRHS (input) INTEGER */ /* The number of right hand sides, i.e., the number of columns */ /* of the matrices B and X. NRHS >= 0. */ /* A (input) COMPLEX array, dimension (LDA,N) */ /* The symmetric matrix A. If UPLO = 'U', the leading N-by-N */ /* upper triangular part of A contains the upper triangular part */ /* of the matrix A, and the strictly lower triangular part of A */ /* is not referenced. If UPLO = 'L', the leading N-by-N lower */ /* triangular part of A contains the lower triangular part of */ /* the matrix A, and the strictly upper triangular part of A is */ /* not referenced. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(1,N). */ /* AF (input or output) COMPLEX array, dimension (LDAF,N) */ /* If FACT = 'F', then AF is an input argument and on entry */ /* contains the block diagonal matrix D and the multipliers used */ /* to obtain the factor U or L from the factorization */ /* A = U*D*U**T or A = L*D*L**T as computed by CSYTRF. */ /* If FACT = 'N', then AF is an output argument and on exit */ /* returns the block diagonal matrix D and the multipliers used */ /* to obtain the factor U or L from the factorization */ /* A = U*D*U**T or A = L*D*L**T. */ /* LDAF (input) INTEGER */ /* The leading dimension of the array AF. LDAF >= max(1,N). */ /* IPIV (input or output) INTEGER array, dimension (N) */ /* If FACT = 'F', then IPIV is an input argument and on entry */ /* contains details of the interchanges and the block structure */ /* of D, as determined by CSYTRF. */ /* If IPIV(k) > 0, then rows and columns k and IPIV(k) were */ /* interchanged and D(k,k) is a 1-by-1 diagonal block. */ /* If UPLO = 'U' and IPIV(k) = IPIV(k-1) < 0, then rows and */ /* columns k-1 and -IPIV(k) were interchanged and D(k-1:k,k-1:k) */ /* is a 2-by-2 diagonal block. If UPLO = 'L' and IPIV(k) = */ /* IPIV(k+1) < 0, then rows and columns k+1 and -IPIV(k) were */ /* interchanged and D(k:k+1,k:k+1) is a 2-by-2 diagonal block. */ /* If FACT = 'N', then IPIV is an output argument and on exit */ /* contains details of the interchanges and the block structure */ /* of D, as determined by CSYTRF. */ /* B (input) COMPLEX array, dimension (LDB,NRHS) */ /* The N-by-NRHS right hand side matrix B. */ /* LDB (input) INTEGER */ /* The leading dimension of the array B. LDB >= max(1,N). */ /* X (output) COMPLEX array, dimension (LDX,NRHS) */ /* If INFO = 0 or INFO = N+1, the N-by-NRHS solution matrix X. */ /* LDX (input) INTEGER */ /* The leading dimension of the array X. LDX >= max(1,N). */ /* RCOND (output) REAL */ /* The estimate of the reciprocal condition number of the matrix */ /* A. If RCOND is less than the machine precision (in */ /* particular, if RCOND = 0), the matrix is singular to working */ /* precision. This condition is indicated by a return code of */ /* INFO > 0. */ /* FERR (output) REAL array, dimension (NRHS) */ /* The estimated forward error bound for each solution vector */ /* X(j) (the j-th column of the solution matrix X). */ /* If XTRUE is the true solution corresponding to X(j), FERR(j) */ /* is an estimated upper bound for the magnitude of the largest */ /* element in (X(j) - XTRUE) divided by the magnitude of the */ /* largest element in X(j). The estimate is as reliable as */ /* the estimate for RCOND, and is almost always a slight */ /* overestimate of the true error. */ /* BERR (output) REAL array, dimension (NRHS) */ /* The componentwise relative backward error of each solution */ /* vector X(j) (i.e., the smallest relative change in */ /* any element of A or B that makes X(j) an exact solution). */ /* WORK (workspace/output) COMPLEX array, dimension (MAX(1,LWORK)) */ /* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ /* LWORK (input) INTEGER */ /* The length of WORK. LWORK >= max(1,2*N), and for best */ /* performance, when FACT = 'N', LWORK >= max(1,2*N,N*NB), where */ /* NB is the optimal blocksize for CSYTRF. */ /* If LWORK = -1, then a workspace query is assumed; the routine */ /* only calculates the optimal size of the WORK array, returns */ /* this value as the first entry of the WORK array, and no error */ /* message related to LWORK is issued by XERBLA. */ /* RWORK (workspace) REAL array, dimension (N) */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument had an illegal value */ /* > 0: if INFO = i, and i is */ /* <= N: D(i,i) is exactly zero. The factorization */ /* has been completed but the factor D is exactly */ /* singular, so the solution and error bounds could */ /* not be computed. RCOND = 0 is returned. */ /* = N+1: D is nonsingular, but RCOND is less than machine */ /* precision, meaning that the matrix is singular */ /* to working precision. Nevertheless, the */ /* solution and error bounds are computed because */ /* there are a number of situations where the */ /* computed solution can be more accurate than the */ /* value of RCOND would suggest. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; af_dim1 = *ldaf; af_offset = 1 + af_dim1; af -= af_offset; --ipiv; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; x_dim1 = *ldx; x_offset = 1 + x_dim1; x -= x_offset; --ferr; --berr; --work; --rwork; /* Function Body */ *info = 0; nofact = lsame_(fact, "N"); lquery = *lwork == -1; if (! nofact && ! lsame_(fact, "F")) { *info = -1; } else if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*nrhs < 0) { *info = -4; } else if (*lda < max(1,*n)) { *info = -6; } else if (*ldaf < max(1,*n)) { *info = -8; } else if (*ldb < max(1,*n)) { *info = -11; } else if (*ldx < max(1,*n)) { *info = -13; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = 1, i__2 = *n << 1; if (*lwork < max(i__1,i__2) && ! lquery) { *info = -18; } } if (*info == 0) { /* Computing MAX */ i__1 = 1, i__2 = *n << 1; lwkopt = max(i__1,i__2); if (nofact) { nb = ilaenv_(&c__1, "CSYTRF", uplo, n, &c_n1, &c_n1, &c_n1); /* Computing MAX */ i__1 = lwkopt, i__2 = *n * nb; lwkopt = max(i__1,i__2); } work[1].r = (real) lwkopt, work[1].i = 0.f; } if (*info != 0) { i__1 = -(*info); xerbla_("CSYSVX", &i__1); return 0; } else if (lquery) { return 0; } if (nofact) { /* Compute the factorization A = U*D*U' or A = L*D*L'. */ clacpy_(uplo, n, n, &a[a_offset], lda, &af[af_offset], ldaf); csytrf_(uplo, n, &af[af_offset], ldaf, &ipiv[1], &work[1], lwork, info); /* Return if INFO is non-zero. */ if (*info > 0) { *rcond = 0.f; return 0; } } /* Compute the norm of the matrix A. */ anorm = clansy_("I", uplo, n, &a[a_offset], lda, &rwork[1]); /* Compute the reciprocal of the condition number of A. */ csycon_(uplo, n, &af[af_offset], ldaf, &ipiv[1], &anorm, rcond, &work[1], info); /* Compute the solution vectors X. */ clacpy_("Full", n, nrhs, &b[b_offset], ldb, &x[x_offset], ldx); csytrs_(uplo, n, nrhs, &af[af_offset], ldaf, &ipiv[1], &x[x_offset], ldx, info); /* Use iterative refinement to improve the computed solutions and */ /* compute error bounds and backward error estimates for them. */ csyrfs_(uplo, n, nrhs, &a[a_offset], lda, &af[af_offset], ldaf, &ipiv[1], &b[b_offset], ldb, &x[x_offset], ldx, &ferr[1], &berr[1], &work[1] , &rwork[1], info); /* Set INFO = N+1 if the matrix is singular to working precision. */ if (*rcond < slamch_("Epsilon")) { *info = *n + 1; } work[1].r = (real) lwkopt, work[1].i = 0.f; return 0; /* End of CSYSVX */ } /* csysvx_ */
lgpl-3.0
fnoble/libswiftnav
clapack-3.2.1-CMAKE/SRC/slaqgb.c
26
6153
/* slaqgb.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" #include "blaswrap.h" /* Subroutine */ int slaqgb_(integer *m, integer *n, integer *kl, integer *ku, real *ab, integer *ldab, real *r__, real *c__, real *rowcnd, real * colcnd, real *amax, char *equed) { /* System generated locals */ integer ab_dim1, ab_offset, i__1, i__2, i__3, i__4, i__5, i__6; /* Local variables */ integer i__, j; real cj, large, small; extern doublereal slamch_(char *); /* -- LAPACK auxiliary routine (version 3.2) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* SLAQGB equilibrates a general M by N band matrix A with KL */ /* subdiagonals and KU superdiagonals using the row and scaling factors */ /* in the vectors R and C. */ /* Arguments */ /* ========= */ /* M (input) INTEGER */ /* The number of rows of the matrix A. M >= 0. */ /* N (input) INTEGER */ /* The number of columns of the matrix A. N >= 0. */ /* KL (input) INTEGER */ /* The number of subdiagonals within the band of A. KL >= 0. */ /* KU (input) INTEGER */ /* The number of superdiagonals within the band of A. KU >= 0. */ /* AB (input/output) REAL array, dimension (LDAB,N) */ /* On entry, the matrix A in band storage, in rows 1 to KL+KU+1. */ /* The j-th column of A is stored in the j-th column of the */ /* array AB as follows: */ /* AB(ku+1+i-j,j) = A(i,j) for max(1,j-ku)<=i<=min(m,j+kl) */ /* On exit, the equilibrated matrix, in the same storage format */ /* as A. See EQUED for the form of the equilibrated matrix. */ /* LDAB (input) INTEGER */ /* The leading dimension of the array AB. LDA >= KL+KU+1. */ /* R (input) REAL array, dimension (M) */ /* The row scale factors for A. */ /* C (input) REAL array, dimension (N) */ /* The column scale factors for A. */ /* ROWCND (input) REAL */ /* Ratio of the smallest R(i) to the largest R(i). */ /* COLCND (input) REAL */ /* Ratio of the smallest C(i) to the largest C(i). */ /* AMAX (input) REAL */ /* Absolute value of largest matrix entry. */ /* EQUED (output) CHARACTER*1 */ /* Specifies the form of equilibration that was done. */ /* = 'N': No equilibration */ /* = 'R': Row equilibration, i.e., A has been premultiplied by */ /* diag(R). */ /* = 'C': Column equilibration, i.e., A has been postmultiplied */ /* by diag(C). */ /* = 'B': Both row and column equilibration, i.e., A has been */ /* replaced by diag(R) * A * diag(C). */ /* Internal Parameters */ /* =================== */ /* THRESH is a threshold value used to decide if row or column scaling */ /* should be done based on the ratio of the row or column scaling */ /* factors. If ROWCND < THRESH, row scaling is done, and if */ /* COLCND < THRESH, column scaling is done. */ /* LARGE and SMALL are threshold values used to decide if row scaling */ /* should be done based on the absolute size of the largest matrix */ /* element. If AMAX > LARGE or AMAX < SMALL, row scaling is done. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Quick return if possible */ /* Parameter adjustments */ ab_dim1 = *ldab; ab_offset = 1 + ab_dim1; ab -= ab_offset; --r__; --c__; /* Function Body */ if (*m <= 0 || *n <= 0) { *(unsigned char *)equed = 'N'; return 0; } /* Initialize LARGE and SMALL. */ small = slamch_("Safe minimum") / slamch_("Precision"); large = 1.f / small; if (*rowcnd >= .1f && *amax >= small && *amax <= large) { /* No row scaling */ if (*colcnd >= .1f) { /* No column scaling */ *(unsigned char *)equed = 'N'; } else { /* Column scaling */ i__1 = *n; for (j = 1; j <= i__1; ++j) { cj = c__[j]; /* Computing MAX */ i__2 = 1, i__3 = j - *ku; /* Computing MIN */ i__5 = *m, i__6 = j + *kl; i__4 = min(i__5,i__6); for (i__ = max(i__2,i__3); i__ <= i__4; ++i__) { ab[*ku + 1 + i__ - j + j * ab_dim1] = cj * ab[*ku + 1 + i__ - j + j * ab_dim1]; /* L10: */ } /* L20: */ } *(unsigned char *)equed = 'C'; } } else if (*colcnd >= .1f) { /* Row scaling, no column scaling */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__4 = 1, i__2 = j - *ku; /* Computing MIN */ i__5 = *m, i__6 = j + *kl; i__3 = min(i__5,i__6); for (i__ = max(i__4,i__2); i__ <= i__3; ++i__) { ab[*ku + 1 + i__ - j + j * ab_dim1] = r__[i__] * ab[*ku + 1 + i__ - j + j * ab_dim1]; /* L30: */ } /* L40: */ } *(unsigned char *)equed = 'R'; } else { /* Row and column scaling */ i__1 = *n; for (j = 1; j <= i__1; ++j) { cj = c__[j]; /* Computing MAX */ i__3 = 1, i__4 = j - *ku; /* Computing MIN */ i__5 = *m, i__6 = j + *kl; i__2 = min(i__5,i__6); for (i__ = max(i__3,i__4); i__ <= i__2; ++i__) { ab[*ku + 1 + i__ - j + j * ab_dim1] = cj * r__[i__] * ab[*ku + 1 + i__ - j + j * ab_dim1]; /* L50: */ } /* L60: */ } *(unsigned char *)equed = 'B'; } return 0; /* End of SLAQGB */ } /* slaqgb_ */
lgpl-3.0
FlibbleMr/neogfx
3rdparty/zlib/zlib-1.2.8/contrib/minizip/minizip.c
1119
15034
/* minizip.c Version 1.1, February 14h, 2010 sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) Modifications of Unzip for Zip64 Copyright (C) 2007-2008 Even Rouault Modifications for Zip64 support on both zip and unzip Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) */ #if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__)) #ifndef __USE_FILE_OFFSET64 #define __USE_FILE_OFFSET64 #endif #ifndef __USE_LARGEFILE64 #define __USE_LARGEFILE64 #endif #ifndef _LARGEFILE64_SOURCE #define _LARGEFILE64_SOURCE #endif #ifndef _FILE_OFFSET_BIT #define _FILE_OFFSET_BIT 64 #endif #endif #ifdef __APPLE__ // In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions #define FOPEN_FUNC(filename, mode) fopen(filename, mode) #define FTELLO_FUNC(stream) ftello(stream) #define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) #else #define FOPEN_FUNC(filename, mode) fopen64(filename, mode) #define FTELLO_FUNC(stream) ftello64(stream) #define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <errno.h> #include <fcntl.h> #ifdef _WIN32 # include <direct.h> # include <io.h> #else # include <unistd.h> # include <utime.h> # include <sys/types.h> # include <sys/stat.h> #endif #include "zip.h" #ifdef _WIN32 #define USEWIN32IOAPI #include "iowin32.h" #endif #define WRITEBUFFERSIZE (16384) #define MAXFILENAME (256) #ifdef _WIN32 uLong filetime(f, tmzip, dt) char *f; /* name of file to get info on */ tm_zip *tmzip; /* return value: access, modific. and creation times */ uLong *dt; /* dostime */ { int ret = 0; { FILETIME ftLocal; HANDLE hFind; WIN32_FIND_DATAA ff32; hFind = FindFirstFileA(f,&ff32); if (hFind != INVALID_HANDLE_VALUE) { FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal); FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0); FindClose(hFind); ret = 1; } } return ret; } #else #ifdef unix || __APPLE__ uLong filetime(f, tmzip, dt) char *f; /* name of file to get info on */ tm_zip *tmzip; /* return value: access, modific. and creation times */ uLong *dt; /* dostime */ { int ret=0; struct stat s; /* results of stat() */ struct tm* filedate; time_t tm_t=0; if (strcmp(f,"-")!=0) { char name[MAXFILENAME+1]; int len = strlen(f); if (len > MAXFILENAME) len = MAXFILENAME; strncpy(name, f,MAXFILENAME-1); /* strncpy doesnt append the trailing NULL, of the string is too long. */ name[ MAXFILENAME ] = '\0'; if (name[len - 1] == '/') name[len - 1] = '\0'; /* not all systems allow stat'ing a file with / appended */ if (stat(name,&s)==0) { tm_t = s.st_mtime; ret = 1; } } filedate = localtime(&tm_t); tmzip->tm_sec = filedate->tm_sec; tmzip->tm_min = filedate->tm_min; tmzip->tm_hour = filedate->tm_hour; tmzip->tm_mday = filedate->tm_mday; tmzip->tm_mon = filedate->tm_mon ; tmzip->tm_year = filedate->tm_year; return ret; } #else uLong filetime(f, tmzip, dt) char *f; /* name of file to get info on */ tm_zip *tmzip; /* return value: access, modific. and creation times */ uLong *dt; /* dostime */ { return 0; } #endif #endif int check_exist_file(filename) const char* filename; { FILE* ftestexist; int ret = 1; ftestexist = FOPEN_FUNC(filename,"rb"); if (ftestexist==NULL) ret = 0; else fclose(ftestexist); return ret; } void do_banner() { printf("MiniZip 1.1, demo of zLib + MiniZip64 package, written by Gilles Vollant\n"); printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n"); } void do_help() { printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \ " -o Overwrite existing file.zip\n" \ " -a Append to existing file.zip\n" \ " -0 Store only\n" \ " -1 Compress faster\n" \ " -9 Compress better\n\n" \ " -j exclude path. store only the file name.\n\n"); } /* calculate the CRC32 of a file, because to encrypt a file, we need known the CRC32 of the file before */ int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc) { unsigned long calculate_crc=0; int err=ZIP_OK; FILE * fin = FOPEN_FUNC(filenameinzip,"rb"); unsigned long size_read = 0; unsigned long total_read = 0; if (fin==NULL) { err = ZIP_ERRNO; } if (err == ZIP_OK) do { err = ZIP_OK; size_read = (int)fread(buf,1,size_buf,fin); if (size_read < size_buf) if (feof(fin)==0) { printf("error in reading %s\n",filenameinzip); err = ZIP_ERRNO; } if (size_read>0) calculate_crc = crc32(calculate_crc,buf,size_read); total_read += size_read; } while ((err == ZIP_OK) && (size_read>0)); if (fin) fclose(fin); *result_crc=calculate_crc; printf("file %s crc %lx\n", filenameinzip, calculate_crc); return err; } int isLargeFile(const char* filename) { int largeFile = 0; ZPOS64_T pos = 0; FILE* pFile = FOPEN_FUNC(filename, "rb"); if(pFile != NULL) { int n = FSEEKO_FUNC(pFile, 0, SEEK_END); pos = FTELLO_FUNC(pFile); printf("File : %s is %lld bytes\n", filename, pos); if(pos >= 0xffffffff) largeFile = 1; fclose(pFile); } return largeFile; } int main(argc,argv) int argc; char *argv[]; { int i; int opt_overwrite=0; int opt_compress_level=Z_DEFAULT_COMPRESSION; int opt_exclude_path=0; int zipfilenamearg = 0; char filename_try[MAXFILENAME+16]; int zipok; int err=0; int size_buf=0; void* buf=NULL; const char* password=NULL; do_banner(); if (argc==1) { do_help(); return 0; } else { for (i=1;i<argc;i++) { if ((*argv[i])=='-') { const char *p=argv[i]+1; while ((*p)!='\0') { char c=*(p++);; if ((c=='o') || (c=='O')) opt_overwrite = 1; if ((c=='a') || (c=='A')) opt_overwrite = 2; if ((c>='0') && (c<='9')) opt_compress_level = c-'0'; if ((c=='j') || (c=='J')) opt_exclude_path = 1; if (((c=='p') || (c=='P')) && (i+1<argc)) { password=argv[i+1]; i++; } } } else { if (zipfilenamearg == 0) { zipfilenamearg = i ; } } } } size_buf = WRITEBUFFERSIZE; buf = (void*)malloc(size_buf); if (buf==NULL) { printf("Error allocating memory\n"); return ZIP_INTERNALERROR; } if (zipfilenamearg==0) { zipok=0; } else { int i,len; int dot_found=0; zipok = 1 ; strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME-1); /* strncpy doesnt append the trailing NULL, of the string is too long. */ filename_try[ MAXFILENAME ] = '\0'; len=(int)strlen(filename_try); for (i=0;i<len;i++) if (filename_try[i]=='.') dot_found=1; if (dot_found==0) strcat(filename_try,".zip"); if (opt_overwrite==2) { /* if the file don't exist, we not append file */ if (check_exist_file(filename_try)==0) opt_overwrite=1; } else if (opt_overwrite==0) if (check_exist_file(filename_try)!=0) { char rep=0; do { char answer[128]; int ret; printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try); ret = scanf("%1s",answer); if (ret != 1) { exit(EXIT_FAILURE); } rep = answer[0] ; if ((rep>='a') && (rep<='z')) rep -= 0x20; } while ((rep!='Y') && (rep!='N') && (rep!='A')); if (rep=='N') zipok = 0; if (rep=='A') opt_overwrite = 2; } } if (zipok==1) { zipFile zf; int errclose; # ifdef USEWIN32IOAPI zlib_filefunc64_def ffunc; fill_win32_filefunc64A(&ffunc); zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc); # else zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0); # endif if (zf == NULL) { printf("error opening %s\n",filename_try); err= ZIP_ERRNO; } else printf("creating %s\n",filename_try); for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++) { if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) && ((argv[i][1]=='o') || (argv[i][1]=='O') || (argv[i][1]=='a') || (argv[i][1]=='A') || (argv[i][1]=='p') || (argv[i][1]=='P') || ((argv[i][1]>='0') || (argv[i][1]<='9'))) && (strlen(argv[i]) == 2))) { FILE * fin; int size_read; const char* filenameinzip = argv[i]; const char *savefilenameinzip; zip_fileinfo zi; unsigned long crcFile=0; int zip64 = 0; zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0; zi.dosDate = 0; zi.internal_fa = 0; zi.external_fa = 0; filetime(filenameinzip,&zi.tmz_date,&zi.dosDate); /* err = zipOpenNewFileInZip(zf,filenameinzip,&zi, NULL,0,NULL,0,NULL / * comment * /, (opt_compress_level != 0) ? Z_DEFLATED : 0, opt_compress_level); */ if ((password != NULL) && (err==ZIP_OK)) err = getFileCrc(filenameinzip,buf,size_buf,&crcFile); zip64 = isLargeFile(filenameinzip); /* The path name saved, should not include a leading slash. */ /*if it did, windows/xp and dynazip couldn't read the zip file. */ savefilenameinzip = filenameinzip; while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' ) { savefilenameinzip++; } /*should the zip file contain any path at all?*/ if( opt_exclude_path ) { const char *tmpptr; const char *lastslash = 0; for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++) { if( *tmpptr == '\\' || *tmpptr == '/') { lastslash = tmpptr; } } if( lastslash != NULL ) { savefilenameinzip = lastslash+1; // base filename follows last slash. } } /**/ err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi, NULL,0,NULL,0,NULL /* comment*/, (opt_compress_level != 0) ? Z_DEFLATED : 0, opt_compress_level,0, /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */ -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password,crcFile, zip64); if (err != ZIP_OK) printf("error in opening %s in zipfile\n",filenameinzip); else { fin = FOPEN_FUNC(filenameinzip,"rb"); if (fin==NULL) { err=ZIP_ERRNO; printf("error in opening %s for reading\n",filenameinzip); } } if (err == ZIP_OK) do { err = ZIP_OK; size_read = (int)fread(buf,1,size_buf,fin); if (size_read < size_buf) if (feof(fin)==0) { printf("error in reading %s\n",filenameinzip); err = ZIP_ERRNO; } if (size_read>0) { err = zipWriteInFileInZip (zf,buf,size_read); if (err<0) { printf("error in writing %s in the zipfile\n", filenameinzip); } } } while ((err == ZIP_OK) && (size_read>0)); if (fin) fclose(fin); if (err<0) err=ZIP_ERRNO; else { err = zipCloseFileInZip(zf); if (err!=ZIP_OK) printf("error in closing %s in the zipfile\n", filenameinzip); } } } errclose = zipClose(zf,NULL); if (errclose != ZIP_OK) printf("error in closing %s\n",filename_try); } else { do_help(); } free(buf); return 0; }
lgpl-3.0
tunneff/tef
deps/boost_1_63_0/libs/python/src/object/inheritance.cpp
127
14710
// Copyright David Abrahams 2002. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/python/object/inheritance.hpp> #include <boost/python/type_id.hpp> #include <boost/graph/breadth_first_search.hpp> #if _MSC_FULL_VER >= 13102171 && _MSC_FULL_VER <= 13102179 # include <boost/graph/reverse_graph.hpp> #endif #include <boost/graph/adjacency_list.hpp> #include <boost/graph/reverse_graph.hpp> #include <boost/property_map/property_map.hpp> #include <boost/bind.hpp> #include <boost/integer_traits.hpp> #include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple_comparison.hpp> #include <queue> #include <vector> #include <functional> // // Procedure: // // The search is a BFS over the space of (type,address) pairs // guided by the edges of the casting graph whose nodes // correspond to classes, and whose edges are traversed by // applying associated cast functions to an address. We use // vertex distance to the goal node in the cast_graph to rate the // paths. The vertex distance to any goal node is calculated on // demand and outdated by the addition of edges to the graph. namespace boost { namespace { enum edge_cast_t { edge_cast = 8010 }; template <class T> inline void unused_variable(const T&) { } } // Install properties BOOST_INSTALL_PROPERTY(edge, cast); namespace { typedef void*(*cast_function)(void*); // // Here we put together the low-level data structures of the // casting graph representation. // typedef python::type_info class_id; // represents a graph of available casts #if 0 struct cast_graph : #else typedef #endif adjacency_list<vecS,vecS, bidirectionalS, no_property // edge index property allows us to look up edges in the connectivity matrix , property<edge_index_t,std::size_t // The function which casts a void* from the edge's source type // to its destination type. , property<edge_cast_t,cast_function> > > #if 0 {}; #else cast_graph; #endif typedef cast_graph::vertex_descriptor vertex_t; typedef cast_graph::edge_descriptor edge_t; struct smart_graph { typedef std::vector<std::size_t>::const_iterator node_distance_map; typedef std::pair<cast_graph::out_edge_iterator , cast_graph::out_edge_iterator> out_edges_t; // Return a map of the distances from any node to the given // target node node_distance_map distances_to(vertex_t target) const { std::size_t n = num_vertices(m_topology); if (m_distances.size() != n * n) { m_distances.clear(); m_distances.resize(n * n, (std::numeric_limits<std::size_t>::max)()); m_known_vertices = n; } std::vector<std::size_t>::iterator to_target = m_distances.begin() + n * target; // this node hasn't been used as a target yet if (to_target[target] != 0) { typedef reverse_graph<cast_graph> reverse_cast_graph; reverse_cast_graph reverse_topology(m_topology); to_target[target] = 0; breadth_first_search( reverse_topology, target , visitor( make_bfs_visitor( record_distances( make_iterator_property_map( to_target , get(vertex_index, reverse_topology) # ifdef BOOST_NO_STD_ITERATOR_TRAITS , *to_target # endif ) , on_tree_edge() )))); } return to_target; } cast_graph& topology() { return m_topology; } cast_graph const& topology() const { return m_topology; } smart_graph() : m_known_vertices(0) {} private: cast_graph m_topology; mutable std::vector<std::size_t> m_distances; mutable std::size_t m_known_vertices; }; smart_graph& full_graph() { static smart_graph x; return x; } smart_graph& up_graph() { static smart_graph x; return x; } // // Our index of class types // using boost::python::objects::dynamic_id_function; typedef tuples::tuple< class_id // static type , vertex_t // corresponding vertex , dynamic_id_function // dynamic_id if polymorphic, or 0 > index_entry_interface; typedef index_entry_interface::inherited index_entry; enum { ksrc_static_t, kvertex, kdynamic_id }; typedef std::vector<index_entry> type_index_t; type_index_t& type_index() { static type_index_t x; return x; } template <class Tuple> struct select1st { typedef typename tuples::element<0, Tuple>::type result_type; result_type const& operator()(Tuple const& x) const { return tuples::get<0>(x); } }; // map a type to a position in the index inline type_index_t::iterator type_position(class_id type) { typedef index_entry entry; return std::lower_bound( type_index().begin(), type_index().end() , boost::make_tuple(type, vertex_t(), dynamic_id_function(0)) , boost::bind<bool>(std::less<class_id>() , boost::bind<class_id>(select1st<entry>(), _1) , boost::bind<class_id>(select1st<entry>(), _2))); } inline index_entry* seek_type(class_id type) { type_index_t::iterator p = type_position(type); if (p == type_index().end() || tuples::get<ksrc_static_t>(*p) != type) return 0; else return &*p; } // Get the entry for a type, inserting if necessary inline type_index_t::iterator demand_type(class_id type) { type_index_t::iterator p = type_position(type); if (p != type_index().end() && tuples::get<ksrc_static_t>(*p) == type) return p; vertex_t v = add_vertex(full_graph().topology()); vertex_t v2 = add_vertex(up_graph().topology()); unused_variable(v2); assert(v == v2); return type_index().insert(p, boost::make_tuple(type, v, dynamic_id_function(0))); } // Map a two types to a vertex in the graph, inserting if necessary typedef std::pair<type_index_t::iterator, type_index_t::iterator> type_index_iterator_pair; inline type_index_iterator_pair demand_types(class_id t1, class_id t2) { // be sure there will be no reallocation type_index().reserve(type_index().size() + 2); type_index_t::iterator first = demand_type(t1); type_index_t::iterator second = demand_type(t2); if (first == second) ++first; return std::make_pair(first, second); } struct q_elt { q_elt(std::size_t distance , void* src_address , vertex_t target , cast_function cast ) : distance(distance) , src_address(src_address) , target(target) , cast(cast) {} std::size_t distance; void* src_address; vertex_t target; cast_function cast; bool operator<(q_elt const& rhs) const { return distance < rhs.distance; } }; // Optimization: // // Given p, src_t, dst_t // // Get a pointer pd to the most-derived object // if it's polymorphic, dynamic_cast to void* // otherwise pd = p // // Get the most-derived typeid src_td // // ptrdiff_t offset = p - pd // // Now we can keep a cache, for [src_t, offset, src_td, dst_t] of // the cast transformation function to use on p and the next src_t // in the chain. src_td, dst_t don't change throughout this // process. In order to represent unreachability, when a pair is // found to be unreachable, we stick a 0-returning "dead-cast" // function in the cache. // This is needed in a few places below inline void* identity_cast(void* p) { return p; } void* search(smart_graph const& g, void* p, vertex_t src, vertex_t dst) { // I think this test was thoroughly bogus -- dwa // If we know there's no path; bail now. // if (src > g.known_vertices() || dst > g.known_vertices()) // return 0; smart_graph::node_distance_map d(g.distances_to(dst)); if (d[src] == (std::numeric_limits<std::size_t>::max)()) return 0; typedef property_map<cast_graph,edge_cast_t>::const_type cast_map; cast_map casts = get(edge_cast, g.topology()); typedef std::pair<vertex_t,void*> search_state; typedef std::vector<search_state> visited_t; visited_t visited; std::priority_queue<q_elt> q; q.push(q_elt(d[src], p, src, identity_cast)); while (!q.empty()) { q_elt top = q.top(); q.pop(); // Check to see if we have a real state void* dst_address = top.cast(top.src_address); if (dst_address == 0) continue; if (top.target == dst) return dst_address; search_state s(top.target,dst_address); visited_t::iterator pos = std::lower_bound( visited.begin(), visited.end(), s); // If already visited, continue if (pos != visited.end() && *pos == s) continue; visited.insert(pos, s); // mark it // expand it: smart_graph::out_edges_t edges = out_edges(s.first, g.topology()); for (cast_graph::out_edge_iterator p = edges.first , finish = edges.second ; p != finish ; ++p ) { edge_t e = *p; q.push(q_elt( d[target(e, g.topology())] , dst_address , target(e, g.topology()) , boost::get(casts, e))); } } return 0; } struct cache_element { typedef tuples::tuple< class_id // source static type , class_id // target type , std::ptrdiff_t // offset within source object , class_id // source dynamic type >::inherited key_type; cache_element(key_type const& k) : key(k) , offset(0) {} key_type key; std::ptrdiff_t offset; BOOST_STATIC_CONSTANT( std::ptrdiff_t, not_found = integer_traits<std::ptrdiff_t>::const_min); bool operator<(cache_element const& rhs) const { return this->key < rhs.key; } bool unreachable() const { return offset == not_found; } }; enum { kdst_t = ksrc_static_t + 1, koffset, ksrc_dynamic_t }; typedef std::vector<cache_element> cache_t; cache_t& cache() { static cache_t x; return x; } inline void* convert_type(void* const p, class_id src_t, class_id dst_t, bool polymorphic) { // Quickly rule out unregistered types index_entry* src_p = seek_type(src_t); if (src_p == 0) return 0; index_entry* dst_p = seek_type(dst_t); if (dst_p == 0) return 0; // Look up the dynamic_id function and call it to get the dynamic // info boost::python::objects::dynamic_id_t dynamic_id = polymorphic ? tuples::get<kdynamic_id>(*src_p)(p) : std::make_pair(p, src_t); // Look in the cache first for a quickie address translation std::ptrdiff_t offset = (char*)p - (char*)dynamic_id.first; cache_element seek(boost::make_tuple(src_t, dst_t, offset, dynamic_id.second)); cache_t& c = cache(); cache_t::iterator const cache_pos = std::lower_bound(c.begin(), c.end(), seek); // if found in the cache, we're done if (cache_pos != c.end() && cache_pos->key == seek.key) { return cache_pos->offset == cache_element::not_found ? 0 : (char*)p + cache_pos->offset; } // If we are starting at the most-derived type, only look in the up graph smart_graph const& g = polymorphic && dynamic_id.second != src_t ? full_graph() : up_graph(); void* result = search( g, p, tuples::get<kvertex>(*src_p) , tuples::get<kvertex>(*dst_p)); // update the cache c.insert(cache_pos, seek)->offset = (result == 0) ? cache_element::not_found : (char*)result - (char*)p; return result; } } namespace python { namespace objects { BOOST_PYTHON_DECL void* find_dynamic_type(void* p, class_id src_t, class_id dst_t) { return convert_type(p, src_t, dst_t, true); } BOOST_PYTHON_DECL void* find_static_type(void* p, class_id src_t, class_id dst_t) { return convert_type(p, src_t, dst_t, false); } BOOST_PYTHON_DECL void add_cast( class_id src_t, class_id dst_t, cast_function cast, bool is_downcast) { // adding an edge will invalidate any record of unreachability in // the cache. static std::size_t expected_cache_len = 0; cache_t& c = cache(); if (c.size() > expected_cache_len) { c.erase(std::remove_if( c.begin(), c.end(), mem_fn(&cache_element::unreachable)) , c.end()); // If any new cache entries get added, we'll have to do this // again when the next edge is added expected_cache_len = c.size(); } type_index_iterator_pair types = demand_types(src_t, dst_t); vertex_t src = tuples::get<kvertex>(*types.first); vertex_t dst = tuples::get<kvertex>(*types.second); cast_graph* const g[2] = { &up_graph().topology(), &full_graph().topology() }; for (cast_graph*const* p = g + (is_downcast ? 1 : 0); p < g + 2; ++p) { edge_t e; bool added; tie(e, added) = add_edge(src, dst, **p); assert(added); put(get(edge_cast, **p), e, cast); put(get(edge_index, **p), e, num_edges(full_graph().topology()) - 1); } } BOOST_PYTHON_DECL void register_dynamic_id_aux( class_id static_id, dynamic_id_function get_dynamic_id) { tuples::get<kdynamic_id>(*demand_type(static_id)) = get_dynamic_id; } }}} // namespace boost::python::objects
lgpl-3.0
EvanHa/rbp
linux/drivers/net/mii.c
1156
12617
/* mii.c: MII interface library Maintained by Jeff Garzik <jgarzik@pobox.com> Copyright 2001,2002 Jeff Garzik Various code came from myson803.c and other files by Donald Becker. Copyright: Written 1998-2002 by Donald Becker. This software may be used and distributed according to the terms of the GNU General Public License (GPL), incorporated herein by reference. Drivers based on or derived from this code fall under the GPL and must retain the authorship, copyright and license notice. This file is not a complete program and may only be used when the entire operating system is licensed under the GPL. The author may be reached as becker@scyld.com, or C/O Scyld Computing Corporation 410 Severn Ave., Suite 210 Annapolis MD 21403 */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/netdevice.h> #include <linux/ethtool.h> #include <linux/mii.h> static u32 mii_get_an(struct mii_if_info *mii, u16 addr) { int advert; advert = mii->mdio_read(mii->dev, mii->phy_id, addr); return mii_lpa_to_ethtool_lpa_t(advert); } /** * mii_ethtool_gset - get settings that are specified in @ecmd * @mii: MII interface * @ecmd: requested ethtool_cmd * * The @ecmd parameter is expected to have been cleared before calling * mii_ethtool_gset(). * * Returns 0 for success, negative on error. */ int mii_ethtool_gset(struct mii_if_info *mii, struct ethtool_cmd *ecmd) { struct net_device *dev = mii->dev; u16 bmcr, bmsr, ctrl1000 = 0, stat1000 = 0; u32 nego; ecmd->supported = (SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_Autoneg | SUPPORTED_TP | SUPPORTED_MII); if (mii->supports_gmii) ecmd->supported |= SUPPORTED_1000baseT_Half | SUPPORTED_1000baseT_Full; /* only supports twisted-pair */ ecmd->port = PORT_MII; /* only supports internal transceiver */ ecmd->transceiver = XCVR_INTERNAL; /* this isn't fully supported at higher layers */ ecmd->phy_address = mii->phy_id; ecmd->mdio_support = ETH_MDIO_SUPPORTS_C22; ecmd->advertising = ADVERTISED_TP | ADVERTISED_MII; bmcr = mii->mdio_read(dev, mii->phy_id, MII_BMCR); bmsr = mii->mdio_read(dev, mii->phy_id, MII_BMSR); if (mii->supports_gmii) { ctrl1000 = mii->mdio_read(dev, mii->phy_id, MII_CTRL1000); stat1000 = mii->mdio_read(dev, mii->phy_id, MII_STAT1000); } if (bmcr & BMCR_ANENABLE) { ecmd->advertising |= ADVERTISED_Autoneg; ecmd->autoneg = AUTONEG_ENABLE; ecmd->advertising |= mii_get_an(mii, MII_ADVERTISE); if (mii->supports_gmii) ecmd->advertising |= mii_ctrl1000_to_ethtool_adv_t(ctrl1000); if (bmsr & BMSR_ANEGCOMPLETE) { ecmd->lp_advertising = mii_get_an(mii, MII_LPA); ecmd->lp_advertising |= mii_stat1000_to_ethtool_lpa_t(stat1000); } else { ecmd->lp_advertising = 0; } nego = ecmd->advertising & ecmd->lp_advertising; if (nego & (ADVERTISED_1000baseT_Full | ADVERTISED_1000baseT_Half)) { ethtool_cmd_speed_set(ecmd, SPEED_1000); ecmd->duplex = !!(nego & ADVERTISED_1000baseT_Full); } else if (nego & (ADVERTISED_100baseT_Full | ADVERTISED_100baseT_Half)) { ethtool_cmd_speed_set(ecmd, SPEED_100); ecmd->duplex = !!(nego & ADVERTISED_100baseT_Full); } else { ethtool_cmd_speed_set(ecmd, SPEED_10); ecmd->duplex = !!(nego & ADVERTISED_10baseT_Full); } } else { ecmd->autoneg = AUTONEG_DISABLE; ethtool_cmd_speed_set(ecmd, ((bmcr & BMCR_SPEED1000 && (bmcr & BMCR_SPEED100) == 0) ? SPEED_1000 : ((bmcr & BMCR_SPEED100) ? SPEED_100 : SPEED_10))); ecmd->duplex = (bmcr & BMCR_FULLDPLX) ? DUPLEX_FULL : DUPLEX_HALF; } mii->full_duplex = ecmd->duplex; /* ignore maxtxpkt, maxrxpkt for now */ return 0; } /** * mii_ethtool_sset - set settings that are specified in @ecmd * @mii: MII interface * @ecmd: requested ethtool_cmd * * Returns 0 for success, negative on error. */ int mii_ethtool_sset(struct mii_if_info *mii, struct ethtool_cmd *ecmd) { struct net_device *dev = mii->dev; u32 speed = ethtool_cmd_speed(ecmd); if (speed != SPEED_10 && speed != SPEED_100 && speed != SPEED_1000) return -EINVAL; if (ecmd->duplex != DUPLEX_HALF && ecmd->duplex != DUPLEX_FULL) return -EINVAL; if (ecmd->port != PORT_MII) return -EINVAL; if (ecmd->transceiver != XCVR_INTERNAL) return -EINVAL; if (ecmd->phy_address != mii->phy_id) return -EINVAL; if (ecmd->autoneg != AUTONEG_DISABLE && ecmd->autoneg != AUTONEG_ENABLE) return -EINVAL; if ((speed == SPEED_1000) && (!mii->supports_gmii)) return -EINVAL; /* ignore supported, maxtxpkt, maxrxpkt */ if (ecmd->autoneg == AUTONEG_ENABLE) { u32 bmcr, advert, tmp; u32 advert2 = 0, tmp2 = 0; if ((ecmd->advertising & (ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | ADVERTISED_1000baseT_Half | ADVERTISED_1000baseT_Full)) == 0) return -EINVAL; /* advertise only what has been requested */ advert = mii->mdio_read(dev, mii->phy_id, MII_ADVERTISE); tmp = advert & ~(ADVERTISE_ALL | ADVERTISE_100BASE4); if (mii->supports_gmii) { advert2 = mii->mdio_read(dev, mii->phy_id, MII_CTRL1000); tmp2 = advert2 & ~(ADVERTISE_1000HALF | ADVERTISE_1000FULL); } tmp |= ethtool_adv_to_mii_adv_t(ecmd->advertising); if (mii->supports_gmii) tmp2 |= ethtool_adv_to_mii_ctrl1000_t(ecmd->advertising); if (advert != tmp) { mii->mdio_write(dev, mii->phy_id, MII_ADVERTISE, tmp); mii->advertising = tmp; } if ((mii->supports_gmii) && (advert2 != tmp2)) mii->mdio_write(dev, mii->phy_id, MII_CTRL1000, tmp2); /* turn on autonegotiation, and force a renegotiate */ bmcr = mii->mdio_read(dev, mii->phy_id, MII_BMCR); bmcr |= (BMCR_ANENABLE | BMCR_ANRESTART); mii->mdio_write(dev, mii->phy_id, MII_BMCR, bmcr); mii->force_media = 0; } else { u32 bmcr, tmp; /* turn off auto negotiation, set speed and duplexity */ bmcr = mii->mdio_read(dev, mii->phy_id, MII_BMCR); tmp = bmcr & ~(BMCR_ANENABLE | BMCR_SPEED100 | BMCR_SPEED1000 | BMCR_FULLDPLX); if (speed == SPEED_1000) tmp |= BMCR_SPEED1000; else if (speed == SPEED_100) tmp |= BMCR_SPEED100; if (ecmd->duplex == DUPLEX_FULL) { tmp |= BMCR_FULLDPLX; mii->full_duplex = 1; } else mii->full_duplex = 0; if (bmcr != tmp) mii->mdio_write(dev, mii->phy_id, MII_BMCR, tmp); mii->force_media = 1; } return 0; } /** * mii_check_gmii_support - check if the MII supports Gb interfaces * @mii: the MII interface */ int mii_check_gmii_support(struct mii_if_info *mii) { int reg; reg = mii->mdio_read(mii->dev, mii->phy_id, MII_BMSR); if (reg & BMSR_ESTATEN) { reg = mii->mdio_read(mii->dev, mii->phy_id, MII_ESTATUS); if (reg & (ESTATUS_1000_TFULL | ESTATUS_1000_THALF)) return 1; } return 0; } /** * mii_link_ok - is link status up/ok * @mii: the MII interface * * Returns 1 if the MII reports link status up/ok, 0 otherwise. */ int mii_link_ok (struct mii_if_info *mii) { /* first, a dummy read, needed to latch some MII phys */ mii->mdio_read(mii->dev, mii->phy_id, MII_BMSR); if (mii->mdio_read(mii->dev, mii->phy_id, MII_BMSR) & BMSR_LSTATUS) return 1; return 0; } /** * mii_nway_restart - restart NWay (autonegotiation) for this interface * @mii: the MII interface * * Returns 0 on success, negative on error. */ int mii_nway_restart (struct mii_if_info *mii) { int bmcr; int r = -EINVAL; /* if autoneg is off, it's an error */ bmcr = mii->mdio_read(mii->dev, mii->phy_id, MII_BMCR); if (bmcr & BMCR_ANENABLE) { bmcr |= BMCR_ANRESTART; mii->mdio_write(mii->dev, mii->phy_id, MII_BMCR, bmcr); r = 0; } return r; } /** * mii_check_link - check MII link status * @mii: MII interface * * If the link status changed (previous != current), call * netif_carrier_on() if current link status is Up or call * netif_carrier_off() if current link status is Down. */ void mii_check_link (struct mii_if_info *mii) { int cur_link = mii_link_ok(mii); int prev_link = netif_carrier_ok(mii->dev); if (cur_link && !prev_link) netif_carrier_on(mii->dev); else if (prev_link && !cur_link) netif_carrier_off(mii->dev); } /** * mii_check_media - check the MII interface for a carrier/speed/duplex change * @mii: the MII interface * @ok_to_print: OK to print link up/down messages * @init_media: OK to save duplex mode in @mii * * Returns 1 if the duplex mode changed, 0 if not. * If the media type is forced, always returns 0. */ unsigned int mii_check_media (struct mii_if_info *mii, unsigned int ok_to_print, unsigned int init_media) { unsigned int old_carrier, new_carrier; int advertise, lpa, media, duplex; int lpa2 = 0; /* check current and old link status */ old_carrier = netif_carrier_ok(mii->dev) ? 1 : 0; new_carrier = (unsigned int) mii_link_ok(mii); /* if carrier state did not change, this is a "bounce", * just exit as everything is already set correctly */ if ((!init_media) && (old_carrier == new_carrier)) return 0; /* duplex did not change */ /* no carrier, nothing much to do */ if (!new_carrier) { netif_carrier_off(mii->dev); if (ok_to_print) netdev_info(mii->dev, "link down\n"); return 0; /* duplex did not change */ } /* * we have carrier, see who's on the other end */ netif_carrier_on(mii->dev); if (mii->force_media) { if (ok_to_print) netdev_info(mii->dev, "link up\n"); return 0; /* duplex did not change */ } /* get MII advertise and LPA values */ if ((!init_media) && (mii->advertising)) advertise = mii->advertising; else { advertise = mii->mdio_read(mii->dev, mii->phy_id, MII_ADVERTISE); mii->advertising = advertise; } lpa = mii->mdio_read(mii->dev, mii->phy_id, MII_LPA); if (mii->supports_gmii) lpa2 = mii->mdio_read(mii->dev, mii->phy_id, MII_STAT1000); /* figure out media and duplex from advertise and LPA values */ media = mii_nway_result(lpa & advertise); duplex = (media & ADVERTISE_FULL) ? 1 : 0; if (lpa2 & LPA_1000FULL) duplex = 1; if (ok_to_print) netdev_info(mii->dev, "link up, %uMbps, %s-duplex, lpa 0x%04X\n", lpa2 & (LPA_1000FULL | LPA_1000HALF) ? 1000 : media & (ADVERTISE_100FULL | ADVERTISE_100HALF) ? 100 : 10, duplex ? "full" : "half", lpa); if ((init_media) || (mii->full_duplex != duplex)) { mii->full_duplex = duplex; return 1; /* duplex changed */ } return 0; /* duplex did not change */ } /** * generic_mii_ioctl - main MII ioctl interface * @mii_if: the MII interface * @mii_data: MII ioctl data structure * @cmd: MII ioctl command * @duplex_chg_out: pointer to @duplex_changed status if there was no * ioctl error * * Returns 0 on success, negative on error. */ int generic_mii_ioctl(struct mii_if_info *mii_if, struct mii_ioctl_data *mii_data, int cmd, unsigned int *duplex_chg_out) { int rc = 0; unsigned int duplex_changed = 0; if (duplex_chg_out) *duplex_chg_out = 0; mii_data->phy_id &= mii_if->phy_id_mask; mii_data->reg_num &= mii_if->reg_num_mask; switch(cmd) { case SIOCGMIIPHY: mii_data->phy_id = mii_if->phy_id; /* fall through */ case SIOCGMIIREG: mii_data->val_out = mii_if->mdio_read(mii_if->dev, mii_data->phy_id, mii_data->reg_num); break; case SIOCSMIIREG: { u16 val = mii_data->val_in; if (mii_data->phy_id == mii_if->phy_id) { switch(mii_data->reg_num) { case MII_BMCR: { unsigned int new_duplex = 0; if (val & (BMCR_RESET|BMCR_ANENABLE)) mii_if->force_media = 0; else mii_if->force_media = 1; if (mii_if->force_media && (val & BMCR_FULLDPLX)) new_duplex = 1; if (mii_if->full_duplex != new_duplex) { duplex_changed = 1; mii_if->full_duplex = new_duplex; } break; } case MII_ADVERTISE: mii_if->advertising = val; break; default: /* do nothing */ break; } } mii_if->mdio_write(mii_if->dev, mii_data->phy_id, mii_data->reg_num, val); break; } default: rc = -EOPNOTSUPP; break; } if ((rc == 0) && (duplex_chg_out) && (duplex_changed)) *duplex_chg_out = 1; return rc; } MODULE_AUTHOR ("Jeff Garzik <jgarzik@pobox.com>"); MODULE_DESCRIPTION ("MII hardware support library"); MODULE_LICENSE("GPL"); EXPORT_SYMBOL(mii_link_ok); EXPORT_SYMBOL(mii_nway_restart); EXPORT_SYMBOL(mii_ethtool_gset); EXPORT_SYMBOL(mii_ethtool_sset); EXPORT_SYMBOL(mii_check_link); EXPORT_SYMBOL(mii_check_media); EXPORT_SYMBOL(mii_check_gmii_support); EXPORT_SYMBOL(generic_mii_ioctl);
lgpl-3.0
lbv/pc-code
solved/x-z/yet-another-number-sequence/lightoj/seq.cpp
2
1630
#include <cstdio> #include <cstring> #define MAXM 4 #define Zero(v) memset((v), 0, sizeof(v)) typedef long long i64; typedef unsigned long long u64; i64 Mod; // // Matrix Exponentiation // typedef i64 t_m; #define MAXR 2 #define MAXC 2 struct Matrix { int r, c; t_m m[MAXR][MAXC]; void init(int R, int C) { Zero(m); r=R; c=C; } }; void matrix_mul(const Matrix &a, const Matrix &b, Matrix &c) { c.r = a.r, c.c = b.c; t_m x; for (int i = 0; i < c.r; ++i) for (int j = 0; j < c.c; ++j) { x = 0; for (int k = 0; k < a.c; ++k) x += a.m[i][k] * b.m[k][j]; c.m[i][j] = x % Mod; } } void matrix_exp(const Matrix &m, u64 e, Matrix &r) { if (e == 1) { r = m; return; } Matrix x; if (e % 2 == 0) { matrix_exp(m, e / 2, x); matrix_mul(x, x, r); return; } matrix_exp(m, e-1, x); matrix_mul(x, m, r); } int a, b, n, m; int p10[MAXM + 1]; Matrix O; int solve() { Mod = p10[m]; if (n == 0) return a % Mod; if (n == 1) return b % Mod; Matrix R; matrix_exp(O, n - 1, R); i64 res = R.m[0][0] * b + R.m[0][1] * a; res %= Mod; return res; } void prepare() { O.init(2, 2); O.m[0][0] = 1; O.m[0][1] = 1; O.m[1][0] = 1; O.m[1][1] = 0; p10[0] = 1; for (int i = 1; i <= MAXM; ++i) p10[i] = p10[i - 1] * 10; } int main() { prepare(); int T; scanf("%d", &T); int ncase = 0; while (T--) { scanf("%d%d%d%d", &a, &b, &n, &m); printf("Case %d: %d\n", ++ncase, solve()); } return 0; }
unlicense
tgatomic/Voltage-Sensing
Firmware/Atmel_project/Atmel_project/u8g_oled/u8g_dev_ssd1322_nhd31oled_bw.c
229
12264
/* u8g_dev_ssd1322_nhd31oled_bw.c 1-Bit (BW) Driver for SSD1322 Controller (OLED Display) Tested with NHD-3.12-25664 Universal 8bit Graphics Library Copyright (c) 2012, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. SSD130x Monochrom OLED Controller SSD131x Character OLED Controller SSD132x Graylevel OLED Controller SSD1331 Color OLED Controller */ #include "u8g.h" /* width must be multiple of 8, largest value is 248 unless u8g 16 bit mode is enabled */ #if defined(U8G_16BIT) #define WIDTH 256 #else #define WIDTH 248 #endif #define HEIGHT 64 #define PAGE_HEIGHT 8 /* http://www.newhavendisplay.com/app_notes/OLED_25664.txt http://www.newhavendisplay.com/forum/viewtopic.php?f=15&t=3758 */ static const uint8_t u8g_dev_ssd1322_1bit_nhd_312_init_seq[] PROGMEM = { U8G_ESC_DLY(10), /* delay 10 ms */ U8G_ESC_CS(0), /* disable chip */ U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_RST(1), /* do reset low pulse with (1*16)+2 milliseconds */ U8G_ESC_CS(1), /* enable chip */ U8G_ESC_DLY(100), /* delay 100 ms */ U8G_ESC_DLY(100), /* delay 100 ms */ U8G_ESC_ADR(0), /* instruction mode */ 0x0fd, /* lock command */ U8G_ESC_ADR(1), /* data mode */ 0x012, /* unlock */ U8G_ESC_ADR(0), /* instruction mode */ 0x0ae, /* display off, sleep mode */ U8G_ESC_ADR(0), /* instruction mode */ 0x0b3, U8G_ESC_ADR(1), /* data mode */ 0x091, /* set display clock divide ratio/oscillator frequency (set clock as 80 frames/sec) */ U8G_ESC_ADR(0), /* instruction mode */ 0x0ca, /* multiplex ratio */ U8G_ESC_ADR(1), /* data mode */ 0x03f, /* 1/64 Duty (0x0F~0x3F) */ U8G_ESC_ADR(0), /* instruction mode */ 0x0a2, U8G_ESC_ADR(1), /* data mode */ 0x000, /* display offset, shift mapping ram counter */ U8G_ESC_ADR(0), /* instruction mode */ 0x0a1, U8G_ESC_ADR(1), /* data mode */ 0x000, /* display start line */ U8G_ESC_ADR(0), /* instruction mode */ 0x0a0, /* Set Re-Map / Dual COM Line Mode */ U8G_ESC_ADR(1), /* data mode */ 0x014, /* was 0x014 */ 0x011, /* was 0x011 */ U8G_ESC_ADR(0), /* instruction mode */ 0x0ab, U8G_ESC_ADR(1), /* data mode */ 0x001, /* Enable Internal VDD Regulator */ U8G_ESC_ADR(0), /* instruction mode */ 0x0b4, /* Display Enhancement A */ U8G_ESC_ADR(1), /* data mode */ 0x0a0, 0x005|0x0fd, U8G_ESC_ADR(0), /* instruction mode */ 0x0c1, /* contrast */ U8G_ESC_ADR(1), /* data mode */ 0x09f, U8G_ESC_ADR(0), /* instruction mode */ 0x0c7, /* Set Scale Factor of Segment Output Current Control */ U8G_ESC_ADR(1), /* data mode */ 0x00f, U8G_ESC_ADR(0), /* instruction mode */ 0x0b9, /* linear gray scale */ U8G_ESC_ADR(0), /* instruction mode */ 0x0b1, /* Phase 1 (Reset) & Phase 2 (Pre-Charge) Period Adjustment */ U8G_ESC_ADR(1), /* data mode */ 0x0e2, U8G_ESC_ADR(0), /* instruction mode */ 0x0d1, /* Display Enhancement B */ U8G_ESC_ADR(1), /* data mode */ 0x082|0x020, 0x020, U8G_ESC_ADR(0), /* instruction mode */ 0x0bb, /* precharge voltage */ U8G_ESC_ADR(1), /* data mode */ 0x01f, U8G_ESC_ADR(0), /* instruction mode */ 0x0b6, /* precharge period */ U8G_ESC_ADR(1), /* data mode */ 0x008, U8G_ESC_ADR(0), /* instruction mode */ 0x0be, /* vcomh */ U8G_ESC_ADR(1), /* data mode */ 0x007, U8G_ESC_ADR(0), /* instruction mode */ 0x0a6, /* normal display */ U8G_ESC_ADR(0), /* instruction mode */ 0x0a9, /* exit partial display */ U8G_ESC_ADR(0), /* instruction mode */ 0x0af, /* display on */ U8G_ESC_CS(0), /* disable chip */ U8G_ESC_END /* end of sequence */ }; static const uint8_t u8g_dev_ssd1322_1bit_nhd_312_prepare_page_seq[] PROGMEM = { U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_CS(1), /* enable chip */ 0x015, /* column address... */ U8G_ESC_ADR(1), /* data mode */ 0x01c, /* start at column 0 */ 0x05b, /* end column */ U8G_ESC_ADR(0), /* instruction mode */ 0x075, /* row address... */ U8G_ESC_ADR(1), /* data mode */ U8G_ESC_END /* end of sequence */ }; static void u8g_dev_ssd1322_1bit_prepare_row(u8g_t *u8g, u8g_dev_t *dev, uint8_t delta_row) { uint8_t row = ((u8g_pb_t *)(dev->dev_mem))->p.page; row *= ((u8g_pb_t *)(dev->dev_mem))->p.page_height; row += delta_row; u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd1322_1bit_nhd_312_prepare_page_seq); u8g_WriteByte(u8g, dev, row); /* start at the selected row */ u8g_WriteByte(u8g, dev, row+1); /* end within the selected row */ u8g_SetAddress(u8g, dev, 0); /* instruction mode mode */ u8g_WriteByte(u8g, dev, 0x05c); /* write to ram */ u8g_SetAddress(u8g, dev, 1); /* data mode */ } static const uint8_t u8g_dev_ssd13xx_sleep_on[] PROGMEM = { U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_CS(1), /* enable chip */ 0x0ae, /* display off */ U8G_ESC_CS(0), /* disable chip, bugfix 12 nov 2014 */ U8G_ESC_END /* end of sequence */ }; static const uint8_t u8g_dev_ssd13xx_sleep_off[] PROGMEM = { U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_CS(1), /* enable chip */ 0x0af, /* display on */ U8G_ESC_DLY(50), /* delay 50 ms */ U8G_ESC_CS(0), /* disable chip, bugfix 12 nov 2014 */ U8G_ESC_END /* end of sequence */ }; uint8_t u8g_dev_ssd1322_nhd31oled_bw_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg) { switch(msg) { case U8G_DEV_MSG_INIT: u8g_InitCom(u8g, dev, U8G_SPI_CLK_CYCLE_300NS); u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd1322_1bit_nhd_312_init_seq); break; case U8G_DEV_MSG_STOP: break; case U8G_DEV_MSG_PAGE_NEXT: { uint8_t i; u8g_pb_t *pb = (u8g_pb_t *)(dev->dev_mem); uint8_t *p = pb->buf; u8g_uint_t cnt; cnt = pb->width; cnt >>= 3; for( i = 0; i < pb->p.page_height; i++ ) { u8g_dev_ssd1322_1bit_prepare_row(u8g, dev, i); /* this will also enable chip select */ #if !defined(U8G_16BIT) u8g_WriteByte(u8g, dev, 0x0ff); u8g_WriteByte(u8g, dev, 0x0ff); #endif u8g_WriteSequenceBWTo16GrDevice(u8g, dev, cnt, p); #if !defined(U8G_16BIT) u8g_WriteByte(u8g, dev, 0x0ff); u8g_WriteByte(u8g, dev, 0x0ff); #endif u8g_MicroDelay(); // for DUE? u8g_SetChipSelect(u8g, dev, 0); p+=cnt; } } break; case U8G_DEV_MSG_CONTRAST: u8g_SetChipSelect(u8g, dev, 1); u8g_SetAddress(u8g, dev, 0); /* instruction mode */ u8g_WriteByte(u8g, dev, 0x081); u8g_SetAddress(u8g, dev, 1); /* data mode */ u8g_WriteByte(u8g, dev, (*(uint8_t *)arg) >> 1); u8g_MicroDelay(); // for DUE? u8g_SetChipSelect(u8g, dev, 0); break; case U8G_DEV_MSG_SLEEP_ON: u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd13xx_sleep_on); return 1; case U8G_DEV_MSG_SLEEP_OFF: u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd13xx_sleep_off); return 1; } return u8g_dev_pb8h1_base_fn(u8g, dev, msg, arg); } uint8_t u8g_dev_ssd1322_nhd31oled_2x_bw_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg) { switch(msg) { case U8G_DEV_MSG_INIT: u8g_InitCom(u8g, dev, U8G_SPI_CLK_CYCLE_300NS); u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd1322_1bit_nhd_312_init_seq); break; case U8G_DEV_MSG_STOP: break; case U8G_DEV_MSG_PAGE_NEXT: { uint8_t i; u8g_pb_t *pb = (u8g_pb_t *)(dev->dev_mem); uint8_t *p = pb->buf; u8g_uint_t cnt; cnt = pb->width; cnt >>= 3; for( i = 0; i < pb->p.page_height; i++ ) { u8g_dev_ssd1322_1bit_prepare_row(u8g, dev, i); /* this will also enable chip select */ #if !defined(U8G_16BIT) u8g_WriteByte(u8g, dev, 0x0ff); u8g_WriteByte(u8g, dev, 0x0ff); #endif u8g_WriteSequenceBWTo16GrDevice(u8g, dev, cnt, p); #if !defined(U8G_16BIT) u8g_WriteByte(u8g, dev, 0x0ff); u8g_WriteByte(u8g, dev, 0x0ff); #endif u8g_MicroDelay(); // for DUE? u8g_SetChipSelect(u8g, dev, 0); p+=cnt; } } break; case U8G_DEV_MSG_CONTRAST: u8g_SetChipSelect(u8g, dev, 1); u8g_SetAddress(u8g, dev, 0); /* instruction mode */ u8g_WriteByte(u8g, dev, 0x0c1); /* 21 May 2013, fixed contrast command */ u8g_SetAddress(u8g, dev, 1); /* data mode */ u8g_WriteByte(u8g, dev, (*(uint8_t *)arg) >> 1); u8g_SetChipSelect(u8g, dev, 0); break; case U8G_DEV_MSG_SLEEP_ON: u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd13xx_sleep_on); return 1; case U8G_DEV_MSG_SLEEP_OFF: u8g_WriteEscSeqP(u8g, dev, u8g_dev_ssd13xx_sleep_off); return 1; } return u8g_dev_pb16h1_base_fn(u8g, dev, msg, arg); } U8G_PB_DEV(u8g_dev_ssd1322_nhd31oled_bw_sw_spi , WIDTH, HEIGHT, PAGE_HEIGHT, u8g_dev_ssd1322_nhd31oled_bw_fn, U8G_COM_SW_SPI); U8G_PB_DEV(u8g_dev_ssd1322_nhd31oled_bw_hw_spi , WIDTH, HEIGHT, PAGE_HEIGHT, u8g_dev_ssd1322_nhd31oled_bw_fn, U8G_COM_HW_SPI); U8G_PB_DEV(u8g_dev_ssd1322_nhd31oled_bw_parallel , WIDTH, HEIGHT, PAGE_HEIGHT, u8g_dev_ssd1322_nhd31oled_bw_fn, U8G_COM_FAST_PARALLEL); #define DWIDTH (WIDTH*2) uint8_t u8g_dev_ssd1322_nhd31oled_2x_bw_buf[DWIDTH] U8G_NOCOMMON ; u8g_pb_t u8g_dev_ssd1322_nhd31oled_2x_bw_pb = { {16, HEIGHT, 0, 0, 0}, WIDTH, u8g_dev_ssd1322_nhd31oled_2x_bw_buf}; u8g_dev_t u8g_dev_ssd1322_nhd31oled_2x_bw_sw_spi = { u8g_dev_ssd1322_nhd31oled_2x_bw_fn, &u8g_dev_ssd1322_nhd31oled_2x_bw_pb, U8G_COM_SW_SPI }; u8g_dev_t u8g_dev_ssd1322_nhd31oled_2x_bw_hw_spi = { u8g_dev_ssd1322_nhd31oled_2x_bw_fn, &u8g_dev_ssd1322_nhd31oled_2x_bw_pb, U8G_COM_HW_SPI };
unlicense
slightperturbation/Cobalt
ext/emsdk_portable/emscripten/1.27.0/tests/unistd/curdir.c
1
2536
#include <stdio.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <emscripten.h> int main() { EM_ASM( var dummy_device = FS.makedev(64, 0); FS.registerDevice(dummy_device, {}); FS.mkdev('/device', dummy_device); FS.mkdir('/folder'); FS.symlink('/folder', '/link'); FS.writeFile('/file', '', { mode: 0777 }); ); char buffer[256]; printf("getwd: %s\n", getwd(buffer)); printf("errno: %d\n", errno); errno = 0; printf("getcwd: %s\n", getcwd(buffer, 256)); printf("errno: %d\n", errno); errno = 0; printf("\n"); printf("chdir(file): %d\n", chdir("/file")); printf("errno: %d\n", errno); if (!errno) { errno = 0; printf("getwd: %s\n", getwd(buffer)); printf("errno: %d\n", errno); errno = 0; printf("getcwd: %s\n", getcwd(buffer, 256)); printf("errno: %d\n", errno); } errno = 0; printf("\n"); printf("chdir(device): %d\n", chdir("/device")); printf("errno: %d\n", errno); if (!errno) { errno = 0; printf("getwd: %s\n", getwd(buffer)); printf("errno: %d\n", errno); errno = 0; printf("getcwd: %s\n", getcwd(buffer, 256)); printf("errno: %d\n", errno); } errno = 0; printf("\n"); printf("chdir(folder): %d\n", chdir("/folder")); printf("errno: %d\n", errno); if (!errno) { errno = 0; printf("getwd: %s\n", getwd(buffer)); printf("errno: %d\n", errno); errno = 0; printf("getcwd: %s\n", getcwd(buffer, 256)); printf("errno: %d\n", errno); } errno = 0; printf("\n"); printf("chdir(nonexistent): %d\n", chdir("/nonexistent")); printf("errno: %d\n", errno); if (!errno) { errno = 0; printf("getwd: %s\n", getwd(buffer)); printf("errno: %d\n", errno); errno = 0; printf("getcwd: %s\n", getcwd(buffer, 256)); printf("errno: %d\n", errno); } errno = 0; printf("\n"); printf("chdir(link): %d\n", chdir("/link")); printf("errno: %d\n", errno); if (!errno) { errno = 0; printf("getwd: %s\n", getwd(buffer)); printf("errno: %d\n", errno); errno = 0; printf("getcwd: %s\n", getcwd(buffer, 256)); printf("errno: %d\n", errno); } errno = 0; printf("\n"); errno = 0; printf("fchdir(/): %d\n", fchdir(open("/", O_RDONLY, 0777))); printf("errno: %d\n", errno); if (!errno) { errno = 0; printf("getwd: %s\n", getwd(buffer)); printf("errno: %d\n", errno); errno = 0; printf("getcwd: %s\n", getcwd(buffer, 256)); printf("errno: %d\n", errno); errno = 0; } return 0; }
apache-2.0
JoyIfBam5/aws-sdk-cpp
aws-cpp-sdk-opsworks/source/model/UpdateAppRequest.cpp
1
3710
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/opsworks/model/UpdateAppRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::OpsWorks::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateAppRequest::UpdateAppRequest() : m_appIdHasBeenSet(false), m_nameHasBeenSet(false), m_descriptionHasBeenSet(false), m_dataSourcesHasBeenSet(false), m_type(AppType::NOT_SET), m_typeHasBeenSet(false), m_appSourceHasBeenSet(false), m_domainsHasBeenSet(false), m_enableSsl(false), m_enableSslHasBeenSet(false), m_sslConfigurationHasBeenSet(false), m_attributesHasBeenSet(false), m_environmentHasBeenSet(false) { } Aws::String UpdateAppRequest::SerializePayload() const { JsonValue payload; if(m_appIdHasBeenSet) { payload.WithString("AppId", m_appId); } if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } if(m_descriptionHasBeenSet) { payload.WithString("Description", m_description); } if(m_dataSourcesHasBeenSet) { Array<JsonValue> dataSourcesJsonList(m_dataSources.size()); for(unsigned dataSourcesIndex = 0; dataSourcesIndex < dataSourcesJsonList.GetLength(); ++dataSourcesIndex) { dataSourcesJsonList[dataSourcesIndex].AsObject(m_dataSources[dataSourcesIndex].Jsonize()); } payload.WithArray("DataSources", std::move(dataSourcesJsonList)); } if(m_typeHasBeenSet) { payload.WithString("Type", AppTypeMapper::GetNameForAppType(m_type)); } if(m_appSourceHasBeenSet) { payload.WithObject("AppSource", m_appSource.Jsonize()); } if(m_domainsHasBeenSet) { Array<JsonValue> domainsJsonList(m_domains.size()); for(unsigned domainsIndex = 0; domainsIndex < domainsJsonList.GetLength(); ++domainsIndex) { domainsJsonList[domainsIndex].AsString(m_domains[domainsIndex]); } payload.WithArray("Domains", std::move(domainsJsonList)); } if(m_enableSslHasBeenSet) { payload.WithBool("EnableSsl", m_enableSsl); } if(m_sslConfigurationHasBeenSet) { payload.WithObject("SslConfiguration", m_sslConfiguration.Jsonize()); } if(m_attributesHasBeenSet) { JsonValue attributesJsonMap; for(auto& attributesItem : m_attributes) { attributesJsonMap.WithString(AppAttributesKeysMapper::GetNameForAppAttributesKeys(attributesItem.first), attributesItem.second); } payload.WithObject("Attributes", std::move(attributesJsonMap)); } if(m_environmentHasBeenSet) { Array<JsonValue> environmentJsonList(m_environment.size()); for(unsigned environmentIndex = 0; environmentIndex < environmentJsonList.GetLength(); ++environmentIndex) { environmentJsonList[environmentIndex].AsObject(m_environment[environmentIndex].Jsonize()); } payload.WithArray("Environment", std::move(environmentJsonList)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection UpdateAppRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "OpsWorks_20130218.UpdateApp")); return headers; }
apache-2.0
PrimeSense/NiTEControls
Wrappers/NiteControls.c/MessageListener.cpp
1
6008
/***************************************************************************** * * * NiTE Controls 1.x Alpha * * Copyright (C) 2013 PrimeSense Ltd. * * * * This file is part of NiTE Controls Lab. * * * * 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 <XnHash.h> #include "MessageListener.h" #include "XnVMessageListener.h" XN_DECLARE_DEFAULT_HASH(XnVObjectID, XnVMessageListener*, MessageListenersHash); MessageListenersHash g_MessageListeners; void xnvMessageListener_AddToHash(XnVObjectID id, XnVMessageListener* pListener) { g_MessageListeners.Set(id, pListener); } XnVMessageListener* xnvMessageListener_GetFromHash(XnVObjectID id) { XnVMessageListener* pListener = NULL; XnStatus rc = g_MessageListeners.Get(id, pListener); if (rc != XN_STATUS_OK) { return NULL; } return pListener; } XnVMessageListener* xnvMessageListener_RemoveFromHash(XnVObjectID id) { XnVMessageListener* pListener = NULL; XnStatus rc = g_MessageListeners.Get(id, pListener); if (rc != XN_STATUS_OK) { return NULL; } g_MessageListeners.Remove(id); return pListener; } XnVObjectID xnvMessageListener_GetID(XnVMessageListener* pListener) { for (MessageListenersHash::ConstIterator iter = g_MessageListeners.begin(); iter != g_MessageListeners.end(); ++iter) { if (pListener == iter.Value()) { return iter.Key(); } } return 0; } XnStatus xnvMessageListener_RegisterActivate(XnVObjectID id, ActivateCB CB, void* pCookie, XnCallbackHandle* pHandle) { XN_VALIDATE_OUTPUT_PTR(pHandle); XnVMessageListener* pListener = NULL; XnStatus rc = g_MessageListeners.Get(id, pListener); if (rc != XN_STATUS_OK) { return XN_STATUS_NITE_UNEXPECTED_TYPE; } *pHandle = pListener->RegisterActivate(pCookie, CB); return XN_STATUS_OK; } XnStatus xnvMessageListener_RegisterDeactivate(XnVObjectID id, DeactivateCB CB, void* pCookie, XnCallbackHandle* pHandle) { XN_VALIDATE_OUTPUT_PTR(pHandle); XnVMessageListener* pListener = NULL; XnStatus rc = g_MessageListeners.Get(id, pListener); if (rc != XN_STATUS_OK) { return XN_STATUS_NITE_UNEXPECTED_TYPE; } *pHandle = pListener->RegisterDeactivate(pCookie, CB); return XN_STATUS_OK; } XnStatus xnvMessageListener_UnregisterActivate(XnVObjectID id, XnCallbackHandle hCB) { XnVMessageListener* pListener = NULL; XnStatus rc = g_MessageListeners.Get(id, pListener); if (rc != XN_STATUS_OK) { return XN_STATUS_NITE_UNEXPECTED_TYPE; } pListener->UnregisterActivate(hCB); return XN_STATUS_OK; } XnStatus xnvMessageListener_UnregisterDeactivate(XnVObjectID id, XnCallbackHandle hCB) { XnVMessageListener* pListener = NULL; XnStatus rc = g_MessageListeners.Get(id, pListener); if (rc != XN_STATUS_OK) { return XN_STATUS_NITE_UNEXPECTED_TYPE; } pListener->UnregisterDeactivate(hCB); return XN_STATUS_OK; } struct XnVExternalUpdateCB { UpdateCB externalCB; void* pCookie; }; XN_DECLARE_DEFAULT_HASH(XnCallbackHandle, XnVExternalUpdateCB*, ExternalUpdateCBs); ExternalUpdateCBs g_ExternalUpdateCBs; void XN_CALLBACK_TYPE InternalUpdateCB(XnVMessage* pMessage, void* pCookie) { XnVExternalUpdateCB* pExternalCB = (XnVExternalUpdateCB*)pCookie; if (pExternalCB->externalCB != NULL) { (*pExternalCB->externalCB)((void*)pMessage, pExternalCB->pCookie); } } XnStatus xnvMessageListener_RegisterUpdate(XnVObjectID id, UpdateCB CB, void* pCookie, XnCallbackHandle* pHandle) { XN_VALIDATE_OUTPUT_PTR(pHandle); XnVMessageListener* pListener = NULL; XnStatus rc = g_MessageListeners.Get(id, pListener); if (rc != XN_STATUS_OK) { return XN_STATUS_NITE_UNEXPECTED_TYPE; } XnVExternalUpdateCB* pNewExternal = XN_NEW(XnVExternalUpdateCB); pNewExternal->externalCB = CB; pNewExternal->pCookie = pCookie; *pHandle = pListener->RegisterUpdate(pNewExternal, InternalUpdateCB); g_ExternalUpdateCBs.Set(*pHandle, pNewExternal); return XN_STATUS_OK; } XnStatus xnvMessageListener_UnregisterUpdate(XnVObjectID id, XnCallbackHandle hCB) { XnVMessageListener* pListener = NULL; XnStatus rc = g_MessageListeners.Get(id, pListener); if (rc != XN_STATUS_OK) { return XN_STATUS_NITE_UNEXPECTED_TYPE; } XnVExternalUpdateCB* pExternal = NULL; rc = g_ExternalUpdateCBs.Remove(hCB, pExternal); if (rc != XN_STATUS_OK) { return rc; } XN_DELETE(pExternal); pListener->UnregisterUpdate(hCB); return XN_STATUS_OK; } XnStatus xnvMessageListener_Update(XnVObjectID id, void* pMessage) { XnVMessageListener* pListener = NULL; XnStatus rc = g_MessageListeners.Get(id, pListener); if (rc != XN_STATUS_OK) { return XN_STATUS_NITE_UNEXPECTED_TYPE; } XnVMessage* pMsg = (XnVMessage*)pMessage; pListener->Update(pMsg); return XN_STATUS_OK; }
apache-2.0
NEWPLAN/AIOS
lib/libc/stdlib/putenv.c
1
1517
/* This file is part of The Firekylin Operating System. * * Copyright 2016 Liuxiaofeng * * 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 <stdlib.h> #include <string.h> #include <errno.h> static char **origenv; int putenv(const char *string) { size_t len; int envc; int remove = 0; char *tmp; char **ep; char **newenv; if (!origenv) origenv = environ; if (!(tmp = strchr(string, '='))) { len = strlen(string); remove = 1; } else len = tmp - string + 1; for (envc = 0, ep = environ; *ep; ++ep) { if (*string == **ep && !memcmp(string, *ep, len)) { if (remove) { for (; ep[1]; ++ep) ep[0] = ep[1]; ep[0] = 0; return 0; } *ep = (char*) string; return 0; } ++envc; } if (tmp) { newenv = (char**) realloc(environ == origenv ? 0 : origenv, (envc + 2) * sizeof(char*)); if (!newenv) return -1; newenv[0] = (char*) string; memcpy(newenv + 1, environ, (envc + 1) * sizeof(char*)); environ = newenv; } return 0; }
apache-2.0
woshipike00/FreeRDP
server/Sample/sfreerdp.c
1
20408
/** * FreeRDP: A Remote Desktop Protocol Implementation * FreeRDP Test Server * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2011 Vic Lee * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <pthread.h> #include <signal.h> #include <sys/time.h> #include <winpr/crt.h> #include <winpr/synch.h> #include <freerdp/constants.h> #include <freerdp/server/rdpsnd.h> #include "sf_audin.h" #include "sf_rdpsnd.h" #include "sfreerdp.h" static char* test_pcap_file = NULL; static BOOL test_dump_rfx_realtime = TRUE; void test_peer_context_new(freerdp_peer* client, testPeerContext* context) { context->rfx_context = rfx_context_new(); context->rfx_context->mode = RLGR3; context->rfx_context->width = client->settings->DesktopWidth; context->rfx_context->height = client->settings->DesktopHeight; rfx_context_set_pixel_format(context->rfx_context, RDP_PIXEL_FORMAT_R8G8B8); context->nsc_context = nsc_context_new(); nsc_context_set_pixel_format(context->nsc_context, RDP_PIXEL_FORMAT_R8G8B8); context->s = stream_new(65536); context->icon_x = -1; context->icon_y = -1; context->vcm = WTSCreateVirtualChannelManager(client); } void test_peer_context_free(freerdp_peer* client, testPeerContext* context) { if (context) { if (context->debug_channel_thread) { SetEvent(context->stopEvent); WaitForSingleObject(context->debug_channel_thread, INFINITE); CloseHandle(context->debug_channel_thread); } stream_free(context->s); free(context->icon_data); free(context->bg_data); rfx_context_free(context->rfx_context); nsc_context_free(context->nsc_context); if (context->debug_channel) WTSVirtualChannelClose(context->debug_channel); if (context->audin) audin_server_context_free(context->audin); if (context->rdpsnd) rdpsnd_server_context_free(context->rdpsnd); WTSDestroyVirtualChannelManager(context->vcm); } } static void test_peer_init(freerdp_peer* client) { client->context_size = sizeof(testPeerContext); client->ContextNew = (psPeerContextNew) test_peer_context_new; client->ContextFree = (psPeerContextFree) test_peer_context_free; freerdp_peer_context_new(client); } static wStream* test_peer_stream_init(testPeerContext* context) { stream_clear(context->s); stream_set_pos(context->s, 0); return context->s; } static void test_peer_begin_frame(freerdp_peer* client) { rdpUpdate* update = client->update; SURFACE_FRAME_MARKER* fm = &update->surface_frame_marker; testPeerContext* context = (testPeerContext*) client->context; fm->frameAction = SURFACECMD_FRAMEACTION_BEGIN; fm->frameId = context->frame_id; update->SurfaceFrameMarker(update->context, fm); } static void test_peer_end_frame(freerdp_peer* client) { rdpUpdate* update = client->update; SURFACE_FRAME_MARKER* fm = &update->surface_frame_marker; testPeerContext* context = (testPeerContext*) client->context; fm->frameAction = SURFACECMD_FRAMEACTION_END; fm->frameId = context->frame_id; update->SurfaceFrameMarker(update->context, fm); context->frame_id++; } static void test_peer_draw_background(freerdp_peer* client) { int size; wStream* s; RFX_RECT rect; BYTE* rgb_data; rdpUpdate* update = client->update; SURFACE_BITS_COMMAND* cmd = &update->surface_bits_command; testPeerContext* context = (testPeerContext*) client->context; if (!client->settings->RemoteFxCodec && !client->settings->NSCodec) return; test_peer_begin_frame(client); s = test_peer_stream_init(context); rect.x = 0; rect.y = 0; rect.width = client->settings->DesktopWidth; rect.height = client->settings->DesktopHeight; size = rect.width * rect.height * 3; rgb_data = malloc(size); memset(rgb_data, 0xA0, size); if (client->settings->RemoteFxCodec) { rfx_compose_message(context->rfx_context, s, &rect, 1, rgb_data, rect.width, rect.height, rect.width * 3); cmd->codecID = client->settings->RemoteFxCodecId; } else { nsc_compose_message(context->nsc_context, s, rgb_data, rect.width, rect.height, rect.width * 3); cmd->codecID = client->settings->NSCodecId; } cmd->destLeft = 0; cmd->destTop = 0; cmd->destRight = rect.width; cmd->destBottom = rect.height; cmd->bpp = 32; cmd->width = rect.width; cmd->height = rect.height; cmd->bitmapDataLength = stream_get_length(s); cmd->bitmapData = stream_get_head(s); update->SurfaceBits(update->context, cmd); free(rgb_data); test_peer_end_frame(client); } static void test_peer_load_icon(freerdp_peer* client) { testPeerContext* context = (testPeerContext*) client->context; FILE* fp; int i; char line[50]; BYTE* rgb_data; int c; if (!client->settings->RemoteFxCodec && !client->settings->NSCodec) return; if ((fp = fopen("test_icon.ppm", "r")) == NULL) return; /* P3 */ fgets(line, sizeof(line), fp); /* Creater comment */ fgets(line, sizeof(line), fp); /* width height */ fgets(line, sizeof(line), fp); sscanf(line, "%d %d", &context->icon_width, &context->icon_height); /* Max */ fgets(line, sizeof(line), fp); rgb_data = malloc(context->icon_width * context->icon_height * 3); for (i = 0; i < context->icon_width * context->icon_height * 3; i++) { if (fgets(line, sizeof(line), fp)) { sscanf(line, "%d", &c); rgb_data[i] = (BYTE)c; } } context->icon_data = rgb_data; /* background with same size, which will be used to erase the icon from old position */ context->bg_data = malloc(context->icon_width * context->icon_height * 3); memset(context->bg_data, 0xA0, context->icon_width * context->icon_height * 3); } static void test_peer_draw_icon(freerdp_peer* client, int x, int y) { wStream* s; RFX_RECT rect; rdpUpdate* update = client->update; SURFACE_BITS_COMMAND* cmd = &update->surface_bits_command; testPeerContext* context = (testPeerContext*) client->context; if (client->update->dump_rfx) return; if (!context) return; if (context->icon_width < 1 || !context->activated) return; test_peer_begin_frame(client); rect.x = 0; rect.y = 0; rect.width = context->icon_width; rect.height = context->icon_height; if (context->icon_x >= 0) { s = test_peer_stream_init(context); if (client->settings->RemoteFxCodec) { rfx_compose_message(context->rfx_context, s, &rect, 1, context->bg_data, rect.width, rect.height, rect.width * 3); cmd->codecID = client->settings->RemoteFxCodecId; } else { nsc_compose_message(context->nsc_context, s, context->bg_data, rect.width, rect.height, rect.width * 3); cmd->codecID = client->settings->NSCodecId; } cmd->destLeft = context->icon_x; cmd->destTop = context->icon_y; cmd->destRight = context->icon_x + context->icon_width; cmd->destBottom = context->icon_y + context->icon_height; cmd->bpp = 32; cmd->width = context->icon_width; cmd->height = context->icon_height; cmd->bitmapDataLength = stream_get_length(s); cmd->bitmapData = stream_get_head(s); update->SurfaceBits(update->context, cmd); } s = test_peer_stream_init(context); if (client->settings->RemoteFxCodec) { rfx_compose_message(context->rfx_context, s, &rect, 1, context->icon_data, rect.width, rect.height, rect.width * 3); cmd->codecID = client->settings->RemoteFxCodecId; } else { nsc_compose_message(context->nsc_context, s, context->icon_data, rect.width, rect.height, rect.width * 3); cmd->codecID = client->settings->NSCodecId; } cmd->destLeft = x; cmd->destTop = y; cmd->destRight = x + context->icon_width; cmd->destBottom = y + context->icon_height; cmd->bpp = 32; cmd->width = context->icon_width; cmd->height = context->icon_height; cmd->bitmapDataLength = stream_get_length(s); cmd->bitmapData = stream_get_head(s); update->SurfaceBits(update->context, cmd); context->icon_x = x; context->icon_y = y; test_peer_end_frame(client); } static BOOL test_sleep_tsdiff(UINT32 *old_sec, UINT32 *old_usec, UINT32 new_sec, UINT32 new_usec) { INT32 sec, usec; if (*old_sec==0 && *old_usec==0) { *old_sec = new_sec; *old_usec = new_usec; return TRUE; } sec = new_sec - *old_sec; usec = new_usec - *old_usec; if (sec<0 || (sec==0 && usec<0)) { printf("Invalid time stamp detected.\n"); return FALSE; } *old_sec = new_sec; *old_usec = new_usec; while (usec < 0) { usec += 1000000; sec--; } if (sec > 0) Sleep(sec * 1000); if (usec > 0) USleep(usec); return TRUE; } void tf_peer_dump_rfx(freerdp_peer* client) { wStream* s; UINT32 prev_seconds; UINT32 prev_useconds; rdpUpdate* update; rdpPcap* pcap_rfx; pcap_record record; s = stream_new(512); update = client->update; client->update->pcap_rfx = pcap_open(test_pcap_file, FALSE); pcap_rfx = client->update->pcap_rfx; if (pcap_rfx == NULL) return; prev_seconds = prev_useconds = 0; while (pcap_has_next_record(pcap_rfx)) { pcap_get_next_record_header(pcap_rfx, &record); s->buffer = realloc(s->buffer, record.length); record.data = s->buffer; s->capacity = record.length; pcap_get_next_record_content(pcap_rfx, &record); s->pointer = s->buffer + s->capacity; if (test_dump_rfx_realtime && test_sleep_tsdiff(&prev_seconds, &prev_useconds, record.header.ts_sec, record.header.ts_usec) == FALSE) break; update->SurfaceCommand(update->context, s); } } static void* tf_debug_channel_thread_func(void* arg) { void* fd; wStream* s; void* buffer; UINT32 bytes_returned = 0; testPeerContext* context = (testPeerContext*) arg; if (WTSVirtualChannelQuery(context->debug_channel, WTSVirtualFileHandle, &buffer, &bytes_returned) == TRUE) { fd = *((void**) buffer); WTSFreeMemory(buffer); context->event = CreateWaitObjectEvent(NULL, TRUE, FALSE, fd); } s = stream_new(4096); WTSVirtualChannelWrite(context->debug_channel, (BYTE*) "test1", 5, NULL); while (1) { WaitForSingleObject(context->event, INFINITE); if (WaitForSingleObject(context->stopEvent, 0) == WAIT_OBJECT_0) break; stream_set_pos(s, 0); if (WTSVirtualChannelRead(context->debug_channel, 0, stream_get_head(s), stream_get_size(s), &bytes_returned) == FALSE) { if (bytes_returned == 0) break; stream_check_size(s, bytes_returned); if (WTSVirtualChannelRead(context->debug_channel, 0, stream_get_head(s), stream_get_size(s), &bytes_returned) == FALSE) { /* should not happen */ break; } } stream_set_pos(s, bytes_returned); printf("got %d bytes\n", bytes_returned); } stream_free(s); return 0; } BOOL tf_peer_post_connect(freerdp_peer* client) { int i; testPeerContext* context = (testPeerContext*) client->context; /** * This callback is called when the entire connection sequence is done, i.e. we've received the * Font List PDU from the client and sent out the Font Map PDU. * The server may start sending graphics output and receiving keyboard/mouse input after this * callback returns. */ printf("Client %s is activated (osMajorType %d osMinorType %d)", client->local ? "(local)" : client->hostname, client->settings->OsMajorType, client->settings->OsMinorType); if (client->settings->AutoLogonEnabled) { printf(" and wants to login automatically as %s\\%s", client->settings->Domain ? client->settings->Domain : "", client->settings->Username); /* A real server may perform OS login here if NLA is not executed previously. */ } printf("\n"); printf("Client requested desktop: %dx%dx%d\n", client->settings->DesktopWidth, client->settings->DesktopHeight, client->settings->ColorDepth); /* A real server should tag the peer as activated here and start sending updates in main loop. */ test_peer_load_icon(client); /* Iterate all channel names requested by the client and activate those supported by the server */ for (i = 0; i < client->settings->ChannelCount; i++) { if (client->settings->ChannelDefArray[i].joined) { if (strncmp(client->settings->ChannelDefArray[i].Name, "rdpdbg", 6) == 0) { context->debug_channel = WTSVirtualChannelOpenEx(context->vcm, "rdpdbg", 0); if (context->debug_channel != NULL) { printf("Open channel rdpdbg.\n"); context->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); context->debug_channel_thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) tf_debug_channel_thread_func, (void*) context, 0, NULL); } } else if (strncmp(client->settings->ChannelDefArray[i].Name, "rdpsnd", 6) == 0) { sf_peer_rdpsnd_init(context); /* Audio Output */ } } } /* Dynamic Virtual Channels */ sf_peer_audin_init(context); /* Audio Input */ /* Return FALSE here would stop the execution of the peer main loop. */ return TRUE; } BOOL tf_peer_activate(freerdp_peer* client) { testPeerContext* context = (testPeerContext*) client->context; rfx_context_reset(context->rfx_context); context->activated = TRUE; if (test_pcap_file != NULL) { client->update->dump_rfx = TRUE; tf_peer_dump_rfx(client); } else { test_peer_draw_background(client); } return TRUE; } void tf_peer_synchronize_event(rdpInput* input, UINT32 flags) { printf("Client sent a synchronize event (flags:0x%X)\n", flags); } void tf_peer_keyboard_event(rdpInput* input, UINT16 flags, UINT16 code) { freerdp_peer* client = input->context->peer; rdpUpdate* update = client->update; testPeerContext* context = (testPeerContext*) input->context; printf("Client sent a keyboard event (flags:0x%X code:0x%X)\n", flags, code); if ((flags & 0x4000) && code == 0x22) /* 'g' key */ { if (client->settings->DesktopWidth != 800) { client->settings->DesktopWidth = 800; client->settings->DesktopHeight = 600; } else { client->settings->DesktopWidth = 640; client->settings->DesktopHeight = 480; } update->DesktopResize(update->context); context->activated = FALSE; } else if ((flags & 0x4000) && code == 0x2E) /* 'c' key */ { if (context->debug_channel) { WTSVirtualChannelWrite(context->debug_channel, (BYTE*) "test2", 5, NULL); } } else if ((flags & 0x4000) && code == 0x2D) /* 'x' key */ { client->Close(client); } else if ((flags & 0x4000) && code == 0x13) /* 'r' key */ { if (!context->audin_open) { context->audin->Open(context->audin); context->audin_open = TRUE; } else { context->audin->Close(context->audin); context->audin_open = FALSE; } } else if ((flags & 0x4000) && code == 0x1F) /* 's' key */ { } } void tf_peer_unicode_keyboard_event(rdpInput* input, UINT16 flags, UINT16 code) { printf("Client sent a unicode keyboard event (flags:0x%X code:0x%X)\n", flags, code); } void tf_peer_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) { //printf("Client sent a mouse event (flags:0x%X pos:%d,%d)\n", flags, x, y); test_peer_draw_icon(input->context->peer, x + 10, y); } void tf_peer_extended_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) { //printf("Client sent an extended mouse event (flags:0x%X pos:%d,%d)\n", flags, x, y); } static void tf_peer_refresh_rect(rdpContext* context, BYTE count, RECTANGLE_16* areas) { BYTE i; printf("Client requested to refresh:\n"); for (i = 0; i < count; i++) { printf(" (%d, %d) (%d, %d)\n", areas[i].left, areas[i].top, areas[i].right, areas[i].bottom); } } static void tf_peer_suppress_output(rdpContext* context, BYTE allow, RECTANGLE_16* area) { if (allow > 0) { printf("Client restore output (%d, %d) (%d, %d).\n", area->left, area->top, area->right, area->bottom); } else { printf("Client minimized and suppress output.\n"); } } static void* test_peer_mainloop(void* arg) { int i; int fds; int max_fds; int rcount; void* rfds[32]; fd_set rfds_set; testPeerContext* context; freerdp_peer* client = (freerdp_peer*) arg; memset(rfds, 0, sizeof(rfds)); test_peer_init(client); /* Initialize the real server settings here */ client->settings->CertificateFile = _strdup("server.crt"); client->settings->PrivateKeyFile = _strdup("server.key"); client->settings->NlaSecurity = FALSE; client->settings->RemoteFxCodec = TRUE; client->settings->ColorDepth = 32; client->settings->SuppressOutput = TRUE; client->settings->RefreshRect = TRUE; client->PostConnect = tf_peer_post_connect; client->Activate = tf_peer_activate; client->input->SynchronizeEvent = tf_peer_synchronize_event; client->input->KeyboardEvent = tf_peer_keyboard_event; client->input->UnicodeKeyboardEvent = tf_peer_unicode_keyboard_event; client->input->MouseEvent = tf_peer_mouse_event; client->input->ExtendedMouseEvent = tf_peer_extended_mouse_event; client->update->RefreshRect = tf_peer_refresh_rect; client->update->SuppressOutput = tf_peer_suppress_output; client->Initialize(client); context = (testPeerContext*) client->context; printf("We've got a client %s\n", client->local ? "(local)" : client->hostname); while (1) { rcount = 0; if (client->GetFileDescriptor(client, rfds, &rcount) != TRUE) { printf("Failed to get FreeRDP file descriptor\n"); break; } WTSVirtualChannelManagerGetFileDescriptor(context->vcm, rfds, &rcount); max_fds = 0; FD_ZERO(&rfds_set); for (i = 0; i < rcount; i++) { fds = (int)(long)(rfds[i]); if (fds > max_fds) max_fds = fds; FD_SET(fds, &rfds_set); } if (max_fds == 0) break; if (select(max_fds + 1, &rfds_set, NULL, NULL, NULL) == -1) { /* these are not really errors */ if (!((errno == EAGAIN) || (errno == EWOULDBLOCK) || (errno == EINPROGRESS) || (errno == EINTR))) /* signal occurred */ { printf("select failed\n"); break; } } if (client->CheckFileDescriptor(client) != TRUE) break; if (WTSVirtualChannelManagerCheckFileDescriptor(context->vcm) != TRUE) break; } printf("Client %s disconnected.\n", client->local ? "(local)" : client->hostname); client->Disconnect(client); freerdp_peer_context_free(client); freerdp_peer_free(client); return NULL; } static void test_peer_accepted(freerdp_listener* instance, freerdp_peer* client) { pthread_t th; pthread_create(&th, 0, test_peer_mainloop, client); pthread_detach(th); } static void test_server_mainloop(freerdp_listener* instance) { int i; int fds; int max_fds; int rcount; void* rfds[32]; fd_set rfds_set; memset(rfds, 0, sizeof(rfds)); while (1) { rcount = 0; if (instance->GetFileDescriptor(instance, rfds, &rcount) != TRUE) { printf("Failed to get FreeRDP file descriptor\n"); break; } max_fds = 0; FD_ZERO(&rfds_set); for (i = 0; i < rcount; i++) { fds = (int)(long)(rfds[i]); if (fds > max_fds) max_fds = fds; FD_SET(fds, &rfds_set); } if (max_fds == 0) break; if (select(max_fds + 1, &rfds_set, NULL, NULL, NULL) == -1) { /* these are not really errors */ if (!((errno == EAGAIN) || (errno == EWOULDBLOCK) || (errno == EINPROGRESS) || (errno == EINTR))) /* signal occurred */ { printf("select failed\n"); break; } } if (instance->CheckFileDescriptor(instance) != TRUE) { printf("Failed to check FreeRDP file descriptor\n"); break; } } instance->Close(instance); } int main(int argc, char* argv[]) { freerdp_listener* instance; /* Ignore SIGPIPE, otherwise an SSL_write failure could crash your server */ signal(SIGPIPE, SIG_IGN); instance = freerdp_listener_new(); instance->PeerAccepted = test_peer_accepted; if (argc > 1) test_pcap_file = argv[1]; if (argc > 2 && !strcmp(argv[2], "--fast")) test_dump_rfx_realtime = FALSE; /* Open the server socket and start listening. */ if (instance->Open(instance, NULL, 3389) && instance->OpenLocal(instance, "/tmp/tfreerdp-server.0")) { /* Entering the server main loop. In a real server the listener can be run in its own thread. */ test_server_mainloop(instance); } freerdp_listener_free(instance); return 0; }
apache-2.0
sschiau/swift
lib/SILOptimizer/Mandatory/AddressLowering.cpp
1
57938
//===--- AddressLowering.cpp - Lower SIL address-only types. --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // This pass lowers SILTypes. On completion, the SILType of every SILValue is // its SIL storage type. A SIL storage type is always an address type for values // that require indirect storage at the LLVM IR level. Consequently, this pass // is required for IRGen. It is a mandatory IRGen preparation pass (not a // diagnostic pass). // // In the following text, items marked "[REUSE]" only apply to the proposed // storage reuse optimization, which is not currently implemented. // // ## State // // A `valueStorageMap` maps each opaque SIL value to its storage // information containing: // // - An ordinal representing the position of this instruction. // // - [REUSE] The identifier of the storage object. An optimized storage object // may have multiple disjoint lifetimes. A storage object may also have // subobjects. Each subobject has its own live range. When considering // liveness of the subobject, one must also consider liveness of the // parent object. // // - If this is a subobject projection, refer back to the value whose // storage object will be the parent that this storage address is a // projection of. // // - The storage address for this subobject. // // ## Step #1: Map opaque values // // Populate `valueStorageMap` in forward order (RPO), giving each opaque value // an ordinal position. // // [REUSE] Assign a storage identifier to each opaque value. Optionally optimize // storage by assigning multiple values the same identifier. // // ## Step #2: Allocate storage // // In reverse order (PO), allocate the parent storage object for each opaque // value. // // [REUSE] If storage has already been allocated for the current live range, // then simply reuse it. // // If the value's use composes a parent object from this value, and use's // storage can be projected from, then mark the value's storage as a projection // from the use value. [REUSE] Also inherit the use's storage identifier, and // add an interval to the live range with the current projection path. // // A use can be projected from if its allocation is available at (dominates) // this value and using the same storage over the interval from this value to // the use does not overlap with the existing live range. // // Checking interference requires checking all operands that have been marked as // projections. In the case of block arguments, it means checking the terminator // operands of all predecessor blocks. // // [REUSE] Rather than checking all value operands, each live range will contain // a set of intervals. Each interval will be associated with a projection path. // // Opaque value's that are the root of all projection paths now have their // `storageAddress` assigned to an `alloc_stack` or argument. Opaque value's // that are projections do not yet have a `storageAddress`. // // ## Step #3. Rewrite opaque values // // In forward order (RPO), rewrite each opaque value definition, and all its // uses. This generally involves creating a new `_addr` variant of the // instruction and obtaining the storage address from the `valueStorageMap`. // // If this value's storage is a projection of the value defined by its composing // use, then first generate instructions to materialize the projection. This is // a recursive process starting with the root of the projection path. // // A projection path will be materialized once, for the leaf subobject. When // this happens, the `storageAddress` will be assigned for any intermediate // projection paths. When those values are rewritten, their `storageAddress` // will already be available. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "address-lowering" #include "swift/SIL/DebugUtils.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILVisitor.h" #include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SetVector.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" using namespace swift; using llvm::SmallSetVector; using llvm::PointerIntPair; llvm::cl::opt<bool> OptimizeOpaqueAddressLowering("optimize-opaque-address-lowering", llvm::cl::init(false)); // Visit all call results. // Stop when the visitor returns `false`. static void visitCallResults(ApplySite apply, llvm::function_ref<bool(SILValue)> visitor) { // FIXME: this entire implementation only really works for ApplyInst. auto applyInst = cast<ApplyInst>(apply); if (applyInst->getType().is<TupleType>()) { // TODO: MultiValueInstruction for (auto *operand : applyInst->getUses()) { if (auto extract = dyn_cast<TupleExtractInst>(operand->getUser())) if (!visitor(extract)) break; } } else visitor(applyInst); } //===----------------------------------------------------------------------===// // ValueStorageMap: Map Opaque/Resilient SILValues to abstract storage units. //===----------------------------------------------------------------------===// namespace { struct ValueStorage { enum { IsProjectionMask = 0x1, IsRewrittenMask = 0x2 }; PointerIntPair<Operand *, 2, unsigned> projectionAndFlags; /// The final address of this storage unit after rewriting the SIL. /// For values linked to their own storage, this is set during storage /// allocation. For projections, it is only set after instruction rewriting. SILValue storageAddress; bool isProjection() const { return projectionAndFlags.getInt() & IsProjectionMask; } /// Return the operand the composes an aggregate from this value. Operand *getComposedOperand() const { assert(isProjection()); return projectionAndFlags.getPointer(); } void setComposedOperand(Operand *oper) { projectionAndFlags.setPointer(oper); projectionAndFlags.setInt(projectionAndFlags.getInt() | IsProjectionMask); } bool isRewritten() const { if (projectionAndFlags.getInt() & IsRewrittenMask) { assert(storageAddress); return true; } return false; } void markRewritten() { projectionAndFlags.setInt(projectionAndFlags.getInt() | IsRewrittenMask); } }; /// Map each opaque/resilient SILValue to its abstract storage. /// O(1) membership test. /// O(n) iteration in RPO order. class ValueStorageMap { typedef std::vector<std::pair<SILValue, ValueStorage>> ValueVector; // Hash of values to ValueVector indices. typedef llvm::DenseMap<SILValue, unsigned> ValueHashMap; ValueVector valueVector; ValueHashMap valueHashMap; public: bool empty() const { return valueVector.empty(); } void clear() { valueVector.clear(); valueHashMap.clear(); } ValueVector::iterator begin() { return valueVector.begin(); } ValueVector::iterator end() { return valueVector.end(); } ValueVector::reverse_iterator rbegin() { return valueVector.rbegin(); } ValueVector::reverse_iterator rend() { return valueVector.rend(); } bool contains(SILValue value) const { return valueHashMap.find(value) != valueHashMap.end(); } unsigned getOrdinal(SILValue value) { auto hashIter = valueHashMap.find(value); assert(hashIter != valueHashMap.end() && "Missing SILValue"); return hashIter->second; } ValueStorage &getStorage(SILValue value) { return valueVector[getOrdinal(value)].second; } // This must be called in RPO order. ValueStorage &insertValue(SILValue value) { auto hashResult = valueHashMap.insert(std::make_pair(value, valueVector.size())); (void)hashResult; assert(hashResult.second && "SILValue already mapped"); valueVector.emplace_back(value, ValueStorage()); return valueVector.back().second; } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // AddressLoweringState: shared state for the pass's analysis and transforms. //===----------------------------------------------------------------------===// namespace { struct AddressLoweringState { SILFunction *F; SILFunctionConventions loweredFnConv; // Dominators remain valid throughout this pass. DominanceInfo *domInfo; // All opaque values and associated storage. ValueStorageMap valueStorageMap; // All call sites with formally indirect SILArgument or SILResult conventions. // Calls are removed from the set when rewritten. SmallSetVector<ApplySite, 16> indirectApplies; // All function-exiting terminators (return or throw instructions). SmallVector<TermInst *, 8> returnInsts; // Delete these instructions after performing transformations. // They must not have any remaining users. SmallSetVector<SILInstruction *, 16> instsToDelete; AddressLoweringState(SILFunction *F, DominanceInfo *domInfo) : F(F), loweredFnConv(F->getLoweredFunctionType(), SILModuleConventions::getLoweredAddressConventions()), domInfo(domInfo) {} bool isDead(SILInstruction *inst) const { return instsToDelete.count(inst); } void markDead(SILInstruction *inst) { #ifndef NDEBUG for (auto result : inst->getResults()) for (Operand *use : result->getUses()) assert(instsToDelete.count(use->getUser())); #endif instsToDelete.insert(inst); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // OpaqueValueVisitor: Map OpaqueValues to ValueStorage. //===----------------------------------------------------------------------===// namespace { /// Collect all opaque/resilient values, inserting them in `valueStorageMap` in /// RPO order. /// /// Collect all call arguments with formally indirect SIL argument convention in /// `indirectOperands` and formally indirect SIL results in `indirectResults`. /// /// TODO: Perform linear-scan style in-place stack slot coloring by keeping /// track of each value's last use. class OpaqueValueVisitor { AddressLoweringState &pass; PostOrderFunctionInfo postorderInfo; public: explicit OpaqueValueVisitor(AddressLoweringState &pass) : pass(pass), postorderInfo(pass.F) {} void mapValueStorage(); protected: void visitApply(ApplySite applySite); void visitValue(SILValue value); }; } // end anonymous namespace /// Top-level entry: Populate `valueStorageMap`, `indirectResults`, and /// `indirectOperands`. /// /// Find all Opaque/Resilient SILValues and add them /// to valueStorageMap in RPO. void OpaqueValueVisitor::mapValueStorage() { for (auto *BB : postorderInfo.getReversePostOrder()) { if (BB->getTerminator()->isFunctionExiting()) pass.returnInsts.push_back(BB->getTerminator()); // Opaque function arguments have already been replaced. if (BB != pass.F->getEntryBlock()) { for (auto argI = BB->args_begin(), argEnd = BB->args_end(); argI != argEnd; ++argI) { visitValue(*argI); } } for (auto &II : *BB) { if (auto apply = ApplySite::isa(&II)) visitApply(apply); for (auto result : II.getResults()) visitValue(result); } } } /// Populate `indirectApplies` and insert this apply in `valueStorageMap` if /// the call's non-tuple result is returned indirectly. void OpaqueValueVisitor::visitApply(ApplySite applySite) { auto calleeConv = applySite.getSubstCalleeConv(); unsigned calleeArgIdx = applySite.getCalleeArgIndexOfFirstAppliedArg(); for (Operand &operand : applySite.getArgumentOperands()) { if (operand.get()->getType().isObject()) { auto argConv = calleeConv.getSILArgumentConvention(calleeArgIdx); if (argConv.isIndirectConvention()) { pass.indirectApplies.insert(applySite); } } ++calleeArgIdx; } if (applySite.getSubstCalleeType()->hasIndirectFormalResults()) { pass.indirectApplies.insert(applySite); if (!applySite.getType().is<TupleType>()) pass.valueStorageMap.insertValue(cast<ApplyInst>(applySite)); return; } } /// If `value` is address-only add it to the `valueStorageMap`. void OpaqueValueVisitor::visitValue(SILValue value) { if (value->getType().isObject() && value->getType().isAddressOnly(*pass.F)) { if (pass.valueStorageMap.contains(value)) { assert(isa<SILFunctionArgument>( pass.valueStorageMap.getStorage(value).storageAddress)); return; } pass.valueStorageMap.insertValue(value); } } //===----------------------------------------------------------------------===// // OpaqueStorageAllocation: Generate alloc_stack and address projections for all // abstract storage locations. //===----------------------------------------------------------------------===// namespace { /// Allocate storage on the stack for every opaque value defined in this /// function in RPO order. If the definition is an argument of this function, /// simply replace the function argument with an address representing the /// caller's storage. /// /// TODO: shrink lifetimes by inserting alloc_stack at the dominance LCA and /// finding the lifetime boundary with a simple backward walk from uses. class OpaqueStorageAllocation { AddressLoweringState &pass; public: explicit OpaqueStorageAllocation(AddressLoweringState &pass) : pass(pass) {} void allocateOpaqueStorage(); protected: void convertIndirectFunctionArgs(); unsigned insertIndirectReturnArgs(); bool canProjectFrom(SingleValueInstruction *innerVal, SILInstruction *composingUse); void allocateForValue(SILValue value, ValueStorage &storage); }; } // end anonymous namespace /// Top-level entry point: allocate storage for all opaque/resilient values. void OpaqueStorageAllocation::allocateOpaqueStorage() { // TODO: I think we need a GenericContextScope for mapTypeIntoContext, but all // tests are currently passing without it. #if 0 auto canFnType = pass.F->getLoweredFunctionType(); // Setup a generic context for argument and result types. swift::Lowering::GenericContextScope scope(pass.F->getModule().Types, canFnType->getGenericSignature()); #endif // Fixup this function's argument types with temporary loads. convertIndirectFunctionArgs(); // Create a new function argument for each indirect result. insertIndirectReturnArgs(); // Populate valueStorageMap. OpaqueValueVisitor(pass).mapValueStorage(); // Create an AllocStack for every opaque value defined in the function. Visit // values in post-order to create storage for aggregates before subobjects. for (auto &valueStorageI : reversed(pass.valueStorageMap)) allocateForValue(valueStorageI.first, valueStorageI.second); } /// Replace each value-typed argument to the current function with an /// address-typed argument by inserting a temporary load instruction. void OpaqueStorageAllocation::convertIndirectFunctionArgs() { // Insert temporary argument loads at the top of the function. SILBuilder argBuilder(pass.F->getEntryBlock()->begin()); argBuilder.setSILConventions( SILModuleConventions::getLoweredAddressConventions()); auto fnConv = pass.F->getConventions(); unsigned argIdx = fnConv.getSILArgIndexOfFirstParam(); for (SILParameterInfo param : pass.F->getLoweredFunctionType()->getParameters()) { if (param.isFormalIndirect() && !fnConv.isSILIndirect(param)) { SILArgument *arg = pass.F->getArgument(argIdx); SILType addrType = arg->getType().getAddressType(); LoadInst *loadArg = argBuilder.createLoad( RegularLocation(const_cast<ValueDecl *>(arg->getDecl())), SILUndef::get(addrType, *pass.F), LoadOwnershipQualifier::Unqualified); arg->replaceAllUsesWith(loadArg); assert(!pass.valueStorageMap.contains(arg)); arg = arg->getParent()->replaceFunctionArgument( arg->getIndex(), addrType, ValueOwnershipKind::Any, arg->getDecl()); loadArg->setOperand(arg); if (addrType.isAddressOnly(*pass.F)) pass.valueStorageMap.insertValue(loadArg).storageAddress = arg; } ++argIdx; } assert(argIdx == fnConv.getSILArgIndexOfFirstParam() + fnConv.getNumSILArguments()); } /// Insert function arguments for any @out result type. Return the number of /// indirect result arguments added. unsigned OpaqueStorageAllocation::insertIndirectReturnArgs() { auto &ctx = pass.F->getModule().getASTContext(); unsigned argIdx = 0; for (auto resultTy : pass.loweredFnConv.getIndirectSILResultTypes()) { auto bodyResultTy = pass.F->mapTypeIntoContext(resultTy); auto var = new (ctx) ParamDecl(ParamDecl::Specifier::InOut, SourceLoc(), SourceLoc(), ctx.getIdentifier("$return_value"), SourceLoc(), ctx.getIdentifier("$return_value"), pass.F->getDeclContext()); pass.F->begin()->insertFunctionArgument(argIdx, bodyResultTy.getAddressType(), ValueOwnershipKind::Any, var); ++argIdx; } assert(argIdx == pass.loweredFnConv.getNumIndirectSILResults()); return argIdx; } /// Is this operand composing an aggregate from a subobject, or simply /// forwarding the operand's value to storage defined elsewhere? /// /// TODO: Handle struct. /// TODO: Make this a visitor. bool OpaqueStorageAllocation::canProjectFrom(SingleValueInstruction *innerVal, SILInstruction *composingUse) { if (!OptimizeOpaqueAddressLowering) return false; SILValue composingValue; switch (composingUse->getKind()) { default: return false; case SILInstructionKind::ApplyInst: // @in operands never need their own storage since they are non-mutating // uses. They simply reuse the storage allocated for their operand. So it // wouldn't make sense to "project" out of the apply argument. return false; case SILInstructionKind::EnumInst: composingValue = cast<EnumInst>(composingUse); break; case SILInstructionKind::InitExistentialValueInst: { // Ensure that all opened archetypes are available at the inner value's // definition. auto *initExistential = cast<InitExistentialValueInst>(composingUse); for (Operand &operand : initExistential->getTypeDependentOperands()) { if (!pass.domInfo->properlyDominates(operand.get(), innerVal)) return false; } composingValue = initExistential; break; } case SILInstructionKind::ReturnInst: return true; case SILInstructionKind::StoreInst: { if (cast<StoreInst>(composingUse)->getSrc() == innerVal && isa<CopyValueInst>(innerVal)) { return true; } return false; } case SILInstructionKind::TupleInst: composingValue = cast<TupleInst>(composingUse); break; } ValueStorage &storage = pass.valueStorageMap.getStorage(composingValue); if (SILValue addr = storage.storageAddress) { if (auto *stackInst = dyn_cast<AllocStackInst>(addr)) { assert(pass.domInfo->properlyDominates(stackInst, innerVal)); return true; } if (isa<SILFunctionArgument>(addr)) { return true; } } else if (storage.isProjection()) return canProjectFrom(innerVal, storage.getComposedOperand()->getUser()); return false; } /// Allocate storage for a single opaque/resilient value. void OpaqueStorageAllocation::allocateForValue(SILValue value, ValueStorage &storage) { assert(!isa<SILFunctionArgument>(value)); if (auto apply = ApplySite::isa(value)) { // Result tuples will be canonicalized during apply rewriting so the tuple // itself is unused. if (value->getType().is<TupleType>()) { assert(apply.getSubstCalleeType()->getNumResults() > 1); return; } } // Argument loads already have a storage address. if (storage.storageAddress) { assert(isa<SILFunctionArgument>(storage.storageAddress)); return; } if (value->hasOneUse()) { // TODO: Handle block arguments. // TODO: Handle subobjects with a single composition, and other non-mutating // uses such as @in arguments. if (auto *def = dyn_cast<SingleValueInstruction>(value)) { Operand *useOper = *value->use_begin(); if (canProjectFrom(def, useOper->getUser())) { storage.setComposedOperand(useOper); return; } } } SILBuilder allocBuilder(pass.F->begin()->begin()); allocBuilder.setSILConventions( SILModuleConventions::getLoweredAddressConventions()); AllocStackInst *allocInstr = allocBuilder.createAllocStack(value.getLoc(), value->getType()); storage.storageAddress = allocInstr; // Insert stack deallocations. for (TermInst *termInst : pass.returnInsts) { SILBuilder deallocBuilder(termInst); deallocBuilder.setSILConventions( SILModuleConventions::getLoweredAddressConventions()); deallocBuilder.createDeallocStack(allocInstr->getLoc(), allocInstr); } } //===----------------------------------------------------------------------===// // AddressMaterialization - materialize storage addresses, generate projections. //===----------------------------------------------------------------------===// namespace { /// Materialize the address of a value's storage. For values that are directly /// mapped to a storage location, simply return the mapped `AllocStackInst`. /// For subobjects emit any necessary `_addr` projections using the provided /// `SILBuilder`. /// /// This is a common utility for ApplyRewriter, AddressOnlyDefRewriter, /// and AddressOnlyUseRewriter. class AddressMaterialization { AddressLoweringState &pass; SILBuilder &B; public: AddressMaterialization(AddressLoweringState &pass, SILBuilder &B) : pass(pass), B(B) {} SILValue initializeOperandMem(Operand *operand); SILValue materializeAddress(SILValue origValue); protected: SILValue materializeProjection(Operand *operand); }; } // anonymous namespace // Materialize an address pointing to initialized memory for this operand, // generating a projection and copy if needed. SILValue AddressMaterialization::initializeOperandMem(Operand *operand) { SILValue def = operand->get(); SILValue destAddr; if (operand->get()->getType().isAddressOnly(*pass.F)) { ValueStorage &storage = pass.valueStorageMap.getStorage(def); // Source value should already be rewritten. assert(storage.isRewritten()); if (storage.isProjection()) destAddr = storage.storageAddress; else { destAddr = materializeProjection(operand); B.createCopyAddr(operand->getUser()->getLoc(), storage.storageAddress, destAddr, IsTake, IsInitialization); } } else { destAddr = materializeProjection(operand); B.createStore(operand->getUser()->getLoc(), operand->get(), destAddr, StoreOwnershipQualifier::Unqualified); } return destAddr; } /// Return the address of the storage for `origValue`. This may involve /// materializing projections. SILValue AddressMaterialization::materializeAddress(SILValue origValue) { ValueStorage &storage = pass.valueStorageMap.getStorage(origValue); if (!storage.storageAddress) storage.storageAddress = materializeProjection(storage.getComposedOperand()); return storage.storageAddress; } SILValue AddressMaterialization::materializeProjection(Operand *operand) { SILInstruction *user = operand->getUser(); switch (user->getKind()) { default: LLVM_DEBUG(user->dump()); llvm_unreachable("Unexpected subobject composition."); case SILInstructionKind::EnumInst: { auto *enumInst = cast<EnumInst>(user); SILValue enumAddr = materializeAddress(enumInst); return B.createInitEnumDataAddr(enumInst->getLoc(), enumAddr, enumInst->getElement(), operand->get()->getType().getAddressType()); } case SILInstructionKind::InitExistentialValueInst: { auto *initExistentialValue = cast<InitExistentialValueInst>(user); SILValue containerAddr = materializeAddress(initExistentialValue); auto canTy = initExistentialValue->getFormalConcreteType(); auto opaque = Lowering::AbstractionPattern::getOpaque(); auto &concreteTL = pass.F->getTypeLowering(opaque, canTy); return B.createInitExistentialAddr( initExistentialValue->getLoc(), containerAddr, canTy, concreteTL.getLoweredType(), initExistentialValue->getConformances()); } case SILInstructionKind::ReturnInst: { assert(pass.loweredFnConv.hasIndirectSILResults()); return pass.F->getArguments()[0]; } case SILInstructionKind::TupleInst: { auto *tupleInst = cast<TupleInst>(user); // Function return values. if (tupleInst->hasOneUse() && isa<ReturnInst>(tupleInst->use_begin()->getUser())) { unsigned resultIdx = tupleInst->getElementIndex(operand); assert(resultIdx < pass.loweredFnConv.getNumIndirectSILResults()); // Cannot call getIndirectSILResults here because that API uses the // original function type. return pass.F->getArguments()[resultIdx]; } // TODO: emit tuple_element_addr llvm_unreachable("Unimplemented"); } } } //===----------------------------------------------------------------------===// // ApplyRewriter - rewrite call sites with indirect arguments. //===----------------------------------------------------------------------===// namespace { /// Rewrite an Apply, lowering its indirect SIL arguments. /// /// Replace indirect parameter arguments of this function with address-type /// arguments. /// /// Insert new indirect result arguments for this function to represent the /// caller's storage. class ApplyRewriter { AddressLoweringState &pass; ApplySite apply; SILBuilder argBuilder; /// For now, we assume that the apply site is a normal apply. ApplyInst *getApplyInst() const { return cast<ApplyInst>(apply); } public: ApplyRewriter(ApplySite origCall, AddressLoweringState &pass) : pass(pass), apply(origCall), argBuilder(origCall.getInstruction()) { argBuilder.setSILConventions( SILModuleConventions::getLoweredAddressConventions()); } void rewriteParameters(); void rewriteIndirectParameter(Operand *operand); void convertApplyWithIndirectResults(); protected: void canonicalizeResults(MutableArrayRef<SingleValueInstruction *> directResultValues, ArrayRef<Operand *> nonCanonicalUses); SILValue materializeIndirectResultAddress( SingleValueInstruction *origDirectResultVal, SILType argTy); }; } // end anonymous namespace /// Rewrite any indirect parameter in place. void ApplyRewriter::rewriteParameters() { // Rewrite all incoming indirect operands. unsigned calleeArgIdx = apply.getCalleeArgIndexOfFirstAppliedArg(); for (Operand &operand : apply.getArgumentOperands()) { if (operand.get()->getType().isObject()) { auto argConv = apply.getSubstCalleeConv().getSILArgumentConvention(calleeArgIdx); if (argConv.isIndirectConvention()) rewriteIndirectParameter(&operand); } ++calleeArgIdx; } } /// Deallocate temporary call-site stack storage. /// /// `argLoad` is non-null for @out args that are loaded. static void insertStackDeallocationAtCall(AllocStackInst *allocInst, SILInstruction *applyInst, SILInstruction *argLoad) { SILInstruction *lastUse = argLoad ? argLoad : applyInst; switch (applyInst->getKind()) { case SILInstructionKind::ApplyInst: { SILBuilder deallocBuilder(&*std::next(lastUse->getIterator())); deallocBuilder.setSILConventions( SILModuleConventions::getLoweredAddressConventions()); deallocBuilder.createDeallocStack(allocInst->getLoc(), allocInst); break; } case SILInstructionKind::TryApplyInst: // TODO!!!: insert dealloc in the catch block. llvm_unreachable("not implemented for this instruction!"); case SILInstructionKind::PartialApplyInst: llvm_unreachable("partial apply cannot have indirect results."); default: llvm_unreachable("not implemented for this instruction!"); } } /// Rewrite a formally indirect parameter in place. /// Update the operand to the incoming value's storage address. /// After this, the SIL argument types no longer match SIL function conventions. /// /// Temporary argument storage may be created for loadable values. /// /// Note: Temporary argument storage does not own its value. If the argument /// is owned, the stored value should already have been copied. void ApplyRewriter::rewriteIndirectParameter(Operand *operand) { SILValue argValue = operand->get(); if (argValue->getType().isAddressOnly(*pass.F)) { ValueStorage &storage = pass.valueStorageMap.getStorage(argValue); // Source value should already be rewritten. assert(storage.isRewritten()); operand->set(storage.storageAddress); return; } // Allocate temporary storage for a loadable operand. AllocStackInst *allocInstr = argBuilder.createAllocStack(apply.getLoc(), argValue->getType()); argBuilder.createStore(apply.getLoc(), argValue, allocInstr, StoreOwnershipQualifier::Unqualified); operand->set(allocInstr); insertStackDeallocationAtCall(allocInstr, apply.getInstruction(), /*argLoad=*/nullptr); } // Canonicalize call result uses. Treat each result of a multi-result call as // an independent value. Currently, SILGen may generate tuple_extract for each // result but generate a single destroy_value for the entire tuple of // results. This makes it impossible to reason about each call result as an // independent value according to the callee's function type. // // directResultValues has an entry for each tuple extract corresponding to // that result if one exists. This function will add an entry to // directResultValues whenever it needs to materialize a TupleExtractInst. void ApplyRewriter::canonicalizeResults( MutableArrayRef<SingleValueInstruction *> directResultValues, ArrayRef<Operand *> nonCanonicalUses) { auto *applyInst = getApplyInst(); for (Operand *operand : nonCanonicalUses) { auto *destroyInst = dyn_cast<DestroyValueInst>(operand->getUser()); if (!destroyInst) llvm::report_fatal_error("Simultaneous use of multiple call results."); for (unsigned resultIdx : indices(directResultValues)) { SingleValueInstruction *result = directResultValues[resultIdx]; if (!result) { SILBuilder resultBuilder(std::next(SILBasicBlock::iterator(applyInst))); resultBuilder.setSILConventions( SILModuleConventions::getLoweredAddressConventions()); result = resultBuilder.createTupleExtract(applyInst->getLoc(), applyInst, resultIdx); directResultValues[resultIdx] = result; } SILBuilder B(destroyInst); B.setSILConventions(SILModuleConventions::getLoweredAddressConventions()); auto &TL = pass.F->getTypeLowering(result->getType()); TL.emitDestroyValue(B, destroyInst->getLoc(), result); } destroyInst->eraseFromParent(); } } /// Return the storage address for the indirect result corresponding to the /// given original result value. Allocate temporary argument storage for any /// indirect results that are unmapped because they are loadable or unused. /// /// origDirectResultVal may be nullptr for unused results. SILValue ApplyRewriter::materializeIndirectResultAddress( SingleValueInstruction *origDirectResultVal, SILType argTy) { if (origDirectResultVal && origDirectResultVal->getType().isAddressOnly(*pass.F)) { auto &storage = pass.valueStorageMap.getStorage(origDirectResultVal); storage.markRewritten(); // Pass the local storage address as the indirect result address. return storage.storageAddress; } // Allocate temporary call-site storage for an unused or loadable result. SILInstruction *origCallInst = apply.getInstruction(); SILLocation loc = origCallInst->getLoc(); auto *allocInst = argBuilder.createAllocStack(loc, argTy); LoadInst *loadInst = nullptr; if (origDirectResultVal) { // TODO: Find the try_apply's result block. // Build results outside-in to next stack allocations. SILBuilder resultBuilder(std::next(SILBasicBlock::iterator(origCallInst))); resultBuilder.setSILConventions( SILModuleConventions::getLoweredAddressConventions()); // This is a formally indirect argument, but is loadable. loadInst = resultBuilder.createLoad(loc, allocInst, LoadOwnershipQualifier::Unqualified); origDirectResultVal->replaceAllUsesWith(loadInst); pass.markDead(origDirectResultVal); } insertStackDeallocationAtCall(allocInst, origCallInst, loadInst); return SILValue(allocInst); } /// Allocate storage for formally indirect results at the given call site. /// Create a new call instruction with indirect SIL arguments. void ApplyRewriter::convertApplyWithIndirectResults() { assert(apply.getSubstCalleeType()->hasIndirectFormalResults()); auto *origCallInst = getApplyInst(); SILFunctionConventions origFnConv = apply.getSubstCalleeConv(); // Gather the original direct return values. // Canonicalize results so no user uses more than one result. SmallVector<SingleValueInstruction *, 8> origDirectResultValues( origFnConv.getNumDirectSILResults()); SmallVector<Operand *, 4> nonCanonicalUses; if (origCallInst->getType().is<TupleType>()) { for (Operand *operand : origCallInst->getUses()) { if (auto *extract = dyn_cast<TupleExtractInst>(operand->getUser())) origDirectResultValues[extract->getFieldNo()] = extract; else nonCanonicalUses.push_back(operand); } if (!nonCanonicalUses.empty()) canonicalizeResults(origDirectResultValues, nonCanonicalUses); } else { // This call has a single, indirect result (convertApplyWithIndirectResults // only handles call with at least one indirect result). // An unused result can remain unmapped. Temporary storage will be allocated // later when fixing up the call's uses. assert(origDirectResultValues.size() == 1); if (!origCallInst->use_empty()) { assert(pass.valueStorageMap.contains(origCallInst)); origDirectResultValues[0] = origCallInst; } } // Prepare to emit a new call instruction. SILLocation loc = origCallInst->getLoc(); SILBuilder callBuilder(origCallInst); callBuilder.setSILConventions( SILModuleConventions::getLoweredAddressConventions()); // The new call instruction's SIL calling convention. SILFunctionConventions loweredCalleeConv( apply.getSubstCalleeType(), SILModuleConventions::getLoweredAddressConventions()); // The new call instruction's SIL argument list. SmallVector<SILValue, 8> newCallArgs(loweredCalleeConv.getNumSILArguments()); // Map the original result indices to new result indices. SmallVector<unsigned, 8> newDirectResultIndices( origFnConv.getNumDirectSILResults()); // Indices used to populate newDirectResultIndices. unsigned oldDirectResultIdx = 0, newDirectResultIdx = 0; // The index of the next indirect result argument. unsigned newResultArgIdx = loweredCalleeConv.getSILArgIndexOfFirstIndirectResult(); // Visit each result. Redirect results that are now indirect by calling // materializeIndirectResultAddress. Result that remain direct will be // redirected later. Populate newCallArgs and newDirectResultIndices. for_each( apply.getSubstCalleeType()->getResults(), origDirectResultValues, [&](SILResultInfo resultInfo, SingleValueInstruction *origDirectResultVal) { // Assume that all original results are direct in SIL. assert(!origFnConv.isSILIndirect(resultInfo)); if (loweredCalleeConv.isSILIndirect(resultInfo)) { SILValue indirectResultAddr = materializeIndirectResultAddress( origDirectResultVal, loweredCalleeConv.getSILType(resultInfo)); // Record the new indirect call argument. newCallArgs[newResultArgIdx++] = indirectResultAddr; // Leave a placeholder for indirect results. newDirectResultIndices[oldDirectResultIdx++] = ~0; } else { // Record the new direct result, and advance the direct result indices. newDirectResultIndices[oldDirectResultIdx++] = newDirectResultIdx++; } // replaceAllUses will be called later to handle direct results that // remain direct results of the new call instruction. }); // Append the existing call arguments to the SIL argument list. They were // already lowered to addresses by rewriteIncomingArgument. assert(newResultArgIdx == loweredCalleeConv.getSILArgIndexOfFirstParam()); unsigned origArgIdx = apply.getSubstCalleeConv().getSILArgIndexOfFirstParam(); for (unsigned endIdx = newCallArgs.size(); newResultArgIdx < endIdx; ++newResultArgIdx, ++origArgIdx) { newCallArgs[newResultArgIdx] = apply.getArgument(origArgIdx); } // Create a new apply with indirect result operands. ApplyInst *newCallInst; switch (origCallInst->getKind()) { case SILInstructionKind::ApplyInst: newCallInst = callBuilder.createApply( loc, apply.getCallee(), apply.getSubstitutionMap(), newCallArgs, cast<ApplyInst>(origCallInst)->isNonThrowing()); break; case SILInstructionKind::TryApplyInst: // TODO: insert dealloc in the catch block. llvm_unreachable("not implemented for this instruction!"); case SILInstructionKind::PartialApplyInst: // Partial apply does not have formally indirect results. default: llvm_unreachable("not implemented for this instruction!"); } // Replace all unmapped uses of the original call with uses of the new call. // // TODO: handle bbargs from try_apply. SILBuilder resultBuilder( std::next(SILBasicBlock::iterator(origCallInst))); resultBuilder.setSILConventions( SILModuleConventions::getLoweredAddressConventions()); SmallVector<Operand*, 8> origUses(origCallInst->getUses()); for (Operand *operand : origUses) { auto *extractInst = dyn_cast<TupleExtractInst>(operand->getUser()); if (!extractInst) { assert(origFnConv.getNumDirectSILResults() == 1); assert(pass.valueStorageMap.contains(origCallInst)); continue; } unsigned origResultIdx = extractInst->getFieldNo(); auto resultInfo = origFnConv.getResults()[origResultIdx]; if (extractInst->getType().isAddressOnly(*pass.F)) { // Uses of indirect results will be rewritten by AddressOnlyUseRewriter. assert(loweredCalleeConv.isSILIndirect(resultInfo)); assert(pass.valueStorageMap.contains(extractInst)); if (extractInst->use_empty()) pass.markDead(extractInst); continue; } if (loweredCalleeConv.isSILIndirect(resultInfo)) { // This loadable indirect use should already be redirected to a load from // the argument storage and marked dead. assert(extractInst->use_empty()); continue; } // Either the new call instruction has only a single direct result, or we // map the original tuple field to the new tuple field. SILValue newValue = newCallInst; if (loweredCalleeConv.getNumDirectSILResults() > 1) { assert(newValue->getType().is<TupleType>()); newValue = resultBuilder.createTupleExtract( extractInst->getLoc(), newValue, newDirectResultIndices[origResultIdx]); } extractInst->replaceAllUsesWith(newValue); extractInst->eraseFromParent(); } if (!pass.valueStorageMap.contains(origCallInst)) pass.markDead(origCallInst); } //===----------------------------------------------------------------------===// // ReturnRewriter - rewrite return instructions for indirect results. //===----------------------------------------------------------------------===// class ReturnRewriter { AddressLoweringState &pass; public: ReturnRewriter(AddressLoweringState &pass) : pass(pass) {} void rewriteReturns(); protected: void rewriteReturn(ReturnInst *returnInst); }; void ReturnRewriter::rewriteReturns() { for (TermInst *termInst : pass.returnInsts) { // TODO: handle throws rewriteReturn(cast<ReturnInst>(termInst)); } } void ReturnRewriter::rewriteReturn(ReturnInst *returnInst) { auto insertPt = SILBasicBlock::iterator(returnInst); auto bbStart = returnInst->getParent()->begin(); while (insertPt != bbStart) { --insertPt; if (!isa<DeallocStackInst>(*insertPt)) break; } SILBuilder B(insertPt); B.setSILConventions(SILModuleConventions::getLoweredAddressConventions()); // Gather direct function results. unsigned numOrigDirectResults = pass.F->getConventions().getNumDirectSILResults(); SmallVector<SILValue, 8> origDirectResultValues; if (numOrigDirectResults == 1) origDirectResultValues.push_back(returnInst->getOperand()); else { auto *tupleInst = cast<TupleInst>(returnInst->getOperand()); origDirectResultValues.append(tupleInst->getElements().begin(), tupleInst->getElements().end()); assert(origDirectResultValues.size() == numOrigDirectResults); } SILFunctionConventions origFnConv(pass.F->getConventions()); (void)origFnConv; // Convert each result. SmallVector<SILValue, 8> newDirectResults; unsigned newResultArgIdx = pass.loweredFnConv.getSILArgIndexOfFirstIndirectResult(); for_each( pass.F->getLoweredFunctionType()->getResults(), origDirectResultValues, [&](SILResultInfo resultInfo, SILValue origDirectResultVal) { // Assume that all original results are direct in SIL. assert(!origFnConv.isSILIndirect(resultInfo)); if (pass.loweredFnConv.isSILIndirect(resultInfo)) { assert(newResultArgIdx < pass.loweredFnConv.getSILArgIndexOfFirstParam()); SILArgument *resultArg = B.getFunction().getArgument(newResultArgIdx); SILType resultTy = origDirectResultVal->getType(); if (resultTy.isAddressOnly(*pass.F)) { ValueStorage &storage = pass.valueStorageMap.getStorage(origDirectResultVal); assert(storage.isRewritten()); if (!storage.isProjection()) { // Copy the result from local storage into the result argument. SILValue resultAddr = storage.storageAddress; B.createCopyAddr(returnInst->getLoc(), resultAddr, resultArg, IsTake, IsInitialization); } } else { // Store the result into the result argument. B.createStore(returnInst->getLoc(), origDirectResultVal, resultArg, StoreOwnershipQualifier::Unqualified); } ++newResultArgIdx; } else { // Record the direct result for populating the result tuple. newDirectResults.push_back(origDirectResultVal); } }); assert(newDirectResults.size() == pass.loweredFnConv.getNumDirectSILResults()); SILValue newReturnVal; if (newDirectResults.empty()) { SILType emptyTy = SILType::getPrimitiveObjectType( B.getModule().getASTContext().TheEmptyTupleType); newReturnVal = B.createTuple(returnInst->getLoc(), emptyTy, {}); } else if (newDirectResults.size() == 1) { newReturnVal = newDirectResults[0]; } else { newReturnVal = B.createTuple(returnInst->getLoc(), pass.loweredFnConv.getSILResultType(), newDirectResults); } SILValue origFullResult = returnInst->getOperand(); returnInst->setOperand(newReturnVal); if (auto *fullResultInst = origFullResult->getDefiningInstruction()) { if (!fullResultInst->hasUsesOfAnyResult()) pass.markDead(fullResultInst); } } //===----------------------------------------------------------------------===// // AddressOnlyUseRewriter - rewrite opaque value uses. //===----------------------------------------------------------------------===// namespace { class AddressOnlyUseRewriter : SILInstructionVisitor<AddressOnlyUseRewriter> { friend SILVisitorBase<AddressOnlyUseRewriter>; friend SILInstructionVisitor<AddressOnlyUseRewriter>; AddressLoweringState &pass; SILBuilder B; AddressMaterialization addrMat; Operand *currOper; public: explicit AddressOnlyUseRewriter(AddressLoweringState &pass) : pass(pass), B(*pass.F), addrMat(pass, B) { B.setSILConventions(SILModuleConventions::getLoweredAddressConventions()); } void visitOperand(Operand *operand) { currOper = operand; visit(operand->getUser()); } protected: void markRewritten(SILValue oldValue, SILValue addr) { auto &storage = pass.valueStorageMap.getStorage(oldValue); storage.storageAddress = addr; storage.markRewritten(); } void beforeVisit(SILInstruction *I) { LLVM_DEBUG(llvm::dbgs() << " REWRITE USE "; I->dump()); B.setInsertionPoint(I); B.setCurrentDebugScope(I->getDebugScope()); } void visitSILInstruction(SILInstruction *I) { LLVM_DEBUG(I->dump()); llvm_unreachable("Unimplemented?!"); } void visitApplyInst(ApplyInst *applyInst) { ApplyRewriter(applyInst, pass).rewriteIndirectParameter(currOper); } void visitCopyValueInst(CopyValueInst *copyInst) { ValueStorage &storage = pass.valueStorageMap.getStorage(copyInst); // Fold a copy into a store. if (storage.isProjection() && isa<StoreInst>(storage.getComposedOperand()->getUser())) { return; } SILValue srcVal = copyInst->getOperand(); SILValue srcAddr = pass.valueStorageMap.getStorage(srcVal).storageAddress; SILValue destAddr = addrMat.materializeAddress(copyInst); B.createCopyAddr(copyInst->getLoc(), srcAddr, destAddr, IsNotTake, IsInitialization); markRewritten(copyInst, destAddr); } void visitDebugValueInst(DebugValueInst *debugInst) { SILValue srcVal = debugInst->getOperand(); SILValue srcAddr = pass.valueStorageMap.getStorage(srcVal).storageAddress; B.createDebugValueAddr(debugInst->getLoc(), srcAddr, *debugInst->getVarInfo()); pass.markDead(debugInst); } void visitDestroyValueInst(DestroyValueInst *destroyInst) { SILValue srcVal = destroyInst->getOperand(); SILValue srcAddr = pass.valueStorageMap.getStorage(srcVal).storageAddress; B.createDestroyAddr(destroyInst->getLoc(), srcAddr); pass.markDead(destroyInst); } // Handle EnumInst on the def side to handle both opaque and // loadable operands. void visitEnumInst(EnumInst *enumInst) {} // Handle InitExistentialValue on the def side to handle both opaque and // loadable operands. void visitInitExistentialValueInst(InitExistentialValueInst *initExistential) {} void visitReturnInst(ReturnInst *returnInst) { // Returns are rewritten for any function with indirect results after opaque // value rewriting. } void visitStoreInst(StoreInst *storeInst) { SILValue srcVal = storeInst->getSrc(); assert(currOper->get() == srcVal); ValueStorage &storage = pass.valueStorageMap.getStorage(srcVal); SILValue srcAddr = storage.storageAddress; IsTake_t isTakeFlag = IsTake; assert(storeInst->getOwnershipQualifier() == StoreOwnershipQualifier::Unqualified); if (storage.isProjection()) { assert(!srcAddr); auto *copyInst = cast<CopyValueInst>(srcVal); ValueStorage &srcStorage = pass.valueStorageMap.getStorage(copyInst->getOperand()); assert(!srcStorage.isProjection()); srcAddr = srcStorage.storageAddress; isTakeFlag = IsNotTake; } // Bitwise copy the value. Two locations now share ownership. This is // modeled as a take-init. B.createCopyAddr(storeInst->getLoc(), srcAddr, storeInst->getDest(), isTakeFlag, IsInitialization); pass.markDead(storeInst); } void visitTupleInst(TupleInst *tupleInst) { // Tuples are rewritten on the def-side, where both direct and indirect // elements are composed. } void visitTupleExtractInst(TupleExtractInst *extractInst) { // Apply results are rewritten when the result definition is visited. if (ApplySite::isa(currOper->get())) return; // TODO: generate tuple_element_addr. // generate copy_addr if we can't project. llvm_unreachable("unimplemented."); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // AddressOnlyDefRewriter - rewrite opaque value definitions. //===----------------------------------------------------------------------===// namespace { class AddressOnlyDefRewriter : SILInstructionVisitor<AddressOnlyDefRewriter> { friend SILVisitorBase<AddressOnlyDefRewriter>; friend SILInstructionVisitor<AddressOnlyDefRewriter>; AddressLoweringState &pass; SILBuilder B; AddressMaterialization addrMat; ValueStorage *storage = nullptr; public: explicit AddressOnlyDefRewriter(AddressLoweringState &pass) : pass(pass), B(*pass.F), addrMat(pass, B) { B.setSILConventions(SILModuleConventions::getLoweredAddressConventions()); } void visitInst(SILInstruction *inst) { visit(inst); } protected: void beforeVisit(SILInstruction *I) { // This cast succeeds beecause only specific instructions get added to // the value storage map. storage = &pass.valueStorageMap.getStorage(cast<SingleValueInstruction>(I)); LLVM_DEBUG(llvm::dbgs() << "REWRITE DEF "; I->dump()); if (storage->storageAddress) LLVM_DEBUG(llvm::dbgs() << " STORAGE "; storage->storageAddress->dump()); B.setInsertionPoint(I); B.setCurrentDebugScope(I->getDebugScope()); } void visitSILInstruction(SILInstruction *I) { LLVM_DEBUG(I->dump()); llvm_unreachable("Unimplemented?!"); } void visitApplyInst(ApplyInst *applyInst) { assert(isa<SingleValueInstruction>(applyInst) && "beforeVisit assumes that ApplyInst is an SVI"); assert(!storage->isRewritten()); // Completely rewrite the apply instruction, handling any remaining // (loadable) indirect parameters, allocating memory for indirect // results, and generating a new apply instruction. ApplyRewriter rewriter(applyInst, pass); rewriter.rewriteParameters(); rewriter.convertApplyWithIndirectResults(); } void visitCopyValueInst(CopyValueInst *copyInst) { // A folded copy is not rewritten. assert(storage->isProjection() || storage->isRewritten()); } void visitEnumInst(EnumInst *enumInst) { SILValue enumAddr; if (enumInst->hasOperand()) { addrMat.initializeOperandMem(&enumInst->getOperandRef()); assert(storage->storageAddress); enumAddr = storage->storageAddress; } else enumAddr = addrMat.materializeAddress(enumInst); B.createInjectEnumAddr(enumInst->getLoc(), enumAddr, enumInst->getElement()); storage->markRewritten(); } void visitInitExistentialValueInst( InitExistentialValueInst *initExistentialValue) { // Initialize memory for the operand which may be opaque or loadable. addrMat.initializeOperandMem(&initExistentialValue->getOperandRef()); assert(storage->storageAddress); storage->markRewritten(); } void visitLoadInst(LoadInst *loadInst) { // Bitwise copy the value. Two locations now share ownership. This is // modeled as a take-init. SILValue addr = pass.valueStorageMap.getStorage(loadInst).storageAddress; if (addr != loadInst->getOperand()) { B.createCopyAddr(loadInst->getLoc(), loadInst->getOperand(), addr, IsTake, IsInitialization); } storage->markRewritten(); } void visitTupleInst(TupleInst *tupleInst) { ValueStorage &storage = pass.valueStorageMap.getStorage(tupleInst); if (storage.isProjection() && isa<ReturnInst>(storage.getComposedOperand()->getUser())) { // For indirectly returned values, each element has its own storage. return; } // For each element, initialize the operand's memory. Some tuple elements // may be loadable types. SILValue tupleAddr = addrMat.materializeAddress(tupleInst); unsigned eltIdx = 0; for (Operand &operand : tupleInst->getAllOperands()) { SILType eltTy = operand.get()->getType(); if (eltTy.isAddressOnly(*pass.F)) addrMat.initializeOperandMem(&operand); else { auto *elementAddr = B.createTupleElementAddr( tupleInst->getLoc(), tupleAddr, eltIdx, eltTy.getAddressType()); B.createStore(tupleInst->getLoc(), operand.get(), elementAddr, StoreOwnershipQualifier::Unqualified); } ++eltIdx; } } void visitTupleExtractInst(TupleExtractInst *extractInst) { // If the source is an opaque tuple, as opposed to a call result, then the // extract is rewritten on the use-side. if (storage->isRewritten()) return; // This must be an indirect result for an apply that has not yet been // rewritten. Rewrite the apply. SILValue srcVal = extractInst->getOperand(); ApplyRewriter(cast<ApplyInst>(srcVal), pass) .convertApplyWithIndirectResults(); assert(storage->storageAddress); } }; } // end anonymous namespace static void rewriteFunction(AddressLoweringState &pass) { AddressOnlyDefRewriter defVisitor(pass); AddressOnlyUseRewriter useVisitor(pass); for (auto &valueStorageI : pass.valueStorageMap) { SILValue valueDef = valueStorageI.first; // TODO: MultiValueInstruction: ApplyInst if (auto *defInst = dyn_cast<SingleValueInstruction>(valueDef)) defVisitor.visitInst(defInst); SmallVector<Operand *, 8> uses(valueDef->getUses()); for (Operand *oper : uses) useVisitor.visitOperand(oper); } // Rewrite any remaining (loadable) indirect parameters. for (ApplySite apply : pass.indirectApplies) { // Calls with indirect formal results have already been rewritten. if (apply.getSubstCalleeType()->hasIndirectFormalResults()) { bool isRewritten = false; visitCallResults(apply, [&](SILValue result) { if (result->getType().isAddressOnly(*pass.F)) { assert(pass.valueStorageMap.getStorage(result).isRewritten()); isRewritten = true; return false; } return true; }); if (!isRewritten) { ApplyRewriter rewriter(apply, pass); rewriter.rewriteParameters(); rewriter.convertApplyWithIndirectResults(); continue; } } ApplyRewriter(apply, pass).rewriteParameters(); } if (pass.F->getLoweredFunctionType()->hasIndirectFormalResults()) ReturnRewriter(pass).rewriteReturns(); } //===----------------------------------------------------------------------===// // AddressLowering: Top-Level Function Transform. //===----------------------------------------------------------------------===// namespace { class AddressLowering : public SILModuleTransform { /// The entry point to this function transformation. void run() override; void runOnFunction(SILFunction *F); }; } // end anonymous namespace void AddressLowering::runOnFunction(SILFunction *F) { auto *DA = PM->getAnalysis<DominanceAnalysis>(); AddressLoweringState pass(F, DA->get(F)); // Rewrite function args and insert alloc_stack/dealloc_stack. OpaqueStorageAllocation allocator(pass); allocator.allocateOpaqueStorage(); LLVM_DEBUG(llvm::dbgs() << "\nREWRITING: " << F->getName(); F->dump()); // Rewrite instructions with address-only operands or results. rewriteFunction(pass); invalidateAnalysis(F, SILAnalysis::InvalidationKind::Instructions); // Instructions that were explicitly marked dead should already have no // users. // // Add the rest of the instructions to the dead list in post order. // FIXME: make sure we cleaned up address-only BB arguments. for (auto &valueStorageI : reversed(pass.valueStorageMap)) { // TODO: MultiValueInstruction: ApplyInst auto *deadInst = dyn_cast<SingleValueInstruction>(valueStorageI.first); if (!deadInst) continue; LLVM_DEBUG(llvm::dbgs() << "DEAD "; deadInst->dump()); #ifndef NDEBUG for (auto result : deadInst->getResults()) for (Operand *operand : result->getUses()) assert(pass.instsToDelete.count(operand->getUser())); #endif pass.instsToDelete.insert(deadInst); } pass.valueStorageMap.clear(); // Delete instructions in postorder recursivelyDeleteTriviallyDeadInstructions(pass.instsToDelete.takeVector(), true); } /// The entry point to this function transformation. void AddressLowering::run() { if (getModule()->getASTContext().LangOpts.EnableSILOpaqueValues) { for (auto &F : *getModule()) runOnFunction(&F); } // Set the SIL state before the PassManager has a chance to run // verification. getModule()->setStage(SILStage::Lowered); } SILTransform *swift::createAddressLowering() { return new AddressLowering(); }
apache-2.0
Simran-B/arangodb
lib/SimpleHttpClient/SimpleHttpClient.cpp
1
32947
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Achim Brandt /// @author Simon Grätzer //////////////////////////////////////////////////////////////////////////////// #include <stddef.h> #include <chrono> #include <cstdint> #include <exception> #include <thread> #include <utility> #include <boost/algorithm/string/predicate.hpp> #include <velocypack/Builder.h> #include <velocypack/Parser.h> #include <velocypack/Slice.h> #include <velocypack/velocypack-aliases.h> #include "SimpleHttpClient.h" #include "ApplicationFeatures/ApplicationServer.h" #include "ApplicationFeatures/CommunicationFeaturePhase.h" #include "Basics/ScopeGuard.h" #include "Basics/StaticStrings.h" #include "Basics/StringUtils.h" #include "Basics/system-compiler.h" #include "Basics/system-functions.h" #include "Endpoint/Endpoint.h" #include "Logger/LogMacros.h" #include "Logger/Logger.h" #include "Logger/LoggerStream.h" #include "Rest/GeneralResponse.h" #include "SimpleHttpClient/GeneralClientConnection.h" #include "SimpleHttpClient/SimpleHttpResult.h" using namespace arangodb; using namespace arangodb::basics; namespace arangodb { namespace httpclient { /// @brief empty map, used for headers std::unordered_map<std::string, std::string> const SimpleHttpClient::NO_HEADERS{}; /// @brief default value for max packet size size_t SimpleHttpClientParams::MaxPacketSize = 512 * 1024 * 1024; SimpleHttpClient::SimpleHttpClient(GeneralClientConnection* connection, SimpleHttpClientParams const& params) : _connection(connection), _deleteConnectionOnDestruction(false), _params(params), _writeBuffer(false), _readBuffer(false), _readBufferOffset(0), _state(IN_CONNECT), _written(0), _errorMessage(""), _nextChunkedSize(0), _method(rest::RequestType::GET), _result(nullptr), _aborted(false) { TRI_ASSERT(connection != nullptr); if (_connection->isConnected()) { _state = FINISHED; } } SimpleHttpClient::SimpleHttpClient(std::unique_ptr<GeneralClientConnection>& connection, SimpleHttpClientParams const& params) : SimpleHttpClient(connection.get(), params) { _deleteConnectionOnDestruction = true; connection.release(); } SimpleHttpClient::~SimpleHttpClient() { // connection may have been invalidated by other objects if (_connection != nullptr) { if (!_params._keepConnectionOnDestruction || !_connection->isConnected()) { _connection->disconnect(); } if (_deleteConnectionOnDestruction) { delete _connection; } } } // ----------------------------------------------------------------------------- // public methods // ----------------------------------------------------------------------------- void SimpleHttpClient::setAborted(bool value) noexcept { _aborted.store(value, std::memory_order_release); setInterrupted(value); } void SimpleHttpClient::setInterrupted(bool value) { if (_connection != nullptr) { _connection->setInterrupted(value); } } bool SimpleHttpClient::isConnected() { return _connection->isConnected(); } void SimpleHttpClient::disconnect() { _connection->disconnect(); } std::string SimpleHttpClient::getEndpointSpecification() const { return _connection == nullptr ? "unknown" : _connection->getEndpointSpecification(); } //////////////////////////////////////////////////////////////////////////////// /// @brief close connection //////////////////////////////////////////////////////////////////////////////// void SimpleHttpClient::close() { // ensure connection has not yet been invalidated TRI_ASSERT(_connection != nullptr); _connection->disconnect(); _state = IN_CONNECT; clearReadBuffer(); } //////////////////////////////////////////////////////////////////////////////// /// @brief send out a request, creating a new HttpResult object /// this version does not allow specifying custom headers /// if the request fails because of connection problems, the request will be /// retried until it either succeeds (at least no connection problem) or there /// have been _maxRetries retries //////////////////////////////////////////////////////////////////////////////// SimpleHttpResult* SimpleHttpClient::retryRequest(rest::RequestType method, std::string const& location, char const* body, size_t bodyLength) { return retryRequest(method, location, body, bodyLength, NO_HEADERS); } //////////////////////////////////////////////////////////////////////////////// /// @brief send out a request, creating a new HttpResult object /// this version does not allow specifying custom headers /// if the request fails because of connection problems, the request will be /// retried until it either succeeds (at least no connection problem) or there /// have been _maxRetries retries //////////////////////////////////////////////////////////////////////////////// SimpleHttpResult* SimpleHttpClient::retryRequest( rest::RequestType method, std::string const& location, char const* body, size_t bodyLength, std::unordered_map<std::string, std::string> const& headers) { SimpleHttpResult* result = nullptr; size_t tries = 0; while (true) { TRI_ASSERT(result == nullptr); result = doRequest(method, location, body, bodyLength, headers); if (result != nullptr && result->isComplete()) { break; } delete result; result = nullptr; if (tries++ >= _params._maxRetries) { LOG_TOPIC("de0be", WARN, arangodb::Logger::HTTPCLIENT) << "" << _params._retryMessage << " - no retries left"; break; } auto& server = _connection->server(); if (server.isStopping()) { // abort this client, will also lead to exiting this loop next setAborted(true); } if (isAborted()) { break; } if (!_params._retryMessage.empty() && (_params._maxRetries - tries) > 0) { LOG_TOPIC("2b48f", WARN, arangodb::Logger::HTTPCLIENT) << "" << _params._retryMessage << " - retries left: " << (_params._maxRetries - tries); } // 1 microsecond == 10^-6 seconds std::this_thread::sleep_for(std::chrono::microseconds(_params._retryWaitTime)); } return result; } //////////////////////////////////////////////////////////////////////////////// /// @brief send out a request, creating a new HttpResult object /// this version does not allow specifying custom headers //////////////////////////////////////////////////////////////////////////////// SimpleHttpResult* SimpleHttpClient::request(rest::RequestType method, std::string const& location, char const* body, size_t bodyLength) { return doRequest(method, location, body, bodyLength, NO_HEADERS); } //////////////////////////////////////////////////////////////////////////////// /// @brief send out a request, creating a new HttpResult object /// this version allows specifying custom headers //////////////////////////////////////////////////////////////////////////////// SimpleHttpResult* SimpleHttpClient::request( rest::RequestType method, std::string const& location, char const* body, size_t bodyLength, std::unordered_map<std::string, std::string> const& headers) { return doRequest(method, location, body, bodyLength, headers); } //////////////////////////////////////////////////////////////////////////////// /// @brief send out a request, worker function //////////////////////////////////////////////////////////////////////////////// SimpleHttpResult* SimpleHttpClient::doRequest( rest::RequestType method, std::string const& location, char const* body, size_t bodyLength, std::unordered_map<std::string, std::string> const& headers) { // ensure connection has not yet been invalidated TRI_ASSERT(_connection != nullptr); if (isAborted()) { return nullptr; } // ensure that result is empty TRI_ASSERT(_result == nullptr); // create a new result _result = new SimpleHttpResult(); auto resultGuard = scopeGuard([this] { delete _result; _result = nullptr; }); // reset error message _errorMessage = ""; auto& server = _connection->server(); auto& comm = server.getFeature<application_features::CommunicationFeaturePhase>(); // set body setRequest(method, rewriteLocation(location), body, bodyLength, headers); // ensure state TRI_ASSERT(_state == IN_CONNECT || _state == IN_WRITE); // respect timeout double endTime = TRI_microtime() + _params._requestTimeout; double remainingTime = _params._requestTimeout; bool haveSentRequest = false; while (_state < FINISHED && remainingTime > 0.0) { // Note that this loop can either be left by timeout or because // a connect did not work (which sets the _state to DEAD). In all // other error conditions we call close() which resets the state // to IN_CONNECT and tries a reconnect. This is important because // it is always possible that we are called with a connection that // has already been closed by the other side. This leads to the // strange effect that the write (if it is small enough) proceeds // but the following read runs into an error. In that case we try // to reconnect one and then give up if this does not work. switch (_state) { case (IN_CONNECT): { handleConnect(); // If this goes wrong, _state is set to DEAD break; } case (IN_WRITE): { size_t bytesWritten = 0; TRI_ASSERT(_writeBuffer.length() >= _written); TRI_set_errno(TRI_ERROR_NO_ERROR); bool res = _connection->handleWrite(remainingTime, static_cast<void const*>(_writeBuffer.c_str() + _written), _writeBuffer.length() - _written, &bytesWritten); if (!res) { setErrorMessage("Error writing to '" + _connection->getEndpoint()->specification() + "' '" + _connection->getErrorDetails() + "'"); this->close(); // this sets _state to IN_CONNECT for a retry } else { _written += bytesWritten; if (_written == _writeBuffer.length()) { _state = IN_READ_HEADER; haveSentRequest = true; } } break; } case (IN_READ_HEADER): case (IN_READ_BODY): case (IN_READ_CHUNKED_HEADER): case (IN_READ_CHUNKED_BODY): { TRI_set_errno(TRI_ERROR_NO_ERROR); // we need to notice if the other side has closed the connection: bool connectionClosed; bool res = _connection->handleRead(remainingTime, _readBuffer, connectionClosed); // If there was an error, then we are doomed: if (!res) { setErrorMessage("Error reading from: '" + _connection->getEndpoint()->specification() + "' '" + _connection->getErrorDetails() + "'"); if (_connection->isInterrupted()) { this->close(); setErrorMessage("Command locally aborted"); return nullptr; } this->close(); // this sets the state to IN_CONNECT for a retry LOG_TOPIC("e5154", DEBUG, arangodb::Logger::HTTPCLIENT) << _errorMessage; std::this_thread::sleep_for(std::chrono::milliseconds(5)); break; } // no error if (connectionClosed) { // write might have succeeded even if the server has closed // the connection, this will then show up here with us being // in state IN_READ_HEADER but nothing read. if (_state == IN_READ_HEADER && 0 == _readBuffer.length()) { this->close(); _state = DEAD; setErrorMessage("Connection closed by remote"); break; } if (_state == IN_READ_HEADER) { processHeader(); } if (_state == IN_READ_BODY) { if (!_result->hasContentLength()) { // If we are reading the body and no content length was // found in the header, then we must read until no more // progress is made (but without an error), this then means // that the server has closed the connection and we must // process the body one more time: _result->setContentLength(_readBuffer.length() - _readBufferOffset); } processBody(); } if (_state != FINISHED) { // If the body was not fully found we give up: this->close(); _state = DEAD; setErrorMessage("Got unexpected response from remote"); } break; } // the connection is still alive: switch (_state) { case (IN_READ_HEADER): processHeader(); break; case (IN_READ_BODY): processBody(); break; case (IN_READ_CHUNKED_HEADER): processChunkedHeader(); break; case (IN_READ_CHUNKED_BODY): processChunkedBody(); break; default: break; } break; } default: break; } if (!comm.getCommAllowed()) { setErrorMessage("Command locally aborted"); return nullptr; } remainingTime = endTime - TRI_microtime(); if (isAborted()) { setErrorMessage("Client request aborted"); break; } } if (_state < FINISHED && _errorMessage.empty()) { setErrorMessage("Request timeout reached"); _result->setHttpReturnCode(static_cast<int>(ResponseCode::GATEWAY_TIMEOUT)); } // set result type in getResult() SimpleHttpResult* result = getResult(haveSentRequest); _result = nullptr; resultGuard.cancel(); // doesn't matter but do it anyway return result; } // ----------------------------------------------------------------------------- // private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief initialize the connection //////////////////////////////////////////////////////////////////////////////// void SimpleHttpClient::handleConnect() { // ensure connection has not yet been invalidated TRI_ASSERT(_connection != nullptr); if (!_connection->connect()) { setErrorMessage("Could not connect to '" + _connection->getEndpoint()->specification() + "' '" + _connection->getErrorDetails() + "'"); _state = DEAD; } else { // can write now _state = IN_WRITE; _written = 0; } } //////////////////////////////////////////////////////////////////////////////// /// @brief clearReadBuffer, clears the read buffer as well as the result //////////////////////////////////////////////////////////////////////////////// void SimpleHttpClient::clearReadBuffer() { _readBuffer.clear(); _readBufferOffset = 0; if (_result) { _result->clear(); } } //////////////////////////////////////////////////////////////////////////////// /// @brief return the result //////////////////////////////////////////////////////////////////////////////// SimpleHttpResult* SimpleHttpClient::getResult(bool haveSentRequest) { _result->setHaveSentRequestFully(haveSentRequest); switch (_state) { case IN_WRITE: _result->setResultType(SimpleHttpResult::WRITE_ERROR); break; case IN_READ_HEADER: case IN_READ_BODY: case IN_READ_CHUNKED_HEADER: case IN_READ_CHUNKED_BODY: _result->setResultType(SimpleHttpResult::READ_ERROR); break; case FINISHED: _result->setResultType(SimpleHttpResult::COMPLETE); break; case IN_CONNECT: default: { _result->setResultType(SimpleHttpResult::COULD_NOT_CONNECT); if (!haveErrorMessage()) { setErrorMessage("Could not connect"); } break; } } if (haveErrorMessage() && _result->getHttpReturnMessage().empty()) { _result->setHttpReturnMessage(_errorMessage); } return _result; } //////////////////////////////////////////////////////////////////////////////// /// @brief prepare a request //////////////////////////////////////////////////////////////////////////////// void SimpleHttpClient::setRequest(rest::RequestType method, std::string const& location, char const* body, size_t bodyLength, std::unordered_map<std::string, std::string> const& headers) { // clear read-buffer (no pipelining!) _readBufferOffset = 0; _readBuffer.reset(); // set HTTP method _method = method; // now fill the write buffer _writeBuffer.clear(); // append method GeneralRequest::appendMethod(method, &_writeBuffer); // append location std::string const* l = &location; std::string appended; if (location.empty() || location[0] != '/') { appended.reserve(1 + location.size()); appended = '/' + location; l = &appended; } _writeBuffer.appendText(*l); // append protocol _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR(" HTTP/1.1\r\n")); // append hostname std::string hostname = _connection->getEndpoint()->host(); LOG_TOPIC("908b8", DEBUG, Logger::HTTPCLIENT) << "request to " << hostname << ": " << GeneralRequest::translateMethod(method) << ' ' << *l; _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("Host: ")); _writeBuffer.appendText(hostname); _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("\r\n")); if (_params._keepAlive) { _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("Connection: Keep-Alive\r\n")); } else { _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("Connection: Close\r\n")); } if (_params._exposeArangoDB) { _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("User-Agent: ArangoDB\r\n")); } // do not automatically advertise deflate support if (_params._supportDeflate) { _writeBuffer.appendText( TRI_CHAR_LENGTH_PAIR("Accept-Encoding: deflate\r\n")); } // do basic authorization std::vector<std::pair<size_t, size_t>> exclusions; size_t pos = 0; if (!_params._jwt.empty()) { _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("Authorization: bearer ")); pos = _writeBuffer.size(); _writeBuffer.appendText(_params._jwt); exclusions.emplace_back(pos, _writeBuffer.size()); _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("\r\n")); } else if (!_params._basicAuth.empty()) { _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("Authorization: Basic ")); pos = _writeBuffer.size(); _writeBuffer.appendText(_params._basicAuth); exclusions.emplace_back(pos, _writeBuffer.size()); _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("\r\n")); } for (auto const& header : headers) { if (boost::iequals(StaticStrings::ContentLength, header.first)) { continue; // skip content-length header } _writeBuffer.appendText(header.first); _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR(": ")); if (boost::iequals(StaticStrings::Authorization, header.first)) { pos = _writeBuffer.size(); _writeBuffer.appendText(header.second); exclusions.emplace_back(pos, _writeBuffer.size()); } else { _writeBuffer.appendText(header.second); } _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("\r\n")); } if (method != rest::RequestType::GET) { _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("Content-Length: ")); _writeBuffer.appendInteger(static_cast<uint64_t>(bodyLength)); _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("\r\n\r\n")); } else { _writeBuffer.appendText(TRI_CHAR_LENGTH_PAIR("\r\n")); } if (body != nullptr) { _writeBuffer.appendText(body, bodyLength); } _writeBuffer.ensureNullTerminated(); if (exclusions.empty()) { LOG_TOPIC("12c4c", TRACE, arangodb::Logger::HTTPCLIENT) << "request: " << _writeBuffer; } else { pos = 0; for (size_t i = 0; i < exclusions.size(); ++i) { LOG_TOPIC("12c4b", TRACE, arangodb::Logger::HTTPCLIENT) << "request: " << std::string_view(_writeBuffer.data() + pos, exclusions[i].first - pos) << "SENSITIVE_DETAILS_HIDDEN"; pos = exclusions[i].second; } LOG_TOPIC("12c4e", TRACE, arangodb::Logger::HTTPCLIENT) << "request: " << std::string_view(_writeBuffer.data() + pos, _writeBuffer.size() - pos); } if (_state == DEAD) { _connection->resetNumConnectRetries(); } // close connection to reset all read and write buffers if (_state != FINISHED) { this->close(); } // we are connected, start with writing if (_connection->isConnected()) { _state = IN_WRITE; _written = 0; } // connect to server else { _state = IN_CONNECT; } TRI_ASSERT(_state == IN_CONNECT || _state == IN_WRITE); } // ----------------------------------------------------------------------------- // private methods // ----------------------------------------------------------------------------- void SimpleHttpClient::processHeader() { TRI_ASSERT(_readBufferOffset <= _readBuffer.length()); size_t remain = _readBuffer.length() - _readBufferOffset; char const* ptr = _readBuffer.c_str() + _readBufferOffset; char const* pos = static_cast<char const*>(memchr(ptr, '\n', remain)); // We enforce the following invariants: // ptr = _readBuffer.c_str() + _readBufferOffset // _readBuffer.length() >= _readBufferOffset // remain = _readBuffer.length() - _readBufferOffset while (pos) { TRI_ASSERT(_readBufferOffset <= _readBuffer.length()); TRI_ASSERT(ptr == _readBuffer.c_str() + _readBufferOffset); TRI_ASSERT(remain == _readBuffer.length() - _readBufferOffset); if (pos > ptr && *(pos - 1) == '\r') { // adjust eol position --pos; } // end of header found if (*ptr == '\r' || *ptr == '\n' || *ptr == '\0') { size_t len = pos - ptr; _readBufferOffset += len + 1; TRI_ASSERT(_readBufferOffset <= _readBuffer.length()); ptr += len + 1; remain -= len + 1; if (*pos == '\r') { // adjust offset if line ended with \r\n ++_readBufferOffset; TRI_ASSERT(_readBufferOffset <= _readBuffer.length()); ptr++; remain--; } // handle chunks if (_result->isChunked()) { _state = IN_READ_CHUNKED_HEADER; processChunkedHeader(); return; } // no content-length header in response else if (!_result->hasContentLength()) { _state = IN_READ_BODY; processBody(); return; } // no body else if (_result->hasContentLength() && _result->getContentLength() == 0) { _result->setResultType(SimpleHttpResult::COMPLETE); _state = FINISHED; if (!_params._keepAlive) { _connection->disconnect(); } return; } // found content-length header in response else if (_result->hasContentLength() && _result->getContentLength() > 0) { if (_result->getContentLength() > _params._maxPacketSize) { std::string errorMessage( "ignoring HTTP response with 'Content-Length' bigger than max " "packet size ("); errorMessage += std::to_string(_result->getContentLength()) + " > " + std::to_string(_params._maxPacketSize) + ")"; setErrorMessage(errorMessage, true); // reset connection this->close(); _state = DEAD; return; } _state = IN_READ_BODY; processBody(); return; } else { TRI_ASSERT(false); } break; } // we have found more header fields else { size_t len = pos - ptr; _result->addHeaderField(ptr, len); if (*pos == '\r') { // adjust length if line ended with \r\n // (header was already added so no harm is done) ++len; } // account for \n ptr += len + 1; _readBufferOffset += len + 1; TRI_ASSERT(_readBufferOffset <= _readBuffer.length()); remain -= (len + 1); TRI_ASSERT(_readBufferOffset <= _readBuffer.length()); TRI_ASSERT(ptr == _readBuffer.c_str() + _readBufferOffset); TRI_ASSERT(remain == _readBuffer.length() - _readBufferOffset); pos = static_cast<char const*>(memchr(ptr, '\n', remain)); } } } void SimpleHttpClient::processBody() { // HEAD requests may be responded to without a body... if (_method == rest::RequestType::HEAD) { _result->setResultType(SimpleHttpResult::COMPLETE); _state = FINISHED; if (!_params._keepAlive) { _connection->disconnect(); } return; } // we need to wait for a close, if content length is unknown if (!_result->hasContentLength()) { return; } // we need to wait for more data if (_readBuffer.length() - _readBufferOffset < _result->getContentLength()) { return; } // body is compressed using deflate. inflate it if (_result->isDeflated()) { _readBuffer.inflate(_result->getBody(), 16384, _readBufferOffset); } // body is not compressed else { // Note that if we are here, then // _result->getContentLength() <= _readBuffer.length()-_readBufferOffset _result->getBody().appendText(_readBuffer.c_str() + _readBufferOffset, _result->getContentLength()); _result->getBody().ensureNullTerminated(); } _readBufferOffset += _result->getContentLength(); TRI_ASSERT(_readBufferOffset <= _readBuffer.length()); _result->setResultType(SimpleHttpResult::COMPLETE); _state = FINISHED; if (!_params._keepAlive) { _connection->disconnect(); } } void SimpleHttpClient::processChunkedHeader() { size_t remain = _readBuffer.length() - _readBufferOffset; char const* ptr = _readBuffer.c_str() + _readBufferOffset; char const* pos = static_cast<char const*>(memchr(ptr, '\n', remain)); // not yet finished, newline is missing if (pos == nullptr) { return; } // adjust eol position if (pos > ptr && *(pos - 1) == '\r') { --pos; } size_t len = pos - (_readBuffer.c_str() + _readBufferOffset); std::string line(_readBuffer.c_str() + _readBufferOffset, len); StringUtils::trimInPlace(line); _readBufferOffset += (len + 1); // adjust offset if line ended with \r\n if (*pos == '\r') { ++_readBufferOffset; TRI_ASSERT(_readBufferOffset <= _readBuffer.length()); } // empty lines are an error if (line[0] == '\r' || line.empty()) { setErrorMessage("found invalid Content-Length", true); // reset connection this->close(); _state = DEAD; return; } uint32_t contentLength; try { contentLength = static_cast<uint32_t>(std::stol(line, nullptr, 16)); } catch (...) { setErrorMessage("found invalid Content-Length", true); // reset connection this->close(); _state = DEAD; return; } // failed: too many bytes if (contentLength > _params._maxPacketSize) { std::string errorMessage( "ignoring HTTP response with 'Content-Length' bigger than max packet " "size ("); errorMessage += std::to_string(contentLength) + " > " + std::to_string(_params._maxPacketSize) + ")"; setErrorMessage(errorMessage, true); // reset connection this->close(); _state = DEAD; return; } _state = IN_READ_CHUNKED_BODY; _nextChunkedSize = contentLength; processChunkedBody(); } void SimpleHttpClient::processChunkedBody() { // HEAD requests may be responded to without a body... if (_method == rest::RequestType::HEAD) { _result->setResultType(SimpleHttpResult::COMPLETE); _state = FINISHED; if (!_params._keepAlive) { _connection->disconnect(); } return; } if (_readBuffer.length() - _readBufferOffset >= _nextChunkedSize + 2) { // last chunk length was 0, therefore we are finished if (_nextChunkedSize == 0) { _result->setResultType(SimpleHttpResult::COMPLETE); _state = FINISHED; if (!_params._keepAlive) { _connection->disconnect(); } return; } if (_result->isDeflated()) { _readBuffer.inflate(_result->getBody(), 16384, _readBufferOffset); _result->getBody().ensureNullTerminated(); } else { _result->getBody().appendText(_readBuffer.c_str() + _readBufferOffset, (size_t)_nextChunkedSize); _result->getBody().ensureNullTerminated(); } _readBufferOffset += (size_t)_nextChunkedSize + 2; _state = IN_READ_CHUNKED_HEADER; processChunkedHeader(); } } //////////////////////////////////////////////////////////////////////////////// /// @brief extract an error message from a response //////////////////////////////////////////////////////////////////////////////// std::string SimpleHttpClient::getHttpErrorMessage(SimpleHttpResult const* result, ErrorCode* errorCode) { if (errorCode != nullptr) { *errorCode = TRI_ERROR_NO_ERROR; } arangodb::basics::StringBuffer const& body = result->getBody(); std::string details; try { std::shared_ptr<VPackBuilder> builder = VPackParser::fromJson(body.c_str(), body.length()); VPackSlice slice = builder->slice(); if (slice.isObject()) { VPackSlice msg = slice.get(StaticStrings::ErrorMessage); int errorNum = slice.get(StaticStrings::ErrorNum).getNumericValue<int>(); if (msg.isString() && msg.getStringLength() > 0 && errorNum > 0) { if (errorCode != nullptr) { *errorCode = ErrorCode{errorNum}; } details = ": ArangoError " + std::to_string(errorNum) + ": " + msg.copyString(); } } } catch (...) { // don't rethrow here. we'll respond with an error message anyway } return "got error from server: HTTP " + std::to_string(result->getHttpReturnCode()) + " (" + result->getHttpReturnMessage() + ")" + details; } //////////////////////////////////////////////////////////////////////////////// /// @brief fetch the version from the server //////////////////////////////////////////////////////////////////////////////// std::string SimpleHttpClient::getServerVersion(ErrorCode* errorCode) { if (errorCode != nullptr) { *errorCode = TRI_ERROR_INTERNAL; } std::unique_ptr<SimpleHttpResult> response( request(rest::RequestType::GET, "/_api/version", nullptr, 0)); if (response == nullptr || !response->isComplete()) { return ""; } if (response->getHttpReturnCode() == static_cast<int>(rest::ResponseCode::OK)) { // default value std::string version = "arango"; arangodb::basics::StringBuffer const& body = response->getBody(); try { std::shared_ptr<VPackBuilder> builder = VPackParser::fromJson(body.c_str(), body.length()); VPackSlice slice = builder->slice(); if (slice.isObject()) { VPackSlice server = slice.get("server"); if (server.isString() && server.copyString() == "arango") { // "server" value is a string and its content is "arango" VPackSlice v = slice.get("version"); if (v.isString()) { version = v.copyString(); } } } if (errorCode != nullptr) { *errorCode = TRI_ERROR_NO_ERROR; } return version; } catch (std::exception const& ex) { setErrorMessage(ex.what(), false); return ""; } catch (...) { setErrorMessage("Unable to parse server response", false); return ""; } } if (response->wasHttpError()) { std::string msg = getHttpErrorMessage(response.get(), errorCode); setErrorMessage(msg, false); } _connection->disconnect(); return ""; } } // namespace httpclient } // namespace arangodb
apache-2.0
cannonrobot/Balance_Car_STM32
product/application/balance_car/vl6180x_application.c
1
15967
/** ****************************************************************************** * File Name : multi_dev.c * Date : 12/1/2015 * Description : multi bear program body ****************************************************************************** * * COPYRIGHT(c) 2014 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #include "stm32f4xx_hal.h" I2C_HandleTypeDef hi2c1; #include <string.h> #include <stdlib.h> #include <stdio.h> #include "vl6180x_api.h" #include "x-nucleo-6180xa1.h" #ifdef DEBUG #include "diag/trace.h" #define debug(msg, ...) trace_printf(msg,__VA_ARGS__) #define trace_warn(msg,...) trace_printf("W %s %d" msg "\n", __func__, __LINE__, __VA_ARGS__) #else #define debug(msg, ...) (void)0 #endif #define DigitDisplay_ms 1 /* ms each digit is kept on */ #define PressBPSwicthTime 1000 /* if user keep bp press more that this mean swicth mode else rooll over use c&se in mode */ void WaitMilliSec(int ms); VL6180xDev_t theVL6180xDev; struct MyVL6180Dev_t BoardDevs[4] = { [0]= { .DevID = 0 }, [1]= { .DevID = 1 }, [2]= { .DevID = 2 }, [3]= { .DevID = 3 }, }; VL6180xDev_t theVL6180xDev = &BoardDevs[0]; /** * VL6180x CubeMX F401 multiple device i2c implementation */ #define i2c_bus (&hi2c1) #define def_i2c_time_out 100 int VL6180x_I2CWrite(VL6180xDev_t dev, uint8_t *buff, uint8_t len) { int status; status = HAL_I2C_Master_Transmit(i2c_bus, dev->I2cAddr, buff, len, def_i2c_time_out); if (status) { XNUCLEO6180XA1_I2C1_Init(&hi2c1); } return status? -1 : 0; } int VL6180x_I2CRead(VL6180xDev_t dev, uint8_t *buff, uint8_t len) { int status; status = HAL_I2C_Master_Receive(i2c_bus, dev->I2cAddr, buff, len, def_i2c_time_out); if (status) { XNUCLEO6180XA1_I2C1_Init(&hi2c1); } return status? -1 : 0; } /** * platform and application specific for XNUCLEO6180XA1 Expansion Board */ void XNUCLEO6180XA1_WaitMilliSec(int n) { WaitMilliSec(n); } volatile int IntrFired = 0; void XNUCLEO6180XA1_UserIntHandler(void) { IntrFired++; } /** * DISPLAY public */ /*************** DISPLAY PUBLIC *********************/ const char *DISP_NextString; /*************** DISPLAY PRIVATE *********************/ static char DISP_CurString[10]; static int DISP_Loop = 0; void DISP_ExecLoopBody(void) { if (DISP_NextString != NULL) { strncpy(DISP_CurString, DISP_NextString, sizeof(DISP_CurString) - 1); DISP_CurString[sizeof(DISP_CurString) - 1] = 0; DISP_NextString = NULL; } XNUCLEO6180XA1_DisplayString(DISP_CurString, DigitDisplay_ms); DISP_Loop++; } /** * Nucleo board specific * */ #define BSP_BP_PORT GPIOC #define BSP_BP_PIN GPIO_PIN_13 int BSP_GetPushButton(void) { GPIO_PinState state; state = HAL_GPIO_ReadPin(BSP_BP_PORT, BSP_BP_PIN); return state; } void BSP_Init(){ GPIO_InitTypeDef GPIO_InitStruct; /*Configure push button GPIO pin : PC13 */ __GPIOC_CLK_ENABLE(); GPIO_InitStruct.Pin = GPIO_PIN_13; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); } void SetDisplayString(const char *msg) { DISP_NextString = msg; } void WaitMilliSec(int ms) { HAL_Delay(ms); /* it's milli sec cos we do set systick to 1KHz */ } /** * call in the main loop * when running under debugger it enable doing direct vl6180x reg access * After breaking at entrance * change the the local index/data and cmd variable to do what needed * reg_cmd -1 wr byte -2wr word -3 wr dword * reg_cmd 1 rd byte 2 rd word 3 rd dword * step to last statement before return and read variable to get rd result exit */ void debug_stuff(void) { int reg_cmd = 0; static uint32_t reg_data; static uint16_t reg_index; if (reg_cmd) { switch (reg_cmd) { case -1: VL6180x_WrByte(theVL6180xDev, reg_index, reg_data); debug("Wr B 0x%X = %d", reg_index, (int )reg_data); break; case -2: VL6180x_WrWord(theVL6180xDev, reg_index, reg_data); debug("Wr W 0x%X = %d", reg_index, (int ) reg_data); break; case -3: VL6180x_WrDWord(theVL6180xDev, reg_index, reg_data); debug("WrDW 0x%X = %d", reg_index, (int )reg_data); break; case 1: reg_data = 0; VL6180x_RdByte(theVL6180xDev, reg_index, (uint8_t*) &reg_data); debug("RD B 0x%X = %d", reg_index, (int )reg_data); break; case 2: reg_data = 0; VL6180x_RdWord(theVL6180xDev, reg_index, (uint16_t*) &reg_data); debug("RD W 0x%X = %d", reg_index, (int )reg_data); break; case 3: VL6180x_RdDWord(theVL6180xDev, reg_index, &reg_data); debug("RD DW 0x%X = %d", reg_index, (int )reg_data); break; default: debug("Invalid command %d", reg_cmd); /* nothing to do*/ ; } } } /** * When button is already pressed it Wait for user to release it * if button remain pressed for given time it return true * These is used to detect mode switch by long press on blue Push Button * * As soon as time is elapsed -rb- is displayed to let user know order * the request to switch mode is taken into account * * @return True if button remain pressed more than specified time */ int PusbButton_WaitUnPress(void) { uint32_t TimeStarted = HAL_GetTick(); uint32_t tick; while (!BSP_GetPushButton()) { ; /* debounce */ DISP_ExecLoopBody(); tick = HAL_GetTick(); if (-TimeStarted > PressBPSwicthTime) { SetDisplayString(" rb "); } } return tick - TimeStarted > PressBPSwicthTime; } void DisplayScroll_UserWait( const char * msg) { int char_time=250; int len; int offset=0; int last_wait=0; uint32_t started; len=strlen(msg); started=HAL_GetTick(); while( BSP_GetPushButton() ){ SetDisplayString(msg+offset); DISP_ExecLoopBody(); if(HAL_GetTick()-started > char_time ){ started=HAL_GetTick(); if( offset+4>=len ){ if( last_wait++ < 4 ){ continue; } last_wait=0; offset=0; } else{ offset++; } } } while( !BSP_GetPushButton() ){ DISP_ExecLoopBody(); } } void HandleError(const char *msg) { static char ErrString[256]="Err "; strcat(ErrString,msg); while (1) { DisplayScroll_UserWait(ErrString); } } void SystemClock_Config(void); void DisplayDelay(int ms){ uint32_t started; started= HAL_GetTick(); while(HAL_GetTick()-started < ms ){ DISP_ExecLoopBody(); } } void DisplayUntilButton(const char *msg){ SetDisplayString(msg); DISP_ExecLoopBody(); /* wait for button to be pressed first */ while( BSP_GetPushButton()) { DISP_ExecLoopBody(); } PusbButton_WaitUnPress(); } #define MAX_DEV 4 int status; int i; int n_dev; int PresentDevMask; int nPresentDevs; int PresentDevIds[MAX_DEV]; VL6180x_RangeData_t Range[MAX_DEV]; int nReady; char DisplayStr[5]; void v16180x_Init(void){ /* MCU Configuration----------------------------------------------------------*/ /* initialize VL6180x expansion board gpio and i2c */ // XNUCLEO6180XA1_GPIO_Init(); // XNUCLEO6180XA1_I2C1_Init(&hi2c1); if (!XNUCLEO6180XA1_IsV2()) { HandleError("V2 expansion board is required"); n_dev=1; } else { n_dev = 4; } /* put all devices under reset */ for (i = 0; i < n_dev; i++) { /* put all under reset */ XNUCLEO6180XA1_ResetId(0, i); } /* detect presence and initialize devices i2c address */ /*set device i2c address for dev[i] = 0x52+(i+1)*2 */ PresentDevMask = 0; nPresentDevs = 0; strcpy(DisplayStr,"TLBR"); for (i = n_dev - 1; i >= 0; i--) { int FinalI2cAddr; uint8_t id; /* unreset device that wake up at default i2c addres 0x52 */ XNUCLEO6180XA1_ResetId(1, i); WaitMilliSec(2); /* at least 400usec before to acces device */ BoardDevs[i].I2cAddr = 0x52; /* to detect device presence try to read it's dev id */ status = VL6180x_RdByte(&BoardDevs[i], IDENTIFICATION_MODEL_ID, &id); if (status) { /* these device is not present skip init and clear it's letter on string */ BoardDevs[i].Present = 0; DisplayStr[i]=' '; continue; } /* device present only */ BoardDevs[i].Present = 1; PresentDevMask |= 1 << i; PresentDevIds[nPresentDevs]=i; nPresentDevs++; status = VL6180x_InitData(&BoardDevs[i]); FinalI2cAddr = 0x52 + ((i+1) * 2); if (FinalI2cAddr != 0x52) { status = VL6180x_SetI2CAddress(&BoardDevs[i], FinalI2cAddr); if( status ){ HandleError("VL6180x_SetI2CAddress fail"); } BoardDevs[i].I2cAddr = FinalI2cAddr; } WaitMilliSec(1); status = VL6180x_RdByte(&BoardDevs[i], IDENTIFICATION_MODEL_ID, &id); WaitMilliSec(1); status= VL6180x_Prepare(&BoardDevs[i]); if( status<0 ){ HandleError("VL6180x_Prepare fail"); } /* Disable Dmax computation */ VL6180x_DMaxSetState(&BoardDevs[i], 0); } } int vl6180x_Get_Value(void){ // DisplayStr[4]=0; // DisplayScroll_UserWait(DisplayStr); char buffer[10]; while (1) { VL6180xDev_t dev; dev = BoardDevs + PresentDevIds[0]+PresentDevIds[1]; VL6180x_RangePollMeasurement(theVL6180xDev, &Range[1]); /* dev = BoardDevs + PresentDevIds[0]+PresentDevIds[1]; status = VL6180x_RangeStartSingleShot(dev); dev->Ready=0; nReady=0; do{ DISP_ExecLoopBody(); dev = BoardDevs + PresentDevIds[0]+PresentDevIds[1]; if( !dev->Ready ){ status = VL6180x_RangeGetMeasurementIfReady(dev, &Range[1]); if( status == 0 ){ if(Range[1].errorStatus == DataNotReady) continue; dev->Ready=1; nReady++; } else { HandleError("VL6180x_RangeStartSingleShot fail"); } } } while( nReady<1); */ /* use all measure now */ /* build the display string each */ strcpy(DisplayStr,"----"); if( Range[1].errorStatus == 0 ){ int ch; sprintf(buffer, "r%3d", (int) Range[1].range_mm); // SetDisplayString( buffer ); /* if( Range[1].range_mm < 60 ){ ch= '_'; } else if( Range[1].range_mm < 120){ ch= '='; } else{ ch= '~'; } DisplayStr[BoardDevs[PresentDevIds[1]].DevID]=ch; */ } else{ /* no distance shut off segment */ // DisplayStr[BoardDevs[PresentDevIds[1]].DevID]=' '; sprintf(buffer, "r " ); } SetDisplayString(buffer); } } int vl6180x_application(void) { // DisplayStr[4]=0; // DisplayScroll_UserWait(DisplayStr); while (1) { VL6180xDev_t dev; /* kick off measure on all device */ for( i=0; i<nPresentDevs; i++){ dev = BoardDevs + PresentDevIds[i]; status = VL6180x_RangeStartSingleShot(dev); if( status<0 ){ HandleError("VL6180x_RangeStartSingleShot fail"); } dev->Ready=0; } /* wait for all present device to have a measure */ nReady=0; do{ DISP_ExecLoopBody(); for( i=0; i<nPresentDevs; i++){ dev = BoardDevs + PresentDevIds[i]; if( !dev->Ready ){ status = VL6180x_RangeGetMeasurementIfReady(dev, &Range[i]); if( status == 0 ){ if(Range[i].errorStatus == DataNotReady) continue; /* New measurement ready */ dev->Ready=1; nReady++; } else { HandleError("VL6180x_RangeStartSingleShot fail"); } } } } while( nReady<nPresentDevs); /* use all measure now */ /* build the display string each */ strcpy(DisplayStr,"----"); for( i=0; i<nPresentDevs; i++){ if( Range[i].errorStatus == 0 ){ int ch; if( Range[i].range_mm < 60 ){ ch= '_'; } else if( Range[i].range_mm < 120){ ch= '='; } else{ ch= '~'; } DisplayStr[BoardDevs[PresentDevIds[i]].DevID]=ch; } else{ /* no distance shut off segment */ DisplayStr[BoardDevs[PresentDevIds[i]].DevID]=' '; } } SetDisplayString(DisplayStr); } } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* USER CODE BEGIN 6 */ trace_printf("assert_param() failed: file \"%s\", line %d\n", file, line); exit(1); /* USER CODE END 6 */ } #endif
apache-2.0
dafer45/TBTK
Lib/src/PropertyExtractor/SelfEnergy2.cpp
1
11204
/* Copyright 2018 Kristofer Björnson * * 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 SelfEnergy2.cpp * * @author Kristofer Björnson */ #include "TBTK/PropertyExtractor/SelfEnergy2.h" #include "TBTK/Functions.h" #include "TBTK/Streams.h" #include "TBTK/Timer.h" #include <cmath> using namespace std; namespace TBTK{ namespace PropertyExtractor{ SelfEnergy2::SelfEnergy2(){ } Property::SelfEnergy SelfEnergy2::calculateSelfEnergy( vector<Index> patterns ){ //Flag that will be set to false if a block subindex without the //IDX_ALL specifier is encountered. SelfEnergyBlockInformation information; information.setCalculateSelfEnergyForAllBlocks(true); //Check input and set calculateSelfEnergyForAllBlocks. for(unsigned int n = 0; n < patterns.size(); n++){ const Index &pattern = *(patterns.begin() + n); vector<Index> components = pattern.split(); TBTKAssert( components.size() == 3, "PropertyExtractor::SelfEnergy2::calculateSelfEnergy()", "Invalid pattern '" << pattern.toString() << "'.", "The Index must be a compound Index with five" << " component Indices, but the number of components" << " are " << components.size() << "." ); for(unsigned int c = 2; c < components.size(); c++){ TBTKAssert( components[c].getSize() == components[1].getSize(), "PropertyExtractor::SelfEnergy2::calculateSelfEnergy()", "Currently the last four Indices has to have" " the same number of subindices. The clash" << " appeared between '" << components[1].toString() << "' and '" << components[c].toString() << "'", "Contact the developer if support for more" << " general Indices is needed." ); //TODO //For general Indices to be supported, a more general //way for finding all possible kIndices is required. //The current method relies on knowing the number of //subindices to append after the kIndex. } for(unsigned int c = 0; c < components[0].getSize(); c++){ if(!components[0][c].isWildcard()){ information.setCalculateSelfEnergyForAllBlocks( false ); } } } //Calculate allIndices. const Solver::SelfEnergy2 &solver = getSolver(); IndexTree allIndices; for(unsigned int n = 0; n < patterns.size(); n++){ const Index &pattern = *(patterns.begin() + n); vector<Index> components = pattern.split(); Index kIndexPattern = components[0]; if(information.getCalculateSelfEnergyForAllBlocks()){ for( unsigned int c = 0; c < kIndexPattern.getSize(); c++ ){ kIndexPattern[c] = 0; } } //TODO //This is the restricting assumption. Index kIndexPatternExtended = kIndexPattern; for(unsigned int n = 0; n < components[1].getSize(); n++) kIndexPatternExtended.pushBack(IDX_ALL); IndexTree kIndexTree = generateIndexTree( {kIndexPatternExtended}, solver.getModel().getHoppingAmplitudeSet(), false, false ); for( IndexTree::ConstIterator iteratorK = kIndexTree.cbegin(); iteratorK != kIndexTree.cend(); ++iteratorK ){ Index kIndex = *iteratorK; kIndex = kIndex.getSubIndex( 0, kIndexPattern.getSize()-1 ); Index intraBlockIndices[2]; for(unsigned int n = 0; n < 2; n++){ intraBlockIndices[n] = Index( kIndex, components[n+1] ); } IndexTree intraBlockIndicesTree[2]; for(unsigned int n = 0; n < 2; n++){ intraBlockIndicesTree[n] = generateIndexTree( {intraBlockIndices[n]}, solver.getModel( ).getHoppingAmplitudeSet(), false, false ); } for( IndexTree::ConstIterator iterator0 = intraBlockIndicesTree[0].cbegin(); iterator0 != intraBlockIndicesTree[0].cend(); ++iterator0 ){ Index index0 = *iterator0; index0 = index0.getSubIndex( kIndex.getSize(), index0.getSize()-1 ); for( IndexTree::ConstIterator iterator1 = intraBlockIndicesTree[1].cbegin(); iterator1 != intraBlockIndicesTree[1].cend(); ++iterator1 ){ Index index1 = *iterator1; index1 = index1.getSubIndex( kIndex.getSize(), index1.getSize()-1 ); allIndices.add({ kIndex, index0, index1 }); } } } } allIndices.generateLinearMap(); //Calculate memoryLayout. IndexTree memoryLayout; for(unsigned int n = 0; n < patterns.size(); n++){ const Index &pattern = *(patterns.begin() + n); vector<Index> components = pattern.split(); TBTKAssert( components.size() == 3, "PropertyExtractor::SelfEnergy2::calculateSelfEnergy()", "Invalid pattern '" << pattern.toString() << "'.", "The Index must be a compound Index with 3 component" << " Indices, but the number of components are " << components.size() << "." ); for(unsigned int n = 2; n < components.size(); n++){ TBTKAssert( components[n].getSize() == components[1].getSize(), "PropertyExtractor::SelfEnergy2::calculateSelfEnergy()", "Currently the last four Indices has to have" " the same number of subindices. The clash" << " appeared between '" << components[1].toString() << "' and '" << components[n].toString() << "'", "Contact the developer if support for more" << " general Indices is needed." ); //TODO //For general Indices to be supported, a more general //way for finding all possible kIndices is required. //The current method relies on knowing the number of //subindices to append after the kIndex. } Index kIndexPattern = components[0]; //TODO //This is the restricting assumption. Index kIndexPatternExtended = kIndexPattern; for(unsigned int n = 0; n < components[1].getSize(); n++) kIndexPatternExtended.pushBack(IDX_ALL); IndexTree kIndexTree = generateIndexTree( {kIndexPatternExtended}, solver.getModel().getHoppingAmplitudeSet(), true, false ); for( IndexTree::ConstIterator iteratorK = kIndexTree.cbegin(); iteratorK != kIndexTree.cend(); ++iteratorK ){ //Index that prepends the intraBlockIndices. Index kIndex = *iteratorK; kIndex = kIndex.getSubIndex( 0, kIndexPattern.getSize()-1 ); Index intraBlockIndices[2]; for(unsigned int n = 0; n < 2; n++){ intraBlockIndices[n] = Index( kIndex, components[n+1] ); } IndexTree intraBlockIndicesTree[2]; for(unsigned int n = 0; n < 2; n++){ intraBlockIndicesTree[n] = generateIndexTree( {intraBlockIndices[n]}, solver.getModel( ).getHoppingAmplitudeSet(), true, false ); } for( IndexTree::ConstIterator iterator0 = intraBlockIndicesTree[0].cbegin(); iterator0 != intraBlockIndicesTree[0].cend(); ++iterator0 ){ Index index0 = *iterator0; index0 = index0.getSubIndex( kIndex.getSize(), index0.getSize()-1 ); for( IndexTree::ConstIterator iterator1 = intraBlockIndicesTree[1].cbegin(); iterator1 != intraBlockIndicesTree[1].cend(); ++iterator1 ){ Index index1 = *iterator1; index1 = index1.getSubIndex( kIndex.getSize(), index1.getSize()-1 ); memoryLayout.add({ kIndex, index0, index1 }); } } } } memoryLayout.generateLinearMap(); const Property::InteractionVertex &interactionVertex = solver.getInteractionVertex(); switch(interactionVertex.getEnergyType()){ case Property::EnergyResolvedProperty<complex<double>>::EnergyType::BosonicMatsubara: { int lowerFermionicMatsubaraEnergyIndex = getLowerFermionicMatsubaraEnergyIndex(); int upperFermionicMatsubaraEnergyIndex = getUpperFermionicMatsubaraEnergyIndex(); TBTKAssert( lowerFermionicMatsubaraEnergyIndex <= upperFermionicMatsubaraEnergyIndex, "PropertyExtractor::SelfEnergy2::calculateSelfEnergy()", "'lowerFermionicMatsubaraEnergyIndex=" << lowerFermionicMatsubaraEnergyIndex << "' must be less" << " or equal to 'upperFermionicMatsubaraEnergyIndex=" << lowerFermionicMatsubaraEnergyIndex << "'.", "This should never happen, contact the developer." ); double temperature = solver.getModel().getTemperature(); double kT = UnitHandler::getConstantInNaturalUnits( "k_B" )*temperature; double fundamentalMatsubaraEnergy = M_PI*kT; Property::SelfEnergy selfEnergy( memoryLayout, lowerFermionicMatsubaraEnergyIndex, upperFermionicMatsubaraEnergyIndex, fundamentalMatsubaraEnergy ); calculate( calculateSelfEnergyCallback, allIndices, memoryLayout, selfEnergy, information ); return selfEnergy; } default: TBTKExit( "PropertyExtractor::SelfEnergy2::calculateSelfEnergy()", "The InteractionVertex has to have the energy type" << " Property::EnergyResolvedProperty::EnergyType::BosonicMatsubara.", "" ); } } void SelfEnergy2::calculateSelfEnergyCallback( PropertyExtractor *cb_this, Property::Property &property, const Index &index, int offset, Information &information ){ SelfEnergy2 *propertyExtractor = (SelfEnergy2*)cb_this; Solver::SelfEnergy2 &solver = propertyExtractor->getSolver(); Property::SelfEnergy &selfEnergy = (Property::SelfEnergy&)property; vector<complex<double>> &data = selfEnergy.getDataRW(); switch(selfEnergy.getEnergyType()){ case Property::EnergyResolvedProperty<complex<double>>::EnergyType::FermionicMatsubara: { if( ( (SelfEnergyBlockInformation&)information ).getCalculateSelfEnergyForAllBlocks() ){ vector<Index> components = index.split(); Property::SelfEnergy s = solver.calculateSelfEnergyAllBlocks( {components[1], components[2]}, propertyExtractor->getLowerFermionicMatsubaraEnergyIndex(), propertyExtractor->getUpperFermionicMatsubaraEnergyIndex() ); const IndexTree &containedIndices = s.getIndexDescriptor().getIndexTree(); for( IndexTree::ConstIterator iterator = containedIndices.cbegin(); iterator != containedIndices.cend(); ++iterator ){ for(unsigned int e = 0; e < s.getBlockSize(); e++){ data[selfEnergy.getOffset(*iterator) + e] += s(*iterator, e); } } } else{ vector<complex<double>> se = solver.calculateSelfEnergy( index, selfEnergy.getLowerMatsubaraEnergyIndex(), selfEnergy.getUpperMatsubaraEnergyIndex() ); for(unsigned int e = 0; e < se.size(); e++) data[offset + e] += se[e]; } break; } default: TBTKExit( "PropertyExtractor::SelfEnergy2::calculateSelfEnergy()", "Only calculations for Matsubara energies supported yet.", "" ); } } SelfEnergy2::SelfEnergyBlockInformation::SelfEnergyBlockInformation(){ calculateSelfEnergyForAllBlocks = false; } }; //End of namespace PropertyExtractor }; //End of namespace TBTK
apache-2.0
digideskio/yara
libyara/arena.c
1
23700
/* Copyright (c) 2013. The YARA 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. */ /* This module implements a structure I've called "arena". An arena is a data container composed of a set of pages. The arena grows automatically when needed by adding new pages to hold new data. Arenas can be saved and loaded from files. */ #include <string.h> #include <assert.h> #include <stdlib.h> #include <stdarg.h> #include <stddef.h> #include <time.h> #include <yara/arena.h> #include <yara/mem.h> #include <yara/error.h> #include <yara/limits.h> #pragma pack(push) #pragma pack(1) typedef struct _ARENA_FILE_HEADER { char magic[4]; uint32_t size; uint8_t version; } ARENA_FILE_HEADER; #pragma pack(pop) #define free_space(page) \ ((page)->size - (page)->used) // // _yr_arena_new_page // // Creates a new arena page of a given size // // Args: // size_t size - Size of the page // // Returns: // A pointer to the newly created YR_ARENA_PAGE structure // YR_ARENA_PAGE* _yr_arena_new_page( size_t size) { YR_ARENA_PAGE* new_page; new_page = (YR_ARENA_PAGE*) yr_malloc(sizeof(YR_ARENA_PAGE)); if (new_page == NULL) return NULL; new_page->address = (uint8_t*) yr_malloc(size); if (new_page->address == NULL) { yr_free(new_page); return NULL; } new_page->size = size; new_page->used = 0; new_page->next = NULL; new_page->prev = NULL; new_page->reloc_list_head = NULL; new_page->reloc_list_tail = NULL; return new_page; } // // _yr_arena_page_for_address // // Returns the page within he arena where an address reside. // // Args: // YR_ARENA* arena - Pointer to the arena // void* address - Address to be located // // Returns: // A pointer the corresponding YR_ARENA_PAGE structure where the address // resides. // YR_ARENA_PAGE* _yr_arena_page_for_address( YR_ARENA* arena, void* address) { YR_ARENA_PAGE* page; // Most of the times this function is called with an address within // the current page, let's check the current page first to avoid // looping through the page list. page = arena->current_page; if (page != NULL && (uint8_t*) address >= page->address && (uint8_t*) address < page->address + page->used) return page; page = arena->page_list_head; while (page != NULL) { if ((uint8_t*) address >= page->address && (uint8_t*) address < page->address + page->used) return page; page = page->next; } return NULL; } // // _yr_arena_make_relocatable // // Tells the arena that certain addresses contains a relocatable pointer. // // Args: // YR_ARENA* arena - Pointer the arena // void* address - Base address // va_list offsets - List of offsets relative to base address // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int _yr_arena_make_relocatable( YR_ARENA* arena, void* base, va_list offsets) { YR_RELOC* reloc; YR_ARENA_PAGE* page; size_t offset; size_t base_offset; int result = ERROR_SUCCESS; page = _yr_arena_page_for_address(arena, base); assert(page != NULL); base_offset = (uint8_t*) base - page->address; offset = va_arg(offsets, size_t); while (offset != -1) { assert(base_offset + offset <= page->used - sizeof(int64_t)); reloc = (YR_RELOC*) yr_malloc(sizeof(YR_RELOC)); if (reloc == NULL) return ERROR_INSUFICIENT_MEMORY; reloc->offset = base_offset + offset; reloc->next = NULL; if (page->reloc_list_head == NULL) page->reloc_list_head = reloc; if (page->reloc_list_tail != NULL) page->reloc_list_tail->next = reloc; page->reloc_list_tail = reloc; offset = va_arg(offsets, size_t); } return result; } // // yr_arena_create // // Creates a new arena. // // Args: // size_t initial_size - Initial size // int flags - Flags // YR_ARENA** arena - Address where a pointer to the new arena will be // written to. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_create( size_t initial_size, int flags, YR_ARENA** arena) { YR_ARENA* new_arena; YR_ARENA_PAGE* new_page; *arena = NULL; new_arena = (YR_ARENA*) yr_malloc(sizeof(YR_ARENA)); if (new_arena == NULL) return ERROR_INSUFICIENT_MEMORY; new_page = _yr_arena_new_page(initial_size); if (new_page == NULL) { yr_free(new_arena); return ERROR_INSUFICIENT_MEMORY; } new_arena->page_list_head = new_page; new_arena->current_page = new_page; new_arena->flags = flags | ARENA_FLAGS_COALESCED; *arena = new_arena; return ERROR_SUCCESS; } // // yr_arena_destroy // // Destroys an arena releasing its resource. // // Args: // YR_ARENA* arena - Pointer to the arena. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // void yr_arena_destroy( YR_ARENA* arena) { YR_RELOC* reloc; YR_RELOC* next_reloc; YR_ARENA_PAGE* page; YR_ARENA_PAGE* next_page; page = arena->page_list_head; while(page != NULL) { next_page = page->next; reloc = page->reloc_list_head; while (reloc != NULL) { next_reloc = reloc->next; yr_free(reloc); reloc = next_reloc; } yr_free(page->address); yr_free(page); page = next_page; } yr_free(arena); } // // yr_arena_base_address // // Returns the base address for the arena. // // Args: // YR_ARENA* arena - Pointer to the arena. // // Returns: // A pointer // void* yr_arena_base_address( YR_ARENA* arena) { return arena->page_list_head->address; } // // yr_arena_next_address // // Given an address and an offset, returns the address where // address + offset resides. The arena is a collection of non-contigous // regions of memory (pages), if address is pointing at the end of a page, // address + offset could cross the page boundary and point at somewhere // within the next page, this function handles these situations. It works // also with negative offsets. // // Args: // YR_ARENA* arena - Pointer to the arena. // void* address - Base address. // int offset - Offset. // // Returns: // A pointer // void* yr_arena_next_address( YR_ARENA* arena, void* address, int offset) { YR_ARENA_PAGE* page; page = _yr_arena_page_for_address(arena, address); assert(page != NULL); if ((uint8_t*) address + offset >= page->address && (uint8_t*) address + offset < page->address + page->used) { return (uint8_t*) address + offset; } if (offset > 0) { offset -= page->address + page->used - (uint8_t*) address; page = page->next; while (page != NULL) { if (offset < page->used) return page->address + offset; offset -= page->used; page = page->next; } } else { offset += page->used; page = page->prev; while (page != NULL) { if (offset < page->used) return page->address + page->used + offset; offset += page->used; page = page->prev; } } return NULL; } // // yr_arena_coalesce // // Coalesce the arena into a single page. This is a required step before // saving the arena to a file. // // Args: // YR_ARENA* arena - Pointer to the arena. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_coalesce( YR_ARENA* arena) { YR_ARENA_PAGE* page; YR_ARENA_PAGE* big_page; YR_ARENA_PAGE* next_page; YR_RELOC* reloc; uint8_t** reloc_address; uint8_t* reloc_target; int total_size = 0; page = arena->page_list_head; while(page != NULL) { total_size += page->used; page = page->next; } // Create a new page that will contain the entire arena. big_page = _yr_arena_new_page(total_size); if (big_page == NULL) return ERROR_INSUFICIENT_MEMORY; // Copy data from current pages to the big page and adjust relocs. page = arena->page_list_head; while (page != NULL) { page->new_address = big_page->address + big_page->used; memcpy(page->new_address, page->address, page->used); reloc = page->reloc_list_head; while(reloc != NULL) { reloc->offset += big_page->used; reloc = reloc->next; } if (big_page->reloc_list_head == NULL) big_page->reloc_list_head = page->reloc_list_head; if (big_page->reloc_list_tail != NULL) big_page->reloc_list_tail->next = page->reloc_list_head; if (page->reloc_list_tail != NULL) big_page->reloc_list_tail = page->reloc_list_tail; big_page->used += page->used; page = page->next; } // Relocate pointers. reloc = big_page->reloc_list_head; while (reloc != NULL) { reloc_address = (uint8_t**) (big_page->address + reloc->offset); reloc_target = *reloc_address; if (reloc_target != NULL) { page = _yr_arena_page_for_address(arena, reloc_target); assert(page != NULL); *reloc_address = page->new_address + (reloc_target - page->address); } reloc = reloc->next; } // Release current pages. page = arena->page_list_head; while(page != NULL) { next_page = page->next; yr_free(page->address); yr_free(page); page = next_page; } arena->page_list_head = big_page; arena->current_page = big_page; arena->flags |= ARENA_FLAGS_COALESCED; return ERROR_SUCCESS; } // // yr_arena_reserve_memory // // Ensures that the arena have enough contiguous memory for future allocations. // if the available space in the current page is lower than "size", a new page // is allocated. // // Args: // YR_ARENA* arena - Pointer to the arena. // size_t size - Size of the region to be reserved. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_reserve_memory( YR_ARENA* arena, size_t size) { YR_ARENA_PAGE* new_page; size_t new_page_size; uint8_t* new_page_address; if (size > free_space(arena->current_page)) { if (arena->flags & ARENA_FLAGS_FIXED_SIZE) return ERROR_INSUFICIENT_MEMORY; // Requested space is bigger than current page's empty space, // lets calculate the size for a new page. new_page_size = arena->current_page->size * 2; while (new_page_size < size) new_page_size *= 2; if (arena->current_page->used == 0) { // Current page is not used at all, it can be reallocated. new_page_address = (uint8_t*) yr_realloc( arena->current_page->address, new_page_size); if (new_page_address == NULL) return ERROR_INSUFICIENT_MEMORY; arena->current_page->address = new_page_address; arena->current_page->size = new_page_size; } else { new_page = _yr_arena_new_page(new_page_size); if (new_page == NULL) return ERROR_INSUFICIENT_MEMORY; new_page->prev = arena->current_page; arena->current_page->next = new_page; arena->current_page = new_page; arena->flags &= ~ARENA_FLAGS_COALESCED; } } return ERROR_SUCCESS; } // // yr_arena_allocate_memory // // Allocates memory within the arena. // // Args: // YR_ARENA* arena - Pointer to the arena. // size_t size - Size of the region to be allocated. // void** allocated_memory - Address of a pointer to newly allocated // region. // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_allocate_memory( YR_ARENA* arena, size_t size, void** allocated_memory) { FAIL_ON_ERROR(yr_arena_reserve_memory(arena, size)); *allocated_memory = arena->current_page->address + \ arena->current_page->used; arena->current_page->used += size; return ERROR_SUCCESS; } // // yr_arena_allocate_struct // // Allocates a structure within the arena. This function is similar to // yr_arena_allocate_memory but additionaly receives a variable-length // list of offsets within the structure where pointers reside. This allows // the arena to keep track of pointers that must be adjusted when memory // is relocated. This is an example on how to invoke this function: // // yr_arena_allocate_struct( // arena, // sizeof(MY_STRUCTURE), // (void**) &my_structure_ptr, // offsetof(MY_STRUCTURE, field_1), // offsetof(MY_STRUCTURE, field_2), // .. // offsetof(MY_STRUCTURE, field_N), // EOL); // // Args: // YR_ARENA* arena - Pointer to the arena. // size_t size - Size of the region to be allocated. // void** allocated_memory - Address of a pointer to newly allocated // region. // ... - Variable number of offsets relative to the // beginning of the struct. Offsets are of type // size_t. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_allocate_struct( YR_ARENA* arena, size_t size, void** allocated_memory, ...) { int result; va_list offsets; va_start(offsets, allocated_memory); result = yr_arena_allocate_memory(arena, size, allocated_memory); if (result == ERROR_SUCCESS) result = _yr_arena_make_relocatable(arena, *allocated_memory, offsets); va_end(offsets); memset(*allocated_memory, 0, size); return result; } // // yr_arena_make_relocatable // // Tells the arena that certain addresses contains a relocatable pointer. // // Args: // YR_ARENA* arena - Pointer to the arena. // void* base - Address within the arena. // ... - Variable number of size_t arguments with offsets // relative to base. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_make_relocatable( YR_ARENA* arena, void* base, ...) { int result; va_list offsets; va_start(offsets, base); result = _yr_arena_make_relocatable(arena, base, offsets); va_end(offsets); return result; } // // yr_arena_write_data // // Writes data to the arena. // // Args: // YR_ARENA* arena - Pointer to the arena. // void* data - Pointer to data to be written. // size_t size - Size of data. // void** written_data - Address where a pointer to the written data will // be returned. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_write_data( YR_ARENA* arena, void* data, size_t size, void** written_data) { void* output; int result; if (size > free_space(arena->current_page)) { result = yr_arena_allocate_memory(arena, size, &output); if (result != ERROR_SUCCESS) return result; } else { output = arena->current_page->address + arena->current_page->used; arena->current_page->used += size; } memcpy(output, data, size); if (written_data != NULL) *written_data = output; return ERROR_SUCCESS; } // // yr_arena_write_string // // Writes string to the arena. // // Args: // YR_ARENA* arena - Pointer to the arena. // const char* string - Pointer to string to be written. // char** written_string - Address where a pointer to the written data will // be returned. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_write_string( YR_ARENA* arena, const char* string, char** written_string) { return yr_arena_write_data( arena, (void*) string, strlen(string) + 1, (void**) written_string); } // // yr_arena_append // // Appends source_arena to target_arena. This operation destroys source_arena, // after returning any pointer to source_arena is no longer valid. // // Args: // YR_ARENA* target_arena - Pointer to target the arena. // YR_ARENA* source_arena - Pointer to source arena. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_append( YR_ARENA* target_arena, YR_ARENA* source_arena) { target_arena->current_page->next = source_arena->page_list_head; source_arena->page_list_head->prev = target_arena->current_page; target_arena->current_page = source_arena->current_page; yr_free(source_arena); return ERROR_SUCCESS; } // // yr_arena_duplicate // // Duplicates the arena, making an exact copy. This function requires the // arena to be coalesced. // // Args: // YR_ARENA* arena - Pointer to the arena. // YR_ARENA** duplicated - Address where a pointer to the new arena arena // will be returned. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_duplicate( YR_ARENA* arena, YR_ARENA** duplicated) { YR_RELOC* reloc; YR_RELOC* new_reloc; YR_ARENA_PAGE* page; YR_ARENA_PAGE* new_page; YR_ARENA* new_arena; uint8_t** reloc_address; uint8_t* reloc_target; // Only coalesced arenas can be duplicated. assert(arena->flags & ARENA_FLAGS_COALESCED); new_arena = (YR_ARENA*) yr_malloc(sizeof(YR_ARENA)); if (new_arena == NULL) return ERROR_INSUFICIENT_MEMORY; page = arena->page_list_head; new_page = _yr_arena_new_page(page->size); if (new_page == NULL) { yr_free(new_arena); return ERROR_INSUFICIENT_MEMORY; } memcpy(new_page->address, page->address, page->size); new_page->used = page->used; reloc = page->reloc_list_head; while (reloc != NULL) { new_reloc = (YR_RELOC*) yr_malloc(sizeof(YR_RELOC)); if (new_reloc == NULL) return ERROR_INSUFICIENT_MEMORY; new_reloc->offset = reloc->offset; new_reloc->next = NULL; if (new_page->reloc_list_head == NULL) new_page->reloc_list_head = new_reloc; if (new_page->reloc_list_tail != NULL) new_page->reloc_list_tail->next = new_reloc; new_page->reloc_list_tail = new_reloc; reloc_address = (uint8_t**) (new_page->address + new_reloc->offset); reloc_target = *reloc_address; if (reloc_target != NULL) { assert(reloc_target >= page->address); assert(reloc_target < page->address + page->used); *reloc_address = reloc_target - \ page->address + \ new_page->address; } reloc = reloc->next; } new_arena->page_list_head = new_page; new_arena->current_page = new_page; new_arena->flags |= ARENA_FLAGS_COALESCED; *duplicated = new_arena; return ERROR_SUCCESS; } // // yr_arena_save // // Saves the arena into a file. If the file exists its overwritten. This // function requires the arena to be coalesced. // // Args: // YR_ARENA* arena - Pointer to the arena. // const char* filename - File path. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_save( YR_ARENA* arena, const char* filename) { YR_ARENA_PAGE* page; YR_RELOC* reloc; FILE* fh; ARENA_FILE_HEADER header; int32_t end_marker = -1; uint8_t** reloc_address; uint8_t* reloc_target; // Only coalesced arenas can be saved. assert(arena->flags & ARENA_FLAGS_COALESCED); fh = fopen(filename, "wb"); if (fh == NULL) return ERROR_COULD_NOT_OPEN_FILE; page = arena->page_list_head; reloc = page->reloc_list_head; // Convert pointers to offsets before saving. while (reloc != NULL) { reloc_address = (uint8_t**) (page->address + reloc->offset); reloc_target = *reloc_address; if (reloc_target != NULL) { assert(reloc_target >= page->address); assert(reloc_target < page->address + page->used); *reloc_address = (uint8_t*) (*reloc_address - page->address); } else { *reloc_address = (uint8_t*) (size_t) 0xFFFABADA; } reloc = reloc->next; } header.magic[0] = 'Y'; header.magic[1] = 'A'; header.magic[2] = 'R'; header.magic[3] = 'A'; header.size = page->size; header.version = ARENA_FILE_VERSION; fwrite(&header, sizeof(header), 1, fh); fwrite(page->address, sizeof(uint8_t), header.size, fh); reloc = page->reloc_list_head; // Convert offsets back to pointers. while (reloc != NULL) { fwrite(&reloc->offset, sizeof(reloc->offset), 1, fh); reloc_address = (uint8_t**) (page->address + reloc->offset); reloc_target = *reloc_address; if (reloc_target != (void*) (size_t) 0xFFFABADA) *reloc_address += (size_t) page->address; else *reloc_address = 0; reloc = reloc->next; } fwrite(&end_marker, sizeof(end_marker), 1, fh); fclose(fh); return ERROR_SUCCESS; } // // yr_arena_load // // Loads an arena from a file. // // Args: // const char* filename - File path. // YR_ARENA** - Address where a pointer to the loaded arena // will be returned. // // Returns: // ERROR_SUCCESS if succeed or the corresponding error code otherwise. // int yr_arena_load( const char* filename, YR_ARENA** arena) { FILE* fh; YR_ARENA_PAGE* page; YR_ARENA* new_arena; ARENA_FILE_HEADER header; int32_t reloc_offset; uint8_t** reloc_address; uint8_t* reloc_target; long file_size; int result; fh = fopen(filename, "rb"); if (fh == NULL) return ERROR_COULD_NOT_OPEN_FILE; fseek(fh, 0, SEEK_END); file_size = ftell(fh); fseek(fh, 0, SEEK_SET); if (fread(&header, sizeof(header), 1, fh) != 1) { fclose(fh); return ERROR_INVALID_FILE; } if (header.magic[0] != 'Y' || header.magic[1] != 'A' || header.magic[2] != 'R' || header.magic[3] != 'A') { fclose(fh); return ERROR_INVALID_FILE; } if (header.size >= file_size) { fclose(fh); return ERROR_CORRUPT_FILE; } if (header.version > ARENA_FILE_VERSION) { fclose(fh); return ERROR_UNSUPPORTED_FILE_VERSION; } result = yr_arena_create(header.size, 0, &new_arena); if (result != ERROR_SUCCESS) { fclose(fh); return result; } page = new_arena->current_page; if (fread(page->address, header.size, 1, fh) != 1) { fclose(fh); yr_arena_destroy(new_arena); return ERROR_CORRUPT_FILE; } page->used = header.size; if (fread(&reloc_offset, sizeof(reloc_offset), 1, fh) != 1) { fclose(fh); yr_arena_destroy(new_arena); return ERROR_CORRUPT_FILE; } while (reloc_offset != -1) { yr_arena_make_relocatable(new_arena, page->address, reloc_offset, EOL); reloc_address = (uint8_t**) (page->address + reloc_offset); reloc_target = *reloc_address; if (reloc_target != (uint8_t*) (size_t) 0xFFFABADA) *reloc_address += (size_t) page->address; else *reloc_address = 0; if (fread(&reloc_offset, sizeof(reloc_offset), 1, fh) != 1) { fclose(fh); yr_arena_destroy(new_arena); return ERROR_CORRUPT_FILE; } } fclose(fh); *arena = new_arena; return ERROR_SUCCESS; }
apache-2.0
DFC-OpenSource/ox-ctrl
core/ox-mq-output.c
1
6485
/* OX: Open-Channel NVM Express SSD Controller * * - Multi-Queue Support for Parallel I/O - Output data and statistics * * Copyright 2018 IT University of Copenhagen * * Written by Ivan Luiz Picoli <ivpi@itu.dk> * * 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 <sys/queue.h> #include <pthread.h> #include <string.h> #include <stdint.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <ox-mq.h> #include <libox.h> #define OXMQ_OUTPUT_BUF_SZ 8192 struct oxmq_output *ox_mq_output_init (uint64_t id, const char *name, uint32_t nodes) { FILE *fp; char filename[80]; struct stat st = {0}; struct oxmq_output *output; uint32_t node_i; if (strlen(name) > 40) return NULL; output = ox_malloc (sizeof (struct oxmq_output), OX_MEM_OX_MQ); if (!output) return NULL; output->id = id; output->nodes = nodes; strcpy (output->name, name); if (stat("output", &st) == -1) mkdir("output", S_IRWXO); sprintf (filename, "output/%lu_%s.csv", id, name); fp = fopen(filename, "a"); if (!fp) goto FREE_OUT; fprintf (fp, "node_sequence;node_id;lba;channel;lun;block;page;" "plane;sector;start;end;latency;type;is_failed;read_memcmp;bytes\n"); fclose(fp); output->node_seq = ox_calloc (sizeof(uint64_t), nodes, OX_MEM_OX_MQ); if (!output->node_seq) goto FREE_OUT; output->queues = ox_malloc (sizeof (struct oxmq_output_tq) * nodes, OX_MEM_OX_MQ); if (!output->queues) goto FREE_NODE; for (node_i = 0; node_i < nodes; node_i++) { output->queues[node_i].rows = ox_malloc (sizeof (struct oxmq_output_row) * OXMQ_OUTPUT_BUF_SZ, OX_MEM_OX_MQ); if (!output->queues[node_i].rows) goto FREE_QUEUE; output->queues[node_i].row_off = 0; TAILQ_INIT (&output->queues[node_i].out_head); } if (pthread_mutex_init (&output->file_mutex, 0)) goto FREE_QUEUE; output->sequence = 0; return output; FREE_QUEUE: while (node_i) { node_i--; ox_free (output->queues[node_i].rows, OX_MEM_OX_MQ); } ox_free (output->queues, OX_MEM_OX_MQ); FREE_NODE: ox_free (output->node_seq, OX_MEM_OX_MQ); FREE_OUT: ox_free (output, OX_MEM_OX_MQ); return NULL; } void ox_mq_output_exit (struct oxmq_output *output) { uint32_t node_i; pthread_mutex_destroy (&output->file_mutex); for (node_i = 0; node_i < output->nodes; node_i++) ox_free (output->queues[node_i].rows, OX_MEM_OX_MQ); ox_free (output->queues, OX_MEM_OX_MQ); ox_free (output->node_seq, OX_MEM_OX_MQ); ox_free (output, OX_MEM_OX_MQ); } static int ox_mq_output_flush_node (struct oxmq_output *output, int node_i) { struct oxmq_output_row *row; char tstart[21], tend[21]; uint32_t row_i; FILE *fp; char filename[80]; sprintf (filename, "output/%lu_%s.csv", output->id, output->name); fp = fopen(filename, "a"); if (!fp) { printf (" [ox-mq: ERROR. File not opened.]\n"); return -1; } for (row_i = 0; row_i < output->queues[node_i].row_off; row_i++) { row = &output->queues[node_i].rows[row_i]; if (!row) { fclose(fp); return -1; } row->ulat = (row->tend - row->tstart) / 1000; sprintf (tstart, "%lu", row->tstart); sprintf (tend, "%lu", row->tend); memmove (tstart, tstart+4, 17); memmove (tend, tend+4, 17); if(fprintf (fp, "%lu;" "%d;" "%lu;" "%d;" "%d;" "%d;" "%d;" "%d;" "%d;" "%s;" "%s;" "%lu;" "%c;" "%d;" "%d;" "%d\n", row->node_seq, row->node_id, row->lba, row->ch, row->lun, row->blk, row->pg, row->pl, row->sec, tstart, tend, row->ulat, row->type, row->failed, row->datacmp, row->size) < 0) { printf (" [ox-mq: ERROR. Not possible flushing results.]\n"); fclose(fp); return -1; } } fclose(fp); return 0; } void ox_mq_output_flush (struct oxmq_output *output) { uint32_t node_i; pthread_mutex_lock (&output->file_mutex); for (node_i = 0; node_i < output->nodes; node_i++) ox_mq_output_flush_node (output, node_i); pthread_mutex_unlock (&output->file_mutex); } struct oxmq_output_row *ox_mq_output_new (struct oxmq_output *output, int node_id) { struct oxmq_output_row *row; if (output->queues[node_id].row_off >= OXMQ_OUTPUT_BUF_SZ) { pthread_mutex_lock (&output->file_mutex); if (!output->queues[node_id].row_off) { pthread_mutex_unlock (&output->file_mutex); goto GET; } ox_mq_output_flush_node (output, node_id); memset (output->queues[node_id].rows, 0x0, sizeof (struct oxmq_output_row) * OXMQ_OUTPUT_BUF_SZ); output->queues[node_id].row_off = 0; pthread_mutex_unlock (&output->file_mutex); } GET: row = &output->queues[node_id].rows[output->queues[node_id].row_off]; output->queues[node_id].row_off++; row->node_id = node_id; row->node_seq = output->node_seq[node_id]; output->node_seq[node_id]++; return row; }
apache-2.0
dselsam/lean
src/library/vm/vm_json.cpp
1
3240
/* Copyright (c) E.W.Ayers 2020. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers */ #include "frontends/lean/json.h" #include "library/vm/vm.h" #include "library/vm/vm_string.h" #include "library/vm/vm_int.h" #include "library/vm/vm_list.h" #include "library/vm/vm_float.h" #include "library/vm/vm_option.h" #include <string> namespace lean { enum json_idx { vstring = 0, vint = 1, vfloat = 2, vbool = 3, vnull = 4, vobject = 5, varray = 6, }; json to_json(vm_obj const & o) { switch (cidx(o)) { case json_idx::vstring: { std::string s = to_string(cfield(o, 0)); return json(s); } case json_idx::vint: { int i = to_int(cfield(o, 0)); return json(i); } case json_idx::vfloat: { float f = to_float(cfield(o, 0)); return json(f); } case json_idx::vbool: { bool b = to_bool(cfield(o, 0)); return json(b); } case json_idx::vnull: { return json(nullptr); } case json_idx::vobject: { json j; vm_obj l = cfield(o, 0); while (!is_simple(l)) { vm_obj h = head(l); std::string key = to_string(cfield(h, 0)); json value = to_json(cfield(h, 1)); j[key] = value; l = tail(l); } return j; } case json_idx::varray: { json j = json::array(); vm_obj l = cfield(o, 0); while (!is_simple(l)) { j.push_back(to_json(head(l))); l = tail(l); } return j; } default: { lean_unreachable(); break; }} } vm_obj to_obj(json const & j) { if (j.is_null()) { return mk_vm_simple(json_idx::vnull); } else if (j.is_boolean()) { return mk_vm_constructor(json_idx::vbool, mk_vm_bool(j)); } else if (j.is_number_float()) { float f = j; return mk_vm_constructor(json_idx::vfloat, to_obj(f)); } else if (j.is_number()) { int i = j; return mk_vm_constructor(json_idx::vint, mk_vm_nat(i)); } else if (j.is_string()) { std::string s = j; return mk_vm_constructor(json_idx::vstring, to_obj(s)); } else if (j.is_array()) { vm_obj o = mk_vm_nil(); for (auto i = j.crbegin(); i != j.crend(); i++) { o = mk_vm_cons(to_obj(*i), o); } return mk_vm_constructor(json_idx::varray, o); } else if (j.is_object()) { vm_obj o = mk_vm_nil(); for (auto el = j.crbegin(); el != j.crend(); el++) { o = mk_vm_cons(mk_vm_pair( to_obj(el.key()), to_obj(el.value())), o); } return mk_vm_constructor(json_idx::vobject, o); } else { lean_unreachable(); } } vm_obj parse(vm_obj const & s) { try { json j = json::parse(to_string(s)); return mk_vm_some(to_obj(j)); } catch(...) { return mk_vm_none(); } } vm_obj unparse(vm_obj const & o) { return to_obj(to_json(o).dump()); } void initialize_vm_json() { DECLARE_VM_BUILTIN(name({"json", "parse"}), parse); DECLARE_VM_BUILTIN(name({"json", "unparse"}), unparse); } void finalize_vm_json() {} }
apache-2.0
GPUOpen-Drivers/llvm
utils/TableGen/SubtargetEmitter.cpp
1
72324
//===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This tablegen backend emits subtarget enumerations. // //===----------------------------------------------------------------------===// #include "CodeGenTarget.h" #include "CodeGenSchedule.h" #include "PredicateExpander.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/MC/MCInstrItineraries.h" #include "llvm/MC/MCSchedule.h" #include "llvm/MC/SubtargetFeature.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" #include <algorithm> #include <cassert> #include <cstdint> #include <iterator> #include <map> #include <string> #include <vector> using namespace llvm; #define DEBUG_TYPE "subtarget-emitter" namespace { class SubtargetEmitter { // Each processor has a SchedClassDesc table with an entry for each SchedClass. // The SchedClassDesc table indexes into a global write resource table, write // latency table, and read advance table. struct SchedClassTables { std::vector<std::vector<MCSchedClassDesc>> ProcSchedClasses; std::vector<MCWriteProcResEntry> WriteProcResources; std::vector<MCWriteLatencyEntry> WriteLatencies; std::vector<std::string> WriterNames; std::vector<MCReadAdvanceEntry> ReadAdvanceEntries; // Reserve an invalid entry at index 0 SchedClassTables() { ProcSchedClasses.resize(1); WriteProcResources.resize(1); WriteLatencies.resize(1); WriterNames.push_back("InvalidWrite"); ReadAdvanceEntries.resize(1); } }; struct LessWriteProcResources { bool operator()(const MCWriteProcResEntry &LHS, const MCWriteProcResEntry &RHS) { return LHS.ProcResourceIdx < RHS.ProcResourceIdx; } }; const CodeGenTarget &TGT; RecordKeeper &Records; CodeGenSchedModels &SchedModels; std::string Target; void Enumeration(raw_ostream &OS, DenseMap<Record *, unsigned> &FeatureMap); unsigned FeatureKeyValues(raw_ostream &OS, const DenseMap<Record *, unsigned> &FeatureMap); unsigned CPUKeyValues(raw_ostream &OS, const DenseMap<Record *, unsigned> &FeatureMap); void FormItineraryStageString(const std::string &Names, Record *ItinData, std::string &ItinString, unsigned &NStages); void FormItineraryOperandCycleString(Record *ItinData, std::string &ItinString, unsigned &NOperandCycles); void FormItineraryBypassString(const std::string &Names, Record *ItinData, std::string &ItinString, unsigned NOperandCycles); void EmitStageAndOperandCycleData(raw_ostream &OS, std::vector<std::vector<InstrItinerary>> &ProcItinLists); void EmitItineraries(raw_ostream &OS, std::vector<std::vector<InstrItinerary>> &ProcItinLists); unsigned EmitRegisterFileTables(const CodeGenProcModel &ProcModel, raw_ostream &OS); void EmitLoadStoreQueueInfo(const CodeGenProcModel &ProcModel, raw_ostream &OS); void EmitExtraProcessorInfo(const CodeGenProcModel &ProcModel, raw_ostream &OS); void EmitProcessorProp(raw_ostream &OS, const Record *R, StringRef Name, char Separator); void EmitProcessorResourceSubUnits(const CodeGenProcModel &ProcModel, raw_ostream &OS); void EmitProcessorResources(const CodeGenProcModel &ProcModel, raw_ostream &OS); Record *FindWriteResources(const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel); Record *FindReadAdvance(const CodeGenSchedRW &SchedRead, const CodeGenProcModel &ProcModel); void ExpandProcResources(RecVec &PRVec, std::vector<int64_t> &Cycles, const CodeGenProcModel &ProcModel); void GenSchedClassTables(const CodeGenProcModel &ProcModel, SchedClassTables &SchedTables); void EmitSchedClassTables(SchedClassTables &SchedTables, raw_ostream &OS); void EmitProcessorModels(raw_ostream &OS); void EmitProcessorLookup(raw_ostream &OS); void EmitSchedModelHelpers(const std::string &ClassName, raw_ostream &OS); void emitSchedModelHelpersImpl(raw_ostream &OS, bool OnlyExpandMCInstPredicates = false); void emitGenMCSubtargetInfo(raw_ostream &OS); void EmitMCInstrAnalysisPredicateFunctions(raw_ostream &OS); void EmitSchedModel(raw_ostream &OS); void EmitHwModeCheck(const std::string &ClassName, raw_ostream &OS); void ParseFeaturesFunction(raw_ostream &OS, unsigned NumFeatures, unsigned NumProcs); public: SubtargetEmitter(RecordKeeper &R, CodeGenTarget &TGT) : TGT(TGT), Records(R), SchedModels(TGT.getSchedModels()), Target(TGT.getName()) {} void run(raw_ostream &o); }; } // end anonymous namespace // // Enumeration - Emit the specified class as an enumeration. // void SubtargetEmitter::Enumeration(raw_ostream &OS, DenseMap<Record *, unsigned> &FeatureMap) { // Get all records of class and sort std::vector<Record*> DefList = Records.getAllDerivedDefinitions("SubtargetFeature"); llvm::sort(DefList, LessRecord()); unsigned N = DefList.size(); if (N == 0) return; if (N + 1 > MAX_SUBTARGET_FEATURES) PrintFatalError("Too many subtarget features! Bump MAX_SUBTARGET_FEATURES."); OS << "namespace " << Target << " {\n"; // Open enumeration. OS << "enum {\n"; // For each record for (unsigned i = 0; i < N; ++i) { // Next record Record *Def = DefList[i]; // Get and emit name OS << " " << Def->getName() << " = " << i << ",\n"; // Save the index for this feature. FeatureMap[Def] = i; } OS << " " << "NumSubtargetFeatures = " << N << "\n"; // Close enumeration and namespace OS << "};\n"; OS << "} // end namespace " << Target << "\n"; } static void printFeatureMask(raw_ostream &OS, RecVec &FeatureList, const DenseMap<Record *, unsigned> &FeatureMap) { std::array<uint64_t, MAX_SUBTARGET_WORDS> Mask = {}; for (unsigned j = 0, M = FeatureList.size(); j < M; ++j) { unsigned Bit = FeatureMap.lookup(FeatureList[j]); Mask[Bit / 64] |= 1ULL << (Bit % 64); } OS << "{ { { "; for (unsigned i = 0; i != Mask.size(); ++i) { OS << "0x"; OS.write_hex(Mask[i]); OS << "ULL, "; } OS << "} } }"; } // // FeatureKeyValues - Emit data of all the subtarget features. Used by the // command line. // unsigned SubtargetEmitter::FeatureKeyValues( raw_ostream &OS, const DenseMap<Record *, unsigned> &FeatureMap) { // Gather and sort all the features std::vector<Record*> FeatureList = Records.getAllDerivedDefinitions("SubtargetFeature"); if (FeatureList.empty()) return 0; llvm::sort(FeatureList, LessRecordFieldName()); // Begin feature table OS << "// Sorted (by key) array of values for CPU features.\n" << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[] = {\n"; // For each feature unsigned NumFeatures = 0; for (unsigned i = 0, N = FeatureList.size(); i < N; ++i) { // Next feature Record *Feature = FeatureList[i]; StringRef Name = Feature->getName(); StringRef CommandLineName = Feature->getValueAsString("Name"); StringRef Desc = Feature->getValueAsString("Desc"); if (CommandLineName.empty()) continue; // Emit as { "feature", "description", { featureEnum }, { i1 , i2 , ... , in } } OS << " { " << "\"" << CommandLineName << "\", " << "\"" << Desc << "\", " << Target << "::" << Name << ", "; RecVec ImpliesList = Feature->getValueAsListOfDefs("Implies"); printFeatureMask(OS, ImpliesList, FeatureMap); OS << " },\n"; ++NumFeatures; } // End feature table OS << "};\n"; return NumFeatures; } // // CPUKeyValues - Emit data of all the subtarget processors. Used by command // line. // unsigned SubtargetEmitter::CPUKeyValues(raw_ostream &OS, const DenseMap<Record *, unsigned> &FeatureMap) { // Gather and sort processor information std::vector<Record*> ProcessorList = Records.getAllDerivedDefinitions("Processor"); llvm::sort(ProcessorList, LessRecordFieldName()); // Begin processor table OS << "// Sorted (by key) array of values for CPU subtype.\n" << "extern const llvm::SubtargetSubTypeKV " << Target << "SubTypeKV[] = {\n"; // For each processor for (Record *Processor : ProcessorList) { StringRef Name = Processor->getValueAsString("Name"); RecVec FeatureList = Processor->getValueAsListOfDefs("Features"); // Emit as { "cpu", "description", 0, { f1 , f2 , ... fn } }, OS << " { " << "\"" << Name << "\", "; printFeatureMask(OS, FeatureList, FeatureMap); // Emit the scheduler model pointer. const std::string &ProcModelName = SchedModels.getModelForProc(Processor).ModelName; OS << ", &" << ProcModelName << " },\n"; } // End processor table OS << "};\n"; return ProcessorList.size(); } // // FormItineraryStageString - Compose a string containing the stage // data initialization for the specified itinerary. N is the number // of stages. // void SubtargetEmitter::FormItineraryStageString(const std::string &Name, Record *ItinData, std::string &ItinString, unsigned &NStages) { // Get states list RecVec StageList = ItinData->getValueAsListOfDefs("Stages"); // For each stage unsigned N = NStages = StageList.size(); for (unsigned i = 0; i < N;) { // Next stage const Record *Stage = StageList[i]; // Form string as ,{ cycles, u1 | u2 | ... | un, timeinc, kind } int Cycles = Stage->getValueAsInt("Cycles"); ItinString += " { " + itostr(Cycles) + ", "; // Get unit list RecVec UnitList = Stage->getValueAsListOfDefs("Units"); // For each unit for (unsigned j = 0, M = UnitList.size(); j < M;) { // Add name and bitwise or ItinString += Name + "FU::" + UnitList[j]->getName().str(); if (++j < M) ItinString += " | "; } int TimeInc = Stage->getValueAsInt("TimeInc"); ItinString += ", " + itostr(TimeInc); int Kind = Stage->getValueAsInt("Kind"); ItinString += ", (llvm::InstrStage::ReservationKinds)" + itostr(Kind); // Close off stage ItinString += " }"; if (++i < N) ItinString += ", "; } } // // FormItineraryOperandCycleString - Compose a string containing the // operand cycle initialization for the specified itinerary. N is the // number of operands that has cycles specified. // void SubtargetEmitter::FormItineraryOperandCycleString(Record *ItinData, std::string &ItinString, unsigned &NOperandCycles) { // Get operand cycle list std::vector<int64_t> OperandCycleList = ItinData->getValueAsListOfInts("OperandCycles"); // For each operand cycle unsigned N = NOperandCycles = OperandCycleList.size(); for (unsigned i = 0; i < N;) { // Next operand cycle const int OCycle = OperandCycleList[i]; ItinString += " " + itostr(OCycle); if (++i < N) ItinString += ", "; } } void SubtargetEmitter::FormItineraryBypassString(const std::string &Name, Record *ItinData, std::string &ItinString, unsigned NOperandCycles) { RecVec BypassList = ItinData->getValueAsListOfDefs("Bypasses"); unsigned N = BypassList.size(); unsigned i = 0; for (; i < N;) { ItinString += Name + "Bypass::" + BypassList[i]->getName().str(); if (++i < NOperandCycles) ItinString += ", "; } for (; i < NOperandCycles;) { ItinString += " 0"; if (++i < NOperandCycles) ItinString += ", "; } } // // EmitStageAndOperandCycleData - Generate unique itinerary stages and operand // cycle tables. Create a list of InstrItinerary objects (ProcItinLists) indexed // by CodeGenSchedClass::Index. // void SubtargetEmitter:: EmitStageAndOperandCycleData(raw_ostream &OS, std::vector<std::vector<InstrItinerary>> &ProcItinLists) { // Multiple processor models may share an itinerary record. Emit it once. SmallPtrSet<Record*, 8> ItinsDefSet; // Emit functional units for all the itineraries. for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { if (!ItinsDefSet.insert(ProcModel.ItinsDef).second) continue; RecVec FUs = ProcModel.ItinsDef->getValueAsListOfDefs("FU"); if (FUs.empty()) continue; StringRef Name = ProcModel.ItinsDef->getName(); OS << "\n// Functional units for \"" << Name << "\"\n" << "namespace " << Name << "FU {\n"; for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j) OS << " const unsigned " << FUs[j]->getName() << " = 1 << " << j << ";\n"; OS << "} // end namespace " << Name << "FU\n"; RecVec BPs = ProcModel.ItinsDef->getValueAsListOfDefs("BP"); if (!BPs.empty()) { OS << "\n// Pipeline forwarding paths for itineraries \"" << Name << "\"\n" << "namespace " << Name << "Bypass {\n"; OS << " const unsigned NoBypass = 0;\n"; for (unsigned j = 0, BPN = BPs.size(); j < BPN; ++j) OS << " const unsigned " << BPs[j]->getName() << " = 1 << " << j << ";\n"; OS << "} // end namespace " << Name << "Bypass\n"; } } // Begin stages table std::string StageTable = "\nextern const llvm::InstrStage " + Target + "Stages[] = {\n"; StageTable += " { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n"; // Begin operand cycle table std::string OperandCycleTable = "extern const unsigned " + Target + "OperandCycles[] = {\n"; OperandCycleTable += " 0, // No itinerary\n"; // Begin pipeline bypass table std::string BypassTable = "extern const unsigned " + Target + "ForwardingPaths[] = {\n"; BypassTable += " 0, // No itinerary\n"; // For each Itinerary across all processors, add a unique entry to the stages, // operand cycles, and pipeline bypass tables. Then add the new Itinerary // object with computed offsets to the ProcItinLists result. unsigned StageCount = 1, OperandCycleCount = 1; std::map<std::string, unsigned> ItinStageMap, ItinOperandMap; for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { // Add process itinerary to the list. ProcItinLists.resize(ProcItinLists.size()+1); // If this processor defines no itineraries, then leave the itinerary list // empty. std::vector<InstrItinerary> &ItinList = ProcItinLists.back(); if (!ProcModel.hasItineraries()) continue; StringRef Name = ProcModel.ItinsDef->getName(); ItinList.resize(SchedModels.numInstrSchedClasses()); assert(ProcModel.ItinDefList.size() == ItinList.size() && "bad Itins"); for (unsigned SchedClassIdx = 0, SchedClassEnd = ItinList.size(); SchedClassIdx < SchedClassEnd; ++SchedClassIdx) { // Next itinerary data Record *ItinData = ProcModel.ItinDefList[SchedClassIdx]; // Get string and stage count std::string ItinStageString; unsigned NStages = 0; if (ItinData) FormItineraryStageString(Name, ItinData, ItinStageString, NStages); // Get string and operand cycle count std::string ItinOperandCycleString; unsigned NOperandCycles = 0; std::string ItinBypassString; if (ItinData) { FormItineraryOperandCycleString(ItinData, ItinOperandCycleString, NOperandCycles); FormItineraryBypassString(Name, ItinData, ItinBypassString, NOperandCycles); } // Check to see if stage already exists and create if it doesn't uint16_t FindStage = 0; if (NStages > 0) { FindStage = ItinStageMap[ItinStageString]; if (FindStage == 0) { // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // indices StageTable += ItinStageString + ", // " + itostr(StageCount); if (NStages > 1) StageTable += "-" + itostr(StageCount + NStages - 1); StageTable += "\n"; // Record Itin class number. ItinStageMap[ItinStageString] = FindStage = StageCount; StageCount += NStages; } } // Check to see if operand cycle already exists and create if it doesn't uint16_t FindOperandCycle = 0; if (NOperandCycles > 0) { std::string ItinOperandString = ItinOperandCycleString+ItinBypassString; FindOperandCycle = ItinOperandMap[ItinOperandString]; if (FindOperandCycle == 0) { // Emit as cycle, // index OperandCycleTable += ItinOperandCycleString + ", // "; std::string OperandIdxComment = itostr(OperandCycleCount); if (NOperandCycles > 1) OperandIdxComment += "-" + itostr(OperandCycleCount + NOperandCycles - 1); OperandCycleTable += OperandIdxComment + "\n"; // Record Itin class number. ItinOperandMap[ItinOperandCycleString] = FindOperandCycle = OperandCycleCount; // Emit as bypass, // index BypassTable += ItinBypassString + ", // " + OperandIdxComment + "\n"; OperandCycleCount += NOperandCycles; } } // Set up itinerary as location and location + stage count int16_t NumUOps = ItinData ? ItinData->getValueAsInt("NumMicroOps") : 0; InstrItinerary Intinerary = { NumUOps, FindStage, uint16_t(FindStage + NStages), FindOperandCycle, uint16_t(FindOperandCycle + NOperandCycles), }; // Inject - empty slots will be 0, 0 ItinList[SchedClassIdx] = Intinerary; } } // Closing stage StageTable += " { 0, 0, 0, llvm::InstrStage::Required } // End stages\n"; StageTable += "};\n"; // Closing operand cycles OperandCycleTable += " 0 // End operand cycles\n"; OperandCycleTable += "};\n"; BypassTable += " 0 // End bypass tables\n"; BypassTable += "};\n"; // Emit tables. OS << StageTable; OS << OperandCycleTable; OS << BypassTable; } // // EmitProcessorData - Generate data for processor itineraries that were // computed during EmitStageAndOperandCycleData(). ProcItinLists lists all // Itineraries for each processor. The Itinerary lists are indexed on // CodeGenSchedClass::Index. // void SubtargetEmitter:: EmitItineraries(raw_ostream &OS, std::vector<std::vector<InstrItinerary>> &ProcItinLists) { // Multiple processor models may share an itinerary record. Emit it once. SmallPtrSet<Record*, 8> ItinsDefSet; // For each processor's machine model std::vector<std::vector<InstrItinerary>>::iterator ProcItinListsIter = ProcItinLists.begin(); for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(), PE = SchedModels.procModelEnd(); PI != PE; ++PI, ++ProcItinListsIter) { Record *ItinsDef = PI->ItinsDef; if (!ItinsDefSet.insert(ItinsDef).second) continue; // Get the itinerary list for the processor. assert(ProcItinListsIter != ProcItinLists.end() && "bad iterator"); std::vector<InstrItinerary> &ItinList = *ProcItinListsIter; // Empty itineraries aren't referenced anywhere in the tablegen output // so don't emit them. if (ItinList.empty()) continue; OS << "\n"; OS << "static const llvm::InstrItinerary "; // Begin processor itinerary table OS << ItinsDef->getName() << "[] = {\n"; // For each itinerary class in CodeGenSchedClass::Index order. for (unsigned j = 0, M = ItinList.size(); j < M; ++j) { InstrItinerary &Intinerary = ItinList[j]; // Emit Itinerary in the form of // { firstStage, lastStage, firstCycle, lastCycle } // index OS << " { " << Intinerary.NumMicroOps << ", " << Intinerary.FirstStage << ", " << Intinerary.LastStage << ", " << Intinerary.FirstOperandCycle << ", " << Intinerary.LastOperandCycle << " }" << ", // " << j << " " << SchedModels.getSchedClass(j).Name << "\n"; } // End processor itinerary table OS << " { 0, uint16_t(~0U), uint16_t(~0U), uint16_t(~0U), uint16_t(~0U) }" "// end marker\n"; OS << "};\n"; } } // Emit either the value defined in the TableGen Record, or the default // value defined in the C++ header. The Record is null if the processor does not // define a model. void SubtargetEmitter::EmitProcessorProp(raw_ostream &OS, const Record *R, StringRef Name, char Separator) { OS << " "; int V = R ? R->getValueAsInt(Name) : -1; if (V >= 0) OS << V << Separator << " // " << Name; else OS << "MCSchedModel::Default" << Name << Separator; OS << '\n'; } void SubtargetEmitter::EmitProcessorResourceSubUnits( const CodeGenProcModel &ProcModel, raw_ostream &OS) { OS << "\nstatic const unsigned " << ProcModel.ModelName << "ProcResourceSubUnits[] = {\n" << " 0, // Invalid\n"; for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) { Record *PRDef = ProcModel.ProcResourceDefs[i]; if (!PRDef->isSubClassOf("ProcResGroup")) continue; RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources"); for (Record *RUDef : ResUnits) { Record *const RU = SchedModels.findProcResUnits(RUDef, ProcModel, PRDef->getLoc()); for (unsigned J = 0; J < RU->getValueAsInt("NumUnits"); ++J) { OS << " " << ProcModel.getProcResourceIdx(RU) << ", "; } } OS << " // " << PRDef->getName() << "\n"; } OS << "};\n"; } static void EmitRetireControlUnitInfo(const CodeGenProcModel &ProcModel, raw_ostream &OS) { int64_t ReorderBufferSize = 0, MaxRetirePerCycle = 0; if (Record *RCU = ProcModel.RetireControlUnit) { ReorderBufferSize = std::max(ReorderBufferSize, RCU->getValueAsInt("ReorderBufferSize")); MaxRetirePerCycle = std::max(MaxRetirePerCycle, RCU->getValueAsInt("MaxRetirePerCycle")); } OS << ReorderBufferSize << ", // ReorderBufferSize\n "; OS << MaxRetirePerCycle << ", // MaxRetirePerCycle\n "; } static void EmitRegisterFileInfo(const CodeGenProcModel &ProcModel, unsigned NumRegisterFiles, unsigned NumCostEntries, raw_ostream &OS) { if (NumRegisterFiles) OS << ProcModel.ModelName << "RegisterFiles,\n " << (1 + NumRegisterFiles); else OS << "nullptr,\n 0"; OS << ", // Number of register files.\n "; if (NumCostEntries) OS << ProcModel.ModelName << "RegisterCosts,\n "; else OS << "nullptr,\n "; OS << NumCostEntries << ", // Number of register cost entries.\n"; } unsigned SubtargetEmitter::EmitRegisterFileTables(const CodeGenProcModel &ProcModel, raw_ostream &OS) { if (llvm::all_of(ProcModel.RegisterFiles, [](const CodeGenRegisterFile &RF) { return RF.hasDefaultCosts(); })) return 0; // Print the RegisterCost table first. OS << "\n// {RegisterClassID, Register Cost, AllowMoveElimination }\n"; OS << "static const llvm::MCRegisterCostEntry " << ProcModel.ModelName << "RegisterCosts" << "[] = {\n"; for (const CodeGenRegisterFile &RF : ProcModel.RegisterFiles) { // Skip register files with a default cost table. if (RF.hasDefaultCosts()) continue; // Add entries to the cost table. for (const CodeGenRegisterCost &RC : RF.Costs) { OS << " { "; Record *Rec = RC.RCDef; if (Rec->getValue("Namespace")) OS << Rec->getValueAsString("Namespace") << "::"; OS << Rec->getName() << "RegClassID, " << RC.Cost << ", " << RC.AllowMoveElimination << "},\n"; } } OS << "};\n"; // Now generate a table with register file info. OS << "\n // {Name, #PhysRegs, #CostEntries, IndexToCostTbl, " << "MaxMovesEliminatedPerCycle, AllowZeroMoveEliminationOnly }\n"; OS << "static const llvm::MCRegisterFileDesc " << ProcModel.ModelName << "RegisterFiles" << "[] = {\n" << " { \"InvalidRegisterFile\", 0, 0, 0, 0, 0 },\n"; unsigned CostTblIndex = 0; for (const CodeGenRegisterFile &RD : ProcModel.RegisterFiles) { OS << " { "; OS << '"' << RD.Name << '"' << ", " << RD.NumPhysRegs << ", "; unsigned NumCostEntries = RD.Costs.size(); OS << NumCostEntries << ", " << CostTblIndex << ", " << RD.MaxMovesEliminatedPerCycle << ", " << RD.AllowZeroMoveEliminationOnly << "},\n"; CostTblIndex += NumCostEntries; } OS << "};\n"; return CostTblIndex; } void SubtargetEmitter::EmitLoadStoreQueueInfo(const CodeGenProcModel &ProcModel, raw_ostream &OS) { unsigned QueueID = 0; if (ProcModel.LoadQueue) { const Record *Queue = ProcModel.LoadQueue->getValueAsDef("QueueDescriptor"); QueueID = 1 + std::distance(ProcModel.ProcResourceDefs.begin(), std::find(ProcModel.ProcResourceDefs.begin(), ProcModel.ProcResourceDefs.end(), Queue)); } OS << " " << QueueID << ", // Resource Descriptor for the Load Queue\n"; QueueID = 0; if (ProcModel.StoreQueue) { const Record *Queue = ProcModel.StoreQueue->getValueAsDef("QueueDescriptor"); QueueID = 1 + std::distance(ProcModel.ProcResourceDefs.begin(), std::find(ProcModel.ProcResourceDefs.begin(), ProcModel.ProcResourceDefs.end(), Queue)); } OS << " " << QueueID << ", // Resource Descriptor for the Store Queue\n"; } void SubtargetEmitter::EmitExtraProcessorInfo(const CodeGenProcModel &ProcModel, raw_ostream &OS) { // Generate a table of register file descriptors (one entry per each user // defined register file), and a table of register costs. unsigned NumCostEntries = EmitRegisterFileTables(ProcModel, OS); // Now generate a table for the extra processor info. OS << "\nstatic const llvm::MCExtraProcessorInfo " << ProcModel.ModelName << "ExtraInfo = {\n "; // Add information related to the retire control unit. EmitRetireControlUnitInfo(ProcModel, OS); // Add information related to the register files (i.e. where to find register // file descriptors and register costs). EmitRegisterFileInfo(ProcModel, ProcModel.RegisterFiles.size(), NumCostEntries, OS); // Add information about load/store queues. EmitLoadStoreQueueInfo(ProcModel, OS); OS << "};\n"; } void SubtargetEmitter::EmitProcessorResources(const CodeGenProcModel &ProcModel, raw_ostream &OS) { EmitProcessorResourceSubUnits(ProcModel, OS); OS << "\n// {Name, NumUnits, SuperIdx, BufferSize, SubUnitsIdxBegin}\n"; OS << "static const llvm::MCProcResourceDesc " << ProcModel.ModelName << "ProcResources" << "[] = {\n" << " {\"InvalidUnit\", 0, 0, 0, 0},\n"; unsigned SubUnitsOffset = 1; for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) { Record *PRDef = ProcModel.ProcResourceDefs[i]; Record *SuperDef = nullptr; unsigned SuperIdx = 0; unsigned NumUnits = 0; const unsigned SubUnitsBeginOffset = SubUnitsOffset; int BufferSize = PRDef->getValueAsInt("BufferSize"); if (PRDef->isSubClassOf("ProcResGroup")) { RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources"); for (Record *RU : ResUnits) { NumUnits += RU->getValueAsInt("NumUnits"); SubUnitsOffset += RU->getValueAsInt("NumUnits"); } } else { // Find the SuperIdx if (PRDef->getValueInit("Super")->isComplete()) { SuperDef = SchedModels.findProcResUnits(PRDef->getValueAsDef("Super"), ProcModel, PRDef->getLoc()); SuperIdx = ProcModel.getProcResourceIdx(SuperDef); } NumUnits = PRDef->getValueAsInt("NumUnits"); } // Emit the ProcResourceDesc OS << " {\"" << PRDef->getName() << "\", "; if (PRDef->getName().size() < 15) OS.indent(15 - PRDef->getName().size()); OS << NumUnits << ", " << SuperIdx << ", " << BufferSize << ", "; if (SubUnitsBeginOffset != SubUnitsOffset) { OS << ProcModel.ModelName << "ProcResourceSubUnits + " << SubUnitsBeginOffset; } else { OS << "nullptr"; } OS << "}, // #" << i+1; if (SuperDef) OS << ", Super=" << SuperDef->getName(); OS << "\n"; } OS << "};\n"; } // Find the WriteRes Record that defines processor resources for this // SchedWrite. Record *SubtargetEmitter::FindWriteResources( const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) { // Check if the SchedWrite is already subtarget-specific and directly // specifies a set of processor resources. if (SchedWrite.TheDef->isSubClassOf("SchedWriteRes")) return SchedWrite.TheDef; Record *AliasDef = nullptr; for (Record *A : SchedWrite.Aliases) { const CodeGenSchedRW &AliasRW = SchedModels.getSchedRW(A->getValueAsDef("AliasRW")); if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) { Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel"); if (&SchedModels.getProcModel(ModelDef) != &ProcModel) continue; } if (AliasDef) PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases " "defined for processor " + ProcModel.ModelName + " Ensure only one SchedAlias exists per RW."); AliasDef = AliasRW.TheDef; } if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes")) return AliasDef; // Check this processor's list of write resources. Record *ResDef = nullptr; for (Record *WR : ProcModel.WriteResDefs) { if (!WR->isSubClassOf("WriteRes")) continue; if (AliasDef == WR->getValueAsDef("WriteType") || SchedWrite.TheDef == WR->getValueAsDef("WriteType")) { if (ResDef) { PrintFatalError(WR->getLoc(), "Resources are defined for both " "SchedWrite and its alias on processor " + ProcModel.ModelName); } ResDef = WR; } } // TODO: If ProcModel has a base model (previous generation processor), // then call FindWriteResources recursively with that model here. if (!ResDef) { PrintFatalError(ProcModel.ModelDef->getLoc(), Twine("Processor does not define resources for ") + SchedWrite.TheDef->getName()); } return ResDef; } /// Find the ReadAdvance record for the given SchedRead on this processor or /// return NULL. Record *SubtargetEmitter::FindReadAdvance(const CodeGenSchedRW &SchedRead, const CodeGenProcModel &ProcModel) { // Check for SchedReads that directly specify a ReadAdvance. if (SchedRead.TheDef->isSubClassOf("SchedReadAdvance")) return SchedRead.TheDef; // Check this processor's list of aliases for SchedRead. Record *AliasDef = nullptr; for (Record *A : SchedRead.Aliases) { const CodeGenSchedRW &AliasRW = SchedModels.getSchedRW(A->getValueAsDef("AliasRW")); if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) { Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel"); if (&SchedModels.getProcModel(ModelDef) != &ProcModel) continue; } if (AliasDef) PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases " "defined for processor " + ProcModel.ModelName + " Ensure only one SchedAlias exists per RW."); AliasDef = AliasRW.TheDef; } if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance")) return AliasDef; // Check this processor's ReadAdvanceList. Record *ResDef = nullptr; for (Record *RA : ProcModel.ReadAdvanceDefs) { if (!RA->isSubClassOf("ReadAdvance")) continue; if (AliasDef == RA->getValueAsDef("ReadType") || SchedRead.TheDef == RA->getValueAsDef("ReadType")) { if (ResDef) { PrintFatalError(RA->getLoc(), "Resources are defined for both " "SchedRead and its alias on processor " + ProcModel.ModelName); } ResDef = RA; } } // TODO: If ProcModel has a base model (previous generation processor), // then call FindReadAdvance recursively with that model here. if (!ResDef && SchedRead.TheDef->getName() != "ReadDefault") { PrintFatalError(ProcModel.ModelDef->getLoc(), Twine("Processor does not define resources for ") + SchedRead.TheDef->getName()); } return ResDef; } // Expand an explicit list of processor resources into a full list of implied // resource groups and super resources that cover them. void SubtargetEmitter::ExpandProcResources(RecVec &PRVec, std::vector<int64_t> &Cycles, const CodeGenProcModel &PM) { assert(PRVec.size() == Cycles.size() && "failed precondition"); for (unsigned i = 0, e = PRVec.size(); i != e; ++i) { Record *PRDef = PRVec[i]; RecVec SubResources; if (PRDef->isSubClassOf("ProcResGroup")) SubResources = PRDef->getValueAsListOfDefs("Resources"); else { SubResources.push_back(PRDef); PRDef = SchedModels.findProcResUnits(PRDef, PM, PRDef->getLoc()); for (Record *SubDef = PRDef; SubDef->getValueInit("Super")->isComplete();) { if (SubDef->isSubClassOf("ProcResGroup")) { // Disallow this for simplicitly. PrintFatalError(SubDef->getLoc(), "Processor resource group " " cannot be a super resources."); } Record *SuperDef = SchedModels.findProcResUnits(SubDef->getValueAsDef("Super"), PM, SubDef->getLoc()); PRVec.push_back(SuperDef); Cycles.push_back(Cycles[i]); SubDef = SuperDef; } } for (Record *PR : PM.ProcResourceDefs) { if (PR == PRDef || !PR->isSubClassOf("ProcResGroup")) continue; RecVec SuperResources = PR->getValueAsListOfDefs("Resources"); RecIter SubI = SubResources.begin(), SubE = SubResources.end(); for( ; SubI != SubE; ++SubI) { if (!is_contained(SuperResources, *SubI)) { break; } } if (SubI == SubE) { PRVec.push_back(PR); Cycles.push_back(Cycles[i]); } } } } // Generate the SchedClass table for this processor and update global // tables. Must be called for each processor in order. void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel, SchedClassTables &SchedTables) { SchedTables.ProcSchedClasses.resize(SchedTables.ProcSchedClasses.size() + 1); if (!ProcModel.hasInstrSchedModel()) return; std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back(); LLVM_DEBUG(dbgs() << "\n+++ SCHED CLASSES (GenSchedClassTables) +++\n"); for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) { LLVM_DEBUG(SC.dump(&SchedModels)); SCTab.resize(SCTab.size() + 1); MCSchedClassDesc &SCDesc = SCTab.back(); // SCDesc.Name is guarded by NDEBUG SCDesc.NumMicroOps = 0; SCDesc.BeginGroup = false; SCDesc.EndGroup = false; SCDesc.WriteProcResIdx = 0; SCDesc.WriteLatencyIdx = 0; SCDesc.ReadAdvanceIdx = 0; // A Variant SchedClass has no resources of its own. bool HasVariants = false; for (const CodeGenSchedTransition &CGT : make_range(SC.Transitions.begin(), SC.Transitions.end())) { if (CGT.ProcIndices[0] == 0 || is_contained(CGT.ProcIndices, ProcModel.Index)) { HasVariants = true; break; } } if (HasVariants) { SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps; continue; } // Determine if the SchedClass is actually reachable on this processor. If // not don't try to locate the processor resources, it will fail. // If ProcIndices contains 0, this class applies to all processors. assert(!SC.ProcIndices.empty() && "expect at least one procidx"); if (SC.ProcIndices[0] != 0) { if (!is_contained(SC.ProcIndices, ProcModel.Index)) continue; } IdxVec Writes = SC.Writes; IdxVec Reads = SC.Reads; if (!SC.InstRWs.empty()) { // This class has a default ReadWrite list which can be overridden by // InstRW definitions. Record *RWDef = nullptr; for (Record *RW : SC.InstRWs) { Record *RWModelDef = RW->getValueAsDef("SchedModel"); if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) { RWDef = RW; break; } } if (RWDef) { Writes.clear(); Reads.clear(); SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads); } } if (Writes.empty()) { // Check this processor's itinerary class resources. for (Record *I : ProcModel.ItinRWDefs) { RecVec Matched = I->getValueAsListOfDefs("MatchedItinClasses"); if (is_contained(Matched, SC.ItinClassDef)) { SchedModels.findRWs(I->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads); break; } } if (Writes.empty()) { LLVM_DEBUG(dbgs() << ProcModel.ModelName << " does not have resources for class " << SC.Name << '\n'); } } // Sum resources across all operand writes. std::vector<MCWriteProcResEntry> WriteProcResources; std::vector<MCWriteLatencyEntry> WriteLatencies; std::vector<std::string> WriterNames; std::vector<MCReadAdvanceEntry> ReadAdvanceEntries; for (unsigned W : Writes) { IdxVec WriteSeq; SchedModels.expandRWSeqForProc(W, WriteSeq, /*IsRead=*/false, ProcModel); // For each operand, create a latency entry. MCWriteLatencyEntry WLEntry; WLEntry.Cycles = 0; unsigned WriteID = WriteSeq.back(); WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name); // If this Write is not referenced by a ReadAdvance, don't distinguish it // from other WriteLatency entries. if (!SchedModels.hasReadOfWrite( SchedModels.getSchedWrite(WriteID).TheDef)) { WriteID = 0; } WLEntry.WriteResourceID = WriteID; for (unsigned WS : WriteSeq) { Record *WriteRes = FindWriteResources(SchedModels.getSchedWrite(WS), ProcModel); // Mark the parent class as invalid for unsupported write types. if (WriteRes->getValueAsBit("Unsupported")) { SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps; break; } WLEntry.Cycles += WriteRes->getValueAsInt("Latency"); SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps"); SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup"); SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup"); SCDesc.BeginGroup |= WriteRes->getValueAsBit("SingleIssue"); SCDesc.EndGroup |= WriteRes->getValueAsBit("SingleIssue"); // Create an entry for each ProcResource listed in WriteRes. RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources"); std::vector<int64_t> Cycles = WriteRes->getValueAsListOfInts("ResourceCycles"); if (Cycles.empty()) { // If ResourceCycles is not provided, default to one cycle per // resource. Cycles.resize(PRVec.size(), 1); } else if (Cycles.size() != PRVec.size()) { // If ResourceCycles is provided, check consistency. PrintFatalError( WriteRes->getLoc(), Twine("Inconsistent resource cycles: !size(ResourceCycles) != " "!size(ProcResources): ") .concat(Twine(PRVec.size())) .concat(" vs ") .concat(Twine(Cycles.size()))); } ExpandProcResources(PRVec, Cycles, ProcModel); for (unsigned PRIdx = 0, PREnd = PRVec.size(); PRIdx != PREnd; ++PRIdx) { MCWriteProcResEntry WPREntry; WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]); assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx"); WPREntry.Cycles = Cycles[PRIdx]; // If this resource is already used in this sequence, add the current // entry's cycles so that the same resource appears to be used // serially, rather than multiple parallel uses. This is important for // in-order machine where the resource consumption is a hazard. unsigned WPRIdx = 0, WPREnd = WriteProcResources.size(); for( ; WPRIdx != WPREnd; ++WPRIdx) { if (WriteProcResources[WPRIdx].ProcResourceIdx == WPREntry.ProcResourceIdx) { WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles; break; } } if (WPRIdx == WPREnd) WriteProcResources.push_back(WPREntry); } } WriteLatencies.push_back(WLEntry); } // Create an entry for each operand Read in this SchedClass. // Entries must be sorted first by UseIdx then by WriteResourceID. for (unsigned UseIdx = 0, EndIdx = Reads.size(); UseIdx != EndIdx; ++UseIdx) { Record *ReadAdvance = FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel); if (!ReadAdvance) continue; // Mark the parent class as invalid for unsupported write types. if (ReadAdvance->getValueAsBit("Unsupported")) { SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps; break; } RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites"); IdxVec WriteIDs; if (ValidWrites.empty()) WriteIDs.push_back(0); else { for (Record *VW : ValidWrites) { WriteIDs.push_back(SchedModels.getSchedRWIdx(VW, /*IsRead=*/false)); } } llvm::sort(WriteIDs); for(unsigned W : WriteIDs) { MCReadAdvanceEntry RAEntry; RAEntry.UseIdx = UseIdx; RAEntry.WriteResourceID = W; RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles"); ReadAdvanceEntries.push_back(RAEntry); } } if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) { WriteProcResources.clear(); WriteLatencies.clear(); ReadAdvanceEntries.clear(); } // Add the information for this SchedClass to the global tables using basic // compression. // // WritePrecRes entries are sorted by ProcResIdx. llvm::sort(WriteProcResources, LessWriteProcResources()); SCDesc.NumWriteProcResEntries = WriteProcResources.size(); std::vector<MCWriteProcResEntry>::iterator WPRPos = std::search(SchedTables.WriteProcResources.begin(), SchedTables.WriteProcResources.end(), WriteProcResources.begin(), WriteProcResources.end()); if (WPRPos != SchedTables.WriteProcResources.end()) SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin(); else { SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size(); SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(), WriteProcResources.end()); } // Latency entries must remain in operand order. SCDesc.NumWriteLatencyEntries = WriteLatencies.size(); std::vector<MCWriteLatencyEntry>::iterator WLPos = std::search(SchedTables.WriteLatencies.begin(), SchedTables.WriteLatencies.end(), WriteLatencies.begin(), WriteLatencies.end()); if (WLPos != SchedTables.WriteLatencies.end()) { unsigned idx = WLPos - SchedTables.WriteLatencies.begin(); SCDesc.WriteLatencyIdx = idx; for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i) if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) == std::string::npos) { SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i]; } } else { SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size(); SchedTables.WriteLatencies.insert(SchedTables.WriteLatencies.end(), WriteLatencies.begin(), WriteLatencies.end()); SchedTables.WriterNames.insert(SchedTables.WriterNames.end(), WriterNames.begin(), WriterNames.end()); } // ReadAdvanceEntries must remain in operand order. SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size(); std::vector<MCReadAdvanceEntry>::iterator RAPos = std::search(SchedTables.ReadAdvanceEntries.begin(), SchedTables.ReadAdvanceEntries.end(), ReadAdvanceEntries.begin(), ReadAdvanceEntries.end()); if (RAPos != SchedTables.ReadAdvanceEntries.end()) SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin(); else { SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size(); SchedTables.ReadAdvanceEntries.insert(RAPos, ReadAdvanceEntries.begin(), ReadAdvanceEntries.end()); } } } // Emit SchedClass tables for all processors and associated global tables. void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables, raw_ostream &OS) { // Emit global WriteProcResTable. OS << "\n// {ProcResourceIdx, Cycles}\n" << "extern const llvm::MCWriteProcResEntry " << Target << "WriteProcResTable[] = {\n" << " { 0, 0}, // Invalid\n"; for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size(); WPRIdx != WPREnd; ++WPRIdx) { MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx]; OS << " {" << format("%2d", WPREntry.ProcResourceIdx) << ", " << format("%2d", WPREntry.Cycles) << "}"; if (WPRIdx + 1 < WPREnd) OS << ','; OS << " // #" << WPRIdx << '\n'; } OS << "}; // " << Target << "WriteProcResTable\n"; // Emit global WriteLatencyTable. OS << "\n// {Cycles, WriteResourceID}\n" << "extern const llvm::MCWriteLatencyEntry " << Target << "WriteLatencyTable[] = {\n" << " { 0, 0}, // Invalid\n"; for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size(); WLIdx != WLEnd; ++WLIdx) { MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx]; OS << " {" << format("%2d", WLEntry.Cycles) << ", " << format("%2d", WLEntry.WriteResourceID) << "}"; if (WLIdx + 1 < WLEnd) OS << ','; OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n'; } OS << "}; // " << Target << "WriteLatencyTable\n"; // Emit global ReadAdvanceTable. OS << "\n// {UseIdx, WriteResourceID, Cycles}\n" << "extern const llvm::MCReadAdvanceEntry " << Target << "ReadAdvanceTable[] = {\n" << " {0, 0, 0}, // Invalid\n"; for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size(); RAIdx != RAEnd; ++RAIdx) { MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx]; OS << " {" << RAEntry.UseIdx << ", " << format("%2d", RAEntry.WriteResourceID) << ", " << format("%2d", RAEntry.Cycles) << "}"; if (RAIdx + 1 < RAEnd) OS << ','; OS << " // #" << RAIdx << '\n'; } OS << "}; // " << Target << "ReadAdvanceTable\n"; // Emit a SchedClass table for each processor. for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(), PE = SchedModels.procModelEnd(); PI != PE; ++PI) { if (!PI->hasInstrSchedModel()) continue; std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())]; OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup," << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n"; OS << "static const llvm::MCSchedClassDesc " << PI->ModelName << "SchedClasses[] = {\n"; // The first class is always invalid. We no way to distinguish it except by // name and position. assert(SchedModels.getSchedClass(0).Name == "NoInstrModel" && "invalid class not first"); OS << " {DBGFIELD(\"InvalidSchedClass\") " << MCSchedClassDesc::InvalidNumMicroOps << ", false, false, 0, 0, 0, 0, 0, 0},\n"; for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) { MCSchedClassDesc &MCDesc = SCTab[SCIdx]; const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx); OS << " {DBGFIELD(\"" << SchedClass.Name << "\") "; if (SchedClass.Name.size() < 18) OS.indent(18 - SchedClass.Name.size()); OS << MCDesc.NumMicroOps << ", " << ( MCDesc.BeginGroup ? "true" : "false" ) << ", " << ( MCDesc.EndGroup ? "true" : "false" ) << ", " << format("%2d", MCDesc.WriteProcResIdx) << ", " << MCDesc.NumWriteProcResEntries << ", " << format("%2d", MCDesc.WriteLatencyIdx) << ", " << MCDesc.NumWriteLatencyEntries << ", " << format("%2d", MCDesc.ReadAdvanceIdx) << ", " << MCDesc.NumReadAdvanceEntries << "}, // #" << SCIdx << '\n'; } OS << "}; // " << PI->ModelName << "SchedClasses\n"; } } void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) { // For each processor model. for (const CodeGenProcModel &PM : SchedModels.procModels()) { // Emit extra processor info if available. if (PM.hasExtraProcessorInfo()) EmitExtraProcessorInfo(PM, OS); // Emit processor resource table. if (PM.hasInstrSchedModel()) EmitProcessorResources(PM, OS); else if(!PM.ProcResourceDefs.empty()) PrintFatalError(PM.ModelDef->getLoc(), "SchedMachineModel defines " "ProcResources without defining WriteRes SchedWriteRes"); // Begin processor itinerary properties OS << "\n"; OS << "static const llvm::MCSchedModel " << PM.ModelName << " = {\n"; EmitProcessorProp(OS, PM.ModelDef, "IssueWidth", ','); EmitProcessorProp(OS, PM.ModelDef, "MicroOpBufferSize", ','); EmitProcessorProp(OS, PM.ModelDef, "LoopMicroOpBufferSize", ','); EmitProcessorProp(OS, PM.ModelDef, "LoadLatency", ','); EmitProcessorProp(OS, PM.ModelDef, "HighLatency", ','); EmitProcessorProp(OS, PM.ModelDef, "MispredictPenalty", ','); bool PostRAScheduler = (PM.ModelDef ? PM.ModelDef->getValueAsBit("PostRAScheduler") : false); OS << " " << (PostRAScheduler ? "true" : "false") << ", // " << "PostRAScheduler\n"; bool CompleteModel = (PM.ModelDef ? PM.ModelDef->getValueAsBit("CompleteModel") : false); OS << " " << (CompleteModel ? "true" : "false") << ", // " << "CompleteModel\n"; OS << " " << PM.Index << ", // Processor ID\n"; if (PM.hasInstrSchedModel()) OS << " " << PM.ModelName << "ProcResources" << ",\n" << " " << PM.ModelName << "SchedClasses" << ",\n" << " " << PM.ProcResourceDefs.size()+1 << ",\n" << " " << (SchedModels.schedClassEnd() - SchedModels.schedClassBegin()) << ",\n"; else OS << " nullptr, nullptr, 0, 0," << " // No instruction-level machine model.\n"; if (PM.hasItineraries()) OS << " " << PM.ItinsDef->getName() << ",\n"; else OS << " nullptr, // No Itinerary\n"; if (PM.hasExtraProcessorInfo()) OS << " &" << PM.ModelName << "ExtraInfo,\n"; else OS << " nullptr // No extra processor descriptor\n"; OS << "};\n"; } } // // EmitSchedModel - Emits all scheduling model tables, folding common patterns. // void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) { OS << "#ifdef DBGFIELD\n" << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n" << "#endif\n" << "#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)\n" << "#define DBGFIELD(x) x,\n" << "#else\n" << "#define DBGFIELD(x)\n" << "#endif\n"; if (SchedModels.hasItineraries()) { std::vector<std::vector<InstrItinerary>> ProcItinLists; // Emit the stage data EmitStageAndOperandCycleData(OS, ProcItinLists); EmitItineraries(OS, ProcItinLists); } OS << "\n// ===============================================================\n" << "// Data tables for the new per-operand machine model.\n"; SchedClassTables SchedTables; for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { GenSchedClassTables(ProcModel, SchedTables); } EmitSchedClassTables(SchedTables, OS); OS << "\n#undef DBGFIELD\n"; // Emit the processor machine model EmitProcessorModels(OS); } static void emitPredicateProlog(const RecordKeeper &Records, raw_ostream &OS) { std::string Buffer; raw_string_ostream Stream(Buffer); // Collect all the PredicateProlog records and print them to the output // stream. std::vector<Record *> Prologs = Records.getAllDerivedDefinitions("PredicateProlog"); llvm::sort(Prologs, LessRecord()); for (Record *P : Prologs) Stream << P->getValueAsString("Code") << '\n'; Stream.flush(); OS << Buffer; } static void emitPredicates(const CodeGenSchedTransition &T, const CodeGenSchedClass &SC, PredicateExpander &PE, raw_ostream &OS) { std::string Buffer; raw_string_ostream SS(Buffer); auto IsTruePredicate = [](const Record *Rec) { return Rec->isSubClassOf("MCSchedPredicate") && Rec->getValueAsDef("Pred")->isSubClassOf("MCTrue"); }; // If not all predicates are MCTrue, then we need an if-stmt. unsigned NumNonTruePreds = T.PredTerm.size() - count_if(T.PredTerm, IsTruePredicate); SS.indent(PE.getIndentLevel() * 2); if (NumNonTruePreds) { bool FirstNonTruePredicate = true; SS << "if ("; PE.setIndentLevel(PE.getIndentLevel() + 2); for (const Record *Rec : T.PredTerm) { // Skip predicates that evaluate to "true". if (IsTruePredicate(Rec)) continue; if (FirstNonTruePredicate) { FirstNonTruePredicate = false; } else { SS << "\n"; SS.indent(PE.getIndentLevel() * 2); SS << "&& "; } if (Rec->isSubClassOf("MCSchedPredicate")) { PE.expandPredicate(SS, Rec->getValueAsDef("Pred")); continue; } // Expand this legacy predicate and wrap it around braces if there is more // than one predicate to expand. SS << ((NumNonTruePreds > 1) ? "(" : "") << Rec->getValueAsString("Predicate") << ((NumNonTruePreds > 1) ? ")" : ""); } SS << ")\n"; // end of if-stmt PE.decreaseIndentLevel(); SS.indent(PE.getIndentLevel() * 2); PE.decreaseIndentLevel(); } SS << "return " << T.ToClassIdx << "; // " << SC.Name << '\n'; SS.flush(); OS << Buffer; } // Used by method `SubtargetEmitter::emitSchedModelHelpersImpl()` to generate // epilogue code for the auto-generated helper. void emitSchedModelHelperEpilogue(raw_ostream &OS, bool ShouldReturnZero) { if (ShouldReturnZero) { OS << " // Don't know how to resolve this scheduling class.\n" << " return 0;\n"; return; } OS << " report_fatal_error(\"Expected a variant SchedClass\");\n"; } bool hasMCSchedPredicates(const CodeGenSchedTransition &T) { return all_of(T.PredTerm, [](const Record *Rec) { return Rec->isSubClassOf("MCSchedPredicate"); }); } void collectVariantClasses(const CodeGenSchedModels &SchedModels, IdxVec &VariantClasses, bool OnlyExpandMCInstPredicates) { for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) { // Ignore non-variant scheduling classes. if (SC.Transitions.empty()) continue; if (OnlyExpandMCInstPredicates) { // Ignore this variant scheduling class no transitions use any meaningful // MCSchedPredicate definitions. if (!any_of(SC.Transitions, [](const CodeGenSchedTransition &T) { return hasMCSchedPredicates(T); })) continue; } VariantClasses.push_back(SC.Index); } } void collectProcessorIndices(const CodeGenSchedClass &SC, IdxVec &ProcIndices) { // A variant scheduling class may define transitions for multiple // processors. This function identifies wich processors are associated with // transition rules specified by variant class `SC`. for (const CodeGenSchedTransition &T : SC.Transitions) { IdxVec PI; std::set_union(T.ProcIndices.begin(), T.ProcIndices.end(), ProcIndices.begin(), ProcIndices.end(), std::back_inserter(PI)); ProcIndices.swap(PI); } } void SubtargetEmitter::emitSchedModelHelpersImpl( raw_ostream &OS, bool OnlyExpandMCInstPredicates) { IdxVec VariantClasses; collectVariantClasses(SchedModels, VariantClasses, OnlyExpandMCInstPredicates); if (VariantClasses.empty()) { emitSchedModelHelperEpilogue(OS, OnlyExpandMCInstPredicates); return; } // Construct a switch statement where the condition is a check on the // scheduling class identifier. There is a `case` for every variant class // defined by the processor models of this target. // Each `case` implements a number of rules to resolve (i.e. to transition from) // a variant scheduling class to another scheduling class. Rules are // described by instances of CodeGenSchedTransition. Note that transitions may // not be valid for all processors. OS << " switch (SchedClass) {\n"; for (unsigned VC : VariantClasses) { IdxVec ProcIndices; const CodeGenSchedClass &SC = SchedModels.getSchedClass(VC); collectProcessorIndices(SC, ProcIndices); OS << " case " << VC << ": // " << SC.Name << '\n'; PredicateExpander PE(Target); PE.setByRef(false); PE.setExpandForMC(OnlyExpandMCInstPredicates); for (unsigned PI : ProcIndices) { OS << " "; // Emit a guard on the processor ID. if (PI != 0) { OS << (OnlyExpandMCInstPredicates ? "if (CPUID == " : "if (SchedModel->getProcessorID() == "); OS << PI << ") "; OS << "{ // " << (SchedModels.procModelBegin() + PI)->ModelName << '\n'; } // Now emit transitions associated with processor PI. for (const CodeGenSchedTransition &T : SC.Transitions) { if (PI != 0 && !count(T.ProcIndices, PI)) continue; // Emit only transitions based on MCSchedPredicate, if it's the case. // At least the transition specified by NoSchedPred is emitted, // which becomes the default transition for those variants otherwise // not based on MCSchedPredicate. // FIXME: preferably, llvm-mca should instead assume a reasonable // default when a variant transition is not based on MCSchedPredicate // for a given processor. if (OnlyExpandMCInstPredicates && !hasMCSchedPredicates(T)) continue; PE.setIndentLevel(3); emitPredicates(T, SchedModels.getSchedClass(T.ToClassIdx), PE, OS); } OS << " }\n"; if (PI == 0) break; } if (SC.isInferred()) OS << " return " << SC.Index << ";\n"; OS << " break;\n"; } OS << " };\n"; emitSchedModelHelperEpilogue(OS, OnlyExpandMCInstPredicates); } void SubtargetEmitter::EmitSchedModelHelpers(const std::string &ClassName, raw_ostream &OS) { OS << "unsigned " << ClassName << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI," << " const TargetSchedModel *SchedModel) const {\n"; // Emit the predicate prolog code. emitPredicateProlog(Records, OS); // Emit target predicates. emitSchedModelHelpersImpl(OS); OS << "} // " << ClassName << "::resolveSchedClass\n\n"; OS << "unsigned " << ClassName << "\n::resolveVariantSchedClass(unsigned SchedClass, const MCInst *MI," << " unsigned CPUID) const {\n" << " return " << Target << "_MC" << "::resolveVariantSchedClassImpl(SchedClass, MI, CPUID);\n" << "} // " << ClassName << "::resolveVariantSchedClass\n\n"; STIPredicateExpander PE(Target); PE.setClassPrefix(ClassName); PE.setExpandDefinition(true); PE.setByRef(false); PE.setIndentLevel(0); for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates()) PE.expandSTIPredicate(OS, Fn); } void SubtargetEmitter::EmitHwModeCheck(const std::string &ClassName, raw_ostream &OS) { const CodeGenHwModes &CGH = TGT.getHwModes(); assert(CGH.getNumModeIds() > 0); if (CGH.getNumModeIds() == 1) return; OS << "unsigned " << ClassName << "::getHwMode() const {\n"; for (unsigned M = 1, NumModes = CGH.getNumModeIds(); M != NumModes; ++M) { const HwMode &HM = CGH.getMode(M); OS << " if (checkFeatures(\"" << HM.Features << "\")) return " << M << ";\n"; } OS << " return 0;\n}\n"; } // // ParseFeaturesFunction - Produces a subtarget specific function for parsing // the subtarget features string. // void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS, unsigned NumFeatures, unsigned NumProcs) { std::vector<Record*> Features = Records.getAllDerivedDefinitions("SubtargetFeature"); llvm::sort(Features, LessRecord()); OS << "// ParseSubtargetFeatures - Parses features string setting specified\n" << "// subtarget options.\n" << "void llvm::"; OS << Target; OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef FS) {\n" << " LLVM_DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n" << " LLVM_DEBUG(dbgs() << \"\\nCPU:\" << CPU << \"\\n\\n\");\n"; if (Features.empty()) { OS << "}\n"; return; } OS << " InitMCProcessorInfo(CPU, FS);\n" << " const FeatureBitset& Bits = getFeatureBits();\n"; for (Record *R : Features) { // Next record StringRef Instance = R->getName(); StringRef Value = R->getValueAsString("Value"); StringRef Attribute = R->getValueAsString("Attribute"); if (Value=="true" || Value=="false") OS << " if (Bits[" << Target << "::" << Instance << "]) " << Attribute << " = " << Value << ";\n"; else OS << " if (Bits[" << Target << "::" << Instance << "] && " << Attribute << " < " << Value << ") " << Attribute << " = " << Value << ";\n"; } OS << "}\n"; } void SubtargetEmitter::emitGenMCSubtargetInfo(raw_ostream &OS) { OS << "namespace " << Target << "_MC {\n" << "unsigned resolveVariantSchedClassImpl(unsigned SchedClass,\n" << " const MCInst *MI, unsigned CPUID) {\n"; emitSchedModelHelpersImpl(OS, /* OnlyExpandMCPredicates */ true); OS << "}\n"; OS << "} // end namespace " << Target << "_MC\n\n"; OS << "struct " << Target << "GenMCSubtargetInfo : public MCSubtargetInfo {\n"; OS << " " << Target << "GenMCSubtargetInfo(const Triple &TT, \n" << " StringRef CPU, StringRef FS, ArrayRef<SubtargetFeatureKV> PF,\n" << " ArrayRef<SubtargetSubTypeKV> PD,\n" << " const MCWriteProcResEntry *WPR,\n" << " const MCWriteLatencyEntry *WL,\n" << " const MCReadAdvanceEntry *RA, const InstrStage *IS,\n" << " const unsigned *OC, const unsigned *FP) :\n" << " MCSubtargetInfo(TT, CPU, FS, PF, PD,\n" << " WPR, WL, RA, IS, OC, FP) { }\n\n" << " unsigned resolveVariantSchedClass(unsigned SchedClass,\n" << " const MCInst *MI, unsigned CPUID) const override {\n" << " return " << Target << "_MC" << "::resolveVariantSchedClassImpl(SchedClass, MI, CPUID); \n"; OS << " }\n"; if (TGT.getHwModes().getNumModeIds() > 1) OS << " unsigned getHwMode() const override;\n"; OS << "};\n"; EmitHwModeCheck(Target + "GenMCSubtargetInfo", OS); } void SubtargetEmitter::EmitMCInstrAnalysisPredicateFunctions(raw_ostream &OS) { OS << "\n#ifdef GET_STIPREDICATE_DECLS_FOR_MC_ANALYSIS\n"; OS << "#undef GET_STIPREDICATE_DECLS_FOR_MC_ANALYSIS\n\n"; STIPredicateExpander PE(Target); PE.setExpandForMC(true); PE.setByRef(true); for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates()) PE.expandSTIPredicate(OS, Fn); OS << "#endif // GET_STIPREDICATE_DECLS_FOR_MC_ANALYSIS\n\n"; OS << "\n#ifdef GET_STIPREDICATE_DEFS_FOR_MC_ANALYSIS\n"; OS << "#undef GET_STIPREDICATE_DEFS_FOR_MC_ANALYSIS\n\n"; std::string ClassPrefix = Target + "MCInstrAnalysis"; PE.setExpandDefinition(true); PE.setClassPrefix(ClassPrefix); PE.setIndentLevel(0); for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates()) PE.expandSTIPredicate(OS, Fn); OS << "#endif // GET_STIPREDICATE_DEFS_FOR_MC_ANALYSIS\n\n"; } // // SubtargetEmitter::run - Main subtarget enumeration emitter. // void SubtargetEmitter::run(raw_ostream &OS) { emitSourceFileHeader("Subtarget Enumeration Source Fragment", OS); OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n"; OS << "#undef GET_SUBTARGETINFO_ENUM\n\n"; DenseMap<Record *, unsigned> FeatureMap; OS << "namespace llvm {\n"; Enumeration(OS, FeatureMap); OS << "} // end namespace llvm\n\n"; OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n"; OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n"; OS << "#undef GET_SUBTARGETINFO_MC_DESC\n\n"; OS << "namespace llvm {\n"; #if 0 OS << "namespace {\n"; #endif unsigned NumFeatures = FeatureKeyValues(OS, FeatureMap); OS << "\n"; EmitSchedModel(OS); OS << "\n"; unsigned NumProcs = CPUKeyValues(OS, FeatureMap); OS << "\n"; #if 0 OS << "} // end anonymous namespace\n\n"; #endif // MCInstrInfo initialization routine. emitGenMCSubtargetInfo(OS); OS << "\nstatic inline MCSubtargetInfo *create" << Target << "MCSubtargetInfoImpl(" << "const Triple &TT, StringRef CPU, StringRef FS) {\n"; OS << " return new " << Target << "GenMCSubtargetInfo(TT, CPU, FS, "; if (NumFeatures) OS << Target << "FeatureKV, "; else OS << "None, "; if (NumProcs) OS << Target << "SubTypeKV, "; else OS << "None, "; OS << '\n'; OS.indent(22); OS << Target << "WriteProcResTable, " << Target << "WriteLatencyTable, " << Target << "ReadAdvanceTable, "; OS << '\n'; OS.indent(22); if (SchedModels.hasItineraries()) { OS << Target << "Stages, " << Target << "OperandCycles, " << Target << "ForwardingPaths"; } else OS << "nullptr, nullptr, nullptr"; OS << ");\n}\n\n"; OS << "} // end namespace llvm\n\n"; OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n"; OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n"; OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n\n"; OS << "#include \"llvm/Support/Debug.h\"\n"; OS << "#include \"llvm/Support/raw_ostream.h\"\n\n"; ParseFeaturesFunction(OS, NumFeatures, NumProcs); OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n"; // Create a TargetSubtargetInfo subclass to hide the MC layer initialization. OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n"; OS << "#undef GET_SUBTARGETINFO_HEADER\n\n"; std::string ClassName = Target + "GenSubtargetInfo"; OS << "namespace llvm {\n"; OS << "class DFAPacketizer;\n"; OS << "namespace " << Target << "_MC {\n" << "unsigned resolveVariantSchedClassImpl(unsigned SchedClass," << " const MCInst *MI, unsigned CPUID);\n" << "} // end namespace " << Target << "_MC\n\n"; OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n" << " explicit " << ClassName << "(const Triple &TT, StringRef CPU, " << "StringRef FS);\n" << "public:\n" << " unsigned resolveSchedClass(unsigned SchedClass, " << " const MachineInstr *DefMI," << " const TargetSchedModel *SchedModel) const override;\n" << " unsigned resolveVariantSchedClass(unsigned SchedClass," << " const MCInst *MI, unsigned CPUID) const override;\n" << " DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)" << " const;\n"; if (TGT.getHwModes().getNumModeIds() > 1) OS << " unsigned getHwMode() const override;\n"; STIPredicateExpander PE(Target); PE.setByRef(false); for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates()) PE.expandSTIPredicate(OS, Fn); OS << "};\n" << "} // end namespace llvm\n\n"; OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n"; OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n"; OS << "#undef GET_SUBTARGETINFO_CTOR\n\n"; OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n\n"; OS << "namespace llvm {\n"; OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n"; OS << "extern const llvm::SubtargetSubTypeKV " << Target << "SubTypeKV[];\n"; OS << "extern const llvm::MCWriteProcResEntry " << Target << "WriteProcResTable[];\n"; OS << "extern const llvm::MCWriteLatencyEntry " << Target << "WriteLatencyTable[];\n"; OS << "extern const llvm::MCReadAdvanceEntry " << Target << "ReadAdvanceTable[];\n"; if (SchedModels.hasItineraries()) { OS << "extern const llvm::InstrStage " << Target << "Stages[];\n"; OS << "extern const unsigned " << Target << "OperandCycles[];\n"; OS << "extern const unsigned " << Target << "ForwardingPaths[];\n"; } OS << ClassName << "::" << ClassName << "(const Triple &TT, StringRef CPU, " << "StringRef FS)\n" << " : TargetSubtargetInfo(TT, CPU, FS, "; if (NumFeatures) OS << "makeArrayRef(" << Target << "FeatureKV, " << NumFeatures << "), "; else OS << "None, "; if (NumProcs) OS << "makeArrayRef(" << Target << "SubTypeKV, " << NumProcs << "), "; else OS << "None, "; OS << '\n'; OS.indent(24); OS << Target << "WriteProcResTable, " << Target << "WriteLatencyTable, " << Target << "ReadAdvanceTable, "; OS << '\n'; OS.indent(24); if (SchedModels.hasItineraries()) { OS << Target << "Stages, " << Target << "OperandCycles, " << Target << "ForwardingPaths"; } else OS << "nullptr, nullptr, nullptr"; OS << ") {}\n\n"; EmitSchedModelHelpers(ClassName, OS); EmitHwModeCheck(ClassName, OS); OS << "} // end namespace llvm\n\n"; OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n"; EmitMCInstrAnalysisPredicateFunctions(OS); } namespace llvm { void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) { CodeGenTarget CGTarget(RK); SubtargetEmitter(RK, CGTarget).run(OS); } } // end namespace llvm
apache-2.0
howard5888/wine
wine-1.7.7/dlls/d3d9/d3d9_main.c
1
4479
/* * Direct3D 9 * * Copyright 2002-2003 Jason Edmeades * Copyright 2002-2003 Raphael Junqueira * Copyright 2005 Oliver Stieber * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * */ #include "config.h" #include "initguid.h" #include "d3d9_private.h" WINE_DEFAULT_DEBUG_CHANNEL(d3d9); static int D3DPERF_event_level = 0; void WINAPI DebugSetMute(void) { /* nothing to do */ } IDirect3D9 * WINAPI DECLSPEC_HOTPATCH Direct3DCreate9(UINT sdk_version) { struct d3d9 *object; TRACE("sdk_version %#x.\n", sdk_version); if (!(object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object)))) return NULL; if (!d3d9_init(object, FALSE)) { WARN("Failed to initialize d3d9.\n"); HeapFree(GetProcessHeap(), 0, object); return NULL; } TRACE("Created d3d9 object %p.\n", object); return (IDirect3D9 *)&object->IDirect3D9Ex_iface; } HRESULT WINAPI DECLSPEC_HOTPATCH Direct3DCreate9Ex(UINT sdk_version, IDirect3D9Ex **d3d9ex) { struct d3d9 *object; TRACE("sdk_version %#x, d3d9ex %p.\n", sdk_version, d3d9ex); if (!(object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object)))) return E_OUTOFMEMORY; if (!d3d9_init(object, TRUE)) { WARN("Failed to initialize d3d9.\n"); HeapFree(GetProcessHeap(), 0, object); return D3DERR_NOTAVAILABLE; } TRACE("Created d3d9 object %p.\n", object); *d3d9ex = &object->IDirect3D9Ex_iface; return D3D_OK; } /******************************************************************* * Direct3DShaderValidatorCreate9 (D3D9.@) * * No documentation available for this function. * SDK only says it is internal and shouldn't be used. */ void* WINAPI Direct3DShaderValidatorCreate9(void) { static int once; if (!once++) FIXME("stub\n"); return NULL; } /******************************************************************* * DllMain */ BOOL WINAPI DllMain(HINSTANCE inst, DWORD reason, void *reserved) { if (reason == DLL_PROCESS_ATTACH) DisableThreadLibraryCalls(inst); return TRUE; } /*********************************************************************** * D3DPERF_BeginEvent (D3D9.@) */ int WINAPI D3DPERF_BeginEvent(D3DCOLOR color, const WCHAR *name) { TRACE("color 0x%08x, name %s.\n", color, debugstr_w(name)); return D3DPERF_event_level++; } /*********************************************************************** * D3DPERF_EndEvent (D3D9.@) */ int WINAPI D3DPERF_EndEvent(void) { TRACE("(void) : stub\n"); return --D3DPERF_event_level; } /*********************************************************************** * D3DPERF_GetStatus (D3D9.@) */ DWORD WINAPI D3DPERF_GetStatus(void) { FIXME("(void) : stub\n"); return 0; } /*********************************************************************** * D3DPERF_SetOptions (D3D9.@) * */ void WINAPI D3DPERF_SetOptions(DWORD options) { FIXME("(%#x) : stub\n", options); } /*********************************************************************** * D3DPERF_QueryRepeatFrame (D3D9.@) */ BOOL WINAPI D3DPERF_QueryRepeatFrame(void) { FIXME("(void) : stub\n"); return FALSE; } /*********************************************************************** * D3DPERF_SetMarker (D3D9.@) */ void WINAPI D3DPERF_SetMarker(D3DCOLOR color, const WCHAR *name) { FIXME("color 0x%08x, name %s stub!\n", color, debugstr_w(name)); } /*********************************************************************** * D3DPERF_SetRegion (D3D9.@) */ void WINAPI D3DPERF_SetRegion(D3DCOLOR color, const WCHAR *name) { FIXME("color 0x%08x, name %s stub!\n", color, debugstr_w(name)); }
apache-2.0
axbannaz/axis2-c
src/core/transport/http/sender/libcurl/axis2_libcurl.c
1
36521
/* * 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. */ #ifdef AXIS2_LIBCURL_ENABLED #include "axis2_libcurl.h" #include <axiom_soap.h> #include <axutil_string.h> #include <axis2_http_transport.h> #include <axiom_output.h> #include <axis2_op_ctx.h> #include <axis2_ctx.h> #include <axis2_conf_ctx.h> #include <axis2_http_client.h> #include <axiom_xml_writer.h> #include <axutil_property.h> #include <axutil_param.h> #include <axutil_types.h> #include <axutil_generic_obj.h> #include <axis2_const.h> #include <axis2_util.h> #include <stdlib.h> #include <axis2_http_sender.h> #include <axis2_http_transport.h> #include "libcurl_stream.h" static int ref = 0; struct axis2_libcurl { axis2_char_t *memory; axutil_array_list_t *alist; unsigned int size; const axutil_env_t *env; char errorbuffer[CURL_ERROR_SIZE]; CURL *handler; axis2_bool_t cookies; }; static size_t axis2_libcurl_write_memory_callback( void *ptr, size_t size, size_t nmemb, void *data); static size_t axis2_libcurl_header_callback( void *ptr, size_t size, size_t nmemb, void *data); static axis2_char_t * axis2_libcurl_get_content_type( axis2_libcurl_t *curl, const axutil_env_t * env); static int axis2_libcurl_get_content_length( axis2_libcurl_t *curl, const axutil_env_t * env); static axis2_http_header_t * axis2_libcurl_get_first_header( axis2_libcurl_t *curl, const axutil_env_t * env, const axis2_char_t * str); static void axis2_libcurl_free_headers( axis2_libcurl_t *curl, const axutil_env_t * env); static axis2_status_t axis2_libcurl_set_options( CURL *handler, const axutil_env_t * env, axis2_msg_ctx_t * msg_ctx); axis2_status_t AXIS2_CALL axis2_libcurl_send( axis2_libcurl_t *data, axiom_output_t * om_output, const axutil_env_t * env, axis2_msg_ctx_t * msg_ctx, axiom_soap_envelope_t * out, const axis2_char_t * str_url, const axis2_char_t * soap_action) { struct curl_slist *headers = NULL; axiom_soap_body_t *soap_body; axis2_bool_t is_soap = AXIS2_TRUE; axis2_bool_t send_via_get = AXIS2_FALSE; axis2_bool_t send_via_head = AXIS2_FALSE; axis2_bool_t send_via_put = AXIS2_FALSE; axis2_bool_t send_via_delete = AXIS2_FALSE; axis2_bool_t doing_mtom = AXIS2_FALSE; axiom_node_t *body_node = NULL; axiom_node_t *data_out = NULL; axutil_property_t *method = NULL; axis2_char_t *method_value = NULL; axiom_xml_writer_t *xml_writer = NULL; axis2_char_t *buffer = NULL; unsigned int buffer_size = 0; int content_length = -1; axis2_char_t *content_type = NULL; axis2_char_t *content_len = AXIS2_HTTP_HEADER_CONTENT_LENGTH_; const axis2_char_t *char_set_enc = NULL; axis2_char_t *content = AXIS2_HTTP_HEADER_CONTENT_TYPE_; axis2_char_t *soap_action_header = AXIS2_HTTP_HEADER_SOAP_ACTION_; axutil_stream_t *in_stream; axutil_property_t *trans_in_property; axutil_string_t *char_set_enc_str; axis2_byte_t *output_stream = NULL; int output_stream_size = 0; CURL *handler; axis2_conf_ctx_t *conf_ctx = NULL; axis2_conf_t *conf = NULL; axis2_transport_out_desc_t *trans_desc = NULL; axutil_param_t *write_xml_declaration_param = NULL; axutil_hash_t *transport_attrs = NULL; axis2_bool_t write_xml_declaration = AXIS2_FALSE; axutil_property_t *property; int *response_length = NULL; axis2_http_status_line_t *status_line = NULL; axis2_char_t *status_line_str = NULL; axis2_char_t *tmp_strcat = NULL; int status_code = 0; AXIS2_PARAM_CHECK(env->error, data, AXIS2_FAILURE); AXIS2_PARAM_CHECK(env->error, data->handler, AXIS2_FAILURE); handler = data->handler; curl_easy_reset(handler); curl_easy_setopt(handler, CURLOPT_ERRORBUFFER, &data->errorbuffer); headers = curl_slist_append(headers, AXIS2_HTTP_HEADER_USER_AGENT_AXIS2C); headers = curl_slist_append(headers, AXIS2_HTTP_HEADER_ACCEPT_); headers = curl_slist_append(headers, AXIS2_HTTP_HEADER_EXPECT_); if(AXIS2_FAILURE == axis2_libcurl_set_options(handler, env, msg_ctx)) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "[axis2libcurl]Setting options in Libcurl failed"); return AXIS2_FAILURE; } if (AXIS2_TRUE == axis2_msg_ctx_get_doing_rest(msg_ctx, env)) { is_soap = AXIS2_FALSE; } else { is_soap = AXIS2_TRUE; } if (!is_soap) { soap_body = axiom_soap_envelope_get_body(out, env); if (!soap_body) { AXIS2_HANDLE_ERROR(env, AXIS2_ERROR_SOAP_ENVELOPE_OR_SOAP_BODY_NULL, AXIS2_FAILURE); return AXIS2_FAILURE; } body_node = axiom_soap_body_get_base_node(soap_body, env); if (!body_node) { AXIS2_HANDLE_ERROR(env, AXIS2_ERROR_SOAP_ENVELOPE_OR_SOAP_BODY_NULL, AXIS2_FAILURE); return AXIS2_FAILURE; } data_out = axiom_node_get_first_element(body_node, env); method = (axutil_property_t *) axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_HTTP_METHOD); if (method) { method_value = (axis2_char_t *) axutil_property_get_value(method, env); } /* The default is POST */ if (method_value && 0 == axutil_strcmp(method_value, AXIS2_HTTP_GET)) { send_via_get = AXIS2_TRUE; } else if (method_value && 0 == axutil_strcmp(method_value, AXIS2_HTTP_HEAD)) { send_via_head = AXIS2_TRUE; } else if (method_value && 0 == axutil_strcmp(method_value, AXIS2_HTTP_PUT)) { send_via_put = AXIS2_TRUE; } else if (method_value && 0 == axutil_strcmp(method_value, AXIS2_HTTP_DELETE)) { send_via_delete = AXIS2_TRUE; } } conf_ctx = axis2_msg_ctx_get_conf_ctx (msg_ctx, env); if (conf_ctx) { conf = axis2_conf_ctx_get_conf (conf_ctx, env); } if (conf) { trans_desc = axis2_conf_get_transport_out (conf, env, AXIS2_TRANSPORT_ENUM_HTTP); } if (trans_desc) { write_xml_declaration_param = axutil_param_container_get_param (axis2_transport_out_desc_param_container (trans_desc, env), env, AXIS2_XML_DECLARATION); } if (write_xml_declaration_param) { transport_attrs = axutil_param_get_attributes (write_xml_declaration_param, env); if (transport_attrs) { axutil_generic_obj_t *obj = NULL; axiom_attribute_t *write_xml_declaration_attr = NULL; axis2_char_t *write_xml_declaration_attr_value = NULL; obj = axutil_hash_get (transport_attrs, AXIS2_ADD_XML_DECLARATION, AXIS2_HASH_KEY_STRING); if (obj) { write_xml_declaration_attr = (axiom_attribute_t *) axutil_generic_obj_get_value (obj, env); } if (write_xml_declaration_attr) { write_xml_declaration_attr_value = axiom_attribute_get_value (write_xml_declaration_attr, env); } if (write_xml_declaration_attr_value && 0 == axutil_strcasecmp (write_xml_declaration_attr_value, AXIS2_VALUE_TRUE)) { write_xml_declaration = AXIS2_TRUE; } } } if (write_xml_declaration) { axiom_output_write_xml_version_encoding (om_output, env); } if (!send_via_get && !send_via_head && !send_via_delete) { xml_writer = axiom_output_get_xml_writer(om_output, env); char_set_enc_str = axis2_msg_ctx_get_charset_encoding(msg_ctx, env); if (!char_set_enc_str) { char_set_enc = AXIS2_DEFAULT_CHAR_SET_ENCODING; } else { char_set_enc = axutil_string_get_buffer(char_set_enc_str, env); } if (!send_via_put && is_soap) { doing_mtom = axis2_msg_ctx_get_doing_mtom(msg_ctx, env); axiom_output_set_do_optimize(om_output, env, doing_mtom); axiom_soap_envelope_serialize(out, env, om_output, AXIS2_FALSE); if (AXIS2_TRUE == axis2_msg_ctx_get_is_soap_11(msg_ctx, env)) { if (AXIS2_ESC_DOUBLE_QUOTE != *soap_action) { axis2_char_t *tmp_soap_action = NULL; tmp_soap_action = AXIS2_MALLOC(env->allocator, (axutil_strlen(soap_action) + 5) * sizeof(axis2_char_t)); sprintf(tmp_soap_action, "\"%s\"", soap_action); tmp_strcat = axutil_stracat(env, soap_action_header,tmp_soap_action); headers = curl_slist_append(headers, tmp_strcat); AXIS2_FREE(env->allocator, tmp_strcat); AXIS2_FREE(env->allocator, tmp_soap_action); } else { tmp_strcat = axutil_stracat(env, soap_action_header, soap_action); headers = curl_slist_append(headers, tmp_strcat ); AXIS2_FREE(env->allocator, tmp_strcat); } } if (doing_mtom) { /*axiom_output_flush(om_output, env, &output_stream, &output_stream_size);*/ axiom_output_flush(om_output, env); content_type = (axis2_char_t *) axiom_output_get_content_type(om_output, env); if (AXIS2_TRUE != axis2_msg_ctx_get_is_soap_11(msg_ctx, env)) { if (axutil_strcmp(soap_action, "")) { /* handle SOAP action for SOAP 1.2 case */ axis2_char_t *temp_content_type = NULL; temp_content_type = axutil_stracat (env, content_type, AXIS2_CONTENT_TYPE_ACTION); content_type = temp_content_type; temp_content_type = axutil_stracat (env, content_type, soap_action); AXIS2_FREE (env->allocator, content_type); content_type = temp_content_type; temp_content_type = axutil_stracat (env, content_type, AXIS2_ESC_DOUBLE_QUOTE_STR); AXIS2_FREE (env->allocator, content_type); content_type = temp_content_type; } } } else if (AXIS2_TRUE == axis2_msg_ctx_get_is_soap_11(msg_ctx, env)) { axis2_char_t *temp_content_type = NULL; content_type = (axis2_char_t *) AXIS2_HTTP_HEADER_ACCEPT_TEXT_XML; content_type = axutil_stracat(env, content_type, AXIS2_CONTENT_TYPE_CHARSET); temp_content_type = axutil_stracat(env, content_type, char_set_enc); AXIS2_FREE(env->allocator, content_type); content_type = temp_content_type; } else { axis2_char_t *temp_content_type = NULL; content_type = (axis2_char_t *) AXIS2_HTTP_HEADER_ACCEPT_APPL_SOAP; content_type = axutil_stracat(env, content_type, AXIS2_CONTENT_TYPE_CHARSET); temp_content_type = axutil_stracat(env, content_type, char_set_enc); AXIS2_FREE(env->allocator, content_type); content_type = temp_content_type; if (axutil_strcmp(soap_action, "")) { temp_content_type = axutil_stracat(env, content_type, AXIS2_CONTENT_TYPE_ACTION); AXIS2_FREE(env->allocator, content_type); content_type = temp_content_type; temp_content_type = axutil_stracat(env, content_type, soap_action); AXIS2_FREE(env->allocator, content_type); content_type = temp_content_type; } temp_content_type = axutil_stracat(env, content_type, AXIS2_SEMI_COLON_STR); AXIS2_FREE(env->allocator, content_type); content_type = temp_content_type; } } else if (is_soap) { AXIS2_LOG_ERROR (env->log, AXIS2_LOG_SI, "Attempt to send SOAP" "message using HTTP PUT failed"); return AXIS2_FAILURE; } else { axutil_property_t *content_type_property = NULL; axutil_hash_t *content_type_hash = NULL; axis2_char_t *content_type_value = NULL; axiom_node_serialize(data_out, env, om_output); content_type_property = (axutil_property_t *) axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_USER_DEFINED_HTTP_HEADER_CONTENT_TYPE); if (content_type_property) { content_type_hash = (axutil_hash_t *) axutil_property_get_value(content_type_property, env); if (content_type_hash) { content_type_value = (char *) axutil_hash_get(content_type_hash, AXIS2_HTTP_HEADER_CONTENT_TYPE, AXIS2_HASH_KEY_STRING); } } if (content_type_value) { content_type = content_type_value; } else { content_type = AXIS2_HTTP_HEADER_ACCEPT_TEXT_XML; } } buffer = axiom_xml_writer_get_xml(xml_writer, env); if (!doing_mtom) { buffer_size = axiom_xml_writer_get_xml_size(xml_writer, env); } else buffer_size = output_stream_size; { char tmp_buf[10]; sprintf(tmp_buf, "%d", buffer_size); tmp_strcat = axutil_stracat(env, content_len, tmp_buf); headers = curl_slist_append(headers, tmp_strcat); AXIS2_FREE(env->allocator, tmp_strcat); tmp_strcat = NULL; tmp_strcat = axutil_stracat(env, content, content_type); headers = curl_slist_append(headers, tmp_strcat); AXIS2_FREE(env->allocator, tmp_strcat); tmp_strcat = NULL; } if (!doing_mtom) { curl_easy_setopt(handler, CURLOPT_POSTFIELDSIZE, buffer_size); curl_easy_setopt(handler, CURLOPT_POSTFIELDS, buffer); } else { curl_easy_setopt(handler, CURLOPT_POSTFIELDSIZE, output_stream_size); curl_easy_setopt(handler, CURLOPT_POSTFIELDS, output_stream); } if (send_via_put) { curl_easy_setopt(handler, CURLOPT_CUSTOMREQUEST, AXIS2_HTTP_PUT); } curl_easy_setopt(handler, CURLOPT_URL, str_url); } else { axis2_char_t *request_param; axis2_char_t *url_encode; request_param = (axis2_char_t *) axis2_http_sender_get_param_string(NULL, env, msg_ctx); url_encode = axutil_strcat(env, str_url, AXIS2_Q_MARK_STR, request_param, NULL); if (send_via_get) { curl_easy_setopt(handler, CURLOPT_HTTPGET, 1); } else if (send_via_head) { curl_easy_setopt(handler, CURLOPT_NOBODY, 1); } else if (send_via_delete) { curl_easy_setopt(handler, CURLOPT_CUSTOMREQUEST, AXIS2_HTTP_DELETE); } curl_easy_setopt(handler, CURLOPT_URL, url_encode); } { axis2_bool_t manage_session; manage_session = axis2_msg_ctx_get_manage_session(msg_ctx, env); if (manage_session == AXIS2_TRUE) { if (data->cookies == AXIS2_FALSE) { /* Ensure cookies enabled to manage session */ /* Pass empty cookie string to enable cookies */ curl_easy_setopt(handler, CURLOPT_COOKIEFILE, " "); data->cookies = AXIS2_TRUE; } } else if (data->cookies == AXIS2_TRUE) { /* Pass special string ALL to reset cookies if any have been enabled. */ /* If cookies have ever been enabled, we reset every time as long as manage_session is false, as there is no clear curl option to turn off the cookie engine once enabled. */ curl_easy_setopt(handler, CURLOPT_COOKIELIST, AXIS2_ALL); } } curl_easy_setopt(handler, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(handler, CURLOPT_WRITEFUNCTION, axis2_libcurl_write_memory_callback); curl_easy_setopt(handler, CURLOPT_WRITEDATA, data); curl_easy_setopt (handler, CURLOPT_HEADERFUNCTION, axis2_libcurl_header_callback); curl_easy_setopt (handler, CURLOPT_WRITEHEADER, data); /* Free response data from previous request */ if( data->size ) { if (data->memory) { AXIS2_FREE(data->env->allocator, data->memory); } data->size = 0; } if (curl_easy_perform(handler)) { AXIS2_LOG_ERROR (env->log, AXIS2_LOG_SI, "%s", &data->errorbuffer); AXIS2_HANDLE_ERROR(env, AXIS2_ERROR_HTTP_CLIENT_TRANSPORT_ERROR, AXIS2_FAILURE); return AXIS2_FAILURE; } in_stream = axutil_stream_create_libcurl(env, data->memory, data->size); trans_in_property = axutil_property_create(env); axutil_property_set_scope(trans_in_property, env, AXIS2_SCOPE_REQUEST); axutil_property_set_free_func(trans_in_property, env, libcurl_stream_free); axutil_property_set_value(trans_in_property, env, in_stream); axis2_msg_ctx_set_property(msg_ctx, env, AXIS2_TRANSPORT_IN, trans_in_property); if (axutil_array_list_size(data->alist, env) > 0) { status_line_str = axutil_array_list_get(data->alist, env, 0); if (status_line_str) { status_line = axis2_http_status_line_create(env, status_line_str); } } if (status_line) { status_code = axis2_http_status_line_get_status_code(status_line, env); } axis2_msg_ctx_set_status_code (msg_ctx, env, status_code); AXIS2_FREE(data->env->allocator, content_type); content_type = axis2_libcurl_get_content_type(data, env); if (content_type) { if (strstr (content_type, AXIS2_HTTP_HEADER_ACCEPT_MULTIPART_RELATED) && strstr (content_type, AXIS2_HTTP_HEADER_ACCEPT_XOP_XML)) { axis2_ctx_t *axis_ctx = axis2_op_ctx_get_base (axis2_msg_ctx_get_op_ctx (msg_ctx, env), env); property = axutil_property_create (env); axutil_property_set_scope (property, env, AXIS2_SCOPE_REQUEST); axutil_property_set_value (property, env, axutil_strdup (env, content_type)); axis2_ctx_set_property (axis_ctx, env, MTOM_RECIVED_CONTENT_TYPE, property); } } content_length = axis2_libcurl_get_content_length(data, env); if (content_length >= 0) { response_length = AXIS2_MALLOC (env->allocator, sizeof (int)); memcpy (response_length, &content_length, sizeof (int)); property = axutil_property_create (env); axutil_property_set_scope (property, env, AXIS2_SCOPE_REQUEST); axutil_property_set_value (property, env, response_length); axis2_msg_ctx_set_property (msg_ctx, env, AXIS2_HTTP_HEADER_CONTENT_LENGTH, property); } curl_slist_free_all (headers); /* release the read http headers. */ /* (commenting out the call below is a clever way to force a premature EOF condition in subsequent messages, as they will be read using the content-length of the first message.) */ axis2_libcurl_free_headers(data, env); AXIS2_FREE(data->env->allocator, content_type); axis2_http_status_line_free( status_line, env); return AXIS2_SUCCESS; } static size_t axis2_libcurl_write_memory_callback( void *ptr, size_t size, size_t nmemb, void *data) { size_t realsize = size * nmemb; axis2_libcurl_t *curl = (axis2_libcurl_t *) data; axis2_char_t *buffer = (axis2_char_t *) AXIS2_MALLOC(curl->env->allocator, curl->size + realsize + 1); if (buffer) { if (curl->size) { memcpy(&(buffer[0]), curl->memory, curl->size); AXIS2_FREE(curl->env->allocator, curl->memory); } memcpy(&(buffer[curl->size]), ptr, realsize); curl->size += (int)realsize; /* We are sure that the difference lies within the int range */ buffer[curl->size] = 0; curl->memory = buffer; } return realsize; } static size_t axis2_libcurl_header_callback( void *ptr, size_t size, size_t nmemb, void *data) { axis2_char_t *memory; size_t realsize = size * nmemb; axis2_libcurl_t *curl = (axis2_libcurl_t *) data; memory = (axis2_char_t *)AXIS2_MALLOC(curl->env->allocator, realsize + 1); if (memory) { memcpy(&(memory[0]), ptr, realsize); memory[realsize] = 0; axutil_array_list_add(curl->alist, curl->env, memory); } return realsize; } axis2_libcurl_t * AXIS2_CALL axis2_libcurl_create( const axutil_env_t * env) { axis2_libcurl_t *curl = NULL; CURLcode code; if (!ref) { /* curl_global_init is not thread-safe so it would be better to do this, as well as the test and increment of ref, under mutex if one is available, or as part of an axis2_initialize() if a global initialize is created. Otherwise the client application should perform the the curl_global_init itself in a thread-safe fashion. */ code = curl_global_init(CURL_GLOBAL_ALL); if (code) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "libcurl curl_global_init failed, error: %d", code); return NULL; } ref++; } curl = (axis2_libcurl_t *) AXIS2_MALLOC(env->allocator, sizeof(axis2_libcurl_t)); if (curl) { curl->memory = 0; curl->size = 0; curl->alist = axutil_array_list_create(env, 15); curl->env = env; curl->handler = curl_easy_init(); curl->cookies = AXIS2_FALSE; if ((!curl->alist) || (!curl->handler)) { axis2_libcurl_free(curl, env); curl = 0; } } return curl; } void AXIS2_CALL axis2_libcurl_free( axis2_libcurl_t *curl, const axutil_env_t * env) { if (!curl) { return; } if (curl->handler) { curl_easy_cleanup (curl->handler); } if (curl->alist) { axis2_libcurl_free_headers(curl, env); axutil_array_list_free(curl->alist, env); curl->alist = NULL; } if (curl->memory) { AXIS2_FREE(env->allocator, curl->memory); } AXIS2_FREE(env->allocator, curl); } static void axis2_libcurl_free_headers( axis2_libcurl_t *curl, const axutil_env_t * env) { int count = 0; axutil_array_list_t *header_group = curl->alist; if (header_group) { while ((count = axutil_array_list_size(header_group, env)) > 0) { axis2_char_t *header = axutil_array_list_remove(header_group, env, count-1); AXIS2_FREE(env->allocator, header); } } } static axis2_http_header_t * axis2_libcurl_get_first_header( axis2_libcurl_t *curl, const axutil_env_t * env, const axis2_char_t * str) { axis2_http_header_t *tmp_header = NULL; axis2_char_t *tmp_header_str = NULL; axis2_char_t *tmp_name = NULL; int i = 0; int count = 0; axutil_array_list_t *header_group = NULL; AXIS2_PARAM_CHECK(env->error, curl, NULL); AXIS2_PARAM_CHECK(env->error, str, NULL); header_group = curl->alist; if (!header_group) { return NULL; } if (0 == axutil_array_list_size(header_group, env)) { return NULL; } count = axutil_array_list_size(header_group, env); for (i = 0; i < count; i++) { tmp_header_str = (axis2_char_t *) axutil_array_list_get(header_group, env, i); if(!tmp_header_str) { continue; } tmp_header = (axis2_http_header_t *) axis2_http_header_create_by_str(env, tmp_header_str); if(!tmp_header) { continue; } tmp_name = axis2_http_header_get_name(tmp_header, env); if (0 == axutil_strcasecmp(str, tmp_name)) { return tmp_header; } else { axis2_http_header_free( tmp_header, env ); } } return NULL; } static int axis2_libcurl_get_content_length( axis2_libcurl_t *curl, const axutil_env_t * env) { axis2_http_header_t *tmp_header; int rtn_value = -1; tmp_header = axis2_libcurl_get_first_header (curl, env, AXIS2_HTTP_HEADER_CONTENT_LENGTH); if (tmp_header) { rtn_value = AXIS2_ATOI(axis2_http_header_get_value(tmp_header, env)); axis2_http_header_free( tmp_header, env ); } return rtn_value; } static axis2_char_t * axis2_libcurl_get_content_type( axis2_libcurl_t *curl, const axutil_env_t * env) { axis2_http_header_t *tmp_header; axis2_char_t *rtn_value = NULL; tmp_header = axis2_libcurl_get_first_header (curl, env, AXIS2_HTTP_HEADER_CONTENT_TYPE); if (tmp_header) { rtn_value = axutil_strdup (env, axis2_http_header_get_value(tmp_header, env) ); axis2_http_header_free( tmp_header, env ); } else { rtn_value = axutil_strdup (env, AXIS2_HTTP_HEADER_ACCEPT_TEXT_PLAIN); } return rtn_value; } /** * axis2_libcurl_set_auth_options maps authentication AXIS2/C options to * libcURL options. * * CURLOPT_USERPWD - char * user:password for authentication * CURLOPT_HTTPAUTH - long bitmask which authentication methods to use */ static axis2_status_t axis2_libcurl_set_auth_options( CURL *handler, const axutil_env_t * env, axis2_msg_ctx_t * msg_ctx) { axutil_property_t *property = NULL; axis2_char_t *uname = NULL; axis2_char_t *passwd = NULL; axis2_char_t *auth_type = NULL; property = axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_HTTP_AUTH_UNAME); if (property) { uname = (axis2_char_t *) axutil_property_get_value(property, env); } property = axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_HTTP_AUTH_PASSWD); if (property) { passwd = (axis2_char_t *) axutil_property_get_value(property, env); } if (uname && passwd) { axis2_char_t buffer[256]; strncpy(buffer, uname, 256); strncat(buffer, ":", 256); strncat(buffer, passwd, 256); curl_easy_setopt(handler, CURLOPT_USERPWD, buffer); } property = (axutil_property_t *)axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_HTTP_AUTH_TYPE); if (property) { auth_type = (axis2_char_t *) axutil_property_get_value(property, env); } if (auth_type && 0 == axutil_strcmp(auth_type, AXIS2_HTTP_AUTH_TYPE_BASIC)) { curl_easy_setopt(handler, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); } else { /* Uses anonymous connection.*/ } return AXIS2_SUCCESS; } /** * axis2_libcurl_set_proxy_options maps proxy AXIS2/C options to * libcURL options. * * CURLOPT_PROXY - char * proxy hostname * CURLOPT_PROXYPORT - long proxy listen port * CURLOPT_PROXYUSERPWD - char * user:password to authenticate to proxy * * TODO: * CURLOPT_PROXYTYPE - long enum type of proxy (HTTP, SOCKS) * CURLOPT_PROXYAUTH - long bitmask which authentication methods to use for proxy */ static axis2_status_t axis2_libcurl_set_proxy_options( CURL *handler, const axutil_env_t * env, axis2_msg_ctx_t * msg_ctx) { axis2_conf_ctx_t *conf_ctx = NULL; axis2_conf_t *conf = NULL; axis2_transport_out_desc_t *trans_desc = NULL; axutil_param_t *proxy_param = NULL; axutil_hash_t *transport_attrs = NULL; axutil_property_t *property = NULL; axis2_char_t *uname = NULL; axis2_char_t *passwd = NULL; axis2_char_t *proxy_host = NULL; axis2_char_t *proxy_port = NULL; property = axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_PROXY_AUTH_UNAME); if (property) { uname = (axis2_char_t *) axutil_property_get_value(property, env); } property = axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_PROXY_AUTH_PASSWD); if (property) { passwd = (axis2_char_t *) axutil_property_get_value(property, env); } conf_ctx = axis2_msg_ctx_get_conf_ctx(msg_ctx, env); if (conf_ctx) { conf = axis2_conf_ctx_get_conf(conf_ctx, env); if (conf) { trans_desc = axis2_conf_get_transport_out(conf, env, AXIS2_TRANSPORT_ENUM_HTTP); } } if (trans_desc) { proxy_param = axutil_param_container_get_param( axis2_transport_out_desc_param_container(trans_desc, env), env, AXIS2_HTTP_PROXY_API); if (!proxy_param) { proxy_param = axutil_param_container_get_param( axis2_transport_out_desc_param_container(trans_desc, env), env, AXIS2_HTTP_PROXY); } if (proxy_param) { transport_attrs = axutil_param_get_attributes(proxy_param, env); } } if (transport_attrs) { axutil_generic_obj_t *obj = NULL; axiom_attribute_t *attr = NULL; if (!uname || !passwd) { obj = axutil_hash_get(transport_attrs, AXIS2_HTTP_PROXY_USERNAME, AXIS2_HASH_KEY_STRING); if (obj) { attr = (axiom_attribute_t *) axutil_generic_obj_get_value(obj, env); } if (attr) { uname = axiom_attribute_get_value(attr, env); } attr = NULL; obj = axutil_hash_get(transport_attrs, AXIS2_HTTP_PROXY_PASSWORD, AXIS2_HASH_KEY_STRING); if (obj) { attr = (axiom_attribute_t *)axutil_generic_obj_get_value(obj, env); } if (attr) { passwd = axiom_attribute_get_value(attr, env); } } obj = axutil_hash_get(transport_attrs, AXIS2_HTTP_PROXY_HOST, AXIS2_HASH_KEY_STRING); if (obj) { attr = (axiom_attribute_t *)axutil_generic_obj_get_value(obj, env); } if (attr) { proxy_host = axiom_attribute_get_value(attr, env); } if (proxy_host) { curl_easy_setopt(handler, CURLOPT_PROXY, proxy_host); } attr = NULL; obj = axutil_hash_get(transport_attrs, AXIS2_HTTP_PROXY_PORT, AXIS2_HASH_KEY_STRING); if (obj) { attr = (axiom_attribute_t *)axutil_generic_obj_get_value(obj, env); } if (attr) { proxy_port = axiom_attribute_get_value(attr, env); } if (proxy_port) { curl_easy_setopt(handler, CURLOPT_PROXYPORT, AXIS2_ATOI(proxy_port)); } } if (uname && passwd) { axis2_char_t buffer[256]; strncpy(buffer, uname, 256); strncat(buffer, ":", 256); strncat(buffer, passwd, 256); curl_easy_setopt(handler, CURLOPT_PROXYUSERPWD, buffer); } return AXIS2_SUCCESS; } /** * axis2_libcurl_set_ssl_options maps SSL AXIS2/C options to * libcURL options. * * CURLOPT_SSL_VERIFYHOST - long enum whether to verify the server identity * CURLOPT_SSL_VERIFYPEER - long boolean whether to verify the server certificate */ static axis2_status_t axis2_libcurl_set_ssl_options( CURL *handler, const axutil_env_t * env, axis2_msg_ctx_t * msg_ctx) { axutil_property_t *property = NULL; axis2_char_t *verify_peer = NULL; axis2_char_t *verify_host = NULL; property = axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_SSL_VERIFY_PEER); if (property) { verify_peer = (axis2_char_t *)axutil_property_get_value(property, env); } if (verify_peer) { if (0 == axutil_strcasecmp(verify_peer, AXIS2_VALUE_TRUE)) { curl_easy_setopt(handler, CURLOPT_SSL_VERIFYPEER, 1); } else { curl_easy_setopt(handler, CURLOPT_SSL_VERIFYPEER, 0); } } property = axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_SSL_VERIFY_HOST); if (property) { verify_host = (axis2_char_t *)axutil_property_get_value(property, env); } if (verify_host) { curl_easy_setopt(handler, CURLOPT_SSL_VERIFYHOST, AXIS2_ATOI(verify_host)); } return AXIS2_SUCCESS; } /** * axis2_libcurl_set_connection_options maps connection AXIS2/C options to * libcURL options. * CURLOPT_CONNECTTIMEOUT_MS - long connection timeout in milliseconds * CURLOPT_TIMEOUT_MS - long transfer timeout in milliseconds */ static axis2_status_t axis2_libcurl_set_connection_options( CURL *handler, const axutil_env_t * env, axis2_msg_ctx_t * msg_ctx) { axutil_property_t *property = NULL; long long_property_value = 0; /* check if timeout has been set by user using options * with axis2_options_set_timeout_in_milli_seconds */ property = axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_HTTP_CONNECTION_TIMEOUT); if (property) { axis2_char_t *value = axutil_property_get_value(property, env); if (value) { long_property_value = AXIS2_ATOI(value); curl_easy_setopt(handler, CURLOPT_CONNECTTIMEOUT_MS, long_property_value); } } property = axis2_msg_ctx_get_property(msg_ctx, env, AXIS2_HTTP_SO_TIMEOUT); if (property) { axis2_char_t *value = axutil_property_get_value(property, env); if (value) { long_property_value = AXIS2_ATOI(value); curl_easy_setopt(handler, CURLOPT_TIMEOUT_MS, long_property_value); } } return AXIS2_SUCCESS; } /** * axis2_libcurl_set_options maps the AXIS2/C options to libcURL options. */ static axis2_status_t axis2_libcurl_set_options( CURL *handler, const axutil_env_t * env, axis2_msg_ctx_t * msg_ctx) { if (axis2_libcurl_set_auth_options(handler, env, msg_ctx) != AXIS2_SUCCESS) { return AXIS2_FAILURE; } if (axis2_libcurl_set_proxy_options(handler, env, msg_ctx) != AXIS2_SUCCESS) { return AXIS2_FAILURE; } if (axis2_libcurl_set_ssl_options(handler, env, msg_ctx) != AXIS2_SUCCESS) { return AXIS2_FAILURE; } if (axis2_libcurl_set_connection_options(handler, env, msg_ctx) != AXIS2_SUCCESS) { return AXIS2_FAILURE; } return AXIS2_SUCCESS; } #endif /* AXIS2_LIBCURL_ENABLED */
apache-2.0
rklabs/folly
folly/portability/Sockets.cpp
1
11891
/* * Copyright 2016-present Facebook, 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. */ #include <folly/portability/Sockets.h> #ifdef _MSC_VER #include <errno.h> #include <fcntl.h> #include <event2/util.h> // @manual #include <MSWSock.h> // @manual #include <folly/ScopeGuard.h> namespace folly { namespace portability { namespace sockets { // We have to startup WSA. static struct FSPInit { FSPInit() { WSADATA dat; WSAStartup(MAKEWORD(2, 2), &dat); } ~FSPInit() { WSACleanup(); } } fspInit; bool is_fh_socket(int fh) { SOCKET h = fd_to_socket(fh); constexpr long kDummyEvents = 0xABCDEF12; WSANETWORKEVENTS e; e.lNetworkEvents = kDummyEvents; WSAEnumNetworkEvents(h, nullptr, &e); return e.lNetworkEvents != kDummyEvents; } SOCKET fd_to_socket(int fd) { if (fd == -1) { return INVALID_SOCKET; } // We do this in a roundabout way to allow us to compile even if // we're doing a bit of trickery to ensure that things aren't // being implicitly converted to a SOCKET by temporarily // adjusting the windows headers to define SOCKET as a // structure. static_assert(sizeof(HANDLE) == sizeof(SOCKET), "Handle size mismatch."); HANDLE tmp = (HANDLE)_get_osfhandle(fd); return *(SOCKET*)&tmp; } int socket_to_fd(SOCKET s) { if (s == INVALID_SOCKET) { return -1; } return _open_osfhandle((intptr_t)s, O_RDWR | O_BINARY); } int translate_wsa_error(int wsaErr) { switch (wsaErr) { case WSAEWOULDBLOCK: return EAGAIN; default: return wsaErr; } } template <class R, class F, class... Args> static R wrapSocketFunction(F f, int s, Args... args) { SOCKET h = fd_to_socket(s); R ret = f(h, args...); errno = translate_wsa_error(WSAGetLastError()); return ret; } int accept(int s, struct sockaddr* addr, socklen_t* addrlen) { return socket_to_fd(wrapSocketFunction<SOCKET>(::accept, s, addr, addrlen)); } int bind(int s, const struct sockaddr* name, socklen_t namelen) { return wrapSocketFunction<int>(::bind, s, name, namelen); } int connect(int s, const struct sockaddr* name, socklen_t namelen) { auto r = wrapSocketFunction<int>(::connect, s, name, namelen); if (r == -1 && WSAGetLastError() == WSAEWOULDBLOCK) { errno = EINPROGRESS; } return r; } int getpeername(int s, struct sockaddr* name, socklen_t* namelen) { return wrapSocketFunction<int>(::getpeername, s, name, namelen); } int getsockname(int s, struct sockaddr* name, socklen_t* namelen) { return wrapSocketFunction<int>(::getsockname, s, name, namelen); } int getsockopt(int s, int level, int optname, char* optval, socklen_t* optlen) { return getsockopt(s, level, optname, (void*)optval, optlen); } int getsockopt(int s, int level, int optname, void* optval, socklen_t* optlen) { auto ret = wrapSocketFunction<int>( ::getsockopt, s, level, optname, (char*)optval, (int*)optlen); if (optname == TCP_NODELAY && *optlen == 1) { // Windows is weird about this value, and documents it as a // BOOL (ie. int) but expects the variable to be bool (1-byte), // so we get to adapt the interface to work that way. *(int*)optval = *(uint8_t*)optval; *optlen = sizeof(int); } return ret; } int inet_aton(const char* cp, struct in_addr* inp) { inp->s_addr = inet_addr(cp); return inp->s_addr == INADDR_NONE ? 0 : 1; } const char* inet_ntop(int af, const void* src, char* dst, socklen_t size) { return ::inet_ntop(af, (char*)src, dst, size_t(size)); } int listen(int s, int backlog) { return wrapSocketFunction<int>(::listen, s, backlog); } int poll(struct pollfd fds[], nfds_t nfds, int timeout) { // TODO: Allow both file descriptors and SOCKETs in this. for (int i = 0; i < nfds; i++) { fds[i].fd = fd_to_socket((int)fds[i].fd); } return ::WSAPoll(fds, (ULONG)nfds, timeout); } ssize_t recv(int s, void* buf, size_t len, int flags) { if ((flags & MSG_DONTWAIT) == MSG_DONTWAIT) { flags &= ~MSG_DONTWAIT; u_long pendingRead = 0; if (ioctlsocket(fd_to_socket(s), FIONREAD, &pendingRead)) { errno = translate_wsa_error(WSAGetLastError()); return -1; } fd_set readSet; FD_ZERO(&readSet); FD_SET(fd_to_socket(s), &readSet); timeval timeout{0, 0}; auto ret = select(1, &readSet, nullptr, nullptr, &timeout); if (ret == 0) { errno = EWOULDBLOCK; return -1; } } return wrapSocketFunction<ssize_t>(::recv, s, (char*)buf, (int)len, flags); } ssize_t recv(int s, char* buf, int len, int flags) { return recv(s, (void*)buf, (size_t)len, flags); } ssize_t recv(int s, void* buf, int len, int flags) { return recv(s, (void*)buf, (size_t)len, flags); } ssize_t recvfrom( int s, void* buf, size_t len, int flags, struct sockaddr* from, socklen_t* fromlen) { if ((flags & MSG_TRUNC) == MSG_TRUNC) { SOCKET h = fd_to_socket(s); WSABUF wBuf{}; wBuf.buf = (CHAR*)buf; wBuf.len = (ULONG)len; WSAMSG wMsg{}; wMsg.dwBufferCount = 1; wMsg.lpBuffers = &wBuf; wMsg.name = from; if (fromlen != nullptr) { wMsg.namelen = *fromlen; } // WSARecvMsg is an extension, so we don't get // the convenience of being able to call it directly, even though // WSASendMsg is part of the normal API -_-... LPFN_WSARECVMSG WSARecvMsg; GUID WSARecgMsg_GUID = WSAID_WSARECVMSG; DWORD recMsgBytes; WSAIoctl( h, SIO_GET_EXTENSION_FUNCTION_POINTER, &WSARecgMsg_GUID, sizeof(WSARecgMsg_GUID), &WSARecvMsg, sizeof(WSARecvMsg), &recMsgBytes, nullptr, nullptr); DWORD bytesReceived; int res = WSARecvMsg(h, &wMsg, &bytesReceived, nullptr, nullptr); errno = translate_wsa_error(WSAGetLastError()); if (res == 0) { return bytesReceived; } if (fromlen != nullptr) { *fromlen = wMsg.namelen; } if ((wMsg.dwFlags & MSG_TRUNC) == MSG_TRUNC) { return wBuf.len + 1; } return -1; } return wrapSocketFunction<ssize_t>( ::recvfrom, s, (char*)buf, (int)len, flags, from, (int*)fromlen); } ssize_t recvfrom( int s, char* buf, int len, int flags, struct sockaddr* from, socklen_t* fromlen) { return recvfrom(s, (void*)buf, (size_t)len, flags, from, fromlen); } ssize_t recvfrom( int s, void* buf, int len, int flags, struct sockaddr* from, socklen_t* fromlen) { return recvfrom(s, (void*)buf, (size_t)len, flags, from, fromlen); } ssize_t recvmsg(int s, struct msghdr* message, int /* flags */) { SOCKET h = fd_to_socket(s); // Don't currently support the name translation. if (message->msg_name != nullptr || message->msg_namelen != 0) { return (ssize_t)-1; } WSAMSG msg; msg.name = nullptr; msg.namelen = 0; msg.Control.buf = (CHAR*)message->msg_control; msg.Control.len = (ULONG)message->msg_controllen; msg.dwFlags = 0; msg.dwBufferCount = (DWORD)message->msg_iovlen; msg.lpBuffers = new WSABUF[message->msg_iovlen]; SCOPE_EXIT { delete[] msg.lpBuffers; }; for (size_t i = 0; i < message->msg_iovlen; i++) { msg.lpBuffers[i].buf = (CHAR*)message->msg_iov[i].iov_base; msg.lpBuffers[i].len = (ULONG)message->msg_iov[i].iov_len; } // WSARecvMsg is an extension, so we don't get // the convenience of being able to call it directly, even though // WSASendMsg is part of the normal API -_-... LPFN_WSARECVMSG WSARecvMsg; GUID WSARecgMsg_GUID = WSAID_WSARECVMSG; DWORD recMsgBytes; WSAIoctl( h, SIO_GET_EXTENSION_FUNCTION_POINTER, &WSARecgMsg_GUID, sizeof(WSARecgMsg_GUID), &WSARecvMsg, sizeof(WSARecvMsg), &recMsgBytes, nullptr, nullptr); DWORD bytesReceived; int res = WSARecvMsg(h, &msg, &bytesReceived, nullptr, nullptr); errno = translate_wsa_error(WSAGetLastError()); return res == 0 ? (ssize_t)bytesReceived : -1; } ssize_t send(int s, const void* buf, size_t len, int flags) { return wrapSocketFunction<ssize_t>( ::send, s, (const char*)buf, (int)len, flags); } ssize_t send(int s, const char* buf, int len, int flags) { return send(s, (const void*)buf, (size_t)len, flags); } ssize_t send(int s, const void* buf, int len, int flags) { return send(s, (const void*)buf, (size_t)len, flags); } ssize_t sendmsg(int s, const struct msghdr* message, int /* flags */) { SOCKET h = fd_to_socket(s); // Unfortunately, WSASendMsg requires the socket to have been opened // as either SOCK_DGRAM or SOCK_RAW, but sendmsg has no such requirement, // so we have to implement it based on send instead :( ssize_t bytesSent = 0; for (size_t i = 0; i < message->msg_iovlen; i++) { int r = -1; if (message->msg_name != nullptr) { r = ::sendto( h, (const char*)message->msg_iov[i].iov_base, (int)message->msg_iov[i].iov_len, message->msg_flags, (const sockaddr*)message->msg_name, (int)message->msg_namelen); } else { r = ::send( h, (const char*)message->msg_iov[i].iov_base, (int)message->msg_iov[i].iov_len, message->msg_flags); } if (r == -1 || size_t(r) != message->msg_iov[i].iov_len) { errno = translate_wsa_error(WSAGetLastError()); if (WSAGetLastError() == WSAEWOULDBLOCK && bytesSent > 0) { return bytesSent; } return -1; } bytesSent += r; } return bytesSent; } ssize_t sendto( int s, const void* buf, size_t len, int flags, const sockaddr* to, socklen_t tolen) { return wrapSocketFunction<ssize_t>( ::sendto, s, (const char*)buf, (int)len, flags, to, (int)tolen); } ssize_t sendto( int s, const char* buf, int len, int flags, const sockaddr* to, socklen_t tolen) { return sendto(s, (const void*)buf, (size_t)len, flags, to, tolen); } ssize_t sendto( int s, const void* buf, int len, int flags, const sockaddr* to, socklen_t tolen) { return sendto(s, buf, (size_t)len, flags, to, tolen); } int setsockopt( int s, int level, int optname, const void* optval, socklen_t optlen) { if (optname == SO_REUSEADDR) { // We don't have an equivelent to the Linux & OSX meaning of this // on Windows, so ignore it. return 0; } else if (optname == SO_REUSEPORT) { // Windows's SO_REUSEADDR option is closer to SO_REUSEPORT than // it is to the Linux & OSX meaning of SO_REUSEADDR. return -1; } return wrapSocketFunction<int>( ::setsockopt, s, level, optname, (char*)optval, optlen); } int setsockopt( int s, int level, int optname, const char* optval, socklen_t optlen) { return setsockopt(s, level, optname, (const void*)optval, optlen); } int shutdown(int s, int how) { return wrapSocketFunction<int>(::shutdown, s, how); } int socket(int af, int type, int protocol) { return socket_to_fd(::socket(af, type, protocol)); } int socketpair(int domain, int type, int protocol, int sv[2]) { if (domain != PF_UNIX || type != SOCK_STREAM || protocol != 0) { return -1; } intptr_t pair[2]; auto r = evutil_socketpair(AF_INET, type, protocol, pair); if (r == -1) { return r; } sv[0] = _open_osfhandle(pair[0], O_RDWR | O_BINARY); sv[1] = _open_osfhandle(pair[1], O_RDWR | O_BINARY); return 0; } } } } #endif
apache-2.0
aws/aws-sdk-cpp
aws-cpp-sdk-wafv2/source/model/RuleActionOverride.cpp
1
1301
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/wafv2/model/RuleActionOverride.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace WAFV2 { namespace Model { RuleActionOverride::RuleActionOverride() : m_nameHasBeenSet(false), m_actionToUseHasBeenSet(false) { } RuleActionOverride::RuleActionOverride(JsonView jsonValue) : m_nameHasBeenSet(false), m_actionToUseHasBeenSet(false) { *this = jsonValue; } RuleActionOverride& RuleActionOverride::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Name")) { m_name = jsonValue.GetString("Name"); m_nameHasBeenSet = true; } if(jsonValue.ValueExists("ActionToUse")) { m_actionToUse = jsonValue.GetObject("ActionToUse"); m_actionToUseHasBeenSet = true; } return *this; } JsonValue RuleActionOverride::Jsonize() const { JsonValue payload; if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } if(m_actionToUseHasBeenSet) { payload.WithObject("ActionToUse", m_actionToUse.Jsonize()); } return payload; } } // namespace Model } // namespace WAFV2 } // namespace Aws
apache-2.0
nedmech/qlcplus
ui/src/virtualconsole/vcclock.cpp
1
12353
/* Q Light Controller Plus vcclock.cpp Copyright (c) Massimo Callegari 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.txt 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 <QXmlStreamReader> #include <QXmlStreamWriter> #include <QDateTime> #include <QStyle> #include <QtGui> #include "qlcfile.h" #include "vcclockproperties.h" #include "virtualconsole.h" #include "vcclock.h" #include "doc.h" #define KXMLQLCVCClockType "Type" #define KXMLQLCVCClockHours "Hours" #define KXMLQLCVCClockMinutes "Minutes" #define KXMLQLCVCClockSeconds "Seconds" #define KXMLQLCVCClockSchedule "Schedule" #define KXMLQLCVCClockScheduleFunc "Function" #define KXMLQLCVCClockScheduleTime "Time" VCClock::VCClock(QWidget* parent, Doc* doc) : VCWidget(parent, doc) , m_clocktype(Clock) , m_scheduleIndex(-1) , m_hh(0) , m_mm(0) , m_ss(0) , m_targetTime(0) , m_currentTime(0) , m_isPaused(true) { /* Set the class name "VCClock" as the object name as well */ setObjectName(VCClock::staticMetaObject.className()); setType(VCWidget::ClockWidget); setCaption(""); resize(QSize(150, 50)); QFont font = qApp->font(); font.setBold(true); font.setPixelSize(28); setFont(font); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(slotUpdateTime())); timer->start(1000); } VCClock::~VCClock() { } void VCClock::slotModeChanged(Doc::Mode mode) { qDebug() << Q_FUNC_INFO; if (mode == Doc::Operate) { if (m_scheduleList.count() > 0) { QTime currTime = QDateTime::currentDateTime().time(); for(int i = 0; i < m_scheduleList.count(); i++) { VCClockSchedule sch = m_scheduleList.at(i); if (sch.time().time() >= currTime) { m_scheduleIndex = i; qDebug() << "VC Clock set to play index:" << i; break; } } } } VCWidget::slotModeChanged(mode); } /********************************************************************* * Type *********************************************************************/ void VCClock::setClockType(VCClock::ClockType type) { m_clocktype = type; update(); } VCClock::ClockType VCClock::clockType() { return m_clocktype; } QString VCClock::typeToString(VCClock::ClockType type) { if (type == Stopwatch) return "Stopwatch"; else if (type == Countdown) return "Countdown"; else return "Clock"; } VCClock::ClockType VCClock::stringToType(QString str) { if (str == "Stopwatch") return Stopwatch; else if (str == "Countdown") return Countdown; else return Clock; } void VCClock::addSchedule(VCClockSchedule schedule) { qDebug() << Q_FUNC_INFO << "--- ID:" << schedule.function() << ", time:" << schedule.time().time().toString(); if (schedule.function() != Function::invalidId()) m_scheduleList.append(schedule); qSort(m_scheduleList); } void VCClock::removeSchedule(int index) { if (index < 0 || index > m_scheduleList.count()) return; m_scheduleList.removeAt(index); } void VCClock::removeAllSchedule() { m_scheduleList.clear(); } QList<VCClockSchedule> VCClock::schedules() { return m_scheduleList; } FunctionParent VCClock::functionParent() const { return FunctionParent(FunctionParent::AutoVCWidget, id()); } void VCClock::setCountdown(int h, int m, int s) { m_hh = h; m_mm = m; m_ss = s; m_targetTime = (m_hh * 3600) + (m_mm * 60) + m_ss; m_currentTime = m_targetTime; } void VCClock::resetTime() { if (m_clocktype == Stopwatch) m_currentTime = 0; else if (m_clocktype == Countdown) m_currentTime = m_targetTime; update(); } void VCClock::slotUpdateTime() { if (mode() == Doc::Operate) { if (m_isPaused == false) { if (m_clocktype == Stopwatch) m_currentTime++; else if (m_clocktype == Countdown && m_currentTime > 0) m_currentTime--; } else { if (m_clocktype == Clock) { if (m_scheduleIndex != -1 && m_scheduleIndex < m_scheduleList.count()) { QTime currTime = QDateTime::currentDateTime().time(); VCClockSchedule sch = m_scheduleList.at(m_scheduleIndex); //qDebug() << "--- > currTime:" << currTime.toString() << ", schTime:" << sch.time().time().toString(); if (sch.time().time().toString() == currTime.toString()) { quint32 fid = sch.function(); Function *func = m_doc->function(fid); if (func != NULL) { func->start(m_doc->masterTimer(), functionParent()); qDebug() << "VC Clock starting function:" << func->name(); } m_scheduleIndex++; if (m_scheduleIndex == m_scheduleList.count()) m_scheduleIndex = 0; } } } } } update(); } /***************************************************************************** * Clipboard *****************************************************************************/ VCWidget* VCClock::createCopy(VCWidget* parent) { Q_ASSERT(parent != NULL); VCClock* clock = new VCClock(parent, m_doc); if (clock->copyFrom(this) == false) { delete clock; clock = NULL; } return clock; } /***************************************************************************** * Properties *****************************************************************************/ void VCClock::editProperties() { VCClockProperties vccp(this, m_doc); if (vccp.exec() == QDialog::Rejected) return; m_doc->setModified(); } /***************************************************************************** * Load & Save *****************************************************************************/ bool VCClock::loadXML(QXmlStreamReader &root) { if (root.name() != KXMLQLCVCClock) { qWarning() << Q_FUNC_INFO << "Clock node not found"; return false; } QXmlStreamAttributes attrs = root.attributes(); if (attrs.hasAttribute(KXMLQLCVCClockType)) { setClockType(stringToType(attrs.value(KXMLQLCVCClockType).toString())); if (clockType() == Countdown) { int h = 0, m = 0, s = 0; if (attrs.hasAttribute(KXMLQLCVCClockHours)) h = attrs.value(KXMLQLCVCClockHours).toString().toInt(); if (attrs.hasAttribute(KXMLQLCVCClockMinutes)) m = attrs.value(KXMLQLCVCClockMinutes).toString().toInt(); if (attrs.hasAttribute(KXMLQLCVCClockSeconds)) s = attrs.value(KXMLQLCVCClockSeconds).toString().toInt(); setCountdown(h, m ,s); } } /* Widget commons */ loadXMLCommon(root); /* Children */ while (root.readNextStartElement()) { if (root.name() == KXMLQLCWindowState) { int x = 0, y = 0, w = 0, h = 0; bool visible = false; loadXMLWindowState(root, &x, &y, &w, &h, &visible); setGeometry(x, y, w, h); } else if (root.name() == KXMLQLCVCWidgetAppearance) { loadXMLAppearance(root); } else if (root.name() == KXMLQLCVCClockSchedule) { VCClockSchedule sch; if (sch.loadXML(root) == true) addSchedule(sch); } else { qWarning() << Q_FUNC_INFO << "Unknown clock tag:" << root.name().toString(); root.skipCurrentElement(); } } return true; } bool VCClock::saveXML(QXmlStreamWriter *doc) { Q_ASSERT(doc != NULL); /* VC Clock entry */ doc->writeStartElement(KXMLQLCVCClock); /* Type */ ClockType type = clockType(); doc->writeAttribute(KXMLQLCVCClockType, typeToString(type)); if (type == Countdown) { doc->writeAttribute(KXMLQLCVCClockHours, QString::number(getHours())); doc->writeAttribute(KXMLQLCVCClockMinutes, QString::number(getMinutes())); doc->writeAttribute(KXMLQLCVCClockSeconds, QString::number(getSeconds())); } saveXMLCommon(doc); /* Window state */ saveXMLWindowState(doc); /* Appearance */ saveXMLAppearance(doc); foreach(VCClockSchedule sch, schedules()) sch.saveXML(doc); /* End the <Clock> tag */ doc->writeEndElement(); return true; } /**************************************************************************** * Drawing ****************************************************************************/ void VCClock::paintEvent(QPaintEvent* e) { QPainter painter(this); if (clockType() == Clock) { QDateTime currTime = QDateTime::currentDateTime(); style()->drawItemText(&painter, rect(), Qt::AlignCenter | Qt::TextWordWrap, palette(), true, currTime.time().toString(), foregroundRole()); } else { quint32 secTime = m_currentTime; uint h, m; h = secTime / 3600; secTime -= (h * 3600); m = secTime / 60; secTime -= (m * 60); style()->drawItemText(&painter, rect(), Qt::AlignCenter | Qt::TextWordWrap, palette(), true, QString("%1:%2:%3").arg(h, 2, 10, QChar('0')) .arg(m, 2, 10, QChar('0')).arg(secTime, 2, 10, QChar('0')), foregroundRole()); } painter.end(); VCWidget::paintEvent(e); } void VCClock::mousePressEvent(QMouseEvent *e) { if (mode() == Doc::Design) { VCWidget::mousePressEvent(e); return; } if (e->button() == Qt::RightButton) { if (clockType() == Stopwatch) m_currentTime = 0; else if (clockType() == Countdown) m_currentTime = m_targetTime; update(); } else if (e->button() == Qt::LeftButton) { if (clockType() == Stopwatch || clockType() == Countdown) m_isPaused = !m_isPaused; update(); } VCWidget::mousePressEvent(e); } /********************************************************************* * VCClockSchedule Class methods *********************************************************************/ bool VCClockSchedule::operator <(const VCClockSchedule &sch) const { if (sch.time() < time()) return false; return true; } bool VCClockSchedule::loadXML(QXmlStreamReader &root) { if (root.name() != KXMLQLCVCClockSchedule) { qWarning() << Q_FUNC_INFO << "Clock Schedule node not found"; return false; } QXmlStreamAttributes attrs = root.attributes(); if (attrs.hasAttribute(KXMLQLCVCClockScheduleFunc)) { setFunction(attrs.value(KXMLQLCVCClockScheduleFunc).toString().toUInt()); if (attrs.hasAttribute(KXMLQLCVCClockScheduleTime)) { QDateTime dt; dt.setTime(QTime::fromString(attrs.value(KXMLQLCVCClockScheduleTime).toString(), "HH:mm:ss")); setTime(dt); } } root.skipCurrentElement(); return true; } bool VCClockSchedule::saveXML(QXmlStreamWriter *doc) { /* Schedule tag */ doc->writeStartElement(KXMLQLCVCClockSchedule); /* Schedule function */ doc->writeAttribute(KXMLQLCVCClockScheduleFunc, QString::number(function())); /* Schedule time */ doc->writeAttribute(KXMLQLCVCClockScheduleTime, time().time().toString()); doc->writeEndElement(); return true; }
apache-2.0
svn2github/ImageMagick
MagickCore/timer.c
1
18345
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT IIIII M M EEEEE RRRR % % T I MM MM E R R % % T I M M M EEE RRRR % % T I M M E R R % % T IIIII M M EEEEE R R % % % % % % MagickCore Timing Methods % % % % Software Design % % Cristy % % January 1993 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Contributed by Bill Radcliffe and Bob Friesenhahn. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/timer.h" /* Define declarations. */ #if !defined(CLOCKS_PER_SEC) #define CLOCKS_PER_SEC 100 #endif /* Forward declarations. */ static double UserTime(void); static void StopTimer(TimerInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e T i m e r I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireTimerInfo() initializes the TimerInfo structure. It effectively % creates a stopwatch and starts it. % % The format of the AcquireTimerInfo method is: % % TimerInfo *AcquireTimerInfo(void) % */ MagickExport TimerInfo *AcquireTimerInfo(void) { TimerInfo *timer_info; timer_info=(TimerInfo *) AcquireMagickMemory(sizeof(*timer_info)); if (timer_info == (TimerInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireString"); (void) ResetMagickMemory(timer_info,0,sizeof(*timer_info)); timer_info->signature=MagickSignature; GetTimerInfo(timer_info); return(timer_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t i n u e T i m e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContinueTimer() resumes a stopped stopwatch. The stopwatch continues % counting from the last StartTimer() onwards. % % The format of the ContinueTimer method is: % % MagickBooleanType ContinueTimer(TimerInfo *time_info) % % A description of each parameter follows. % % o time_info: Time statistics structure. % */ MagickExport MagickBooleanType ContinueTimer(TimerInfo *time_info) { assert(time_info != (TimerInfo *) NULL); assert(time_info->signature == MagickSignature); if (time_info->state == UndefinedTimerState) return(MagickFalse); if (time_info->state == StoppedTimerState) { time_info->user.total-=time_info->user.stop-time_info->user.start; time_info->elapsed.total-=time_info->elapsed.stop- time_info->elapsed.start; } time_info->state=RunningTimerState; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T i m e r I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyTimerInfo() zeros memory associated with the TimerInfo structure. % % The format of the DestroyTimerInfo method is: % % TimerInfo *DestroyTimerInfo(TimerInfo *timer_info) % % A description of each parameter follows: % % o timer_info: The cipher context. % */ MagickExport TimerInfo *DestroyTimerInfo(TimerInfo *timer_info) { assert(timer_info != (TimerInfo *) NULL); assert(timer_info->signature == MagickSignature); timer_info->signature=(~MagickSignature); timer_info=(TimerInfo *) RelinquishMagickMemory(timer_info); return(timer_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E l a p s e d T i m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ElapsedTime() returns the elapsed time (in seconds) since the last call to % StartTimer(). % % The format of the ElapsedTime method is: % % double ElapsedTime() % */ static double ElapsedTime(void) { #if defined(MAGICKCORE_HAVE_TIMES) struct tms timer; return((double) times(&timer)/CLOCKS_PER_SEC); #else #if defined(MAGICKCORE_WINDOWS_SUPPORT) return(NTElapsedTime()); #else return((double) clock()/CLOCKS_PER_SEC); #endif #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t E l a p s e d T i m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetElapsedTime() returns the elapsed time (in seconds) passed between the % start and stop events. If the stopwatch is still running, it is stopped % first. % % The format of the GetElapsedTime method is: % % double GetElapsedTime(TimerInfo *time_info) % % A description of each parameter follows. % % o time_info: Timer statistics structure. % */ MagickExport double GetElapsedTime(TimerInfo *time_info) { assert(time_info != (TimerInfo *) NULL); assert(time_info->signature == MagickSignature); if (time_info->state == UndefinedTimerState) return(0.0); if (time_info->state == RunningTimerState) StopTimer(time_info); return(time_info->elapsed.total); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T i m e r I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetTimerInfo() initializes the TimerInfo structure. % % The format of the GetTimerInfo method is: % % void GetTimerInfo(TimerInfo *time_info) % % A description of each parameter follows. % % o time_info: Timer statistics structure. % */ MagickExport void GetTimerInfo(TimerInfo *time_info) { /* Create a stopwatch and start it. */ assert(time_info != (TimerInfo *) NULL); (void) ResetMagickMemory(time_info,0,sizeof(*time_info)); time_info->state=UndefinedTimerState; time_info->signature=MagickSignature; StartTimer(time_info,MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t U s e r T i m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetUserTime() returns the User time (user and system) by the operating % system (in seconds) between the start and stop events. If the stopwatch is % still running, it is stopped first. % % The format of the GetUserTime method is: % % double GetUserTime(TimerInfo *time_info) % % A description of each parameter follows. % % o time_info: Timer statistics structure. % */ MagickExport double GetUserTime(TimerInfo *time_info) { assert(time_info != (TimerInfo *) NULL); assert(time_info->signature == MagickSignature); if (time_info->state == UndefinedTimerState) return(0.0); if (time_info->state == RunningTimerState) StopTimer(time_info); return(time_info->user.total); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t T i m e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetTimer() resets the stopwatch. % % The format of the ResetTimer method is: % % void ResetTimer(TimerInfo *time_info) % % A description of each parameter follows. % % o time_info: Timer statistics structure. % */ MagickExport void ResetTimer(TimerInfo *time_info) { assert(time_info != (TimerInfo *) NULL); assert(time_info->signature == MagickSignature); StopTimer(time_info); time_info->elapsed.stop=0.0; time_info->user.stop=0.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S t a r t T i m e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StartTimer() starts the stopwatch. % % The format of the StartTimer method is: % % void StartTimer(TimerInfo *time_info,const MagickBooleanType reset) % % A description of each parameter follows. % % o time_info: Timer statistics structure. % % o reset: If reset is MagickTrue, then the stopwatch is reset prior to % starting. If reset is MagickFalse, then timing is continued without % resetting the stopwatch. % */ MagickExport void StartTimer(TimerInfo *time_info,const MagickBooleanType reset) { assert(time_info != (TimerInfo *) NULL); assert(time_info->signature == MagickSignature); if (reset != MagickFalse) { /* Reset the stopwatch before starting it. */ time_info->user.total=0.0; time_info->elapsed.total=0.0; } if (time_info->state != RunningTimerState) { time_info->elapsed.start=ElapsedTime(); time_info->user.start=UserTime(); } time_info->state=RunningTimerState; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S t o p T i m e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StopTimer() stops the stopwatch. % % The format of the StopTimer method is: % % void StopTimer(TimerInfo *time_info) % % A description of each parameter follows. % % o time_info: Timer statistics structure. % */ static void StopTimer(TimerInfo *time_info) { assert(time_info != (TimerInfo *) NULL); assert(time_info->signature == MagickSignature); time_info->elapsed.stop=ElapsedTime(); time_info->user.stop=UserTime(); if (time_info->state == RunningTimerState) { time_info->user.total+=time_info->user.stop- time_info->user.start+MagickEpsilon; time_info->elapsed.total+=time_info->elapsed.stop- time_info->elapsed.start+MagickEpsilon; } time_info->state=StoppedTimerState; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + U s e r T i m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UserTime() returns the total time the process has been scheduled (in % seconds) since the last call to StartTimer(). % % The format of the UserTime method is: % % double UserTime() % */ static double UserTime(void) { #if defined(MAGICKCORE_HAVE_TIMES) struct tms timer; (void) times(&timer); return((double) (timer.tms_utime+timer.tms_stime)/CLOCKS_PER_SEC); #else #if defined(MAGICKCORE_WINDOWS_SUPPORT) return(NTUserTime()); #else return((double) clock()/CLOCKS_PER_SEC); #endif #endif }
apache-2.0
svagionitis/aws-sdk-cpp
aws-cpp-sdk-servicecatalog/source/model/TerminateProvisionedProductResult.cpp
2
1509
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/servicecatalog/model/TerminateProvisionedProductResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::ServiceCatalog::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; TerminateProvisionedProductResult::TerminateProvisionedProductResult() { } TerminateProvisionedProductResult::TerminateProvisionedProductResult(const AmazonWebServiceResult<JsonValue>& result) { *this = result; } TerminateProvisionedProductResult& TerminateProvisionedProductResult::operator =(const AmazonWebServiceResult<JsonValue>& result) { const JsonValue& jsonValue = result.GetPayload(); if(jsonValue.ValueExists("RecordDetail")) { m_recordDetail = jsonValue.GetObject("RecordDetail"); } return *this; }
apache-2.0
google/earthenterprise
earth_enterprise/src/fusion/fusionui/AssetManager.cpp
2
63028
// Copyright 2017 Google Inc. // Copyright 2020 The Open GEE Contributors // // 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 "fusion/fusionui/AssetManager.h" #include "Qt/qobjectdefs.h" #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <iostream> #include <Qt/qstring.h> #include <Qt/qstringlist.h> #include <Qt/qcombobox.h> #include <Qt/qapplication.h> #include <Qt/qmessagebox.h> #include <Qt/qpixmap.h> #include <Qt/q3header.h> using QHeader = Q3Header; #include <Qt/qprogressdialog.h> #include <Qt/qlineedit.h> #include <Qt/qtabwidget.h> #include <Qt/qimage.h> #include <Qt/qpushbutton.h> #include <Qt/qinputdialog.h> #include <Qt/qlayout.h> #include <Qt/qpainter.h> #include <Qt/qcheckbox.h> #include <Qt/qsplitter.h> #include <Qt/q3widgetstack.h> using QWidgetStack = Q3WidgetStack; #include <Qt/qcursor.h> #include <Qt/qthread.h> #include <Qt/q3dragobject.h> using QImageDrag = Q3ImageDrag; #include <Qt/q3mimefactory.h> using QMimeSourceFactory = Q3MimeSourceFactory; #include "fusion/autoingest/plugins/RasterProductAsset.h" #include "fusion/autoingest/plugins/MercatorRasterProductAsset.h" #include "fusion/autoingest/plugins/RasterProjectAsset.h" #include "fusion/autoingest/plugins/MercatorRasterProjectAsset.h" #include "fusion/autoingest/plugins/VectorProductAsset.h" #include "fusion/autoingest/plugins/VectorProjectAsset.h" #include "fusion/autoingest/plugins/VectorLayerXAsset.h" #include "fusion/autoingest/plugins/MapLayerAsset.h" #include "fusion/autoingest/plugins/MapProjectAsset.h" #include "fusion/autoingest/plugins/MapDatabaseAsset.h" #include "fusion/autoingest/plugins/MercatorMapDatabaseAsset.h" #include "fusion/autoingest/plugins/SourceAsset.h" #include "fusion/autoingest/plugins/DatabaseAsset.h" #include "fusion/autoingest/plugins/KMLProjectAsset.h" #include "fusion/autoingest/plugins/GEDBAsset.h" #include "fusion/autoingest/.idl/ServerCombination.h" #include "fusion/autoingest/.idl/gstProvider.h" #include "fusion/fusionui/AssetBase.h" #include "fusion/fusionui/AssetDisplayHelper.h" #include "fusion/fusionui/Preferences.h" #include "fusion/fusionui/AssetVersionProperties.h" #include "fusion/fusionui/AssetIconView.h" #include "fusion/fusionui/AssetTableView.h" #include "fusion/fusionui/AssetProperties.h" #include "fusion/fusionui/SourceFileDialog.h" #include "fusion/fusionui/ImageryAsset.h" #include "fusion/fusionui/MercatorImageryAsset.h" #include "fusion/fusionui/TerrainAsset.h" #include "fusion/fusionui/VectorAsset.h" #include "fusion/fusionui/SystemListener.h" #include "fusion/fusionui/MainWindow.h" #include "fusion/fusionui/Database.h" #include "fusion/fusionui/NewAsset.h" #include "fusion/fusionui/MapLayer.h" #include "fusion/fusionui/MapProject.h" #include "fusion/fusionui/MapDatabase.h" #include "fusion/fusionui/MercatorMapDatabase.h" #include "fusion/fusionui/ImageryProject.h" #include "fusion/fusionui/MercatorImageryProject.h" #include "fusion/fusionui/KMLProject.h" #include "fusion/fusionui/VectorLayer.h" #include "fusion/fusionui/VectorProject.h" #include "fusion/fusionui/TerrainProject.h" #include "fusion/fusionui/PushDatabaseDialog.h" #include "fusion/fusionui/PublishDatabaseDialog.h" #include "fusion/fusionui/geGuiProgress.h" #include "fusion/fusionui/geGuiAuth.h" #include "fusion/gepublish/PublisherClient.h" #include "fusion/gst/gstAssetManager.h" #include "fusion/gst/gstRegistry.h" #include "fusion/fusionversion.h" #include "common/notify.h" #include <array> namespace { const char* const folder_closed_xpm[]={ "16 16 9 1", "g c #808080", "b c #c0c000", "e c #c0c0c0", "# c #000000", "c c #ffff00", ". c None", "a c #585858", "f c #a0a0a4", "d c #ffffff", "..###...........", ".#abc##.........", ".#daabc#####....", ".#ddeaabbccc#...", ".#dedeeabbbba...", ".#edeeeeaaaab#..", ".#deeeeeeefe#ba.", ".#eeeeeeefef#ba.", ".#eeeeeefeff#ba.", ".#eeeeefefff#ba.", ".##geefeffff#ba.", "...##gefffff#ba.", ".....##fffff#ba.", ".......##fff#b##", ".........##f#b##", "...........####." }; const char* const folder_open_xpm[]={ "16 16 11 1", "# c #000000", "g c #c0c0c0", "e c #303030", "a c #ffa858", "b c #808080", "d c #a0a0a4", "f c #585858", "c c #ffdca8", "h c #dcdcdc", "i c #ffffff", ". c None", "....###.........", "....#ab##.......", "....#acab####...", "###.#acccccca#..", "#ddefaaaccccca#.", "#bdddbaaaacccab#", ".eddddbbaaaacab#", ".#bddggdbbaaaab#", "..edgdggggbbaab#", "..#bgggghghdaab#", "...ebhggghicfab#", "....#edhhiiidab#", "......#egiiicfb#", "........#egiibb#", "..........#egib#", "............#ee#" }; QPixmap* folderClosed = 0; QPixmap* folderOpen = 0; class AssetFolder : public QListViewItem { public: AssetFolder(QListViewItem* parent, const gstAssetFolder& f); AssetFolder(Q3ListView* parent, const gstAssetFolder& f); const gstAssetFolder& getFolder() const { return folder; } void setOpen(bool m); void populate(); AssetFolder* newFolder(const QString& text, QString &error); int rtti() const { return type_; } private: gstAssetFolder folder; int type_; }; // ----------------------------------------------------------------------------- AssetFolder::AssetFolder(Q3ListView* parent, const gstAssetFolder& f) : QListViewItem(parent, f.name()), folder(f), type_(ASSET_MANAGER) { setPixmap(0, *folderClosed); setExpandable(true); } AssetFolder::AssetFolder(QListViewItem* parent, const gstAssetFolder& f) : QListViewItem(parent, f.name()), folder(f), type_(ASSET_FOLDER) { setPixmap(0, *folderClosed); setExpandable(f.getAssetFolders().size() != 0); setRenameEnabled(0, false); } void AssetFolder::setOpen(bool o) { // always clear out all children QListViewItem* item = firstChild(); while (item) { takeItem(item); delete item; item = firstChild(); } if (o && folder.getAssetFolders().size() != 0) { setPixmap(0, *folderOpen); populate(); } else { setPixmap(0, *folderClosed); } QListViewItem::setOpen(o); } void AssetFolder::populate() { std::vector<gstAssetFolder> folders = folder.getAssetFolders(); for (const auto& it : folders) { (void)new AssetFolder(this, it); } } AssetFolder* AssetFolder::newFolder(const QString& text, QString &error) { if (!folder.newFolder(text, error)) return NULL; if (!isExpandable()) setExpandable(true); // if the folder was already opened, we need to create the // AssetFolder object if (isOpen()) return new AssetFolder(this, folder.getChildFolder(text)); // however, if it is closed, the setOpen() call will see this // new directory and build the AssetFolder object, so we need to find it setOpen(true); QListViewItem* child = firstChild(); while (child) { if (child->text(0) == text) return dynamic_cast<AssetFolder*>(child); child = child->nextSibling(); } return NULL; } // ----------------------------------------------------------------------------- static QPixmap uic_load_pixmap_AssetManager(const QString& name) { const QMimeSource* m = QMimeSourceFactory::defaultFactory()->data(name); if (!m) return QPixmap(); QPixmap pix; QImageDrag::decode(m, pix); return pix; } bool DatabaseHasValidVersion(const Asset &asset) { for (const auto& version : asset->versions) { AssetVersion asset_version(version); if (asset_version->state != AssetDefs::Succeeded) continue; if (asset_version->subtype == kMapDatabaseSubtype) { MapDatabaseAssetVersion mdav(asset_version); if (!mdav->GetMapdbChild()) continue; } else if (asset_version->subtype == kMercatorMapDatabaseSubtype) { MercatorMapDatabaseAssetVersion mdav(asset_version); if (!mdav->GetMapdbChild()) continue; } else { DatabaseAssetVersion dav(asset_version); // Make sure it's a new database with a gedb child GEDBAssetVersion gedb(dav->GetGedbChild()); if (!gedb) continue; // Make sure that the gedb child has the newest config version if (!gedb->config._IsCurrentIdlVersion()) { continue; } } return true; } return false; } } // namespace // ----------------------------------------------------------------------------- const std::array<AssetDefs::Type,6> TypeSet = {{ AssetDefs::Invalid, AssetDefs::Vector, AssetDefs::Imagery, AssetDefs::Terrain, AssetDefs::Map, AssetDefs::Database }}; const std::array<std::string,5> SubTypeSet = {{ "", kResourceSubtype, kLayer, kProjectSubtype, kDatabaseSubtype }}; // ----------------------------------------------------------------------------- QString AssetManager::AssetRoot() { PrefsConfig prefs = Preferences::getConfig(); if (prefs.showFullAssetPath) { return QString(AssetDefs::AssetRoot().c_str()); } else { return QString("ASSET_ROOT"); } } // ----------------------------------------------------------------------------- std::vector<AssetAction*> AssetAction::all_actions; AssetAction::AssetAction(QObject* parent, AssetBase* asset_window) : QAction(parent), asset_window_(asset_window) { setText(asset_window->Name()); AssetDisplayHelper helper(asset_window->AssetType(), asset_window->AssetSubtype()); setIconSet(QIconSet(helper.GetPixmap())); connect(this, SIGNAL(activated()), asset_window, SLOT(showNormal())); connect(this, SIGNAL(activated()), asset_window, SLOT(raise())); connect(asset_window, SIGNAL(NameChanged(const QString&)), this, SLOT(NameChanged(const QString&))); connect(asset_window, SIGNAL(destroyed()), this, SLOT(Cleanup())); all_actions.push_back(this); } void AssetAction::NameChanged(const QString& text) { setText(text); } void AssetAction::Cleanup() { std::vector<AssetAction*>::iterator pos = std::find(all_actions.begin(), all_actions.end(), this); if (pos != all_actions.end()) all_actions.erase(pos); delete this; } QString AssetAction::Name() const { return asset_window_->Name(); } AssetAction* AssetAction::FindAsset(const QString& txt) { for (const auto& it : all_actions) { if (it->Name() == txt) return it; } return NULL; } bool AssetAction::OkToCloseAll() { for (const auto& it : all_actions) { if (!it->asset_window_->OkToQuit()) return false; } return true; } void AssetAction::CloseAll() { // make a copy of our asset window vector since deleting will // invalidate iterators on the original std::vector<AssetAction*> close_actions = all_actions; for (auto& it : close_actions) { if (it->asset_window_->OkToQuit()) { delete it->asset_window_; } else { // terminate at first failure return; } } } void AssetAction::Cascade(const QPoint& start_pos) { const int xoffset = 13; const int yoffset = 20; int x = start_pos.x() + xoffset; int y = start_pos.y() + yoffset; for (auto& it : all_actions) { it->asset_window_->move(x, y); it->asset_window_->showNormal(); it->asset_window_->raise(); x += xoffset; y += yoffset; } } //------------------------------------------------------------------------------ ServeThread::ServeThread(PublisherClient* publisher_client, const std::string& gedb_path) : publisher_client_(publisher_client), gedb_path_(gedb_path), retval_(false) { } ServeThread::~ServeThread() { } void ServeThread::start() { QThread::start(); } PushThread::PushThread(PublisherClient* publisher_client, const std::string& gedb_path) : ServeThread(publisher_client, gedb_path) { } void PushThread::run(void) { #if 1 retval_ = publisher_client_->PushDatabase(gedb_path_); #else // Note: can be used for testing. while (progress_->done() < progress_->total()) { notify(NFY_WARN, "PushThread: %zd/%zd", progress_->done(), progress_->total()); progress_->incrementDone(1); sleep(1); } retval_ = true; #endif emit sfinished(); } PublishThread::PublishThread(PublisherClient* publisher_client, const std::string& gedb_path, const std::string& target_path) : ServeThread(publisher_client, gedb_path), target_path_(target_path) { } void PublishThread::run(void) { retval_ = publisher_client_->PublishDatabase(gedb_path_, target_path_); emit sfinished(); } ServeAssistant::ServeAssistant(QProgressDialog* progress_dialog, geGuiProgress* progress, geGuiAuth* auth) : progress_dialog_(progress_dialog), progress_(progress), auth_(auth) { QObject::connect(&timer_, SIGNAL(timeout()), this, SLOT(Perform())); } ServeAssistant::~ServeAssistant() { } void ServeAssistant::Start() { timer_.start(100); } void ServeAssistant::Stop() { timer_.stop(); } void ServeAssistant::SetCanceled() { progress_->setCanceled(); } void ServeAssistant::Perform() { progress_dialog_->setMinimum(0); progress_dialog_->setMaximum(progress_->total()); progress_dialog_->setValue(progress_->done()); // Check to see if a request for user authentication has been made. // If so, pop up the dialog and signal when we are finished. // Note: IsRequestPending() has a mutex to prevent a race condition. if (auth_->IsRequestPending()) { auth_->ExecAndSignal(); } } //------------------------------------------------------------------------------ AssetManager* AssetManager::self = NULL; std::string AssetManager::GetProviderById(std::uint32_t id) { ProviderMap::const_iterator found = provider_map_.find(id); if (found != provider_map_.end()) { return found->second; } return std::string(); } AssetManager::AssetManager(QWidget* parent) : AssetManagerBase(parent), icon_grid_(128), filter_type_(0), filter_subtype_(0), asset_manager_icon_choice_orig_( Preferences::getConfig().assetManagerIconChoice) { { gstProviderSet providers; if (providers.Load()) { for (const auto& it : providers.items) { provider_map_[it.id] = it.key; } } } connect(categories, SIGNAL(contextMenuRequested(Q3ListViewItem*, const QPoint&, int)), this, SLOT(rmbClicked(Q3ListViewItem*, const QPoint&, int))); connect(assetTabWidget, SIGNAL(currentChanged(QWidget*)), this, SLOT(selectFolder())); connect(assetTableView, SIGNAL(doubleClicked(int, int, int, const QPoint&)), this, SLOT(doubleClicked(int, int, int, const QPoint&))); connect(assetTableView, SIGNAL(contextMenuRequested(int, int, const QPoint&)), this, SLOT(tableAssetMenu(int, int, const QPoint&))); connect(assetIconView, SIGNAL(contextMenuRequested(Q3IconViewItem*, const QPoint&)), this, SLOT(iconAssetMenu(Q3IconViewItem*, const QPoint&))); connect(assetTableView, SIGNAL(currentChanged(int, int)), this, SLOT(CurrentAssetChanged(int, int))); if (folderOpen == 0) { folderOpen = new QPixmap(folder_open_xpm); folderClosed = new QPixmap(folder_closed_xpm); } categories->header()->setStretchEnabled(true); categories->header()->hide(); if (khExists(Preferences::filepath("assetmanager.layout").toUtf8().constData())) { if (layout_persist_.Load( Preferences::filepath("assetmanager.layout").toUtf8().constData())) { // update filter combox filter_type_ = layout_persist_.filterType; filter_subtype_ = layout_persist_.filterSubType; typeCombo->setCurrentItem(filter_type_); subtypeCombo->setCurrentItem(filter_subtype_); // update position if(layout_persist_.width > 4000 || layout_persist_.width < 100) { layout_persist_.width = DEFAULT_WINDOW_WIDTH; } if(layout_persist_.height > 4000 || layout_persist_.height < 100) { layout_persist_.height = DEFAULT_WINDOW_HEIGHT; } resize(layout_persist_.width, layout_persist_.height); move(layout_persist_.xpos, layout_persist_.ypos); // update viewmode if (layout_persist_.viewMode == AssetManagerLayout::List) { assetTabWidget->setCurrentPage(0); } else if (layout_persist_.viewMode == AssetManagerLayout::Preview) { assetTabWidget->setCurrentPage(1); } // update visibility if (layout_persist_.showme) show(); showHiddenAssets(layout_persist_.showHidden); showHiddenCheck->setChecked(layout_persist_.showHidden); if (layout_persist_.folderSplitter.front() != 0) { Q3ValueList<int> splitter_list = layout_persist_.folderSplitter; folder_splitter->setSizes(splitter_list); } } } setCaption(tr("Asset Manager") + Preferences::CaptionText()); self = this; // disable some buttons in LT Mode if (GetFusionProductType() == FusionLT) { newImageryResourceAction->removeFrom(Toolbar); newTerrainResourceAction->removeFrom(Toolbar); newImageryProjectAction->removeFrom(Toolbar); newTerrainProjectAction->removeFrom(Toolbar); } toolbar_chooser_combo->setCurrentItem(asset_manager_icon_choice_orig_); } AssetManager::~AssetManager() { if (asset_manager_icon_choice_orig_ != Preferences::getConfig().assetManagerIconChoice) { Preferences::getConfig().Save(Preferences::filepath("preferences.xml").toUtf8().constData()); } layout_persist_.showme = isShown(); if (assetTabWidget->currentPageIndex() == 0) { layout_persist_.viewMode = AssetManagerLayout::List; } else if (assetTabWidget->currentPageIndex() == 1) { layout_persist_.viewMode = AssetManagerLayout::Preview; } gstAssetFolder folder = GetSelectedFolder(); if (folder.isValid()) { layout_persist_.selectedPath = folder.relativePath(); } else { layout_persist_.selectedPath = QString::null; } layout_persist_.folderSplitter.clear(); Q3ValueList<int> folder_splitter_list = folder_splitter->sizes(); for (Q3ValueList<int>::Iterator it = folder_splitter_list.begin(); it != folder_splitter_list.end(); ++it) { layout_persist_.folderSplitter.push_back(*it); } layout_persist_.filterType = filter_type_; layout_persist_.filterSubType = filter_subtype_; layout_persist_.Save(Preferences::filepath("assetmanager.layout").toUtf8().constData()); } AssetManagerLayout::Size AssetManager::GetLayoutSize(const QString& name) { return self->layout_persist_.FindLayoutByName(name); } void AssetManager::SetLayoutSize(const QString& name, int width, int height) { self->layout_persist_.SetLayoutSize(name, width, height); } void AssetManager::HandleNewWindow(AssetBase* asset_window) { AssetDisplayHelper helper(asset_window->AssetType(), asset_window->AssetSubtype()); AssetAction* action = new AssetAction(this, asset_window); action->addTo(Window); asset_window->setIcon(helper.GetPixmap()); asset_window->move(QCursor::pos()); asset_window->show(); } bool AssetManager::RestoreExisting(const std::string& asset_ref) { AssetAction* action = AssetAction::FindAsset(asset_ref.c_str()); if (action == NULL) { return false; } else { action->activate(QAction::Trigger); // could also be QAction::Hover return true; } } bool AssetManager::OkToQuit() { return AssetAction::OkToCloseAll(); } void AssetManager::CloseAllWindows() { AssetAction::CloseAll(); } void AssetManager::CascadeWindows() { AssetAction::Cascade(pos()); } void AssetManager::CreateNewAsset() { NewAsset new_asset(this); AssetDisplayHelper::AssetKey asset_type = new_asset.ChooseAssetType(); switch (asset_type) { case AssetDisplayHelper::Key_VectorProduct: HandleNewWindow(new VectorAsset(this)); break; case AssetDisplayHelper::Key_VectorLayer: HandleNewWindow(new VectorLayer(this)); break; case AssetDisplayHelper::Key_VectorProject: HandleNewWindow(new VectorProject(this)); break; case AssetDisplayHelper::Key_ImageryProduct: HandleNewWindow(new ImageryAsset(this)); break; case AssetDisplayHelper::Key_MercatorImageryProduct: HandleNewWindow(new MercatorImageryAsset(this)); break; case AssetDisplayHelper::Key_ImageryProject: HandleNewWindow(new ImageryProject(this)); break; case AssetDisplayHelper::Key_MercatorImageryProject: HandleNewWindow(new ImageryProject(this)); break; case AssetDisplayHelper::Key_TerrainProduct: HandleNewWindow(new TerrainAsset(this)); break; case AssetDisplayHelper::Key_TerrainProject: HandleNewWindow(new TerrainProject(this)); break; case AssetDisplayHelper::Key_Database: HandleNewWindow(new Database(this)); break; case AssetDisplayHelper::Key_MapLayer: HandleNewWindow(new MapLayer(this)); break; case AssetDisplayHelper::Key_MapProject: HandleNewWindow(new MapProject(this)); break; case AssetDisplayHelper::Key_MapDatabase: HandleNewWindow(new MapDatabase(this)); break; case AssetDisplayHelper::Key_MercatorMapDatabase: HandleNewWindow(new MercatorMapDatabase(this)); break; case AssetDisplayHelper::Key_KMLProject: HandleNewWindow(new KMLProject(this)); break; case AssetDisplayHelper::Key_Invalid: case AssetDisplayHelper::Key_Unknown: // do nothing break; } } void AssetManager::NewVectorAsset() { HandleNewWindow(new VectorAsset(this)); } void AssetManager::NewVectorLayer() { HandleNewWindow(new VectorLayer(this)); } void AssetManager::NewVectorProject() { HandleNewWindow(new VectorProject(this)); } void AssetManager::NewImageryAsset() { HandleNewWindow(new ImageryAsset(this)); } void AssetManager::NewMercatorImageryAsset() { HandleNewWindow(new MercatorImageryAsset(this)); } void AssetManager::NewImageryProject() { HandleNewWindow(new ImageryProject(this)); } void AssetManager::NewMercatorImageryProject() { HandleNewWindow(new MercatorImageryProject(this)); } void AssetManager::NewTerrainAsset() { HandleNewWindow(new TerrainAsset(this)); } void AssetManager::NewTerrainProject() { HandleNewWindow(new TerrainProject(this)); } void AssetManager::NewMapLayer() { HandleNewWindow(new MapLayer(this)); } void AssetManager::NewMapProject() { HandleNewWindow(new MapProject(this)); } void AssetManager::NewMapDatabase() { HandleNewWindow(new MapDatabase(this)); } void AssetManager::ToolbarChooserComboActivated(int choice) { Preferences::getConfig().assetManagerIconChoice = static_cast<PrefsConfig::ShowAssetManagerIconType>(choice); HideIcons(); ShowIcons(); } void AssetManager::NewMercatorMapDatabase() { HandleNewWindow(new MercatorMapDatabase(this)); } void AssetManager::NewKMLProject() { HandleNewWindow(new KMLProject(this)); } void AssetManager::NewDatabase() { HandleNewWindow(new Database(this)); } void AssetManager::moveEvent(QMoveEvent* event) { const QPoint& pt = event->pos(); // XXX only update if this is a valid event // XXX this is clearly a QT bug! if (x() != 0 && y() != 0) { layout_persist_.xpos = pt.x(); layout_persist_.ypos = pt.y(); } } void AssetManager::resizeEvent(QResizeEvent* event) { const QSize& sz = event->size(); layout_persist_.width = sz.width(); layout_persist_.height = sz.height(); } void AssetManager::RemoveToolBarIcons() { newVectorResourceAction->removeFrom(Toolbar); newVectorProjectAction->removeFrom(Toolbar); newImageryResourceAction->removeFrom(Toolbar); newImageryProjectAction->removeFrom(Toolbar); newTerrainResourceAction->removeFrom(Toolbar); newTerrainProjectAction->removeFrom(Toolbar); newDatabaseAction->removeFrom(Toolbar); newImageryResourceMercatorAction->removeFrom(Toolbar); newImageryProjectMercatorAction->removeFrom(Toolbar); newMapLayerAction->removeFrom(Toolbar); newMapProjectAction->removeFrom(Toolbar); newMapDatabaseMercatorAction->removeFrom(Toolbar); newMapDatabaseAction->removeFrom(Toolbar); } void AssetManager::ShowIcons() { switch (asset_manager_icon_choice_ = Preferences::getConfig().assetManagerIconChoice) { case PrefsConfig::ShowEarthIcons: newImageryResourceAction->addTo(Toolbar); newImageryProjectAction->addTo(Toolbar); newVectorResourceAction->addTo(Toolbar); newVectorProjectAction->addTo(Toolbar); newTerrainResourceAction->addTo(Toolbar); newTerrainProjectAction->addTo(Toolbar); newDatabaseAction->addTo(Toolbar); break; case PrefsConfig::ShowMercatorMapIcons: newImageryResourceMercatorAction->addTo(Toolbar); newImageryProjectMercatorAction->addTo(Toolbar); newVectorResourceAction->addTo(Toolbar); newMapLayerAction->addTo(Toolbar); newMapProjectAction->addTo(Toolbar); newMapDatabaseMercatorAction->addTo(Toolbar); break; case PrefsConfig::ShowWjs84MapIcons: newImageryResourceAction->addTo(Toolbar); newImageryProjectAction->addTo(Toolbar); newVectorResourceAction->addTo(Toolbar); newMapLayerAction->addTo(Toolbar); newMapProjectAction->addTo(Toolbar); newMapDatabaseAction->addTo(Toolbar); break; default: break; } } void AssetManager::show() { if (!isVisible()) { connect(SystemListener::instance, SIGNAL(assetsChanged(const AssetChanges&)), this, SLOT(assetsChanged(const AssetChanges&))); RedrawTree(true); } HideIcons(); ShowIcons(); AssetManagerBase::show(); } void AssetManager::HideIcons() { switch (asset_manager_icon_choice_) { case PrefsConfig::ShowEarthIcons: newVectorResourceAction->removeFrom(Toolbar); newVectorProjectAction->removeFrom(Toolbar); newImageryResourceAction->removeFrom(Toolbar); newImageryProjectAction->removeFrom(Toolbar); newTerrainResourceAction->removeFrom(Toolbar); newTerrainProjectAction->removeFrom(Toolbar); newDatabaseAction->removeFrom(Toolbar); break; case PrefsConfig::ShowMercatorMapIcons: newVectorResourceAction->removeFrom(Toolbar); newImageryResourceMercatorAction->removeFrom(Toolbar); newImageryProjectMercatorAction->removeFrom(Toolbar); newMapLayerAction->removeFrom(Toolbar); newMapProjectAction->removeFrom(Toolbar); newMapDatabaseMercatorAction->removeFrom(Toolbar); break; case PrefsConfig::ShowWjs84MapIcons: newVectorResourceAction->removeFrom(Toolbar); newImageryResourceAction->removeFrom(Toolbar); newImageryProjectAction->removeFrom(Toolbar); newMapLayerAction->removeFrom(Toolbar); newMapProjectAction->removeFrom(Toolbar); newMapDatabaseAction->removeFrom(Toolbar); break; default: break; } } void AssetManager::hide() { disconnect(SystemListener::instance, SIGNAL(assetsChanged(const AssetChanges&)), this, SLOT(assetsChanged(const AssetChanges&))); HideIcons(); AssetManagerBase::hide(); } void AssetManager::RedrawTree(bool select_top) { categories->clear(); if (theAssetManager == NULL) { QMessageBox::warning(this, "Warning", trUtf8("Asset Manager is misconfigured!"), tr("OK"), 0, 0, 1); return; } const gstAssetFolder& assetroot = theAssetManager->getAssetRoot(); AssetFolder* parent = new AssetFolder(categories, assetroot); parent->setText(0, AssetRoot()); parent->setOpen(true); // first time drawing the tree might need to restore // previous view. if (!layout_persist_.selectedPath.isEmpty()) { OpenFolder(layout_persist_.selectedPath); layout_persist_.selectedPath = QString::null; } else if (select_top && categories->firstChild()) { categories->setSelected(categories->firstChild(), true); } } void AssetManager::addAsset() { } void AssetManager::childCollapsed(QListViewItem* item) { AssetFolder* assetfolder = dynamic_cast<AssetFolder*>(item); if (assetfolder == NULL) return; gstAssetFolder folder = GetSelectedFolder(); if (!folder.isValid()) categories->setSelected(assetfolder, true); } void AssetManager::rmbClicked(QListViewItem* item, const QPoint& pos, int) { enum { REFRESH, NEW_FOLDER }; QPopupMenu menu(this); menu.insertItem(trUtf8("Refresh"), REFRESH); menu.insertSeparator(); QString folder_name; AssetFolder* asset_folder = dynamic_cast<AssetFolder*>(item); if (asset_folder != NULL) { folder_name = asset_folder->getFolder().fullPath(); } menu.insertItem(trUtf8("New Subfolder..."), NEW_FOLDER); switch (menu.exec(pos)) { case REFRESH: refresh(); break; case NEW_FOLDER: NewFolder(folder_name); break; } } void AssetManager::tableAssetMenu(int row, int col, const QPoint& mouse_pos) { gstAssetHandle handle = GetAssetByRow(row); if (!handle->isValid()) return; ShowAssetMenu(handle, mouse_pos); } void AssetManager::iconAssetMenu(QIconViewItem* item, const QPoint& mouse_pos) { AssetIcon* icon = dynamic_cast<AssetIcon*>(item); if (icon == NULL) return; ShowAssetMenu(icon->getAssetHandle(), mouse_pos); } void AssetManager::ShowAssetMenu(const gstAssetHandle& asset_handle, const QPoint& mouse_pos) { enum { BUILD_ASSET, CANCEL_ASSET, MODIFY_ASSET, PUSH_DB, PUBLISH_DB, ASSET_PROPERTIES, CURR_VER_PROPERTIES }; QPopupMenu menu(this); Asset current_asset = asset_handle->getAsset(); AssetVersion current_version(current_asset->CurrVersionRef()); // first item in menu should be the asset name since the table // might get redrawn after the menu has popped-up AssetDisplayHelper a(current_asset->type, current_asset->subtype); std::string shortName = shortAssetName(asset_handle->getName()); menu.insertItem(a.GetPixmap(), shortName.c_str()); menu.insertSeparator(); menu.insertSeparator(); if (current_version) { menu.insertItem(trUtf8("Current Version Properties"), CURR_VER_PROPERTIES); } menu.insertItem(trUtf8("Asset Versions"), ASSET_PROPERTIES); if (current_version && current_version->CanCancel()) { menu.insertItem(trUtf8("Cancel Current Version"), CANCEL_ASSET); } if (current_asset->type == AssetDefs::Database) { int push_item_id = menu.insertItem(trUtf8("Push"), PUSH_DB); if (DatabaseHasValidVersion(current_asset)) { menu.setItemEnabled(push_item_id, TRUE); } else { menu.setItemEnabled(push_item_id, FALSE); } // Note: Switches off Publish functionality. // The virtual host is removed from Server Combination, // So it contains only URL, while for publishing we need URL + virtual // host. // Thought is to encourage server UI for all publishing. // menu.insertItem(trUtf8("Publish"), PUBLISH_DB); } menu.insertItem(trUtf8("&Build"), BUILD_ASSET); menu.insertItem(trUtf8("Modify"), MODIFY_ASSET); switch (menu.exec(mouse_pos)) { case BUILD_ASSET: BuildAsset(asset_handle); refresh(); break; case CANCEL_ASSET: CancelAsset(asset_handle); refresh(); break; case MODIFY_ASSET: ModifyAsset(asset_handle); refresh(); break; case ASSET_PROPERTIES: ShowAssetProperties(asset_handle); break; case CURR_VER_PROPERTIES: ShowCurrVerProperties(asset_handle); break; case PUSH_DB: PushDatabase(asset_handle); refresh(); break; case PUBLISH_DB: PublishDatabase(asset_handle); refresh(); break; } } void AssetManager::showHiddenAssets(bool checked) { layout_persist_.showHidden = checked; // force redraw of table view or icon view selectFolder(); } void AssetManager::CurrentAssetChanged(int row, int col) { #if 0 if (row == -1 || col == -1) { detail_stack->raiseWidget(0); return; } gstAssetHandle handle = GetAssetByRow(row); Asset current_asset = handle->getAsset(); AssetVersion current_version(current_asset->CurrVersionRef()); if (current_asset->type == AssetDefs::Database) { detail_stack->raiseWidget(1); } else { detail_stack->raiseWidget(2); } #endif } void AssetManager::doubleClicked(int row, int col, int button, const QPoint& mouse_pos) { // clicking on background deselects current asset if (row == -1 || col == -1) return; gstAssetHandle handle = GetAssetByRow(row); if (!handle->isValid()) return; if (col == 0) ModifyAsset(handle); if (col == 3 || col == 4) ShowCurrVerProperties(handle); } void AssetManager::ShowAssetProperties(const gstAssetHandle& handle) { AssetProperties* properties = new AssetProperties(NULL, handle); properties->show(); } void AssetManager::ShowCurrVerProperties(const gstAssetHandle& handle) { Asset currAsset = handle->getAsset(); AssetVersionProperties::Open(currAsset->CurrVersionRef()); } gstAssetHandle AssetManager::GetAssetByRow(int row) { if (row == -1) return gstAssetHandleImpl::Create(gstAssetFolder(QString::null), QString::null); return assetTableView->GetAssetHandle(row); } void AssetManager::BuildAsset(const gstAssetHandle& handle) { QString error; if (!theAssetManager->buildAsset(handle, error)) { if (error.isEmpty()) error = tr("Build has unknown problems.\n"); QMessageBox::critical(this, tr("Error"), error, tr("OK"), 0, 0, 0); } } void AssetManager::CancelAsset(const gstAssetHandle& handle) { QString error; if (!theAssetManager->cancelAsset(handle, error)) { if (error.isEmpty()) error = tr("Cancel has unknown problems.\n"); QMessageBox::critical(this, tr("Error"), error, tr("OK"), 0, 0, 0); } } class FixCursor { public: FixCursor(QWidget* p) : parent(p) {} ~FixCursor() { parent->setCursor(Qt::arrowCursor); } private: QWidget* parent; }; void AssetManager::PushDatabase(const gstAssetHandle& handle) { Asset asset = handle->getAsset(); ServerCombinationSet sc_set; sc_set.Load(); if (asset->versions.size() == 0) { QMessageBox::critical(this, "Error", tr("Please build the database first."), 0, 0, 0); return; } if (sc_set.combinations.size() == 0) { QMessageBox::critical(this, "Error", tr("Please add at least one server" "association using the Publisher tool."), 0, 0, 0); return; } std::vector<QString> nicknames; for (const auto& it : sc_set.combinations) { nicknames.push_back(it.nickname); } PushDatabaseDialog push_db_dlg(this, asset, nicknames); if (!push_db_dlg.HasValidVersions()) { QMessageBox::critical( this, "Error", tr("This database does not have a single pushable version." " Try rebuilding the database."), 0, 0, 0); return; } if (push_db_dlg.exec() != QDialog::Accepted) return; AssetVersion db_asset_version(); std::string gedb_path; AssetVersion gedb_version; if (asset->subtype == kMapDatabaseSubtype) { MapDatabaseAssetVersion mdav(push_db_dlg.GetSelectedVersion()); gedb_version = mdav->GetMapdbChild(); } else if (asset->subtype == kMercatorMapDatabaseSubtype) { MercatorMapDatabaseAssetVersion mdav(push_db_dlg.GetSelectedVersion()); gedb_version = mdav->GetMapdbChild(); } else { DatabaseAssetVersion dav(push_db_dlg.GetSelectedVersion()); gedb_version = dav->GetGedbChild(); } gedb_path = gedb_version->GetOutputFilename(0); QString nickname = push_db_dlg.GetSelectedNickname(); // Update the preferences with the user's choice. We want to remember these // choices so that we can automatically select this server next time they // push/publish. std::string database_name = shortAssetName(asset->GetRef().toString()); Preferences::UpdatePublishServerDbMap(database_name, nickname.toUtf8().constData()); ServerConfig stream_server, search_server; for (const auto& it : sc_set.combinations) { if (nickname == it.nickname) { stream_server = it.stream; search_server = stream_server; break; } } geGuiProgress progress(100); geGuiAuth auth(this); // Currently, the auth dialog will be executed in the current thread. auth.SetSynchronous(true); PublisherClient publisher_client(AssetDefs::MasterHostName(), stream_server, search_server, &progress, &auth); if (!publisher_client.AddDatabase( gedb_path, push_db_dlg.GetSelectedVersion())) { QMessageBox::critical(this, "Push Failed", tr("Error: %1 ").arg(publisher_client.ErrMsg().c_str()), 0, 0, 0); return; } FixCursor fix_cursor(this); QProgressDialog progress_dialog(tr("Pushing database..."), tr("Cancel"), 0, 100, this); progress_dialog.setCaption(tr("Pushing")); // PublisherClient will now be run in a separate thread, // so any calls to the auth dialog now need to be asynchronous. auth.SetSynchronous(false); PushThread push_thread(&publisher_client, gedb_path); { ServeAssistant push_assistant(&progress_dialog, &progress, &auth); QObject::connect(&progress_dialog, SIGNAL(canceled()), &push_assistant, SLOT(SetCanceled())); QObject::connect(&push_thread, SIGNAL(sfinished()), &push_assistant, SLOT(Stop())); // TODO: may still need? QObject::connect(&push_thread, SIGNAL(sfinished()), &push_thread, SLOT(deleteLater())); push_thread.start(); push_assistant.Start(); progress_dialog.show(); while (push_thread.isRunning()) { qApp->processEvents(); } } if (progress_dialog.wasCanceled()) { QMessageBox::critical(this, "Push Interrupted", tr("Push Interrupted"), 0, 0, 0); return; } // hide progress dialog progress_dialog.reset(); if (!push_thread.retval()) { QMessageBox::critical(this, "Push Failed", tr("Error: %1").arg(publisher_client.ErrMsg().c_str()), 0, 0, 0); return; } QMessageBox::information(this, tr("Success"), tr("Database Successfully Pushed"), QMessageBox::Ok, 0, 0); } void AssetManager::PublishDatabase(const gstAssetHandle& handle) { Asset asset = handle->getAsset(); ServerCombinationSet sc_set; sc_set.Load(); if (asset->versions.size() == 0) { QMessageBox::critical(this, "Error", tr("Please build the database first."), 0, 0, 0); return; } if (sc_set.combinations.size() == 0) { QMessageBox::critical(this, "Error", tr("Please add at least one server" "association using the Publisher tool."), 0, 0, 0); return; } std::vector<QString> nicknames; for (const auto& it : sc_set.combinations) { nicknames.push_back(it.nickname); } PublishDatabaseDialog publish_db_dlg(this, asset, nicknames); if (!publish_db_dlg.HasValidVersions()) { QMessageBox::critical(this, "Error", tr("This database does not have a single publishable version." " Try rebuilding the database."), 0, 0, 0); return; } if (publish_db_dlg.exec() != QDialog::Accepted) return; std::string target_path = publish_db_dlg.GetTargetPath(); AssetVersion db_asset_version(); std::string gedb_path; AssetVersion gedb_version; if (asset->subtype == kMapDatabaseSubtype) { MapDatabaseAssetVersion mdav(publish_db_dlg.GetSelectedVersion()); gedb_version = mdav->GetMapdbChild(); } else if (asset->subtype == kMercatorMapDatabaseSubtype) { MercatorMapDatabaseAssetVersion mdav(publish_db_dlg.GetSelectedVersion()); gedb_version = mdav->GetMapdbChild(); } else { DatabaseAssetVersion dav(publish_db_dlg.GetSelectedVersion()); gedb_version = dav->GetGedbChild(); } gedb_path = gedb_version->GetOutputFilename(0); QString nickname = publish_db_dlg.GetSelectedNickname(); // Update the preferences with the user's choice. We want to remember these // choices so that we can automatically select this server next time they // push/publish. std::string database_name = shortAssetName(asset->GetRef().toString()); Preferences::UpdatePublishServerDbMap(database_name, nickname.toUtf8().constData()); ServerConfig stream_server, search_server; for (const auto& it : sc_set.combinations) { if (nickname == it.nickname) { stream_server = it.stream; search_server = stream_server; break; } } geGuiProgress progress(100); geGuiAuth auth(this); // Currently, the auth dialog will be executed in the current thread. auth.SetSynchronous(true); PublisherClient publisher_client(AssetDefs::MasterHostName(), stream_server, search_server, &progress, &auth); FixCursor fix_cursor(this); QProgressDialog progress_dialog(tr("Publishing database..."), tr("Cancel"), 0, 100, this); progress_dialog.setCaption(tr("Publishing")); // PublisherClient will now be run in a separate thread, // so any calls to the auth dialog now need to be asynchronous. auth.SetSynchronous(false); PublishThread publish_thread(&publisher_client, gedb_path, target_path); { ServeAssistant publish_assistant(&progress_dialog, &progress, &auth); QObject::connect(&progress_dialog, SIGNAL(canceled()), &publish_assistant, SLOT(SetCanceled())); QObject::connect( &publish_thread, SIGNAL(sfinished()), &publish_assistant, SLOT(Stop())); // TODO: May still need? QObject::connect(&publish_thread, SIGNAL(sfinished()), &publish_thread, SLOT(deleteLater())); publish_thread.start(); publish_assistant.Start(); progress_dialog.show(); while (publish_thread.isRunning()) { qApp->processEvents(); } } if (progress_dialog.wasCanceled()) { QMessageBox::critical(this, "Publish Interrupted", tr("Publish Interrupted"), 0, 0, 0); return; } // hide progress dialog progress_dialog.reset(); if (!publish_thread.retval()) { QMessageBox::critical(this, "Publish Failed", tr("Error: %1").arg(publisher_client.ErrMsg().c_str()), 0, 0, 0); return; } QMessageBox::information(this, tr("Success"), tr("Database Successfully Published"), QMessageBox::Ok, 0, 0); } void AssetManager::ModifyAsset(const gstAssetHandle& handle) { Asset current_asset = handle->getAsset(); std::string assetref = current_asset->GetRef(); if (RestoreExisting(assetref)) return; AssetBase* asset_window = NULL; if (current_asset->type == AssetDefs::Imagery && current_asset->subtype == kProductSubtype) { RasterProductAsset prod(assetref); RasterProductImportRequest request(prod->type); request.assetname = assetref; request.config = prod->config; request.meta = prod->meta; SourceAssetVersion source(prod->inputs[0]); assert(source); request.sources = source->config; asset_window = new ImageryAsset(this, request); } else if (current_asset->type == AssetDefs::Imagery && current_asset->subtype == kMercatorProductSubtype) { MercatorRasterProductAsset prod(assetref); RasterProductImportRequest request(prod->type); request.assetname = assetref; request.config = prod->config; request.meta = prod->meta; SourceAssetVersion source(prod->inputs[0]); assert(source); request.sources = source->config; asset_window = new MercatorImageryAsset(this, request); } else if (current_asset->type == AssetDefs::Terrain && current_asset->subtype == kProductSubtype) { RasterProductAsset prod(assetref); RasterProductImportRequest request(prod->type); request.assetname = assetref; request.config = prod->config; request.meta = prod->meta; SourceAssetVersion source(prod->inputs[0]); assert(source); request.sources = source->config; asset_window = new TerrainAsset(this, request); } else if (current_asset->type == AssetDefs::Vector && current_asset->subtype == kProductSubtype) { VectorProductAsset prod(assetref); VectorProductImportRequest request; request.assetname = assetref; request.config = prod->config; request.meta = prod->meta; SourceAssetVersion source(prod->inputs[0]); assert(source); request.sources = source->config; asset_window = new VectorAsset(this, request); } else if (current_asset->type == AssetDefs::Database && current_asset->subtype == kDatabaseSubtype) { DatabaseAsset dbasset(assetref); DatabaseEditRequest request; request.assetname = assetref; request.config = dbasset->config; request.meta = dbasset->meta; asset_window = new Database(this, request); } else if (current_asset->type == AssetDefs::Database && current_asset->subtype == kMapDatabaseSubtype) { MapDatabaseAsset dbasset(assetref); MapDatabaseEditRequest request; request.assetname = assetref; request.config = dbasset->config; request.meta = dbasset->meta; asset_window = new MapDatabase(this, request); } else if (current_asset->type == AssetDefs::Database && current_asset->subtype == kMercatorMapDatabaseSubtype) { MercatorMapDatabaseAsset dbasset(assetref); MapDatabaseEditRequest request; request.assetname = assetref; request.config = dbasset->config; request.meta = dbasset->meta; asset_window = new MercatorMapDatabase(this, request); } else if (current_asset->type == AssetDefs::Map && current_asset->subtype == kLayer) { MapLayerEditRequest request; request.assetname = assetref; MapLayerAsset layer(assetref); request.config = layer->config; request.meta = layer->meta; asset_window = new MapLayer(this, request); } else if (current_asset->type == AssetDefs::Map && current_asset->subtype == kProjectSubtype) { MapProjectEditRequest request; request.assetname = assetref; MapProjectAsset project(assetref); request.config = project->config; request.meta = project->meta; asset_window = new MapProject(this, request); } else if (current_asset->type == AssetDefs::Vector && current_asset->subtype == kLayer) { VectorLayerXEditRequest request; request.assetname = assetref; VectorLayerXAsset layer(assetref); request.config = layer->config; request.meta = layer->meta; asset_window = new VectorLayer(this, request); } else if (current_asset->type == AssetDefs::Vector && current_asset->subtype == kProjectSubtype) { VectorProjectEditRequest request; request.assetname = assetref; VectorProjectAsset project(assetref); request.config = project->config; request.meta = project->meta; asset_window = new VectorProject(this, request); } else if (current_asset->type == AssetDefs::Imagery && current_asset->subtype == kProjectSubtype) { RasterProjectEditRequest request(AssetDefs::Imagery); request.assetname = assetref; RasterProjectAsset project(assetref); request.config = project->config; request.meta = project->meta; asset_window = new ImageryProject(this, request); } else if (current_asset->type == AssetDefs::Imagery && current_asset->subtype == kMercatorProjectSubtype) { RasterProjectEditRequest request(AssetDefs::Imagery); request.assetname = assetref; MercatorRasterProjectAsset project(assetref); request.config = project->config; request.meta = project->meta; asset_window = new MercatorImageryProject(this, request); } else if (current_asset->type == AssetDefs::Terrain && current_asset->subtype == kProjectSubtype) { RasterProjectEditRequest request(AssetDefs::Terrain); request.assetname = assetref; RasterProjectAsset project(assetref); request.config = project->config; request.meta = project->meta; asset_window = new TerrainProject(this, request); } else if (current_asset->type == AssetDefs::KML && current_asset->subtype == kProjectSubtype) { KMLProjectEditRequest request; request.assetname = assetref; KMLProjectAsset project(assetref); request.config = project->config; request.meta = project->meta; asset_window = new KMLProject(this, request); } if (asset_window) { HandleNewWindow(asset_window); } } void AssetManager::refresh() { // int row = assetTableView->currentRow(); // remember which folder is selected QString save_path; AssetFolder* item = dynamic_cast<AssetFolder*>(categories->selectedItem()); if (item != NULL) { save_path = item->getFolder().relativePath(); } // now reselect the folder if (save_path.isEmpty()) { RedrawTree(true); } else { RedrawTree(false); OpenFolder(save_path); } } void AssetManager::assetsChanged(const AssetChanges& changes) { // figure out the currently selected directory QString currpath; AssetFolder* item = dynamic_cast<AssetFolder*>(categories->selectedItem()); if (item != NULL) { currpath = item->getFolder().relativePath(); } if (currpath.isEmpty()) { currpath = "."; } // convert it to std::string only once for speed std::string curr = currpath.toStdString(); // check to see if any of the changes are in this directory std::set<std::string> changedHere; for(const auto& i : changes.items) { if (khDirname(i.ref) == curr) { changedHere.insert(AssetVersionRef(i.ref).AssetRef()); } } if (changedHere.size()) { gstAssetFolder folder = GetSelectedFolder(); if (assetTabWidget->currentPageIndex() == 0) { TrackChangesInTableView(folder, changedHere); } else { UpdateIconView(folder); } } } void AssetManager::NewFolder(const QString& folder_name) { assert(theAssetManager != NULL); bool ok; QString text = QInputDialog::getText(tr("New Subfolder"), tr("Name:"), QLineEdit::Normal, QString::null, &ok, this); if (!ok || text.isEmpty()) return; if (text.contains(QRegExp("[\\W+]"))) { QMessageBox::warning(this, "Warning", tr("Invalid directory name: \n") + text + QString("\n\n") + tr("Please use only letters, numbers and " "underscores."), tr("OK"), 0, 0, 1); return; } QListViewItem* item; if (folder_name.isEmpty()) { item = categories->firstChild(); } else { item = OpenFolder(gstAssetFolder(folder_name).relativePath()); } if (item == NULL) { QMessageBox::warning(this, "Warning", tr("Unable to create new directory: \n") + folder_name + "/" + text + QString("\n\n") + tr("Please confirm directory path in shell."), tr("OK"), 0, 0, 1); return; } AssetFolder* asset_folder = dynamic_cast<AssetFolder*>(item); if (!asset_folder) return; QString error; AssetFolder* new_folder = asset_folder->newFolder(text, error); if (!new_folder) { if (error.isEmpty()) { // This error is because we have a problem making the widgetry QMessageBox::warning(this, "Warning", tr("Internal error while creating directory"), tr("OK"), 0, 0, 1); } else { // This is where we will see permissions and other filesytem errors QMessageBox::warning(this, "Warning", error, tr("OK"), 0, 0, 1); } return; } categories->setSelected(new_folder, true); } QListViewItem* AssetManager::OpenFolder(const QString& folder) { // this will always be the root item QListViewItem* item = categories->firstChild(); QStringList list = QStringList::split('/', folder); for (QStringList::Iterator it = list.begin(); it != list.end(); ++it) { item = item->firstChild(); if (item == 0) return NULL; while (item->text(0) != *it) { item = item->nextSibling(); if (item == 0) return NULL; } item->setOpen(true); } categories->setSelected(item, true); return item; } gstAssetFolder AssetManager::GetSelectedFolder() const { AssetFolder* asset_folder = dynamic_cast<AssetFolder*>(categories->selectedItem()); if (asset_folder) return asset_folder->getFolder(); return gstAssetFolder(QString::null); } void AssetManager::selectFolder() { gstAssetFolder folder = GetSelectedFolder(); if (!folder.isValid()) return; locationLineEdit->setText(AssetRoot() + "/" + folder.relativePath()); if (assetTabWidget->currentPageIndex() == 0) { UpdateTableView(folder); } else { UpdateIconView(folder); } } void AssetManager::UpdateTableItem(int row, gstAssetHandle handle, Asset asset) { // Only set the AssetTableItem if it doesn't exist yet (new items) // If we're doing an assetsChanged update, the AssetTableItem can stay // the same. QTableItem *prev = assetTableView->item(row, 0); if (!prev) { AssetTableItem* ati = new AssetTableItem(assetTableView, handle); assetTableView->setItem(row, 0, ati); } // now set the rest of the columns int col = 1; std::string category = asset->PrettySubtype(); if (category == kMercatorProductSubtype) { category = kResourceSubtype; } assetTableView->setText(row, col++, category.c_str()); { std::string providerstr; if ((asset->subtype == kProductSubtype) && ((asset->type == AssetDefs::Imagery) || (asset->type == AssetDefs::Terrain))) { RasterProductAsset prod = asset; providerstr = GetProviderById(prod->config.provider_id_); } else if ((asset->subtype == kMercatorProductSubtype) && (asset->type == AssetDefs::Imagery)) { MercatorRasterProductAsset prod = asset; providerstr = GetProviderById(prod->config.provider_id_); } else if ((asset->subtype == kProductSubtype) && (asset->type == AssetDefs::Vector)) { VectorProductAsset prod = asset; providerstr = GetProviderById(prod->config.provider_id_); } else { providerstr = asset->meta.GetValue("provider").toUtf8().constData(); } assetTableView->setText(row, col++, providerstr.c_str()); } AssetVersion version(asset->CurrVersionRef()); if (version) { assetTableView->setText(row, col++, version->meta.GetValue("createdtime")); assetTableView->setItem(row, col++, new AssetStateItem(assetTableView, version->PrettyState().c_str())); } else { assetTableView->setText(row, col++, "None"); assetTableView->setItem(row, col++, new AssetStateItem(assetTableView, "None")); } assetTableView->adjustRow(row); for (int i = 0; i < assetTableView->numRows(); ++i) { std::string aname { assetTableView->GetItem(i)->GetAssetHandle() ->getAsset()->GetRef().toString().c_str() }; int bpos = aname.rfind('/') + 1, epos = aname.rfind('.'); aname = aname.substr(bpos,epos-bpos); if (aname != assetTableView->GetItem(i)->text().toStdString()) { assetTableView->GetItem(i)->setText(aname.c_str()); } } } void AssetManager::TrackChangesInTableView( const gstAssetFolder &folder, const std::set<std::string> &changed) { // process each changed assetRef // one for (const auto& ref : changed) { QString baseRef = khBasename(ref).c_str(); bool found = false; // try to find a match in the existing items for (int row = 0; row < assetTableView->numRows(); ++row) { AssetTableItem* item = assetTableView->GetItem(row); gstAssetHandle handle = item->GetAssetHandle(); if (handle->getName() == baseRef) { found = true; // Will refetch record from disk if it has changed // NOTE: Using NFS on linux can cause a race here. The system // manager writes the record and then sends me a message. I look at // the file on disk but it hasn't changed yet. :-( Asset asset = handle->getAsset(); if (!IsAssetVisible(asset)) { assetTableView->removeRow(row); } else { UpdateTableItem(row, handle, asset); } break; } } if (!found) { // no match found. This is a new one gstAssetHandle handle = gstAssetHandleImpl::Create(folder, baseRef); Asset asset = handle->getAsset(); if (!IsAssetVisible(asset)) continue; int numRows = assetTableView->numRows(); assetTableView->setNumRows(numRows + 1); UpdateTableItem(numRows, handle, asset); } } // resort in case we just changed a sort key // This mostly does the right thing by preserving scroll position, etc // But it can end up changing the selection assetTableView->sortColumn (assetTableView->horizontalHeader()->sortIndicatorSection(), assetTableView->horizontalHeader()->sortIndicatorOrder() == Qt::AscendingOrder, true /* whole rows */); } void AssetManager::UpdateTableView(const gstAssetFolder& folder) { // reset table assetTableView->setNumCols(0); assetTableView->setNumRows(0); if (!folder.isValid()) return; assetTableView->setNumCols(5); QHeader* header = assetTableView->horizontalHeader(); int col = 0; header->setLabel(col++, tr("Asset Name")); header->setLabel(col++, tr("Category")); header->setLabel(col++, tr("Provider")); header->setLabel(col++, tr("Current Version")); header->setLabel(col++, tr("Current State")); // put directories here // std::vector<gstAssetGroups> std::vector<gstAssetHandle> items = folder.getAssetHandles(); if (items.empty()) { return; } assetTableView->setUpdatesEnabled(false); int rowcount = 0; for (const auto& item : items) { gstAssetHandle handle = item; Asset asset = handle->getAsset(); bool visible = IsAssetVisible(asset); if (!visible) continue; assetTableView->setNumRows(rowcount + 1); UpdateTableItem(rowcount++, handle, asset); } assetTableView->sortColumn(1, true, true); assetTableView->horizontalHeader()->setSortIndicator(1, true); assetTableView->setUpdatesEnabled(true); for (int c = 0; c < assetTableView->numCols(); ++c) assetTableView->adjustColumn(c); repaint(); } void AssetManager::filterType(int menuid) { if (filter_type_ != menuid) { filter_type_ = menuid; selectFolder(); } } void AssetManager::filterSubType(int menuid) { if (filter_subtype_ != menuid) { filter_subtype_ = menuid; selectFolder(); } } bool AssetManager::IsAssetVisible(const Asset& asset) const { // skip invalid assets if (asset->type == AssetDefs::Invalid) return false; std::string category = asset->PrettySubtype(); if (category == kMercatorProductSubtype) { category = kResourceSubtype; } // check filters if (!MatchFilter(asset->type, category)) return false; // if the "show hidden" check is off, skip any asset that // has the "hidden" meta field set if (!showHiddenCheck->isChecked()) { bool hidden = asset->meta.GetAs("hidden", false); if (hidden) return false; } return true; } bool AssetManager::MatchFilter(AssetDefs::Type type, const std::string& subtype) const { if (GetFusionProductType() == FusionLT) { if (type == AssetDefs::Imagery || type == AssetDefs::Terrain) return false; } // quick exit if not filtering if (filter_type_ == 0 && filter_subtype_ == 0) return true; const std::string* subtype_ptr = &subtype; // special-case the new maps database if (type == AssetDefs::Database && (subtype == kMapDatabaseSubtype || subtype == kMercatorMapDatabaseSubtype)) { type = AssetDefs::Map; subtype_ptr = &kDatabaseSubtype; } if (type == AssetDefs::Imagery) { if (subtype == kMercatorProductSubtype) { subtype_ptr = &kProductSubtype; } else if (subtype == kMercatorProjectSubtype) { subtype_ptr = &kProjectSubtype; } } // check major type if (filter_type_ != 0 && TypeSet[filter_type_] != type) return false; // now check minor type (subtype) if (filter_subtype_ != 0 && SubTypeSet[filter_subtype_] != *subtype_ptr) return false; return true; } void AssetManager::UpdateIconView(const gstAssetFolder& folder) { assetIconView->clear(); if (!folder.isValid()) return; std::vector<gstAssetHandle> items = folder.getAssetHandles(); if (items.empty()) return; for (const auto& item : items) { Asset asset = item->getAsset(); if (IsAssetVisible(asset)) new AssetIcon(assetIconView, item, icon_grid_); } resetIconView(icon_grid_); } void AssetManager::resetIconView(int grid_size) { assetIconView->setGridX(grid_size + 20); assetIconView->setGridY(grid_size + 20); assetIconView->arrangeItemsInGrid(); } void AssetManager::resizeIconView(int sz) { if (icon_grid_ != sz) { icon_grid_ = sz; for (QIconViewItem* item = assetIconView->firstItem(); item; item = item->nextItem()) { static_cast<AssetIcon*>(item)->resize(sz); } resetIconView(sz); } } QColorGroup AssetManager::GetStateDrawStyle( const std::string& txt, QPainter* p, const QColorGroup& cg) { bool bold = false; QColor clr = cg.text(); if (txt == "Canceled" || txt == "Failed") { bold = true; clr = QColor(255,0,0); } else if (txt == "Blocked") { bold = true; clr = QColor(255, 162, 0); // orange } else if (txt == "Succeeded") { bold = true; } else if (txt == "Queued" || txt == "InProgress" || txt == "Waiting") { bold = true; clr = QColor(0, 170, 0); // green } QFont f = p->font(); f.setBold(bold); p->setFont(f); QColorGroup ngrp = cg; ngrp.setColor(QColorGroup::Text, clr); return ngrp; }
apache-2.0
xunilrj/sandbox
courses/columbia-cg-animation/week04/include/eigen/test/vectorization_logic.cpp
4
5042
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #define EIGEN_DEBUG_ASSIGN #include "main.h" #include <typeinfo> template<typename Dst, typename Src> bool test_assign(const Dst&, const Src&, int traversal, int unrolling) { ei_assign_traits<Dst,Src>::debug(); return ei_assign_traits<Dst,Src>::Traversal==traversal && ei_assign_traits<Dst,Src>::Unrolling==unrolling; } template<typename Dst, typename Src> bool test_assign(int traversal, int unrolling) { ei_assign_traits<Dst,Src>::debug(); return ei_assign_traits<Dst,Src>::Traversal==traversal && ei_assign_traits<Dst,Src>::Unrolling==unrolling; } template<typename Xpr> bool test_redux(const Xpr&, int traversal, int unrolling) { typedef ei_redux_traits<ei_scalar_sum_op<typename Xpr::Scalar>,Xpr> traits; return traits::Traversal==traversal && traits::Unrolling==unrolling; } void test_vectorization_logic() { #ifdef EIGEN_VECTORIZE VERIFY(test_assign(Vector4f(),Vector4f(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector4f(),Vector4f()+Vector4f(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector4f(),Vector4f().cwiseProduct(Vector4f()), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector4f(),Vector4f().cast<float>(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix4f(),Matrix4f(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix4f(),Matrix4f()+Matrix4f(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix4f(),Matrix4f().cwiseProduct(Matrix4f()), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix<float,16,16>(),Matrix<float,16,16>()+Matrix<float,16,16>(), InnerVectorizedTraversal,InnerUnrolling)); VERIFY(test_assign(Matrix<float,16,16,DontAlign|EIGEN_DEFAULT_MATRIX_STORAGE_ORDER_OPTION>(),Matrix<float,16,16>()+Matrix<float,16,16>(), LinearTraversal,NoUnrolling)); VERIFY(test_assign(Matrix<float,2,2,DontAlign|EIGEN_DEFAULT_MATRIX_STORAGE_ORDER_OPTION>(),Matrix<float,2,2>()+Matrix<float,2,2>(), LinearTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix<float,6,2>(),Matrix<float,6,2>().cwiseQuotient(Matrix<float,6,2>()), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix<float,17,17>(),Matrix<float,17,17>()+Matrix<float,17,17>(), LinearTraversal,NoUnrolling)); VERIFY(test_assign(Matrix<float,3,3>(),Matrix<float,3,3>()+Matrix<float,3,3>(), LinearTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix<float,4,4>(),Matrix<float,17,17>().block<4,4>(2,3)+Matrix<float,17,17>().block<4,4>(10,4), DefaultTraversal,CompleteUnrolling)); VERIFY(test_assign(MatrixXf(10,10),MatrixXf(20,20).block(10,10,2,3), SliceVectorizedTraversal,NoUnrolling)); VERIFY((test_assign< Map<Matrix<float,4,8>, Aligned, OuterStride<12> >, Matrix<float,4,8> >(InnerVectorizedTraversal,CompleteUnrolling))); VERIFY((test_assign< Map<Matrix<float,4,8>, Aligned, InnerStride<12> >, Matrix<float,4,8> >(DefaultTraversal,CompleteUnrolling))); VERIFY(test_redux(VectorXf(10), LinearVectorizedTraversal,NoUnrolling)); VERIFY(test_redux(Matrix<float,5,2>(), DefaultTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix<float,6,2>(), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix<float,16,16>(), LinearVectorizedTraversal,NoUnrolling)); VERIFY(test_redux(Matrix<float,16,16>().block<4,4>(1,2), DefaultTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix<float,16,16,ColMajor>().block<8,1>(1,2), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix<float,16,16,RowMajor>().block<1,8>(2,1), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix<double,7,3>(), DefaultTraversal,CompleteUnrolling)); #endif // EIGEN_VECTORIZE }
apache-2.0
vovythevov/CTK
Libs/DICOM/Core/ctkDICOMModel.cpp
4
29852
/*========================================================================= Library: CTK Copyright (c) Kitware 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.txt 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. =========================================================================*/ // Qt includes #include <QStringList> #include <QSqlDriver> #include <QSqlError> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlResult> #include <QTime> #include <QDebug> // dcmtk includes #include "dcvrpn.h" // ctkDICOMCore includes #include "ctkDICOMModel.h" #include "ctkLogger.h" static ctkLogger logger ( "org.commontk.dicom.DICOMModel" ); struct Node; Q_DECLARE_METATYPE(Qt::CheckState); Q_DECLARE_METATYPE(QStringList); //------------------------------------------------------------------------------ class ctkDICOMModelPrivate { Q_DECLARE_PUBLIC(ctkDICOMModel); protected: ctkDICOMModel* const q_ptr; public: ctkDICOMModelPrivate(ctkDICOMModel&); virtual ~ctkDICOMModelPrivate(); void init(); void fetch(const QModelIndex& indexValue, int limit); Node* createNode(int row, const QModelIndex& parentValue)const; Node* nodeFromIndex(const QModelIndex& indexValue)const; //QModelIndexList indexListFromNode(const Node* node)const; //QModelIndexList modelIndexList(Node* node = 0)const; //int childrenCount(Node* node = 0)const; // move it in the Node struct QVariant value(Node* parentValue, int row, int field)const; QVariant value(const QModelIndex& indexValue, int row, int field)const; QString generateQuery(const QString& fields, const QString& table, const QString& conditions = QString())const; void updateQueries(Node* node)const; Node* RootNode; QSqlDatabase DataBase; QList<QMap<int, QVariant> > Headers; QString Sort; QMap<QString, QVariant> SearchParameters; ctkDICOMModel::IndexType StartLevel; ctkDICOMModel::IndexType EndLevel; }; //------------------------------------------------------------------------------ // 1 node per row // TBD: should probably use the QStandardItems instead. struct Node { ~Node() { foreach(Node* node, this->Children) { delete node; } this->Children.clear(); } ctkDICOMModel::IndexType Type; Node* Parent; QVector<Node*> Children; int Row; QSqlQuery Query; QString UID; int RowCount; bool AtEnd; bool Fetching; QMap<int, QVariant> Data; }; //------------------------------------------------------------------------------ ctkDICOMModelPrivate::ctkDICOMModelPrivate(ctkDICOMModel& o):q_ptr(&o) { this->RootNode = 0; this->StartLevel = ctkDICOMModel::RootType; this->EndLevel = ctkDICOMModel::ImageType; } //------------------------------------------------------------------------------ ctkDICOMModelPrivate::~ctkDICOMModelPrivate() { delete this->RootNode; this->RootNode = 0; } //------------------------------------------------------------------------------ void ctkDICOMModelPrivate::init() { QMap<int, QVariant> data; data[Qt::DisplayRole] = QString("Name"); this->Headers << data; data[Qt::DisplayRole] = QString("Age"); this->Headers << data; data[Qt::DisplayRole] = QString("Scan"); this->Headers << data; data[Qt::DisplayRole] = QString("Date"); this->Headers << data; data[Qt::DisplayRole] = QString("Subject ID"); this->Headers << data; data[Qt::DisplayRole] = QString("Number"); this->Headers << data; data[Qt::DisplayRole] = QString("Institution"); this->Headers << data; data[Qt::DisplayRole] = QString("Referrer"); this->Headers << data; data[Qt::DisplayRole] = QString("Performer"); this->Headers << data; } //------------------------------------------------------------------------------ Node* ctkDICOMModelPrivate::nodeFromIndex(const QModelIndex& indexValue)const { return indexValue.isValid() ? reinterpret_cast<Node*>(indexValue.internalPointer()) : this->RootNode; } /* //------------------------------------------------------------------------------ QModelIndexList ctkDICOMModelPrivate::indexListFromNode(const Node* node)const { Q_Q(const ctkDICOMModel); Q_ASSERT(node); QModelIndexList indexList; Node* parentNode = node->Parent; if (parentNode == 0) { return indexList; } int field = parentNode->Query.record().indexOf("UID"); int row = -1; for (row = 0; row < parentNode->RowCount; ++row) { QString uid = this->value(parentNode, row, field).toString(); if (uid == node->UID) { break; } } if (row >= parentNode->RowCount) { return indexList; } for (int column = 0 ; column < this->Headers.size(); ++column) { indexList.append(q->createIndex(row, column, parentNode)); } return indexList; } //------------------------------------------------------------------------------ QModelIndexList ctkDICOMModelPrivate::modelIndexList(Node* node)const { QModelIndexList list; if (node == 0) { node = this->RootNode; } foreach(Node* child, node->Children) { list.append(this->indexListFromNode(child)); } foreach(Node* child, node->Children) { list.append(this->modelIndexList(child)); } return list; } //------------------------------------------------------------------------------ int ctkDICOMModelPrivate::childrenCount(Node* node)const { int count = 0; if (node == 0) { node = this->RootNode; } count += node->Children.size(); foreach(Node* child, node->Children) { count += this->childrenCount(child); } return count; } */ //------------------------------------------------------------------------------ Node* ctkDICOMModelPrivate::createNode(int row, const QModelIndex& parentValue)const { Node* node = new Node; Node* nodeParent = 0; if (row == -1) {// root node node->Type = ctkDICOMModel::RootType; node->Parent = 0; #if CHECKABLE_COLUMNS // CHECKABLE_COLUMNS are disabled by default - they are not yet used by other // parts of the ctkDICOM infrastructure so they are misleading to the user node->Data[Qt::CheckStateRole] = Qt::Unchecked; #endif } else { nodeParent = this->nodeFromIndex(parentValue); nodeParent->Children.push_back(node); node->Parent = nodeParent; node->Type = ctkDICOMModel::IndexType(nodeParent->Type + 1); } node->Row = row; if (node->Type != ctkDICOMModel::RootType) { int field = 0;//nodeParent->Query.record().indexOf("UID"); node->UID = this->value(parentValue, row, field).toString(); #if CHECKABLE_COLUMNS node->Data[Qt::CheckStateRole] = node->Parent->Data[Qt::CheckStateRole]; #endif } node->RowCount = 0; node->AtEnd = false; node->Fetching = false; this->updateQueries(node); return node; } //------------------------------------------------------------------------------ QVariant ctkDICOMModelPrivate::value(const QModelIndex& parentValue, int row, int column) const { Node* node = this->nodeFromIndex(parentValue); if (row >= node->RowCount) { const_cast<ctkDICOMModelPrivate *>(this)->fetch(parentValue, row + 256); } return this->value(node, row, column); } //------------------------------------------------------------------------------ QVariant ctkDICOMModelPrivate::value(Node* parentNode, int row, int column) const { if (row < 0 || column < 0 || !parentNode || row >= parentNode->RowCount) { return QVariant(); } if (!parentNode->Query.seek(row)) { qDebug() << parentNode->Query.lastError(); Q_ASSERT(parentNode->Query.seek(row)); return QVariant(); } QVariant res = parentNode->Query.value(column); Q_ASSERT(res.isValid()); return res; } //------------------------------------------------------------------------------ QString ctkDICOMModelPrivate::generateQuery(const QString& fields, const QString& table, const QString& conditions)const { QString res = QString("SELECT ") + fields + QString(" FROM ") + table; if (!conditions.isEmpty()) { res += QString(" WHERE ") + conditions; } if (!this->Sort.isEmpty()) { res += QString(" ORDER BY ") + this->Sort; } logger.debug ( "ctkDICOMModelPrivate::generateQuery: query is: " + res ); return res; } //------------------------------------------------------------------------------ void ctkDICOMModelPrivate::updateQueries(Node* node)const { // are you kidding me, it should be virtualized here :-) QString query; QString condition; switch(node->Type) { default: Q_ASSERT(node->Type == ctkDICOMModel::RootType); break; case ctkDICOMModel::RootType: //query = QString("SELECT FROM "); if(this->SearchParameters["Name"].toString() != ""){ condition.append("PatientsName LIKE \"%" + this->SearchParameters["Name"].toString() + "%\""); } query = this->generateQuery("UID as UID, PatientsName as Name, PatientsAge as Age, PatientsBirthDate as Date, PatientID as \"Subject ID\"","Patients", condition); logger.debug ( "ctkDICOMModelPrivate::updateQueries for Root: query is: " + query ); break; case ctkDICOMModel::PatientType: //query = QString("SELECT FROM Studies WHERE PatientsUID='%1'").arg(node->UID); if(this->SearchParameters["Study"].toString() != "") { condition.append("StudyDescription LIKE \"%" + this->SearchParameters["Study"].toString() + "%\"" + " AND "); } if(this->SearchParameters["Modalities"].value<QStringList>().count() > 0) { condition.append("ModalitiesInStudy IN (\"" + this->SearchParameters["Modalities"].value<QStringList>().join("\",\"") + "\") AND "); } if(this->SearchParameters["StartDate"].toString() != "" && this->SearchParameters["EndDate"].toString() != "") { condition.append(" ( StudyDate BETWEEN \'" + QDate::fromString(this->SearchParameters["StartDate"].toString(), "yyyyMMdd").toString("yyyy-MM-dd") + "\' AND \'" + QDate::fromString(this->SearchParameters["EndDate"].toString(), "yyyyMMdd").toString("yyyy-MM-dd") + "\' ) AND "); } query = this->generateQuery("StudyInstanceUID as UID, StudyDescription as Name, ModalitiesInStudy as Scan, StudyDate as Date, AccessionNumber as Number, InstitutionName as Institution, ReferringPhysician as Referrer, PerformingPhysiciansName as Performer", "Studies", condition + QString("PatientsUID='%1'").arg(node->UID)); logger.debug ( "ctkDICOMModelPrivate::updateQueries for Patient: query is: " + query ); break; case ctkDICOMModel::StudyType: //query = QString("SELECT SeriesInstanceUID as UID, SeriesDescription as Name, BodyPartExamined as Scan, SeriesDate as Date, AcquisitionNumber as Number FROM Series WHERE StudyInstanceUID='%1'").arg(node->UID); if(this->SearchParameters["Series"].toString() != "") { condition.append("SeriesDescription LIKE \"%" + this->SearchParameters["Series"].toString() + "%\"" + " AND "); } query = this->generateQuery("SeriesInstanceUID as UID, SeriesDescription as Name, Modality as Age, SeriesNumber as Scan, BodyPartExamined as \"Subject ID\", SeriesDate as Date, AcquisitionNumber as Number","Series",condition + QString("StudyInstanceUID='%1'").arg(node->UID)); logger.debug ( "ctkDICOMModelPrivate::updateQueries for Study: query is: " + query ); break; case ctkDICOMModel::SeriesType: if(this->SearchParameters["ID"].toString() != "") { condition.append("SOPInstanceUID LIKE \"%" + this->SearchParameters["ID"].toString() + "%\"" + " AND "); } //query = QString("SELECT Filename as UID, Filename as Name, SeriesInstanceUID as Date FROM Images WHERE SeriesInstanceUID='%1'").arg(node->UID); query = this->generateQuery("SOPInstanceUID as UID, Filename as Name, SeriesInstanceUID as Date", "Images", condition + QString("SeriesInstanceUID='%1'").arg(node->UID)); logger.debug ( "ctkDICOMModelPrivate::updateQueries for Series: query is: " + query ); break; case ctkDICOMModel::ImageType: break; } node->Query = QSqlQuery(query, this->DataBase); foreach(Node* child, node->Children) { this->updateQueries(child); } } //------------------------------------------------------------------------------ void ctkDICOMModelPrivate::fetch(const QModelIndex& indexValue, int limit) { Q_Q(ctkDICOMModel); Node* node = this->nodeFromIndex(indexValue); if (node->AtEnd || limit <= node->RowCount || node->Fetching/*|| bottom.column() == -1*/) { return; } node->Fetching = true; int newRowCount; const int oldRowCount = node->RowCount; // try to seek directly if (node->Query.seek(limit - 1)) { newRowCount = limit; } else { newRowCount = qMax(oldRowCount, 1); if (node->Query.seek(newRowCount - 1)) { while (node->Query.next()) { ++newRowCount; } } else { // empty or invalid query newRowCount = 0; } node->AtEnd = true; // this is the end. } if (newRowCount > 0 && newRowCount > node->RowCount) { q->beginInsertRows(indexValue, node->RowCount, newRowCount - 1); node->RowCount = newRowCount; node->Fetching = false; q->endInsertRows(); } else { node->RowCount = newRowCount; node->Fetching = false; } } //------------------------------------------------------------------------------ ctkDICOMModel::ctkDICOMModel(QObject* parentObject) : Superclass(parentObject) , d_ptr(new ctkDICOMModelPrivate(*this)) { Q_D(ctkDICOMModel); d->init(); } //------------------------------------------------------------------------------ ctkDICOMModel::~ctkDICOMModel() { } //------------------------------------------------------------------------------ bool ctkDICOMModel::canFetchMore ( const QModelIndex & parentValue ) const { Q_D(const ctkDICOMModel); Node* node = d->nodeFromIndex(parentValue); return node ? !node->AtEnd : false; } //------------------------------------------------------------------------------ int ctkDICOMModel::columnCount ( const QModelIndex & _parent ) const { Q_D(const ctkDICOMModel); Q_UNUSED(_parent); return d->RootNode != 0 ? d->Headers.size() : 0; } //------------------------------------------------------------------------------ QVariant ctkDICOMModel::data ( const QModelIndex & dataIndex, int role ) const { Q_D(const ctkDICOMModel); if ( role == UIDRole ) { Node* node = d->nodeFromIndex(dataIndex); return node ? node->UID : QString() ; } else if ( role == TypeRole ) { Node* node = d->nodeFromIndex(dataIndex); return node ? node->Type : 0; } else if ( dataIndex.column() == 0 && role == Qt::CheckStateRole) { Node* node = d->nodeFromIndex(dataIndex); return node ? node->Data[Qt::CheckStateRole] : 0; } if (role != Qt::DisplayRole && role != Qt::EditRole) { if (dataIndex.column() != 0) { return QVariant(); } Node* node = d->nodeFromIndex(dataIndex); if (!node) { return QVariant(); } return node->Data[role]; } QModelIndex parentIndex = this->parent(dataIndex); Node* parentNode = d->nodeFromIndex(parentIndex); if (dataIndex.row() >= parentNode->RowCount) { const_cast<ctkDICOMModelPrivate *>(d)->fetch(dataIndex, dataIndex.row()); } QString columnName = d->Headers[dataIndex.column()][Qt::DisplayRole].toString(); int field = parentNode->Query.record().indexOf(columnName); if (field < 0) { // Not all the columns are in the record, it's ok to have no field here. // Return an empty string in that case (not a QVariant() that means it's // invalid). return QString(); } QVariant dataValue=d->value(parentIndex, dataIndex.row(), field); if (dataValue.isNull()) { if (columnName.compare("Name")==0) { return QString("No description"); } } if (columnName.compare("Name")==0) { OFString dicomName = dataValue.toString().toStdString().c_str(); OFString formattedName; OFString lastName, firstName, middleName, namePrefix, nameSuffix; OFCondition l_error = DcmPersonName::getNameComponentsFromString(dicomName, lastName, firstName, middleName, namePrefix, nameSuffix); if (l_error.good()) { formattedName.clear(); /* concatenate name components per this convention * Last, First Middle, Suffix (Prefix) * */ if (!lastName.empty()) { formattedName += lastName; if ( !(firstName.empty() && middleName.empty()) ) { formattedName += ","; } } if (!firstName.empty()) { formattedName += " "; formattedName += firstName; } if (!middleName.empty()) { formattedName += " "; formattedName += middleName; } if (!nameSuffix.empty()) { formattedName += ", "; formattedName += nameSuffix; } if (!namePrefix.empty()) { formattedName += " ("; formattedName += namePrefix; formattedName += ")"; } } return QString(formattedName.c_str()); } return dataValue; } //------------------------------------------------------------------------------ void ctkDICOMModel::fetchMore ( const QModelIndex & parentValue ) { Q_D(ctkDICOMModel); Node* node = d->nodeFromIndex(parentValue); d->fetch(parentValue, qMax(node->RowCount, 0) + 256); } //------------------------------------------------------------------------------ Qt::ItemFlags ctkDICOMModel::flags ( const QModelIndex & modelIndex ) const { Q_D(const ctkDICOMModel); Qt::ItemFlags indexFlags = Qt::ItemIsSelectable | Qt::ItemIsEnabled; if (modelIndex.column() != 0) { return indexFlags; } Node* node = d->nodeFromIndex(modelIndex); if (!node) { return indexFlags; } bool checkable = true; node->Data[Qt::CheckStateRole].toInt(&checkable); indexFlags = indexFlags | (checkable ? Qt::ItemIsUserCheckable : Qt::NoItemFlags); return indexFlags; } //------------------------------------------------------------------------------ bool ctkDICOMModel::hasChildren ( const QModelIndex & parentIndex ) const { Q_D(const ctkDICOMModel); // only items in the first columns have index, shortcut the following for // speed issues. if (parentIndex.column() > 0) { return false; } Node* node = d->nodeFromIndex(parentIndex); if (!node) { return false; } // We want to show only until EndLevel if(node->Type >= d->EndLevel)return false; // It's not because we don't have row that we don't have children, maybe it // just means that the children haven't been fetched yet if (node->RowCount == 0 && !node->AtEnd) { // We don't want to fetch the data because we don't want to add children // to the index yet (it would be a mess to add rows inside a hasChildren) //const_cast<qCTKDCMTKModelPrivate*>(d)->fetch(parentIndex, 1); bool res = node->Query.seek(0); if (!res) { // now we know there is no children to the node, don't try next time. node->AtEnd = true; } return res; } return node->RowCount > 0; } //------------------------------------------------------------------------------ QVariant ctkDICOMModel::headerData(int section, Qt::Orientation orientation, int role)const { Q_D(const ctkDICOMModel); if (orientation == Qt::Vertical) { if (role != Qt::DisplayRole) { return QVariant(); } return section; } if (section < 0 || section >= d->Headers.size()) { return QVariant(); } return d->Headers[section][role]; } //------------------------------------------------------------------------------ QModelIndex ctkDICOMModel::index ( int row, int column, const QModelIndex & parentIndex ) const { Q_D(const ctkDICOMModel); // only the first column has children if (d->RootNode == 0 || parentIndex.column() > 0) { return QModelIndex(); } Node* parentNode = d->nodeFromIndex(parentIndex); int field = 0;// always 0//parentNode->Query.record().indexOf("UID"); QString uid = d->value(parentIndex, row, field).toString(); Node* node = 0; foreach(Node* tmpNode, parentNode->Children) { if (tmpNode->UID == uid) { node = tmpNode; break; } } // TODO: Here it is assumed that ctkDICOMModel::index is called with valid // arguments, we should probably be a bit more careful. if (node == 0) { node = d->createNode(row, parentIndex); } return this->createIndex(row, column, node); } //------------------------------------------------------------------------------ QModelIndex ctkDICOMModel::parent ( const QModelIndex & indexValue ) const { Q_D(const ctkDICOMModel); if (!indexValue.isValid()) { return QModelIndex(); } Node* node = d->nodeFromIndex(indexValue); Q_ASSERT(node); Node* parentNode = node->Parent; if (parentNode == 0) {// node is root return QModelIndex(); } return parentNode == d->RootNode ? QModelIndex() : this->createIndex(parentNode->Row, 0, parentNode); /* need to recalculate the parent row Node* greatParentNode = parentNode->Parent; if (greatParentNode == 0) { return QModelIndex(); } int field = greatParentNode->Query.record().indexOf("UID"); int row = -1; for (row = 0; row < greatParentNode->RowCount; ++row) { QString uid = d->value(greatParentNode, row, field).toString(); if (uid == parentNode->UID) { break; } } Q_ASSERT(row < greatParentNode->RowCount); return this->createIndex(row, 0, parentNode); */ } //------------------------------------------------------------------------------ int ctkDICOMModel::rowCount ( const QModelIndex & parentValue ) const { Q_D(const ctkDICOMModel); if (d->RootNode == 0 || parentValue.column() > 0) { return 0; } Node* node = d->nodeFromIndex(parentValue); Q_ASSERT(node); // Returns the amount of rows currently cached on the client. return node ? node->RowCount : 0; } //------------------------------------------------------------------------------ bool ctkDICOMModel::setData(const QModelIndex &index, const QVariant &value, int role) { Q_D(const ctkDICOMModel); if (role != Qt::CheckStateRole) { return false; } Node* node = d->nodeFromIndex(index); if (!node || node->Data[role] == value) { return false; } node->Data[role] = value; emit dataChanged(index, index); for(int i=0; i<node->Children.count(); i++) { this->setChildData(index.child(i,0), value, role); } if(index.parent().isValid()) { this->setParentData(index.parent(), value, role); } return true; } //------------------------------------------------------------------------------ bool ctkDICOMModel::setChildData(const QModelIndex &index, const QVariant &value, int role) { Q_D(const ctkDICOMModel); if (role != Qt::CheckStateRole) { return false; } Node* node = d->nodeFromIndex(index); if (!node || node->Data[role] == value) { return false; } node->Data[role] = value; emit dataChanged(index, index); for(int i=0; i<node->Children.count(); i++) { this->setData(index.child(i,0), value, role); } return true; } //------------------------------------------------------------------------------ bool ctkDICOMModel::setParentData(const QModelIndex &index, const QVariant &value, int role) { Q_D(const ctkDICOMModel); if(!index.isValid()){ return false; } if (role != Qt::CheckStateRole) { return false; } else { bool checkedExist = false; bool partiallyCheckedExist = false; bool uncheckedExist = false; for(int i=0; i<index.model()->rowCount(index); i++) { Node* childNode = d->nodeFromIndex(index.child(i,0)); if(childNode->Data[Qt::CheckStateRole].toUInt() == Qt::Checked) { checkedExist = true; } else if(childNode->Data[Qt::CheckStateRole].toUInt() == Qt::PartiallyChecked) { partiallyCheckedExist = true; } else if(childNode->Data[Qt::CheckStateRole].toUInt() == Qt::Unchecked) { uncheckedExist = true; } } #ifdef CHECKABLE_COLUMNS if(partiallyCheckedExist || (checkedExist && uncheckedExist)) { node->Data[Qt::CheckStateRole].toUInt() = Qt::PartiallyChecked; } else if(checkedExist) { node->Data[Qt::CheckStateRole].toUInt() = Qt::Checked; } else if(uncheckedExist) { node->Data[Qt::CheckStateRole].toUInt() = Qt::Unchecked; } else { node->Data[Qt::CheckStateRole].toUInt() = Qt::Unchecked; } #endif emit dataChanged(index, index); this->setParentData(index.parent(), value, role); } return true; } //------------------------------------------------------------------------------ void ctkDICOMModel::setDatabase(const QSqlDatabase &db) { Q_D(ctkDICOMModel); this->beginResetModel(); d->DataBase = db; delete d->RootNode; d->RootNode = 0; if (d->DataBase.tables().empty()) { //Q_ASSERT(d->DataBase.isOpen()); this->endResetModel(); return; } d->RootNode = d->createNode(-1, QModelIndex()); this->endResetModel(); // TODO, use hasQuerySize everywhere, not only in setDataBase() bool hasQuerySize = d->RootNode->Query.driver()->hasFeature(QSqlDriver::QuerySize); if (hasQuerySize && d->RootNode->Query.size() > 0) { int newRowCount= d->RootNode->Query.size(); beginInsertRows(QModelIndex(), 0, qMax(0, newRowCount - 1)); d->RootNode->RowCount = newRowCount; d->RootNode->AtEnd = true; endInsertRows(); } d->fetch(QModelIndex(), 256); } //------------------------------------------------------------------------------ void ctkDICOMModel::setDatabase(const QSqlDatabase &db,const QMap<QString, QVariant>& parameters) { Q_D(ctkDICOMModel); this->beginResetModel(); d->DataBase = db; d->SearchParameters = parameters; delete d->RootNode; d->RootNode = 0; if (d->DataBase.tables().empty()) { //Q_ASSERT(d->DataBase.isOpen()); this->endResetModel(); return; } d->RootNode = d->createNode(-1, QModelIndex()); this->endResetModel(); // TODO, use hasQuerySize everywhere, not only in setDataBase() bool hasQuerySize = d->RootNode->Query.driver()->hasFeature(QSqlDriver::QuerySize); if (hasQuerySize && d->RootNode->Query.size() > 0) { int newRowCount= d->RootNode->Query.size(); beginInsertRows(QModelIndex(), 0, qMax(0, newRowCount - 1)); d->RootNode->RowCount = newRowCount; d->RootNode->AtEnd = true; endInsertRows(); } d->fetch(QModelIndex(), 256); } //------------------------------------------------------------------------------ ctkDICOMModel::IndexType ctkDICOMModel::endLevel()const { Q_D(const ctkDICOMModel); return d->EndLevel; } //------------------------------------------------------------------------------ void ctkDICOMModel::setEndLevel(ctkDICOMModel::IndexType level) { Q_D(ctkDICOMModel); d->EndLevel = level; } //------------------------------------------------------------------------------ void ctkDICOMModel::reset() { Q_D(ctkDICOMModel); // this could probably be done in a more elegant way this->setDatabase(d->DataBase); } //------------------------------------------------------------------------------ void ctkDICOMModel::sort(int column, Qt::SortOrder order) { Q_D(ctkDICOMModel); /* The following would work if there is no fetch involved. ORDER BY doesn't just apply on the fetched item. By sorting new items can show up in the model, and we need to be more careful emit layoutAboutToBeChanged(); QModelIndexList oldIndexList = d->modelIndexList(); d->Sort = QString("\"%1\" %2") .arg(d->Headers[column]) .arg(order == Qt::AscendingOrder ? "ASC" : "DESC"); d->updateQueries(d->RootNode); QModelIndexList newIndexList = d->modelIndexList(); Q_ASSERT(oldIndexList.count() == newIndexList.count()); this->changePersistentIndexList(oldIndexList, newIndexList); emit layoutChanged(); */ this->beginResetModel(); delete d->RootNode; d->RootNode = 0; d->Sort = QString("\"%1\" %2") .arg(d->Headers[column][Qt::DisplayRole].toString()) .arg(order == Qt::AscendingOrder ? "ASC" : "DESC"); d->RootNode = d->createNode(-1, QModelIndex()); this->endResetModel(); } //------------------------------------------------------------------------------ bool ctkDICOMModel::setHeaderData ( int section, Qt::Orientation orientation, const QVariant & value, int role) { Q_D(ctkDICOMModel); if (orientation == Qt::Vertical) { return false; } if (section < 0 || section >= d->Headers.size() || d->Headers[section][role] == value) { return false; } d->Headers[section][role] = value; emit this->headerDataChanged(orientation, section, section); return true; }
apache-2.0
aws/aws-sdk-cpp
aws-cpp-sdk-serverlessrepo/source/model/CreateApplicationVersionRequest.cpp
4
1242
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/serverlessrepo/model/CreateApplicationVersionRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::ServerlessApplicationRepository::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateApplicationVersionRequest::CreateApplicationVersionRequest() : m_applicationIdHasBeenSet(false), m_semanticVersionHasBeenSet(false), m_sourceCodeArchiveUrlHasBeenSet(false), m_sourceCodeUrlHasBeenSet(false), m_templateBodyHasBeenSet(false), m_templateUrlHasBeenSet(false) { } Aws::String CreateApplicationVersionRequest::SerializePayload() const { JsonValue payload; if(m_sourceCodeArchiveUrlHasBeenSet) { payload.WithString("sourceCodeArchiveUrl", m_sourceCodeArchiveUrl); } if(m_sourceCodeUrlHasBeenSet) { payload.WithString("sourceCodeUrl", m_sourceCodeUrl); } if(m_templateBodyHasBeenSet) { payload.WithString("templateBody", m_templateBody); } if(m_templateUrlHasBeenSet) { payload.WithString("templateUrl", m_templateUrl); } return payload.View().WriteReadable(); }
apache-2.0
OLR-xray/XRay-NEW
XRay/xr_3da/stalker_net/gamespy.net/serverbrowsing/sb_queryengine.c
4
20014
#include "sb_serverbrowsing.h" #include "sb_internal.h" #ifdef GSI_MANIC_DEBUG // Make sure the server isn't already in the fifo void FIFODebugCheckAdd(SBServerFIFO *fifo, SBServer server) { SBServer aServer = fifo->first; while(aServer != NULL) { assert(aServer != server); aServer = aServer->next; } } // Verify the contents of the fifo void FIFODebugCheck(SBServerFIFO *fifo) { int i=0; SBServer aServer; assert(fifo != NULL); aServer = fifo->first; for (i=0; i < fifo->count; i++) { assert(aServer != NULL); aServer = aServer->next; } } #else #define FIFODebugCheckAdd(a,b) #define FIFODebugCheck(a) #endif //FIFO Queue management functions static void FIFOAddRear(SBServerFIFO *fifo, SBServer server) { FIFODebugCheckAdd(fifo, server); if (fifo->last != NULL) fifo->last->next = server; fifo->last = server; server->next = NULL; if (fifo->first == NULL) fifo->first = server; fifo->count++; FIFODebugCheck(fifo); } static void FIFOAddFront(SBServerFIFO *fifo, SBServer server) { FIFODebugCheckAdd(fifo, server); server->next = fifo->first; fifo->first = server; if (fifo->last == NULL) fifo->last = server; fifo->count++; FIFODebugCheck(fifo); } static SBServer FIFOGetFirst(SBServerFIFO *fifo) { SBServer hold; hold = fifo->first; if (hold != NULL) { fifo->first = hold->next; if (fifo->first == NULL) fifo->last = NULL; fifo->count--; } FIFODebugCheck(fifo); return hold; } static SBBool FIFORemove(SBServerFIFO *fifo, SBServer server) { SBServer hold, prev; prev = NULL; hold = fifo->first; while (hold != NULL) { if (hold == server) //found { if (prev != NULL) //there is a previous.. prev->next = hold->next; if (fifo->first == hold) fifo->first = hold->next; if (fifo->last == hold) fifo->last = prev; fifo->count--; // assert((fifo->count == 0 && fifo->first == NULL && fifo->last == NULL) || fifo->count > 0); return SBTrue; } prev = hold; hold = hold->next; } FIFODebugCheck(fifo); return SBFalse; } static void FIFOClear(SBServerFIFO *fifo) { fifo->first = fifo->last = NULL; fifo->count = 0; FIFODebugCheck(fifo); } #ifdef SB_ICMP_SUPPORT static unsigned short IPChecksum(const unsigned short *buf, int len) { unsigned long cksum = 0; //Calculate the checksum while (len > 1) { cksum += *buf++; len -= sizeof(unsigned short); } //If we have one char left if (len) { cksum += *(unsigned char*)buf; } //Complete the calculations cksum = (cksum >> 16) + (cksum & 0xffff); cksum += (cksum >> 16); //Return the value (inversed) return (unsigned short)(~cksum); } #endif static void QEStartQuery(SBQueryEngine *engine, SBServer server) { unsigned char queryBuffer[256]; int queryLen; gsi_bool querySuccess = gsi_false; struct sockaddr_in saddr; saddr.sin_family = AF_INET; server->updatetime = current_time(); if (server->state & STATE_PENDINGICMPQUERY) //send an ICMP ping request { #ifdef SB_ICMP_SUPPORT #if !defined(SN_SYSTEMS) SBICMPHeader *_icmp = (SBICMPHeader *)(queryBuffer); //todo: alignment issues on PS2 _icmp->type = SB_ICMP_ECHO; _icmp->code = 0; _icmp->un.idseq = server->updatetime; //no need for network byte order since only we read the reply _icmp->cksum = 0; queryLen = sizeof(SBICMPHeader) + 6; memcpy(queryBuffer + sizeof(SBICMPHeader), &server->publicip, 4); //put some data in the echo packet that we can use to verify the reply memcpy(queryBuffer + sizeof(SBICMPHeader) + 4, &server->publicport, 2); _icmp->cksum = IPChecksum((unsigned short *)queryBuffer, queryLen); if (SBServerGetFlags(server) & ICMP_IP_FLAG) //there is a special ICMP address { saddr.sin_addr.s_addr = server->icmpip; } else { saddr.sin_addr.s_addr = server->publicip; } sendto(engine->icmpsock, (char *)queryBuffer, queryLen, 0, (struct sockaddr *)&saddr, sizeof(saddr)); querySuccess = gsi_true; #else int result; sndev_set_ping_ip_type optval; optval.ip_addr = server->icmpip; gsDebugFormat(GSIDebugCat_SB, GSIDebugType_Network, GSIDebugLevel_WarmError, "Attempting to send ICMP ping to %s\r\n", inet_ntoa(*((struct in_addr*)&server->icmpip))); result = sndev_set_options(0, SN_DEV_SET_PING_IP, (void*)&optval, sizeof(optval)); // tell SN to ping this addr if (result==SN_PING_FAIL) { gsDebugFormat(GSIDebugCat_SB, GSIDebugType_Network, GSIDebugLevel_WarmError, "ICMP ping attempt failed on SNSystems (unknown error)\r\n"); querySuccess = gsi_true; // let the SDK process failures as a timed out ping } else if (result==SN_PING_FULL) { gsDebugFormat(GSIDebugCat_SB, GSIDebugType_Network, GSIDebugLevel_WarmError, "ICMP ping attempt failed on SNSystems (SN_PING_FULL)\r\n"); querySuccess = gsi_false; } else querySuccess = gsi_true; #endif #endif } else //send a UDP query { if (engine->queryversion == QVERSION_QR2) { if (server->state & STATE_PENDINGQUERYCHALLENGE) { // send IP verify request now, but send qr2 query later when IP verify returns int pos = 0; queryBuffer[pos++] = QR2_MAGIC_1; queryBuffer[pos++] = QR2_MAGIC_2; queryBuffer[pos++] = 0x09; // ip verify prequery //set the request key memcpy(&queryBuffer[pos], &server->updatetime, 4); pos += 4; queryLen = pos; } else { gsi_u32 challengeNBO = htonl(server->querychallenge); int pos = 0; //set the header queryBuffer[pos++] = QR2_MAGIC_1; queryBuffer[pos++] = QR2_MAGIC_2; queryBuffer[pos++] = 0; memcpy(&queryBuffer[pos], &server->updatetime, 4); //set the request key pos += 4; if (challengeNBO != 0) { memcpy(&queryBuffer[pos], &challengeNBO, 4); // set the challenge pos += 4; } if (server->state & STATE_PENDINGBASICQUERY) { int i; queryBuffer[pos++] = (unsigned char)engine->numserverkeys; for (i = 0 ; i < engine->numserverkeys ; i++) queryBuffer[pos++] = engine->serverkeys[i]; //don't request any player or team keys queryBuffer[pos++] = 0x00; queryBuffer[pos++] = 0x00; queryLen = pos; } else //request all keys for everyone { queryBuffer[pos++] = 0xFF; queryBuffer[pos++] = 0xFF; queryBuffer[pos++] = 0xFF; // Tell the server we support split packets queryBuffer[pos++] = 0x1; queryLen = pos; // 11 } } } else //GOA { if (server->state & STATE_PENDINGBASICQUERY) //original - do a \basic\info\ query { memcpy(queryBuffer, BASIC_GOA_QUERY, BASIC_GOA_QUERY_LEN); queryLen = BASIC_GOA_QUERY_LEN; } else //original - do a \status\ query { memcpy(queryBuffer, FULL_GOA_QUERY, FULL_GOA_QUERY_LEN); queryLen = FULL_GOA_QUERY_LEN; } } if (server->publicip == engine->mypublicip && (server->flags & PRIVATE_IP_FLAG)) //try querying the private IP { saddr.sin_addr.s_addr = server->privateip; saddr.sin_port = server->privateport; } else { saddr.sin_addr.s_addr = server->publicip; saddr.sin_port = server->publicport; } sendto(engine->querysock, (char *)queryBuffer, queryLen, 0, (struct sockaddr *)&saddr, sizeof(saddr)); querySuccess = gsi_true; } //add it to the query list if (gsi_is_true(querySuccess)) FIFOAddRear(&engine->querylist, server); else server->updatetime = 0; } void SBQueryEngineInit(SBQueryEngine *engine, int maxupdates, int queryversion, SBBool lanBrowse, SBEngineCallbackFn callback, void *instance) { // 11-03-2004 : Added by Saad Nader // fix for LANs and unnecessary availability check /////////////////////////////////////////////////// if(lanBrowse == SBFalse) { if(__GSIACResult != GSIACAvailable) return; } SocketStartUp(); engine->queryversion = queryversion; engine->maxupdates = maxupdates; engine->numserverkeys = 0; engine->ListCallback = callback; engine->instance = instance; engine->mypublicip = 0; engine->querysock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); #if defined(SB_ICMP_SUPPORT) #if defined(SN_SYSTEMS) { // reset SNSystems internal ICMP ping structures sndev_set_ping_reset_type optval; optval.timeout_ms = MAX_QUERY_MSEC; // this gets rounded up to 3 sec optval.reserved = 0; sndev_set_options(0, SN_DEV_SET_PING_RESET, &optval, sizeof(optval)); } #else engine->icmpsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); #endif #endif FIFOClear(&engine->pendinglist); FIFOClear(&engine->querylist); } void SBQueryEngineSetPublicIP(SBQueryEngine *engine, goa_uint32 mypublicip) { engine->mypublicip = mypublicip; } void SBEngineHaltUpdates(SBQueryEngine *engine) { FIFOClear(&engine->pendinglist); FIFOClear(&engine->querylist); } void SBEngineCleanup(SBQueryEngine *engine) { closesocket(engine->querysock); #ifdef SB_ICMP_SUPPORT #if !defined(SN_SYSTEMS) closesocket(engine->icmpsock); #endif #endif engine->querysock = INVALID_SOCKET; FIFOClear(&engine->pendinglist); FIFOClear(&engine->querylist); } //NOTE: the server must not be in the pending or update list currently! void SBQueryEngineUpdateServer(SBQueryEngine *engine, SBServer server, int addfront, int querytype, SBBool usequerychallenge) { // Assert state of FIFOs FIFODebugCheckAdd(&engine->pendinglist, server); FIFODebugCheckAdd(&engine->querylist, server); server->state &= (unsigned char)~(STATE_PENDINGBASICQUERY|STATE_PENDINGFULLQUERY|STATE_PENDINGICMPQUERY|STATE_PENDINGQUERYCHALLENGE|STATE_QUERYFAILED); //clear out these flags server->splitResponseBitmap = 0; server->querychallenge = 0; #ifndef SB_ICMP_SUPPORT if (querytype == QTYPE_ICMP) return; // ICMP not supported #endif if (querytype == QTYPE_BASIC) server->state |= STATE_PENDINGBASICQUERY; else if (querytype == QTYPE_FULL) server->state |= STATE_PENDINGFULLQUERY; else if (querytype == QTYPE_ICMP) server->state |= STATE_PENDINGICMPQUERY; else return; // hoterror: unsupported querytype! if (usequerychallenge && (querytype == QTYPE_FULL || querytype == QTYPE_BASIC)) server->state |= STATE_PENDINGQUERYCHALLENGE; if (engine->querylist.count < engine->maxupdates) //add it now.. { QEStartQuery(engine, server); return; } //else need to queue it if (addfront) FIFOAddFront(&engine->pendinglist, server); else FIFOAddRear(&engine->pendinglist, server); } SBServer SBQueryEngineUpdateServerByIP(SBQueryEngine *engine, const char *ip, unsigned short queryport, int addfront, int querytype, SBBool usequerychallenge) { //need to create a new server SBServer server; goa_uint32 ipaddr; ipaddr = inet_addr(ip); server = SBAllocServer(NULL, ipaddr, htons(queryport)); server->flags = UNSOLICITED_UDP_FLAG; //we assume we can talk directly to it SBQueryEngineUpdateServer(engine, server, addfront, querytype, usequerychallenge); return server; } static void ParseSingleQR2Reply(SBQueryEngine *engine, SBServer server, char *data, int len) { int i; int dlen; // 0x00 == qr2 query response, 0x09 == qr2 challenge response if (data[0] != 0x00 && data[0] != 0x09) return; //we could test the request key here for added security, or skip data += 5; len -= 5; if (server->state & STATE_PENDINGQUERYCHALLENGE) { server->state &= (unsigned char)~(STATE_PENDINGQUERYCHALLENGE); if (len > 0) { server->querychallenge = (gsi_u32)atoi(data); FIFORemove(&engine->querylist, server); // remove it QEStartQuery(engine, server); // readd it with a keys query engine->ListCallback(engine, qe_challengereceived, server, engine->instance); return; } } else if (server->state & STATE_PENDINGBASICQUERY) { //need to pick out the keys they selected for (i = 0 ; i < engine->numserverkeys ; i++) { dlen = NTSLengthSB(data, len); if (dlen < 0) break; //add the value SBServerAddKeyValue(server, qr2_registered_key_list[engine->serverkeys[i]], data); data += dlen; len -= dlen; } server->state |= STATE_BASICKEYS|STATE_VALIDPING; } else //need to parse out all the keys { // Is this a split packet format? if (*data && strncmp("splitnum", data, 8)==0) { SBServerParseQR2FullKeysSplit(server, data, len); if (server->splitResponseBitmap != 0xFF) return; server->state |= STATE_FULLKEYS|STATE_BASICKEYS|STATE_VALIDPING; } else { // single packet SBServerParseQR2FullKeysSingle(server, data, len); server->state |= STATE_FULLKEYS|STATE_BASICKEYS|STATE_VALIDPING; } } server->state &= (unsigned char)~(STATE_PENDINGBASICQUERY|STATE_PENDINGFULLQUERY); server->updatetime = current_time() - server->updatetime; FIFORemove(&engine->querylist, server); engine->ListCallback(engine, qe_updatesuccess, server, engine->instance); } static void ParseSingleGOAReply(SBQueryEngine *engine, SBServer server, char *data, int len) { int isfinal; //need to check before parse as it will modify the string isfinal = (strstr(data,"\\final\\") != NULL); SBServerParseKeyVals(server, data); if (isfinal) { if (server->state & STATE_PENDINGBASICQUERY) server->state |= STATE_BASICKEYS|STATE_VALIDPING; else server->state |= STATE_FULLKEYS|STATE_VALIDPING; server->state &= (unsigned char)~(STATE_PENDINGBASICQUERY|STATE_PENDINGFULLQUERY); server->updatetime = current_time() - server->updatetime; FIFORemove(&engine->querylist, server); engine->ListCallback(engine, qe_updatesuccess, server, engine->instance); } GSI_UNUSED(len); } static SBBool ParseSingleICMPReply(SBQueryEngine *engine, SBServer server, char *data, int len) { #ifdef SB_ICMP_SUPPORT SBIPHeader *ipheader = (SBIPHeader *)data; SBICMPHeader *icmpheader; int ipheaderlen; goa_uint32 packetpublicip; unsigned short packetpublicport; //todo: byte alignment on PS2 ipheaderlen = (u_char)(ipheader->ip_hl_ver & 15); ipheaderlen *= 4; icmpheader = (SBICMPHeader *)(data + ipheaderlen); if (icmpheader->type != SB_ICMP_ECHO_REPLY) return SBFalse; if (icmpheader->un.idseq != server->updatetime) return SBFalse; if (len < ipheaderlen + (int)sizeof(SBICMPHeader) + 6) return SBFalse; //not enough data //check the server IP and port memcpy(&packetpublicip, data + ipheaderlen + sizeof(SBICMPHeader), 4); memcpy(&packetpublicport, data + ipheaderlen + sizeof(SBICMPHeader) + 4, 2); if (packetpublicport != server->publicport || packetpublicip != server->publicip) return SBFalse; //else its a valid echo server->updatetime = current_time() - server->updatetime; server->state |= STATE_VALIDPING; server->state &= (unsigned char)~(STATE_PENDINGICMPQUERY); FIFORemove(&engine->querylist, server); engine->ListCallback(engine, qe_updatesuccess, server, engine->instance); #else GSI_UNUSED(engine); GSI_UNUSED(server); GSI_UNUSED(data); GSI_UNUSED(len); #endif return SBTrue; } #if defined(SN_SYSTEMS) && defined(SB_ICMP_SUPPORT) static void ProcessIncomingICMPReplies(SBQueryEngine *engine) { SBServer server; int result = 0; int found = 0; int i = 0; sndev_stat_ping_times_type optval; gsi_i32 optsize = sizeof(optval); // Get the ICMP replies from the SNSystems stack result = sndev_get_status(0, SN_DEV_STAT_PING_TIMES, (void*)&optval, &optsize); if (result != 0) { gsDebugFormat(GSIDebugCat_SB, GSIDebugType_Network, GSIDebugLevel_WarmError, "Failed on sndev_get_status (checking ICMP pings): %d\r\n", result); return; } if (optval.num_entries == 0) return; // no outstanding pings (according to sn_systems) // match servers to ping responses for (server = engine->querylist.first; server != NULL; server = server->next) { if ((server->state & STATE_PENDINGICMPQUERY) == 0 || (server->flags & ICMP_IP_FLAG) == 0) continue; // server not flagged for ICMP // find this server for (i=0; i<optval.num_entries; i++) { if (server->icmpip == optval.times[i].ip_addr) { if (optval.times[i].status == SN_PING_TIMES_CODE_GOTREPLY) { server->updatetime = optval.times[i].time_ms; server->state |= STATE_VALIDPING; server->state &= (unsigned char)~(STATE_PENDINGICMPQUERY); FIFORemove(&engine->querylist, server); engine->ListCallback(engine, qe_updatesuccess, server, engine->instance); } //else // let query engine timeout queries on its own (for simplicity) found++; if (found == optval.num_entries) return; // found them all } } } } #endif // SN_SYSTEMS && SB_ICMP_SUPPORT static void ProcessIncomingReplies(SBQueryEngine *engine, SBBool icmpSocket) { int i; char indata[MAX_RECVFROM_SIZE]; struct sockaddr_in saddr; int saddrlen = sizeof(saddr); SBServer server; SOCKET recvSock = 0; if (icmpSocket) { #ifdef SB_ICMP_SUPPORT #if defined(SN_SYSTEMS) ProcessIncomingICMPReplies(engine); return; #else recvSock = engine->icmpsock; #endif #endif } else { recvSock = engine->querysock; } // Process all information in the socket buffer while(CanReceiveOnSocket(recvSock)) { i = (int)recvfrom(recvSock, indata, sizeof(indata) - 1, 0, (struct sockaddr *)&saddr, &saddrlen); if (gsiSocketIsError(i)) break; indata[i] = 0; //find the server in our query list for (server = engine->querylist.first ; server != NULL ; server = server->next) { if ((icmpSocket && (server->flags & ICMP_IP_FLAG) && server->icmpip == saddr.sin_addr.s_addr) || //if it's an ICMP query and it matches the ICMP address (server->publicip == saddr.sin_addr.s_addr && (server->publicport == saddr.sin_port || icmpSocket)) || //if it matches public - port doesnt need to match for ICMP (server->publicip == engine->mypublicip && (server->flags & PRIVATE_IP_FLAG) && server->privateip == saddr.sin_addr.s_addr && server->privateport == saddr.sin_port)) //or has a private, and matches { if (icmpSocket) { if (ParseSingleICMPReply(engine, server, indata, i)) break; //only break if it matches exactly, since we may have multiple outstanding pings to the same ICMPIP for different servers! } else { if (engine->queryversion == QVERSION_QR2) ParseSingleQR2Reply(engine, server, indata, i); else ParseSingleGOAReply(engine, server, indata, i); break; } } } } } static void TimeoutOldQueries(SBQueryEngine *engine) { gsi_time ctime = current_time(); while (engine->querylist.first != NULL) { if (ctime > engine->querylist.first->updatetime + MAX_QUERY_MSEC) { engine->querylist.first->flags |= STATE_QUERYFAILED; engine->querylist.first->updatetime = MAX_QUERY_MSEC; engine->querylist.first->flags &= (unsigned char)~(STATE_PENDINGBASICQUERY|STATE_PENDINGFULLQUERY|STATE_PENDINGICMPQUERY); engine->ListCallback(engine, qe_updatefailed, engine->querylist.first, engine->instance); FIFOGetFirst(&engine->querylist); } else break; //since servers are added in FIFO order, nothing later can have already expired } } static void QueueNextQueries(SBQueryEngine *engine) { while (engine->querylist.count < engine->maxupdates && engine->pendinglist.count > 0) { SBServer server = FIFOGetFirst(&engine->pendinglist); QEStartQuery(engine, server); } } void SBQueryEngineThink(SBQueryEngine *engine) { if (engine->querylist.count == 0) //not querying anything - we can go away return; ProcessIncomingReplies(engine, SBFalse); #ifdef SB_ICMP_SUPPORT ProcessIncomingReplies(engine, SBTrue); #endif TimeoutOldQueries(engine); if (engine->pendinglist.count > 0) QueueNextQueries(engine); if (engine->querylist.count == 0) //we are now idle.. engine->ListCallback(engine, qe_engineidle, NULL, engine->instance); } void SBQueryEngineAddQueryKey(SBQueryEngine *engine, unsigned char keyid) { if (engine->numserverkeys < MAX_QUERY_KEYS) engine->serverkeys[engine->numserverkeys++] = keyid; } //remove a server from our update FIFOs void SBQueryEngineRemoveServerFromFIFOs(SBQueryEngine *engine, SBServer server) { SBBool ret; // remove the server from the current query list ret = FIFORemove(&engine->querylist, server); if(ret) return; // -- Caution: assumes that server will not be in pendinglist FIFORemove(&engine->pendinglist, server); }
apache-2.0
michelborgess/RealOne-Victara-Kernel
arch/arm/mach-msm/rpm-regulator-smd.c
1286
50051
/* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #define pr_fmt(fmt) "%s: " fmt, __func__ #include <linux/module.h> #include <linux/err.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/string.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/regulator/driver.h> #include <linux/regulator/machine.h> #include <linux/regulator/of_regulator.h> #include <mach/rpm-smd.h> #include <mach/rpm-regulator-smd.h> #include <mach/socinfo.h> /* Debug Definitions */ enum { RPM_VREG_DEBUG_REQUEST = BIT(0), RPM_VREG_DEBUG_FULL_REQUEST = BIT(1), RPM_VREG_DEBUG_DUPLICATE = BIT(2), }; static int rpm_vreg_debug_mask; module_param_named( debug_mask, rpm_vreg_debug_mask, int, S_IRUSR | S_IWUSR ); #define vreg_err(req, fmt, ...) \ pr_err("%s: " fmt, req->rdesc.name, ##__VA_ARGS__) /* RPM regulator request types */ enum rpm_regulator_smd_type { RPM_REGULATOR_SMD_TYPE_LDO, RPM_REGULATOR_SMD_TYPE_SMPS, RPM_REGULATOR_SMD_TYPE_VS, RPM_REGULATOR_SMD_TYPE_NCP, RPM_REGULATOR_SMD_TYPE_MAX, }; /* RPM resource parameters */ enum rpm_regulator_param_index { RPM_REGULATOR_PARAM_ENABLE, RPM_REGULATOR_PARAM_VOLTAGE, RPM_REGULATOR_PARAM_CURRENT, RPM_REGULATOR_PARAM_MODE_LDO, RPM_REGULATOR_PARAM_MODE_SMPS, RPM_REGULATOR_PARAM_PIN_CTRL_ENABLE, RPM_REGULATOR_PARAM_PIN_CTRL_MODE, RPM_REGULATOR_PARAM_FREQUENCY, RPM_REGULATOR_PARAM_HEAD_ROOM, RPM_REGULATOR_PARAM_QUIET_MODE, RPM_REGULATOR_PARAM_FREQ_REASON, RPM_REGULATOR_PARAM_CORNER, RPM_REGULATOR_PARAM_BYPASS, RPM_REGULATOR_PARAM_FLOOR_CORNER, RPM_REGULATOR_PARAM_MAX, }; enum rpm_regulator_smps_mode { RPM_REGULATOR_SMPS_MODE_AUTO = 0, RPM_REGULATOR_SMPS_MODE_IPEAK = 1, RPM_REGULATOR_SMPS_MODE_PWM = 2, }; enum rpm_regulator_ldo_mode { RPM_REGULATOR_LDO_MODE_IPEAK = 0, RPM_REGULATOR_LDO_MODE_HPM = 1, }; #define RPM_SET_CONFIG_ACTIVE BIT(0) #define RPM_SET_CONFIG_SLEEP BIT(1) #define RPM_SET_CONFIG_BOTH (RPM_SET_CONFIG_ACTIVE \ | RPM_SET_CONFIG_SLEEP) struct rpm_regulator_param { char *name; char *property_name; u32 key; u32 min; u32 max; u32 supported_regulator_types; }; #define PARAM(_idx, _support_ldo, _support_smps, _support_vs, _support_ncp, \ _name, _min, _max, _property_name) \ [RPM_REGULATOR_PARAM_##_idx] = { \ .name = _name, \ .property_name = _property_name, \ .min = _min, \ .max = _max, \ .supported_regulator_types = \ _support_ldo << RPM_REGULATOR_SMD_TYPE_LDO | \ _support_smps << RPM_REGULATOR_SMD_TYPE_SMPS | \ _support_vs << RPM_REGULATOR_SMD_TYPE_VS | \ _support_ncp << RPM_REGULATOR_SMD_TYPE_NCP, \ } static struct rpm_regulator_param params[RPM_REGULATOR_PARAM_MAX] = { /* ID LDO SMPS VS NCP name min max property-name */ PARAM(ENABLE, 1, 1, 1, 1, "swen", 0, 1, "qcom,init-enable"), PARAM(VOLTAGE, 1, 1, 0, 1, "uv", 0, 0x7FFFFFF, "qcom,init-voltage"), PARAM(CURRENT, 1, 1, 0, 0, "ma", 0, 0x1FFF, "qcom,init-current"), PARAM(MODE_LDO, 1, 0, 0, 0, "lsmd", 0, 1, "qcom,init-ldo-mode"), PARAM(MODE_SMPS, 0, 1, 0, 0, "ssmd", 0, 2, "qcom,init-smps-mode"), PARAM(PIN_CTRL_ENABLE, 1, 1, 1, 0, "pcen", 0, 0xF, "qcom,init-pin-ctrl-enable"), PARAM(PIN_CTRL_MODE, 1, 1, 1, 0, "pcmd", 0, 0x1F, "qcom,init-pin-ctrl-mode"), PARAM(FREQUENCY, 0, 1, 0, 1, "freq", 0, 31, "qcom,init-frequency"), PARAM(HEAD_ROOM, 1, 0, 0, 1, "hr", 0, 0x7FFFFFFF, "qcom,init-head-room"), PARAM(QUIET_MODE, 0, 1, 0, 0, "qm", 0, 2, "qcom,init-quiet-mode"), PARAM(FREQ_REASON, 0, 1, 0, 1, "resn", 0, 8, "qcom,init-freq-reason"), PARAM(CORNER, 1, 1, 0, 0, "corn", 0, 6, "qcom,init-voltage-corner"), PARAM(BYPASS, 1, 0, 0, 0, "bypa", 0, 1, "qcom,init-disallow-bypass"), PARAM(FLOOR_CORNER, 1, 1, 0, 0, "vfc", 0, 6, "qcom,init-voltage-floor-corner"), }; struct rpm_regulator_mode_map { int ldo_mode; int smps_mode; }; static struct rpm_regulator_mode_map mode_mapping[] = { [RPM_REGULATOR_MODE_AUTO] = {-1, RPM_REGULATOR_SMPS_MODE_AUTO}, [RPM_REGULATOR_MODE_IPEAK] = {RPM_REGULATOR_LDO_MODE_IPEAK, RPM_REGULATOR_SMPS_MODE_IPEAK}, [RPM_REGULATOR_MODE_HPM] = {RPM_REGULATOR_LDO_MODE_HPM, RPM_REGULATOR_SMPS_MODE_PWM}, }; struct rpm_vreg_request { u32 param[RPM_REGULATOR_PARAM_MAX]; u32 valid; u32 modified; }; struct rpm_vreg { struct rpm_vreg_request aggr_req_active; struct rpm_vreg_request aggr_req_sleep; struct list_head reg_list; const char *resource_name; u32 resource_id; bool allow_atomic; int regulator_type; int hpm_min_load; int enable_time; struct spinlock slock; struct mutex mlock; unsigned long flags; bool sleep_request_sent; bool apps_only; struct msm_rpm_request *handle_active; struct msm_rpm_request *handle_sleep; }; struct rpm_regulator { struct regulator_desc rdesc; struct regulator_dev *rdev; struct rpm_vreg *rpm_vreg; struct list_head list; bool set_active; bool set_sleep; bool always_send_voltage; bool always_send_current; struct rpm_vreg_request req; int system_load; int min_uV; int max_uV; }; /* * This voltage in uV is returned by get_voltage functions when there is no way * to determine the current voltage level. It is needed because the regulator * framework treats a 0 uV voltage as an error. */ #define VOLTAGE_UNKNOWN 1 /* * Regulator requests sent in the active set take effect immediately. Requests * sent in the sleep set take effect when the Apps processor transitions into * RPM assisted power collapse. For any given regulator, if an active set * request is present, but not a sleep set request, then the active set request * is used at all times, even when the Apps processor is power collapsed. * * The rpm-regulator-smd takes advantage of this default usage of the active set * request by only sending a sleep set request if it differs from the * corresponding active set request. */ #define RPM_SET_ACTIVE MSM_RPM_CTX_ACTIVE_SET #define RPM_SET_SLEEP MSM_RPM_CTX_SLEEP_SET static u32 rpm_vreg_string_to_int(const u8 *str) { int i, len; u32 output = 0; len = strnlen(str, sizeof(u32)); for (i = 0; i < len; i++) output |= str[i] << (i * 8); return output; } static inline void rpm_vreg_lock(struct rpm_vreg *rpm_vreg) { if (rpm_vreg->allow_atomic) spin_lock_irqsave(&rpm_vreg->slock, rpm_vreg->flags); else mutex_lock(&rpm_vreg->mlock); } static inline void rpm_vreg_unlock(struct rpm_vreg *rpm_vreg) { if (rpm_vreg->allow_atomic) spin_unlock_irqrestore(&rpm_vreg->slock, rpm_vreg->flags); else mutex_unlock(&rpm_vreg->mlock); } static inline bool rpm_vreg_active_or_sleep_enabled(struct rpm_vreg *rpm_vreg) { return (rpm_vreg->aggr_req_active.param[RPM_REGULATOR_PARAM_ENABLE] && (rpm_vreg->aggr_req_active.valid & BIT(RPM_REGULATOR_PARAM_ENABLE))) || ((rpm_vreg->aggr_req_sleep.param[RPM_REGULATOR_PARAM_ENABLE]) && (rpm_vreg->aggr_req_sleep.valid & BIT(RPM_REGULATOR_PARAM_ENABLE))); } static inline bool rpm_vreg_shared_active_or_sleep_enabled_valid (struct rpm_vreg *rpm_vreg) { return !rpm_vreg->apps_only && ((rpm_vreg->aggr_req_active.valid & BIT(RPM_REGULATOR_PARAM_ENABLE)) || (rpm_vreg->aggr_req_sleep.valid & BIT(RPM_REGULATOR_PARAM_ENABLE))); } /* * This is used when voting for LPM or HPM by subtracting or adding to the * hpm_min_load of a regulator. It has units of uA. */ #define LOAD_THRESHOLD_STEP 1000 static inline int rpm_vreg_hpm_min_uA(struct rpm_vreg *rpm_vreg) { return rpm_vreg->hpm_min_load; } static inline int rpm_vreg_lpm_max_uA(struct rpm_vreg *rpm_vreg) { return rpm_vreg->hpm_min_load - LOAD_THRESHOLD_STEP; } #define MICRO_TO_MILLI(uV) ((uV) / 1000) #define MILLI_TO_MICRO(uV) ((uV) * 1000) #define DEBUG_PRINT_BUFFER_SIZE 512 #define REQ_SENT 0 #define REQ_PREV 1 #define REQ_CACHED 2 #define REQ_TYPES 3 static void rpm_regulator_req(struct rpm_regulator *regulator, int set, bool sent) { char buf[DEBUG_PRINT_BUFFER_SIZE]; size_t buflen = DEBUG_PRINT_BUFFER_SIZE; struct rpm_vreg *rpm_vreg = regulator->rpm_vreg; struct rpm_vreg_request *aggr; bool first; u32 mask[REQ_TYPES] = {0, 0, 0}; const char *req_names[REQ_TYPES] = {"sent", "prev", "cached"}; int pos = 0; int i, j; aggr = (set == RPM_SET_ACTIVE) ? &rpm_vreg->aggr_req_active : &rpm_vreg->aggr_req_sleep; if (rpm_vreg_debug_mask & RPM_VREG_DEBUG_DUPLICATE) { mask[REQ_SENT] = aggr->modified; mask[REQ_PREV] = aggr->valid & ~aggr->modified; } else if (sent && (rpm_vreg_debug_mask & RPM_VREG_DEBUG_FULL_REQUEST)) { mask[REQ_SENT] = aggr->modified; mask[REQ_PREV] = aggr->valid & ~aggr->modified; } else if (sent && (rpm_vreg_debug_mask & RPM_VREG_DEBUG_REQUEST)) { mask[REQ_SENT] = aggr->modified; } if (!(mask[REQ_SENT] | mask[REQ_PREV])) return; if (set == RPM_SET_SLEEP && !rpm_vreg->sleep_request_sent) { mask[REQ_CACHED] = mask[REQ_SENT] | mask[REQ_PREV]; mask[REQ_SENT] = 0; mask[REQ_PREV] = 0; } pos += scnprintf(buf + pos, buflen - pos, "%s%s: ", KERN_INFO, __func__); pos += scnprintf(buf + pos, buflen - pos, "%s %u (%s): s=%s", rpm_vreg->resource_name, rpm_vreg->resource_id, regulator->rdesc.name, (set == RPM_SET_ACTIVE ? "act" : "slp")); for (i = 0; i < REQ_TYPES; i++) { if (mask[i]) pos += scnprintf(buf + pos, buflen - pos, "; %s: ", req_names[i]); first = true; for (j = 0; j < RPM_REGULATOR_PARAM_MAX; j++) { if (mask[i] & BIT(j)) { pos += scnprintf(buf + pos, buflen - pos, "%s%s=%u", (first ? "" : ", "), params[j].name, aggr->param[j]); first = false; } } } pos += scnprintf(buf + pos, buflen - pos, "\n"); printk(buf); } #define RPM_VREG_SET_PARAM(_regulator, _param, _val) \ { \ (_regulator)->req.param[RPM_REGULATOR_PARAM_##_param] = _val; \ (_regulator)->req.modified |= BIT(RPM_REGULATOR_PARAM_##_param); \ } \ static int rpm_vreg_add_kvp_to_request(struct rpm_vreg *rpm_vreg, const u32 *param, int idx, u32 set) { struct msm_rpm_request *handle; handle = (set == RPM_SET_ACTIVE ? rpm_vreg->handle_active : rpm_vreg->handle_sleep); if (rpm_vreg->allow_atomic) return msm_rpm_add_kvp_data_noirq(handle, params[idx].key, (u8 *)&param[idx], 4); else return msm_rpm_add_kvp_data(handle, params[idx].key, (u8 *)&param[idx], 4); } static void rpm_vreg_check_modified_requests(const u32 *prev_param, const u32 *param, u32 prev_valid, u32 *modified) { u32 value_changed = 0; int i; for (i = 0; i < RPM_REGULATOR_PARAM_MAX; i++) { if (param[i] != prev_param[i]) value_changed |= BIT(i); } /* * Only keep bits that are for changed parameters or previously * invalid parameters. */ *modified &= value_changed | ~prev_valid; } static int rpm_vreg_add_modified_requests(struct rpm_regulator *regulator, u32 set, const u32 *param, u32 modified) { struct rpm_vreg *rpm_vreg = regulator->rpm_vreg; int rc = 0; int i; for (i = 0; i < RPM_REGULATOR_PARAM_MAX; i++) { /* Only send requests for modified parameters. */ if (modified & BIT(i)) { rc = rpm_vreg_add_kvp_to_request(rpm_vreg, param, i, set); if (rc) { vreg_err(regulator, "add KVP failed: %s %u; %s, rc=%d\n", rpm_vreg->resource_name, rpm_vreg->resource_id, params[i].name, rc); return rc; } } } return rc; } static int rpm_vreg_send_request(struct rpm_regulator *regulator, u32 set) { struct rpm_vreg *rpm_vreg = regulator->rpm_vreg; struct msm_rpm_request *handle = (set == RPM_SET_ACTIVE ? rpm_vreg->handle_active : rpm_vreg->handle_sleep); int rc; if (rpm_vreg->allow_atomic) rc = msm_rpm_wait_for_ack_noirq(msm_rpm_send_request_noirq( handle)); else rc = msm_rpm_wait_for_ack(msm_rpm_send_request(handle)); if (rc) vreg_err(regulator, "msm rpm send failed: %s %u; set=%s, " "rc=%d\n", rpm_vreg->resource_name, rpm_vreg->resource_id, (set == RPM_SET_ACTIVE ? "act" : "slp"), rc); return rc; } #define RPM_VREG_AGGR_MIN(_idx, _param_aggr, _param_reg) \ { \ _param_aggr[RPM_REGULATOR_PARAM_##_idx] \ = min(_param_aggr[RPM_REGULATOR_PARAM_##_idx], \ _param_reg[RPM_REGULATOR_PARAM_##_idx]); \ } #define RPM_VREG_AGGR_MAX(_idx, _param_aggr, _param_reg) \ { \ _param_aggr[RPM_REGULATOR_PARAM_##_idx] \ = max(_param_aggr[RPM_REGULATOR_PARAM_##_idx], \ _param_reg[RPM_REGULATOR_PARAM_##_idx]); \ } #define RPM_VREG_AGGR_SUM(_idx, _param_aggr, _param_reg) \ { \ _param_aggr[RPM_REGULATOR_PARAM_##_idx] \ += _param_reg[RPM_REGULATOR_PARAM_##_idx]; \ } #define RPM_VREG_AGGR_OR(_idx, _param_aggr, _param_reg) \ { \ _param_aggr[RPM_REGULATOR_PARAM_##_idx] \ |= _param_reg[RPM_REGULATOR_PARAM_##_idx]; \ } /* * Aggregation is performed on each parameter based on the way that the RPM * aggregates that type internally between RPM masters. */ static void rpm_vreg_aggregate_params(u32 *param_aggr, const u32 *param_reg) { RPM_VREG_AGGR_MAX(ENABLE, param_aggr, param_reg); RPM_VREG_AGGR_MAX(VOLTAGE, param_aggr, param_reg); RPM_VREG_AGGR_SUM(CURRENT, param_aggr, param_reg); RPM_VREG_AGGR_MAX(MODE_LDO, param_aggr, param_reg); RPM_VREG_AGGR_MAX(MODE_SMPS, param_aggr, param_reg); RPM_VREG_AGGR_OR(PIN_CTRL_ENABLE, param_aggr, param_reg); RPM_VREG_AGGR_OR(PIN_CTRL_MODE, param_aggr, param_reg); RPM_VREG_AGGR_MIN(FREQUENCY, param_aggr, param_reg); RPM_VREG_AGGR_MAX(HEAD_ROOM, param_aggr, param_reg); RPM_VREG_AGGR_MAX(QUIET_MODE, param_aggr, param_reg); RPM_VREG_AGGR_MAX(FREQ_REASON, param_aggr, param_reg); RPM_VREG_AGGR_MAX(CORNER, param_aggr, param_reg); RPM_VREG_AGGR_MAX(BYPASS, param_aggr, param_reg); RPM_VREG_AGGR_MAX(FLOOR_CORNER, param_aggr, param_reg); } static int rpm_vreg_aggregate_requests(struct rpm_regulator *regulator) { struct rpm_vreg *rpm_vreg = regulator->rpm_vreg; u32 param_active[RPM_REGULATOR_PARAM_MAX]; u32 param_sleep[RPM_REGULATOR_PARAM_MAX]; u32 modified_active, modified_sleep; struct rpm_regulator *reg; bool sleep_set_differs = false; bool send_active = false; bool send_sleep = false; int rc = 0; int i; memset(param_active, 0, sizeof(param_active)); memset(param_sleep, 0, sizeof(param_sleep)); modified_active = rpm_vreg->aggr_req_active.modified; modified_sleep = rpm_vreg->aggr_req_sleep.modified; /* * Aggregate all of the requests for this regulator in both active * and sleep sets. */ list_for_each_entry(reg, &rpm_vreg->reg_list, list) { if (reg->set_active) { rpm_vreg_aggregate_params(param_active, reg->req.param); modified_active |= reg->req.modified; } if (reg->set_sleep) { rpm_vreg_aggregate_params(param_sleep, reg->req.param); modified_sleep |= reg->req.modified; } } /* * Check if the aggregated sleep set parameter values differ from the * aggregated active set parameter values. */ if (!rpm_vreg->sleep_request_sent) { for (i = 0; i < RPM_REGULATOR_PARAM_MAX; i++) { if ((param_active[i] != param_sleep[i]) && (modified_sleep & BIT(i))) { sleep_set_differs = true; break; } } } /* Add KVPs to the active set RPM request if they have new values. */ rpm_vreg_check_modified_requests(rpm_vreg->aggr_req_active.param, param_active, rpm_vreg->aggr_req_active.valid, &modified_active); rc = rpm_vreg_add_modified_requests(regulator, RPM_SET_ACTIVE, param_active, modified_active); if (rc) return rc; send_active = modified_active; /* * Sleep set configurations are only sent if they differ from the * active set values. This is because the active set values will take * effect during rpm assisted power collapse in the absence of sleep set * values. * * However, once a sleep set request is sent for a given regulator, * additional sleep set requests must be sent in the future even if they * match the corresponding active set requests. */ if (rpm_vreg->sleep_request_sent || sleep_set_differs) { /* Add KVPs to the sleep set RPM request if they are new. */ rpm_vreg_check_modified_requests(rpm_vreg->aggr_req_sleep.param, param_sleep, rpm_vreg->aggr_req_sleep.valid, &modified_sleep); rc = rpm_vreg_add_modified_requests(regulator, RPM_SET_SLEEP, param_sleep, modified_sleep); if (rc) return rc; send_sleep = modified_sleep; } /* Send active set request to the RPM if it contains new KVPs. */ if (send_active) { rc = rpm_vreg_send_request(regulator, RPM_SET_ACTIVE); if (rc) return rc; rpm_vreg->aggr_req_active.valid |= modified_active; } /* Store the results of the aggregation. */ rpm_vreg->aggr_req_active.modified = modified_active; memcpy(rpm_vreg->aggr_req_active.param, param_active, sizeof(param_active)); /* Handle debug printing of the active set request. */ rpm_regulator_req(regulator, RPM_SET_ACTIVE, send_active); if (send_active) rpm_vreg->aggr_req_active.modified = 0; /* Send sleep set request to the RPM if it contains new KVPs. */ if (send_sleep) { rc = rpm_vreg_send_request(regulator, RPM_SET_SLEEP); if (rc) return rc; else rpm_vreg->sleep_request_sent = true; rpm_vreg->aggr_req_sleep.valid |= modified_sleep; } /* Store the results of the aggregation. */ rpm_vreg->aggr_req_sleep.modified = modified_sleep; memcpy(rpm_vreg->aggr_req_sleep.param, param_sleep, sizeof(param_sleep)); /* Handle debug printing of the sleep set request. */ rpm_regulator_req(regulator, RPM_SET_SLEEP, send_sleep); if (send_sleep) rpm_vreg->aggr_req_sleep.modified = 0; /* * Loop over all requests for this regulator to update the valid and * modified values for use in future aggregation. */ list_for_each_entry(reg, &rpm_vreg->reg_list, list) { reg->req.valid |= reg->req.modified; reg->req.modified = 0; } return rc; } static int rpm_vreg_is_enabled(struct regulator_dev *rdev) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); return reg->req.param[RPM_REGULATOR_PARAM_ENABLE]; } static int rpm_vreg_enable(struct regulator_dev *rdev) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); int rc; u32 prev_enable; rpm_vreg_lock(reg->rpm_vreg); prev_enable = reg->req.param[RPM_REGULATOR_PARAM_ENABLE]; RPM_VREG_SET_PARAM(reg, ENABLE, 1); rc = rpm_vreg_aggregate_requests(reg); if (rc) { vreg_err(reg, "enable failed, rc=%d", rc); RPM_VREG_SET_PARAM(reg, ENABLE, prev_enable); } rpm_vreg_unlock(reg->rpm_vreg); return rc; } static int rpm_vreg_disable(struct regulator_dev *rdev) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); int rc; u32 prev_enable; rpm_vreg_lock(reg->rpm_vreg); prev_enable = reg->req.param[RPM_REGULATOR_PARAM_ENABLE]; RPM_VREG_SET_PARAM(reg, ENABLE, 0); rc = rpm_vreg_aggregate_requests(reg); if (rc) { vreg_err(reg, "enable failed, rc=%d", rc); RPM_VREG_SET_PARAM(reg, ENABLE, prev_enable); } rpm_vreg_unlock(reg->rpm_vreg); return rc; } static int rpm_vreg_set_voltage(struct regulator_dev *rdev, int min_uV, int max_uV, unsigned *selector) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); int rc = 0; u32 prev_voltage; rpm_vreg_lock(reg->rpm_vreg); prev_voltage = reg->req.param[RPM_REGULATOR_PARAM_VOLTAGE]; RPM_VREG_SET_PARAM(reg, VOLTAGE, min_uV); /* * Only send a new voltage if the regulator is currently enabled or * if the regulator has been configured to always send voltage updates. */ if (reg->always_send_voltage || rpm_vreg_active_or_sleep_enabled(reg->rpm_vreg) || rpm_vreg_shared_active_or_sleep_enabled_valid(reg->rpm_vreg)) rc = rpm_vreg_aggregate_requests(reg); if (rc) { vreg_err(reg, "set voltage failed, rc=%d", rc); RPM_VREG_SET_PARAM(reg, VOLTAGE, prev_voltage); } rpm_vreg_unlock(reg->rpm_vreg); return rc; } static int rpm_vreg_get_voltage(struct regulator_dev *rdev) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); int uV; uV = reg->req.param[RPM_REGULATOR_PARAM_VOLTAGE]; if (uV == 0) uV = VOLTAGE_UNKNOWN; return uV; } static int rpm_vreg_set_voltage_corner(struct regulator_dev *rdev, int min_uV, int max_uV, unsigned *selector) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); int rc = 0; int corner; u32 prev_corner; /* * Translate from values which work as inputs in the * regulator_set_voltage function to the actual corner values * sent to the RPM. */ corner = min_uV - RPM_REGULATOR_CORNER_NONE; if (corner < params[RPM_REGULATOR_PARAM_CORNER].min || corner > params[RPM_REGULATOR_PARAM_CORNER].max) { vreg_err(reg, "corner=%d is not within allowed range: [%u, %u]\n", corner, params[RPM_REGULATOR_PARAM_CORNER].min, params[RPM_REGULATOR_PARAM_CORNER].max); return -EINVAL; } rpm_vreg_lock(reg->rpm_vreg); prev_corner = reg->req.param[RPM_REGULATOR_PARAM_CORNER]; RPM_VREG_SET_PARAM(reg, CORNER, corner); /* * Only send a new voltage corner if the regulator is currently enabled * or if the regulator has been configured to always send voltage * updates. */ if (reg->always_send_voltage || rpm_vreg_active_or_sleep_enabled(reg->rpm_vreg) || rpm_vreg_shared_active_or_sleep_enabled_valid(reg->rpm_vreg)) rc = rpm_vreg_aggregate_requests(reg); if (rc) { vreg_err(reg, "set voltage corner failed, rc=%d", rc); RPM_VREG_SET_PARAM(reg, CORNER, prev_corner); } rpm_vreg_unlock(reg->rpm_vreg); return rc; } static int rpm_vreg_get_voltage_corner(struct regulator_dev *rdev) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); return reg->req.param[RPM_REGULATOR_PARAM_CORNER] + RPM_REGULATOR_CORNER_NONE; } static int rpm_vreg_set_voltage_floor_corner(struct regulator_dev *rdev, int min_uV, int max_uV, unsigned *selector) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); int rc = 0; int corner; u32 prev_corner; /* * Translate from values which work as inputs in the * regulator_set_voltage function to the actual corner values * sent to the RPM. */ corner = min_uV - RPM_REGULATOR_CORNER_NONE; if (corner < params[RPM_REGULATOR_PARAM_FLOOR_CORNER].min || corner > params[RPM_REGULATOR_PARAM_FLOOR_CORNER].max) { vreg_err(reg, "corner=%d is not within allowed range: [%u, %u]\n", corner, params[RPM_REGULATOR_PARAM_FLOOR_CORNER].min, params[RPM_REGULATOR_PARAM_FLOOR_CORNER].max); return -EINVAL; } rpm_vreg_lock(reg->rpm_vreg); prev_corner = reg->req.param[RPM_REGULATOR_PARAM_FLOOR_CORNER]; RPM_VREG_SET_PARAM(reg, FLOOR_CORNER, corner); /* * Only send a new voltage floor corner if the regulator is currently * enabled or if the regulator has been configured to always send * voltage updates. */ if (reg->always_send_voltage || rpm_vreg_active_or_sleep_enabled(reg->rpm_vreg) || rpm_vreg_shared_active_or_sleep_enabled_valid(reg->rpm_vreg)) rc = rpm_vreg_aggregate_requests(reg); if (rc) { vreg_err(reg, "set voltage corner failed, rc=%d", rc); RPM_VREG_SET_PARAM(reg, FLOOR_CORNER, prev_corner); } rpm_vreg_unlock(reg->rpm_vreg); return rc; } static int rpm_vreg_get_voltage_floor_corner(struct regulator_dev *rdev) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); return reg->req.param[RPM_REGULATOR_PARAM_FLOOR_CORNER] + RPM_REGULATOR_CORNER_NONE; } static int rpm_vreg_set_mode(struct regulator_dev *rdev, unsigned int mode) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); int rc = 0; u32 prev_current; int prev_uA; rpm_vreg_lock(reg->rpm_vreg); prev_current = reg->req.param[RPM_REGULATOR_PARAM_CURRENT]; prev_uA = MILLI_TO_MICRO(prev_current); if (mode == REGULATOR_MODE_NORMAL) { /* Make sure that request current is in HPM range. */ if (prev_uA < rpm_vreg_hpm_min_uA(reg->rpm_vreg)) RPM_VREG_SET_PARAM(reg, CURRENT, MICRO_TO_MILLI(rpm_vreg_hpm_min_uA(reg->rpm_vreg))); } else if (REGULATOR_MODE_IDLE) { /* Make sure that request current is in LPM range. */ if (prev_uA > rpm_vreg_lpm_max_uA(reg->rpm_vreg)) RPM_VREG_SET_PARAM(reg, CURRENT, MICRO_TO_MILLI(rpm_vreg_lpm_max_uA(reg->rpm_vreg))); } else { vreg_err(reg, "invalid mode: %u\n", mode); rpm_vreg_unlock(reg->rpm_vreg); return -EINVAL; } /* * Only send a new load current value if the regulator is currently * enabled or if the regulator has been configured to always send * current updates. */ if (reg->always_send_current || rpm_vreg_active_or_sleep_enabled(reg->rpm_vreg) || rpm_vreg_shared_active_or_sleep_enabled_valid(reg->rpm_vreg)) rc = rpm_vreg_aggregate_requests(reg); if (rc) { vreg_err(reg, "set mode failed, rc=%d", rc); RPM_VREG_SET_PARAM(reg, CURRENT, prev_current); } rpm_vreg_unlock(reg->rpm_vreg); return rc; } static unsigned int rpm_vreg_get_mode(struct regulator_dev *rdev) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); return (reg->req.param[RPM_REGULATOR_PARAM_CURRENT] >= MICRO_TO_MILLI(reg->rpm_vreg->hpm_min_load)) ? REGULATOR_MODE_NORMAL : REGULATOR_MODE_IDLE; } static unsigned int rpm_vreg_get_optimum_mode(struct regulator_dev *rdev, int input_uV, int output_uV, int load_uA) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); u32 load_mA; load_uA += reg->system_load; load_mA = MICRO_TO_MILLI(load_uA); if (load_mA > params[RPM_REGULATOR_PARAM_CURRENT].max) load_mA = params[RPM_REGULATOR_PARAM_CURRENT].max; rpm_vreg_lock(reg->rpm_vreg); RPM_VREG_SET_PARAM(reg, CURRENT, load_mA); rpm_vreg_unlock(reg->rpm_vreg); return (load_uA >= reg->rpm_vreg->hpm_min_load) ? REGULATOR_MODE_NORMAL : REGULATOR_MODE_IDLE; } static int rpm_vreg_enable_time(struct regulator_dev *rdev) { struct rpm_regulator *reg = rdev_get_drvdata(rdev); return reg->rpm_vreg->enable_time; } /** * rpm_regulator_get() - lookup and obtain a handle to an RPM regulator * @dev: device for regulator consumer * @supply: supply name * * Returns a struct rpm_regulator corresponding to the regulator producer, * or ERR_PTR() containing errno. * * This function may only be called from nonatomic context. */ struct rpm_regulator *rpm_regulator_get(struct device *dev, const char *supply) { struct rpm_regulator *framework_reg; struct rpm_regulator *priv_reg = NULL; struct regulator *regulator; struct rpm_vreg *rpm_vreg; regulator = regulator_get(dev, supply); if (IS_ERR(regulator)) { pr_err("could not find regulator for: dev=%s, supply=%s, rc=%ld\n", (dev ? dev_name(dev) : ""), (supply ? supply : ""), PTR_ERR(regulator)); return ERR_CAST(regulator); } framework_reg = regulator_get_drvdata(regulator); if (framework_reg == NULL) { pr_err("regulator structure not found.\n"); regulator_put(regulator); return ERR_PTR(-ENODEV); } regulator_put(regulator); rpm_vreg = framework_reg->rpm_vreg; priv_reg = kzalloc(sizeof(struct rpm_regulator), GFP_KERNEL); if (priv_reg == NULL) { vreg_err(framework_reg, "could not allocate memory for " "regulator\n"); return ERR_PTR(-ENOMEM); } /* * Allocate a regulator_dev struct so that framework callback functions * can be called from the private API functions. */ priv_reg->rdev = kzalloc(sizeof(struct regulator_dev), GFP_KERNEL); if (priv_reg->rdev == NULL) { vreg_err(framework_reg, "could not allocate memory for " "regulator_dev\n"); kfree(priv_reg); return ERR_PTR(-ENOMEM); } priv_reg->rdev->reg_data = priv_reg; priv_reg->rpm_vreg = rpm_vreg; priv_reg->rdesc.name = framework_reg->rdesc.name; priv_reg->rdesc.ops = framework_reg->rdesc.ops; priv_reg->set_active = framework_reg->set_active; priv_reg->set_sleep = framework_reg->set_sleep; priv_reg->min_uV = framework_reg->min_uV; priv_reg->max_uV = framework_reg->max_uV; priv_reg->system_load = framework_reg->system_load; might_sleep_if(!rpm_vreg->allow_atomic); rpm_vreg_lock(rpm_vreg); list_add(&priv_reg->list, &rpm_vreg->reg_list); rpm_vreg_unlock(rpm_vreg); return priv_reg; } EXPORT_SYMBOL_GPL(rpm_regulator_get); static int rpm_regulator_check_input(struct rpm_regulator *regulator) { if (IS_ERR_OR_NULL(regulator) || regulator->rpm_vreg == NULL) { pr_err("invalid rpm_regulator pointer\n"); return -EINVAL; } might_sleep_if(!regulator->rpm_vreg->allow_atomic); return 0; } /** * rpm_regulator_put() - free the RPM regulator handle * @regulator: RPM regulator handle * * Parameter reaggregation does not take place when rpm_regulator_put is called. * Therefore, regulator enable state and voltage must be configured * appropriately before calling rpm_regulator_put. * * This function may be called from either atomic or nonatomic context. If this * function is called from atomic context, then the regulator being operated on * must be configured via device tree with qcom,allow-atomic == 1. */ void rpm_regulator_put(struct rpm_regulator *regulator) { struct rpm_vreg *rpm_vreg; int rc = rpm_regulator_check_input(regulator); if (rc) return; rpm_vreg = regulator->rpm_vreg; might_sleep_if(!rpm_vreg->allow_atomic); rpm_vreg_lock(rpm_vreg); list_del(&regulator->list); rpm_vreg_unlock(rpm_vreg); kfree(regulator->rdev); kfree(regulator); } EXPORT_SYMBOL_GPL(rpm_regulator_put); /** * rpm_regulator_enable() - enable regulator output * @regulator: RPM regulator handle * * Returns 0 on success or errno on failure. * * This function may be called from either atomic or nonatomic context. If this * function is called from atomic context, then the regulator being operated on * must be configured via device tree with qcom,allow-atomic == 1. */ int rpm_regulator_enable(struct rpm_regulator *regulator) { int rc = rpm_regulator_check_input(regulator); if (rc) return rc; return rpm_vreg_enable(regulator->rdev); } EXPORT_SYMBOL_GPL(rpm_regulator_enable); /** * rpm_regulator_disable() - disable regulator output * @regulator: RPM regulator handle * * Returns 0 on success or errno on failure. * * The enable state of the regulator is determined by aggregating the requests * of all consumers. Therefore, it is possible that the regulator will remain * enabled even after rpm_regulator_disable is called. * * This function may be called from either atomic or nonatomic context. If this * function is called from atomic context, then the regulator being operated on * must be configured via device tree with qcom,allow-atomic == 1. */ int rpm_regulator_disable(struct rpm_regulator *regulator) { int rc = rpm_regulator_check_input(regulator); if (rc) return rc; return rpm_vreg_disable(regulator->rdev); } EXPORT_SYMBOL_GPL(rpm_regulator_disable); /** * rpm_regulator_set_voltage() - set regulator output voltage * @regulator: RPM regulator handle * @min_uV: minimum required voltage in uV * @max_uV: maximum acceptable voltage in uV * * Sets a voltage regulator to the desired output voltage. This can be set * while the regulator is disabled or enabled. If the regulator is enabled then * the voltage will change to the new value immediately; otherwise, if the * regulator is disabled, then the regulator will output at the new voltage when * enabled. * * The min_uV to max_uV voltage range requested must intersect with the * voltage constraint range configured for the regulator. * * Returns 0 on success or errno on failure. * * The final voltage value that is sent to the RPM is aggregated based upon the * values requested by all consumers of the regulator. This corresponds to the * maximum min_uV value. * * This function may be called from either atomic or nonatomic context. If this * function is called from atomic context, then the regulator being operated on * must be configured via device tree with qcom,allow-atomic == 1. */ int rpm_regulator_set_voltage(struct rpm_regulator *regulator, int min_uV, int max_uV) { int rc = rpm_regulator_check_input(regulator); int uV = min_uV; if (rc) return rc; if (regulator->rpm_vreg->regulator_type == RPM_REGULATOR_SMD_TYPE_VS) { vreg_err(regulator, "unsupported regulator type: %d\n", regulator->rpm_vreg->regulator_type); return -EINVAL; } if (min_uV > max_uV) { vreg_err(regulator, "min_uV=%d must be less than max_uV=%d\n", min_uV, max_uV); return -EINVAL; } if (uV < regulator->min_uV && max_uV >= regulator->min_uV) uV = regulator->min_uV; if (uV < regulator->min_uV || uV > regulator->max_uV) { vreg_err(regulator, "request v=[%d, %d] is outside allowed " "v=[%d, %d]\n", min_uV, max_uV, regulator->min_uV, regulator->max_uV); return -EINVAL; } return regulator->rdesc.ops->set_voltage(regulator->rdev, uV, uV, NULL); } EXPORT_SYMBOL_GPL(rpm_regulator_set_voltage); /** * rpm_regulator_set_mode() - set regulator operating mode * @regulator: RPM regulator handle * @mode: operating mode requested for the regulator * * Requests that the mode of the regulator be set to the mode specified. This * parameter is aggregated using a max function such that AUTO < IPEAK < HPM. * * Returns 0 on success or errno on failure. */ int rpm_regulator_set_mode(struct rpm_regulator *regulator, enum rpm_regulator_mode mode) { int index = 0; u32 new_mode, prev_mode; int rc; rc = rpm_regulator_check_input(regulator); if (rc) return rc; if (mode < 0 || mode >= ARRAY_SIZE(mode_mapping)) { vreg_err(regulator, "invalid mode requested: %d\n", mode); return -EINVAL; } switch (regulator->rpm_vreg->regulator_type) { case RPM_REGULATOR_SMD_TYPE_SMPS: index = RPM_REGULATOR_PARAM_MODE_SMPS; new_mode = mode_mapping[mode].smps_mode; break; case RPM_REGULATOR_SMD_TYPE_LDO: index = RPM_REGULATOR_PARAM_MODE_LDO; new_mode = mode_mapping[mode].ldo_mode; break; default: vreg_err(regulator, "unsupported regulator type: %d\n", regulator->rpm_vreg->regulator_type); return -EINVAL; }; if (new_mode < params[index].min || new_mode > params[index].max) { vreg_err(regulator, "invalid mode requested: %d for type: %d\n", mode, regulator->rpm_vreg->regulator_type); return -EINVAL; } rpm_vreg_lock(regulator->rpm_vreg); prev_mode = regulator->req.param[index]; regulator->req.param[index] = new_mode; regulator->req.modified |= BIT(index); rc = rpm_vreg_aggregate_requests(regulator); if (rc) { vreg_err(regulator, "set mode failed, rc=%d", rc); regulator->req.param[index] = prev_mode; } rpm_vreg_unlock(regulator->rpm_vreg); return rc; } EXPORT_SYMBOL_GPL(rpm_regulator_set_mode); static struct regulator_ops ldo_ops = { .enable = rpm_vreg_enable, .disable = rpm_vreg_disable, .is_enabled = rpm_vreg_is_enabled, .set_voltage = rpm_vreg_set_voltage, .get_voltage = rpm_vreg_get_voltage, .set_mode = rpm_vreg_set_mode, .get_mode = rpm_vreg_get_mode, .get_optimum_mode = rpm_vreg_get_optimum_mode, .enable_time = rpm_vreg_enable_time, }; static struct regulator_ops ldo_corner_ops = { .enable = rpm_vreg_enable, .disable = rpm_vreg_disable, .is_enabled = rpm_vreg_is_enabled, .set_voltage = rpm_vreg_set_voltage_corner, .get_voltage = rpm_vreg_get_voltage_corner, .set_mode = rpm_vreg_set_mode, .get_mode = rpm_vreg_get_mode, .get_optimum_mode = rpm_vreg_get_optimum_mode, .enable_time = rpm_vreg_enable_time, }; static struct regulator_ops ldo_floor_corner_ops = { .enable = rpm_vreg_enable, .disable = rpm_vreg_disable, .is_enabled = rpm_vreg_is_enabled, .set_voltage = rpm_vreg_set_voltage_floor_corner, .get_voltage = rpm_vreg_get_voltage_floor_corner, .set_mode = rpm_vreg_set_mode, .get_mode = rpm_vreg_get_mode, .get_optimum_mode = rpm_vreg_get_optimum_mode, .enable_time = rpm_vreg_enable_time, }; static struct regulator_ops smps_ops = { .enable = rpm_vreg_enable, .disable = rpm_vreg_disable, .is_enabled = rpm_vreg_is_enabled, .set_voltage = rpm_vreg_set_voltage, .get_voltage = rpm_vreg_get_voltage, .set_mode = rpm_vreg_set_mode, .get_mode = rpm_vreg_get_mode, .get_optimum_mode = rpm_vreg_get_optimum_mode, .enable_time = rpm_vreg_enable_time, }; static struct regulator_ops smps_corner_ops = { .enable = rpm_vreg_enable, .disable = rpm_vreg_disable, .is_enabled = rpm_vreg_is_enabled, .set_voltage = rpm_vreg_set_voltage_corner, .get_voltage = rpm_vreg_get_voltage_corner, .set_mode = rpm_vreg_set_mode, .get_mode = rpm_vreg_get_mode, .get_optimum_mode = rpm_vreg_get_optimum_mode, .enable_time = rpm_vreg_enable_time, }; static struct regulator_ops smps_floor_corner_ops = { .enable = rpm_vreg_enable, .disable = rpm_vreg_disable, .is_enabled = rpm_vreg_is_enabled, .set_voltage = rpm_vreg_set_voltage_floor_corner, .get_voltage = rpm_vreg_get_voltage_floor_corner, .set_mode = rpm_vreg_set_mode, .get_mode = rpm_vreg_get_mode, .get_optimum_mode = rpm_vreg_get_optimum_mode, .enable_time = rpm_vreg_enable_time, }; static struct regulator_ops switch_ops = { .enable = rpm_vreg_enable, .disable = rpm_vreg_disable, .is_enabled = rpm_vreg_is_enabled, .enable_time = rpm_vreg_enable_time, }; static struct regulator_ops ncp_ops = { .enable = rpm_vreg_enable, .disable = rpm_vreg_disable, .is_enabled = rpm_vreg_is_enabled, .set_voltage = rpm_vreg_set_voltage, .get_voltage = rpm_vreg_get_voltage, .enable_time = rpm_vreg_enable_time, }; static struct regulator_ops *vreg_ops[] = { [RPM_REGULATOR_SMD_TYPE_LDO] = &ldo_ops, [RPM_REGULATOR_SMD_TYPE_SMPS] = &smps_ops, [RPM_REGULATOR_SMD_TYPE_VS] = &switch_ops, [RPM_REGULATOR_SMD_TYPE_NCP] = &ncp_ops, }; static int __devexit rpm_vreg_device_remove(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct rpm_regulator *reg; struct rpm_vreg *rpm_vreg; reg = platform_get_drvdata(pdev); if (reg) { rpm_vreg = reg->rpm_vreg; rpm_vreg_lock(rpm_vreg); regulator_unregister(reg->rdev); list_del(&reg->list); kfree(reg); rpm_vreg_unlock(rpm_vreg); } else { dev_err(dev, "%s: drvdata missing\n", __func__); return -EINVAL; } platform_set_drvdata(pdev, NULL); return 0; } static int __devexit rpm_vreg_resource_remove(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct rpm_regulator *reg, *reg_temp; struct rpm_vreg *rpm_vreg; rpm_vreg = platform_get_drvdata(pdev); if (rpm_vreg) { rpm_vreg_lock(rpm_vreg); list_for_each_entry_safe(reg, reg_temp, &rpm_vreg->reg_list, list) { /* Only touch data for private consumers. */ if (reg->rdev->desc == NULL) { list_del(&reg->list); kfree(reg->rdev); kfree(reg); } else { dev_err(dev, "%s: not all child devices have " "been removed\n", __func__); } } rpm_vreg_unlock(rpm_vreg); msm_rpm_free_request(rpm_vreg->handle_active); msm_rpm_free_request(rpm_vreg->handle_sleep); kfree(rpm_vreg); } else { dev_err(dev, "%s: drvdata missing\n", __func__); return -EINVAL; } platform_set_drvdata(pdev, NULL); return 0; } /* * This probe is called for child rpm-regulator devices which have * properties which are required to configure individual regulator * framework regulators for a given RPM regulator resource. */ static int __devinit rpm_vreg_device_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *node = dev->of_node; struct regulator_init_data *init_data; struct rpm_vreg *rpm_vreg; struct rpm_regulator *reg; int rc = 0; int i, regulator_type; u32 val; if (!dev->of_node) { dev_err(dev, "%s: device tree information missing\n", __func__); return -ENODEV; } if (pdev->dev.parent == NULL) { dev_err(dev, "%s: parent device missing\n", __func__); return -ENODEV; } rpm_vreg = dev_get_drvdata(pdev->dev.parent); if (rpm_vreg == NULL) { dev_err(dev, "%s: rpm_vreg not found in parent device\n", __func__); return -ENODEV; } reg = kzalloc(sizeof(struct rpm_regulator), GFP_KERNEL); if (reg == NULL) { dev_err(dev, "%s: could not allocate memory for reg\n", __func__); return -ENOMEM; } regulator_type = rpm_vreg->regulator_type; reg->rpm_vreg = rpm_vreg; reg->rdesc.ops = vreg_ops[regulator_type]; reg->rdesc.owner = THIS_MODULE; reg->rdesc.type = REGULATOR_VOLTAGE; /* * Switch to voltage corner regulator ops if qcom,use-voltage-corner * is specified in the device node (SMPS and LDO only). */ if (of_property_read_bool(node, "qcom,use-voltage-corner")) { if (of_property_read_bool(node, "qcom,use-voltage-floor-corner")) { dev_err(dev, "%s: invalid properties: both qcom,use-voltage-corner and qcom,use-voltage-floor-corner specified\n", __func__); goto fail_free_reg; } if (regulator_type == RPM_REGULATOR_SMD_TYPE_SMPS) reg->rdesc.ops = &smps_corner_ops; else if (regulator_type == RPM_REGULATOR_SMD_TYPE_LDO) reg->rdesc.ops = &ldo_corner_ops; } else if (of_property_read_bool(node, "qcom,use-voltage-floor-corner")) { if (regulator_type == RPM_REGULATOR_SMD_TYPE_SMPS) reg->rdesc.ops = &smps_floor_corner_ops; else if (regulator_type == RPM_REGULATOR_SMD_TYPE_LDO) reg->rdesc.ops = &ldo_floor_corner_ops; } reg->always_send_voltage = of_property_read_bool(node, "qcom,always-send-voltage"); reg->always_send_current = of_property_read_bool(node, "qcom,always-send-current"); if (regulator_type == RPM_REGULATOR_SMD_TYPE_VS) reg->rdesc.n_voltages = 0; else reg->rdesc.n_voltages = 2; rc = of_property_read_u32(node, "qcom,set", &val); if (rc) { dev_err(dev, "%s: sleep set and/or active set must be " "configured via qcom,set property, rc=%d\n", __func__, rc); goto fail_free_reg; } else if (!(val & RPM_SET_CONFIG_BOTH)) { dev_err(dev, "%s: qcom,set=%u property is invalid\n", __func__, val); rc = -EINVAL; goto fail_free_reg; } reg->set_active = !!(val & RPM_SET_CONFIG_ACTIVE); reg->set_sleep = !!(val & RPM_SET_CONFIG_SLEEP); init_data = of_get_regulator_init_data(dev, node); if (init_data == NULL) { dev_err(dev, "%s: unable to allocate memory\n", __func__); rc = -ENOMEM; goto fail_free_reg; } if (init_data->constraints.name == NULL) { dev_err(dev, "%s: regulator name not specified\n", __func__); rc = -EINVAL; goto fail_free_reg; } init_data->constraints.input_uV = init_data->constraints.max_uV; if (of_get_property(node, "parent-supply", NULL)) init_data->supply_regulator = "parent"; /* * Fill in ops and mode masks based on callbacks specified for * this type of regulator. */ if (reg->rdesc.ops->enable) init_data->constraints.valid_ops_mask |= REGULATOR_CHANGE_STATUS; if (reg->rdesc.ops->get_voltage) init_data->constraints.valid_ops_mask |= REGULATOR_CHANGE_VOLTAGE; if (reg->rdesc.ops->get_mode) { init_data->constraints.valid_ops_mask |= REGULATOR_CHANGE_MODE | REGULATOR_CHANGE_DRMS; init_data->constraints.valid_modes_mask |= REGULATOR_MODE_NORMAL | REGULATOR_MODE_IDLE; } reg->rdesc.name = init_data->constraints.name; reg->min_uV = init_data->constraints.min_uV; reg->max_uV = init_data->constraints.max_uV; /* Initialize the param array based on optional properties. */ for (i = 0; i < RPM_REGULATOR_PARAM_MAX; i++) { rc = of_property_read_u32(node, params[i].property_name, &val); if (rc == 0) { if (params[i].supported_regulator_types & BIT(regulator_type)) { if (val < params[i].min || val > params[i].max) { pr_warn("%s: device tree property: " "%s=%u is outsided allowed " "range [%u, %u]\n", reg->rdesc.name, params[i].property_name, val, params[i].min, params[i].max); continue; } reg->req.param[i] = val; reg->req.modified |= BIT(i); } else { pr_warn("%s: regulator type=%d does not support" " device tree property: %s\n", reg->rdesc.name, regulator_type, params[i].property_name); } } } of_property_read_u32(node, "qcom,system-load", &reg->system_load); rpm_vreg_lock(rpm_vreg); list_add(&reg->list, &rpm_vreg->reg_list); rpm_vreg_unlock(rpm_vreg); reg->rdev = regulator_register(&reg->rdesc, dev, init_data, reg, node); if (IS_ERR(reg->rdev)) { rc = PTR_ERR(reg->rdev); reg->rdev = NULL; pr_err("regulator_register failed: %s, rc=%d\n", reg->rdesc.name, rc); goto fail_remove_from_list; } platform_set_drvdata(pdev, reg); pr_debug("successfully probed: %s\n", reg->rdesc.name); return 0; fail_remove_from_list: rpm_vreg_lock(rpm_vreg); list_del(&reg->list); rpm_vreg_unlock(rpm_vreg); fail_free_reg: kfree(reg); return rc; } /* * This probe is called for parent rpm-regulator devices which have * properties which are required to identify a given RPM resource. */ static int __devinit rpm_vreg_resource_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *node = dev->of_node; struct rpm_vreg *rpm_vreg; int val = 0; u32 resource_type; int rc; if (!dev->of_node) { dev_err(dev, "%s: device tree information missing\n", __func__); return -ENODEV; } /* Create new rpm_vreg entry. */ rpm_vreg = kzalloc(sizeof(struct rpm_vreg), GFP_KERNEL); if (rpm_vreg == NULL) { dev_err(dev, "%s: could not allocate memory for vreg\n", __func__); return -ENOMEM; } /* Required device tree properties: */ rc = of_property_read_string(node, "qcom,resource-name", &rpm_vreg->resource_name); if (rc) { dev_err(dev, "%s: qcom,resource-name missing in DT node\n", __func__); goto fail_free_vreg; } resource_type = rpm_vreg_string_to_int(rpm_vreg->resource_name); rc = of_property_read_u32(node, "qcom,resource-id", &rpm_vreg->resource_id); if (rc) { dev_err(dev, "%s: qcom,resource-id missing in DT node\n", __func__); goto fail_free_vreg; } rc = of_property_read_u32(node, "qcom,regulator-type", &rpm_vreg->regulator_type); if (rc) { dev_err(dev, "%s: qcom,regulator-type missing in DT node\n", __func__); goto fail_free_vreg; } if ((rpm_vreg->regulator_type < 0) || (rpm_vreg->regulator_type >= RPM_REGULATOR_SMD_TYPE_MAX)) { dev_err(dev, "%s: invalid regulator type: %d\n", __func__, rpm_vreg->regulator_type); rc = -EINVAL; goto fail_free_vreg; } /* Optional device tree properties: */ of_property_read_u32(node, "qcom,allow-atomic", &val); rpm_vreg->allow_atomic = !!val; of_property_read_u32(node, "qcom,enable-time", &rpm_vreg->enable_time); of_property_read_u32(node, "qcom,hpm-min-load", &rpm_vreg->hpm_min_load); rpm_vreg->apps_only = of_property_read_bool(node, "qcom,apps-only"); rpm_vreg->handle_active = msm_rpm_create_request(RPM_SET_ACTIVE, resource_type, rpm_vreg->resource_id, RPM_REGULATOR_PARAM_MAX); if (rpm_vreg->handle_active == NULL || IS_ERR(rpm_vreg->handle_active)) { rc = PTR_ERR(rpm_vreg->handle_active); dev_err(dev, "%s: failed to create active RPM handle, rc=%d\n", __func__, rc); goto fail_free_vreg; } rpm_vreg->handle_sleep = msm_rpm_create_request(RPM_SET_SLEEP, resource_type, rpm_vreg->resource_id, RPM_REGULATOR_PARAM_MAX); if (rpm_vreg->handle_sleep == NULL || IS_ERR(rpm_vreg->handle_sleep)) { rc = PTR_ERR(rpm_vreg->handle_sleep); dev_err(dev, "%s: failed to create sleep RPM handle, rc=%d\n", __func__, rc); goto fail_free_handle_active; } INIT_LIST_HEAD(&rpm_vreg->reg_list); if (rpm_vreg->allow_atomic) spin_lock_init(&rpm_vreg->slock); else mutex_init(&rpm_vreg->mlock); platform_set_drvdata(pdev, rpm_vreg); rc = of_platform_populate(node, NULL, NULL, dev); if (rc) { dev_err(dev, "%s: failed to add child nodes, rc=%d\n", __func__, rc); goto fail_unset_drvdata; } pr_debug("successfully probed: %s (%08X) %u\n", rpm_vreg->resource_name, resource_type, rpm_vreg->resource_id); return rc; fail_unset_drvdata: platform_set_drvdata(pdev, NULL); msm_rpm_free_request(rpm_vreg->handle_sleep); fail_free_handle_active: msm_rpm_free_request(rpm_vreg->handle_active); fail_free_vreg: kfree(rpm_vreg); return rc; } static struct of_device_id rpm_vreg_match_table_device[] = { { .compatible = "qcom,rpm-regulator-smd", }, {} }; static struct of_device_id rpm_vreg_match_table_resource[] = { { .compatible = "qcom,rpm-regulator-smd-resource", }, {} }; static struct platform_driver rpm_vreg_device_driver = { .probe = rpm_vreg_device_probe, .remove = __devexit_p(rpm_vreg_device_remove), .driver = { .name = "qcom,rpm-regulator-smd", .owner = THIS_MODULE, .of_match_table = rpm_vreg_match_table_device, }, }; static struct platform_driver rpm_vreg_resource_driver = { .probe = rpm_vreg_resource_probe, .remove = __devexit_p(rpm_vreg_resource_remove), .driver = { .name = "qcom,rpm-regulator-smd-resource", .owner = THIS_MODULE, .of_match_table = rpm_vreg_match_table_resource, }, }; /** * rpm_regulator_smd_driver_init() - initialized SMD RPM regulator driver * * This function registers the SMD RPM regulator platform drivers. * * Returns 0 on success or errno on failure. */ int __init rpm_regulator_smd_driver_init(void) { static bool initialized; int i, rc; if (initialized) return 0; else initialized = true; /* Store parameter string names as integers */ for (i = 0; i < RPM_REGULATOR_PARAM_MAX; i++) params[i].key = rpm_vreg_string_to_int(params[i].name); rc = platform_driver_register(&rpm_vreg_device_driver); if (rc) return rc; return platform_driver_register(&rpm_vreg_resource_driver); } EXPORT_SYMBOL_GPL(rpm_regulator_smd_driver_init); static void __exit rpm_vreg_exit(void) { platform_driver_unregister(&rpm_vreg_device_driver); platform_driver_unregister(&rpm_vreg_resource_driver); } module_init(rpm_regulator_smd_driver_init); module_exit(rpm_vreg_exit); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("MSM SMD RPM regulator driver");
apache-2.0
TheCallSign/Clifton-Source
src/game/server/hl2/npc_barney.cpp
7
7047
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "ai_default.h" #include "ai_task.h" #include "ai_schedule.h" #include "ai_node.h" #include "ai_hull.h" #include "ai_hint.h" #include "ai_squad.h" #include "ai_senses.h" #include "ai_navigator.h" #include "ai_motor.h" #include "ai_behavior.h" #include "ai_baseactor.h" #include "ai_behavior_lead.h" #include "ai_behavior_follow.h" #include "ai_behavior_standoff.h" #include "ai_behavior_assault.h" #include "npc_playercompanion.h" #include "soundent.h" #include "game.h" #include "npcevent.h" #include "activitylist.h" #include "vstdlib/random.h" #include "engine/IEngineSound.h" #include "sceneentity.h" #include "ai_behavior_functank.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define BARNEY_MODEL "models/barney.mdl" ConVar sk_barney_health( "sk_barney_health","0"); //========================================================= // Barney activities //========================================================= class CNPC_Barney : public CNPC_PlayerCompanion { public: DECLARE_CLASS( CNPC_Barney, CNPC_PlayerCompanion ); DECLARE_SERVERCLASS(); DECLARE_DATADESC(); virtual void Precache() { // Prevents a warning SelectModel( ); BaseClass::Precache(); PrecacheScriptSound( "NPC_Barney.FootstepLeft" ); PrecacheScriptSound( "NPC_Barney.FootstepRight" ); PrecacheScriptSound( "NPC_Barney.Die" ); PrecacheInstancedScene( "scenes/Expressions/BarneyIdle.vcd" ); PrecacheInstancedScene( "scenes/Expressions/BarneyAlert.vcd" ); PrecacheInstancedScene( "scenes/Expressions/BarneyCombat.vcd" ); } void Spawn( void ); void SelectModel(); Class_T Classify( void ); void Weapon_Equip( CBaseCombatWeapon *pWeapon ); bool CreateBehaviors( void ); void HandleAnimEvent( animevent_t *pEvent ); bool ShouldLookForBetterWeapon() { return false; } void OnChangeRunningBehavior( CAI_BehaviorBase *pOldBehavior, CAI_BehaviorBase *pNewBehavior ); void DeathSound( const CTakeDamageInfo &info ); void GatherConditions(); void UseFunc( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); CAI_FuncTankBehavior m_FuncTankBehavior; COutputEvent m_OnPlayerUse; DEFINE_CUSTOM_AI; }; LINK_ENTITY_TO_CLASS( npc_barney, CNPC_Barney ); //--------------------------------------------------------- // //--------------------------------------------------------- IMPLEMENT_SERVERCLASS_ST(CNPC_Barney, DT_NPC_Barney) END_SEND_TABLE() //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CNPC_Barney ) // m_FuncTankBehavior DEFINE_OUTPUT( m_OnPlayerUse, "OnPlayerUse" ), DEFINE_USEFUNC( UseFunc ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Barney::SelectModel() { SetModelName( AllocPooledString( BARNEY_MODEL ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Barney::Spawn( void ) { Precache(); m_iHealth = 80; m_iszIdleExpression = MAKE_STRING("scenes/Expressions/BarneyIdle.vcd"); m_iszAlertExpression = MAKE_STRING("scenes/Expressions/BarneyAlert.vcd"); m_iszCombatExpression = MAKE_STRING("scenes/Expressions/BarneyCombat.vcd"); BaseClass::Spawn(); AddEFlags( EFL_NO_DISSOLVE | EFL_NO_MEGAPHYSCANNON_RAGDOLL | EFL_NO_PHYSCANNON_INTERACTION ); NPCInit(); SetUse( &CNPC_Barney::UseFunc ); } //----------------------------------------------------------------------------- // Purpose: // Output : //----------------------------------------------------------------------------- Class_T CNPC_Barney::Classify( void ) { return CLASS_PLAYER_ALLY_VITAL; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_Barney::Weapon_Equip( CBaseCombatWeapon *pWeapon ) { BaseClass::Weapon_Equip( pWeapon ); if( hl2_episodic.GetBool() && FClassnameIs( pWeapon, "weapon_ar2" ) ) { // Allow Barney to defend himself at point-blank range in c17_05. pWeapon->m_fMinRange1 = 0.0f; } } //--------------------------------------------------------- //--------------------------------------------------------- void CNPC_Barney::HandleAnimEvent( animevent_t *pEvent ) { switch( pEvent->event ) { case NPC_EVENT_LEFTFOOT: { EmitSound( "NPC_Barney.FootstepLeft", pEvent->eventtime ); } break; case NPC_EVENT_RIGHTFOOT: { EmitSound( "NPC_Barney.FootstepRight", pEvent->eventtime ); } break; default: BaseClass::HandleAnimEvent( pEvent ); break; } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CNPC_Barney::DeathSound( const CTakeDamageInfo &info ) { // Sentences don't play on dead NPCs SentenceStop(); EmitSound( "npc_barney.die" ); } bool CNPC_Barney::CreateBehaviors( void ) { BaseClass::CreateBehaviors(); AddBehavior( &m_FuncTankBehavior ); return true; } void CNPC_Barney::OnChangeRunningBehavior( CAI_BehaviorBase *pOldBehavior, CAI_BehaviorBase *pNewBehavior ) { if ( pNewBehavior == &m_FuncTankBehavior ) { m_bReadinessCapable = false; } else if ( pOldBehavior == &m_FuncTankBehavior ) { m_bReadinessCapable = IsReadinessCapable(); } BaseClass::OnChangeRunningBehavior( pOldBehavior, pNewBehavior ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_Barney::GatherConditions() { BaseClass::GatherConditions(); // Handle speech AI. Don't do AI speech if we're in scripts unless permitted by the EnableSpeakWhileScripting input. if ( m_NPCState == NPC_STATE_IDLE || m_NPCState == NPC_STATE_ALERT || m_NPCState == NPC_STATE_COMBAT || ( ( m_NPCState == NPC_STATE_SCRIPT ) && CanSpeakWhileScripting() ) ) { DoCustomSpeechAI(); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_Barney::UseFunc( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_bDontUseSemaphore = true; SpeakIfAllowed( TLK_USE ); m_bDontUseSemaphore = false; m_OnPlayerUse.FireOutput( pActivator, pCaller ); } //----------------------------------------------------------------------------- // // Schedules // //----------------------------------------------------------------------------- AI_BEGIN_CUSTOM_NPC( npc_barney, CNPC_Barney ) AI_END_CUSTOM_NPC()
apache-2.0
avigad/lean
src/tests/shared/env.c
7
16530
/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <stdlib.h> #include <stdio.h> #include "api/lean.h" void check_core(int v, unsigned l) { if (!v) { printf("Test failed at line %d\n", l); exit(1); } } #define check(v) check_core(v, __LINE__) lean_name mk_name(char const * n) { lean_exception ex; lean_name a, r; check(lean_name_mk_anonymous(&a, &ex)); check(lean_name_mk_str(a, n, &r, &ex)); lean_name_del(a); return r; } lean_univ mk_uparam(char const * n) { lean_exception ex; lean_univ r; lean_name _n = mk_name(n); check(lean_univ_mk_param(_n, &r, &ex)); lean_name_del(_n); return r; } lean_list_name mk_unary_name_list(lean_name u) { lean_exception ex; lean_list_name n, r; check(lean_list_name_mk_nil(&n, &ex)); check(lean_list_name_mk_cons(u, n, &r, &ex)); lean_list_name_del(n); return r; } lean_env mk_env() { lean_exception ex; lean_env r; check(lean_env_mk_std(LEAN_TRUST_HIGH, &r, &ex)); return r; } lean_expr mk_constant(char const * n, lean_list_univ us) { lean_exception ex; lean_name _n = mk_name(n); lean_expr r; check(lean_expr_mk_const(_n, us, &r, &ex)); lean_name_del(_n); return r; } lean_expr mk_var(unsigned i) { lean_exception ex; lean_expr r; check(lean_expr_mk_var(i, &r, &ex)); return r; } lean_expr mk_sort(lean_univ u) { lean_exception ex; lean_expr r; check(lean_expr_mk_sort(u, &r, &ex)); return r; } /** create a constant with a single universe parameter */ lean_expr mk_const(char const * n, lean_univ u) { lean_exception ex; lean_name _n = mk_name(n); lean_list_univ l1, l2; check(lean_list_univ_mk_nil(&l1, &ex)); check(lean_list_univ_mk_cons(u, l1, &l2, &ex)); lean_expr r; check(lean_expr_mk_const(_n, l2, &r, &ex)); lean_name_del(_n); lean_list_univ_del(l1); lean_list_univ_del(l2); return r; } lean_expr mk_pi(char const * n, lean_expr d, lean_expr c) { lean_exception ex; lean_name name = mk_name(n); lean_expr r; check(lean_expr_mk_pi(name, d, c, LEAN_BINDER_DEFAULT, &r, &ex)); lean_name_del(name); return r; } lean_expr mk_lambda(char const * n, lean_expr d, lean_expr c) { lean_exception ex; lean_name name = mk_name(n); lean_expr r; check(lean_expr_mk_lambda(name, d, c, LEAN_BINDER_DEFAULT, &r, &ex)); lean_name_del(name); return r; } lean_expr mk_local(char const * n, lean_expr t) { lean_exception ex; lean_name _n = mk_name(n); lean_expr r; check(lean_expr_mk_local(_n, t, &r, &ex)); lean_name_del(_n); return r; } lean_decl mk_def(char const * n, lean_list_name p, lean_expr t, lean_expr v) { lean_exception ex; lean_name name = mk_name(n); lean_decl r; check(lean_decl_mk_def(name, p, t, v, 0, lean_true, &r, &ex)); lean_name_del(name); return r; } void print_univ_and_del(lean_name n) { lean_exception ex; char const * s; check(lean_name_to_string(n, &s, &ex)); printf("universe: %s\n", s); lean_string_del(s); lean_name_del(n); } void print_expr(lean_expr e) { lean_exception ex; char const * s; check(lean_expr_to_string(e, &s, &ex)); printf("%s\n", s); lean_string_del(s); } void print_decl_and_del(lean_decl d) { lean_exception ex; lean_name n; lean_expr t; char const * s; check(lean_decl_get_name(d, &n, &ex)); check(lean_name_to_string(n, &s, &ex)); printf("declaration name: %s\n", s); check(lean_decl_get_type(d, &t, &ex)); printf(" type: "); print_expr(t); if (lean_decl_get_kind(d) == LEAN_DECL_DEF || lean_decl_get_kind(d) == LEAN_DECL_THM) { lean_expr v; check(lean_decl_get_value(d, &v, &ex)); printf(" value: "); print_expr(v); lean_expr_del(v); } lean_expr_del(t); lean_name_del(n); lean_string_del(s); lean_decl_del(d); } void test_add_univ() { lean_exception ex; lean_name u = mk_name("u"); lean_name v = mk_name("v"); lean_env env = mk_env(); lean_env new_env; check(lean_env_add_univ(env, u, &new_env, &ex)); check(lean_env_contains_univ(new_env, u)); check(!lean_env_contains_univ(new_env, v)); check(lean_env_for_each_univ(new_env, print_univ_and_del, &ex)); lean_name_del(u); lean_name_del(v); lean_env_del(env); lean_env_del(new_env); } void test_id() { lean_exception ex; lean_univ l = mk_uparam("l"); lean_env env = mk_env(); lean_expr v0 = mk_var(0); lean_expr v1 = mk_var(1); lean_expr AA = mk_pi("a", v0, v1); lean_expr Type = mk_sort(l); lean_expr id_type = mk_pi("A", Type, AA); lean_expr f = mk_lambda("a", v0, v0); lean_expr id_val = mk_lambda("A", Type, f); lean_name l_name = mk_name("l"); lean_list_name id_ps = mk_unary_name_list(l_name); lean_decl id_def = mk_def("id", id_ps, id_type, id_val); lean_name id_name = mk_name("id"); lean_cert_decl id_cert_def; lean_env new_env; lean_univ zero, one; lean_bool is_lt; check(lean_expr_lt(f, id_val, &is_lt, &ex) && is_lt); check(lean_expr_lt(id_val, f, &is_lt, &ex) && !is_lt); printf("id type: "); print_expr(id_type); printf("id value: "); print_expr(id_val); printf("-------\n"); /* type check definition */ check(lean_decl_check(env, id_def, &id_cert_def, &ex)); /* add certified definition to environment */ check(lean_env_add(env, id_cert_def, &new_env, &ex)); check(!lean_env_contains_decl(env, id_name)); check(lean_env_contains_decl(new_env, id_name)); check(lean_env_for_each_decl(new_env, print_decl_and_del, &ex)); check(lean_univ_mk_zero(&zero, &ex)); check(lean_univ_mk_succ(zero, &one, &ex)); check(lean_univ_lt(zero, one, &is_lt, &ex) && is_lt); check(lean_univ_lt(one, zero, &is_lt, &ex) && !is_lt); { lean_type_checker tc; lean_expr T0 = mk_sort(zero); lean_expr T1 = mk_sort(one); lean_expr id1 = mk_const("id", one); lean_expr id1T1, id1T1T0; lean_expr n1; check(lean_expr_mk_app(id1, T1, &id1T1, &ex)); check(lean_expr_mk_app(id1T1, T0, &id1T1T0, &ex)); check(lean_type_checker_mk(new_env, &tc, &ex)); printf("WHNF test\n"); print_expr(id1T1T0); check(lean_type_checker_whnf(tc, id1T1T0, &n1, &ex)); printf("=====>\n"); print_expr(n1); lean_expr_del(n1); printf("Infer type test\n"); print_expr(id1T1); check(lean_type_checker_infer(tc, id1T1, &n1, &ex)); printf("=====>\n"); print_expr(n1); lean_expr_del(n1); lean_type_checker_del(tc); lean_expr_del(T0); lean_expr_del(T1); lean_expr_del(id1); lean_expr_del(id1T1); lean_expr_del(id1T1T0); } lean_univ_del(l); lean_env_del(env); lean_expr_del(v0); lean_expr_del(v1); lean_expr_del(Type); lean_expr_del(AA); lean_expr_del(id_type); lean_expr_del(f); lean_expr_del(id_val); lean_decl_del(id_def); lean_list_name_del(id_ps); lean_name_del(l_name); lean_cert_decl_del(id_cert_def); lean_env_del(new_env); lean_name_del(id_name); lean_univ_del(zero); lean_univ_del(one); } void test_path() { lean_exception ex; char const * p; check(lean_get_std_path(&p, &ex)); printf("LEAN_PATH: %s\n", p); lean_string_del(p); } void print_decl_name_and_del(lean_decl d) { lean_exception ex; lean_name n; char const * s; check(lean_decl_get_name(d, &n, &ex)); check(lean_name_to_string(n, &s, &ex)); printf("declaration name: %s\n", s); lean_name_del(n); lean_string_del(s); lean_decl_del(d); } void test_import() { lean_exception ex; lean_env env = mk_env(); lean_name std = mk_name("standard"); lean_list_name ms = mk_unary_name_list(std); lean_options o; lean_ios ios; lean_env new_env; lean_decl nat_gcd_decl; lean_name nat = mk_name("nat"); lean_name nat_gcd; lean_expr nat_gcd_val; char const * s; check(lean_options_mk_empty(&o, &ex)); check(lean_ios_mk_std(o, &ios, &ex)); check(lean_env_import(env, ios, ms, &new_env, &ex)); check(lean_env_for_each_decl(new_env, print_decl_name_and_del, &ex)); check(lean_name_mk_str(nat, "gcd", &nat_gcd, &ex)); check(lean_env_get_decl(new_env, nat_gcd, &nat_gcd_decl, &ex)); check(lean_decl_get_value(nat_gcd_decl, &nat_gcd_val, &ex)); check(lean_expr_to_pp_string(new_env, ios, nat_gcd_val, &s, &ex)); printf("nat.gcd\n%s\n", s); lean_env_del(env); lean_name_del(std); lean_list_name_del(ms); lean_options_del(o); lean_ios_del(ios); lean_env_del(new_env); lean_name_del(nat); lean_name_del(nat_gcd); lean_decl_del(nat_gcd_decl); lean_expr_del(nat_gcd_val); lean_string_del(s); } lean_univ mk_one() { lean_exception ex; lean_univ zero, one; check(lean_univ_mk_zero(&zero, &ex)); check(lean_univ_mk_succ(zero, &one, &ex)); lean_univ_del(zero); return one; } lean_univ mk_max(lean_univ u1, lean_univ u2) { lean_exception ex; lean_univ r; check(lean_univ_mk_max(u1, u2, &r, &ex)); return r; } lean_expr mk_app(lean_expr f, lean_expr a) { lean_exception ex; lean_expr r; check(lean_expr_mk_app(f, a, &r, &ex)); return r; } void test_inductive() { // declare list type lean_exception ex = 0; lean_env env = mk_env(); lean_name l_name = mk_name("l"); lean_univ l = mk_uparam("l"); lean_univ one = mk_one(); lean_univ m1l = mk_max(one, l); lean_expr Typel = mk_sort(l); lean_expr Typem1l = mk_sort(m1l); lean_expr list_type = mk_pi("A", Typel, Typem1l); lean_name list_name = mk_name("list"); lean_expr list = mk_const("list", l); lean_expr v0 = mk_var(0); // nil : Pi (A : Type.{l}), list.{l} A lean_expr list_v0 = mk_app(list, v0); lean_expr nil_type = mk_pi("A", Typel, list_v0); lean_expr nil = mk_local("nil", nil_type); // cons : Pi (A : Type.{l}), A -> list.{l} A -> list.{l} A lean_expr v1 = mk_var(1); lean_expr v2 = mk_var(2); lean_expr list_v2 = mk_app(list, v2); lean_expr list_v1 = mk_app(list, v1); lean_expr cons_type1 = mk_pi("tail", list_v1, list_v2); lean_expr cons_type2 = mk_pi("head", v0, cons_type1); lean_expr cons_type = mk_pi("A", Typel, cons_type2); lean_expr cons = mk_local("cons", cons_type); // lean_list_expr cs1, cs2, list_cs; lean_inductive_type list_ind_type; lean_list_inductive_type li1, list_ind_types; lean_list_name ls1, ls; lean_inductive_decl list_decl; lean_env new_env; check(lean_list_name_mk_nil(&ls1, &ex)); check(lean_list_name_mk_cons(l_name, ls1, &ls, &ex)); check(lean_list_expr_mk_nil(&cs1, &ex)); check(lean_list_expr_mk_cons(nil, cs1, &cs2, &ex)); check(lean_list_expr_mk_cons(cons, cs2, &list_cs, &ex)); check(lean_inductive_type_mk(list_name, list_type, list_cs, &list_ind_type, &ex)); check(lean_list_inductive_type_mk_nil(&li1, &ex)); check(lean_list_inductive_type_mk_cons(list_ind_type, li1, &list_ind_types, &ex)); check(lean_inductive_decl_mk(ls, 1, list_ind_types, &list_decl, &ex)); check(lean_env_add_inductive(env, list_decl, &new_env, &ex)); { unsigned n; lean_inductive_decl d; lean_name cons_name = mk_name("cons"); lean_name r_name; lean_list_inductive_type types; check(lean_env_get_inductive_type_num_indices(new_env, list_name, &n, &ex) && n == 0); check(lean_env_get_inductive_type_num_minor_premises(new_env, list_name, &n, &ex) && n == 2); check(!lean_env_is_inductive_type(env, list_name, &d, &ex)); check(lean_env_is_inductive_type(new_env, list_name, &d, &ex)); check(lean_inductive_decl_get_num_params(d, &n, &ex) && n == 1); check(lean_inductive_decl_get_types(d, &types, &ex)); check(lean_list_inductive_type_is_cons(types)); check(lean_env_is_constructor(new_env, cons_name, &r_name, &ex) && lean_name_eq(list_name, r_name)); lean_list_inductive_type_del(types); lean_inductive_decl_del(d); lean_name_del(cons_name); lean_name_del(r_name); } lean_env_del(env); lean_name_del(list_name); lean_name_del(l_name); lean_univ_del(l); lean_univ_del(one); lean_univ_del(m1l); lean_expr_del(Typel); lean_expr_del(Typem1l); lean_expr_del(list_type); lean_expr_del(list); lean_expr_del(v0); lean_expr_del(list_v0); lean_expr_del(nil_type); lean_expr_del(nil); lean_expr_del(v1); lean_expr_del(v2); lean_expr_del(list_v2); lean_expr_del(list_v1); lean_expr_del(cons_type1); lean_expr_del(cons_type2); lean_expr_del(cons_type); lean_expr_del(cons); lean_list_expr_del(cs1); lean_list_expr_del(cs2); lean_list_expr_del(list_cs); lean_inductive_type_del(list_ind_type); lean_list_inductive_type_del(li1); lean_list_inductive_type_del(list_ind_types); lean_list_name_del(ls1); lean_list_name_del(ls); lean_inductive_decl_del(list_decl); lean_env_del(new_env); } void test_parser() { lean_exception ex = 0; lean_env env = mk_env(); lean_ios ios; lean_env new_env; lean_ios new_ios; lean_options o; check(lean_options_mk_empty(&o, &ex)); check(lean_ios_mk_std(o, &ios, &ex)); check(lean_parse_commands(env, ios, "import standard open nat definition double (a : nat) := a + a check double 4 eval double 4", &new_env, &new_ios, &ex)); { lean_name double_name = mk_name("double"); lean_decl double_decl; lean_expr double_decl_value; char const * s; check(lean_env_get_decl(new_env, double_name, &double_decl, &ex)); check(lean_decl_get_value(double_decl, &double_decl_value, &ex)); check(lean_expr_to_pp_string(new_env, new_ios, double_decl_value, &s, &ex)); printf("definition of double\n%s\n", s); lean_name_del(double_name); lean_decl_del(double_decl); lean_expr_del(double_decl_value); lean_string_del(s); } { lean_expr e; lean_list_name ps; // remark: we can use notation from the namespace nat because we have executed 'open nat' // when we created new_env check(lean_parse_expr(new_env, new_ios, "double (2 + 3)", &e, &ps, &ex)); char const * s; check(lean_expr_to_pp_string(new_env, new_ios, e, &s, &ex)); printf("parsed expression: %s\n", s); lean_string_del(s); lean_expr_del(e); lean_list_name_del(ps); } lean_options_del(o); lean_env_del(env); lean_env_del(new_env); lean_ios_del(ios); lean_ios_del(new_ios); } void test_parser_error() { lean_exception ex = 0; lean_env env = mk_env(); lean_ios ios; lean_env new_env; lean_ios new_ios; lean_options o; check(lean_options_mk_empty(&o, &ex)); check(lean_ios_mk_std(o, &ios, &ex)); check(!lean_parse_commands(env, ios, "import data.nat open nat definition double (a : nat) := a + true", &new_env, &new_ios, &ex)); { lean_exception ex2 = 0; char const * s1 = lean_exception_get_message(ex); char const * s2 = lean_exception_get_detailed_message(ex); char const * s3; printf("\nexception kind: %d\n", lean_exception_get_kind(ex)); printf("exception message: %s\n", s1); printf("exception detailed message: %s\n", s2); check(lean_exception_to_pp_string(env, ios, ex, &s3, &ex2)); printf("exception: %s\n", s3); lean_string_del(s1); lean_string_del(s2); lean_string_del(s3); } lean_options_del(o); lean_exception_del(ex); lean_env_del(env); lean_ios_del(ios); } int main() { test_add_univ(); test_id(); test_path(); test_import(); test_inductive(); test_parser(); test_parser_error(); return 0; }
apache-2.0
raphaelchang/quadthingy-software
base_station/ChibiOS_16.1.4/testhal/STM32/STM32F37x/USB_CDC/main.c
8
7194
/* ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio 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 <stdio.h> #include <string.h> #include "ch.h" #include "hal.h" #include "test.h" #include "shell.h" #include "chprintf.h" #include "usbcfg.h" /* * DP resistor control. */ #define usb_lld_connect_bus(usbp) palClearPad(GPIOC, GPIOC_USB_DISCONNECT) #define usb_lld_disconnect_bus(usbp) palSetPad(GPIOC, GPIOC_USB_DISCONNECT) /*===========================================================================*/ /* Command line related. */ /*===========================================================================*/ #define SHELL_WA_SIZE THD_WORKING_AREA_SIZE(2048) #define TEST_WA_SIZE THD_WORKING_AREA_SIZE(256) static void cmd_mem(BaseSequentialStream *chp, int argc, char *argv[]) { size_t n, size; (void)argv; if (argc > 0) { chprintf(chp, "Usage: mem\r\n"); return; } n = chHeapStatus(NULL, &size); chprintf(chp, "core free memory : %u bytes\r\n", chCoreGetStatusX()); chprintf(chp, "heap fragments : %u\r\n", n); chprintf(chp, "heap free total : %u bytes\r\n", size); } static void cmd_threads(BaseSequentialStream *chp, int argc, char *argv[]) { static const char *states[] = {CH_STATE_NAMES}; thread_t *tp; (void)argv; if (argc > 0) { chprintf(chp, "Usage: threads\r\n"); return; } chprintf(chp, " addr stack prio refs state time\r\n"); tp = chRegFirstThread(); do { chprintf(chp, "%08lx %08lx %4lu %4lu %9s\r\n", (uint32_t)tp, (uint32_t)tp->p_ctx.r13, (uint32_t)tp->p_prio, (uint32_t)(tp->p_refs - 1), states[tp->p_state]); tp = chRegNextThread(tp); } while (tp != NULL); } static void cmd_test(BaseSequentialStream *chp, int argc, char *argv[]) { thread_t *tp; (void)argv; if (argc > 0) { chprintf(chp, "Usage: test\r\n"); return; } tp = chThdCreateFromHeap(NULL, TEST_WA_SIZE, chThdGetPriorityX(), TestThread, chp); if (tp == NULL) { chprintf(chp, "out of memory\r\n"); return; } chThdWait(tp); } /* Can be measured using dd if=/dev/xxxx of=/dev/null bs=512 count=10000.*/ static void cmd_write(BaseSequentialStream *chp, int argc, char *argv[]) { static uint8_t buf[] = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; (void)argv; if (argc > 0) { chprintf(chp, "Usage: write\r\n"); return; } while (chnGetTimeout((BaseChannel *)chp, TIME_IMMEDIATE) == Q_TIMEOUT) { #if 1 /* Writing in channel mode.*/ chnWrite(&SDU1, buf, sizeof buf - 1); #else /* Writing in buffer mode.*/ (void) obqGetEmptyBufferTimeout(&SDU1.obqueue, TIME_INFINITE); memcpy(SDU1.obqueue.ptr, buf, SERIAL_USB_BUFFERS_SIZE); obqPostFullBuffer(&SDU1.obqueue, SERIAL_USB_BUFFERS_SIZE); #endif } chprintf(chp, "\r\n\nstopped\r\n"); } static const ShellCommand commands[] = { {"mem", cmd_mem}, {"threads", cmd_threads}, {"test", cmd_test}, {"write", cmd_write}, {NULL, NULL} }; static const ShellConfig shell_cfg1 = { (BaseSequentialStream *)&SDU1, commands }; /*===========================================================================*/ /* Generic code. */ /*===========================================================================*/ /* * Red LED blinker thread, times are in milliseconds. */ static THD_WORKING_AREA(waThread1, 128); static THD_FUNCTION(Thread1, arg) { (void)arg; chRegSetThreadName("blinker"); while (true) { systime_t time = serusbcfg.usbp->state == USB_ACTIVE ? 250 : 500; palClearPad(GPIOC, GPIOC_LED1); chThdSleepMilliseconds(time); palSetPad(GPIOC, GPIOC_LED1); chThdSleepMilliseconds(time); } } /* * Application entry point. */ int main(void) { thread_t *shelltp = NULL; /* * System initializations. * - HAL initialization, this also initializes the configured device drivers * and performs the board-specific initializations. * - Kernel initialization, the main() function becomes a thread and the * RTOS is active. */ halInit(); chSysInit(); /* * Initializes a serial-over-USB CDC driver. */ sduObjectInit(&SDU1); sduStart(&SDU1, &serusbcfg); /* * Activates the USB driver and then the USB bus pull-up on D+. * Note, a delay is inserted in order to not have to disconnect the cable * after a reset. */ usbDisconnectBus(serusbcfg.usbp); chThdSleepMilliseconds(1500); usbStart(serusbcfg.usbp, &usbcfg); usbConnectBus(serusbcfg.usbp); /* * Shell manager initialization. */ shellInit(); /* * Creates the blinker thread. */ chThdCreateStatic(waThread1, sizeof(waThread1), NORMALPRIO, Thread1, NULL); /* * Normal main() thread activity, in this demo it does nothing except * sleeping in a loop and check the button state. */ while (true) { if (!shelltp && (SDU1.config->usbp->state == USB_ACTIVE)) shelltp = shellCreate(&shell_cfg1, SHELL_WA_SIZE, NORMALPRIO); else if (chThdTerminatedX(shelltp)) { chThdRelease(shelltp); /* Recovers memory of the previous shell. */ shelltp = NULL; /* Triggers spawning of a new shell. */ } chThdSleepMilliseconds(1000); } }
apache-2.0
indashnet/InDashNet.Open.UN2000
android/external/clang/test/Sema/format-strings-scanf.c
9
9110
// RUN: %clang_cc1 -fsyntax-only -verify -Wformat-nonliteral %s // Test that -Wformat=0 works: // RUN: %clang_cc1 -fsyntax-only -Werror -Wformat=0 %s #include <stdarg.h> typedef __typeof(sizeof(int)) size_t; typedef struct _FILE FILE; typedef __WCHAR_TYPE__ wchar_t; int fscanf(FILE * restrict, const char * restrict, ...) ; int scanf(const char * restrict, ...) ; int sscanf(const char * restrict, const char * restrict, ...) ; int my_scanf(const char * restrict, ...) __attribute__((__format__(__scanf__, 1, 2))); int vscanf(const char * restrict, va_list); int vfscanf(FILE * restrict, const char * restrict, va_list); int vsscanf(const char * restrict, const char * restrict, va_list); void test(const char *s, int *i) { scanf(s, i); // expected-warning{{ormat string is not a string literal}} scanf("%0d", i); // expected-warning{{zero field width in scanf format string is unused}} scanf("%00d", i); // expected-warning{{zero field width in scanf format string is unused}} scanf("%d%[asdfasdfd", i, s); // expected-warning{{no closing ']' for '%[' in scanf format string}} unsigned short s_x; scanf ("%" "hu" "\n", &s_x); // no-warning scanf("%y", i); // expected-warning{{invalid conversion specifier 'y'}} scanf("%%"); // no-warning scanf("%%%1$d", i); // no-warning scanf("%1$d%%", i); // no-warning scanf("%d", i, i); // expected-warning{{data argument not used by format string}} scanf("%*d", i); // // expected-warning{{data argument not used by format string}} scanf("%*d", i); // // expected-warning{{data argument not used by format string}} scanf("%*d%1$d", i); // no-warning scanf("%s", (char*)0); // no-warning scanf("%s", (volatile char*)0); // no-warning scanf("%s", (signed char*)0); // no-warning scanf("%s", (unsigned char*)0); // no-warning scanf("%hhu", (signed char*)0); // no-warning } void bad_length_modifiers(char *s, void *p, wchar_t *ws, long double *ld) { scanf("%hhs", "foo"); // expected-warning{{length modifier 'hh' results in undefined behavior or no effect with 's' conversion specifier}} scanf("%1$zp", &p); // expected-warning{{length modifier 'z' results in undefined behavior or no effect with 'p' conversion specifier}} scanf("%ls", ws); // no-warning scanf("%#.2Lf", ld); // expected-warning{{invalid conversion specifier '#'}} } // Test that the scanf call site is where the warning is attached. If the // format string is somewhere else, point to it in a note. void pr9751() { int *i; char str[100]; const char kFormat1[] = "%00d"; // expected-note{{format string is defined here}}} scanf(kFormat1, i); // expected-warning{{zero field width in scanf format string is unused}} scanf("%00d", i); // expected-warning{{zero field width in scanf format string is unused}} const char kFormat2[] = "%["; // expected-note{{format string is defined here}}} scanf(kFormat2, str); // expected-warning{{no closing ']' for '%[' in scanf format string}} scanf("%[", str); // expected-warning{{no closing ']' for '%[' in scanf format string}} const char kFormat3[] = "%hu"; // expected-note{{format string is defined here}}} scanf(kFormat3, &i); // expected-warning {{format specifies type 'unsigned short *' but the argument}} const char kFormat4[] = "%lp"; // expected-note{{format string is defined here}}} scanf(kFormat4, &i); // expected-warning {{length modifier 'l' results in undefined behavior or no effect with 'p' conversion specifier}} } void test_variants(int *i, const char *s, ...) { FILE *f = 0; char buf[100]; fscanf(f, "%ld", i); // expected-warning{{format specifies type 'long *' but the argument has type 'int *'}} sscanf(buf, "%ld", i); // expected-warning{{format specifies type 'long *' but the argument has type 'int *'}} my_scanf("%ld", i); // expected-warning{{format specifies type 'long *' but the argument has type 'int *'}} va_list ap; va_start(ap, s); vscanf("%[abc", ap); // expected-warning{{no closing ']' for '%[' in scanf format string}} vfscanf(f, "%[abc", ap); // expected-warning{{no closing ']' for '%[' in scanf format string}} vsscanf(buf, "%[abc", ap); // expected-warning{{no closing ']' for '%[' in scanf format string}} } void test_scanlist(int *ip, char *sp, wchar_t *ls) { scanf("%[abc]", ip); // expected-warning{{format specifies type 'char *' but the argument has type 'int *'}} scanf("%h[abc]", sp); // expected-warning{{length modifier 'h' results in undefined behavior or no effect with '[' conversion specifier}} scanf("%l[xyx]", ls); // no-warning scanf("%ll[xyx]", ls); // expected-warning {{length modifier 'll' results in undefined behavior or no effect with '[' conversion specifier}} } void test_alloc_extension(char **sp, wchar_t **lsp, float *fp) { /* Make sure "%a" gets parsed as a conversion specifier for float, * even when followed by an 's', 'S' or '[', which would cause it to be * parsed as a length modifier in C90. */ scanf("%as", sp); // expected-warning{{format specifies type 'float *' but the argument has type 'char **'}} scanf("%aS", lsp); // expected-warning{{format specifies type 'float *' but the argument has type 'wchar_t **'}} scanf("%a[bcd]", sp); // expected-warning{{format specifies type 'float *' but the argument has type 'char **'}} // Test that the 'm' length modifier is only allowed with s, S, c, C or [. // TODO: Warn that 'm' is an extension. scanf("%ms", sp); // No warning. scanf("%mS", lsp); // No warning. scanf("%mc", sp); // No warning. scanf("%mC", lsp); // No warning. scanf("%m[abc]", sp); // No warning. scanf("%md", sp); // expected-warning{{length modifier 'm' results in undefined behavior or no effect with 'd' conversion specifier}} // Test argument type check for the 'm' length modifier. scanf("%ms", fp); // expected-warning{{format specifies type 'char **' but the argument has type 'float *'}} scanf("%mS", fp); // expected-warning-re{{format specifies type 'wchar_t \*\*' \(aka '[^']+'\) but the argument has type 'float \*'}} scanf("%mc", fp); // expected-warning{{format specifies type 'char **' but the argument has type 'float *'}} scanf("%mC", fp); // expected-warning-re{{format specifies type 'wchar_t \*\*' \(aka '[^']+'\) but the argument has type 'float \*'}} scanf("%m[abc]", fp); // expected-warning{{format specifies type 'char **' but the argument has type 'float *'}} } void test_quad(int *x, long long *llx) { scanf("%qd", x); // expected-warning{{format specifies type 'long long *' but the argument has type 'int *'}} scanf("%qd", llx); // no-warning } void test_writeback(int *x) { scanf("%n", (void*)0); // expected-warning{{format specifies type 'int *' but the argument has type 'void *'}} scanf("%n %c", x, x); // expected-warning{{format specifies type 'char *' but the argument has type 'int *'}} scanf("%hhn", (signed char*)0); // no-warning scanf("%hhn", (char*)0); // no-warning scanf("%hhn", (unsigned char*)0); // no-warning scanf("%hhn", (int*)0); // expected-warning{{format specifies type 'signed char *' but the argument has type 'int *'}} scanf("%hn", (short*)0); // no-warning scanf("%hn", (unsigned short*)0); // no-warning scanf("%hn", (int*)0); // expected-warning{{format specifies type 'short *' but the argument has type 'int *'}} scanf("%n", (int*)0); // no-warning scanf("%n", (unsigned int*)0); // no-warning scanf("%n", (char*)0); // expected-warning{{format specifies type 'int *' but the argument has type 'char *'}} scanf("%ln", (long*)0); // no-warning scanf("%ln", (unsigned long*)0); // no-warning scanf("%ln", (int*)0); // expected-warning{{format specifies type 'long *' but the argument has type 'int *'}} scanf("%lln", (long long*)0); // no-warning scanf("%lln", (unsigned long long*)0); // no-warning scanf("%lln", (int*)0); // expected-warning{{format specifies type 'long long *' but the argument has type 'int *'}} scanf("%qn", (long long*)0); // no-warning scanf("%qn", (unsigned long long*)0); // no-warning scanf("%qn", (int*)0); // expected-warning{{format specifies type 'long long *' but the argument has type 'int *'}} } void test_qualifiers(const int *cip, volatile int* vip, const char *ccp, volatile char* vcp, const volatile int *cvip) { scanf("%d", cip); // expected-warning{{format specifies type 'int *' but the argument has type 'const int *'}} scanf("%n", cip); // expected-warning{{format specifies type 'int *' but the argument has type 'const int *'}} scanf("%s", ccp); // expected-warning{{format specifies type 'char *' but the argument has type 'const char *'}} scanf("%d", cvip); // expected-warning{{format specifies type 'int *' but the argument has type 'const volatile int *'}} scanf("%d", vip); // No warning. scanf("%n", vip); // No warning. scanf("%c", vcp); // No warning. typedef int* ip_t; typedef const int* cip_t; scanf("%d", (ip_t)0); // No warning. scanf("%d", (cip_t)0); // expected-warning{{format specifies type 'int *' but the argument has type 'cip_t' (aka 'const int *')}} }
apache-2.0
adam8157/gpdb
src/backend/gporca/libgpopt/src/xforms/CXformLeftOuterApply2LeftOuterJoin.cpp
10
1715
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2012 EMC Corp. // // @filename: // CXformLeftOuterApply2LeftOuterJoin.cpp // // @doc: // Implementation of transform //--------------------------------------------------------------------------- #include "gpopt/xforms/CXformLeftOuterApply2LeftOuterJoin.h" #include "gpos/base.h" using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CXformLeftOuterApply2LeftOuterJoin::Exfp // // @doc: // Compute xform promise for a given expression handle; // outer references are not allowed // //--------------------------------------------------------------------------- CXform::EXformPromise CXformLeftOuterApply2LeftOuterJoin::Exfp(CExpressionHandle &exprhdl) const { // if there are outer refs that include columns from the immediate outer child, the // transformation is applicable if (exprhdl.HasOuterRefs(1 /*child_index*/) && !CUtils::FInnerUsesExternalColsOnly(exprhdl)) { return CXform::ExfpHigh; } return CXform::ExfpNone; } //--------------------------------------------------------------------------- // @function: // CXformLeftOuterApply2LeftOuterJoin::Transform // // @doc: // Actual transformation // //--------------------------------------------------------------------------- void CXformLeftOuterApply2LeftOuterJoin::Transform(CXformContext *pxfctxt, CXformResult *pxfres, CExpression *pexpr) const { GPOS_ASSERT(nullptr != pxfctxt); GPOS_ASSERT(FPromising(pxfctxt->Pmp(), this, pexpr)); GPOS_ASSERT(FCheckPattern(pexpr)); Decorrelate(pxfctxt, pxfres, pexpr); } // EOF
apache-2.0
matsprea/omim
base/base_tests/geo_object_id_tests.cpp
10
1933
#include "testing/testing.hpp" #include "base/geo_object_id.hpp" namespace base { UNIT_TEST(GeoObjectId) { GeoObjectId const invalid(GeoObjectId::kInvalid); TEST_EQUAL(invalid.GetType(), GeoObjectId::Type::Invalid, ()); TEST_EQUAL(DebugPrint(invalid), "Invalid 0", ()); GeoObjectId const node(GeoObjectId::Type::ObsoleteOsmNode, 12345); TEST_EQUAL(node.GetSerialId(), 12345ULL, ()); TEST_EQUAL(node.GetType(), GeoObjectId::Type::ObsoleteOsmNode, ()); TEST_EQUAL(DebugPrint(node), "Osm Node 12345", ()); GeoObjectId const way(GeoObjectId::Type::ObsoleteOsmWay, 93245123456332ULL); TEST_EQUAL(way.GetSerialId(), 93245123456332ULL, ()); TEST_EQUAL(way.GetType(), GeoObjectId::Type::ObsoleteOsmWay, ()); TEST_EQUAL(DebugPrint(way), "Osm Way 93245123456332", ()); GeoObjectId const relation(GeoObjectId::Type::ObsoleteOsmRelation, 5); TEST_EQUAL(relation.GetSerialId(), 5ULL, ()); TEST_EQUAL(relation.GetType(), GeoObjectId::Type::ObsoleteOsmRelation, ()); TEST_EQUAL(DebugPrint(relation), "Osm Relation 5", ()); // 2^48 - 1, maximal possible serial id. GeoObjectId const surrogate(GeoObjectId::Type::OsmSurrogate, 281474976710655ULL); TEST_EQUAL(surrogate.GetSerialId(), 281474976710655ULL, ()); TEST_EQUAL(surrogate.GetType(), GeoObjectId::Type::OsmSurrogate, ()); TEST_EQUAL(DebugPrint(surrogate), "Osm Surrogate 281474976710655", ()); // 0 is not prohibited by the encoding even though OSM ids start from 1. GeoObjectId const booking(GeoObjectId::Type::BookingComNode, 0); TEST_EQUAL(booking.GetSerialId(), 0, ()); TEST_EQUAL(booking.GetType(), GeoObjectId::Type::BookingComNode, ()); TEST_EQUAL(DebugPrint(booking), "Booking.com 0", ()); GeoObjectId const fias(GeoObjectId::Type::Fias, 0xf1a5); TEST_EQUAL(fias.GetSerialId(), 0xf1a5, ()); TEST_EQUAL(fias.GetType(), GeoObjectId::Type::Fias, ()); TEST_EQUAL(DebugPrint(fias), "FIAS 61861", ()); } } // namespace base
apache-2.0
shenki/skiboot
ccan/str/test/run.c
13
2632
#include <ccan/str/str.h> #include <ccan/str/str.c> #include <stdlib.h> #include <stdio.h> #include <ccan/tap/tap.h> #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0])) static const char *substrings[] = { "far", "bar", "baz", "b", "ba", "z", "ar", NULL }; #define NUM_SUBSTRINGS (ARRAY_SIZE(substrings) - 1) static char *strdup_rev(const char *s) { char *ret = strdup(s); unsigned int i; for (i = 0; i < strlen(s); i++) ret[i] = s[strlen(s) - i - 1]; return ret; } int main(void) { unsigned int i, j, n; char *strings[NUM_SUBSTRINGS * NUM_SUBSTRINGS]; n = 0; for (i = 0; i < NUM_SUBSTRINGS; i++) { for (j = 0; j < NUM_SUBSTRINGS; j++) { strings[n] = malloc(strlen(substrings[i]) + strlen(substrings[j]) + 1); sprintf(strings[n++], "%s%s", substrings[i], substrings[j]); } } plan_tests(n * n * 5 + 16); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { unsigned int k, identical = 0; char *reva, *revb; /* Find first difference. */ for (k = 0; strings[i][k]==strings[j][k]; k++) { if (k == strlen(strings[i])) { identical = 1; break; } } if (identical) ok1(streq(strings[i], strings[j])); else ok1(!streq(strings[i], strings[j])); /* Postfix test should be equivalent to prefix * test on reversed string. */ reva = strdup_rev(strings[i]); revb = strdup_rev(strings[j]); if (!strings[i][k]) { ok1(strstarts(strings[j], strings[i])); ok1(strends(revb, reva)); } else { ok1(!strstarts(strings[j], strings[i])); ok1(!strends(revb, reva)); } if (!strings[j][k]) { ok1(strstarts(strings[i], strings[j])); ok1(strends(reva, revb)); } else { ok1(!strstarts(strings[i], strings[j])); ok1(!strends(reva, revb)); } free(reva); free(revb); } } for (i = 0; i < n; i++) free(strings[i]); ok1(streq(stringify(NUM_SUBSTRINGS), "((sizeof(substrings) / sizeof(substrings[0])) - 1)")); ok1(streq(stringify(ARRAY_SIZE(substrings)), "(sizeof(substrings) / sizeof(substrings[0]))")); ok1(streq(stringify(i == 0), "i == 0")); ok1(strcount("aaaaaa", "b") == 0); ok1(strcount("aaaaaa", "a") == 6); ok1(strcount("aaaaaa", "aa") == 3); ok1(strcount("aaaaaa", "aaa") == 2); ok1(strcount("aaaaaa", "aaaa") == 1); ok1(strcount("aaaaaa", "aaaaa") == 1); ok1(strcount("aaaaaa", "aaaaaa") == 1); ok1(strcount("aaa aaa", "b") == 0); ok1(strcount("aaa aaa", "a") == 6); ok1(strcount("aaa aaa", "aa") == 2); ok1(strcount("aaa aaa", "aaa") == 2); ok1(strcount("aaa aaa", "aaaa") == 0); ok1(strcount("aaa aaa", "aaaaa") == 0); return exit_status(); }
apache-2.0
fengshao0907/Open-Source-Research
HotSpot1.7-JVM-Linux-x86/src/cpu/x86/vm/interp_masm_x86_32.cpp
14
51911
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "interp_masm_x86_32.hpp" #include "interpreter/interpreter.hpp" #include "interpreter/interpreterRuntime.hpp" #include "oops/arrayOop.hpp" #include "oops/markOop.hpp" #include "oops/methodDataOop.hpp" #include "oops/methodOop.hpp" #include "prims/jvmtiExport.hpp" #include "prims/jvmtiRedefineClassesTrace.hpp" #include "prims/jvmtiThreadState.hpp" #include "runtime/basicLock.hpp" #include "runtime/biasedLocking.hpp" #include "runtime/sharedRuntime.hpp" #ifdef TARGET_OS_FAMILY_linux # include "thread_linux.inline.hpp" #endif #ifdef TARGET_OS_FAMILY_solaris # include "thread_solaris.inline.hpp" #endif #ifdef TARGET_OS_FAMILY_windows # include "thread_windows.inline.hpp" #endif #ifdef TARGET_OS_FAMILY_bsd # include "thread_bsd.inline.hpp" #endif // Implementation of InterpreterMacroAssembler #ifdef CC_INTERP void InterpreterMacroAssembler::get_method(Register reg) { movptr(reg, Address(rbp, -(sizeof(BytecodeInterpreter) + 2 * wordSize))); movptr(reg, Address(reg, byte_offset_of(BytecodeInterpreter, _method))); } #endif // CC_INTERP #ifndef CC_INTERP void InterpreterMacroAssembler::call_VM_leaf_base( address entry_point, int number_of_arguments ) { // interpreter specific // // Note: No need to save/restore bcp & locals (rsi & rdi) pointer // since these are callee saved registers and no blocking/ // GC can happen in leaf calls. // Further Note: DO NOT save/restore bcp/locals. If a caller has // already saved them so that it can use rsi/rdi as temporaries // then a save/restore here will DESTROY the copy the caller // saved! There used to be a save_bcp() that only happened in // the ASSERT path (no restore_bcp). Which caused bizarre failures // when jvm built with ASSERTs. #ifdef ASSERT { Label L; cmpptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD); jcc(Assembler::equal, L); stop("InterpreterMacroAssembler::call_VM_leaf_base: last_sp != NULL"); bind(L); } #endif // super call MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments); // interpreter specific // Used to ASSERT that rsi/rdi were equal to frame's bcp/locals // but since they may not have been saved (and we don't want to // save them here (see note above) the assert is invalid. } void InterpreterMacroAssembler::call_VM_base( Register oop_result, Register java_thread, Register last_java_sp, address entry_point, int number_of_arguments, bool check_exceptions ) { #ifdef ASSERT { Label L; cmpptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD); jcc(Assembler::equal, L); stop("InterpreterMacroAssembler::call_VM_base: last_sp != NULL"); bind(L); } #endif /* ASSERT */ // interpreter specific // // Note: Could avoid restoring locals ptr (callee saved) - however doesn't // really make a difference for these runtime calls, since they are // slow anyway. Btw., bcp must be saved/restored since it may change // due to GC. assert(java_thread == noreg , "not expecting a precomputed java thread"); save_bcp(); // super call MacroAssembler::call_VM_base(oop_result, java_thread, last_java_sp, entry_point, number_of_arguments, check_exceptions); // interpreter specific restore_bcp(); restore_locals(); } void InterpreterMacroAssembler::check_and_handle_popframe(Register java_thread) { if (JvmtiExport::can_pop_frame()) { Label L; // Initiate popframe handling only if it is not already being processed. If the flag // has the popframe_processing bit set, it means that this code is called *during* popframe // handling - we don't want to reenter. Register pop_cond = java_thread; // Not clear if any other register is available... movl(pop_cond, Address(java_thread, JavaThread::popframe_condition_offset())); testl(pop_cond, JavaThread::popframe_pending_bit); jcc(Assembler::zero, L); testl(pop_cond, JavaThread::popframe_processing_bit); jcc(Assembler::notZero, L); // Call Interpreter::remove_activation_preserving_args_entry() to get the // address of the same-named entrypoint in the generated interpreter code. call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_preserving_args_entry)); jmp(rax); bind(L); get_thread(java_thread); } } void InterpreterMacroAssembler::load_earlyret_value(TosState state) { get_thread(rcx); movl(rcx, Address(rcx, JavaThread::jvmti_thread_state_offset())); const Address tos_addr (rcx, JvmtiThreadState::earlyret_tos_offset()); const Address oop_addr (rcx, JvmtiThreadState::earlyret_oop_offset()); const Address val_addr (rcx, JvmtiThreadState::earlyret_value_offset()); const Address val_addr1(rcx, JvmtiThreadState::earlyret_value_offset() + in_ByteSize(wordSize)); switch (state) { case atos: movptr(rax, oop_addr); movptr(oop_addr, NULL_WORD); verify_oop(rax, state); break; case ltos: movl(rdx, val_addr1); // fall through case btos: // fall through case ctos: // fall through case stos: // fall through case itos: movl(rax, val_addr); break; case ftos: fld_s(val_addr); break; case dtos: fld_d(val_addr); break; case vtos: /* nothing to do */ break; default : ShouldNotReachHere(); } // Clean up tos value in the thread object movl(tos_addr, (int32_t) ilgl); movptr(val_addr, NULL_WORD); NOT_LP64(movptr(val_addr1, NULL_WORD)); } void InterpreterMacroAssembler::check_and_handle_earlyret(Register java_thread) { if (JvmtiExport::can_force_early_return()) { Label L; Register tmp = java_thread; movptr(tmp, Address(tmp, JavaThread::jvmti_thread_state_offset())); testptr(tmp, tmp); jcc(Assembler::zero, L); // if (thread->jvmti_thread_state() == NULL) exit; // Initiate earlyret handling only if it is not already being processed. // If the flag has the earlyret_processing bit set, it means that this code // is called *during* earlyret handling - we don't want to reenter. movl(tmp, Address(tmp, JvmtiThreadState::earlyret_state_offset())); cmpl(tmp, JvmtiThreadState::earlyret_pending); jcc(Assembler::notEqual, L); // Call Interpreter::remove_activation_early_entry() to get the address of the // same-named entrypoint in the generated interpreter code. get_thread(java_thread); movptr(tmp, Address(java_thread, JavaThread::jvmti_thread_state_offset())); pushl(Address(tmp, JvmtiThreadState::earlyret_tos_offset())); call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_early_entry), 1); jmp(rax); bind(L); get_thread(java_thread); } } void InterpreterMacroAssembler::get_unsigned_2_byte_index_at_bcp(Register reg, int bcp_offset) { assert(bcp_offset >= 0, "bcp is still pointing to start of bytecode"); movl(reg, Address(rsi, bcp_offset)); bswapl(reg); shrl(reg, 16); } void InterpreterMacroAssembler::get_cache_index_at_bcp(Register reg, int bcp_offset, size_t index_size) { assert(bcp_offset > 0, "bcp is still pointing to start of bytecode"); if (index_size == sizeof(u2)) { load_unsigned_short(reg, Address(rsi, bcp_offset)); } else if (index_size == sizeof(u4)) { assert(EnableInvokeDynamic, "giant index used only for JSR 292"); movl(reg, Address(rsi, bcp_offset)); // Check if the secondary index definition is still ~x, otherwise // we have to change the following assembler code to calculate the // plain index. assert(constantPoolCacheOopDesc::decode_secondary_index(~123) == 123, "else change next line"); notl(reg); // convert to plain index } else if (index_size == sizeof(u1)) { assert(EnableInvokeDynamic, "tiny index used only for JSR 292"); load_unsigned_byte(reg, Address(rsi, bcp_offset)); } else { ShouldNotReachHere(); } } void InterpreterMacroAssembler::get_cache_and_index_at_bcp(Register cache, Register index, int bcp_offset, size_t index_size) { assert_different_registers(cache, index); get_cache_index_at_bcp(index, bcp_offset, index_size); movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize)); assert(sizeof(ConstantPoolCacheEntry) == 4*wordSize, "adjust code below"); shlptr(index, 2); // convert from field index to ConstantPoolCacheEntry index } void InterpreterMacroAssembler::get_cache_and_index_and_bytecode_at_bcp(Register cache, Register index, Register bytecode, int byte_no, int bcp_offset, size_t index_size) { get_cache_and_index_at_bcp(cache, index, bcp_offset, index_size); movptr(bytecode, Address(cache, index, Address::times_ptr, constantPoolCacheOopDesc::base_offset() + ConstantPoolCacheEntry::indices_offset())); const int shift_count = (1 + byte_no) * BitsPerByte; assert((byte_no == TemplateTable::f1_byte && shift_count == ConstantPoolCacheEntry::bytecode_1_shift) || (byte_no == TemplateTable::f2_byte && shift_count == ConstantPoolCacheEntry::bytecode_2_shift), "correct shift count"); shrptr(bytecode, shift_count); assert(ConstantPoolCacheEntry::bytecode_1_mask == ConstantPoolCacheEntry::bytecode_2_mask, "common mask"); andptr(bytecode, ConstantPoolCacheEntry::bytecode_1_mask); } void InterpreterMacroAssembler::get_cache_entry_pointer_at_bcp(Register cache, Register tmp, int bcp_offset, size_t index_size) { assert(cache != tmp, "must use different register"); get_cache_index_at_bcp(tmp, bcp_offset, index_size); assert(sizeof(ConstantPoolCacheEntry) == 4*wordSize, "adjust code below"); // convert from field index to ConstantPoolCacheEntry index // and from word offset to byte offset shll(tmp, 2 + LogBytesPerWord); movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize)); // skip past the header addptr(cache, in_bytes(constantPoolCacheOopDesc::base_offset())); addptr(cache, tmp); // construct pointer to cache entry } // Generate a subtype check: branch to ok_is_subtype if sub_klass is // a subtype of super_klass. EAX holds the super_klass. Blows ECX. // Resets EDI to locals. Register sub_klass cannot be any of the above. void InterpreterMacroAssembler::gen_subtype_check( Register Rsub_klass, Label &ok_is_subtype ) { assert( Rsub_klass != rax, "rax, holds superklass" ); assert( Rsub_klass != rcx, "used as a temp" ); assert( Rsub_klass != rdi, "used as a temp, restored from locals" ); // Profile the not-null value's klass. profile_typecheck(rcx, Rsub_klass, rdi); // blows rcx, reloads rdi // Do the check. check_klass_subtype(Rsub_klass, rax, rcx, ok_is_subtype); // blows rcx // Profile the failure of the check. profile_typecheck_failed(rcx); // blows rcx } void InterpreterMacroAssembler::f2ieee() { if (IEEEPrecision) { fstp_s(Address(rsp, 0)); fld_s(Address(rsp, 0)); } } void InterpreterMacroAssembler::d2ieee() { if (IEEEPrecision) { fstp_d(Address(rsp, 0)); fld_d(Address(rsp, 0)); } } // Java Expression Stack void InterpreterMacroAssembler::pop_ptr(Register r) { pop(r); } void InterpreterMacroAssembler::pop_i(Register r) { pop(r); } void InterpreterMacroAssembler::pop_l(Register lo, Register hi) { pop(lo); pop(hi); } void InterpreterMacroAssembler::pop_f() { fld_s(Address(rsp, 0)); addptr(rsp, 1 * wordSize); } void InterpreterMacroAssembler::pop_d() { fld_d(Address(rsp, 0)); addptr(rsp, 2 * wordSize); } void InterpreterMacroAssembler::pop(TosState state) { switch (state) { case atos: pop_ptr(rax); break; case btos: // fall through case ctos: // fall through case stos: // fall through case itos: pop_i(rax); break; case ltos: pop_l(rax, rdx); break; case ftos: pop_f(); break; case dtos: pop_d(); break; case vtos: /* nothing to do */ break; default : ShouldNotReachHere(); } verify_oop(rax, state); } void InterpreterMacroAssembler::push_ptr(Register r) { push(r); } void InterpreterMacroAssembler::push_i(Register r) { push(r); } void InterpreterMacroAssembler::push_l(Register lo, Register hi) { push(hi); push(lo); } void InterpreterMacroAssembler::push_f() { // Do not schedule for no AGI! Never write beyond rsp! subptr(rsp, 1 * wordSize); fstp_s(Address(rsp, 0)); } void InterpreterMacroAssembler::push_d(Register r) { // Do not schedule for no AGI! Never write beyond rsp! subptr(rsp, 2 * wordSize); fstp_d(Address(rsp, 0)); } void InterpreterMacroAssembler::push(TosState state) { verify_oop(rax, state); switch (state) { case atos: push_ptr(rax); break; case btos: // fall through case ctos: // fall through case stos: // fall through case itos: push_i(rax); break; case ltos: push_l(rax, rdx); break; case ftos: push_f(); break; case dtos: push_d(rax); break; case vtos: /* nothing to do */ break; default : ShouldNotReachHere(); } } // Helpers for swap and dup void InterpreterMacroAssembler::load_ptr(int n, Register val) { movptr(val, Address(rsp, Interpreter::expr_offset_in_bytes(n))); } void InterpreterMacroAssembler::store_ptr(int n, Register val) { movptr(Address(rsp, Interpreter::expr_offset_in_bytes(n)), val); } void InterpreterMacroAssembler::prepare_to_jump_from_interpreted() { // set sender sp lea(rsi, Address(rsp, wordSize)); // record last_sp movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), rsi); } // Jump to from_interpreted entry of a call unless single stepping is possible // in this thread in which case we must call the i2i entry void InterpreterMacroAssembler::jump_from_interpreted(Register method, Register temp) { prepare_to_jump_from_interpreted(); if (JvmtiExport::can_post_interpreter_events()) { Label run_compiled_code; // JVMTI events, such as single-stepping, are implemented partly by avoiding running // compiled code in threads for which the event is enabled. Check here for // interp_only_mode if these events CAN be enabled. get_thread(temp); // interp_only is an int, on little endian it is sufficient to test the byte only // Is a cmpl faster? cmpb(Address(temp, JavaThread::interp_only_mode_offset()), 0); jccb(Assembler::zero, run_compiled_code); jmp(Address(method, methodOopDesc::interpreter_entry_offset())); bind(run_compiled_code); } jmp(Address(method, methodOopDesc::from_interpreted_offset())); } // The following two routines provide a hook so that an implementation // can schedule the dispatch in two parts. Intel does not do this. void InterpreterMacroAssembler::dispatch_prolog(TosState state, int step) { // Nothing Intel-specific to be done here. } void InterpreterMacroAssembler::dispatch_epilog(TosState state, int step) { dispatch_next(state, step); } void InterpreterMacroAssembler::dispatch_base(TosState state, address* table, bool verifyoop) { verify_FPU(1, state); if (VerifyActivationFrameSize) { Label L; mov(rcx, rbp); subptr(rcx, rsp); int min_frame_size = (frame::link_offset - frame::interpreter_frame_initial_sp_offset) * wordSize; cmpptr(rcx, min_frame_size); jcc(Assembler::greaterEqual, L); stop("broken stack frame"); bind(L); } if (verifyoop) verify_oop(rax, state); Address index(noreg, rbx, Address::times_ptr); ExternalAddress tbl((address)table); ArrayAddress dispatch(tbl, index); jump(dispatch); } void InterpreterMacroAssembler::dispatch_only(TosState state) { dispatch_base(state, Interpreter::dispatch_table(state)); } void InterpreterMacroAssembler::dispatch_only_normal(TosState state) { dispatch_base(state, Interpreter::normal_table(state)); } void InterpreterMacroAssembler::dispatch_only_noverify(TosState state) { dispatch_base(state, Interpreter::normal_table(state), false); } void InterpreterMacroAssembler::dispatch_next(TosState state, int step) { // load next bytecode (load before advancing rsi to prevent AGI) load_unsigned_byte(rbx, Address(rsi, step)); // advance rsi increment(rsi, step); dispatch_base(state, Interpreter::dispatch_table(state)); } void InterpreterMacroAssembler::dispatch_via(TosState state, address* table) { // load current bytecode load_unsigned_byte(rbx, Address(rsi, 0)); dispatch_base(state, table); } // remove activation // // Unlock the receiver if this is a synchronized method. // Unlock any Java monitors from syncronized blocks. // Remove the activation from the stack. // // If there are locked Java monitors // If throw_monitor_exception // throws IllegalMonitorStateException // Else if install_monitor_exception // installs IllegalMonitorStateException // Else // no error processing void InterpreterMacroAssembler::remove_activation(TosState state, Register ret_addr, bool throw_monitor_exception, bool install_monitor_exception, bool notify_jvmdi) { // Note: Registers rax, rdx and FPU ST(0) may be in use for the result // check if synchronized method Label unlocked, unlock, no_unlock; get_thread(rcx); const Address do_not_unlock_if_synchronized(rcx, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset())); movbool(rbx, do_not_unlock_if_synchronized); mov(rdi,rbx); movbool(do_not_unlock_if_synchronized, false); // reset the flag movptr(rbx, Address(rbp, frame::interpreter_frame_method_offset * wordSize)); // get method access flags movl(rcx, Address(rbx, methodOopDesc::access_flags_offset())); testl(rcx, JVM_ACC_SYNCHRONIZED); jcc(Assembler::zero, unlocked); // Don't unlock anything if the _do_not_unlock_if_synchronized flag // is set. mov(rcx,rdi); testbool(rcx); jcc(Assembler::notZero, no_unlock); // unlock monitor push(state); // save result // BasicObjectLock will be first in list, since this is a synchronized method. However, need // to check that the object has not been unlocked by an explicit monitorexit bytecode. const Address monitor(rbp, frame::interpreter_frame_initial_sp_offset * wordSize - (int)sizeof(BasicObjectLock)); lea (rdx, monitor); // address of first monitor movptr (rax, Address(rdx, BasicObjectLock::obj_offset_in_bytes())); testptr(rax, rax); jcc (Assembler::notZero, unlock); pop(state); if (throw_monitor_exception) { empty_FPU_stack(); // remove possible return value from FPU-stack, otherwise stack could overflow // Entry already unlocked, need to throw exception call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception)); should_not_reach_here(); } else { // Monitor already unlocked during a stack unroll. // If requested, install an illegal_monitor_state_exception. // Continue with stack unrolling. if (install_monitor_exception) { empty_FPU_stack(); // remove possible return value from FPU-stack, otherwise stack could overflow call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::new_illegal_monitor_state_exception)); } jmp(unlocked); } bind(unlock); unlock_object(rdx); pop(state); // Check that for block-structured locking (i.e., that all locked objects has been unlocked) bind(unlocked); // rax, rdx: Might contain return value // Check that all monitors are unlocked { Label loop, exception, entry, restart; const int entry_size = frame::interpreter_frame_monitor_size() * wordSize; const Address monitor_block_top(rbp, frame::interpreter_frame_monitor_block_top_offset * wordSize); const Address monitor_block_bot(rbp, frame::interpreter_frame_initial_sp_offset * wordSize); bind(restart); movptr(rcx, monitor_block_top); // points to current entry, starting with top-most entry lea(rbx, monitor_block_bot); // points to word before bottom of monitor block jmp(entry); // Entry already locked, need to throw exception bind(exception); if (throw_monitor_exception) { empty_FPU_stack(); // remove possible return value from FPU-stack, otherwise stack could overflow // Throw exception call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception)); should_not_reach_here(); } else { // Stack unrolling. Unlock object and install illegal_monitor_exception // Unlock does not block, so don't have to worry about the frame push(state); mov(rdx, rcx); unlock_object(rdx); pop(state); if (install_monitor_exception) { empty_FPU_stack(); // remove possible return value from FPU-stack, otherwise stack could overflow call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::new_illegal_monitor_state_exception)); } jmp(restart); } bind(loop); cmpptr(Address(rcx, BasicObjectLock::obj_offset_in_bytes()), (int32_t)NULL_WORD); // check if current entry is used jcc(Assembler::notEqual, exception); addptr(rcx, entry_size); // otherwise advance to next entry bind(entry); cmpptr(rcx, rbx); // check if bottom reached jcc(Assembler::notEqual, loop); // if not at bottom then check this entry } bind(no_unlock); // jvmti support if (notify_jvmdi) { notify_method_exit(state, NotifyJVMTI); // preserve TOSCA } else { notify_method_exit(state, SkipNotifyJVMTI); // preserve TOSCA } // remove activation movptr(rbx, Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize)); // get sender sp leave(); // remove frame anchor pop(ret_addr); // get return address mov(rsp, rbx); // set sp to sender sp if (UseSSE) { // float and double are returned in xmm register in SSE-mode if (state == ftos && UseSSE >= 1) { subptr(rsp, wordSize); fstp_s(Address(rsp, 0)); movflt(xmm0, Address(rsp, 0)); addptr(rsp, wordSize); } else if (state == dtos && UseSSE >= 2) { subptr(rsp, 2*wordSize); fstp_d(Address(rsp, 0)); movdbl(xmm0, Address(rsp, 0)); addptr(rsp, 2*wordSize); } } } #endif /* !CC_INTERP */ // Lock object // // Argument: rdx : Points to BasicObjectLock to be used for locking. Must // be initialized with object to lock void InterpreterMacroAssembler::lock_object(Register lock_reg) { assert(lock_reg == rdx, "The argument is only for looks. It must be rdx"); if (UseHeavyMonitors) { call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter), lock_reg); } else { Label done; const Register swap_reg = rax; // Must use rax, for cmpxchg instruction const Register obj_reg = rcx; // Will contain the oop const int obj_offset = BasicObjectLock::obj_offset_in_bytes(); const int lock_offset = BasicObjectLock::lock_offset_in_bytes (); const int mark_offset = lock_offset + BasicLock::displaced_header_offset_in_bytes(); Label slow_case; // Load object pointer into obj_reg %rcx movptr(obj_reg, Address(lock_reg, obj_offset)); if (UseBiasedLocking) { // Note: we use noreg for the temporary register since it's hard // to come up with a free register on all incoming code paths biased_locking_enter(lock_reg, obj_reg, swap_reg, noreg, false, done, &slow_case); } // Load immediate 1 into swap_reg %rax, movptr(swap_reg, (int32_t)1); // Load (object->mark() | 1) into swap_reg %rax, orptr(swap_reg, Address(obj_reg, 0)); // Save (object->mark() | 1) into BasicLock's displaced header movptr(Address(lock_reg, mark_offset), swap_reg); assert(lock_offset == 0, "displached header must be first word in BasicObjectLock"); if (os::is_MP()) { lock(); } cmpxchgptr(lock_reg, Address(obj_reg, 0)); if (PrintBiasedLockingStatistics) { cond_inc32(Assembler::zero, ExternalAddress((address) BiasedLocking::fast_path_entry_count_addr())); } jcc(Assembler::zero, done); // Test if the oopMark is an obvious stack pointer, i.e., // 1) (mark & 3) == 0, and // 2) rsp <= mark < mark + os::pagesize() // // These 3 tests can be done by evaluating the following // expression: ((mark - rsp) & (3 - os::vm_page_size())), // assuming both stack pointer and pagesize have their // least significant 2 bits clear. // NOTE: the oopMark is in swap_reg %rax, as the result of cmpxchg subptr(swap_reg, rsp); andptr(swap_reg, 3 - os::vm_page_size()); // Save the test result, for recursive case, the result is zero movptr(Address(lock_reg, mark_offset), swap_reg); if (PrintBiasedLockingStatistics) { cond_inc32(Assembler::zero, ExternalAddress((address) BiasedLocking::fast_path_entry_count_addr())); } jcc(Assembler::zero, done); bind(slow_case); // Call the runtime routine for slow case call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter), lock_reg); bind(done); } } // Unlocks an object. Used in monitorexit bytecode and remove_activation. // // Argument: rdx : Points to BasicObjectLock structure for lock // Throw an IllegalMonitorException if object is not locked by current thread // // Uses: rax, rbx, rcx, rdx void InterpreterMacroAssembler::unlock_object(Register lock_reg) { assert(lock_reg == rdx, "The argument is only for looks. It must be rdx"); if (UseHeavyMonitors) { call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg); } else { Label done; const Register swap_reg = rax; // Must use rax, for cmpxchg instruction const Register header_reg = rbx; // Will contain the old oopMark const Register obj_reg = rcx; // Will contain the oop save_bcp(); // Save in case of exception // Convert from BasicObjectLock structure to object and BasicLock structure // Store the BasicLock address into %rax, lea(swap_reg, Address(lock_reg, BasicObjectLock::lock_offset_in_bytes())); // Load oop into obj_reg(%rcx) movptr(obj_reg, Address(lock_reg, BasicObjectLock::obj_offset_in_bytes ())); // Free entry movptr(Address(lock_reg, BasicObjectLock::obj_offset_in_bytes()), NULL_WORD); if (UseBiasedLocking) { biased_locking_exit(obj_reg, header_reg, done); } // Load the old header from BasicLock structure movptr(header_reg, Address(swap_reg, BasicLock::displaced_header_offset_in_bytes())); // Test for recursion testptr(header_reg, header_reg); // zero for recursive case jcc(Assembler::zero, done); // Atomic swap back the old header if (os::is_MP()) lock(); cmpxchgptr(header_reg, Address(obj_reg, 0)); // zero for recursive case jcc(Assembler::zero, done); // Call the runtime routine for slow case. movptr(Address(lock_reg, BasicObjectLock::obj_offset_in_bytes()), obj_reg); // restore obj call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg); bind(done); restore_bcp(); } } #ifndef CC_INTERP // Test ImethodDataPtr. If it is null, continue at the specified label void InterpreterMacroAssembler::test_method_data_pointer(Register mdp, Label& zero_continue) { assert(ProfileInterpreter, "must be profiling interpreter"); movptr(mdp, Address(rbp, frame::interpreter_frame_mdx_offset * wordSize)); testptr(mdp, mdp); jcc(Assembler::zero, zero_continue); } // Set the method data pointer for the current bcp. void InterpreterMacroAssembler::set_method_data_pointer_for_bcp() { assert(ProfileInterpreter, "must be profiling interpreter"); Label set_mdp; push(rax); push(rbx); get_method(rbx); // Test MDO to avoid the call if it is NULL. movptr(rax, Address(rbx, in_bytes(methodOopDesc::method_data_offset()))); testptr(rax, rax); jcc(Assembler::zero, set_mdp); // rbx,: method // rsi: bcp call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::bcp_to_di), rbx, rsi); // rax,: mdi // mdo is guaranteed to be non-zero here, we checked for it before the call. movptr(rbx, Address(rbx, in_bytes(methodOopDesc::method_data_offset()))); addptr(rbx, in_bytes(methodDataOopDesc::data_offset())); addptr(rax, rbx); bind(set_mdp); movptr(Address(rbp, frame::interpreter_frame_mdx_offset * wordSize), rax); pop(rbx); pop(rax); } void InterpreterMacroAssembler::verify_method_data_pointer() { assert(ProfileInterpreter, "must be profiling interpreter"); #ifdef ASSERT Label verify_continue; push(rax); push(rbx); push(rcx); push(rdx); test_method_data_pointer(rcx, verify_continue); // If mdp is zero, continue get_method(rbx); // If the mdp is valid, it will point to a DataLayout header which is // consistent with the bcp. The converse is highly probable also. load_unsigned_short(rdx, Address(rcx, in_bytes(DataLayout::bci_offset()))); addptr(rdx, Address(rbx, methodOopDesc::const_offset())); lea(rdx, Address(rdx, constMethodOopDesc::codes_offset())); cmpptr(rdx, rsi); jcc(Assembler::equal, verify_continue); // rbx,: method // rsi: bcp // rcx: mdp call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::verify_mdp), rbx, rsi, rcx); bind(verify_continue); pop(rdx); pop(rcx); pop(rbx); pop(rax); #endif // ASSERT } void InterpreterMacroAssembler::set_mdp_data_at(Register mdp_in, int constant, Register value) { // %%% this seems to be used to store counter data which is surely 32bits // however 64bit side stores 64 bits which seems wrong assert(ProfileInterpreter, "must be profiling interpreter"); Address data(mdp_in, constant); movptr(data, value); } void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in, int constant, bool decrement) { // Counter address Address data(mdp_in, constant); increment_mdp_data_at(data, decrement); } void InterpreterMacroAssembler::increment_mdp_data_at(Address data, bool decrement) { assert( DataLayout::counter_increment==1, "flow-free idiom only works with 1" ); assert(ProfileInterpreter, "must be profiling interpreter"); // %%% 64bit treats this as 64 bit which seems unlikely if (decrement) { // Decrement the register. Set condition codes. addl(data, -DataLayout::counter_increment); // If the decrement causes the counter to overflow, stay negative Label L; jcc(Assembler::negative, L); addl(data, DataLayout::counter_increment); bind(L); } else { assert(DataLayout::counter_increment == 1, "flow-free idiom only works with 1"); // Increment the register. Set carry flag. addl(data, DataLayout::counter_increment); // If the increment causes the counter to overflow, pull back by 1. sbbl(data, 0); } } void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in, Register reg, int constant, bool decrement) { Address data(mdp_in, reg, Address::times_1, constant); increment_mdp_data_at(data, decrement); } void InterpreterMacroAssembler::set_mdp_flag_at(Register mdp_in, int flag_byte_constant) { assert(ProfileInterpreter, "must be profiling interpreter"); int header_offset = in_bytes(DataLayout::header_offset()); int header_bits = DataLayout::flag_mask_to_header_mask(flag_byte_constant); // Set the flag orl(Address(mdp_in, header_offset), header_bits); } void InterpreterMacroAssembler::test_mdp_data_at(Register mdp_in, int offset, Register value, Register test_value_out, Label& not_equal_continue) { assert(ProfileInterpreter, "must be profiling interpreter"); if (test_value_out == noreg) { cmpptr(value, Address(mdp_in, offset)); } else { // Put the test value into a register, so caller can use it: movptr(test_value_out, Address(mdp_in, offset)); cmpptr(test_value_out, value); } jcc(Assembler::notEqual, not_equal_continue); } void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in, int offset_of_disp) { assert(ProfileInterpreter, "must be profiling interpreter"); Address disp_address(mdp_in, offset_of_disp); addptr(mdp_in,disp_address); movptr(Address(rbp, frame::interpreter_frame_mdx_offset * wordSize), mdp_in); } void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in, Register reg, int offset_of_disp) { assert(ProfileInterpreter, "must be profiling interpreter"); Address disp_address(mdp_in, reg, Address::times_1, offset_of_disp); addptr(mdp_in, disp_address); movptr(Address(rbp, frame::interpreter_frame_mdx_offset * wordSize), mdp_in); } void InterpreterMacroAssembler::update_mdp_by_constant(Register mdp_in, int constant) { assert(ProfileInterpreter, "must be profiling interpreter"); addptr(mdp_in, constant); movptr(Address(rbp, frame::interpreter_frame_mdx_offset * wordSize), mdp_in); } void InterpreterMacroAssembler::update_mdp_for_ret(Register return_bci) { assert(ProfileInterpreter, "must be profiling interpreter"); push(return_bci); // save/restore across call_VM call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::update_mdp_for_ret), return_bci); pop(return_bci); } void InterpreterMacroAssembler::profile_taken_branch(Register mdp, Register bumped_count) { if (ProfileInterpreter) { Label profile_continue; // If no method data exists, go to profile_continue. // Otherwise, assign to mdp test_method_data_pointer(mdp, profile_continue); // We are taking a branch. Increment the taken count. // We inline increment_mdp_data_at to return bumped_count in a register //increment_mdp_data_at(mdp, in_bytes(JumpData::taken_offset())); Address data(mdp, in_bytes(JumpData::taken_offset())); // %%% 64bit treats these cells as 64 bit but they seem to be 32 bit movl(bumped_count,data); assert( DataLayout::counter_increment==1, "flow-free idiom only works with 1" ); addl(bumped_count, DataLayout::counter_increment); sbbl(bumped_count, 0); movl(data,bumped_count); // Store back out // The method data pointer needs to be updated to reflect the new target. update_mdp_by_offset(mdp, in_bytes(JumpData::displacement_offset())); bind (profile_continue); } } void InterpreterMacroAssembler::profile_not_taken_branch(Register mdp) { if (ProfileInterpreter) { Label profile_continue; // If no method data exists, go to profile_continue. test_method_data_pointer(mdp, profile_continue); // We are taking a branch. Increment the not taken count. increment_mdp_data_at(mdp, in_bytes(BranchData::not_taken_offset())); // The method data pointer needs to be updated to correspond to the next bytecode update_mdp_by_constant(mdp, in_bytes(BranchData::branch_data_size())); bind (profile_continue); } } void InterpreterMacroAssembler::profile_call(Register mdp) { if (ProfileInterpreter) { Label profile_continue; // If no method data exists, go to profile_continue. test_method_data_pointer(mdp, profile_continue); // We are making a call. Increment the count. increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset())); // The method data pointer needs to be updated to reflect the new target. update_mdp_by_constant(mdp, in_bytes(CounterData::counter_data_size())); bind (profile_continue); } } void InterpreterMacroAssembler::profile_final_call(Register mdp) { if (ProfileInterpreter) { Label profile_continue; // If no method data exists, go to profile_continue. test_method_data_pointer(mdp, profile_continue); // We are making a call. Increment the count. increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset())); // The method data pointer needs to be updated to reflect the new target. update_mdp_by_constant(mdp, in_bytes(VirtualCallData::virtual_call_data_size())); bind (profile_continue); } } void InterpreterMacroAssembler::profile_virtual_call(Register receiver, Register mdp, Register reg2, bool receiver_can_be_null) { if (ProfileInterpreter) { Label profile_continue; // If no method data exists, go to profile_continue. test_method_data_pointer(mdp, profile_continue); Label skip_receiver_profile; if (receiver_can_be_null) { Label not_null; testptr(receiver, receiver); jccb(Assembler::notZero, not_null); // We are making a call. Increment the count for null receiver. increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset())); jmp(skip_receiver_profile); bind(not_null); } // Record the receiver type. record_klass_in_profile(receiver, mdp, reg2, true); bind(skip_receiver_profile); // The method data pointer needs to be updated to reflect the new target. update_mdp_by_constant(mdp, in_bytes(VirtualCallData:: virtual_call_data_size())); bind(profile_continue); } } void InterpreterMacroAssembler::record_klass_in_profile_helper( Register receiver, Register mdp, Register reg2, int start_row, Label& done, bool is_virtual_call) { if (TypeProfileWidth == 0) { if (is_virtual_call) { increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset())); } return; } int last_row = VirtualCallData::row_limit() - 1; assert(start_row <= last_row, "must be work left to do"); // Test this row for both the receiver and for null. // Take any of three different outcomes: // 1. found receiver => increment count and goto done // 2. found null => keep looking for case 1, maybe allocate this cell // 3. found something else => keep looking for cases 1 and 2 // Case 3 is handled by a recursive call. for (int row = start_row; row <= last_row; row++) { Label next_test; bool test_for_null_also = (row == start_row); // See if the receiver is receiver[n]. int recvr_offset = in_bytes(VirtualCallData::receiver_offset(row)); test_mdp_data_at(mdp, recvr_offset, receiver, (test_for_null_also ? reg2 : noreg), next_test); // (Reg2 now contains the receiver from the CallData.) // The receiver is receiver[n]. Increment count[n]. int count_offset = in_bytes(VirtualCallData::receiver_count_offset(row)); increment_mdp_data_at(mdp, count_offset); jmp(done); bind(next_test); if (row == start_row) { Label found_null; // Failed the equality check on receiver[n]... Test for null. testptr(reg2, reg2); if (start_row == last_row) { // The only thing left to do is handle the null case. if (is_virtual_call) { jccb(Assembler::zero, found_null); // Receiver did not match any saved receiver and there is no empty row for it. // Increment total counter to indicate polymorphic case. increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset())); jmp(done); bind(found_null); } else { jcc(Assembler::notZero, done); } break; } // Since null is rare, make it be the branch-taken case. jcc(Assembler::zero, found_null); // Put all the "Case 3" tests here. record_klass_in_profile_helper(receiver, mdp, reg2, start_row + 1, done, is_virtual_call); // Found a null. Keep searching for a matching receiver, // but remember that this is an empty (unused) slot. bind(found_null); } } // In the fall-through case, we found no matching receiver, but we // observed the receiver[start_row] is NULL. // Fill in the receiver field and increment the count. int recvr_offset = in_bytes(VirtualCallData::receiver_offset(start_row)); set_mdp_data_at(mdp, recvr_offset, receiver); int count_offset = in_bytes(VirtualCallData::receiver_count_offset(start_row)); movptr(reg2, (intptr_t)DataLayout::counter_increment); set_mdp_data_at(mdp, count_offset, reg2); if (start_row > 0) { jmp(done); } } void InterpreterMacroAssembler::record_klass_in_profile(Register receiver, Register mdp, Register reg2, bool is_virtual_call) { assert(ProfileInterpreter, "must be profiling"); Label done; record_klass_in_profile_helper(receiver, mdp, reg2, 0, done, is_virtual_call); bind (done); } void InterpreterMacroAssembler::profile_ret(Register return_bci, Register mdp) { if (ProfileInterpreter) { Label profile_continue; uint row; // If no method data exists, go to profile_continue. test_method_data_pointer(mdp, profile_continue); // Update the total ret count. increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset())); for (row = 0; row < RetData::row_limit(); row++) { Label next_test; // See if return_bci is equal to bci[n]: test_mdp_data_at(mdp, in_bytes(RetData::bci_offset(row)), return_bci, noreg, next_test); // return_bci is equal to bci[n]. Increment the count. increment_mdp_data_at(mdp, in_bytes(RetData::bci_count_offset(row))); // The method data pointer needs to be updated to reflect the new target. update_mdp_by_offset(mdp, in_bytes(RetData::bci_displacement_offset(row))); jmp(profile_continue); bind(next_test); } update_mdp_for_ret(return_bci); bind (profile_continue); } } void InterpreterMacroAssembler::profile_null_seen(Register mdp) { if (ProfileInterpreter) { Label profile_continue; // If no method data exists, go to profile_continue. test_method_data_pointer(mdp, profile_continue); set_mdp_flag_at(mdp, BitData::null_seen_byte_constant()); // The method data pointer needs to be updated. int mdp_delta = in_bytes(BitData::bit_data_size()); if (TypeProfileCasts) { mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size()); } update_mdp_by_constant(mdp, mdp_delta); bind (profile_continue); } } void InterpreterMacroAssembler::profile_typecheck_failed(Register mdp) { if (ProfileInterpreter && TypeProfileCasts) { Label profile_continue; // If no method data exists, go to profile_continue. test_method_data_pointer(mdp, profile_continue); int count_offset = in_bytes(CounterData::count_offset()); // Back up the address, since we have already bumped the mdp. count_offset -= in_bytes(VirtualCallData::virtual_call_data_size()); // *Decrement* the counter. We expect to see zero or small negatives. increment_mdp_data_at(mdp, count_offset, true); bind (profile_continue); } } void InterpreterMacroAssembler::profile_typecheck(Register mdp, Register klass, Register reg2) { if (ProfileInterpreter) { Label profile_continue; // If no method data exists, go to profile_continue. test_method_data_pointer(mdp, profile_continue); // The method data pointer needs to be updated. int mdp_delta = in_bytes(BitData::bit_data_size()); if (TypeProfileCasts) { mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size()); // Record the object type. record_klass_in_profile(klass, mdp, reg2, false); assert(reg2 == rdi, "we know how to fix this blown reg"); restore_locals(); // Restore EDI } update_mdp_by_constant(mdp, mdp_delta); bind(profile_continue); } } void InterpreterMacroAssembler::profile_switch_default(Register mdp) { if (ProfileInterpreter) { Label profile_continue; // If no method data exists, go to profile_continue. test_method_data_pointer(mdp, profile_continue); // Update the default case count increment_mdp_data_at(mdp, in_bytes(MultiBranchData::default_count_offset())); // The method data pointer needs to be updated. update_mdp_by_offset(mdp, in_bytes(MultiBranchData::default_displacement_offset())); bind (profile_continue); } } void InterpreterMacroAssembler::profile_switch_case(Register index, Register mdp, Register reg2) { if (ProfileInterpreter) { Label profile_continue; // If no method data exists, go to profile_continue. test_method_data_pointer(mdp, profile_continue); // Build the base (index * per_case_size_in_bytes()) + case_array_offset_in_bytes() movptr(reg2, (intptr_t)in_bytes(MultiBranchData::per_case_size())); // index is positive and so should have correct value if this code were // used on 64bits imulptr(index, reg2); addptr(index, in_bytes(MultiBranchData::case_array_offset())); // Update the case count increment_mdp_data_at(mdp, index, in_bytes(MultiBranchData::relative_count_offset())); // The method data pointer needs to be updated. update_mdp_by_offset(mdp, index, in_bytes(MultiBranchData::relative_displacement_offset())); bind (profile_continue); } } #endif // !CC_INTERP void InterpreterMacroAssembler::verify_oop(Register reg, TosState state) { if (state == atos) MacroAssembler::verify_oop(reg); } #ifndef CC_INTERP void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) { if (state == ftos || state == dtos) MacroAssembler::verify_FPU(stack_depth); } #endif /* CC_INTERP */ void InterpreterMacroAssembler::notify_method_entry() { // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to // track stack depth. If it is possible to enter interp_only_mode we add // the code to check if the event should be sent. if (JvmtiExport::can_post_interpreter_events()) { Label L; get_thread(rcx); movl(rcx, Address(rcx, JavaThread::interp_only_mode_offset())); testl(rcx,rcx); jcc(Assembler::zero, L); call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_entry)); bind(L); } { SkipIfEqual skip_if(this, &DTraceMethodProbes, 0); get_thread(rcx); get_method(rbx); call_VM_leaf( CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), rcx, rbx); } // RedefineClasses() tracing support for obsolete method entry if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) { get_thread(rcx); get_method(rbx); call_VM_leaf( CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry), rcx, rbx); } } void InterpreterMacroAssembler::notify_method_exit( TosState state, NotifyMethodExitMode mode) { // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to // track stack depth. If it is possible to enter interp_only_mode we add // the code to check if the event should be sent. if (mode == NotifyJVMTI && JvmtiExport::can_post_interpreter_events()) { Label L; // Note: frame::interpreter_frame_result has a dependency on how the // method result is saved across the call to post_method_exit. If this // is changed then the interpreter_frame_result implementation will // need to be updated too. // For c++ interpreter the result is always stored at a known location in the frame // template interpreter will leave it on the top of the stack. NOT_CC_INTERP(push(state);) get_thread(rcx); movl(rcx, Address(rcx, JavaThread::interp_only_mode_offset())); testl(rcx,rcx); jcc(Assembler::zero, L); call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_exit)); bind(L); NOT_CC_INTERP(pop(state);) } { SkipIfEqual skip_if(this, &DTraceMethodProbes, 0); NOT_CC_INTERP(push(state)); get_thread(rbx); get_method(rcx); call_VM_leaf( CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), rbx, rcx); NOT_CC_INTERP(pop(state)); } } // Jump if ((*counter_addr += increment) & mask) satisfies the condition. void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr, int increment, int mask, Register scratch, bool preloaded, Condition cond, Label* where) { if (!preloaded) { movl(scratch, counter_addr); } incrementl(scratch, increment); movl(counter_addr, scratch); andl(scratch, mask); jcc(cond, *where); }
apache-2.0
graetzer/arangodb
3rdParty/boost/1.71.0/libs/asio/example/cpp11/executors/priority_scheduler.cpp
14
3940
#include <boost/asio/dispatch.hpp> #include <boost/asio/execution_context.hpp> #include <condition_variable> #include <iostream> #include <memory> #include <mutex> #include <queue> using boost::asio::dispatch; using boost::asio::execution_context; class priority_scheduler : public execution_context { public: // A class that satisfies the Executor requirements. class executor_type { public: executor_type(priority_scheduler& ctx, int pri) noexcept : context_(ctx), priority_(pri) { } priority_scheduler& context() const noexcept { return context_; } void on_work_started() const noexcept { // This executor doesn't count work. Instead, the scheduler simply runs // until explicitly stopped. } void on_work_finished() const noexcept { // This executor doesn't count work. Instead, the scheduler simply runs // until explicitly stopped. } template <class Func, class Alloc> void dispatch(Func&& f, const Alloc& a) const { post(std::forward<Func>(f), a); } template <class Func, class Alloc> void post(Func f, const Alloc& a) const { auto p(std::allocate_shared<item<Func>>( typename std::allocator_traits< Alloc>::template rebind_alloc<char>(a), priority_, std::move(f))); std::lock_guard<std::mutex> lock(context_.mutex_); context_.queue_.push(p); context_.condition_.notify_one(); } template <class Func, class Alloc> void defer(Func&& f, const Alloc& a) const { post(std::forward<Func>(f), a); } friend bool operator==(const executor_type& a, const executor_type& b) noexcept { return &a.context_ == &b.context_; } friend bool operator!=(const executor_type& a, const executor_type& b) noexcept { return &a.context_ != &b.context_; } private: priority_scheduler& context_; int priority_; }; executor_type get_executor(int pri = 0) noexcept { return executor_type(*const_cast<priority_scheduler*>(this), pri); } void run() { std::unique_lock<std::mutex> lock(mutex_); for (;;) { condition_.wait(lock, [&]{ return stopped_ || !queue_.empty(); }); if (stopped_) return; auto p(queue_.top()); queue_.pop(); lock.unlock(); p->execute_(p); lock.lock(); } } void stop() { std::lock_guard<std::mutex> lock(mutex_); stopped_ = true; condition_.notify_all(); } private: struct item_base { int priority_; void (*execute_)(std::shared_ptr<item_base>&); }; template <class Func> struct item : item_base { item(int pri, Func f) : function_(std::move(f)) { priority_ = pri; execute_ = [](std::shared_ptr<item_base>& p) { Func tmp(std::move(static_cast<item*>(p.get())->function_)); p.reset(); tmp(); }; } Func function_; }; struct item_comp { bool operator()( const std::shared_ptr<item_base>& a, const std::shared_ptr<item_base>& b) { return a->priority_ < b->priority_; } }; std::mutex mutex_; std::condition_variable condition_; std::priority_queue< std::shared_ptr<item_base>, std::vector<std::shared_ptr<item_base>>, item_comp> queue_; bool stopped_ = false; }; int main() { priority_scheduler sched; auto low = sched.get_executor(0); auto med = sched.get_executor(1); auto high = sched.get_executor(2); dispatch(low, []{ std::cout << "1\n"; }); dispatch(low, []{ std::cout << "11\n"; }); dispatch(med, []{ std::cout << "2\n"; }); dispatch(med, []{ std::cout << "22\n"; }); dispatch(high, []{ std::cout << "3\n"; }); dispatch(high, []{ std::cout << "33\n"; }); dispatch(high, []{ std::cout << "333\n"; }); dispatch(sched.get_executor(-1), [&]{ sched.stop(); }); sched.run(); }
apache-2.0
rokuz/omim
3party/opening_hours/parse_timespans.cpp
18
3124
#include "parse_opening_hours.hpp" #include "opening_hours_parsers.hpp" #include <boost/spirit/include/phoenix_bind.hpp> #include <boost/spirit/include/phoenix_operator.hpp> namespace osmoh { namespace parsing { time_selector_parser::time_selector_parser() : time_selector_parser::base_type(main) { using qi::int_; using qi::_1; using qi::_2; using qi::_3; using qi::_a; using qi::_val; using qi::lit; using charset::char_; using osmoh::HourMinutes; using osmoh::TimeEvent; using osmoh::Time; using osmoh::Timespan; hour_minutes = (hours >> lit(':') >> minutes) [bind(&HourMinutes::AddDuration, _val, _1), bind(&HourMinutes::AddDuration, _val, _2)] ; extended_hour_minutes = (exthours >> lit(':') >> minutes)[bind(&HourMinutes::AddDuration, _val, _1), bind(&HourMinutes::AddDuration, _val, _2)] ; variable_time = ( lit('(') >> charset::no_case[event] [bind(&TimeEvent::SetEvent, _val, _1)] >> ( (lit('+') >> hour_minutes) [bind(&TimeEvent::SetOffset, _val, _1)] | (lit('-') >> hour_minutes) [bind(&TimeEvent::SetOffset, _val, -_1)] ) >> lit(')') ) | charset::no_case[event][bind(&TimeEvent::SetEvent, _val, _1)] ; extended_time = extended_hour_minutes [bind(&Time::SetHourMinutes, _val, _1)] | variable_time [bind(&Time::SetEvent, _val, _1)] ; time = hour_minutes [bind(&Time::SetHourMinutes, _val, _1)] | variable_time [bind(&Time::SetEvent, _val, _1)] ; timespan = (time >> dash >> extended_time >> '/' >> hour_minutes) [bind(&Timespan::SetStart, _val, _1), bind(&Timespan::SetEnd, _val, _2), bind(&Timespan::SetPeriod, _val, _3)] | (time >> dash >> extended_time >> '/' >> minutes) [bind(&Timespan::SetStart, _val, _1), bind(&Timespan::SetEnd, _val, _2), bind(&Timespan::SetPeriod, _val, _3)] | (time >> dash >> extended_time >> '+') [bind(&Timespan::SetStart, _val, _1), bind(&Timespan::SetEnd, _val, _2), bind(&Timespan::SetPlus, _val, true)] | (time >> dash >> extended_time) [bind(&Timespan::SetStart, _val, _1), bind(&Timespan::SetEnd, _val, _2)] | (time >> '+') [bind(&Timespan::SetStart, _val, _1), bind(&Timespan::SetPlus, _val, true)] // This rule is only used for collection_times tag wish is not in our interest. // | time[bind(&Timespan::SetStart, _val, _1)] ; main %= timespan % ','; BOOST_SPIRIT_DEBUG_NODE(main); BOOST_SPIRIT_DEBUG_NODE(timespan); BOOST_SPIRIT_DEBUG_NODE(time); BOOST_SPIRIT_DEBUG_NODE(extended_time); BOOST_SPIRIT_DEBUG_NODE(variable_time); BOOST_SPIRIT_DEBUG_NODE(extended_hour_minutes); } } bool Parse(std::string const & str, TTimespans & context) { return osmoh::ParseImpl<parsing::time_selector_parser>(str, context); } } // namespace osmoh
apache-2.0
mbrukman/bazel
third_party/grpc/src/core/statistics/census_init.c
23
1930
/* * * Copyright 2015-2016, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "src/core/statistics/census_interface.h" #include <grpc/support/log.h> #include "src/core/statistics/census_rpc_stats.h" #include "src/core/statistics/census_tracing.h" void census_init(void) { census_tracing_init(); census_stats_store_init(); } void census_shutdown(void) { census_stats_store_shutdown(); census_tracing_shutdown(); }
apache-2.0
efortuna/AndroidSDKClone
ndk/sources/cxx-stl/llvm-libc++/libcxx/test/containers/sequences/deque/deque.cons/size_value_alloc.pass.cpp
28
1593
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <deque> // deque(size_type n, const value_type& v, const allocator_type& a); #include <deque> #include <cassert> #include "min_allocator.h" template <class T, class Allocator> void test(unsigned n, const T& x, const Allocator& a) { typedef std::deque<T, Allocator> C; typedef typename C::const_iterator const_iterator; C d(n, x, a); assert(d.get_allocator() == a); assert(d.size() == n); assert(distance(d.begin(), d.end()) == d.size()); for (const_iterator i = d.begin(), e = d.end(); i != e; ++i) assert(*i == x); } int main() { { std::allocator<int> a; test(0, 5, a); test(1, 10, a); test(10, 11, a); test(1023, -11, a); test(1024, 25, a); test(1025, 0, a); test(2047, 110, a); test(2048, -500, a); test(2049, 654, a); test(4095, 78, a); test(4096, 1165, a); test(4097, 157, a); } #if __cplusplus >= 201103L { min_allocator<int> a; test(0, 5, a); test(1, 10, a); test(10, 11, a); test(1023, -11, a); test(1024, 25, a); test(1025, 0, a); test(2047, 110, a); test(2048, -500, a); test(2049, 654, a); test(4095, 78, a); test(4096, 1165, a); test(4097, 157, a); } #endif }
apache-2.0
gerald-yang/ubuntu-iotivity-demo
iotivity-1.0.1/resource/csdk/stack/samples/tizen/SimpleClientServer/ocrouting.cpp
29
1863
/* **************************************************************** * * Copyright 2015 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. * ******************************************************************/ #include <stdio.h> #include <string.h> #include <string> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <pthread.h> #include <array> #include <iostream> #include "ocstack.h" #include "logger.h" #include "ocpayload.h" using namespace std; #define TAG "ocrouting" int gQuitFlag = 0; /* SIGINT handler: set gQuitFlag to 1 for graceful termination */ void handleSigInt(int signum) { if (signum == SIGINT) { gQuitFlag = 1; } } int main() { cout << "\nOCRouting sample is starting..."; if (OCInit(NULL, 0, OC_GATEWAY) != OC_STACK_OK) { cout << "\nOCStack init error"; return 0; } // Break from loop with Ctrl-C cout << "\nEntering ocrouting main loop..."; signal(SIGINT, handleSigInt); while (!gQuitFlag) { if (OCProcess() != OC_STACK_OK) { cout << "\nOCStack process error"; return 0; } } cout << "\nExiting ocrouting main loop..."; if (OCStop() != OC_STACK_OK) { cout << "\nOCStack process error"; } return 0; }
apache-2.0
davidfather/TizenRT
os/kernel/environ/env_findvar.c
31
5039
/**************************************************************************** * * 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. * ****************************************************************************/ /**************************************************************************** * kernel/environ/env_findvar.c * * Copyright (C) 2007, 2009, 2013-2014 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <tinyara/config.h> #ifndef CONFIG_DISABLE_ENVIRON #include <stdbool.h> #include <string.h> #include <sched.h> #include "environ/environ.h" /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: env_cmpname ****************************************************************************/ static bool env_cmpname(const char *pszname, const char *peqname) { /* Search until we find anything different in the two names */ for (; *pszname == *peqname; pszname++, peqname++) ; /* On sucess, pszname will end with '\0' and peqname with '=' */ if (*pszname == '\0' && *peqname == '=') { return true; } return false; } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: env_findvar * * Description: * Search the provided environment structure for the variable of the * specified name. * * Parameters: * group The task group containging environment array to be searched. * pname The variable name to find * * Return Value: * A pointer to the name=value string in the environment * * Assumptions: * - Not called from an interrupt handler * - Pre-emptions is disabled by caller * ****************************************************************************/ FAR char *env_findvar(FAR struct task_group_s *group, const char *pname) { char *ptr; char *end; /* Verify input parameters */ DEBUGASSERT(group && pname); /* Search for a name=value string with matching name */ end = &group->tg_envp[group->tg_envsize]; for (ptr = group->tg_envp; ptr < end && !env_cmpname(pname, ptr); ptr += (strlen(ptr) + 1)) ; /* Check for success */ return (ptr < end) ? ptr : NULL; } #endif /* CONFIG_DISABLE_ENVIRON */
apache-2.0
bentwire/mbed
libraries/mbed/targets/hal/TARGET_STM/TARGET_STM32F7/i2c_api.c
31
13080
/* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2015, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* */ #include "mbed_assert.h" #include "i2c_api.h" #if DEVICE_I2C #include "cmsis.h" #include "pinmap.h" #include "PeripheralPins.h" #include "mbed_error.h" /* Timeout values for flags and events waiting loops. These timeouts are not based on accurate values, they just guarantee that the application will not remain stuck if the I2C communication is corrupted. */ #define FLAG_TIMEOUT ((int)0x4000) #define LONG_TIMEOUT ((int)0x8000) I2C_HandleTypeDef I2cHandle; int i2c1_inited = 0; /* Ready for next F7 devices int i2c2_inited = 0; int i2c3_inited = 0; int i2c4_inited = 0; */ void i2c_init(i2c_t *obj, PinName sda, PinName scl) { // Determine the I2C to use I2CName i2c_sda = (I2CName)pinmap_peripheral(sda, PinMap_I2C_SDA); I2CName i2c_scl = (I2CName)pinmap_peripheral(scl, PinMap_I2C_SCL); obj->i2c = (I2CName)pinmap_merge(i2c_sda, i2c_scl); MBED_ASSERT(obj->i2c != (I2CName)NC); // Enable I2C clock and pinout if not done if ((obj->i2c == I2C_1) && !i2c1_inited) { i2c1_inited = 1; __HAL_RCC_I2C1_CONFIG(RCC_I2C1CLKSOURCE_PCLK1); __HAL_RCC_I2C1_CLK_ENABLE(); // Configure I2C1 pins pinmap_pinout(sda, PinMap_I2C_SDA); pinmap_pinout(scl, PinMap_I2C_SCL); pin_mode(sda, OpenDrain); pin_mode(scl, OpenDrain); } /* Ready for next F7 devices #if defined(I2C2_BASE) if ((obj->i2c == I2C_2) && !i2c2_inited) { i2c2_inited = 1; __HAL_RCC_I2C2_CONFIG(RCC_I2C2CLKSOURCE_PCLK1); __HAL_RCC_I2C2_CLK_ENABLE(); // Configure I2C2 pins pinmap_pinout(sda, PinMap_I2C_SDA); pinmap_pinout(scl, PinMap_I2C_SCL); pin_mode(sda, OpenDrain); pin_mode(scl, OpenDrain); } #endif #if defined(I2C3_BASE) if ((obj->i2c == I2C_3) && !i2c3_inited) { i2c3_inited = 1; __HAL_RCC_I2C3_CONFIG(RCC_I2C3CLKSOURCE_PCLK1); __HAL_RCC_I2C3_CLK_ENABLE(); // Configure I2C3 pins pinmap_pinout(sda, PinMap_I2C_SDA); pinmap_pinout(scl, PinMap_I2C_SCL); pin_mode(sda, OpenDrain); pin_mode(scl, OpenDrain); } #endif #if defined(I2C4_BASE) if ((obj->i2c == I2C_4) && !i2c4_inited) { i2c4_inited = 1; __HAL_RCC_I2C4_CONFIG(RCC_I2C4CLKSOURCE_PCLK1); __HAL_RCC_I2C4_CLK_ENABLE(); // Configure I2C4 pins pinmap_pinout(sda, PinMap_I2C_SDA); pinmap_pinout(scl, PinMap_I2C_SCL); pin_mode(sda, OpenDrain); pin_mode(scl, OpenDrain); } #endif */ // Reset to clear pending flags if any i2c_reset(obj); // I2C configuration i2c_frequency(obj, 100000); // 100 kHz per default } void i2c_frequency(i2c_t *obj, int hz) { uint32_t tim = 0; MBED_ASSERT((hz == 100000) || (hz == 400000) || (hz == 1000000)); I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); int timeout; // wait before init timeout = LONG_TIMEOUT; while ((__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY)) && (timeout-- != 0)) {} /* Values calculated with I2C_Timing_Configuration tool (excel file) * Standard mode (up to 100 kHz) * Fast Mode (up to 400 kHz) * Fast Mode Plus (up to 1 MHz) Below values obtained with: - I2Cx clock source = APB1CLK = 54 MHz - Analog filter delay = ON - Digital filter coefficient = 0 */ switch (hz) { case 100000: tim = 0x10916998; // Standard mode with Rise time = 120ns, Fall time = 120ns break; case 400000: tim = 0x00B11B54; // Fast Mode with Rise time = 120ns, Fall time = 120ns break; case 1000000: tim = 0x0090091B; // Fast Mode Plus with Rise time = 120ns, Fall time = 10ns break; default: break; } // I2C configuration I2cHandle.Init.Timing = tim; I2cHandle.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; I2cHandle.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; I2cHandle.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; I2cHandle.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; I2cHandle.Init.OwnAddress1 = 0; I2cHandle.Init.OwnAddress2 = 0; I2cHandle.Init.OwnAddress2Masks = I2C_OA2_NOMASK; if (HAL_I2C_Init(&I2cHandle) != HAL_OK) { error("Cannot initialize I2C"); } } inline int i2c_start(i2c_t *obj) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); int timeout; I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); // Clear Acknowledge failure flag __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_AF); // Generate the START condition i2c->CR2 |= I2C_CR2_START; // Wait the START condition has been correctly sent timeout = FLAG_TIMEOUT; while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY) == RESET) { if ((timeout--) == 0) { return 1; } } return 0; } inline int i2c_stop(i2c_t *obj) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); // Generate the STOP condition i2c->CR2 |= I2C_CR2_STOP; return 0; } int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); int timeout; int count; int value; /* update CR2 register */ i2c->CR2 = (i2c->CR2 & (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP))) | (uint32_t)(((uint32_t)address & I2C_CR2_SADD) | (((uint32_t)length << 16) & I2C_CR2_NBYTES) | (uint32_t)I2C_SOFTEND_MODE | (uint32_t)I2C_GENERATE_START_READ); // Read all bytes for (count = 0; count < length; count++) { value = i2c_byte_read(obj, 0); data[count] = (char)value; } // Wait transfer complete timeout = LONG_TIMEOUT; while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TC) == RESET) { timeout--; if (timeout == 0) { return -1; } } __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_TC); // If not repeated start, send stop. if (stop) { i2c_stop(obj); /* Wait until STOPF flag is set */ timeout = FLAG_TIMEOUT; while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_STOPF) == RESET) { timeout--; if (timeout == 0) { return -1; } } /* Clear STOP Flag */ __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_STOPF); } return length; } int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); int timeout; int count; /* update CR2 register */ i2c->CR2 = (i2c->CR2 & (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP))) | (uint32_t)(((uint32_t)address & I2C_CR2_SADD) | (((uint32_t)length << 16) & I2C_CR2_NBYTES) | (uint32_t)I2C_SOFTEND_MODE | (uint32_t)I2C_GENERATE_START_WRITE); for (count = 0; count < length; count++) { i2c_byte_write(obj, data[count]); } // Wait transfer complete timeout = FLAG_TIMEOUT; while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TC) == RESET) { timeout--; if (timeout == 0) { return -1; } } __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_TC); // If not repeated start, send stop. if (stop) { i2c_stop(obj); /* Wait until STOPF flag is set */ timeout = FLAG_TIMEOUT; while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_STOPF) == RESET) { timeout--; if (timeout == 0) { return -1; } } /* Clear STOP Flag */ __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_STOPF); } return count; } int i2c_byte_read(i2c_t *obj, int last) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); int timeout; // Wait until the byte is received timeout = FLAG_TIMEOUT; while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_RXNE) == RESET) { if ((timeout--) == 0) { return -1; } } return (int)i2c->RXDR; } int i2c_byte_write(i2c_t *obj, int data) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); int timeout; // Wait until the previous byte is transmitted timeout = FLAG_TIMEOUT; while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TXIS) == RESET) { if ((timeout--) == 0) { return 0; } } i2c->TXDR = (uint8_t)data; return 1; } void i2c_reset(i2c_t *obj) { int timeout; // wait before reset timeout = LONG_TIMEOUT; while ((__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY)) && (timeout-- != 0)); __I2C1_FORCE_RESET(); __I2C1_RELEASE_RESET(); } #if DEVICE_I2CSLAVE void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); uint16_t tmpreg; // disable i2c->OAR1 &= (uint32_t)(~I2C_OAR1_OA1EN); // Get the old register value tmpreg = i2c->OAR1; // Reset address bits tmpreg &= 0xFC00; // Set new address tmpreg |= (uint16_t)((uint16_t)address & (uint16_t)0x00FE); // 7-bits // Store the new register value i2c->OAR1 = tmpreg; // enable i2c->OAR1 |= I2C_OAR1_OA1EN; } void i2c_slave_mode(i2c_t *obj, int enable_slave) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); uint16_t tmpreg; // Get the old register value tmpreg = i2c->OAR1; // Enable / disable slave if (enable_slave == 1) { tmpreg |= I2C_OAR1_OA1EN; } else { tmpreg &= (uint32_t)(~I2C_OAR1_OA1EN); } // Set new mode i2c->OAR1 = tmpreg; } // See I2CSlave.h #define NoData 0 // the slave has not been addressed #define ReadAddressed 1 // the master has requested a read from this slave (slave = transmitter) #define WriteGeneral 2 // the master is writing to all slave #define WriteAddressed 3 // the master is writing to this slave (slave = receiver) int i2c_slave_receive(i2c_t *obj) { I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); int retValue = NoData; if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY) == 1) { if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_ADDR) == 1) { if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_DIR) == 1) retValue = ReadAddressed; else retValue = WriteAddressed; __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_ADDR); } } return (retValue); } int i2c_slave_read(i2c_t *obj, char *data, int length) { char size = 0; while (size < length) data[size++] = (char)i2c_byte_read(obj, 0); return size; } int i2c_slave_write(i2c_t *obj, const char *data, int length) { char size = 0; I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); do { i2c_byte_write(obj, data[size]); size++; } while (size < length); return size; } #endif // DEVICE_I2CSLAVE #endif // DEVICE_I2C
apache-2.0
BartokW/sagetv
third_party/mplayer/get_path.c
32
4101
/* * Get path to config dir/file. * * Return Values: * Returns the pointer to the ALLOCATED buffer containing the * zero terminated path string. This buffer has to be FREED * by the caller. * */ #ifdef MACOSX_BUNDLE #include <CoreFoundation/CoreFoundation.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #endif char *get_path(const char *filename){ char *homedir; char *buff; #if defined(__MINGW32__) static char *config_dir = "/mplayer"; #else static char *config_dir = "/.mplayer"; #endif int len; #ifdef MACOSX_BUNDLE struct stat dummy; CFIndex maxlen=256; CFURLRef res_url_ref=NULL; CFURLRef bdl_url_ref=NULL; char *res_url_path = NULL; char *bdl_url_path = NULL; #endif if ((homedir = getenv("MPLAYER_HOME")) != NULL) config_dir = ""; else if ((homedir = getenv("HOME")) == NULL) #if defined(__MINGW32__)||defined(__CYGWIN__) /*hack to get fonts etc. loaded outside of cygwin environment*/ { int i,imax=0; char exedir[260]; GetModuleFileNameA(NULL, exedir, 260); for(i=0; i< strlen(exedir);i++)if(exedir[i] =='\\'){exedir[i]='/';imax=i;} exedir[imax]='\0'; homedir = exedir; } #else return NULL; #endif len = strlen(homedir) + strlen(config_dir) + 1; if (filename == NULL) { if ((buff = (char *) malloc(len)) == NULL) return NULL; sprintf(buff, "%s%s", homedir, config_dir); } else { len += strlen(filename) + 1; if ((buff = (char *) malloc(len)) == NULL) return NULL; sprintf(buff, "%s%s/%s", homedir, config_dir, filename); } #ifdef MACOSX_BUNDLE if(stat(buff, &dummy)) { res_url_ref=CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle()); bdl_url_ref=CFBundleCopyBundleURL(CFBundleGetMainBundle()); if(res_url_ref&&bdl_url_ref) { res_url_path=malloc(maxlen); bdl_url_path=malloc(maxlen); while(!CFURLGetFileSystemRepresentation(res_url_ref, true, res_url_path, maxlen)) { maxlen*=2; res_url_path=realloc(res_url_path, maxlen); } CFRelease(res_url_ref); while(!CFURLGetFileSystemRepresentation(bdl_url_ref, true, bdl_url_path, maxlen)) { maxlen*=2; bdl_url_path=realloc(bdl_url_path, maxlen); } CFRelease(bdl_url_ref); if( strcmp(res_url_path, bdl_url_path) == 0) res_url_path = NULL; } if(res_url_path&&filename) { if((strlen(filename)+strlen(res_url_path)+2)>maxlen) { maxlen=strlen(filename)+strlen(res_url_path)+2; } free(buff); buff = (char *) malloc(maxlen); strcpy(buff, res_url_path); strcat(buff,"/"); strcat(buff, filename); } } #endif mp_msg(MSGT_GLOBAL,MSGL_V,"get_path('%s') -> '%s'\n",filename,buff); return buff; } #if defined(WIN32) && defined(USE_WIN32DLL) void set_path_env() { /*make our codec dirs available for LoadLibraryA()*/ char tmppath[MAX_PATH*2 + 1]; char win32path[MAX_PATH]; char realpath[MAX_PATH]; #ifdef __CYGWIN__ cygwin_conv_to_full_win32_path(WIN32_PATH,win32path); strcpy(tmppath,win32path); #ifdef USE_REALCODECS cygwin_conv_to_full_win32_path(REALCODEC_PATH,realpath); sprintf(tmppath,"%s;%s",win32path,realpath); #endif /*USE_REALCODECS*/ #else /*__CYGWIN__*/ /* Expand to absolute path unless it's already absolute */ if(!strstr(WIN32_PATH,":") && WIN32_PATH[0] != '\\'){ GetModuleFileNameA(NULL, win32path, MAX_PATH); strcpy(strrchr(win32path, '\\') + 1, WIN32_PATH); } else strcpy(win32path,WIN32_PATH); strcpy(tmppath,win32path); #ifdef USE_REALCODECS /* Expand to absolute path unless it's already absolute */ if(!strstr(REALCODEC_PATH,":") && REALCODEC_PATH[0] != '\\'){ GetModuleFileNameA(NULL, realpath, MAX_PATH); strcpy(strrchr(realpath, '\\') + 1, REALCODEC_PATH); } else strcpy(realpath,REALCODEC_PATH); sprintf(tmppath,"%s;%s",win32path,realpath); #endif /*USE_REALCODECS*/ #endif /*__CYGWIN__*/ mp_msg(MSGT_WIN32, MSGL_V,"Setting PATH to %s\n",tmppath); if (!SetEnvironmentVariableA("PATH", tmppath)) mp_msg(MSGT_WIN32, MSGL_WARN, "Cannot set PATH!"); } #endif /*WIN32 && USE_WIN32DLL*/
apache-2.0
ckewinjones/sagetv
third_party/mplayer/libmpdemux/demux_rtp_codec.cpp
32
15757
////////// Codec-specific routines used to interface between "MPlayer" ////////// and the "LIVE555 Streaming Media" libraries: #include "demux_rtp_internal.h" extern "C" { #include <limits.h> #include <math.h> #include "stheader.h" #include "base64.h" } #ifdef USE_LIBAVCODEC AVCodecParserContext * h264parserctx; #endif // Copied from vlc static unsigned char* parseH264ConfigStr( char const* configStr, unsigned int& configSize ) { char *dup, *psz; int i, i_records = 1; if( configSize ) configSize = 0; if( configStr == NULL || *configStr == '\0' ) return NULL; psz = dup = strdup( configStr ); /* Count the number of comma's */ for( psz = dup; *psz != '\0'; ++psz ) { if( *psz == ',') { ++i_records; *psz = '\0'; } } unsigned char *cfg = new unsigned char[5 * strlen(dup)]; psz = dup; for( i = 0; i < i_records; i++ ) { cfg[configSize++] = 0x00; cfg[configSize++] = 0x00; cfg[configSize++] = 0x01; configSize += av_base64_decode( (uint8_t*)&cfg[configSize], psz, 5 * strlen(dup) - 3 ); psz += strlen(psz)+1; } if( dup ) free( dup ); return cfg; } static void needVideoFrameRate(demuxer_t* demuxer, MediaSubsession* subsession); // forward static Boolean parseQTState_video(QuickTimeGenericRTPSource::QTState const& qtState, unsigned& fourcc); // forward static Boolean parseQTState_audio(QuickTimeGenericRTPSource::QTState const& qtState, unsigned& fourcc, unsigned& numChannels); // forward static BITMAPINFOHEADER * insertVideoExtradata(BITMAPINFOHEADER *bih, unsigned char * extraData, unsigned size) { BITMAPINFOHEADER * original = bih; if (!size || size > INT_MAX - sizeof(BITMAPINFOHEADER)) return bih; bih = (BITMAPINFOHEADER*)realloc(bih, sizeof(BITMAPINFOHEADER) + size); if (!bih) return original; bih->biSize = sizeof(BITMAPINFOHEADER) + size; memcpy(bih+1, extraData, size); return bih; } void rtpCodecInitialize_video(demuxer_t* demuxer, MediaSubsession* subsession, unsigned& flags) { flags = 0; // Create a dummy video stream header // to make the main MPlayer code happy: sh_video_t* sh_video = new_sh_video(demuxer,0); BITMAPINFOHEADER* bih = (BITMAPINFOHEADER*)calloc(1,sizeof(BITMAPINFOHEADER)); bih->biSize = sizeof(BITMAPINFOHEADER); sh_video->bih = bih; demux_stream_t* d_video = demuxer->video; d_video->sh = sh_video; sh_video->ds = d_video; // Map known video MIME types to the BITMAPINFOHEADER parameters // that this program uses. (Note that not all types need all // of the parameters to be set.) if (strcmp(subsession->codecName(), "MPV") == 0) { flags |= RTPSTATE_IS_MPEG12_VIDEO; } else if (strcmp(subsession->codecName(), "MP1S") == 0 || strcmp(subsession->codecName(), "MP2T") == 0) { flags |= RTPSTATE_IS_MPEG12_VIDEO|RTPSTATE_IS_MULTIPLEXED; } else if (strcmp(subsession->codecName(), "H263") == 0 || strcmp(subsession->codecName(), "H263-2000") == 0 || strcmp(subsession->codecName(), "H263-1998") == 0) { bih->biCompression = sh_video->format = mmioFOURCC('H','2','6','3'); needVideoFrameRate(demuxer, subsession); } else if (strcmp(subsession->codecName(), "H264") == 0) { bih->biCompression = sh_video->format = mmioFOURCC('H','2','6','4'); unsigned int configLen = 0; unsigned char* configData = parseH264ConfigStr(subsession->fmtp_spropparametersets(), configLen); sh_video->bih = bih = insertVideoExtradata(bih, configData, configLen); delete[] configData; #ifdef USE_LIBAVCODEC av_register_codec_parser(&h264_parser); h264parserctx = av_parser_init(CODEC_ID_H264); #endif needVideoFrameRate(demuxer, subsession); } else if (strcmp(subsession->codecName(), "H261") == 0) { bih->biCompression = sh_video->format = mmioFOURCC('H','2','6','1'); needVideoFrameRate(demuxer, subsession); } else if (strcmp(subsession->codecName(), "JPEG") == 0) { bih->biCompression = sh_video->format = mmioFOURCC('M','J','P','G'); needVideoFrameRate(demuxer, subsession); } else if (strcmp(subsession->codecName(), "MP4V-ES") == 0) { bih->biCompression = sh_video->format = mmioFOURCC('m','p','4','v'); // For the codec to work correctly, it may need a 'VOL Header' to be // inserted at the front of the data stream. Construct this from the // "config" MIME parameter, which was present (hopefully) in the // session's SDP description: unsigned configLen; unsigned char* configData = parseGeneralConfigStr(subsession->fmtp_config(), configLen); sh_video->bih = bih = insertVideoExtradata(bih, configData, configLen); needVideoFrameRate(demuxer, subsession); } else if (strcmp(subsession->codecName(), "X-QT") == 0 || strcmp(subsession->codecName(), "X-QUICKTIME") == 0) { // QuickTime generic RTP format, as described in // http://developer.apple.com/quicktime/icefloe/dispatch026.html // We can't initialize this stream until we've received the first packet // that has QuickTime "sdAtom" information in the header. So, keep // reading packets until we get one: unsigned char* packetData; unsigned packetDataLen; float pts; QuickTimeGenericRTPSource* qtRTPSource = (QuickTimeGenericRTPSource*)(subsession->rtpSource()); unsigned fourcc; do { if (!awaitRTPPacket(demuxer, demuxer->video, packetData, packetDataLen, pts)) { return; } } while (!parseQTState_video(qtRTPSource->qtState, fourcc)); bih->biCompression = sh_video->format = fourcc; bih->biWidth = qtRTPSource->qtState.width; bih->biHeight = qtRTPSource->qtState.height; uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86; uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom + qtRTPSource->qtState.sdAtomSize; while (pos+8 < endpos) { unsigned atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3]; if (atomLength == 0 || atomLength > endpos-pos) break; if ((!memcmp(pos+4, "avcC", 4) && fourcc==mmioFOURCC('a','v','c','1') || !memcmp(pos+4, "esds", 4) || !memcmp(pos+4, "SMI ", 4) && fourcc==mmioFOURCC('S','V','Q','3')) && atomLength > 8) { sh_video->bih = bih = insertVideoExtradata(bih, pos+8, atomLength-8); break; } pos += atomLength; } needVideoFrameRate(demuxer, subsession); } else { fprintf(stderr, "Unknown MPlayer format code for MIME type \"video/%s\"\n", subsession->codecName()); } } void rtpCodecInitialize_audio(demuxer_t* demuxer, MediaSubsession* subsession, unsigned& flags) { flags = 0; // Create a dummy audio stream header // to make the main MPlayer code happy: sh_audio_t* sh_audio = new_sh_audio(demuxer,0); WAVEFORMATEX* wf = (WAVEFORMATEX*)calloc(1,sizeof(WAVEFORMATEX)); sh_audio->wf = wf; demux_stream_t* d_audio = demuxer->audio; d_audio->sh = sh_audio; sh_audio->ds = d_audio; wf->nChannels = subsession->numChannels(); // Map known audio MIME types to the WAVEFORMATEX parameters // that this program uses. (Note that not all types need all // of the parameters to be set.) wf->nSamplesPerSec = subsession->rtpSource()->timestampFrequency(); // by default if (strcmp(subsession->codecName(), "MPA") == 0 || strcmp(subsession->codecName(), "MPA-ROBUST") == 0 || strcmp(subsession->codecName(), "X-MP3-DRAFT-00") == 0) { wf->wFormatTag = sh_audio->format = 0x55; // Note: 0x55 is for layer III, but should work for I,II also wf->nSamplesPerSec = 0; // sample rate is deduced from the data } else if (strcmp(subsession->codecName(), "AC3") == 0) { wf->wFormatTag = sh_audio->format = 0x2000; wf->nSamplesPerSec = 0; // sample rate is deduced from the data } else if (strcmp(subsession->codecName(), "L16") == 0) { wf->wFormatTag = sh_audio->format = 0x736f7774; // "twos" wf->nBlockAlign = 1; wf->wBitsPerSample = 16; wf->cbSize = 0; } else if (strcmp(subsession->codecName(), "L8") == 0) { wf->wFormatTag = sh_audio->format = 0x20776172; // "raw " wf->nBlockAlign = 1; wf->wBitsPerSample = 8; wf->cbSize = 0; } else if (strcmp(subsession->codecName(), "PCMU") == 0) { wf->wFormatTag = sh_audio->format = 0x7; wf->nAvgBytesPerSec = 8000; wf->nBlockAlign = 1; wf->wBitsPerSample = 8; wf->cbSize = 0; } else if (strcmp(subsession->codecName(), "PCMA") == 0) { wf->wFormatTag = sh_audio->format = 0x6; wf->nAvgBytesPerSec = 8000; wf->nBlockAlign = 1; wf->wBitsPerSample = 8; wf->cbSize = 0; } else if (strcmp(subsession->codecName(), "AMR") == 0) { wf->wFormatTag = sh_audio->format = mmioFOURCC('s','a','m','r'); } else if (strcmp(subsession->codecName(), "AMR-WB") == 0) { wf->wFormatTag = sh_audio->format = mmioFOURCC('s','a','w','b'); } else if (strcmp(subsession->codecName(), "GSM") == 0) { wf->wFormatTag = sh_audio->format = mmioFOURCC('a','g','s','m'); wf->nAvgBytesPerSec = 1650; wf->nBlockAlign = 33; wf->wBitsPerSample = 16; wf->cbSize = 0; } else if (strcmp(subsession->codecName(), "QCELP") == 0) { wf->wFormatTag = sh_audio->format = mmioFOURCC('Q','c','l','p'); wf->nAvgBytesPerSec = 1750; wf->nBlockAlign = 35; wf->wBitsPerSample = 16; wf->cbSize = 0; } else if (strcmp(subsession->codecName(), "MP4A-LATM") == 0) { wf->wFormatTag = sh_audio->format = mmioFOURCC('m','p','4','a'); // For the codec to work correctly, it needs "AudioSpecificConfig" // data, which is parsed from the "StreamMuxConfig" string that // was present (hopefully) in the SDP description: unsigned codecdata_len; sh_audio->codecdata = parseStreamMuxConfigStr(subsession->fmtp_config(), codecdata_len); sh_audio->codecdata_len = codecdata_len; //faad doesn't understand LATM's data length field, so omit it ((MPEG4LATMAudioRTPSource*)subsession->rtpSource())->omitLATMDataLengthField(); } else if (strcmp(subsession->codecName(), "MPEG4-GENERIC") == 0) { wf->wFormatTag = sh_audio->format = mmioFOURCC('m','p','4','a'); // For the codec to work correctly, it needs "AudioSpecificConfig" // data, which was present (hopefully) in the SDP description: unsigned codecdata_len; sh_audio->codecdata = parseGeneralConfigStr(subsession->fmtp_config(), codecdata_len); sh_audio->codecdata_len = codecdata_len; } else if (strcmp(subsession->codecName(), "X-QT") == 0 || strcmp(subsession->codecName(), "X-QUICKTIME") == 0) { // QuickTime generic RTP format, as described in // http://developer.apple.com/quicktime/icefloe/dispatch026.html // We can't initialize this stream until we've received the first packet // that has QuickTime "sdAtom" information in the header. So, keep // reading packets until we get one: unsigned char* packetData; unsigned packetDataLen; float pts; QuickTimeGenericRTPSource* qtRTPSource = (QuickTimeGenericRTPSource*)(subsession->rtpSource()); unsigned fourcc, numChannels; do { if (!awaitRTPPacket(demuxer, demuxer->audio, packetData, packetDataLen, pts)) { return; } } while (!parseQTState_audio(qtRTPSource->qtState, fourcc, numChannels)); wf->wFormatTag = sh_audio->format = fourcc; wf->nChannels = numChannels; uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 52; uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom + qtRTPSource->qtState.sdAtomSize; while (pos+8 < endpos) { unsigned atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3]; if (atomLength == 0 || atomLength > endpos-pos) break; if (!memcmp(pos+4, "wave", 4) && fourcc==mmioFOURCC('Q','D','M','2') && atomLength > 8 && atomLength <= INT_MAX) { sh_audio->codecdata = (unsigned char*) malloc(atomLength-8); if (sh_audio->codecdata) { memcpy(sh_audio->codecdata, pos+8, atomLength-8); sh_audio->codecdata_len = atomLength-8; } break; } pos += atomLength; } } else { fprintf(stderr, "Unknown MPlayer format code for MIME type \"audio/%s\"\n", subsession->codecName()); } } static void needVideoFrameRate(demuxer_t* demuxer, MediaSubsession* subsession) { // For some codecs, MPlayer's decoding software can't (or refuses to :-) // figure out the frame rate by itself, so (unless the user specifies // it manually, using "-fps") we figure it out ourselves here, using the // presentation timestamps in successive packets, extern float force_fps; if (force_fps != 0.0) return; // user used "-fps" demux_stream_t* d_video = demuxer->video; sh_video_t* sh_video = (sh_video_t*)(d_video->sh); // If we already know the subsession's video frame rate, use it: int fps = (int)(subsession->videoFPS()); if (fps != 0) { sh_video->fps = fps; sh_video->frametime = 1.0f/fps; return; } // Keep looking at incoming frames until we see two with different, // non-zero "pts" timestamps: unsigned char* packetData; unsigned packetDataLen; float lastPTS = 0.0, curPTS; unsigned const maxNumFramesToWaitFor = 300; int lastfps = 0; for (unsigned i = 0; i < maxNumFramesToWaitFor; ++i) { if (!awaitRTPPacket(demuxer, d_video, packetData, packetDataLen, curPTS)) { break; } if (curPTS != lastPTS && lastPTS != 0.0) { // Use the difference between these two "pts"s to guess the frame rate. // (should really check that there were no missing frames inbetween)##### // Guess the frame rate as an integer. If it's not, use "-fps" instead. fps = (int)(1/fabs(curPTS-lastPTS) + 0.5); // rounding if (fps == lastfps) { fprintf(stderr, "demux_rtp: Guessed the video frame rate as %d frames-per-second.\n\t(If this is wrong, use the \"-fps <frame-rate>\" option instead.)\n", fps); sh_video->fps = fps; sh_video->frametime=1.0f/fps; return; } if (fps>lastfps) lastfps = fps; } lastPTS = curPTS; } fprintf(stderr, "demux_rtp: Failed to guess the video frame rate\n"); } static Boolean parseQTState_video(QuickTimeGenericRTPSource::QTState const& qtState, unsigned& fourcc) { // qtState's "sdAtom" field is supposed to contain a QuickTime video // 'sample description' atom. This atom's name is the 'fourcc' that we want: char const* sdAtom = qtState.sdAtom; if (sdAtom == NULL || qtState.sdAtomSize < 2*4) return False; fourcc = *(unsigned*)(&sdAtom[4]); // put in host order return True; } static Boolean parseQTState_audio(QuickTimeGenericRTPSource::QTState const& qtState, unsigned& fourcc, unsigned& numChannels) { // qtState's "sdAtom" field is supposed to contain a QuickTime audio // 'sample description' atom. This atom's name is the 'fourcc' that we want. // Also, the top half of the 5th word following the atom name should // contain the number of channels ("numChannels") that we want: char const* sdAtom = qtState.sdAtom; if (sdAtom == NULL || qtState.sdAtomSize < 7*4) return False; fourcc = *(unsigned*)(&sdAtom[4]); // put in host order char const* word7Ptr = &sdAtom[6*4]; numChannels = (word7Ptr[0]<<8)|(word7Ptr[1]); return True; }
apache-2.0
lightcyphers/otp
erts/etc/win32/port_entry.c
34
2282
/* * %CopyrightBegin% * * Copyright Ericsson AB 1998-2016. 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. * * %CopyrightEnd% */ /* ** This is an entry point for port programs, ** it is used to set the console control handler of the process when ** erlang process is run as a service. ** Note that this entry point is only for ** Console programs, Windowing programs can just route the WM_QUERYENDSESSION ** and WM_ENDSESSION to the default window procedure to aquire the same ** functionality. ** ** Creator Patrik Nyblom ** ** Notes: ** You would really not want to use ANY of the standard library in this ** routine, the standard library is not yet initiated... */ #include <windows.h> /* ** The runtime libraries startup routine in the Microsoft Visual C CRT */ extern void mainCRTStartup(void); /* ** A Console control handler that ignores the logoff events, ** and lets the default handler take care of other events. */ BOOL WINAPI erl_port_default_handler(DWORD ctrl){ if(ctrl == CTRL_LOGOFF_EVENT) return TRUE; if(ctrl == CTRL_SHUTDOWN_EVENT) return TRUE; return FALSE; } /* ** This is the entry point, it takes no parameters and never returns. */ void erl_port_entry(void){ char buffer[2]; /* * We assume we're running as a service if this environment variable * is defined */ if(GetEnvironmentVariable("ERLSRV_SERVICE_NAME",buffer,(DWORD) 2)){ #ifdef HARDDEBUG DWORD dummy; WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), "Setting handler\r\n",17,&dummy, NULL); #endif /* HARDDEBUG */ /* ** Actually set the control handler */ SetConsoleCtrlHandler(&erl_port_default_handler, TRUE); } /* ** Call the CRT's real startup routine. */ mainCRTStartup(); }
apache-2.0
Vizerai/grpc
src/ruby/ext/grpc/rb_channel_args.c
35
5077
/* * * Copyright 2015 gRPC 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. * */ #include <ruby/ruby.h> #include "rb_channel_args.h" #include "rb_grpc_imports.generated.h" #include <grpc/grpc.h> #include "rb_grpc.h" static rb_data_type_t grpc_rb_channel_args_data_type = { "grpc_channel_args", {GRPC_RB_GC_NOT_MARKED, GRPC_RB_GC_DONT_FREE, GRPC_RB_MEMSIZE_UNAVAILABLE, {NULL, NULL}}, NULL, NULL, #ifdef RUBY_TYPED_FREE_IMMEDIATELY RUBY_TYPED_FREE_IMMEDIATELY #endif }; /* A callback the processes the hash key values in channel_args hash */ static int grpc_rb_channel_create_in_process_add_args_hash_cb(VALUE key, VALUE val, VALUE args_obj) { const char* the_key; grpc_channel_args* args; switch (TYPE(key)) { case T_STRING: the_key = StringValuePtr(key); break; case T_SYMBOL: the_key = rb_id2name(SYM2ID(key)); break; default: rb_raise(rb_eTypeError, "bad chan arg: got <%s>, want <String|Symbol>", rb_obj_classname(key)); return ST_STOP; } TypedData_Get_Struct(args_obj, grpc_channel_args, &grpc_rb_channel_args_data_type, args); if (args->num_args <= 0) { rb_raise(rb_eRuntimeError, "hash_cb bug: num_args is %lu for key:%s", args->num_args, StringValueCStr(key)); return ST_STOP; } args->args[args->num_args - 1].key = (char*)the_key; switch (TYPE(val)) { case T_SYMBOL: args->args[args->num_args - 1].type = GRPC_ARG_STRING; args->args[args->num_args - 1].value.string = (char*)rb_id2name(SYM2ID(val)); --args->num_args; return ST_CONTINUE; case T_STRING: args->args[args->num_args - 1].type = GRPC_ARG_STRING; args->args[args->num_args - 1].value.string = StringValueCStr(val); --args->num_args; return ST_CONTINUE; case T_FIXNUM: args->args[args->num_args - 1].type = GRPC_ARG_INTEGER; args->args[args->num_args - 1].value.integer = NUM2INT(val); --args->num_args; return ST_CONTINUE; default: rb_raise(rb_eTypeError, "%s: bad value: got <%s>, want <String|Fixnum>", StringValueCStr(key), rb_obj_classname(val)); return ST_STOP; } rb_raise(rb_eRuntimeError, "impl bug: hash_cb reached to far while on key:%s", StringValueCStr(key)); return ST_STOP; } /* channel_convert_params allows the call to grpc_rb_hash_convert_to_channel_args to be made within an rb_protect exception-handler. This allows any allocated memory to be freed before propagating any exception that occurs */ typedef struct channel_convert_params { VALUE src_hash; grpc_channel_args* dst; } channel_convert_params; static VALUE grpc_rb_hash_convert_to_channel_args0(VALUE as_value) { ID id_size = rb_intern("size"); VALUE grpc_rb_cChannelArgs = rb_define_class("TmpChannelArgs", rb_cObject); channel_convert_params* params = (channel_convert_params*)as_value; size_t num_args = 0; if (!NIL_P(params->src_hash) && TYPE(params->src_hash) != T_HASH) { rb_raise(rb_eTypeError, "bad channel args: got:<%s> want: a hash or nil", rb_obj_classname(params->src_hash)); return Qnil; } if (TYPE(params->src_hash) == T_HASH) { num_args = NUM2INT(rb_funcall(params->src_hash, id_size, 0)); params->dst->num_args = num_args; params->dst->args = ALLOC_N(grpc_arg, num_args); MEMZERO(params->dst->args, grpc_arg, num_args); rb_hash_foreach( params->src_hash, grpc_rb_channel_create_in_process_add_args_hash_cb, TypedData_Wrap_Struct(grpc_rb_cChannelArgs, &grpc_rb_channel_args_data_type, params->dst)); /* reset num_args as grpc_rb_channel_create_in_process_add_args_hash_cb * decrements it during has processing */ params->dst->num_args = num_args; } return Qnil; } void grpc_rb_hash_convert_to_channel_args(VALUE src_hash, grpc_channel_args* dst) { channel_convert_params params; int status = 0; /* Make a protected call to grpc_rb_hash_convert_channel_args */ params.src_hash = src_hash; params.dst = dst; rb_protect(grpc_rb_hash_convert_to_channel_args0, (VALUE)&params, &status); if (status != 0) { if (dst->args != NULL) { /* Free any allocated memory before propagating the error */ xfree(dst->args); } rb_jump_tag(status); } }
apache-2.0
llvm-mirror/compiler-rt
lib/sanitizer_common/sanitizer_coverage_win_dll_thunk.cpp
35
1055
//===-- sanitizer_coverage_win_dll_thunk.cpp ------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines a family of thunks that should be statically linked into // the DLLs that have instrumentation in order to delegate the calls to the // shared runtime that lives in the main binary. // See https://github.com/google/sanitizers/issues/209 for the details. //===----------------------------------------------------------------------===// #ifdef SANITIZER_DLL_THUNK #include "sanitizer_win_dll_thunk.h" // Sanitizer Coverage interface functions. #define INTERFACE_FUNCTION(Name) INTERCEPT_SANITIZER_FUNCTION(Name) #define INTERFACE_WEAK_FUNCTION(Name) INTERCEPT_SANITIZER_WEAK_FUNCTION(Name) #include "sanitizer_coverage_interface.inc" #endif // SANITIZER_DLL_THUNK
apache-2.0
TeamVee-Kanas/android_kernel_samsung_kanas
sound/soc/davinci/davinci-i2s.c
2598
23796
/* * ALSA SoC I2S (McBSP) Audio Layer for TI DAVINCI processor * * Author: Vladimir Barinov, <vbarinov@embeddedalley.com> * Copyright: (C) 2007 MontaVista Software, Inc., <source@mvista.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/clk.h> #include <linux/platform_data/davinci_asp.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/initval.h> #include <sound/soc.h> #include "davinci-pcm.h" #include "davinci-i2s.h" /* * NOTE: terminology here is confusing. * * - This driver supports the "Audio Serial Port" (ASP), * found on dm6446, dm355, and other DaVinci chips. * * - But it labels it a "Multi-channel Buffered Serial Port" * (McBSP) as on older chips like the dm642 ... which was * backward-compatible, possibly explaining that confusion. * * - OMAP chips have a controller called McBSP, which is * incompatible with the DaVinci flavor of McBSP. * * - Newer DaVinci chips have a controller called McASP, * incompatible with ASP and with either McBSP. * * In short: this uses ASP to implement I2S, not McBSP. * And it won't be the only DaVinci implemention of I2S. */ #define DAVINCI_MCBSP_DRR_REG 0x00 #define DAVINCI_MCBSP_DXR_REG 0x04 #define DAVINCI_MCBSP_SPCR_REG 0x08 #define DAVINCI_MCBSP_RCR_REG 0x0c #define DAVINCI_MCBSP_XCR_REG 0x10 #define DAVINCI_MCBSP_SRGR_REG 0x14 #define DAVINCI_MCBSP_PCR_REG 0x24 #define DAVINCI_MCBSP_SPCR_RRST (1 << 0) #define DAVINCI_MCBSP_SPCR_RINTM(v) ((v) << 4) #define DAVINCI_MCBSP_SPCR_XRST (1 << 16) #define DAVINCI_MCBSP_SPCR_XINTM(v) ((v) << 20) #define DAVINCI_MCBSP_SPCR_GRST (1 << 22) #define DAVINCI_MCBSP_SPCR_FRST (1 << 23) #define DAVINCI_MCBSP_SPCR_FREE (1 << 25) #define DAVINCI_MCBSP_RCR_RWDLEN1(v) ((v) << 5) #define DAVINCI_MCBSP_RCR_RFRLEN1(v) ((v) << 8) #define DAVINCI_MCBSP_RCR_RDATDLY(v) ((v) << 16) #define DAVINCI_MCBSP_RCR_RFIG (1 << 18) #define DAVINCI_MCBSP_RCR_RWDLEN2(v) ((v) << 21) #define DAVINCI_MCBSP_RCR_RFRLEN2(v) ((v) << 24) #define DAVINCI_MCBSP_RCR_RPHASE BIT(31) #define DAVINCI_MCBSP_XCR_XWDLEN1(v) ((v) << 5) #define DAVINCI_MCBSP_XCR_XFRLEN1(v) ((v) << 8) #define DAVINCI_MCBSP_XCR_XDATDLY(v) ((v) << 16) #define DAVINCI_MCBSP_XCR_XFIG (1 << 18) #define DAVINCI_MCBSP_XCR_XWDLEN2(v) ((v) << 21) #define DAVINCI_MCBSP_XCR_XFRLEN2(v) ((v) << 24) #define DAVINCI_MCBSP_XCR_XPHASE BIT(31) #define DAVINCI_MCBSP_SRGR_FWID(v) ((v) << 8) #define DAVINCI_MCBSP_SRGR_FPER(v) ((v) << 16) #define DAVINCI_MCBSP_SRGR_FSGM (1 << 28) #define DAVINCI_MCBSP_SRGR_CLKSM BIT(29) #define DAVINCI_MCBSP_PCR_CLKRP (1 << 0) #define DAVINCI_MCBSP_PCR_CLKXP (1 << 1) #define DAVINCI_MCBSP_PCR_FSRP (1 << 2) #define DAVINCI_MCBSP_PCR_FSXP (1 << 3) #define DAVINCI_MCBSP_PCR_SCLKME (1 << 7) #define DAVINCI_MCBSP_PCR_CLKRM (1 << 8) #define DAVINCI_MCBSP_PCR_CLKXM (1 << 9) #define DAVINCI_MCBSP_PCR_FSRM (1 << 10) #define DAVINCI_MCBSP_PCR_FSXM (1 << 11) enum { DAVINCI_MCBSP_WORD_8 = 0, DAVINCI_MCBSP_WORD_12, DAVINCI_MCBSP_WORD_16, DAVINCI_MCBSP_WORD_20, DAVINCI_MCBSP_WORD_24, DAVINCI_MCBSP_WORD_32, }; static const unsigned char data_type[SNDRV_PCM_FORMAT_S32_LE + 1] = { [SNDRV_PCM_FORMAT_S8] = 1, [SNDRV_PCM_FORMAT_S16_LE] = 2, [SNDRV_PCM_FORMAT_S32_LE] = 4, }; static const unsigned char asp_word_length[SNDRV_PCM_FORMAT_S32_LE + 1] = { [SNDRV_PCM_FORMAT_S8] = DAVINCI_MCBSP_WORD_8, [SNDRV_PCM_FORMAT_S16_LE] = DAVINCI_MCBSP_WORD_16, [SNDRV_PCM_FORMAT_S32_LE] = DAVINCI_MCBSP_WORD_32, }; static const unsigned char double_fmt[SNDRV_PCM_FORMAT_S32_LE + 1] = { [SNDRV_PCM_FORMAT_S8] = SNDRV_PCM_FORMAT_S16_LE, [SNDRV_PCM_FORMAT_S16_LE] = SNDRV_PCM_FORMAT_S32_LE, }; struct davinci_mcbsp_dev { struct device *dev; struct davinci_pcm_dma_params dma_params[2]; void __iomem *base; #define MOD_DSP_A 0 #define MOD_DSP_B 1 int mode; u32 pcr; struct clk *clk; /* * Combining both channels into 1 element will at least double the * amount of time between servicing the dma channel, increase * effiency, and reduce the chance of overrun/underrun. But, * it will result in the left & right channels being swapped. * * If relabeling the left and right channels is not possible, * you may want to let the codec know to swap them back. * * It may allow x10 the amount of time to service dma requests, * if the codec is master and is using an unnecessarily fast bit clock * (ie. tlvaic23b), independent of the sample rate. So, having an * entire frame at once means it can be serviced at the sample rate * instead of the bit clock rate. * * In the now unlikely case that an underrun still * occurs, both the left and right samples will be repeated * so that no pops are heard, and the left and right channels * won't end up being swapped because of the underrun. */ unsigned enable_channel_combine:1; unsigned int fmt; int clk_div; int clk_input_pin; bool i2s_accurate_sck; }; static inline void davinci_mcbsp_write_reg(struct davinci_mcbsp_dev *dev, int reg, u32 val) { __raw_writel(val, dev->base + reg); } static inline u32 davinci_mcbsp_read_reg(struct davinci_mcbsp_dev *dev, int reg) { return __raw_readl(dev->base + reg); } static void toggle_clock(struct davinci_mcbsp_dev *dev, int playback) { u32 m = playback ? DAVINCI_MCBSP_PCR_CLKXP : DAVINCI_MCBSP_PCR_CLKRP; /* The clock needs to toggle to complete reset. * So, fake it by toggling the clk polarity. */ davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_PCR_REG, dev->pcr ^ m); davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_PCR_REG, dev->pcr); } static void davinci_mcbsp_start(struct davinci_mcbsp_dev *dev, struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_platform *platform = rtd->platform; int playback = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK); u32 spcr; u32 mask = playback ? DAVINCI_MCBSP_SPCR_XRST : DAVINCI_MCBSP_SPCR_RRST; spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG); if (spcr & mask) { /* start off disabled */ davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr & ~mask); toggle_clock(dev, playback); } if (dev->pcr & (DAVINCI_MCBSP_PCR_FSXM | DAVINCI_MCBSP_PCR_FSRM | DAVINCI_MCBSP_PCR_CLKXM | DAVINCI_MCBSP_PCR_CLKRM)) { /* Start the sample generator */ spcr |= DAVINCI_MCBSP_SPCR_GRST; davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr); } if (playback) { /* Stop the DMA to avoid data loss */ /* while the transmitter is out of reset to handle XSYNCERR */ if (platform->driver->ops->trigger) { int ret = platform->driver->ops->trigger(substream, SNDRV_PCM_TRIGGER_STOP); if (ret < 0) printk(KERN_DEBUG "Playback DMA stop failed\n"); } /* Enable the transmitter */ spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG); spcr |= DAVINCI_MCBSP_SPCR_XRST; davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr); /* wait for any unexpected frame sync error to occur */ udelay(100); /* Disable the transmitter to clear any outstanding XSYNCERR */ spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG); spcr &= ~DAVINCI_MCBSP_SPCR_XRST; davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr); toggle_clock(dev, playback); /* Restart the DMA */ if (platform->driver->ops->trigger) { int ret = platform->driver->ops->trigger(substream, SNDRV_PCM_TRIGGER_START); if (ret < 0) printk(KERN_DEBUG "Playback DMA start failed\n"); } } /* Enable transmitter or receiver */ spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG); spcr |= mask; if (dev->pcr & (DAVINCI_MCBSP_PCR_FSXM | DAVINCI_MCBSP_PCR_FSRM)) { /* Start frame sync */ spcr |= DAVINCI_MCBSP_SPCR_FRST; } davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr); } static void davinci_mcbsp_stop(struct davinci_mcbsp_dev *dev, int playback) { u32 spcr; /* Reset transmitter/receiver and sample rate/frame sync generators */ spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG); spcr &= ~(DAVINCI_MCBSP_SPCR_GRST | DAVINCI_MCBSP_SPCR_FRST); spcr &= playback ? ~DAVINCI_MCBSP_SPCR_XRST : ~DAVINCI_MCBSP_SPCR_RRST; davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr); toggle_clock(dev, playback); } #define DEFAULT_BITPERSAMPLE 16 static int davinci_i2s_set_dai_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt) { struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(cpu_dai); unsigned int pcr; unsigned int srgr; bool inv_fs = false; /* Attention srgr is updated by hw_params! */ srgr = DAVINCI_MCBSP_SRGR_FSGM | DAVINCI_MCBSP_SRGR_FPER(DEFAULT_BITPERSAMPLE * 2 - 1) | DAVINCI_MCBSP_SRGR_FWID(DEFAULT_BITPERSAMPLE - 1); dev->fmt = fmt; /* set master/slave audio interface */ switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBS_CFS: /* cpu is master */ pcr = DAVINCI_MCBSP_PCR_FSXM | DAVINCI_MCBSP_PCR_FSRM | DAVINCI_MCBSP_PCR_CLKXM | DAVINCI_MCBSP_PCR_CLKRM; break; case SND_SOC_DAIFMT_CBM_CFS: pcr = DAVINCI_MCBSP_PCR_FSRM | DAVINCI_MCBSP_PCR_FSXM; /* * Selection of the clock input pin that is the * input for the Sample Rate Generator. * McBSP FSR and FSX are driven by the Sample Rate * Generator. */ switch (dev->clk_input_pin) { case MCBSP_CLKS: pcr |= DAVINCI_MCBSP_PCR_CLKXM | DAVINCI_MCBSP_PCR_CLKRM; break; case MCBSP_CLKR: pcr |= DAVINCI_MCBSP_PCR_SCLKME; break; default: dev_err(dev->dev, "bad clk_input_pin\n"); return -EINVAL; } break; case SND_SOC_DAIFMT_CBM_CFM: /* codec is master */ pcr = 0; break; default: printk(KERN_ERR "%s:bad master\n", __func__); return -EINVAL; } /* interface format */ switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: /* Davinci doesn't support TRUE I2S, but some codecs will have * the left and right channels contiguous. This allows * dsp_a mode to be used with an inverted normal frame clk. * If your codec is master and does not have contiguous * channels, then you will have sound on only one channel. * Try using a different mode, or codec as slave. * * The TLV320AIC33 is an example of a codec where this works. * It has a variable bit clock frequency allowing it to have * valid data on every bit clock. * * The TLV320AIC23 is an example of a codec where this does not * work. It has a fixed bit clock frequency with progressively * more empty bit clock slots between channels as the sample * rate is lowered. */ inv_fs = true; case SND_SOC_DAIFMT_DSP_A: dev->mode = MOD_DSP_A; break; case SND_SOC_DAIFMT_DSP_B: dev->mode = MOD_DSP_B; break; default: printk(KERN_ERR "%s:bad format\n", __func__); return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_NB_NF: /* CLKRP Receive clock polarity, * 1 - sampled on rising edge of CLKR * valid on rising edge * CLKXP Transmit clock polarity, * 1 - clocked on falling edge of CLKX * valid on rising edge * FSRP Receive frame sync pol, 0 - active high * FSXP Transmit frame sync pol, 0 - active high */ pcr |= (DAVINCI_MCBSP_PCR_CLKXP | DAVINCI_MCBSP_PCR_CLKRP); break; case SND_SOC_DAIFMT_IB_IF: /* CLKRP Receive clock polarity, * 0 - sampled on falling edge of CLKR * valid on falling edge * CLKXP Transmit clock polarity, * 0 - clocked on rising edge of CLKX * valid on falling edge * FSRP Receive frame sync pol, 1 - active low * FSXP Transmit frame sync pol, 1 - active low */ pcr |= (DAVINCI_MCBSP_PCR_FSXP | DAVINCI_MCBSP_PCR_FSRP); break; case SND_SOC_DAIFMT_NB_IF: /* CLKRP Receive clock polarity, * 1 - sampled on rising edge of CLKR * valid on rising edge * CLKXP Transmit clock polarity, * 1 - clocked on falling edge of CLKX * valid on rising edge * FSRP Receive frame sync pol, 1 - active low * FSXP Transmit frame sync pol, 1 - active low */ pcr |= (DAVINCI_MCBSP_PCR_CLKXP | DAVINCI_MCBSP_PCR_CLKRP | DAVINCI_MCBSP_PCR_FSXP | DAVINCI_MCBSP_PCR_FSRP); break; case SND_SOC_DAIFMT_IB_NF: /* CLKRP Receive clock polarity, * 0 - sampled on falling edge of CLKR * valid on falling edge * CLKXP Transmit clock polarity, * 0 - clocked on rising edge of CLKX * valid on falling edge * FSRP Receive frame sync pol, 0 - active high * FSXP Transmit frame sync pol, 0 - active high */ break; default: return -EINVAL; } if (inv_fs == true) pcr ^= (DAVINCI_MCBSP_PCR_FSXP | DAVINCI_MCBSP_PCR_FSRP); davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SRGR_REG, srgr); dev->pcr = pcr; davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_PCR_REG, pcr); return 0; } static int davinci_i2s_dai_set_clkdiv(struct snd_soc_dai *cpu_dai, int div_id, int div) { struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(cpu_dai); if (div_id != DAVINCI_MCBSP_CLKGDV) return -ENODEV; dev->clk_div = div; return 0; } static int davinci_i2s_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(dai); struct davinci_pcm_dma_params *dma_params = &dev->dma_params[substream->stream]; struct snd_interval *i = NULL; int mcbsp_word_length, master; unsigned int rcr, xcr, srgr, clk_div, freq, framesize; u32 spcr; snd_pcm_format_t fmt; unsigned element_cnt = 1; /* general line settings */ spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG); if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { spcr |= DAVINCI_MCBSP_SPCR_RINTM(3) | DAVINCI_MCBSP_SPCR_FREE; davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr); } else { spcr |= DAVINCI_MCBSP_SPCR_XINTM(3) | DAVINCI_MCBSP_SPCR_FREE; davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr); } master = dev->fmt & SND_SOC_DAIFMT_MASTER_MASK; fmt = params_format(params); mcbsp_word_length = asp_word_length[fmt]; switch (master) { case SND_SOC_DAIFMT_CBS_CFS: freq = clk_get_rate(dev->clk); srgr = DAVINCI_MCBSP_SRGR_FSGM | DAVINCI_MCBSP_SRGR_CLKSM; srgr |= DAVINCI_MCBSP_SRGR_FWID(mcbsp_word_length * 8 - 1); if (dev->i2s_accurate_sck) { clk_div = 256; do { framesize = (freq / (--clk_div)) / params->rate_num * params->rate_den; } while (((framesize < 33) || (framesize > 4095)) && (clk_div)); clk_div--; srgr |= DAVINCI_MCBSP_SRGR_FPER(framesize - 1); } else { /* symmetric waveforms */ clk_div = freq / (mcbsp_word_length * 16) / params->rate_num * params->rate_den; srgr |= DAVINCI_MCBSP_SRGR_FPER(mcbsp_word_length * 16 - 1); } clk_div &= 0xFF; srgr |= clk_div; break; case SND_SOC_DAIFMT_CBM_CFS: srgr = DAVINCI_MCBSP_SRGR_FSGM; clk_div = dev->clk_div - 1; srgr |= DAVINCI_MCBSP_SRGR_FWID(mcbsp_word_length * 8 - 1); srgr |= DAVINCI_MCBSP_SRGR_FPER(mcbsp_word_length * 16 - 1); clk_div &= 0xFF; srgr |= clk_div; break; case SND_SOC_DAIFMT_CBM_CFM: /* Clock and frame sync given from external sources */ i = hw_param_interval(params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS); srgr = DAVINCI_MCBSP_SRGR_FSGM; srgr |= DAVINCI_MCBSP_SRGR_FWID(snd_interval_value(i) - 1); pr_debug("%s - %d FWID set: re-read srgr = %X\n", __func__, __LINE__, snd_interval_value(i) - 1); i = hw_param_interval(params, SNDRV_PCM_HW_PARAM_FRAME_BITS); srgr |= DAVINCI_MCBSP_SRGR_FPER(snd_interval_value(i) - 1); break; default: return -EINVAL; } davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SRGR_REG, srgr); rcr = DAVINCI_MCBSP_RCR_RFIG; xcr = DAVINCI_MCBSP_XCR_XFIG; if (dev->mode == MOD_DSP_B) { rcr |= DAVINCI_MCBSP_RCR_RDATDLY(0); xcr |= DAVINCI_MCBSP_XCR_XDATDLY(0); } else { rcr |= DAVINCI_MCBSP_RCR_RDATDLY(1); xcr |= DAVINCI_MCBSP_XCR_XDATDLY(1); } /* Determine xfer data type */ fmt = params_format(params); if ((fmt > SNDRV_PCM_FORMAT_S32_LE) || !data_type[fmt]) { printk(KERN_WARNING "davinci-i2s: unsupported PCM format\n"); return -EINVAL; } if (params_channels(params) == 2) { element_cnt = 2; if (double_fmt[fmt] && dev->enable_channel_combine) { element_cnt = 1; fmt = double_fmt[fmt]; } switch (master) { case SND_SOC_DAIFMT_CBS_CFS: case SND_SOC_DAIFMT_CBS_CFM: rcr |= DAVINCI_MCBSP_RCR_RFRLEN2(0); xcr |= DAVINCI_MCBSP_XCR_XFRLEN2(0); rcr |= DAVINCI_MCBSP_RCR_RPHASE; xcr |= DAVINCI_MCBSP_XCR_XPHASE; break; case SND_SOC_DAIFMT_CBM_CFM: case SND_SOC_DAIFMT_CBM_CFS: rcr |= DAVINCI_MCBSP_RCR_RFRLEN2(element_cnt - 1); xcr |= DAVINCI_MCBSP_XCR_XFRLEN2(element_cnt - 1); break; default: return -EINVAL; } } dma_params->acnt = dma_params->data_type = data_type[fmt]; dma_params->fifo_level = 0; mcbsp_word_length = asp_word_length[fmt]; switch (master) { case SND_SOC_DAIFMT_CBS_CFS: case SND_SOC_DAIFMT_CBS_CFM: rcr |= DAVINCI_MCBSP_RCR_RFRLEN1(0); xcr |= DAVINCI_MCBSP_XCR_XFRLEN1(0); break; case SND_SOC_DAIFMT_CBM_CFM: case SND_SOC_DAIFMT_CBM_CFS: rcr |= DAVINCI_MCBSP_RCR_RFRLEN1(element_cnt - 1); xcr |= DAVINCI_MCBSP_XCR_XFRLEN1(element_cnt - 1); break; default: return -EINVAL; } rcr |= DAVINCI_MCBSP_RCR_RWDLEN1(mcbsp_word_length) | DAVINCI_MCBSP_RCR_RWDLEN2(mcbsp_word_length); xcr |= DAVINCI_MCBSP_XCR_XWDLEN1(mcbsp_word_length) | DAVINCI_MCBSP_XCR_XWDLEN2(mcbsp_word_length); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_XCR_REG, xcr); else davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_RCR_REG, rcr); pr_debug("%s - %d srgr=%X\n", __func__, __LINE__, srgr); pr_debug("%s - %d xcr=%X\n", __func__, __LINE__, xcr); pr_debug("%s - %d rcr=%X\n", __func__, __LINE__, rcr); return 0; } static int davinci_i2s_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(dai); int playback = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK); davinci_mcbsp_stop(dev, playback); return 0; } static int davinci_i2s_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(dai); int ret = 0; int playback = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK); switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: davinci_mcbsp_start(dev, substream); break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: davinci_mcbsp_stop(dev, playback); break; default: ret = -EINVAL; } return ret; } static int davinci_i2s_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(dai); snd_soc_dai_set_dma_data(dai, substream, dev->dma_params); return 0; } static void davinci_i2s_shutdown(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(dai); int playback = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK); davinci_mcbsp_stop(dev, playback); } #define DAVINCI_I2S_RATES SNDRV_PCM_RATE_8000_96000 static const struct snd_soc_dai_ops davinci_i2s_dai_ops = { .startup = davinci_i2s_startup, .shutdown = davinci_i2s_shutdown, .prepare = davinci_i2s_prepare, .trigger = davinci_i2s_trigger, .hw_params = davinci_i2s_hw_params, .set_fmt = davinci_i2s_set_dai_fmt, .set_clkdiv = davinci_i2s_dai_set_clkdiv, }; static struct snd_soc_dai_driver davinci_i2s_dai = { .playback = { .channels_min = 2, .channels_max = 2, .rates = DAVINCI_I2S_RATES, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, .capture = { .channels_min = 2, .channels_max = 2, .rates = DAVINCI_I2S_RATES, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, .ops = &davinci_i2s_dai_ops, }; static const struct snd_soc_component_driver davinci_i2s_component = { .name = "davinci-i2s", }; static int davinci_i2s_probe(struct platform_device *pdev) { struct snd_platform_data *pdata = pdev->dev.platform_data; struct davinci_mcbsp_dev *dev; struct resource *mem, *ioarea, *res; enum dma_event_q asp_chan_q = EVENTQ_0; enum dma_event_q ram_chan_q = EVENTQ_1; int ret; mem = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!mem) { dev_err(&pdev->dev, "no mem resource?\n"); return -ENODEV; } ioarea = devm_request_mem_region(&pdev->dev, mem->start, resource_size(mem), pdev->name); if (!ioarea) { dev_err(&pdev->dev, "McBSP region already claimed\n"); return -EBUSY; } dev = devm_kzalloc(&pdev->dev, sizeof(struct davinci_mcbsp_dev), GFP_KERNEL); if (!dev) return -ENOMEM; if (pdata) { dev->enable_channel_combine = pdata->enable_channel_combine; dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].sram_size = pdata->sram_size_playback; dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].sram_size = pdata->sram_size_capture; dev->clk_input_pin = pdata->clk_input_pin; dev->i2s_accurate_sck = pdata->i2s_accurate_sck; asp_chan_q = pdata->asp_chan_q; ram_chan_q = pdata->ram_chan_q; } dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].asp_chan_q = asp_chan_q; dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].ram_chan_q = ram_chan_q; dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].asp_chan_q = asp_chan_q; dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].ram_chan_q = ram_chan_q; dev->clk = clk_get(&pdev->dev, NULL); if (IS_ERR(dev->clk)) return -ENODEV; clk_enable(dev->clk); dev->base = devm_ioremap(&pdev->dev, mem->start, resource_size(mem)); if (!dev->base) { dev_err(&pdev->dev, "ioremap failed\n"); ret = -ENOMEM; goto err_release_clk; } dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].dma_addr = (dma_addr_t)(mem->start + DAVINCI_MCBSP_DXR_REG); dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].dma_addr = (dma_addr_t)(mem->start + DAVINCI_MCBSP_DRR_REG); /* first TX, then RX */ res = platform_get_resource(pdev, IORESOURCE_DMA, 0); if (!res) { dev_err(&pdev->dev, "no DMA resource\n"); ret = -ENXIO; goto err_release_clk; } dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].channel = res->start; res = platform_get_resource(pdev, IORESOURCE_DMA, 1); if (!res) { dev_err(&pdev->dev, "no DMA resource\n"); ret = -ENXIO; goto err_release_clk; } dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].channel = res->start; dev->dev = &pdev->dev; dev_set_drvdata(&pdev->dev, dev); ret = snd_soc_register_component(&pdev->dev, &davinci_i2s_component, &davinci_i2s_dai, 1); if (ret != 0) goto err_release_clk; ret = davinci_soc_platform_register(&pdev->dev); if (ret) { dev_err(&pdev->dev, "register PCM failed: %d\n", ret); goto err_unregister_component; } return 0; err_unregister_component: snd_soc_unregister_component(&pdev->dev); err_release_clk: clk_disable(dev->clk); clk_put(dev->clk); return ret; } static int davinci_i2s_remove(struct platform_device *pdev) { struct davinci_mcbsp_dev *dev = dev_get_drvdata(&pdev->dev); snd_soc_unregister_component(&pdev->dev); davinci_soc_platform_unregister(&pdev->dev); clk_disable(dev->clk); clk_put(dev->clk); dev->clk = NULL; return 0; } static struct platform_driver davinci_mcbsp_driver = { .probe = davinci_i2s_probe, .remove = davinci_i2s_remove, .driver = { .name = "davinci-mcbsp", .owner = THIS_MODULE, }, }; module_platform_driver(davinci_mcbsp_driver); MODULE_AUTHOR("Vladimir Barinov"); MODULE_DESCRIPTION("TI DAVINCI I2S (McBSP) SoC Interface"); MODULE_LICENSE("GPL");
apache-2.0
tmiranda1962/sagetv-1
third_party/ffmpeg/libswscale/options.c
43
3742
/* * Copyright (C) 2001-2003 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/avutil.h" #include "libavcodec/opt.h" #include "swscale.h" #include "swscale_internal.h" static const char * sws_context_to_name(void * ptr) { return "swscaler"; } #define OFFSET(x) offsetof(SwsContext, x) #define DEFAULT 0 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM static const AVOption options[] = { { "sws_flags", "scaler/cpu flags", OFFSET(flags), FF_OPT_TYPE_FLAGS, DEFAULT, 0, UINT_MAX, VE, "sws_flags" }, { "fast_bilinear", "fast bilinear", 0, FF_OPT_TYPE_CONST, SWS_FAST_BILINEAR, INT_MIN, INT_MAX, VE, "sws_flags" }, { "bilinear", "bilinear", 0, FF_OPT_TYPE_CONST, SWS_BILINEAR, INT_MIN, INT_MAX, VE, "sws_flags" }, { "bicubic", "bicubic", 0, FF_OPT_TYPE_CONST, SWS_BICUBIC, INT_MIN, INT_MAX, VE, "sws_flags" }, { "experimental", "experimental", 0, FF_OPT_TYPE_CONST, SWS_X, INT_MIN, INT_MAX, VE, "sws_flags" }, { "neighbor", "nearest neighbor", 0, FF_OPT_TYPE_CONST, SWS_POINT, INT_MIN, INT_MAX, VE, "sws_flags" }, { "area", "averaging area", 0, FF_OPT_TYPE_CONST, SWS_AREA, INT_MIN, INT_MAX, VE, "sws_flags" }, { "bicublin", "luma bicubic, chroma bilinear", 0, FF_OPT_TYPE_CONST, SWS_BICUBLIN, INT_MIN, INT_MAX, VE, "sws_flags" }, { "gauss", "gaussian", 0, FF_OPT_TYPE_CONST, SWS_GAUSS, INT_MIN, INT_MAX, VE, "sws_flags" }, { "sinc", "sinc", 0, FF_OPT_TYPE_CONST, SWS_SINC, INT_MIN, INT_MAX, VE, "sws_flags" }, { "lanczos", "lanczos", 0, FF_OPT_TYPE_CONST, SWS_LANCZOS, INT_MIN, INT_MAX, VE, "sws_flags" }, { "spline", "natural bicubic spline", 0, FF_OPT_TYPE_CONST, SWS_SPLINE, INT_MIN, INT_MAX, VE, "sws_flags" }, { "print_info", "print info", 0, FF_OPT_TYPE_CONST, SWS_PRINT_INFO, INT_MIN, INT_MAX, VE, "sws_flags" }, { "accurate_rnd", "accurate rounding", 0, FF_OPT_TYPE_CONST, SWS_ACCURATE_RND, INT_MIN, INT_MAX, VE, "sws_flags" }, { "mmx", "MMX SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_MMX, INT_MIN, INT_MAX, VE, "sws_flags" }, { "mmx2", "MMX2 SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_MMX2, INT_MIN, INT_MAX, VE, "sws_flags" }, { "3dnow", "3DNOW SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_3DNOW, INT_MIN, INT_MAX, VE, "sws_flags" }, { "altivec", "AltiVec SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_ALTIVEC, INT_MIN, INT_MAX, VE, "sws_flags" }, { "bfin", "Blackfin SIMD acceleration", 0, FF_OPT_TYPE_CONST, SWS_CPU_CAPS_BFIN, INT_MIN, INT_MAX, VE, "sws_flags" }, { "full_chroma_int", "full chroma interpolation", 0 , FF_OPT_TYPE_CONST, SWS_FULL_CHR_H_INT, INT_MIN, INT_MAX, VE, "sws_flags" }, { "full_chroma_inp", "full chroma input", 0 , FF_OPT_TYPE_CONST, SWS_FULL_CHR_H_INP, INT_MIN, INT_MAX, VE, "sws_flags" }, { "bitexact", "", 0 , FF_OPT_TYPE_CONST, SWS_BITEXACT, INT_MIN, INT_MAX, VE, "sws_flags" }, { NULL } }; const AVClass sws_context_class = { "SWScaler", sws_context_to_name, options };
apache-2.0
infinnovation/mbed-os
targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_tim.c
45
46399
/** ****************************************************************************** * @file stm32f1xx_ll_tim.c * @author MCD Application Team * @version V1.1.0 * @date 14-April-2017 * @brief TIM LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_ll_tim.h" #include "stm32f1xx_ll_bus.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32F1xx_LL_Driver * @{ */ #if defined (TIM1) || defined (TIM2) || defined (TIM3) || defined (TIM4) || defined (TIM5) || defined (TIM6) || defined (TIM7) || defined (TIM8) || defined (TIM9) || defined (TIM10) || defined (TIM11) || defined (TIM12) || defined (TIM13) || defined (TIM14) || defined (TIM15) || defined (TIM16) || defined (TIM17) /** @addtogroup TIM_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @addtogroup TIM_LL_Private_Macros * @{ */ #define IS_LL_TIM_COUNTERMODE(__VALUE__) (((__VALUE__) == LL_TIM_COUNTERMODE_UP) \ || ((__VALUE__) == LL_TIM_COUNTERMODE_DOWN) \ || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP) \ || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_DOWN) \ || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP_DOWN)) #define IS_LL_TIM_CLOCKDIVISION(__VALUE__) (((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV1) \ || ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV2) \ || ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV4)) #define IS_LL_TIM_OCMODE(__VALUE__) (((__VALUE__) == LL_TIM_OCMODE_FROZEN) \ || ((__VALUE__) == LL_TIM_OCMODE_ACTIVE) \ || ((__VALUE__) == LL_TIM_OCMODE_INACTIVE) \ || ((__VALUE__) == LL_TIM_OCMODE_TOGGLE) \ || ((__VALUE__) == LL_TIM_OCMODE_FORCED_INACTIVE) \ || ((__VALUE__) == LL_TIM_OCMODE_FORCED_ACTIVE) \ || ((__VALUE__) == LL_TIM_OCMODE_PWM1) \ || ((__VALUE__) == LL_TIM_OCMODE_PWM2)) #define IS_LL_TIM_OCSTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCSTATE_DISABLE) \ || ((__VALUE__) == LL_TIM_OCSTATE_ENABLE)) #define IS_LL_TIM_OCPOLARITY(__VALUE__) (((__VALUE__) == LL_TIM_OCPOLARITY_HIGH) \ || ((__VALUE__) == LL_TIM_OCPOLARITY_LOW)) #define IS_LL_TIM_OCIDLESTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCIDLESTATE_LOW) \ || ((__VALUE__) == LL_TIM_OCIDLESTATE_HIGH)) #define IS_LL_TIM_ACTIVEINPUT(__VALUE__) (((__VALUE__) == LL_TIM_ACTIVEINPUT_DIRECTTI) \ || ((__VALUE__) == LL_TIM_ACTIVEINPUT_INDIRECTTI) \ || ((__VALUE__) == LL_TIM_ACTIVEINPUT_TRC)) #define IS_LL_TIM_ICPSC(__VALUE__) (((__VALUE__) == LL_TIM_ICPSC_DIV1) \ || ((__VALUE__) == LL_TIM_ICPSC_DIV2) \ || ((__VALUE__) == LL_TIM_ICPSC_DIV4) \ || ((__VALUE__) == LL_TIM_ICPSC_DIV8)) #define IS_LL_TIM_IC_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_IC_FILTER_FDIV1) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N2) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N4) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N8) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N6) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N8) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N6) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N8) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N6) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N8) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N5) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N6) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N8) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N5) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N6) \ || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N8)) #define IS_LL_TIM_IC_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \ || ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING)) #define IS_LL_TIM_ENCODERMODE(__VALUE__) (((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI1) \ || ((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI2) \ || ((__VALUE__) == LL_TIM_ENCODERMODE_X4_TI12)) #define IS_LL_TIM_IC_POLARITY_ENCODER(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \ || ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING)) #define IS_LL_TIM_OSSR_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSR_DISABLE) \ || ((__VALUE__) == LL_TIM_OSSR_ENABLE)) #define IS_LL_TIM_OSSI_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSI_DISABLE) \ || ((__VALUE__) == LL_TIM_OSSI_ENABLE)) #define IS_LL_TIM_LOCK_LEVEL(__VALUE__) (((__VALUE__) == LL_TIM_LOCKLEVEL_OFF) \ || ((__VALUE__) == LL_TIM_LOCKLEVEL_1) \ || ((__VALUE__) == LL_TIM_LOCKLEVEL_2) \ || ((__VALUE__) == LL_TIM_LOCKLEVEL_3)) #define IS_LL_TIM_BREAK_STATE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_DISABLE) \ || ((__VALUE__) == LL_TIM_BREAK_ENABLE)) #define IS_LL_TIM_BREAK_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_POLARITY_LOW) \ || ((__VALUE__) == LL_TIM_BREAK_POLARITY_HIGH)) #define IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(__VALUE__) (((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_DISABLE) \ || ((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_ENABLE)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /** @defgroup TIM_LL_Private_Functions TIM Private Functions * @{ */ static ErrorStatus OC1Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); static ErrorStatus OC2Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); static ErrorStatus OC3Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); static ErrorStatus OC4Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); static ErrorStatus IC1Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); static ErrorStatus IC2Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); static ErrorStatus IC3Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); static ErrorStatus IC4Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIM_LL_Exported_Functions * @{ */ /** @addtogroup TIM_LL_EF_Init * @{ */ /** * @brief Set TIMx registers to their reset values. * @param TIMx Timer instance * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: invalid TIMx instance */ ErrorStatus LL_TIM_DeInit(TIM_TypeDef *TIMx) { ErrorStatus result = SUCCESS; /* Check the parameters */ assert_param(IS_TIM_INSTANCE(TIMx)); if (TIMx == TIM2) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM2); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM2); } #if defined(TIM1) else if (TIMx == TIM1) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM1); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM1); } #endif #if defined(TIM3) else if (TIMx == TIM3) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM3); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM3); } #endif #if defined(TIM4) else if (TIMx == TIM4) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM4); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM4); } #endif #if defined(TIM5) else if (TIMx == TIM5) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM5); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM5); } #endif #if defined(TIM6) else if (TIMx == TIM6) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM6); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM6); } #endif #if defined (TIM7) else if (TIMx == TIM7) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM7); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM7); } #endif #if defined(TIM8) else if (TIMx == TIM8) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM8); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM8); } #endif #if defined(TIM9) else if (TIMx == TIM9) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM9); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM9); } #endif #if defined(TIM10) else if (TIMx == TIM10) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM10); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM10); } #endif #if defined(TIM11) else if (TIMx == TIM11) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM11); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM11); } #endif #if defined(TIM12) else if (TIMx == TIM12) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM12); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM12); } #endif #if defined(TIM13) else if (TIMx == TIM13) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM13); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM13); } #endif #if defined(TIM14) else if (TIMx == TIM14) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM14); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM14); } #endif #if defined(TIM15) else if (TIMx == TIM15) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM15); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM15); } #endif #if defined(TIM16) else if (TIMx == TIM16) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM16); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM16); } #endif #if defined(TIM17) else if (TIMx == TIM17) { LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM17); LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM17); } #endif else { result = ERROR; } return result; } /** * @brief Set the fields of the time base unit configuration data structure * to their default values. * @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure (time base unit configuration data structure) * @retval None */ void LL_TIM_StructInit(LL_TIM_InitTypeDef *TIM_InitStruct) { /* Set the default configuration */ TIM_InitStruct->Prescaler = (uint16_t)0x0000; TIM_InitStruct->CounterMode = LL_TIM_COUNTERMODE_UP; TIM_InitStruct->Autoreload = 0xFFFFFFFFU; TIM_InitStruct->ClockDivision = LL_TIM_CLOCKDIVISION_DIV1; TIM_InitStruct->RepetitionCounter = (uint8_t)0x00; } /** * @brief Configure the TIMx time base unit. * @param TIMx Timer Instance * @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure (TIMx time base unit configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ ErrorStatus LL_TIM_Init(TIM_TypeDef *TIMx, LL_TIM_InitTypeDef *TIM_InitStruct) { uint32_t tmpcr1 = 0U; /* Check the parameters */ assert_param(IS_TIM_INSTANCE(TIMx)); assert_param(IS_LL_TIM_COUNTERMODE(TIM_InitStruct->CounterMode)); assert_param(IS_LL_TIM_CLOCKDIVISION(TIM_InitStruct->ClockDivision)); tmpcr1 = LL_TIM_ReadReg(TIMx, CR1); if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx)) { /* Select the Counter Mode */ MODIFY_REG(tmpcr1, (TIM_CR1_DIR | TIM_CR1_CMS), TIM_InitStruct->CounterMode); } if (IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx)) { /* Set the clock division */ MODIFY_REG(tmpcr1, TIM_CR1_CKD, TIM_InitStruct->ClockDivision); } /* Write to TIMx CR1 */ LL_TIM_WriteReg(TIMx, CR1, tmpcr1); /* Set the Autoreload value */ LL_TIM_SetAutoReload(TIMx, TIM_InitStruct->Autoreload); /* Set the Prescaler value */ LL_TIM_SetPrescaler(TIMx, TIM_InitStruct->Prescaler); if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx)) { /* Set the Repetition Counter value */ LL_TIM_SetRepetitionCounter(TIMx, TIM_InitStruct->RepetitionCounter); } /* Generate an update event to reload the Prescaler and the repetition counter value (if applicable) immediately */ LL_TIM_GenerateEvent_UPDATE(TIMx); return SUCCESS; } /** * @brief Set the fields of the TIMx output channel configuration data * structure to their default values. * @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure (the output channel configuration data structure) * @retval None */ void LL_TIM_OC_StructInit(LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct) { /* Set the default configuration */ TIM_OC_InitStruct->OCMode = LL_TIM_OCMODE_FROZEN; TIM_OC_InitStruct->OCState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct->OCNState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct->CompareValue = 0x00000000U; TIM_OC_InitStruct->OCPolarity = LL_TIM_OCPOLARITY_HIGH; TIM_OC_InitStruct->OCNPolarity = LL_TIM_OCPOLARITY_HIGH; TIM_OC_InitStruct->OCIdleState = LL_TIM_OCIDLESTATE_LOW; TIM_OC_InitStruct->OCNIdleState = LL_TIM_OCIDLESTATE_LOW; } /** * @brief Configure the TIMx output channel. * @param TIMx Timer Instance * @param Channel This parameter can be one of the following values: * @arg @ref LL_TIM_CHANNEL_CH1 * @arg @ref LL_TIM_CHANNEL_CH2 * @arg @ref LL_TIM_CHANNEL_CH3 * @arg @ref LL_TIM_CHANNEL_CH4 * @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure (TIMx output channel configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx output channel is initialized * - ERROR: TIMx output channel is not initialized */ ErrorStatus LL_TIM_OC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct) { ErrorStatus result = ERROR; switch (Channel) { case LL_TIM_CHANNEL_CH1: result = OC1Config(TIMx, TIM_OC_InitStruct); break; case LL_TIM_CHANNEL_CH2: result = OC2Config(TIMx, TIM_OC_InitStruct); break; case LL_TIM_CHANNEL_CH3: result = OC3Config(TIMx, TIM_OC_InitStruct); break; case LL_TIM_CHANNEL_CH4: result = OC4Config(TIMx, TIM_OC_InitStruct); break; default: break; } return result; } /** * @brief Set the fields of the TIMx input channel configuration data * structure to their default values. * @param TIM_ICInitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (the input channel configuration data structure) * @retval None */ void LL_TIM_IC_StructInit(LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) { /* Set the default configuration */ TIM_ICInitStruct->ICPolarity = LL_TIM_IC_POLARITY_RISING; TIM_ICInitStruct->ICActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; TIM_ICInitStruct->ICPrescaler = LL_TIM_ICPSC_DIV1; TIM_ICInitStruct->ICFilter = LL_TIM_IC_FILTER_FDIV1; } /** * @brief Configure the TIMx input channel. * @param TIMx Timer Instance * @param Channel This parameter can be one of the following values: * @arg @ref LL_TIM_CHANNEL_CH1 * @arg @ref LL_TIM_CHANNEL_CH2 * @arg @ref LL_TIM_CHANNEL_CH3 * @arg @ref LL_TIM_CHANNEL_CH4 * @param TIM_IC_InitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (TIMx input channel configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx output channel is initialized * - ERROR: TIMx output channel is not initialized */ ErrorStatus LL_TIM_IC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_IC_InitTypeDef *TIM_IC_InitStruct) { ErrorStatus result = ERROR; switch (Channel) { case LL_TIM_CHANNEL_CH1: result = IC1Config(TIMx, TIM_IC_InitStruct); break; case LL_TIM_CHANNEL_CH2: result = IC2Config(TIMx, TIM_IC_InitStruct); break; case LL_TIM_CHANNEL_CH3: result = IC3Config(TIMx, TIM_IC_InitStruct); break; case LL_TIM_CHANNEL_CH4: result = IC4Config(TIMx, TIM_IC_InitStruct); break; default: break; } return result; } /** * @brief Fills each TIM_EncoderInitStruct field with its default value * @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (encoder interface configuration data structure) * @retval None */ void LL_TIM_ENCODER_StructInit(LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct) { /* Set the default configuration */ TIM_EncoderInitStruct->EncoderMode = LL_TIM_ENCODERMODE_X2_TI1; TIM_EncoderInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING; TIM_EncoderInitStruct->IC1ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; TIM_EncoderInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1; TIM_EncoderInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1; TIM_EncoderInitStruct->IC2Polarity = LL_TIM_IC_POLARITY_RISING; TIM_EncoderInitStruct->IC2ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; TIM_EncoderInitStruct->IC2Prescaler = LL_TIM_ICPSC_DIV1; TIM_EncoderInitStruct->IC2Filter = LL_TIM_IC_FILTER_FDIV1; } /** * @brief Configure the encoder interface of the timer instance. * @param TIMx Timer Instance * @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (TIMx encoder interface configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ ErrorStatus LL_TIM_ENCODER_Init(TIM_TypeDef *TIMx, LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct) { uint32_t tmpccmr1 = 0U; uint32_t tmpccer = 0U; /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(TIMx)); assert_param(IS_LL_TIM_ENCODERMODE(TIM_EncoderInitStruct->EncoderMode)); assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC1Polarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC1ActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC1Prescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC1Filter)); assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC2Polarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC2ActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC2Prescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC2Filter)); /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E); /* Get the TIMx CCMR1 register value */ tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Configure TI1 */ tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1ActiveInput >> 16U); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Filter >> 16U); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Prescaler >> 16U); /* Configure TI2 */ tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2ActiveInput >> 8U); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Filter >> 8U); tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Prescaler >> 8U); /* Set TI1 and TI2 polarity and enable TI1 and TI2 */ tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP); tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC1Polarity); tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC2Polarity << 4U); tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E); /* Set encoder mode */ LL_TIM_SetEncoderMode(TIMx, TIM_EncoderInitStruct->EncoderMode); /* Write to TIMx CCMR1 */ LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); return SUCCESS; } /** * @brief Set the fields of the TIMx Hall sensor interface configuration data * structure to their default values. * @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (HALL sensor interface configuration data structure) * @retval None */ void LL_TIM_HALLSENSOR_StructInit(LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct) { /* Set the default configuration */ TIM_HallSensorInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING; TIM_HallSensorInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1; TIM_HallSensorInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1; TIM_HallSensorInitStruct->CommutationDelay = 0U; } /** * @brief Configure the Hall sensor interface of the timer instance. * @note TIMx CH1, CH2 and CH3 inputs connected through a XOR * to the TI1 input channel * @note TIMx slave mode controller is configured in reset mode. Selected internal trigger is TI1F_ED. * @note Channel 1 is configured as input, IC1 is mapped on TRC. * @note Captured value stored in TIMx_CCR1 correspond to the time elapsed * between 2 changes on the inputs. It gives information about motor speed. * @note Channel 2 is configured in output PWM 2 mode. * @note Compare value stored in TIMx_CCR2 corresponds to the commutation delay. * @note OC2REF is selected as trigger output on TRGO. * @param TIMx Timer Instance * @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (TIMx HALL sensor interface configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ ErrorStatus LL_TIM_HALLSENSOR_Init(TIM_TypeDef *TIMx, LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct) { uint32_t tmpcr2 = 0U; uint32_t tmpccmr1 = 0U; uint32_t tmpccer = 0U; uint32_t tmpsmcr = 0U; /* Check the parameters */ assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(TIMx)); assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_HallSensorInitStruct->IC1Polarity)); assert_param(IS_LL_TIM_ICPSC(TIM_HallSensorInitStruct->IC1Prescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_HallSensorInitStruct->IC1Filter)); /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E); /* Get the TIMx CR2 register value */ tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); /* Get the TIMx CCMR1 register value */ tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Get the TIMx SMCR register value */ tmpsmcr = LL_TIM_ReadReg(TIMx, SMCR); /* Connect TIMx_CH1, CH2 and CH3 pins to the TI1 input */ tmpcr2 |= TIM_CR2_TI1S; /* OC2REF signal is used as trigger output (TRGO) */ tmpcr2 |= LL_TIM_TRGO_OC2REF; /* Configure the slave mode controller */ tmpsmcr &= (uint32_t)~(TIM_SMCR_TS | TIM_SMCR_SMS); tmpsmcr |= LL_TIM_TS_TI1F_ED; tmpsmcr |= LL_TIM_SLAVEMODE_RESET; /* Configure input channel 1 */ tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC); tmpccmr1 |= (uint32_t)(LL_TIM_ACTIVEINPUT_TRC >> 16U); tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Filter >> 16U); tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Prescaler >> 16U); /* Configure input channel 2 */ tmpccmr1 &= (uint32_t)~(TIM_CCMR1_OC2M | TIM_CCMR1_OC2FE | TIM_CCMR1_OC2PE | TIM_CCMR1_OC2CE); tmpccmr1 |= (uint32_t)(LL_TIM_OCMODE_PWM2 << 8U); /* Set Channel 1 polarity and enable Channel 1 and Channel2 */ tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP); tmpccer |= (uint32_t)(TIM_HallSensorInitStruct->IC1Polarity); tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E); /* Write to TIMx CR2 */ LL_TIM_WriteReg(TIMx, CR2, tmpcr2); /* Write to TIMx SMCR */ LL_TIM_WriteReg(TIMx, SMCR, tmpsmcr); /* Write to TIMx CCMR1 */ LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); /* Write to TIMx CCR2 */ LL_TIM_OC_SetCompareCH2(TIMx, TIM_HallSensorInitStruct->CommutationDelay); return SUCCESS; } /** * @brief Set the fields of the Break and Dead Time configuration data structure * to their default values. * @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure (Break and Dead Time configuration data structure) * @retval None */ void LL_TIM_BDTR_StructInit(LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct) { /* Set the default configuration */ TIM_BDTRInitStruct->OSSRState = LL_TIM_OSSR_DISABLE; TIM_BDTRInitStruct->OSSIState = LL_TIM_OSSI_DISABLE; TIM_BDTRInitStruct->LockLevel = LL_TIM_LOCKLEVEL_OFF; TIM_BDTRInitStruct->DeadTime = (uint8_t)0x00; TIM_BDTRInitStruct->BreakState = LL_TIM_BREAK_DISABLE; TIM_BDTRInitStruct->BreakPolarity = LL_TIM_BREAK_POLARITY_LOW; TIM_BDTRInitStruct->AutomaticOutput = LL_TIM_AUTOMATICOUTPUT_DISABLE; } /** * @brief Configure the Break and Dead Time feature of the timer instance. * @note As the bits AOE, BKP, BKE, OSSR, OSSI and DTG[7:0] can be write-locked * depending on the LOCK configuration, it can be necessary to configure all of * them during the first write access to the TIMx_BDTR register. * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not * a timer instance provides a break input. * @param TIMx Timer Instance * @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure(Break and Dead Time configuration data structure) * @retval An ErrorStatus enumeration value: * - SUCCESS: Break and Dead Time is initialized * - ERROR: not applicable */ ErrorStatus LL_TIM_BDTR_Init(TIM_TypeDef *TIMx, LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct) { uint32_t tmpbdtr = 0; /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(TIMx)); assert_param(IS_LL_TIM_OSSR_STATE(TIM_BDTRInitStruct->OSSRState)); assert_param(IS_LL_TIM_OSSI_STATE(TIM_BDTRInitStruct->OSSIState)); assert_param(IS_LL_TIM_LOCK_LEVEL(TIM_BDTRInitStruct->LockLevel)); assert_param(IS_LL_TIM_BREAK_STATE(TIM_BDTRInitStruct->BreakState)); assert_param(IS_LL_TIM_BREAK_POLARITY(TIM_BDTRInitStruct->BreakPolarity)); assert_param(IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(TIM_BDTRInitStruct->AutomaticOutput)); /* Set the Lock level, the Break enable Bit and the Polarity, the OSSR State, the OSSI State, the dead time value and the Automatic Output Enable Bit */ /* Set the BDTR bits */ MODIFY_REG(tmpbdtr, TIM_BDTR_DTG, TIM_BDTRInitStruct->DeadTime); MODIFY_REG(tmpbdtr, TIM_BDTR_LOCK, TIM_BDTRInitStruct->LockLevel); MODIFY_REG(tmpbdtr, TIM_BDTR_OSSI, TIM_BDTRInitStruct->OSSIState); MODIFY_REG(tmpbdtr, TIM_BDTR_OSSR, TIM_BDTRInitStruct->OSSRState); MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, TIM_BDTRInitStruct->BreakState); MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, TIM_BDTRInitStruct->BreakPolarity); MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, TIM_BDTRInitStruct->AutomaticOutput); MODIFY_REG(tmpbdtr, TIM_BDTR_MOE, TIM_BDTRInitStruct->AutomaticOutput); /* Set TIMx_BDTR */ LL_TIM_WriteReg(TIMx, BDTR, tmpbdtr); return SUCCESS; } /** * @} */ /** * @} */ /** @addtogroup TIM_LL_Private_Functions TIM Private Functions * @brief Private functions * @{ */ /** * @brief Configure the TIMx output channel 1. * @param TIMx Timer Instance * @param TIM_OCInitStruct pointer to the the TIMx output channel 1 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus OC1Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) { uint32_t tmpccmr1 = 0U; uint32_t tmpccer = 0U; uint32_t tmpcr2 = 0U; /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(TIMx)); assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 1: Reset the CC1E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC1E); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Get the TIMx CR2 register value */ tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); /* Get the TIMx CCMR1 register value */ tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); /* Reset Capture/Compare selection Bits */ CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC1S); /* Set the Output Compare Mode */ MODIFY_REG(tmpccmr1, TIM_CCMR1_OC1M, TIM_OCInitStruct->OCMode); /* Set the Output Compare Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC1P, TIM_OCInitStruct->OCPolarity); /* Set the Output State */ MODIFY_REG(tmpccer, TIM_CCER_CC1E, TIM_OCInitStruct->OCState); if (IS_TIM_BREAK_INSTANCE(TIMx)) { assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC1NP, TIM_OCInitStruct->OCNPolarity << 2U); /* Set the complementary output State */ MODIFY_REG(tmpccer, TIM_CCER_CC1NE, TIM_OCInitStruct->OCNState << 2U); /* Set the Output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS1, TIM_OCInitStruct->OCIdleState); /* Set the complementary output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS1N, TIM_OCInitStruct->OCNIdleState << 1U); } /* Write to TIMx CR2 */ LL_TIM_WriteReg(TIMx, CR2, tmpcr2); /* Write to TIMx CCMR1 */ LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); /* Set the Capture Compare Register value */ LL_TIM_OC_SetCompareCH1(TIMx, TIM_OCInitStruct->CompareValue); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); return SUCCESS; } /** * @brief Configure the TIMx output channel 2. * @param TIMx Timer Instance * @param TIM_OCInitStruct pointer to the the TIMx output channel 2 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus OC2Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) { uint32_t tmpccmr1 = 0U; uint32_t tmpccer = 0U; uint32_t tmpcr2 = 0U; /* Check the parameters */ assert_param(IS_TIM_CC2_INSTANCE(TIMx)); assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 2: Reset the CC2E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC2E); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Get the TIMx CR2 register value */ tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); /* Get the TIMx CCMR1 register value */ tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); /* Reset Capture/Compare selection Bits */ CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC2S); /* Select the Output Compare Mode */ MODIFY_REG(tmpccmr1, TIM_CCMR1_OC2M, TIM_OCInitStruct->OCMode << 8U); /* Set the Output Compare Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC2P, TIM_OCInitStruct->OCPolarity << 4U); /* Set the Output State */ MODIFY_REG(tmpccer, TIM_CCER_CC2E, TIM_OCInitStruct->OCState << 4U); if (IS_TIM_BREAK_INSTANCE(TIMx)) { assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC2NP, TIM_OCInitStruct->OCNPolarity << 6U); /* Set the complementary output State */ MODIFY_REG(tmpccer, TIM_CCER_CC2NE, TIM_OCInitStruct->OCNState << 6U); /* Set the Output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS2, TIM_OCInitStruct->OCIdleState << 2U); /* Set the complementary output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS2N, TIM_OCInitStruct->OCNIdleState << 3U); } /* Write to TIMx CR2 */ LL_TIM_WriteReg(TIMx, CR2, tmpcr2); /* Write to TIMx CCMR1 */ LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); /* Set the Capture Compare Register value */ LL_TIM_OC_SetCompareCH2(TIMx, TIM_OCInitStruct->CompareValue); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); return SUCCESS; } /** * @brief Configure the TIMx output channel 3. * @param TIMx Timer Instance * @param TIM_OCInitStruct pointer to the the TIMx output channel 3 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus OC3Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) { uint32_t tmpccmr2 = 0U; uint32_t tmpccer = 0U; uint32_t tmpcr2 = 0U; /* Check the parameters */ assert_param(IS_TIM_CC3_INSTANCE(TIMx)); assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 3: Reset the CC3E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC3E); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Get the TIMx CR2 register value */ tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); /* Get the TIMx CCMR2 register value */ tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2); /* Reset Capture/Compare selection Bits */ CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC3S); /* Select the Output Compare Mode */ MODIFY_REG(tmpccmr2, TIM_CCMR2_OC3M, TIM_OCInitStruct->OCMode); /* Set the Output Compare Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC3P, TIM_OCInitStruct->OCPolarity << 8U); /* Set the Output State */ MODIFY_REG(tmpccer, TIM_CCER_CC3E, TIM_OCInitStruct->OCState << 8U); if (IS_TIM_BREAK_INSTANCE(TIMx)) { assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC3NP, TIM_OCInitStruct->OCNPolarity << 10U); /* Set the complementary output State */ MODIFY_REG(tmpccer, TIM_CCER_CC3NE, TIM_OCInitStruct->OCNState << 10U); /* Set the Output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS3, TIM_OCInitStruct->OCIdleState << 4U); /* Set the complementary output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS3N, TIM_OCInitStruct->OCNIdleState << 5U); } /* Write to TIMx CR2 */ LL_TIM_WriteReg(TIMx, CR2, tmpcr2); /* Write to TIMx CCMR2 */ LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2); /* Set the Capture Compare Register value */ LL_TIM_OC_SetCompareCH3(TIMx, TIM_OCInitStruct->CompareValue); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); return SUCCESS; } /** * @brief Configure the TIMx output channel 4. * @param TIMx Timer Instance * @param TIM_OCInitStruct pointer to the the TIMx output channel 4 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus OC4Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) { uint32_t tmpccmr2 = 0U; uint32_t tmpccer = 0U; uint32_t tmpcr2 = 0U; /* Check the parameters */ assert_param(IS_TIM_CC4_INSTANCE(TIMx)); assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); /* Disable the Channel 4: Reset the CC4E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC4E); /* Get the TIMx CCER register value */ tmpccer = LL_TIM_ReadReg(TIMx, CCER); /* Get the TIMx CR2 register value */ tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); /* Get the TIMx CCMR2 register value */ tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2); /* Reset Capture/Compare selection Bits */ CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC4S); /* Select the Output Compare Mode */ MODIFY_REG(tmpccmr2, TIM_CCMR2_OC4M, TIM_OCInitStruct->OCMode << 8U); /* Set the Output Compare Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC4P, TIM_OCInitStruct->OCPolarity << 12U); /* Set the Output State */ MODIFY_REG(tmpccer, TIM_CCER_CC4E, TIM_OCInitStruct->OCState << 12U); if (IS_TIM_BREAK_INSTANCE(TIMx)) { assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the Output Idle state */ MODIFY_REG(tmpcr2, TIM_CR2_OIS4, TIM_OCInitStruct->OCIdleState << 6U); } /* Write to TIMx CR2 */ LL_TIM_WriteReg(TIMx, CR2, tmpcr2); /* Write to TIMx CCMR2 */ LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2); /* Set the Capture Compare Register value */ LL_TIM_OC_SetCompareCH4(TIMx, TIM_OCInitStruct->CompareValue); /* Write to TIMx CCER */ LL_TIM_WriteReg(TIMx, CCER, tmpccer); return SUCCESS; } /** * @brief Configure the TIMx input channel 1. * @param TIMx Timer Instance * @param TIM_ICInitStruct pointer to the the TIMx input channel 1 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus IC1Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) { /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(TIMx)); assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); /* Disable the Channel 1: Reset the CC1E Bit */ TIMx->CCER &= (uint32_t)~TIM_CCER_CC1E; /* Select the Input and set the filter and the prescaler value */ MODIFY_REG(TIMx->CCMR1, (TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC), (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U); /* Select the Polarity and set the CC1E Bit */ MODIFY_REG(TIMx->CCER, (TIM_CCER_CC1P | TIM_CCER_CC1NP), (TIM_ICInitStruct->ICPolarity | TIM_CCER_CC1E)); return SUCCESS; } /** * @brief Configure the TIMx input channel 2. * @param TIMx Timer Instance * @param TIM_ICInitStruct pointer to the the TIMx input channel 2 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus IC2Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) { /* Check the parameters */ assert_param(IS_TIM_CC2_INSTANCE(TIMx)); assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); /* Disable the Channel 2: Reset the CC2E Bit */ TIMx->CCER &= (uint32_t)~TIM_CCER_CC2E; /* Select the Input and set the filter and the prescaler value */ MODIFY_REG(TIMx->CCMR1, (TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC), (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); /* Select the Polarity and set the CC2E Bit */ MODIFY_REG(TIMx->CCER, (TIM_CCER_CC2P | TIM_CCER_CC2NP), ((TIM_ICInitStruct->ICPolarity << 4U) | TIM_CCER_CC2E)); return SUCCESS; } /** * @brief Configure the TIMx input channel 3. * @param TIMx Timer Instance * @param TIM_ICInitStruct pointer to the the TIMx input channel 3 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus IC3Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) { /* Check the parameters */ assert_param(IS_TIM_CC3_INSTANCE(TIMx)); assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); /* Disable the Channel 3: Reset the CC3E Bit */ TIMx->CCER &= (uint32_t)~TIM_CCER_CC3E; /* Select the Input and set the filter and the prescaler value */ MODIFY_REG(TIMx->CCMR2, (TIM_CCMR2_CC3S | TIM_CCMR2_IC3F | TIM_CCMR2_IC3PSC), (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U); /* Select the Polarity and set the CC3E Bit */ MODIFY_REG(TIMx->CCER, (TIM_CCER_CC3P | TIM_CCER_CC3NP), ((TIM_ICInitStruct->ICPolarity << 8U) | TIM_CCER_CC3E)); return SUCCESS; } /** * @brief Configure the TIMx input channel 4. * @param TIMx Timer Instance * @param TIM_ICInitStruct pointer to the the TIMx input channel 4 configuration data structure * @retval An ErrorStatus enumeration value: * - SUCCESS: TIMx registers are de-initialized * - ERROR: not applicable */ static ErrorStatus IC4Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) { /* Check the parameters */ assert_param(IS_TIM_CC4_INSTANCE(TIMx)); assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); /* Disable the Channel 4: Reset the CC4E Bit */ TIMx->CCER &= (uint32_t)~TIM_CCER_CC4E; /* Select the Input and set the filter and the prescaler value */ MODIFY_REG(TIMx->CCMR2, (TIM_CCMR2_CC4S | TIM_CCMR2_IC4F | TIM_CCMR2_IC4PSC), (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); /* Select the Polarity and set the CC4E Bit */ MODIFY_REG(TIMx->CCER, TIM_CCER_CC4P, ((TIM_ICInitStruct->ICPolarity << 12U) | TIM_CCER_CC4E)); return SUCCESS; } /** * @} */ /** * @} */ #endif /* TIM1 || TIM2 || TIM3 || TIM4 || TIM5 || TIM6 || TIM7 || TIM8 || TIM9 || TIM10 || TIM11 || TIM12 || TIM13 || TIM14 || TIM15 || TIM16 || TIM17 */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
apache-2.0
enikki/otp
lib/erl_interface/test/ei_format_SUITE_data/ei_format_test.c
46
4375
/* * %CopyrightBegin% * * Copyright Ericsson AB 2001-2013. 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. * * %CopyrightEnd% */ #ifdef VXWORKS #include "reclaim.h" #endif #include "ei_runner.h" #include <string.h> /* * Purpose: Tests the ei_format() function. * Author: Jakob */ static void send_format2(char* format, char* p) { ei_x_buff x; ei_x_new(&x); ei_x_format(&x, format, p); send_bin_term(&x); free(x.buff); } static void send_format(char* format) { send_format2(format, NULL); } TESTCASE(atoms) { send_format("''"); send_format("'a'"); send_format("'A'"); send_format("'abc'"); send_format("'Abc'"); send_format("'ab@c'"); send_format("'The rain in Spain stays mainly in the plains'"); send_format("a"); send_format("ab"); send_format("abc"); send_format("ab@c"); send_format(" abcdefghijklmnopq "); send_format2("~a", ""); send_format2("~a", "a"); send_format2("~a", "A"); send_format2("~a", "abc"); send_format2("~a", "Abc"); send_format2("~a", "ab@c"); send_format2("~a", "The rain in Spain stays mainly in the plains"); send_format2("~a", "a"); send_format2("~a", "ab"); send_format2("~a", "abc"); send_format2("~a","ab@c"); send_format2("~a", " abcdefghijklmnopq "); report(1); } TESTCASE(tuples) { send_format("{}"); send_format("{a}"); send_format("{a, b}"); send_format("{a, b, c}"); send_format("{1}"); send_format("{[]}"); send_format("{[], []}"); send_format("{[], a, b, c}"); send_format("{[], a, [], b, c}"); send_format("{[], a, '', b, c}"); report(1); } TESTCASE(lists) { /* FIXME cases to add? ETERM* a; ETERM* b; ETERM* c; */ ei_x_buff x; static char str[65537]; send_format("[]"); send_format("[a]"); send_format("[a, b]"); send_format("[a, b, c]"); send_format("[1]"); send_format("[[]]"); send_format("[[], []]"); send_format("[[], a, b, c]"); send_format("[[], a, [], b, c]"); send_format("[[], a, '', b, c]"); send_format("[[x, 2], [y, 3], [z, 4]]"); send_format("[{a,b},{c,d}]"); /* OTP-4777 */ ei_x_new(&x); /* b = erl_format("[{addr, ~s, ~i}]", "E-street", 42); a = ei_format(x, "[{name, ~a}, {age, ~i}, {data, ~w}]", "Madonna", 21, b); send_bin_term(a); erl_free_term(b);*/ ei_x_format(&x, "[{pi, ~f}, {'cos(70)', ~f}]", (float)3.1415, (float)0.34202); send_bin_term(&x); x.index = 0; /* otherwise it'll send the previous term again */ ei_x_format(&x, "[[pi, ~d], ['cos(70)', ~d]]", 3.1415, 0.34202); send_bin_term(&x); /* a = erl_mk_float(3.1415); b = erl_mk_float(0.34202); send_bin_term(ei_format("[[pi, ~w], ['cos(70)', ~w]]", a, b)); erl_free_term(a); erl_free_term(b); a = erl_mk_float(3.1415); b = erl_mk_float(0.34202); c = erl_mk_empty_list(); send_bin_term(ei_format("[[~a, ~w], ~w, [~s, ~w]]", "pi", a, c, "cos(70)", b)); erl_free_term(a); erl_free_term(b); erl_free_term(c); */ x.index = 0; /* otherwise it'll send the previous term again */ ei_x_format(&x, "[~i]", -1); send_bin_term(&x); x.index = 0; ei_x_format(&x, "~s","hejsan"); send_bin_term(&x); memset(str,'A',65535); str[65535] = '\0'; str[65536] = '\0'; x.index = 0; ei_x_format(&x, "~s",str); send_bin_term(&x); str[65535] = 'A'; x.index = 0; ei_x_format(&x, "~s",str); send_bin_term(&x); free(x.buff); report(1); } TESTCASE(format_wo_ver) { /* OTP-6795 * make example with format_wo_ver */ ei_x_buff x; ei_x_new (&x); ei_x_format(&x, "[-1, +2, ~c, {~a,~s},{~a,~i}]", 'c', "a", "b", "c", 10); send_bin_term(&x); free(x.buff); report(1); }
apache-2.0
hwfwgrp/mbed
libraries/mbed/targets/cmsis/TARGET_STM/TARGET_STM32F1/stm32f1xx_hal_can.c
50
46355
/** ****************************************************************************** * @file stm32f1xx_hal_can.c * @author MCD Application Team * @version V1.0.0 * @date 15-December-2014 * @brief CAN HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Controller Area Network (CAN) peripheral: * + Initialization and de-initialization functions * + IO operation functions * + Peripheral Control functions * + Peripheral State and Error functions * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] (#) Enable the CAN controller interface clock using __HAL_RCC_CAN1_CLK_ENABLE() for CAN1 and __HAL_RCC_CAN2_CLK_ENABLE() for CAN2 -@- In case you are using CAN2 only, you have to enable the CAN1 clock. (#) CAN pins configuration (++) Enable the clock for the CAN GPIOs using the following function: __HAL_RCC_GPIOx_CLK_ENABLE(); (++) Connect and configure the involved CAN pins using the following function HAL_GPIO_Init(); (#) Initialise and configure the CAN using HAL_CAN_Init() function. (#) Transmit the desired CAN frame using HAL_CAN_Transmit() function. (#) Receive a CAN frame using HAL_CAN_Receive() function. *** Polling mode IO operation *** ================================= [..] (+) Start the CAN peripheral transmission and wait the end of this operation using HAL_CAN_Transmit(), at this stage user can specify the value of timeout according to his end application (+) Start the CAN peripheral reception and wait the end of this operation using HAL_CAN_Receive(), at this stage user can specify the value of timeout according to his end application *** Interrupt mode IO operation *** =================================== [..] (+) Start the CAN peripheral transmission using HAL_CAN_Transmit_IT() (+) Start the CAN peripheral reception using HAL_CAN_Receive_IT() (+) Use HAL_CAN_IRQHandler() called under the used CAN Interrupt subroutine (+) At CAN end of transmission HAL_CAN_TxCpltCallback() function is executed and user can add his own code by customization of function pointer HAL_CAN_TxCpltCallback (+) In case of CAN Error, HAL_CAN_ErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_CAN_ErrorCallback *** CAN HAL driver macros list *** ============================================= [..] Below the list of most used macros in CAN HAL driver. (+) __HAL_CAN_ENABLE_IT: Enable the specified CAN interrupts (+) __HAL_CAN_DISABLE_IT: Disable the specified CAN interrupts (+) __HAL_CAN_GET_IT_SOURCE: Check if the specified CAN interrupt source is enabled or disabled (+) __HAL_CAN_CLEAR_FLAG: Clear the CAN's pending flags (+) __HAL_CAN_GET_FLAG: Get the selected CAN's flag status [..] (@) You can refer to the CAN HAL driver header file for more useful macros @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal.h" #ifdef HAL_CAN_MODULE_ENABLED #if defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || \ defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) /** @addtogroup STM32F1xx_HAL_Driver * @{ */ /** @defgroup CAN CAN * @brief CAN driver modules * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup CAN_Private_Constants CAN Private Constants * @{ */ #define CAN_TIMEOUT_VALUE 10 #define CAN_TI0R_STID_BIT_POSITION ((uint32_t)21) /* Position of LSB bits STID in register CAN_TI0R */ #define CAN_TI0R_EXID_BIT_POSITION ((uint32_t) 3) /* Position of LSB bits EXID in register CAN_TI0R */ #define CAN_TDL0R_DATA0_BIT_POSITION ((uint32_t) 0) /* Position of LSB bits DATA0 in register CAN_TDL0R */ #define CAN_TDL0R_DATA1_BIT_POSITION ((uint32_t) 8) /* Position of LSB bits DATA1 in register CAN_TDL0R */ #define CAN_TDL0R_DATA2_BIT_POSITION ((uint32_t)16) /* Position of LSB bits DATA2 in register CAN_TDL0R */ #define CAN_TDL0R_DATA3_BIT_POSITION ((uint32_t)24) /* Position of LSB bits DATA3 in register CAN_TDL0R */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static HAL_StatusTypeDef CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber); static HAL_StatusTypeDef CAN_Transmit_IT(CAN_HandleTypeDef* hcan); /* Exported functions ---------------------------------------------------------*/ /** @defgroup CAN_Exported_Functions CAN Exported Functions * @{ */ /** @defgroup CAN_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim ============================================================================== ##### Initialization and de-initialization functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Initialize and configure the CAN. (+) De-initialize the CAN. @endverbatim * @{ */ /** * @brief Initializes the CAN peripheral according to the specified * parameters in the CAN_InitStruct. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval HAL status */ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan) { uint32_t status = CAN_INITSTATUS_FAILED; /* Default init status */ uint32_t tickstart = 0; uint32_t tmp_mcr = 0; /* Check CAN handle */ if(hcan == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_CAN_ALL_INSTANCE(hcan->Instance)); assert_param(IS_FUNCTIONAL_STATE(hcan->Init.TTCM)); assert_param(IS_FUNCTIONAL_STATE(hcan->Init.ABOM)); assert_param(IS_FUNCTIONAL_STATE(hcan->Init.AWUM)); assert_param(IS_FUNCTIONAL_STATE(hcan->Init.NART)); assert_param(IS_FUNCTIONAL_STATE(hcan->Init.RFLM)); assert_param(IS_FUNCTIONAL_STATE(hcan->Init.TXFP)); assert_param(IS_CAN_MODE(hcan->Init.Mode)); assert_param(IS_CAN_SJW(hcan->Init.SJW)); assert_param(IS_CAN_BS1(hcan->Init.BS1)); assert_param(IS_CAN_BS2(hcan->Init.BS2)); assert_param(IS_CAN_PRESCALER(hcan->Init.Prescaler)); if(hcan->State == HAL_CAN_STATE_RESET) { /* Allocate lock resource and initialize it */ hcan-> Lock = HAL_UNLOCKED; /* Init the low level hardware */ HAL_CAN_MspInit(hcan); } /* Initialize the CAN state*/ hcan->State = HAL_CAN_STATE_BUSY; /* Exit from sleep mode */ CLEAR_BIT(hcan->Instance->MCR, CAN_MCR_SLEEP); /* Request initialisation */ SET_BIT(hcan->Instance->MCR, CAN_MCR_INRQ); /* Get timeout */ tickstart = HAL_GetTick(); /* Wait the acknowledge */ while(HAL_IS_BIT_CLR(hcan->Instance->MSR, CAN_MSR_INAK)) { if((HAL_GetTick()-tickstart) > CAN_TIMEOUT_VALUE) { hcan->State= HAL_CAN_STATE_TIMEOUT; /* Process unlocked */ __HAL_UNLOCK(hcan); return HAL_TIMEOUT; } } /* Check acknowledge */ if ((hcan->Instance->MSR & CAN_MSR_INAK) == CAN_MSR_INAK) { /* Set the time triggered communication mode */ if (hcan->Init.TTCM == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_TTCM); } /* Set the automatic bus-off management */ if (hcan->Init.ABOM == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_ABOM); } /* Set the automatic wake-up mode */ if (hcan->Init.AWUM == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_AWUM); } /* Set the no automatic retransmission */ if (hcan->Init.NART == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_NART); } /* Set the receive FIFO locked mode */ if (hcan->Init.RFLM == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_RFLM); } /* Set the transmit FIFO priority */ if (hcan->Init.TXFP == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_TXFP); } /* Update register MCR */ MODIFY_REG(hcan->Instance->MCR, CAN_MCR_TTCM | CAN_MCR_ABOM | CAN_MCR_AWUM | CAN_MCR_NART | CAN_MCR_RFLM | CAN_MCR_TXFP, tmp_mcr); /* Set the bit timing register */ WRITE_REG(hcan->Instance->BTR, (uint32_t)(hcan->Init.Mode | hcan->Init.SJW | hcan->Init.BS1 | hcan->Init.BS2 | (hcan->Init.Prescaler - 1) )); /* Request leave initialisation */ CLEAR_BIT(hcan->Instance->MCR, CAN_MCR_INRQ); /* Get timeout */ tickstart = HAL_GetTick(); /* Wait the acknowledge */ while(HAL_IS_BIT_CLR(hcan->Instance->MSR, CAN_MSR_INAK)) { if((HAL_GetTick()-tickstart) > CAN_TIMEOUT_VALUE) { hcan->State= HAL_CAN_STATE_TIMEOUT; /* Process unlocked */ __HAL_UNLOCK(hcan); return HAL_TIMEOUT; } } /* Check acknowledged */ if (HAL_IS_BIT_SET(hcan->Instance->MSR, CAN_MSR_INAK)) { status = CAN_INITSTATUS_SUCCESS; } } if(status == CAN_INITSTATUS_SUCCESS) { /* Set CAN error code to none */ hcan->ErrorCode = HAL_CAN_ERROR_NONE; /* Initialize the CAN state */ hcan->State = HAL_CAN_STATE_READY; /* Return function status */ return HAL_OK; } else { /* Initialize the CAN state */ hcan->State = HAL_CAN_STATE_ERROR; /* Return function status */ return HAL_ERROR; } } /** * @brief Configures the CAN reception filter according to the specified * parameters in the CAN_FilterInitStruct. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @param sFilterConfig: pointer to a CAN_FilterConfTypeDef structure that * contains the filter configuration information. * @retval None */ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTypeDef* sFilterConfig) { uint32_t filternbrbitpos = 0; /* Check the parameters */ assert_param(IS_CAN_FILTER_NUMBER(sFilterConfig->FilterNumber)); assert_param(IS_CAN_FILTER_MODE(sFilterConfig->FilterMode)); assert_param(IS_CAN_FILTER_SCALE(sFilterConfig->FilterScale)); assert_param(IS_CAN_FILTER_FIFO(sFilterConfig->FilterFIFOAssignment)); assert_param(IS_FUNCTIONAL_STATE(sFilterConfig->FilterActivation)); assert_param(IS_CAN_BANKNUMBER(sFilterConfig->BankNumber)); filternbrbitpos = ((uint32_t)1) << sFilterConfig->FilterNumber; /* Initialisation mode for the filter */ /* Select the start slave bank */ MODIFY_REG(hcan->Instance->FMR , CAN_FMR_CAN2SB , CAN_FMR_FINIT | (uint32_t)(sFilterConfig->BankNumber << 8) ); /* Filter Deactivation */ CLEAR_BIT(hcan->Instance->FA1R, filternbrbitpos); /* Filter Scale */ if (sFilterConfig->FilterScale == CAN_FILTERSCALE_16BIT) { /* 16-bit scale for the filter */ CLEAR_BIT(hcan->Instance->FS1R, filternbrbitpos); /* First 16-bit identifier and First 16-bit mask */ /* Or First 16-bit identifier and Second 16-bit identifier */ hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR1 = ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdLow) << 16) | (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdLow); /* Second 16-bit identifier and Second 16-bit mask */ /* Or Third 16-bit identifier and Fourth 16-bit identifier */ hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR2 = ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16) | (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdHigh); } if (sFilterConfig->FilterScale == CAN_FILTERSCALE_32BIT) { /* 32-bit scale for the filter */ SET_BIT(hcan->Instance->FS1R, filternbrbitpos); /* 32-bit identifier or First 32-bit identifier */ hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR1 = ((0x0000FFFF & (uint32_t)sFilterConfig->FilterIdHigh) << 16) | (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdLow); /* 32-bit mask or Second 32-bit identifier */ hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR2 = ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16) | (0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdLow); } /* Filter Mode */ if (sFilterConfig->FilterMode == CAN_FILTERMODE_IDMASK) { /*Id/Mask mode for the filter*/ CLEAR_BIT(hcan->Instance->FM1R, filternbrbitpos); } else /* CAN_FilterInitStruct->CAN_FilterMode == CAN_FilterMode_IdList */ { /*Identifier list mode for the filter*/ SET_BIT(hcan->Instance->FM1R, filternbrbitpos); } /* Filter FIFO assignment */ if (sFilterConfig->FilterFIFOAssignment == CAN_FILTER_FIFO0) { /* FIFO 0 assignation for the filter */ CLEAR_BIT(hcan->Instance->FFA1R, filternbrbitpos); } else { /* FIFO 1 assignation for the filter */ SET_BIT(hcan->Instance->FFA1R, filternbrbitpos); } /* Filter activation */ if (sFilterConfig->FilterActivation == ENABLE) { SET_BIT(hcan->Instance->FA1R, filternbrbitpos); } /* Leave the initialisation mode for the filter */ CLEAR_BIT(hcan->Instance->FMR, ((uint32_t)CAN_FMR_FINIT)); /* Return function status */ return HAL_OK; } /** * @brief Deinitializes the CANx peripheral registers to their default reset values. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval HAL status */ HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef* hcan) { /* Check CAN handle */ if(hcan == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_CAN_ALL_INSTANCE(hcan->Instance)); /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY; /* DeInit the low level hardware */ HAL_CAN_MspDeInit(hcan); /* Change CAN state */ hcan->State = HAL_CAN_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(hcan); /* Return function status */ return HAL_OK; } /** * @brief Initializes the CAN MSP. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval None */ __weak void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan) { /* NOTE : This function Should not be modified, when the callback is needed, the HAL_CAN_MspInit can be implemented in the user file */ } /** * @brief DeInitializes the CAN MSP. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval None */ __weak void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan) { /* NOTE : This function Should not be modified, when the callback is needed, the HAL_CAN_MspDeInit can be implemented in the user file */ } /** * @} */ /** @defgroup CAN_Exported_Functions_Group2 Input and Output operation functions * @brief I/O operation functions * @verbatim ============================================================================== ##### IO operation functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Transmit a CAN frame message. (+) Receive a CAN frame message. (+) Enter CAN peripheral in sleep mode. (+) Wake up the CAN peripheral from sleep mode. @endverbatim * @{ */ /** * @brief Initiates and transmits a CAN frame message. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @param Timeout: Specify Timeout value * @retval HAL status */ HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef* hcan, uint32_t Timeout) { uint32_t transmitmailbox = CAN_TXSTATUS_NOMAILBOX; uint32_t tickstart = 0; /* Check the parameters */ assert_param(IS_CAN_IDTYPE(hcan->pTxMsg->IDE)); assert_param(IS_CAN_RTR(hcan->pTxMsg->RTR)); assert_param(IS_CAN_DLC(hcan->pTxMsg->DLC)); /* Process locked */ __HAL_LOCK(hcan); if(hcan->State == HAL_CAN_STATE_BUSY_RX) { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_TX_RX; } else { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_TX; } /* Select one empty transmit mailbox */ if (HAL_IS_BIT_SET(hcan->Instance->TSR, CAN_TSR_TME0)) { transmitmailbox = 0; } else if (HAL_IS_BIT_SET(hcan->Instance->TSR, CAN_TSR_TME1)) { transmitmailbox = 1; } else if (HAL_IS_BIT_SET(hcan->Instance->TSR, CAN_TSR_TME2)) { transmitmailbox = 2; } else { transmitmailbox = CAN_TXSTATUS_NOMAILBOX; } if (transmitmailbox != CAN_TXSTATUS_NOMAILBOX) { /* Set up the Id */ hcan->Instance->sTxMailBox[transmitmailbox].TIR &= CAN_TI0R_TXRQ; if (hcan->pTxMsg->IDE == CAN_ID_STD) { assert_param(IS_CAN_STDID(hcan->pTxMsg->StdId)); hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << CAN_TI0R_STID_BIT_POSITION) | hcan->pTxMsg->RTR); } else { assert_param(IS_CAN_EXTID(hcan->pTxMsg->ExtId)); hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << CAN_TI0R_EXID_BIT_POSITION) | hcan->pTxMsg->IDE | hcan->pTxMsg->RTR); } /* Set up the DLC */ hcan->pTxMsg->DLC &= (uint8_t)0x0000000F; hcan->Instance->sTxMailBox[transmitmailbox].TDTR &= (uint32_t)0xFFFFFFF0; hcan->Instance->sTxMailBox[transmitmailbox].TDTR |= hcan->pTxMsg->DLC; /* Set up the data field */ WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDLR, ((uint32_t)hcan->pTxMsg->Data[3] << CAN_TDL0R_DATA3_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[2] << CAN_TDL0R_DATA2_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[1] << CAN_TDL0R_DATA1_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[0] << CAN_TDL0R_DATA0_BIT_POSITION) ); WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDHR, ((uint32_t)hcan->pTxMsg->Data[7] << CAN_TDL0R_DATA3_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[6] << CAN_TDL0R_DATA2_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[5] << CAN_TDL0R_DATA1_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[4] << CAN_TDL0R_DATA0_BIT_POSITION) ); /* Request transmission */ SET_BIT(hcan->Instance->sTxMailBox[transmitmailbox].TIR, CAN_TI0R_TXRQ); /* Get timeout */ tickstart = HAL_GetTick(); /* Check End of transmission flag */ while(!(__HAL_CAN_TRANSMIT_STATUS(hcan, transmitmailbox))) { /* Check for the Timeout */ if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0) || ((HAL_GetTick()-tickstart) > Timeout)) { hcan->State = HAL_CAN_STATE_TIMEOUT; /* Process unlocked */ __HAL_UNLOCK(hcan); return HAL_TIMEOUT; } } } if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_RX; /* Process unlocked */ __HAL_UNLOCK(hcan); } else { /* Change CAN state */ hcan->State = HAL_CAN_STATE_READY; } /* Process unlocked */ __HAL_UNLOCK(hcan); /* Return function status */ return HAL_OK; } else { /* Change CAN state */ hcan->State = HAL_CAN_STATE_ERROR; /* Process unlocked */ __HAL_UNLOCK(hcan); /* Return function status */ return HAL_ERROR; } } /** * @brief Initiates and transmits a CAN frame message. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval HAL status */ HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef* hcan) { uint32_t transmitmailbox = CAN_TXSTATUS_NOMAILBOX; /* Check the parameters */ assert_param(IS_CAN_IDTYPE(hcan->pTxMsg->IDE)); assert_param(IS_CAN_RTR(hcan->pTxMsg->RTR)); assert_param(IS_CAN_DLC(hcan->pTxMsg->DLC)); if((hcan->State == HAL_CAN_STATE_READY) || (hcan->State == HAL_CAN_STATE_BUSY_RX)) { /* Process Locked */ __HAL_LOCK(hcan); /* Select one empty transmit mailbox */ if(HAL_IS_BIT_SET(hcan->Instance->TSR, CAN_TSR_TME0)) { transmitmailbox = 0; } else if(HAL_IS_BIT_SET(hcan->Instance->TSR, CAN_TSR_TME1)) { transmitmailbox = 1; } else if(HAL_IS_BIT_SET(hcan->Instance->TSR, CAN_TSR_TME2)) { transmitmailbox = 2; } else { transmitmailbox = CAN_TXSTATUS_NOMAILBOX; } if(transmitmailbox != CAN_TXSTATUS_NOMAILBOX) { /* Set up the Id */ hcan->Instance->sTxMailBox[transmitmailbox].TIR &= CAN_TI0R_TXRQ; if (hcan->pTxMsg->IDE == CAN_ID_STD) { assert_param(IS_CAN_STDID(hcan->pTxMsg->StdId)); hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << CAN_TI0R_STID_BIT_POSITION) | hcan->pTxMsg->RTR); } else { assert_param(IS_CAN_EXTID(hcan->pTxMsg->ExtId)); hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << CAN_TI0R_EXID_BIT_POSITION) | hcan->pTxMsg->IDE | hcan->pTxMsg->RTR); } /* Set up the DLC */ hcan->pTxMsg->DLC &= (uint8_t)0x0000000F; hcan->Instance->sTxMailBox[transmitmailbox].TDTR &= (uint32_t)0xFFFFFFF0; hcan->Instance->sTxMailBox[transmitmailbox].TDTR |= hcan->pTxMsg->DLC; /* Set up the data field */ WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDLR, ((uint32_t)hcan->pTxMsg->Data[3] << CAN_TDL0R_DATA3_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[2] << CAN_TDL0R_DATA2_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[1] << CAN_TDL0R_DATA1_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[0] << CAN_TDL0R_DATA0_BIT_POSITION) ); WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDHR, ((uint32_t)hcan->pTxMsg->Data[7] << CAN_TDL0R_DATA3_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[6] << CAN_TDL0R_DATA2_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[5] << CAN_TDL0R_DATA1_BIT_POSITION) | ((uint32_t)hcan->pTxMsg->Data[4] << CAN_TDL0R_DATA0_BIT_POSITION) ); if(hcan->State == HAL_CAN_STATE_BUSY_RX) { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_TX_RX; } else { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_TX; } /* Set CAN error code to none */ hcan->ErrorCode = HAL_CAN_ERROR_NONE; /* Process Unlocked */ __HAL_UNLOCK(hcan); /* Enable interrupts: */ /* - Enable Error warning Interrupt */ /* - Enable Error passive Interrupt */ /* - Enable Bus-off Interrupt */ /* - Enable Last error code Interrupt */ /* - Enable Error Interrupt */ /* - Enable Transmit mailbox empty Interrupt */ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EWG | CAN_IT_EPV | CAN_IT_BOF | CAN_IT_LEC | CAN_IT_ERR | CAN_IT_TME ); /* Request transmission */ hcan->Instance->sTxMailBox[transmitmailbox].TIR |= CAN_TI0R_TXRQ; } } else { return HAL_BUSY; } return HAL_OK; } /** * @brief Receives a correct CAN frame. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @param FIFONumber: FIFO Number value * @param Timeout: Specify Timeout value * @retval HAL status * @retval None */ HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef* hcan, uint8_t FIFONumber, uint32_t Timeout) { uint32_t tickstart = 0; /* Check the parameters */ assert_param(IS_CAN_FIFO(FIFONumber)); /* Process locked */ __HAL_LOCK(hcan); if(hcan->State == HAL_CAN_STATE_BUSY_TX) { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_TX_RX; } else { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_RX; } /* Get tick */ tickstart = HAL_GetTick(); /* Check pending message */ while(__HAL_CAN_MSG_PENDING(hcan, FIFONumber) == 0) { /* Check for the Timeout */ if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0) || ((HAL_GetTick()-tickstart) > Timeout)) { hcan->State = HAL_CAN_STATE_TIMEOUT; /* Process unlocked */ __HAL_UNLOCK(hcan); return HAL_TIMEOUT; } } } /* Get the Id */ hcan->pRxMsg->IDE = (uint8_t)CAN_ID_EXT & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; if (hcan->pRxMsg->IDE == CAN_ID_STD) { hcan->pRxMsg->StdId = (uint32_t)0x000007FF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 21); } else { hcan->pRxMsg->ExtId = (uint32_t)0x1FFFFFFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 3); } hcan->pRxMsg->RTR = (uint8_t)CAN_RTR_REMOTE & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; /* Get the DLC */ hcan->pRxMsg->DLC = (uint8_t)0x0F & hcan->Instance->sFIFOMailBox[FIFONumber].RDTR; /* Get the FMI */ hcan->pRxMsg->FMI = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDTR >> 8); /* Get the data field */ hcan->pRxMsg->Data[0] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDLR; hcan->pRxMsg->Data[1] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 8); hcan->pRxMsg->Data[2] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 16); hcan->pRxMsg->Data[3] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 24); hcan->pRxMsg->Data[4] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDHR; hcan->pRxMsg->Data[5] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 8); hcan->pRxMsg->Data[6] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 16); hcan->pRxMsg->Data[7] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 24); /* Release the FIFO */ if(FIFONumber == CAN_FIFO0) { /* Release FIFO0 */ __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO0); } else /* FIFONumber == CAN_FIFO1 */ { /* Release FIFO1 */ __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO1); } if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_TX; } else { /* Change CAN state */ hcan->State = HAL_CAN_STATE_READY; } /* Process unlocked */ __HAL_UNLOCK(hcan); /* Return function status */ return HAL_OK; } /** * @brief Receives a correct CAN frame. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @param FIFONumber: Specify the FIFO number * @retval HAL status * @retval None */ HAL_StatusTypeDef HAL_CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber) { /* Check the parameters */ assert_param(IS_CAN_FIFO(FIFONumber)); if((hcan->State == HAL_CAN_STATE_READY) || (hcan->State == HAL_CAN_STATE_BUSY_TX)) { /* Process locked */ __HAL_LOCK(hcan); if(hcan->State == HAL_CAN_STATE_BUSY_TX) { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_TX_RX; } else { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_RX; } /* Set CAN error code to none */ hcan->ErrorCode = HAL_CAN_ERROR_NONE; /* Enable interrupts: */ /* - Enable Error warning Interrupt */ /* - Enable Error passive Interrupt */ /* - Enable Bus-off Interrupt */ /* - Enable Last error code Interrupt */ /* - Enable Error Interrupt */ /* - Enable Transmit mailbox empty Interrupt */ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EWG | CAN_IT_EPV | CAN_IT_BOF | CAN_IT_LEC | CAN_IT_ERR | CAN_IT_TME ); /* Process unlocked */ __HAL_UNLOCK(hcan); if(FIFONumber == CAN_FIFO0) { /* Enable FIFO 0 message pending Interrupt */ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_FMP0); } else { /* Enable FIFO 1 message pending Interrupt */ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_FMP1); } } else { return HAL_BUSY; } /* Return function status */ return HAL_OK; } /** * @brief Enters the Sleep (low power) mode. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval HAL status. */ HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef* hcan) { uint32_t tickstart = 0; /* Process locked */ __HAL_LOCK(hcan); /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY; /* Request Sleep mode */ MODIFY_REG(hcan->Instance->MCR, CAN_MCR_INRQ , CAN_MCR_SLEEP ); /* Sleep mode status */ if (HAL_IS_BIT_CLR(hcan->Instance->MSR, CAN_MSR_SLAK) || HAL_IS_BIT_SET(hcan->Instance->MSR, CAN_MSR_INAK) ) { /* Process unlocked */ __HAL_UNLOCK(hcan); /* Return function status */ return HAL_ERROR; } /* Get tick */ tickstart = HAL_GetTick(); /* Wait the acknowledge */ while (HAL_IS_BIT_CLR(hcan->Instance->MSR, CAN_MSR_SLAK) || HAL_IS_BIT_SET(hcan->Instance->MSR, CAN_MSR_INAK) ) { if((HAL_GetTick()-tickstart) > CAN_TIMEOUT_VALUE) { hcan->State = HAL_CAN_STATE_TIMEOUT; /* Process unlocked */ __HAL_UNLOCK(hcan); return HAL_TIMEOUT; } } /* Change CAN state */ hcan->State = HAL_CAN_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(hcan); /* Return function status */ return HAL_OK; } /** * @brief Wakes up the CAN peripheral from sleep mode, after that the CAN peripheral * is in the normal mode. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval HAL status. */ HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef* hcan) { uint32_t tickstart = 0; /* Process locked */ __HAL_LOCK(hcan); /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY; /* Wake up request */ CLEAR_BIT(hcan->Instance->MCR, CAN_MCR_SLEEP); /* Get timeout */ tickstart = HAL_GetTick(); /* Sleep mode status */ while((hcan->Instance->MSR & CAN_MSR_SLAK) == CAN_MSR_SLAK) { if((HAL_GetTick()-tickstart) > CAN_TIMEOUT_VALUE) { hcan->State= HAL_CAN_STATE_TIMEOUT; /* Process unlocked */ __HAL_UNLOCK(hcan); return HAL_TIMEOUT; } } if(HAL_IS_BIT_SET(hcan->Instance->MSR, CAN_MSR_SLAK)) { /* Process unlocked */ __HAL_UNLOCK(hcan); /* Return function status */ return HAL_ERROR; } /* Change CAN state */ hcan->State = HAL_CAN_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(hcan); /* Return function status */ return HAL_OK; } /** * @brief Handles CAN interrupt request * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval None */ void HAL_CAN_IRQHandler(CAN_HandleTypeDef* hcan) { /* Check End of transmission flag */ if(__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_TME)) { if((__HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_0)) || (__HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_1)) || (__HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_2))) { /* Call transmit function */ CAN_Transmit_IT(hcan); } } /* Check End of reception flag for FIFO0 */ if((__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FMP0)) && (__HAL_CAN_MSG_PENDING(hcan, CAN_FIFO0) != 0)) { /* Call receive function */ CAN_Receive_IT(hcan, CAN_FIFO0); } /* Check End of reception flag for FIFO1 */ if((__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FMP1)) && (__HAL_CAN_MSG_PENDING(hcan, CAN_FIFO1) != 0)) { /* Call receive function */ CAN_Receive_IT(hcan, CAN_FIFO1); } /* Check Error Warning Flag */ if((__HAL_CAN_GET_FLAG(hcan, CAN_FLAG_EWG)) && (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_EWG)) && (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) { /* Set CAN error code to EWG error */ hcan->ErrorCode |= HAL_CAN_ERROR_EWG; /* No need for clear of Error Warning Flag as read-only */ } /* Check Error Passive Flag */ if((__HAL_CAN_GET_FLAG(hcan, CAN_FLAG_EPV)) && (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_EPV)) && (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) { /* Set CAN error code to EPV error */ hcan->ErrorCode |= HAL_CAN_ERROR_EPV; /* No need for clear of Error Passive Flag as read-only */ } /* Check Bus-Off Flag */ if((__HAL_CAN_GET_FLAG(hcan, CAN_FLAG_BOF)) && (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_BOF)) && (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) { /* Set CAN error code to BOF error */ hcan->ErrorCode |= HAL_CAN_ERROR_BOF; /* No need for clear of Bus-Off Flag as read-only */ } /* Check Last error code Flag */ if((!HAL_IS_BIT_CLR(hcan->Instance->ESR, CAN_ESR_LEC)) && (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_LEC)) && (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) { switch(hcan->Instance->ESR & CAN_ESR_LEC) { case(CAN_ESR_LEC_0): /* Set CAN error code to STF error */ hcan->ErrorCode |= HAL_CAN_ERROR_STF; break; case(CAN_ESR_LEC_1): /* Set CAN error code to FOR error */ hcan->ErrorCode |= HAL_CAN_ERROR_FOR; break; case(CAN_ESR_LEC_1 | CAN_ESR_LEC_0): /* Set CAN error code to ACK error */ hcan->ErrorCode |= HAL_CAN_ERROR_ACK; break; case(CAN_ESR_LEC_2): /* Set CAN error code to BR error */ hcan->ErrorCode |= HAL_CAN_ERROR_BR; break; case(CAN_ESR_LEC_2 | CAN_ESR_LEC_0): /* Set CAN error code to BD error */ hcan->ErrorCode |= HAL_CAN_ERROR_BD; break; case(CAN_ESR_LEC_2 | CAN_ESR_LEC_1): /* Set CAN error code to CRC error */ hcan->ErrorCode |= HAL_CAN_ERROR_CRC; break; default: break; } /* Clear Last error code Flag */ CLEAR_BIT(hcan->Instance->ESR, CAN_ESR_LEC); } /* Call the Error call Back in case of Errors */ if(hcan->ErrorCode != HAL_CAN_ERROR_NONE) { /* Set the CAN state ready to be able to start again the process */ hcan->State = HAL_CAN_STATE_READY; /* Call Error callback function */ HAL_CAN_ErrorCallback(hcan); } } /** * @brief Transmission complete callback in non blocking mode * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval None */ __weak void HAL_CAN_TxCpltCallback(CAN_HandleTypeDef* hcan) { /* NOTE : This function Should not be modified, when the callback is needed, the HAL_CAN_TxCpltCallback can be implemented in the user file */ } /** * @brief Transmission complete callback in non blocking mode * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval None */ __weak void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan) { /* NOTE : This function Should not be modified, when the callback is needed, the HAL_CAN_RxCpltCallback can be implemented in the user file */ } /** * @brief Error CAN callback. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval None */ __weak void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan) { /* NOTE : This function Should not be modified, when the callback is needed, the HAL_CAN_ErrorCallback can be implemented in the user file */ } /** * @} */ /** @defgroup CAN_Exported_Functions_Group3 Peripheral State and Error functions * @brief CAN Peripheral State functions * @verbatim ============================================================================== ##### Peripheral State and Error functions ##### ============================================================================== [..] This subsection provides functions allowing to : (+) Check the CAN state. (+) Check CAN Errors detected during interrupt process @endverbatim * @{ */ /** * @brief return the CAN state * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval HAL state */ HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef* hcan) { /* Return CAN state */ return hcan->State; } /** * @brief Return the CAN error code * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval CAN Error Code */ uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan) { return hcan->ErrorCode; } /** * @} */ /** * @} */ /** @defgroup CAN_Private_Functions CAN Private Functions * @{ */ /** * @brief Initiates and transmits a CAN frame message. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval HAL status */ static HAL_StatusTypeDef CAN_Transmit_IT(CAN_HandleTypeDef* hcan) { /* Disable Transmit mailbox empty Interrupt */ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_TME); if(hcan->State == HAL_CAN_STATE_BUSY_TX) { /* Disable interrupts: */ /* - Disable Error warning Interrupt */ /* - Disable Error passive Interrupt */ /* - Disable Bus-off Interrupt */ /* - Disable Last error code Interrupt */ /* - Disable Error Interrupt */ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EWG | CAN_IT_EPV | CAN_IT_BOF | CAN_IT_LEC | CAN_IT_ERR ); } if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) { /* Change CAN state */ hcan->State = HAL_CAN_STATE_BUSY_RX; } else { /* Change CAN state */ hcan->State = HAL_CAN_STATE_READY; } /* Transmission complete callback */ HAL_CAN_TxCpltCallback(hcan); return HAL_OK; } /** * @brief Receives a correct CAN frame. * @param hcan: Pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @param FIFONumber: Specify the FIFO number * @retval HAL status * @retval None */ static HAL_StatusTypeDef CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber) { /* Get the Id */ hcan->pRxMsg->IDE = (uint8_t)0x04 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; if (hcan->pRxMsg->IDE == CAN_ID_STD) { hcan->pRxMsg->StdId = (uint32_t)0x000007FF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 21); } else { hcan->pRxMsg->ExtId = (uint32_t)0x1FFFFFFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 3); } hcan->pRxMsg->RTR = (uint8_t)0x02 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; /* Get the DLC */ hcan->pRxMsg->DLC = (uint8_t)0x0F & hcan->Instance->sFIFOMailBox[FIFONumber].RDTR; /* Get the FMI */ hcan->pRxMsg->FMI = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDTR >> 8); /* Get the data field */ hcan->pRxMsg->Data[0] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDLR; hcan->pRxMsg->Data[1] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 8); hcan->pRxMsg->Data[2] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 16); hcan->pRxMsg->Data[3] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 24); hcan->pRxMsg->Data[4] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDHR; hcan->pRxMsg->Data[5] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 8); hcan->pRxMsg->Data[6] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 16); hcan->pRxMsg->Data[7] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 24); /* Release the FIFO */ /* Release FIFO0 */ if (FIFONumber == CAN_FIFO0) { __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO0); /* Disable FIFO 0 message pending Interrupt */ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_FMP0); } /* Release FIFO1 */ else /* FIFONumber == CAN_FIFO1 */ { __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO1); /* Disable FIFO 1 message pending Interrupt */ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_FMP1); } if(hcan->State == HAL_CAN_STATE_BUSY_RX) { /* Disable interrupts: */ /* - Disable Error warning Interrupt */ /* - Disable Error passive Interrupt */ /* - Disable Bus-off Interrupt */ /* - Disable Last error code Interrupt */ /* - Disable Error Interrupt */ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EWG | CAN_IT_EPV | CAN_IT_BOF | CAN_IT_LEC | CAN_IT_ERR ); } if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) { /* Disable CAN state */ hcan->State = HAL_CAN_STATE_BUSY_TX; } else { /* Change CAN state */ hcan->State = HAL_CAN_STATE_READY; } /* Receive complete callback */ HAL_CAN_RxCpltCallback(hcan); /* Return function status */ return HAL_OK; } /** * @} */ /** * @} */ #endif /* STM32F103x6) || STM32F103xB || STM32F103xE || */ /* STM32F103xG) || STM32F105xC || STM32F107xC */ #endif /* HAL_CAN_MODULE_ENABLED */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
apache-2.0
andyqzb/twemproxy
src/event/nc_kqueue.c
56
10605
/* * twemproxy - A fast and lightweight proxy for memcached protocol. * Copyright (C) 2011 Twitter, 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. */ #include <nc_core.h> #ifdef NC_HAVE_KQUEUE #include <sys/event.h> struct event_base * event_base_create(int nevent, event_cb_t cb) { struct event_base *evb; int status, kq; struct kevent *change, *event; ASSERT(nevent > 0); kq = kqueue(); if (kq < 0) { log_error("kqueue failed: %s", strerror(errno)); return NULL; } change = nc_calloc(nevent, sizeof(*change)); if (change == NULL) { status = close(kq); if (status < 0) { log_error("close kq %d failed, ignored: %s", kq, strerror(errno)); } return NULL; } event = nc_calloc(nevent, sizeof(*event)); if (event == NULL) { nc_free(change); status = close(kq); if (status < 0) { log_error("close kq %d failed, ignored: %s", kq, strerror(errno)); } return NULL; } evb = nc_alloc(sizeof(*evb)); if (evb == NULL) { nc_free(change); nc_free(event); status = close(kq); if (status < 0) { log_error("close kq %d failed, ignored: %s", kq, strerror(errno)); } return NULL; } evb->kq = kq; evb->change = change; evb->nchange = 0; evb->event = event; evb->nevent = nevent; evb->nreturned = 0; evb->nprocessed = 0; evb->cb = cb; log_debug(LOG_INFO, "kq %d with nevent %d", evb->kq, evb->nevent); return evb; } void event_base_destroy(struct event_base *evb) { int status; if (evb == NULL) { return; } ASSERT(evb->kq > 0); nc_free(evb->change); nc_free(evb->event); status = close(evb->kq); if (status < 0) { log_error("close kq %d failed, ignored: %s", evb->kq, strerror(errno)); } evb->kq = -1; nc_free(evb); } int event_add_in(struct event_base *evb, struct conn *c) { struct kevent *event; ASSERT(evb->kq > 0); ASSERT(c != NULL); ASSERT(c->sd > 0); ASSERT(evb->nchange < evb->nevent); if (c->recv_active) { return 0; } event = &evb->change[evb->nchange++]; EV_SET(event, c->sd, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, c); c->recv_active = 1; return 0; } int event_del_in(struct event_base *evb, struct conn *c) { struct kevent *event; ASSERT(evb->kq > 0); ASSERT(c != NULL); ASSERT(c->sd > 0); ASSERT(evb->nchange < evb->nevent); if (!c->recv_active) { return 0; } event = &evb->change[evb->nchange++]; EV_SET(event, c->sd, EVFILT_READ, EV_DELETE, 0, 0, c); c->recv_active = 0; return 0; } int event_add_out(struct event_base *evb, struct conn *c) { struct kevent *event; ASSERT(evb->kq > 0); ASSERT(c != NULL); ASSERT(c->sd > 0); ASSERT(c->recv_active); ASSERT(evb->nchange < evb->nevent); if (c->send_active) { return 0; } event = &evb->change[evb->nchange++]; EV_SET(event, c->sd, EVFILT_WRITE, EV_ADD | EV_CLEAR, 0, 0, c); c->send_active = 1; return 0; } int event_del_out(struct event_base *evb, struct conn *c) { struct kevent *event; ASSERT(evb->kq > 0); ASSERT(c != NULL); ASSERT(c->sd > 0); ASSERT(c->recv_active); ASSERT(evb->nchange < evb->nevent); if (!c->send_active) { return 0; } event = &evb->change[evb->nchange++]; EV_SET(event, c->sd, EVFILT_WRITE, EV_DELETE, 0, 0, c); c->send_active = 0; return 0; } int event_add_conn(struct event_base *evb, struct conn *c) { ASSERT(evb->kq > 0); ASSERT(c != NULL); ASSERT(c->sd > 0); ASSERT(!c->recv_active); ASSERT(!c->send_active); ASSERT(evb->nchange < evb->nevent); event_add_in(evb, c); event_add_out(evb, c); return 0; } int event_del_conn(struct event_base *evb, struct conn *c) { int i; ASSERT(evb->kq > 0); ASSERT(c != NULL); ASSERT(c->sd > 0); ASSERT(evb->nchange < evb->nevent); event_del_out(evb, c); event_del_in(evb, c); /* * Now, eliminate pending events for c->sd (there should be at most one * other event). This is important because we will close c->sd and free * c when we return. */ for (i = evb->nprocessed + 1; i < evb->nreturned; i++) { struct kevent *ev = &evb->event[i]; if (ev->ident == (uintptr_t)c->sd) { ev->flags = 0; ev->filter = 0; break; } } return 0; } int event_wait(struct event_base *evb, int timeout) { int kq = evb->kq; struct timespec ts, *tsp; ASSERT(kq > 0); /* kevent should block indefinitely if timeout < 0 */ if (timeout < 0) { tsp = NULL; } else { tsp = &ts; tsp->tv_sec = timeout / 1000LL; tsp->tv_nsec = (timeout % 1000LL) * 1000000LL; } for (;;) { /* * kevent() is used both to register new events with kqueue, and to * retrieve any pending events. Changes that should be applied to the * kqueue are given in the change[] and any returned events are placed * in event[], up to the maximum sized allowed by nevent. The number * of entries actually placed in event[] is returned by the kevent() * call and saved in nreturned. * * Events are registered with the system by the application via a * struct kevent, and an event is uniquely identified with the system * by a (kq, ident, filter) tuple. This means that there can be only * one (ident, filter) pair for a given kqueue. */ evb->nreturned = kevent(kq, evb->change, evb->nchange, evb->event, evb->nevent, tsp); evb->nchange = 0; if (evb->nreturned > 0) { for (evb->nprocessed = 0; evb->nprocessed < evb->nreturned; evb->nprocessed++) { struct kevent *ev = &evb->event[evb->nprocessed]; uint32_t events = 0; log_debug(LOG_VVERB, "kevent %04"PRIX32" with filter %d " "triggered on sd %d", ev->flags, ev->filter, ev->ident); /* * If an error occurs while processing an element of the * change[] and there is enough room in the event[], then the * event event will be placed in the eventlist with EV_ERROR * set in flags and the system error(errno) in data. */ if (ev->flags & EV_ERROR) { /* * Error messages that can happen, when a delete fails. * EBADF happens when the file descriptor has been closed * ENOENT when the file descriptor was closed and then * reopened. * EINVAL for some reasons not understood; EINVAL * should not be returned ever; but FreeBSD does :-\ * An error is also indicated when a callback deletes an * event we are still processing. In that case the data * field is set to ENOENT. */ if (ev->data == EBADF || ev->data == EINVAL || ev->data == ENOENT || ev->data == EINTR) { continue; } events |= EVENT_ERR; } if (ev->filter == EVFILT_READ) { events |= EVENT_READ; } if (ev->filter == EVFILT_WRITE) { events |= EVENT_WRITE; } if (evb->cb != NULL && events != 0) { evb->cb(ev->udata, events); } } return evb->nreturned; } if (evb->nreturned == 0) { if (timeout == -1) { log_error("kevent on kq %d with %d events and %d timeout " "returned no events", kq, evb->nevent, timeout); return -1; } return 0; } if (errno == EINTR) { continue; } log_error("kevent on kq %d with %d events failed: %s", kq, evb->nevent, strerror(errno)); return -1; } NOT_REACHED(); } void event_loop_stats(event_stats_cb_t cb, void *arg) { struct stats *st = arg; int status, kq; struct kevent change, event; struct timespec ts, *tsp; kq = kqueue(); if (kq < 0) { log_error("kqueue failed: %s", strerror(errno)); return; } EV_SET(&change, st->sd, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, NULL); /* kevent should block indefinitely if st->interval < 0 */ if (st->interval < 0) { tsp = NULL; } else { tsp = &ts; tsp->tv_sec = st->interval / 1000LL; tsp->tv_nsec = (st->interval % 1000LL) * 1000000LL; } for (;;) { int nreturned; nreturned = kevent(kq, &change, 1, &event, 1, tsp); if (nreturned < 0) { if (errno == EINTR) { continue; } log_error("kevent on kq %d with m %d failed: %s", kq, st->sd, strerror(errno)); goto error; } ASSERT(nreturned <= 1); if (nreturned == 1) { struct kevent *ev = &event; if (ev->flags & EV_ERROR) { if (ev->data == EINTR) { continue; } log_error("kevent on kq %d with m %d failed: %s", kq, st->sd, strerror(ev->data)); goto error; } } cb(st, &nreturned); } error: status = close(kq); if (status < 0) { log_error("close kq %d failed, ignored: %s", kq, strerror(errno)); } kq = -1; } #endif /* NC_HAVE_KQUEUE */
apache-2.0
sergecodd/FireFox-OS
B2G/external/bluetooth/bluez/audio/media.c
56
17745
/* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2006-2007 Nokia Corporation * Copyright (C) 2004-2009 Marcel Holtmann <marcel@holtmann.org> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <errno.h> #include <glib.h> #include <gdbus.h> #include "../src/adapter.h" #include "../src/dbus-common.h" #include "log.h" #include "error.h" #include "device.h" #include "avdtp.h" #include "media.h" #include "transport.h" #include "a2dp.h" #include "headset.h" #include "manager.h" #ifndef DBUS_TYPE_UNIX_FD #define DBUS_TYPE_UNIX_FD -1 #endif #define MEDIA_INTERFACE "org.bluez.Media" #define MEDIA_ENDPOINT_INTERFACE "org.bluez.MediaEndpoint" #define REQUEST_TIMEOUT (3 * 1000) /* 3 seconds */ struct media_adapter { bdaddr_t src; /* Adapter address */ char *path; /* Adapter path */ DBusConnection *conn; /* Adapter connection */ GSList *endpoints; /* Endpoints list */ }; struct endpoint_request { DBusMessage *msg; DBusPendingCall *call; media_endpoint_cb_t cb; void *user_data; }; struct media_endpoint { struct a2dp_sep *sep; char *sender; /* Endpoint DBus bus id */ char *path; /* Endpoint object path */ char *uuid; /* Endpoint property UUID */ uint8_t codec; /* Endpoint codec */ uint8_t *capabilities; /* Endpoint property capabilities */ size_t size; /* Endpoint capabilities size */ guint hs_watch; guint watch; struct endpoint_request *request; struct media_transport *transport; struct media_adapter *adapter; }; static GSList *adapters = NULL; static void endpoint_request_free(struct endpoint_request *request) { if (request->call) dbus_pending_call_unref(request->call); dbus_message_unref(request->msg); g_free(request); } static void media_endpoint_cancel(struct media_endpoint *endpoint) { struct endpoint_request *request = endpoint->request; if (request->call) dbus_pending_call_cancel(request->call); endpoint_request_free(request); endpoint->request = NULL; } static void media_endpoint_remove(struct media_endpoint *endpoint) { struct media_adapter *adapter = endpoint->adapter; if (g_slist_find(adapter->endpoints, endpoint) == NULL) return; info("Endpoint unregistered: sender=%s path=%s", endpoint->sender, endpoint->path); adapter->endpoints = g_slist_remove(adapter->endpoints, endpoint); if (endpoint->sep) a2dp_remove_sep(endpoint->sep); if (endpoint->hs_watch) headset_remove_state_cb(endpoint->hs_watch); if (endpoint->request) media_endpoint_cancel(endpoint); if (endpoint->transport) media_transport_destroy(endpoint->transport); g_dbus_remove_watch(adapter->conn, endpoint->watch); g_free(endpoint->capabilities); g_free(endpoint->sender); g_free(endpoint->path); g_free(endpoint->uuid); g_free(endpoint); } static void media_endpoint_exit(DBusConnection *connection, void *user_data) { struct media_endpoint *endpoint = user_data; endpoint->watch = 0; media_endpoint_remove(endpoint); } static void headset_setconf_cb(struct media_endpoint *endpoint, void *ret, int size, void *user_data) { struct audio_device *dev = user_data; if (ret != NULL) return; headset_set_state(dev, HEADSET_STATE_DISCONNECTED); } static void headset_state_changed(struct audio_device *dev, headset_state_t old_state, headset_state_t new_state, void *user_data) { struct media_endpoint *endpoint = user_data; DBG(""); switch (new_state) { case HEADSET_STATE_DISCONNECTED: media_endpoint_clear_configuration(endpoint); break; case HEADSET_STATE_CONNECTING: media_endpoint_set_configuration(endpoint, dev, NULL, 0, headset_setconf_cb, dev); break; case HEADSET_STATE_CONNECTED: break; case HEADSET_STATE_PLAY_IN_PROGRESS: break; case HEADSET_STATE_PLAYING: break; } } static struct media_endpoint *media_endpoint_create(struct media_adapter *adapter, const char *sender, const char *path, const char *uuid, gboolean delay_reporting, uint8_t codec, uint8_t *capabilities, int size, int *err) { struct media_endpoint *endpoint; endpoint = g_new0(struct media_endpoint, 1); endpoint->sender = g_strdup(sender); endpoint->path = g_strdup(path); endpoint->uuid = g_strdup(uuid); endpoint->codec = codec; if (size > 0) { endpoint->capabilities = g_new(uint8_t, size); memcpy(endpoint->capabilities, capabilities, size); endpoint->size = size; } endpoint->adapter = adapter; if (strcasecmp(uuid, A2DP_SOURCE_UUID) == 0) { endpoint->sep = a2dp_add_sep(&adapter->src, AVDTP_SEP_TYPE_SOURCE, codec, delay_reporting, endpoint, err); if (endpoint->sep == NULL) goto failed; } else if (strcasecmp(uuid, A2DP_SINK_UUID) == 0) { endpoint->sep = a2dp_add_sep(&adapter->src, AVDTP_SEP_TYPE_SINK, codec, delay_reporting, endpoint, err); if (endpoint->sep == NULL) goto failed; } else if (strcasecmp(uuid, HFP_AG_UUID) == 0 || g_strcmp0(uuid, HSP_AG_UUID) == 0) { struct audio_device *dev; endpoint->hs_watch = headset_add_state_cb(headset_state_changed, endpoint); dev = manager_find_device(NULL, &adapter->src, BDADDR_ANY, AUDIO_HEADSET_INTERFACE, TRUE); if (dev) media_endpoint_set_configuration(endpoint, dev, NULL, 0, headset_setconf_cb, dev); } else { if (err) *err = -EINVAL; goto failed; } endpoint->watch = g_dbus_add_disconnect_watch(adapter->conn, sender, media_endpoint_exit, endpoint, NULL); adapter->endpoints = g_slist_append(adapter->endpoints, endpoint); info("Endpoint registered: sender=%s path=%s", sender, path); if (err) *err = 0; return endpoint; failed: g_free(endpoint); return NULL; } static struct media_endpoint *media_adapter_find_endpoint( struct media_adapter *adapter, const char *sender, const char *path, const char *uuid) { GSList *l; for (l = adapter->endpoints; l; l = l->next) { struct media_endpoint *endpoint = l->data; if (sender && g_strcmp0(endpoint->sender, sender) != 0) continue; if (path && g_strcmp0(endpoint->path, path) != 0) continue; if (uuid && g_strcmp0(endpoint->uuid, uuid) != 0) continue; return endpoint; } return NULL; } const char *media_endpoint_get_sender(struct media_endpoint *endpoint) { return endpoint->sender; } static int parse_properties(DBusMessageIter *props, const char **uuid, gboolean *delay_reporting, uint8_t *codec, uint8_t **capabilities, int *size) { gboolean has_uuid = FALSE; gboolean has_codec = FALSE; while (dbus_message_iter_get_arg_type(props) == DBUS_TYPE_DICT_ENTRY) { const char *key; DBusMessageIter value, entry; int var; dbus_message_iter_recurse(props, &entry); dbus_message_iter_get_basic(&entry, &key); dbus_message_iter_next(&entry); dbus_message_iter_recurse(&entry, &value); var = dbus_message_iter_get_arg_type(&value); if (strcasecmp(key, "UUID") == 0) { if (var != DBUS_TYPE_STRING) return -EINVAL; dbus_message_iter_get_basic(&value, uuid); has_uuid = TRUE; } else if (strcasecmp(key, "Codec") == 0) { if (var != DBUS_TYPE_BYTE) return -EINVAL; dbus_message_iter_get_basic(&value, codec); has_codec = TRUE; } else if (strcasecmp(key, "DelayReporting") == 0) { if (var != DBUS_TYPE_BOOLEAN) return -EINVAL; dbus_message_iter_get_basic(&value, delay_reporting); } else if (strcasecmp(key, "Capabilities") == 0) { DBusMessageIter array; if (var != DBUS_TYPE_ARRAY) return -EINVAL; dbus_message_iter_recurse(&value, &array); dbus_message_iter_get_fixed_array(&array, capabilities, size); } dbus_message_iter_next(props); } return (has_uuid && has_codec) ? 0 : -EINVAL; } static DBusMessage *register_endpoint(DBusConnection *conn, DBusMessage *msg, void *data) { struct media_adapter *adapter = data; DBusMessageIter args, props; const char *sender, *path, *uuid; gboolean delay_reporting = FALSE; uint8_t codec; uint8_t *capabilities; int size = 0; int err; sender = dbus_message_get_sender(msg); dbus_message_iter_init(msg, &args); dbus_message_iter_get_basic(&args, &path); dbus_message_iter_next(&args); if (media_adapter_find_endpoint(adapter, sender, path, NULL) != NULL) return btd_error_already_exists(msg); dbus_message_iter_recurse(&args, &props); if (dbus_message_iter_get_arg_type(&props) != DBUS_TYPE_DICT_ENTRY) return btd_error_invalid_args(msg); if (parse_properties(&props, &uuid, &delay_reporting, &codec, &capabilities, &size) < 0) return btd_error_invalid_args(msg); if (media_endpoint_create(adapter, sender, path, uuid, delay_reporting, codec, capabilities, size, &err) == FALSE) { if (err == -EPROTONOSUPPORT) return btd_error_not_supported(msg); else return btd_error_invalid_args(msg); } return g_dbus_create_reply(msg, DBUS_TYPE_INVALID); } static DBusMessage *unregister_endpoint(DBusConnection *conn, DBusMessage *msg, void *data) { struct media_adapter *adapter = data; struct media_endpoint *endpoint; const char *sender, *path; if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID)) return NULL; sender = dbus_message_get_sender(msg); endpoint = media_adapter_find_endpoint(adapter, sender, path, NULL); if (endpoint == NULL) return btd_error_does_not_exist(msg); media_endpoint_remove(endpoint); return g_dbus_create_reply(msg, DBUS_TYPE_INVALID); } static GDBusMethodTable media_methods[] = { { "RegisterEndpoint", "oa{sv}", "", register_endpoint }, { "UnregisterEndpoint", "o", "", unregister_endpoint }, { }, }; static void path_free(void *data) { struct media_adapter *adapter = data; g_slist_foreach(adapter->endpoints, (GFunc) media_endpoint_release, NULL); g_slist_free(adapter->endpoints); dbus_connection_unref(adapter->conn); adapters = g_slist_remove(adapters, adapter); g_free(adapter->path); g_free(adapter); } int media_register(DBusConnection *conn, const char *path, const bdaddr_t *src) { struct media_adapter *adapter; if (DBUS_TYPE_UNIX_FD < 0) return -EPERM; adapter = g_new0(struct media_adapter, 1); adapter->conn = dbus_connection_ref(conn); bacpy(&adapter->src, src); adapter->path = g_strdup(path); if (!g_dbus_register_interface(conn, path, MEDIA_INTERFACE, media_methods, NULL, NULL, adapter, path_free)) { error("D-Bus failed to register %s path", path); path_free(adapter); return -1; } adapters = g_slist_append(adapters, adapter); return 0; } void media_unregister(const char *path) { GSList *l; for (l = adapters; l; l = l->next) { struct media_adapter *adapter = l->data; if (g_strcmp0(path, adapter->path) == 0) { g_dbus_unregister_interface(adapter->conn, path, MEDIA_INTERFACE); return; } } } size_t media_endpoint_get_capabilities(struct media_endpoint *endpoint, uint8_t **capabilities) { *capabilities = endpoint->capabilities; return endpoint->size; } static void endpoint_reply(DBusPendingCall *call, void *user_data) { struct media_endpoint *endpoint = user_data; struct endpoint_request *request = endpoint->request; DBusMessage *reply; DBusError err; gboolean value; void *ret = NULL; int size = -1; /* steal_reply will always return non-NULL since the callback * is only called after a reply has been received */ reply = dbus_pending_call_steal_reply(call); dbus_error_init(&err); if (dbus_set_error_from_message(&err, reply)) { error("Endpoint replied with an error: %s", err.name); /* Clear endpoint configuration in case of NO_REPLY error */ if (dbus_error_has_name(&err, DBUS_ERROR_NO_REPLY)) { if (request->cb) request->cb(endpoint, NULL, size, request->user_data); media_endpoint_clear_configuration(endpoint); dbus_message_unref(reply); dbus_error_free(&err); return; } dbus_error_free(&err); goto done; } dbus_error_init(&err); if (dbus_message_is_method_call(request->msg, MEDIA_ENDPOINT_INTERFACE, "SelectConfiguration")) { DBusMessageIter args, array; uint8_t *configuration; dbus_message_iter_init(reply, &args); dbus_message_iter_recurse(&args, &array); dbus_message_iter_get_fixed_array(&array, &configuration, &size); ret = configuration; goto done; } else if (!dbus_message_get_args(reply, &err, DBUS_TYPE_INVALID)) { error("Wrong reply signature: %s", err.message); dbus_error_free(&err); goto done; } size = 1; value = TRUE; ret = &value; done: dbus_message_unref(reply); if (request->cb) request->cb(endpoint, ret, size, request->user_data); endpoint_request_free(request); endpoint->request = NULL; } static gboolean media_endpoint_async_call(DBusConnection *conn, DBusMessage *msg, struct media_endpoint *endpoint, media_endpoint_cb_t cb, void *user_data) { struct endpoint_request *request; if (endpoint->request) return FALSE; request = g_new0(struct endpoint_request, 1); /* Timeout should be less than avdtp request timeout (4 seconds) */ if (dbus_connection_send_with_reply(conn, msg, &request->call, REQUEST_TIMEOUT) == FALSE) { error("D-Bus send failed"); g_free(request); return FALSE; } dbus_pending_call_set_notify(request->call, endpoint_reply, endpoint, NULL); request->msg = msg; request->cb = cb; request->user_data = user_data; endpoint->request = request; DBG("Calling %s: name = %s path = %s", dbus_message_get_member(msg), dbus_message_get_destination(msg), dbus_message_get_path(msg)); return TRUE; } gboolean media_endpoint_set_configuration(struct media_endpoint *endpoint, struct audio_device *device, uint8_t *configuration, size_t size, media_endpoint_cb_t cb, void *user_data) { DBusConnection *conn; DBusMessage *msg; const char *path; DBusMessageIter iter; if (endpoint->transport != NULL || endpoint->request != NULL) return FALSE; conn = endpoint->adapter->conn; endpoint->transport = media_transport_create(conn, endpoint, device, configuration, size); if (endpoint->transport == NULL) return FALSE; msg = dbus_message_new_method_call(endpoint->sender, endpoint->path, MEDIA_ENDPOINT_INTERFACE, "SetConfiguration"); if (msg == NULL) { error("Couldn't allocate D-Bus message"); return FALSE; } dbus_message_iter_init_append(msg, &iter); path = media_transport_get_path(endpoint->transport); dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &path); transport_get_properties(endpoint->transport, &iter); return media_endpoint_async_call(conn, msg, endpoint, cb, user_data); } gboolean media_endpoint_select_configuration(struct media_endpoint *endpoint, uint8_t *capabilities, size_t length, media_endpoint_cb_t cb, void *user_data) { DBusConnection *conn; DBusMessage *msg; if (endpoint->request != NULL) return FALSE; conn = endpoint->adapter->conn; msg = dbus_message_new_method_call(endpoint->sender, endpoint->path, MEDIA_ENDPOINT_INTERFACE, "SelectConfiguration"); if (msg == NULL) { error("Couldn't allocate D-Bus message"); return FALSE; } dbus_message_append_args(msg, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &capabilities, length, DBUS_TYPE_INVALID); return media_endpoint_async_call(conn, msg, endpoint, cb, user_data); } void media_endpoint_clear_configuration(struct media_endpoint *endpoint) { DBusConnection *conn; DBusMessage *msg; const char *path; if (endpoint->transport == NULL) return; if (endpoint->request) media_endpoint_cancel(endpoint); conn = endpoint->adapter->conn; msg = dbus_message_new_method_call(endpoint->sender, endpoint->path, MEDIA_ENDPOINT_INTERFACE, "ClearConfiguration"); if (msg == NULL) { error("Couldn't allocate D-Bus message"); goto done; } path = media_transport_get_path(endpoint->transport); dbus_message_append_args(msg, DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID); g_dbus_send_message(conn, msg); done: media_transport_destroy(endpoint->transport); endpoint->transport = NULL; } void media_endpoint_release(struct media_endpoint *endpoint) { DBusMessage *msg; DBG("sender=%s path=%s", endpoint->sender, endpoint->path); /* already exit */ if (endpoint->watch == 0) return; msg = dbus_message_new_method_call(endpoint->sender, endpoint->path, MEDIA_ENDPOINT_INTERFACE, "Release"); if (msg == NULL) { error("Couldn't allocate D-Bus message"); return; } g_dbus_send_message(endpoint->adapter->conn, msg); media_endpoint_remove(endpoint); } struct a2dp_sep *media_endpoint_get_sep(struct media_endpoint *endpoint) { return endpoint->sep; } const char *media_endpoint_get_uuid(struct media_endpoint *endpoint) { return endpoint->uuid; } uint8_t media_endpoint_get_codec(struct media_endpoint *endpoint) { return endpoint->codec; } struct media_transport *media_endpoint_get_transport( struct media_endpoint *endpoint) { return endpoint->transport; }
apache-2.0
indashnet/InDashNet.Open.UN2000
lichee/linux-3.4/arch/sparc/kernel/auxio_32.c
4409
3803
/* auxio.c: Probing for the Sparc AUXIO register at boot time. * * Copyright (C) 1996 David S. Miller (davem@caip.rutgers.edu) */ #include <linux/stddef.h> #include <linux/init.h> #include <linux/spinlock.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/export.h> #include <asm/oplib.h> #include <asm/io.h> #include <asm/auxio.h> #include <asm/string.h> /* memset(), Linux has no bzero() */ #include <asm/cpu_type.h> /* Probe and map in the Auxiliary I/O register */ /* auxio_register is not static because it is referenced * in entry.S::floppy_tdone */ void __iomem *auxio_register = NULL; static DEFINE_SPINLOCK(auxio_lock); void __init auxio_probe(void) { phandle node, auxio_nd; struct linux_prom_registers auxregs[1]; struct resource r; switch (sparc_cpu_model) { case sparc_leon: case sun4d: case sun4: return; default: break; } node = prom_getchild(prom_root_node); auxio_nd = prom_searchsiblings(node, "auxiliary-io"); if(!auxio_nd) { node = prom_searchsiblings(node, "obio"); node = prom_getchild(node); auxio_nd = prom_searchsiblings(node, "auxio"); if(!auxio_nd) { #ifdef CONFIG_PCI /* There may be auxio on Ebus */ return; #else if(prom_searchsiblings(node, "leds")) { /* VME chassis sun4m machine, no auxio exists. */ return; } prom_printf("Cannot find auxio node, cannot continue...\n"); prom_halt(); #endif } } if(prom_getproperty(auxio_nd, "reg", (char *) auxregs, sizeof(auxregs)) <= 0) return; prom_apply_obio_ranges(auxregs, 0x1); /* Map the register both read and write */ r.flags = auxregs[0].which_io & 0xF; r.start = auxregs[0].phys_addr; r.end = auxregs[0].phys_addr + auxregs[0].reg_size - 1; auxio_register = of_ioremap(&r, 0, auxregs[0].reg_size, "auxio"); /* Fix the address on sun4m and sun4c. */ if((((unsigned long) auxregs[0].phys_addr) & 3) == 3 || sparc_cpu_model == sun4c) auxio_register += (3 - ((unsigned long)auxio_register & 3)); set_auxio(AUXIO_LED, 0); } unsigned char get_auxio(void) { if(auxio_register) return sbus_readb(auxio_register); return 0; } EXPORT_SYMBOL(get_auxio); void set_auxio(unsigned char bits_on, unsigned char bits_off) { unsigned char regval; unsigned long flags; spin_lock_irqsave(&auxio_lock, flags); switch(sparc_cpu_model) { case sun4c: regval = sbus_readb(auxio_register); sbus_writeb(((regval | bits_on) & ~bits_off) | AUXIO_ORMEIN, auxio_register); break; case sun4m: if(!auxio_register) break; /* VME chassis sun4m, no auxio. */ regval = sbus_readb(auxio_register); sbus_writeb(((regval | bits_on) & ~bits_off) | AUXIO_ORMEIN4M, auxio_register); break; case sun4d: break; default: panic("Can't set AUXIO register on this machine."); } spin_unlock_irqrestore(&auxio_lock, flags); } EXPORT_SYMBOL(set_auxio); /* sun4m power control register (AUXIO2) */ volatile unsigned char * auxio_power_register = NULL; void __init auxio_power_probe(void) { struct linux_prom_registers regs; phandle node; struct resource r; /* Attempt to find the sun4m power control node. */ node = prom_getchild(prom_root_node); node = prom_searchsiblings(node, "obio"); node = prom_getchild(node); node = prom_searchsiblings(node, "power"); if (node == 0 || (s32)node == -1) return; /* Map the power control register. */ if (prom_getproperty(node, "reg", (char *)&regs, sizeof(regs)) <= 0) return; prom_apply_obio_ranges(&regs, 1); memset(&r, 0, sizeof(r)); r.flags = regs.which_io & 0xF; r.start = regs.phys_addr; r.end = regs.phys_addr + regs.reg_size - 1; auxio_power_register = (unsigned char *) of_ioremap(&r, 0, regs.reg_size, "auxpower"); /* Display a quick message on the console. */ if (auxio_power_register) printk(KERN_INFO "Power off control detected.\n"); }
apache-2.0
awetzel/otp
erts/emulator/test/port_bif_SUITE_data/port_test.c
59
13041
/* * Author: Bjorn Gustavsson * Purpose: A port program to be used for testing the open_port bif. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #ifndef __WIN32__ #include <unistd.h> #include <sys/time.h> #define O_BINARY 0 #define _setmode(fd, mode) #endif #ifdef __WIN32__ #include "windows.h" #include "winbase.h" #endif #define REDIR_STDOUT(fd) if (dup2(fd, 1) == -1) { \ fprintf(stderr, "%s: failed to duplicate handle %d to 1: %d\n", \ port_data->progname, fd, errno); \ exit(1); \ } #define MAIN(argc, argv) main(argc, argv) extern int errno; typedef struct { char* progname; /* Name of this program (from argv[0]). */ int header_size; /* Number of bytes in each packet header: * 1, 2, or 4, or 0 for a continous byte stream. */ int fd_from_erl; /* File descriptor from Erlang. */ int fd_to_erl; /* File descriptor to Erlang. */ unsigned char* io_buf; /* Buffer for file i/o. */ int io_buf_size; /* Current size of i/o buffer. */ int delay_mode; /* If set, this program will wait 5 seconds * after reading the header for a packet * before reading the rest. */ int break_mode; /* If set, this program will close standard * input, which should case broken pipe * error in the writer. */ int quit_mode; /* If set, this program will exit * just after reading the packet header. */ int slow_writes; /* Writes back the reply in chunks with * sleeps in between. The value is the * chunk size. If 0, normal writes are done. */ char* output_file; /* File into which the result will be written. */ int no_packet_loop; /* No packet loop. */ int limited_bytecount; /* Only answer a limited number of bytes, then exit (stream mode) */ } PORT_TEST_DATA; PORT_TEST_DATA* port_data; static int packet_loop(); static void reply(); static void write_reply(); static void ensure_buf_big_enough(); static int readn(); static void delay(unsigned ms); static void dump(unsigned char* buf, int sz, int max); static void replace_stdout(char* filename); static void generate_reply(char* spec); #ifndef HAVE_STRERROR extern int sys_nerr; #ifndef sys_errlist /* sys_errlist is sometimes defined to call a function on win32 */ extern char *sys_errlist[]; #endif char* strerror(err) int err; { static char msgstr[1024]; if (err == 0) { msgstr[0] = '\0'; } else if (0 < err && err < sys_nerr) { strcpy(msgstr, sys_errlist[err]); } else { sprintf(msgstr, "Unknown error %d", err); } return msgstr; } #endif MAIN(argc, argv) int argc; char *argv[]; { int ret; if((port_data = (PORT_TEST_DATA *) malloc(sizeof(PORT_TEST_DATA))) == NULL) { fprintf(stderr, "Couldn't malloc for port_data"); exit(1); } port_data->header_size = 0; port_data->io_buf_size = 0; port_data->delay_mode = 0; port_data->break_mode = 0; port_data->quit_mode = 0; port_data->slow_writes = 0; port_data->output_file = NULL; port_data->no_packet_loop = 0; port_data->progname = argv[0]; port_data->fd_from_erl = 0; port_data->fd_to_erl = 1; port_data->limited_bytecount = 0; _setmode(0, _O_BINARY); _setmode(1, _O_BINARY); while (argc > 1 && argv[1][0] == '-') { switch (argv[1][1]) { case 'b': /* Break mode. */ port_data->break_mode = 1; break; case 'c': /* Close standard output. */ close(port_data->fd_to_erl); break; case 'd': /* Delay mode. */ port_data->delay_mode = 1; break; case 'n': /* No packet loop. */ port_data->no_packet_loop = 1; break; case 'o': /* Output to file. */ port_data->output_file = argv[1]+2; break; case 'q': /* Quit mode. */ port_data->quit_mode = 1; break; case 'r': /* Generate reply. */ generate_reply(argv[1]+2); break; case 's': /* Slow writes. */ port_data->slow_writes = atoi(argv[1]+2); break; case 'h': /* Header size for packets. */ switch (argv[1][2]) { case '0': port_data->header_size = 0; break; case '1': port_data->header_size = 1; break; case '2': port_data->header_size = 2; break; case '4': port_data->header_size = 4; break; case '\0': fprintf(stderr, "%s: missing header size for -h\n", port_data->progname); return 1; default: fprintf(stderr, "%s: illegal packet header size: %c\n", port_data->progname, argv[1][2]); return 1; } break; case 'e': port_data->fd_to_erl = 2; break; case 'l': port_data->limited_bytecount = atoi(argv[1]+2); break; default: fprintf(stderr, "Unrecognized switch: %s\n", argv[1]); free(port_data); exit(1); } argc--, argv++; } if (argc > 1) { /* XXX Add error printout here */ } if (port_data->no_packet_loop){ free(port_data); exit(0); } /* * If an output file was given, let it replace standard output. */ if (port_data->output_file) replace_stdout(port_data->output_file); ret = packet_loop(); if(port_data->io_buf_size > 0) free(port_data->io_buf); free(port_data); return ret; } static int packet_loop(void) { int total_read = 0; port_data->io_buf = (unsigned char*) malloc(1); /* Allocate once, so realloc works (SunOS) */ for (;;) { int packet_length; /* Length of current packet. */ int i; int bytes_read; /* Number of bytes read. */ /* * Read the packet header, if any. */ if (port_data->header_size == 0) { if(port_data->limited_bytecount && port_data->limited_bytecount - total_read < 4096) packet_length = port_data->limited_bytecount - total_read; else packet_length = 4096; } else { ensure_buf_big_enough(port_data->header_size); if (readn(port_data->fd_from_erl, port_data->io_buf, port_data->header_size) != port_data->header_size) { return(1); } /* * Get the length of this packet. */ packet_length = 0; for (i = 0; i < port_data->header_size; i++) packet_length = (packet_length << 8) | port_data->io_buf[i]; } /* * Delay if delay mode. */ if (port_data->delay_mode) { delay(5000L); } if (port_data->quit_mode) { return(1); } else if (port_data->break_mode) { close(0); delay(32000L); return(1); } /* * Read the packet itself. */ ensure_buf_big_enough(packet_length+4+1); /* At least five bytes. */ port_data->io_buf[4] = '\0'; if (port_data->header_size == 0) { bytes_read = read(port_data->fd_from_erl, port_data->io_buf+4, packet_length); if (bytes_read == 0) return(1); if (bytes_read < 0) { fprintf(stderr, "Error reading %d bytes: %s\n", packet_length, strerror(errno)); return(1); } total_read += bytes_read; } else { bytes_read = readn(port_data->fd_from_erl, port_data->io_buf+4, packet_length); if (bytes_read != packet_length) { fprintf(stderr, "%s: couldn't read packet of length %d\r\n", port_data->progname, packet_length); return(1); } } /* * Act on the command. */ if (port_data->header_size == 0) { reply(port_data->io_buf+4, bytes_read); if(port_data->limited_bytecount && port_data->limited_bytecount <= total_read){ delay(5000L); return(0); } } else { switch (port_data->io_buf[4]) { case 'p': /* ping */ port_data->io_buf[4] = 'P'; reply(port_data->io_buf+4, bytes_read); break; case 'e': /* echo */ reply(port_data->io_buf+4, bytes_read); break; default: fprintf(stderr, "%s: bad packet of length %d received: ", port_data->progname, bytes_read); dump(port_data->io_buf+4, bytes_read, 10); fprintf(stderr, "\r\n"); return(1); } } } } /* * Sends a packet back to Erlang. */ static void reply(buf, size) char* buf; /* Buffer with reply. The four bytes before * this pointer must be allocated so that * this function can put the header there. */ int size; /* Size of buffer to send. */ { int n; /* Temporary to hold size. */ int i; /* Loop counter. */ /* * Fill the header starting with the least significant byte * (this will work even if there is no header). */ n = size; for (i = 0; i < port_data->header_size; i++) { *--buf = (char) n; /* Store least significant byte. */ n = n >> 8; } size += port_data->header_size; write_reply(buf, size); } static void write_reply(buf, size) char* buf; /* Buffer with reply. Must contain header. */ int size; /* Size of buffer to send. */ { int n; /* Temporary to hold size. */ if (port_data->slow_writes <= 0) { /* Normal, "fast", write. */ write(port_data->fd_to_erl, buf, size); } else { /* * Write chunks with delays in between. */ while (size > 0) { n = size > port_data->slow_writes ? port_data->slow_writes : size; write(port_data->fd_to_erl, buf, n); size -= n; buf += n; if (size) delay(500L); } } } /* * Ensures that our I/O buffer is big enough for the packet to come. */ static void ensure_buf_big_enough(size) int size; /* Needed size of buffer. */ { if (port_data->io_buf_size >= size) return; port_data->io_buf = (unsigned char*) realloc(port_data->io_buf, size); if (port_data->io_buf == NULL) { fprintf(stderr, "%s: insufficient memory for i/o buffer of size %d\n", port_data->progname, size); exit(1); } port_data->io_buf_size = size; } /* * Reads len number of bytes. */ static int readn(fd, buf, len) int fd; /* File descriptor to read from. */ unsigned char *buf; /* Store in this buffer. */ int len; /* Number of bytes to read. */ { int n; /* Byte count in last read call. */ int sofar; /* Bytes read so far. */ sofar = 0; do { if ((n = read(fd, buf+sofar, len-sofar)) <= 0) /* error or EOF in read */ return(n); sofar += n; } while (sofar < len); return sofar; } static void replace_stdout(filename) char* filename; /* Name of file to replace standard output. */ { int fd; fd = open(filename, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0666); if (fd == -1) { fprintf(stderr, "%s: failed to open %s for writing: %d\n", port_data->progname, filename, errno); exit(1); } REDIR_STDOUT(fd); } static void dump(buf, sz, max) unsigned char* buf; int sz; int max; { int i, imax; char comma[5]; comma[0] = ','; comma[1] = '\0'; if (!sz) return; if (sz > max) imax = max; else imax = sz; for (i=0; i<imax; i++) { if (i == imax-1) { if (sz > max) strcpy(comma, ",..."); else comma[0] = 0; } if (isdigit(buf[i])) { fprintf(stderr, "%u%s", (int)(buf[i]), comma); } else { if (isalpha(buf[i])) { fprintf(stderr, "%c%s", buf[i], comma); } else { fprintf(stderr, "%u%s", (int)(buf[i]), comma); } } } } /* * Delays (sleeps) the given number of milli-seconds. */ static void delay(unsigned ms) { #ifdef __WIN32__ Sleep(ms); #else struct timeval t; t.tv_sec = ms/1000; t.tv_usec = (ms % 1000) * 1000; select(0, NULL, NULL, NULL, &t); #endif } /* * Generates a reply buffer given the specification. * * <packet-bytes>,<start-character>,<increment>,<size> * * Where: * <packet-bytes> is */ static void generate_reply(spec) char* spec; /* Specification for reply. */ { typedef struct item { int start; /* Start character. */ int incrementer; /* How much to increment. */ size_t size; /* Size of reply buffer. */ } Item; Item items[256]; int last; int cur; size_t total_size; char* buf; /* Reply buffer. */ char* s; /* Current pointer into buffer. */ int c; total_size = 0; last = 0; while (*spec) { char* colon; items[last].incrementer = 1; items[last].start = *spec++; items[last].size = atoi(spec); total_size += port_data->header_size+items[last].size; last++; if ((colon = strchr(spec, ':')) == NULL) { spec += strlen(spec); } else { *colon = '\0'; spec = colon+1; } } buf = (char *) malloc(total_size); if (buf == NULL) { fprintf(stderr, "%s: insufficent memory for reply buffer of size %d\n", port_data->progname, total_size); exit(1); } s = buf; for (cur = 0; cur < last; cur++) { int i; size_t n; n = items[cur].size; s += port_data->header_size; for (i = 0; i < port_data->header_size; i++) { *--s = (char) n; /* Store least significant byte. */ n = n >> 8; } s += port_data->header_size; c = items[cur].start; for (i = 0; i < items[cur].size; i++) { *s++ = c; c++; if (c > 126) { c = 33; } } } write_reply(buf, s-buf); }
apache-2.0
RockySteveJobs/python-for-android
python3-alpha/openssl/crypto/x509v3/v3_akey.c
829
6531
/* v3_akey.c */ /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project 1999. */ /* ==================================================================== * Copyright (c) 1999 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/conf.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/x509v3.h> static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method, AUTHORITY_KEYID *akeyid, STACK_OF(CONF_VALUE) *extlist); static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values); const X509V3_EXT_METHOD v3_akey_id = { NID_authority_key_identifier, X509V3_EXT_MULTILINE, ASN1_ITEM_ref(AUTHORITY_KEYID), 0,0,0,0, 0,0, (X509V3_EXT_I2V)i2v_AUTHORITY_KEYID, (X509V3_EXT_V2I)v2i_AUTHORITY_KEYID, 0,0, NULL }; static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method, AUTHORITY_KEYID *akeyid, STACK_OF(CONF_VALUE) *extlist) { char *tmp; if(akeyid->keyid) { tmp = hex_to_string(akeyid->keyid->data, akeyid->keyid->length); X509V3_add_value("keyid", tmp, &extlist); OPENSSL_free(tmp); } if(akeyid->issuer) extlist = i2v_GENERAL_NAMES(NULL, akeyid->issuer, extlist); if(akeyid->serial) { tmp = hex_to_string(akeyid->serial->data, akeyid->serial->length); X509V3_add_value("serial", tmp, &extlist); OPENSSL_free(tmp); } return extlist; } /* Currently two options: * keyid: use the issuers subject keyid, the value 'always' means its is * an error if the issuer certificate doesn't have a key id. * issuer: use the issuers cert issuer and serial number. The default is * to only use this if keyid is not present. With the option 'always' * this is always included. */ static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values) { char keyid=0, issuer=0; int i; CONF_VALUE *cnf; ASN1_OCTET_STRING *ikeyid = NULL; X509_NAME *isname = NULL; GENERAL_NAMES * gens = NULL; GENERAL_NAME *gen = NULL; ASN1_INTEGER *serial = NULL; X509_EXTENSION *ext; X509 *cert; AUTHORITY_KEYID *akeyid; for(i = 0; i < sk_CONF_VALUE_num(values); i++) { cnf = sk_CONF_VALUE_value(values, i); if(!strcmp(cnf->name, "keyid")) { keyid = 1; if(cnf->value && !strcmp(cnf->value, "always")) keyid = 2; } else if(!strcmp(cnf->name, "issuer")) { issuer = 1; if(cnf->value && !strcmp(cnf->value, "always")) issuer = 2; } else { X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,X509V3_R_UNKNOWN_OPTION); ERR_add_error_data(2, "name=", cnf->name); return NULL; } } if(!ctx || !ctx->issuer_cert) { if(ctx && (ctx->flags==CTX_TEST)) return AUTHORITY_KEYID_new(); X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,X509V3_R_NO_ISSUER_CERTIFICATE); return NULL; } cert = ctx->issuer_cert; if(keyid) { i = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1); if((i >= 0) && (ext = X509_get_ext(cert, i))) ikeyid = X509V3_EXT_d2i(ext); if(keyid==2 && !ikeyid) { X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,X509V3_R_UNABLE_TO_GET_ISSUER_KEYID); return NULL; } } if((issuer && !ikeyid) || (issuer == 2)) { isname = X509_NAME_dup(X509_get_issuer_name(cert)); serial = M_ASN1_INTEGER_dup(X509_get_serialNumber(cert)); if(!isname || !serial) { X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS); goto err; } } if(!(akeyid = AUTHORITY_KEYID_new())) goto err; if(isname) { if(!(gens = sk_GENERAL_NAME_new_null()) || !(gen = GENERAL_NAME_new()) || !sk_GENERAL_NAME_push(gens, gen)) { X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,ERR_R_MALLOC_FAILURE); goto err; } gen->type = GEN_DIRNAME; gen->d.dirn = isname; } akeyid->issuer = gens; akeyid->serial = serial; akeyid->keyid = ikeyid; return akeyid; err: X509_NAME_free(isname); M_ASN1_INTEGER_free(serial); M_ASN1_OCTET_STRING_free(ikeyid); return NULL; }
apache-2.0
autopulated/mbed
libraries/dsp/cmsis_dsp/TransformFunctions/arm_cfft_radix4_init_f32.c
67
6132
/* ---------------------------------------------------------------------- * Copyright (C) 2010-2013 ARM Limited. All rights reserved. * * $Date: 17. January 2013 * $Revision: V1.4.1 * * Project: CMSIS DSP Library * Title: arm_cfft_radix4_init_f32.c * * Description: Radix-4 Decimation in Frequency Floating-point CFFT & CIFFT Initialization function * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #include "arm_math.h" #include "arm_common_tables.h" /** * @ingroup groupTransforms */ /** * @addtogroup ComplexFFT * @{ */ /** * @brief Initialization function for the floating-point CFFT/CIFFT. * @deprecated Do not use this function. It has been superceded by \ref arm_cfft_f32 and will be removed * in the future. * @param[in,out] *S points to an instance of the floating-point CFFT/CIFFT structure. * @param[in] fftLen length of the FFT. * @param[in] ifftFlag flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. * @param[in] bitReverseFlag flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if <code>fftLen</code> is not a supported value. * * \par Description: * \par * The parameter <code>ifftFlag</code> controls whether a forward or inverse transform is computed. * Set(=1) ifftFlag for calculation of CIFFT otherwise CFFT is calculated * \par * The parameter <code>bitReverseFlag</code> controls whether output is in normal order or bit reversed order. * Set(=1) bitReverseFlag for output to be in normal order otherwise output is in bit reversed order. * \par * The parameter <code>fftLen</code> Specifies length of CFFT/CIFFT process. Supported FFT Lengths are 16, 64, 256, 1024. * \par * This Function also initializes Twiddle factor table pointer and Bit reversal table pointer. */ arm_status arm_cfft_radix4_init_f32( arm_cfft_radix4_instance_f32 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag) { /* Initialise the default arm status */ arm_status status = ARM_MATH_SUCCESS; /* Initialise the FFT length */ S->fftLen = fftLen; /* Initialise the Twiddle coefficient pointer */ S->pTwiddle = (float32_t *) twiddleCoef; /* Initialise the Flag for selection of CFFT or CIFFT */ S->ifftFlag = ifftFlag; /* Initialise the Flag for calculation Bit reversal or not */ S->bitReverseFlag = bitReverseFlag; /* Initializations of structure parameters depending on the FFT length */ switch (S->fftLen) { case 4096u: /* Initializations of structure parameters for 4096 point FFT */ /* Initialise the twiddle coef modifier value */ S->twidCoefModifier = 1u; /* Initialise the bit reversal table modifier */ S->bitRevFactor = 1u; /* Initialise the bit reversal table pointer */ S->pBitRevTable = (uint16_t *) armBitRevTable; /* Initialise the 1/fftLen Value */ S->onebyfftLen = 0.000244140625; break; case 1024u: /* Initializations of structure parameters for 1024 point FFT */ /* Initialise the twiddle coef modifier value */ S->twidCoefModifier = 4u; /* Initialise the bit reversal table modifier */ S->bitRevFactor = 4u; /* Initialise the bit reversal table pointer */ S->pBitRevTable = (uint16_t *) & armBitRevTable[3]; /* Initialise the 1/fftLen Value */ S->onebyfftLen = 0.0009765625f; break; case 256u: /* Initializations of structure parameters for 256 point FFT */ S->twidCoefModifier = 16u; S->bitRevFactor = 16u; S->pBitRevTable = (uint16_t *) & armBitRevTable[15]; S->onebyfftLen = 0.00390625f; break; case 64u: /* Initializations of structure parameters for 64 point FFT */ S->twidCoefModifier = 64u; S->bitRevFactor = 64u; S->pBitRevTable = (uint16_t *) & armBitRevTable[63]; S->onebyfftLen = 0.015625f; break; case 16u: /* Initializations of structure parameters for 16 point FFT */ S->twidCoefModifier = 256u; S->bitRevFactor = 256u; S->pBitRevTable = (uint16_t *) & armBitRevTable[255]; S->onebyfftLen = 0.0625f; break; default: /* Reporting argument error if fftSize is not valid value */ status = ARM_MATH_ARGUMENT_ERROR; break; } return (status); } /** * @} end of ComplexFFT group */
apache-2.0
svastm/mbed
libraries/net/lwip/lwip/api/netifapi.c
583
4836
/** * @file * Network Interface Sequential API module * */ /* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * */ #include "lwip/opt.h" #if LWIP_NETIF_API /* don't build if not configured for use in lwipopts.h */ #include "lwip/netifapi.h" #include "lwip/tcpip.h" /** * Call netif_add() inside the tcpip_thread context. */ void do_netifapi_netif_add(struct netifapi_msg_msg *msg) { if (!netif_add( msg->netif, msg->msg.add.ipaddr, msg->msg.add.netmask, msg->msg.add.gw, msg->msg.add.state, msg->msg.add.init, msg->msg.add.input)) { msg->err = ERR_IF; } else { msg->err = ERR_OK; } TCPIP_NETIFAPI_ACK(msg); } /** * Call netif_set_addr() inside the tcpip_thread context. */ void do_netifapi_netif_set_addr(struct netifapi_msg_msg *msg) { netif_set_addr( msg->netif, msg->msg.add.ipaddr, msg->msg.add.netmask, msg->msg.add.gw); msg->err = ERR_OK; TCPIP_NETIFAPI_ACK(msg); } /** * Call the "errtfunc" (or the "voidfunc" if "errtfunc" is NULL) inside the * tcpip_thread context. */ void do_netifapi_netif_common(struct netifapi_msg_msg *msg) { if (msg->msg.common.errtfunc != NULL) { msg->err = msg->msg.common.errtfunc(msg->netif); } else { msg->err = ERR_OK; msg->msg.common.voidfunc(msg->netif); } TCPIP_NETIFAPI_ACK(msg); } /** * Call netif_add() in a thread-safe way by running that function inside the * tcpip_thread context. * * @note for params @see netif_add() */ err_t netifapi_netif_add(struct netif *netif, ip_addr_t *ipaddr, ip_addr_t *netmask, ip_addr_t *gw, void *state, netif_init_fn init, netif_input_fn input) { struct netifapi_msg msg; msg.function = do_netifapi_netif_add; msg.msg.netif = netif; msg.msg.msg.add.ipaddr = ipaddr; msg.msg.msg.add.netmask = netmask; msg.msg.msg.add.gw = gw; msg.msg.msg.add.state = state; msg.msg.msg.add.init = init; msg.msg.msg.add.input = input; TCPIP_NETIFAPI(&msg); return msg.msg.err; } /** * Call netif_set_addr() in a thread-safe way by running that function inside the * tcpip_thread context. * * @note for params @see netif_set_addr() */ err_t netifapi_netif_set_addr(struct netif *netif, ip_addr_t *ipaddr, ip_addr_t *netmask, ip_addr_t *gw) { struct netifapi_msg msg; msg.function = do_netifapi_netif_set_addr; msg.msg.netif = netif; msg.msg.msg.add.ipaddr = ipaddr; msg.msg.msg.add.netmask = netmask; msg.msg.msg.add.gw = gw; TCPIP_NETIFAPI(&msg); return msg.msg.err; } /** * call the "errtfunc" (or the "voidfunc" if "errtfunc" is NULL) in a thread-safe * way by running that function inside the tcpip_thread context. * * @note use only for functions where there is only "netif" parameter. */ err_t netifapi_netif_common(struct netif *netif, netifapi_void_fn voidfunc, netifapi_errt_fn errtfunc) { struct netifapi_msg msg; msg.function = do_netifapi_netif_common; msg.msg.netif = netif; msg.msg.msg.common.voidfunc = voidfunc; msg.msg.msg.common.errtfunc = errtfunc; TCPIP_NETIFAPI(&msg); return msg.msg.err; } #endif /* LWIP_NETIF_API */
apache-2.0
syDengWJ/opengl-series
platforms/ios/03_matrices/source/tdogl/Texture.cpp
94
2266
/* tdogl::Texture Copyright 2012 Thomas Dalling - http://tomdalling.com/ 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 "Texture.h" #include <stdexcept> using namespace tdogl; static GLenum TextureFormatForBitmapFormat(Bitmap::Format format) { switch (format) { case Bitmap::Format_Grayscale: return GL_LUMINANCE; case Bitmap::Format_GrayscaleAlpha: return GL_LUMINANCE_ALPHA; case Bitmap::Format_RGB: return GL_RGB; case Bitmap::Format_RGBA: return GL_RGBA; default: throw std::runtime_error("Unrecognised Bitmap::Format"); } } Texture::Texture(const Bitmap& bitmap, GLint minMagFiler, GLint wrapMode) : _originalWidth((GLfloat)bitmap.width()), _originalHeight((GLfloat)bitmap.height()) { glGenTextures(1, &_object); glBindTexture(GL_TEXTURE_2D, _object); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minMagFiler); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, minMagFiler); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode); glTexImage2D(GL_TEXTURE_2D, 0, TextureFormatForBitmapFormat(bitmap.format()), (GLsizei)bitmap.width(), (GLsizei)bitmap.height(), 0, TextureFormatForBitmapFormat(bitmap.format()), GL_UNSIGNED_BYTE, bitmap.pixelBuffer()); glBindTexture(GL_TEXTURE_2D, 0); } Texture::~Texture() { glDeleteTextures(1, &_object); } GLuint Texture::object() const { return _object; } GLfloat Texture::originalWidth() const { return _originalWidth; } GLfloat Texture::originalHeight() const { return _originalHeight; }
apache-2.0
ghostkim-sc/SMG920T_profiling_enabled
fs/xfs/xfs_aops.c
634
45257
/* * Copyright (c) 2000-2005 Silicon Graphics, Inc. * All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it would be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_log.h" #include "xfs_sb.h" #include "xfs_ag.h" #include "xfs_trans.h" #include "xfs_mount.h" #include "xfs_bmap_btree.h" #include "xfs_dinode.h" #include "xfs_inode.h" #include "xfs_inode_item.h" #include "xfs_alloc.h" #include "xfs_error.h" #include "xfs_iomap.h" #include "xfs_vnodeops.h" #include "xfs_trace.h" #include "xfs_bmap.h" #include <linux/aio.h> #include <linux/gfp.h> #include <linux/mpage.h> #include <linux/pagevec.h> #include <linux/writeback.h> void xfs_count_page_state( struct page *page, int *delalloc, int *unwritten) { struct buffer_head *bh, *head; *delalloc = *unwritten = 0; bh = head = page_buffers(page); do { if (buffer_unwritten(bh)) (*unwritten) = 1; else if (buffer_delay(bh)) (*delalloc) = 1; } while ((bh = bh->b_this_page) != head); } STATIC struct block_device * xfs_find_bdev_for_inode( struct inode *inode) { struct xfs_inode *ip = XFS_I(inode); struct xfs_mount *mp = ip->i_mount; if (XFS_IS_REALTIME_INODE(ip)) return mp->m_rtdev_targp->bt_bdev; else return mp->m_ddev_targp->bt_bdev; } /* * We're now finished for good with this ioend structure. * Update the page state via the associated buffer_heads, * release holds on the inode and bio, and finally free * up memory. Do not use the ioend after this. */ STATIC void xfs_destroy_ioend( xfs_ioend_t *ioend) { struct buffer_head *bh, *next; for (bh = ioend->io_buffer_head; bh; bh = next) { next = bh->b_private; bh->b_end_io(bh, !ioend->io_error); } if (ioend->io_iocb) { inode_dio_done(ioend->io_inode); if (ioend->io_isasync) { aio_complete(ioend->io_iocb, ioend->io_error ? ioend->io_error : ioend->io_result, 0); } } mempool_free(ioend, xfs_ioend_pool); } /* * Fast and loose check if this write could update the on-disk inode size. */ static inline bool xfs_ioend_is_append(struct xfs_ioend *ioend) { return ioend->io_offset + ioend->io_size > XFS_I(ioend->io_inode)->i_d.di_size; } STATIC int xfs_setfilesize_trans_alloc( struct xfs_ioend *ioend) { struct xfs_mount *mp = XFS_I(ioend->io_inode)->i_mount; struct xfs_trans *tp; int error; tp = xfs_trans_alloc(mp, XFS_TRANS_FSYNC_TS); error = xfs_trans_reserve(tp, 0, XFS_FSYNC_TS_LOG_RES(mp), 0, 0, 0); if (error) { xfs_trans_cancel(tp, 0); return error; } ioend->io_append_trans = tp; /* * We may pass freeze protection with a transaction. So tell lockdep * we released it. */ rwsem_release(&ioend->io_inode->i_sb->s_writers.lock_map[SB_FREEZE_FS-1], 1, _THIS_IP_); /* * We hand off the transaction to the completion thread now, so * clear the flag here. */ current_restore_flags_nested(&tp->t_pflags, PF_FSTRANS); return 0; } /* * Update on-disk file size now that data has been written to disk. */ STATIC int xfs_setfilesize( struct xfs_ioend *ioend) { struct xfs_inode *ip = XFS_I(ioend->io_inode); struct xfs_trans *tp = ioend->io_append_trans; xfs_fsize_t isize; /* * The transaction may have been allocated in the I/O submission thread, * thus we need to mark ourselves as beeing in a transaction manually. * Similarly for freeze protection. */ current_set_flags_nested(&tp->t_pflags, PF_FSTRANS); rwsem_acquire_read(&VFS_I(ip)->i_sb->s_writers.lock_map[SB_FREEZE_FS-1], 0, 1, _THIS_IP_); xfs_ilock(ip, XFS_ILOCK_EXCL); isize = xfs_new_eof(ip, ioend->io_offset + ioend->io_size); if (!isize) { xfs_iunlock(ip, XFS_ILOCK_EXCL); xfs_trans_cancel(tp, 0); return 0; } trace_xfs_setfilesize(ip, ioend->io_offset, ioend->io_size); ip->i_d.di_size = isize; xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL); xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); return xfs_trans_commit(tp, 0); } /* * Schedule IO completion handling on the final put of an ioend. * * If there is no work to do we might as well call it a day and free the * ioend right now. */ STATIC void xfs_finish_ioend( struct xfs_ioend *ioend) { if (atomic_dec_and_test(&ioend->io_remaining)) { struct xfs_mount *mp = XFS_I(ioend->io_inode)->i_mount; if (ioend->io_type == XFS_IO_UNWRITTEN) queue_work(mp->m_unwritten_workqueue, &ioend->io_work); else if (ioend->io_append_trans || (ioend->io_isdirect && xfs_ioend_is_append(ioend))) queue_work(mp->m_data_workqueue, &ioend->io_work); else xfs_destroy_ioend(ioend); } } /* * IO write completion. */ STATIC void xfs_end_io( struct work_struct *work) { xfs_ioend_t *ioend = container_of(work, xfs_ioend_t, io_work); struct xfs_inode *ip = XFS_I(ioend->io_inode); int error = 0; if (XFS_FORCED_SHUTDOWN(ip->i_mount)) { ioend->io_error = -EIO; goto done; } if (ioend->io_error) goto done; /* * For unwritten extents we need to issue transactions to convert a * range to normal written extens after the data I/O has finished. */ if (ioend->io_type == XFS_IO_UNWRITTEN) { error = xfs_iomap_write_unwritten(ip, ioend->io_offset, ioend->io_size); } else if (ioend->io_isdirect && xfs_ioend_is_append(ioend)) { /* * For direct I/O we do not know if we need to allocate blocks * or not so we can't preallocate an append transaction as that * results in nested reservations and log space deadlocks. Hence * allocate the transaction here. While this is sub-optimal and * can block IO completion for some time, we're stuck with doing * it this way until we can pass the ioend to the direct IO * allocation callbacks and avoid nesting that way. */ error = xfs_setfilesize_trans_alloc(ioend); if (error) goto done; error = xfs_setfilesize(ioend); } else if (ioend->io_append_trans) { error = xfs_setfilesize(ioend); } else { ASSERT(!xfs_ioend_is_append(ioend)); } done: if (error) ioend->io_error = -error; xfs_destroy_ioend(ioend); } /* * Call IO completion handling in caller context on the final put of an ioend. */ STATIC void xfs_finish_ioend_sync( struct xfs_ioend *ioend) { if (atomic_dec_and_test(&ioend->io_remaining)) xfs_end_io(&ioend->io_work); } /* * Allocate and initialise an IO completion structure. * We need to track unwritten extent write completion here initially. * We'll need to extend this for updating the ondisk inode size later * (vs. incore size). */ STATIC xfs_ioend_t * xfs_alloc_ioend( struct inode *inode, unsigned int type) { xfs_ioend_t *ioend; ioend = mempool_alloc(xfs_ioend_pool, GFP_NOFS); /* * Set the count to 1 initially, which will prevent an I/O * completion callback from happening before we have started * all the I/O from calling the completion routine too early. */ atomic_set(&ioend->io_remaining, 1); ioend->io_isasync = 0; ioend->io_isdirect = 0; ioend->io_error = 0; ioend->io_list = NULL; ioend->io_type = type; ioend->io_inode = inode; ioend->io_buffer_head = NULL; ioend->io_buffer_tail = NULL; ioend->io_offset = 0; ioend->io_size = 0; ioend->io_iocb = NULL; ioend->io_result = 0; ioend->io_append_trans = NULL; INIT_WORK(&ioend->io_work, xfs_end_io); return ioend; } STATIC int xfs_map_blocks( struct inode *inode, loff_t offset, struct xfs_bmbt_irec *imap, int type, int nonblocking) { struct xfs_inode *ip = XFS_I(inode); struct xfs_mount *mp = ip->i_mount; ssize_t count = 1 << inode->i_blkbits; xfs_fileoff_t offset_fsb, end_fsb; int error = 0; int bmapi_flags = XFS_BMAPI_ENTIRE; int nimaps = 1; if (XFS_FORCED_SHUTDOWN(mp)) return -XFS_ERROR(EIO); if (type == XFS_IO_UNWRITTEN) bmapi_flags |= XFS_BMAPI_IGSTATE; if (!xfs_ilock_nowait(ip, XFS_ILOCK_SHARED)) { if (nonblocking) return -XFS_ERROR(EAGAIN); xfs_ilock(ip, XFS_ILOCK_SHARED); } ASSERT(ip->i_d.di_format != XFS_DINODE_FMT_BTREE || (ip->i_df.if_flags & XFS_IFEXTENTS)); ASSERT(offset <= mp->m_super->s_maxbytes); if (offset + count > mp->m_super->s_maxbytes) count = mp->m_super->s_maxbytes - offset; end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + count); offset_fsb = XFS_B_TO_FSBT(mp, offset); error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, imap, &nimaps, bmapi_flags); xfs_iunlock(ip, XFS_ILOCK_SHARED); if (error) return -XFS_ERROR(error); if (type == XFS_IO_DELALLOC && (!nimaps || isnullstartblock(imap->br_startblock))) { error = xfs_iomap_write_allocate(ip, offset, count, imap); if (!error) trace_xfs_map_blocks_alloc(ip, offset, count, type, imap); return -XFS_ERROR(error); } #ifdef DEBUG if (type == XFS_IO_UNWRITTEN) { ASSERT(nimaps); ASSERT(imap->br_startblock != HOLESTARTBLOCK); ASSERT(imap->br_startblock != DELAYSTARTBLOCK); } #endif if (nimaps) trace_xfs_map_blocks_found(ip, offset, count, type, imap); return 0; } STATIC int xfs_imap_valid( struct inode *inode, struct xfs_bmbt_irec *imap, xfs_off_t offset) { offset >>= inode->i_blkbits; return offset >= imap->br_startoff && offset < imap->br_startoff + imap->br_blockcount; } /* * BIO completion handler for buffered IO. */ STATIC void xfs_end_bio( struct bio *bio, int error) { xfs_ioend_t *ioend = bio->bi_private; ASSERT(atomic_read(&bio->bi_cnt) >= 1); ioend->io_error = test_bit(BIO_UPTODATE, &bio->bi_flags) ? 0 : error; /* Toss bio and pass work off to an xfsdatad thread */ bio->bi_private = NULL; bio->bi_end_io = NULL; bio_put(bio); xfs_finish_ioend(ioend); } STATIC void xfs_submit_ioend_bio( struct writeback_control *wbc, xfs_ioend_t *ioend, struct bio *bio) { atomic_inc(&ioend->io_remaining); bio->bi_private = ioend; bio->bi_end_io = xfs_end_bio; submit_bio(wbc->sync_mode == WB_SYNC_ALL ? WRITE_SYNC : WRITE, bio); } STATIC struct bio * xfs_alloc_ioend_bio( struct buffer_head *bh) { int nvecs = bio_get_nr_vecs(bh->b_bdev); struct bio *bio = bio_alloc(GFP_NOIO, nvecs); ASSERT(bio->bi_private == NULL); bio->bi_sector = bh->b_blocknr * (bh->b_size >> 9); bio->bi_bdev = bh->b_bdev; return bio; } STATIC void xfs_start_buffer_writeback( struct buffer_head *bh) { ASSERT(buffer_mapped(bh)); ASSERT(buffer_locked(bh)); ASSERT(!buffer_delay(bh)); ASSERT(!buffer_unwritten(bh)); mark_buffer_async_write(bh); set_buffer_uptodate(bh); clear_buffer_dirty(bh); } STATIC void xfs_start_page_writeback( struct page *page, int clear_dirty, int buffers) { ASSERT(PageLocked(page)); ASSERT(!PageWriteback(page)); if (clear_dirty) clear_page_dirty_for_io(page); set_page_writeback(page); unlock_page(page); /* If no buffers on the page are to be written, finish it here */ if (!buffers) end_page_writeback(page); } static inline int bio_add_buffer(struct bio *bio, struct buffer_head *bh) { return bio_add_page(bio, bh->b_page, bh->b_size, bh_offset(bh)); } /* * Submit all of the bios for all of the ioends we have saved up, covering the * initial writepage page and also any probed pages. * * Because we may have multiple ioends spanning a page, we need to start * writeback on all the buffers before we submit them for I/O. If we mark the * buffers as we got, then we can end up with a page that only has buffers * marked async write and I/O complete on can occur before we mark the other * buffers async write. * * The end result of this is that we trip a bug in end_page_writeback() because * we call it twice for the one page as the code in end_buffer_async_write() * assumes that all buffers on the page are started at the same time. * * The fix is two passes across the ioend list - one to start writeback on the * buffer_heads, and then submit them for I/O on the second pass. * * If @fail is non-zero, it means that we have a situation where some part of * the submission process has failed after we have marked paged for writeback * and unlocked them. In this situation, we need to fail the ioend chain rather * than submit it to IO. This typically only happens on a filesystem shutdown. */ STATIC void xfs_submit_ioend( struct writeback_control *wbc, xfs_ioend_t *ioend, int fail) { xfs_ioend_t *head = ioend; xfs_ioend_t *next; struct buffer_head *bh; struct bio *bio; sector_t lastblock = 0; /* Pass 1 - start writeback */ do { next = ioend->io_list; for (bh = ioend->io_buffer_head; bh; bh = bh->b_private) xfs_start_buffer_writeback(bh); } while ((ioend = next) != NULL); /* Pass 2 - submit I/O */ ioend = head; do { next = ioend->io_list; bio = NULL; /* * If we are failing the IO now, just mark the ioend with an * error and finish it. This will run IO completion immediately * as there is only one reference to the ioend at this point in * time. */ if (fail) { ioend->io_error = -fail; xfs_finish_ioend(ioend); continue; } for (bh = ioend->io_buffer_head; bh; bh = bh->b_private) { if (!bio) { retry: bio = xfs_alloc_ioend_bio(bh); } else if (bh->b_blocknr != lastblock + 1) { xfs_submit_ioend_bio(wbc, ioend, bio); goto retry; } if (bio_add_buffer(bio, bh) != bh->b_size) { xfs_submit_ioend_bio(wbc, ioend, bio); goto retry; } lastblock = bh->b_blocknr; } if (bio) xfs_submit_ioend_bio(wbc, ioend, bio); xfs_finish_ioend(ioend); } while ((ioend = next) != NULL); } /* * Cancel submission of all buffer_heads so far in this endio. * Toss the endio too. Only ever called for the initial page * in a writepage request, so only ever one page. */ STATIC void xfs_cancel_ioend( xfs_ioend_t *ioend) { xfs_ioend_t *next; struct buffer_head *bh, *next_bh; do { next = ioend->io_list; bh = ioend->io_buffer_head; do { next_bh = bh->b_private; clear_buffer_async_write(bh); unlock_buffer(bh); } while ((bh = next_bh) != NULL); mempool_free(ioend, xfs_ioend_pool); } while ((ioend = next) != NULL); } /* * Test to see if we've been building up a completion structure for * earlier buffers -- if so, we try to append to this ioend if we * can, otherwise we finish off any current ioend and start another. * Return true if we've finished the given ioend. */ STATIC void xfs_add_to_ioend( struct inode *inode, struct buffer_head *bh, xfs_off_t offset, unsigned int type, xfs_ioend_t **result, int need_ioend) { xfs_ioend_t *ioend = *result; if (!ioend || need_ioend || type != ioend->io_type) { xfs_ioend_t *previous = *result; ioend = xfs_alloc_ioend(inode, type); ioend->io_offset = offset; ioend->io_buffer_head = bh; ioend->io_buffer_tail = bh; if (previous) previous->io_list = ioend; *result = ioend; } else { ioend->io_buffer_tail->b_private = bh; ioend->io_buffer_tail = bh; } bh->b_private = NULL; ioend->io_size += bh->b_size; } STATIC void xfs_map_buffer( struct inode *inode, struct buffer_head *bh, struct xfs_bmbt_irec *imap, xfs_off_t offset) { sector_t bn; struct xfs_mount *m = XFS_I(inode)->i_mount; xfs_off_t iomap_offset = XFS_FSB_TO_B(m, imap->br_startoff); xfs_daddr_t iomap_bn = xfs_fsb_to_db(XFS_I(inode), imap->br_startblock); ASSERT(imap->br_startblock != HOLESTARTBLOCK); ASSERT(imap->br_startblock != DELAYSTARTBLOCK); bn = (iomap_bn >> (inode->i_blkbits - BBSHIFT)) + ((offset - iomap_offset) >> inode->i_blkbits); ASSERT(bn || XFS_IS_REALTIME_INODE(XFS_I(inode))); bh->b_blocknr = bn; set_buffer_mapped(bh); } STATIC void xfs_map_at_offset( struct inode *inode, struct buffer_head *bh, struct xfs_bmbt_irec *imap, xfs_off_t offset) { ASSERT(imap->br_startblock != HOLESTARTBLOCK); ASSERT(imap->br_startblock != DELAYSTARTBLOCK); xfs_map_buffer(inode, bh, imap, offset); set_buffer_mapped(bh); clear_buffer_delay(bh); clear_buffer_unwritten(bh); } /* * Test if a given page is suitable for writing as part of an unwritten * or delayed allocate extent. */ STATIC int xfs_check_page_type( struct page *page, unsigned int type) { if (PageWriteback(page)) return 0; if (page->mapping && page_has_buffers(page)) { struct buffer_head *bh, *head; int acceptable = 0; bh = head = page_buffers(page); do { if (buffer_unwritten(bh)) acceptable += (type == XFS_IO_UNWRITTEN); else if (buffer_delay(bh)) acceptable += (type == XFS_IO_DELALLOC); else if (buffer_dirty(bh) && buffer_mapped(bh)) acceptable += (type == XFS_IO_OVERWRITE); else break; } while ((bh = bh->b_this_page) != head); if (acceptable) return 1; } return 0; } /* * Allocate & map buffers for page given the extent map. Write it out. * except for the original page of a writepage, this is called on * delalloc/unwritten pages only, for the original page it is possible * that the page has no mapping at all. */ STATIC int xfs_convert_page( struct inode *inode, struct page *page, loff_t tindex, struct xfs_bmbt_irec *imap, xfs_ioend_t **ioendp, struct writeback_control *wbc) { struct buffer_head *bh, *head; xfs_off_t end_offset; unsigned long p_offset; unsigned int type; int len, page_dirty; int count = 0, done = 0, uptodate = 1; xfs_off_t offset = page_offset(page); if (page->index != tindex) goto fail; if (!trylock_page(page)) goto fail; if (PageWriteback(page)) goto fail_unlock_page; if (page->mapping != inode->i_mapping) goto fail_unlock_page; if (!xfs_check_page_type(page, (*ioendp)->io_type)) goto fail_unlock_page; /* * page_dirty is initially a count of buffers on the page before * EOF and is decremented as we move each into a cleanable state. * * Derivation: * * End offset is the highest offset that this page should represent. * If we are on the last page, (end_offset & (PAGE_CACHE_SIZE - 1)) * will evaluate non-zero and be less than PAGE_CACHE_SIZE and * hence give us the correct page_dirty count. On any other page, * it will be zero and in that case we need page_dirty to be the * count of buffers on the page. */ end_offset = min_t(unsigned long long, (xfs_off_t)(page->index + 1) << PAGE_CACHE_SHIFT, i_size_read(inode)); /* * If the current map does not span the entire page we are about to try * to write, then give up. The only way we can write a page that spans * multiple mappings in a single writeback iteration is via the * xfs_vm_writepage() function. Data integrity writeback requires the * entire page to be written in a single attempt, otherwise the part of * the page we don't write here doesn't get written as part of the data * integrity sync. * * For normal writeback, we also don't attempt to write partial pages * here as it simply means that write_cache_pages() will see it under * writeback and ignore the page until some point in the future, at * which time this will be the only page in the file that needs * writeback. Hence for more optimal IO patterns, we should always * avoid partial page writeback due to multiple mappings on a page here. */ if (!xfs_imap_valid(inode, imap, end_offset)) goto fail_unlock_page; len = 1 << inode->i_blkbits; p_offset = min_t(unsigned long, end_offset & (PAGE_CACHE_SIZE - 1), PAGE_CACHE_SIZE); p_offset = p_offset ? roundup(p_offset, len) : PAGE_CACHE_SIZE; page_dirty = p_offset / len; bh = head = page_buffers(page); do { if (offset >= end_offset) break; if (!buffer_uptodate(bh)) uptodate = 0; if (!(PageUptodate(page) || buffer_uptodate(bh))) { done = 1; continue; } if (buffer_unwritten(bh) || buffer_delay(bh) || buffer_mapped(bh)) { if (buffer_unwritten(bh)) type = XFS_IO_UNWRITTEN; else if (buffer_delay(bh)) type = XFS_IO_DELALLOC; else type = XFS_IO_OVERWRITE; if (!xfs_imap_valid(inode, imap, offset)) { done = 1; continue; } lock_buffer(bh); if (type != XFS_IO_OVERWRITE) xfs_map_at_offset(inode, bh, imap, offset); xfs_add_to_ioend(inode, bh, offset, type, ioendp, done); page_dirty--; count++; } else { done = 1; } } while (offset += len, (bh = bh->b_this_page) != head); if (uptodate && bh == head) SetPageUptodate(page); if (count) { if (--wbc->nr_to_write <= 0 && wbc->sync_mode == WB_SYNC_NONE) done = 1; } xfs_start_page_writeback(page, !page_dirty, count); return done; fail_unlock_page: unlock_page(page); fail: return 1; } /* * Convert & write out a cluster of pages in the same extent as defined * by mp and following the start page. */ STATIC void xfs_cluster_write( struct inode *inode, pgoff_t tindex, struct xfs_bmbt_irec *imap, xfs_ioend_t **ioendp, struct writeback_control *wbc, pgoff_t tlast) { struct pagevec pvec; int done = 0, i; pagevec_init(&pvec, 0); while (!done && tindex <= tlast) { unsigned len = min_t(pgoff_t, PAGEVEC_SIZE, tlast - tindex + 1); if (!pagevec_lookup(&pvec, inode->i_mapping, tindex, len)) break; for (i = 0; i < pagevec_count(&pvec); i++) { done = xfs_convert_page(inode, pvec.pages[i], tindex++, imap, ioendp, wbc); if (done) break; } pagevec_release(&pvec); cond_resched(); } } STATIC void xfs_vm_invalidatepage( struct page *page, unsigned long offset) { trace_xfs_invalidatepage(page->mapping->host, page, offset); block_invalidatepage(page, offset); } /* * If the page has delalloc buffers on it, we need to punch them out before we * invalidate the page. If we don't, we leave a stale delalloc mapping on the * inode that can trip a BUG() in xfs_get_blocks() later on if a direct IO read * is done on that same region - the delalloc extent is returned when none is * supposed to be there. * * We prevent this by truncating away the delalloc regions on the page before * invalidating it. Because they are delalloc, we can do this without needing a * transaction. Indeed - if we get ENOSPC errors, we have to be able to do this * truncation without a transaction as there is no space left for block * reservation (typically why we see a ENOSPC in writeback). * * This is not a performance critical path, so for now just do the punching a * buffer head at a time. */ STATIC void xfs_aops_discard_page( struct page *page) { struct inode *inode = page->mapping->host; struct xfs_inode *ip = XFS_I(inode); struct buffer_head *bh, *head; loff_t offset = page_offset(page); if (!xfs_check_page_type(page, XFS_IO_DELALLOC)) goto out_invalidate; if (XFS_FORCED_SHUTDOWN(ip->i_mount)) goto out_invalidate; xfs_alert(ip->i_mount, "page discard on page %p, inode 0x%llx, offset %llu.", page, ip->i_ino, offset); xfs_ilock(ip, XFS_ILOCK_EXCL); bh = head = page_buffers(page); do { int error; xfs_fileoff_t start_fsb; if (!buffer_delay(bh)) goto next_buffer; start_fsb = XFS_B_TO_FSBT(ip->i_mount, offset); error = xfs_bmap_punch_delalloc_range(ip, start_fsb, 1); if (error) { /* something screwed, just bail */ if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) { xfs_alert(ip->i_mount, "page discard unable to remove delalloc mapping."); } break; } next_buffer: offset += 1 << inode->i_blkbits; } while ((bh = bh->b_this_page) != head); xfs_iunlock(ip, XFS_ILOCK_EXCL); out_invalidate: xfs_vm_invalidatepage(page, 0); return; } /* * Write out a dirty page. * * For delalloc space on the page we need to allocate space and flush it. * For unwritten space on the page we need to start the conversion to * regular allocated space. * For any other dirty buffer heads on the page we should flush them. */ STATIC int xfs_vm_writepage( struct page *page, struct writeback_control *wbc) { struct inode *inode = page->mapping->host; struct buffer_head *bh, *head; struct xfs_bmbt_irec imap; xfs_ioend_t *ioend = NULL, *iohead = NULL; loff_t offset; unsigned int type; __uint64_t end_offset; pgoff_t end_index, last_index; ssize_t len; int err, imap_valid = 0, uptodate = 1; int count = 0; int nonblocking = 0; trace_xfs_writepage(inode, page, 0); ASSERT(page_has_buffers(page)); /* * Refuse to write the page out if we are called from reclaim context. * * This avoids stack overflows when called from deeply used stacks in * random callers for direct reclaim or memcg reclaim. We explicitly * allow reclaim from kswapd as the stack usage there is relatively low. * * This should never happen except in the case of a VM regression so * warn about it. */ if (WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) == PF_MEMALLOC)) goto redirty; /* * Given that we do not allow direct reclaim to call us, we should * never be called while in a filesystem transaction. */ if (WARN_ON(current->flags & PF_FSTRANS)) goto redirty; /* Is this page beyond the end of the file? */ offset = i_size_read(inode); end_index = offset >> PAGE_CACHE_SHIFT; last_index = (offset - 1) >> PAGE_CACHE_SHIFT; if (page->index >= end_index) { unsigned offset_into_page = offset & (PAGE_CACHE_SIZE - 1); /* * Skip the page if it is fully outside i_size, e.g. due to a * truncate operation that is in progress. We must redirty the * page so that reclaim stops reclaiming it. Otherwise * xfs_vm_releasepage() is called on it and gets confused. */ if (page->index >= end_index + 1 || offset_into_page == 0) goto redirty; /* * The page straddles i_size. It must be zeroed out on each * and every writepage invocation because it may be mmapped. * "A file is mapped in multiples of the page size. For a file * that is not a multiple of the page size, the remaining * memory is zeroed when mapped, and writes to that region are * not written out to the file." */ zero_user_segment(page, offset_into_page, PAGE_CACHE_SIZE); } end_offset = min_t(unsigned long long, (xfs_off_t)(page->index + 1) << PAGE_CACHE_SHIFT, offset); len = 1 << inode->i_blkbits; bh = head = page_buffers(page); offset = page_offset(page); type = XFS_IO_OVERWRITE; if (wbc->sync_mode == WB_SYNC_NONE) nonblocking = 1; do { int new_ioend = 0; if (offset >= end_offset) break; if (!buffer_uptodate(bh)) uptodate = 0; /* * set_page_dirty dirties all buffers in a page, independent * of their state. The dirty state however is entirely * meaningless for holes (!mapped && uptodate), so skip * buffers covering holes here. */ if (!buffer_mapped(bh) && buffer_uptodate(bh)) { imap_valid = 0; continue; } if (buffer_unwritten(bh)) { if (type != XFS_IO_UNWRITTEN) { type = XFS_IO_UNWRITTEN; imap_valid = 0; } } else if (buffer_delay(bh)) { if (type != XFS_IO_DELALLOC) { type = XFS_IO_DELALLOC; imap_valid = 0; } } else if (buffer_uptodate(bh)) { if (type != XFS_IO_OVERWRITE) { type = XFS_IO_OVERWRITE; imap_valid = 0; } } else { if (PageUptodate(page)) ASSERT(buffer_mapped(bh)); /* * This buffer is not uptodate and will not be * written to disk. Ensure that we will put any * subsequent writeable buffers into a new * ioend. */ imap_valid = 0; continue; } if (imap_valid) imap_valid = xfs_imap_valid(inode, &imap, offset); if (!imap_valid) { /* * If we didn't have a valid mapping then we need to * put the new mapping into a separate ioend structure. * This ensures non-contiguous extents always have * separate ioends, which is particularly important * for unwritten extent conversion at I/O completion * time. */ new_ioend = 1; err = xfs_map_blocks(inode, offset, &imap, type, nonblocking); if (err) goto error; imap_valid = xfs_imap_valid(inode, &imap, offset); } if (imap_valid) { lock_buffer(bh); if (type != XFS_IO_OVERWRITE) xfs_map_at_offset(inode, bh, &imap, offset); xfs_add_to_ioend(inode, bh, offset, type, &ioend, new_ioend); count++; } if (!iohead) iohead = ioend; } while (offset += len, ((bh = bh->b_this_page) != head)); if (uptodate && bh == head) SetPageUptodate(page); xfs_start_page_writeback(page, 1, count); /* if there is no IO to be submitted for this page, we are done */ if (!ioend) return 0; ASSERT(iohead); /* * Any errors from this point onwards need tobe reported through the IO * completion path as we have marked the initial page as under writeback * and unlocked it. */ if (imap_valid) { xfs_off_t end_index; end_index = imap.br_startoff + imap.br_blockcount; /* to bytes */ end_index <<= inode->i_blkbits; /* to pages */ end_index = (end_index - 1) >> PAGE_CACHE_SHIFT; /* check against file size */ if (end_index > last_index) end_index = last_index; xfs_cluster_write(inode, page->index + 1, &imap, &ioend, wbc, end_index); } /* * Reserve log space if we might write beyond the on-disk inode size. */ err = 0; if (ioend->io_type != XFS_IO_UNWRITTEN && xfs_ioend_is_append(ioend)) err = xfs_setfilesize_trans_alloc(ioend); xfs_submit_ioend(wbc, iohead, err); return 0; error: if (iohead) xfs_cancel_ioend(iohead); if (err == -EAGAIN) goto redirty; xfs_aops_discard_page(page); ClearPageUptodate(page); unlock_page(page); return err; redirty: redirty_page_for_writepage(wbc, page); unlock_page(page); return 0; } STATIC int xfs_vm_writepages( struct address_space *mapping, struct writeback_control *wbc) { xfs_iflags_clear(XFS_I(mapping->host), XFS_ITRUNCATED); return generic_writepages(mapping, wbc); } /* * Called to move a page into cleanable state - and from there * to be released. The page should already be clean. We always * have buffer heads in this call. * * Returns 1 if the page is ok to release, 0 otherwise. */ STATIC int xfs_vm_releasepage( struct page *page, gfp_t gfp_mask) { int delalloc, unwritten; trace_xfs_releasepage(page->mapping->host, page, 0); xfs_count_page_state(page, &delalloc, &unwritten); if (WARN_ON(delalloc)) return 0; if (WARN_ON(unwritten)) return 0; return try_to_free_buffers(page); } STATIC int __xfs_get_blocks( struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create, int direct) { struct xfs_inode *ip = XFS_I(inode); struct xfs_mount *mp = ip->i_mount; xfs_fileoff_t offset_fsb, end_fsb; int error = 0; int lockmode = 0; struct xfs_bmbt_irec imap; int nimaps = 1; xfs_off_t offset; ssize_t size; int new = 0; if (XFS_FORCED_SHUTDOWN(mp)) return -XFS_ERROR(EIO); offset = (xfs_off_t)iblock << inode->i_blkbits; ASSERT(bh_result->b_size >= (1 << inode->i_blkbits)); size = bh_result->b_size; if (!create && direct && offset >= i_size_read(inode)) return 0; /* * Direct I/O is usually done on preallocated files, so try getting * a block mapping without an exclusive lock first. For buffered * writes we already have the exclusive iolock anyway, so avoiding * a lock roundtrip here by taking the ilock exclusive from the * beginning is a useful micro optimization. */ if (create && !direct) { lockmode = XFS_ILOCK_EXCL; xfs_ilock(ip, lockmode); } else { lockmode = xfs_ilock_map_shared(ip); } ASSERT(offset <= mp->m_super->s_maxbytes); if (offset + size > mp->m_super->s_maxbytes) size = mp->m_super->s_maxbytes - offset; end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + size); offset_fsb = XFS_B_TO_FSBT(mp, offset); error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap, &nimaps, XFS_BMAPI_ENTIRE); if (error) goto out_unlock; if (create && (!nimaps || (imap.br_startblock == HOLESTARTBLOCK || imap.br_startblock == DELAYSTARTBLOCK))) { if (direct || xfs_get_extsz_hint(ip)) { /* * Drop the ilock in preparation for starting the block * allocation transaction. It will be retaken * exclusively inside xfs_iomap_write_direct for the * actual allocation. */ xfs_iunlock(ip, lockmode); error = xfs_iomap_write_direct(ip, offset, size, &imap, nimaps); if (error) return -error; new = 1; } else { /* * Delalloc reservations do not require a transaction, * we can go on without dropping the lock here. If we * are allocating a new delalloc block, make sure that * we set the new flag so that we mark the buffer new so * that we know that it is newly allocated if the write * fails. */ if (nimaps && imap.br_startblock == HOLESTARTBLOCK) new = 1; error = xfs_iomap_write_delay(ip, offset, size, &imap); if (error) goto out_unlock; xfs_iunlock(ip, lockmode); } trace_xfs_get_blocks_alloc(ip, offset, size, 0, &imap); } else if (nimaps) { trace_xfs_get_blocks_found(ip, offset, size, 0, &imap); xfs_iunlock(ip, lockmode); } else { trace_xfs_get_blocks_notfound(ip, offset, size); goto out_unlock; } if (imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK) { /* * For unwritten extents do not report a disk address on * the read case (treat as if we're reading into a hole). */ if (create || !ISUNWRITTEN(&imap)) xfs_map_buffer(inode, bh_result, &imap, offset); if (create && ISUNWRITTEN(&imap)) { if (direct) bh_result->b_private = inode; set_buffer_unwritten(bh_result); } } /* * If this is a realtime file, data may be on a different device. * to that pointed to from the buffer_head b_bdev currently. */ bh_result->b_bdev = xfs_find_bdev_for_inode(inode); /* * If we previously allocated a block out beyond eof and we are now * coming back to use it then we will need to flag it as new even if it * has a disk address. * * With sub-block writes into unwritten extents we also need to mark * the buffer as new so that the unwritten parts of the buffer gets * correctly zeroed. */ if (create && ((!buffer_mapped(bh_result) && !buffer_uptodate(bh_result)) || (offset >= i_size_read(inode)) || (new || ISUNWRITTEN(&imap)))) set_buffer_new(bh_result); if (imap.br_startblock == DELAYSTARTBLOCK) { BUG_ON(direct); if (create) { set_buffer_uptodate(bh_result); set_buffer_mapped(bh_result); set_buffer_delay(bh_result); } } /* * If this is O_DIRECT or the mpage code calling tell them how large * the mapping is, so that we can avoid repeated get_blocks calls. */ if (direct || size > (1 << inode->i_blkbits)) { xfs_off_t mapping_size; mapping_size = imap.br_startoff + imap.br_blockcount - iblock; mapping_size <<= inode->i_blkbits; ASSERT(mapping_size > 0); if (mapping_size > size) mapping_size = size; if (mapping_size > LONG_MAX) mapping_size = LONG_MAX; bh_result->b_size = mapping_size; } return 0; out_unlock: xfs_iunlock(ip, lockmode); return -error; } int xfs_get_blocks( struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { return __xfs_get_blocks(inode, iblock, bh_result, create, 0); } STATIC int xfs_get_blocks_direct( struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { return __xfs_get_blocks(inode, iblock, bh_result, create, 1); } /* * Complete a direct I/O write request. * * If the private argument is non-NULL __xfs_get_blocks signals us that we * need to issue a transaction to convert the range from unwritten to written * extents. In case this is regular synchronous I/O we just call xfs_end_io * to do this and we are done. But in case this was a successful AIO * request this handler is called from interrupt context, from which we * can't start transactions. In that case offload the I/O completion to * the workqueues we also use for buffered I/O completion. */ STATIC void xfs_end_io_direct_write( struct kiocb *iocb, loff_t offset, ssize_t size, void *private, int ret, bool is_async) { struct xfs_ioend *ioend = iocb->private; /* * While the generic direct I/O code updates the inode size, it does * so only after the end_io handler is called, which means our * end_io handler thinks the on-disk size is outside the in-core * size. To prevent this just update it a little bit earlier here. */ if (offset + size > i_size_read(ioend->io_inode)) i_size_write(ioend->io_inode, offset + size); /* * blockdev_direct_IO can return an error even after the I/O * completion handler was called. Thus we need to protect * against double-freeing. */ iocb->private = NULL; ioend->io_offset = offset; ioend->io_size = size; ioend->io_iocb = iocb; ioend->io_result = ret; if (private && size > 0) ioend->io_type = XFS_IO_UNWRITTEN; if (is_async) { ioend->io_isasync = 1; xfs_finish_ioend(ioend); } else { xfs_finish_ioend_sync(ioend); } } STATIC ssize_t xfs_vm_direct_IO( int rw, struct kiocb *iocb, const struct iovec *iov, loff_t offset, unsigned long nr_segs) { struct inode *inode = iocb->ki_filp->f_mapping->host; struct block_device *bdev = xfs_find_bdev_for_inode(inode); struct xfs_ioend *ioend = NULL; ssize_t ret; if (rw & WRITE) { size_t size = iov_length(iov, nr_segs); /* * We cannot preallocate a size update transaction here as we * don't know whether allocation is necessary or not. Hence we * can only tell IO completion that one is necessary if we are * not doing unwritten extent conversion. */ iocb->private = ioend = xfs_alloc_ioend(inode, XFS_IO_DIRECT); if (offset + size > XFS_I(inode)->i_d.di_size) ioend->io_isdirect = 1; ret = __blockdev_direct_IO(rw, iocb, inode, bdev, iov, offset, nr_segs, xfs_get_blocks_direct, xfs_end_io_direct_write, NULL, 0); if (ret != -EIOCBQUEUED && iocb->private) goto out_destroy_ioend; } else { ret = __blockdev_direct_IO(rw, iocb, inode, bdev, iov, offset, nr_segs, xfs_get_blocks_direct, NULL, NULL, 0); } return ret; out_destroy_ioend: xfs_destroy_ioend(ioend); return ret; } /* * Punch out the delalloc blocks we have already allocated. * * Don't bother with xfs_setattr given that nothing can have made it to disk yet * as the page is still locked at this point. */ STATIC void xfs_vm_kill_delalloc_range( struct inode *inode, loff_t start, loff_t end) { struct xfs_inode *ip = XFS_I(inode); xfs_fileoff_t start_fsb; xfs_fileoff_t end_fsb; int error; start_fsb = XFS_B_TO_FSB(ip->i_mount, start); end_fsb = XFS_B_TO_FSB(ip->i_mount, end); if (end_fsb <= start_fsb) return; xfs_ilock(ip, XFS_ILOCK_EXCL); error = xfs_bmap_punch_delalloc_range(ip, start_fsb, end_fsb - start_fsb); if (error) { /* something screwed, just bail */ if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) { xfs_alert(ip->i_mount, "xfs_vm_write_failed: unable to clean up ino %lld", ip->i_ino); } } xfs_iunlock(ip, XFS_ILOCK_EXCL); } STATIC void xfs_vm_write_failed( struct inode *inode, struct page *page, loff_t pos, unsigned len) { loff_t block_offset = pos & PAGE_MASK; loff_t block_start; loff_t block_end; loff_t from = pos & (PAGE_CACHE_SIZE - 1); loff_t to = from + len; struct buffer_head *bh, *head; ASSERT(block_offset + from == pos); head = page_buffers(page); block_start = 0; for (bh = head; bh != head || !block_start; bh = bh->b_this_page, block_start = block_end, block_offset += bh->b_size) { block_end = block_start + bh->b_size; /* skip buffers before the write */ if (block_end <= from) continue; /* if the buffer is after the write, we're done */ if (block_start >= to) break; if (!buffer_delay(bh)) continue; if (!buffer_new(bh) && block_offset < i_size_read(inode)) continue; xfs_vm_kill_delalloc_range(inode, block_offset, block_offset + bh->b_size); } } /* * This used to call block_write_begin(), but it unlocks and releases the page * on error, and we need that page to be able to punch stale delalloc blocks out * on failure. hence we copy-n-waste it here and call xfs_vm_write_failed() at * the appropriate point. */ STATIC int xfs_vm_write_begin( struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { pgoff_t index = pos >> PAGE_CACHE_SHIFT; struct page *page; int status; ASSERT(len <= PAGE_CACHE_SIZE); page = grab_cache_page_write_begin(mapping, index, flags | AOP_FLAG_NOFS); if (!page) return -ENOMEM; status = __block_write_begin(page, pos, len, xfs_get_blocks); if (unlikely(status)) { struct inode *inode = mapping->host; xfs_vm_write_failed(inode, page, pos, len); unlock_page(page); if (pos + len > i_size_read(inode)) truncate_pagecache(inode, pos + len, i_size_read(inode)); page_cache_release(page); page = NULL; } *pagep = page; return status; } /* * On failure, we only need to kill delalloc blocks beyond EOF because they * will never be written. For blocks within EOF, generic_write_end() zeros them * so they are safe to leave alone and be written with all the other valid data. */ STATIC int xfs_vm_write_end( struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { int ret; ASSERT(len <= PAGE_CACHE_SIZE); ret = generic_write_end(file, mapping, pos, len, copied, page, fsdata); if (unlikely(ret < len)) { struct inode *inode = mapping->host; size_t isize = i_size_read(inode); loff_t to = pos + len; if (to > isize) { truncate_pagecache(inode, to, isize); xfs_vm_kill_delalloc_range(inode, isize, to); } } return ret; } STATIC sector_t xfs_vm_bmap( struct address_space *mapping, sector_t block) { struct inode *inode = (struct inode *)mapping->host; struct xfs_inode *ip = XFS_I(inode); trace_xfs_vm_bmap(XFS_I(inode)); xfs_ilock(ip, XFS_IOLOCK_SHARED); filemap_write_and_wait(mapping); xfs_iunlock(ip, XFS_IOLOCK_SHARED); return generic_block_bmap(mapping, block, xfs_get_blocks); } STATIC int xfs_vm_readpage( struct file *unused, struct page *page) { return mpage_readpage(page, xfs_get_blocks); } STATIC int xfs_vm_readpages( struct file *unused, struct address_space *mapping, struct list_head *pages, unsigned nr_pages) { return mpage_readpages(mapping, pages, nr_pages, xfs_get_blocks); } /* * This is basically a copy of __set_page_dirty_buffers() with one * small tweak: buffers beyond EOF do not get marked dirty. If we mark them * dirty, we'll never be able to clean them because we don't write buffers * beyond EOF, and that means we can't invalidate pages that span EOF * that have been marked dirty. Further, the dirty state can leak into * the file interior if the file is extended, resulting in all sorts of * bad things happening as the state does not match the underlying data. * * XXX: this really indicates that bufferheads in XFS need to die. Warts like * this only exist because of bufferheads and how the generic code manages them. */ STATIC int xfs_vm_set_page_dirty( struct page *page) { struct address_space *mapping = page->mapping; struct inode *inode = mapping->host; loff_t end_offset; loff_t offset; int newly_dirty; if (unlikely(!mapping)) return !TestSetPageDirty(page); end_offset = i_size_read(inode); offset = page_offset(page); spin_lock(&mapping->private_lock); if (page_has_buffers(page)) { struct buffer_head *head = page_buffers(page); struct buffer_head *bh = head; do { if (offset < end_offset) set_buffer_dirty(bh); bh = bh->b_this_page; offset += 1 << inode->i_blkbits; } while (bh != head); } newly_dirty = !TestSetPageDirty(page); spin_unlock(&mapping->private_lock); if (newly_dirty) { /* sigh - __set_page_dirty() is static, so copy it here, too */ unsigned long flags; spin_lock_irqsave(&mapping->tree_lock, flags); if (page->mapping) { /* Race with truncate? */ WARN_ON_ONCE(!PageUptodate(page)); account_page_dirtied(page, mapping); radix_tree_tag_set(&mapping->page_tree, page_index(page), PAGECACHE_TAG_DIRTY); } spin_unlock_irqrestore(&mapping->tree_lock, flags); __mark_inode_dirty(mapping->host, I_DIRTY_PAGES); } return newly_dirty; } const struct address_space_operations xfs_address_space_operations = { .readpage = xfs_vm_readpage, .readpages = xfs_vm_readpages, .writepage = xfs_vm_writepage, .writepages = xfs_vm_writepages, .set_page_dirty = xfs_vm_set_page_dirty, .releasepage = xfs_vm_releasepage, .invalidatepage = xfs_vm_invalidatepage, .write_begin = xfs_vm_write_begin, .write_end = xfs_vm_write_end, .bmap = xfs_vm_bmap, .direct_IO = xfs_vm_direct_IO, .migratepage = buffer_migrate_page, .is_partially_uptodate = block_is_partially_uptodate, .error_remove_page = generic_error_remove_page, };
apache-2.0
loilo-inc/PdfRendererCompat
lib/src/main/cpp/external/libpng/contrib/arm-neon/android-ndk.c
133
1358
/* contrib/arm-neon/android-ndk.c * * Copyright (c) 2014 Glenn Randers-Pehrson * Written by John Bowler, 2014. * Last changed in libpng 1.6.10 [March 6, 2014] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * SEE contrib/arm-neon/README before reporting bugs * * STATUS: COMPILED, UNTESTED * BUG REPORTS: png-mng-implement@sourceforge.net * * png_have_neon implemented for the Android NDK, see: * * Documentation: * http://www.kandroid.org/ndk/docs/CPU-ARM-NEON.html * http://code.google.com/p/android/issues/detail?id=49065 * * NOTE: this requires that libpng is built against the Android NDK and linked * with an implementation of the Android ARM 'cpu-features' library. The code * has been compiled only, not linked: no version of the library has been found, * only the header files exist in the NDK. */ #include <cpu-features.h> static int png_have_neon(png_structp png_ptr) { /* This is a whole lot easier than the linux code, however it is probably * implemented as below, therefore it is better to cache the result (these * function calls may be slow!) */ PNG_UNUSED(png_ptr) return android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM && (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0; }
apache-2.0
BackupGGCode/python-for-android
python3-alpha/openssl/crypto/ecdh/ecdhtest.c
652
10526
/* crypto/ecdh/ecdhtest.c */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * The Elliptic Curve Public-Key Crypto Library (ECC Code) included * herein is developed by SUN MICROSYSTEMS, INC., and is contributed * to the OpenSSL project. * * The ECC Code is licensed pursuant to the OpenSSL open source * license provided below. * * The ECDH software is originally written by Douglas Stebila of * Sun Microsystems Laboratories. * */ /* ==================================================================== * Copyright (c) 1998-2003 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../e_os.h" #include <openssl/opensslconf.h> /* for OPENSSL_NO_ECDH */ #include <openssl/crypto.h> #include <openssl/bio.h> #include <openssl/bn.h> #include <openssl/objects.h> #include <openssl/rand.h> #include <openssl/sha.h> #include <openssl/err.h> #ifdef OPENSSL_NO_ECDH int main(int argc, char *argv[]) { printf("No ECDH support\n"); return(0); } #else #include <openssl/ec.h> #include <openssl/ecdh.h> #ifdef OPENSSL_SYS_WIN16 #define MS_CALLBACK _far _loadds #else #define MS_CALLBACK #endif #if 0 static void MS_CALLBACK cb(int p, int n, void *arg); #endif static const char rnd_seed[] = "string to make the random number generator think it has entropy"; static const int KDF1_SHA1_len = 20; static void *KDF1_SHA1(const void *in, size_t inlen, void *out, size_t *outlen) { #ifndef OPENSSL_NO_SHA if (*outlen < SHA_DIGEST_LENGTH) return NULL; else *outlen = SHA_DIGEST_LENGTH; return SHA1(in, inlen, out); #else return NULL; #endif } static int test_ecdh_curve(int nid, const char *text, BN_CTX *ctx, BIO *out) { EC_KEY *a=NULL; EC_KEY *b=NULL; BIGNUM *x_a=NULL, *y_a=NULL, *x_b=NULL, *y_b=NULL; char buf[12]; unsigned char *abuf=NULL,*bbuf=NULL; int i,alen,blen,aout,bout,ret=0; const EC_GROUP *group; a = EC_KEY_new_by_curve_name(nid); b = EC_KEY_new_by_curve_name(nid); if (a == NULL || b == NULL) goto err; group = EC_KEY_get0_group(a); if ((x_a=BN_new()) == NULL) goto err; if ((y_a=BN_new()) == NULL) goto err; if ((x_b=BN_new()) == NULL) goto err; if ((y_b=BN_new()) == NULL) goto err; BIO_puts(out,"Testing key generation with "); BIO_puts(out,text); #ifdef NOISY BIO_puts(out,"\n"); #else (void)BIO_flush(out); #endif if (!EC_KEY_generate_key(a)) goto err; if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field) { if (!EC_POINT_get_affine_coordinates_GFp(group, EC_KEY_get0_public_key(a), x_a, y_a, ctx)) goto err; } #ifndef OPENSSL_NO_EC2M else { if (!EC_POINT_get_affine_coordinates_GF2m(group, EC_KEY_get0_public_key(a), x_a, y_a, ctx)) goto err; } #endif #ifdef NOISY BIO_puts(out," pri 1="); BN_print(out,a->priv_key); BIO_puts(out,"\n pub 1="); BN_print(out,x_a); BIO_puts(out,","); BN_print(out,y_a); BIO_puts(out,"\n"); #else BIO_printf(out," ."); (void)BIO_flush(out); #endif if (!EC_KEY_generate_key(b)) goto err; if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field) { if (!EC_POINT_get_affine_coordinates_GFp(group, EC_KEY_get0_public_key(b), x_b, y_b, ctx)) goto err; } #ifndef OPENSSL_NO_EC2M else { if (!EC_POINT_get_affine_coordinates_GF2m(group, EC_KEY_get0_public_key(b), x_b, y_b, ctx)) goto err; } #endif #ifdef NOISY BIO_puts(out," pri 2="); BN_print(out,b->priv_key); BIO_puts(out,"\n pub 2="); BN_print(out,x_b); BIO_puts(out,","); BN_print(out,y_b); BIO_puts(out,"\n"); #else BIO_printf(out,"."); (void)BIO_flush(out); #endif alen=KDF1_SHA1_len; abuf=(unsigned char *)OPENSSL_malloc(alen); aout=ECDH_compute_key(abuf,alen,EC_KEY_get0_public_key(b),a,KDF1_SHA1); #ifdef NOISY BIO_puts(out," key1 ="); for (i=0; i<aout; i++) { sprintf(buf,"%02X",abuf[i]); BIO_puts(out,buf); } BIO_puts(out,"\n"); #else BIO_printf(out,"."); (void)BIO_flush(out); #endif blen=KDF1_SHA1_len; bbuf=(unsigned char *)OPENSSL_malloc(blen); bout=ECDH_compute_key(bbuf,blen,EC_KEY_get0_public_key(a),b,KDF1_SHA1); #ifdef NOISY BIO_puts(out," key2 ="); for (i=0; i<bout; i++) { sprintf(buf,"%02X",bbuf[i]); BIO_puts(out,buf); } BIO_puts(out,"\n"); #else BIO_printf(out,"."); (void)BIO_flush(out); #endif if ((aout < 4) || (bout != aout) || (memcmp(abuf,bbuf,aout) != 0)) { #ifndef NOISY BIO_printf(out, " failed\n\n"); BIO_printf(out, "key a:\n"); BIO_printf(out, "private key: "); BN_print(out, EC_KEY_get0_private_key(a)); BIO_printf(out, "\n"); BIO_printf(out, "public key (x,y): "); BN_print(out, x_a); BIO_printf(out, ","); BN_print(out, y_a); BIO_printf(out, "\nkey b:\n"); BIO_printf(out, "private key: "); BN_print(out, EC_KEY_get0_private_key(b)); BIO_printf(out, "\n"); BIO_printf(out, "public key (x,y): "); BN_print(out, x_b); BIO_printf(out, ","); BN_print(out, y_b); BIO_printf(out, "\n"); BIO_printf(out, "generated key a: "); for (i=0; i<bout; i++) { sprintf(buf, "%02X", bbuf[i]); BIO_puts(out, buf); } BIO_printf(out, "\n"); BIO_printf(out, "generated key b: "); for (i=0; i<aout; i++) { sprintf(buf, "%02X", abuf[i]); BIO_puts(out,buf); } BIO_printf(out, "\n"); #endif fprintf(stderr,"Error in ECDH routines\n"); ret=0; } else { #ifndef NOISY BIO_printf(out, " ok\n"); #endif ret=1; } err: ERR_print_errors_fp(stderr); if (abuf != NULL) OPENSSL_free(abuf); if (bbuf != NULL) OPENSSL_free(bbuf); if (x_a) BN_free(x_a); if (y_a) BN_free(y_a); if (x_b) BN_free(x_b); if (y_b) BN_free(y_b); if (b) EC_KEY_free(b); if (a) EC_KEY_free(a); return(ret); } int main(int argc, char *argv[]) { BN_CTX *ctx=NULL; int ret=1; BIO *out; CRYPTO_malloc_debug_init(); CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); #ifdef OPENSSL_SYS_WIN32 CRYPTO_malloc_init(); #endif RAND_seed(rnd_seed, sizeof rnd_seed); out=BIO_new(BIO_s_file()); if (out == NULL) EXIT(1); BIO_set_fp(out,stdout,BIO_NOCLOSE); if ((ctx=BN_CTX_new()) == NULL) goto err; /* NIST PRIME CURVES TESTS */ if (!test_ecdh_curve(NID_X9_62_prime192v1, "NIST Prime-Curve P-192", ctx, out)) goto err; if (!test_ecdh_curve(NID_secp224r1, "NIST Prime-Curve P-224", ctx, out)) goto err; if (!test_ecdh_curve(NID_X9_62_prime256v1, "NIST Prime-Curve P-256", ctx, out)) goto err; if (!test_ecdh_curve(NID_secp384r1, "NIST Prime-Curve P-384", ctx, out)) goto err; if (!test_ecdh_curve(NID_secp521r1, "NIST Prime-Curve P-521", ctx, out)) goto err; #ifndef OPENSSL_NO_EC2M /* NIST BINARY CURVES TESTS */ if (!test_ecdh_curve(NID_sect163k1, "NIST Binary-Curve K-163", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect163r2, "NIST Binary-Curve B-163", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect233k1, "NIST Binary-Curve K-233", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect233r1, "NIST Binary-Curve B-233", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect283k1, "NIST Binary-Curve K-283", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect283r1, "NIST Binary-Curve B-283", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect409k1, "NIST Binary-Curve K-409", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect409r1, "NIST Binary-Curve B-409", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect571k1, "NIST Binary-Curve K-571", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect571r1, "NIST Binary-Curve B-571", ctx, out)) goto err; #endif ret = 0; err: ERR_print_errors_fp(stderr); if (ctx) BN_CTX_free(ctx); BIO_free(out); CRYPTO_cleanup_all_ex_data(); ERR_remove_thread_state(NULL); CRYPTO_mem_leaks_fp(stderr); EXIT(ret); return(ret); } #if 0 static void MS_CALLBACK cb(int p, int n, void *arg) { char c='*'; if (p == 0) c='.'; if (p == 1) c='+'; if (p == 2) c='*'; if (p == 3) c='\n'; BIO_write((BIO *)arg,&c,1); (void)BIO_flush((BIO *)arg); #ifdef LINT p=n; #endif } #endif #endif
apache-2.0
tung7970/mbed-os-1
hal/targets/hal/TARGET_Freescale/TARGET_KSDK2_MCUS/TARGET_KL27Z/drivers/fsl_tpm.c
167
25738
/* * Copyright (c) 2015, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "fsl_tpm.h" /******************************************************************************* * Definitions ******************************************************************************/ #define TPM_COMBINE_SHIFT (8U) /******************************************************************************* * Prototypes ******************************************************************************/ /*! * @brief Gets the instance from the base address * * @param base TPM peripheral base address * * @return The TPM instance */ static uint32_t TPM_GetInstance(TPM_Type *base); /******************************************************************************* * Variables ******************************************************************************/ /*! @brief Pointers to TPM bases for each instance. */ static TPM_Type *const s_tpmBases[] = TPM_BASE_PTRS; /*! @brief Pointers to TPM clocks for each instance. */ static const clock_ip_name_t s_tpmClocks[] = TPM_CLOCKS; /******************************************************************************* * Code ******************************************************************************/ static uint32_t TPM_GetInstance(TPM_Type *base) { uint32_t instance; uint32_t tpmArrayCount = (sizeof(s_tpmBases) / sizeof(s_tpmBases[0])); /* Find the instance index from base address mappings. */ for (instance = 0; instance < tpmArrayCount; instance++) { if (s_tpmBases[instance] == base) { break; } } assert(instance < tpmArrayCount); return instance; } void TPM_Init(TPM_Type *base, const tpm_config_t *config) { assert(config); /* Enable the module clock */ CLOCK_EnableClock(s_tpmClocks[TPM_GetInstance(base)]); #if defined(FSL_FEATURE_TPM_HAS_GLOBAL) && FSL_FEATURE_TPM_HAS_GLOBAL /* TPM reset is available on certain SoC's */ TPM_Reset(base); #endif /* Set the clock prescale factor */ base->SC = TPM_SC_PS(config->prescale); /* Setup the counter operation */ base->CONF = TPM_CONF_DOZEEN(config->enableDoze) | TPM_CONF_GTBEEN(config->useGlobalTimeBase) | TPM_CONF_CROT(config->enableReloadOnTrigger) | TPM_CONF_CSOT(config->enableStartOnTrigger) | TPM_CONF_CSOO(config->enableStopOnOverflow) | #if defined(FSL_FEATURE_TPM_HAS_PAUSE_COUNTER_ON_TRIGGER) && FSL_FEATURE_TPM_HAS_PAUSE_COUNTER_ON_TRIGGER TPM_CONF_CPOT(config->enablePauseOnTrigger) | #endif #if defined(FSL_FEATURE_TPM_HAS_EXTERNAL_TRIGGER_SELECTION) && FSL_FEATURE_TPM_HAS_EXTERNAL_TRIGGER_SELECTION TPM_CONF_TRGSRC(config->triggerSource) | #endif TPM_CONF_TRGSEL(config->triggerSelect); if (config->enableDebugMode) { base->CONF |= TPM_CONF_DBGMODE_MASK; } else { base->CONF &= ~TPM_CONF_DBGMODE_MASK; } } void TPM_Deinit(TPM_Type *base) { /* Stop the counter */ base->SC &= ~TPM_SC_CMOD_MASK; /* Gate the TPM clock */ CLOCK_DisableClock(s_tpmClocks[TPM_GetInstance(base)]); } void TPM_GetDefaultConfig(tpm_config_t *config) { assert(config); /* TPM clock divide by 1 */ config->prescale = kTPM_Prescale_Divide_1; /* Use internal TPM counter as timebase */ config->useGlobalTimeBase = false; /* TPM counter continues in doze mode */ config->enableDoze = false; /* TPM counter pauses when in debug mode */ config->enableDebugMode = false; /* TPM counter will not be reloaded on input trigger */ config->enableReloadOnTrigger = false; /* TPM counter continues running after overflow */ config->enableStopOnOverflow = false; /* TPM counter starts immediately once it is enabled */ config->enableStartOnTrigger = false; #if defined(FSL_FEATURE_TPM_HAS_PAUSE_COUNTER_ON_TRIGGER) && FSL_FEATURE_TPM_HAS_PAUSE_COUNTER_ON_TRIGGER config->enablePauseOnTrigger = false; #endif /* Choose trigger select 0 as input trigger for controlling counter operation */ config->triggerSelect = kTPM_Trigger_Select_0; #if defined(FSL_FEATURE_TPM_HAS_EXTERNAL_TRIGGER_SELECTION) && FSL_FEATURE_TPM_HAS_EXTERNAL_TRIGGER_SELECTION /* Choose external trigger source to control counter operation */ config->triggerSource = kTPM_TriggerSource_External; #endif } status_t TPM_SetupPwm(TPM_Type *base, const tpm_chnl_pwm_signal_param_t *chnlParams, uint8_t numOfChnls, tpm_pwm_mode_t mode, uint32_t pwmFreq_Hz, uint32_t srcClock_Hz) { assert(chnlParams); assert(pwmFreq_Hz); assert(numOfChnls); assert(srcClock_Hz); uint32_t mod; uint32_t tpmClock = (srcClock_Hz / (1U << (base->SC & TPM_SC_PS_MASK))); uint16_t cnv; uint8_t i; #if defined(FSL_FEATURE_TPM_HAS_QDCTRL) && FSL_FEATURE_TPM_HAS_QDCTRL /* Clear quadrature Decoder mode because in quadrature Decoder mode PWM doesn't operate*/ base->QDCTRL &= ~TPM_QDCTRL_QUADEN_MASK; #endif switch (mode) { case kTPM_EdgeAlignedPwm: #if defined(FSL_FEATURE_TPM_HAS_COMBINE) && FSL_FEATURE_TPM_HAS_COMBINE case kTPM_CombinedPwm: #endif base->SC &= ~TPM_SC_CPWMS_MASK; mod = (tpmClock / pwmFreq_Hz) - 1; break; case kTPM_CenterAlignedPwm: base->SC |= TPM_SC_CPWMS_MASK; mod = tpmClock / (pwmFreq_Hz * 2); break; default: return kStatus_Fail; } /* Return an error in case we overflow the registers, probably would require changing * clock source to get the desired frequency */ if (mod > 65535U) { return kStatus_Fail; } /* Set the PWM period */ base->MOD = mod; /* Setup each TPM channel */ for (i = 0; i < numOfChnls; i++) { /* Return error if requested dutycycle is greater than the max allowed */ if (chnlParams->dutyCyclePercent > 100) { return kStatus_Fail; } #if defined(FSL_FEATURE_TPM_HAS_COMBINE) && FSL_FEATURE_TPM_HAS_COMBINE if (mode == kTPM_CombinedPwm) { uint16_t cnvFirstEdge; /* This check is added for combined mode as the channel number should be the pair number */ if (chnlParams->chnlNumber >= (FSL_FEATURE_TPM_CHANNEL_COUNTn(base) / 2)) { return kStatus_Fail; } /* Return error if requested value is greater than the max allowed */ if (chnlParams->firstEdgeDelayPercent > 100) { return kStatus_Fail; } /* Configure delay of the first edge */ if (chnlParams->firstEdgeDelayPercent == 0) { /* No delay for the first edge */ cnvFirstEdge = 0; } else { cnvFirstEdge = (mod * chnlParams->firstEdgeDelayPercent) / 100; } /* Configure dutycycle */ if (chnlParams->dutyCyclePercent == 0) { /* Signal stays low */ cnv = 0; cnvFirstEdge = 0; } else { cnv = (mod * chnlParams->dutyCyclePercent) / 100; /* For 100% duty cycle */ if (cnv >= mod) { cnv = mod + 1; } } /* Set the combine bit for the channel pair */ base->COMBINE |= (1U << (TPM_COMBINE_COMBINE0_SHIFT + (TPM_COMBINE_SHIFT * chnlParams->chnlNumber))); /* When switching mode, disable channel n first */ base->CONTROLS[chnlParams->chnlNumber * 2].CnSC &= ~(TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); /* Wait till mode change to disable channel is acknowledged */ while ((base->CONTROLS[chnlParams->chnlNumber * 2].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Set the requested PWM mode for channel n, PWM output requires mode select to be set to 2 */ base->CONTROLS[chnlParams->chnlNumber * 2].CnSC |= ((chnlParams->level << TPM_CnSC_ELSA_SHIFT) | (2U << TPM_CnSC_MSA_SHIFT)); /* Wait till mode change is acknowledged */ while (!(base->CONTROLS[chnlParams->chnlNumber * 2].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Set the channel pair values */ base->CONTROLS[chnlParams->chnlNumber * 2].CnV = cnvFirstEdge; /* When switching mode, disable channel n + 1 first */ base->CONTROLS[(chnlParams->chnlNumber * 2) + 1].CnSC &= ~(TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); /* Wait till mode change to disable channel is acknowledged */ while ((base->CONTROLS[(chnlParams->chnlNumber * 2) + 1].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Set the requested PWM mode for channel n + 1, PWM output requires mode select to be set to 2 */ base->CONTROLS[(chnlParams->chnlNumber * 2) + 1].CnSC |= ((chnlParams->level << TPM_CnSC_ELSA_SHIFT) | (2U << TPM_CnSC_MSA_SHIFT)); /* Wait till mode change is acknowledged */ while (!(base->CONTROLS[(chnlParams->chnlNumber * 2) + 1].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Set the channel pair values */ base->CONTROLS[(chnlParams->chnlNumber * 2) + 1].CnV = cnvFirstEdge + cnv; } else { #endif if (chnlParams->dutyCyclePercent == 0) { /* Signal stays low */ cnv = 0; } else { cnv = (mod * chnlParams->dutyCyclePercent) / 100; /* For 100% duty cycle */ if (cnv >= mod) { cnv = mod + 1; } } /* When switching mode, disable channel first */ base->CONTROLS[chnlParams->chnlNumber].CnSC &= ~(TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); /* Wait till mode change to disable channel is acknowledged */ while ((base->CONTROLS[chnlParams->chnlNumber].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Set the requested PWM mode, PWM output requires mode select to be set to 2 */ base->CONTROLS[chnlParams->chnlNumber].CnSC |= ((chnlParams->level << TPM_CnSC_ELSA_SHIFT) | (2U << TPM_CnSC_MSA_SHIFT)); /* Wait till mode change is acknowledged */ while (!(base->CONTROLS[chnlParams->chnlNumber].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } base->CONTROLS[chnlParams->chnlNumber].CnV = cnv; #if defined(FSL_FEATURE_TPM_HAS_COMBINE) && FSL_FEATURE_TPM_HAS_COMBINE } #endif chnlParams++; } return kStatus_Success; } void TPM_UpdatePwmDutycycle(TPM_Type *base, tpm_chnl_t chnlNumber, tpm_pwm_mode_t currentPwmMode, uint8_t dutyCyclePercent) { assert(chnlNumber < FSL_FEATURE_TPM_CHANNEL_COUNTn(base)); uint16_t cnv, mod; mod = base->MOD; #if defined(FSL_FEATURE_TPM_HAS_COMBINE) && FSL_FEATURE_TPM_HAS_COMBINE if (currentPwmMode == kTPM_CombinedPwm) { uint16_t cnvFirstEdge; /* This check is added for combined mode as the channel number should be the pair number */ if (chnlNumber >= (FSL_FEATURE_TPM_CHANNEL_COUNTn(base) / 2)) { return; } cnv = (mod * dutyCyclePercent) / 100; cnvFirstEdge = base->CONTROLS[chnlNumber * 2].CnV; /* For 100% duty cycle */ if (cnv >= mod) { cnv = mod + 1; } base->CONTROLS[(chnlNumber * 2) + 1].CnV = cnvFirstEdge + cnv; } else { #endif cnv = (mod * dutyCyclePercent) / 100; /* For 100% duty cycle */ if (cnv >= mod) { cnv = mod + 1; } base->CONTROLS[chnlNumber].CnV = cnv; #if defined(FSL_FEATURE_TPM_HAS_COMBINE) && FSL_FEATURE_TPM_HAS_COMBINE } #endif } void TPM_UpdateChnlEdgeLevelSelect(TPM_Type *base, tpm_chnl_t chnlNumber, uint8_t level) { assert(chnlNumber < FSL_FEATURE_TPM_CHANNEL_COUNTn(base)); uint32_t reg = base->CONTROLS[chnlNumber].CnSC & ~(TPM_CnSC_CHF_MASK); /* When switching mode, disable channel first */ base->CONTROLS[chnlNumber].CnSC &= ~(TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); /* Wait till mode change to disable channel is acknowledged */ while ((base->CONTROLS[chnlNumber].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Clear the field and write the new level value */ reg &= ~(TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); reg |= ((uint32_t)level << TPM_CnSC_ELSA_SHIFT) & (TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); base->CONTROLS[chnlNumber].CnSC = reg; /* Wait till mode change is acknowledged */ reg &= (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); while (reg != (base->CONTROLS[chnlNumber].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } } void TPM_SetupInputCapture(TPM_Type *base, tpm_chnl_t chnlNumber, tpm_input_capture_edge_t captureMode) { assert(chnlNumber < FSL_FEATURE_TPM_CHANNEL_COUNTn(base)); #if defined(FSL_FEATURE_TPM_HAS_QDCTRL) && FSL_FEATURE_TPM_HAS_QDCTRL /* Clear quadrature Decoder mode for channel 0 or 1*/ if ((chnlNumber == 0) || (chnlNumber == 1)) { base->QDCTRL &= ~TPM_QDCTRL_QUADEN_MASK; } #endif #if defined(FSL_FEATURE_TPM_HAS_COMBINE) && FSL_FEATURE_TPM_HAS_COMBINE /* Clear the combine bit for chnlNumber */ base->COMBINE &= ~(1U << TPM_COMBINE_SHIFT * (chnlNumber / 2)); #endif /* When switching mode, disable channel first */ base->CONTROLS[chnlNumber].CnSC &= ~(TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); /* Wait till mode change to disable channel is acknowledged */ while ((base->CONTROLS[chnlNumber].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Set the requested input capture mode */ base->CONTROLS[chnlNumber].CnSC |= captureMode; /* Wait till mode change is acknowledged */ while (!(base->CONTROLS[chnlNumber].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } } void TPM_SetupOutputCompare(TPM_Type *base, tpm_chnl_t chnlNumber, tpm_output_compare_mode_t compareMode, uint32_t compareValue) { assert(chnlNumber < FSL_FEATURE_TPM_CHANNEL_COUNTn(base)); #if defined(FSL_FEATURE_TPM_HAS_QDCTRL) && FSL_FEATURE_TPM_HAS_QDCTRL /* Clear quadrature Decoder mode for channel 0 or 1 */ if ((chnlNumber == 0) || (chnlNumber == 1)) { base->QDCTRL &= ~TPM_QDCTRL_QUADEN_MASK; } #endif /* When switching mode, disable channel first */ base->CONTROLS[chnlNumber].CnSC &= ~(TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); /* Wait till mode change to disable channel is acknowledged */ while ((base->CONTROLS[chnlNumber].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Setup the channel output behaviour when a match occurs with the compare value */ base->CONTROLS[chnlNumber].CnSC |= compareMode; /* Setup the compare value */ base->CONTROLS[chnlNumber].CnV = compareValue; /* Wait till mode change is acknowledged */ while (!(base->CONTROLS[chnlNumber].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } } #if defined(FSL_FEATURE_TPM_HAS_COMBINE) && FSL_FEATURE_TPM_HAS_COMBINE void TPM_SetupDualEdgeCapture(TPM_Type *base, tpm_chnl_t chnlPairNumber, const tpm_dual_edge_capture_param_t *edgeParam, uint32_t filterValue) { assert(edgeParam); assert(chnlPairNumber < FSL_FEATURE_TPM_CHANNEL_COUNTn(base) / 2); uint32_t reg; /* Clear quadrature Decoder mode for channel 0 or 1*/ #if defined(FSL_FEATURE_TPM_HAS_QDCTRL) && FSL_FEATURE_TPM_HAS_QDCTRL if (chnlPairNumber == 0) { base->QDCTRL &= ~TPM_QDCTRL_QUADEN_MASK; } #endif /* Unlock: When switching mode, disable channel first */ base->CONTROLS[chnlPairNumber * 2].CnSC &= ~(TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); /* Wait till mode change to disable channel is acknowledged */ while ((base->CONTROLS[chnlPairNumber * 2].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } base->CONTROLS[chnlPairNumber * 2 + 1].CnSC &= ~(TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); /* Wait till mode change to disable channel is acknowledged */ while ((base->CONTROLS[chnlPairNumber * 2 + 1].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Now, the registers for input mode can be operated. */ if (edgeParam->enableSwap) { /* Set the combine and swap bits for the channel pair */ base->COMBINE |= (TPM_COMBINE_COMBINE0_MASK | TPM_COMBINE_COMSWAP0_MASK) << (TPM_COMBINE_SHIFT * chnlPairNumber); /* Input filter setup for channel n+1 input */ reg = base->FILTER; reg &= ~(TPM_FILTER_CH0FVAL_MASK << (TPM_FILTER_CH1FVAL_SHIFT * (chnlPairNumber + 1))); reg |= (filterValue << (TPM_FILTER_CH1FVAL_SHIFT * (chnlPairNumber + 1))); base->FILTER = reg; } else { reg = base->COMBINE; /* Clear the swap bit for the channel pair */ reg &= ~(TPM_COMBINE_COMSWAP0_MASK << (TPM_COMBINE_COMSWAP0_SHIFT * chnlPairNumber)); /* Set the combine bit for the channel pair */ reg |= TPM_COMBINE_COMBINE0_MASK << (TPM_COMBINE_SHIFT * chnlPairNumber); base->COMBINE = reg; /* Input filter setup for channel n input */ reg = base->FILTER; reg &= ~(TPM_FILTER_CH0FVAL_MASK << (TPM_FILTER_CH1FVAL_SHIFT * chnlPairNumber)); reg |= (filterValue << (TPM_FILTER_CH1FVAL_SHIFT * chnlPairNumber)); base->FILTER = reg; } /* Setup the edge detection from channel n */ base->CONTROLS[chnlPairNumber * 2].CnSC |= edgeParam->currChanEdgeMode; /* Wait till mode change is acknowledged */ while (!(base->CONTROLS[chnlPairNumber * 2].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Setup the edge detection from channel n+1 */ base->CONTROLS[(chnlPairNumber * 2) + 1].CnSC |= edgeParam->nextChanEdgeMode; /* Wait till mode change is acknowledged */ while (!(base->CONTROLS[(chnlPairNumber * 2) + 1].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } } #endif #if defined(FSL_FEATURE_TPM_HAS_QDCTRL) && FSL_FEATURE_TPM_HAS_QDCTRL void TPM_SetupQuadDecode(TPM_Type *base, const tpm_phase_params_t *phaseAParams, const tpm_phase_params_t *phaseBParams, tpm_quad_decode_mode_t quadMode) { assert(phaseAParams); assert(phaseBParams); base->CONTROLS[0].CnSC &= ~(TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); /* Wait till mode change to disable channel is acknowledged */ while ((base->CONTROLS[0].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } uint32_t reg; /* Set Phase A filter value */ reg = base->FILTER; reg &= ~(TPM_FILTER_CH0FVAL_MASK); reg |= TPM_FILTER_CH0FVAL(phaseAParams->phaseFilterVal); base->FILTER = reg; #if defined(FSL_FEATURE_TPM_HAS_POL) && FSL_FEATURE_TPM_HAS_POL /* Set Phase A polarity */ if (phaseAParams->phasePolarity) { base->POL |= TPM_POL_POL0_MASK; } else { base->POL &= ~TPM_POL_POL0_MASK; } #endif base->CONTROLS[1].CnSC &= ~(TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK); /* Wait till mode change to disable channel is acknowledged */ while ((base->CONTROLS[1].CnSC & (TPM_CnSC_MSA_MASK | TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK | TPM_CnSC_ELSB_MASK))) { } /* Set Phase B filter value */ reg = base->FILTER; reg &= ~(TPM_FILTER_CH1FVAL_MASK); reg |= TPM_FILTER_CH1FVAL(phaseBParams->phaseFilterVal); base->FILTER = reg; #if defined(FSL_FEATURE_TPM_HAS_POL) && FSL_FEATURE_TPM_HAS_POL /* Set Phase B polarity */ if (phaseBParams->phasePolarity) { base->POL |= TPM_POL_POL1_MASK; } else { base->POL &= ~TPM_POL_POL1_MASK; } #endif /* Set Quadrature mode */ reg = base->QDCTRL; reg &= ~(TPM_QDCTRL_QUADMODE_MASK); reg |= TPM_QDCTRL_QUADMODE(quadMode); base->QDCTRL = reg; /* Enable Quad decode */ base->QDCTRL |= TPM_QDCTRL_QUADEN_MASK; } #endif void TPM_EnableInterrupts(TPM_Type *base, uint32_t mask) { uint32_t chnlInterrupts = (mask & 0xFF); uint8_t chnlNumber = 0; /* Enable the timer overflow interrupt */ if (mask & kTPM_TimeOverflowInterruptEnable) { base->SC |= TPM_SC_TOIE_MASK; } /* Enable the channel interrupts */ while (chnlInterrupts) { if (chnlInterrupts & 0x1) { base->CONTROLS[chnlNumber].CnSC |= TPM_CnSC_CHIE_MASK; } chnlNumber++; chnlInterrupts = chnlInterrupts >> 1U; } } void TPM_DisableInterrupts(TPM_Type *base, uint32_t mask) { uint32_t chnlInterrupts = (mask & 0xFF); uint8_t chnlNumber = 0; /* Disable the timer overflow interrupt */ if (mask & kTPM_TimeOverflowInterruptEnable) { base->SC &= ~TPM_SC_TOIE_MASK; } /* Disable the channel interrupts */ while (chnlInterrupts) { if (chnlInterrupts & 0x1) { base->CONTROLS[chnlNumber].CnSC &= ~TPM_CnSC_CHIE_MASK; } chnlNumber++; chnlInterrupts = chnlInterrupts >> 1U; } } uint32_t TPM_GetEnabledInterrupts(TPM_Type *base) { uint32_t enabledInterrupts = 0; int8_t chnlCount = FSL_FEATURE_TPM_CHANNEL_COUNTn(base); /* The CHANNEL_COUNT macro returns -1 if it cannot match the TPM instance */ assert(chnlCount != -1); /* Check if timer overflow interrupt is enabled */ if (base->SC & TPM_SC_TOIE_MASK) { enabledInterrupts |= kTPM_TimeOverflowInterruptEnable; } /* Check if the channel interrupts are enabled */ while (chnlCount > 0) { chnlCount--; if (base->CONTROLS[chnlCount].CnSC & TPM_CnSC_CHIE_MASK) { enabledInterrupts |= (1U << chnlCount); } } return enabledInterrupts; }
apache-2.0
zjshen/hadoop-in-docker
hadoop-hdfs-project/hadoop-hdfs/src/main/native/fuse-dfs/fuse_stat_struct.c
205
3402
/** * 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. */ #include <math.h> #include <pthread.h> #include <grp.h> #include <pwd.h> #include "fuse_dfs.h" #include "fuse_stat_struct.h" #include "fuse_context_handle.h" /* * getpwuid and getgrgid return static structs so we safeguard the contents * while retrieving fields using the 2 structs below. * NOTE: if using both, always get the passwd struct firt! */ extern pthread_mutex_t passwdstruct_mutex; extern pthread_mutex_t groupstruct_mutex; const int default_id = 99; // nobody - not configurable since soon uids in dfs, yeah! const int blksize = 512; /** * Converts from a hdfs hdfsFileInfo to a POSIX stat struct * */ int fill_stat_structure(hdfsFileInfo *info, struct stat *st) { assert(st); assert(info); // initialize the stat structure memset(st, 0, sizeof(struct stat)); // by default: set to 0 to indicate not supported for directory because we cannot (efficiently) get this info for every subdirectory st->st_nlink = (info->mKind == kObjectKindDirectory) ? 0 : 1; uid_t owner_id = default_id; if (info->mOwner != NULL) { // // Critical section - protect from concurrent calls in different threads since // the struct below is static. // (no returns until end) // pthread_mutex_lock(&passwdstruct_mutex); struct passwd *passwd_info = getpwnam(info->mOwner); owner_id = passwd_info == NULL ? default_id : passwd_info->pw_uid; // // End critical section // pthread_mutex_unlock(&passwdstruct_mutex); } gid_t group_id = default_id; if (info->mGroup != NULL) { // // Critical section - protect from concurrent calls in different threads since // the struct below is static. // (no returns until end) // pthread_mutex_lock(&groupstruct_mutex); struct group *grp = getgrnam(info->mGroup); group_id = grp == NULL ? default_id : grp->gr_gid; // // End critical section // pthread_mutex_unlock(&groupstruct_mutex); } short perm = (info->mKind == kObjectKindDirectory) ? (S_IFDIR | 0777) : (S_IFREG | 0666); if (info->mPermissions > 0) { perm = (info->mKind == kObjectKindDirectory) ? S_IFDIR: S_IFREG ; perm |= info->mPermissions; } // set stat metadata st->st_size = (info->mKind == kObjectKindDirectory) ? 4096 : info->mSize; st->st_blksize = blksize; st->st_blocks = ceil(st->st_size/st->st_blksize); st->st_mode = perm; st->st_uid = owner_id; st->st_gid = group_id; st->st_atime = info->mLastAccess; st->st_mtime = info->mLastMod; st->st_ctime = info->mLastMod; return 0; }
apache-2.0
ghostkim-sc/SMG920T_profiling_enabled
drivers/media/pci/cx18/cx18-irq.c
13820
2326
/* * cx18 interrupt handling * * Copyright (C) 2007 Hans Verkuil <hverkuil@xs4all.nl> * Copyright (C) 2008 Andy Walls <awalls@md.metrocast.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ #include "cx18-driver.h" #include "cx18-io.h" #include "cx18-irq.h" #include "cx18-mailbox.h" #include "cx18-scb.h" static void xpu_ack(struct cx18 *cx, u32 sw2) { if (sw2 & IRQ_CPU_TO_EPU_ACK) wake_up(&cx->mb_cpu_waitq); if (sw2 & IRQ_APU_TO_EPU_ACK) wake_up(&cx->mb_apu_waitq); } static void epu_cmd(struct cx18 *cx, u32 sw1) { if (sw1 & IRQ_CPU_TO_EPU) cx18_api_epu_cmd_irq(cx, CPU); if (sw1 & IRQ_APU_TO_EPU) cx18_api_epu_cmd_irq(cx, APU); } irqreturn_t cx18_irq_handler(int irq, void *dev_id) { struct cx18 *cx = (struct cx18 *)dev_id; u32 sw1, sw2, hw2; sw1 = cx18_read_reg(cx, SW1_INT_STATUS) & cx->sw1_irq_mask; sw2 = cx18_read_reg(cx, SW2_INT_STATUS) & cx->sw2_irq_mask; hw2 = cx18_read_reg(cx, HW2_INT_CLR_STATUS) & cx->hw2_irq_mask; if (sw1) cx18_write_reg_expect(cx, sw1, SW1_INT_STATUS, ~sw1, sw1); if (sw2) cx18_write_reg_expect(cx, sw2, SW2_INT_STATUS, ~sw2, sw2); if (hw2) cx18_write_reg_expect(cx, hw2, HW2_INT_CLR_STATUS, ~hw2, hw2); if (sw1 || sw2 || hw2) CX18_DEBUG_HI_IRQ("received interrupts " "SW1: %x SW2: %x HW2: %x\n", sw1, sw2, hw2); /* * SW1 responses have to happen first. The sending XPU times out the * incoming mailboxes on us rather rapidly. */ if (sw1) epu_cmd(cx, sw1); /* To do: interrupt-based I2C handling if (hw2 & (HW2_I2C1_INT|HW2_I2C2_INT)) { } */ if (sw2) xpu_ack(cx, sw2); return (sw1 || sw2 || hw2) ? IRQ_HANDLED : IRQ_NONE; }
apache-2.0