text
stringlengths 65
6.05M
| lang
stringclasses 8
values | type
stringclasses 2
values | id
stringlengths 64
64
|
---|---|---|---|
/*
* Copyright (C) Obigo AB, 2002-2007.
* All rights reserved.
*
* This software is covered by the license agreement between
* the end user and Obigo AB, and may be
* used and copied only in accordance with the terms of the
* said agreement.
*
* Obigo AB assumes no responsibility or
* liability for any errors or inaccuracies in this software,
* or any consequential, incidental or indirect damage arising
* out of the use of the software.
*
*/
/*
* brs_plti.c
*
* Created by Anders Edenbrandt, Fri Oct 12 14:06:00 2001.
*
* Plug-in for WTAI functionality.
*
* Revision history:
*
*/
#include "brs_cfg.h"
#include "brs_plg.h"
#include "brs_if.h"
#include "stk_if.h"
#include "msf_chrs.h"
#include "msf_cmmn.h"
#include "msf_url.h"
#include "msf_lib.h"
#include "msf_tel.h"
#include "msf_core.h"
#include "msf_chrt.h"
/************************************************************
* Constants
************************************************************/
#define BRS_WTAI_MAKE_CALL 0
#define BRS_WTAI_SEND_DTMF 1
#define BRS_WTAI_ADD_PB_ENTRY 2
/************************************************************
* Type definitions
************************************************************/
typedef struct {
int r;
char *result_var;
} brs_plti_result_t;
/************************************************************
* Function declarations
************************************************************/
static void
brs_plti_func_instantiate (brs_plg_t *pl);
static void
brs_plti_func_request (brs_plg_t *pl, brs_plg_request_data_t *req);
static void
brs_plti_func_response (brs_plg_t *pl);
static void
brs_plti_uri_instantiate (brs_plg_t *pl);
static void
brs_plti_uri_request (brs_plg_t *pl, brs_plg_request_data_t *req);
static void
brs_plti_uri_response (brs_plg_t *pl);
static void
brs_plti_sig_response (brs_plg_t *pl, int signal, int value);
static void
brs_plti_delete (brs_plg_t *pl);
static int
brs_plti_is_phone_number (char *number);
static int
brs_plti_is_dtmf (char *dtmf);
/************************************************************
* Function definitions
************************************************************/
void
brs_plti_register (void)
{
brs_plg_info_t info;
/* Lib index = 512, and func index = 0, means WTAPublic.makeCall.
* That function takes one parameter. */
info.run_wmls_func.num_params = 1;
brs_plg_register (BRS_PLG_TYPE_RUN_WMLS_FUNC,
"512/0", &info, brs_plti_func_instantiate);
/* Lib index = 512, and func index = 1, means WTAPublic.sendDTMF.
* That function takes one parameter. */
info.run_wmls_func.num_params = 1;
brs_plg_register (BRS_PLG_TYPE_RUN_WMLS_FUNC,
"512/1", &info, brs_plti_func_instantiate);
/* Lib index = 512, and func index = 0, means WTAPublic.addPBEntry.
* That function takes two parameters. */
info.run_wmls_func.num_params = 2;
brs_plg_register (BRS_PLG_TYPE_RUN_WMLS_FUNC,
"512/2", &info, brs_plti_func_instantiate);
/* Also, register to handle the URI-versions: */
brs_plg_register (BRS_PLG_TYPE_REQUEST_URL, "wtai", NULL, brs_plti_uri_instantiate);
/* Register to handle the "tel" scheme. */
brs_plg_register (BRS_PLG_TYPE_REQUEST_URL, "tel", NULL, brs_plti_uri_instantiate);
}
static void
brs_plti_func_instantiate (brs_plg_t *pl)
{
brs_plti_result_t *res;
pl->pl_request = brs_plti_func_request;
pl->pl_delete = brs_plti_delete;
pl->pl_run = brs_plti_func_response;
pl->pl_sig_response = brs_plti_sig_response;
res = brs_plg_alloc (sizeof (brs_plti_result_t));
res->r = 0;
res->result_var = NULL;
pl->pl_data = res;
}
static void
brs_plti_uri_instantiate (brs_plg_t *pl)
{
brs_plti_result_t *res;
pl->pl_request = brs_plti_uri_request;
pl->pl_delete = brs_plti_delete;
pl->pl_run = brs_plti_uri_response;
pl->pl_sig_response = brs_plti_sig_response;
res = brs_plg_alloc (sizeof (brs_plti_result_t));
res->r = 0;
res->result_var = NULL;
pl->pl_data = res;
}
static void
brs_plti_delete (brs_plg_t *pl)
{
brs_plti_result_t *res = pl->pl_data;
if (res != NULL) {
brs_plg_free (res->result_var);
brs_plg_free (res);
}
}
static void
brs_plti_func_request (brs_plg_t *pl, brs_plg_request_data_t *req)
{
int num_params = req->run_wmls_func.num_params;
brs_plg_wmls_var_t *params = req->run_wmls_func.params;
int r = 0;
switch (req->run_wmls_func.func_index) {
case BRS_WTAI_MAKE_CALL:
if ((params == NULL) || (num_params != 1)) {
r = 1;
}
else if ((params[0].type != BRS_PLG_WMLS_VAR_STRING) ||
!brs_plti_is_phone_number (params[0]._u.s_val.s)) {
r = 2;
}
else {
MSF_TEL_MAKE_CALL (MSF_MODID_BRS, (MSF_UINT16)(pl->pl_id), params[0]._u.s_val.s);
}
break;
case BRS_WTAI_SEND_DTMF:
if ((params == NULL) || (num_params != 1)) {
r = 1;
}
else if ((params[0].type != BRS_PLG_WMLS_VAR_STRING) ||
!brs_plti_is_dtmf (params[0]._u.s_val.s)) {
r = 2;
}
else {
MSF_TEL_SEND_DTMF (MSF_MODID_BRS, (MSF_UINT16)(pl->pl_id), params[0]._u.s_val.s);
}
break;
case BRS_WTAI_ADD_PB_ENTRY:
if ((params == NULL) || (num_params != 2)) {
r = 1;
}
else if ((params[0].type != BRS_PLG_WMLS_VAR_STRING) ||
!brs_plti_is_phone_number (params[0]._u.s_val.s) ||
(params[1].type != BRS_PLG_WMLS_VAR_STRING)) {
r = 2;
}
else {
MSF_PB_ADD_ENTRY (MSF_MODID_BRS, (MSF_UINT16)(pl->pl_id),
params[1]._u.s_val.s, params[0]._u.s_val.s);
}
break;
}
brs_plg_wmlsvar_array_delete (num_params, params);
if (r == 1) {
brs_plg_abort (pl, BRS_ERROR_WMLS_INTERPRETING);
}
else if (r == 2) {
brs_plti_result_t *res = pl->pl_data;
res->r = 1;
brs_plti_func_response (pl);
}
}
/*
* Deliver the response from the WMLScript function call.
*/
static void
brs_plti_func_response (brs_plg_t *pl)
{
brs_plg_response_data_t res;
brs_plg_wmls_var_t *result;
brs_plti_result_t *p = pl->pl_data;
int r = 1;
if (p != NULL)
r = p->r;
result = brs_plg_alloc (sizeof (brs_plg_wmls_var_t));
if (r > 0) {
result->type = BRS_PLG_WMLS_VAR_INVALID;
}
else if (r == 0) {
result->type = BRS_PLG_WMLS_VAR_STRING;
result->_u.s_val.charset = MSF_CHARSET_UTF_8;
result->_u.s_val.s_len = 0;
result->_u.s_val.s = msf_cmmn_strdup (MSF_MODID_BRS, "");
}
else {
result->type = BRS_PLG_WMLS_VAR_INTEGER;
result->_u.i_val = r;
}
res.run_wmls_func.status_code = BRS_PLG_STATUS_OK;
res.run_wmls_func.result = result;
brs_plg_response (pl, &res);
brs_plg_done (pl);
}
static void
brs_plti_uri_request (brs_plg_t *pl, brs_plg_request_data_t *req)
{
brs_plti_result_t *res;
char *lib_name = NULL;
char *func_name = NULL;
char *param1 = NULL;
char *param2 = NULL;
char *result_var = NULL;
char *tmp;
int func_index = -1;
int isTELscheme = 0;
/* Check the scheme of the url */
tmp = msf_url_get_scheme (MSF_MODID_BRS, req->request_url.url);
if (msf_cmmn_strcmp_nc (tmp, "tel") == 0)
{
/* a "tel" scheme */
isTELscheme = 1;
}
brs_plg_free (tmp);
lib_name = msf_url_get_host (MSF_MODID_BRS, req->request_url.url);
if (isTELscheme == 0 && ((lib_name == NULL) || msf_cmmn_strcmp_nc (lib_name, "wp")))
{
goto err_return;
}
if (isTELscheme == 0)
{
tmp = msf_url_get_path (MSF_MODID_BRS, req->request_url.url);
if (tmp == NULL)
goto err_return;
msf_cmmn_strcpy_lc (tmp, tmp + 1);
func_name = msf_url_unescape_string (MSF_MODID_BRS, tmp);
brs_plg_free (tmp);
if (!msf_cmmn_strcmp_nc (func_name, "mc"))
func_index = BRS_WTAI_MAKE_CALL;
else if (!msf_cmmn_strcmp_nc (func_name, "sd"))
func_index = BRS_WTAI_SEND_DTMF;
else if (!msf_cmmn_strcmp_nc (func_name, "ap"))
func_index = BRS_WTAI_ADD_PB_ENTRY;
if (func_index < 0)
goto err_return;
res = pl->pl_data;
param1 = msf_url_get_parameters (MSF_MODID_BRS, req->request_url.url);
if (param1 == NULL)
goto err_return;
result_var = strchr (param1, '!');
if (result_var != NULL)
{
*result_var = '\0';
result_var++;
res->result_var = msf_url_unescape_string (MSF_MODID_BRS, result_var);
}
else
{
res->result_var = NULL;
}
}
else
{
/* "tel" scheme is used to make call */
func_index = BRS_WTAI_MAKE_CALL;
res = pl->pl_data;
/* Get the phone number */
param1 = msf_url_get_path (MSF_MODID_BRS, req->request_url.url);
if (param1 == NULL)
goto err_return;
tmp = msf_cmmn_skip_blanks(param1);
msf_cmmn_strcpy_lc (param1, tmp);
res->result_var = NULL;
}
switch (func_index) {
case BRS_WTAI_MAKE_CALL:
tmp = msf_url_unescape_string (MSF_MODID_BRS, param1);
brs_plg_free (param1);
param1 = tmp;
if (!brs_plti_is_phone_number (param1))
goto err_return;
MSF_TEL_MAKE_CALL (MSF_MODID_BRS, (MSF_UINT16)(pl->pl_id), param1);
break;
case BRS_WTAI_SEND_DTMF:
tmp = msf_url_unescape_string (MSF_MODID_BRS, param1);
brs_plg_free (param1);
param1 = tmp;
if (!brs_plti_is_dtmf (param1))
goto err_return;
MSF_TEL_SEND_DTMF (MSF_MODID_BRS, (MSF_UINT16)(pl->pl_id), param1);
break;
case BRS_WTAI_ADD_PB_ENTRY:
param2 = strchr (param1, ';');
if (param2 != NULL)
{
*param2 = '\0';
param2 = msf_url_unescape_string (MSF_MODID_BRS, param2 + 1);
}
else
{
param2 = msf_cmmn_strdup(MSF_MODID_BRS, (const char *)"");
}
tmp = msf_url_unescape_string (MSF_MODID_BRS, param1);
brs_plg_free (param1);
param1 = tmp;
if (!brs_plti_is_phone_number (param1))
goto err_return;
/* JWO 031015; corrected the order of the parameters; param1 is the number
* and param2 is the name; thus the order in the call below must be
* first param2 and then param1. This fixes TR13127.
*/
MSF_PB_ADD_ENTRY (MSF_MODID_BRS, (MSF_UINT16)(pl->pl_id), param2, param1);
break;
}
brs_plg_free (req->request_url.url);
brs_plg_free (req->request_url.fragment);
brs_plg_free (req->request_url.headers);
brs_plg_free (lib_name);
brs_plg_free (func_name);
brs_plg_free (param1);
brs_plg_free (param2);
return;
err_return:
brs_plg_free (req->request_url.url);
brs_plg_free (req->request_url.fragment);
brs_plg_free (req->request_url.headers);
brs_plg_free (lib_name);
brs_plg_free (func_name);
brs_plg_free (param1);
brs_plg_free (param2);
brs_plg_abort (pl, STK_ERR_INVALID_URL);
}
static void
brs_plti_uri_response (brs_plg_t *pl)
{
brs_plg_response_data_t ret;
brs_plti_result_t *res = pl->pl_data;
char buf[10];
if ((res != NULL) && (res->result_var != NULL))
{
if (res->r == 0) {
buf[0] = '\0';
}
else {
sprintf (buf, "%d", res->r);
}
brs_plg_set_wml_variable (pl, res->result_var, buf);
}
ret.request_url.headers = NULL;
ret.request_url.status_code = BRS_PLG_STATUS_NO_NAVIGATION;
brs_plg_response (pl, &ret);
brs_plg_done (pl);
}
static void
brs_plti_sig_response (brs_plg_t *pl, int signal, int value)
{
brs_plti_result_t *res = pl->pl_data;
signal = signal;
res->r = value;
brs_plg_schedule (pl);
}
static int
brs_plti_is_phone_number (char *number)
{
char *p = number;
if (number == NULL)
return 0;
if (*p == '+')
p++;
if (*p == '\0')
return 0;
while (*p != '\0') {
if (!ct_isdigit (*p))
return 0;
p++;
}
return 1;
}
static int
brs_plti_is_dtmf (char *dtmf)
{
char *p = dtmf;
if ((dtmf == NULL) || (*p == '\0'))
return 0;
while (*p != '\0') {
if((!ct_isdigit (*p)) &&
(*p != 'A') &&
(*p != 'B') &&
(*p != 'C') &&
(*p != 'D') &&
(*p != '*') &&
(*p != '#') &&
(*p != ','))
return 0;
p++;
}
return 1;
}
| C | CL | 7f71214d6c1fa5deb37db3e1a9e477ade3ce2320ae533a3990778ef2c20b5096 |
/*
* Copyright 2016 WebAssembly Community Group participants
*
* 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 "validator.h"
#include "config.h"
#include <assert.h>
#include <inttypes.h>
#include <memory.h>
#include <stdarg.h>
#include <stdio.h>
#include "allocator.h"
#include "ast-parser-lexer-shared.h"
#include "binary-reader-ast.h"
#include "binary-reader.h"
#include "type-checker.h"
typedef enum ActionResultKind {
ACTION_RESULT_KIND_ERROR,
ACTION_RESULT_KIND_TYPES,
ACTION_RESULT_KIND_TYPE,
} ActionResultKind;
typedef struct ActionResult {
ActionResultKind kind;
union {
const WabtTypeVector* types;
WabtType type;
};
} ActionResult;
typedef struct Context {
WabtSourceErrorHandler* error_handler;
WabtAllocator* allocator;
WabtAstLexer* lexer;
const WabtScript* script;
const WabtModule* current_module;
const WabtFunc* current_func;
int current_table_index;
int current_memory_index;
int current_global_index;
int num_imported_globals;
WabtTypeChecker typechecker;
const WabtLocation* expr_loc; /* Cached for access by on_typechecker_error */
WabtResult result;
} Context;
static void WABT_PRINTF_FORMAT(3, 4)
print_error(Context* ctx, const WabtLocation* loc, const char* fmt, ...) {
ctx->result = WABT_ERROR;
va_list args;
va_start(args, fmt);
wabt_ast_format_error(ctx->error_handler, loc, ctx->lexer, fmt, args);
va_end(args);
}
static void on_typechecker_error(const char* msg, void* user_data) {
Context* ctx = user_data;
print_error(ctx, ctx->expr_loc, "%s", msg);
}
static WabtBool is_power_of_two(uint32_t x) {
return x && ((x & (x - 1)) == 0);
}
static uint32_t get_opcode_natural_alignment(WabtOpcode opcode) {
uint32_t memory_size = wabt_get_opcode_memory_size(opcode);
assert(memory_size != 0);
return memory_size;
}
static WabtResult check_var(Context* ctx,
int max_index,
const WabtVar* var,
const char* desc,
int* out_index) {
assert(var->type == WABT_VAR_TYPE_INDEX);
if (var->index >= 0 && var->index < max_index) {
if (out_index)
*out_index = var->index;
return WABT_OK;
}
print_error(ctx, &var->loc, "%s variable out of range (max %d)", desc,
max_index);
return WABT_ERROR;
}
static WabtResult check_func_var(Context* ctx,
const WabtVar* var,
const WabtFunc** out_func) {
int index;
if (WABT_FAILED(check_var(ctx, ctx->current_module->funcs.size, var,
"function", &index))) {
return WABT_ERROR;
}
if (out_func)
*out_func = ctx->current_module->funcs.data[index];
return WABT_OK;
}
static WabtResult check_global_var(Context* ctx,
const WabtVar* var,
const WabtGlobal** out_global,
int* out_global_index) {
int index;
if (WABT_FAILED(check_var(ctx, ctx->current_module->globals.size, var,
"global", &index))) {
return WABT_ERROR;
}
if (out_global)
*out_global = ctx->current_module->globals.data[index];
if (out_global_index)
*out_global_index = index;
return WABT_OK;
}
static WabtType get_global_var_type_or_any(Context* ctx, const WabtVar* var) {
const WabtGlobal* global;
if (WABT_SUCCEEDED(check_global_var(ctx, var, &global, NULL)))
return global->type;
return WABT_TYPE_ANY;
}
static WabtResult check_func_type_var(Context* ctx,
const WabtVar* var,
const WabtFuncType** out_func_type) {
int index;
if (WABT_FAILED(check_var(ctx, ctx->current_module->func_types.size, var,
"function type", &index))) {
return WABT_ERROR;
}
if (out_func_type)
*out_func_type = ctx->current_module->func_types.data[index];
return WABT_OK;
}
static WabtResult check_table_var(Context* ctx,
const WabtVar* var,
const WabtTable** out_table) {
int index;
if (WABT_FAILED(check_var(ctx, ctx->current_module->tables.size, var, "table",
&index))) {
return WABT_ERROR;
}
if (out_table)
*out_table = ctx->current_module->tables.data[index];
return WABT_OK;
}
static WabtResult check_memory_var(Context* ctx,
const WabtVar* var,
const WabtMemory** out_memory) {
int index;
if (WABT_FAILED(check_var(ctx, ctx->current_module->memories.size, var,
"memory", &index))) {
return WABT_ERROR;
}
if (out_memory)
*out_memory = ctx->current_module->memories.data[index];
return WABT_OK;
}
static WabtResult check_local_var(Context* ctx,
const WabtVar* var,
WabtType* out_type) {
const WabtFunc* func = ctx->current_func;
int max_index = wabt_get_num_params_and_locals(func);
int index = wabt_get_local_index_by_var(func, var);
if (index >= 0 && index < max_index) {
if (out_type) {
int num_params = wabt_get_num_params(func);
if (index < num_params) {
*out_type = wabt_get_param_type(func, index);
} else {
*out_type = ctx->current_func->local_types.data[index - num_params];
}
}
return WABT_OK;
}
if (var->type == WABT_VAR_TYPE_NAME) {
print_error(ctx, &var->loc,
"undefined local variable \"" PRIstringslice "\"",
WABT_PRINTF_STRING_SLICE_ARG(var->name));
} else {
print_error(ctx, &var->loc, "local variable out of range (max %d)",
max_index);
}
return WABT_ERROR;
}
static WabtType get_local_var_type_or_any(Context* ctx, const WabtVar* var) {
WabtType type = WABT_TYPE_ANY;
check_local_var(ctx, var, &type);
return type;
}
static void check_align(Context* ctx,
const WabtLocation* loc,
uint32_t alignment,
uint32_t natural_alignment) {
if (alignment != WABT_USE_NATURAL_ALIGNMENT) {
if (!is_power_of_two(alignment))
print_error(ctx, loc, "alignment must be power-of-two");
if (alignment > natural_alignment) {
print_error(ctx, loc,
"alignment must not be larger than natural alignment (%u)",
natural_alignment);
}
}
}
static void check_offset(Context* ctx,
const WabtLocation* loc,
uint64_t offset) {
if (offset > UINT32_MAX) {
print_error(ctx, loc, "offset must be less than or equal to 0xffffffff");
}
}
static void check_type(Context* ctx,
const WabtLocation* loc,
WabtType actual,
WabtType expected,
const char* desc) {
if (expected != actual) {
print_error(ctx, loc, "type mismatch at %s. got %s, expected %s", desc,
wabt_get_type_name(actual), wabt_get_type_name(expected));
}
}
static void check_type_index(Context* ctx,
const WabtLocation* loc,
WabtType actual,
WabtType expected,
const char* desc,
int index,
const char* index_kind) {
if (expected != actual && expected != WABT_TYPE_ANY &&
actual != WABT_TYPE_ANY) {
print_error(ctx, loc, "type mismatch for %s %d of %s. got %s, expected %s",
index_kind, index, desc, wabt_get_type_name(actual),
wabt_get_type_name(expected));
}
}
static void check_types(Context* ctx,
const WabtLocation* loc,
const WabtTypeVector* actual,
const WabtTypeVector* expected,
const char* desc,
const char* index_kind) {
if (actual->size == expected->size) {
size_t i;
for (i = 0; i < actual->size; ++i) {
check_type_index(ctx, loc, actual->data[i], expected->data[i], desc, i,
index_kind);
}
} else {
print_error(ctx, loc, "expected %" PRIzd " %ss, got %" PRIzd,
expected->size, index_kind, actual->size);
}
}
static void check_const_types(Context* ctx,
const WabtLocation* loc,
const WabtTypeVector* actual,
const WabtConstVector* expected,
const char* desc) {
if (actual->size == expected->size) {
size_t i;
for (i = 0; i < actual->size; ++i) {
check_type_index(ctx, loc, actual->data[i], expected->data[i].type, desc,
i, "result");
}
} else {
print_error(ctx, loc, "expected %" PRIzd " results, got %" PRIzd,
expected->size, actual->size);
}
}
static void check_const_type(Context* ctx,
const WabtLocation* loc,
WabtType actual,
const WabtConstVector* expected,
const char* desc) {
WabtTypeVector actual_types;
WABT_ZERO_MEMORY(actual_types);
actual_types.size = actual == WABT_TYPE_VOID ? 0 : 1;
actual_types.data = &actual;
check_const_types(ctx, loc, &actual_types, expected, desc);
}
static void check_assert_return_nan_type(Context* ctx,
const WabtLocation* loc,
WabtType actual,
const char* desc) {
/* when using assert_return_nan, the result can be either a f32 or f64 type
* so we special case it here. */
if (actual != WABT_TYPE_F32 && actual != WABT_TYPE_F64) {
print_error(ctx, loc, "type mismatch at %s. got %s, expected f32 or f64",
desc, wabt_get_type_name(actual));
}
}
static void check_expr(Context* ctx, const WabtExpr* expr);
static void check_expr_list(Context* ctx,
const WabtLocation* loc,
const WabtExpr* first) {
if (first) {
const WabtExpr* expr;
for (expr = first; expr; expr = expr->next)
check_expr(ctx, expr);
}
}
static void check_has_memory(Context* ctx,
const WabtLocation* loc,
WabtOpcode opcode) {
if (ctx->current_module->memories.size == 0) {
print_error(ctx, loc, "%s requires an imported or defined memory.",
wabt_get_opcode_name(opcode));
}
}
static void check_expr(Context* ctx, const WabtExpr* expr) {
ctx->expr_loc = &expr->loc;
switch (expr->type) {
case WABT_EXPR_TYPE_BINARY:
wabt_typechecker_on_binary(&ctx->typechecker, expr->binary.opcode);
break;
case WABT_EXPR_TYPE_BLOCK:
wabt_typechecker_on_block(&ctx->typechecker, &expr->block.sig);
check_expr_list(ctx, &expr->loc, expr->block.first);
wabt_typechecker_on_end(&ctx->typechecker);
break;
case WABT_EXPR_TYPE_BR:
wabt_typechecker_on_br(&ctx->typechecker, expr->br.var.index);
break;
case WABT_EXPR_TYPE_BR_IF:
wabt_typechecker_on_br_if(&ctx->typechecker, expr->br_if.var.index);
break;
case WABT_EXPR_TYPE_BR_TABLE: {
wabt_typechecker_begin_br_table(&ctx->typechecker);
size_t i;
for (i = 0; i < expr->br_table.targets.size; ++i) {
wabt_typechecker_on_br_table_target(
&ctx->typechecker, expr->br_table.targets.data[i].index);
}
wabt_typechecker_on_br_table_target(&ctx->typechecker,
expr->br_table.default_target.index);
wabt_typechecker_end_br_table(&ctx->typechecker);
break;
}
case WABT_EXPR_TYPE_CALL: {
const WabtFunc* callee;
if (WABT_SUCCEEDED(check_func_var(ctx, &expr->call.var, &callee))) {
wabt_typechecker_on_call(&ctx->typechecker,
&callee->decl.sig.param_types,
&callee->decl.sig.result_types);
}
break;
}
case WABT_EXPR_TYPE_CALL_INDIRECT: {
const WabtFuncType* func_type;
if (ctx->current_module->tables.size == 0) {
print_error(ctx, &expr->loc,
"found call_indirect operator, but no table");
}
if (WABT_SUCCEEDED(
check_func_type_var(ctx, &expr->call_indirect.var, &func_type))) {
wabt_typechecker_on_call_indirect(&ctx->typechecker,
&func_type->sig.param_types,
&func_type->sig.result_types);
}
break;
}
case WABT_EXPR_TYPE_COMPARE:
wabt_typechecker_on_compare(&ctx->typechecker, expr->compare.opcode);
break;
case WABT_EXPR_TYPE_CONST:
wabt_typechecker_on_const(&ctx->typechecker, expr->const_.type);
break;
case WABT_EXPR_TYPE_CONVERT:
wabt_typechecker_on_convert(&ctx->typechecker, expr->convert.opcode);
break;
case WABT_EXPR_TYPE_DROP:
wabt_typechecker_on_drop(&ctx->typechecker);
break;
case WABT_EXPR_TYPE_GET_GLOBAL:
wabt_typechecker_on_get_global(
&ctx->typechecker,
get_global_var_type_or_any(ctx, &expr->get_global.var));
break;
case WABT_EXPR_TYPE_GET_LOCAL:
wabt_typechecker_on_get_local(
&ctx->typechecker,
get_local_var_type_or_any(ctx, &expr->get_local.var));
break;
case WABT_EXPR_TYPE_GROW_MEMORY:
check_has_memory(ctx, &expr->loc, WABT_OPCODE_GROW_MEMORY);
wabt_typechecker_on_grow_memory(&ctx->typechecker);
break;
case WABT_EXPR_TYPE_IF:
wabt_typechecker_on_if(&ctx->typechecker, &expr->if_.true_.sig);
check_expr_list(ctx, &expr->loc, expr->if_.true_.first);
if (expr->if_.false_) {
wabt_typechecker_on_else(&ctx->typechecker);
check_expr_list(ctx, &expr->loc, expr->if_.false_);
}
wabt_typechecker_on_end(&ctx->typechecker);
break;
case WABT_EXPR_TYPE_LOAD:
check_has_memory(ctx, &expr->loc, expr->load.opcode);
check_align(ctx, &expr->loc, expr->load.align,
get_opcode_natural_alignment(expr->load.opcode));
check_offset(ctx, &expr->loc, expr->load.offset);
wabt_typechecker_on_load(&ctx->typechecker, expr->load.opcode);
break;
case WABT_EXPR_TYPE_LOOP:
wabt_typechecker_on_loop(&ctx->typechecker, &expr->loop.sig);
check_expr_list(ctx, &expr->loc, expr->loop.first);
wabt_typechecker_on_end(&ctx->typechecker);
break;
case WABT_EXPR_TYPE_CURRENT_MEMORY:
check_has_memory(ctx, &expr->loc, WABT_OPCODE_CURRENT_MEMORY);
wabt_typechecker_on_current_memory(&ctx->typechecker);
break;
case WABT_EXPR_TYPE_NOP:
break;
case WABT_EXPR_TYPE_RETURN:
wabt_typechecker_on_return(&ctx->typechecker);
break;
case WABT_EXPR_TYPE_SELECT:
wabt_typechecker_on_select(&ctx->typechecker);
break;
case WABT_EXPR_TYPE_SET_GLOBAL:
wabt_typechecker_on_set_global(
&ctx->typechecker,
get_global_var_type_or_any(ctx, &expr->set_global.var));
break;
case WABT_EXPR_TYPE_SET_LOCAL:
wabt_typechecker_on_set_local(
&ctx->typechecker,
get_local_var_type_or_any(ctx, &expr->set_local.var));
break;
case WABT_EXPR_TYPE_STORE:
check_has_memory(ctx, &expr->loc, expr->store.opcode);
check_align(ctx, &expr->loc, expr->store.align,
get_opcode_natural_alignment(expr->store.opcode));
check_offset(ctx, &expr->loc, expr->store.offset);
wabt_typechecker_on_store(&ctx->typechecker, expr->store.opcode);
break;
case WABT_EXPR_TYPE_TEE_LOCAL:
wabt_typechecker_on_tee_local(
&ctx->typechecker,
get_local_var_type_or_any(ctx, &expr->tee_local.var));
break;
case WABT_EXPR_TYPE_UNARY:
wabt_typechecker_on_unary(&ctx->typechecker, expr->unary.opcode);
break;
case WABT_EXPR_TYPE_UNREACHABLE:
wabt_typechecker_on_unreachable(&ctx->typechecker);
break;
}
}
static void check_func_signature_matches_func_type(
Context* ctx,
const WabtLocation* loc,
const WabtFuncSignature* sig,
const WabtFuncType* func_type) {
check_types(ctx, loc, &sig->result_types, &func_type->sig.result_types,
"function", "result");
check_types(ctx, loc, &sig->param_types, &func_type->sig.param_types,
"function", "argument");
}
static void check_func(Context* ctx,
const WabtLocation* loc,
const WabtFunc* func) {
ctx->current_func = func;
if (wabt_get_num_results(func) > 1) {
print_error(ctx, loc, "multiple result values not currently supported.");
/* don't run any other checks, the won't test the result_type properly */
return;
}
if (wabt_decl_has_func_type(&func->decl)) {
const WabtFuncType* func_type;
if (WABT_SUCCEEDED(
check_func_type_var(ctx, &func->decl.type_var, &func_type))) {
check_func_signature_matches_func_type(ctx, loc, &func->decl.sig,
func_type);
}
}
ctx->expr_loc = loc;
wabt_typechecker_begin_function(&ctx->typechecker,
&func->decl.sig.result_types);
check_expr_list(ctx, loc, func->first_expr);
wabt_typechecker_end_function(&ctx->typechecker);
ctx->current_func = NULL;
}
static void print_const_expr_error(Context* ctx,
const WabtLocation* loc,
const char* desc) {
print_error(ctx, loc,
"invalid %s, must be a constant expression; either *.const or "
"get_global.",
desc);
}
static void check_const_init_expr(Context* ctx,
const WabtLocation* loc,
const WabtExpr* expr,
WabtType expected_type,
const char* desc) {
WabtType type = WABT_TYPE_VOID;
if (expr) {
if (expr->next != NULL) {
print_const_expr_error(ctx, loc, desc);
return;
}
switch (expr->type) {
case WABT_EXPR_TYPE_CONST:
type = expr->const_.type;
break;
case WABT_EXPR_TYPE_GET_GLOBAL: {
const WabtGlobal* ref_global = NULL;
int ref_global_index;
if (WABT_FAILED(check_global_var(ctx, &expr->get_global.var,
&ref_global, &ref_global_index))) {
return;
}
type = ref_global->type;
/* globals can only reference previously defined, internal globals */
if (ref_global_index >= ctx->current_global_index) {
print_error(ctx, loc,
"initializer expression can only reference a previously "
"defined global");
} else if (ref_global_index >= ctx->num_imported_globals) {
print_error(
ctx, loc,
"initializer expression can only reference an imported global");
}
if (ref_global->mutable_) {
print_error(
ctx, loc,
"initializer expression cannot reference a mutable global");
}
break;
}
default:
print_const_expr_error(ctx, loc, desc);
return;
}
}
check_type(ctx, expr ? &expr->loc : loc, type, expected_type, desc);
}
static void check_global(Context* ctx,
const WabtLocation* loc,
const WabtGlobal* global) {
check_const_init_expr(ctx, loc, global->init_expr, global->type,
"global initializer expression");
}
static void check_limits(Context* ctx,
const WabtLocation* loc,
const WabtLimits* limits,
uint64_t absolute_max,
const char* desc) {
if (limits->initial > absolute_max) {
print_error(ctx, loc, "initial %s (%" PRIu64 ") must be <= (%" PRIu64 ")",
desc, limits->initial, absolute_max);
}
if (limits->has_max) {
if (limits->max > absolute_max) {
print_error(ctx, loc, "max %s (%" PRIu64 ") must be <= (%" PRIu64 ")",
desc, limits->max, absolute_max);
}
if (limits->max < limits->initial) {
print_error(ctx, loc,
"max %s (%" PRIu64 ") must be >= initial %s (%" PRIu64 ")",
desc, limits->max, desc, limits->initial);
}
}
}
static void check_table(Context* ctx,
const WabtLocation* loc,
const WabtTable* table) {
if (ctx->current_table_index == 1)
print_error(ctx, loc, "only one table allowed");
check_limits(ctx, loc, &table->elem_limits, UINT32_MAX, "elems");
}
static void check_elem_segments(Context* ctx, const WabtModule* module) {
WabtModuleField* field;
for (field = module->first_field; field; field = field->next) {
if (field->type != WABT_MODULE_FIELD_TYPE_ELEM_SEGMENT)
continue;
WabtElemSegment* elem_segment = &field->elem_segment;
const WabtTable* table;
if (!WABT_SUCCEEDED(
check_table_var(ctx, &elem_segment->table_var, &table)))
continue;
size_t i;
for (i = 0; i < elem_segment->vars.size; ++i) {
if (!WABT_SUCCEEDED(
check_func_var(ctx, &elem_segment->vars.data[i], NULL)))
continue;
}
check_const_init_expr(ctx, &field->loc, elem_segment->offset, WABT_TYPE_I32,
"elem segment offset");
}
}
static void check_memory(Context* ctx,
const WabtLocation* loc,
const WabtMemory* memory) {
if (ctx->current_memory_index == 1)
print_error(ctx, loc, "only one memory block allowed");
check_limits(ctx, loc, &memory->page_limits, WABT_MAX_PAGES, "pages");
}
static void check_data_segments(Context* ctx, const WabtModule* module) {
WabtModuleField* field;
for (field = module->first_field; field; field = field->next) {
if (field->type != WABT_MODULE_FIELD_TYPE_DATA_SEGMENT)
continue;
WabtDataSegment* data_segment = &field->data_segment;
const WabtMemory* memory;
if (!WABT_SUCCEEDED(
check_memory_var(ctx, &data_segment->memory_var, &memory)))
continue;
check_const_init_expr(ctx, &field->loc, data_segment->offset, WABT_TYPE_I32,
"data segment offset");
}
}
static void check_import(Context* ctx,
const WabtLocation* loc,
const WabtImport* import) {
switch (import->kind) {
case WABT_EXTERNAL_KIND_FUNC:
if (wabt_decl_has_func_type(&import->func.decl))
check_func_type_var(ctx, &import->func.decl.type_var, NULL);
break;
case WABT_EXTERNAL_KIND_TABLE:
check_table(ctx, loc, &import->table);
ctx->current_table_index++;
break;
case WABT_EXTERNAL_KIND_MEMORY:
check_memory(ctx, loc, &import->memory);
ctx->current_memory_index++;
break;
case WABT_EXTERNAL_KIND_GLOBAL:
if (import->global.mutable_) {
print_error(ctx, loc, "mutable globals cannot be imported");
}
ctx->num_imported_globals++;
ctx->current_global_index++;
break;
case WABT_NUM_EXTERNAL_KINDS:
assert(0);
break;
}
}
static void check_export(Context* ctx, const WabtExport* export_) {
switch (export_->kind) {
case WABT_EXTERNAL_KIND_FUNC:
check_func_var(ctx, &export_->var, NULL);
break;
case WABT_EXTERNAL_KIND_TABLE:
check_table_var(ctx, &export_->var, NULL);
break;
case WABT_EXTERNAL_KIND_MEMORY:
check_memory_var(ctx, &export_->var, NULL);
break;
case WABT_EXTERNAL_KIND_GLOBAL: {
const WabtGlobal* global;
if (WABT_SUCCEEDED(check_global_var(ctx, &export_->var, &global, NULL))) {
if (global->mutable_) {
print_error(ctx, &export_->var.loc,
"mutable globals cannot be exported");
}
}
break;
}
case WABT_NUM_EXTERNAL_KINDS:
assert(0);
break;
}
}
static void on_duplicate_binding(WabtBindingHashEntry* a,
WabtBindingHashEntry* b,
void* user_data) {
Context* ctx = user_data;
/* choose the location that is later in the file */
WabtLocation* a_loc = &a->binding.loc;
WabtLocation* b_loc = &b->binding.loc;
WabtLocation* loc = a_loc->line > b_loc->line ? a_loc : b_loc;
print_error(ctx, loc, "redefinition of export \"" PRIstringslice "\"",
WABT_PRINTF_STRING_SLICE_ARG(a->binding.name));
}
static void check_duplicate_export_bindings(Context* ctx,
const WabtModule* module) {
wabt_find_duplicate_bindings(&module->export_bindings, on_duplicate_binding,
ctx);
}
static void check_module(Context* ctx, const WabtModule* module) {
WabtBool seen_start = WABT_FALSE;
ctx->current_module = module;
ctx->current_table_index = 0;
ctx->current_memory_index = 0;
ctx->current_global_index = 0;
ctx->num_imported_globals = 0;
WabtModuleField* field;
for (field = module->first_field; field != NULL; field = field->next) {
switch (field->type) {
case WABT_MODULE_FIELD_TYPE_FUNC:
check_func(ctx, &field->loc, &field->func);
break;
case WABT_MODULE_FIELD_TYPE_GLOBAL:
check_global(ctx, &field->loc, &field->global);
ctx->current_global_index++;
break;
case WABT_MODULE_FIELD_TYPE_IMPORT:
check_import(ctx, &field->loc, &field->import);
break;
case WABT_MODULE_FIELD_TYPE_EXPORT:
check_export(ctx, &field->export_);
break;
case WABT_MODULE_FIELD_TYPE_TABLE:
check_table(ctx, &field->loc, &field->table);
ctx->current_table_index++;
break;
case WABT_MODULE_FIELD_TYPE_ELEM_SEGMENT:
/* checked below */
break;
case WABT_MODULE_FIELD_TYPE_MEMORY:
check_memory(ctx, &field->loc, &field->memory);
ctx->current_memory_index++;
break;
case WABT_MODULE_FIELD_TYPE_DATA_SEGMENT:
/* checked below */
break;
case WABT_MODULE_FIELD_TYPE_FUNC_TYPE:
break;
case WABT_MODULE_FIELD_TYPE_START: {
if (seen_start) {
print_error(ctx, &field->loc, "only one start function allowed");
}
const WabtFunc* start_func = NULL;
check_func_var(ctx, &field->start, &start_func);
if (start_func) {
if (wabt_get_num_params(start_func) != 0) {
print_error(ctx, &field->loc, "start function must be nullary");
}
if (wabt_get_num_results(start_func) != 0) {
print_error(ctx, &field->loc,
"start function must not return anything");
}
}
seen_start = WABT_TRUE;
break;
}
}
}
check_elem_segments(ctx, module);
check_data_segments(ctx, module);
check_duplicate_export_bindings(ctx, module);
}
/* returns the result type of the invoked function, checked by the caller;
* returning NULL means that another error occured first, so the result type
* should be ignored. */
static const WabtTypeVector* check_invoke(Context* ctx,
const WabtAction* action) {
const WabtActionInvoke* invoke = &action->invoke;
const WabtModule* module =
wabt_get_module_by_var(ctx->script, &action->module_var);
if (!module) {
print_error(ctx, &action->loc, "unknown module");
return NULL;
}
WabtExport* export = wabt_get_export_by_name(module, &invoke->name);
if (!export) {
print_error(ctx, &action->loc,
"unknown function export \"" PRIstringslice "\"",
WABT_PRINTF_STRING_SLICE_ARG(invoke->name));
return NULL;
}
WabtFunc* func = wabt_get_func_by_var(module, &export->var);
if (!func) {
/* this error will have already been reported, just skip it */
return NULL;
}
size_t actual_args = invoke->args.size;
size_t expected_args = wabt_get_num_params(func);
if (expected_args != actual_args) {
print_error(ctx, &action->loc, "too %s parameters to function. got %" PRIzd
", expected %" PRIzd,
actual_args > expected_args ? "many" : "few", actual_args,
expected_args);
return NULL;
}
size_t i;
for (i = 0; i < actual_args; ++i) {
WabtConst* const_ = &invoke->args.data[i];
check_type_index(ctx, &const_->loc, const_->type,
wabt_get_param_type(func, i), "invoke", i, "argument");
}
return &func->decl.sig.result_types;
}
static WabtResult check_get(Context* ctx,
const WabtAction* action,
WabtType* out_type) {
const WabtActionGet* get = &action->get;
const WabtModule* module =
wabt_get_module_by_var(ctx->script, &action->module_var);
if (!module) {
print_error(ctx, &action->loc, "unknown module");
return WABT_ERROR;
}
WabtExport* export = wabt_get_export_by_name(module, &get->name);
if (!export) {
print_error(ctx, &action->loc,
"unknown global export \"" PRIstringslice "\"",
WABT_PRINTF_STRING_SLICE_ARG(get->name));
return WABT_ERROR;
}
WabtGlobal* global = wabt_get_global_by_var(module, &export->var);
if (!global) {
/* this error will have already been reported, just skip it */
return WABT_ERROR;
}
*out_type = global->type;
return WABT_OK;
}
static ActionResult check_action(Context* ctx, const WabtAction* action) {
ActionResult result;
WABT_ZERO_MEMORY(result);
switch (action->type) {
case WABT_ACTION_TYPE_INVOKE:
result.types = check_invoke(ctx, action);
result.kind =
result.types ? ACTION_RESULT_KIND_TYPES : ACTION_RESULT_KIND_ERROR;
break;
case WABT_ACTION_TYPE_GET:
if (WABT_SUCCEEDED(check_get(ctx, action, &result.type)))
result.kind = ACTION_RESULT_KIND_TYPE;
else
result.kind = ACTION_RESULT_KIND_ERROR;
break;
}
return result;
}
static void check_command(Context* ctx, const WabtCommand* command) {
switch (command->type) {
case WABT_COMMAND_TYPE_MODULE:
check_module(ctx, &command->module);
break;
case WABT_COMMAND_TYPE_ACTION:
/* ignore result type */
check_action(ctx, &command->action);
break;
case WABT_COMMAND_TYPE_REGISTER:
case WABT_COMMAND_TYPE_ASSERT_MALFORMED:
case WABT_COMMAND_TYPE_ASSERT_INVALID:
case WABT_COMMAND_TYPE_ASSERT_INVALID_NON_BINARY:
case WABT_COMMAND_TYPE_ASSERT_UNLINKABLE:
case WABT_COMMAND_TYPE_ASSERT_UNINSTANTIABLE:
/* ignore */
break;
case WABT_COMMAND_TYPE_ASSERT_RETURN: {
const WabtAction* action = &command->assert_return.action;
ActionResult result = check_action(ctx, action);
switch (result.kind) {
case ACTION_RESULT_KIND_TYPES:
check_const_types(ctx, &action->loc, result.types,
&command->assert_return.expected, "action");
break;
case ACTION_RESULT_KIND_TYPE:
check_const_type(ctx, &action->loc, result.type,
&command->assert_return.expected, "action");
break;
case ACTION_RESULT_KIND_ERROR:
/* error occurred, don't do any further checks */
break;
}
break;
}
case WABT_COMMAND_TYPE_ASSERT_RETURN_NAN: {
const WabtAction* action = &command->assert_return_nan.action;
ActionResult result = check_action(ctx, action);
/* a valid result type will either be f32 or f64; convert a TYPES result
* into a TYPE result, so it is easier to check below. WABT_TYPE_ANY is
* used to specify a type that should not be checked (because an earlier
* error occurred). */
if (result.kind == ACTION_RESULT_KIND_TYPES) {
if (result.types->size == 1) {
result.kind = ACTION_RESULT_KIND_TYPE;
result.type = result.types->data[0];
} else {
print_error(ctx, &action->loc, "expected 1 result, got %" PRIzd,
result.types->size);
result.type = WABT_TYPE_ANY;
}
}
if (result.kind == ACTION_RESULT_KIND_TYPE &&
result.type != WABT_TYPE_ANY)
check_assert_return_nan_type(ctx, &action->loc, result.type, "action");
break;
}
case WABT_COMMAND_TYPE_ASSERT_TRAP:
case WABT_COMMAND_TYPE_ASSERT_EXHAUSTION:
/* ignore result type */
check_action(ctx, &command->assert_trap.action);
break;
case WABT_NUM_COMMAND_TYPES:
assert(0);
break;
}
}
static void wabt_destroy_context(Context* ctx) {
wabt_destroy_typechecker(&ctx->typechecker);
}
WabtResult wabt_validate_script(WabtAllocator* allocator,
WabtAstLexer* lexer,
const struct WabtScript* script,
WabtSourceErrorHandler* error_handler) {
Context ctx;
WABT_ZERO_MEMORY(ctx);
ctx.allocator = allocator;
ctx.lexer = lexer;
ctx.error_handler = error_handler;
ctx.result = WABT_OK;
ctx.script = script;
WabtTypeCheckerErrorHandler tc_error_handler;
tc_error_handler.on_error = on_typechecker_error;
tc_error_handler.user_data = &ctx;
ctx.typechecker.allocator = allocator;
ctx.typechecker.error_handler = &tc_error_handler;
size_t i;
for (i = 0; i < script->commands.size; ++i)
check_command(&ctx, &script->commands.data[i]);
wabt_destroy_context(&ctx);
return ctx.result;
}
| C | CL | 8754470a58ca2e347f2f90d32aae4ec03f83b7acf74d731155deb7e3fcfedcce |
/*
*
* Author: Vinay Hiremath
* [email protected]
* www.vhmath.com
*
* Description: Implementation of a disjoint-sets data structure.
*/
#include <stdio.h>
#include <stdlib.h>
#include "dsjsets.h"
/* O(1) OPERATION
* --------------
* Initializes the disjoint-sets data structure with a size of
* 0 and its dsets array as a NULL pointer. ASSUMES MEMORY HAS
* ALREADY BEEN ALLOCATED FOR PARAMETER D.
*/
void dsjsets_init(dsjsets *d){
//NULL-check the parameter
if (!d)
return;
// NULL the dsets array
d->dsets = NULL;
// this is empty right now
d->size = 0;
}
/* O(N) OPERATION
* --------------
* Adds n unconnected sets to the dsets array of parameter d.
* If d is NULL or n is less than or equal to 0 this function
* does nothing.
*/
void dsjsets_addelems(dsjsets *d, int n){
// NULL-check d and make sure n makes sense
if (!d || (n <= 0))
return;
// if this is the first time adding elements
if (!(d->dsets)){
// allocate the memory
d->dsets = (int *)malloc(n*sizeof(int));
// initialize these sets to -1 (disjoint)
int i;
for (i = 0; i < n; i++)
d->dsets[i] = -1;
// update size
d->size = n;
return;
}
// we need to realloc
d->dsets = (int *)realloc(d->dsets, (n + d->size)*sizeof(int));
// initialize new sets to -1
int i;
for (i = n; i < (d->size + n); i++)
d->dsets[i] = -1;
// update size
d->size += n;
}
/* O(log*N) OPERATION
* ------------------
* Finds the root of nth element. If n does not make sense, d is
* NULL or d has not been initialized, this function returns -1.
*/
int dsjsets_find(dsjsets *d, int n){
// NULL-check d and make sure n makes sense
if (!d || !(d->dsets) || n < 0 || n >= d->size)
return -1;
// if this is a root set, return
if (d->dsets[n] < 0)
return n;
// otherwise recurse until you hit the root
int rootSet = dsjsets_find(d, d->dsets[n]);
// point to the root set (path compression)
d->dsets[n] = rootSet;
return rootSet;
}
/* O(logN) OPERATION
* -----------------
* Unions sets a and b. Implemented such that the bigger set
* points to the smaller set. If the indexes of a and b don't
* make sense, this function does nothing. This function also
* does nothing if d is NULL or has not been initialized.
*/
void dsjsets_union(dsjsets *d, int a, int b){
// NULL-check d and make sure a and b make sense
if (!d || !(d->dsets) || a < 0 || a >= d->size
|| b < 0 || b >= d->size)
return;
// get the roots of a and b
int aRoot = dsjsets_find(d, a);
int bRoot = dsjsets_find(d, b);
// and their sizes
int aSize = d->dsets[aRoot];
int bSize = d->dsets[bRoot];
// union
if (bSize < aSize){
// point set a to set b
d->dsets[aRoot] = bRoot;
// update size of set b
d->dsets[bRoot] += aSize;
return;
}
// set a's size is less than or equal to b's
// point set b to set a
d->dsets[bRoot] = aRoot;
// update size of set a
d->dsets[aRoot] += bSize;
}
/* O(1) OPERATION
* --------------
* Returns the the number of sets in this data structure. If
* d is NULL, this returns 0.
*/
int dsjsets_size(dsjsets *d){
// NULL-check the parameter
if (!d)
return 0;
return d->size;
}
/* O(N) OPERATION
* --------------
* Traverses through the disjoint sets, printing their values.
* A negative value signifies a root node with a tree size equal
* to the magnitude of its value. A positive value signifies a
* child node pointing to its parent, whose index is given by this
* value. If this data structure is empty or NULL, this function
* does nothing.
*/
void dsjsets_print(dsjsets *d){
// NULL and size-check the parameter
if (!d || !(d->dsets) || !(d->size))
return;
// traverse and print
int i;
for (i = 0; i < d->size; i++){
if (i != (d->size -1))
printf("(set %d: %d) ", i, d->dsets[i]);
else
printf("(set %d: %d)\n", i, d->dsets[i]);
}
}
/* O(1) OPERATION
* --------------
* Destroys the memory associated with this disjoint sets data
* structure. THIS FUNCTION SHOULD BE CALLED BEFORE ANY DISJOINT
* SETS OBJECT LEAVES SCOPE TO AVOID MEMORY LEAKS.
*/
void dsjsets_destroy(dsjsets *d){
// NULL-check the parameter
if (!d || !(d->dsets))
return;
free(d->dsets);
d->dsets = NULL;
d->size = 0;
}
| C | CL | 3ba623de37c9b974787c0ffeb3b55faff7c95ec50a3c725d51050f56ebb13cfc |
// Externs.h
// Global seed for random number generation
extern int global_seed;
// Global for preventing two responses to the same question
extern int question_answered;
// Global for preventing reduction of object2
extern int object2_is_not_a_true_object;
// Globals for talking to myself
extern int intercept;
extern int intercepted;
extern int suppress_reply;
// Global for suppressing banner at intro
extern int no_banner;
// Global for suppressing taking action during a script
extern int suppress_actions;
// Global to determine if we are running a script
extern int mid_script;
// Globals to support running a script
extern int command_number;
extern int skip_commands;
// Global for thinking in spare time
extern int housekeeping;
// Global for using context-sensitive phrase files
extern char frsfiles[FILELEN][FILELEN];
extern int num_frs_files;
// Strings
extern char response[WORDSIZE][SENTLEN];
extern int num_response_words;
extern char object1[WORDSIZE][SENTLEN];
extern int num_object1_words;
extern char object2[WORDSIZE][SENTLEN];
extern int num_object2_words;
// Flags
extern int alldebug;
extern int maint;
extern int filelog;
extern int done_looping; // for main while loop
extern int running_script; // exit from script instead of exit program
extern int VIEWGLOBALS;
extern int training_mode; // If TRUE then program will ask questions and
// store facts permanently
extern int phase; // Number of the program's current phase
extern int recurse_num; // Number of recursions in process_input
extern int capture_output; // Capture output from a script
extern int rule_fired; // Mark hypotheses as generated if rule just fired
extern int output_is_open; // If TRUE then output file is open, If FALSE start new output file
extern int write_to_kb; // If TRUE then write fact to Knowledge Base
extern int stripped_s; // If TRUE prevent match_phrase from infinite looping
extern int added_s;
// Files
extern char datapath[PATHLEN];
| C | CL | a9ca9496bed3fa4d433ae1603a2f6ca3ba87f9799b31af7e43de642672159b5b |
/*
* CAN.h
*
* Created on: 2017��12��21��
* Author: Palmer
*/
#ifndef CAN_H_
#define CAN_H_
#include "S32K116.h" /* include peripheral declarations S32K144 */
#include "devassert.h"
#define BIT1ERR 1
#define BIT0ERR 2
#define ACKERR 3
#define CRCERR 4
#define FRMERR 5
#define STFERR 6
#define ReceiveDataFlag 0x00000030
#ifndef NULL
#define NULL 0
#endif
#define EnableCAN0 1
#define EnableCAN1 1
#define EnableCAN2 1
typedef enum
{
CAN_100K = 100,
CAN_125K = 125,
CAN_250K = 250,
CAN_500K = 500,
CAN_1000K = 1000
} comm_spd_enum;
typedef enum
{
clock_4M = 4,
clock_8M = 8,
clock_16M = 16,
clock_25M = 25,
clock_50M = 50
} clockspd_enum;
typedef struct
{
comm_spd_enum comm_spd; //ͨ���ٶ�
uint8_t CAN_ch; //can ͨ��
clockspd_enum clockspd; //ʱ���ٶȣ���λ M
uint8_t clockSrc; //ʱ��Դѡ�� 0���ⲿʱ�ӣ� 1���ڲ�ʱ��
uint16_t SampPoint; //�����㣬 0.01%���ȣ����� 80%=8000��
} canInit_Struct;
typedef uint8_t (*FunType_Frame)(uint32_t id, uint8_t *data, uint8_t len);
typedef uint8_t (*FunType_Error)(uint8_t ErrorCode);
extern uint8_t CAN_Tx_Call(uint32_t id, uint8_t *data, uint8_t len);
extern uint8_t J1939_CAN_Init(void);
extern void J1939_FLEXCAN_DRV_Deinit(void);
#endif /* CAN_H_ */
| C | CL | 1b7d3ae23c39532a63ec6701b84641db08f2e8c41209753e9f40b014aaaa9ba4 |
/*
* ===========================================================================================
*
* Filename: sunxi_eise.h
*
* Description: EISE HAL definition.
*
* Version: Melis3.0
* Create: 2020-01-09 11:11:56
* Revision: none
* Compiler:
*
* Author: ganqiuye([email protected])
* Organization: SWC-MPD
* Last Modified: 2020-04-02 17:32:52
*
* ===========================================================================================
*/
#ifndef SUNXI_HAL_EISE_H
#define SUNXI_HAL_EISE_H
#include <hal_clk.h>
#include "hal_sem.h"
#ifdef __cplusplus
extern "C"
{
#endif
#include "sunxi_hal_common.h"
#define DEVICE_NAME "sunxi_eise"
/* system address */
#define PLL_ISE_CTRL_REG (0x00D0)
#define EISE_CLK_REG (0x06D0)
#define MBUS_CLK_GATING_REG (0x0804)
#define EISE_BGR_REG (0x06DC)
/* eise register */
#define EISE_CTRL_REG (0x00)
#define EISE_IN_SIZE (0x28)
#define EISE_OUT_SIZE (0x38)
#define EISE_ICFG_REG (0x04)
#define EISE_OCFG_REG (0x08)
#define EISE_INTERRUPT_EN (0x0c)
#define EISE_TIME_OUT_NUM (0x3c)
#define EISE_INTERRUPT_STATUS (0x10)
#define EISE_ERROR_FLAG (0x14)
#define EISE_RESET_REG (0x88)
struct eise_register{
unsigned int addr;
unsigned int value;
};
typedef struct hal_eise_t{
unsigned int eise_base_addr;
unsigned int ccmu_base_addr;
// unsigned long err_cnt;
//unsigned long interrupt_times;
unsigned int irq_id;
hal_clk_id_t pclk;
hal_clk_id_t mclk;
hal_sem_t hal_sem;
}hal_eise_t;
typedef struct sunxi_hal_driver_eise
{
int32_t (*initialize)(int32_t dev);
int32_t (*uninitialize)(int32_t dev);
int32_t (*send)(int32_t dev, const char *data, uint32_t num);
int32_t (*receive)(int32_t dev, int *data, uint32_t num);
int32_t (*control)(int32_t dev, uint32_t control, void* arg);
sunxi_hal_poll_ops *poll_ops;
} const sunxi_hal_driver_eise_t;
#ifdef __cplusplus
}
#endif
#endif
| C | CL | 7ac9469c249fef312b62875873e525e806d01ef950cf63f286a712b3b3959da6 |
cocci_test_suite() {
u8 cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 67 */;
void *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 66 */;
void cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 346 */;
struct mwifiex_roc_cfg cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 330 */;
struct ieee_types_wmm_parameter *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 33 */;
struct mwifiex_ie_types_data *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 32 */;
u16 cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 31 */;
u8 *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 30 */;
struct sk_buff *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 27 */;
struct mwifiex_private *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 26 */;
int cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 26 */;
struct host_cmd_ds_11n_batimeout *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 115 */;
struct mwifiex_sta_node *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 113 */;
struct mwifiex_assoc_event *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 112 */;
struct station_info *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 111 */;
u32 cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 110 */;
struct mwifiex_adapter *cocci_id/* drivers/net/wireless/marvell/mwifiex/uap_event.c 108 */;
}
| C | CL | e061f1e2dbad615e5d9f945c67f4bd2f6a5a16171e3debe5f7021a72057bc761 |
/*************************************************************************************
File Name: prod_cons_mt.c
Objective: Implement a monitor to allow the passage of data between producer and
consumer threads via a shared buffer.
Created By: Kristopher Lowell
Date Created: 3/20/2019
File History:
Created - Approx. 8 hours - KCL - 3/20/2019
*************************************************************************************/
#include "prod_cons_mt.h"
void monitor_init(void) // Initialize monitor values and buffer
{
monitor.buffer = (int *) malloc(sizeof(int) * bufferCapacity); // Dynamically allocate buffer since the capacity is dependent on passed value from command line
monitor.head = 0;
monitor.tail = 0; // Circular buffer (technically array) has head and tail start in same place
monitor.size = 0;
pthread_cond_init(&monitor.notFull, NULL); // Initializing the condition variables
pthread_cond_init(&monitor.notEmpty, NULL);
pthread_mutex_init(&monitor.lock, NULL); // Initializing the lock (mutual exclusion)
}
void monitor_read(unsigned threadID)
{
int data;
bool blocked = false;
pthread_mutex_lock(&monitor.lock);
while(!monitor.size) // If the buffer is empty, wait for a producer to put an integer in
{
if(!blocked)
{
printf("C%d: Blocked due to empty buffer.\n", threadID);
blocked = true;
}
pthread_cond_wait(&monitor.notEmpty, &monitor.lock);
}
if(blocked)
printf("C%d: Done waiting on empty buffer.\n", threadID);
data = monitor.buffer[monitor.head];
printf("C%d: Reading %d from position %d.\n", threadID, data, monitor.head);
monitor.head = (monitor.head + 1) % bufferCapacity; // Increment head node index, taking care of overflow
monitor.size--; // Decrement size to reflect a dequeue
pthread_cond_signal(&monitor.notFull); // Signal another (producer) thread that the buffer can no longer be full
pthread_mutex_unlock(&monitor.lock);
}
void monitor_write(int data, unsigned threadID)
{
bool blocked = false;
pthread_mutex_lock(&monitor.lock);
while(monitor.size == bufferCapacity) // If the buffer is full, wait for a consumer to take an integer out
{
if(!blocked)
{
printf("P%d: Blocked due to full buffer.\n", threadID);
blocked = true;
}
pthread_cond_wait(&monitor.notFull, &monitor.lock);
}
if(blocked)
printf("P%d: Done waiting on full buffer.\n", threadID);
printf("P%d: Writing %d to position %d.\n", threadID, data, monitor.tail);
monitor.buffer[monitor.tail] = data;
monitor.tail = (monitor.tail + 1) % bufferCapacity; // Increment tail node index, taking care of overflow
monitor.size++;
pthread_cond_signal(&monitor.notEmpty); // Singal another (consumer) thread that the buffer can no longer be empty
pthread_mutex_unlock(&monitor.lock);
}
void monitor_destroy(void)
{
free(monitor.buffer); // De-allocate the memory used for the buffer
monitor.buffer = NULL;
pthread_cond_destroy(&monitor.notFull); // Properly destroy the condition variables
pthread_cond_destroy(&monitor.notEmpty);
pthread_mutex_destroy(&monitor.lock); // Properly destroy the lock
} | C | CL | 4526dcb1cc72c250a7d4f4a059081adbaa0e92973da0f186d103abcddae16bb7 |
/** @file
* Copyright (c) 2018, Arm Limited or its affiliates. All rights reserved.
* SPDX-License-Identifier : Apache-2.0
*
* 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.
**/
#ifndef _VAL_PERIPHERALS_H_
#define _VAL_PERIPHERALS_H_
#include "val_common.h"
#include "val_target.h"
#include "val_infra.h"
tbsa_status_t val_i2c_read (addr_t addr, uint8_t *data, uint32_t len);
tbsa_status_t val_i2c_write (addr_t addr, uint8_t *data, uint32_t len);
tbsa_status_t val_spi_init (void);
tbsa_status_t val_spi_read (addr_t addr, uint8_t *data, uint32_t len);
tbsa_status_t val_spi_write (addr_t addr, uint8_t *data, uint32_t len);
tbsa_status_t val_timer_init (addr_t addr, uint32_t time_us, uint32_t timer_tick_us);
tbsa_status_t val_timer_enable (addr_t addr);
tbsa_status_t val_timer_disable (addr_t addr);
tbsa_status_t val_timer_interrupt_clear(addr_t addr);
tbsa_status_t val_wd_timer_init (addr_t addr, uint32_t time_us, uint32_t timer_tick_us);
tbsa_status_t val_wd_timer_enable (addr_t addr);
tbsa_status_t val_wd_timer_disable (addr_t addr);
tbsa_status_t val_is_wd_timer_enabled (addr_t addr);
tbsa_status_t val_mpc_configure_security_attribute (addr_t mpc, addr_t start_addr,addr_t end_addr, mem_tgt_attr_t sec_attr);
tbsa_status_t val_uart_init(addr_t addr);
tbsa_status_t val_uart_tx (addr_t addr, const void *data, uint32_t num);
tbsa_status_t val_nvram_read (addr_t base, uint32_t offset, void *buffer, int size);
tbsa_status_t val_nvram_write (addr_t base, uint32_t offset, void *buffer, int size);
tbsa_status_t val_rtc_init (void);
bool_t val_is_rtc_trustable (addr_t addr);
bool_t val_is_rtc_synced_to_server (addr_t addr);
#endif /* _VAL_PERIPHERALS_H_ */
| C | CL | 346943fe01e97705776f24c9fd816af82bfe84d91892d4ea811dde965877f4f0 |
#ifndef _GRNET_DEF_INC
#define _GRNET_DEF_INC
#include <ke_defs.h>
#include <granit_dos.h>
#define GRNET_NAMES_LEN 16
#define DEF_POLINOM_DEL 64709
#ifndef GRNET_DATA_LEN
#define GRNET_DATA_LEN 256
#endif
const long NetSecret = 0x5850494EuL; //NIPX
const long
CmConnect = 1,
CmDisconnect = 2,
CmData = 3,
CmRetranslation = 5, //Передача телемеханич .данных (TKadr)
CmBeginTU = 6, //Начало Управления
CmResetTU = 7, //Отмена Управления
CmQueryTU = 8, //Запрос клиента на начало управления
CmTuFalse = 9, //Неуспешное ТУ
CmQuery = 10, //Запрос данных по всей базе
CmTuOn = 11, // ТУ - Включить
CmTuOff = 12,
CmTrNorm = 13,
CmTuCancel = 14,
CmEnableTU = 15,
CmDisableTU = 16,
CmErrorTU = 17,
CmActivateTR = 18,
CmQueryCp = 20, //Вызов по КП
CmQueryFa = 21, //Вызов по фа
CmQueryGroup = 22, //Вызов по группе
CmIdle = 0x100,
CmTxFile = 0x200,//Начало передачи файла
CmTxFileChunk = 0x201,//Очередной кусок
CmTxFileDone = 0x202,//Завершение файла
CmRxFileDone = 0x203,//Завершение файла
CmCantTxFile = 0x204,//Не возмодно передать файл
CmErrorTxFile = 0x205,//Ошибка при передаче файла
CmResumeTxFile = 0x206,//Восстановление передачи
CmGetAllRetro = 0x400,//Запрос на передачу ретро
CmGetAllRetroOK = 0x401,//Передача ретро началась
CmGetAllRetroNone = 0x402,//Ретро не ведется
CmGetAllRetroBad = 0x403,//Невозможно в данный момент передать ре
CmModemOff = 45000, //Модем потерял связь
CmInformation = 0xFFF0,
CmError = 0xFFFA,
CmServerNotFound = 0xFFFB,
CmTestString = 0xFFFC,
CmCheckConnect = 0xFFFD,
CmOutputQueueEmpty = 0xFFFE //Очередь на передачу пуста
;
#define CONNECT_NO_ERROR 0
#define CONNECT_SPACE_ERROR 1 //Нет места в списке
#define CONNECT_LEVEL_ERROR 2 //Такой уровень клиентов не поддерживается
#define CONNECT_DENY_ERROR 3 //Сервер отказал в соединении
#define GRNET_FLAG_RECEIPT 0x00000001
#define GRNET_FLAG_NEEDRECEIPT 0x00010000
#pragma pack (push,1)
typedef struct _GRNET_KADR
{
DWORD secret_dword;
WORD receipt;
WORD need_receipt;
DWORD command;
WORD id;
WORD kadr_num;
WORD retry_num;
WORD data_len;
DWORD check_sum;
BYTE data[ANYSIZE_ARRAY];
}GRNET_KADR,*LPGRNET_KADR;
typedef struct _GRNET_BEGIN_CONNECTION
{
char server_name[GRNET_NAMES_LEN]; // ..
char client_name[GRNET_NAMES_LEN]; // ..
WORD client_level; // .. устанавливается клиентом
/*************************/
WORD ID; // ..
WORD error_connection; // ..Устанавливается сервером
}GRNET_BEGIN_CONNECTION ,*LPGRNET_BEGIN_CONNECTION;
#pragma pack (pop)
void __fastcall grnet_protect (LPGRNET_KADR kadr);
BOOL __fastcall grnet_check (LPGRNET_KADR kadr);
BOOL __fastcall grnet_init_kadr(LPGRNET_KADR kadr,DWORD cmd,WORD kadr_num,WORD id,BOOL need_receipt,LPVOID data,DWORD data_len);
inline
DWORD __fastcall grnet_kadr_len(LPGRNET_KADR kadr)
{ return kadr->data_len+sizeof(GRNET_KADR)-sizeof(kadr->data);}
#endif
| C | CL | 54c955c3395e75e640d11f3f630d1533d73865e7f2701b500bd32894a6de024f |
#ifndef _F_AST_
#define _F_AST_
#include "f_def.h"
#include "type.h"
#include "symbol.h"
typedef enum ast_type
{
AST_NULL,
/* operations */
AST_ADD,
AST_MIN,
AST_MUL,
AST_DIV,
AST_MOD,
/* comparison */
AST_EQUAL,
AST_NOT_EQUAL,
AST_LESSER,
AST_GREATER,
AST_LESSER_EQUAL,
AST_GREATER_EQUAL,
/* prefix operator */
AST_UNARY_PLUS,
AST_UNARY_MINUS,
AST_UNARY_NOT,
/* bitwise operaions */
AST_BIT_NOT,
/* prefix expression */
AST_PRE_INCREMENT,
AST_PRE_DECREMENT,
/* postfix expression */
AST_POST_INCREMENT,
AST_POST_DECREMENT,
/* pointer stuff (also prefix operaions) */
AST_DEREF,
AST_ADDRESS,
/* @note: should this be part of conversions/casting? */
AST_PROMOTE,
/* list */
AST_LIST,
/* assignment */
AST_ASSIGN,
/* conditional */
AST_IF,
AST_WHILE,
/* primary */
AST_LITERAL,
AST_IDENTIFIER,
AST_FUNCTION_CALL,
AST_NOP,
_AST_COUNT
} ast_type_t;
typedef enum ast_value_type
{
AST_RVALUE,
AST_LVALUE
} ast_value_type_t;
typedef struct ast_node ast_node_t;
typedef struct ast_node
{
ast_type_t type;
/* @performance: could be index into an array we alloc from */
ast_node_t *left;
ast_node_t *center;
ast_node_t *right;
ast_value_type_t value_type;
union
{
literal_t literal;
/* used to store the the type of and expression */
type_info_t expr_type;
/* if type is an lvalue */
sym_id_t sym_id;
};
} ast_node_t;
typedef struct parser parser_t;
const char *f_ast_type_to_str(ast_type_t type);
void f_print_ast(ast_node_t *node, uint32_t level);
void f_print_ast_postorder(ast_node_t *node);
uint32_t f_ast_tree_size(ast_node_t *tree);
void f_ast_postorder_array(ast_node_t *tree, ast_node_t **array);
ast_node_t *f_make_ast_node(parser_t *parser, ast_type_t type, ast_node_t *left, ast_node_t *center,
ast_node_t *right);
#endif
| C | CL | 20f333e30eab913279a5b6d482097d62269e11e9ca8d315a142a4b9bcfd26a2a |
/*
* socket_unix_domain.h
*
* Created on: Jun 3, 2016
* Author: ahnmh-vw
*/
#ifndef SOCKET_UNIX_DOMAIN_H_
#define SOCKET_UNIX_DOMAIN_H_
#include <sys/un.h> // sockaddr_un
#include <sys/socket.h>
#include "tlpi_hdr.h"
// 소켓 경로명을 사용되는 디렉토리는 접근과 쓰기가 가능해야 함.
#define SOCKET_PATH "/tmp/unix_domain_socket"
#define BUF_SIZE 100
void socket_unix_domain_stream_server();
void socket_unix_domain_stream_client();
void socket_unix_domain_datagram_server();
void socket_unix_domain_datagram_client();
void socket_pair_sample(int argc, char *argv[]);
#endif /* SOCKET_UNIX_DOMAIN_H_ */
| C | CL | 80b2e915032b34bef55b7a227f7c740273eb62bc331ea0e51697bb3cc123668b |
/*===========================================================================
*
* MCU library
*
* Marusenkov S.A., "[email protected]", 2014-2016
*
* THIS SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND
* INCLUDING THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR
* TRADE PRACTICE.
*
*---------------------------------------------------------------------------
*
* File 1986BE9x_SSP.c. SSP functions.
*
*===========================================================================*/
#include "../../inc/SSP.h"
#include <string.h>
//SSP1,SSP2 configurations
static SSPConfig cfgSSP1;
static SSPConfig cfgSSP2;
#if (TARGET_MCU == MCU_1986BE9x)
//2 SSP blocks
static _ssp *regSSPs[2] = { SSP1, SSP2 };
static SSPConfig *cfgSSPs[2] = { &cfgSSP1, &cfgSSP2 };
#elif (TARGET_MCU == MCU_1986BE1x)
//3 SSP blocks
static SSPConfig cfgSSP3;
static _ssp *regSSPs[3] = { SSP1, SSP2, SSP3 };
static SSPConfig *cfgSSPs[3] = { &cfgSSP1, &cfgSSP2, &cfgSSP3 };
#elif (TARGET_MCU == MCU_1901BC1x)
//4 SSP blocks
static SSPConfig cfgSSP3;
static SSPConfig cfgSSP4;
static _ssp *regSSPs[4] = { SSP1, SSP2, SSP3, SSP4 };
static SSPConfig *cfgSSPs[4] = { &cfgSSP1, &cfgSSP2, &cfgSSP3, &cfgSSP4 };
#endif
#define GetRegSSPX(x) (regSSPs[(x)])
#define GetCfgSSPX(x) (cfgSSPs[(x)])
typedef struct tag_SSPClkParams
{
//Input params
u32 speed;
u8 mode;
//Output params
u32 ospeed;
u8 brg;
u8 cpsr;
u8 scr;
} SSPClkParams;
/* */
static MCRESULT TuneSSPClkParams(SSPClkParams *p)
{
MCRESULT result;
u32 scr, cpsr, brg;
u32 minN, hclk, N;
u32 dfSpeed, dfSpeedSaved;
u32 ospeed;
u8 isFound = 0;
hclk = GetHCLK();
//sspclk / speed >= 2 for master, >= 12 for slave mode
minN = (p->mode == SSP_MODE_MASTER) ? 2 : 12;
dfSpeedSaved = p->speed;
brg = 1;
//brg = [0..7], step 1
while(brg < 8)
{
//scr = [0..255], step 1
scr = 0;
while(scr < 64)
{
//cpsr = [2..254], step 2
cpsr = 2;
while(cpsr < 255)
{
N = cpsr * (scr + 1);
if (N < minN)
{
cpsr += 2;
continue;
}
//SSPCLK = HCLK / (2^BRG) = HCLK >> BRG
ospeed = (hclk >> brg) / N;
dfSpeed = ospeed >= p->speed ?
ospeed - p->speed : p->speed - ospeed;
if (dfSpeed < dfSpeedSaved)
{
dfSpeedSaved = dfSpeed;
p->ospeed = ospeed;
p->brg = (u8)brg;
p->cpsr = (u8)cpsr;
p->scr = (u8)scr;
isFound = 1;
}
cpsr += 2;
} //while cpsr
scr++;
} //while scr
brg++;
} //while brg
if (isFound)
result = MCR_OK;
else
result = MCR_SETUPCLK_FAIL;
return (result);
}
#define SSPx_PORTCTRL_CONFIG (PN_NOPULLUP | PN_NOPULLDOWN | PN_NOSHMIT |\
PN_CTRLDRIVER | PN_NOINFILTER)
#define SSPx_PORTRXTX_CONFIG SSPx_PORTCTRL_CONFIG
#define SSPRxTx(port,func,prx,ptx) portRxTx = port; funcRxTx = func;\
pinRx = prx; pinTx = ptx;
#define SSPCtrl(port,func,pfss,pclk) portCtrl = port; funcCtrl = func;\
pinFSS = pfss; pinCLK = pclk;
static MCRESULT SSPMapPortPins(const SSPConfig *cfg)
{
PORTBLOCK portRxTx, portCtrl;
u32 pinRx, pinTx, pinFSS, pinCLK;
u32 funcRxTx, funcCtrl;
u32 isPinsDefined = 1;
switch(cfg->ssp)
{
//--- Select mapping 1986BE91T ---
#if (TARGET_MCU == MCU_1986BE9x)
case SSP_N1: //1986BE91T SSP1
{
switch(cfg->mapRxTx)
{
case SSP1_MAP_RXTX_B14B15: { SSPRxTx(PORT_B, PN_ALTER, PN14, PN15); break; }
case SSP1_MAP_RXTX_F3F0: { SSPRxTx(PORT_F, PN_ALTER, PN3, PN0); break; }
case SSP1_MAP_RXTX_D11D12: { SSPRxTx(PORT_D, PN_REMAP, PN11, PN12); break; }
default: isPinsDefined = 0; break;
} //case SSP_N1, switch(cfg->mapRxTx)
switch(cfg->mapCtrl)
{
case SSP1_MAP_CTRL_B12B13: { SSPCtrl(PORT_B, PN_ALTER, PN12, PN13); break; }
case SSP1_MAP_CTRL_F2F1: { SSPCtrl(PORT_F, PN_ALTER, PN2, PN1); break; }
case SSP1_MAP_CTRL_D9D10: { SSPCtrl(PORT_D, PN_REMAP, PN9, PN10); break; }
default: isPinsDefined = 0; break;
} //case SSP_N1, switch(cfg->mapCtrl)
break;
} //case SSP_N1
case SSP_N2: //1986BE91T SSP2
{
switch(cfg->mapRxTx)
{
case SSP2_MAP_RXTX_D2D6: { SSPRxTx(PORT_D, PN_ALTER, PN2, PN6); break; }
case SSP2_MAP_RXTX_B14B15: { SSPRxTx(PORT_B, PN_REMAP, PN14, PN15); break; }
case SSP2_MAP_RXTX_C2C3: { SSPRxTx(PORT_C, PN_REMAP, PN2, PN3); break; }
case SSP2_MAP_RXTX_F14F15: { SSPRxTx(PORT_F, PN_REMAP, PN14, PN15); break; }
default: isPinsDefined = 0; break;
} //case SSP_N2, switch(cfg->mapRxTx)
switch(cfg->mapCtrl)
{
case SSP2_MAP_CTRL_D3D5: { SSPCtrl(PORT_D, PN_ALTER, PN3, PN5); break; }
case SSP2_MAP_CTRL_B12B13: { SSPCtrl(PORT_B, PN_REMAP, PN12, PN13); break; }
case SSP2_MAP_CTRL_C0C1: { SSPCtrl(PORT_C, PN_REMAP, PN0, PN1); break; }
case SSP2_MAP_CTRL_F12F13: { SSPCtrl(PORT_F, PN_REMAP, PN12, PN13); break; }
default: isPinsDefined = 0; break;
} //case SSP_N2, switch(cfg->mapCtrl)
break;
} //case SSP_N2
//--- End mapping 1986BE91T ---
//--- Select mapping 1986BE1T ---
#elif (TARGET_MCU == MCU_1986BE1x)
case SSP_N1: //1986BE1T SSP1
{
switch(cfg->mapRxTx)
{
case SSP1_MAP_RXTX_C6C5: { SSPRxTx(PORT_C, PN_ALTER, PN6, PN5); break; }
case SSP1_MAP_RXTX_D3D2: { SSPRxTx(PORT_D, PN_ALTER, PN3, PN2); break; }
case SSP1_MAP_RXTX_C5C6: { SSPRxTx(PORT_C, PN_REMAP, PN5, PN6); break; }
default: isPinsDefined = 0; break;
} //case SSP_N1, switch(cfg->mapRxTx)
switch(cfg->mapCtrl)
{
case SSP1_MAP_CTRL_C8C7: { SSPCtrl(PORT_C, PN_ALTER, PN8, PN7); break; }
case SSP1_MAP_CTRL_D5D4: { SSPCtrl(PORT_D, PN_ALTER, PN5, PN4); break; }
default: isPinsDefined = 0; break;
} //case SSP_N1, switch(cfg->mapCtrl)
break;
} //case SSP_N1
case SSP_N2: //1986BE1T SSP2
{
switch(cfg->mapRxTx)
{
case SSP2_MAP_RXTX_C10C9: { SSPRxTx(PORT_C, PN_BASIC, PN10, PN9); break; }
case SSP2_MAP_RXTX_D8D7: { SSPRxTx(PORT_D, PN_BASIC, PN8, PN7); break; }
default: isPinsDefined = 0; break;
} //case SSP_N2, switch(cfg->mapRxTx)
switch(cfg->mapCtrl)
{
case SSP2_MAP_CTRL_C12C11: { SSPCtrl(PORT_C, PN_BASIC, PN12, PN11); break; }
case SSP2_MAP_CTRL_D10D9: { SSPCtrl(PORT_D, PN_BASIC, PN10, PN9); break; }
default: isPinsDefined = 0; break;
} //case SSP_N2, switch(cfg->mapCtrl)
break;
} //case SSP_N2
case SSP_N3: //1986BE1T SSP3
{
//Rx/Tx pins at different ports
switch(cfg->mapRxTx)
{
case SSP3_MAP_RXTX_D12F15:
{ //Rx/Tx
InitializePORTEx(PORT_D, PN12, 0,
PN_REMAP | PN_INPUT | SSPx_PORTRXTX_CONFIG);
InitializePORTEx(PORT_F, PN15, 0,
PN_REMAP | PN_PWR_FASTEST | SSPx_PORTRXTX_CONFIG);
break;
}
case SSP3_MAP_RXTX_F15D12:
{ //Rx/Tx
InitializePORTEx(PORT_F, PN15, 0,
PN_BASIC | PN_INPUT | SSPx_PORTRXTX_CONFIG);
InitializePORTEx(PORT_D, PN12, 0,
PN_BASIC | PN_PWR_FASTEST | SSPx_PORTRXTX_CONFIG);
break;
}
default: isPinsDefined = 0; break;
}
switch(cfg->mapCtrl)
{
case SSP3_MAP_CTRL_F13F14:
{
//FSS/CLK PINS
u32 pwr;
pwr = (cfg->mode == SSP_MODE_MASTER) ? PN_PWR_FASTEST : PN_INPUT;
InitializePORTEx(PORT_F, PN13|PN14, 0,
pwr | PN_REMAP | SSPx_PORTCTRL_CONFIG);
break;
}
default: isPinsDefined = 0; break;
}
//SSP pins already initialized: return
return isPinsDefined ? MCR_OK : MCR_INVALID_MAPPING;
} //case SSP_N3
//--- End mapping 1986BE1T ---
//Select mapping 1901BC1T
#elif (TARGET_MCU == MCU_1901BC1x)
case SSP_N1: //1901BC1T SSP1
{
switch(cfg->mapRxTx)
{
case SSP1_MAP_RXTX_A12A13: { SSPRxTx(PORT_A, PN_ALTER, PN12, PN13); break; }
case SSP1_MAP_RXTX_D4D2: { SSPRxTx(PORT_D, PN_ALTER, PN4, PN2); break; }
case SSP1_MAP_RXTX_E12E13: { SSPRxTx(PORT_E, PN_ALTER, PN12, PN13); break; }
default: isPinsDefined = 0; break;
}
switch(cfg->mapCtrl)
{
case SSP1_MAP_CTRL_A15A14: { SSPCtrl(PORT_A, PN_ALTER, PN15, PN14); break; }
case SSP1_MAP_CTRL_D3D5: { SSPCtrl(PORT_D, PN_ALTER, PN3, PN5); break; }
case SSP1_MAP_CTRL_E15E14: { SSPCtrl(PORT_E, PN_ALTER, PN15, PN14); break; }
default: isPinsDefined = 0; break;
}
break;
} //case SSP_N1
case SSP_N2: //1901BC1T SSP2
{
switch(cfg->mapRxTx)
{
case SSP2_MAP_RXTX_A11A10: { SSPRxTx(PORT_A, PN_ALTER, PN11, PN10); break; }
case SSP2_MAP_RXTX_B15B14: { SSPRxTx(PORT_B, PN_ALTER, PN15, PN14); break; }
case SSP2_MAP_RXTX_D13D15: { SSPRxTx(PORT_D, PN_ALTER, PN13, PN15); break; }
case SSP2_MAP_RXTX_E6E4: { SSPRxTx(PORT_E, PN_ALTER, PN6, PN4); break; }
default: isPinsDefined = 0; break;
}
switch(cfg->mapCtrl)
{
case SSP2_MAP_CTRL_A9A8: { SSPCtrl(PORT_A, PN_ALTER, PN9, PN8); break; }
case SSP2_MAP_CTRL_B13B12: { SSPCtrl(PORT_B, PN_ALTER, PN13, PN12); break; }
case SSP2_MAP_CTRL_D12D14: { SSPCtrl(PORT_D, PN_ALTER, PN12, PN14); break; }
case SSP2_MAP_CTRL_E5E7: { SSPCtrl(PORT_E, PN_ALTER, PN5, PN7); break; }
default: isPinsDefined = 0; break;
}
break;
} //case SSP_N2
case SSP_N3: //1901BC1T SSP3
{
switch(cfg->mapRxTx)
{
case SSP3_MAP_RXTX_C10C8: { SSPRxTx(PORT_C, PN_ALTER, PN10, PN8); break; }
case SSP3_MAP_RXTX_F14F12: { SSPRxTx(PORT_F, PN_ALTER, PN14, PN12); break; }
default: isPinsDefined = 0; break;
}
switch(cfg->mapCtrl)
{
case SSP3_MAP_CTRL_C9C11: { SSPCtrl(PORT_C, PN_ALTER, PN9, PN11); break; }
case SSP3_MAP_CTRL_F13F15: { SSPCtrl(PORT_F, PN_ALTER, PN13, PN15); break; }
default: isPinsDefined = 0; break;
}
break;
} //case SSP_N3
case SSP_N4: //1901BC1T SSP4
{
switch(cfg->mapRxTx)
{
case SSP4_MAP_RXTX_C3C4: { SSPRxTx(PORT_C, PN_ALTER, PN3, PN4); break; }
case SSP4_MAP_RXTX_C15C14: { SSPRxTx(PORT_C, PN_ALTER, PN15, PN14); break; }
case SSP4_MAP_RXTX_E3E2: { SSPRxTx(PORT_E, PN_ALTER, PN3, PN2); break; }
case SSP4_MAP_RXTX_F2F3: { SSPRxTx(PORT_F, PN_ALTER, PN2, PN3); break; }
default: isPinsDefined = 0; break;
}
switch(cfg->mapCtrl)
{
case SSP4_MAP_CTRL_C0C5: { SSPCtrl(PORT_C, PN_ALTER, PN0, PN5); break; }
case SSP4_MAP_CTRL_C12C13: { SSPCtrl(PORT_C, PN_ALTER, PN12, PN13); break; }
case SSP4_MAP_CTRL_E0E1: { SSPCtrl(PORT_E, PN_ALTER, PN0, PN1); break; }
case SSP4_MAP_CTRL_F5F4: { SSPCtrl(PORT_F, PN_ALTER, PN5, PN4); break; }
default: isPinsDefined = 0; break;
}
break;
} //case SSP_N4
//--- End mapping 1901BC1T ---
#endif
default:
return MCR_INVALID_PORT;
}
//Configure ports
if (isPinsDefined)
{
u32 pwr;
pwr = (cfg->mode == SSP_MODE_MASTER) ? PN_PWR_FASTEST : PN_INPUT;
//Initialize port pins
//FSS/CLK
InitializePORTEx(portCtrl, pinFSS, 0, funcCtrl | pwr | SSPx_PORTCTRL_CONFIG);
InitializePORTEx(portCtrl, pinCLK, 0, funcCtrl | pwr | SSPx_PORTCTRL_CONFIG);
//RXD/TXD
InitializePORTEx(portRxTx, pinRx, 0, funcRxTx | PN_INPUT | SSPx_PORTRXTX_CONFIG);
InitializePORTEx(portRxTx, pinTx, 0, funcRxTx | PN_PWR_FASTEST | SSPx_PORTRXTX_CONFIG);
return MCR_OK;
}
else
return MCR_INVALID_MAPPING;
}
#undef SSPCtrl
#undef SSPRxTx
/* */
MCRESULT SSPSetSpeedInternal(SSPBLOCK ssp, u32 speed, u8 mode);
/* */
MCRESULT InitializeSSP(const SSPConfig *cfg)
{
//u16 sspInitBufferData[SSP_FIFO_TX_LENGTH] = {0, 0, 0, 0, 0, 0, 0, 0};
SSPConfig *destCfg;
_ssp *reg;
u32 valCR1;
if (!cfg)
return MCR_INVALID_CFG;
else if (cfg->ssp >= SSP_COUNT)
return MCR_INVALID_PORT;
//Pointer to configuration
destCfg = cfgSSPs[(cfg->ssp)];
//Copy configuration
memcpy(destCfg, cfg, sizeof(SSPConfig));
//Map port
if (SSPMapPortPins(destCfg) != MCR_OK)
return MCR_INVALID_PORT;
if (SSPSetSpeedInternal(destCfg->ssp, destCfg->speed, destCfg->mode) != MCR_OK)
return MCR_SETUPSPEED_FAIL;
//Turn OFF selected SSP
TurnSSP(destCfg->ssp, 0);
//Get SSPx registers
reg = GetRegSSPX(destCfg->ssp);
//Set DSS[3..0] - frame length
reg->CR0 &= ~0x000F;
reg->CR0 |= ((destCfg->dataBits - 1) & 0x000F);
//Set FRF[5..4] - frame format (protocol)
reg->CR0 &= ~0x30;
reg->CR0 |= (destCfg->proto & 0x03) << 4;
//Specified protocol options
switch (destCfg->proto)
{
//SPI protocol options
case SSP_PROTO_SPI:
{
//Set/reset SPO[6] - clock polarity
if (destCfg->opts & SSP_OPTS_SPI_POLHIGH)
reg->CR0 |= PN6;
else
reg->CR0 &= ~PN6;
//Set/reset SPH[7] - register data
if (destCfg->opts & SSP_OPTS_SPI_PHASE2)
reg->CR0 |= PN7;
else
reg->CR0 &= ~PN7;
break;
}
}
valCR1 = (reg->CR1 & 0x0F);
//LBM[0]: 1/0 - enable/disable loopback
if (destCfg->opts & SSP_OPTS_LOOPBACK)
valCR1 |= PN0;
else
valCR1 &= ~PN0;
//Set MS[2]: 0/1 - master/slave
if (destCfg->mode == SSP_MODE_MASTER)
valCR1 &= ~PN2;
else
valCR1 |= PN2;
reg->CR1 = (u8)(valCR1 & 0x0F);
//IMSC register:
//RORIM[0] - receiver overflow interrupt
//RTIM[1] - receiver timeout interrupt
//RXIM[2] - receiver interrupt
//TXIM[3] - tx FIFO is filled to 50% or less
#if (__SSP_MODULE_VERSION == 2)
//VERSION=2
if (destCfg->received || destCfg->transmitted)
{
reg->IMSC = 0;
//RXIM[2]=RTIM[1]=RORIM[0]=1
if (destCfg->received)
reg->IMSC |= (PN2 | PN1 | PN0);
//TXIM[3]=1
if (destCfg->transmitted)
reg->IMSC |= PN3;
//Enable SSPx interrupt
switch(destCfg->ssp)
{
case SSP_N1: IRQEnable(IRQ_SSP1); break;
case SSP_N2: IRQEnable(IRQ_SSP2); break;
#if (TARGET_MCU == MCU_1986BE1x || TARGET_MCU == MCUM_1901BC1T)
case SSP_N3: IRQEnable(IRQ_SSP3); break;
#endif
#if (TARGET_MCU == MCUM_1901BC1T)
case SSP_N4: IRQEnable(IRQ_SSP4); break;
#endif
}
}
#else
//VERSION=1
if (destCfg->received)
{
//RXIM[2]=RTIM[1]=RORIM[0]=1
reg->IMSC |= (PN2 | PN1 | PN0);
//Enable SSPx interrupt
switch(destCfg->ssp)
{
case SSP_N1: IRQEnable(IRQ_SSP1); break;
case SSP_N2: IRQEnable(IRQ_SSP2); break;
#if (TARGET_MCU == MCU_1986BE1x || TARGET_MCU == MCUM_1901BC1T)
case SSP_N3: IRQEnable(IRQ_SSP3); break;
#endif
#if (TARGET_MCU == MCUM_1901BC1T)
case SSP_N4: IRQEnable(IRQ_SSP4); break;
#endif
}
}
#endif /* __SSP_MODULE_VERSION */
else
{
//Disable SSPx interrupt
reg->IMSC &= ~(PN3 | PN2 | PN1 | PN0);
switch(destCfg->ssp)
{
case SSP_N1: IRQDisable(IRQ_SSP1); break;
case SSP_N2: IRQDisable(IRQ_SSP2); break;
#if (TARGET_MCU == MCU_1986BE1x || TARGET_MCU == MCUM_1901BC1T)
case SSP_N3: IRQDisable(IRQ_SSP3); break;
#endif
#if (TARGET_MCU == MCUM_1901BC1T)
case SSP_N4: IRQDisable(IRQ_SSP4); break;
#endif
}
}
return MCR_OK;
}
/* Set SSP speed */
MCRESULT SSPSetSpeedInternal(SSPBLOCK ssp, u32 speed, u8 mode)
{
_ssp *reg;
SSPClkParams clkp;
//Check ssp block index
if (ssp >= SSP_COUNT)
return MCR_INVALID_PORT;
//Check requested speed
if (speed > SSP_MAX_SPEED)
speed = SSP_MAX_SPEED;
clkp.speed = speed;
clkp.mode = mode;
clkp.brg = 0;
clkp.cpsr = 0;
clkp.scr = 0;
//Tune clock parameters
if (TuneSSPClkParams(&clkp) != MCR_OK)
return MCR_SETUPCLK_FAIL;
//Configure SSPx clock (FSSPCLK)
switch(ssp)
{
case SSP_N1:
{
//Enable SSP1 clock
ClkEnable(CLK_SSP1);
//SSP1_CLK_EN[24] = 0
RST_CLK->SSP_CLOCK &= ~PN24;
//Setup SSP1_BRG[7..0] at [0..7]
//FSSPCLK = HCLK / (1 << BRG)
RST_CLK->SSP_CLOCK &= ~0xFF;
RST_CLK->SSP_CLOCK |= clkp.brg;
//SSP1_CLK_EN[24] = 1
RST_CLK->SSP_CLOCK |= PN24;
break;
}
case SSP_N2:
{
//Enable SSP2 clock
ClkEnable(CLK_SSP2);
//SSP2_CLK_EN[25] = 0
RST_CLK->SSP_CLOCK &= ~PN25;
//Setup SSP2_BRG[15..8] at [0..7]
//FSSPCLK = HCLK / (1 << BRG)
RST_CLK->SSP_CLOCK &= ~(0xFF << 8);
RST_CLK->SSP_CLOCK |= clkp.brg << 8;
//SSP2_CLK_EN[25] = 1
RST_CLK->SSP_CLOCK |= PN25;
break;
}
#if (TARGET_MCU == MCU_1986BE1x || TARGET_MCU == MCU_1901BC1x)
case SSP_N3:
{
//Enable SSP2 clock
ClkEnable(CLK_SSP3);
//SSP3_CLK_EN[26] = 0
RST_CLK->SSP_CLOCK &= ~PN26;
//Setup SSP3_BRG[23..16] at [0..7]
//FSSPCLK = HCLK / (1 << BRG)
RST_CLK->SSP_CLOCK &= ~(0xFF << 16);
RST_CLK->SSP_CLOCK |= clkp.brg << 16;
//SSP3_CLK_EN[26] = 1
RST_CLK->SSP_CLOCK |= PN26;
break;
}
#endif
#if (TARGET_MCU == MCU_1901BC1x)
case SSP_N4:
{
//Enable SSP4 clock
ClkEnable(CLK_SSP4);
//SSP4_CLK_EN[24] = 0
RST_CLK->SSP_CLOCK2 &= ~PN24;
//Setup SSP4_BRG[7..0]
//FSSPCLK = HCLK / (1 << BRG)
RST_CLK->SSP_CLOCK2 &= ~0xFF;
RST_CLK->SSP_CLOCK2 |= clkp.brg;
//SSP4_CLK_EN[24] = 1
RST_CLK->SSP_CLOCK2 |= PN24;
break;
}
#endif
}
reg = GetRegSSPX(ssp);
//Set SCR, CPSR: clock out (FSSPCLKOUT)
//FSSPCLKOUT = FSSPCLK / (CPSR * (SCR + 1))
//Set SCR[15..8]
reg->CR0 &= ~(0xFF << 8);
reg->CR0 |= (clkp.scr << 8);
//Set CPSR[7..0]
reg->CPSR &= ~0xFF;
reg->CPSR = clkp.cpsr;
return MCR_OK;
}
/* Set SSP speed */
MCRESULT SSPSetSpeed(SSPBLOCK ssp, u32 speed)
{
u32 isWasON;
_ssp *reg;
SSPConfig *destCfg;
MCRESULT result;
//Check ssp block index
if (ssp >= SSP_COUNT)
return MCR_INVALID_PORT;
reg = GetRegSSPX(ssp);
destCfg = cfgSSPs[ssp];
//SSE[1] = 1/0 - SSP ON/OFF
isWasON = (reg->CR1 & PN1) ? 1 : 0;
//Turn SSP OFF
TurnSSP(ssp, 0);
//Setup speed
result = SSPSetSpeedInternal(ssp, speed, destCfg->mode);
//Turn SSP ON
if (isWasON && result == MCR_OK)
TurnSSP(ssp, 1);
return result;
}
/* Get SSP clock, Hz */
u32 GetSSPClk(SSPBLOCK ssp)
{
u32 hclk = GetHCLK();
u32 clk = 0;
//FSSPCLK = HCLK / (1 << BRG)
switch(ssp)
{
case SSP_N1:
{
//SSP1 enable and SSP1_CLK_EN[24]
if (!(RST_CLK->PER_CLOCK & (1 << CLK_SSP1)) ||
!(RST_CLK->SSP_CLOCK & PN24))
break;
//SSP1_BRG[7..0]
clk = hclk / (1 << (u8)RST_CLK->SSP_CLOCK);
break;
}
case SSP_N2:
{
//SSP2 enable and SSP2_CLK_EN[25]
if (!(RST_CLK->PER_CLOCK & (1 << CLK_SSP2)) ||
!(RST_CLK->SSP_CLOCK & PN25))
break;
//SSP2_BRG[15..8]
clk = hclk / (1 << ((u8)(RST_CLK->SSP_CLOCK >> 8)));
break;
}
#if (TARGET_MCU == MCU_1986BE1x || TARGET_MCU == MCU_1901BC1x)
case SSP_N3:
{
//SSP3 enable and SSP3_CLK_EN[26]
if (!(RST_CLK->PER_CLOCK & (1 << CLK_SSP3)) ||
!(RST_CLK->SSP_CLOCK & PN26))
break;
//SSP3_BRG[23..16]
clk = hclk / (1 << ((u8)(RST_CLK->SSP_CLOCK >> 16)));
break;
}
#endif
#if (TARGET_MCU == MCU_1901BC1x)
case SSP_N4:
{
//SSP4 enable and SSP4_CLK_EN[24]
if (!(RST_CLK->PER_CLOCK & (1 << CLK_SSP4)) ||
!(RST_CLK->SSP_CLOCK2 & PN24))
break;
//SSP4_BRG[7..0]
clk = hclk / (1 << ((u8)(RST_CLK->SSP_CLOCK2)));
break;
}
#endif
}
return clk;
}
/* Get SSP speed, bit/s */
u32 GetSSPSpeed(SSPBLOCK ssp)
{
_ssp *reg = GetRegSSPX(ssp);
//FSSPCLKOUT = FSSPCLK / (CPSR * (SCR + 1))
//CPSR[7..0], SCR[15..8]
//if SSE[1] is set SSP turned ON
if (reg->CR1 & PN1)
return (u32)(GetSSPClk(ssp) / ( (u8)reg->CPSR * ((u8)(reg->CR0 >> 8) + 1)) );
else
return 0;
}
/* */
void TurnSSP(SSPBLOCK ssp, u8 turn)
{
_ssp *reg = GetRegSSPX(ssp);
//Set/reset SSE[1] - turn ON/OFF SSP
if (turn)
reg->CR1 |= PN1;
else
{
//while BSY[4] == 1 - while SSP is busy
//while(reg->SR & PN4);
reg->CR1 &= ~PN1;
}
}
/* */
void TurnSSPTx(SSPBLOCK ssp, u8 turn)
{
_ssp *reg = GetRegSSPX(ssp);
//if MS[2] = 0 - its master mode
//SOD[3] used only at slave mode
if (!(reg->CR1 & PN2))
return;
if (turn)
reg->CR1 &= ~PN3; //Reset SOD[3]: enable TxD
else
reg->CR1 |= PN3; //Set SOD[3]: disable TxD
}
/* Turn ON/OFF SSP loopback */
void TurnSSPLB(SSPBLOCK ssp, u8 on)
{
_ssp *reg;
u32 valCR1;
reg = GetRegSSPX(ssp);
valCR1 = (reg->CR1 & 0x0F);
//LBM[0]: 1/0 - enable/disable loopback
if (on)
valCR1 |= PN0;
else
valCR1 &= ~PN0;
reg->CR1 = (u8)(valCR1 & 0x0F);
}
/* */
void SSPWaitNotBusy(SSPBLOCK ssp)
{
_ssp *reg = GetRegSSPX(ssp);
//while BSY[4] == 1 - while SSP is busy
while(reg->SR & PN4);
}
/* Indicating that input fifo is empty */
u8 IsSSPInFifoEmpty(SSPBLOCK ssp)
{
//RNE[2]: 1/0 - input fifo not empty/empty
return (GetRegSSPX(ssp)->SR & PN2) ? 0 : 1;
}
/* Indicating that input fifo is full */
u8 IsSSPInFifoFull(SSPBLOCK ssp)
{
//RFF[3]: 1/0 - input fifo full/not full
return (GetRegSSPX(ssp)->SR & PN3) ? 1 : 0;
}
/* Indicating that output fifo is empty */
u8 IsSSPOutFifoEmpty(SSPBLOCK ssp)
{
//TFE[0]: 1/0 - output fifo empty/not empty
return (GetRegSSPX(ssp)->SR & PN0) ? 1 : 0;
}
/* Indicating that output fifo is full */
u8 IsSSPOutFifoFull(SSPBLOCK ssp)
{
//TNF[1]: 1/0 - output fifo not full/full
return (GetRegSSPX(ssp)->SR & PN1) ? 0 : 1;
}
/* Indicates that SSP busy: tx/rx data or tx FIFO not empty */
u8 IsSSPBusy(SSPBLOCK ssp)
{
//BSY[4]: 1 - SSP tx/rx data or tx FIFO not empty
return (GetRegSSPX(ssp)->SR & PN4);
}
/* Fill output fifo cells with specified value */
void SSPInitOutFifo(SSPBLOCK ssp, u32 v)
{
s32 i = 0;
_ssp *reg = GetRegSSPX(ssp);
while(i < SSP_FIFO_TX_LENGTH)
{
reg->DR = (u16)v;
i++;
}
}
/* Flush output data */
void SSPFlush(SSPBLOCK ssp)
{
_ssp *reg = GetRegSSPX(ssp);
//TFE[0]: 1/0 - output fifo empty/not empty
while ((reg->SR & PN0) == 0) __NOP();
}
/* */
s32 SSPRead(SSPBLOCK ssp, void *dest, s32 count)
{
s32 i = 0;
_ssp *reg = GetRegSSPX(ssp);
if (GetCfgSSPX(ssp)->dataBits != 8)
{
//Frame size: 16 bit
u16 *pdata16 = (u16*)dest;
//RNE[2]: 1 - input fifo not empty
//read data
while((reg->SR & PN2) && i < count)
{
*pdata16++ = reg->DR;
i += 2;
}
}
else
{
//Frame size: 8 bit
u8 *pdata8 = (u8*)dest;
//RNE[2]: 1 - input fifo not empty
//read data
while((reg->SR & PN2) && i < count)
{
*pdata8++ = reg->DR;
i++;
}
}
return i;
}
/* */
s32 SSPWrite(SSPBLOCK ssp, const void *src, s32 count)
{
s32 i = 0, n;
_ssp *reg = GetRegSSPX(ssp);
if (GetCfgSSPX(ssp)->dataBits != 8)
{
//Frame size: 16 bit
const u16 *pdata16 = (u16*)src;
//V1. TNF[1]: 0 - output fifo is full.
/* while(i < count)
{
while(!(reg->SR & PN1));
reg->DR = *pdata16++;
i += 2;
} */
//V2. TNF[1]: 1 - output fifo is not full.
/* while(i < count)
{
if (reg->SR & PN1)
{
reg->DR = *pdata16++;
i += 2;
}
}
*/
//V3. TFE[0]: 1 - output fifo is empty
while(i < count)
{
if (reg->SR & PN0)
{
n = 0;
while(i < count && n++ < SSP_FIFO_TX_LENGTH)
{
reg->DR = *pdata16++;
i += 2;
}
}
}
//odd byte count
if (count & 1)
{
//TFE[0]: 1 - output fifo is empty
while (!(reg->SR & PN0));
//Write last byte
reg->DR = (u16)(((u8*)src)[count - 1]);
}
}
else
{
//Frame size: 8 bit
const u8 *pdata8 = (u8*)src;
//V1. TNF[1]: 0 - output fifo is full.
/* while(i < count)
{
while(!(reg->SR & PN1));
reg->DR = *pdata8++;
i++;
} */
//V2. TNF[1]: 1 - output fifo is not full.
while(i < count)
{
if (reg->SR & PN1)
{
reg->DR = *pdata8++;
i++;
}
}
//V3. TFE[0]: 1 - output fifo is empty
//With errors: write SD card block (512 bytes)
/*while(i < count)
{
if (reg->SR & PN0)
{
n = 0;
while(i++ < count && n++ < SSP_FIFO_TX_LENGTH)
reg->DR = *pdata8++;
}
}*/
}
return i;
}
/* Read one element from SSP fifo */
s32 SSPReadFifo(SSPBLOCK ssp, u16 *data)
{
_ssp *reg = GetRegSSPX(ssp);
*data = reg->DR;
return 1;
}
/* Write one element to SSP fifo */
s32 SSPWriteFifo(SSPBLOCK ssp, u16 data)
{
_ssp *reg = GetRegSSPX(ssp);
reg->DR = data;
return 1;
}
/* */
__IRQH_FATTR void SSPx_IRQHandler(_ssp *reg, SSPConfig *cfg)
{
#if (__SSP_MODULE_VERSION == 2)
u32 mis = reg->MIS;
//RXMIS[2]=1, RTMIS[1]=1 or RORMIS[0]=1
if (mis & (PN2 | PN1 | PN0))
{
//Set RTIC[1], RORIC[0]: 1 - cancel interrupt
reg->ICR |= PN1 | PN0;
if (cfg->received)
cfg->received();
}
//TXMIS[3]=1
if (mis & PN3)
{
if (cfg->transmitted)
cfg->transmitted();
}
#else
//RXMIS[2]=1, RTMIS[1]=1 or RORMIS[0]=1
if (reg->MIS & (PN2 | PN1 | PN0))
{
//Set RTIC[1], RORIC[0]: 1 - cancel interrupt
reg->ICR |= PN1 | PN0;
if (cfg->received)
cfg->received();
}
#endif /* __SSP_MODULE_VERSION */
}
/* */
void SSP1_IRQHandler(void)
{
SSPx_IRQHandler(SSP1, &cfgSSP1);
}
/* */
void SSP2_IRQHandler(void)
{
SSPx_IRQHandler(SSP2, &cfgSSP2);
}
#if (TARGET_MCU == MCU_1986BE1x || TARGET_MCU == MCU_1901BC1x)
/* */
void SSP3_IRQHandler(void)
{
SSPx_IRQHandler(SSP3, &cfgSSP3);
}
#endif /* TARGET_MCU == MCU_1986BE1x || TARGET_MCU == MCU_1901BC1x */
#if (TARGET_MCU == MCU_1901BC1x)
/* */
void SSP4_IRQHandler(void)
{
SSPx_IRQHandler(SSP4, &cfgSSP4);
}
#endif /* TARGET_MCU == MCU_1901BC1x */
/*===========================================================================
* End of file 1986BE9x_SSP.c
*===========================================================================*/
| C | CL | 11459a948c46fb2ba1162c29f9377e4ddf86697fd810876ee3e522ea7261566b |
#ifndef CLOX_VM_H
#define CLOX_VM_H
#include "chunk.h"
#include "object.h"
#include "value.h"
#include "table.h"
#define FRAMES_MAX 64
#define STACK_MAX (UINT8_MAX * FRAMES_MAX)
struct call_frame {
obj_function_t *function;
uint8_t *ip;
value_t *slots;
};
struct vm {
struct call_frame frames[FRAMES_MAX];
int frame_count;
value_t stack[STACK_MAX]; /* the virtual machine's stack*/
value_t *stack_top; /* the top of the vm's stack */
struct obj *objects; /* head of list of objects to be tracked by vm*/
struct table strings; /* hash table of interned strings */
struct table globals; /* hash table for global variables */
bool repl_mode;
};
typedef enum {
INTERPRET_OK,
INTERPRET_COMPILE_ERROR,
INTERPRET_RUNTIME_ERROR,
} interpret_result_t;
extern struct vm vm;
void init_vm();
void free_vm();
interpret_result_t interpret_vm(const char *c);
void push(value_t val);
value_t pop();
#endif | C | CL | 0eba1b176ae2d2b38fa11053a6284e072de74b469148dcbe39c3a66157d57a72 |
/******************************************************************************
* track_drv_ble_gatt.h -
*
* Copyright .
*
* DESCRIPTION: -
* BLE GATT协议处理 ,这里是BCM模块,TRACK不要直接操作
*
* modification history
* --------------------
* v1.0 2017-05-22, chengjun create this file
*
******************************************************************************/
#ifndef _TRACK_BLE_GATT_H
#define _TRACK_BLE_GATT_H
/****************************************************************************
* Include Files 包含头文件
*****************************************************************************/
#include "stack_msgs.h"
#include "stack_ltlcom.h"
#include "drvsignals.h"
#include "kal_public_defs.h"
//#include "btostypes.h"
/*****************************************************************************
* Define 宏定义
*****************************************************************************/
//#define __BLE_NF2318_LOG__
/*****************************************************************************
* Typedef Enum
*****************************************************************************/
/*****************************************************************************
* Struct 数据结构定义
*****************************************************************************/
typedef struct
{
LOCAL_PARA_HDR
kal_uint8 ble_switch;
char name_data[20];
kal_uint8 devicesn[20];
}track_ble_switch_msg_struct;
typedef struct
{
LOCAL_PARA_HDR
kal_uint8 reply_data[30];//kal_uint8 reply_data[10]; // 2318的蓝牙数据大于20,这把大小10 改为30;
}track_reply_ble_msg_struct;
typedef struct
{
LOCAL_PARA_HDR
kal_uint8 len;
kal_uint8 buff[5];
}track_ble_data_msg_struct;
typedef enum
{
BLE_MAC_ADDR=0,
BLE_EVT_LOCK,
BLE_EVT_UNLOCK,
BLE_EVT_MAX
}BLE_EVT;
/*****************************************************************************
* Local variable 局部变量
*****************************************************************************/
/****************************************************************************
* Global Variable - Extern 全局变量
*****************************************************************************/
/****************************************************************************
* Global Variable - Extern 引用全局变量
*****************************************************************************/
/*****************************************************************************
* Global Functions - Extern 引用外部函数
*****************************************************************************/
/*****************************************************************************
* Local Functions 本地函数
*****************************************************************************/
#endif /* _TRACK_BLE_GATT_H */
| C | CL | 75c9b3e9c1128a0f5b6b49b8a8b597969b2d6c7ecf071d74c74b0e45b15647aa |
/*
* Copyright (c) 2016-2017, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//!
//! \file vphal_common_tools.h
//! \brief vphal tools interface clarification
//! \details vphal tools interface clarification inlcuding:
//! some marcro, enum, structure, function
//!
#ifndef __VPHAL_COMMON_TOOLS_H__
#define __VPHAL_COMMON_TOOLS_H__
// max size of status table, this value must be power of 2 such as 256, 512, 1024, etc.
// so VPHAL_STATUS_TABLE_MAX_SIZE-1 can form a one-filled mask to wind back a VPHAL_STATUS_TABLE ring table.
#define VPHAL_STATUS_TABLE_MAX_SIZE 512
//!
//! Structure VPHAL_STATUS_ENTRY
//! \brief Pre-Processing - Query status struct
//!
typedef struct _VPHAL_STATUS_ENTRY
{
uint32_t StatusFeedBackID;
MOS_GPU_CONTEXT GpuContextOrdinal;
uint32_t dwTag; // software tag, updated by driver for every command submit.
uint32_t dwStatus; // 0:OK; 1:Not Ready; 2:Not Available; 3:Error;
} VPHAL_STATUS_ENTRY, *PVPHAL_STATUS_ENTRY;
//!
//! \brief Structure to VPHAL Status table
//!
typedef struct _VPHAL_STATUS_TABLE
{
VPHAL_STATUS_ENTRY aTableEntries[VPHAL_STATUS_TABLE_MAX_SIZE];
uint32_t uiHead;
uint32_t uiCurrent;
} VPHAL_STATUS_TABLE, *PVPHAL_STATUS_TABLE;
//!
//! Structure STATUS_TABLE_UPDATE_PARAMS
//! \brief Pre-Processing - params for updating status report table
//!
typedef struct _STATUS_TABLE_UPDATE_PARAMS
{
bool bReportStatus;
bool bSurfIsRenderTarget;
PVPHAL_STATUS_TABLE pStatusTable;
uint32_t StatusFeedBackID;
#if (_DEBUG || _RELEASE_INTERNAL)
bool bTriggerGPUHang;
#endif
} STATUS_TABLE_UPDATE_PARAMS, *PSTATUS_TABLE_UPDATE_PARAMS;
//!
//! \brief Structure to query status params from application
//! be noted that the structure is defined by app (msdk) so we cannot reorder its entries or size
//!
typedef struct _QUERY_STATUS_REPORT_APP
{
uint32_t StatusFeedBackID;
uint32_t dwStatus : 8; //!< 0: OK; 1: Not Ready; 2: Not Available; 3: Error;
uint32_t : 24; //!< Reserved
uint32_t dwReserved[4]; //!< keep this to align what application (msdk lib) defined
} QUERY_STATUS_REPORT_APP, *PQUERY_STATUS_REPORT_APP;
//!
//! \brief VPreP status
//!
typedef enum _VPREP_STATUS
{
VPREP_OK = 0,
VPREP_NOTREADY = 1,
VPREP_NOTAVAILABLE = 2,
VPREP_ERROR = 3
} VPREP_STATUS;
//!
//! \brief Internal Override/Reporting Video Processing Configuration Values
//!
typedef struct _VP_CONFIG
{
bool bSettingReadDone; // Settings have been read
bool bVpComponentReported; // Vp Component has been reported
uint32_t dwVpPath; // Video Processing path
uint32_t dwVpComponent; // Video Processing Component
uint32_t dwCreatedDeinterlaceMode; // Created Deinterlace mode
uint32_t dwCurrentDeinterlaceMode; // Current Deinterlace mode
uint32_t dwReportedDeinterlaceMode; // Reported Deinterlace mode
uint32_t dwCreatedScalingMode; // Created Scaling mode
uint32_t dwCurrentScalingMode; // Current Scaling mode
uint32_t dwReportedScalingMode; // Reported Scaling mode
uint32_t dwReportedFastCopyMode; // Reported FastCopy mode
uint32_t dwCurrentXVYCCState; // Current xvYCC State
uint32_t dwReportedXVYCCState; // Reported xvYCC state
uint32_t dwCurrentOutputPipeMode; // Current Output Pipe Mode
uint32_t dwReportedOutputPipeMode; // Reported Ouput Pipe Mode
uint32_t dwCurrentVEFeatureInUse; // Current VEFeatureInUse
uint32_t dwReportedVEFeatureInUse; // Reported VEFeatureInUse
uint32_t dwCurrentFrcMode; // Current Frame Rate Conversion Mode
uint32_t dwReportedFrcMode; // Reported Frame Rate Conversion Mode
uint32_t dwVPMMCInUse; // Memory compression enable flag
uint32_t dwVPMMCInUseReported; // Reported Memory compression enable flag
uint32_t dwRTCompressible; // RT MMC Compressible flag
uint32_t dwRTCompressibleReported; // RT MMC Reported compressible flag
uint32_t dwRTCompressMode; // RT MMC Compression Mode
uint32_t dwRTCompressModeReported; // RT MMC Reported Compression Mode
uint32_t dwFFDICompressible; // FFDI Compressible flag
uint32_t dwFFDICompressMode; // FFDI Compression mode
uint32_t dwFFDNCompressible; // FFDN Compressible flag
uint32_t dwFFDNCompressMode; // FFDN Compression mode
uint32_t dwSTMMCompressible; // STMM Compressible flag
uint32_t dwSTMMCompressMode; // STMM Compression mode
uint32_t dwScalerCompressible; // Scaler Compressible flag for Gen10
uint32_t dwScalerCompressMode; // Scaler Compression mode for Gen10
uint32_t dwPrimaryCompressible; // Input Primary Surface Compressible flag
uint32_t dwPrimaryCompressMode; // Input Primary Surface Compression mode
uint32_t dwFFDICompressibleReported; // FFDI Reported Compressible flag
uint32_t dwFFDICompressModeReported; // FFDI Reported Compression mode
uint32_t dwFFDNCompressibleReported; // FFDN Reported Compressible flag
uint32_t dwFFDNCompressModeReported; // FFDN Reported Compression mode
uint32_t dwSTMMCompressibleReported; // STMM Reported Compressible flag
uint32_t dwSTMMCompressModeReported; // STMM Reported Compression mode
uint32_t dwScalerCompressibleReported; // Scaler Reported Compressible flag for Gen10
uint32_t dwScalerCompressModeReported; // Scaler Reported Compression mode for Gen10
uint32_t dwPrimaryCompressibleReported; // Input Primary Surface Reported Compressible flag
uint32_t dwPrimaryCompressModeReported; // Input Primary Surface Reported Compression mode
uint32_t dwCapturePipeInUse; // Capture pipe
uint32_t dwCapturePipeInUseReported; // Reported Capture pipe
uint32_t dwCurrentCompositionMode; // In Place or Legacy Composition
uint32_t dwReportedCompositionMode; // Reported Composition Mode
uint32_t dwCurrentHdrMode; // Current Hdr Mode
uint32_t dwReportedHdrMode; // Reported Hdr Mode
// Configurations for cache control
uint32_t dwDndiReferenceBuffer;
uint32_t dwDndiOutputBuffer;
uint32_t dwIecpOutputBuffer;
uint32_t dwDnOutputBuffer;
uint32_t dwStmmBuffer;
uint32_t dwPhase2RenderTarget;
uint32_t dwPhase2Source;
uint32_t dwPhase1Source;
// For Deinterlace Mode - the flags reflect the content size and SKU,
// should not be changed after initialized.
bool bFFDI;
} VP_CONFIG, *PVP_CONFIG;
//!
//! \brief status query param
//!
typedef struct _VPHAL_STATUS_PARAM
{
uint32_t FrameId;
VPREP_STATUS BltStatus;
} VPHAL_STATUS_PARAM, *PVPHAL_STATUS_PARAM;
//!
//! Structure VPHAL_QUERYVARIANCE_PARAMS
//! \brief Query Variance Parameters
//!
typedef struct _VPHAL_QUERYVARIANCE_PARAMS
{
uint32_t dwFrameNumber;
void* pVariances;
} VPHAL_QUERYVARIANCE_PARAMS, *PVPHAL_QUERYVARIANCE_PARAMS;
//!
//! \brief Query Multiple Variance Parameters
//!
typedef struct _VPHAL_BATCHQUERYVARIANCE_PARAMS
{
uint32_t FrameCount;
uint32_t BufferSize;
void *pBuffer;
} VPHAL_BATCHQUERYVARIANCE_PARAMS, *PVPHAL_BATCHQUERYVARIANCE_PARAMS;
//!
//! Structure VPHAL_SPLIT_SCREEN_DEMO_POSITION
//! \brief Split-Screen Demo Mode Position
//!
typedef enum _VPHAL_SPLIT_SCREEN_DEMO_POSITION
{
SPLIT_SCREEN_DEMO_DISABLED = 0,
SPLIT_SCREEN_DEMO_LEFT,
SPLIT_SCREEN_DEMO_RIGHT,
SPLIT_SCREEN_DEMO_TOP,
SPLIT_SCREEN_DEMO_BOTTOM,
SPLIT_SCREEN_DEMO_END_POS_LIST
} VPHAL_SPLIT_SCREEN_DEMO_POSITION;
//!
//! Structure VPHAL_SPLIT_SCREEN_DEMO_MODE_PARAMS
//! \brief Split-Screen Demo Mode Parameters
//!
typedef struct _VPHAL_SPLIT_SCREEN_DEMO_MODE_PARAMS
{
VPHAL_SPLIT_SCREEN_DEMO_POSITION Position; //!< Position of split mode area (disable features)
bool bDisableACE : 1; //!< Disable ACE
bool bDisableAVS : 1; //!< Disable AVS
bool bDisableDN : 1; //!< Disable DN
bool bDisableFMD : 1; //!< Disable FMD
bool bDisableIEF : 1; //!< Disable IEF
bool bDisableProcamp : 1; //!< Disable Procamp
bool bDisableSTE : 1; //!< Disable STE
bool bDisableTCC : 1; //!< Disable TCC
bool bDisableIS : 1; //!< Disable IS
bool bDisableDrDb : 1; //!< Disable DRDB
bool bDisableDNUV : 1; //!< Disable DNUV
bool bDisableFRC : 1; //!< Disable FRC
bool bDisableLACE : 1; //!< Disable LACE
} VPHAL_SPLIT_SCREEN_DEMO_MODE_PARAMS, *PVPHAL_SPLIT_SCREEN_DEMO_MODE_PARAMS;
#endif // __VPHAL_COMMON_TOOLS_H__
| C | CL | 9b9fc112de2ab38bb0302e4d2a7e7e4f6d9968cab0c98264ce603bb74799a6c7 |
/*
* Copyright 2017 Hewlett Packard Enterprise Development LP
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder 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.
*/
#ifndef NVWAL_ATOMICS_H_
#define NVWAL_ATOMICS_H_
/**
* @file nvwal_atomics.h
* This file wraps atomic functions defined in C11 in case the client program
* does not allow using C11 features.
* nvwal_xxx wraps xxx function/macro in C11.
* Do NOT directly use xxx in our code. Always use nvwal_xxx enums/macros/functions.
*
* In order to support RHEL 7.x, we alter stdatomic.h with our own implementation.
* This header should work for the following compilers:
* \li gcc 4.9 and later should work trivially with stdatomic.h.
* \li Reasonably new clang should work trivially with stdatomic.h.
* \li gcc 4.8 is supported via our own version of atomic wrappers.
*
* We don't wrap macros for old clang as rigorously as for old gcc.
* We think it's fine as few poeple \e have \e to use old clang
* as opposed to old gcc that people can't replace tend to abound.
* gcc 4.7 and older are \b not supported. Sorry.
*
* @see http://en.cppreference.com/w/c/atomic
* @see https://gist.github.com/nhatminhle/5181506
* @ingroup LIBNVWAL_INTERNAL
* @addtogroup LIBNVWAL_INTERNAL
* @{
*/
/*
* If __STDC_NO_ATOMICS__ is defined, we surely don't have stdatomic.h.
* However, an old version of gcc (4.8) does not follow this rule.
* If it's 4.8, we go into this route, too.
*/
#if defined(__STDC_NO_ATOMICS__) || (defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ == 8))
/*
* stdatomic.h doesn't exist! We need to implement it by ourselves.
* We assume this is gcc 4.8 or later, so at least the 'internal' version
* of the macros (e.g., __ATOMIC_RELAXED) exist with a bit different name.
* To support 4.7 and older, we have to really emulate all
* logics with older gcc maro.. not worth it.
* @see https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html
*/
typedef enum {
nvwal_memory_order_relaxed = __ATOMIC_RELAXED,
nvwal_memory_order_consume = __ATOMIC_CONSUME,
nvwal_memory_order_acquire = __ATOMIC_ACQUIRE,
nvwal_memory_order_release = __ATOMIC_RELEASE,
nvwal_memory_order_acq_rel = __ATOMIC_ACQ_REL,
nvwal_memory_order_seq_cst = __ATOMIC_SEQ_CST,
} nvwal_memory_order;
#define nvwal_atomic_init(PTR, VAL) atomic_init(PTR, VAL)
#define nvwal_atomic_store(PTR, VAL) __atomic_store_n(PTR, VAL, __ATOMIC_SEQ_CST)
#define nvwal_atomic_store_explicit(PTR, VAL, ORD)\
__atomic_store_n(PTR, VAL, ORD)
#define nvwal_atomic_load(PTR) __atomic_load_n(PTR, __ATOMIC_SEQ_CST)
#define nvwal_atomic_load_explicit(PTR, ORD)\
__atomic_load_n(PTR, ORD)
#define nvwal_atomic_exchange(PTR, VAL) __atomic_exchange(PTR, VAL, __ATOMIC_SEQ_CST)
#define nvwal_atomic_exchange_explicit(PTR, VAL, ORD)\
__atomic_exchange(PTR, VAL, ORD)
/* bool __atomic_compare_exchange_n (type *ptr, type *expected, type desired, bool weak, int success_memorder, int failure_memorder) */
#define nvwal_atomic_compare_exchange_weak(PTR, VAL, DES)\
__atomic_compare_exchange_n(PTR, VAL, DES, 1, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)
#define nvwal_atomic_compare_exchange_weak_explicit(PTR, VAL, DES, SUCC_ORD, FAIL_ORD)\
__atomic_compare_exchange_n(PTR, VAL, DES, 1, SUCC_ORD, FAIL_ORD)
#define nvwal_atomic_compare_exchange_strong(PTR, VAL, DES)\
__atomic_compare_exchange_n(PTR, VAL, DES, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)
#define nvwal_atomic_compare_exchange_strong_explicit(PTR, VAL, DES, SUCC_ORD, FAIL_ORD)\
__atomic_compare_exchange_n(PTR, VAL, DES, ORD, 0, SUCC_ORD, FAIL_ORD)
#define nvwal_atomic_fetch_add(PTR, VAL) __atomic_fetch_add(PTR, VAL, __ATOMIC_SEQ_CST)
#define nvwal_atomic_fetch_add_explicit(PTR, VAL, ORD)\
__atomic_fetch_add(PTR, VAL, ORD)
#define nvwal_atomic_fetch_sub(PTR, VAL) __atomic_fetch_sub(PTR, VAL, __ATOMIC_SEQ_CST)
#define nvwal_atomic_fetch_sub_explicit(PTR, VAL, ORD)\
__atomic_fetch_sub(PTR, VAL, ORD)
#define nvwal_atomic_fetch_or(PTR, VAL) __atomic_fetch_or(PTR, VAL, __ATOMIC_SEQ_CST)
#define nvwal_atomic_fetch_or_explicit(PTR, VAL, ORD)\
__atomic_fetch_or(PTR, VAL, ORD)
#define nvwal_atomic_fetch_xor(PTR, VAL) atomic_fetch_xor(PTR, VAL, __ATOMIC_SEQ_CST)
#define nvwal_atomic_fetch_xor_explicit(PTR, VAL, ORD)\
__atomic_fetch_xor(PTR, VAL, ORD)
#define nvwal_atomic_fetch_and(PTR, VAL) atomic_fetch_and(PTR, VAL, __ATOMIC_SEQ_CST)
#define nvwal_atomic_fetch_and_explicit(PTR, VAL, ORD)\
__atomic_fetch_and(PTR, VAL, ORD)
#define nvwal_atomic_thread_fence(ORD) __atomic_thread_fence(ORD)
#else /* __STDC_NO_ATOMICS__ */
/* We have stdatomic.h! This case is trivial */
#include <stdatomic.h>
typedef enum {
nvwal_memory_order_relaxed = memory_order_relaxed,
nvwal_memory_order_consume = memory_order_consume,
nvwal_memory_order_acquire = memory_order_acquire,
nvwal_memory_order_release = memory_order_release,
nvwal_memory_order_acq_rel = memory_order_acq_rel,
nvwal_memory_order_seq_cst = memory_order_seq_cst,
} nvwal_memory_order;
#define nvwal_atomic_init(PTR, VAL) atomic_init(PTR, VAL)
#define nvwal_atomic_store(PTR, VAL) atomic_store(PTR, VAL)
#define nvwal_atomic_store_explicit(PTR, VAL, ORD)\
atomic_store_explicit(PTR, VAL, ORD)
#define nvwal_atomic_load(PTR) atomic_load(PTR)
#define nvwal_atomic_load_explicit(PTR, ORD)\
atomic_load_explicit(PTR, ORD)
#define nvwal_atomic_exchange(PTR, VAL) atomic_exchange(PTR, VAL)
#define nvwal_atomic_exchange_explicit(PTR, VAL, ORD)\
atomic_exchange_explicit(PTR, VAL, ORD)
#define nvwal_atomic_compare_exchange_weak(PTR, VAL, DES)\
atomic_compare_exchange_weak(PTR, VAL, DES)
#define nvwal_atomic_compare_exchange_weak_explicit(PTR, VAL, DES, SUCC_ORD, FAIL_ORD)\
atomic_compare_exchange_weak_explicit(PTR, VAL, DES, SUCC_ORD, FAIL_ORD)
#define nvwal_atomic_compare_exchange_strong(PTR, VAL, DES)\
atomic_compare_exchange_strong(PTR, VAL, DES)
#define nvwal_atomic_compare_exchange_strong_explicit(PTR, VAL, DES, SUCC_ORD, FAIL_ORD)\
atomic_compare_exchange_strong_explicit(PTR, VAL, DES, SUCC_ORD, FAIL_ORD)
#define nvwal_atomic_fetch_add(PTR, VAL) atomic_fetch_add(PTR, VAL)
#define nvwal_atomic_fetch_add_explicit(PTR, VAL, ORD)\
atomic_fetch_add_explicit(PTR, VAL, ORD)
#define nvwal_atomic_fetch_sub(PTR, VAL) atomic_fetch_sub(PTR, VAL)
#define nvwal_atomic_fetch_sub_explicit(PTR, VAL, ORD)\
atomic_fetch_sub_explicit(PTR, VAL, ORD)
#define nvwal_atomic_fetch_or(PTR, VAL) atomic_fetch_or(PTR, VAL)
#define nvwal_atomic_fetch_or_explicit(PTR, VAL, ORD)\
atomic_fetch_or_explicit(PTR, VAL, ORD)
#define nvwal_atomic_fetch_xor(PTR, VAL) atomic_fetch_xor(PTR, VAL)
#define nvwal_atomic_fetch_xor_explicit(PTR, VAL, ORD)\
atomic_fetch_xor_explicit(PTR, VAL, ORD)
#define nvwal_atomic_fetch_and(PTR, VAL) atomic_fetch_and(PTR, VAL)
#define nvwal_atomic_fetch_and_explicit(PTR, VAL, ORD)\
atomic_fetch_and_explicit(PTR, VAL, ORD)
#define nvwal_atomic_thread_fence(ORD) atomic_thread_fence(ORD)
#endif /* __STDC_NO_ATOMICS__ */
/** And a few, implementation-agnostic shorthand. */
#define nvwal_atomic_load_acquire(PTR)\
nvwal_atomic_load_explicit(PTR, nvwal_memory_order_acquire)
#define nvwal_atomic_load_consume(PTR)\
nvwal_atomic_load_explicit(PTR, nvwal_memory_order_consume)
#define nvwal_atomic_store_release(PTR, VAL)\
nvwal_atomic_store_explicit(PTR, VAL, nvwal_memory_order_release)
/** @} */
#endif /* NVWAL_ATOMICS_H_ */
| C | CL | 737b7334afd6f779efe09903851ffc3b477ca00df109a3a1385d08a0ee8dc128 |
/*
* Copyright 2012-15 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: AMD
*
*/
#include "dm_services.h"
#define DIVIDER 10000
/* S2D13 value in [-3.00...0.9999] */
#define S2D13_MIN (-3 * DIVIDER)
#define S2D13_MAX (3 * DIVIDER)
uint16_t fixed_point_to_int_frac(
struct fixed31_32 arg,
uint8_t integer_bits,
uint8_t fractional_bits)
{
int32_t numerator;
int32_t divisor = 1 << fractional_bits;
uint16_t result;
uint16_t d = (uint16_t)dc_fixpt_floor(
dc_fixpt_abs(
arg));
if (d <= (uint16_t)(1 << integer_bits) - (1 / (uint16_t)divisor))
numerator = (uint16_t)dc_fixpt_round(
dc_fixpt_mul_int(
arg,
divisor));
else {
numerator = dc_fixpt_floor(
dc_fixpt_sub(
dc_fixpt_from_int(
1LL << integer_bits),
dc_fixpt_recip(
dc_fixpt_from_int(
divisor))));
}
if (numerator >= 0)
result = (uint16_t)numerator;
else
result = (uint16_t)(
(1 << (integer_bits + fractional_bits + 1)) + numerator);
if ((result != 0) && dc_fixpt_lt(
arg, dc_fixpt_zero))
result |= 1 << (integer_bits + fractional_bits);
return result;
}
/**
* convert_float_matrix
* This converts a double into HW register spec defined format S2D13.
* @param :
* @return None
*/
void convert_float_matrix(
uint16_t *matrix,
struct fixed31_32 *flt,
uint32_t buffer_size)
{
const struct fixed31_32 min_2_13 =
dc_fixpt_from_fraction(S2D13_MIN, DIVIDER);
const struct fixed31_32 max_2_13 =
dc_fixpt_from_fraction(S2D13_MAX, DIVIDER);
uint32_t i;
for (i = 0; i < buffer_size; ++i) {
uint32_t reg_value =
fixed_point_to_int_frac(
dc_fixpt_clamp(
flt[i],
min_2_13,
max_2_13),
2,
13);
matrix[i] = (uint16_t)reg_value;
}
}
| C | CL | b0d428b310832e5952b71632f3e1b1f44891f98fb050a2f4d3cbc2bb093432f6 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct fwdarg {char* arg; int ispath; } ;
/* Variables and functions */
int /*<<< orphan*/ memmove (char*,char*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ strlen (char*) ;
__attribute__((used)) static int
parse_fwd_field(char **p, struct fwdarg *fwd)
{
char *ep, *cp = *p;
int ispath = 0;
if (*cp == '\0') {
*p = NULL;
return -1; /* end of string */
}
/*
* A field escaped with square brackets is used literally.
* XXX - allow ']' to be escaped via backslash?
*/
if (*cp == '[') {
/* find matching ']' */
for (ep = cp + 1; *ep != ']' && *ep != '\0'; ep++) {
if (*ep == '/')
ispath = 1;
}
/* no matching ']' or not at end of field. */
if (ep[0] != ']' || (ep[1] != ':' && ep[1] != '\0'))
return -1;
/* NUL terminate the field and advance p past the colon */
*ep++ = '\0';
if (*ep != '\0')
*ep++ = '\0';
fwd->arg = cp + 1;
fwd->ispath = ispath;
*p = ep;
return 0;
}
for (cp = *p; *cp != '\0'; cp++) {
switch (*cp) {
case '\\':
memmove(cp, cp + 1, strlen(cp + 1) + 1);
if (*cp == '\0')
return -1;
break;
case '/':
ispath = 1;
break;
case ':':
*cp++ = '\0';
goto done;
}
}
done:
fwd->arg = *p;
fwd->ispath = ispath;
*p = cp;
return 0;
} | C | CL | 730dcc2e017391fd134efab274f39a430def9ba381e1bf116becb9884637d257 |
#include <stdio.h>
#include <math.h>
/* define struct of type complex
* contains real and imaginary parts, of type double
*/
typedef struct complex_t
{
double Re;
double Im;
} complex;
// function h1(t) of type complex
complex h1(double t_k)
{
complex h;
h.Re = cos(t_k) + cos(5*(t_k)); //real part of h1
h.Im = sin(t_k) + sin(5*(t_k)); //imaginary part of h1
return h;
}
// function h2(t) of type complex
complex h2(double t_k)
{
complex h;
h.Re = exp(-(t_k - M_PI) * (t_k - M_PI) / 2); //real part of h2
h.Im = 0.0; //imaginary part of h2
return h;
}
// exponential used in discrete fourier transform
complex e(int n, int k, int N)
{
complex e;
e.Re = cos(2 * M_PI * n * k / N); //real part of exponential
e.Im = -sin(2 * M_PI * n * k / N); //imaginary part of exponential
return e;
}
// sampling function
void sample(complex (*p_func)(double), complex *p_array, int funcNumber, int N)
{
int k; // summation integer
double t_k; // t_k = (k * T) / N
complex h;
FILE *fp; // file pointer
// create text file h.txt and open for writing
fp = fopen("./DataFiles/h.txt", "w");
/* sample h(t) function N times from k = 0 to k = N - 1
* N is number of sample values
*/
for(k = 0; k < N; k++)
{
t_k = k * 2 * M_PI / N; // define t_k
h = p_func(t_k); // set complex h to function pointer
// print real and imaginary parts of h, and t_k, to file
fprintf(fp, "%.2f, ", h.Re);
fprintf(fp, "%.2f, ", h.Im);
fprintf(fp, "%.2f\n", t_k);
// assign same real and imaginary parts of h to arrays for use in DFT
(*(p_array + k)).Re = h.Re;
(*(p_array + k)).Im = h.Im;
}
fclose(fp); // close h.txt
// if h(t) is h1(t), rename file to h1.txt
if(funcNumber == 1)
{
rename("./DataFiles/h.txt", "./DataFiles/h1.txt");
}
// if h(t) is h2(t), rename file to h2.txt
if(funcNumber == 2)
{
rename("./DataFiles/h.txt", "./DataFiles/h2.txt");
}
}
// function to load in h3(t) data
void load_h3(complex *p_array)
{
int N = 200; // N, number of samples
FILE *fp; // file pointer
int k_[N]; // define 2 local arrays for k and t_k to read in data from file
double t_k_[N];
fp = fopen("./DataFiles/h3.txt", "r"); //open h3.txt for reading
// loop through all lines of the file
for(int j = 0; j < N; j++)
{
// scan each line of the text file into the ith element of the arrays, delimiter ", "
fscanf(fp, "%d, %lf, %lf, %lf", &k_[j], &t_k_[j], &(*(p_array + j)).Re, &(*(p_array + j)).Im);
}
// pointers are used to save Re & Im to arrays in main
}
// discrete fourier transform (DFT) function
void dft(complex *p_array1, complex (*p_exp)(int, int, int), complex *p_array2, int funcNumber, int N)
{
double t_k, w_n; // t_k & w_n for use in functions, for time and frequency
complex e, H; // local variables of type complex. H is DFT of h
for(int n = 0; n < N; n++) // loop n from n = 0 to n = N - 1
{
for(int k = 0; k < N; k++) // for each n value, sum up values over all k from k = 0 to k = N - 1
{
t_k = k * 2 * M_PI / N;
// set complex e equal to the pointer to the exponential function
e = p_exp(n, k, N);
H.Re = H.Re + ((*(p_array1 + k)).Re * e.Re) - ((*(p_array1 + k)).Im * e.Im); // Im * Im = Re (i^2 = -1)
H.Im = H.Im + ((*(p_array1 + k)).Re * e.Im) + ((*(p_array1 + k)).Im * e.Re);
} // use pointers to arrays from sample function to apply DFT and sum up over all k values
//once k = N - 1 reached, save Re and Im part of H to output arrays in main, using pointers
(*(p_array2 + n)).Re = H.Re;
(*(p_array2 + n)).Im = H.Im;
H.Re = 0; H.Im = 0; // reset Re & Im parts of H to zero for next n value
// if function called is h1(t) or h2(t)
if(funcNumber == 1 || funcNumber == 2)
{
w_n = n * 2 * M_PI / N;
printf("For w%d = %.2f, H%d(w) = %.2f + i%.2f\n", n, w_n, n, (*(p_array2 + n)).Re, (*(p_array2 + n)).Im);
} // print values of w and H(w) to the screen for all n values
}
}
// inverse discrete fourier transform (IDFT) function
void idft(complex(*p_exp)(int, int, int), complex *p_array, int funcNumber, int skipValue, int N)
{
double t_k;
complex e, h_; // h_ (h') is the IDFT of H
complex max_H[200] = {0}; // local array to save 4 values of H_3 with largest amplitude for use in IDFT
FILE *fp;
fp = fopen("./DataFiles/h_.txt", "w"); // create file h_.txt and open for writing
if(funcNumber == 3) // if function called is h3(t)
{
int maxn; // maximum n
double amp;
double maxAmp = 0; // initially set max amplitude value to zero
// loop m to find the 4 values of largest amplitude
for(int m = 0; m < 4; m++)
{
// for each m value, cycle through every element of array produced in DFT function
for(int n = 0; n < N; n++)
{
//calculate amplitude for each element of array by square rooting sum of Re part squared and Im part squared
amp = sqrt(((*(p_array + n)).Re * (*(p_array + n)).Re) + ((*(p_array + n)).Im * (*(p_array + n)).Im));
// updates max n and max amplitude if larger than current stored value
if(amp > maxAmp)
{
maxAmp = amp;
maxn = n;
}
}
// save Re & Im part of nth element of array to local array
max_H[maxn].Re = (*(p_array + maxn)).Re;
max_H[maxn].Im = (*(p_array + maxn)).Im;
// set nth element to zero after saving to new array so that this value is not found on next cycle through array
(*(p_array + maxn)).Re = 0;
(*(p_array + maxn)).Im = 0;
maxAmp = 0;
maxn = 0;
}
}
for(int k = 0; k < N; k++)
{
if(funcNumber == 3) // if function called is h3(t)
{
/* use new local max H array with 4 values of greatest amplitude, and all other values zero,
* to apply IDFT & sum up over all n values
*/
for(int n = 0; n < N; n++)
{
// set complex e equal to pointer to exponential function
e = p_exp(n, k, N);
h_.Re = h_.Re + (max_H[n].Re * e.Re) + (max_H[n].Im * e.Im);
h_.Im = h_.Im - (max_H[n].Re * e.Im) + (max_H[n].Im * e.Re);
}
}
else // if function called is h1(t) or h2(t)
{
for(int n = 0; n < N; n++)
{
e = p_exp(n, k, N);
if(n == skipValue) // if n value equals the skip value
{
continue; // increment n value to n value after skip value, & return to condition part of for loop
}
h_.Re = h_.Re + ((*(p_array + n)).Re * e.Re) + ((*(p_array + n)).Im * e.Im);
h_.Im = h_.Im - ((*(p_array + n)).Re * e.Im) + ((*(p_array + n)).Im * e.Re);
}
// use pointers to arrays from DFT function to apply IDFT & sum up over all n values
}
// once all n or m values have been summed up, divide Re & Im parts by N
h_.Re = h_.Re / N;
h_.Im = h_.Im / N;
t_k = k * 2 * M_PI / N;
// print Re & Im parts of h'(t), & t_k to file
fprintf(fp, "%.2f, ", h_.Re);
fprintf(fp, "%.2f, ", h_.Im);
fprintf(fp, "%.2f\n", t_k);
h_.Re = 0; h_.Im = 0;
}
fclose(fp);
if(funcNumber == 1)
{
rename("./DataFiles/h_.txt", "./DataFiles/h1_.txt"); // if h'(t) is h1'(t), rename file to h1_.txt
}
if(funcNumber == 2)
{
rename("./DataFiles/h_.txt", "./DataFiles/h2_.txt"); // if h'(t) is h2'(t), rename file to h2_.txt
}
if(funcNumber == 3)
{
rename("./DataFiles/h_.txt", "./DataFiles/h3_.txt"); // if h'(t) is h3'(t), rename file to h3_.txt
}
}
int main()
{
int N = 100; // number of samples
// complex function pointers to h1(t), h2(t) and exponential function
complex (*p_h1_func)(double);
complex (*p_h2_func)(double);
complex (*p_e_func)(int, int, int);
// set address the pointers point to, as the address of the functions
p_h1_func = &h1;
p_h2_func = &h2;
p_e_func = &e;
// define complex arrays for use in sampling & DFT functions
complex h1_n[N], h2_n[N];
// define complex arrays for use in DFT & IDFT function
complex H1_n[N], H2_n[N];
//define complex pointers for the 4 arrays
complex *p_h1;
complex *p_h2;
complex *p_H1;
complex *p_H2;
/* set address the pointers point to as the address of the arrays
* the pointer points to the first element in the array
*/
p_h1 = h1_n;
p_h2 = h2_n;
p_H1 = H1_n;
p_H2 = H2_n;
// sampling h1
sample(p_h1_func, p_h1, 1, N);
// sampling h2
sample(p_h2_func, p_h2, 2, N);
// discrete fourier transform of h1
printf("For the first function:\n");
dft(p_h1, p_e_func, p_H1, 1, N);
printf("\n");
// discrete fourier transform of h2
printf("For the second function:\n");
dft(p_h2, p_e_func, p_H2, 2, N);
// inverse discrete fourier transform of H1
idft(p_e_func, p_H1, 1, 1, N);
// inverse discrete fourier transform of H2
idft(p_e_func, p_H2, 2, 0, N);
N = 200; // set number of samples to 200
complex h3_n[N]; // complex array for use in sampling & DFT functions
complex H3_n[N]; // complex arrays for use in DFT & IDFT function
complex *p_h3; // complex pointers for the 2 arrays
complex *p_H3;
p_h3 = h3_n; // set address the pointers point to as the address of the arrays
p_H3 = H3_n;
// load h3 data
load_h3(p_h3);
// discrete fourier transform of h3
dft(p_h3, p_e_func, p_H3, 3, N);
// inverse discrete fourier transform of H3
idft(p_e_func, p_H3, 3, 0, N);
return 0;
}
| C | CL | 3d2ce1f13a390883aeecdb231898583dc62341f8bb096e674a6dad9144da0032 |
#ifndef _TUTORIAL1_QUESTION7_H
#define _TUTORIAL1_QUESTION7_H
__global__ void kernelQuestion7(
double S0,
double r,
double T,
double sigma,
double K,
int n,
double *d_Z,
double *d_out,
int M,
double *d_sumsq)
{
int thdsPerBlk = blockDim.x; // Number of threads per block
int tidxKernel = blockIdx.x*thdsPerBlk + threadIdx.x;
int totalThds = thdsPerBlk*gridDim.x;
extern __shared__ double partials[];
double sum = 0.0;
double sumsq = 0.0;
double sqT = sqrt(T);
if(blockIdx.x < M) {
for(int zIdx=tidxKernel; zIdx<n; zIdx+=totalThds) {
double ST = S0*exp( (r-0.5*sigma*sigma)*T + sigma*sqT*d_Z[zIdx] );
double x = (ST>K ? ST-K : 0.0);
x = exp(-r*T)*x;
sum += x;
sumsq += x*x;
}
} else {
for(int zIdx=tidxKernel; zIdx<n; zIdx+=totalThds) {
double ST = S0*exp( (r-0.5*sigma*sigma)*T + sigma*sqT*d_Z[zIdx] );
double x = (ST>K ? ST-K : 0.0);
x = exp(-r*T)*x;
sum += x;
}
}
partials[threadIdx.x] = sum;
__syncthreads();
if(threadIdx.x == 0) {
sum = 0.0;
for(int i=0; i<thdsPerBlk; i++) {
sum += partials[i];
}
d_out[blockIdx.x] = sum;
}
// Hold the other threads so that thread0 can do sum
__syncthreads();
// Now write sum of squares
partials[threadIdx.x] = sumsq;
__syncthreads();
if(blockIdx.x < M && threadIdx.x == 0) {
sum = 0.0;
for(int i=0; i<thdsPerBlk; i++) {
sum += partials[i];
}
d_sumsq[blockIdx.x] = sum;
}
}
void question7()
{
cout << endl;
cout << "Tutorial 1, Question 7" << endl;
int n = 100000000;
int nthds = 672;
int nblks = 140;
int M = 35;
double
r = 0.02,
T = 1.0,
sigma = 0.09,
K = 100.0,
S0 = 100.0;
double *d_Z = NULL;
double *d_out = NULL;
double *d_sumsq = NULL;
check( cudaMalloc((void**)&d_Z, sizeof(double)*n) );
check( cudaMalloc((void**)&d_out, sizeof(double)*nblks) );
check( cudaMalloc((void**)&d_sumsq, sizeof(double)*nblks) );
generateRandomNumbers(n, d_Z);
kernelQuestion7<<<nblks, nthds, sizeof(double)*nthds>>>(S0, r, T, sigma, K, n, d_Z, d_out, M, d_sumsq);
check( cudaGetLastError() );
double *out = new double[nblks];
double * sumsq = new double[M];
check( cudaMemcpy(out, d_out, sizeof(double)*nblks, cudaMemcpyDeviceToHost) );
check( cudaMemcpy(sumsq, d_sumsq, sizeof(double)*M, cudaMemcpyDeviceToHost) );
double sum = 0.0;
for(int i=0; i<nblks; i++) {
sum += out[i];
}
double mcEst = sum/n;
cout << "average=" << mcEst << endl;
cout << endl;
sum = 0.0;
double sq = 0.0;
for(int i=0; i<M; i++) {
sum += out[i];
sq += sumsq[i];
}
// Number of loops that all blocks will do (note: round down)
int nloops = n/(nthds*nblks);
// Remainder of points to be cleaned up on final loop
int rem = n%(nthds*nblks);
// Number of points read by first M thread blocks
int points = M*nthds*nloops + min(rem,M*nthds);
double ave = sum/points;
double variance = sq/points - ave*ave;
double stdev = sqrt(variance);
cout << "Sum of first M blocks=" << sum << endl;
cout << "Sum of squares of first M blocks=" << sq << endl;
cout << "Variance of first M blocks=" << variance << endl;
cout << " 99% Confidence interval is (" << mcEst - 3.0*stdev/sqrt((double)n) << ", " << mcEst + 3.0*stdev/sqrt((double)n) << ")" << endl;
cout << " Width of interval is " << 6.0*stdev/sqrt((double)n) << endl << endl;
check( cudaFree(d_Z) );
check( cudaFree(d_out) );
check( cudaFree(d_sumsq) );
delete[] sumsq;
delete[] out;
}
#endif
| C | CL | 0b35df8945ddb2fdebebd59fd426bdbbac513e2ce9283dab33233ed3eeda7271 |
/*
Projet : ELE216 - Laboratoire 1
Date : 15 fevrier 2021
Par : Gabriel Gandubert et Hugo Cusson-Bouthillier
Definition : Encapsulation du type d'operation et des criteres recu par le
programme principal.
Contient:
Structure des operations qui permet de combiner les types de criteres (commandes)
et le type d'operation.
La structure est defini ici, mais le "typedef" est dans le module client.h.
FONCTIONS PUBLIQUES :
operation_creer : Creation d'une structure des operations.
operation_liberer : Liberation d'une strcuture des operations.
operation_get_critere_i : Lecture d'un critere specifique de la
structure interne.
operation_get_critere : Lecture de la structure des criteres.
operation_get_taille_crit : Lecture du nombre d'element pour un critere
specifique.
operation_get_t : Lecture de l'element T de la structure des
operations.
operation_get_type_titre : Lecture de l'element type_tire de la structure
des operations.
operation_set_t : Modificateur de l'element T de la structure
des operations.
operation_set_critere : Modificateur de la structure des criteres
de la structure des operations.
operation_set_type_titre : Modificateur de l'element type_titre de la
structures des operations.
serialiser_operation : Transformation de la structure des operations
en chaine de caractere pour la communication.
deserialiser_operation : Transformation de la chaine de caractere
serialisee en structure des operations.
*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
// Header file
#include "client.h"
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* TYPES ET STRUCTURES OPAQUES */
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/**
* @brief : Structure de donnees permettant de contenir l'operation et les criteres
* recu dans le programme principal.
* @note : HLR04 Structure des operations contenant la strucutre des criteres,
l'operation choisi et le type de titre pour l'ajout.
*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* IMPLLEMENTATION FONCTIONS PUBLIQUES */
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
// Creation d'une structure pour l'operation exigee. Par defaut: mode recherche.
pt_operation operation_creer(void)
{
// on utilise calloc pour avoir 1 espace contigu de taille de la struct tout a 0
// s'il plante il va renvoyer NULL par lui meme
return (pt_operation) calloc(1, sizeof(struct operation));
}
//----------------------------------------------------------------------------------------
// Liberation de la structure de l'operation exigee ainsi que le(s) critere(s) contenu(s).
extern void operation_liberer(void* oper)
{
pt_operation op=oper;
// Si la structure est valide, liberer.
if(op != NULL)
{
// Si les criteres sont valides, liberer.
if(op->critere != NULL)
{
critere_liberer(op->critere);
}
free(op);
op = NULL;
}
}
//----------------------------------------------------------------------------------------
// Retourne un element de la structure des criteres.
const char* operation_get_critere_i(pt_operation oper, t_tag_critere tag, unsigned int i)
{
if(oper != NULL)
{
return critere_get_element_i(oper->critere, tag, i);
}
return NULL;
}
//----------------------------------------------------------------------------------------
/*
* Retourne le pointeur des criteres. Si l'une des deux structure n'est pas initialisee,
* La fonction retourne un pointeur NULL.
*/
const pt_critere operation_get_critere(pt_operation oper)
{
/*
* Retourner le critere si la structure d'operation existe.
* Il est possible que la structure des criteres soit nul.
*/
if(oper != NULL)
{
return oper->critere;
}
return NULL;
}
//----------------------------------------------------------------------------------------
// Retourne la taille du premier tableau du critere selectionnee.
unsigned int operation_get_taille_crit(pt_operation const oper, t_tag_critere tag)
{
if(oper != NULL && tag)
{
return critere_get_taille(tag, oper->critere);
}
return 0;
}
//----------------------------------------------------------------------------------------
/*
* Retourne le type d'operation voulu dans la structure.
* si la structure n'existe pas, la fonction retourne 0.
*/
const type_alias operation_get_t(pt_operation oper)
{
if(oper != NULL)
{
return (const type_alias) oper->T;
}
return (const type_alias) EMPTY_ARGUMENT;
}
//----------------------------------------------------------------------------------------
// Retroune le type de titre de la structure.
const char* operation_get_type_titre(pt_operation oper)
{
if(oper != NULL)
{
return (const char*) critere_get_type_titre(oper->critere);
}
return NULL;
}
//----------------------------------------------------------------------------------------
// Changement du type d'operation de la structure des operations.
unsigned int operation_set_t(pt_operation oper, type_alias T)
{
// Verification de l'existance de la structure d'operation.
if(oper != NULL)
{
// Verification du type de recherche attendu.
if(T == RECHERCHE || T == RETRAIT|| T == AJOUT)
{
oper->T = T;
return OPERATION_SUCCESS;
}
// Argument null ou incorrect seront traitees de la meme facon.
else
{
return EMPTY_ARGUMENT;
}
}
return EMPTY_POINTER;
}
//----------------------------------------------------------------------------------------
// Changement des criteres de la structure des operations.
unsigned int operation_set_critere(pt_operation oper, pt_critere critere)
{
// Verification de l'existance de la structure d'operation.
if(oper != NULL)
{
if(critere == NULL)
{
return EMPTY_ARGUMENT;
}
// Verification si la structure de critere est deja present.
if(oper->critere == NULL)
{
oper->critere = critere;
return OPERATION_SUCCESS;
}
// Si la structure existe, modifier le contenu.
else
{
critere_liberer(oper->critere);
oper->critere = critere;
return OPERATION_SUCCESS;
}
}
return EMPTY_POINTER;
}
//----------------------------------------------------------------------------------------
// Changement du type de titre de la structure des operations.
unsigned int operation_set_type_titre(pt_operation oper, char* type_titre)
{
// Verification de l'existance de la structure d'operation.
if(oper == NULL)
return EMPTY_POINTER;
// Verification de l'existance du type de titre.
if(type_titre == NULL)
{
return EMPTY_ARGUMENT;
}
// Verification si la structure de critere est deja present.
if( oper->critere == NULL ){
return EMPTY_POINTER;
}
return (
critere_set_type_titre(oper->critere,type_titre)==TRUE
? OPERATION_SUCCESS
: EMPTY_POINTER
);
}
//----------------------------------------------------------------------------------------
// Serialisation de la structure des operations.
str serialiser_operation(pt_operation oper)
{
str buf =NULL; // chaine de caractere tampon pour la sortie.
str buf2 =NULL;
BOOL success =TRUE; // Variable BOOLeen pour indiquation de reussite.
char type_operation[2] = "\0"; // Tableau pour ajouter le type d'operation.
if(!oper)
return NULL;
if(!(buf=critere_serialiser(oper->critere)))
return NULL;
if(!(buf2=calloc(strlen(buf)+2,sizeof(char)))){
free(buf);
return NULL;
}
strcpy(buf2+1,buf);
*buf2=oper->T;
free(buf);
return buf2;
}
//----------------------------------------------------------------------------------------
// Deserialisation d'une chaine de caracteres en une structure des operations.
pt_operation deserialiser_operation(cstr serie){
pt_operation oper = operation_creer(); // Structure des operations a retourner
char type_titre[2] = {0,0};
// Validation des parametres et des allocations dynamiques.
if(!serie || !oper){
return NULL;
}
*type_titre=(oper->T=*serie);
oper->critere=critere_deserialiser(serie+1);
if(!oper->critere)
free(oper);
critere_set_type_titre(oper->critere,type_titre);
return oper;
}
//----------------------------------------------------------------------------------------
| C | CL | f8ffe007842f87ef19c24195683e633764eae96e7ad634276bb5d91e04628950 |
/* $Id$ */
/* Copyright (c) 2011-2022 Pierre Pronchery <[email protected]> */
/* This file is part of DeforaOS Desktop Locker */
/* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY ITS AUTHORS 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 AUTHORS 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 <unistd.h>
#include <stdio.h>
#include <locale.h>
#include <libintl.h>
#include <gtk/gtk.h>
#include "locker.h"
#include "../config.h"
#define _(string) gettext(string)
/* constants */
#ifndef PREFIX
# define PREFIX "/usr/local"
#endif
#ifndef DATADIR
# define DATADIR PREFIX "/share"
#endif
#ifndef LOCALEDIR
# define LOCALEDIR DATADIR "/locale"
#endif
#ifndef PROGNAME_LOCKER
# define PROGNAME_LOCKER "locker"
#endif
/* locker */
/* private */
/* prototypes */
static int _error(char const * message, int ret);
static int _usage(void);
/* functions */
/* error */
static int _error(char const * message, int ret)
{
fputs(PROGNAME_LOCKER ": ", stderr);
perror(message);
return ret;
}
/* usage */
static int _usage(void)
{
fprintf(stderr, _("Usage: %s [-d demo][-p plug-in]\n"
" -d Demo sub-system to load\n"
" -p Authentication plug-in to load\n"), PROGNAME_LOCKER);
return 1;
}
/* public */
/* functions */
/* main */
int main(int argc, char * argv[])
{
int o;
char const * demo = NULL;
char const * auth = NULL;
Locker * locker;
if(setlocale(LC_ALL, "") == NULL)
_error("setlocale", 1);
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
gtk_init(&argc, &argv);
while((o = getopt(argc, argv, "d:p:")) != -1)
switch(o)
{
case 'd':
demo = optarg;
break;
case 'p':
auth = optarg;
break;
default:
return _usage();
}
if(optind != argc)
return _usage();
if((locker = locker_new(demo, auth)) == NULL)
return 2;
gtk_main();
locker_delete(locker);
return 0;
}
| C | CL | b9f266846774b3b7424199f6e8110389eb7871a0abdf12985ea8044fe0e7f128 |
#include <QApplication>
#include "RayApp.H"
#include "RayCanvas.H"
#include <MyRayCanvas.H>
#include <TAIntersectCanvas.H>
#include <TARayCanvas.H>
#include <TASceneviewCanvas.H>
#include <string.h>
/* This is the entry point to your application. You should add
* functionality to parse command line parameters to control your
* render settings
*/
int main(int argc, char** argv) {
QApplication qApplication(argc, argv);
RayApp app;
/* Default width and height */
int width = 500;
int height = 500;
/* Default scene to render
* When you get started, you should probably change to a much simpler scene
*/
const char* scene = "/course/cs123/data/scenes/ray/sphere_texture_test.xml";
/* Start up a sceneview canvas to preview the scene quickly before
* rendering. Feel free to replace this with your implementation of
* sceneview.
*/
TASceneviewCanvas taSceneviewCanvas(width, height);
taSceneviewCanvas.enableMarquee();
app.addCanvas(&taSceneviewCanvas, "GL Preview");
/* Starts up an intersect canvas - this is an implementation of the basic
* ray tracing algorithm
*/
TAIntersectCanvas taCanvas(width, height);
app.addCanvas(&taCanvas, "Intersect Demo");
MyRayCanvas myRayCanvas(width, height);
app.addCanvas(&myRayCanvas, "My Ray");
/* Starts up a TASceneviewCanvas with default width 500 and height 500
* Here are two examples on how to set render settings. You can find the
* the possible setting options in RayCanvas.H */
TARayCanvas taRayCanvas(width, height);
taRayCanvas.setRenderSetting(RAY_OPTION_RECURSION_DEPTH, 6);
taRayCanvas.setRenderSetting(RAY_OPTION_SUPERSAMPLING, 3);
app.addCanvas(&taRayCanvas, "Ray Demo");
/* Load scene in each canvas */
taSceneviewCanvas.loadScene(scene);
taCanvas.loadScene(scene);
myRayCanvas.loadScene(scene);
taRayCanvas.loadScene(scene);
/* Start up your Canvas and add it to the app. */
return qApplication.exec();
}
| C | CL | c558c7dd172190f11089e90d0919fe9021102b0665d161bd07322575d4a697e3 |
/*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE 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 ANY
- 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.
*====================================================================*/
/*
* convertfilestopdf.c
*
* Converts all image files in the given directory with matching substring
* to a pdf, with the specified scaling factor <= 1.0 applied to all
* images.
*
* See below for syntax and usage.
*
* The images are displayed at a resolution that depends on the
* input resolution (res) and the scaling factor (scalefact) that
* is applied to the images before conversion to pdf. Internally
* we multiply these, so that the generated pdf will render at the
* same resolution as if it hadn't been scaled. By downscaling, you
* reduce the size of the images.
*
* For jpeg and jp2k, downscaling reduces pdf size by the square of
* the scale factor.
* * The jpeg quality can be specified from 1 (very poor) to 100
* (best available, but still lossy); use 0 for the default (75).
* * The jp2k quality can be specified from 27 (very poor) to 45 (nearly
* lossless; use 0 for the default (34). You can use 100 to
* require lossless, but this is very expensive and not recommended.
*/
#ifdef HAVE_CONFIG_H
#include <config_auto.h>
#endif /* HAVE_CONFIG_H */
#include <string.h>
#include "allheaders.h"
int main(int argc,
char **argv)
{
char *dirin, *substr, *title, *fileout;
l_int32 ret, res, type, quality;
l_float32 scalefactor;
if (argc != 9) {
lept_stderr(
" Syntax: convertfilestopdf dirin substr res"
" scalefactor encoding_type quality title fileout\n"
" dirin: input directory for image files\n"
" substr: Use 'allfiles' to convert all files\n"
" in the directory.\n"
" res: Input resolution of each image;\n"
" assumed to all be the same\n"
" scalefactor: Use to scale all images\n"
" encoding_type:\n"
" L_DEFAULT_ENCODE = 0 (based on the image)\n"
" L_JPEG_ENCODE = 1\n"
" L_G4_ENCODE = 2\n"
" L_FLATE_ENCODE = 3\n"
" L_JP2K_ENCODE = 4\n"
" quality: used for jpeg; 1-100, 0 for default (75);\n"
" used for jp2k: 27-45, 0 for default (34)\n"
" title: Use 'none' to omit\n"
" fileout: Output pdf file\n");
return 1;
}
dirin = argv[1];
substr = argv[2];
res = atoi(argv[3]);
scalefactor = atof(argv[4]);
type = atoi(argv[5]);
quality = atoi(argv[6]);
title = argv[7];
fileout = argv[8];
if (!strcmp(substr, "allfiles"))
substr = NULL;
if (scalefactor <= 0.0 || scalefactor > 2.0) {
L_WARNING("invalid scalefactor: setting to 1.0\n", __func__);
scalefactor = 1.0;
}
if (!strcmp(title, "none"))
title = NULL;
setLeptDebugOK(1);
ret = convertFilesToPdf(dirin, substr, res, scalefactor, type,
quality, title, fileout);
return ret;
}
| C | CL | 1f1edfb6282561f789004d09e733b1a3a4477215e943e2ded14fb9f47b1603f6 |
/*
* Copyright (C) 2003 by Pavel Chromy. All rights reserved.
* Copyright (C) 2001-2006 by egnite Software GmbH. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* 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.
*
* For additional information see http://www.ethernut.de/
* -
*
* This software has been inspired by all the valuable work done by
* Jesper Hansen <[email protected]>. Many thanks for all his help.
*/
/*
* $Log$
* Revision 1.4 2008/08/11 06:59:18 haraldkipp
* BSD types replaced by stdint types (feature request #1282721).
*
* Revision 1.3 2006/05/15 11:46:00 haraldkipp
* Bug corrected, which stopped player on flush. Now flushing plays
* the remaining bytes in the buffer.
* VS1001 ports are now fully configurable.
* Several changes had been added to adapt the code to newer
* Nut/OS style, like replacing outp with outb and using API
* routines for interrupt control.
*
* Revision 1.2 2006/01/23 19:52:10 haraldkipp
* Added required typecasts before left shift.
*
* Revision 1.1 2005/07/26 18:02:40 haraldkipp
* Moved from dev.
*
* Revision 1.3 2004/03/16 16:48:27 haraldkipp
* Added Jan Dubiec's H8/300 port.
*
* Revision 1.2 2003/07/21 18:06:34 haraldkipp
* Buffer function removed. The driver is now using the banked memory routines.
* New functions allows the application to enable/disable decoder interrupts.
*
* Revision 1.1.1.1 2003/05/09 14:40:58 haraldkipp
* Initial using 3.2.1
*
* Revision 1.12 2003/05/06 18:35:21 harald
* ICCAVR port
*
* Revision 1.11 2003/04/21 16:43:54 harald
* Added more comments.
* Avoid initializing static globals to zero.
* New function VsSdiWrite/_P checks DREQ
* Removed decoder interrupt en/disable from low level routines.
* Keep decoder in reset state until ports have been initialized.
* Do not send initial zero bytes as the datasheet recommends.
* A single nop is sufficient delay during reset active.
* Clear interrupt flag after reset to avoid useless interrupt.
* Available buffer size corrected.
* New function to read header information.
* New function invokes decoder memory test.
* Beep makes use of VsSdiWrite.
*
* Revision 1.10 2003/04/18 14:46:08 harald
* Copyright update by the maintainer, after none of the original code had
* been left. We have a clean BSD licence now.
* This release had been prepared by Pavel Chromy.
* BSYNC vs. transfer in progress issue in VsSdiPutByte().
* Fixed possible transfer in progress issue in VsPlayerFeed().
* HW reset may be forced by VS_SM_RESET mode bit
*
* Revision 1.9 2003/04/07 20:29:20 harald
* Redesigned by Pavel Chromy
*
* Revision 1.9 2003/04/04 15:01:00 mac
* VS_STATUS_EMTY is reported correctly.
*
* Revision 1.9 2003/02/14 13:39:00 mac
* Several serious bugs fixed,
* interrupt routine completely remade.
* Unreliable spurious interrupts detection removed.
* Mpeg frame detection removed.
* Watermark check removed (this was rather limiting)
* Can be optionaly compiled not to use SPI
*
* Revision 1.8 2003/02/04 17:50:55 harald
* Version 3 released
*
* Revision 1.7 2003/01/14 16:15:19 harald
* Sending twice the number of zeros to end MP3 stream.
* Check for spurious interrupts to detect hanging chip.
* Simpler portable inline assembler for short delays.
*
* Revision 1.6 2002/11/02 15:15:13 harald
* Library dependencies removed
*
* Revision 1.5 2002/09/15 16:44:14 harald
* *** empty log message ***
*
* Revision 1.4 2002/08/16 17:49:02 harald
* First public release
*
* Revision 1.3 2002/06/26 17:29:08 harald
* First pre-release with 2.4 stack
*
*/
/*
* This header file specifies the hardware port bits. You
* need to change or replace it, if your hardware differs.
*/
#include <cfg/arch/avr.h>
#include <sys/atom.h>
#include <sys/event.h>
#include <sys/timer.h>
#include <sys/heap.h>
#include <dev/irqreg.h>
#include <dev/vs1001k.h>
#include <sys/bankmem.h>
#include <stddef.h> /* NULL definition */
/*!
* \addtogroup xgVs1001
*/
/*@{*/
#ifndef VS_SCK_BIT
/*!
* \brief VS1001 serial control interface clock input bit.
*
* The first rising clock edge after XCS has gone low marks the first
* bit to be written to the decoder.
*/
#define VS_SCK_BIT 0
#endif
#if !defined(VS_SCK_AVRPORT) || (VS_SCK_AVRPORT == AVRPORTB)
#define VS_SCK_PORT PORTB /*!< Port register of \ref VS_SCK_BIT. */
#define VS_SCK_DDR DDRB /*!< Data direction register of \ref VS_SCK_BIT. */
#elif (VS_SCK_AVRPORT == AVRPORTD)
#define VS_SCK_PORT PORTD
#define VS_SCK_DDR DDRD
#elif (VS_SCK_AVRPORT == AVRPORTE)
#define VS_SCK_PORT PORTE
#define VS_SCK_DDR DDRE
#elif (VS_SCK_AVRPORT == AVRPORTF)
#define VS_SCK_PORT PORTF
#define VS_SCK_DDR DDRF
#else
#warning "Bad SCK port specification"
#endif
#ifndef VS_SS_BIT
/*!
* \brief VS1001 serial data interface clock input bit.
*/
#define VS_SS_BIT 1
#endif
#if !defined(VS_SS_AVRPORT) || (VS_SS_AVRPORT == AVRPORTB)
#define VS_SS_PORT PORTB /*!< Port output register of \ref VS_SS_BIT. */
#define VS_SS_DDR DDRB /*!< Data direction register of \ref VS_SS_BIT. */
#elif (VS_SS_AVRPORT == AVRPORTD)
#define VS_SS_PORT PORTD
#define VS_SS_DDR DDRD
#elif (VS_SS_AVRPORT == AVRPORTE)
#define VS_SS_PORT PORTE
#define VS_SS_DDR DDRE
#elif (VS_SS_AVRPORT == AVRPORTF)
#define VS_SS_PORT PORTF
#define VS_SS_DDR DDRF
#else
#warning "Bad SS port specification"
#endif
#ifndef VS_SI_BIT
/*!
* \brief VS1001 serial control interface data input.
*
* The decoder samples this input on the rising edge of SCK if XCS is low.
*/
#define VS_SI_BIT 2
#endif
#if !defined(VS_SI_AVRPORT) || (VS_SI_AVRPORT == AVRPORTB)
#define VS_SI_PORT PORTB /*!< Port output register of \ref VS_SI_BIT. */
#define VS_SI_DDR DDRB /*!< Data direction register of \ref VS_SI_BIT. */
#elif (VS_SI_AVRPORT == AVRPORTD)
#define VS_SI_PORT PORTD
#define VS_SI_DDR DDRD
#elif (VS_SI_AVRPORT == AVRPORTE)
#define VS_SI_PORT PORTE
#define VS_SI_DDR DDRE
#elif (VS_SI_AVRPORT == AVRPORTF)
#define VS_SI_PORT PORTF
#define VS_SI_DDR DDRF
#else
#warning "Bad SI port specification"
#endif
#ifndef VS_SO_BIT
/*!
* \brief VS1001 serial control interface data output.
*
* If data is transfered from the decoder, bits are shifted out on the
* falling SCK edge. If data is transfered to the decoder, SO is at a
* high impedance state.
*/
#define VS_SO_BIT 3
#endif
#if !defined(VS_SO_AVRPORT) || (VS_SO_AVRPORT == AVRPORTB)
#define VS_SO_PIN PINB /*!< Port input register of \ref VS_SO_BIT. */
#define VS_SO_DDR DDRB /*!< Data direction register of \ref VS_SO_BIT. */
#elif (VS_SO_AVRPORT == AVRPORTD)
#define VS_SO_PIN PIND
#define VS_SO_DDR DDRD
#elif (VS_SO_AVRPORT == AVRPORTE)
#define VS_SO_PIN PINE
#define VS_SO_DDR DDRE
#elif (VS_SO_AVRPORT == AVRPORTF)
#define VS_SO_PIN PINF
#define VS_SO_DDR DDRF
#else
#warning "Bad SO port specification"
#endif
#ifndef VS_XCS_BIT
/*!
* \brief VS1001 active low chip select input.
*
* A high level forces the serial interface into standby mode, ending
* the current operation. A high level also forces serial output (SO)
* to high impedance state.
*/
#define VS_XCS_BIT 4
#endif
#if !defined(VS_XCS_AVRPORT) || (VS_XCS_AVRPORT == AVRPORTB)
#define VS_XCS_PORT PORTB /*!< Port output register of \ref VS_XCS_BIT. */
#define VS_XCS_DDR DDRB /*!< Data direction register of \ref VS_XCS_BIT. */
#elif (VS_XCS_AVRPORT == AVRPORTD)
#define VS_XCS_PORT PORTD
#define VS_XCS_DDR DDRD
#elif (VS_XCS_AVRPORT == AVRPORTE)
#define VS_XCS_PORT PORTE
#define VS_XCS_DDR DDRE
#elif (VS_XCS_AVRPORT == AVRPORTF)
#define VS_XCS_PORT PORTF
#define VS_XCS_DDR DDRF
#else
#warning "Bad XCS port specification"
#endif
#ifndef VS_BSYNC_BIT
/*!
* \brief VS1001 serial data interface bit sync.
*
* The first DCLK sampling edge, during which BSYNC is high, marks the
* first bit of a data byte.
*/
#define VS_BSYNC_BIT 5
#endif
#if !defined(VS_BSYNC_AVRPORT) || (VS_BSYNC_AVRPORT == AVRPORTB)
#define VS_BSYNC_PORT PORTB /*!< Port output register of \ref VS_BSYNC_BIT. */
#define VS_BSYNC_DDR DDRB /*!< Data direction register of \ref VS_BSYNC_BIT. */
#elif (VS_BSYNC_AVRPORT == AVRPORTD)
#define VS_BSYNC_PORT PORTD
#define VS_BSYNC_DDR DDRD
#elif (VS_BSYNC_AVRPORT == AVRPORTE)
#define VS_BSYNC_PORT PORTE
#define VS_BSYNC_DDR DDRE
#elif (VS_BSYNC_AVRPORT == AVRPORTF)
#define VS_BSYNC_PORT PORTF
#define VS_BSYNC_DDR DDRF
#else
#warning "Bad BSYNC port specification"
#endif
#ifndef VS_RESET_BIT
/*!
* \brief VS1001 hardware reset input.
*/
#define VS_RESET_BIT 7
#endif
#if !defined(VS_RESET_AVRPORT) || (VS_RESET_AVRPORT == AVRPORTB)
#define VS_RESET_PORT PORTB /*!< Port output register of \ref VS_RESET_BIT. */
#define VS_RESET_DDR DDRB /*!< Data direction register of \ref VS_RESET_BIT. */
#elif (VS_RESET_AVRPORT == AVRPORTD)
#define VS_RESET_PORT PORTD
#define VS_RESET_DDR DDRD
#elif (VS_RESET_AVRPORT == AVRPORTE)
#define VS_RESET_PORT PORTE
#define VS_RESET_DDR DDRE
#elif (VS_RESET_AVRPORT == AVRPORTF)
#define VS_RESET_PORT PORTF
#define VS_RESET_DDR DDRF
#else
#warning "Bad RESET port specification"
#endif
#ifndef VS_SIGNAL_IRQ
/*!
* \brief VS1001 data request interrupt.
*/
#define VS_SIGNAL sig_INTERRUPT6
#define VS_DREQ_BIT 6
#define VS_DREQ_PORT PORTE /*!< Port output register of \ref VS_DREQ_BIT. */
#define VS_DREQ_PIN PINE /*!< Port input register of \ref VS_DREQ_BIT. */
#define VS_DREQ_DDR DDRE /*!< Data direction register of \ref VS_DREQ_BIT. */
#elif (VS_SIGNAL_IRQ == INT0)
#define VS_SIGNAL sig_INTERRUPT0
#define VS_DREQ_BIT 0
#define VS_DREQ_PORT PORTD
#define VS_DREQ_PIN PIND
#define VS_DREQ_DDR DDRD
#elif (VS_SIGNAL_IRQ == INT1)
#define VS_SIGNAL sig_INTERRUPT1
#define VS_DREQ_BIT 1
#define VS_DREQ_PORT PORTD
#define VS_DREQ_PIN PIND
#define VS_DREQ_DDR DDRD
#elif (VS_SIGNAL_IRQ == INT2)
#define VS_SIGNAL sig_INTERRUPT2
#define VS_DREQ_BIT 2
#define VS_DREQ_PORT PORTD
#define VS_DREQ_PIN PIND
#define VS_DREQ_DDR DDRD
#elif (VS_SIGNAL_IRQ == INT3)
#define VS_SIGNAL sig_INTERRUPT3
#define VS_DREQ_BIT 3
#define VS_DREQ_PORT PORTD
#define VS_DREQ_PIN PIND
#define VS_DREQ_DDR DDRD
#elif (VS_SIGNAL_IRQ == INT4)
#define VS_SIGNAL sig_INTERRUPT4
#define VS_DREQ_BIT 4
#define VS_DREQ_PORT PORTE
#define VS_DREQ_PIN PINE
#define VS_DREQ_DDR DDRE
#elif (VS_SIGNAL_IRQ == INT5)
#define VS_SIGNAL sig_INTERRUPT5
#define VS_DREQ_BIT 5
#define VS_DREQ_PORT PORTE
#define VS_DREQ_PIN PINE
#define VS_DREQ_DDR DDRE
#elif (VS_SIGNAL_IRQ == INT7)
#define VS_SIGNAL sig_INTERRUPT7
#define VS_DREQ_BIT 7
#define VS_DREQ_PORT PORTE
#define VS_DREQ_PIN PINE
#define VS_DREQ_DDR DDRE
#else
#warning "Bad interrupt specification"
#endif
static volatile uint8_t vs_status = VS_STATUS_STOPPED;
static volatile uint16_t vs_flush;
/*
* \brief Write a byte to the VS1001 data interface.
*
* The caller is responsible for checking the DREQ line. Also make sure,
* that decoder interrupts are disabled.
*
* \param b Byte to be shifted to the decoder's data interface.
*/
static INLINE void VsSdiPutByte(uint8_t b)
{
#ifdef VS_NOSPI
uint8_t mask = 0x80;
sbi(VS_BSYNC_PORT, VS_BSYNC_BIT);
while (mask) {
if (b & mask)
sbi(VS_SI_PORT, VS_SI_BIT);
else
cbi(VS_SI_PORT, VS_SI_BIT);
sbi(VS_SS_PORT, VS_SS_BIT);
mask >>= 1;
cbi(VS_SS_PORT, VS_SS_BIT);
cbi(VS_BSYNC_PORT, VS_BSYNC_BIT);
}
#else
/* Wait for previous SPI transfer to finish. */
loop_until_bit_is_set(SPSR, SPIF);
sbi(VS_BSYNC_PORT, VS_BSYNC_BIT);
outb(SPDR, b);
_NOP();
_NOP();
_NOP();
_NOP();
cbi(VS_BSYNC_PORT, VS_BSYNC_BIT);
#endif
}
/*!
* \brief Write a specified number of bytes to the VS1001 data interface.
*
* This function will check the DREQ line. Decoder interrupts must have
* been disabled before calling this function.
*/
static int VsSdiWrite(const uint8_t * data, uint16_t len)
{
uint16_t try = 5000;
while (len--) {
while (try-- && bit_is_clear(VS_DREQ_PIN, VS_DREQ_BIT));
VsSdiPutByte(*data);
data++;
}
return try ? 0 : -1;
}
/*!
* \brief Write a specified number of bytes from program space to the
* VS1001 data interface.
*
* This function is similar to VsSdiWrite() except that the data is
* located in program space.
*/
static int VsSdiWrite_P(PGM_P data, uint16_t len)
{
uint16_t try = 5000;
while (len--) {
while (try-- && bit_is_clear(VS_DREQ_PIN, VS_DREQ_BIT));
VsSdiPutByte(PRG_RDB(data));
data++;
}
return try ? 0 : -1;
}
/*!
* \brief Write a byte to the serial control interface.
*
* Decoder interrupts must have been disabled and the decoder chip
* select must have been enabled before calling this function.
*/
static INLINE void VsSciPutByte(uint8_t data)
{
uint8_t mask = 0x80;
/*
* Loop until all 8 bits are processed.
*/
while (mask) {
/* Set data line. */
if (data & mask)
sbi(VS_SI_PORT, VS_SI_BIT);
else
cbi(VS_SI_PORT, VS_SI_BIT);
/* Toggle clock and shift mask. */
sbi(VS_SCK_PORT, VS_SCK_BIT);
mask >>= 1;
cbi(VS_SCK_PORT, VS_SCK_BIT);
}
}
/*!
* \brief Read a byte from the serial control interface.
*
* Decoder interrupts must have been disabled and the decoder chip
* select must have been enabled before calling this function.
*/
static INLINE uint8_t VsSciGetByte(void)
{
uint8_t mask = 0x80;
uint8_t data = 0;
/*
* Loop until all 8 bits are processed.
*/
while (mask) {
/* Toggle clock and get the data. */
sbi(VS_SCK_PORT, VS_SCK_BIT);
if (bit_is_set(VS_SO_PIN, VS_SO_BIT))
data |= mask;
mask >>= 1;
cbi(VS_SCK_PORT, VS_SCK_BIT);
}
return data;
}
/*!
* \brief Write to a decoder register.
*
* Decoder interrupts must have been disabled before calling this function.
*/
static void VsRegWrite(uint8_t reg, uint16_t data)
{
/* Select chip. */
cbi(VS_XCS_PORT, VS_XCS_BIT);
#ifndef VS_NOSPI
/* Disable SPI */
cbi(SPCR, SPE);
#endif
VsSciPutByte(VS_OPCODE_WRITE);
VsSciPutByte(reg);
VsSciPutByte((uint8_t) (data >> 8));
VsSciPutByte((uint8_t) data);
#ifndef VS_NOSPI
/* Re-enable SPI. Hint given by Jesper Hansen. */
outb(SPCR, BV(MSTR) | BV(SPE));
outb(SPSR, inb(SPSR));
#endif
/* Deselect chip. */
sbi(VS_XCS_PORT, VS_XCS_BIT);
}
/*
* \brief Read from a register.
*
* Decoder interrupts must have been disabled before calling this function.
*
* \return Register contents.
*/
static uint16_t VsRegRead(uint8_t reg)
{
uint16_t data;
/* Disable interrupts and select chip. */
cbi(VS_XCS_PORT, VS_XCS_BIT);
#ifndef VS_NOSPI
/* Disable SPI. */
cbi(SPCR, SPE);
#endif
VsSciPutByte(VS_OPCODE_READ);
VsSciPutByte(reg);
data = (uint16_t)VsSciGetByte() << 8;
data |= VsSciGetByte();
#ifndef VS_NOSPI
/* Re-enable SPI. Changed due to a hint by Jesper. */
outb(SPCR, BV(MSTR) | BV(SPE));
outb(SPSR, inb(SPSR));
#endif
/* Deselect chip and enable interrupts. */
sbi(VS_XCS_PORT, VS_XCS_BIT);
return data;
}
/*!
* \brief Enable or disable player interrupts.
*
* This routine is typically used by applications when dealing with
* unprotected buffers.
*
* \param enable Disables interrupts when zero. Otherwise interrupts
* are enabled.
*
* \return Zero if interrupts were disabled before this call.
*/
uint8_t VsPlayerInterrupts(uint8_t enable)
{
static uint8_t is_enabled = 0;
uint8_t rc;
rc = is_enabled;
if(enable) {
NutIrqEnable(&VS_SIGNAL);
}
else {
NutIrqDisable(&VS_SIGNAL);
}
is_enabled = enable;
return rc;
}
/*
* \brief Feed the decoder with data.
*
* This function serves two purposes:
* - It is called by VsPlayerKick() to initially fill the decoder buffer.
* - It is used as an interrupt handler for the decoder.
*/
static void VsPlayerFeed(void *arg)
{
uint8_t ief;
uint8_t j = 32;
size_t total = 0;
if (bit_is_clear(VS_DREQ_PIN, VS_DREQ_BIT)) {
return;
}
/*
* We are hanging around here some time and may block other important
* interrupts. Disable decoder interrupts and enable global interrupts.
*/
ief = VsPlayerInterrupts(0);
sei();
/*
* Feed the decoder until its buffer is full or we ran out of data.
*/
if (vs_status == VS_STATUS_RUNNING) {
char *bp = 0;
size_t consumed = 0;
size_t available = 0;
do {
if(consumed >= available) {
/* Commit previously consumed bytes. */
if(consumed) {
NutSegBufReadCommit(consumed);
consumed = 0;
}
/* All bytes consumed, request new. */
bp = NutSegBufReadRequest(&available);
if(available == 0) {
/* End of stream. */
vs_status = VS_STATUS_EOF;
break;
}
}
/* We have some data in the buffer, feed it. */
VsSdiPutByte(*bp);
bp++;
consumed++;
total++;
if (total > 4096) {
vs_status = VS_STATUS_EOF;
break;
}
/* Allow 32 bytes to be sent as long as DREQ is set, This includes
the one in progress. */
if (bit_is_set(VS_DREQ_PIN, VS_DREQ_BIT))
j = 32;
} while(j--);
/* Finally re-enable the producer buffer. */
NutSegBufReadLast(consumed);
}
/*
* Flush the internal VS buffer.
*/
if(vs_status != VS_STATUS_RUNNING && vs_flush) {
do {
VsSdiPutByte(0);
if (--vs_flush == 0) {
/* Decoder internal buffer is flushed. */
vs_status = VS_STATUS_EMPTY;
break;
}
/* Allow 32 bytes to be sent as long as DREQ is set, This includes
the one in progress. */
if (bit_is_set(VS_DREQ_PIN, VS_DREQ_BIT))
j = 32;
} while(j--);
}
VsPlayerInterrupts(ief);
}
/*!
* \brief Start playback.
*
* This routine will send the first MP3 data bytes to the
* decoder, until it is completely filled. The data buffer
* should have been filled before calling this routine.
*
* Decoder interrupts will be enabled.
*
* \return 0 on success, -1 otherwise.
*/
int VsPlayerKick(void)
{
/*
* Start feeding the decoder with data.
*/
VsPlayerInterrupts(0);
vs_status = VS_STATUS_RUNNING;
VsPlayerFeed(NULL);
VsPlayerInterrupts(1);
return 0;
}
/*!
* \brief Stops the playback.
*
* This routine will stops the MP3 playback, VsPlayerKick() may be used
* to resume the playback.
*
* \return 0 on success, -1 otherwise.
*/
int VsPlayerStop(void)
{
uint8_t ief;
ief = VsPlayerInterrupts(0);
/* Check whether we need to stop at all to not overwrite other than running status */
if (vs_status == VS_STATUS_RUNNING) {
vs_status = VS_STATUS_STOPPED;
}
VsPlayerInterrupts(ief);
return 0;
}
/*!
* \brief Sets up decoder internal buffer flushing.
*
* This routine will set up internal VS buffer flushing,
* unless the buffer is already empty and starts the playback
* if necessary. The internal VS buffer is flushed in VsPlayerFeed()
* at the end of the stream.
*
* Decoder interrupts will be enabled.
*
* \return 0 on success, -1 otherwise.
*/
int VsPlayerFlush(void)
{
VsPlayerInterrupts(0);
/* Set up fluhing unless both buffers are empty. */
if (vs_status != VS_STATUS_EMPTY || NutSegBufUsed()) {
if (vs_flush == 0)
vs_flush = VS_FLUSH_BYTES;
/* start the playback if necessary */
if (vs_status != VS_STATUS_RUNNING)
VsPlayerKick();
}
VsPlayerInterrupts(1);
return 0;
}
/*!
* \brief Initialize the VS1001 hardware interface.
*
* \return 0 on success, -1 otherwise.
*/
int VsPlayerInit(void)
{
/* Disable decoder interrupts. */
VsPlayerInterrupts(0);
/* Keep decoder in reset state. */
cbi(VS_RESET_PORT, VS_RESET_BIT);
sbi(VS_RESET_DDR, VS_RESET_BIT);
/* Set BSYNC output low. */
cbi(VS_BSYNC_PORT, VS_BSYNC_BIT);
sbi(VS_BSYNC_DDR, VS_BSYNC_BIT);
/* Set MP3 chip select output low. */
sbi(VS_XCS_PORT, VS_XCS_BIT);
sbi(VS_XCS_DDR, VS_XCS_BIT);
/* Set DREQ input with pullup. */
sbi(VS_DREQ_PORT, VS_DREQ_BIT);
cbi(VS_DREQ_DDR, VS_DREQ_BIT);
/* Init SPI Port. */
sbi(VS_SI_DDR, VS_SI_BIT);
sbi(VS_SS_DDR, VS_SS_BIT);
cbi(VS_SO_DDR, VS_SO_BIT);
/* Set SCK output low. */
cbi(VS_SCK_PORT, VS_SCK_BIT);
sbi(VS_SCK_DDR, VS_SCK_BIT);
#ifndef VS_NOSPI
{
uint8_t dummy; /* Required by some compilers. */
/*
* Init SPI mode to no interrupts, enabled, MSB first, master mode,
* rising clock and fosc/4 clock speed. Send an initial zero byte to
* make sure SPIF is set. Note, that the decoder reset line is still
* active.
*/
outb(SPCR, BV(MSTR) | BV(SPE));
dummy = inb(SPSR);
outb(SPDR, 0);
}
#endif
/* Register the interrupt routine */
if (NutRegisterIrqHandler(&VS_SIGNAL, VsPlayerFeed, NULL)) {
return -1;
}
/* Rising edge will generate interrupts. */
NutIrqSetMode(&VS_SIGNAL, NUT_IRQMODE_RISINGEDGE);
/* Release decoder reset line. */
sbi(VS_RESET_PORT, VS_RESET_BIT);
NutDelay(4);
/* Force frequency change (see datasheet). */
VsRegWrite(VS_CLOCKF_REG, 0x9800);
VsRegWrite(VS_INT_FCTLH_REG, 0x8008);
NutDelay(200);
/* Clear any spurious interrupt. */
outb(EIFR, BV(VS_DREQ_BIT));
return 0;
}
/*!
* \brief Software reset the decoder.
*
* This function is typically called after VsPlayerInit() and at the end
* of each track.
*
* \param mode Any of the following flags may be or'ed
* - VS_SM_DIFF Left channel inverted.
* - VS_SM_FFWD Fast forward.
* - VS_SM_RESET Force hardware reset.
* - VS_SM_PDOWN Switch to power down mode.
* - VS_SM_BASS Bass/treble enhancer.
*
* \return 0 on success, -1 otherwise.
*/
int VsPlayerReset(uint16_t mode)
{
/* Disable decoder interrupts and feeding. */
VsPlayerInterrupts(0);
vs_status = VS_STATUS_STOPPED;
/* Software reset, set modes of decoder. */
VsRegWrite(VS_MODE_REG, VS_SM_RESET | mode);
NutDelay(2);
/*
* Check for correct reset.
*/
if ((mode & VS_SM_RESET) != 0 || bit_is_clear(VS_DREQ_PIN, VS_DREQ_BIT)) {
/* If not succeeded, give it one more chance and try hw reset,
HW reset may also be forced by VS_SM_RESET mode bit. */
cbi(VS_RESET_PORT, VS_RESET_BIT);
_NOP();
sbi(VS_RESET_PORT, VS_RESET_BIT);
NutDelay(4);
/* Set the requested modes. */
VsRegWrite(VS_MODE_REG, VS_SM_RESET | mode);
NutDelay(2);
if (bit_is_clear(VS_DREQ_PIN, VS_DREQ_BIT))
return -1;
}
/* Force frequency change (see datasheet). */
VsRegWrite(VS_CLOCKF_REG, 0x9800);
VsRegWrite(VS_INT_FCTLH_REG, 0x8008);
NutDelay(2);
/* Clear any spurious interrupts. */
outb(EIFR, BV(VS_DREQ_BIT));
return 0;
}
/*!
* \brief Set mode register of the decoder.
*
* \param mode Any of the following flags may be or'ed
* - VS_SM_DIFF Left channel inverted.
* - VS_SM_FFWD Fast forward.
* - VS_SM_RESET Software reset.
* - VS_SM_PDOWN Switch to power down mode.
* - VS_SM_BASS Bass/treble enhancer.
*
* \return 0 on success, -1 otherwise.
*/
int VsPlayerSetMode(uint16_t mode)
{
uint8_t ief;
ief = VsPlayerInterrupts(0);
VsRegWrite(VS_MODE_REG, mode);
VsPlayerInterrupts(ief);
return 0;
}
/*!
* \brief Returns play time since last reset.
*
* \return Play time since reset in seconds
*/
uint16_t VsPlayTime(void)
{
uint16_t rc;
uint8_t ief;
ief = VsPlayerInterrupts(0);
rc = VsRegRead(VS_DECODE_TIME_REG);
VsPlayerInterrupts(ief);
return rc;
}
/*!
* \brief Returns status of the player.
*
* \return Any of the following value:
* - VS_STATUS_STOPPED Player is ready to be started by VsPlayerKick().
* - VS_STATUS_RUNNING Player is running.
* - VS_STATUS_EOF Player has reached the end of a stream after VsPlayerFlush() has been called.
* - VS_STATUS_EMPTY Player runs out of data. VsPlayerKick() will restart it.
*/
uint8_t VsGetStatus(void)
{
return vs_status;
}
#ifdef __GNUC__
/*!
* \brief Query MP3 stream header information.
*
* \param vshi Pointer to VS_HEADERINFO structure.
*
* \return 0 on success, -1 otherwise.
*/
int VsGetHeaderInfo(VS_HEADERINFO * vshi)
{
uint16_t *usp = (uint16_t *) vshi;
uint8_t ief;
ief = VsPlayerInterrupts(0);
*usp = VsRegRead(VS_HDAT1_REG);
*++usp = VsRegRead(VS_HDAT0_REG);
VsPlayerInterrupts(ief);
return 0;
}
#endif
/*!
* \brief Initialize decoder memory test and return result.
*
* \return Memory test result.
* - Bit 0: Good X ROM
* - Bit 1: Good Y ROM (high)
* - Bit 2: Good Y ROM (low)
* - Bit 3: Good Y RAM
* - Bit 4: Good X RAM
* - Bit 5: Good Instruction RAM (high)
* - Bit 6: Good Instruction RAM (low)
*/
uint16_t VsMemoryTest(void)
{
uint16_t rc;
uint8_t ief;
static prog_char mtcmd[] = { 0x4D, 0xEA, 0x6D, 0x54, 0x00, 0x00, 0x00, 0x00 };
ief = VsPlayerInterrupts(0);
VsSdiWrite_P(mtcmd, sizeof(mtcmd));
NutDelay(40);
rc = VsRegRead(VS_HDAT0_REG);
VsPlayerInterrupts(ief);
return rc;
}
/*!
* \brief Set volume.
*
* \param left Left channel volume.
* \param right Right channel volume.
*
* \return 0 on success, -1 otherwise.
*/
int VsSetVolume(uint8_t left, uint8_t right)
{
uint8_t ief;
ief = VsPlayerInterrupts(0);
VsRegWrite(VS_VOL_REG, (((uint16_t) left) << 8) | (uint16_t) right);
VsPlayerInterrupts(ief);
return 0;
}
/*!
* \brief Sine wave beep.
*
* \param fsin Frequency.
* \param ms Duration.
*
* \return 0 on success, -1 otherwise.
*/
int VsBeep(uint8_t fsin, uint8_t ms)
{
uint8_t ief;
static prog_char on[] = { 0x53, 0xEF, 0x6E };
static prog_char off[] = { 0x45, 0x78, 0x69, 0x74 };
static prog_char end[] = { 0x00, 0x00, 0x00, 0x00 };
/* Disable decoder interrupts. */
ief = VsPlayerInterrupts(0);
fsin = 56 + (fsin & 7) * 9;
VsSdiWrite_P(on, sizeof(on));
VsSdiWrite(&fsin, 1);
VsSdiWrite_P(end, sizeof(end));
NutDelay(ms);
VsSdiWrite_P(off, sizeof(off));
VsSdiWrite_P(end, sizeof(end));
/* Enable decoder interrupts. */
VsPlayerInterrupts(ief);
return 0;
}
/*@}*/
| C | CL | 76bc5daf3163471dd98b5bce968dcbe830e834c76bd53361b9898efaa582ee30 |
/*
* queue.c
*
* Implementazione delle funzioni dichiarate nel file queue.h
*
* Autore: Nicolò Maffi
* Data: 16/05/2020
* Versione: 1.1
*/
#include "queue.h"
queue initqueue()
{
queue q;
q.base = NULL; //Il puntatore alla base della coda è nullo per l'inizializzazione
q.top = NULL; //Il puntatore alla cima della coda è nullo per l'inizializzazione
return q;
}
short enqueue(queue *q, int value)
{
node *tmp = NULL; //Puntatore di supporto
if(q == NULL) //Controllo della validità del puntatore alla coda
return 0;
tmp = (node *)calloc(1, sizeof(node)); //Creazione di un nuovo nodo
tmp->value = value; //Impostazione del valore del nodo
if(q->base != NULL) //Se base non è null (non è la prima operazione di accodamento) *
q->base->next = tmp; //* viene collegato il nodo precedente a quello nuovo
q->base = tmp; //base ora punta al nuovo nodo (la coda si estende)
if(q->top == NULL) //Se top è null (è la prima operazione di accodamento) *
q->top = q->base; //top punta alla stessa cella puntata da base
return 1;
}
short dequeue(queue *q, int *value)
{
node *tmp = NULL; //Puntatore di supporto
//Controllo della validità dei puntatori passati come parametri
//Se il il puntatore top è nullo la coda è vuota -> non si può effettuare l'estrazione
if(q == NULL || value == NULL || q->top == NULL)
return 0;
tmp = q->top;
*value = q->top->value; //Impostazione del valore che restituirà l'estrazione
q->top = q->top->next; //Il puntatore top ora punta al nodo successivo (la coda si riduce)
free(tmp); //Deallocazione del nodo sulla cima della coda
if(q->top == NULL) //Se top è nullo (ultima operazione di estrazione possibile) *
q->base = q->top; //* top punta alla stessa cella puntata da base
return 1;
}
size_t queuedim(queue *q)
{
node *tmp = NULL; //Puntatore di supporto
size_t dim = 0; //Dimensione della coda
//Controllo della validità dei puntatori passati come parametri
//Se il il puntatore top è nullo la coda è vuota -> non ha dimensione
if(q == NULL || q->top == NULL)
return 0;
tmp = q->top;
for(dim = 0; tmp != NULL; dim++) //Viene incrementata la dimensione della coda fino a quando tmp è nullo
tmp = tmp->next; //tmp punta alla cella successiva
return dim;
} | C | CL | 9b45628aac09d0ab5b11d47421b13a838bcca1d78b2f3dd0b7ca2a99c50abd75 |
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "rs485.h"
#include "stm32f10x_conf.h"
#include <string.h>
#include "crc.h"
#include "modbus.h"
#define RX_SIZE 512
#define TX_SIZE 512
static unsigned short rxBreakTime=10; // delay between a request and an answer
static volatile unsigned char rx_buf[RX_SIZE];
static unsigned char tx_buf[TX_SIZE];
static volatile unsigned short rx_cnt=0;
static unsigned short tmp_tmr=0;
unsigned short linkTmr=0;
extern unsigned short mAddress;
extern unsigned long baudRate;
extern unsigned short twoStopBits;
extern unsigned short parityState;
static buf rx;
static buf tx;
static unsigned short led_tmr = 0;
static buf hello;
const char* helloString = "\r\nMC35 MODULE ver 1.0\r\n";
static void initRS485(void); // initialization of uart
static char checkRxData(void); // return non zero if data has been received
void write_data(buf* data); // send data to uart
// different pause between a request and an answer for different baudrates
static unsigned short getRxBreakTime() {
unsigned short res = 10;
switch(baudRate) {
case 115200:res = 10;break;
case 57600:res = 20;break;
case 38400:res = 40;break;
case 19200:res = 80;break;
case 9600:res=160;break;
}
return res;
}
void initRS485(void)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
rxBreakTime = getRxBreakTime();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE );
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = baudRate;
if(twoStopBits) USART_InitStructure.USART_StopBits = USART_StopBits_2;
else USART_InitStructure.USART_StopBits = USART_StopBits_1;
if(parityState==0) {
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_Parity = USART_Parity_No;
}else if(parityState==1) {
USART_InitStructure.USART_Parity = USART_Parity_Odd;
USART_InitStructure.USART_WordLength = USART_WordLength_9b;
}
else if(parityState==2) {
USART_InitStructure.USART_Parity = USART_Parity_Even;
USART_InitStructure.USART_WordLength = USART_WordLength_9b;
}
else {
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
}
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_DeInit( TIM5 );
TIM_TimeBaseStructInit( &TIM_TimeBaseStructure );
TIM_TimeBaseStructure.TIM_Prescaler = 0xFFF;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = ( unsigned short ) 0xFFFF;
TIM_TimeBaseInit( TIM5, &TIM_TimeBaseStructure );
TIM_ARRPreloadConfig( TIM5, ENABLE );
TIM_Cmd( TIM5, ENABLE );
USART_DMACmd(USART1, USART_DMAReq_Tx, ENABLE);
USART_Cmd(USART1, ENABLE);
GPIO_WriteBit(GPIOA, GPIO_Pin_8, Bit_SET);
hello.cnt = strlen(helloString);
hello.ptr = (unsigned char*)helloString;
write_data(&hello);
}
void rs485Task( void *pvParameters )
{
portTickType xLastExecutionTime;
initRS485();
xLastExecutionTime = xTaskGetTickCount();
for(;;)
{
tmp_tmr++;
if(tmp_tmr>=1000) {tmp_tmr = 0; linkTmr++;}
if(checkRxData())
{
if(GetCRC16((unsigned char*)rx_buf,rx_cnt)==0) // check CRC
{
if((rx_buf[0]==0)||(rx_buf[0]==255)||(rx_buf[0]==mAddress))
{
linkTmr = 0;
rx.cnt = rx_cnt;
rx.ptr = (unsigned char*)rx_buf;
modbusCmd* res = searchCmd(&rx); // search modbus command
if(res->isCmd) // if command has been found
{
tx.ptr = tx_buf;
tx.cnt = TX_SIZE; // max count of data
sendAnswer(res,&tx);
if(++led_tmr&0x01) GPIOA->ODR ^= GPIO_Pin_0;
}
}
}
rx_cnt = 0;
}
vTaskDelayUntil( &xLastExecutionTime, RS485_DELAY );
}
}
void write_data(buf* data)
{
DMA_InitTypeDef DMA_InitStructure;
if(data == 0) return;
if(data->cnt == 0) return;
GPIO_WriteBit(GPIOA, GPIO_Pin_8, Bit_SET);
DMA_DeInit(DMA1_Channel4);
DMA_InitStructure.DMA_PeripheralBaseAddr = USART1_BASE + 4;
DMA_InitStructure.DMA_MemoryBaseAddr = (u32)data->ptr;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
DMA_InitStructure.DMA_BufferSize = data->cnt;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel4, &DMA_InitStructure);
DMA_ITConfig(DMA1_Channel4, DMA_IT_TC, ENABLE);
USART_ITConfig(USART1, USART_IT_RXNE, DISABLE);
DMA_Cmd(DMA1_Channel4, ENABLE);
}
char checkRxData(void)
{
if((rx_cnt)&&(TIM5->CNT >= rxBreakTime)) return 1;
return 0;
}
void USART1_IRQHandler(void)
{
if(USART_GetITStatus(USART1, USART_IT_TC) != RESET)
{
USART_ClearITPendingBit(USART1, USART_IT_TC);
if(USART_GetFlagStatus(USART1, USART_FLAG_TXE)!=RESET)
{
GPIO_WriteBit(GPIOA, GPIO_Pin_8, Bit_RESET);
USART_ITConfig(USART1, USART_IT_TC, DISABLE);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
}
}
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
TIM5->CNT=0;
rx_buf[rx_cnt++] = USART_ReceiveData(USART1);
if(rx_cnt>=RX_SIZE) rx_cnt=0;
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
}
}
void DMA1_Channel4_IRQHandler(void)
{
if(DMA_GetITStatus(DMA1_IT_TC4) != RESET)
{
DMA_Cmd(DMA1_Channel4, DISABLE);
DMA_ClearITPendingBit(DMA1_IT_GL4);
USART_ITConfig(USART1, USART_IT_TC, ENABLE);
}
}
| C | CL | 0547aaaddf34f8bb0073a4ddc05d735cb521ce840d1a8db8219ba34ea5690804 |
/* Copyright 2006-2009 Nick Mathewson; See COPYING for license information. */
#include "mix3impl.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <openssl/aes.h>
#include <openssl/rsa.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
void
mix3_aes_ctr_crypt(char *out, const char *inp, size_t len, AES_KEY *aes)
{
unsigned char ivec[AES_BLOCK_SIZE], ecount[AES_BLOCK_SIZE];
unsigned num = 0;
assert (inp && out && aes);
memset(ecount, sizeof(ecount), 0);
memset(ivec, sizeof(ivec), 0);
AES_ctr128_encrypt((const unsigned char*)inp, (unsigned char *)out,
len, aes, ivec, ecount, &num);
memset(ecount, sizeof(ecount), 0);
}
void
mix3_aes_ctr_crypt_offset(char *out, const char *inp, size_t len,
AES_KEY *aes, off_t off)
{
unsigned char ivec[AES_BLOCK_SIZE], ecount[AES_BLOCK_SIZE];
unsigned num = 0;
int i;
assert (inp && out && aes);
num = off & 15;
off >>= 4;
for (i=0;i<AES_BLOCK_SIZE;++i) {
ivec[AES_BLOCK_SIZE-1-1] = off & 255;
off >>= 8;
}
AES_encrypt(ivec, ecount, aes);
AES_ctr128_encrypt((const unsigned char*)inp, (unsigned char *)out,
len, aes, ivec, ecount, &num);
memset(ecount, sizeof(ecount), 0);
}
void
mix3_prng(char *out, size_t len, AES_KEY *aes)
{
memset(out, len, 0);
mix3_aes_ctr_crypt(out, out, len, aes);
}
static void
xor(char *out, const char *inp, size_t len)
{
while (--len)
*out++ ^= *inp++;
}
static void
lioness_mac(unsigned char *out, const char *data, size_t datalen, const char *key, int keynum)
{
char k[LIONESS_KEY_LEN];
SHA_CTX sha;
assert(out && data && datalen && key);
memcpy(k, key, LIONESS_KEY_LEN);
k[LIONESS_KEY_LEN - 1] ^= keynum;
SHA1_Init(&sha);
SHA1_Update(&sha, k, sizeof(k));
SHA1_Update(&sha, data, datalen);
SHA1_Update(&sha, k, sizeof(k));
SHA1_Final(out, &sha);
memset(k, sizeof(k), 0);
memset(&sha, sizeof(sha), 0);
}
void
mix3_lioness_encrypt(char *buf, size_t len, const char *key)
{
unsigned char k[LIONESS_KEY_LEN];
AES_KEY aes;
assert(buf && key);
assert(len > SHA1_LEN);
lioness_mac(k, buf, SHA1_LEN, key, 0);
AES_set_encrypt_key(k, 128, &aes);
mix3_aes_ctr_crypt(buf + SHA1_LEN, buf + SHA1_LEN, len - SHA1_LEN, &aes);
lioness_mac(k, buf+SHA1_LEN, len-SHA1_LEN, key, 1);
xor(buf, (char*)k, SHA1_LEN);
lioness_mac(k, buf, SHA1_LEN, key, 2);
AES_set_encrypt_key(k, 128, &aes);
mix3_aes_ctr_crypt(buf + SHA1_LEN, buf + SHA1_LEN, len - SHA1_LEN, &aes);
lioness_mac(k, buf + SHA1_LEN, len - SHA1_LEN, key, 3);
xor(buf, (char*)k, SHA1_LEN);
memset(&aes, sizeof(aes), 0);
memset(k, sizeof(aes), 0);
}
void
mix3_aes_subkey_init(AES_KEY *aes, const char *master_key,
size_t master_key_len, const char *subkey)
{
SHA_CTX ctx;
unsigned char k[SHA1_LEN];
SHA1_Init(&ctx);
SHA1_Update(&ctx, master_key, master_key_len);
SHA1_Update(&ctx, subkey, strlen(subkey));
SHA1_Final(k, &ctx);
AES_set_encrypt_key(k, 128, aes);
}
void
mix3_lioness_decrypt(char *buf, size_t len, const char *key)
{
unsigned char k[LIONESS_KEY_LEN];
AES_KEY aes;
assert(buf && key);
assert(len > SHA1_LEN);
lioness_mac(k, buf + SHA1_LEN, len - SHA1_LEN, key, 3);
xor(buf, (char*)k, SHA1_LEN);
lioness_mac(k, buf, SHA1_LEN, key, 2);
AES_set_encrypt_key(k, 128, &aes);
mix3_aes_ctr_crypt(buf + SHA1_LEN, buf + SHA1_LEN, len - SHA1_LEN, &aes);
lioness_mac(k, buf + SHA1_LEN, len - SHA1_LEN, key, 1);
xor(buf, (char*)k, SHA1_LEN);
lioness_mac(k, buf, SHA1_LEN, key, 0);
AES_set_encrypt_key(k, 128, &aes);
mix3_aes_ctr_crypt(buf + SHA1_LEN, buf + SHA1_LEN, len - SHA1_LEN, &aes);
memset(&aes, sizeof(aes), 0);
memset(k, sizeof(aes), 0);
}
mix3_status_t
_mix3_parse_base64(char **out, size_t *len_out, const char *s, size_t len_in)
{
EVP_ENCODE_CTX ctx;
int len, len2;
unsigned char *mem;
size_t guess_len = (len_in/64+1)*49;
mem = mix3_alloc(guess_len);
if (!mem)
return MIX3_NOMEM;
EVP_DecodeInit(&ctx);
EVP_DecodeUpdate(&ctx, mem, &len, (const unsigned char*)s, len_in);
EVP_DecodeFinal(&ctx, mem, &len2);
*len_out = (size_t)(len+len2);
*out = (char*)mem;
return MIX3_OK;
}
| C | CL | b2127774af3d17a5610af02a8af32ebeec818c72b28404fd1d6ba86172ced7f0 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_10__ TYPE_5__ ;
typedef struct TYPE_9__ TYPE_4__ ;
typedef struct TYPE_8__ TYPE_3__ ;
typedef struct TYPE_7__ TYPE_2__ ;
typedef struct TYPE_6__ TYPE_1__ ;
/* Type definitions */
struct TYPE_9__ {int /*<<< orphan*/ itid; } ;
struct iscsi_text_response_hdr {int hdr_second_dword; int /*<<< orphan*/ max_cmd_sn; int /*<<< orphan*/ exp_cmd_sn; int /*<<< orphan*/ stat_sn; int /*<<< orphan*/ ttt; int /*<<< orphan*/ flags; int /*<<< orphan*/ opcode; } ;
struct TYPE_7__ {struct iscsi_text_response_hdr text_response; } ;
struct TYPE_8__ {TYPE_2__ iscsi_hdr; } ;
union iscsi_cqe {TYPE_4__ cqe_solicited; TYPE_3__ cqe_common; } ;
struct qedi_ctx {int /*<<< orphan*/ dbg_ctx; int /*<<< orphan*/ tasks; } ;
struct TYPE_10__ {scalar_t__ resp_buf; scalar_t__ resp_wr_ptr; int /*<<< orphan*/ resp_hdr; } ;
struct qedi_conn {TYPE_5__ gen_pdu; int /*<<< orphan*/ iscsi_conn_id; int /*<<< orphan*/ active_cmd_count; TYPE_1__* cls_conn; } ;
struct qedi_cmd {int io_cmd_in_list; int /*<<< orphan*/ task_id; int /*<<< orphan*/ state; int /*<<< orphan*/ io_cmd; } ;
struct iscsi_text_rsp {void* max_cmdsn; void* exp_cmdsn; void* statsn; int /*<<< orphan*/ ttt; int /*<<< orphan*/ itt; int /*<<< orphan*/ dlength; scalar_t__ hlength; int /*<<< orphan*/ flags; int /*<<< orphan*/ opcode; } ;
struct iscsi_task {scalar_t__ dd_data; } ;
struct iscsi_session {int /*<<< orphan*/ back_lock; int /*<<< orphan*/ age; } ;
struct iscsi_hdr {int dummy; } ;
struct iscsi_conn {struct iscsi_session* session; } ;
struct e4_iscsi_task_context {void* max_cmdsn; void* exp_cmdsn; void* statsn; int /*<<< orphan*/ ttt; int /*<<< orphan*/ itt; int /*<<< orphan*/ dlength; scalar_t__ hlength; int /*<<< orphan*/ flags; int /*<<< orphan*/ opcode; } ;
struct TYPE_6__ {struct iscsi_conn* dd_data; } ;
/* Variables and functions */
int ISCSI_TEXT_RESPONSE_HDR_DATA_SEG_LEN_MASK ;
int /*<<< orphan*/ QEDI_INFO (int /*<<< orphan*/ *,int /*<<< orphan*/ ,char*,int /*<<< orphan*/ ,int /*<<< orphan*/ ,...) ;
int /*<<< orphan*/ QEDI_LOG_INFO ;
int /*<<< orphan*/ QEDI_LOG_TID ;
int /*<<< orphan*/ RESPONSE_RECEIVED ;
int /*<<< orphan*/ __iscsi_complete_pdu (struct iscsi_conn*,struct iscsi_hdr*,scalar_t__,scalar_t__) ;
int /*<<< orphan*/ build_itt (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
void* cpu_to_be32 (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ hton24 (int /*<<< orphan*/ ,int) ;
scalar_t__ likely (int) ;
int /*<<< orphan*/ list_del_init (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ memset (struct iscsi_text_rsp*,char,int) ;
int /*<<< orphan*/ qedi_clear_task_idx (struct qedi_ctx*,int /*<<< orphan*/ ) ;
struct iscsi_text_rsp* qedi_get_task_mem (int /*<<< orphan*/ *,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ spin_lock (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ spin_unlock (int /*<<< orphan*/ *) ;
__attribute__((used)) static void qedi_process_text_resp(struct qedi_ctx *qedi,
union iscsi_cqe *cqe,
struct iscsi_task *task,
struct qedi_conn *qedi_conn)
{
struct iscsi_conn *conn = qedi_conn->cls_conn->dd_data;
struct iscsi_session *session = conn->session;
struct e4_iscsi_task_context *task_ctx;
struct iscsi_text_rsp *resp_hdr_ptr;
struct iscsi_text_response_hdr *cqe_text_response;
struct qedi_cmd *cmd;
int pld_len;
cmd = (struct qedi_cmd *)task->dd_data;
task_ctx = qedi_get_task_mem(&qedi->tasks, cmd->task_id);
cqe_text_response = &cqe->cqe_common.iscsi_hdr.text_response;
spin_lock(&session->back_lock);
resp_hdr_ptr = (struct iscsi_text_rsp *)&qedi_conn->gen_pdu.resp_hdr;
memset(resp_hdr_ptr, 0, sizeof(struct iscsi_hdr));
resp_hdr_ptr->opcode = cqe_text_response->opcode;
resp_hdr_ptr->flags = cqe_text_response->flags;
resp_hdr_ptr->hlength = 0;
hton24(resp_hdr_ptr->dlength,
(cqe_text_response->hdr_second_dword &
ISCSI_TEXT_RESPONSE_HDR_DATA_SEG_LEN_MASK));
resp_hdr_ptr->itt = build_itt(cqe->cqe_solicited.itid,
conn->session->age);
resp_hdr_ptr->ttt = cqe_text_response->ttt;
resp_hdr_ptr->statsn = cpu_to_be32(cqe_text_response->stat_sn);
resp_hdr_ptr->exp_cmdsn = cpu_to_be32(cqe_text_response->exp_cmd_sn);
resp_hdr_ptr->max_cmdsn = cpu_to_be32(cqe_text_response->max_cmd_sn);
pld_len = cqe_text_response->hdr_second_dword &
ISCSI_TEXT_RESPONSE_HDR_DATA_SEG_LEN_MASK;
qedi_conn->gen_pdu.resp_wr_ptr = qedi_conn->gen_pdu.resp_buf + pld_len;
memset(task_ctx, '\0', sizeof(*task_ctx));
QEDI_INFO(&qedi->dbg_ctx, QEDI_LOG_TID,
"Freeing tid=0x%x for cid=0x%x\n",
cmd->task_id, qedi_conn->iscsi_conn_id);
if (likely(cmd->io_cmd_in_list)) {
cmd->io_cmd_in_list = false;
list_del_init(&cmd->io_cmd);
qedi_conn->active_cmd_count--;
} else {
QEDI_INFO(&qedi->dbg_ctx, QEDI_LOG_INFO,
"Active cmd list node already deleted, tid=0x%x, cid=0x%x, io_cmd_node=%p\n",
cmd->task_id, qedi_conn->iscsi_conn_id,
&cmd->io_cmd);
}
cmd->state = RESPONSE_RECEIVED;
qedi_clear_task_idx(qedi, cmd->task_id);
__iscsi_complete_pdu(conn, (struct iscsi_hdr *)resp_hdr_ptr,
qedi_conn->gen_pdu.resp_buf,
(qedi_conn->gen_pdu.resp_wr_ptr -
qedi_conn->gen_pdu.resp_buf));
spin_unlock(&session->back_lock);
} | C | CL | df7321cfcede076f6829b55085083fb41c419ec0697d3a6414528ff3e6879d30 |
#include <string.h>
#include "utt_cache.h"
typedef gboolean (*UttCheckFunc) (gpointer data, gpointer user_data);
/* deep first search */
static void
recursive_iterate_children (struct cache_node *node, UttCheckFunc cfunc, GFunc func, gpointer user_data)
{
struct cache_node *sibling;
if (!func) {
return;
}
while (node) {
recursive_iterate_children (node->children, cfunc, func, user_data);
sibling = node->sibling;
if (cfunc (node, user_data)) {
func (node, user_data);
}
/* may node is already free */
node = sibling;
}
}
/*
* cache_node_path:
* @node: the cache_node object
*
* Get node's full path, node name separate by '/'.
*
* Return value: node path, value should be free with g_free ().
*/
static gchar *
cache_node_path (struct cache_node *node)
{
g_return_val_if_fail (node, NULL);
GList *list = NULL;
gchar *name, *buf;
gint len = 0;
do {
len += strlen (node->name) + 1;
list = g_list_prepend (list, node->name);
node = node->parent;
} while (node);
buf = g_malloc0 (len);
do {
if (buf[0] != '\0') {
strncat (buf, "/", len);
}
name = list->data;
strncat (buf, name, len);
list = g_list_next (list);
} while (list);
return buf;
}
static void
append_to_cachefile (struct cache_node *node, FILE *fp)
{
gchar *fullname;
fullname = cache_node_path (node);
fwrite (fullname, strlen (fullname) + 1, 1, fp);
fwrite (&node->data_size, sizeof (node->data_size), 1, fp);
fwrite (node->data, node->data_size, 1, fp);
g_free (fullname);
}
static gboolean
check_if_node_have_data (struct cache_node *node, gpointer user_data)
{
g_return_val_if_fail (node, FALSE);
return !!node->data;
}
void
utt_cache_flush (struct utt_cache *cache)
{
FILE *fp;
if (!(cache && cache->root && cache->root->children)) {
return;
}
fp = g_fopen (cache->cachefile, "wb");
if (!fp) {
g_warning ("open cachefile '%s' fail", cache->cachefile);
return;
}
recursive_iterate_children (cache->root->children, (UttCheckFunc)check_if_node_have_data,
(GFunc)append_to_cachefile, fp);
fclose (fp);
}
struct utt_cache *
utt_cache_new ()
{
struct utt_cache *cache;
cache = g_new0 (struct utt_cache, 1);
return cache;
}
static void
load_cachefile (struct utt_cache *cache, FILE *fp)
{
#define FULLNAME_MAXSIZE 256
gchar fullname[FULLNAME_MAXSIZE];
gchar ch;
gint ret, i, data_size;
gchar *data;
i = 0;
for (;;) {
ret = fread (&ch, sizeof (ch), 1, fp);
if (ret != 1) {
break;
}
fullname[i++] = ch;
if (ch == '\0') {
ret = fread (&data_size, sizeof (data_size), 1, fp);
if (ret != 1) {
g_warning ("read data_size fail");
break;
}
data = g_malloc (data_size);
ret = fread (data, data_size, 1, fp);
if (ret != 1) {
g_warning ("read data fail");
g_free (data);
break;
}
utt_cache_add (cache, fullname, data, data_size);
g_free (data);
i = 0;
continue;
}
if (i >= FULLNAME_MAXSIZE) {
g_warning ("fullname size is bigger than %d", FULLNAME_MAXSIZE);
break;
}
}
#undef FULLNAME_MAXSIZE
}
gboolean
utt_cache_set_cachefile (struct utt_cache *cache, gchar *path)
{
FILE *fp;
if (!cache || !path) {
return FALSE;
}
if (cache->cachefile) {
g_free (cache->cachefile);
}
cache->cachefile = g_strdup (path);
fp = g_fopen (path, "rb");
if (!fp) {
return FALSE;
}
load_cachefile (cache, fp);
fclose (fp);
return TRUE;
}
static void
free_tree_node (struct cache_node *node, void *user_data)
{
g_free (node->name);
node->name = NULL;
g_free (node->data);
node->data = NULL;
g_free (node);
}
static gboolean
always_return_true (gpointer data, gpointer user_data)
{
return TRUE;
}
static void
free_cache_tree (struct cache_root *root)
{
if (!root) {
return;
}
recursive_iterate_children (root->children, always_return_true,
(GFunc)free_tree_node, NULL);
g_free (root);
}
void
utt_cache_destroy (struct utt_cache *cache)
{
if (!cache) {
return;
}
if (cache->cachefile) {
g_free (cache->cachefile);
}
free_cache_tree (cache->root);
g_free (cache);
}
static gboolean
validate_cache_char (gchar ch)
{
if (g_ascii_isalnum (ch) || ch == '-' || ch == '_') {
return TRUE;
}
return FALSE;
}
static gboolean
validate_cache_name (gchar *name)
{
gint i, end;
g_return_val_if_fail (name, FALSE);
end = strlen (name) - 1;
if (!(end >= 0 && validate_cache_char (name[0]) && validate_cache_char (name[end]))) {
g_warning ("invalidate name '%s'", name);
return FALSE;
}
for (i = 1; i < end; i++) {
if (validate_cache_char (name[i])) {
continue;
}
if (name[i] != '/' ||
(name[i] == '/' && name[i + 1] == '/')) {
g_warning ("invalidate name '%s'\n", name);
return FALSE;
}
}
return TRUE;
}
static struct cache_node *
cache_children_find_name (struct cache_node *children, gchar *name)
{
struct cache_node *node = children;
while (node && g_strcmp0 (node->name, name) != 0) {
node = node->sibling;
}
return node;
}
/*
* utt_cache_add_internal:
* @cache: the utt_cache object
* @name: the register cache path
* @data: save data
* @data_size: @data size
* @replace: if found data already exist, replace it or not.
*
* Add custom data to utt cahce tree.
* @data bind with @name, its size is @data_size.
*
* Return value: TRUE, if add success, FALSE on fail.
*/
static gboolean
utt_cache_add_internal (struct utt_cache *cache, gchar *name, void *data, gint data_size, gboolean replace)
{
struct cache_node **children, *new_node, *node, *parent;
gchar **vector;
gboolean ret = FALSE;
gint i;
g_return_val_if_fail (cache && data && (data_size > 0), FALSE);
g_return_val_if_fail (validate_cache_name (name), FALSE);
if (G_UNLIKELY (!cache->root)) {
cache->root = g_new0 (struct cache_root, 1);
}
children = &cache->root->children;
parent = NULL;
vector = g_strsplit (name, "/", 0);
for (i = 0; vector[i]; i++) {
node = cache_children_find_name (*children, vector[i]);
if (!node) {
new_node = g_new0 (struct cache_node, 1);
new_node->name = g_strdup (vector[i]);
if (!vector[i + 1]) {
new_node->data_size = data_size;
new_node->data = g_malloc (data_size);
memcpy (new_node->data, data, data_size);
new_node->parent = parent;
}
if (*children) {
new_node->sibling = *children;
}
*children = new_node;
children = &new_node->children;
parent = new_node;
}
else {
if (!vector[i + 1]) {
if (replace) {
g_free (node->data);
node->data_size = data_size;
node->data = g_malloc (data_size);
memcpy (node->data, data, data_size);
ret = TRUE;
}
else {
ret = FALSE;
}
break;
}
children = &node->children;
parent = node;
}
}
g_strfreev (vector);
return ret;
}
gboolean
utt_cache_add (struct utt_cache *cache, gchar *name, void *data, gint data_size)
{
return utt_cache_add_internal (cache, name, data, data_size, FALSE);
}
gboolean
utt_cache_update (struct utt_cache *cache, gchar *name, void *data, gint data_size)
{
return utt_cache_add_internal (cache, name, data, data_size, TRUE);
}
struct utt_cache_item *
utt_cache_query (struct utt_cache *cache, gchar *name)
{
struct cache_node *children, *node;
struct utt_cache_item *item = NULL;
gchar **vector;
gint i;
if (!(cache && cache->root && validate_cache_name (name))) {
return NULL;
}
children = cache->root->children;
vector = g_strsplit (name, "/", 0);
for (i = 0; vector[i]; i++) {
node = cache_children_find_name (children, vector[i]);
if (!node) {
break;
}
children = node->children;
}
g_strfreev (vector);
if (node) {
item = g_new0 (struct utt_cache_item, 1);
item->data = node->data;
item->data_size = node->data_size;
}
return item;
}
| C | CL | 4fe60705eaf6613f25ca4420dba35457c7b44fd79ad60e0b11fc5b63559a8874 |
/*
* ISDA CDS Standard Model
*
* Copyright (C) 2009 International Swaps and Derivatives Association, Inc.
* Developed and supported in collaboration with Markit
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the ISDA CDS Standard Model Public License.
*/
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include "bastypes.h"
#include "convert.h"
#include "ldate.h"
#ifdef __cplusplus
extern "C"
{
#endif
typedef enum
{
JPMCDS_SINGLE_REFIX,
} TSwapType;
typedef enum
{
JPMCDS_NO_STUB,
JPMCDS_BACK_STUB,
JPMCDS_FRONT_STUB,
JPMCDS_TWO_STUB
} TStubType;
/*f
***************************************************************************
** Creates a date schedule for one stream of a swap.
***************************************************************************
*/
TCouponDateList* JpmcdsNewCouponDatesSwap(
TDate startDate, /* (I) Effective date of stream */
TDate matDate, /* (I) Maturity date of stream */
TDateInterval *couponInterval, /* (I) Time between payments */
TBoolean adjustLastAccDate, /* (I) Maturity date adjusted */
TBoolean inArrears, /* (I) Arrears setting flag */
int payOffsetDays, /* (I) Days from acc end to payment */
int resetOffsetDays, /* (I) Days from accrual to reset */
TBoolean stubAtEnd, /* (I) TRUE=back stub,FALSE=front stub*/
TBoolean longStub, /* (I) TRUE=long stub,FALSE=short stub*/
TDate firstRollDate, /* (I) Date of first cashflow */
TDate lastRollDate, /* (I) Acc start of final period */
TDate fullFirstCoupDate, /* (I) Acc start of first period */
long payBadDayConv, /* (I) Bad day convention for payment*/
long accBadDayConv, /* (I) Bad day convention for accrual*/
long resetBadDayConv, /* (I) Bad day convention for resets*/
char *holidayFile); /* (I) See JpmcdsBusinessDay */
/*f
***************************************************************************
** Creates a new empty TCouponDateList.
***************************************************************************
*/
TCouponDateList* JpmcdsNewEmptyCouponDateList(int numPeriods);
/*f
***************************************************************************
** Frees a TCouponDateList.
***************************************************************************
*/
void JpmcdsFreeCouponDateList
(TCouponDateList *theSchedule); /* (I) */
/*f
***************************************************************************
** Checks the details for a stream schedule.
***************************************************************************
*/
int JpmcdsCouponDateListCheck(TCouponDateList *schedule);
/*f
***************************************************************************
** Generate a list of unadjusted coupon dates for the stream.
***************************************************************************
*/
int JpmcdsGenerateUnadjDates(
TDate startDate,
TDate matDate,
TDateInterval *couponInterval,
TBoolean stubAtEnd,
TBoolean longStub,
TDate firstRollDate,
TDate lastRollDate,
TDateList **dateList,
long *stubInfo);
#ifdef __cplusplus
}
#endif
#endif /* SCHEDULE_H */
| C | CL | 7e1488c2a7fd796baec93ae98a7d16b5c6da3738722f15c7caca4749b5ce7b55 |
/*
* llib little C library
* BSD licence
* Copyright Steve Donovan, 2013
*/
#ifndef _LLIB_VALUE_H
#define _LLIB_VALUE_H
#include "obj.h"
typedef enum ValueType_ {
ValueNull = 0,
ValueRef = 0x100,
ValueString = ValueRef + 1,
ValueError= ValueRef + 2,
ValueFloat = 1,
ValueInt = 2,
ValueValue = ValueRef + 3,
ValuePointer = 3,
ValueBool = 4
} ValueType;
typedef void *PValue;
#define value_is_list(v) list_object(v)
#define value_is_array(v) obj_is_array(v)
#define value_is_map(v) map_object(v)
#define value_errorf(fmt,...) value_error(str_fmt(fmt,__VA_ARGS__))
#define value_as_int(P) (int)(*(long long*)(P))
#define value_as_float(P) (*(double*)(P))
#define value_as_bool(P) (*(bool*)(P))
#define value_as_string(P) ((char*)P)
bool value_is_string(PValue v);
bool value_is_error(PValue v);
PValue value_error (const char *msg);
bool value_is_float(PValue v);
PValue value_float (double x);
bool value_is_int(PValue v);
PValue value_int (long long i);
bool value_is_bool(PValue v);
PValue value_bool (bool i);
bool value_is_box(PValue v);
bool value_is_simple_map(PValue v);
PValue value_parse(const char *str, ValueType type);
const char *value_tostring(PValue v);
#endif
| C | CL | ad8145e14214f5325376a24a6c85e69d12ab2205123448d0a44cd16cbc4c2d00 |
/*
SDL_ps2_main.c, [email protected]
*/
#include "SDL_config.h"
#ifdef __PS2__
#include "SDL_main.h"
#include "SDL_error.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <kernel.h>
#include <sifrpc.h>
#include <iopcontrol.h>
#include <sbv_patches.h>
#include <ps2_filesystem_driver.h>
#ifdef main
#undef main
#endif
__attribute__((weak)) void reset_IOP()
{
SifInitRpc(0);
while (!SifIopReset(NULL, 0)) {
}
while (!SifIopSync()) {
}
}
static void prepare_IOP()
{
reset_IOP();
SifInitRpc(0);
sbv_patch_enable_lmb();
sbv_patch_disable_prefix_check();
sbv_patch_fileio();
}
static void init_drivers()
{
init_ps2_filesystem_driver();
}
static void deinit_drivers()
{
deinit_ps2_filesystem_driver();
}
int main(int argc, char *argv[])
{
int res;
char cwd[FILENAME_MAX];
prepare_IOP();
init_drivers();
getcwd(cwd, sizeof(cwd));
waitUntilDeviceIsReady(cwd);
res = SDL_main(argc, argv);
deinit_drivers();
return res;
}
#endif /* _PS2 */
/* vi: set ts=4 sw=4 expandtab: */
| C | CL | 21e0629b62d4ec8c5f938c18269a3d79c95709a77f839114d10df8a7a9966e13 |
#ifndef _PQ_PARSE_HEADER_SEEN
#define _PQ_PARSE_HEADER_SEEN
#define COLORFUL_OUTPUT
#include "colorful_output.h"
#include "pq_records.h" // Include for all code linking pq_parse
// Constants
#define PQ_HH 1
#define PQ_HH_TEXT "HydraHarp"
#define PQ_PH 2
#define PQ_PH_TEXT "PicoHarp 300"
#define PQ_HH_V1 1
#define PQ_HH_V1_TEXT "1.0"
#define PQ_HH_V2 2
#define PQ_HH_V2_TEXT "2.0"
#define PQ_PH_V2 2
#define PQ_PH_V2_TEXT "2.0"
#define PQ_HH_MAX_CHANNELS 10
#define PQ_T2_MODE 2
#define PQ_T3_MODE 3
#define PTU_FILE 10
// Errors
#define PQ_DONE_PARSING 1
#define PQ_FILETYPE_INSTRUMENT_NOT_RECOGNIZED -1
#define PQ_FILETYPE_VERSION_NOT_RECOGNIZED -2
#define PQ_ILLEGAL_IDENTIFIER -3
// New Definitions and Structures for PTU files
// THESE TAG HEADERS STUFF ARE FROM THE PICOQUANT
// some important Tag Idents (TTagHead.Ident) that we will need to read the most common content of a PTU file
// check the output of this program and consult the tag dictionary if you need more
#define TTTRTagTTTRRecType "TTResultFormat_TTTRRecType"
#define TTTRTagNumRecords "TTResult_NumberOfRecords" // Number of TTTR Records in the File;
#define TTTRTagRes "MeasDesc_Resolution" // Resolution for the Dtime (T3 Only)
#define TTTRTagGlobRes "MeasDesc_GlobalResolution" // Global Resolution of TimeTag(T2) /NSync (T3)
#define TTTRInputChannels "HW_InpChannels" // Number of input channels
#define TTTRSyncRate "TTResult_SyncRate" // Number of input channels
#define FileTagEnd "Header_End" // Always appended as last tag (BLOCKEND)
// TagTypes (TTagHead.Typ)
#define tyEmpty8 0xFFFF0008
#define tyBool8 0x00000008
#define tyInt8 0x10000008
#define tyBitSet64 0x11000008
#define tyColor8 0x12000008
#define tyFloat8 0x20000008
#define tyTDateTime 0x21000008
#define tyFloat8Array 0x2001FFFF
#define tyAnsiString 0x4001FFFF
#define tyWideString 0x4002FFFF
#define tyBinaryBlob 0xFFFFFFFF
// RecordTypes
#define rtPicoHarpT3 0x00010303 // (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $03 (PicoHarp)
#define rtPicoHarpT2 0x00010203 // (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $03 (PicoHarp)
#define rtHydraHarpT3 0x00010304 // (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $04 (HydraHarp)
#define rtHydraHarpT2 0x00010204 // (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $04 (HydraHarp)
#define rtHydraHarp2T3 0x01010304 // (SubID = $01 ,RecFmt: $01) (V2), T-Mode: $03 (T3), HW: $04 (HydraHarp)
#define rtHydraHarp2T2 0x01010204 // (SubID = $01 ,RecFmt: $01) (V2), T-Mode: $02 (T2), HW: $04 (HydraHarp)
#define rtTimeHarp260NT3 0x00010305 // (SubID = $00 ,RecFmt: $01) (V2), T-Mode: $03 (T3), HW: $05 (TimeHarp260N)
#define rtTimeHarp260NT2 0x00010205 // (SubID = $00 ,RecFmt: $01) (V2), T-Mode: $02 (T2), HW: $05 (TimeHarp260N)
#define rtTimeHarp260PT3 0x00010306 // (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T3), HW: $06 (TimeHarp260P)
#define rtTimeHarp260PT2 0x00010206 // (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $06 (TimeHarp260P)
#pragma pack(8) //structure alignment to 8 byte boundaries
// A Tag entry
struct TgHd {
char Ident[32]; // Identifier of the tag
int Idx; // Index for multiple tags or -1
unsigned int Typ; // Type of tag ty..... see const section
long long TagValue; // Value of tag.
} TagHead;
// First 16 bytes determine what we do with rest of file (.xt2/.xt3 vs. .ptu)
static union {
struct {
char Magic[8];
char Version[8];
};
char instrument[16];
} pq_identifier;
// Structures for parsing header
static struct {
char version[6];
char creator_name[18];
char creator_version[12];
char datetime[18];
char crlf[2];
char comments[256];
int32_t num_curves; // Irrelevant
int32_t num_record_bits; // 32 in all known file versions
} pq_file_text;
typedef struct {
int32_t map_to;
int32_t show;
} pq_curve_t;
typedef struct {
int32_t disp_linlog;
uint32_t disp_info[4];
pq_curve_t disp_curves[8];
} pq_dispblock_t;
typedef struct {
float start;
float step;
float end;
} pq_params_t;
typedef struct {
int32_t mode;
int32_t num_per_curve;
int32_t time;
int32_t wait_time;
} pq_repeat_block_t;
typedef struct {
int32_t model_code;
int32_t version_code;
} pq_hh_moduleinfo_t;
typedef struct {
int32_t module_index;
int32_t cfd_level;
int32_t cfd_zero_cross;
int32_t offset;
} pq_hh_chan_t;
static struct {
int32_t sync_rate; // in Hz
int32_t stop_after; // in ms
int32_t stop_reason; // 0=timeover, 1=manual, 2=overflow, 3=error
int32_t image_header_size;
int64_t num_records;
} pq_hh_tttr;
pq_hh_chan_t pq_hh_chanblock[PQ_HH_MAX_CHANNELS];
int32_t pq_hh_rates[PQ_HH_MAX_CHANNELS];
static struct {
int32_t active_curve; // Irrelevant for tttr modes
int32_t meas_mode; // 0=interactive, 1=reserved, 2=T2, 3=T3
int32_t meas_sub_mode; // 0=oscilloscope, 1=integration, 2=TRES
int32_t binning; // Irrelevant for tttr modes
double resolution; // in ps
int32_t offset; // Irrelevant for tttr modes
int32_t acquire_time; // in ms
uint32_t stop_at_num_counts; // Irrelevant for tttr modes
int32_t stop_on_overflow; // Irrelevant for tttr modes
int32_t restart; // Irrelevant for tttr modes
pq_dispblock_t dispblock;
pq_params_t params[3];
pq_repeat_block_t repeat; //Irrelevant for tttr modes
char script_name[20];
char hardware_ident[16];
char hardware_part_num[8];
int32_t hardware_serial;
int32_t num_modules;
pq_hh_moduleinfo_t modules_info[10];
double base_resolution; // in ps
int64_t inputs_enabled; // bitfield for enabled inputs
int32_t num_input_channels;
int32_t clock_source; // 0=internal, 1=external
int32_t external_devices; // bitfield
int32_t marker_settings; // bitfield
int32_t sync_divider;
int32_t sync_cfd_level; // in mV
int32_t sync_cfd_zerocross; // in mV
int32_t sync_offset; // in ps
} pq_hh_header;
typedef struct {
int32_t input_type; // 0=custom, 1=NIM, 2=TTL
int32_t input_level; // in mV
int32_t input_edge; // 0=falling, 1=rising
int32_t cfd_present; // 0=no, 1=yes
int32_t cfd_level; // in mV
int32_t cfd_zero_cross; // in mV
} pq_ph_router_info_t;
// Note: as of PicoHarp file version 2.0, pq_ph_board_info occurs only once in a file, but in
// later versions this may change.
typedef struct {
char hardware_name[16]; // Currently "PicoHarp 300"
char hardware_version[8]; // Currently "1.0" or "2.0"
int32_t hardware_serial;
int32_t sync_divider; // Note that chan0 == sync
int32_t chan0_cfd_zerocross; // in mV
int32_t chan0_cfd_level; // in mV
int32_t chan1_cfd_zerocross; // in mV
int32_t chan1_cfd_level; // in mV
float resolution; // In nanoseconds!!!
int32_t router_model; // 0=none, 1=PHR_402, 2=PHR_403, 3=PHR_800
int32_t router_enabled; // 0=disabled, 1=enabled
pq_ph_router_info_t router_info[4]; // As of version 2.0, number of router channels must be 4.
} pq_ph_board_info_t;
static struct {
int32_t num_routing_channels; // 1 or 4
int32_t num_boards; // Currently 1, but may change in future. See comment above pq_ph_board_info
int32_t active_curve; // Irrelevant for tttr modes
int32_t meas_mode; // 0=interactive, 1=reserved, 2=T2, 3=T3
int32_t meas_sub_mode; // 0=oscilloscope, 1=integration, 2=TRES
int32_t binning; // Irrelevant for tttr modes, but notable that it's called RangeNo in PicoHarp manual
int32_t offset; // Irrelevant for tttr modes
int32_t acquire_time; // in ms
int32_t stop_at_num_counts; // Irrelevant for tttr modes
int32_t stop_on_overflow; // Irrelevant for tttr modes
int32_t restart; // Irrelevant for tttr modes
pq_dispblock_t dispblock; // Irrelevant for tttr modes
pq_params_t params[3]; // Irrelevant for tttr modes
pq_repeat_block_t repeat; //Irrelevant for tttr modes
char ScriptName[20];
pq_ph_board_info_t board_info;
// This is where the T2/T3 header begins
int32_t external_devices; // Bitwise coded
int32_t reserved[2];
int32_t chan0_inp_rate;
int32_t chan1_inp_rate;
int32_t stop_after; // in ms
int32_t stop_reason; // 0=timeover, 1=manual, 2=overflow
int32_t num_records;
int32_t image_header_size;
} pq_ph_header;
typedef uint32_t pq_image_header_record;
// This is the output format
typedef struct {
int32_t instrument;
int32_t fmt_version;
int32_t meas_mode;
ttd_t resolution;
int32_t sync_rate;
ttd_t sync_period;
size_t num_records;
size_t num_channels;
} pq_fileinfo_t;
// Function API
int pq_parse_header(FILE *fp, pq_fileinfo_t *file_info);
int pq_parse_filetype(FILE *fp, pq_fileinfo_t *file_info);
void pq_print_file_info(pq_fileinfo_t *file_info);
#endif // _PQ_PARSE_HEADER_SEEN
| C | CL | 7a40c0be8592354d063416281e99b828095e26fbe24c003ffaed8a16593e1596 |
/**
* @file EXTI.h
* @brief EXTI.h
* @author bespoon.com
* @date 30/1/2015
*/
/*
* Copyright (C) Bespoon 2014-2015. No Part of the source code shall be
* reproduced, transmitted, distributed, used nor modified in any way without
* the express prior written authorization of Bespoon.
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __HAL_EXTI_H
#define __HAL_EXTI_H
void HAL_EXTI_DeInit( void);
void HAL_EXTI_Init (void);
void HAL_EXTI_LowPower (void);
#endif /* __HAL_EXTI_H */
| C | CL | 9cba3d8355277ac10b984095587cf916db5d120a6cd566938918b22e531ee472 |
/*
* Automatically Generated from Mathematica.
* Thu 8 Apr 2021 07:50:09 GMT+08:00
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "H_ankle_joint_right_src.h"
#ifdef _MSC_VER
#define INLINE __forceinline /* use __forceinline (VC++ specific) */
#else
#define INLINE static __inline__ /* use standard inline */
#endif
/**
* Copied from Wolfram Mathematica C Definitions file mdefs.hpp
* Changed marcos to inline functions (Eric Cousineau)
*/
INLINE double Power(double x, double y) { return pow(x, y); }
INLINE double Sqrt(double x) { return sqrt(x); }
INLINE double Abs(double x) { return fabs(x); }
INLINE double Exp(double x) { return exp(x); }
INLINE double Log(double x) { return log(x); }
INLINE double Sin(double x) { return sin(x); }
INLINE double Cos(double x) { return cos(x); }
INLINE double Tan(double x) { return tan(x); }
INLINE double Csc(double x) { return 1.0/sin(x); }
INLINE double Sec(double x) { return 1.0/cos(x); }
INLINE double ArcSin(double x) { return asin(x); }
INLINE double ArcCos(double x) { return acos(x); }
/* update ArcTan function to use atan2 instead. */
INLINE double ArcTan(double x, double y) { return atan2(y,x); }
INLINE double Sinh(double x) { return sinh(x); }
INLINE double Cosh(double x) { return cosh(x); }
INLINE double Tanh(double x) { return tanh(x); }
#define E 2.71828182845904523536029
#define Pi 3.14159265358979323846264
#define Degree 0.01745329251994329576924
/*
* Sub functions
*/
static void output1(double *p_output1,const double *var1)
{
double t472;
double t670;
double t465;
double t482;
double t679;
double t1110;
double t645;
double t760;
double t910;
double t445;
double t1120;
double t1182;
double t1212;
double t1339;
double t1066;
double t1273;
double t1309;
double t338;
double t1416;
double t1485;
double t1530;
double t1600;
double t1633;
double t1729;
double t1753;
double t1803;
double t1827;
double t1973;
double t1317;
double t1848;
double t1854;
double t325;
double t2003;
double t2011;
double t2079;
double t2140;
double t1896;
double t2103;
double t2104;
double t252;
double t2186;
double t2269;
double t2392;
double t125;
double t2689;
double t2749;
double t2844;
double t2916;
double t2929;
double t2939;
double t2910;
double t2943;
double t2959;
double t3017;
double t3025;
double t3035;
double t3048;
double t3051;
double t3072;
double t2976;
double t3082;
double t3091;
double t3122;
double t3130;
double t3139;
double t2498;
double t3110;
double t3168;
double t3226;
double t3290;
double t3376;
double t3386;
double t3542;
double t3544;
double t3604;
double t3666;
double t3676;
double t3685;
double t3697;
double t3715;
double t3719;
double t3623;
double t3764;
double t3809;
double t3843;
double t3859;
double t3877;
double t3840;
double t3901;
double t3927;
double t3932;
double t3937;
double t3968;
double t2112;
double t2446;
double t2465;
double t2510;
double t2550;
double t2571;
double t3281;
double t3413;
double t3453;
double t3464;
double t3499;
double t3508;
double t3929;
double t3994;
double t4002;
double t4070;
double t4097;
double t4115;
double t4602;
double t4650;
double t5007;
double t5009;
double t5354;
double t5358;
double t5486;
double t5504;
double t5556;
double t5576;
double t4289;
double t4294;
double t4326;
double t4651;
double t4669;
double t4679;
double t4709;
double t4743;
double t4884;
double t4890;
double t4902;
double t4932;
double t4944;
double t4987;
double t4998;
double t5019;
double t5052;
double t5059;
double t5280;
double t5287;
double t5312;
double t5365;
double t5401;
double t5406;
double t5430;
double t5453;
double t5462;
double t5505;
double t5520;
double t5521;
double t5528;
double t5534;
double t5548;
double t5616;
double t5647;
double t5655;
double t5680;
double t5704;
double t5711;
double t4327;
double t4338;
double t4354;
double t4374;
double t4378;
double t4394;
t472 = Cos(var1[5]);
t670 = Sin(var1[3]);
t465 = Cos(var1[3]);
t482 = Sin(var1[4]);
t679 = Sin(var1[5]);
t1110 = Sin(var1[13]);
t645 = t465*t472*t482;
t760 = t670*t679;
t910 = t645 + t760;
t445 = Cos(var1[13]);
t1120 = -1.*t472*t670;
t1182 = t465*t482*t679;
t1212 = t1120 + t1182;
t1339 = Cos(var1[15]);
t1066 = t445*t910;
t1273 = -1.*t1110*t1212;
t1309 = t1066 + t1273;
t338 = Sin(var1[15]);
t1416 = Cos(var1[14]);
t1485 = Cos(var1[4]);
t1530 = t1416*t465*t1485;
t1600 = Sin(var1[14]);
t1633 = t1110*t910;
t1729 = t445*t1212;
t1753 = t1633 + t1729;
t1803 = t1600*t1753;
t1827 = t1530 + t1803;
t1973 = Cos(var1[16]);
t1317 = t338*t1309;
t1848 = t1339*t1827;
t1854 = t1317 + t1848;
t325 = Sin(var1[16]);
t2003 = t1339*t1309;
t2011 = -1.*t338*t1827;
t2079 = t2003 + t2011;
t2140 = Cos(var1[17]);
t1896 = -1.*t325*t1854;
t2103 = t1973*t2079;
t2104 = t1896 + t2103;
t252 = Sin(var1[17]);
t2186 = t1973*t1854;
t2269 = t325*t2079;
t2392 = t2186 + t2269;
t125 = Sin(var1[18]);
t2689 = t472*t670*t482;
t2749 = -1.*t465*t679;
t2844 = t2689 + t2749;
t2916 = t465*t472;
t2929 = t670*t482*t679;
t2939 = t2916 + t2929;
t2910 = t445*t2844;
t2943 = -1.*t1110*t2939;
t2959 = t2910 + t2943;
t3017 = t1416*t1485*t670;
t3025 = t1110*t2844;
t3035 = t445*t2939;
t3048 = t3025 + t3035;
t3051 = t1600*t3048;
t3072 = t3017 + t3051;
t2976 = t338*t2959;
t3082 = t1339*t3072;
t3091 = t2976 + t3082;
t3122 = t1339*t2959;
t3130 = -1.*t338*t3072;
t3139 = t3122 + t3130;
t2498 = Cos(var1[18]);
t3110 = -1.*t325*t3091;
t3168 = t1973*t3139;
t3226 = t3110 + t3168;
t3290 = t1973*t3091;
t3376 = t325*t3139;
t3386 = t3290 + t3376;
t3542 = t445*t1485*t472;
t3544 = -1.*t1485*t1110*t679;
t3604 = t3542 + t3544;
t3666 = -1.*t1416*t482;
t3676 = t1485*t472*t1110;
t3685 = t445*t1485*t679;
t3697 = t3676 + t3685;
t3715 = t1600*t3697;
t3719 = t3666 + t3715;
t3623 = t338*t3604;
t3764 = t1339*t3719;
t3809 = t3623 + t3764;
t3843 = t1339*t3604;
t3859 = -1.*t338*t3719;
t3877 = t3843 + t3859;
t3840 = -1.*t325*t3809;
t3901 = t1973*t3877;
t3927 = t3840 + t3901;
t3932 = t1973*t3809;
t3937 = t325*t3877;
t3968 = t3932 + t3937;
t2112 = t252*t2104;
t2446 = t2140*t2392;
t2465 = t2112 + t2446;
t2510 = t2140*t2104;
t2550 = -1.*t252*t2392;
t2571 = t2510 + t2550;
t3281 = t252*t3226;
t3413 = t2140*t3386;
t3453 = t3281 + t3413;
t3464 = t2140*t3226;
t3499 = -1.*t252*t3386;
t3508 = t3464 + t3499;
t3929 = t252*t3927;
t3994 = t2140*t3968;
t4002 = t3929 + t3994;
t4070 = t2140*t3927;
t4097 = -1.*t252*t3968;
t4115 = t4070 + t4097;
t4602 = -1.*t1416;
t4650 = 1. + t4602;
t5007 = -1.*t1339;
t5009 = 1. + t5007;
t5354 = -1.*t1973;
t5358 = 1. + t5354;
t5486 = -1.*t2140;
t5504 = 1. + t5486;
t5556 = -1.*t2498;
t5576 = 1. + t5556;
t4289 = t2498*t2465;
t4294 = t125*t2571;
t4326 = t4289 + t4294;
t4651 = -0.049*t4650;
t4669 = -0.135*t1600;
t4679 = 0. + t4651 + t4669;
t4709 = 0.135*t1110;
t4743 = 0. + t4709;
t4884 = -1.*t445;
t4890 = 1. + t4884;
t4902 = -0.135*t4890;
t4932 = 0. + t4902;
t4944 = -0.135*t4650;
t4987 = 0.049*t1600;
t4998 = 0. + t4944 + t4987;
t5019 = -0.09*t5009;
t5052 = 0.049*t338;
t5059 = 0. + t5019 + t5052;
t5280 = -0.049*t5009;
t5287 = -0.09*t338;
t5312 = 0. + t5280 + t5287;
t5365 = -0.049*t5358;
t5401 = -0.21*t325;
t5406 = 0. + t5365 + t5401;
t5430 = -0.21*t5358;
t5453 = 0.049*t325;
t5462 = 0. + t5430 + t5453;
t5505 = -0.2707*t5504;
t5520 = 0.0016*t252;
t5521 = 0. + t5505 + t5520;
t5528 = -0.0016*t5504;
t5534 = -0.2707*t252;
t5548 = 0. + t5528 + t5534;
t5616 = 0.0184*t5576;
t5647 = -0.7055*t125;
t5655 = 0. + t5616 + t5647;
t5680 = -0.7055*t5576;
t5704 = -0.0184*t125;
t5711 = 0. + t5680 + t5704;
t4327 = t2498*t3453;
t4338 = t125*t3508;
t4354 = t4327 + t4338;
t4374 = t2498*t4002;
t4378 = t125*t4115;
t4394 = t4374 + t4378;
p_output1[0]=t125*t2465 - 1.*t2498*t2571;
p_output1[1]=t125*t3453 - 1.*t2498*t3508;
p_output1[2]=t125*t4002 - 1.*t2498*t4115;
p_output1[3]=0.;
p_output1[4]=t4326;
p_output1[5]=t4354;
p_output1[6]=t4394;
p_output1[7]=0.;
p_output1[8]=-1.*t1416*t1753 + t1485*t1600*t465;
p_output1[9]=-1.*t1416*t3048 + t1485*t1600*t670;
p_output1[10]=-1.*t1416*t3697 - 1.*t1600*t482;
p_output1[11]=0.;
p_output1[12]=0. - 0.7055*(-1.*t125*t2465 + t2498*t2571) + 0.0184*t4326 - 0.1305*(t1416*t1753 - 1.*t1485*t1600*t465) + t1485*t465*t4679 + t1212*t4932 + t1753*t4998 + t1309*t5059 + t1827*t5312 + t1854*t5406 + t2079*t5462 + t2104*t5521 + t2392*t5548 + t2465*t5655 + t2571*t5711 + t4743*t910 + var1[0];
p_output1[13]=0. - 0.7055*(-1.*t125*t3453 + t2498*t3508) + 0.0184*t4354 + t2844*t4743 + t2939*t4932 + t3048*t4998 + t2959*t5059 + t3072*t5312 + t3091*t5406 + t3139*t5462 + t3226*t5521 + t3386*t5548 + t3453*t5655 + t3508*t5711 + t1485*t4679*t670 - 0.1305*(t1416*t3048 - 1.*t1485*t1600*t670) + var1[1];
p_output1[14]=0. - 0.7055*(-1.*t125*t4002 + t2498*t4115) + 0.0184*t4394 + t1485*t472*t4743 - 1.*t4679*t482 - 0.1305*(t1416*t3697 + t1600*t482) + t3697*t4998 + t3604*t5059 + t3719*t5312 + t3809*t5406 + t3877*t5462 + t3927*t5521 + t3968*t5548 + t4002*t5655 + t4115*t5711 + t1485*t4932*t679 + var1[2];
p_output1[15]=1.;
}
void H_ankle_joint_right_src(double *p_output1, const double *var1)
{
/* Call Subroutines */
output1(p_output1, var1);
}
| C | CL | 0d47cf331731151cdb8b0cc326cced052572203cc6cf90911e2f9b2158395ab4 |
/**
* \file
* \brief Simple heap allocator.
*
* This file implements a very simple heap allocator, based on K&R malloc.
*/
/*
* Copyright (c) 2008, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
*/
#include <barrelfish/barrelfish.h>
#include <barrelfish/heap.h>
/**
* \brief Initialise a new heap
*
* \param heap Heap structure to be filled in
* \param buf Memory buffer out of which to allocate
* \param buflen Size of buffer
* \param morecore_func Function to call to increase heap, or NULL
*/
void heap_init(struct heap *heap, void *buf, size_t buflen,
Morecore_func_t morecore_func)
{
assert(heap != NULL);
assert(buf != NULL);
assert(buflen > sizeof(union heap_header));
// Initialise base header (nothing allocated)
heap->base.s.ptr = heap->freep = &heap->base;
heap->base.s.size = 0;
heap->morecore_func = morecore_func;
// Insert freelist header into new memory buffer
union heap_header *h = buf;
h->s.size = buflen / sizeof(union heap_header);
// Add header to freelist
heap_free(heap, (void *)(h + 1));
}
/**
* \brief Equivalent of malloc; allocates memory out of given heap.
*
* \returns NULL on failure
*/
void *heap_alloc(struct heap *heap, size_t nbytes)
{
union heap_header *p, *prevp;
unsigned nunits;
nunits = (nbytes + sizeof(union heap_header) - 1)
/ sizeof(union heap_header) + 1;
prevp = heap->freep;
assert(prevp != NULL);
for (p = prevp->s.ptr;; prevp = p, p = p->s.ptr) {
if (p->s.size >= nunits) { /* big enough */
if (p->s.size == nunits) { /* exactly */
prevp->s.ptr = p->s.ptr;
} else { /* allocate tail end */
p->s.size -= nunits;
p += p->s.size;
p->s.size = nunits;
}
heap->freep = prevp;
return (void *) (p + 1);
}
if (p == heap->freep) { /* wrapped around free list */
/* try morecore, if we have one */
if (heap->morecore_func == NULL
|| (p = (union heap_header *)
heap->morecore_func(heap, nunits)) == NULL) {
return NULL; /* none left */
}
}
}
}
/**
* \brief Equivalent of free: put block back in free list.
*/
void heap_free(struct heap *heap, void *ap)
{
union heap_header *bp, *p;
assert(heap != NULL);
assert(heap->freep != NULL);
if (ap == NULL) {
return;
}
bp = (union heap_header *) ap - 1; /* point to block header */
for (p = heap->freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) {
if (p >= p->s.ptr && (bp > p || bp < p->s.ptr)) {
break; /* freed block at start or end of arena */
}
}
if (bp + bp->s.size == p->s.ptr) { /* join to upper nbr */
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else {
bp->s.ptr = p->s.ptr;
}
if (p + p->s.size == bp) { /* join to lower nbr */
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else {
p->s.ptr = bp;
}
heap->freep = p;
}
/**
* \brief Allocate and map in one or more pages of memory
*/
static void *pages_alloc(size_t pages)
{
assert(!"not implemented");
return NULL;
}
/**
* \brief sbrk() equivalent.
*
* This function allocates at least the amount given by 'nu' in sizeof(::Header)
* byte units. It returns a pointer to the freelist header of the memory region.
* NULL is returned when out of memory.
*
* \param nu Number of memory units (1 unit == sizeof(::Header) bytes)
*
* \return Pointer to freelist header of new memory region or NULL on out of
* memory.
*/
union heap_header *heap_default_morecore(struct heap *heap, unsigned nu)
{
union heap_header *up;
size_t nb = ROUND_UP(nu * sizeof(union heap_header),
BASE_PAGE_SIZE);
// Allocate requested number of pages and insert freelist header
up = (union heap_header*)pages_alloc(DIVIDE_ROUND_UP(nb, BASE_PAGE_SIZE));
up->s.size = nb / sizeof(union heap_header);
// Add header to freelist
heap_free(heap, (void *)(up + 1));
return up;
}
| C | CL | e12a9228adb81d59d1344f2fc66907c6e83d57b9e036663193e42094acf10a22 |
/**
* 定义目标语言中的一等对象的实现
*/
#pragma once
#include "base/hash.h"
#include "base/vector.h"
#include <stdbool.h>
#include <stdint.h>
typedef enum {
OBJECT_BOOL,
OBJECT_CHAR,
OBJECT_FUN,
OBJECT_INT,
OBJECT_MAP,
OBJECT_NIL,
OBJECT_SYMBOL,
OBJECT_VECTOR,
} OBJECT_T;
typedef enum {
FUN_NATIVE,
FUN_UDF,
} FUN_T;
typedef struct {
OBJECT_T type;
union {
bool bool_value;
int integer;
uint32_t char_value;
struct {
FUN_T type;
union {
struct {
int arity;
void *impl;
} native;
struct {
int entry;
} udf;
} u;
} fun;
hash_table_t *map;
char *symbol;
vector_t *vector;
} u;
} object_t;
#define OBJECT_BOOL_VALUE(x) ((x)->u.bool_value)
#define OBJECT_CHAR_VALUE(x) ((x)->u.char_value)
#define OBJECT_FUN_TYPE(x) ((x)->u.fun.type)
#define OBJECT_FUN_NATIVE_ARITY(x) ((x)->u.fun.u.native.arity)
#define OBJECT_FUN_NATIVE_IMPL(x) ((x)->u.fun.u.native.impl)
#define OBJECT_FUN_UDF_ENTRY(x) ((x)->u.fun.u.udf.entry)
#define OBJECT_INT_VALUE(x) ((x)->u.integer)
#define OBJECT_SYMBOL_NAME(x) ((x)->u.symbol)
extern object_t *object_bool_new(bool);
extern object_t *object_char_new(uint32_t);
extern object_t *object_fun_native_new(int, void *);
extern object_t *object_fun_udf_new(int);
extern object_t *object_int_new(int);
extern object_t *object_map_new(void);
extern object_t *object_nil_new(void);
extern object_t *object_symbol_new(const char *);
extern object_t *object_symbol_intern(const char *);
extern object_t *object_vector_new(void);
extern void object_print(object_t *);
| C | CL | 78b438d4697eb730a60bb1698a6fe59e64f514361e8d07c610362ff81554dd16 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_10__ TYPE_4__ ;
typedef struct TYPE_9__ TYPE_3__ ;
typedef struct TYPE_8__ TYPE_2__ ;
typedef struct TYPE_7__ TYPE_1__ ;
/* Type definitions */
typedef int /*<<< orphan*/ uint8_t ;
struct st_quicly_default_encrypt_cid_t {TYPE_4__* cid_encrypt_ctx; } ;
struct TYPE_8__ {int len; int /*<<< orphan*/ cid; } ;
typedef TYPE_2__ quicly_cid_t ;
struct TYPE_9__ {int master_id; int thread_id; int path_id; int /*<<< orphan*/ node_id; } ;
typedef TYPE_3__ quicly_cid_plaintext_t ;
typedef int /*<<< orphan*/ quicly_cid_encryptor_t ;
struct TYPE_10__ {TYPE_1__* algo; } ;
struct TYPE_7__ {int block_size; } ;
/* Variables and functions */
int /*<<< orphan*/ assert (int) ;
int /*<<< orphan*/ generate_reset_token (struct st_quicly_default_encrypt_cid_t*,void*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ ptls_cipher_encrypt (TYPE_4__*,int /*<<< orphan*/ ,int /*<<< orphan*/ *,int) ;
int /*<<< orphan*/ * quicly_encode32 (int /*<<< orphan*/ *,int) ;
int /*<<< orphan*/ * quicly_encode64 (int /*<<< orphan*/ *,int /*<<< orphan*/ ) ;
__attribute__((used)) static void default_encrypt_cid(quicly_cid_encryptor_t *_self, quicly_cid_t *encrypted, void *reset_token,
const quicly_cid_plaintext_t *plaintext)
{
struct st_quicly_default_encrypt_cid_t *self = (void *)_self;
uint8_t buf[16], *p;
/* encode */
p = buf;
switch (self->cid_encrypt_ctx->algo->block_size) {
case 8:
break;
case 16:
p = quicly_encode64(p, plaintext->node_id);
break;
default:
assert(!"unexpected block size");
break;
}
p = quicly_encode32(p, plaintext->master_id);
p = quicly_encode32(p, (plaintext->thread_id << 8) | plaintext->path_id);
assert(p - buf == self->cid_encrypt_ctx->algo->block_size);
/* generate CID */
ptls_cipher_encrypt(self->cid_encrypt_ctx, encrypted->cid, buf, self->cid_encrypt_ctx->algo->block_size);
encrypted->len = self->cid_encrypt_ctx->algo->block_size;
/* generate stateless reset token if requested */
if (reset_token != NULL)
generate_reset_token(self, reset_token, encrypted->cid);
} | C | CL | f8cc3a12202fbdf91632ddc0004e393847b8b39aa97c1db7627f3eae2e8de801 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ xml_node_t ;
typedef int /*<<< orphan*/ xml_namespace_t ;
struct xml_node_ctx {int dummy; } ;
/* Variables and functions */
int /*<<< orphan*/ xml_node_add_child (struct xml_node_ctx*,int /*<<< orphan*/ *,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ * xml_node_create (struct xml_node_ctx*,int /*<<< orphan*/ *,int /*<<< orphan*/ *,char*) ;
int /*<<< orphan*/ * xml_node_create_root (struct xml_node_ctx*,char*,char*,int /*<<< orphan*/ **,char*) ;
xml_node_t * soap_build_envelope(struct xml_node_ctx *ctx, xml_node_t *node)
{
xml_node_t *envelope, *body;
xml_namespace_t *ns;
envelope = xml_node_create_root(
ctx, "http://www.w3.org/2003/05/soap-envelope", "soap12", &ns,
"Envelope");
if (envelope == NULL)
return NULL;
body = xml_node_create(ctx, envelope, ns, "Body");
xml_node_add_child(ctx, body, node);
return envelope;
} | C | CL | 6df7529ee68573740ee1457e3680d82c5428a708d4480b1edae5eb61615d80bb |
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI */
#ifndef _Included_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI
#define _Included_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI
* Method: setFilterSelect
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_setFilterSelect
(JNIEnv *, jclass, jint, jint);
/*
* Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI
* Method: getFilterSelect
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_getFilterSelect
(JNIEnv *, jclass, jint);
/*
* Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI
* Method: setFilterPeriod
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_setFilterPeriod
(JNIEnv *, jclass, jint, jint);
/*
* Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI
* Method: getFilterPeriod
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_getFilterPeriod
(JNIEnv *, jclass, jint);
#ifdef __cplusplus
}
#endif
#endif
| C | CL | 6c6f4cbd10b88b60f7cb005e0e118b0ed33309ffb11d2768ac83a04ffca2dd2f |
/**********************************************************************************************************************
* COPYRIGHT
* -------------------------------------------------------------------------------------------------------------------
* \verbatim
*
* This software is copyright protected and proprietary to Vector Informatik GmbH.
* Vector Informatik GmbH grants to you only those rights as set out in the license conditions.
* All other rights remain with Vector Informatik GmbH.
* \endverbatim
* -------------------------------------------------------------------------------------------------------------------
* FILE DESCRIPTION
* -------------------------------------------------------------------------------------------------------------------
* File: Rte_EcuM.h
* Config: WLC.dpa
* ECU-Project: WLC
*
* Generator: MICROSAR RTE Generator Version 4.20.0
* RTE Core Version 1.20.0
* License: CBD1900162
*
* Description: Application header file for SW-C <EcuM>
*********************************************************************************************************************/
/* double include prevention */
#ifndef _RTE_ECUM_H
# define _RTE_ECUM_H
# ifndef RTE_CORE
# ifdef RTE_APPLICATION_HEADER_FILE
# error Multiple application header files included.
# endif
# define RTE_APPLICATION_HEADER_FILE
# ifndef RTE_PTR2ARRAYBASETYPE_PASSING
# define RTE_PTR2ARRAYBASETYPE_PASSING
# endif
# endif
# ifdef __cplusplus
extern "C"
{
# endif /* __cplusplus */
/* include files */
# include "Rte_EcuM_Type.h"
# include "Rte_DataHandleType.h"
# define EcuM_START_SEC_CODE
# include "EcuM_MemMap.h" /* PRQA S 5087 */ /* MD_MSR_19.1 */
/**********************************************************************************************************************
* Runnable entities
*********************************************************************************************************************/
# ifndef RTE_CORE
# define RTE_RUNNABLE_EcuM_MainFunction EcuM_MainFunction
# define RTE_RUNNABLE_GetBootTarget EcuM_GetBootTarget
# define RTE_RUNNABLE_GetLastShutdownTarget EcuM_GetLastShutdownTarget
# define RTE_RUNNABLE_GetShutdownCause EcuM_GetShutdownCause
# define RTE_RUNNABLE_GetShutdownTarget EcuM_GetShutdownTarget
# define RTE_RUNNABLE_SelectBootTarget EcuM_SelectBootTarget
# define RTE_RUNNABLE_SelectShutdownCause EcuM_SelectShutdownCause
# define RTE_RUNNABLE_SelectShutdownTarget EcuM_SelectShutdownTarget
# endif
FUNC(void, EcuM_CODE) EcuM_MainFunction(void); /* PRQA S 0850, 3451 */ /* MD_MSR_19.8, MD_Rte_3451 */
FUNC(Std_ReturnType, EcuM_CODE) EcuM_GetBootTarget(P2VAR(EcuM_BootTargetType, AUTOMATIC, RTE_ECUM_APPL_VAR) BootTarget); /* PRQA S 0850, 3451 */ /* MD_MSR_19.8, MD_Rte_3451 */
FUNC(Std_ReturnType, EcuM_CODE) EcuM_GetLastShutdownTarget(P2VAR(EcuM_StateType, AUTOMATIC, RTE_ECUM_APPL_VAR) target, P2VAR(EcuM_ModeType, AUTOMATIC, RTE_ECUM_APPL_VAR) resetSleepMode); /* PRQA S 0850, 3451 */ /* MD_MSR_19.8, MD_Rte_3451 */
FUNC(Std_ReturnType, EcuM_CODE) EcuM_GetShutdownCause(P2VAR(EcuM_ShutdownCauseType, AUTOMATIC, RTE_ECUM_APPL_VAR) shutdownCause); /* PRQA S 0850, 3451 */ /* MD_MSR_19.8, MD_Rte_3451 */
FUNC(Std_ReturnType, EcuM_CODE) EcuM_GetShutdownTarget(P2VAR(EcuM_StateType, AUTOMATIC, RTE_ECUM_APPL_VAR) target, P2VAR(EcuM_ModeType, AUTOMATIC, RTE_ECUM_APPL_VAR) resetSleepMode); /* PRQA S 0850, 3451 */ /* MD_MSR_19.8, MD_Rte_3451 */
FUNC(Std_ReturnType, EcuM_CODE) EcuM_SelectBootTarget(EcuM_BootTargetType BootTarget); /* PRQA S 0850, 3451 */ /* MD_MSR_19.8, MD_Rte_3451 */
FUNC(Std_ReturnType, EcuM_CODE) EcuM_SelectShutdownCause(EcuM_ShutdownCauseType shutdownCause); /* PRQA S 0850, 3451 */ /* MD_MSR_19.8, MD_Rte_3451 */
FUNC(Std_ReturnType, EcuM_CODE) EcuM_SelectShutdownTarget(EcuM_StateType targetState, EcuM_ModeType resetSleepMode); /* PRQA S 0850, 3451 */ /* MD_MSR_19.8, MD_Rte_3451 */
# define EcuM_STOP_SEC_CODE
# include "EcuM_MemMap.h" /* PRQA S 5087 */ /* MD_MSR_19.1 */
# ifndef RTE_CORE
/**********************************************************************************************************************
* Application errors
*********************************************************************************************************************/
# define RTE_E_EcuM_BootTarget_E_NOT_OK (1U)
# define RTE_E_EcuM_ShutdownTarget_E_NOT_OK (1U)
# endif /* !defined(RTE_CORE) */
# ifdef __cplusplus
} /* extern "C" */
# endif /* __cplusplus */
#endif /* _RTE_ECUM_H */
/**********************************************************************************************************************
MISRA 2004 violations and justifications
*********************************************************************************************************************/
/* module specific MISRA deviations:
MD_Rte_3451: MISRA rule: 8.8
Reason: Schedulable entities are declared by the RTE and also by the BSW modules.
Risk: No functional risk.
Prevention: Not required.
*/
| C | CL | 280456d256e39d4add30d4dab1d15e6590d3603603d3ce33edc103ef39e02b26 |
/**
* @file ci_flash_data_info.c
* @brief flash data struct
* @version
* @date
*
* @copyright Copyright (c) 2019 Chipintelli Technology Co., Ltd.
*
*/
#include <stdint.h>
#include <ci112x_system.h>
#include <string.h>
#include <stdlib.h>
#include "ci_flash_data_info.h"
#include "ci_log.h"
#include "dichotomy_find.h"
#include "flash_rw_process.h"
#include "ci_nvdata_manage.h"
#include "ci112x_spiflash.h"
#include "command_file_reader.h"
#include "sdk_default_config.h"
#include "FreeRTOS.h"
#include "task.h"
#include "command_info.h"
#include "firmware_updater.h"
static partition_table_t partition_table = {0};
/**
* @brief Get the fw version object
*
* @param product_version 包含硬件版本号, 软件版本号
* @return uint32_t RETURN_ERR 获取失败, RETURN_OK 获取成功
*/
int32_t get_fw_version(product_version_t *product_version)
{
if(product_version == NULL)
{
return RETURN_ERR;
}
product_version->hard_ware_version = partition_table.hard_ware_version;
product_version->soft_ware_version = partition_table.soft_ware_version;
return RETURN_OK;
}
uint32_t get_group_addr(uint32_t partition_addr, uint16_t group_id)
{
uint32_t ret = (uint32_t)-1;
uint16_t group_number;
//读取分组数量
post_read_flash((char *)&group_number,partition_addr,sizeof(group_number));
uint32_t table_size = 2 + sizeof(group_header_t)*group_number;
group_table_t *p_group_table = pvPortMalloc(table_size);
if (p_group_table)
{
//读取分组列表
post_read_flash((char *)p_group_table,partition_addr,table_size);
for(int i = 0;i < group_number;i++)
{
if (p_group_table->group_header[i].group_id == group_id)
{
ret = p_group_table->group_header[i].group_addr;
ret += partition_addr;
}
}
vPortFree(p_group_table);
}
else
{
ci_logerr(LOG_FLASH_CTL, "not enough memory\n");
}
return ret;
}
file_table_t * get_file_table(uint32_t group_addr)
{
uint16_t file_number;
//读取指定分组中文件的数量
post_read_flash((char *)&file_number,group_addr,sizeof(file_number));
uint32_t table_size = 2 + sizeof(file_header_t)*file_number;
file_table_t *p_file_table = pvPortMalloc(table_size);
if (p_file_table)
{
//读取分组列表
post_read_flash((char *)p_file_table,group_addr,table_size);
return p_file_table;
}
else
{
ci_logerr(LOG_FLASH_CTL, "not enough memory\n");
}
return NULL;
}
void release_file_table(file_table_t * p_file_table)
{
vPortFree(p_file_table);
}
uint32_t get_file_addr(uint32_t group_addr, uint16_t file_id, uint32_t *p_file_addr, uint32_t *p_file_size)
{
uint32_t ret = 0;
uint16_t file_number;
//读取指定分组中文件的数量
post_read_flash((char *)&file_number,group_addr,sizeof(file_number));
uint32_t table_size = 2 + sizeof(file_header_t)*file_number;
file_table_t *p_file_table = get_file_table(group_addr);
if (p_file_table)
{
//读取分组列表
post_read_flash((char *)p_file_table,group_addr,table_size);
for(int i = 0;i < file_number;i++)
{
if (p_file_table->file_header[i].file_id == file_id)
{
if (p_file_addr)
{
*p_file_addr = p_file_table->file_header[i].file_addr;
}
if (p_file_size)
{
*p_file_size = p_file_table->file_header[i].file_size;
}
ret = 1;
}
}
vPortFree(p_file_table);
}
return ret;
}
#if (COPYRIGHT_VERIFICATION && (ENCRYPT_ALGORITHM == ENCRYPT_USER_DEFINE))
static int user_encrypt(char * in_buffer, int in_len, char *out_buffer, int out_len)
{
//以下为实例代码,加密强度很低,用户可以根据自己的加密算法修改
for (int i = 0;i < in_len;i++)
{
out_buffer[i] = in_buffer[i] ^ 0x5A;
}
}
#endif
uint32_t ci_flash_data_info_init(uint8_t default_model_group_id)
{
#if COPYRIGHT_VERIFICATION
{
#if (ENCRYPT_ALGORITHM == ENCRYPT_DEFAULT)
char *password = "mynameispassword";
if (!copyright_verification2(password, strlen(password)))
{
//请修改以下校验失败处理,以下方式很容易被破解,仅供参考
while(1)
{
mprintf("encrypt check failed\n");
}
}
#elif (ENCRYPT_ALGORITHM == ENCRYPT_USER_DEFINE)
if (!copyright_verification1(user_encrypt, 16))
{
//请修改以下校验失败处理,以下方式很容易被破解,仅供参考
while(1)
{
mprintf("encrypt check failed\n");
}
}
#endif
}
#endif
//读取分区信息表
post_read_flash((char *)&partition_table,FILECONFIG_SPIFLASH_START_ADDR,sizeof(partition_table_t));
//检查分区有效性,如果有无效分区,返回错误,应用程序应该进入升级模式
if (0 != partition_table.dnn_model_status ||
0 != partition_table.asr_cmd_model_status ||
0 != partition_table.voice_status ||
0 != partition_table.user_file_status)
{
#if OTA_ENABLE
// 进入升级模式,升级完成后会重启系统,所以以下调用不会返回。
firmware_update_main(OTA_UART_BAUDRATE);
#else
return 2;
#endif
}
cinv_init(partition_table.nv_data_offset, partition_table.nv_data_size);
ci_loginfo(LOG_NVDATA,"nv_data_offset = %08x\n",partition_table.nv_data_offset);
ci_loginfo(LOG_NVDATA,"nv_data_size = %08x\n",partition_table.nv_data_size);
uint32_t file_addr;
if (get_file_addr(partition_table.user_file_offset, COMMAND_INFO_FILE_ID, &file_addr, NULL))
{
file_addr += partition_table.user_file_offset;
return cmd_info_init(file_addr, partition_table.voice_offset, default_model_group_id);
}
return 1;
}
uint32_t get_dnn_addr_by_id(uint16_t dnn_file_id, uint32_t *p_dnn_addr, uint32_t *p_dnn_size)
{
if (get_file_addr(partition_table.dnn_model_offset, dnn_file_id, p_dnn_addr, p_dnn_size))
{
*p_dnn_addr += partition_table.dnn_model_offset;
return 1;
}
return 0;
}
uint32_t get_asr_addr_by_id(int asr_id, uint32_t *p_asr_addr, uint32_t *p_asr_size)
{
if(((asr_id+1)>cmd_file_get_model_number())||(asr_id<0))
{
mprintf("asr_mode id err\n");
return 0;
}
if (get_file_addr(partition_table.asr_cmd_model_offset, asr_id, p_asr_addr, p_asr_size))
{
mprintf("partition_table.asr_cmd_model_offset : 0x%x asr_id is %d\n",partition_table.asr_cmd_model_offset,asr_id);
*p_asr_addr += partition_table.asr_cmd_model_offset;
}
else
{
mprintf("get_file_addr:asr err\n");
return 0;
}
return 1;
}
uint32_t get_current_model_addr(uint32_t *p_dnn_addr, uint32_t *p_dnn_size, uint32_t *p_asr_addr, uint32_t *p_addr_size)
{
uint32_t dnn_file_id, asr_file_id;
cmd_info_get_cur_model_id(&dnn_file_id, &asr_file_id, NULL); //读取模型ID
uint32_t failed = 0;
//Get DNN address and size.
if (get_file_addr(partition_table.dnn_model_offset, dnn_file_id, p_dnn_addr, p_dnn_size))
{
*p_dnn_addr += partition_table.dnn_model_offset;
}
else
{
failed = 1;
}
if (get_file_addr(partition_table.asr_cmd_model_offset, asr_file_id, p_asr_addr, p_addr_size))
{
*p_asr_addr += partition_table.asr_cmd_model_offset;
}
else
{
failed = 1;
}
if (failed)
{
while(1)mprintf("Error data in flash\n");
}
else
{
return 0;
}
}
uint32_t get_userfile_addr(uint16_t file_id, uint32_t *p_file_addr, uint32_t *p_file_size)
{
if ((NULL == p_file_addr) ||(NULL == p_file_size))
{
return 1;
}
if (get_file_addr(partition_table.user_file_offset, file_id, p_file_addr, p_file_size))
{
(*p_file_addr) += partition_table.user_file_offset;
return 0;
}
return 1;
}
#define CFR_CATCH_SIZE (1024*4)
typedef struct cached_flash_reader_info{
int32_t start_addr_in_flash;
uint8_t *cached_reader_buffer;
int32_t cached_start_offset;
int32_t cached_end_offset;
}cached_flash_reader_info_t;
static cached_flash_reader_info_t cached_flash_reader_info = {-CFR_CATCH_SIZE, NULL, 0,0};
uint32_t cached_flash_reader_init(uint32_t start_addr_in_flash)
{
if (cached_flash_reader_info.cached_reader_buffer)
{
free(cached_flash_reader_info.cached_reader_buffer);
}
cached_flash_reader_info.cached_reader_buffer = malloc(CFR_CATCH_SIZE);
if (cached_flash_reader_info.cached_reader_buffer)
{
cached_flash_reader_info.start_addr_in_flash = start_addr_in_flash;
return 1;
}
return 0;
}
uint32_t cached_flash_reader_read(int32_t read_offset, uint8_t *read_buffer, uint32_t read_length)
{
uint32_t first_read_length = 0;
uint32_t second_read_length = 0;
if (read_offset >= cached_flash_reader_info.cached_end_offset || read_offset < cached_flash_reader_info.cached_start_offset)
{
int32_t start_offset = cached_flash_reader_info.start_addr_in_flash + read_offset;
//int32_t mod = start_offset % CFR_CATCH_SIZE;
//start_offset = start_offset - mod;
cached_flash_reader_info.cached_start_offset = start_offset - cached_flash_reader_info.start_addr_in_flash;
cached_flash_reader_info.cached_end_offset = cached_flash_reader_info.cached_start_offset + CFR_CATCH_SIZE;
post_read_flash((char *)cached_flash_reader_info.cached_reader_buffer, start_offset, CFR_CATCH_SIZE);
}
uint32_t left_length = cached_flash_reader_info.cached_end_offset - read_offset;
if (read_length < left_length)
{
first_read_length = read_length;
second_read_length = 0;
}
else
{
first_read_length = left_length;
second_read_length = read_length - left_length;
}
memcpy(read_buffer, cached_flash_reader_info.cached_reader_buffer+read_offset-cached_flash_reader_info.cached_start_offset, first_read_length);
if (second_read_length)
{
int32_t start_offset = cached_flash_reader_info.start_addr_in_flash + read_offset;
//int32_t mod = start_offset % CFR_CATCH_SIZE;
//start_offset = start_offset - mod + CFR_CATCH_SIZE;
cached_flash_reader_info.cached_start_offset = start_offset - cached_flash_reader_info.start_addr_in_flash;
cached_flash_reader_info.cached_end_offset = cached_flash_reader_info.cached_start_offset + CFR_CATCH_SIZE;
post_read_flash((char *)cached_flash_reader_info.cached_reader_buffer, start_offset, CFR_CATCH_SIZE);
memcpy(read_buffer + first_read_length, cached_flash_reader_info.cached_reader_buffer+first_read_length, second_read_length);
return read_length;
}
return first_read_length;
}
uint32_t cached_flash_reader_destroy(void)
{
if (cached_flash_reader_info.cached_reader_buffer)
{
free(cached_flash_reader_info.cached_reader_buffer);
}
cached_flash_reader_info.cached_reader_buffer = NULL;
cached_flash_reader_info.cached_start_offset = -1;
cached_flash_reader_info.cached_end_offset = -1;
return 0;
}
| C | CL | 62ee708e3c5bada66729f37ac71526d998fbff40fbb0d702c20fb96cd7cfb9d1 |
/**
******************************************************************************
* @file max7312.c burn in system
* @author h&h
* @version
* @date 2018
* @brief max7312 driver
******************************************************************************
**/
#include "include.h"
#define MAX7312_I2C_PORT I2C1
#define MAX7312_DEVICE_NUM 2U
#define MAX7312_DEVICE_0_ADDR 0x4E
#define MAX7312_DEVICE_1_ADDR 0x46
#define MAX7312_DEVICE_2_ADDR 0x42
#define MAX7312_DEVICE_ALL_OUTPUT 0x00
#define MAX7312_DEVICE_ALL_INTPUT 0xFF
#define MAX7312_DEVICE_ALL_HI 0xFF
#define MAX7312_DEVICE_ALL_LO 0x00
#define MAX7312_COMMAND_00 0x00 /*input port 1*/
#define MAX7312_COMMAND_01 0x01 /*input port 2*/
#define MAX7312_COMMAND_02 0x02 /*output port 1*/
#define MAX7312_COMMAND_03 0x03 /*ouput port 2*/
#define MAX7312_COMMAND_04 0x04 /*port 1 inversion*/
#define MAX7312_COMMAND_05 0x05 /*port 2 inversion*/
#define MAX7312_COMMAND_06 0x06 /*port 1 config*/
#define MAX7312_COMMAND_07 0x07 /*port 2 config*/
#define MAX7312_COMMAND_08 0x08 /*timeout*/
#define MAX7312_COMMAND_FF 0xFF /*reserve*/
typedef struct
{
uint8_t max7312_cmd_00;
uint8_t max7312_cmd_01;
uint8_t max7312_cmd_02;
uint8_t max7312_cmd_03;
uint8_t max7312_cmd_04;
uint8_t max7312_cmd_05;
uint8_t max7312_cmd_06;
uint8_t max7312_cmd_07;
uint8_t max7312_cmd_08;
uint8_t max7312_cmd_FF;
}max7312_command_tst;
const max7312_command_tst max7312_command_cst =
{
MAX7312_COMMAND_00,
MAX7312_COMMAND_01,
MAX7312_COMMAND_02,
MAX7312_COMMAND_03,
MAX7312_COMMAND_04,
MAX7312_COMMAND_05,
MAX7312_COMMAND_06,
MAX7312_COMMAND_07,
MAX7312_COMMAND_08,
MAX7312_COMMAND_FF
};
typedef struct
{
uint8_t input[2];
uint8_t output[2];
uint8_t polarity[2];
uint8_t configuration[2];
}max7312_reg_tst;
max7312_reg_tst max7312_reg_st[MAX7312_DEVICE_NUM];
const uint8_t max7312_dev_addr_ca[MAX7312_DEVICE_NUM] =
{
MAX7312_DEVICE_0_ADDR,
MAX7312_DEVICE_1_ADDR,
};
static uint8_t Max7312_Write_Register(uint8_t dev_id, uint8_t reg, uint8_t* w_data);
static uint8_t Max7312_Read_Register(uint8_t dev_id, uint8_t reg, uint8_t* r_data);
static uint8_t Max7312_Write_Reg_Check(uint8_t dev_id, uint8_t reg, uint8_t *w_data, uint8_t *r_data);
void Max7312_init(void)
{
uint8_t res;
res = Max7312_Set_All_Port_Output(0);
res &= Max7312_Set_All_Port_Lo(0);
res &= Max7312_Set_All_Port_Output(1);
res &= Max7312_Set_All_Port_Lo(1);
}
uint8_t Max7312_Set_All_Port_Output(uint8_t dev_id)
{
uint8_t ret1, ret2;
ret1 = Max7312_Set_Port1_IO(dev_id, MAX7312_DEVICE_ALL_OUTPUT);
ret2 = Max7312_Set_Port2_IO(dev_id, MAX7312_DEVICE_ALL_OUTPUT);
return (ret1 & ret2);
}
uint8_t Max7312_Set_All_Port_Input(uint8_t dev_id)
{
uint8_t ret1, ret2;
ret1 = Max7312_Set_Port1_IO(dev_id, MAX7312_DEVICE_ALL_INTPUT);
ret2 = Max7312_Set_Port2_IO(dev_id, MAX7312_DEVICE_ALL_INTPUT);
return (ret1 & ret2);
}
uint8_t Max7312_Set_All_Port_Hi(uint8_t dev_id)
{
uint8_t ret1, ret2;
ret1 = Max7312_Set_Port1_HiLo(dev_id, MAX7312_DEVICE_ALL_HI);
ret2 = Max7312_Set_Port2_HiLo(dev_id, MAX7312_DEVICE_ALL_HI);
return (ret1 & ret2);
}
uint8_t Max7312_Set_All_Port_Lo(uint8_t dev_id)
{
uint8_t ret1, ret2;
ret1 = Max7312_Set_Port1_HiLo(dev_id, MAX7312_DEVICE_ALL_LO);
ret2 = Max7312_Set_Port2_HiLo(dev_id, MAX7312_DEVICE_ALL_LO);
return (ret1 & ret2);
}
uint8_t Max7312_Set_Port1_IO(uint8_t dev_id, uint8_t io)
{
uint8_t ret = ERROR;
uint8_t reg;
uint8_t w_data;
uint8_t *r_data = max7312_reg_st[dev_id].configuration;
w_data = io;
reg = max7312_command_cst.max7312_cmd_06;
ret = Max7312_Write_Reg_Check(dev_id, reg, &w_data, &r_data[0]);
return ret;
}
uint8_t Max7312_Set_Port2_IO(uint8_t dev_id, uint8_t io)
{
uint8_t ret = ERROR;
uint8_t reg;
uint8_t w_data;
uint8_t *r_data = max7312_reg_st[dev_id].configuration;
w_data = io;
reg = max7312_command_cst.max7312_cmd_07;
ret = Max7312_Write_Reg_Check(dev_id, reg, &w_data, &r_data[1]);
return ret;
}
uint8_t Max7312_Set_Port1_HiLo(uint8_t dev_id, uint8_t io_st)
{
uint8_t ret = ERROR;
uint8_t reg;
uint8_t w_data;
uint8_t *r_data = max7312_reg_st[dev_id].output;
w_data = io_st;
reg = max7312_command_cst.max7312_cmd_02;
ret = Max7312_Write_Reg_Check(dev_id, reg, &w_data, &r_data[0]);
return ret;
}
uint8_t Max7312_Set_Port2_HiLo(uint8_t dev_id, uint8_t io_st)
{
uint8_t ret = ERROR;
uint8_t reg;
uint8_t w_data;
uint8_t *r_data = max7312_reg_st[dev_id].output;
w_data = io_st;
reg = max7312_command_cst.max7312_cmd_03;
ret = Max7312_Write_Reg_Check(dev_id, reg, &w_data, &r_data[1]);
return ret;
}
static uint8_t Max7312_Write_Reg_Check(uint8_t dev_id, uint8_t reg, uint8_t *w_data, uint8_t *r_data)
{
uint8_t ret;
uint8_t *wdata = w_data;
uint8_t *rdata = r_data;
ret = Max7312_Write_Register(dev_id, reg, w_data);
if(SUCCESS == ret)
{
ret = Max7312_Read_Register(dev_id, reg, r_data );
if(SUCCESS == ret)
{
if( *wdata == *rdata )
{
ret = SUCCESS;
}
else
{
ret = ERROR;
}
}
else
{
ret = ERROR;
}
}
else
{
ret = ERROR;
}
return ret;
}
static uint8_t Max7312_Write_Register(uint8_t dev_id, uint8_t reg, uint8_t* w_data)
{
uint8_t ret;
uint8_t SlaveAddress;
if(dev_id > MAX7312_DEVICE_NUM)
return ERROR;
if((void*)0 == w_data)
return ERROR;
SlaveAddress = max7312_dev_addr_ca[dev_id];
ret = I2c_command_write(MAX7312_I2C_PORT, reg, 1, SlaveAddress, w_data);
if(SUCCESS == ret)
{
ret = SUCCESS;
}
else
{
ret = ERROR;
}
return ret;
}
static uint8_t Max7312_Read_Register(uint8_t dev_id, uint8_t reg, uint8_t* r_data)
{
uint8_t ret;
uint8_t SlaveAddress;
if(dev_id > MAX7312_DEVICE_NUM)
return ERROR;
if((void*)0 == r_data)
return ERROR;
SlaveAddress = max7312_dev_addr_ca[dev_id];
ret = I2c_command_read(MAX7312_I2C_PORT, reg, 1, SlaveAddress, r_data );
if(SUCCESS == ret)
{
ret = SUCCESS;
}
else
{
ret = ERROR;
}
return ret;
}
#ifdef DEBUG_MAX7312
void test_max7312(void)
{
/* Enable peripheral clocks --------------------------------------------------*/
/* GPIOB Periph clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
/* I2C1 and I2C2 Periph clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C2, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
/* Configure I2C2 pins: SCL and SDA ----------------------------------------*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
I2C_InitTypeDef I2C_InitStructure;
I2C_InitStructure.I2C_Mode = I2C_Mode_SMBusHost;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x31;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 400000;
I2C_Init(I2C2, &I2C_InitStructure);
/* disable I2C1 PEC Transmission */
I2C_CalculatePEC(I2C2, DISABLE);
I2C_Cmd(I2C2,ENABLE);
Max7312_Set_All_Port_Output(0);
Max7312_Set_All_Port_Lo(0);
Max7312_Set_All_Port_Hi(0);
Max7312_Set_All_Port_Output(1);
Max7312_Set_All_Port_Lo(1);
Max7312_Set_All_Port_Hi(1);
Max7312_Set_All_Port_Output(2);
Max7312_Set_All_Port_Lo(2);
Max7312_Set_All_Port_Hi(2);
#if 0
while(1)
{
Max7312_Set_All_Port_Output(0);
Delay_ms(400);
Max7312_Set_All_Port_Hi(0);
Delay_ms(400);
Max7312_Set_All_Port_Lo(0);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0x1234);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0xa3f9);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0xc580);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0xa3f9);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0x1482);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0x4474);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0x9685);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0xfea0);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0x5583);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0xa3f9);
Delay_ms(400);
Max7312_Set_Port_IO(0,0xFF00);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0x1234);
Delay_ms(400);
Max7312_Set_Port_HiLo(0, 0xa3f9);
Delay_ms(400);
Max7312_Set_All_Port_Output(1);
Delay_ms(400);
Max7312_Set_All_Port_Hi(1);
Delay_ms(400);
Max7312_Set_All_Port_Lo(1);
Max7312_Set_Port_HiLo(1, 0x1234);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0xa3f9);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0xc580);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0xa3f9);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0x1482);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0x4474);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0x9685);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0xfea0);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0x5583);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0xa3f9);
Delay_ms(400);
Max7312_Set_Port_IO(1,0xFF00);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0x1234);
Delay_ms(400);
Max7312_Set_Port_HiLo(1, 0xa3f9);
Delay_ms(400);
Max7312_Set_All_Port_Output(2);
Delay_ms(400);
Max7312_Set_All_Port_Hi(2);
Delay_ms(400);
Max7312_Set_All_Port_Lo(2);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0x1234);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0xa3f9);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0xc580);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0xa3f9);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0x1482);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0x4474);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0x9685);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0xfea0);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0x5583);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0xa3f9);
Delay_ms(400);
Max7312_Set_Port_IO(2,0xFF00);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0x1234);
Delay_ms(400);
Max7312_Set_Port_HiLo(2, 0xa3f9);
Delay_ms(400);
}
#endif
}
#endif
/******************* (C) COPYRIGHT *****END OF FILE****/ | C | CL | a75aee37a9942bed1b94e325cb6c1cf3a39330bba9f290645c12f911502c23f4 |
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2019 RDK Management
*
* 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.
*/
#ifndef GDIAL_APP_H_
#define GDIAL_APP_H_
#include <glib.h>
#include <glib-object.h>
G_BEGIN_DECLS
#define GDIAL_TYPE_APP (gdial_app_get_type ())
G_DECLARE_FINAL_TYPE (GDialApp, gdial_app, GDIAL, APP, GObject)
#define GDIAL_APP_NAME "name"
#define GDIAL_APP_STATE "state"
#define GDIAL_APP_INSTANCE_ID "instance-id"
#define GDIAL_APP_GET_STATE(app) ((app)->state)
#define GDIAL_APP_INSTANCE_NONE (G_MAXINT-1)
typedef enum {
GDIAL_APP_STATE_STOPPED = 0,
GDIAL_APP_STATE_HIDE,
GDIAL_APP_STATE_RUNNING,
GDIAL_APP_STATE_MAX
} GDialAppState;
typedef enum {
GDIAL_APP_ERROR_NONE = 0,
GDIAL_APP_ERROR_NOT_IMPLEMENTED = GDIAL_APP_STATE_MAX,
GDIAL_APP_ERROR_FORBIDDEN,
GDIAL_APP_ERROR_UNAUTH,
GDIAL_APP_ERROR_IMPL_ = 0x1000,
GDIAL_APP_ERROR_BAD_REQUEST,
GDIAL_APP_ERROR_UNAVAILABLE,
GDIAL_APP_ERROR_INVALID,
GDIAL_APP_ERROR_INTERNAL,
GDIAL_APP_ERROR_MAX,
} GDialAppError;
typedef gint gdial_instance_id_t;
struct _GDialApp {
GObject parent;
gchar *name;
GDialAppState state;
gint instance_id;
const gchar *instance_sid;
};
GType gdial_app_get_type (void);
GDialApp* gdial_app_new(const char *app_name);
GDialAppError gdial_app_start(GDialApp *app, const gchar *payload, const gchar *query, const gchar *additional_data_url, gpointer state_cb_data);
GDialAppError gdial_app_hide(GDialApp *app);
GDialAppError gdial_app_resume(GDialApp *app);
GDialAppError gdial_app_stop(GDialApp *app);
GDialAppError gdial_app_state(GDialApp *app);
const gchar *gdial_app_state_to_string(GDialAppState state);
gint gdial_app_get_instance_id(GDialApp *app);
GDialApp *gdial_app_find_instance_by_name(const gchar *app_name);
GDialApp *gdial_app_find_instance_by_instance_id(gint instance_id);
gchar *gdial_app_get_additional_dial_data_by_key(GDialApp *app, const gchar *key);
void gdial_app_set_additional_dial_data(GDialApp *app, GHashTable *additional_dial_data);
GHashTable *gdial_app_get_additional_dial_data(GDialApp *app);
void gdial_app_refresh_additional_dial_data(GDialApp *app);
void gdial_app_clear_additional_dial_data(GDialApp *app);
gchar * gdial_app_state_response_new(GDialApp *app, const gchar *dial_ver, const gchar *xmlns, int *len);
GDIAL_STATIC gboolean gdial_app_write_additional_dial_data(const gchar *app_name, const gchar *data, size_t length);
GDIAL_STATIC gboolean gdial_app_read_additional_dial_data(const gchar *app_name, gchar **data, size_t *length);
GDIAL_STATIC gboolean gdial_app_remove_additional_dial_data_file(const gchar *app_name);
gchar *gdial_app_get_launch_payload(GDialApp *app);
void gdial_app_set_launch_payload(GDialApp *app, const gchar *payload);
void gdial_app_force_shutdown(GDialApp *app);
G_END_DECLS
#endif
| C | CL | 3037fd5328dae9fecdd7ceb75ab7e24f77322c06a56f4bfe9d934126c8d22dd1 |
#include <esp_types.h>
#include "string.h"
#include "esp_log.h"
#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/ip_addr.h"
#include "lwip/api.h"
#include "lwip/netdb.h"
#include "esp_system.h"
#include "platform/platform.h"
#include "tcpip_adapter.h"
#include "esp_alink.h"
#define SOMAXCONN 5
static const char *TAG = "alink_network";
static alink_err_t network_create_socket( pplatform_netaddr_t netaddr, int type, struct sockaddr_in *paddr, int *psock)
{
ALINK_PARAM_CHECK(netaddr == NULL);
ALINK_PARAM_CHECK(paddr == NULL);
ALINK_PARAM_CHECK(psock == NULL);
struct hostent *hp;
uint32_t ip;
alink_err_t ret;
if (NULL == netaddr->host) {
ip = htonl(INADDR_ANY);
} else {
hp = gethostbyname(netaddr->host);
ALINK_ERROR_CHECK(hp == NULL, ALINK_ERR, "gethostbyname ret:%p", hp);
struct ip4_addr *ip4_addr = (struct ip4_addr *)hp->h_addr;
char ipaddr_tmp[64] = {0};
sprintf(ipaddr_tmp, IPSTR, IP2STR(ip4_addr));
ALINK_LOGI("alink server host: %s, ip: %s\n", netaddr->host, ipaddr_tmp);
ip = inet_addr(ipaddr_tmp);
}
*psock = socket(AF_INET, type, 0);
if (*psock < 0) return -1;
memset(paddr, 0, sizeof(struct sockaddr_in));
int opt_val = 1;
ret = setsockopt(*psock, SOL_SOCKET, SO_REUSEADDR, &opt_val, sizeof(opt_val));
ALINK_ERROR_CHECK(ret != 0, ALINK_ERR, "setsockopt SO_REUSEADDR errno: %d", errno);
paddr->sin_addr.s_addr = ip;
paddr->sin_family = AF_INET;
paddr->sin_port = htons( netaddr->port );
return ALINK_OK;
}
void *platform_udp_server_create(_IN_ uint16_t port)
{
struct sockaddr_in addr;
int server_socket;
alink_err_t ret;
platform_netaddr_t netaddr = {NULL, port};
ret = network_create_socket(&netaddr, SOCK_DGRAM, &addr, &server_socket);
ALINK_ERROR_CHECK(ret != ALINK_OK, NULL, "network_create_socket");
ret = bind(server_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
if (-1 == bind(server_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in))) {
platform_udp_close((void *)server_socket);
ALINK_LOGE("socket bind");
perror("socket bind");
return NULL;
}
return (void *)server_socket;
}
void *platform_udp_client_create(void)
{
struct sockaddr_in addr;
int sock;
platform_netaddr_t netaddr = {NULL, 0};
alink_err_t ret;
ret = network_create_socket(&netaddr, SOCK_DGRAM, &addr, &sock);
ALINK_ERROR_CHECK(ret != ALINK_OK, NULL, "network_create_socket");
return (void *)sock;
}
void *platform_udp_multicast_server_create(pplatform_netaddr_t netaddr)
{
ALINK_PARAM_CHECK(netaddr == NULL);
struct sockaddr_in addr;
int sock;
struct ip_mreq mreq;
alink_err_t ret = 0;
platform_netaddr_t netaddr_client = {NULL, netaddr->port};
memset(&addr, 0, sizeof(addr));
memset(&mreq, 0, sizeof(mreq));
ret = network_create_socket(&netaddr_client, SOCK_DGRAM, &addr, &sock);
ALINK_ERROR_CHECK(ret != ALINK_OK, NULL, "network_create_socket");
if (-1 == bind(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr_in))) {
ALINK_LOGE("socket bind, errno: %d", errno);
perror("socket bind");
platform_udp_close((void *)sock);
return NULL;
}
mreq.imr_multiaddr.s_addr = inet_addr(netaddr->host);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, sizeof(mreq)) < 0) {
ALINK_LOGE("setsockopt IP_ADD_MEMBERSHIP");
platform_udp_close((void *)sock);
return NULL;
}
return (void *)sock;
}
void platform_udp_close(void *handle)
{
close((int)handle);
}
int platform_udp_sendto(
_IN_ void *handle,
_IN_ const char *buffer,
_IN_ uint32_t length,
_IN_ pplatform_netaddr_t netaddr)
{
ALINK_PARAM_CHECK((int)handle < 0);
ALINK_PARAM_CHECK(buffer == NULL);
ALINK_PARAM_CHECK(netaddr == NULL);
int ret_code;
struct hostent *hp;
struct sockaddr_in addr;
hp = gethostbyname(netaddr->host);
ALINK_ERROR_CHECK(hp == NULL, ALINK_ERR, "gethostbyname Can't resolute the host address hp:%p", hp);
addr.sin_addr.s_addr = *((u_int *)(hp->h_addr));
//addr.sin_addr.S_un.S_addr = *((u_int *)(hp->h_addr));
addr.sin_family = AF_INET;
addr.sin_port = htons( netaddr->port );
ret_code = sendto((int)handle,
buffer,
length,
0,
(struct sockaddr *)&addr,
sizeof(struct sockaddr_in));
ALINK_ERROR_CHECK(ret_code <= 0, ALINK_ERR, "sendto ret:%d, errno:%d", ret_code, errno);
return ret_code;
}
int platform_udp_recvfrom(
_IN_ void *handle,
_OUT_ char *buffer,
_IN_ uint32_t length,
_OUT_OPT_ pplatform_netaddr_t netaddr)
{
ALINK_PARAM_CHECK((int)handle < 0);
ALINK_PARAM_CHECK(buffer == NULL);
int ret_code;
struct sockaddr_in addr;
unsigned int addr_len = sizeof(addr);
ret_code = recvfrom((int)handle, buffer, length, 0, (struct sockaddr *)&addr, &addr_len);
ALINK_ERROR_CHECK(ret_code <= 0, ALINK_ERR, "recvfrom ret:%d, errno:%d", ret_code, errno);
if (NULL != netaddr) {
netaddr->port = ntohs(addr.sin_port);
if (NULL != netaddr->host) {
strcpy(netaddr->host, inet_ntoa(addr.sin_addr));
}
}
return ret_code;
}
void *platform_tcp_server_create(_IN_ uint16_t port)
{
struct sockaddr_in addr;
int server_socket;
alink_err_t ret = 0;
platform_netaddr_t netaddr = {NULL, port};
ret = network_create_socket(&netaddr, SOCK_DGRAM, &addr, &server_socket);
ALINK_ERROR_CHECK(ret != ALINK_OK, NULL, "network_create_socket");
if (-1 == bind(server_socket, (struct sockaddr *)&addr, sizeof(addr))) {
ALINK_LOGE("bind");
platform_tcp_close((void *)server_socket);
return NULL;
}
if (0 != listen(server_socket, SOMAXCONN)) {
ALINK_LOGE("listen");
platform_tcp_close((void *)server_socket);
return NULL;
}
return (void *)server_socket;
}
void *platform_tcp_server_accept(_IN_ void *server)
{
ALINK_PARAM_CHECK(server == NULL);
struct sockaddr_in addr;
unsigned int addr_length = sizeof(addr);
int new_client;
new_client = accept((int)server, (struct sockaddr*)&addr, &addr_length);
ALINK_ERROR_CHECK(new_client <= 0, NULL, "accept errno:%d", errno);
return (void *)new_client;
}
void *platform_tcp_client_connect(_IN_ pplatform_netaddr_t netaddr)
{
ALINK_PARAM_CHECK(netaddr == NULL);
struct sockaddr_in addr;
int sock;
alink_err_t ret = 0;
ret = network_create_socket(netaddr, SOCK_STREAM, &addr, &sock);
ALINK_ERROR_CHECK(ret != ALINK_OK, NULL, "network_create_socket");
if (-1 == connect(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr_in))) {
ALINK_LOGE("connect errno: %d", errno);
perror("connect");
platform_tcp_close((void *)sock);
return NULL;
}
return (void *)sock;
}
int platform_tcp_send(_IN_ void *handle, _IN_ const char *buffer, _IN_ uint32_t length)
{
ALINK_PARAM_CHECK((int)handle < 0);
ALINK_PARAM_CHECK(buffer == NULL);
int bytes_sent;
bytes_sent = send((int)handle, buffer, length, 0);
ALINK_LOGW()
ALINK_ERROR_CHECK(bytes_sent <= 0, ALINK_ERR, "send ret:%d", bytes_sent);
return bytes_sent;
}
int platform_tcp_recv(_IN_ void *handle, _OUT_ char *buffer, _IN_ uint32_t length)
{
ALINK_PARAM_CHECK((int)handle < 0);
ALINK_PARAM_CHECK(buffer == NULL);
int bytes_received;
bytes_received = recv((int)handle, buffer, length, 0);
ALINK_ERROR_CHECK(bytes_received <= 0, ALINK_ERR, "recv ret:%d", bytes_received);
return bytes_received;
}
void platform_tcp_close(_IN_ void *handle)
{
close((int)handle);
}
int platform_select(void *read_fds[PLATFORM_SOCKET_MAXNUMS],
void *write_fds[PLATFORM_SOCKET_MAXNUMS],
int timeout_ms)
{
ALINK_PARAM_CHECK(read_fds == NULL);
// ALINK_PARAM_CHECK(write_fds == NULL);
int i, ret_code = -1;
struct timeval timeout_value;
struct timeval *ptimeval = &timeout_value;
fd_set *pfd_read_set, *pfd_write_set;
if (PLATFORM_WAIT_INFINITE == timeout_ms) {
ptimeval = NULL;
} else {
ptimeval->tv_sec = timeout_ms / 1000;
ptimeval->tv_usec = (timeout_ms % 1000) * 1000;
}
pfd_read_set = NULL;
pfd_write_set = NULL;
if (NULL != read_fds) {
if (((int *)read_fds)[1] == 0 && ((int *)read_fds)[2] == 0) {
ALINK_LOGD("read_fds: %d %d %d %d",
((int *)read_fds)[0], ((int *)read_fds)[1], ((int *)read_fds)[2], ((int *)read_fds)[3]);
int tmp_fd[PLATFORM_SOCKET_MAXNUMS] = {((int *)read_fds)[0], -1, -1, -1, -1, -1, -1, -1, -1, -1};
memcpy((int *)read_fds, tmp_fd, sizeof(tmp_fd));
}
pfd_read_set = malloc(sizeof(fd_set));
if (NULL == pfd_read_set) {
ALINK_LOGE("pfd_read_set");
goto do_exit;
}
FD_ZERO(pfd_read_set);
for ( i = 0; i < PLATFORM_SOCKET_MAXNUMS; ++i )
{
if ( PLATFORM_INVALID_FD != read_fds[i] )
{
FD_SET((int)read_fds[i], pfd_read_set);
}
}
}
if (NULL != write_fds)
{
pfd_write_set = malloc(sizeof(fd_set));
if (NULL == pfd_write_set) {
ALINK_LOGE("pfd_write_set");
goto do_exit;
}
FD_ZERO(pfd_write_set);
for ( i = 0; i < PLATFORM_SOCKET_MAXNUMS; ++i ) {
if ( PLATFORM_INVALID_FD != write_fds[i] ) {
FD_SET((int)write_fds[i], pfd_write_set);
}
}
}
ret_code = select(FD_SETSIZE, pfd_read_set, pfd_write_set, NULL, ptimeval);
if (ret_code >= 0) {
if (NULL != read_fds) {
for ( i = 0; i < PLATFORM_SOCKET_MAXNUMS; ++i ) {
if (PLATFORM_INVALID_FD != read_fds[i]
&& !FD_ISSET((int)read_fds[i], pfd_read_set)) {
read_fds[i] = PLATFORM_INVALID_FD;
}
}
}
if (NULL != write_fds) {
for ( i = 0; i < PLATFORM_SOCKET_MAXNUMS; ++i ) {
if (PLATFORM_INVALID_FD != write_fds[i]
&& !FD_ISSET((int)write_fds[i], pfd_write_set)) {
write_fds[i] = PLATFORM_INVALID_FD;
}
}
}
}
do_exit:
if (pfd_read_set) free(pfd_read_set);
if (pfd_write_set) free(pfd_write_set);
ALINK_ERROR_CHECK(ret_code < 0, ret_code, "select ret:%d, errno: %d", ret_code, errno);
return ret_code;
}
| C | CL | cde8ce14d3f6dd8540532477dbdbfa6e5dde2f2e61c92e24579a086a199e9a33 |
/*************************************************************************
*
* Copyright 1993 Mentor Graphics Corporation
* All Rights Reserved.
*
* THIS WORK CONTAINS TRADE SECRET AND PROPRIETARY INFORMATION WHICH IS
* THE PROPERTY OF MENTOR GRAPHICS CORPORATION OR ITS LICENSORS AND IS
* SUBJECT TO LICENSE TERMS.
*
*************************************************************************/
/*************************************************************************
* FILE NAME
*
* mib2_sck.c
*
* COMPONENT
*
* MIB II - Socket Group.
*
* DESCRIPTION
*
* This file contain the functions that are responsible for
* maintaining statistics for Socket group.
*
* DATA STRUCTURES
*
* None
*
* FUNCTIONS
*
* MIB2_Socket_List_Information
*
* DEPENDENCIES
*
* nu_net.h
*
*************************************************************************/
#include "networking/nu_net.h"
#if (INCLUDE_MIB2_RFC1213 == NU_TRUE)
#if ( ((MIB2_UDP_INCLUDE == NU_TRUE) && (INCLUDE_UDP == NU_TRUE)) || \
((MIB2_TCP_INCLUDE == NU_TRUE) && (INCLUDE_TCP == NU_TRUE)) )
#if ( (MIB2_TCP_INCLUDE == NU_TRUE) && (INCLUDE_TCP == NU_TRUE) )
extern INT MIB2_Tcp_Compare(UINT32, UINT32, UINT16, UINT16,
UINT32, UINT32, UINT16, UINT16);
extern STATUS MIB2_TcpEntry_GetNext(UINT8 *, UINT32 *, UINT8 *, UINT32 *,
SOCKET_STRUCT *);
#endif /* ( (MIB2_TCP_INCLUDE == NU_TRUE) && (INCLUDE_TCP == NU_TRUE) ) */
#if ( (INCLUDE_UDP == NU_TRUE) && (MIB2_UDP_INCLUDE == NU_TRUE) )
STATUS MIB2_UdpEntry_GetNext(UINT8 *, UINT32 *,
SOCKET_STRUCT *);
INT MIB2_Udp_Compare(UINT32, UINT16, UINT32, UINT16);
#endif /* ( (INCLUDE_UDP == NU_TRUE) && (MIB2_UDP_INCLUDE == NU_TRUE) ) */
/*-----------------------------------------------------------------------
* socket list information
*----------------------------------------------------------------------*/
/*************************************************************************
*
* FUNCTION
*
* MIB2_Socket_List_Information
*
* DESCRIPTION
*
* This function gets a required information after traversing
* socket list.
*
* INPUTS
*
* protocol protocol (TCP/UDP)
* getflag type of request (get or getnext)
* *local_addr local address.
* *local_port local port
* *remote_addr remote address
* *remote_port remote port
* *socket_info the data-structure in which information
* will be returned
*
* OUTPUTS
*
* NU_FALSE if no information are found
* NU_TRUE if approximate information are found
*
*************************************************************************/
STATUS MIB2_Socket_List_Information(INT protocol, UINT8 getflag,
UINT8 *local_addr, UINT32 *local_port,
UINT8 *remote_addr, UINT32 *remote_port,
SOCKET_STRUCT *socket_info)
{
STATUS status;
INT i, result;
#if ( (MIB2_TCP_INCLUDE == NU_FALSE) || (INCLUDE_TCP == NU_FALSE) )
UNUSED_PARAMETER(remote_addr);
UNUSED_PARAMETER(remote_port);
#endif /* ( (MIB2_TCP_INCLUDE == NU_FALSE) || (INCLUDE_TCP == NU_FALSE) ) */
/* Obtain Semaphore, so that changes are not made while looking through
* the table
*/
status = NU_Obtain_Semaphore(&TCP_Resource, NU_SUSPEND);
if (status != NU_SUCCESS)
{
NLOG_Error_Log("Failed to obtain semaphore", NERR_SEVERE,
__FILE__, __LINE__);
NET_DBG_Notify(status, __FILE__, __LINE__,
NU_Current_Task_Pointer(), NU_NULL);
return (NU_NULL);
}
status = NU_FALSE;
/* at least local address should be present in both cases [TCP/UDP] */
if (local_addr)
{
switch (protocol)
{
#if ( (MIB2_TCP_INCLUDE == NU_TRUE) && (INCLUDE_TCP == NU_TRUE) )
/* if the incoming protocol is TCP */
case NU_PROTO_TCP:
/* condition is true if it is a get request */
if (getflag)
{
/* Look for an entry which is equal to the one passed. */
for (i = 0; i < NSOCKETS; i++)
{
/* Check if the protocol of socket list entry is
* TCP
*/
if ( (SCK_Sockets[i] != NU_NULL) &&
(SCK_Sockets[i]->s_protocol == (UINT16)NU_PROTO_TCP) &&
(SCK_Sockets[i]->s_family == NU_FAMILY_IP) )
{
/* call the function to check whether incoming
* parameters matches with the current socket
*/
result = MIB2_Tcp_Compare(IP_ADDR(local_addr),
IP_ADDR(remote_addr),
((UINT16)(*local_port)), ((UINT16)(*remote_port)),
IP_ADDR((SCK_Sockets[i]->s_local_addr.ip_num.is_ip_addrs)),
IP_ADDR((SCK_Sockets[i]->s_foreign_addr.ip_num.is_ip_addrs)),
SCK_Sockets[i]->s_local_addr.port_num,
SCK_Sockets[i]->s_foreign_addr.port_num);
/* if condition is satisfied then return the
* information
*/
if (result == 0)
{
/* copying the information from socket list to
* socket_info
*/
memcpy((VOID*)socket_info, (VOID*)SCK_Sockets[i],
(UINT32)sizeof(struct sock_struct));
status = NU_TRUE;
break;
}
}
} /* end for loop which traverse socket list for all sockets */
}
/* else clause will be true in case of getnext or getbulk request */
else
{
/* call the function to get information of next entry in
* the socket list
*/
status = MIB2_TcpEntry_GetNext(local_addr, local_port,
remote_addr, remote_port,
socket_info);
}
break;
#endif /* ( (MIB2_TCP_INCLUDE == NU_TRUE) && (INCLUDE_TCP == NU_TRUE) ) */
#if ( (MIB2_UDP_INCLUDE == NU_TRUE) && (INCLUDE_UDP == NU_TRUE) )
/* if the incoming protocol is UDP */
case NU_PROTO_UDP:
/* condition is true if it is a get request */
if (getflag)
{
/* Look for an entry which is equal to the one passed. */
for (i = 0; i < NSOCKETS; i++)
{
/* Check if the protocol is UDP */
if ( (SCK_Sockets[i] != NU_NULL) &&
(SCK_Sockets[i]->s_protocol == (UINT16)NU_PROTO_UDP) &&
(SCK_Sockets[i]->s_family == NU_FAMILY_IP) )
{
/* call the function to check whether incoming
* parameters matches with the current socket
*/
result = MIB2_Udp_Compare(IP_ADDR(local_addr), ((UINT16)(*local_port)),
IP_ADDR(SCK_Sockets[i]->s_local_addr.ip_num.is_ip_addrs),
SCK_Sockets[i]->s_local_addr.port_num);
/*if condition is satisfied then return the information */
if (result == 0)
{
/* copying the information from socket list to
* socket_info
*/
memcpy((VOID*)socket_info, (VOID*)SCK_Sockets[i],
(UINT32)sizeof(struct sock_struct));
status = NU_TRUE;
break;
}
}
} /* end for loop which traverse socket list for all sockets */
}
/* else clause will be true in case of getnext or getbulk request */
else
{
/* call the function to get the next in the socket list */
status = MIB2_UdpEntry_GetNext(local_addr, local_port, socket_info);
}
break;
#endif /* ( (MIB2_UDP_INCLUDE == NU_TRUE) && (INCLUDE_UDP == NU_TRUE) ) */
/* if none of above protocol is matched then simply return false */
default:
status = NU_FALSE;
break;
}
}
else
{
status = NU_FALSE;
}
/* release the semaphores because list traversing is over */
if (NU_Release_Semaphore(&TCP_Resource) != NU_SUCCESS)
{
NLOG_Error_Log("Failed to release semaphore", NERR_SEVERE,
__FILE__, __LINE__);
NET_DBG_Notify(NU_INVALID_SEMAPHORE, __FILE__, __LINE__,
NU_Current_Task_Pointer(), NU_NULL);
}
return (status);
} /* MIB2_Socket_List_Information */
#endif /* ( ((MIB2_UDP_INCLUDE == NU_TRUE) && (INCLUDE_UDP == NU_TRUE)) || \
((MIB2_TCP_INCLUDE == NU_TRUE) && (INCLUDE_TCP == NU_TRUE)) ) */
#endif /* (INCLUDE_MIB2_RFC1213 == NU_TRUE) */
| C | CL | de041c287d81af3c53735681bb1c2eed5dae168d512606cb33913c29b19d3a74 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct cx231xx {scalar_t__ model; int /*<<< orphan*/ * vdev; int /*<<< orphan*/ * vbi_dev; int /*<<< orphan*/ * radio_dev; } ;
/* Variables and functions */
scalar_t__ CX231XX_BOARD_CNXT_VIDEO_GRABBER ;
int /*<<< orphan*/ cx231xx_417_unregister (struct cx231xx*) ;
int /*<<< orphan*/ cx231xx_info (char*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ video_device_node_name (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ video_device_release (int /*<<< orphan*/ *) ;
scalar_t__ video_is_registered (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ video_unregister_device (int /*<<< orphan*/ *) ;
void cx231xx_release_analog_resources(struct cx231xx *dev)
{
/*FIXME: I2C IR should be disconnected */
if (dev->radio_dev) {
if (video_is_registered(dev->radio_dev))
video_unregister_device(dev->radio_dev);
else
video_device_release(dev->radio_dev);
dev->radio_dev = NULL;
}
if (dev->vbi_dev) {
cx231xx_info("V4L2 device %s deregistered\n",
video_device_node_name(dev->vbi_dev));
if (video_is_registered(dev->vbi_dev))
video_unregister_device(dev->vbi_dev);
else
video_device_release(dev->vbi_dev);
dev->vbi_dev = NULL;
}
if (dev->vdev) {
cx231xx_info("V4L2 device %s deregistered\n",
video_device_node_name(dev->vdev));
if (dev->model == CX231XX_BOARD_CNXT_VIDEO_GRABBER)
cx231xx_417_unregister(dev);
if (video_is_registered(dev->vdev))
video_unregister_device(dev->vdev);
else
video_device_release(dev->vdev);
dev->vdev = NULL;
}
} | C | CL | 3295ca8b34a4eb0d3f7fb2aea70e4ef642cd625680a8b8662c74f75e1a3f9e9a |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memccpy.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lbaela <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/19 14:06:54 by lbaela #+# #+# */
/* Updated: 2021/04/27 15:35:21 by lbaela ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/* Function copies up to 'n' bytes from string 'src' to string 'dst'.
If the character 'c' occurs in the string 'src', the copy stops and a pointer
to the byte after the 'copy of c' in the string 'dst' is returned.
If 'n' bytes are copied, a NULL pointer is returned.
If 'src' and 'dst' overlap the behavior is undefined. */
void *ft_memccpy(void *dst, const void *src, int c, size_t n)
{
unsigned int i;
i = 0;
while (i < n)
{
((unsigned char *)dst)[i] = ((unsigned char *)src)[i];
if (((unsigned char *)src)[i] == (unsigned char)c)
{
return (dst + ++i);
}
i++;
}
return (NULL);
}
| C | CL | 071fb3aca1c2dcd7a271274cfc70ca8819e1a1d7d5375cdf8dfb3c7253325bec |
#ifndef NODE_H
#define NODE_H
/**
* @brief Represents the type of the node stored in the stack node
*/
typedef enum DataType { TOKEN, ASTNODE } DataType;
typedef void *Element;
/**
* @brief The stack node which holds the token/ASTNode
*/
typedef struct stack_elt_t *StackNode;
typedef struct stack_elt_t
{
DataType dtype;
Element val;
StackNode next;
void (*print_elt)(StackNode);
} stack_elt_t;
#endif | C | CL | 8c9e3ef65869dca8ef3ceb4861acce4cfc30e33e201d0a7880134fe3c9274619 |
//[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
/**
* GAME FREAK inc.
*
* @file bct_surver.h
* @brief サーバー
* @author tomoya takahashi
* @data 2007.06.19
*
*/
//]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
#ifndef __BCT_SURVER_H__
#define __BCT_SURVER_H__
#include "bct_common.h"
//-----------------------------------------------------------------------------
/**
* 定数宣言
*/
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/**
* 構造体宣言
*/
//-----------------------------------------------------------------------------
//-------------------------------------
/// サーバーシステム
//=====================================
typedef struct _BCT_SURVER BCT_SURVER;
//-----------------------------------------------------------------------------
/**
* プロトタイプ宣言
*/
//-----------------------------------------------------------------------------
extern BCT_SURVER* BCT_SURVER_Init( u32 heapID, u32 timeover, u32 comm_num, const BCT_GAMEDATA* cp_gamedata );
extern void BCT_SURVER_Delete( BCT_SURVER* p_wk );
// メイン関数
// FALSEが帰ってきたら終了
// 終了命令とスコアをみんなに送る
extern BOOL BCT_SURVER_Main( BCT_SURVER* p_wk );
// ゲームレベルの変更をチェック
extern BOOL BCT_SURVER_CheckGameLevelChange( const BCT_SURVER* cp_wk ); // 変更があったか?
extern void BCT_SURVER_ClearGameLevelChange( BCT_SURVER* p_wk ); // フラグをクリア
extern u32 BCT_SURVER_GetGameLevel( const BCT_SURVER* cp_wk ); // 今のレベルを取得
// 木の実が入った情報を設定
extern void BCT_SURVER_SetNutData( BCT_SURVER* p_wk, const BCT_NUT_COMM* cp_data, u32 plno );
// みんなのスコアを収集
extern void BCT_SURVER_ScoreSet( BCT_SURVER* p_wk, u32 score, u32 plno );
extern BOOL BCT_SURVER_ScoreAllUserGetCheck( const BCT_SURVER* cp_wk );
extern void BCT_SURVER_ScoreGet( BCT_SURVER* p_wk, BCT_SCORE_COMM* p_data );
// カウントダウンを進めるか設定
extern void BCT_SURVER_SetCountDown( BCT_SURVER* p_wk, BOOL flag );
#endif // __BCT_SURVER_H__
| C | CL | 54c91cb7dc5d022deff98b42e53d5885b279d4942e88e25d167d7e0607a872fd |
#ifndef MACRO_G4GEMEIC_C
#define MACRO_G4GEMEIC_C
#include <GlobalVariables.C>
#include <g4detectors/PHG4SectorSubsystem.h>
#include <g4main/PHG4Reco.h>
#include <string>
R__LOAD_LIBRARY(libg4detectors.so)
int make_GEM_station(string name, PHG4Reco *g4Reco, double zpos, double etamin, double etamax, const int N_Sector = 8, double tilt = 0, bool doTilt = false);
void AddLayers_MiniTPCDrift(PHG4SectorSubsystem *gem);
namespace Enable
{
bool EGEM = false;
bool EGEM_FULL = false;
bool FGEM = false;
bool FGEM_ORIG = false;
} // namespace Enable
void EGEM_Init()
{
BlackHoleGeometry::max_radius = std::max(BlackHoleGeometry::max_radius, 80.);
// extends only to -z
BlackHoleGeometry::min_z = std::min(BlackHoleGeometry::min_z, -160.);
}
void FGEM_Init()
{
BlackHoleGeometry::max_radius = std::max(BlackHoleGeometry::max_radius, 150.);
BlackHoleGeometry::max_z = std::max(BlackHoleGeometry::max_z, 282.);
}
void EGEMSetup(PHG4Reco *g4Reco)
{
/* Careful with dimensions! If GEM station volumes overlap, e.g. with TPC volume, they will be
* drawn in event display but will NOT register any hits.
*
* Geometric constraints:
* TPC length = 211 cm --> from z = -105.5 to z = +105.5
*/
if (Enable::EGEM && Enable::EGEM_FULL)
{
cout << "EGEM and EGEM_FULL cannot be enabled simultaneously" << endl;
}
float thickness = 3.;
if (Enable::EGEM)
{
make_GEM_station("EGEM_2", g4Reco, -137.0 + thickness, -1.4, -3.5);
make_GEM_station("EGEM_3", g4Reco, -160.0 + thickness, -1.5, -3.6);
}
if (Enable::EGEM_FULL)
{
make_GEM_station("EGEM_0", g4Reco, -20.5 + thickness, -0.94, -1.95);
make_GEM_station("EGEM_1", g4Reco, -69.5 + thickness, -2.07, -3.21);
make_GEM_station("EGEM_2", g4Reco, -137.0 + thickness, -1.4, -3.5);
make_GEM_station("EGEM_3", g4Reco, -160.0 + thickness, -1.5, -3.6);
}
}
void FGEMSetup(PHG4Reco *g4Reco, const int N_Sector = 8, //
const double min_eta = 1.245 //
)
{
const double tilt = .1;
double etamax;
double zpos;
PHG4SectorSubsystem *gem;
///////////////////////////////////////////////////////////////////////////
if (Enable::FGEM_ORIG)
{
make_GEM_station("FGEM_0", g4Reco, 17.5, 0.94, 1.95, N_Sector);
make_GEM_station("FGEM_1", g4Reco, 66.5, 2.07, 3.20, N_Sector);
}
///////////////////////////////////////////////////////////////////////////
if (Enable::FGEM_ORIG)
{
etamax = 3.3;
}
else
{
etamax = 2;
}
make_GEM_station("FGEM_2", g4Reco, 134.0, min_eta, etamax, N_Sector);
///////////////////////////////////////////////////////////////////////////
make_GEM_station("FGEM_3", g4Reco, 157.0, min_eta, 3.3, N_Sector, tilt, true);
///////////////////////////////////////////////////////////////////////////
make_GEM_station("FGEM_4", g4Reco, 271.0, 2, 3.5, N_Sector);
make_GEM_station("FGEM_4_LowerEta", g4Reco, 271.0, min_eta, 2, N_Sector, tilt, true);
}
// ======================================================================================================================
void addPassiveMaterial(PHG4Reco *g4Reco)
{
float z_pos = 130.0;
// This is a mockup calorimeter in the forward (hadron-going) direction
PHG4CylinderSubsystem *cyl_f = new PHG4CylinderSubsystem("CALO_FORWARD_PASSIVE", 0);
cyl_f->set_double_param("length", 5); // Length in z direction in cm
cyl_f->set_double_param("radius", z_pos * 0.0503 - 0.180808); // beampipe needs to fit here
cyl_f->set_double_param("thickness", 43); //
cyl_f->set_string_param("material", "G4_Al");
cyl_f->set_double_param("place_z", z_pos);
//cyl_f->SetActive(1);
cyl_f->SuperDetector("passive_F");
//cyl_f->set_color(0,1,1,0.3); //reddish
g4Reco->registerSubsystem(cyl_f);
// This is a mockup calorimeter in the backward (electron-going) direction
PHG4CylinderSubsystem *cyl_b = new PHG4CylinderSubsystem("CALO_BACKWARD_PASSIVE", 0);
cyl_b->set_double_param("length", 5); // Length in z direction in cm
cyl_b->set_double_param("radius", abs(-z_pos * 0.030 - 0.806)); // beampipe needs to fit here
cyl_b->set_double_param("thickness", 43); //
cyl_b->set_string_param("material", "G4_Al");
cyl_b->set_double_param("place_z", -z_pos);
//cyl_b->SetActive(1);
cyl_b->SuperDetector("passive_B");
//cyl_b->set_color(0,1,1,0.3); //reddish
g4Reco->registerSubsystem(cyl_b);
}
//! Add drift layers to mini TPC
void AddLayers_MiniTPCDrift(PHG4SectorSubsystem *gem)
{
assert(gem);
const double cm = PHG4Sector::Sector_Geometry::Unit_cm();
const double mm = 0.1 * cm;
const double um = 1e-3 * mm;
// const int N_Layers = 70; // used for mini-drift TPC timing digitalization
const int N_Layers = 1; // simplified setup
const double thickness = 2 * cm;
gem->get_geometry().AddLayer("EntranceWindow", "G4_MYLAR", 25 * um, false, 100);
gem->get_geometry().AddLayer("Cathode", "G4_GRAPHITE", 10 * um, false, 100);
for (int d = 1; d <= N_Layers; d++)
{
ostringstream s;
s << "DriftLayer_";
s << d;
gem->get_geometry().AddLayer(s.str(), "G4_METHANE", thickness / N_Layers, true);
}
}
int make_GEM_station(string name, PHG4Reco *g4Reco, double zpos, double etamin,
double etamax, const int N_Sector = 8, double tilt = 0, bool doTilt = false)
{
// cout
// << "make_GEM_station - GEM construction with PHG4SectorSubsystem - make_GEM_station_EdgeReadout of "
// << name << endl;
double polar_angle = 0;
if (doTilt)
{
zpos = zpos - (zpos * sin(tilt) + zpos * cos(tilt) * tan(PHG4Sector::Sector_Geometry::eta_to_polar_angle(2) - tilt)) * sin(tilt);
}
else
{
if (zpos < 0)
{
zpos = -zpos;
polar_angle = M_PI;
}
}
if (etamax < etamin)
{
double t = etamax;
etamax = etamin;
etamin = t;
}
PHG4SectorSubsystem *gem;
gem = new PHG4SectorSubsystem(name);
gem->SuperDetector(name);
if (doTilt)
{
gem->get_geometry().set_normal_polar_angle((PHG4Sector::Sector_Geometry::eta_to_polar_angle(etamin) + PHG4Sector::Sector_Geometry::eta_to_polar_angle(etamax)) / 2);
gem->get_geometry().set_normal_start(zpos * PHG4Sector::Sector_Geometry::Unit_cm(), PHG4Sector::Sector_Geometry::eta_to_polar_angle(etamax));
}
else
{
gem->get_geometry().set_normal_polar_angle(polar_angle);
gem->get_geometry().set_normal_start(zpos * PHG4Sector::Sector_Geometry::Unit_cm());
}
gem->get_geometry().set_min_polar_angle(PHG4Sector::Sector_Geometry::eta_to_polar_angle(etamax));
gem->get_geometry().set_max_polar_angle(PHG4Sector::Sector_Geometry::eta_to_polar_angle(etamin));
gem->get_geometry().set_max_polar_edge(PHG4Sector::Sector_Geometry::FlatEdge());
gem->get_geometry().set_min_polar_edge(PHG4Sector::Sector_Geometry::FlatEdge());
gem->get_geometry().set_N_Sector(N_Sector);
gem->get_geometry().set_material("G4_METHANE");
gem->OverlapCheck(Enable::OVERLAPCHECK);
AddLayers_MiniTPCDrift(gem);
gem->get_geometry().AddLayers_HBD_GEM();
gem->OverlapCheck(Enable::OVERLAPCHECK);
g4Reco->registerSubsystem(gem);
return 0;
}
#endif
| C | CL | 2a5268a87fa5515376936b7daa5cce98193dced99092c3a97e056674e66f4b12 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __AWSS_DEV_AP_H__
#define __AWSS_DEV_AP_H__
#if defined(__cplusplus) /* If this is a C++ compiler, use C linkage */
extern "C"
{
#endif
int awss_dev_ap_stop(void);
int awss_dev_ap_start(void);
int wifimgr_process_dev_ap_switchap_request(void *ctx, void *resource, void *remote, void *request);
#if defined(__cplusplus) /* If this is a C++ compiler, use C linkage */
}
#endif
#endif
| C | CL | eae3eaf34753832b2e23fd5268fc48d31a956cb0fef13302889f699d01cdc30c |
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/krb/authdata_dec.c */
/*
* Copyright 1990 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
/*
* Copyright (c) 2006-2008, Novell, 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.
* * The copyright holder's name is not 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 "k5-int.h"
#include "int-proto.h"
krb5_error_code KRB5_CALLCONV
krb5_decode_authdata_container(krb5_context context,
krb5_authdatatype type,
const krb5_authdata *container,
krb5_authdata ***authdata)
{
krb5_error_code code;
krb5_data data;
*authdata = NULL;
if ((container->ad_type & AD_TYPE_FIELD_TYPE_MASK) != type)
return EINVAL;
data.length = container->length;
data.data = (char *)container->contents;
code = decode_krb5_authdata(&data, authdata);
if (code)
return code;
return 0;
}
struct find_authdata_context {
krb5_authdata **out;
size_t space;
size_t length;
};
static krb5_error_code
grow_find_authdata(krb5_context context, struct find_authdata_context *fctx,
krb5_authdata *elem)
{
krb5_error_code retval = 0;
if (fctx->length == fctx->space) {
krb5_authdata **new;
if (fctx->space >= 256) {
k5_setmsg(context, ERANGE,
"More than 256 authdata matched a query");
return ERANGE;
}
new = realloc(fctx->out,
sizeof (krb5_authdata *)*(2*fctx->space+1));
if (new == NULL)
return ENOMEM;
fctx->out = new;
fctx->space *=2;
}
fctx->out[fctx->length+1] = NULL;
retval = krb5int_copy_authdatum(context, elem,
&fctx->out[fctx->length]);
if (retval == 0)
fctx->length++;
return retval;
}
static krb5_error_code
find_authdata_1(krb5_context context, krb5_authdata *const *in_authdat,
krb5_authdatatype ad_type, struct find_authdata_context *fctx,
int from_ap_req)
{
int i = 0;
krb5_error_code retval = 0;
for (i = 0; in_authdat[i] && retval == 0; i++) {
krb5_authdata *ad = in_authdat[i];
krb5_authdata **decoded_container;
switch (ad->ad_type) {
case KRB5_AUTHDATA_IF_RELEVANT:
if (retval == 0)
retval = krb5_decode_authdata_container(context,
ad->ad_type,
ad,
&decoded_container);
if (retval == 0) {
retval = find_authdata_1(context,
decoded_container,
ad_type,
fctx,
from_ap_req);
krb5_free_authdata(context, decoded_container);
}
break;
case KRB5_AUTHDATA_SIGNTICKET:
case KRB5_AUTHDATA_KDC_ISSUED:
case KRB5_AUTHDATA_WIN2K_PAC:
case KRB5_AUTHDATA_CAMMAC:
case KRB5_AUTHDATA_AUTH_INDICATOR:
if (from_ap_req)
continue;
default:
if (ad->ad_type == ad_type && retval == 0)
retval = grow_find_authdata(context, fctx, ad);
break;
}
}
return retval;
}
krb5_error_code KRB5_CALLCONV
krb5_find_authdata(krb5_context context,
krb5_authdata *const *ticket_authdata,
krb5_authdata *const *ap_req_authdata,
krb5_authdatatype ad_type, krb5_authdata ***results)
{
krb5_error_code retval = 0;
struct find_authdata_context fctx;
fctx.length = 0;
fctx.space = 2;
fctx.out = calloc(fctx.space+1, sizeof (krb5_authdata *));
*results = NULL;
if (fctx.out == NULL)
return ENOMEM;
if (ticket_authdata)
retval = find_authdata_1( context, ticket_authdata, ad_type, &fctx, 0);
if ((retval==0) && ap_req_authdata)
retval = find_authdata_1( context, ap_req_authdata, ad_type, &fctx, 1);
if ((retval== 0) && fctx.length)
*results = fctx.out;
else krb5_free_authdata(context, fctx.out);
return retval;
}
krb5_error_code KRB5_CALLCONV
krb5_verify_authdata_kdc_issued(krb5_context context,
const krb5_keyblock *key,
const krb5_authdata *ad_kdcissued,
krb5_principal *issuer,
krb5_authdata ***authdata)
{
krb5_error_code code;
krb5_ad_kdcissued *ad_kdci;
krb5_data data, *data2;
krb5_boolean valid = FALSE;
if ((ad_kdcissued->ad_type & AD_TYPE_FIELD_TYPE_MASK) !=
KRB5_AUTHDATA_KDC_ISSUED)
return EINVAL;
if (issuer != NULL)
*issuer = NULL;
if (authdata != NULL)
*authdata = NULL;
data.length = ad_kdcissued->length;
data.data = (char *)ad_kdcissued->contents;
code = decode_krb5_ad_kdcissued(&data, &ad_kdci);
if (code != 0)
return code;
if (!krb5_c_is_keyed_cksum(ad_kdci->ad_checksum.checksum_type)) {
krb5_free_ad_kdcissued(context, ad_kdci);
return KRB5KRB_AP_ERR_INAPP_CKSUM;
}
code = encode_krb5_authdata(ad_kdci->elements, &data2);
if (code != 0) {
krb5_free_ad_kdcissued(context, ad_kdci);
return code;
}
code = krb5_c_verify_checksum(context, key,
KRB5_KEYUSAGE_AD_KDCISSUED_CKSUM,
data2, &ad_kdci->ad_checksum, &valid);
if (code != 0) {
krb5_free_ad_kdcissued(context, ad_kdci);
krb5_free_data(context, data2);
return code;
}
krb5_free_data(context, data2);
if (valid == FALSE) {
krb5_free_ad_kdcissued(context, ad_kdci);
return KRB5KRB_AP_ERR_BAD_INTEGRITY;
}
if (issuer != NULL) {
*issuer = ad_kdci->i_principal;
ad_kdci->i_principal = NULL;
}
if (authdata != NULL) {
*authdata = ad_kdci->elements;
ad_kdci->elements = NULL;
}
krb5_free_ad_kdcissued(context, ad_kdci);
return 0;
}
/*
* Decode authentication indicator strings from authdata and return as an
* allocated array of krb5_data pointers. The caller must initialize
* *indicators to NULL for the first call, and successive calls will reallocate
* and append to the indicators array.
*/
krb5_error_code
k5_authind_decode(const krb5_authdata *ad, krb5_data ***indicators)
{
krb5_error_code ret = 0;
krb5_data der_ad, **strdata = NULL, **ai_list = *indicators;
size_t count, scount;
if (ad == NULL || ad->ad_type != KRB5_AUTHDATA_AUTH_INDICATOR)
goto cleanup;
/* Count existing auth indicators. */
for (count = 0; ai_list != NULL && ai_list[count] != NULL; count++);
der_ad = make_data(ad->contents, ad->length);
ret = decode_utf8_strings(&der_ad, &strdata);
if (ret)
return ret;
/* Count new auth indicators. */
for (scount = 0; strdata[scount] != NULL; scount++);
ai_list = realloc(ai_list, (count + scount + 1) * sizeof(*ai_list));
if (ai_list == NULL) {
ret = ENOMEM;
goto cleanup;
}
*indicators = ai_list;
/* Steal decoder-allocated pointers and free the container array. */
memcpy(ai_list + count, strdata, scount * sizeof(*strdata));
ai_list[count + scount] = NULL;
free(strdata);
strdata = NULL;
cleanup:
k5_free_data_ptr_list(strdata);
return ret;
}
| C | CL | 41289115648d4ff6993ca4ca1ccce27f164ec3a87c49fdc6158e21cbb65a87a3 |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: smtetwa <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/08/11 10:40:29 by smtetwa #+# #+# */
/* Updated: 2018/08/19 10:17:12 by smtetwa ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
#include "helpers.h"
static size_t udigit_count(uintmax_t n, unsigned int base)
{
size_t i;
i = 0;
if (n == 0)
return (1);
while (n)
{
i++;
n /= base;
}
return (i);
}
char *ft_uitoa(uintmax_t n, unsigned int base, const char *dig,
size_t precision)
{
size_t count;
char *str;
count = udigit_count(n, base);
if (count < precision)
count = precision;
str = ft_memalloc(count + 1);
if (str == NULL)
return (NULL);
while (count > 0)
{
str[count - 1] = dig[n % base];
count--;
n /= base;
}
return (str);
}
static size_t digit_count(intmax_t n, int base)
{
size_t i;
i = 0;
if (n == 0)
return (1);
while (n)
{
i++;
n /= base;
}
return (i);
}
static inline char *itoa_inner(int count, char sign, char neg, uintmax_t v)
{
static char *dig = "0123456789";
char *str;
int base;
base = 10;
str = ft_memalloc(count + neg + 1);
if (str == NULL)
return (NULL);
if (sign)
str[0] = sign;
while (count > 0)
{
str[count + neg - 1] = dig[v % base];
count--;
v /= base;
}
return (str);
}
char *ft_itoa(intmax_t n, t_list_param param, char sign)
{
int count;
char neg;
uintmax_t v;
neg = (n < 0 || sign ? 1 : 0);
count = digit_count(n, 10);
if (count < param.precision)
count = param.precision;
if (!(param.flags & FT_FLAG_MINUS) && (param.flags & FT_FLAG_ZERO)
&& count < (int)param.width - neg)
{
count = (int)param.width - neg;
if (param.precision > 0)
count = param.precision;
}
v = (n < 0 ? -n : n);
if (n < 0)
sign = '-';
return (itoa_inner(count, sign, neg, v));
}
| C | CL | cc9cf2fba1f4ba01139af3be4d57ac0f346af06409a81536a17bd568717d76b6 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
struct super_block {unsigned long s_blocksize_bits; } ;
struct inode {unsigned long i_blkbits; struct super_block* i_sb; } ;
struct buffer_head {unsigned long b_size; } ;
typedef scalar_t__ sector_t ;
struct TYPE_2__ {unsigned long mmu_private; } ;
/* Variables and functions */
TYPE_1__* EXFAT_I (struct inode*) ;
int /*<<< orphan*/ __lock_super (struct super_block*) ;
int /*<<< orphan*/ __unlock_super (struct super_block*) ;
int exfat_bmap (struct inode*,scalar_t__,scalar_t__*,unsigned long*,int*) ;
int /*<<< orphan*/ map_bh (struct buffer_head*,struct super_block*,scalar_t__) ;
unsigned long min (unsigned long,unsigned long) ;
int /*<<< orphan*/ set_buffer_new (struct buffer_head*) ;
__attribute__((used)) static int exfat_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
struct super_block *sb = inode->i_sb;
unsigned long max_blocks = bh_result->b_size >> inode->i_blkbits;
int err;
unsigned long mapped_blocks;
sector_t phys;
__lock_super(sb);
err = exfat_bmap(inode, iblock, &phys, &mapped_blocks, &create);
if (err) {
__unlock_super(sb);
return err;
}
if (phys) {
max_blocks = min(mapped_blocks, max_blocks);
if (create) {
EXFAT_I(inode)->mmu_private += max_blocks <<
sb->s_blocksize_bits;
set_buffer_new(bh_result);
}
map_bh(bh_result, sb, phys);
}
bh_result->b_size = max_blocks << sb->s_blocksize_bits;
__unlock_super(sb);
return 0;
} | C | CL | ddfef63c1b69bc78069f5cf1a05b7fe2302a21124cb36cca5a73ec4d46bf9c42 |
/* server process */
#include <my_global.h>
#include <mysql.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
//#include <iostream.h>
void finish_with_error(MYSQL *con)
{
fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}
#define SIZE sizeof(struct sockaddr_in)
#define MAX 5
int newsockfd;
void general(int m);
void catcher(int sig);
MYSQL *con;
pthread_mutex_t msg_mutex = PTHREAD_MUTEX_INITIALIZER;
int status, *status_ptr = &status;
struct mymsg{
int lineno;
void* ptr;
int size;
};
void handle(struct mymsg ms, int result, int target_client);
void sendfree(struct mymsg ms, int target_client);
int main(void)
{
con = mysql_init(NULL);
if (con == NULL)
{
fprintf(stderr, "%s\n", mysql_error(con));
exit(1);
}
if (mysql_real_connect(con, "localhost", "yogin16", "123", "leashing", 0, NULL, 0) == NULL)
{
finish_with_error(con);
}
if (mysql_query(con, "DROP TABLE IF EXISTS Memory"))
{
finish_with_error(con);
}
if (mysql_query(con, "CREATE TABLE Memory(ClientId INT, Pointer INT, Size INT, CanFree BOOLEAN)"))
{
finish_with_error(con);
}
static struct sigaction act;
act.sa_handler = catcher;
sigfillset(&(act.sa_mask));
sigaction(SIGSTOP, &act, NULL);
time_t mytime;
mytime = time(NULL);
//printf(ctime(&mytime));
FILE *fp = fopen("log.txt", "w+");
int sockfd;
char c;
pthread_t thread[MAX];
int i=-1;
struct sockaddr_in server = {AF_INET, 7000, INADDR_ANY};
/* set up the transport end point */
struct sockaddr_in client;
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket call failed");
exit(1);
}
/* bind an address to the end point */
if ( bind(sockfd, (struct sockaddr *)&server, SIZE) == -1)
{
perror("bind call failed");
exit(1);
}
/* start listening for incoming connections */
if ( listen(sockfd, 5) == -1 )
{
perror("listen call failed");
exit(1) ;
}
for (;;)
{
/* accept a connection */
if ( (newsockfd = accept(sockfd, NULL, NULL)) == -1)
{
perror("accept call failed");
continue;
}
/* parent doesn't need the newsockfd */
i++;
if(pthread_create(&thread[i], NULL, general, newsockfd) != 0)
{
fprintf(stderr, "thread creation failed");
exit(1);
}
if(pthread_join(thread[i], (void **)status_ptr) != 0)
{
fprintf(stderr, "termination failed");
exit(1);
}
// close(newsockfd);
}
}
void general(int pintu)
{
pthread_mutex_lock(&msg_mutex);
int target = pintu;
int d;
struct mymsg ms;
int result;
pthread_mutex_unlock(&msg_mutex);
////// //recv(target, &d, sizeof(int), 0) ;
do
{
result = recv(target, &ms, sizeof(struct mymsg), 0);
handle(ms, result, target);
}while(result > 0);
// close(newsockfd);
// exit (0);
}
void handle(struct mymsg ms, int result, int target_client)
{
printf("\nbytes: %d data: ptr: %d lineno: %d size : %d\n", result, ms.ptr, ms.lineno, ms.size);
if(result>0)
{
FILE *fp;
int i1=0, i2;
fp = fopen("table.txt", "r");
if (fp == NULL) {
printf("I couldn't open table.txt for reading.\n");
exit(0);
}
while (fscanf(fp, "%d %d\n", &i1, &i2) == 2)
{
printf("i: %d, type_is: %d\n", i1, i2);
if(i1==ms.lineno)
break;
}
if(i1==0)
{
printf("Unknown request detected of line no %d .\n", ms.lineno);
}
if(i2==1){ //if message type indicates freeing the memory!
sendfree(ms, target_client);
}
else if(i2==2){ //if message type indicates decoys..
printf("ms is decoy %d ignored.\n",i1);
}
else if(i2==0){ //if message is of malloc type
char p[10],s[10],r[10];
snprintf(p, sizeof(p), "%d", target_client);
snprintf(s, sizeof(s), "%d", ms.ptr);
snprintf(r, sizeof(r), "%d", ms.size);
char q[512];
strcpy(q, "INSERT INTO Memory VALUES(");
strncat(q, p, sizeof(p));
strncat(q, ",", 1);
strncat(q, s, sizeof(s));
strncat(q, ",", 1);
strncat(q, r, sizeof(r));
strncat(q, ",", 1);
strncat(q, "false)",6);
if (mysql_query(con, q))
{
finish_with_error(con);
}
printf("ms is malloc, %d pointer accepted\n", ms.ptr);
}
}
}
void sendfree(struct mymsg ms, int target_client)
{
//the queries here can not be performed! STILL COULDNT FIND THE ERROR!
/*
what this function do???
first it reads which pointer is being freed by the client, and update CanFree flag in the database.
Then look for the size of the pointer, which was stored in the table, while malloc was created, in the INSERT query.
THEN, query the table to find list of pointers, who "CanFree" and are of same size!
Since no other CanFree is processed here yet, it will give only one current pointer.
then it sends to client.
WHAT TO add? : RAND() to ROW, and use CanFree flag.
*/
char *size;
char p[10],s[10];
snprintf(p, sizeof(p), "%d", target_client);
snprintf(s, sizeof(s), "%d", ms.ptr);
char q[512];
strcpy(q, "SELECT Size FROM Memory WHERE ClientID=");
strncat(q, p, sizeof(p));
strncat(q, " and Pointer=",13);
strncat(q, s, sizeof(s));
printf("first query string...\n");
//"UPDATE Memory SET CanFree = true WHERE ClientID=target_client and Pointer= ms.ptr"
if (mysql_query(con, q))
{
// printf("\nslfihdkjgvfjbsdjvbscvkjbsdkjvbxcbvkjxbvkjbdkjbvkljsv\n");
finish_with_error(con);
}
printf("first query fired!!!\n");
MYSQL_RES *result = mysql_store_result(con);
printf("WTFFFF\n");
if (result == NULL)
{
printf("\nerror in if\n");
finish_with_error(con);
}
int num_fields = mysql_num_fields(result);
printf("###############%d ############\n", num_fields);
MYSQL_ROW row;
//row = mysql_fetch_row(result);
while ((row = mysql_fetch_row(result)))
{
printf("HOLY SHIT");
for(int i = 0; i < num_fields; i++)
{
printf("%s ", row[i] ? row[i] : "NULL");
size = row[i];
}
printf("\n");
}
printf("###############%d %s############\n", num_fields, size);
char q1[512];
strcpy(q1, "UPDATE Memory SET CanFree = true WHERE ClientID=");
strncat(q1, p, sizeof(p));
strncat(q1, " and Pointer=",13);
strncat(q1, s, sizeof(s));
/*while ((row = mysql_fetch_row(result)))
{
for(int i = 0; i < num_fields; i++)
{
printf("%s ", row[i] ? row[i] : "NULL");
}
printf("\n");
}*/
if (mysql_query(con, q1))
{
finish_with_error(con);
}
printf("\n/!-------------------------------------------( %s )-----------------\n",size);
char q2[512];
//char ss[10];
//snprintf(ss, sizeof(ss), "%d", size);
strcpy(q2, "SELECT Pointer FROM Memory WHERE ClientID=");
strncat(q2, p, sizeof(p));
strncat(q2, " and Size=",10);
strcat(q2, size);
strncat(q2, " and CanFree=true",18);
if (mysql_query(con, q2))
{
printf("BC, I told you not to do it\n");
finish_with_error(con);
}
//MYSQL_RES *
MYSQL_RES *result1 = mysql_store_result(con);
if (result1 == NULL)
{
finish_with_error(con);
}
int num_fields1 = mysql_num_fields(result1);
int num_rows1 = mysql_num_rows(result1);
int ptr[num_rows1];
MYSQL_ROW row1;
while ((row1 = mysql_fetch_row(result1)))
{
int counter=0;
printf("HOLY SHIT AGAIn\n");
for(int i = 0; i < num_fields1; i++)
{
printf("\n%s ", row1[i] ? row1[i] : "NULL");
//ptr=row1[i];
}
ptr[counter]=atoi(row1[0]);
printf("\n");
printf("\n here i am: %d", ptr[0]);
counter++;
}
//int ptr = row1[0];
send(target_client, &ptr[0], sizeof(int), 0);
//DELETE FROM Memory WHERE ClientID = target_client and Pointer = ptr; ///////////////////////Still one query remaining to implement.
char z[10];
snprintf(z, sizeof(z), "%d", ptr[0]);
char q3[512];
//char ss[10];
//snprintf(ss, sizeof(ss), "%d", size);
strcpy(q3, "DELETE FROM Memory WHERE ClientID=");
strncat(q3, p, sizeof(p));
strncat(q3, " and Pointer=",13);
strncat(q3, z, sizeof(z));
if (mysql_query(con, q3))
{
finish_with_error(con);
}
}
void catcher(int sig)
{
printf("server has to close");
printf("\n server is stopping now: ");
printf("\n saare client ab bhukhe marenge. ");
exit(1);
}
| C | CL | 8e5be1dddb12ee3466cfc9e06564d04192720e50c451d8a671ab069ba3750c35 |
/**
* ========================================================================
* @file db.h
* @brief
* @author smyang
* @version 1.0
* @date 2012-07-12
* Modify $Date: 2012-08-02 18:30:56 +0800 (Thu, 02 Aug 2012) $
* Modify $Author: smyang $
* Copyright: TaoMee, Inc. ShangHai CN. All rights reserved.
* ========================================================================
*/
#ifndef H_DB_H_2012_07_12
#define H_DB_H_2012_07_12
#include "itl_common.h"
void init_connect_to_db();
bool is_db_fd(int fd);
bool is_connected_to_db();
void close_db_fd();
int send_to_db(const void * buf, uint32_t len);
int send_to_db(uint16_t cmd, Cmessage * p_out);
int dispatch_db(int fd, const char * buf, uint32_t len);
int db_get_work_switch_config();
void init_time_event();
#endif
| C | CL | 9e3939098c0c15cbc6c3570c18f0ef3c5c2ca0b662f918712f2116936a6697fb |
/******************************************************************************
* Copyright 2016
* Author: Ponnarasu M.
* No guarantees, warrantees, or promises, implied or otherwise.
* May be used for hobby or commercial purposes provided copyright
* notice remains intact.
*
*****************************************************************************/
#ifndef _LCD_H_
#define _LCD_H_
#define LCD_CLR_DISP 0X00010000 /* 1 Clear display screen */
#define LCD_RET_HOME 0X00020000 /* 2 Return home */
#define LCD_LS_CURS 0X00040000 /* 4 Shift cursor to left */
#define LCD_RS_DISP 0X00050000 /* 5 Shift display right */
#define LCD_RS_CURS 0X00060000 /* 6 Shift cursor to right */
#define LCD_LS_DISP 0X00080000 /* 7 Shift display left */
#define LCD_DOFF_COFF 0X00080000 /* 8 Display off, Cursor off */
#define LCD_DOFF_CON 0X000A0000 /* A Display off, Cursor on */
#define LCD_DON_COFF 0X000C0000 /* C Display on, cursor off */
#define LCD_DON_CBLNK 0X000E0000 /* E Display on, cursor blinking */
#define LCD_DOFF_CBLNK 0X000F0000 /* F Display on, cursor blinking */
#define LCD_LS_CPOS 0X00100000 /* 10 Shift cursor position to left */
#define LCD_RS_CPOS 0X00140000 /* 14 Shift cursor position to right */
#define LCD_LS_ENTDISP 0X00180000 /* 18 Shift the entire display to the left */
#define LCD_RS_ENTDISP 0X001C0000 /* 1C Shift the entire display to the right */
#define LCD_CUR_BEG1L 0X00800000 /* 80 Force cursor to beginning of 1st line */
#define LCD_CUR_BEG2L 0X00C00000 /* C0 Force cursor to beginning of 2nd line */
#define LCD_DISP_PROP 0X00380000 /* 38 2 lines and 5x7 matrix */
#define LCD_EN_PIN_MASK 0x40000000 /* EN(P0.30) */
#define LCD_RW_PIN_MASK 0x20000000 /* R/W(P0.29) */
#define LCD_RS_PIN_MASK 0x10000000 /* RS(P0.28) */
#define LCD_DATA_PIN_MASK 0X00FF0000 /* Data[0-7] P1.16..23 */
#define LCD_D7_PIN_MASK 0x00800000 /* Data7 P1.23 */
/******************************************************************************
*
* Function Name: void Lcd_DispChar(void)
*
* Description:
* This function is used to write display data into LCD
*
* Parameters:
* unsigned char input: ASCII data to be written
*
* Returns:
* void
*
*****************************************************************************/
void Lcd_DispChar(unsigned char input);
/******************************************************************************
*
* Function Name: void Lcd_WriteCommand(void)
*
* Description:
* This function is used to write command into LCD
*
* Parameters:
* unsigned long command: see LCD.h
*
* Returns:
* void
*
*****************************************************************************/
void Lcd_WriteCommand(unsigned long command);
/******************************************************************************
*
* Function Name: void Lcd_Init(void)
*
* Description:
* This function initialized LCD
*
* Parameters:
* void
*
* Returns:
* void
*
*****************************************************************************/
void Lcd_Init(void);
/*Reference: ASCII code */
/*
Char Dec Oct Hex | Char Dec Oct Hex | Char Dec Oct Hex | Char Dec Oct Hex
-------------------------------------------------------------------------------------
(nul) 0 0000 0x00 | (sp) 32 0040 0x20 | @ 64 0100 0x40 | ` 96 0140 0x60
(soh) 1 0001 0x01 | ! 33 0041 0x21 | A 65 0101 0x41 | a 97 0141 0x61
(stx) 2 0002 0x02 | " 34 0042 0x22 | B 66 0102 0x42 | b 98 0142 0x62
(etx) 3 0003 0x03 | # 35 0043 0x23 | C 67 0103 0x43 | c 99 0143 0x63
(eot) 4 0004 0x04 | $ 36 0044 0x24 | D 68 0104 0x44 | d 100 0144 0x64
(enq) 5 0005 0x05 | % 37 0045 0x25 | E 69 0105 0x45 | e 101 0145 0x65
(ack) 6 0006 0x06 | & 38 0046 0x26 | F 70 0106 0x46 | f 102 0146 0x66
(bel) 7 0007 0x07 | ' 39 0047 0x27 | G 71 0107 0x47 | g 103 0147 0x67
(bs) 8 0010 0x08 | ( 40 0050 0x28 | H 72 0110 0x48 | h 104 0150 0x68
(ht) 9 0011 0x09 | ) 41 0051 0x29 | I 73 0111 0x49 | i 105 0151 0x69
(nl) 10 0012 0x0a | * 42 0052 0x2a | J 74 0112 0x4a | j 106 0152 0x6a
(vt) 11 0013 0x0b | + 43 0053 0x2b | K 75 0113 0x4b | k 107 0153 0x6b
(np) 12 0014 0x0c | , 44 0054 0x2c | L 76 0114 0x4c | l 108 0154 0x6c
(cr) 13 0015 0x0d | - 45 0055 0x2d | M 77 0115 0x4d | m 109 0155 0x6d
(so) 14 0016 0x0e | . 46 0056 0x2e | N 78 0116 0x4e | n 110 0156 0x6e
(si) 15 0017 0x0f | / 47 0057 0x2f | O 79 0117 0x4f | o 111 0157 0x6f
(dle) 16 0020 0x10 | 0 48 0060 0x30 | P 80 0120 0x50 | p 112 0160 0x70
(dc1) 17 0021 0x11 | 1 49 0061 0x31 | Q 81 0121 0x51 | q 113 0161 0x71
(dc2) 18 0022 0x12 | 2 50 0062 0x32 | R 82 0122 0x52 | r 114 0162 0x72
(dc3) 19 0023 0x13 | 3 51 0063 0x33 | S 83 0123 0x53 | s 115 0163 0x73
(dc4) 20 0024 0x14 | 4 52 0064 0x34 | T 84 0124 0x54 | t 116 0164 0x74
(nak) 21 0025 0x15 | 5 53 0065 0x35 | U 85 0125 0x55 | u 117 0165 0x75
(syn) 22 0026 0x16 | 6 54 0066 0x36 | V 86 0126 0x56 | v 118 0166 0x76
(etb) 23 0027 0x17 | 7 55 0067 0x37 | W 87 0127 0x57 | w 119 0167 0x77
(can) 24 0030 0x18 | 8 56 0070 0x38 | X 88 0130 0x58 | x 120 0170 0x78
(em) 25 0031 0x19 | 9 57 0071 0x39 | Y 89 0131 0x59 | y 121 0171 0x79
(sub) 26 0032 0x1a | : 58 0072 0x3a | Z 90 0132 0x5a | z 122 0172 0x7a
(esc) 27 0033 0x1b | ; 59 0073 0x3b | [ 91 0133 0x5b | { 123 0173 0x7b
(fs) 28 0034 0x1c | < 60 0074 0x3c | \ 92 0134 0x5c | | 124 0174 0x7c
(gs) 29 0035 0x1d | = 61 0075 0x3d | ] 93 0135 0x5d | } 125 0175 0x7d
(rs) 30 0036 0x1e | > 62 0076 0x3e | ^ 94 0136 0x5e | ~ 126 0176 0x7e
(us) 31 0037 0x1f | ? 63 0077 0x3f | _ 95 0137 0x5f | (del) 127 0177 0x7f
*/
#endif
| C | CL | ccc34127bbc5c9e82f777bbd146e47f888048a245fb69966b166f18c183a066e |
/******************************************************************************
Copyright © 1995-2003,2004,2005-2014 Freescale Semiconductor Inc.
All Rights Reserved
This is proprietary source code of Freescale Semiconductor Inc., and its use
is subject to the CodeWarrior EULA. The copyright notice above does not
evidence any actual or intended publication of such source code.
*******************************************************************************/
/******************************************************************************
$Date: 2012/11/22 16:28:44 $
$Id: os_message_queue.c,v 1.3 2012/11/22 16:28:44 sw Exp $
$Source: /cvsdata/SmartDSP/source/common/os_message_queue.c,v $
$Revision: 1.3 $
******************************************************************************/
/******************************************************************************
@File os_message_queues.c
@Description Intercore messages runtime functions.
In this file messages functions are implemented.The basic idea
is to connect a shared 4 bytes of data with a virtual interrupt
to enable one core pass a message to another. While the message
is posted, no other core can post a message on it so the data
is not changed until the destination core fetches the message.
@Cautions None.
*//***************************************************************************/
#include "smartdsp_os_.h"
#include "os_runtime.h"
#include "os_rm_.h"
#include "os_queue_.h"
#include "os_message_queue_.h"
#include "os_message_queue_shared_.h"
#if (OS_MULTICORE == ON)
extern os_message_queue_t* g_message_queue_list;
extern uint16_t g_max_os_message_queue;
/*****************************************************************************/
os_status osMessageQueuePost(os_msg_handle msg_num,
uint32_t* msg_data)
{
os_status status;
#ifdef MESSAGE_QUEUE_ERROR_CHECKING
if (msg_num >= g_max_os_message_queue)
{
#ifdef MESSAGE_QUEUE_ERROR_ASSERT
OS_ASSERT;
#endif /* MESSAGE_ERROR_ASSERT */
return OS_ERR_MSG_INVALID;
}
#endif
status = osQueueEnqueueMultiple(g_message_queue_list[msg_num].queue, msg_data);
if(status != OS_SUCCESS) return status;
/* generate VIRT interrupt */
status = messageQueueNotify(msg_num);
OS_ASSERT_COND(status == OS_SUCCESS);
return status;
}
/*****************************************************************************/
os_status osMessageQueueGet(os_msg_handle msg_num, uint32_t* msg_data)
{
os_status status;
#ifdef MESSAGE_QUEUE_ERROR_CHECKING
if (msg_num >= g_max_os_message_queue)
{
#ifdef MESSAGE_QUEUE_ERROR_ASSERT
OS_ASSERT;
#endif /* MESSAGE_ERROR_ASSERT */
return OS_ERR_MSG_INVALID;
}
#endif
status = osQueueDequeueMultiple(g_message_queue_list[msg_num].queue, msg_data);
return status;
}
/*****************************************************************************/
os_status osMessageQueueDispatcher(os_msg_handle msg_num, os_msg_function handler, os_hwi_arg hwi_arg,uint32_t* msg_data)
{
os_status status;
OS_ASSERT_COND(handler != NULL);
/* Try to get message */
status = osMessageQueueGet(msg_num,msg_data);
if(status != OS_SUCCESS) return status;
/* call user handler */
return handler(hwi_arg,msg_data);
}
/*****************************************************************************/
#endif // (OS_MULTICORE == ON)
| C | CL | 91f91a36a66434827b30794718a457c58ef84ef6a8fabd0b48ab87c9f4d28d18 |
cocci_test_suite() {
u32 cocci_id/* drivers/media/rc/ir-xmp-decoder.c 77 */;
u32 *cocci_id/* drivers/media/rc/ir-xmp-decoder.c 76 */;
u8 cocci_id/* drivers/media/rc/ir-xmp-decoder.c 75 */;
struct xmp_dec *cocci_id/* drivers/media/rc/ir-xmp-decoder.c 36 */;
struct ir_raw_event cocci_id/* drivers/media/rc/ir-xmp-decoder.c 34 */;
struct rc_dev *cocci_id/* drivers/media/rc/ir-xmp-decoder.c 34 */;
int cocci_id/* drivers/media/rc/ir-xmp-decoder.c 34 */;
enum xmp_state{STATE_INACTIVE, STATE_LEADER_PULSE, STATE_NIBBLE_SPACE,} cocci_id/* drivers/media/rc/ir-xmp-decoder.c 21 */;
void __exit cocci_id/* drivers/media/rc/ir-xmp-decoder.c 205 */;
void cocci_id/* drivers/media/rc/ir-xmp-decoder.c 205 */;
int __init cocci_id/* drivers/media/rc/ir-xmp-decoder.c 197 */;
struct ir_raw_handler cocci_id/* drivers/media/rc/ir-xmp-decoder.c 191 */;
}
| C | CL | 2029b36c071cd7ce434749f50516b1db8e7f31ec160ec34bcc41e23e084286f1 |
/** $Id: tape.c 1182 2008-12-22 22:08:36Z dchassin $
Copyright (C) 2008 Battelle Memorial Institute
@file tape.c
@addtogroup tapes Players and recorders (tape)
@ingroup modules
Tape players and recorders are used to manage the boundary conditions
and record properties of objects during simulation. There are two kinds
of players and two kinds of recorders:
- \p player is used to play a recording of a single value to property of an object
- \p shaper is used to play a periodic scaled shape to a property of groups of objects
- \p recorder is used to collect a recording of one of more properties of an object
- \p collector is used to collect an aggregation of a property from a group of objects
@{
**/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include "gridlabd.h"
#include "object.h"
#include "aggregate.h"
#include "histogram.h"
#define _TAPE_C
#include "tape.h"
#include "file.h"
#include "odbc.h"
#define MAP_DOUBLE(X,LO,HI) {#X,VT_DOUBLE,&X,LO,HI}
#define MAP_INTEGER(X,LO,HI) {#X,VT_INTEGER,&X,LO,HI}
#define MAP_STRING(X) {#X,VT_STRING,X,sizeof(X),0}
#define MAP_END {NULL}
VARMAP varmap[] = {
/* add module variables you want to be available using module_setvar in core */
MAP_STRING(timestamp_format),
MAP_END
};
extern CLASS *player_class;
extern CLASS *shaper_class;
extern CLASS *recorder_class;
extern CLASS *multi_recorder_class;
extern CLASS *collector_class;
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#define _WIN32_WINNT 0x0400
#include <windows.h>
#ifndef DLEXT
#define DLEXT ".dll"
#endif
#define DLLOAD(P) LoadLibrary(P)
#define DLSYM(H,S) GetProcAddress((HINSTANCE)H,S)
#define snprintf _snprintf
#else /* ANSI */
#include "dlfcn.h"
#ifndef DLEXT
#define DLEXT ".so"
#else
#endif
#define DLLOAD(P) dlopen(P,RTLD_LAZY)
#define DLSYM(H,S) dlsym(H,S)
#endif
static TAPEFUNCS *funcs = NULL;
static char1024 tape_gnuplot_path;
int32 flush_interval = 0;
typedef int (*OPENFUNC)(void *, char *, char *);
typedef char *(*READFUNC)(void *, char *, unsigned int);
typedef int (*WRITEFUNC)(void *, char *, char *);
typedef int (*REWINDFUNC)(void *);
typedef void (*CLOSEFUNC)(void *);
TAPEFUNCS *get_ftable(char *mode){
/* check what we've already loaded */
char256 modname;
TAPEFUNCS *fptr = funcs;
TAPEOPS *ops = NULL;
void *lib = NULL;
CALLBACKS **c = NULL;
char *tpath = NULL;
while(fptr != NULL){
if(strcmp(fptr->mode, mode) == 0)
return fptr;
fptr = fptr->next;
}
/* fptr = NULL */
fptr = malloc(sizeof(TAPEFUNCS));
if(fptr == NULL)
{
gl_error("get_ftable(char *mode='%s'): out of memory", mode);
return NULL; /* out of memory */
}
snprintf(modname, 1024, "tape_%s" DLEXT, mode);
tpath = gl_findfile(modname, NULL, 0|4);
if(tpath == NULL){
gl_error("unable to locate %s", modname);
return NULL;
}
lib = fptr->hLib = DLLOAD(tpath);
if(fptr->hLib == NULL){
gl_error("tape module: unable to load DLL for %s", modname);
return NULL;
}
c = (CALLBACKS **)DLSYM(lib, "callback");
if(c)
*c = callback;
// nonfatal ommission
ops = fptr->collector = malloc(sizeof(TAPEOPS));
ops->open = (OPENFUNC)DLSYM(lib, "open_collector");
ops->read = NULL;
ops->write = (WRITEFUNC)DLSYM(lib, "write_collector");
ops->rewind = NULL;
ops->close = (CLOSEFUNC)DLSYM(lib, "close_collector");
ops = fptr->player = malloc(sizeof(TAPEOPS));
ops->open = (OPENFUNC)DLSYM(lib, "open_player");
ops->read = (READFUNC)DLSYM(lib, "read_player");
ops->write = NULL;
ops->rewind = (REWINDFUNC)DLSYM(lib, "rewind_player");
ops->close = (CLOSEFUNC)DLSYM(lib, "close_player");
ops = fptr->recorder = malloc(sizeof(TAPEOPS));
ops->open = (OPENFUNC)DLSYM(lib, "open_recorder");
ops->read = NULL;
ops->write = (WRITEFUNC)DLSYM(lib, "write_recorder");
ops->rewind = NULL;
ops->close = (CLOSEFUNC)DLSYM(lib, "close_recorder");
ops = fptr->histogram = malloc(sizeof(TAPEOPS));
ops->open = (OPENFUNC)DLSYM(lib, "open_histogram");
ops->read = NULL;
ops->write = (WRITEFUNC)DLSYM(lib, "write_histogram");
ops->rewind = NULL;
ops->close = (CLOSEFUNC)DLSYM(lib, "close_histogram");
ops = fptr->shaper = malloc(sizeof(TAPEOPS));
ops->open = (OPENFUNC)DLSYM(lib, "open_shaper");
ops->read = (READFUNC)DLSYM(lib, "read_shaper");
ops->write = NULL;
ops->rewind = (REWINDFUNC)DLSYM(lib, "rewind_shaper");
ops->close = (CLOSEFUNC)DLSYM(lib, "close_shaper");
fptr->next = funcs;
funcs = fptr;
return funcs;
}
EXPORT CLASS *init(CALLBACKS *fntable, void *module, int argc, char *argv[])
{
struct recorder my;
struct collector my2;
if (set_callback(fntable)==NULL)
{
errno = EINVAL;
return NULL;
}
/* globals for the tape module*/
sprintf(tape_gnuplot_path, "c:/Program Files/GnuPlot/bin/wgnuplot.exe");
gl_global_create("tape::gnuplot_path",PT_char1024,&tape_gnuplot_path,NULL);
gl_global_create("tape::flush_interval",PT_int32,&flush_interval,NULL);
/* register the first class implemented, use SHARE to reveal variables */
player_class = gl_register_class(module,"player",sizeof(struct player),PC_PRETOPDOWN);
PUBLISH_STRUCT(player,char256,property);
PUBLISH_STRUCT(player,char1024,file);
PUBLISH_STRUCT(player,char8,filetype);
PUBLISH_STRUCT(player,int32,loop);
/* register the first class implemented, use SHARE to reveal variables */
shaper_class = gl_register_class(module,"shaper",sizeof(struct shaper),PC_PRETOPDOWN);
PUBLISH_STRUCT(shaper,char1024,file);
PUBLISH_STRUCT(shaper,char8,filetype);
PUBLISH_STRUCT(shaper,char256,group);
PUBLISH_STRUCT(shaper,char256,property);
PUBLISH_STRUCT(shaper,double,magnitude);
PUBLISH_STRUCT(shaper,double,events);
/* register the other classes as needed, */
recorder_class = gl_register_class(module,"recorder",sizeof(struct recorder),PC_POSTTOPDOWN);
PUBLISH_STRUCT(recorder,char1024,property);
PUBLISH_STRUCT(recorder,char32,trigger);
PUBLISH_STRUCT(recorder,char1024,file);
PUBLISH_STRUCT(recorder,char1024,multifile);
//PUBLISH_STRUCT(recorder,int64,interval);
PUBLISH_STRUCT(recorder,int32,limit);
PUBLISH_STRUCT(recorder,char1024,plotcommands);
PUBLISH_STRUCT(recorder,char32,xdata);
PUBLISH_STRUCT(recorder,char32,columns);
if(gl_publish_variable(recorder_class,
PT_double, "interval[s]", ((char*)&(my.dInterval) - (char *)&my),
PT_enumeration, "output", ((char*)&(my.output) - (char *)&my),
PT_KEYWORD, "SCREEN", SCREEN,
PT_KEYWORD, "EPS", EPS,
PT_KEYWORD, "GIF", GIF,
PT_KEYWORD, "JPG", JPG,
PT_KEYWORD, "PDF", PDF,
PT_KEYWORD, "PNG", PNG,
PT_KEYWORD, "SVG", SVG,
NULL) < 1)
GL_THROW("Could not publish property output for recorder");
/* register the other classes as needed, */
multi_recorder_class = gl_register_class(module,"multi_recorder",sizeof(struct recorder),PC_POSTTOPDOWN);
if(gl_publish_variable(multi_recorder_class,
PT_double, "interval[s]", ((char*)&(my.dInterval) - (char *)&my),
PT_char1024, "property", ((char*)&(my.property) - (char *)&my),
PT_char32, "trigger", ((char*)&(my.trigger) - (char *)&my),
PT_char1024, "file", ((char*)&(my.file) - (char *)&my),
PT_char1024, "multifile", ((char*)&(my.multifile) - (char *)&my),
PT_int32, "limit", ((char*)&(my.limit) - (char *)&my),
PT_char1024, "plotcommands", ((char*)&(my.plotcommands) - (char *)&my),
PT_char32, "xdata", ((char*)&(my.xdata) - (char *)&my),
PT_char32, "columns", ((char*)&(my.columns) - (char *)&my),
PT_enumeration, "output", ((char*)&(my.output) - (char *)&my),
PT_KEYWORD, "SCREEN", SCREEN,
PT_KEYWORD, "EPS", EPS,
PT_KEYWORD, "GIF", GIF,
PT_KEYWORD, "JPG", JPG,
PT_KEYWORD, "PDF", PDF,
PT_KEYWORD, "PNG", PNG,
PT_KEYWORD, "SVG", SVG,
NULL) < 1)
GL_THROW("Could not publish property output for multi_recorder");
/* register the other classes as needed, */
collector_class = gl_register_class(module,"collector",sizeof(struct collector),PC_POSTTOPDOWN);
PUBLISH_STRUCT(collector,char1024,property);
PUBLISH_STRUCT(collector,char32,trigger);
PUBLISH_STRUCT(collector,char1024,file);
//PUBLISH_STRUCT(collector,int64,interval);
PUBLISH_STRUCT(collector,int32,limit);
PUBLISH_STRUCT(collector,char256,group);
if(gl_publish_variable(collector_class,
PT_double, "interval[s]", ((char*)&(my2.dInterval) - (char *)&my2),
NULL) < 1)
GL_THROW("Could not publish property output for collector");
/* new histogram() */
new_histogram(module);
#if 0
new_loadshape(module);
#endif // zero
// new_schedule(module);
/* always return the first class registered */
return player_class;
}
EXPORT int check(void)
{
unsigned int errcount=0;
/* check players */
{ OBJECT *obj=NULL;
FINDLIST *players = gl_find_objects(FL_NEW,FT_CLASS,SAME,"tape",FT_END);
while ((obj=gl_find_next(players,obj))!=NULL)
{
struct player *pData = OBJECTDATA(obj,struct player);
if (gl_findfile(pData->file,NULL,FF_EXIST)==NULL)
{
errcount++;
gl_error("player %s (id=%d) uses the file '%s', which cannot be found", obj->name?obj->name:"(unnamed)", obj->id, pData->file);
}
}
}
/* check shapers */
{ OBJECT *obj=NULL;
FINDLIST *shapers = gl_find_objects(FL_NEW,FT_CLASS,SAME,"shaper",FT_END);
while ((obj=gl_find_next(shapers,obj))!=NULL)
{
struct shaper *pData = OBJECTDATA(obj,struct shaper);
if (gl_findfile(pData->file,NULL,FF_EXIST)==NULL)
{
errcount++;
gl_error("shaper %s (id=%d) uses the file '%s', which cannot be found", obj->name?obj->name:"(unnamed)", obj->id, pData->file);
}
}
}
return errcount;
}
int do_kill()
{
/* if global memory needs to be released, this is the time to do it */
return 0;
}
/**@}*/
| C | CL | 79010f4fa60dbf0e3fe1be6a3befc1813e14206fe4341da1664ab4318a7809f7 |
/**TODO Tentar colocar os DTO pertecentes ao protocolo aqui.
Ex: A estrutura de dados utilizado para informar a configuração
A estrutura de dados de envio dos sensores telosb
**/
/* Abaixo structs do protocolo firmado */
/*Definição de DTOs e payload*/
//Não funcionou trafegar enum mesmo após o cast
// typedef enum TipoPacote {
// PEDIR_CONFIGURACAO = (nx_uint8_t) 1, //Verificar se é necessário, pois se o pacote não for broadcast não será desnecessário, configuracao serve tanto p/ o root qnt p/ um endpoint
// CONFIGURACAO,
// LUMINOSIDADE
// } TipoPacote;
// typedef nx_struct PedidoConfiguracao {
// } PedidoConfiguracao;
// Dado monitorado pelos sensores
#ifndef _CATRACAH
#define _CATRACAH
#define TipoPacote nx_uint8_t
//Dá para endereçar 256 dispositivos
#define DispositivoId nx_uint8_t
#define CONFIGURACAO 1
#define REQ_CONF 2
#define LEITURA 3
#define nx_bool nx_uint8_t
//Msg para
typedef nx_struct LeituraSensorMsg {
TipoPacote tipo;
DispositivoId dispositivoId;
nx_uint16_t luminosidade;
} LeituraSensorMsg;
//Msg para ACKs e outros fins
typedef nx_struct CatracaMsg {
//TipoPacote tipo, configuracao, reconfiguracao e luminosidade
TipoPacote tipo;
DispositivoId dispositivoId;
//PayloadCatraca payloadCatraca; //não consegui usar void*, logo õ tamanho não é variável
} CatracaMsg;
typedef nx_struct ConfiguracaoMsg {
//TODO verificar possibilidade de uso de typeof
TipoPacote tipo; // campo necessario apenas devido a tamanhos coincidentes
DispositivoId dispositivoId;
nx_uint16_t tmpSensor; //Intervalo de monitoramento em millis
nx_uint16_t valorLuminancia;
nx_uint16_t tmpAck; //Intervalo de pacote ack em millis
nx_bool transferirSempre;
} ConfiguracaoMsg;
CatracaMsg* contruirPacote(void* catracaPayloadAddress);
enum {
AM_RADIO_CATRACA_MSG = 7,
};
#endif
/*Fim de dtos de protocolo*/ | C | CL | a79b0b215290cd59fcc6d0ac0775cd736fe8d86691ca47d23ba18aa8db8deb37 |
//-----------------------------------------------------------------------------
// File: D3DUtil.h
//
// Desc: Helper functions and typing shortcuts for Direct3D programming.
//
//
// Copyright (C) 1997 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#ifndef D3DUTIL_H
#define D3DUTIL_H
#include <ddraw.h>
#include <d3d.h>
//-----------------------------------------------------------------------------
// Typing shortcuts for deleting and freeing objects.
//-----------------------------------------------------------------------------
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
//-----------------------------------------------------------------------------
// Short cut functions for creating and using DX structures
//-----------------------------------------------------------------------------
VOID D3DUtil_InitDeviceDesc( D3DDEVICEDESC& ddDevDesc );
VOID D3DUtil_InitSurfaceDesc( DDSURFACEDESC2& ddsd, DWORD dwFlags=0,
DWORD dwCaps=0 );
VOID D3DUtil_InitViewport( D3DVIEWPORT2& vdViewData, DWORD dwWidth=0,
DWORD dwHeight=0 );
VOID D3DUtil_InitMaterial( D3DMATERIAL& mdMtrlData, FLOAT r=0.0f, FLOAT g=0.0f,
FLOAT b=0.0f );
VOID D3DUtil_InitLight( D3DLIGHT& ldLightData, D3DLIGHTTYPE ltType,
FLOAT x=0.0f, FLOAT y=0.0f, FLOAT z=0.0f );
//-----------------------------------------------------------------------------
// Miscellaneous helper functions
//-----------------------------------------------------------------------------
LPDIRECTDRAW4 D3DUtil_GetDirectDrawFromDevice( LPDIRECT3DDEVICE3 pd3dDevice );
DWORD D3DUtil_GetDeviceMemoryType( LPDIRECT3DDEVICE3 pd3dDevice );
DWORD D3DUtil_GetDisplayDepth( LPDIRECTDRAW4 pDD4=NULL );
//-----------------------------------------------------------------------------
// D3D Matrix functions. For performance reasons, some functions are inline.
//-----------------------------------------------------------------------------
HRESULT D3DUtil_SetViewMatrix( D3DMATRIX& mat, D3DVECTOR& vFrom,
D3DVECTOR& vAt, D3DVECTOR& vUp );
HRESULT D3DUtil_SetProjectionMatrix( D3DMATRIX& mat, FLOAT fFOV = 1.570795f,
FLOAT fAspect = 1.0f,
FLOAT fNearPlane = 1.0f,
FLOAT fFarPlane = 1000.0f );
inline VOID D3DUtil_SetIdentityMatrix( D3DMATRIX& m )
{
m._12 = m._13 = m._14 = m._21 = m._23 = m._24 = 0.0f;
m._31 = m._32 = m._34 = m._41 = m._42 = m._43 = 0.0f;
m._11 = m._22 = m._33 = m._44 = 1.0f;
}
inline VOID D3DUtil_SetTranslateMatrix( D3DMATRIX& m, FLOAT tx, FLOAT ty,
FLOAT tz )
{ D3DUtil_SetIdentityMatrix( m ); m._41 = tx; m._42 = ty; m._43 = tz; }
inline VOID D3DUtil_SetTranslateMatrix( D3DMATRIX& m, D3DVECTOR& v )
{ D3DUtil_SetTranslateMatrix( m, v.x, v.y, v.z ); }
inline VOID D3DUtil_SetScaleMatrix( D3DMATRIX& m, FLOAT sx, FLOAT sy,
FLOAT sz )
{ D3DUtil_SetIdentityMatrix( m ); m._11 = sx; m._22 = sy; m._33 = sz; }
inline VOID SetScaleMatrix( D3DMATRIX& m, D3DVECTOR& v )
{ D3DUtil_SetScaleMatrix( m, v.x, v.y, v.z ); }
VOID D3DUtil_SetRotateXMatrix( D3DMATRIX& mat, FLOAT fRads );
VOID D3DUtil_SetRotateYMatrix( D3DMATRIX& mat, FLOAT fRads );
VOID D3DUtil_SetRotateZMatrix( D3DMATRIX& mat, FLOAT fRads );
VOID D3DUtil_SetRotationMatrix( D3DMATRIX& mat, D3DVECTOR& vDir,
FLOAT fRads );
//-----------------------------------------------------------------------------
// Debug printing support
//-----------------------------------------------------------------------------
HRESULT _DbgOut( TCHAR*, DWORD, HRESULT, TCHAR* );
#if defined(DEBUG) | defined(_DEBUG)
#define DEBUG_MSG(str) _DbgOut( __FILE__, (DWORD)__LINE__, 0, str )
#define DEBUG_ERR(hr,str) _DbgOut( __FILE__, (DWORD)__LINE__, hr, str )
#else
#define DEBUG_MSG(str) (0L)
#define DEBUG_ERR(hr,str) (hr)
#endif
#endif // D3DUTIL_H
| C | CL | 339551a1b42481a7076144d61a761f872cef9d65cbb3aa186405199e4d45068f |
/*=======================================================================================*
* @file MyComp_ut_mocks.h
* @author Dami Pa
* @version 0.0.1
* @date 2020-03-17
* @brief Header file for MyComp_ut_mocks module
*
* This file contains function declarations for Mocks generation.
*======================================================================================*/
/*----------------------- DEFINE TO PREVENT RECURSIVE INCLUSION ------------------------*/
#ifndef MY_COMP_UT_MOCKS_H_
#define MY_COMP_UT_MOCKS_H_
#ifdef __cplusplus
extern "C" {
#endif
/*======================================================================================*/
/* ####### PREPROCESSOR DIRECTIVES ####### */
/*======================================================================================*/
/*-------------------------------- INCLUDE DIRECTIVES ----------------------------------*/
#include "Sts_Common.h"
/*--------------------------- EXPORTED OBJECT-LIKE MACROS ------------------------------*/
/*-------------------------- EXPORTED FUNCTION-LIKE MACROS -----------------------------*/
/*======================================================================================*/
/* ####### EXPORTED TYPE DECLARATIONS ####### */
/*======================================================================================*/
/*---------------------------- ALL TYPE DECLARATIONS -----------------------------------*/
/*-------------------------------- OTHER TYPEDEFS --------------------------------------*/
/*------------------------------------- ENUMS ------------------------------------------*/
/*------------------------------- STRUCT AND UNIONS ------------------------------------*/
/*======================================================================================*/
/* ####### EXPORTED OBJECT DECLARATIONS ####### */
/*======================================================================================*/
/*======================================================================================*/
/* ####### EXPORTED FUNCTIONS PROTOTYPES ####### */
/*======================================================================================*/
/*======================================================================================*/
/* ####### INLINE FUNCTIONS ####### */
/*======================================================================================*/
#ifdef __cplusplus
}
#endif
#endif /* MY_COMP_UT_MOCKS_H_ */
| C | CL | 494b410c053dc7def2382f24f1642d15df7fce03b9e110361a243d3fa179f28f |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_15__ TYPE_3__ ;
typedef struct TYPE_14__ TYPE_2__ ;
typedef struct TYPE_13__ TYPE_1__ ;
/* Type definitions */
typedef int /*<<< orphan*/ uint8_t ;
struct TYPE_13__ {int width; int height; int use_argb; int /*<<< orphan*/ argb_stride; int /*<<< orphan*/ argb; int /*<<< orphan*/ * stats; } ;
typedef TYPE_1__ WebPPicture ;
struct TYPE_14__ {int lossless; int exact; int method; int quality; } ;
typedef TYPE_2__ WebPConfig ;
typedef int /*<<< orphan*/ WebPAuxStats ;
struct TYPE_15__ {int /*<<< orphan*/ error_; } ;
typedef TYPE_3__ VP8LBitWriter ;
/* Variables and functions */
int /*<<< orphan*/ VP8LBitWriterWipeOut (TYPE_3__* const) ;
scalar_t__ VP8LEncodeStream (TYPE_2__*,TYPE_1__*,TYPE_3__* const,int /*<<< orphan*/ ) ;
scalar_t__ VP8_ENC_OK ;
int /*<<< orphan*/ WebPConfigInit (TYPE_2__*) ;
int /*<<< orphan*/ WebPDispatchAlphaToGreen (int /*<<< orphan*/ const* const,int,int,int,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ WebPPictureAlloc (TYPE_1__*) ;
int /*<<< orphan*/ WebPPictureFree (TYPE_1__*) ;
int /*<<< orphan*/ WebPPictureInit (TYPE_1__*) ;
int /*<<< orphan*/ assert (int) ;
__attribute__((used)) static int EncodeLossless(const uint8_t* const data, int width, int height,
int effort_level, // in [0..6] range
int use_quality_100, VP8LBitWriter* const bw,
WebPAuxStats* const stats) {
int ok = 0;
WebPConfig config;
WebPPicture picture;
WebPPictureInit(&picture);
picture.width = width;
picture.height = height;
picture.use_argb = 1;
picture.stats = stats;
if (!WebPPictureAlloc(&picture)) return 0;
// Transfer the alpha values to the green channel.
WebPDispatchAlphaToGreen(data, width, picture.width, picture.height,
picture.argb, picture.argb_stride);
WebPConfigInit(&config);
config.lossless = 1;
// Enable exact, or it would alter RGB values of transparent alpha, which is
// normally OK but not here since we are not encoding the input image but an
// internal encoding-related image containing necessary exact information in
// RGB channels.
config.exact = 1;
config.method = effort_level; // impact is very small
// Set a low default quality for encoding alpha. Ensure that Alpha quality at
// lower methods (3 and below) is less than the threshold for triggering
// costly 'BackwardReferencesTraceBackwards'.
// If the alpha quality is set to 100 and the method to 6, allow for a high
// lossless quality to trigger the cruncher.
config.quality =
(use_quality_100 && effort_level == 6) ? 100 : 8.f * effort_level;
assert(config.quality >= 0 && config.quality <= 100.f);
// TODO(urvang): Temporary fix to avoid generating images that trigger
// a decoder bug related to alpha with color cache.
// See: https://code.google.com/p/webp/issues/detail?id=239
// Need to re-enable this later.
ok = (VP8LEncodeStream(&config, &picture, bw, 0 /*use_cache*/) == VP8_ENC_OK);
WebPPictureFree(&picture);
ok = ok && !bw->error_;
if (!ok) {
VP8LBitWriterWipeOut(bw);
return 0;
}
return 1;
} | C | CL | 11a44562176e021f09e5b5c64357ce445da1cf883217be3e8857e5e7fe01f417 |
/*
* ============================================================================
*
* Authors: Prashant Pandey <[email protected]>
* Rob Johnson <[email protected]>
*
* ============================================================================
*/
#ifndef _GQF_FILE_H_
#define _GQF_FILE_H_
#include <inttypes.h>
#include <pthread.h>
#include <stdbool.h>
#include "gqf.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Initialize a file-backed (i.e. mmapped) CQF at "filename". */
bool cqf_initfile(CQF *qf,
uint64_t nslots,
uint64_t key_bits,
uint64_t value_bits,
enum cqf_hashmode hash,
uint32_t seed,
const char *filename);
#define QF_USEFILE_READ_ONLY (0x01)
#define QF_USEFILE_READ_WRITE (0x02)
/* mmap existing cqf in "filename" into "qf". */
uint64_t cqf_usefile(CQF *qf, const char *filename, int flag);
/* Resize the QF to the specified number of slots. Uses mmap to
* initialize the new file, and calls munmap() on the old memory.
* Return value:
* >= 0: number of keys copied during resizing.
* */
int64_t cqf_resize_file(CQF *qf, uint64_t nslots);
bool cqf_closefile(CQF *qf);
bool cqf_deletefile(CQF *qf);
/* write data structure of to the disk */
uint64_t cqf_serialize(const CQF *qf, const char *filename);
/* read data structure off the disk */
uint64_t cqf_deserialize(CQF *qf, const char *filename);
/* This wraps qfi_next, using madvise(DONTNEED) to reduce our RSS.
Only valid on mmapped QFs, i.e. cqfs from cqf_initfile and
cqf_usefile. */
int qfi_next_madvise(QFi *qfi);
/* Furthermore, you can call this immediately after constructing the
qfi to call madvise(DONTNEED) on the portion of the cqf up to the
first element visited by the qfi. */
int qfi_initial_madvise(QFi *qfi);
#ifdef __cplusplus
}
#endif
#endif // _GQF_FILE_H_
| C | CL | d8b8b4b006e3f33aa77ecaa740e134ea61c5f779bcf772b4b4073fa203542a4c |
/*
* Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
Change History (most recent first):
$Log: dnssd_ipc.h,v $
Revision 1.9 2004/09/22 20:05:38 majka
Integrated
3725573 - Need Error Codes for handling Lighthouse setup failure on NAT
3805822 - Socket-based APIs aren't endian-safe
3806739 - DNSServiceSetDefaultDomainForUser header comments incorrect
Revision 1.8.2.1 2004/09/20 21:54:33 ksekar
<rdar://problem/3805822> Socket-based APIs aren't endian-safe
Revision 1.8 2004/09/17 20:19:01 majka
Integrated 3804522
Revision 1.7.2.1 2004/09/17 20:15:30 ksekar
*** empty log message ***
Revision 1.7 2004/09/16 23:45:24 majka
Integrated 3775315 and 3765280.
Revision 1.6.4.1 2004/09/02 19:43:41 ksekar
<rdar://problem/3775315>: Sync dns-sd client files between Libinfo and
mDNSResponder projects
Revision 1.11 2004/08/10 06:24:56 cheshire
Use types with precisely defined sizes for 'op' and 'reg_index', for better
compatibility if the daemon and the client stub are built using different compilers
Revision 1.10 2004/07/07 17:39:25 shersche
Change MDNS_SERVERPORT from 5533 to 5354.
Revision 1.9 2004/06/25 00:26:27 rpantos
Changes to fix the Posix build on Solaris.
Revision 1.8 2004/06/18 04:56:51 rpantos
Add layer for platform code
Revision 1.7 2004/06/12 01:08:14 cheshire
Changes for Windows compatibility
Revision 1.6 2003/08/12 19:56:25 cheshire
Update to APSL 2.0
*/
#ifndef DNSSD_IPC_H
#define DNSSD_IPC_H
#include "dns_sd.h"
//
// Common cross platform services
//
#if defined(WIN32)
# include <winsock2.h>
# define dnssd_InvalidSocket INVALID_SOCKET
# define dnssd_EWOULDBLOCK WSAEWOULDBLOCK
# define dnssd_EINTR WSAEINTR
# define MSG_WAITALL 0
# define dnssd_sock_t SOCKET
# define dnssd_sockbuf_t
# define dnssd_close(sock) closesocket(sock)
# define dnssd_errno() WSAGetLastError()
# define ssize_t int
# define getpid _getpid
#else
# include <sys/types.h>
# include <unistd.h>
# include <sys/un.h>
# include <string.h>
# include <stdio.h>
# include <stdlib.h>
# include <sys/stat.h>
# include <sys/socket.h>
# include <netinet/in.h>
# define dnssd_InvalidSocket -1
# define dnssd_EWOULDBLOCK EWOULDBLOCK
# define dnssd_EINTR EINTR
# define dnssd_EPIPE EPIPE
# define dnssd_sock_t int
# define dnssd_close(sock) close(sock)
# define dnssd_errno() errno
#endif
#if defined(USE_TCP_LOOPBACK)
# define AF_DNSSD AF_INET
# define MDNS_TCP_SERVERADDR "127.0.0.1"
# define MDNS_TCP_SERVERPORT 5354
# define LISTENQ 5
# define dnssd_sockaddr_t struct sockaddr_in
#else
# define AF_DNSSD AF_LOCAL
# define MDNS_UDS_SERVERPATH "/var/run/mDNSResponder"
# define LISTENQ 100
// longest legal control path length
# define MAX_CTLPATH 256
# define dnssd_sockaddr_t struct sockaddr_un
#endif
//#define UDSDEBUG // verbose debug output
// Compatibility workaround
#ifndef AF_LOCAL
#define AF_LOCAL AF_UNIX
#endif
// General UDS constants
#define TXT_RECORD_INDEX ((uint32_t)(-1)) // record index for default text record
// IPC data encoding constants and types
#define VERSION 1
#define IPC_FLAGS_NOREPLY 1 // set flag if no asynchronous replies are to be sent to client
#define IPC_FLAGS_REUSE_SOCKET 2 // set flag if synchronous errors are to be sent via the primary socket
// (if not set, first string in message buffer must be path to error socket
typedef enum
{
connection = 1, // connected socket via DNSServiceConnect()
reg_record_request, // reg/remove record only valid for connected sockets
remove_record_request,
enumeration_request,
reg_service_request,
browse_request,
resolve_request,
query_request,
reconfirm_record_request,
add_record_request,
update_record_request,
setdomain_request
} request_op_t;
typedef enum
{
enumeration_reply = 64,
reg_service_reply,
browse_reply,
resolve_reply,
query_reply,
reg_record_reply
} reply_op_t;
typedef struct ipc_msg_hdr_struct ipc_msg_hdr;
// client stub callback to process message from server and deliver results to
// client application
typedef void (*process_reply_callback)
(
DNSServiceRef sdr,
ipc_msg_hdr *hdr,
char *msg
);
// allow 64-bit client to interoperate w/ 32-bit daemon
typedef union
{
void *context;
uint32_t ptr64[2];
} client_context_t;
typedef struct ipc_msg_hdr_struct
{
uint32_t version;
uint32_t datalen;
uint32_t flags;
uint32_t op; // request_op_t or reply_op_t
client_context_t client_context; // context passed from client, returned by server in corresponding reply
uint32_t reg_index; // identifier for a record registered via DNSServiceRegisterRecord() on a
// socket connected by DNSServiceConnect(). Must be unique in the scope of the connection, such that and
// index/socket pair uniquely identifies a record. (Used to select records for removal by DNSServiceRemoveRecord())
} ipc_msg_hdr_struct;
// it is advanced to point to the next field, or the end of the message
// routines to write to and extract data from message buffers.
// caller responsible for bounds checking.
// ptr is the address of the pointer to the start of the field.
// it is advanced to point to the next field, or the end of the message
void put_long(const uint32_t l, char **ptr);
uint32_t get_long(char **ptr);
void put_short(uint16_t s, char **ptr);
uint16_t get_short(char **ptr);
#define put_flags put_long
#define get_flags get_long
#define put_error_code put_long
#define get_error_code get_long
int put_string(const char *str, char **ptr);
int get_string(char **ptr, char *buffer, int buflen);
void put_rdata(const int rdlen, const char *rdata, char **ptr);
char *get_rdata(char **ptr, int rdlen); // return value is rdata pointed to by *ptr -
// rdata is not copied from buffer.
void ConvertHeaderBytes(ipc_msg_hdr *hdr);
#endif // DNSSD_IPC_H
| C | CL | fda5ce19bee6b928424a297200f102ee38a191df07cf909e2368eafa8cd6aa1e |
/*
Copyright (c) 1990, 1991 X Consortium
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
*
* Copyright 1990, 1991 by UniSoft Group Limited.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of UniSoft not be
* used in advertising or publicity pertaining to distribution of the
* software without specific, written prior permission. UniSoft
* makes no representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
* $XConsortium: getsize.c,v 1.5 94/04/17 21:00:48 rws Exp $
*/
#include "Xlib.h"
#include "Xutil.h"
#include "pixval.h"
/*
* Get the size of a drawable. Just uses XGetGeometry but avoids all
* the other information that you get with that.
* Either of widthp or heightp can be NULL.
*/
void
getsize(disp, d, widthp, heightp)
Display *disp;
Drawable d;
unsigned int *widthp;
unsigned int *heightp;
{
unsigned int dummy;
Window root;
int x;
int y;
unsigned int border;
unsigned int depth;
XGetGeometry(disp, d, &root, &x, &y,
widthp? widthp: &dummy,
heightp? heightp: &dummy, &border, &depth);
}
/*
* Returns the depth of the given drawable.
*/
unsigned int
getdepth(disp, d)
Display *disp;
Drawable d;
{
Window root;
int x;
int y;
unsigned int width;
unsigned int height;
unsigned int border;
unsigned int depth;
XGetGeometry(disp, d, &root, &x, &y, &width, &height,
&border, &depth);
return(depth);
}
| C | CL | eaf7656334d35b0578b172ba38a00dd9d2561bba2e99b878c9b26984459a0bcd |
#include <rescol/pot.h>
#include <rescol/viewerfunc.h>
static char help[] = "write potential curve";
int main(int argc, char **args) {
PetscErrorCode ierr;
MPI_Comm comm = MPI_COMM_SELF;
POT pot;
ViewerFunc viewer; ViewerFuncCreate(&viewer, comm);
int J = 0;
PetscReal mu = 1.0;
ierr = PetscInitialize(&argc, &args, (char*)0, help); CHKERRQ(ierr);
ierr = PetscOptionsBegin(comm, "", "write_pot options", "none");
ierr = POTCreateFromOptions(&pot, comm); CHKERRQ(ierr);
ierr = ViewerFuncSetFromOptions(viewer); CHKERRQ(ierr);
ierr = PetscOptionsGetInt(NULL, "-J", &J, NULL); CHKERRQ(ierr);
ierr = PetscOptionsGetReal(NULL, "-mu", &mu, NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
if(!ViewerFuncIsActive(viewer))
SETERRQ(comm, 1, "ViewerFunc is bad state");
PetscPrintf(comm, "J=%d\n", J);
PetscPrintf(comm, "mu=%f\n", mu);
POTView(pot);
ViewerFuncView(viewer, PETSC_VIEWER_STDOUT_SELF);
if(!ViewerFuncIsActive(viewer))
POTViewFunc(pot, viewer);
ierr = POTDestroy(&pot); CHKERRQ(ierr);
ierr = ViewerFuncDestroy(&viewer); CHKERRQ(ierr);
ierr = PetscFinalize(); CHKERRQ(ierr);
return 0;
}
| C | CL | d36fde419b2b88829e54b00049762a292922749cca9ac71028dca479d57f70d0 |
/* PBMLIB_FUSION TOOL VERSION: 4.46 */
/* GENERATED: THU JAN 20 2011 */
/*=============================================================================
P B M L I B _ F U S I O N _ S V C . C
GENERAL DESCRIPTION
This is an AUTO GENERATED file that dispatches RPC requests targetting the
pbmlib_fusion api.
---------------------------------------------------------------------------
Copyright (c) 2011 QUALCOMM Incorporated.
All Rights Reserved. QUALCOMM Proprietary and Confidential.
---------------------------------------------------------------------------
=============================================================================*/
/*=============================================================================
Edit History
AUTO GENERATED */
/* Generated by following versions of Htorpc modules:
Id: //source/qcom/qct/core/mproc/tools/rel/2h09/htorpc/htorpc.pl#1
Id: //source/qcom/qct/core/mproc/tools/rel/2h09/htorpc/lib/Htorpc/Start.pm#1
Id: //source/qcom/qct/core/mproc/tools/rel/2h09/htorpc/lib/Htorpc/Htoxdr.pm#1
Id: //source/qcom/qct/core/mproc/tools/rel/2h09/htorpc/lib/Htorpc/XDR.pm#3
Id: //source/qcom/qct/core/mproc/tools/rel/2h09/htorpc/lib/Htorpc/Output.pm#4
Id: //source/qcom/qct/core/mproc/tools/rel/2h09/htorpc/lib/Htorpc/Parser.pm#1
Id: //source/qcom/qct/core/mproc/tools/rel/2h09/htorpc/lib/Htorpc/Metacomments.pm#1
Id: //source/qcom/qct/core/mproc/tools/rel/2h09/htorpc/lib/Htorpc/SymbolTable.pm#1
pbmlib_fusion Definition File(s):
=============================================================================*/
/*=============================================================================
$Header: //source/qcom/qct/modem/api/rapi/pbm/main/latest/src/pbmlib_fusion_svc.c#3 $
=============================================================================*/
/* Include files */
#include "oncrpc.h"
#include "pbmlib_fusion.h"
#include "pbmlib_fusion_rpc.h"
/* Only one copy needed per API */
//static opaque_auth Pbmlib_fusionCred = { ONCRPC_AUTH_NONE, 0, 0 };
static opaque_auth Pbmlib_fusionVerf = { ONCRPC_AUTH_NONE, 0, 0 };
static opaque_auth Pbmlib_fusioncbCred = { ONCRPC_AUTH_NONE, 0, 0 };
static opaque_auth Pbmlib_fusioncbVerf = { ONCRPC_AUTH_NONE, 0, 0 };
/*=======================================================================
Prototypes for the API's RPC Server Functions
=======================================================================*/
static void pbmlib_fusionprog_0x00010003 ( struct svc_req *rqstp, xdr_s_type *srv );
static void pbmlib_fusion_null_0x00010003( xdr_s_type *svc );
static void pbmlib_fusion_rpc_glue_code_info_remote_0x00010003( xdr_s_type *svc );
static void pbmlib_fusion_api_versions_0x00010003( xdr_s_type *srv );
static void pbm_clear_call_history_fusion_0x00010003( xdr_s_type *srv );
static void pbm_is_init_completed_fusion_0x00010003( xdr_s_type *srv );
static void pbm_enum_rec_init_fusion_0x00010003( xdr_s_type *srv );
static void pbm_enum_next_rec_id_fusion_0x00010003( xdr_s_type *srv );
static void pbm_file_info_fusion_0x00010003( xdr_s_type *srv );
static void pbm_extended_file_info_fusion_0x00010003( xdr_s_type *srv );
static void pbm_find_location_fusion_0x00010003( xdr_s_type *srv );
static void pbm_find_name_next_fusion_0x00010003( xdr_s_type *srv );
static void pbm_find_name_fusion_0x00010003( xdr_s_type *srv );
static void pbm_find_number_fusion_0x00010003( xdr_s_type *srv );
static void pbm_get_num_recs_fusion_0x00010003( xdr_s_type *srv );
static void pbm_calculate_fields_size_from_id_fusion_0x00010003( xdr_s_type *srv );
static void pbm_record_read_fusion_0x00010003( xdr_s_type *srv );
static void pbm_record_write_fusion_0x00010003( xdr_s_type *srv );
static void pbm_reg_event_cb_fusion_0x00010003( xdr_s_type *srv );
static void pbm_write_fusion_0x00010003( xdr_s_type *srv );
static void pbm_write_lock_fusion_0x00010003( xdr_s_type *srv );
static void pbm_write_unlock_fusion_0x00010003( xdr_s_type *srv );
static void pbm_get_field_info_count_fusion_0x00010003( xdr_s_type *srv );
static void pbm_get_field_info_fusion_0x00010003( xdr_s_type *srv );
static void pbm_record_validate_fusion_0x00010003( xdr_s_type *srv );
static void pbm_clear_phonebook_fusion_0x00010003( xdr_s_type *srv );
static void pbm_emergency_number_fusion_0x00010003( xdr_s_type *srv );
static void pbm_emergency_number_cat_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_emergency_number_cat_fusion_0x00010003( xdr_s_type *srv );
static void pbm_number_match_fusion_0x00010003( xdr_s_type *srv );
static void pbm_fdn_number_match_fusion_0x00010003( xdr_s_type *srv );
static void pbm_notify_register_fusion_0x00010003( xdr_s_type *srv );
static void pbm_notify_unregister_fusion_0x00010003( xdr_s_type *srv );
static void pbm_have_uids_changed_fusion_0x00010003( xdr_s_type *srv );
static void pbm_validate_uid_changes_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_enum_rec_init_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_enum_next_rec_id_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_enum_rec_init_ext_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_enum_rec_init_ext_free_handle_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_enum_next_rec_id_ext_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_find_location_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_find_name_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_find_number_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_get_num_recs_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_calculate_fields_size_from_id_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_record_read_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_record_write_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_write_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_get_field_info_count_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_get_field_info_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_record_validate_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_clear_phonebook_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_extended_file_info_fusion_0x00010003( xdr_s_type *srv );
static void pbm_session_extended_file_info_async_fusion_0x00010003( xdr_s_type *srv );
/*=======================================================================
Prototypes for the API's Callback RPC clients
=======================================================================*/
static void PBM_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003(
pbm_return_type ret,
pbm_device_type pb_id,
int records_used,
int number_of_records,
int text_len
);
static void PBM_EXTENDED_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003(pbm_return_type ret, pbm_device_type pb_id, pbm_extended_fileinfo_s_type *info);
static void PBM_FIND_CB_FUNC_fusion_clnt_0x00010003(pbm_return_type ret, pbm_record_s_type *rec);
static void PBM_WRITE_CB_FUNC_fusion_clnt_0x00010003(pbm_writecb_data_s_type *cb_data);
static void PBM_EVENT_FUNC_fusion_clnt_0x00010003(boolean ready);
static void PBM_WRITE_COMPAT_CB_FUNC_fusion_clnt_0x00010003(pbm_return_type ret);
static void PBM_NOTIFY_FUNC_fusion_clnt_0x00010003(void *user_data, pbm_notify_data_s_type *notify_data);
static void PBM_SESSION_EXTENDED_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003(pbm_return_type ret, pbm_phonebook_type pb_id, pbm_extended_fileinfo_s_type *info);
/******************************************************************************/
/*=======================================================================
API RPC Server Implementation
=======================================================================*/
static uint32 pbmlib_fusion_api_versions_table[] = { 0x00010001 , 0x00010002 , 0x00010003 };
uint32 * pbmlib_fusion_api_versions(uint32 *size_entries)
{
if (size_entries != NULL)
{
*size_entries = sizeof( pbmlib_fusion_api_versions_table) / sizeof(uint32);
}
return pbmlib_fusion_api_versions_table;
}
void pbmlib_fusion_app_init( void )
{
(void) svc_register_auto_apiversions(PBMLIB_FUSIONPROG, PBMLIB_FUSIONVERS, pbmlib_fusionprog_0x00010003,
pbmlib_fusion_api_versions);
} /* pbmlib_fusion_app_init */
void pbmlib_fusion_app_lock( boolean lock )
{
svc_lock( PBMLIB_FUSIONPROG, PBMLIB_FUSIONVERS, lock );
} /* pbmlib_fusion_app_lock */
static void pbmlib_fusionprog_0x00010003 ( struct svc_req *rqstp, xdr_s_type *srv )
{
switch ( rqstp->rq_proc ) {
case ONCRPC_PBMLIB_FUSION_NULL_PROC:
pbmlib_fusion_null_0x00010003( srv );
break;
case ONCRPC_PBMLIB_FUSION_RPC_GLUE_CODE_INFO_REMOTE_PROC:
pbmlib_fusion_rpc_glue_code_info_remote_0x00010003( srv );
break;
case ONCRPC_PBM_CLEAR_CALL_HISTORY_FUSION_PROC:
pbm_clear_call_history_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_IS_INIT_COMPLETED_FUSION_PROC:
pbm_is_init_completed_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_ENUM_REC_INIT_FUSION_PROC:
pbm_enum_rec_init_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_ENUM_NEXT_REC_ID_FUSION_PROC:
pbm_enum_next_rec_id_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_FILE_INFO_FUSION_PROC:
pbm_file_info_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_EXTENDED_FILE_INFO_FUSION_PROC:
pbm_extended_file_info_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_FIND_LOCATION_FUSION_PROC:
pbm_find_location_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_FIND_NAME_NEXT_FUSION_PROC:
pbm_find_name_next_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_FIND_NAME_FUSION_PROC:
pbm_find_name_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_FIND_NUMBER_FUSION_PROC:
pbm_find_number_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_GET_NUM_RECS_FUSION_PROC:
pbm_get_num_recs_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_CALCULATE_FIELDS_SIZE_FROM_ID_FUSION_PROC:
pbm_calculate_fields_size_from_id_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_RECORD_READ_FUSION_PROC:
pbm_record_read_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_RECORD_WRITE_FUSION_PROC:
pbm_record_write_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_REG_EVENT_CB_FUSION_PROC:
pbm_reg_event_cb_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_WRITE_FUSION_PROC:
pbm_write_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_WRITE_LOCK_FUSION_PROC:
pbm_write_lock_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_WRITE_UNLOCK_FUSION_PROC:
pbm_write_unlock_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_GET_FIELD_INFO_COUNT_FUSION_PROC:
pbm_get_field_info_count_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_GET_FIELD_INFO_FUSION_PROC:
pbm_get_field_info_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_RECORD_VALIDATE_FUSION_PROC:
pbm_record_validate_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_CLEAR_PHONEBOOK_FUSION_PROC:
pbm_clear_phonebook_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_EMERGENCY_NUMBER_FUSION_PROC:
pbm_emergency_number_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_EMERGENCY_NUMBER_CAT_FUSION_PROC:
pbm_emergency_number_cat_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_EMERGENCY_NUMBER_CAT_FUSION_PROC:
pbm_session_emergency_number_cat_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_NUMBER_MATCH_FUSION_PROC:
pbm_number_match_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_FDN_NUMBER_MATCH_FUSION_PROC:
pbm_fdn_number_match_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_NOTIFY_REGISTER_FUSION_PROC:
pbm_notify_register_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_NOTIFY_UNREGISTER_FUSION_PROC:
pbm_notify_unregister_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_HAVE_UIDS_CHANGED_FUSION_PROC:
pbm_have_uids_changed_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_VALIDATE_UID_CHANGES_FUSION_PROC:
pbm_validate_uid_changes_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_ENUM_REC_INIT_FUSION_PROC:
pbm_session_enum_rec_init_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_ENUM_NEXT_REC_ID_FUSION_PROC:
pbm_session_enum_next_rec_id_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_ENUM_REC_INIT_EXT_FUSION_PROC:
pbm_session_enum_rec_init_ext_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_ENUM_REC_INIT_EXT_FREE_HANDLE_FUSION_PROC:
pbm_session_enum_rec_init_ext_free_handle_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_ENUM_NEXT_REC_ID_EXT_FUSION_PROC:
pbm_session_enum_next_rec_id_ext_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_FIND_LOCATION_FUSION_PROC:
pbm_session_find_location_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_FIND_NAME_FUSION_PROC:
pbm_session_find_name_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_FIND_NUMBER_FUSION_PROC:
pbm_session_find_number_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_GET_NUM_RECS_FUSION_PROC:
pbm_session_get_num_recs_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_CALCULATE_FIELDS_SIZE_FROM_ID_FUSION_PROC:
pbm_session_calculate_fields_size_from_id_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_RECORD_READ_FUSION_PROC:
pbm_session_record_read_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_RECORD_WRITE_FUSION_PROC:
pbm_session_record_write_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_WRITE_FUSION_PROC:
pbm_session_write_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_GET_FIELD_INFO_COUNT_FUSION_PROC:
pbm_session_get_field_info_count_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_GET_FIELD_INFO_FUSION_PROC:
pbm_session_get_field_info_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_RECORD_VALIDATE_FUSION_PROC:
pbm_session_record_validate_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_CLEAR_PHONEBOOK_FUSION_PROC:
pbm_session_clear_phonebook_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_EXTENDED_FILE_INFO_FUSION_PROC:
pbm_session_extended_file_info_fusion_0x00010003( srv );
break;
case ONCRPC_PBM_SESSION_EXTENDED_FILE_INFO_ASYNC_FUSION_PROC:
pbm_session_extended_file_info_async_fusion_0x00010003( srv );
break;
case ONCRPC_PBMLIB_FUSION_API_VERSIONS_PROC:
pbmlib_fusion_api_versions_0x00010003( srv );
break;
default:
// invalid RPC procedure number
(void) XDR_MSG_DONE( srv );
svcerr_default_err( srv, rqstp, pbmlib_fusion_api_versions );
break;
}
oncrpcxdr_mem_free( srv );
} /* pbmlib_fusionprog_0x00010003 */
/******************************************************************************/
static void pbmlib_fusion_null_0x00010003( xdr_s_type *srv )
{
if ( ! XDR_MSG_DONE( srv ) ) {
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
if ( ! xdr_reply_msg_start( srv, &Pbmlib_fusionVerf ) ) {
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbmlib_fusion_null_0x00010003 */
static void pbmlib_fusion_rpc_glue_code_info_remote_0x00010003( xdr_s_type *srv )
{
uint32 toolvers = PBMLIB_FUSION_TOOLVERS; /* 4.46 */
uint32 proghash = 0x00010003; /* 0x00010003 */
uint32 cbproghash = 0x00010003; /* 0x00010003 */
uint32 features = PBMLIB_FUSION_FEATURES; /* ONCRPC Server Cleanup Support */
if ( ! XDR_MSG_DONE( srv ) ) {
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
if ( ! xdr_reply_msg_start( srv, &Pbmlib_fusionVerf ) ||
! XDR_SEND_UINT32( srv, &toolvers ) ||
! XDR_SEND_UINT32( srv, &features ) ||
! XDR_SEND_UINT32( srv, &proghash ) ||
! XDR_SEND_UINT32( srv, &cbproghash ) )
{
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbmlib_fusion_rpc_glue_code_info_remote_0x00010003 */
static void pbm_clear_call_history_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
pbm_return_type pbm_clear_call_history_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_clear_call_history_fusion_result = pbm_clear_call_history_fusion();
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_clear_call_history_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_clear_call_history_fusion_0x00010003 */
static void pbm_is_init_completed_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean pbm_is_init_completed_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_is_init_completed_fusion_result = pbm_is_init_completed_fusion();
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_BOOLEAN( srv, &pbm_is_init_completed_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_is_init_completed_fusion_0x00010003 */
static void pbm_enum_rec_init_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
void *memset_temp;
uint16 length_uint16;
pbm_device_type pb_id = PBM_DEFAULT;
uint16 category = 0;
pbm_field_id_e_type field_id = 0;
uint8 *data_ptr = NULL;
uint16 data_size = 0;
uint32 flags = 0;
pbm_return_type pbm_enum_rec_init_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT16( srv, &category );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT16( srv, &field_id );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_UINT16( srv, &length_uint16 );
/* XDR OP NUMBER = 5 */
if ( xdr_status && length_uint16 > 0 )
{
xdr_op_number = 5;
memset_temp = oncrpcxdr_mem_alloc( srv, length_uint16 * sizeof( *data_ptr ));
memset(memset_temp, 0, length_uint16 * sizeof( *data_ptr ));
data_ptr = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, data_ptr, length_uint16);
}
}
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_RECV_UINT16( srv, &data_size );
}
/* XDR OP NUMBER = 7 */
if ( xdr_status )
{
xdr_op_number = 7;
xdr_status = XDR_RECV_UINT32( srv, &flags );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_enum_rec_init_fusion_result = pbm_enum_rec_init_fusion(pb_id, category, field_id, data_ptr, data_size, flags);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_enum_rec_init_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_enum_rec_init_fusion_0x00010003 */
static void pbm_enum_next_rec_id_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean output_pointer_not_null;
uint16 *rec_id_ptr = NULL;
pbm_return_type pbm_enum_next_rec_id_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
/* The server must know whether to allocate memory for the output parameter
* rec_id_ptr or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
rec_id_ptr = oncrpcxdr_mem_alloc( srv, sizeof(*rec_id_ptr) );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_enum_next_rec_id_fusion_result = pbm_enum_next_rec_id_fusion(rec_id_ptr);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_enum_next_rec_id_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &rec_id_ptr, XDR_SEND_UINT16, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_enum_next_rec_id_fusion_0x00010003 */
static void pbm_file_info_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
pbm_device_type pb_id = PBM_DEFAULT;
PBM_FILE_INFO_CB_FUNC_fusion cb1;
pbm_return_type pbm_file_info_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_FILE_INFO_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_file_info_fusion_result = pbm_file_info_fusion(pb_id, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_file_info_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_file_info_fusion_0x00010003 */
static void pbm_extended_file_info_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
pbm_device_type pb_id = PBM_DEFAULT;
PBM_EXTENDED_FILE_INFO_CB_FUNC_fusion cb1;
pbm_return_type pbm_extended_file_info_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_EXTENDED_FILE_INFO_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_EXTENDED_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_extended_file_info_fusion_result = pbm_extended_file_info_fusion(pb_id, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_extended_file_info_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_extended_file_info_fusion_0x00010003 */
static void pbm_find_location_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
boolean output_pointer_not_null;
pbm_device_type pb_id = PBM_DEFAULT;
int index = 0;
pbm_record_s_type *data = NULL;
PBM_FIND_CB_FUNC_fusion cb1;
pbm_return_type pbm_find_location_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_INT( srv, &index );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/* The server must know whether to allocate memory for the output parameter
* data or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
data = oncrpcxdr_mem_alloc( srv, sizeof(*data) );
}
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_FIND_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_FIND_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_find_location_fusion_result = pbm_find_location_fusion(pb_id, index, data, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_find_location_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
XDR_SEND_POINTER( srv, &data, xdr_pbmlib_fusion_send_pbm_record_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_find_location_fusion_0x00010003 */
static void pbm_find_name_next_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
pbm_return_type pbm_find_name_next_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_find_name_next_fusion_result = pbm_find_name_next_fusion();
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_find_name_next_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_find_name_next_fusion_0x00010003 */
static void pbm_find_name_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
void *memset_temp;
uint32 length_uint32;
boolean output_pointer_not_null;
pbm_device_type pb_id = PBM_DEFAULT;
char *name = NULL;
pbm_record_s_type *data = NULL;
PBM_FIND_CB_FUNC_fusion cb1;
pbm_return_type pbm_find_name_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT32( srv, &length_uint32 );
/* XDR OP NUMBER = 3 */
if ( xdr_status && length_uint32 > 0 )
{
xdr_op_number = 3;
if ( name == NULL ) {
memset_temp = oncrpcxdr_mem_alloc( srv, length_uint32);
memset(memset_temp, 0, length_uint32);
name = memset_temp;
}
xdr_status = XDR_RECV_STRING(srv, name, length_uint32);
}
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
/* The server must know whether to allocate memory for the output parameter
* data or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
data = oncrpcxdr_mem_alloc( srv, sizeof(*data) );
}
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_FIND_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_FIND_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_find_name_fusion_result = pbm_find_name_fusion(pb_id, name, data, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_find_name_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
XDR_SEND_POINTER( srv, &data, xdr_pbmlib_fusion_send_pbm_record_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_find_name_fusion_0x00010003 */
static void pbm_find_number_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
void *memset_temp;
int length_int;
boolean output_pointer_not_null;
pbm_device_type pb_id = PBM_DEFAULT;
byte *number = NULL;
int loc_number_len = 0;
pbm_record_s_type *record = NULL;
PBM_FIND_CB_FUNC_fusion cb1;
pbm_return_type pbm_find_number_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_INT( srv, &length_int );
/* XDR OP NUMBER = 3 */
if ( xdr_status && length_int > 0 )
{
xdr_op_number = 3;
memset_temp = oncrpcxdr_mem_alloc( srv, length_int * sizeof( *number ));
memset(memset_temp, 0, length_int * sizeof( *number ));
number = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, number, length_int);
}
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_INT( srv, &loc_number_len );
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
/* The server must know whether to allocate memory for the output parameter
* record or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
record = oncrpcxdr_mem_alloc( srv, sizeof(*record) );
}
}
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_FIND_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_FIND_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_find_number_fusion_result = pbm_find_number_fusion(pb_id, number, loc_number_len, record, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_find_number_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
XDR_SEND_POINTER( srv, &record, xdr_pbmlib_fusion_send_pbm_record_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_find_number_fusion_0x00010003 */
static void pbm_get_num_recs_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
pbm_device_type pb_id = PBM_DEFAULT;
uint16 pbm_get_num_recs_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_get_num_recs_fusion_result = pbm_get_num_recs_fusion(pb_id);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_UINT16( srv, &pbm_get_num_recs_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_get_num_recs_fusion_0x00010003 */
static void pbm_calculate_fields_size_from_id_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint16 rec_id = 0;
int pbm_calculate_fields_size_from_id_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT16( srv, &rec_id );
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_calculate_fields_size_from_id_fusion_result = pbm_calculate_fields_size_from_id_fusion(rec_id);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_INT( srv, &pbm_calculate_fields_size_from_id_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_calculate_fields_size_from_id_fusion_0x00010003 */
static void pbm_record_read_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean output_pointer_not_null;
uint32 length_uint32;
uint16 rec_id = 0;
uint16 *category_ptr = NULL;
int *num_fields_ptr = NULL;
uint8 *data_buf = NULL;
uint32 data_buf_size = 0;
pbm_return_type pbm_record_read_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT16( srv, &rec_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
/* The server must know whether to allocate memory for the output parameter
* category_ptr or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
category_ptr = oncrpcxdr_mem_alloc( srv, sizeof(*category_ptr) );
}
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/* The server must know whether to allocate memory for the output parameter
* num_fields_ptr or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
num_fields_ptr = oncrpcxdr_mem_alloc( srv, sizeof(*num_fields_ptr) );
}
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
/* The server must know whether to allocate memory for the output parameter
* data_buf or not. A boolean is received to indicate that. The maximum number
* of objects that could be pointed to by this pointer is also received.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
xdr_status = XDR_RECV_UINT32( srv, &length_uint32 );
data_buf = oncrpcxdr_mem_alloc( srv, length_uint32 * sizeof(*data_buf) );
}
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
xdr_status = XDR_RECV_UINT32( srv, &data_buf_size );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_record_read_fusion_result = pbm_record_read_fusion(rec_id, category_ptr, num_fields_ptr, data_buf, data_buf_size);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_record_read_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &category_ptr, XDR_SEND_UINT16, xdr_status );
/*lint -restore */
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &num_fields_ptr, XDR_SEND_INT, xdr_status );
/*lint -restore */
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
if ( data_buf != NULL ) {
length_uint32 = data_buf_size;
length_uint32 = ( length_uint32 > 1500 ? 1500 : length_uint32 );
xdr_status = XDR_SEND_UINT32( srv, &length_uint32 );
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_SEND_BYTES(srv, data_buf, length_uint32);
}
} else {
length_uint32 = 0;
xdr_status = XDR_SEND_UINT32( srv, &length_uint32 );
}
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_record_read_fusion_0x00010003 */
static void pbm_record_write_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
void *memset_temp;
int length_int;
pbm_device_type pb_id = PBM_DEFAULT;
uint16 *rec_id_ptr = NULL;
uint16 cat = 0;
int num_fields = 0;
uint8 *data_buf = NULL;
int data_buf_size = 0;
PBM_WRITE_CB_FUNC_fusion cb1;
void *user_data = NULL;
pbm_return_type pbm_record_write_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
/*lint -save -e123*/
XDR_RECV_POINTER( srv, &rec_id_ptr, XDR_RECV_UINT16, xdr_status );
/*lint -restore */
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT16( srv, &cat );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_INT( srv, &num_fields );
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
xdr_status = XDR_RECV_INT( srv, &length_int );
/* XDR OP NUMBER = 6 */
if ( xdr_status && length_int > 0 )
{
xdr_op_number = 6;
memset_temp = oncrpcxdr_mem_alloc( srv, length_int * sizeof( *data_buf ));
memset(memset_temp, 0, length_int * sizeof( *data_buf ));
data_buf = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, data_buf, length_int);
}
}
/* XDR OP NUMBER = 7 */
if ( xdr_status )
{
xdr_op_number = 7;
xdr_status = XDR_RECV_INT( srv, &data_buf_size );
}
/* XDR OP NUMBER = 8 */
if ( xdr_status )
{
xdr_op_number = 8;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_WRITE_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_WRITE_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
/* XDR OP NUMBER = 9 */
if ( xdr_status )
{
xdr_op_number = 9;
xdr_status = XDR_RECV_HANDLE( srv, &user_data );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_record_write_fusion_result = pbm_record_write_fusion(pb_id, rec_id_ptr, cat, num_fields, data_buf, data_buf_size, cb1, user_data);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_record_write_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &rec_id_ptr, XDR_SEND_UINT16, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_record_write_fusion_0x00010003 */
static void pbm_reg_event_cb_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
PBM_EVENT_FUNC_fusion cb1;
pbm_return_type pbm_reg_event_cb_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_EVENT_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_EVENT_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_reg_event_cb_fusion_result = pbm_reg_event_cb_fusion(cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_reg_event_cb_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_reg_event_cb_fusion_0x00010003 */
static void pbm_write_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
pbm_device_type pb_id = PBM_DEFAULT;
pbm_record_s_type *record = NULL;
PBM_WRITE_COMPAT_CB_FUNC_fusion cb1;
pbm_return_type pbm_write_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
XDR_RECV_POINTER( srv, &record, xdr_pbmlib_fusion_recv_pbm_record_s_type, xdr_status );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_WRITE_COMPAT_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_WRITE_COMPAT_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_write_fusion_result = pbm_write_fusion(pb_id, record, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_write_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
XDR_SEND_POINTER( srv, &record, xdr_pbmlib_fusion_send_pbm_record_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_write_fusion_0x00010003 */
static void pbm_write_lock_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
pbm_lock_type_e_type type = PBM_LOCK_NOT_INIT;
void *user_data = NULL;
PBM_WRITE_CB_FUNC_fusion cb1;
pbm_return_type pbm_write_lock_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &type );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_HANDLE( srv, &user_data );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_WRITE_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_WRITE_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_write_lock_fusion_result = pbm_write_lock_fusion(type, user_data, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_write_lock_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_write_lock_fusion_0x00010003 */
static void pbm_write_unlock_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
pbm_return_type pbm_write_unlock_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_write_unlock_fusion_result = pbm_write_unlock_fusion();
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_write_unlock_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_write_unlock_fusion_0x00010003 */
static void pbm_get_field_info_count_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean output_pointer_not_null;
pbm_device_type pb_id = PBM_DEFAULT;
pbm_cat_e_type cat = PBM_CAT_NONE;
int *num = NULL;
pbm_return_type pbm_get_field_info_count_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_ENUM( srv, &cat );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/* The server must know whether to allocate memory for the output parameter
* num or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
num = oncrpcxdr_mem_alloc( srv, sizeof(*num) );
}
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_get_field_info_count_fusion_result = pbm_get_field_info_count_fusion(pb_id, cat, num);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_get_field_info_count_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &num, XDR_SEND_INT, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_get_field_info_count_fusion_0x00010003 */
static void pbm_get_field_info_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
int i;
boolean output_pointer_not_null;
uint32 length_uint32;
int length_int;
pbm_device_type pb_id = PBM_DEFAULT;
pbm_cat_e_type cat = PBM_CAT_NONE;
pbm_field_info_s_type *pf = NULL;
int size = 0;
pbm_return_type pbm_get_field_info_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_ENUM( srv, &cat );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/* The server must know whether to allocate memory for the output parameter
* pf or not. A boolean is received to indicate that. The maximum number
* of objects that could be pointed to by this pointer is also received.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
xdr_status = XDR_RECV_UINT32( srv, &length_uint32 );
pf = oncrpcxdr_mem_alloc( srv, length_uint32 * sizeof(*pf) );
}
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_INT( srv, &size );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_get_field_info_fusion_result = pbm_get_field_info_fusion(pb_id, cat, pf, size);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_get_field_info_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
if ( pf != NULL ) {
length_int = (size/sizeof(pbm_field_info_s_type));
length_int = ( length_int > 80 ? 80 : length_int );
xdr_status = XDR_SEND_INT( srv, &length_int );
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
/* Calling array of XDR routines */
for ( i = 0; xdr_status && i < (length_int); i++ ) {
/*lint -save -e545*/
xdr_status = xdr_pbmlib_fusion_send_pbm_field_info_s_type( srv, &(pf[i]) );
/*lint -restore */
}
}
} else {
length_int = 0;
xdr_status = XDR_SEND_INT( srv, &length_int );
}
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_get_field_info_fusion_0x00010003 */
static void pbm_record_validate_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
void *memset_temp;
int length_int;
pbm_device_type pb_id = PBM_DEFAULT;
uint16 rec_id = 0;
pbm_cat_e_type cat = PBM_CAT_NONE;
uint8 *data_buf = NULL;
int data_buf_size = 0;
int num_fields = 0;
pbm_return_type pbm_record_validate_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT16( srv, &rec_id );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_ENUM( srv, &cat );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_INT( srv, &length_int );
/* XDR OP NUMBER = 5 */
if ( xdr_status && length_int > 0 )
{
xdr_op_number = 5;
memset_temp = oncrpcxdr_mem_alloc( srv, length_int * sizeof( *data_buf ));
memset(memset_temp, 0, length_int * sizeof( *data_buf ));
data_buf = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, data_buf, length_int);
}
}
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_RECV_INT( srv, &data_buf_size );
}
/* XDR OP NUMBER = 7 */
if ( xdr_status )
{
xdr_op_number = 7;
xdr_status = XDR_RECV_INT( srv, &num_fields );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_record_validate_fusion_result = pbm_record_validate_fusion(pb_id, rec_id, cat, data_buf, data_buf_size, num_fields);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_record_validate_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_record_validate_fusion_0x00010003 */
static void pbm_clear_phonebook_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
pbm_device_type pb_id = PBM_DEFAULT;
pbm_return_type pbm_clear_phonebook_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &pb_id );
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_clear_phonebook_fusion_result = pbm_clear_phonebook_fusion(pb_id);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_clear_phonebook_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_clear_phonebook_fusion_0x00010003 */
static void pbm_emergency_number_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
void *memset_temp;
byte length_byte;
byte *num = NULL;
byte len = 0;
boolean pbm_emergency_number_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT8( srv, &length_byte );
/* XDR OP NUMBER = 2 */
if ( xdr_status && length_byte > 0 )
{
xdr_op_number = 2;
memset_temp = oncrpcxdr_mem_alloc( srv, length_byte * sizeof( *num ));
memset(memset_temp, 0, length_byte * sizeof( *num ));
num = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, num, length_byte);
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT8( srv, &len );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_emergency_number_fusion_result = pbm_emergency_number_fusion(num, len);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_BOOLEAN( srv, &pbm_emergency_number_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_emergency_number_fusion_0x00010003 */
static void pbm_emergency_number_cat_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
void *memset_temp;
byte length_byte;
boolean output_pointer_not_null;
byte *num = NULL;
byte len = 0;
uint8 *ecc_category_ptr = NULL;
boolean pbm_emergency_number_cat_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT8( srv, &length_byte );
/* XDR OP NUMBER = 2 */
if ( xdr_status && length_byte > 0 )
{
xdr_op_number = 2;
memset_temp = oncrpcxdr_mem_alloc( srv, length_byte * sizeof( *num ));
memset(memset_temp, 0, length_byte * sizeof( *num ));
num = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, num, length_byte);
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT8( srv, &len );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
/* The server must know whether to allocate memory for the output parameter
* ecc_category_ptr or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
ecc_category_ptr = oncrpcxdr_mem_alloc( srv, sizeof(*ecc_category_ptr) );
}
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_emergency_number_cat_fusion_result = pbm_emergency_number_cat_fusion(num, len, ecc_category_ptr);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_BOOLEAN( srv, &pbm_emergency_number_cat_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &ecc_category_ptr, XDR_SEND_UINT8, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_emergency_number_cat_fusion_0x00010003 */
static void pbm_session_emergency_number_cat_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
void *memset_temp;
byte length_byte;
boolean output_pointer_not_null;
pbm_session_enum_type sess_type = PBM_SESSION_DEFAULT;
byte *num = NULL;
byte len = 0;
uint8 *ecc_category_ptr = NULL;
boolean pbm_session_emergency_number_cat_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_ENUM( srv, &sess_type );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT8( srv, &length_byte );
/* XDR OP NUMBER = 3 */
if ( xdr_status && length_byte > 0 )
{
xdr_op_number = 3;
memset_temp = oncrpcxdr_mem_alloc( srv, length_byte * sizeof( *num ));
memset(memset_temp, 0, length_byte * sizeof( *num ));
num = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, num, length_byte);
}
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_UINT8( srv, &len );
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
/* The server must know whether to allocate memory for the output parameter
* ecc_category_ptr or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
ecc_category_ptr = oncrpcxdr_mem_alloc( srv, sizeof(*ecc_category_ptr) );
}
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_emergency_number_cat_fusion_result = pbm_session_emergency_number_cat_fusion(sess_type, num, len, ecc_category_ptr);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_BOOLEAN( srv, &pbm_session_emergency_number_cat_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &ecc_category_ptr, XDR_SEND_UINT8, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_emergency_number_cat_fusion_0x00010003 */
static void pbm_number_match_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
void *memset_temp;
byte length_byte;
byte *sim_num = NULL;
byte sim_num_len = 0;
byte *dialed_num = NULL;
byte dialed_num_len = 0;
boolean pbm_number_match_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT8( srv, &length_byte );
/* XDR OP NUMBER = 2 */
if ( xdr_status && length_byte > 0 )
{
xdr_op_number = 2;
memset_temp = oncrpcxdr_mem_alloc( srv, length_byte * sizeof( *sim_num ));
memset(memset_temp, 0, length_byte * sizeof( *sim_num ));
sim_num = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, sim_num, length_byte);
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT8( srv, &sim_num_len );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_UINT8( srv, &length_byte );
/* XDR OP NUMBER = 5 */
if ( xdr_status && length_byte > 0 )
{
xdr_op_number = 5;
memset_temp = oncrpcxdr_mem_alloc( srv, length_byte * sizeof( *dialed_num ));
memset(memset_temp, 0, length_byte * sizeof( *dialed_num ));
dialed_num = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, dialed_num, length_byte);
}
}
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_RECV_UINT8( srv, &dialed_num_len );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_number_match_fusion_result = pbm_number_match_fusion(sim_num, sim_num_len, dialed_num, dialed_num_len);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_BOOLEAN( srv, &pbm_number_match_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_number_match_fusion_0x00010003 */
static void pbm_fdn_number_match_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
void *memset_temp;
byte length_byte;
byte *sim_num = NULL;
byte sim_num_len = 0;
byte *dialed_num = NULL;
byte dialed_num_len = 0;
boolean pbm_fdn_number_match_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT8( srv, &length_byte );
/* XDR OP NUMBER = 2 */
if ( xdr_status && length_byte > 0 )
{
xdr_op_number = 2;
memset_temp = oncrpcxdr_mem_alloc( srv, length_byte * sizeof( *sim_num ));
memset(memset_temp, 0, length_byte * sizeof( *sim_num ));
sim_num = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, sim_num, length_byte);
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT8( srv, &sim_num_len );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_UINT8( srv, &length_byte );
/* XDR OP NUMBER = 5 */
if ( xdr_status && length_byte > 0 )
{
xdr_op_number = 5;
memset_temp = oncrpcxdr_mem_alloc( srv, length_byte * sizeof( *dialed_num ));
memset(memset_temp, 0, length_byte * sizeof( *dialed_num ));
dialed_num = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, dialed_num, length_byte);
}
}
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_RECV_UINT8( srv, &dialed_num_len );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_fdn_number_match_fusion_result = pbm_fdn_number_match_fusion(sim_num, sim_num_len, dialed_num, dialed_num_len);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_BOOLEAN( srv, &pbm_fdn_number_match_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_fdn_number_match_fusion_0x00010003 */
static void pbm_notify_register_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
PBM_NOTIFY_FUNC_fusion cb1;
void *user_data = NULL;
pbm_return_type pbm_notify_register_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_NOTIFY_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_NOTIFY_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_HANDLE( srv, &user_data );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_notify_register_fusion_result = pbm_notify_register_fusion(cb1, user_data);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_notify_register_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_notify_register_fusion_0x00010003 */
static void pbm_notify_unregister_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
PBM_NOTIFY_FUNC_fusion cb1;
void *user_data = NULL;
pbm_return_type pbm_notify_unregister_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_NOTIFY_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_NOTIFY_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_HANDLE( srv, &user_data );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_notify_unregister_fusion_result = pbm_notify_unregister_fusion(cb1, user_data);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_notify_unregister_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_notify_unregister_fusion_0x00010003 */
static void pbm_have_uids_changed_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean pbm_have_uids_changed_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_have_uids_changed_fusion_result = pbm_have_uids_changed_fusion();
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_BOOLEAN( srv, &pbm_have_uids_changed_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_have_uids_changed_fusion_0x00010003 */
static void pbm_validate_uid_changes_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
pbm_return_type pbm_validate_uid_changes_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_validate_uid_changes_fusion_result = pbm_validate_uid_changes_fusion();
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_validate_uid_changes_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_validate_uid_changes_fusion_0x00010003 */
static void pbm_session_enum_rec_init_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
void *memset_temp;
uint16 length_uint16;
pbm_phonebook_type pb_id;
uint16 category = 0;
pbm_field_id_e_type field_id = 0;
uint8 *data_ptr = NULL;
uint16 data_size = 0;
uint32 flags = 0;
pbm_return_type pbm_session_enum_rec_init_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT16( srv, &category );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT16( srv, &field_id );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_UINT16( srv, &length_uint16 );
/* XDR OP NUMBER = 5 */
if ( xdr_status && length_uint16 > 0 )
{
xdr_op_number = 5;
memset_temp = oncrpcxdr_mem_alloc( srv, length_uint16 * sizeof( *data_ptr ));
memset(memset_temp, 0, length_uint16 * sizeof( *data_ptr ));
data_ptr = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, data_ptr, length_uint16);
}
}
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_RECV_UINT16( srv, &data_size );
}
/* XDR OP NUMBER = 7 */
if ( xdr_status )
{
xdr_op_number = 7;
xdr_status = XDR_RECV_UINT32( srv, &flags );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_enum_rec_init_fusion_result = pbm_session_enum_rec_init_fusion(pb_id, category, field_id, data_ptr, data_size, flags);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_enum_rec_init_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_enum_rec_init_fusion_0x00010003 */
static void pbm_session_enum_next_rec_id_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean output_pointer_not_null;
uint32 *rec_id_ptr = NULL;
pbm_return_type pbm_session_enum_next_rec_id_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
/* The server must know whether to allocate memory for the output parameter
* rec_id_ptr or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
rec_id_ptr = oncrpcxdr_mem_alloc( srv, sizeof(*rec_id_ptr) );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_enum_next_rec_id_fusion_result = pbm_session_enum_next_rec_id_fusion(rec_id_ptr);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_enum_next_rec_id_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &rec_id_ptr, XDR_SEND_UINT32, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_enum_next_rec_id_fusion_0x00010003 */
static void pbm_session_enum_rec_init_ext_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
void *memset_temp;
uint16 length_uint16;
boolean output_pointer_not_null;
pbm_phonebook_type pb_id;
uint16 category = 0;
pbm_field_id_e_type field_id = 0;
uint8 *data_ptr = NULL;
uint16 data_size = 0;
uint32 flags = 0;
uint8 *handle = NULL;
pbm_return_type pbm_session_enum_rec_init_ext_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT16( srv, &category );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT16( srv, &field_id );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_UINT16( srv, &length_uint16 );
/* XDR OP NUMBER = 5 */
if ( xdr_status && length_uint16 > 0 )
{
xdr_op_number = 5;
memset_temp = oncrpcxdr_mem_alloc( srv, length_uint16 * sizeof( *data_ptr ));
memset(memset_temp, 0, length_uint16 * sizeof( *data_ptr ));
data_ptr = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, data_ptr, length_uint16);
}
}
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_RECV_UINT16( srv, &data_size );
}
/* XDR OP NUMBER = 7 */
if ( xdr_status )
{
xdr_op_number = 7;
xdr_status = XDR_RECV_UINT32( srv, &flags );
}
/* XDR OP NUMBER = 8 */
if ( xdr_status )
{
xdr_op_number = 8;
/* The server must know whether to allocate memory for the output parameter
* handle or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
handle = oncrpcxdr_mem_alloc( srv, sizeof(*handle) );
}
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_enum_rec_init_ext_fusion_result = pbm_session_enum_rec_init_ext_fusion(pb_id, category, field_id, data_ptr, data_size, flags, handle);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_enum_rec_init_ext_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &handle, XDR_SEND_UINT8, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_enum_rec_init_ext_fusion_0x00010003 */
static void pbm_session_enum_rec_init_ext_free_handle_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint8 handle = 0;
pbm_return_type pbm_session_enum_rec_init_ext_free_handle_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT8( srv, &handle );
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_enum_rec_init_ext_free_handle_fusion_result = pbm_session_enum_rec_init_ext_free_handle_fusion(handle);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_enum_rec_init_ext_free_handle_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_enum_rec_init_ext_free_handle_fusion_0x00010003 */
static void pbm_session_enum_next_rec_id_ext_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean output_pointer_not_null;
uint32 *rec_id_ptr = NULL;
uint8 handle = 0;
pbm_return_type pbm_session_enum_next_rec_id_ext_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
/* The server must know whether to allocate memory for the output parameter
* rec_id_ptr or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
rec_id_ptr = oncrpcxdr_mem_alloc( srv, sizeof(*rec_id_ptr) );
}
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT8( srv, &handle );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_enum_next_rec_id_ext_fusion_result = pbm_session_enum_next_rec_id_ext_fusion(rec_id_ptr, handle);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_enum_next_rec_id_ext_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &rec_id_ptr, XDR_SEND_UINT32, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_enum_next_rec_id_ext_fusion_0x00010003 */
static void pbm_session_find_location_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean output_pointer_not_null;
pbm_phonebook_type pb_id;
int index = 0;
pbm_record_s_type *data = NULL;
pbm_return_type pbm_session_find_location_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_INT( srv, &index );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/* The server must know whether to allocate memory for the output parameter
* data or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
data = oncrpcxdr_mem_alloc( srv, sizeof(*data) );
}
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_find_location_fusion_result = pbm_session_find_location_fusion(pb_id, index, data);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_find_location_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
XDR_SEND_POINTER( srv, &data, xdr_pbmlib_fusion_send_pbm_record_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_find_location_fusion_0x00010003 */
static void pbm_session_find_name_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
void *memset_temp;
uint32 length_uint32;
boolean output_pointer_not_null;
pbm_phonebook_type pb_id;
char *name = NULL;
pbm_record_s_type *data = NULL;
PBM_FIND_CB_FUNC_fusion cb1;
pbm_return_type pbm_session_find_name_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT32( srv, &length_uint32 );
/* XDR OP NUMBER = 3 */
if ( xdr_status && length_uint32 > 0 )
{
xdr_op_number = 3;
if ( name == NULL ) {
memset_temp = oncrpcxdr_mem_alloc( srv, length_uint32);
memset(memset_temp, 0, length_uint32);
name = memset_temp;
}
xdr_status = XDR_RECV_STRING(srv, name, length_uint32);
}
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
/* The server must know whether to allocate memory for the output parameter
* data or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
data = oncrpcxdr_mem_alloc( srv, sizeof(*data) );
}
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_FIND_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_FIND_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_find_name_fusion_result = pbm_session_find_name_fusion(pb_id, name, data, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_find_name_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
XDR_SEND_POINTER( srv, &data, xdr_pbmlib_fusion_send_pbm_record_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_find_name_fusion_0x00010003 */
static void pbm_session_find_number_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
void *memset_temp;
int length_int;
boolean output_pointer_not_null;
pbm_phonebook_type pb_id;
byte *number = NULL;
int loc_number_len = 0;
pbm_record_s_type *record = NULL;
PBM_FIND_CB_FUNC_fusion cb1;
pbm_return_type pbm_session_find_number_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_INT( srv, &length_int );
/* XDR OP NUMBER = 3 */
if ( xdr_status && length_int > 0 )
{
xdr_op_number = 3;
memset_temp = oncrpcxdr_mem_alloc( srv, length_int * sizeof( *number ));
memset(memset_temp, 0, length_int * sizeof( *number ));
number = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, number, length_int);
}
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_INT( srv, &loc_number_len );
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
/* The server must know whether to allocate memory for the output parameter
* record or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
record = oncrpcxdr_mem_alloc( srv, sizeof(*record) );
}
}
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_FIND_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_FIND_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_find_number_fusion_result = pbm_session_find_number_fusion(pb_id, number, loc_number_len, record, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_find_number_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
XDR_SEND_POINTER( srv, &record, xdr_pbmlib_fusion_send_pbm_record_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_find_number_fusion_0x00010003 */
static void pbm_session_get_num_recs_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
pbm_phonebook_type pb_id;
uint16 pbm_session_get_num_recs_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_get_num_recs_fusion_result = pbm_session_get_num_recs_fusion(pb_id);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_UINT16( srv, &pbm_session_get_num_recs_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_get_num_recs_fusion_0x00010003 */
static void pbm_session_calculate_fields_size_from_id_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 rec_id = 0;
int pbm_session_calculate_fields_size_from_id_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT32( srv, &rec_id );
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_calculate_fields_size_from_id_fusion_result = pbm_session_calculate_fields_size_from_id_fusion(rec_id);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_INT( srv, &pbm_session_calculate_fields_size_from_id_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_calculate_fields_size_from_id_fusion_0x00010003 */
static void pbm_session_record_read_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean output_pointer_not_null;
uint32 length_uint32;
uint32 rec_id = 0;
uint16 *category_ptr = NULL;
int *num_fields_ptr = NULL;
uint8 *data_buf = NULL;
uint32 data_buf_size = 0;
pbm_return_type pbm_session_record_read_fusion_result;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = XDR_RECV_UINT32( srv, &rec_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
/* The server must know whether to allocate memory for the output parameter
* category_ptr or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
category_ptr = oncrpcxdr_mem_alloc( srv, sizeof(*category_ptr) );
}
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/* The server must know whether to allocate memory for the output parameter
* num_fields_ptr or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
num_fields_ptr = oncrpcxdr_mem_alloc( srv, sizeof(*num_fields_ptr) );
}
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
/* The server must know whether to allocate memory for the output parameter
* data_buf or not. A boolean is received to indicate that. The maximum number
* of objects that could be pointed to by this pointer is also received.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
xdr_status = XDR_RECV_UINT32( srv, &length_uint32 );
data_buf = oncrpcxdr_mem_alloc( srv, length_uint32 * sizeof(*data_buf) );
}
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
xdr_status = XDR_RECV_UINT32( srv, &data_buf_size );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_record_read_fusion_result = pbm_session_record_read_fusion(rec_id, category_ptr, num_fields_ptr, data_buf, data_buf_size);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_record_read_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &category_ptr, XDR_SEND_UINT16, xdr_status );
/*lint -restore */
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &num_fields_ptr, XDR_SEND_INT, xdr_status );
/*lint -restore */
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
if ( data_buf != NULL ) {
length_uint32 = data_buf_size;
length_uint32 = ( length_uint32 > 1500 ? 1500 : length_uint32 );
xdr_status = XDR_SEND_UINT32( srv, &length_uint32 );
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_SEND_BYTES(srv, data_buf, length_uint32);
}
} else {
length_uint32 = 0;
xdr_status = XDR_SEND_UINT32( srv, &length_uint32 );
}
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_record_read_fusion_0x00010003 */
static void pbm_session_record_write_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
void *memset_temp;
int length_int;
pbm_phonebook_type pb_id;
uint32 *rec_id_ptr = NULL;
uint16 cat = 0;
int num_fields = 0;
uint8 *data_buf = NULL;
int data_buf_size = 0;
PBM_WRITE_CB_FUNC_fusion cb1;
void *user_data = NULL;
pbm_return_type pbm_session_record_write_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
/*lint -save -e123*/
XDR_RECV_POINTER( srv, &rec_id_ptr, XDR_RECV_UINT32, xdr_status );
/*lint -restore */
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT16( srv, &cat );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_INT( srv, &num_fields );
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
xdr_status = XDR_RECV_INT( srv, &length_int );
/* XDR OP NUMBER = 6 */
if ( xdr_status && length_int > 0 )
{
xdr_op_number = 6;
memset_temp = oncrpcxdr_mem_alloc( srv, length_int * sizeof( *data_buf ));
memset(memset_temp, 0, length_int * sizeof( *data_buf ));
data_buf = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, data_buf, length_int);
}
}
/* XDR OP NUMBER = 7 */
if ( xdr_status )
{
xdr_op_number = 7;
xdr_status = XDR_RECV_INT( srv, &data_buf_size );
}
/* XDR OP NUMBER = 8 */
if ( xdr_status )
{
xdr_op_number = 8;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_WRITE_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_WRITE_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
/* XDR OP NUMBER = 9 */
if ( xdr_status )
{
xdr_op_number = 9;
xdr_status = XDR_RECV_HANDLE( srv, &user_data );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_record_write_fusion_result = pbm_session_record_write_fusion(pb_id, rec_id_ptr, cat, num_fields, data_buf, data_buf_size, cb1, user_data);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_record_write_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &rec_id_ptr, XDR_SEND_UINT32, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_record_write_fusion_0x00010003 */
static void pbm_session_write_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
pbm_phonebook_type pb_id;
pbm_record_s_type *record = NULL;
PBM_WRITE_COMPAT_CB_FUNC_fusion cb1;
pbm_return_type pbm_session_write_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
XDR_RECV_POINTER( srv, &record, xdr_pbmlib_fusion_recv_pbm_record_s_type, xdr_status );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_WRITE_COMPAT_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_WRITE_COMPAT_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_write_fusion_result = pbm_session_write_fusion(pb_id, record, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_write_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
XDR_SEND_POINTER( srv, &record, xdr_pbmlib_fusion_send_pbm_record_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_write_fusion_0x00010003 */
static void pbm_session_get_field_info_count_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean output_pointer_not_null;
pbm_phonebook_type pb_id;
pbm_cat_e_type cat = PBM_CAT_NONE;
int *num = NULL;
pbm_return_type pbm_session_get_field_info_count_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_ENUM( srv, &cat );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/* The server must know whether to allocate memory for the output parameter
* num or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
num = oncrpcxdr_mem_alloc( srv, sizeof(*num) );
}
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_get_field_info_count_fusion_result = pbm_session_get_field_info_count_fusion(pb_id, cat, num);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_get_field_info_count_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &num, XDR_SEND_INT, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_get_field_info_count_fusion_0x00010003 */
static void pbm_session_get_field_info_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
int i;
boolean output_pointer_not_null;
uint32 length_uint32;
int length_int;
pbm_phonebook_type pb_id;
pbm_cat_e_type cat = PBM_CAT_NONE;
pbm_field_info_s_type *pf = NULL;
int size = 0;
pbm_return_type pbm_session_get_field_info_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_ENUM( srv, &cat );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/* The server must know whether to allocate memory for the output parameter
* pf or not. A boolean is received to indicate that. The maximum number
* of objects that could be pointed to by this pointer is also received.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
xdr_status = XDR_RECV_UINT32( srv, &length_uint32 );
pf = oncrpcxdr_mem_alloc( srv, length_uint32 * sizeof(*pf) );
}
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_INT( srv, &size );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_get_field_info_fusion_result = pbm_session_get_field_info_fusion(pb_id, cat, pf, size);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_get_field_info_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
if ( pf != NULL ) {
length_int = (size/sizeof(pbm_field_info_s_type));
length_int = ( length_int > 80 ? 80 : length_int );
xdr_status = XDR_SEND_INT( srv, &length_int );
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
/* Calling array of XDR routines */
for ( i = 0; xdr_status && i < (length_int); i++ ) {
/*lint -save -e545*/
xdr_status = xdr_pbmlib_fusion_send_pbm_field_info_s_type( srv, &(pf[i]) );
/*lint -restore */
}
}
} else {
length_int = 0;
xdr_status = XDR_SEND_INT( srv, &length_int );
}
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_get_field_info_fusion_0x00010003 */
static void pbm_session_record_validate_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
void *memset_temp;
int length_int;
pbm_phonebook_type pb_id;
uint32 rec_id = 0;
pbm_cat_e_type cat = PBM_CAT_NONE;
uint8 *data_buf = NULL;
int data_buf_size = 0;
int num_fields = 0;
pbm_return_type pbm_session_record_validate_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT32( srv, &rec_id );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_RECV_ENUM( srv, &cat );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_RECV_INT( srv, &length_int );
/* XDR OP NUMBER = 5 */
if ( xdr_status && length_int > 0 )
{
xdr_op_number = 5;
memset_temp = oncrpcxdr_mem_alloc( srv, length_int * sizeof( *data_buf ));
memset(memset_temp, 0, length_int * sizeof( *data_buf ));
data_buf = memset_temp;
xdr_status = XDR_RECV_BYTES(srv, data_buf, length_int);
}
}
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_RECV_INT( srv, &data_buf_size );
}
/* XDR OP NUMBER = 7 */
if ( xdr_status )
{
xdr_op_number = 7;
xdr_status = XDR_RECV_INT( srv, &num_fields );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_record_validate_fusion_result = pbm_session_record_validate_fusion(pb_id, rec_id, cat, data_buf, data_buf_size, num_fields);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_record_validate_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_record_validate_fusion_0x00010003 */
static void pbm_session_clear_phonebook_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
pbm_phonebook_type pb_id;
pbm_return_type pbm_session_clear_phonebook_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_clear_phonebook_fusion_result = pbm_session_clear_phonebook_fusion(pb_id);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_clear_phonebook_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_clear_phonebook_fusion_0x00010003 */
static void pbm_session_extended_file_info_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
boolean output_pointer_not_null;
pbm_phonebook_type pb_id;
pbm_extended_fileinfo_s_type *info = NULL;
pbm_return_type pbm_session_extended_file_info_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
/* The server must know whether to allocate memory for the output parameter
* info or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
info = oncrpcxdr_mem_alloc( srv, sizeof(*info) );
}
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_extended_file_info_fusion_result = pbm_session_extended_file_info_fusion(pb_id, info);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_extended_file_info_fusion_result );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
XDR_SEND_POINTER( srv, &info, xdr_pbmlib_fusion_send_pbm_extended_fileinfo_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_extended_file_info_fusion_0x00010003 */
static void pbm_session_extended_file_info_async_fusion_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 cb_id1;
pbm_phonebook_type pb_id;
PBM_SESSION_EXTENDED_FILE_INFO_CB_FUNC_fusion cb1;
pbm_return_type pbm_session_extended_file_info_async_fusion_result;
/*
* For struct or union parameters, use memset to zero out their memory on
* the stack to make sure any pointer members are initialized to NULL
*/
memset( (void *) &pb_id, 0, sizeof(pb_id) );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_pbmlib_fusion_recv_pbm_phonebook_type( srv, &pb_id );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_RECV_UINT32( srv, &cb_id1 );
}
/* Assignment added to suppress compiler warnings */
cb1 = NULL;
if ( xdr_status )
{
/*lint -save -e611*/
cb1 = (PBM_SESSION_EXTENDED_FILE_INFO_CB_FUNC_fusion) rpc_svc_callback_register( (void *) PBM_SESSION_EXTENDED_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003, srv, cb_id1 );
/*lint -restore */
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbm_session_extended_file_info_async_fusion_result = pbm_session_extended_file_info_async_fusion(pb_id, cb1);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_ENUM( srv, &pbm_session_extended_file_info_async_fusion_result );
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbm_session_extended_file_info_async_fusion_0x00010003 */
/*===========================================================================
API Standard function for api versioning
===========================================================================*/
static void pbmlib_fusion_api_versions_0x00010003( xdr_s_type *srv )
{
boolean xdr_status = TRUE;
int xdr_op_number = 0;
uint32 i;
boolean output_pointer_not_null;
uint32 length_uint32;
uint32 *len = NULL;
uint32 *pbmlib_fusion_api_versions_result = NULL;
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
/* The server must know whether to allocate memory for the output parameter
* len or not. A boolean is received to indicate that.
*/
xdr_status = XDR_RECV_UINT8( srv, &output_pointer_not_null );
if ( xdr_status && output_pointer_not_null ) {
len = oncrpcxdr_mem_alloc( srv, sizeof(*len) );
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( srv ) || ! xdr_status ) {
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_decode reply
svcerr_decode( srv );
return;
}
pbmlib_fusion_api_versions_result = pbmlib_fusion_api_versions(len);
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_reply_msg_start( srv, &Pbmlib_fusionVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
if ( pbmlib_fusion_api_versions_result != NULL && len != NULL) {
length_uint32 = *len;
xdr_status = XDR_SEND_UINT32( srv, &length_uint32 );
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/* Calling array of XDR routines */
for ( i = 0; xdr_status && i < (length_uint32); i++ ) {
/*lint -save -e545*/
xdr_status = XDR_SEND_UINT32( srv, &(pbmlib_fusion_api_versions_result[i]) );
/*lint -restore */
}
}
} else {
length_uint32 = 0;
xdr_status = XDR_SEND_UINT32( srv, &length_uint32 );
}
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
/*lint -save -e123*/
XDR_SEND_POINTER( srv, &len, XDR_SEND_UINT32, xdr_status );
/*lint -restore */
}
if ( ! xdr_status )
{
XDR_OP_ERR( srv, xdr_op_number );
// send svcerr_systemerr reply
svcerr_systemerr( srv );
return;
}
if ( ! XDR_MSG_SEND( srv, NULL ) ) {
XDR_MSG_SEND_ERR( srv, NULL );
}
} /* pbmlib_fusion_api_versions_0x00010003 */
/*===========================================================================
API Callback Clients
===========================================================================*/
static void PBM_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003(
pbm_return_type ret,
pbm_device_type pb_id,
int records_used,
int number_of_records,
int text_len
)
{
xdr_s_type *clnt = NULL;
rpc_reply_header reply_header;
rpc_cb_data_type *rpc_cb_data = NULL;
boolean xdr_status = TRUE;
int xdr_op_number = 0;
rpc_cb_data = rpc_svc_cb_data_lookup();
if ( rpc_cb_data == NULL )
{
RPC_SVC_CB_DATA_LOOKUP_ERR();
return;
}
clnt = rpc_clnt_for_callback( rpc_cb_data );
oncrpcxdr_mem_free( clnt );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_call_msg_start( clnt,
PBMLIB_FUSIONCBPROG, PBM_FILE_INFO_CB_FUNC_FUSION_VERS,
ONCRPC_PBM_FILE_INFO_CB_FUNC_FUSION_PROC, &Pbmlib_fusioncbCred, &Pbmlib_fusioncbVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_UINT32( clnt, &rpc_cb_data->cb_id );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_SEND_ENUM( clnt, &ret );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_SEND_ENUM( clnt, &pb_id );
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
xdr_status = XDR_SEND_INT( clnt, &records_used );
}
/* XDR OP NUMBER = 6 */
if ( xdr_status )
{
xdr_op_number = 6;
xdr_status = XDR_SEND_INT( clnt, &number_of_records );
}
/* XDR OP NUMBER = 7 */
if ( xdr_status )
{
xdr_op_number = 7;
xdr_status = XDR_SEND_INT( clnt, &text_len );
}
if ( ! xdr_status )
{
XDR_OP_ERR(clnt, xdr_op_number);
return;
}
/* Send the RPC message and block waiting for a reply */
if ( ! XDR_MSG_SEND( clnt, &reply_header ) )
{
XDR_MSG_SEND_ERR( clnt, &reply_header );
return;
}
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( reply_header.stat != RPC_MSG_ACCEPTED ) {
XDR_CALL_REJECTED_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( reply_header.u.ar.stat != RPC_ACCEPT_SUCCESS ) {
XDR_ERR_ON_SERVER_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( clnt ) || ! xdr_status )
{
XDR_OP_ERR( clnt, xdr_op_number );
return;
}
} /* PBM_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003 */
static void PBM_EXTENDED_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003(pbm_return_type ret, pbm_device_type pb_id, pbm_extended_fileinfo_s_type *info)
{
xdr_s_type *clnt = NULL;
rpc_reply_header reply_header;
rpc_cb_data_type *rpc_cb_data = NULL;
boolean xdr_status = TRUE;
int xdr_op_number = 0;
rpc_cb_data = rpc_svc_cb_data_lookup();
if ( rpc_cb_data == NULL )
{
RPC_SVC_CB_DATA_LOOKUP_ERR();
return;
}
clnt = rpc_clnt_for_callback( rpc_cb_data );
oncrpcxdr_mem_free( clnt );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_call_msg_start( clnt,
PBMLIB_FUSIONCBPROG, PBM_EXTENDED_FILE_INFO_CB_FUNC_FUSION_VERS,
ONCRPC_PBM_EXTENDED_FILE_INFO_CB_FUNC_FUSION_PROC, &Pbmlib_fusioncbCred, &Pbmlib_fusioncbVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_UINT32( clnt, &rpc_cb_data->cb_id );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_SEND_ENUM( clnt, &ret );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = XDR_SEND_ENUM( clnt, &pb_id );
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
XDR_SEND_POINTER( clnt, &info, xdr_pbmlib_fusion_send_pbm_extended_fileinfo_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR(clnt, xdr_op_number);
return;
}
/* Send the RPC message and block waiting for a reply */
if ( ! XDR_MSG_SEND( clnt, &reply_header ) )
{
XDR_MSG_SEND_ERR( clnt, &reply_header );
return;
}
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( reply_header.stat != RPC_MSG_ACCEPTED ) {
XDR_CALL_REJECTED_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( reply_header.u.ar.stat != RPC_ACCEPT_SUCCESS ) {
XDR_ERR_ON_SERVER_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( clnt ) || ! xdr_status )
{
XDR_OP_ERR( clnt, xdr_op_number );
return;
}
} /* PBM_EXTENDED_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003 */
static void PBM_FIND_CB_FUNC_fusion_clnt_0x00010003(pbm_return_type ret, pbm_record_s_type *rec)
{
xdr_s_type *clnt = NULL;
rpc_reply_header reply_header;
rpc_cb_data_type *rpc_cb_data = NULL;
boolean xdr_status = TRUE;
int xdr_op_number = 0;
rpc_cb_data = rpc_svc_cb_data_lookup();
if ( rpc_cb_data == NULL )
{
RPC_SVC_CB_DATA_LOOKUP_ERR();
return;
}
clnt = rpc_clnt_for_callback( rpc_cb_data );
oncrpcxdr_mem_free( clnt );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_call_msg_start( clnt,
PBMLIB_FUSIONCBPROG, PBM_FIND_CB_FUNC_FUSION_VERS,
ONCRPC_PBM_FIND_CB_FUNC_FUSION_PROC, &Pbmlib_fusioncbCred, &Pbmlib_fusioncbVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_UINT32( clnt, &rpc_cb_data->cb_id );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_SEND_ENUM( clnt, &ret );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
XDR_SEND_POINTER( clnt, &rec, xdr_pbmlib_fusion_send_pbm_record_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR(clnt, xdr_op_number);
return;
}
/* Send the RPC message and block waiting for a reply */
if ( ! XDR_MSG_SEND( clnt, &reply_header ) )
{
XDR_MSG_SEND_ERR( clnt, &reply_header );
return;
}
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( reply_header.stat != RPC_MSG_ACCEPTED ) {
XDR_CALL_REJECTED_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( reply_header.u.ar.stat != RPC_ACCEPT_SUCCESS ) {
XDR_ERR_ON_SERVER_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( clnt ) || ! xdr_status )
{
XDR_OP_ERR( clnt, xdr_op_number );
return;
}
} /* PBM_FIND_CB_FUNC_fusion_clnt_0x00010003 */
static void PBM_WRITE_CB_FUNC_fusion_clnt_0x00010003(pbm_writecb_data_s_type *cb_data)
{
xdr_s_type *clnt = NULL;
rpc_reply_header reply_header;
rpc_cb_data_type *rpc_cb_data = NULL;
boolean xdr_status = TRUE;
int xdr_op_number = 0;
rpc_cb_data = rpc_svc_cb_data_lookup();
if ( rpc_cb_data == NULL )
{
RPC_SVC_CB_DATA_LOOKUP_ERR();
return;
}
clnt = rpc_clnt_for_callback( rpc_cb_data );
oncrpcxdr_mem_free( clnt );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_call_msg_start( clnt,
PBMLIB_FUSIONCBPROG, PBM_WRITE_CB_FUNC_FUSION_VERS,
ONCRPC_PBM_WRITE_CB_FUNC_FUSION_PROC, &Pbmlib_fusioncbCred, &Pbmlib_fusioncbVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_UINT32( clnt, &rpc_cb_data->cb_id );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
XDR_SEND_POINTER( clnt, &cb_data, xdr_pbmlib_fusion_send_pbm_writecb_data_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR(clnt, xdr_op_number);
return;
}
/* Send the RPC message and block waiting for a reply */
if ( ! XDR_MSG_SEND( clnt, &reply_header ) )
{
XDR_MSG_SEND_ERR( clnt, &reply_header );
return;
}
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( reply_header.stat != RPC_MSG_ACCEPTED ) {
XDR_CALL_REJECTED_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( reply_header.u.ar.stat != RPC_ACCEPT_SUCCESS ) {
XDR_ERR_ON_SERVER_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( clnt ) || ! xdr_status )
{
XDR_OP_ERR( clnt, xdr_op_number );
return;
}
} /* PBM_WRITE_CB_FUNC_fusion_clnt_0x00010003 */
static void PBM_EVENT_FUNC_fusion_clnt_0x00010003(boolean ready)
{
xdr_s_type *clnt = NULL;
rpc_reply_header reply_header;
rpc_cb_data_type *rpc_cb_data = NULL;
boolean xdr_status = TRUE;
int xdr_op_number = 0;
rpc_cb_data = rpc_svc_cb_data_lookup();
if ( rpc_cb_data == NULL )
{
RPC_SVC_CB_DATA_LOOKUP_ERR();
return;
}
clnt = rpc_clnt_for_callback( rpc_cb_data );
oncrpcxdr_mem_free( clnt );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_call_msg_start( clnt,
PBMLIB_FUSIONCBPROG, PBM_EVENT_FUNC_FUSION_VERS,
ONCRPC_PBM_EVENT_FUNC_FUSION_PROC, &Pbmlib_fusioncbCred, &Pbmlib_fusioncbVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_UINT32( clnt, &rpc_cb_data->cb_id );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_SEND_BOOLEAN( clnt, &ready );
}
if ( ! xdr_status )
{
XDR_OP_ERR(clnt, xdr_op_number);
return;
}
/* Send the RPC message and block waiting for a reply */
if ( ! XDR_MSG_SEND( clnt, &reply_header ) )
{
XDR_MSG_SEND_ERR( clnt, &reply_header );
return;
}
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( reply_header.stat != RPC_MSG_ACCEPTED ) {
XDR_CALL_REJECTED_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( reply_header.u.ar.stat != RPC_ACCEPT_SUCCESS ) {
XDR_ERR_ON_SERVER_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( clnt ) || ! xdr_status )
{
XDR_OP_ERR( clnt, xdr_op_number );
return;
}
} /* PBM_EVENT_FUNC_fusion_clnt_0x00010003 */
static void PBM_WRITE_COMPAT_CB_FUNC_fusion_clnt_0x00010003(pbm_return_type ret)
{
xdr_s_type *clnt = NULL;
rpc_reply_header reply_header;
rpc_cb_data_type *rpc_cb_data = NULL;
boolean xdr_status = TRUE;
int xdr_op_number = 0;
rpc_cb_data = rpc_svc_cb_data_lookup();
if ( rpc_cb_data == NULL )
{
RPC_SVC_CB_DATA_LOOKUP_ERR();
return;
}
clnt = rpc_clnt_for_callback( rpc_cb_data );
oncrpcxdr_mem_free( clnt );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_call_msg_start( clnt,
PBMLIB_FUSIONCBPROG, PBM_WRITE_COMPAT_CB_FUNC_FUSION_VERS,
ONCRPC_PBM_WRITE_COMPAT_CB_FUNC_FUSION_PROC, &Pbmlib_fusioncbCred, &Pbmlib_fusioncbVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_UINT32( clnt, &rpc_cb_data->cb_id );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_SEND_ENUM( clnt, &ret );
}
if ( ! xdr_status )
{
XDR_OP_ERR(clnt, xdr_op_number);
return;
}
/* Send the RPC message and block waiting for a reply */
if ( ! XDR_MSG_SEND( clnt, &reply_header ) )
{
XDR_MSG_SEND_ERR( clnt, &reply_header );
return;
}
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( reply_header.stat != RPC_MSG_ACCEPTED ) {
XDR_CALL_REJECTED_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( reply_header.u.ar.stat != RPC_ACCEPT_SUCCESS ) {
XDR_ERR_ON_SERVER_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( clnt ) || ! xdr_status )
{
XDR_OP_ERR( clnt, xdr_op_number );
return;
}
} /* PBM_WRITE_COMPAT_CB_FUNC_fusion_clnt_0x00010003 */
static void PBM_NOTIFY_FUNC_fusion_clnt_0x00010003(void *user_data, pbm_notify_data_s_type *notify_data)
{
xdr_s_type *clnt = NULL;
rpc_reply_header reply_header;
rpc_cb_data_type *rpc_cb_data = NULL;
boolean xdr_status = TRUE;
int xdr_op_number = 0;
rpc_cb_data = rpc_svc_cb_data_lookup();
if ( rpc_cb_data == NULL )
{
RPC_SVC_CB_DATA_LOOKUP_ERR();
return;
}
clnt = rpc_clnt_for_callback( rpc_cb_data );
oncrpcxdr_mem_free( clnt );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_call_msg_start( clnt,
PBMLIB_FUSIONCBPROG, PBM_NOTIFY_FUNC_FUSION_VERS,
ONCRPC_PBM_NOTIFY_FUNC_FUSION_PROC, &Pbmlib_fusioncbCred, &Pbmlib_fusioncbVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_UINT32( clnt, &rpc_cb_data->cb_id );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_SEND_HANDLE( clnt, &user_data );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
XDR_SEND_POINTER( clnt, ¬ify_data, xdr_pbmlib_fusion_send_pbm_notify_data_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR(clnt, xdr_op_number);
return;
}
/* Send the RPC message and block waiting for a reply */
if ( ! XDR_MSG_SEND( clnt, &reply_header ) )
{
XDR_MSG_SEND_ERR( clnt, &reply_header );
return;
}
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( reply_header.stat != RPC_MSG_ACCEPTED ) {
XDR_CALL_REJECTED_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( reply_header.u.ar.stat != RPC_ACCEPT_SUCCESS ) {
XDR_ERR_ON_SERVER_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( clnt ) || ! xdr_status )
{
XDR_OP_ERR( clnt, xdr_op_number );
return;
}
} /* PBM_NOTIFY_FUNC_fusion_clnt_0x00010003 */
static void PBM_SESSION_EXTENDED_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003(pbm_return_type ret, pbm_phonebook_type pb_id, pbm_extended_fileinfo_s_type *info)
{
xdr_s_type *clnt = NULL;
rpc_reply_header reply_header;
rpc_cb_data_type *rpc_cb_data = NULL;
boolean xdr_status = TRUE;
int xdr_op_number = 0;
rpc_cb_data = rpc_svc_cb_data_lookup();
if ( rpc_cb_data == NULL )
{
RPC_SVC_CB_DATA_LOOKUP_ERR();
return;
}
clnt = rpc_clnt_for_callback( rpc_cb_data );
oncrpcxdr_mem_free( clnt );
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
xdr_status = xdr_call_msg_start( clnt,
PBMLIB_FUSIONCBPROG, PBM_SESSION_EXTENDED_FILE_INFO_CB_FUNC_FUSION_VERS,
ONCRPC_PBM_SESSION_EXTENDED_FILE_INFO_CB_FUNC_FUSION_PROC, &Pbmlib_fusioncbCred, &Pbmlib_fusioncbVerf );
/* XDR OP NUMBER = 2 */
if ( xdr_status )
{
xdr_op_number = 2;
xdr_status = XDR_SEND_UINT32( clnt, &rpc_cb_data->cb_id );
}
/* XDR OP NUMBER = 3 */
if ( xdr_status )
{
xdr_op_number = 3;
xdr_status = XDR_SEND_ENUM( clnt, &ret );
}
/* XDR OP NUMBER = 4 */
if ( xdr_status )
{
xdr_op_number = 4;
xdr_status = xdr_pbmlib_fusion_send_pbm_phonebook_type( clnt, &pb_id );
}
/* XDR OP NUMBER = 5 */
if ( xdr_status )
{
xdr_op_number = 5;
XDR_SEND_POINTER( clnt, &info, xdr_pbmlib_fusion_send_pbm_extended_fileinfo_s_type, xdr_status );
}
if ( ! xdr_status )
{
XDR_OP_ERR(clnt, xdr_op_number);
return;
}
/* Send the RPC message and block waiting for a reply */
if ( ! XDR_MSG_SEND( clnt, &reply_header ) )
{
XDR_MSG_SEND_ERR( clnt, &reply_header );
return;
}
/* XDR OP NUMBER = 1 */
xdr_op_number = 1;
if ( reply_header.stat != RPC_MSG_ACCEPTED ) {
XDR_CALL_REJECTED_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( reply_header.u.ar.stat != RPC_ACCEPT_SUCCESS ) {
XDR_ERR_ON_SERVER_ERR( clnt, &reply_header );
xdr_status = FALSE;
}
if ( xdr_status )
{
xdr_op_number++;
}
if ( ! XDR_MSG_DONE( clnt ) || ! xdr_status )
{
XDR_OP_ERR( clnt, xdr_op_number );
return;
}
} /* PBM_SESSION_EXTENDED_FILE_INFO_CB_FUNC_fusion_clnt_0x00010003 */
| C | CL | 88bb810a11457cc1c69b19016ac7ef355d872fc3a5ef014cf21c07cda8ea64b4 |
/* Last Update on 2014-03-19 */
/* Add a factor of 1.4 in the .eps field */
/* Update on 2014-02-20 */
/* In this version, data are dumped to one single core (ThisTask = 0) that writes. */
/* In the old version, zero values are generated in random snapshots on UMASS, no clue yet. */
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef OUTPUT_TIPSY
#ifdef HAVE_HDF5
#include <hdf5.h>
#endif
#include "allvars.h"
#include "proto.h"
#include "tipsydefs_n2.h"
/*! \file io_tipsy.c
* \brief Output of a snapshot file to disk in tipsy binary/aux/idnum format.
*/
static int n_type[6];
static long long ntot_type_all[6];
static MyFloat unit_Time, unit_Density, unit_Length, unit_Mass, unit_Velocity;
static FILE *binfile, *auxfile, *idfile;
#ifdef OUTPUT_TIPSY_AW
static FILE *awfile;
#endif
static int task;
static int n_for_this_task;
/*! This function writes a snapshot of the particle distribution to one or
* several files using Gadget's default file format. If
* NumFilesPerSnapshot>1, the snapshot is distributed into several files,
* which are written simultaneously. Each file contains data from a group of
* processors of size roughly NTask/NumFilesPerSnapshot.
*/
void savetipsy(int num)
{
size_t bytes;
int i,n;
void tipsy_write_gas(),tipsy_write_dark(),tipsy_write_star(),tipsy_write_aux_gas(),tipsy_write_aux_star(),tipsy_write_idnum();
#ifdef OUTPUT_TIPSY_AW
void tipsy_write_aw_gas();
#endif
double t0, t1;
CPU_Step[CPU_MISC] += measure_time();
#if defined(SFR) || defined(BLACK_HOLES)
rearrange_particle_sequence();
/* ensures that new tree will be constructed */
All.NumForcesSinceLastDomainDecomp = (long long) (1 + All.TreeDomainUpdateFrequency * All.TotNumPart);
#endif
if(!(CommBuffer = mymalloc(bytes = All.BufferSize * 1024 * 1024)))
{
printf("failed to allocate memory for `CommBuffer' (%g MB).\n", bytes / (1024.0 * 1024.0));
endrun(2);
}
/* determine global and local particle numbers */
for(n = 0; n < 6; n++)
n_type[n] = 0;
for(n = 0; n < NumPart; n++)
n_type[P[n].Type]++;
sumup_large_ints(6, n_type, ntot_type_all);
if(DumpFlag) {
if(ThisTask == 0){
printf("\nwriting tipsy snapshot files... \n");
/* Open files */
char buf[500];
sprintf(buf, "%s%s_%03d.bin", All.OutputDir, All.SnapshotFileBase, num);
binfile = fopen(buf, "w");
sprintf(buf, "%s%s_%03d.aux", All.OutputDir, All.SnapshotFileBase, num);
auxfile = fopen(buf, "w");
sprintf(buf, "%s%s_%03d.idnum", All.OutputDir, All.SnapshotFileBase, num);
idfile = fopen(buf, "w");
#ifdef OUTPUT_TIPSY_AW
sprintf(buf, "%s%s_%03d.aw", All.OutputDir, All.SnapshotFileBase, num);
awfile = fopen(buf, "w");
#endif
}
/* Output tipsy header */
if(ThisTask == 0) {
tipsy_header.time = All.Time;
tipsy_header.ndim = 3;
for( i=0, tipsy_header.nbodies=0; i<6; i++ ) tipsy_header.nbodies += ntot_type_all[i];
tipsy_header.nsph = ntot_type_all[0];
tipsy_header.ndark = ntot_type_all[1];
tipsy_header.nstar = ntot_type_all[4];
// fprintf(stdout,"savetipsy: %g %d %d %d %d\n",tipsy_header.time,tipsy_header.nbodies,tipsy_header.nsph,tipsy_header.ndark,tipsy_header.nstar);
my_fwrite(&tipsy_header, sizeof(tipsy_header), 1, binfile);
}
MPI_Barrier(MPI_COMM_WORLD);
/* Output tipsy binary */
t0 = second();
cosmounits();
tipsy_write_gas(0);
tipsy_write_dark(1);
tipsy_write_star(4);
MPI_Barrier(MPI_COMM_WORLD);
if(ThisTask == 0)
fclose(binfile);
t1 = second();
if(ThisTask == 0) printf("outputting tipsy binary file took = %g sec\n", timediff(t0, t1));
/* Output auxiliary file */
t0 = second();
tipsy_write_aux_gas(0);
tipsy_write_aux_star(4);
MPI_Barrier(MPI_COMM_WORLD);
if(ThisTask == 0)
fclose(auxfile);
t1 = second();
if(ThisTask == 0) printf("outputting auxiliary file took = %g sec\n", timediff(t0, t1));
#ifdef OUTPUT_TIPSY_AW
/* Output analytic wind file */
t0 = second();
tipsy_write_aw_gas(0);
MPI_Barrier(MPI_COMM_WORLD);
if(ThisTask == 0)
fclose(awfile);
t1 = second();
if(ThisTask == 0) printf("outputting analytic wind file took = %g sec\n", timediff(t0, t1));
#endif
/* Output idnum file */
t0 = second();
tipsy_write_idnum();
MPI_Barrier(MPI_COMM_WORLD);
if(ThisTask == 0)
fclose(idfile);
t1 = second();
if(ThisTask == 0) printf("outputting idnum file took = %g sec\n", timediff(t0, t1));
}
myfree(CommBuffer);
return;
}
/* Outputs tipsy gas particles, with Gadget particle type itype (usually =0) */
void tipsy_write_gas(int itype)
{
struct gas_particle gasp;
MyOutputFloat Temp,metal_tot;
MyFloat MeanWeight,a3inv=1;
int i,j;
MPI_Status status;
int pc, blockmaxlen, blocklen, offset=0;
struct gas_particle *write_buffer;
blockmaxlen = ((int) (All.BufferSize * 1024 * 1024)) / sizeof(gasp);
/* Output gas particles */
if(All.ComovingIntegrationOn) a3inv = 1. / (All.Time*All.Time*All.Time);
for(task = 0; task < NTask; task++){
// IMPORT/EXPORT N_TYPE
if(task == ThisTask){
n_for_this_task = n_type[itype];
for(i=0; i<NTask; i++)
if(i != ThisTask)
MPI_Send(&n_for_this_task, 1, MPI_INT,
i, TAG_NFORTHISTASK, MPI_COMM_WORLD);
}
else
MPI_Recv(&n_for_this_task, 1, MPI_INT,
task, TAG_NFORTHISTASK, MPI_COMM_WORLD, &status);
//By Now, On ALL cores, n_for_this_task = task.n_type[itype]
while(n_for_this_task > 0){
write_buffer = (struct gas_particle *) CommBuffer;
pc = n_for_this_task;
if(pc > blockmaxlen)
pc = blockmaxlen;
blocklen = pc;
if(task == ThisTask){
// FILL BUFFER
for( i=offset; i<NumPart; i++ ) {
if( P[i].Type != itype ) continue;
gasp.mass = P[i].Mass*All.UnitMass_in_g/unit_Mass;
gasp.pos[0] = P[i].Pos[0]*All.UnitLength_in_cm/unit_Length-0.5;
gasp.pos[1] = P[i].Pos[1]*All.UnitLength_in_cm/unit_Length-0.5;
gasp.pos[2] = P[i].Pos[2]*All.UnitLength_in_cm/unit_Length-0.5;
gasp.vel[0] = P[i].Vel[0]*All.UnitVelocity_in_cm_per_s/unit_Velocity/sqrt(All.Time);
gasp.vel[1] = P[i].Vel[1]*All.UnitVelocity_in_cm_per_s/unit_Velocity/sqrt(All.Time);
gasp.vel[2] = P[i].Vel[2]*All.UnitVelocity_in_cm_per_s/unit_Velocity/sqrt(All.Time);
gasp.phi = P[i].p.Potential*All.UnitVelocity_in_cm_per_s*All.UnitVelocity_in_cm_per_s/(unit_Velocity*unit_Velocity);
MeanWeight= 4.0/(3*HYDROGEN_MASSFRAC+1+4*HYDROGEN_MASSFRAC*SphP[i].Ne)*PROTONMASS;
#ifndef DENSITY_INDEPENDENT_SPH
Temp = DMAX(All.MinEgySpec, SphP[i].Entropy / GAMMA_MINUS1 * pow(SphP[i].d.Density * a3inv, GAMMA_MINUS1)); // internal energy so far
#else
Temp = DMAX(All.MinEgySpec, SphP[i].Entropy / GAMMA_MINUS1 * pow(SphP[i].EgyWtDensity * a3inv, GAMMA_MINUS1));
#endif
#if defined(ANALYTIC_WINDS) && !defined(WIND_ENTROPY)
if(SphP[i].wind_flag == 1)
Temp = DMAX(All.MinEgySpec, SphP[i].Entropy);
#endif
Temp *= MeanWeight/BOLTZMANN * GAMMA_MINUS1 * All.UnitEnergy_in_cgs/ All.UnitMass_in_g; // now convert to T
gasp.temp = Temp;
gasp.hsmooth = SphP[i].Hsml*All.UnitLength_in_cm/unit_Length;
/* gasp.hsmooth = sqrt(GAMMA * SphP[i].Pressure / SphP[i].d.Density) * All.cf_afac3; SoundSpeed */
gasp.rho = SphP[i].d.Density*All.UnitMass_in_g/(All.UnitLength_in_cm*All.UnitLength_in_cm*All.UnitLength_in_cm*unit_Density);
#ifdef ANALYTIC_WINDS
if(SphP[i].wind_flag == 1)
/* gasp.rho = SphP[i].ambient_density*All.UnitMass_in_g/(All.UnitLength_in_cm*All.UnitLength_in_cm*All.UnitLength_in_cm*unit_Density); */
gasp.rho = get_cloud_density(i)*All.UnitMass_in_g/(All.UnitLength_in_cm*All.UnitLength_in_cm*All.UnitLength_in_cm*unit_Density);
#endif
#ifdef METALS
for( j=0,metal_tot=0.; j<NMETALS; j++ ) metal_tot += P[i].Metallicity[j];
gasp.metals = metal_tot;
#else
gasp.metals = 0.;
#endif
*write_buffer++ = gasp;
pc --;
if( pc == 0 ) break;
}
offset = i+1; // tested, i++ is not done
// Send data ONLY to write_task ONLY WHEN ThisTask != 0
if(ThisTask != 0)
MPI_Ssend(CommBuffer, sizeof(gasp)*blocklen, MPI_BYTE,
0, TAG_PDATA, MPI_COMM_WORLD);
// Ssend: blocking synchronous send
} // task != ThisTask
else{
// Receive data ONLY when task != (ThisTask == 0)
if(ThisTask == 0)
MPI_Recv(CommBuffer, sizeof(gasp)*blocklen, MPI_BYTE,
task, TAG_PDATA, MPI_COMM_WORLD, &status);
}
if(ThisTask == 0)
my_fwrite(CommBuffer, sizeof(gasp), blocklen, binfile);
// NOTE: n_for_this_task must be imported from "task" to writeTask(0)
n_for_this_task -= blocklen;
} // while loop
} // task loop
return;
}
/* Outputs tipsy dark particles, with Gadget particle type itype (ex: 1,2,3) */
void tipsy_write_dark(int itype)
{
struct dark_particle darkp;
int i;
MPI_Status status;
int pc, blockmaxlen, blocklen, offset=0;
struct dark_particle *write_buffer;
blockmaxlen = ((int) (All.BufferSize * 1024 * 1024)) / sizeof(darkp);
/* Output halo particles */
for(task = 0; task < NTask; task++){
// IMPORT/EXPORT N_TYPE
if(task == ThisTask){
n_for_this_task = n_type[itype];
for(i=0; i<NTask; i++)
if(i != ThisTask)
MPI_Send(&n_for_this_task, 1, MPI_INT,
i, TAG_NFORTHISTASK, MPI_COMM_WORLD);
}
else
MPI_Recv(&n_for_this_task, 1, MPI_INT,
task, TAG_NFORTHISTASK, MPI_COMM_WORLD, &status);
while(n_for_this_task > 0){
write_buffer = (struct dark_particle *) CommBuffer;
pc = n_for_this_task;
if(pc > blockmaxlen)
pc = blockmaxlen;
blocklen = pc;
if(task == ThisTask){
// FILL BUFFER
for( i=offset; i<NumPart; i++ ) {
if( P[i].Type != itype ) continue;
darkp.mass = P[i].Mass*All.UnitMass_in_g/unit_Mass;
darkp.pos[0] = P[i].Pos[0]*All.UnitLength_in_cm/unit_Length-0.5;
darkp.pos[1] = P[i].Pos[1]*All.UnitLength_in_cm/unit_Length-0.5;
darkp.pos[2] = P[i].Pos[2]*All.UnitLength_in_cm/unit_Length-0.5;
darkp.vel[0] = P[i].Vel[0]*All.UnitVelocity_in_cm_per_s/unit_Velocity/sqrt(All.Time);
darkp.vel[1] = P[i].Vel[1]*All.UnitVelocity_in_cm_per_s/unit_Velocity/sqrt(All.Time);
darkp.vel[2] = P[i].Vel[2]*All.UnitVelocity_in_cm_per_s/unit_Velocity/sqrt(All.Time);
darkp.phi = P[i].p.Potential*All.UnitVelocity_in_cm_per_s*All.UnitVelocity_in_cm_per_s/(unit_Velocity*unit_Velocity);
darkp.eps = 1.4 * All.SofteningHalo*All.UnitLength_in_cm/unit_Length;
*write_buffer++ = darkp;
pc --;
if( pc == 0 ) break;
}
offset = i+1;
// Send data
if(ThisTask != 0)
MPI_Ssend(CommBuffer, sizeof(darkp)*blocklen, MPI_BYTE,
0, TAG_PDATA, MPI_COMM_WORLD);
}
else{
if(ThisTask == 0)
MPI_Recv(CommBuffer, sizeof(darkp)*blocklen, MPI_BYTE,
task, TAG_PDATA, MPI_COMM_WORLD, &status);
}
if(ThisTask == 0)
my_fwrite(CommBuffer, sizeof(darkp), blocklen, binfile);
n_for_this_task -= blocklen;
}
}
return;
}
/* Outputs tipsy star particles, with Gadget particle type itype (usually =4) */
void tipsy_write_star(int itype)
{
struct star_particle starp;
MyOutputFloat metal_tot;
double get_time_from_step();
int i,j;
MPI_Status status;
int pc, blockmaxlen, blocklen, offset=0;
struct star_particle *write_buffer;
blockmaxlen = ((int) (All.BufferSize * 1024 * 1024)) / sizeof(starp);
/* Output star particles */
for(task = 0; task < NTask; task++){
// IMPORT/EXPORT N_TYPE
if(task == ThisTask){
n_for_this_task = n_type[itype];
for(i=0; i<NTask; i++)
if(i != ThisTask)
MPI_Send(&n_for_this_task, 1, MPI_INT,
i, TAG_NFORTHISTASK, MPI_COMM_WORLD);
}
else
MPI_Recv(&n_for_this_task, 1, MPI_INT,
task, TAG_NFORTHISTASK, MPI_COMM_WORLD, &status);
while(n_for_this_task > 0){
write_buffer = (struct star_particle *) CommBuffer;
pc = n_for_this_task;
if(pc > blockmaxlen)
pc = blockmaxlen;
blocklen = pc;
if(task == ThisTask){
// FILL BUFFER
for( i=offset; i<NumPart; i++ ) {
if( P[i].Type != itype ) continue;
starp.mass = P[i].Mass*All.UnitMass_in_g/unit_Mass;
starp.pos[0] = P[i].Pos[0]*All.UnitLength_in_cm/unit_Length-0.5;
starp.pos[1] = P[i].Pos[1]*All.UnitLength_in_cm/unit_Length-0.5;
starp.pos[2] = P[i].Pos[2]*All.UnitLength_in_cm/unit_Length-0.5;
starp.vel[0] = P[i].Vel[0]*All.UnitVelocity_in_cm_per_s/unit_Velocity/sqrt(All.Time);
starp.vel[1] = P[i].Vel[1]*All.UnitVelocity_in_cm_per_s/unit_Velocity/sqrt(All.Time);
starp.vel[2] = P[i].Vel[2]*All.UnitVelocity_in_cm_per_s/unit_Velocity/sqrt(All.Time);
starp.phi = P[i].p.Potential*All.UnitVelocity_in_cm_per_s*All.UnitVelocity_in_cm_per_s/(unit_Velocity*unit_Velocity);
starp.eps = 1.4 * All.SofteningHalo*All.UnitLength_in_cm/unit_Length;
#ifdef STELLARAGE
starp.tform = get_time_from_step(All.Ti_Current);
#endif
#ifdef METALS
for( j=0,metal_tot=0.; j<NMETALS; j++ ) metal_tot += P[i].Metallicity[j];
starp.metals = metal_tot;
#else
starp.metals = 0.;
#endif
*write_buffer++ = starp; // Tricky 1
pc --;
if( pc == 0 ) break;
}
if(ThisTask != 0)
MPI_Ssend(CommBuffer, sizeof(starp)*blocklen, MPI_BYTE,
0, TAG_PDATA, MPI_COMM_WORLD);
}
else{
if(ThisTask == 0)
MPI_Recv(CommBuffer, sizeof(starp)*blocklen, MPI_BYTE,
task, TAG_PDATA, MPI_COMM_WORLD, &status);
}
if(ThisTask == 0)
my_fwrite(CommBuffer, sizeof(starp), blocklen, binfile);
n_for_this_task -= blocklen;
}
// NOTE: n_for_this_task must be imported from "task" to writeTask(0)
} // task loop
return;
}
void tipsy_write_aux_gas(int itype)
{
struct aux_gas_data auxgp;
MyFloat ne,nh0,nHeII;
MyFloat a3inv=1;
int i,j;
MPI_Status status;
int pc, blockmaxlen, blocklen, offset=0;
if(All.ComovingIntegrationOn) a3inv = 1 / (All.Time*All.Time*All.Time);
struct aux_gas_data *write_buffer;
blockmaxlen = ((int) (All.BufferSize * 1024 * 1024)) / sizeof(auxgp);
for(task = 0; task < NTask; task++){
if(task == ThisTask){
n_for_this_task = n_type[itype];
for(i=0; i<NTask; i++)
if(i != ThisTask)
MPI_Send(&n_for_this_task, 1, MPI_INT,
i, TAG_NFORTHISTASK, MPI_COMM_WORLD);
}
else
MPI_Recv(&n_for_this_task, 1, MPI_INT,
task, TAG_NFORTHISTASK, MPI_COMM_WORLD, &status);
while(n_for_this_task > 0){
write_buffer = (struct aux_gas_data *) CommBuffer;
pc = n_for_this_task;
if(pc > blockmaxlen)
pc = blockmaxlen;
blocklen = pc;
if(task == ThisTask){
for( i=offset; i<NumPart; i++ ) {
if( P[i].Type != itype ) continue;
for( j=0; j<NMETALS; j++ ) auxgp.metal[j] = P[i].Metallicity[j];
/* auxgp.metal[0] = SphP[i].h_eff; */
/* auxgp.metal[1] = SphP[i].MaxSignalVel * All.cf_afac3; */
/* auxgp.metal[2] = SphP[i].NV_DivVel; */
/* auxgp.metal[3] = SphP[i].NV_dt_DivVel; */
#ifdef SFR
auxgp.sfr = get_starformation_rate(i);
#else
auxgp.sfr = 0;
#endif
#ifdef OUTPUTTMAX
auxgp.tmax = P[i].Tmax;
#else
auxgp.tmax = 0.0;
#endif
#ifdef WINDS
auxgp.delaytime = SphP[i].DelayTime;
#else
auxgp.delaytime = 0.;
#endif
ne = SphP[i].Ne;
AbundanceRatios(DMAX(All.MinEgySpec, SphP[i].Entropy / GAMMA_MINUS1 * pow(SphP[i].d.Density * a3inv , GAMMA_MINUS1)), SphP[i].d.Density * a3inv, &ne, &nh0, &nHeII);
auxgp.ne = ne;
auxgp.nh = nh0;
#ifdef SFR
auxgp.nspawn = P[i].NumStarsGen;
#ifdef ANALYTIC_WINDS_DEBUG
auxgp.nspawn = P[i].TimeBin;
#endif
#else
auxgp.nspawn = 0;
#endif
/* SHUIYAO: 13-04-09 */
#ifdef WINDS
auxgp.nrec = P[i].Nrec;
#ifdef ANALYTIC_WINDS_DEBUG
auxgp.nrec = SphP[i].numngb_wind / SphP[i].numngb_evaluated;
#endif
#else
auxgp.nrec = 0;
#endif
/* SHUIYAO: 13-07-16 */
#ifdef OUTPUT_ALPHA
auxgp.alpha = SphP[i].alpha;
#endif
*write_buffer++ = auxgp;
pc --;
if(pc == 0) break;
}
offset = i + 1;
if(ThisTask != 0)
MPI_Ssend(CommBuffer, sizeof(auxgp)*blocklen, MPI_BYTE,
0, TAG_PDATA, MPI_COMM_WORLD);
}// task == ThisTask
else{
if(ThisTask == 0)
MPI_Recv(CommBuffer, sizeof(auxgp)*blocklen, MPI_BYTE,
task, TAG_PDATA, MPI_COMM_WORLD, &status);
}
if(ThisTask == 0)
my_fwrite(CommBuffer, sizeof(auxgp), blocklen, auxfile);
n_for_this_task -= blocklen;
} // while loop
}// task loop
return;
}
void tipsy_write_aux_star(int itype)
{
struct aux_star_data auxsp;
int i,j;
MPI_Status status;
int pc, blockmaxlen, blocklen, offset=0;
struct aux_star_data *write_buffer;
blockmaxlen = ((int) (All.BufferSize * 1024 * 1024)) / sizeof(auxsp);
for(task = 0; task < NTask; task++){
// IMPORT/EXPORT N_TYPE
if(task == ThisTask){
n_for_this_task = n_type[itype];
for(i=0; i<NTask; i++)
if(i != ThisTask)
MPI_Send(&n_for_this_task, 1, MPI_INT,
i, TAG_NFORTHISTASK, MPI_COMM_WORLD);
}
else
MPI_Recv(&n_for_this_task, 1, MPI_INT,
task, TAG_NFORTHISTASK, MPI_COMM_WORLD, &status);
while(n_for_this_task > 0){
write_buffer = (struct aux_star_data *) CommBuffer;
pc = n_for_this_task;
if(pc > blockmaxlen)
pc = blockmaxlen;
blocklen = pc;
if(task == ThisTask){
for( i=offset; i<NumPart; i++ ) {
if( P[i].Type != itype ) continue;
for( j=0; j<NMETALS; j++ ) auxsp.metal[j] = P[i].Metallicity[j];
#ifdef STELLARAGE
auxsp.age = P[i].StellarAge; // formation expansion factor (All.Time)
#else
auxsp.age = 0;
#endif
#ifdef OUTPUTTMAX
auxsp.tmax = P[i].Tmax;
#else
auxsp.tmax = 0;
#endif
#ifdef SFR
auxsp.nspawn = P[i].NumStarsGen;
#else
auxsp.nspawn = 0;
#endif
/* SHUIYAO: 13-04-09 */
#ifdef WINDS
auxsp.nrec = P[i].Nrec;
#else
auxsp.nrec = 0;
#endif
*write_buffer++ = auxsp;
pc --;
if( pc == 0 ) break;
}
offset = i+1;
if(ThisTask != 0)
MPI_Ssend(CommBuffer, sizeof(auxsp)*blocklen, MPI_BYTE,
0, TAG_PDATA, MPI_COMM_WORLD);
}
else{
if(ThisTask == 0)
MPI_Recv(CommBuffer, sizeof(auxsp)*blocklen, MPI_BYTE,
task, TAG_PDATA, MPI_COMM_WORLD, &status);
}
if(ThisTask == 0)
my_fwrite(CommBuffer, sizeof(auxsp), blocklen, auxfile);
n_for_this_task -= blocklen;
}
} // task loop
return;
}
void tipsy_write_idnum()
{
int i;
MPI_Status status;
int pc, blockmaxlen, blocklen;
int itype;
MyIDType *write_buffer;
blockmaxlen = ((int) (All.BufferSize * 1024 * 1024)) / sizeof(MyIDType);
// itype here
for(itype = 0; itype < 6; itype++){
if(itype == 2) continue;
if(itype == 3) continue;
if(itype == 5) continue;
for(task = 0; task < NTask; task++){
// IMPORT/EXPORT N_TYPE
if(task == ThisTask){
n_for_this_task = n_type[itype];
for(i=0; i<NTask; i++) // Starting from CPU 0 to Ntask-1
if(i != ThisTask)
MPI_Send(&n_for_this_task, 1, MPI_INT,
i, TAG_NFORTHISTASK, MPI_COMM_WORLD);
}
else
MPI_Recv(&n_for_this_task, 1, MPI_INT,
task, TAG_NFORTHISTASK, MPI_COMM_WORLD, &status);
// Every CPU receive n_type[itype] from CPU i
while(n_for_this_task > 0){
write_buffer = (MyIDType *) CommBuffer;
pc = n_for_this_task;
if(pc > blockmaxlen)
pc = blockmaxlen;
blocklen = pc;
if( task == ThisTask){
for( i=0; i<NumPart; i++ ) {
if( P[i].Type != itype ) continue;
*write_buffer++ = P[i].ID;
pc --;
if(pc == 0) break;
}
// Send data
if(ThisTask != 0)
MPI_Ssend(CommBuffer, sizeof(MyIDType)*blocklen, MPI_BYTE,
0, TAG_PDATA, MPI_COMM_WORLD);
}
else{
if(ThisTask == 0)
MPI_Recv(CommBuffer, sizeof(MyIDType)*blocklen, MPI_BYTE,
task, TAG_PDATA, MPI_COMM_WORLD, &status);
}
if(ThisTask == 0)
my_fwrite(CommBuffer, sizeof(MyIDType), blocklen, idfile);
n_for_this_task -= blocklen;
MPI_Barrier(MPI_COMM_WORLD);
}
}
}
return;
}
/* conversion to tipsy "standard" units: L=1,Omega=1 */
void cosmounits(void)
{
unit_Time=sqrt(8*M_PI/3)*CM_PER_MPC/(100*All.HubbleParam*1.e5);
unit_Density=1.8791E-29*All.HubbleParam*All.HubbleParam;
unit_Length=All.BoxSize*CM_PER_MPC*1.e-3;
unit_Mass=unit_Density*unit_Length*unit_Length*unit_Length/(All.HubbleParam*All.HubbleParam);
unit_Velocity=unit_Length/unit_Time;
return;
}
/* ************ MPI Parallel I/O Stuff *********************** */
/* Opens snapshot tipsy output file with given suffix for snapshot num */
MPI_File My_MPI_open(char *suffix, int num)
{
MPI_File fh;
char mpi_err_str[MPI_MAX_ERROR_STRING];
int mpi_err_strlen;
int mpi_err;
char buf[500];
sprintf(buf, "%s%s_%03d.%s", All.OutputDir, All.SnapshotFileBase, num, suffix);
if ((mpi_err = MPI_File_open(MPI_COMM_WORLD, buf,
MPI_MODE_WRONLY | MPI_MODE_CREATE,
MPI_INFO_NULL, &fh)) != MPI_SUCCESS) {
MPI_Error_string(mpi_err, mpi_err_str, &mpi_err_strlen);
printf("Proc %d: ", ThisTask);
printf("MPI_File_open failed (%s)\n", mpi_err_str);
endrun(1013);
}
return fh;
}
#endif // OUTPUT_TIPSY
#ifdef OUTPUTCOOLINGRATE
void write_coolingrate(int num)
{
int i;
char fname[300], mkcmd[200];
FILE *fcool;
double dtcool, dtcond, dmcool, u, dmdtcool;
sprintf(mkcmd, "mkdir -p %sCOOLING%03d", All.OutputDir, num);
system(mkcmd);
sprintf(fname, "%sCOOLING%03d/%s.%d", All.OutputDir, num, "cooling", ThisTask);
if(!(fcool = fopen(fname, "w")))
{
printf("can't open file `%s`\n", fname);
endrun(1183);
}
for(i=0;i<N_gas;i++){
u = SphP[i].Entropy / GAMMA_MINUS1 * pow(get_Density_for_Energy(i), GAMMA_MINUS1);
dtcool = u / SphP[i].dUcool * All.UnitTime_in_s / 3.1536e16; // Gyr
dtcond = u / SphP[i].dUcond * All.UnitTime_in_s / 3.1536e16; // Gyr
// dtcond = inf if dUcond == 0.0
dmdtcool = P[i].Mass / All.HubbleParam / dtcool; // 10^10Msolar/Gyr
fprintf(fcool, "%d %g %g %g %g %g %g\n",
P[i].ID, SphP[i].Mgal, dmdtcool,
dtcool,
SphP[i].dUcool, SphP[i].dUcond, SphP[i].dUvisc
);
}
fclose(fcool);
}
#endif // OUTPUTCOOLINGRATE
#ifdef OUTPUT_TIPSY_AW
void tipsy_write_aw_gas(int itype)
{
struct aw_gas_data awgp;
MyFloat a3inv=1;
int i,j;
MPI_Status status;
int pc, blockmaxlen, blocklen, offset=0;
double Uint, Temp, MeanWeight, u_ambient, dtime;
cosmounits();
if(All.ComovingIntegrationOn) a3inv = 1 / (All.Time*All.Time*All.Time);
struct aw_gas_data *write_buffer; // aw
blockmaxlen = ((int) (All.BufferSize * 1024 * 1024)) / sizeof(awgp);
for(task = 0; task < NTask; task++){
if(task == ThisTask){
n_for_this_task = n_type[itype];
for(i=0; i<NTask; i++)
if(i != ThisTask)
MPI_Send(&n_for_this_task, 1, MPI_INT,
i, TAG_NFORTHISTASK, MPI_COMM_WORLD);
}
else
MPI_Recv(&n_for_this_task, 1, MPI_INT,
task, TAG_NFORTHISTASK, MPI_COMM_WORLD, &status);
while(n_for_this_task > 0){
write_buffer = (struct aw_gas_data *) CommBuffer;
pc = n_for_this_task;
if(pc > blockmaxlen)
pc = blockmaxlen;
blocklen = pc;
if(task == ThisTask){
for( i=offset; i<NumPart; i++ ) {
if( P[i].Type != itype ) continue;
/* Set Value for awgp here */
/* -------------------------------- */
awgp.wind_flag = SphP[i].wind_flag;
#ifndef DISABLE_WIND_MASSLOSS
if(awgp.wind_flag > 0) awgp.wind_mass = P[i].Mass;
else awgp.wind_mass = SphP[i].WindMass;
#else
awgp.wind_mass = -1.0;
#endif
MeanWeight= 4.0/(3*HYDROGEN_MASSFRAC+1+4*HYDROGEN_MASSFRAC*SphP[i].Ne)*PROTONMASS;
// Internal Energy and Cooling Time
Uint = SphP[i].Entropy / GAMMA_MINUS1 * pow(get_Density_for_Energy(i), GAMMA_MINUS1);
if(SphP[i].wind_flag == 1) Uint = SphP[i].Entropy;
awgp.dtcool = Uint / SphP[i].dUcool * All.UnitTime_in_s / 3.1536e16; // Gyr
// dU/dt from wind impact; or dU/dt from wind
awgp.dudt = SphP[i].dUcond * All.UnitPressure_in_cgs / All.UnitDensity_in_cgs; // physical
dtime = ( (P[i].Ti_endstep - P[i].Ti_begstep) * All.Timebase_interval /
All.cf_hubble_a * All.UnitTime_in_s) / All.HubbleParam;
awgp.dudt /= dtime;
// Ambient Temperature and Density
Temp = DMAX(All.MinEgySpec, Uint);
Temp *= MeanWeight/BOLTZMANN * GAMMA_MINUS1 * All.UnitEnergy_in_cgs/ All.UnitMass_in_g;
if(SphP[i].wind_flag == 1)
u_ambient = SphP[i].u_ambient / SphP[i].kernel_sum_mass;
Temp = GAMMA_MINUS1 / BOLTZMANN * (u_ambient) * PROTONMASS * 0.62;
awgp.temp = Temp;
awgp.rho = SphP[i].d.Density*All.UnitMass_in_g/(All.UnitLength_in_cm*All.UnitLength_in_cm*All.UnitLength_in_cm*unit_Density);
if(SphP[i].wind_flag == 1)
awgp.rho = SphP[i].ambient_density*All.UnitMass_in_g/(All.UnitLength_in_cm*All.UnitLength_in_cm*All.UnitLength_in_cm*unit_Density);
// Cloud Radius
if(SphP[i].wind_flag > 0)
awgp.rcloud = SphP[i].r_cloud / CM_PER_MPC * 1.e3;
else awgp.rcloud = SphP[i].Hsml * All.atime / All.HubbleParam;
/* -------------------------------- */
*write_buffer++ = awgp;
pc --;
if(pc == 0) break;
}
offset = i + 1;
if(ThisTask != 0)
MPI_Ssend(CommBuffer, sizeof(awgp)*blocklen, MPI_BYTE,
0, TAG_PDATA, MPI_COMM_WORLD);
}// task == ThisTask
else{
if(ThisTask == 0)
MPI_Recv(CommBuffer, sizeof(awgp)*blocklen, MPI_BYTE,
task, TAG_PDATA, MPI_COMM_WORLD, &status);
}
if(ThisTask == 0)
my_fwrite(CommBuffer, sizeof(awgp), blocklen, awfile);
n_for_this_task -= blocklen;
} // while loop
}// task loop
return;
}
#endif
| C | CL | f74e6617cd668883b4ae277fc42339e66ae1746fb2abf4e5d3053320dd083e18 |
/**
******************************************************************************
* @file stm8s_itc.h
* @brief This file contains all functions prototype and macros for the ITC peripheral.
* @author STMicroelectronics - MCD Application Team
* @version V1.1.1
* @date 06/05/2009
******************************************************************************
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2009 STMicroelectronics</center></h2>
* @image html logo.bmp
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM8S_ITC_H__
#define __STM8S_ITC_H__
/* Includes ------------------------------------------------------------------*/
#include "stm8s.h"
/* Exported types ------------------------------------------------------------*/
/** @addtogroup ITC_Exported_Types
* @{
*/
/**
* @brief ITC Interrupt Lines selection
*/
typedef enum {
ITC_IRQ_TLI = (u8)0,
ITC_IRQ_AWU = (u8)1,
ITC_IRQ_CLK = (u8)2,
ITC_IRQ_PORTA = (u8)3,
ITC_IRQ_PORTB = (u8)4,
ITC_IRQ_PORTC = (u8)5,
ITC_IRQ_PORTD = (u8)6,
ITC_IRQ_PORTE = (u8)7,
#ifdef STM8S208
ITC_IRQ_CAN_RX = (u8)8,
ITC_IRQ_CAN_TX = (u8)9,
#endif /*STM8S208*/
#ifdef STM8S903
ITC_IRQ_PORTF = (u8)8,
#endif /*STM8S903*/
ITC_IRQ_SPI = (u8)10,
ITC_IRQ_TIM1_OVF = (u8)11,
ITC_IRQ_TIM1_CAPCOM = (u8)12,
#ifdef STM8S903
ITC_IRQ_TIM5_OVFTRI = (u8)13,
ITC_IRQ_TIM5_CAPCOM = (u8)14,
#else
ITC_IRQ_TIM2_OVF = (u8)13,
ITC_IRQ_TIM2_CAPCOM = (u8)14,
#endif /*STM8S903*/
ITC_IRQ_TIM3_OVF = (u8)15,
ITC_IRQ_TIM3_CAPCOM = (u8)16,
ITC_IRQ_UART1_TX = (u8)17,
ITC_IRQ_UART1_RX = (u8)18,
ITC_IRQ_I2C = (u8)19,
#ifdef STM8S105
ITC_IRQ_UART2_TX = (u8)20,
ITC_IRQ_UART2_RX = (u8)21,
#endif /*STM8S105*/
#if defined(STM8S208) ||defined(STM8S207)
ITC_IRQ_UART3_TX = (u8)20,
ITC_IRQ_UART3_RX = (u8)21,
ITC_IRQ_ADC2 = (u8)22,
#endif /*STM8S208 or STM8S207*/
#if defined(STM8S105) ||defined(STM8S103) ||defined(STM8S905)
ITC_IRQ_ADC1 = (u8)22,
#endif /*STM8S105, STM8S103 or STM8S905 */
#ifdef STM8S903
ITC_IRQ_TIM6_OVFTRI = (u8)23,
#else
ITC_IRQ_TIM4_OVF = (u8)23,
#endif /*STM8S903*/
ITC_IRQ_EEPROM_EEC = (u8)24
} ITC_Irq_TypeDef;
/**
* @brief ITC Priority Levels selection
*/
typedef enum {
ITC_PRIORITYLEVEL_0 = (u8)0x02, /*!< Software priority level 0 (cannot be written) */
ITC_PRIORITYLEVEL_1 = (u8)0x01, /*!< Software priority level 1 */
ITC_PRIORITYLEVEL_2 = (u8)0x00, /*!< Software priority level 2 */
ITC_PRIORITYLEVEL_3 = (u8)0x03 /*!< Software priority level 3 */
} ITC_PriorityLevel_TypeDef;
/**
* @}
*/
/* Exported constants --------------------------------------------------------*/
/** @addtogroup ITC_Exported_Constants
* @{
*/
#define CPU_SOFT_INT_DISABLED ((u8)0x28) /*!< Mask for I1 and I0 bits in CPU_CC register */
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/**
* @brief Macros used by the assert function in order to check the different functions parameters.
* @addtogroup ITC_Private_Macros
* @{
*/
/* Used by assert function */
#define IS_ITC_IRQ_OK(IRQ) ((IRQ) <= (u8)24)
/* Used by assert function */
#define IS_ITC_PRIORITY_OK(PriorityValue) \
(((PriorityValue) == ITC_PRIORITYLEVEL_0) || \
((PriorityValue) == ITC_PRIORITYLEVEL_1) || \
((PriorityValue) == ITC_PRIORITYLEVEL_2) || \
((PriorityValue) == ITC_PRIORITYLEVEL_3))
/* Used by assert function */
#define IS_ITC_INTERRUPTS_DISABLED (ITC_GetSoftIntStatus() == CPU_SOFT_INT_DISABLED)
/**
* @}
*/
/* Exported functions ------------------------------------------------------- */
/** @addtogroup ITC_Exported_Functions
* @{
*/
u8 ITC_GetCPUCC(void);
void ITC_DeInit(void);
u8 ITC_GetSoftIntStatus(void);
void ITC_SetSoftwarePriority(ITC_Irq_TypeDef IrqNum, ITC_PriorityLevel_TypeDef PriorityValue);
ITC_PriorityLevel_TypeDef ITC_GetSoftwarePriority(ITC_Irq_TypeDef IrqNum);
/**
* @}
*/
#endif /* __STM8S_ITC_H__ */
/******************* (C) COPYRIGHT 2009 STMicroelectronics *****END OF FILE****/
| C | CL | 28f07ada226f723918f5da2c43e70b15a8948e16774906543e7bf2cdd453e38c |
#include "board.h"
#include "io.h"
#include "lcd.h"
#define MAIN3
int cpt=0;
volatile int pushed=0;
//****************************************************************************
// functions prototypes
//****************************************************************************
extern void irq_enable();
extern void irq_disable();
//****************************************************************************
// Test EINT1 button
//****************************************************************************
#ifdef MAIN1
#define EXT_EINT0_BIT 0
#define EXT_EINT1_BIT 1
#define EXT_EINT2_BIT 2
#define EXT_EINT3_BIT 3
#define EXT_LEVEL_SENSITIVE 0
#define EXT_EDGE_SENSITIVE 1
#define EXT_LOW 0
#define EXT_HIGH 1
#define EXT_FALLING 0
#define EXT_RISING 1
// eint1_isr
// eint1 ISR (Interrupt Service Routine)
#ifdef __IRQ_HANDLER__
static void eint1_isr()
{
pushed = 1;
_EXTINT = 1<<EXT_EINT1_BIT;
}
#else
static __attribute__((interrupt("IRQ"))) void eint1_isr()
{
pushed = 1;
_EXTINT = 1<<EXT_EINT1_BIT;
_VICVectAddr=0;
}
#endif
int main()
{
lcd_init();
lcd_display(LCD_DISPLAY_DISPLAY_ON);
//==============================================================
// config external irq on P0.14
//==============================================================
io_configure(_IO0, IO_PIN_14, IO_PIN_FUNC2);
//_PINSEL0 = (_PINSEL0 & 0xCFFFFFFF) | 0x20000000; // EINT1 -> P0.14
// edge sensitive
_EXTMODE = (_EXTMODE & (~(1<<EXT_EINT1_BIT))) | (EXT_EDGE_SENSITIVE<<EXT_EINT1_BIT);
// rising edge
_EXTPOLAR = (_EXTMODE & (~(1<<EXT_EINT1_BIT))) | (EXT_RISING<<EXT_EINT1_BIT);
// acknowledge pending irq
_EXTINT = 1<<EXT_EINT1_BIT;
_VICVectAddr=0;
// interrupt config
_VICVectCntl4 = 0x2F;
_VICVectAddr4 = (uint32_t)eint1_isr;
_VICIntSelect &= 0xFFFF7FFF;
_VICIntEnable |= 0x8000;
//==============================================================
irq_enable();
while (1) {
if (pushed) {
lcd_clear();
lcd_home();
lcd_printf("%d",++cpt);
pushed=0;
}
}
return 0;
}
#endif
//****************************************************************************
// Test Timer0
//****************************************************************************
#ifdef MAIN2
// TxCTCR (Timer Counter Control Register)
#define TxCTCR_CNT_RISEDGE_PCLK (0<<0)
#define TxCTCR_CNT_RISEDGE_CAPX (1<<0)
#define TxCTCR_CNT_FALEDGE_PCLK (2<<0)
#define TxCTCR_CNT_FALEDGE_CAPX (3<<0)
#define TxCTCR_CNT_INPUT_CAPX_0 (0<<2)
#define TxCTCR_CNT_INPUT_CAPX_1 (1<<2)
#define TxCTCR_CNT_INPUT_CAPX_2 (2<<2)
#define TxCTCR_CNT_INPUT_CAPX_3 (3<<2)
// TxTCR (Timer Control Register)
#define TxTCR_COUNTER_START (1<<0)
#define TxTCR_COUNTER_STOP (0)
#define TxTCR_COUNTER_RESET (1<<1)
// TxMCR (Match Control Register)
#define TxMCR_INT_ON_MR0 (1<<0) // MR0
#define TxMCR_RESET_ON_MR0 (1<<1)
#define TxMCR_STOP_ON_MR0 (1<<2)
#define TxMCR_INT_ON_MR1 (1<<3) // MR1
#define TxMCR_RESET_ON_MR1 (1<<4)
#define TxMCR_STOP_ON_MR1 (1<<5)
#define TxMCR_INT_ON_MR2 (1<<6) // MR2
#define TxMCR_RESET_ON_MR2 (1<<7)
#define TxMCR_STOP_ON_MR2 (1<<8)
#define TxMCR_INT_ON_MR3 (1<<9) // MR3
#define TxMCR_RESET_ON_MR3 (1<<10)
#define TxMCR_STOP_ON_MR3 (1<<11)
// TxIR (Interrupt Register)
#define TxIR_MR0_FLAG (1<<0)
#define TxIR_MR1_FLAG (1<<1)
#define TxIR_MR2_FLAG (1<<2)
#define TxIR_MR3_FLAG (1<<3)
#define TxIR_CR0_FLAG (1<<4)
#define TxIR_CR1_FLAG (1<<5)
#define TxIR_CR2_FLAG (1<<6)
#define TxIR_CR3_FLAG (1<<7)
volatile unsigned int time_ms=0;
#ifdef __IRQ_HANDLER__
static void timer0_isr()
{
time_ms++;
_T0IR = TxIR_MR0_FLAG; // Clear interrupt flag by writing 1 to Bit 0
}
#else
static __attribute__((interrupt("IRQ"))) void timer0_isr()
{
time_ms++;
_T0IR = TxIR_MR0_FLAG; // Clear interrupt flag by writing 1 to Bit 0
_VICVectAddr=0;
}
#endif
int main()
{
lcd_init();
lcd_display(LCD_DISPLAY_DISPLAY_ON);
//==============================================================
// config Timer0
//==============================================================
_T0CTCR = TxCTCR_CNT_RISEDGE_PCLK; // count on rising edge of pclk
_T0TCR = TxTCR_COUNTER_RESET; // timer stop and reset
_T0MR0 = 99; // Compare-hit at mSec
_T0MCR = TxMCR_INT_ON_MR0 | TxMCR_RESET_ON_MR0; // Interrupt and Reset on MR0
_T0PR = Fpclk/1000/100-1;
_T0IR = 0xFF; // Reset IRQ flags
_VICVectAddr=0;
// interrupt config
_VICVectCntl2 = 0x24;
_VICVectAddr2 = (uint32_t)timer0_isr;
_VICIntSelect &= 0xFFFFFFEF;
_VICIntEnable |= 0x00000010;
//==============================================================
irq_enable();
_T0TCR = TxTCR_COUNTER_START;
while (1) {
if ((time_ms%10)==0) {
lcd_goto_xy(1,1);
lcd_printf("%8d",time_ms);
}
}
return 0;
}
#endif
//****************************************************************************
// Chronometer
//****************************************************************************
#ifdef MAIN3
volatile unsigned int time_ms=0;
unsigned int time_inter=0;
unsigned int state=0;
// TxCTCR (Timer Counter Control Register)
#define TxCTCR_CNT_RISEDGE_PCLK (0<<0)
#define TxCTCR_CNT_RISEDGE_CAPX (1<<0)
#define TxCTCR_CNT_FALEDGE_PCLK (2<<0)
#define TxCTCR_CNT_FALEDGE_CAPX (3<<0)
#define TxCTCR_CNT_INPUT_CAPX_0 (0<<2)
#define TxCTCR_CNT_INPUT_CAPX_1 (1<<2)
#define TxCTCR_CNT_INPUT_CAPX_2 (2<<2)
#define TxCTCR_CNT_INPUT_CAPX_3 (3<<2)
// TxTCR (Timer Control Register)
#define TxTCR_COUNTER_START (1<<0)
#define TxTCR_COUNTER_STOP (0)
#define TxTCR_COUNTER_RESET (1<<1)
// TxMCR (Match Control Register)
#define TxMCR_INT_ON_MR0 (1<<0) // MR0
#define TxMCR_RESET_ON_MR0 (1<<1)
#define TxMCR_STOP_ON_MR0 (1<<2)
#define TxMCR_INT_ON_MR1 (1<<3) // MR1
#define TxMCR_RESET_ON_MR1 (1<<4)
#define TxMCR_STOP_ON_MR1 (1<<5)
#define TxMCR_INT_ON_MR2 (1<<6) // MR2
#define TxMCR_RESET_ON_MR2 (1<<7)
#define TxMCR_STOP_ON_MR2 (1<<8)
#define TxMCR_INT_ON_MR3 (1<<9) // MR3
#define TxMCR_RESET_ON_MR3 (1<<10)
#define TxMCR_STOP_ON_MR3 (1<<11)
// TxIR (Interrupt Register)
#define TxIR_MR0_FLAG (1<<0)
#define TxIR_MR1_FLAG (1<<1)
#define TxIR_MR2_FLAG (1<<2)
#define TxIR_MR3_FLAG (1<<3)
#define TxIR_CR0_FLAG (1<<4)
#define TxIR_CR1_FLAG (1<<5)
#define TxIR_CR2_FLAG (1<<6)
#define TxIR_CR3_FLAG (1<<7)
#ifdef __IRQ_HANDLER__
static void timer0_isr()
{
time_ms++;
_T0IR = TxIR_MR0_FLAG; // Clear interrupt flag by writing 1 to Bit 0
}
#else
static __attribute__((interrupt("IRQ"))) void timer0_isr()
{
time_ms++;
_T0IR = TxIR_MR0_FLAG; // Clear interrupt flag by writing 1 to Bit 0
_VICVectAddr=0;
}
#endif
#define EXT_EINT0_BIT 0
#define EXT_EINT1_BIT 1
#define EXT_EINT2_BIT 2
#define EXT_EINT3_BIT 3
#define EXT_LEVEL_SENSITIVE 0
#define EXT_EDGE_SENSITIVE 1
#define EXT_LOW 0
#define EXT_HIGH 1
#define EXT_FALLING 0
#define EXT_RISING 1
// eint1_isr
// eint1 ISR (Interrupt Service Routine)
#ifdef __IRQ_HANDLER__
static void eint1_isr()
{
pushed = 1;
_EXTINT = 1<<EXT_EINT1_BIT;
}
#else
static __attribute__((interrupt("IRQ"))) void eint1_isr()
{
pushed = 1;
_EXTINT = 1<<EXT_EINT1_BIT;
_VICVectAddr=0;
}
#endif
int main()
{
lcd_init();
lcd_display(LCD_DISPLAY_DISPLAY_ON);
//==============================================================
// config external irq on P0.14
//==============================================================
io_configure(_IO0, IO_PIN_14, IO_PIN_FUNC2);
//_PINSEL0 = (_PINSEL0 & 0xCFFFFFFF) | 0x20000000; // EINT1 -> P0.14
// edge sensitive
_EXTMODE = (_EXTMODE & (~(1<<EXT_EINT1_BIT))) | (EXT_EDGE_SENSITIVE<<EXT_EINT1_BIT);
// rising edge
_EXTPOLAR = (_EXTMODE & (~(1<<EXT_EINT1_BIT))) | (EXT_RISING<<EXT_EINT1_BIT);
// acknoledge pending irq
_EXTINT = 1<<EXT_EINT1_BIT;
_VICVectAddr=0;
// interrupt config
_VICVectCntl4 = 0x2F;
_VICVectAddr4 = (uint32_t)eint1_isr;
_VICIntSelect &= 0xFFFF7FFF;
_VICIntEnable |= 0x8000;
//==============================================================
// config Timer0
//==============================================================
_T0CTCR = TxCTCR_CNT_RISEDGE_PCLK; // count on rising edgle of pclk
_T0TCR = TxTCR_COUNTER_RESET; // timer stop and reset
_T0MR0 = 99; // Compare-hit at mSec
_T0MCR = TxMCR_INT_ON_MR0 | TxMCR_RESET_ON_MR0; // Interrupt and Reset on MR0
_T0PR = Fpclk/1000/100-1;
_T0IR = 0xFF; // Reset IRQ flags
_VICVectAddr=0;
// interrupt config
_VICVectCntl2 = 0x24;
_VICVectAddr2 = (uint32_t)timer0_isr;
_VICIntSelect &= 0xFFFFFFEF;
_VICIntEnable |= 0x00000010;
//==============================================================
irq_enable();
lcd_printf("%8d ms",time_ms);
while (1) {
switch (state) {
case 0: // initial state
if (pushed) {
_T0TCR = TxTCR_COUNTER_START;
pushed=0;
state=1;
}
break;
case 1: // count
lcd_goto_xy(1,1);
lcd_printf("%8d ms",time_ms);
if (pushed) {
time_inter=time_ms;
lcd_goto_xy(1,2);
lcd_printf("%8d ms",time_inter);
pushed=0;
state=2;
}
break;
case 2: // count, show intermediate time
lcd_goto_xy(1,1);
lcd_printf("%8d ms",time_ms);
if (pushed) {
_T0TCR = TxTCR_COUNTER_STOP;
lcd_goto_xy(1,2);
lcd_printf("%8d ms",time_ms-time_inter);
pushed=0;
state=3;
}
break;
case 3:
if (pushed) {
time_ms=0;
lcd_clear();
lcd_home();
lcd_printf("%8d ms",time_ms);
pushed=0;
state=0;
}
break;
}
}
return 0;
}
#endif | C | CL | a0f78bc0354d5ab5a86e22e144d4b1604fb2d9cac2219aded488c8f56e191a33 |
/*
* File: RF_uart.h
* Author: Tankin
*
* Created on 2 juillet 2018, 15:05
*/
/******************************************************************************/
/************ Declaration de la trame RF ***************************/
/******************************************************************************/
/******************************************************************************/
/*** La trame RF se décompose en 8 paties dans l'ordre suivant : ***/
/*** ***/
/*** 1) Trame de début 2 octet ***/
/*** 2) ID Source 1 octet ***/
/*** 3) ID Destinataire 1 octet ***/
/*** 4) Objet 1 octet ***/
/*** 5) Taille 1 octet ***/
/*** 6) Données 1 à 8 octet(s) ***/
/*** 7) Checksum 1 octet ***/
/*** 8) Trame de fin 1 octet ***/
/******************************************************************************/
/******************************************************************************/
#ifndef RF_UART_H
#define RF_UART_H
#ifdef MODULE_RF
/** D E F I N E S ****************************************/
//type de communication RF
#define AvecACK
#define AvecWatchdog
#define RF_AVEC_INTERRUPTION
//Mode de test avec clignotement de LED
//#define MODE_TEST_RF //ne fonctionne pas sans ?
//#define MODE_TEST_RF_ENVOI
//#define MODE_TEST_RF2
//#define MODE_TEST_RF_ACK
//adresse des machine sur le réseau RF
#define ID_GROS_ROBOT 1
#define ID_PETIT_ROBOT 2
#define ID_BALISE 3
#define ID_PC 4
#define ID_MIN ID_GROS_ROBOT
#define ID_MAX ID_PC
//adresse du porteur du code
#ifdef PETIT_ROBOT
#define MON_ID ID_PETIT_ROBOT //ATTENTION ERR BATEAU
#endif
#ifdef GROS_ROBOT
#define MON_ID ID_GROS_ROBOT
#endif
//octet envoyé à chaque débbut ou fin de message envoyé pour faciliter le décodage
#define DEBUT_TRAME 0b00100100 //$
#define FIN_TRAME 0b00100011 //#
#define OBJET_MIN ERR
#define OBJET_MAX CHAINE_PERSONNEL
/** S T R U C T U R E S ****************************************/
//Structure qui rassemble les informations à transmettre par RF
typedef struct
{
uint8_t IDDestinataire; //adresse de la machine destinataire
uint8_t objet; //nom de l'élément à envoyer (cf enum _Objet)
uint8_t taille; //nombre d'octet de la variable à envoyer
uint8_t data[8]; //décomposition en octets de la variable à envoyer
}_emissionRF;
//Structure qui rassemble les informations brutes d'une communication RF brute reçues
typedef struct
{
volatile _Bool libre : 1; //La structure est en cours de modification
uint8_t indice; //pointe vers l'étape actuel de la trame, à quoi correspond l'octet reçu
uint8_t IDSource; //adresse de la machine qui viens d'envoyer le message
uint8_t objet; //nom de l'élément reçu (cf enum _Objet)
uint8_t taille; //nombre d'octet de la variable reçu
uint8_t data[8]; //suite d'octet(s) reçu correspondant à une valeur de variable
uint8_t checksum; //checksum du message reçu (cf fonction checksumEmi() et checksumRec())
}_receptionRF;
//Structure qui stocke les variables reçues avec un flag 'la variable est reçu' pour chaque var
typedef struct
{
volatile _Bool ACK :1; //message de bien recu (ACKnoledge)
_Bool flag_X_PETIT_ROBOT :1; //=1 quand la coordonné X du petit robot peut etre lue
double X_PETIT_ROBOT; //coordonné X du petit robot
_Bool flag_Y_PETIT_ROBOT :1; //=1 quand la coordonné Y du petit robot peut etre lue
double Y_PETIT_ROBOT; //coordonné Y du petit robot
_Bool flag_X_GROS_ROBOT :1; //=1 quand la coordonné X du gros robot peut etre lue
double X_GROS_ROBOT; //coordonné X du gros robot
_Bool flag_Y_GROS_ROBOT :1; //=1 quand la coordonné Y du gros robot peut etre lue
double Y_GROS_ROBOT; //coordonné Y du gros robot
_Bool TOP_DEPART :1; //Signal pour confirmer les JACKs
_Bool flag_MESSAGE_PERSONNEL :1; //=1 quand le message personnel peut être lue
uint64_t MESSAGE_PERSONNEL; //Message personnalisé par le 3e argument de la fonction envoie()
_Bool flag_CHAINE_PERSONNEL :1; //=1 quand la chine personnel peut être lue
char CHAINE_PERSONNEL[8]; //Chaine de caractère qui s'envoi avec la fonction envoieChainePerso
}_infoRF;
//Structure qui rassemble les octets à transmettre par RF par la fonction envoiSurInterruption()
typedef struct
{
uint8_t trame[16]; //trame d'octets à envoyer
uint8_t taille; //taille de la trame d'octets (nombre d'octet utile dans trame[16])
volatile _Bool trameAEnvoyer : 1; //=1 quand une trame doit être envoyé
uint8_t watchdog; //compteur d'envoi, au dela de 100 envoi, on s'arret d'envoyé
}_trameRF;
/**E N U M S **********************************/
//Objet déterminant ce qui est envoyé/reçu par RF (cf fonction envoie(...))
typedef enum
{
ERR=0, //Le message précedent est éroné (non implémenté)
ACK, //Bien reçu le message précedent
PING_RF, //Demande d'ACK
DEMANDE, //Demande d'une variable (est utilisé automatiquement lors de l'appel de la fonction demande)
TOP_DEPART, //Baisse le flag TOP_DEPART du destinataire
X_PETIT_ROBOT, //Envoie la coordoné X du petit robot
Y_PETIT_ROBOT, //Envoie la coordoné Y du petit robot
X_GROS_ROBOT, //Envoie la coordoné X du gros robot
Y_GROS_ROBOT, //Envoie la coordoné Y du gros robot
PERSONNEL, //objet pour envoyer un message personalisé avec le 3e argument de la fonction envoie()
CHAINE_PERSONNEL,
SERIALUS
}_Objet;
//déjà défini plus haut
//#define OBJET_MIN ERR
//#define OBJET_MAX CHAINE_PERSO
/** P R O T O T Y P E S **********************************/
/**
* @brief : Fonction permettant d'envoyer le caractere A sur la liaison serie
*/
//void envoieASCII();
/**
* @brief : Fonction permettant de recevoir le caractere A sur la liaison serie
* @param : octet : octet recu par l'interruption UART1
*/
void receptionASCII(uint8_t buf);
/** Fonction initialisation **********************************/
/**
* @brief : initialise les flags de réception (infoRF, receptionRF et trameRF)
*/
void initRF();
/** Fonction checksum**********************************/
/**
* @brief : Fonction qui calcul un checksum par adition de objet et data[] de
* la structure _emissionRF
* @return : renvoie la somme
*/
uint8_t checksumEmi();
/**
* @brief : Fonction qui calcul un checksum par adition de objet et data[] de
* la structure _receptionRF
* @return : renvoie la somme
*/
uint8_t checksumRec();
/** fonction d'emission **********************************/
/**
* @brief : Fonction qui envoie une variable qui sera stocker dans la structure infoRF
* @param : objet : nom de l'élement à envoyer (liste d'objet : enum _Objet)
* @param : IDDestinataire : nom du destinataire (liste de destinataire : #define dans ce fichier)
* @param : messagePerso : Valeur à transmettre avec l'objet PERSONNEL, avec les autres objet la valeur n'est pas prise en compte
*/
void envoie(uint8_t objet,uint8_t IDDestinataire,uint64_t messagePerso);
/**
* @brief : Fonction qui replie le champ data de la struture emissionRF
* Décompose les variables de plus de 1 octet en plusieurs octet
* @param : info : variable à convertir et stocker
*/
void completeDataEmi(unsigned long long info);
/**
* @brief : Fonction qui crée la trame d'octets à transmettre à partir de la structure emissionRF
*/
void ConstruitTrame();
/** fonction de réception **********************************/
/**
* @brief : Fonction appelé lors de l'interruption de réception UART1 (réception d'un octet).
* Stocke les données recues dans la structure receptioinRF
* @param : octet : 8 bits recus sur la liaison UART1
*/
void recoitOctet(uint8_t octet);
/**
* @brief : Fonction qui vérifie le checksum
* envoie un ACK (acknoledge=bien recu) si le checksum est bon et que le message recu n'est pas un checksum
* met le flag libre (prêt à recevoir) à 1 sinon
*/
void verifTame();
/**
* @brief : Fonction qui stocke dans la structure infoRF la variable recu selon l'objet puis met le flag libre à 1
*/
void traitementTrame();
/**
* @brief : assemble les octets recus dans la structure receptionRF.data pour reformer la valeur
* @return : renvoie la valeur des octets recomposés
*/
unsigned long long convertitVarDouble();
/**
* @brief : demande au destinataire d'utiliser la fonction envoie() avec l'objet passé en premier argument et le demandeur comme destinataire
* @param : objet : élément demandé parmis l'énumération _Objet
* @param : IDDestinataire : nom du destinataire (liste de destinataire : #define dans ce fichier)
*/
void demande(uint8_t objet, uint8_t IDDestinataire);
/**
* @brief : Fonction qui envoie une chaine de 8 caractère qui sera stocker dans la structure infoRF.CHAINE_PERSONNEL
* @param : IDDestinataire : nom du destinataire (liste de destinataire : #define dans ce fichier)
* @param : chainePerso : chaine de char à transmettre
*/
void envoieChainePerso(uint8_t IDDestinataire,char* chainePerso);
/**
* @brief : envoi la trame stocker dans la structure trameRF
* l'envoi se fait tout les 100 ms avec le timer _T4Interrupt
* la fonction est appelé par le timer et si trameRF.trameAEnvoyer==1 alors la trame est envoyée
*/
void envoieRFSurInterruption();
/** Fonction de test**********************************/
void testRFEnvoyeur();
void testRFReceveur();
void debugEnvoyeur();
void debugReceveur();
void testRapiditeEnvoyeur();
void testRapiditeReceveur();
#endif /* MODULE_RF */
#endif /* RF_UART_H */
| C | CL | 4866cd0437f739f6a99452e5318f7b34db422203cf8a099d90d1da0032c4aedb |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct archive_entry {int dummy; } ;
struct archive {int dummy; } ;
/* Variables and functions */
int /*<<< orphan*/ archive_entry_clear (struct archive_entry*) ;
int /*<<< orphan*/ archive_entry_copy_pathname (struct archive_entry*,char*) ;
int /*<<< orphan*/ archive_entry_copy_pathname_w (struct archive_entry*,char*) ;
int /*<<< orphan*/ archive_entry_free (struct archive_entry*) ;
struct archive_entry* archive_entry_new () ;
int /*<<< orphan*/ archive_match_excluded (struct archive*,struct archive_entry*) ;
int /*<<< orphan*/ archive_match_free (struct archive*) ;
int /*<<< orphan*/ archive_match_path_excluded (struct archive*,struct archive_entry*) ;
int /*<<< orphan*/ assert (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ assertEqualInt (int,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ failure (char*) ;
__attribute__((used)) static void
exclusion_from_file(struct archive *m)
{
struct archive_entry *ae;
if (!assert((ae = archive_entry_new()) != NULL)) {
archive_match_free(m);
return;
}
/* Test with 'first', which should not be excluded. */
archive_entry_copy_pathname(ae, "first");
failure("'first' should not be excluded");
assertEqualInt(0, archive_match_path_excluded(m, ae));
assertEqualInt(0, archive_match_excluded(m, ae));
archive_entry_clear(ae);
archive_entry_copy_pathname_w(ae, L"first");
failure("'first' should not be excluded");
assertEqualInt(0, archive_match_path_excluded(m, ae));
assertEqualInt(0, archive_match_excluded(m, ae));
/* Test with 'second', which should be excluded. */
archive_entry_copy_pathname(ae, "second");
failure("'second' should be excluded");
assertEqualInt(1, archive_match_path_excluded(m, ae));
assertEqualInt(1, archive_match_excluded(m, ae));
archive_entry_clear(ae);
archive_entry_copy_pathname_w(ae, L"second");
failure("'second' should be excluded");
assertEqualInt(1, archive_match_path_excluded(m, ae));
assertEqualInt(1, archive_match_excluded(m, ae));
/* Test with 'third', which should not be excluded. */
archive_entry_copy_pathname(ae, "third");
failure("'third' should not be excluded");
assertEqualInt(0, archive_match_path_excluded(m, ae));
assertEqualInt(0, archive_match_excluded(m, ae));
archive_entry_clear(ae);
archive_entry_copy_pathname_w(ae, L"third");
failure("'third' should not be excluded");
assertEqualInt(0, archive_match_path_excluded(m, ae));
assertEqualInt(0, archive_match_excluded(m, ae));
/* Test with 'four', which should be excluded. */
archive_entry_copy_pathname(ae, "four");
failure("'four' should be excluded");
assertEqualInt(1, archive_match_path_excluded(m, ae));
assertEqualInt(1, archive_match_excluded(m, ae));
archive_entry_clear(ae);
archive_entry_copy_pathname_w(ae, L"four");
failure("'four' should be excluded");
assertEqualInt(1, archive_match_path_excluded(m, ae));
assertEqualInt(1, archive_match_excluded(m, ae));
/* Clean up. */
archive_entry_free(ae);
} | C | CL | 7d1b0c4b9d95acc5f0c2170d4f98b531e3e8794cd8348d9879f9bb08c0f0e793 |
/* -----------------------------------------------------------------------
* examine.c nfsc SAS
*
* $Locker: $
*
* $Id: examine.c,v 1.5 92/10/07 15:14:12 bj Exp $
*
* $Revision: 1.5 $
*
* $Header: Hog:Other/inet/src/c/nfsc/RCS/examine.c,v 1.5 92/10/07 15:14:12 bj Exp $
*
*------------------------------------------------------------------------
*/
/*
* nfs_examine()
* nfs_examinenext()
*/
#include "fs.h"
#include <string.h>
#define ZEROCOOKIE(c) bzero(&(c), NFS_COOKIESIZE);
/* local functions */
static entry *get_entry_list(struct mount_pt *mt, register struct DosPacket *dp,
nfs_fh *dirp, nfscookie pos, bool_t *eofp);
static void makefib(struct mount_pt *mt,struct DosPacket *dp,
register struct FileInfoBlock *fib, struct entry *rl,
register nfs_fh *fh);
static void makerootfib(
struct mount_pt *mt,
struct DosPacket *dp,
register struct FileInfoBlock *fib,
fattr *attr);
/*
* Return list of directory entries for given directory.
*/
static entry *
get_entry_list(mt, dp, dirp, pos, eofp)
struct mount_pt *mt;
register struct DosPacket *dp;
nfs_fh *dirp;
nfscookie pos;
bool_t *eofp;
{
struct readdirargs ra;
struct readdirres rr;
enum clnt_stat err;
*eofp = TRUE;
ra.count = mt->mt_rdsize;
ra.dir = *dirp;
ra.cookie = pos;
bzero(&rr, sizeof(rr));
err = nfs_call(mt, NFSPROC_READDIR, xdr_readdirargs, &ra,
xdr_my_readdirres, &rr);
if(err != RPC_SUCCESS || rr.status != NFS_OK){
dp->dp_Res2 = fh_status(err, rr.status);
return (struct entry *)NULL;
}
*eofp = rr.readdirres_u.reply.eof;
return rr.readdirres_u.reply.entries;
}
/*
** nfs_examine(mount_pt *mt, struct DosPacket *dp, int type)
**
** ACTION_EXAMINE_OBJECT
**
** dp->dp_Arg1 LOCK Lock of object to examine
** dp->dp_Arg2 BPTR FileInfoBlock to fill in
**
** dp->dp_Res1 BOOL Success/Failure (DOSTRUE/DOSFALSE)
** dp->dp_Res2 CODE Failure code if Res1 is DOSFALSE
**
** ACTION_EXAMINE_FH
**
** dp->dp_Arg1 BPTR FileHandle on open file
**
** Examine searchs the parent directory of the object described by the given
** lock. For files, the parent directory is kept in the lock. When we
** examine a directory we always lookup ".." as the search dir - this method
** is more robust in the event the directory tree has been mv'ed. An
** Examine() on a file can fail if the file was moved after it was created
** and nfs.handlers idea of the parent directory is no longer correct. In
** such a situation NFSERR_STALE is returned.
*/
void
nfs_examine(mt, dp)
struct mount_pt *mt;
struct DosPacket *dp;
{
register struct entry *rl;
register struct fdata *fd;
struct FileInfoBlock *fib;
char name[NFS_MAXNAMLEN];
struct entry *head, trl;
struct diropres dor;
register long fid;
bool_t found = FALSE;
bool_t eof;
nfscookie pos;
nfs_fh dir;
if( dp->dp_Type == ACTION_EXAMINE_FH ) { /* FileHandle */
fd = (struct fdata *)dp->dp_Arg1;
if(fd==0 || (((u_long)fd)&1) || fd->fd_magic != FD_MAGIC){
dp->dp_Res2 = ERROR_INVALID_LOCK;
return;
}
} else /* Lock */
CHECKLOCK(fd, dp);
if (fd->fd_type == FD_LINK) {
dp->dp_Res2 = ERROR_IS_SOFT_LINK;
return;
}
fib = btod(dp->dp_Arg2, struct FileInfoBlock *);
/*
* Examine resets any directory scans in process
*/
ZEROCOOKIE(fd->fd_dirpos);
if(fd->fd_head){
xdr_free(xdr_my_entry_list, &fd->fd_head);
fd->fd_head = fd->fd_next = (struct entry *)NULL;
}
if(fd->fd_type == FD_DIR){
if(fd->fd_dir_fid == mt->mt_lock.fd_dir_fid){ /* root */
struct attrstat fa;
enum clnt_stat err;
err = nfs_call(mt, NFSPROC_GETATTR,
xdr_nfs_fh, &mt->mt_lock.fd_dir,
xdr_attrstat, &fa);
if(err != RPC_SUCCESS || fa.status != NFS_OK){
dp->dp_Res2 = fh_status(err, fa.status);
return ;
}
makerootfib(mt, dp, fib, &fa.attrstat_u.attributes);
return;
} if(!get_parent(mt, dp, &fd->fd_dir, &dor)){
return;
}
fid = fd->fd_dir_fid;
dir = dor.diropres_u.diropres.file;
} else {
fid = fd->fd_file_fid;
dir = fd->fd_dir;
}
/*
* Search owning directory for object with fileid that matches
* the one we're looking for. This can fail under certain
* conditions, eg file movement after creation, not having
* read permission on the searched directory, etc.
*/
pos = fd->fd_dirpos;
do {
head = get_entry_list(mt, dp, &dir, pos, &eof);
for(rl = head; rl != (struct entry *)NULL; rl = rl->nextentry){
if(fid == rl->fileid){
strcpy(name, rl->name);
trl = *rl; trl.name = name;
found = TRUE;
break;
}
pos = rl->cookie;
}
if(head){
xdr_free(xdr_my_entry_list, &head);
}
} while (!found && !eof);
if(found){
makefib(mt, dp, fib, &trl, &dir);
} else {
dp->dp_Res2 = (fd->fd_type == FD_FILE) ? NFSERR_STALE:ERROR_OBJECT_NOT_FOUND;
}
}
void
nfs_examine_next(mt, dp)
struct mount_pt *mt;
register struct DosPacket *dp;
{
struct FileInfoBlock *fib;
register struct entry *rl;
register struct fdata *fd;
nfscookie pos;
bool_t eof;
int got_one;
CHECKDIR(fd, dp);
got_one = 0;
pos = fd->fd_dirpos;
do {
if(rl = fd->fd_next){
fd->fd_next = rl->nextentry;
} else {
if(fd->fd_head){
xdr_free(xdr_my_entry_list, &fd->fd_head);
fd->fd_head = fd->fd_next = (struct entry *)NULL;
}
rl = get_entry_list(mt, dp, &fd->fd_dir, pos, &eof);
if(rl == NULL && eof){ /* test for end of directory */
break;
}
fd->fd_head = rl;
fd->fd_next = rl ? rl->nextentry : (struct entry *)NULL;
}
if(rl == (struct entry *)NULL){
break;
}
if(rl->name[0] == '.'){
if(rl->name[1] == 0){
pos = rl->cookie;
continue;
}
if(rl->name[1] == '.' && rl->name[2] == 0){
pos = rl->cookie;
continue;
}
}
got_one++;
} while(!got_one);
fib = btod(dp->dp_Arg2, struct FileInfoBlock *);
if(got_one){
makefib(mt, dp, fib, rl, &fd->fd_dir);
fd->fd_dirpos = rl->cookie;
} else {
fib->fib_FileName[0] = fib->fib_Comment[0] = 0;
dp->dp_Res2 = ERROR_NO_MORE_ENTRIES;
}
}
/*
* Fill in FileInfoBlock to reflect the volume name. This is used
* when an application does an Examine() operation on the volume node.
*/
static void makerootfib(mt, dp, fib, attr)
struct mount_pt *mt;
struct DosPacket *dp;
register struct FileInfoBlock *fib;
fattr *attr;
{
unsigned char *cp;
cp = btod(mt->mt_vol->dol_Name, unsigned char *);
bcopy(cp, fib->fib_FileName, cp[0]+1);
fib->fib_FileName[cp[0]+1] = 0;
fib->fib_Comment[0] = 0;
fib->fib_DirEntryType = fib->fib_EntryType = 2;
fib->fib_DiskKey = attr->fileid;
fib->fib_Size = fib->fib_NumBlocks = 0;
if(dp->dp_Type == ACTION_EX_OBJECT){
*((struct fattr *)dp->dp_Arg3) = *attr;
}
dp->dp_Res1 = DOS_TRUE;
}
/*
* Fill in <fib> using information in <rl>. Must do lookup in <fh> to find
* file size and date information. Unix dates are relative to Jan 1st, 1970,
* while AmigaDOS dates are relative to Jan 1st, 1978; must translate by
* difference in seconds. Date returned for file is modification time.
*/
#define MIN_PER_DAY (24*60)
#define SEC_PER_DAY (MIN_PER_DAY*60)
#define UNIX_DELTAT (((1978-1970)*365 + 2 /* 2 leap years */)*SEC_PER_DAY)
static void makefib(mt, dp, fib, rl, fh)
struct mount_pt *mt;
struct DosPacket *dp;
register struct FileInfoBlock *fib;
struct entry *rl;
register nfs_fh *fh;
{
register u_long amiga_secs, prot;
int len, tz_min_off;
struct diropargs di;
struct diropres dor;
enum clnt_stat err;
long mode;
len = min(strlen(rl->name),106);
strncpy(&fib->fib_FileName[1], rl->name,len);
fib->fib_FileName[len+1] = 0;
fib->fib_FileName[0] = len;
fib->fib_Comment[0] = 0;
fib->fib_DiskKey = rl->fileid;
di.name = rl->name; di.dir = *fh;
//KPrintF("makefib: lookup %s\n",di.name);
err = nfs_call(mt, NFSPROC_LOOKUP, xdr_diropargs, &di,
xdr_diropres, &dor);
if(err != RPC_SUCCESS || dor.status != NFS_OK){
//KPrintF("err=%ld status=%ld\n",err,dor.status);
dp->dp_Res2 = fh_status(err, dor.status);
return;
}
if(dp->dp_Type==ACTION_EX_OBJECT || dp->dp_Type==ACTION_EX_NEXT){
*((struct fattr *)dp->dp_Arg3) = dor.diropres_u.diropres.attributes;
}
mode = dor.diropres_u.diropres.attributes.mode;
//KPrintF("mode = x%lx\n",mode);
if ((mode & NFSMODE_LNK) == NFSMODE_LNK ) fib->fib_DirEntryType = ST_SOFTLINK;
else if ((mode & NFSMODE_REG) == NFSMODE_REG ) fib->fib_DirEntryType = ST_FILE;
else if ((mode & NFSMODE_DIR) == NFSMODE_DIR ) fib->fib_DirEntryType = ST_USERDIR;
//KPrintF("fib_DirEntryType=%ld\n",fib->fib_DirEntryType);
fib->fib_EntryType = fib->fib_DirEntryType;
if (fib->fib_DirEntryType < 0){
fib->fib_Size = dor.diropres_u.diropres.attributes.size;
fib->fib_NumBlocks = dor.diropres_u.diropres.attributes.blocks;
} else {
fib->fib_Size = fib->fib_NumBlocks = 0;
}
tz_min_off = get_tz();
amiga_secs = (dor.diropres_u.diropres.attributes.mtime.seconds -
tz_min_off * 60) - UNIX_DELTAT;
fib->fib_Date.ds_Days = amiga_secs / SEC_PER_DAY;
fib->fib_Date.ds_Minute = (amiga_secs % SEC_PER_DAY)/60;
fib->fib_Date.ds_Tick = (amiga_secs % 60)*TICKS_PER_SECOND;
#define UID dor.diropres_u.diropres.attributes.uid
#define GID dor.diropres_u.diropres.attributes.gid
#define MODE dor.diropres_u.diropres.attributes.mode
prot = perm_unix_to_amiga(UID, GID, MODE);
#undef UID
#undef GID
#undef MODE
fib->fib_Protection = prot;
dp->dp_Res1 = DOS_TRUE; dp->dp_Res2 = 0;
}
/*
* SetDate(Arg1:Unused, Arg2: Lock, Arg3: Name, Arg4 :(struct DateStamp *))
* Update last modified (mtime) on UNIX object
*/
void
nfs_setdate(mt,dp)
struct mount_pt *mt;
register struct DosPacket *dp;
{
char name[NFS_MAXNAMLEN];
int status, tz_min_off;
struct fdata *fd, tfd;
struct DateStamp *dst;
struct sattrargs saa;
struct attrstat fa;
enum clnt_stat err;
long amiga_secs;
fd = dp->dp_Arg2==0 ? &mt->mt_lock : btod(dp->dp_Arg2, struct fdata *);
if (fd->fd_magic != FD_MAGIC || fd->fd_type != FD_DIR) {
dp->dp_Res2 = ERROR_INVALID_LOCK;
return;
}
status = ptofh(mt, dp, fd, btod(dp->dp_Arg3, char *), &tfd, name);
if (status != ALLFOUND){
return;
}
if(tfd.fd_type == FD_FILE){
saa.file = tfd.fd_file;
} else {
saa.file = tfd.fd_dir;
}
saa.attributes.uid = -1;
saa.attributes.gid = -1;
saa.attributes.size = -1;
saa.attributes.atime.seconds = -1;
saa.attributes.atime.useconds = -1;
saa.attributes.mode = -1;
tz_min_off = get_tz();
dst = (struct DateStamp *) dp->dp_Arg4;
amiga_secs = dst->ds_Days * SEC_PER_DAY + dst->ds_Minute * 60
+ dst->ds_Tick / TICKS_PER_SECOND;
saa.attributes.mtime.seconds = amiga_secs + UNIX_DELTAT + tz_min_off*60;
saa.attributes.mtime.useconds = -1;
err = nfs_call(mt, NFSPROC_SETATTR, xdr_sattrargs, &saa,
xdr_attrstat, &fa);
if(err != RPC_SUCCESS || fa.status != NFS_OK){
dp->dp_Res2 = fh_status(err, fa.status);
} else {
dp->dp_Res1 = DOS_TRUE;
dp->dp_Res2 = 0;
}
}
| C | CL | e24f8c15bf7f38f3583bd91a7dbb05a9aadbbba18b249da644f1083517843cc4 |
/* d9lgic.f -- translated by f2c (version 20041007).
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
*/
/** This routine has been editted to be thread safe **/
#define V3P_NETLIB_SRC
#include "v3p_netlib.h"
/* Table of constant values */
static integer c__3 = 3;
static integer c__1 = 1;
static integer c__2 = 2;
/* DECK D9LGIC */
doublereal d9lgic_(doublereal *a, doublereal *x, doublereal *alx)
{
/* Initialized data */
/* static */ doublereal eps = 0.;
/* System generated locals */
doublereal ret_val;
/* Builtin functions */
double log(doublereal);
/* Local variables */
integer k;
doublereal p, r__, s, t, fk, xma, xpa;
extern doublereal d1mach_(integer *);
extern /* Subroutine */ int xermsg_(const char *, const char *, const char *, integer *,
integer *, ftnlen, ftnlen, ftnlen);
/* ***BEGIN PROLOGUE D9LGIC */
/* ***SUBSIDIARY */
/* ***PURPOSE Compute the log complementary incomplete Gamma function */
/* for large X and for A .LE. X. */
/* ***LIBRARY SLATEC (FNLIB) */
/* ***CATEGORY C7E */
/* ***TYPE DOUBLE PRECISION (R9LGIC-S, D9LGIC-D) */
/* ***KEYWORDS COMPLEMENTARY INCOMPLETE GAMMA FUNCTION, FNLIB, LARGE X, */
/* LOGARITHM, SPECIAL FUNCTIONS */
/* ***AUTHOR Fullerton, W., (LANL) */
/* ***DESCRIPTION */
/* Compute the log complementary incomplete gamma function for large X */
/* and for A .LE. X. */
/* ***REFERENCES (NONE) */
/* ***ROUTINES CALLED D1MACH, XERMSG */
/* ***REVISION HISTORY (YYMMDD) */
/* 770701 DATE WRITTEN */
/* 890531 Changed all specific intrinsics to generic. (WRB) */
/* 890531 REVISION DATE from Version 3.2 */
/* 891214 Prologue converted to Version 4.0 format. (BAB) */
/* 900315 CALLs to XERROR changed to CALLs to XERMSG. (THJ) */
/* 900720 Routine changed from user-callable to subsidiary. (WRB) */
/* ***END PROLOGUE D9LGIC */
/* ***FIRST EXECUTABLE STATEMENT D9LGIC */
// d1mach has been made thread safe, so there is no need for the
// statics in determining eps
// if (eps == 0.) {
// eps = .5 * d1mach_(&c__3);
// }
eps = .5 * d1mach_(&c__3);
xpa = *x + 1. - *a;
xma = *x - 1. - *a;
r__ = 0.;
p = 1.;
s = p;
for (k = 1; k <= 300; ++k) {
fk = (doublereal) k;
t = fk * (*a - fk) * (r__ + 1.);
r__ = -t / ((xma + fk * 2.) * (xpa + fk * 2.) + t);
p = r__ * p;
s += p;
if (abs(p) < eps * s) {
goto L20;
}
/* L10: */
}
xermsg_("SLATEC", "D9LGIC", "NO CONVERGENCE IN 300 TERMS OF CONTINUED FR"
"ACTION", &c__1, &c__2, (ftnlen)6, (ftnlen)6, (ftnlen)49);
L20:
ret_val = *a * *alx - *x + log(s / xpa);
return ret_val;
} /* d9lgic_ */
| C | CL | 1bf00f6d5ce61d7b7cdf359759533151c83c039ec9aec0b0c402bc817046cfc4 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_4__ TYPE_2__ ;
typedef struct TYPE_3__ TYPE_1__ ;
/* Type definitions */
struct TYPE_3__ {int /*<<< orphan*/ pixelformat; int /*<<< orphan*/ height; int /*<<< orphan*/ width; } ;
struct TYPE_4__ {TYPE_1__ pix; } ;
struct v4l2_format {scalar_t__ type; TYPE_2__ fmt; } ;
struct coda_ctx {int /*<<< orphan*/ vdoa; } ;
/* Variables and functions */
int EINVAL ;
scalar_t__ V4L2_BUF_TYPE_VIDEO_CAPTURE ;
int /*<<< orphan*/ round_up (int /*<<< orphan*/ ,int) ;
int vdoa_context_configure (int /*<<< orphan*/ *,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
__attribute__((used)) static int coda_try_fmt_vdoa(struct coda_ctx *ctx, struct v4l2_format *f,
bool *use_vdoa)
{
int err;
if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
if (!use_vdoa)
return -EINVAL;
if (!ctx->vdoa) {
*use_vdoa = false;
return 0;
}
err = vdoa_context_configure(NULL, round_up(f->fmt.pix.width, 16),
f->fmt.pix.height, f->fmt.pix.pixelformat);
if (err) {
*use_vdoa = false;
return 0;
}
*use_vdoa = true;
return 0;
} | C | CL | 73ca9b9344a33185f72d97871f26ea33e775abc0267234fa3954cc2154ce5954 |
/*
* CANopen Object Dictionary storage object (blank example).
*
* @file CO_storageBlank.c
* @author Janez Paternoster
* @copyright 2021 Janez Paternoster
*
* This file is part of CANopenNode, an opensource CANopen Stack.
* Project home page is <https://github.com/CANopenNode/CANopenNode>.
* For more information on CANopen see <http://www.can-cia.org/>.
*
* 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 "CO_storageBlank.h"
#if (CO_CONFIG_STORAGE) & CO_CONFIG_STORAGE_ENABLE
/*
* Function for writing data on "Store parameters" command - OD object 1010
*
* For more information see file CO_storage.h, CO_storage_entry_t.
*/
static ODR_t storeBlank(CO_storage_entry_t *entry, CO_CANmodule_t *CANmodule) {
/* Open a file and write data to it */
/* file = open(entry->pathToFileOrPointerToMemory); */
CO_LOCK_OD(CANmodule);
/* write(entry->addr, entry->len, file); */
CO_UNLOCK_OD(CANmodule);
return ODR_OK;
}
/*
* Function for restoring data on "Restore default parameters" command - OD 1011
*
* For more information see file CO_storage.h, CO_storage_entry_t.
*/
static ODR_t restoreBlank(CO_storage_entry_t *entry, CO_CANmodule_t *CANmodule){
/* disable (delete) the file, so default values will stay after startup */
return ODR_OK;
}
CO_ReturnError_t CO_storageBlank_init(CO_storage_t *storage,
CO_CANmodule_t *CANmodule,
OD_entry_t *OD_1010_StoreParameters,
OD_entry_t *OD_1011_RestoreDefaultParam,
CO_storage_entry_t *entries,
uint8_t entriesCount,
uint32_t *storageInitError)
{
CO_ReturnError_t ret;
/* verify arguments */
if (storage == NULL || entries == NULL || entriesCount == 0
|| storageInitError == NULL
) {
return CO_ERROR_ILLEGAL_ARGUMENT;
}
/* initialize storage and OD extensions */
ret = CO_storage_init(storage,
CANmodule,
OD_1010_StoreParameters,
OD_1011_RestoreDefaultParam,
storeBlank,
restoreBlank,
entries,
entriesCount);
if (ret != CO_ERROR_NO) {
return ret;
}
/* initialize entries */
*storageInitError = 0;
for (uint8_t i = 0; i < entriesCount; i++) {
CO_storage_entry_t *entry = &entries[i];
/* verify arguments */
if (entry->addr == NULL || entry->len == 0 || entry->subIndexOD < 2) {
*storageInitError = i;
return CO_ERROR_ILLEGAL_ARGUMENT;
}
/* Open a file and read data from file to entry->addr */
/* file = open(entry->pathToFileOrPointerToMemory); */
/* read(entry->addr, entry->len, file); */
}
return ret;
}
#endif /* (CO_CONFIG_STORAGE) & CO_CONFIG_STORAGE_ENABLE */
| C | CL | 6cce7b9cab170a9194e19c0d9bc2f9969a17423dd0a344f9cf640dc1757489a1 |
/* XACC.C - Routinen zur Behandlung des XACC-Protokolls
nach der Spezifikation vom 28. November 1992,
erweitert um Mag!X 2.0
(c) 1993 Harald Sommerfeldt @ KI im Maus-Netz
E-Mail: [email protected] */
/* Geschichte:
22.03.93: erste Version
03.08.93: luft auch unter Speicherschutz (MiNT)
05.09.93: berarbeitet und als seperater Quelltext XACC.C
06.09.93: fngt den fatalen Fehler von Watchdog 1.4 ab, welches im
Singletasking-Fall als Antwort von ACC_ID flschlicherweise
fleiig ACC_ACC's verschickt, die auch noch eine falsche ID (16)
enthalten, so da das AES sich die Kugel gibt, falls man versucht,
darauf zu antworten :-(((
*/
/* Hinweise:
- dieser Quelltext ist Freeware und darf daher 1. nur umsonst und 2. nur
komplett (XACC.C, XACC.H, XACCTEST.C, XACCTEST.PRJ, XACCTEST.PRG,
XACC2.TXT) weitergegeben werden!
- dieser Quelltext kann ohne Hinweis auf mein Copyright in eigene Programme
nach belieben eingebunden werden, die Entfernung meines Copyrightes in
diesem Quelltext ist jedoch nicht erlaubt!
- dieser Quelltext wurde mit Tabweite 3 entwickelt
*/
/* bekannte Bugs:
- diese Routinen laufen NICHT mit Mag!X 1.x, sondern erst ab Mag!X 2.00!
- die Variable 'xacc' wird zwar gesetzt, aber ansonsten ignoriert
*/
#define XACC_ACC
/* Dieses Routinen funktionieren auch, wenn das Programm als ACC luft.
Ist dies bei eigenen Programmen nicht der Fall, so knnen die dafr
zustndigen Routinen durch Lschung dieser Zeile ausmaskiert werden,
um redundanten Quellcode zu vermeiden. */
#define XACC_PRG
/* Dieses Routinen funktionieren auch, wenn das Programm als PRG luft. */
/* #define XACC_RECONLY */
/* Diese Routinen knnen nur per XACC empfangen, nicht selber senden.
Dies ist z.B. sinnvoll, wenn man als ACC das XACC nicht aktiv benutzt,
d.h. selbst keine Applikationen anmorsen will, man kann aber korrekt
durch XACC angesprochen werden.
Das XACC-Protokoll ist hierbei vollstndig implementiert!!! */
#if !defined( XACC_ACC ) && !defined( XACC_PRG )
#error Warum binden Sie diesen Quelltext berhaupt ein?
#endif
#if defined( XACC_SMALL ) && defined( XACC_PRG )
#error XACC_SMALL ist nur bei ACCs mglich
#endif
#include <aes.h>
#include <tos.h>
#include <string.h>
#include <stddef.h>
#include "xacc.h"
/* bentigte AES-Definitionen */
#ifdef __PUREC__
#define ap_version _GemParBlk.global[0] /* AES-Versionsnummer (z.B. 0x140 = 1.40) */
#define ap_count _GemParBlk.global[1] /* Anzahl der max. laufenden Applikationen */
#define ap_id _GemParBlk.global[2] /* eigene ID */
#endif
/* bentigte allgemeine Definitionen */
#define NIL -1
typedef enum { FALSE, TRUE } bool;
/* globale Variablen */
static bool xacc; /* XACC-Protokoll aktiviert */
static bool xacc_singletask; /* alte Spezifikation vom 12.3.89 verwenden? */
static char *xacc_name; /* Platz fr den eigenen XACC-Namen */
static unsigned xacc_groups; /* eigenes XACC-Group-Wort */
static int xacc_menuid; /* die ID des Meneintrages bzw. -1 */
#ifndef XACC_SMALL
struct xaccs xaccs[MAX_XACC]; /* Strukturen, um sich die XACC-Partner zu merken */
#endif
/* XACC-Protokoll initialisieren,
diese Routine MUSS beim Programmstart irgendwann nach appl_init() aufgerufen werden */
int xacc_init( int menu_id, const char *name, int sizeofname, unsigned groups )
{
int i;
xacc = TRUE;
/* den XACC-Namen in einem global zugnglichen
(Speicherschutz!) unterbringen */
if ( ap_version >= 0x0400 && xacc_cookie( 'MiNT', NULL ) )
xacc_name = Mxalloc( sizeofname, 0x0022 );
else
xacc_name = Malloc( sizeofname );
if ( xacc_name == NULL ) return xacc = FALSE;
memcpy( xacc_name, name, sizeofname );
/* die Men-ID und das Group-Wort merken */
xacc_menuid = menu_id;
xacc_groups = groups;
#ifndef XACC_SMALL
/* erstmal alle Eintrge lschen */
for ( i = 0; i < MAX_XACC; i++ ) xaccs[i].id = -1;
#endif
/* unter einem Multi-AES-TOS gilt die neue Spezifikation... */
if ( ap_count != 1 ) {
xacc_singletask = FALSE;
/* AES 4.0 (z.B. MTOS) oder MagX? */
if ( ap_version >= 0x400 || xacc_cookie( 'MagX', NULL ) ) {
int type, id;
char name[10];
/* ...wir senden also an alle Applikationen unseren Willkommensgru */
for ( i = appl_search( 0, name, &type, &id ); i; i = appl_search( 1, name, &type, &id ) ) {
if ( (type & 6) != 0 ) xacc_id( id, ACC_ID );
}
}
else xacc = FALSE; /* sorry, wird wohl nichts draus... */
}
/* ansonsten handelt es sich um ein altes, trostloses Singletasking-AES,
wo wir das angestaubte XACC-Protokoll vom 12.3.89 verwenden */
else xacc_singletask = TRUE;
return xacc;
}
/* XACC-Protokoll deinitialisieren,
diese Routine MUSS irgendwann beim Programmende vor appl_exit() aufgerufen werden */
#ifndef XACC_SMALL
void xacc_exit( void )
{
int i;
/* Im Multitasking-Fall ... */
if ( !xacc_singletask ) {
/* ... verabschieden wir und brav und hflich (mittels ACC_EXIT) */
for ( i = 0; i < MAX_XACC; i++ ) {
if ( xaccs[i].id >= 0 ) xacc_id( xaccs[i].id, ACC_EXIT );
}
}
if ( xacc_name != NULL ) Mfree( xacc_name );
}
#endif
/* die Nachricht in msgbuf verarbeiten, falls es sich um eine
Nachricht des Types AC_CLOSE, ACC_ID, ACC_ACC oder ACC_EXIT handelt;
es wird TRUE zurckgegeben, falls die Nachricht komplett verarbeitet wurde */
int xacc_message( const int *msgbuf )
{
int i;
#ifdef XACC_ACC
if ( msgbuf[0] == AC_CLOSE ) {
/* wenn wir dem Singletasking-Protokoll hrig sind,
ist dies der Moment, wo der Elefant das Wasser lt:
das XACC-Protokoll wird angekurbelt */
if ( xacc_singletask ) {
#ifndef XACC_SMALL
/* erstmal alle Eintrge lschen... */
for ( i = 0; i < MAX_XACC; i++ ) xaccs[i].id = -1;
#endif
/* ...dann die Lawine in Gang setzen: ACC_ID ans Haupt-
programm verschicken; die Bedingung ap_id != 0 sollte
hierbei eigentlich immer erfllt sein, aber man wei
ja nie, wer einem so alles eine AC_CLOSE-Nachricht
andrehen will (z.B. Schlemi!) */
if ( ap_id != 0 ) xacc_id( 0, ACC_ID );
}
return FALSE;
}
#endif
if ( msgbuf[0] == ACC_ID ) {
/* wenn wir dem Single-Tasking-Protokoll hrig sind,
ist dies der Moment, wo der Elefant das Wasser gelassen hat:
das XACC-Protokoll wurde angekurbelt */
if ( xacc_singletask ) {
#ifdef XACC_PRG
if ( ap_id == 0 ) { /* nur wenn wir ein PRG sind... */
int mymsgbuf[8];
/* ...verschicken wir fleiig Grukarten (ACC_ACC) */
mymsgbuf[0] = ACC_ACC;
mymsgbuf[1] = ap_id;
mymsgbuf[2] = 0;
mymsgbuf[3] = msgbuf[3];
mymsgbuf[4] = msgbuf[4];
mymsgbuf[5] = msgbuf[5];
mymsgbuf[6] = msgbuf[6];
mymsgbuf[7] = msgbuf[1];
for ( i = 0; i < MAX_XACC; i++ ) {
if ( xaccs[i].id >= 0 ) appl_write( xaccs[i].id, 16, mymsgbuf );
}
/* dem Auslser dieser Lawine einen Heiratsantrag schicken */
xacc_id( msgbuf[1], ACC_ID );
}
#else
;
#endif
}
/* im Falle des Multitasking-Protokolls tut sich hier nicht
ganz so viel: Wir erwiedern das Moin (ACC_ID) mit Moin-Moin (ACC_ACC) */
else xacc_id( msgbuf[1], ACC_ACC );
#ifndef XACC_SMALL
/* auf jeden Fall lassen wir ein ACC_ID nicht ungestraft
durchgehen, der Absender wird in der Fahndungsliste vermerkt! */
xacc_remid( msgbuf[1], msgbuf );
#endif
return TRUE;
}
else if ( msgbuf[0] == ACC_ACC ) {
/* ACC_ACC ist vergleichsweise harmlos: Im Singletasking-Fall
erhalten wir so als ACC von anderen ACCs Kenntnis (und
vermitteln diesen die Kenntnis ber uns), im Multitasking-Fall
ist dies einfach das Moin-Moin auf das Moin (ACC_ID)
ACHTUNG: Im ersten Fall steht die interessante Id bei
msgbuf[7], im zweiteren bei msgbuf[1]! */
if ( xacc_singletask ) {
#ifdef XACC_ACC
if ( ap_id != 0 ) { /* sollte eigentlich immer der Fall sein,
im Falle Watchdog 1.4 leider nicht :-((( */
xacc_id( msgbuf[7], ACC_ID );
#ifndef XACC_SMALL
xacc_remid( msgbuf[7], msgbuf );
#endif
}
#else
;
#endif
}
#ifndef XACC_SMALL
else xacc_remid( msgbuf[1], msgbuf );
#endif
return TRUE;
}
else if ( msgbuf[0] == ACC_EXIT ) {
/* Der Untergang der Titanic, hier allerdings nicht ohne
Vorankndigung: Die Id wird mangels grnen Punkt nicht
wiederverwertet, sondern wandert auf den Mll */
xacc_killid( msgbuf[1] ); /* wech mit den Altlasten */
return TRUE;
}
return FALSE;
}
/* ein Teil des Ganzen als XACC-Nachricht versenden
dest_id : die ap_id des glcklichen Empfngers
message : Nachrichtentyp (ACC_IMG oder ACC_META)
addr : Adresse des Speicherblockes
length : Lnge des Speicherblockes
last : Letzter Speicherblock? (FALSE/TRUE) */
int xacc_send( int dest_id, int message, void *addr, long length, int last )
{
int msgbuf[8];
msgbuf[0] = message;
msgbuf[1] = ap_id;
msgbuf[2] = 0;
msgbuf[3] = last;
*(const char **)(msgbuf+4) = addr;
*(long *)(msgbuf+6) = length;
return appl_write( dest_id, 16, msgbuf );
}
/* ACC_ACK als Antwort auf ACC_TEXT, ACC_KEY, ACC_META oder ACC_IMG versenden
dest_id : die ap_id des (un-)glcklichen Empfngers
ok : TRUE oder FALSE */
int xacc_ack( int dest_id, int ok )
{
int msgbuf[8];
msgbuf[0] = ACC_ACK;
msgbuf[1] = ap_id;
msgbuf[2] = 0;
msgbuf[3] = ok;
msgbuf[4] = msgbuf[5] = msgbuf[6] = msgbuf[7] = 0;
return appl_write( dest_id, 16, msgbuf );
}
/* die eigene XACC-ID versenden
dest_id : die ap_id des glcklichen Empfngers
message : ACC_ID oder ACC_ACC, je nach Lust & Laune */
int xacc_id( int dest_id, int message )
{
int msgbuf[8];
/* da in xacc_init() die eigene ap_id nicht herausgefiltert wird,
wird hier verhindert, da wir uns selber eine Nachricht schicken */
if ( dest_id != ap_id ) {
msgbuf[0] = message; /* Nachrichtentyp */
msgbuf[1] = ap_id; /* unsere ap_id */
msgbuf[2] = 0; /* Lnge der Nachricht - 16 */
msgbuf[3] = xacc_groups; /* die von uns untersttzten XACC-Gruppen */
*(const char **)(msgbuf+4) = xacc_name; /* unser XACC-Name */
msgbuf[6] = xacc_menuid; /* unsere Menkennung (falls ACC), sonst -1 */
msgbuf[7] = NIL; /* reserviert */
return appl_write( dest_id, 16, msgbuf );
}
return 0;
}
/* XACC-Eintrag vermerken (bei ACC_ID & ACC_ACC)
id : die ap_id des Absenders,
msgbuf : der empfangene Nachrichtenpuffer */
#ifndef XACC_SMALL
int xacc_remid( int id, const int *msgbuf )
{
int i;
/* eventuell alten Eintrag mit der gleichen Id vorher lschen.
es gibt verschiedene Flle, wo dies notwendig ist:
- ein Eintrag ist veraltet, da das Programm abgestrzt ist
und daher kein ACC_EXIT versandt hat
- beim Singletasking-Protokoll kann ein ACC mehrere ACC_ACC
vom gleichen ACC erhalten
- beim Multitasking-Protokolls erhlt ein ACC _IMMER_ von einem
anderen ACC beim Neustart des Rechners sowohl ein ACC_ID als
auch ein ACC_ACC
*/
xacc_killid( id );
/* nun gehts aber los! */
for ( i = 0; i < MAX_XACC; i++ ) { /* XACC-Liste abklappern */
if ( xaccs[i].id < 0 ) { /* freier Eintrag gefunden */
xaccs[i].id = id; /* Eintrag vermerken */
xaccs[i].groups = msgbuf[3];
xaccs[i].name = *(const char **)(msgbuf+4);
return TRUE;
}
}
return FALSE;
}
#endif
/* XACC-Eintrag lschen (z.B. bei ACC_EXIT)
id : die nicht mehr gltige ap_id */
#ifndef XACC_SMALL
int xacc_killid( int id )
{
int i;
for ( i = 0; i < MAX_XACC; i++ ) { /* XACC-Liste abklappern */
if ( xaccs[i].id == id ) { /* Id gefunden ! */
xaccs[i].id = NIL; /* Eintrag in der Liste freigeben */
return TRUE;
}
}
return FALSE;
}
#endif
/* Wert eines Cookies holen, zurckgegeben wird TRUE bei Erfolg */
typedef struct {
long cookie, value;
} cookiejar;
int xacc_cookie( long cookie, long *value )
{
cookiejar *_p_cookies;
void *sp;
sp = (void *)Super( NULL );
_p_cookies = *(void **)0x5A0; /* Zeiger auf Cookiejar holen */
Super( sp );
if ( _p_cookies != NULL ) { /* wenn Cookiejar installiert ... */
/* ... dann Cookies abklappern ... */
for (; _p_cookies->cookie != 0L; _p_cookies++ ) {
if ( _p_cookies->cookie == cookie ) {
/* ... bis der gewnschte Eintrag ist */
if ( value != NULL ) *value = _p_cookies->value;
return TRUE;
}
}
}
return FALSE;
}
| C | CL | b88b39edaa148348315096321a5d3b15ca33a59552d5a121079be518e1c63d3c |
#include <std.h>
inherit OBJECT;
void create(){
::create();
set_name("plate");
set_id(({"plate","dinner plate","magical plate","china plate","plate of cleanliness"}));
set_short("%^RESET%^%^MAGENTA%^China Plate of C%^CYAN%^l%^MAGENTA%^eanl%^BOLD%^i%^RESET%^%^MAGENTA%^ness%^RESET%^ +1");
set_obvious_short("%^RESET%^%^MAGENTA%^a spotlessly clean china plate%^RESET%^");
set_long("%^RESET%^%^MAGENTA%^This plate is made of %^WHITE%^fine bone "
"china%^MAGENTA%^. It has been painted with the image of %^RED%^colorful "
"flowers %^MAGENTA%^across its surface, and has been %^CYAN%^glazed %^MAGENTA%^"
"to preserve it from damage. The edges of the china bear small inward "
"%^ORANGE%^notches %^MAGENTA%^to add a crimped, decorative edge to the plate. "
"It is absolutely %^RESET%^spotless%^MAGENTA%^, as though it had never been "
"used.%^RESET%^");
set_lore("Plates such as this are highly prized by housekeepers everywhere. "
"Such an enchantment as lies upon this one, is usually reserved for only the "
"finest of plates and dinnerware. The magic serves both to protect the plate "
"from harm, as no damage will chip or crack it, and to keep it spotlessly clean "
"without need of washing. The perfect addition to any kitchen!");
set_property("lore difficulty",15);
set_value(0);
set_weight(0);
}
int isMagic(){ return 1; }
| C | CL | c75ab1e1e8df0ce81daf8f677aeaac7fc8bae9dd369cc031d9a029a71c97edfd |
#include "usart.h"
#include "config.h"
#include "stdio.h"
#include "struct_all.h"
#include "protocol.h"
#define BYTE0(dwTemp) (*(char *)(&dwTemp))
#define BYTE1(dwTemp) (*((char *)(&dwTemp) + 1))
#define BYTE2(dwTemp) (*((char *)(&dwTemp) + 2))
#define BYTE3(dwTemp) (*((char *)(&dwTemp) + 3))
//static uint8_t TxCount=0;
//static uint8_t Count=0;
//static uint8_t TxBuff[256];//串口发送缓冲区
uint8_t RxBuff[2][50]; //串口接收缓冲区
uint8_t Line0,Line1; //串口接收双缓冲切换
typedef union {unsigned char byte[4];float num;}t_floattobyte;
t_floattobyte floattobyte;
//u16 USART_RX_STA=0;
///*******************************************************************************
//* Function Name : USART_Configuration
//* Description : Configure Open_USARTx
//* Input : None
//* Output : None
//* Return : None
//* Attention : None
//*******************************************************************************/
u8 TxBuffer[256];
u8 TxCounter=0;
u8 count=0;
u8 RxBuffer[50];
u8 RxState = 0;
u8 RxBufferNum = 0;
u8 RxBufferCnt = 0;
u8 RxLen = 0;
//////////////////////////////////////////////////////////////////
//加入以下代码,支持printf函数,而不需要选择use MicroLIB
#if 1
#pragma import(__use_no_semihosting)
//标准库需要的支持函数
struct __FILE
{
int handle;
};
FILE __stdout;
//定义_sys_exit()以避免使用半主机模式
_sys_exit(int x)
{
x = x;
}
//重定义fputc函数
int fputc(int ch, FILE *f)
{
while((USART1->SR&0X40)==0);//循环发送,直到发送完毕
USART1->DR = (u8) ch;
return ch;
}
#endif
void Usart1_Init(u32 baudrate)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1);
//Open_USARTx_TX -> PA9 , Open_USARTx_RX -PA10
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = baudrate;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
/* Enable the Open_USART Transmit interrupt: this interrupt is generated when the
Open_USARTx transmit data register is empty */
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
USART_Cmd(USART1, ENABLE);
}
void USART1_NVIC_Configuration(void) //设置串口中断优先级
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void USART1_IRQHandler(void) //串口1中断服务程序
{
if(USART1->SR & USART_SR_ORE)//ORE中断
{
u8 com_data = USART1->DR;//USART_ClearFlag(USART1,USART_IT_ORE);
}
//发送中断
if((USART1->SR & (1<<7))&&(USART1->CR1 & USART_CR1_TXEIE))//if(USART_GetITStatus(USART1,USART_IT_TXE)!=RESET)
{
USART1->DR = TxBuffer[TxCounter++]; //写DR清除中断标志
if(TxCounter == count)
{
USART1->CR1 &= ~USART_CR1_TXEIE; //关闭TXE中断//USART_ITConfig(USART1,USART_IT_TXE,DISABLE);
}
}
//接收中断 (接收寄存器非空) /////////////////////////////////////////////////////////////////////////////////////////
if(USART1->SR & (1<<5))//if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
static uint8_t Head = 0;
static uint8_t Line = 0;
uint8_t com_data = USART1->DR;
if(Head==0) //寻找帧头
{
if(com_data=='$')
{
RxBuff[Line][0] = com_data;
Head = 1;
}
}
else if(Head==1)
{
if(com_data=='M')
{
RxBuff[Line][1] = com_data;
Head = 2;
}
else
Head = 0;
}
else if(Head==2)
{
if(com_data=='<')//上位机发送给MWC
{
RxBuff[Line][2] = com_data;
Head = 3;
}
else
Head = 0;
}
else
{
RxBuff[Line][Head] = com_data;
Head ++;
}
if(Head==RxBuff[Line][3]+6) //数据接收完毕
{
Head = 0;
if(Line)
{
Line = 0; //切换缓存
Line1 = 1;
}
else
{
Line = 1;
Line0 = 1;
}
}
}
}
/******************************************************************************
函数原型: void Uart_Check(void)
功 能: 串口缓冲数据处理
*******************************************************************************/
void Uart_Check(void)
{
uint8_t Line_address;
if(Line0==1 || Line1==1)
{
if(Line0==1)//确定缓冲队列
{
Line0 = 0;Line_address = 0;
}
else
{
Line1 = 0;Line_address = 1;
}
switch (RxBuff[Line_address][4])
{
case MSP_SET_PID : //设置PID参数
pid[0].kp = RxBuff[Line_address][5];
pid[0].ki = RxBuff[Line_address][6];
pid[0].kd = RxBuff[Line_address][7];
pid[1].kp = RxBuff[Line_address][8];
pid[1].ki = RxBuff[Line_address][9];
pid[1].kd = RxBuff[Line_address][10];
pid[2].kp = RxBuff[Line_address][11];
pid[2].ki = RxBuff[Line_address][12];
pid[2].kd = RxBuff[Line_address][13];
Print_MSP_SET_PID();
Print_MSP_PID();
break;
case MSP_PID : //读取PID参数
Print_MSP_PID();
break;
case MSP_ACC_CALIBRATION : //校正加速度计
Do_ACC_Offset();
break;
case MSP_MAG_CALIBRATION : //原是校正磁力计,这里用来校正陀螺仪
Do_GYRO_Offset();
break;
case MSP_RESET_CONF : //重置PID
{
PID_Reset();
Print_MSP_PID();
//NRF_Send_TX(RxBuff[Line_address],32);
break;
}
}
}
}
/**************************实现函数********************************************
*******************************************************************************/
uint8_t Uart1_Put_Char(unsigned char DataToSend)
{
TxBuffer[count++] = DataToSend;
if(!(USART1->CR1 & USART_CR1_TXEIE))
USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
return DataToSend;
}
void Uart1_Put_Buf(unsigned char *DataToSend , u8 data_num)
{ u8 i;
for(i=0;i<data_num;i++)
TxBuffer[count++] = *(DataToSend+i);
if(!(USART1->CR1 & USART_CR1_TXEIE))
USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
}
uint8_t Uart1_Put_Int16(uint16_t DataToSend)
{
uint8_t sum = 0;
TxBuffer[count++] = BYTE1(DataToSend);
TxBuffer[count++] = BYTE0(DataToSend);
if(!(USART1->CR1 & USART_CR1_TXEIE))
USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
sum += BYTE1(DataToSend);
sum += BYTE0(DataToSend);
return sum;
}
uint8_t Uart1_Put_Float(float DataToSend)
{
uint8_t sum = 0;
floattobyte.num=DataToSend;
TxBuffer[count++] = floattobyte.byte[3];
TxBuffer[count++] = floattobyte.byte[2];
TxBuffer[count++] = floattobyte.byte[1];
TxBuffer[count++] = floattobyte.byte[0];
if(!(USART1->CR1 & USART_CR1_TXEIE))
USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
sum += BYTE3(DataToSend);
sum += BYTE2(DataToSend);
sum += BYTE1(DataToSend);
sum += BYTE0(DataToSend);
return sum;
}
void Uart1_Put_String(unsigned char *Str)
{
//判断Str指向的数据是否有效.
while(*Str)
{
//是否是回车字符 如果是,则发送相应的回车 0x0d 0x0a
if(*Str=='\r')Uart1_Put_Char(0x0d);
else if(*Str=='\n')Uart1_Put_Char(0x0a);
else Uart1_Put_Char(*Str);
//指针++ 指向下一个字节.
Str++;
}
}
| C | CL | b37a4bc3df388f6449b0613d7d5f5d038223327b1864f6368f325102e6598e7b |
/******************************************************************************
* Copyright (c) 2002 Linux UPnP Internet Gateway Device Project *
* All rights reserved. *
* *
* This file is part of The Linux UPnP Internet Gateway Device (IGD). *
* *
* The Linux UPnP IGD is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* The Linux UPnP IGD 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 Foobar; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
* *
* *
******************************************************************************/
//
// Special thanks to Genmei Mori and his team for the work he done on the
// ipchains version of this code. .
//
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
//#include <syslog.h>
#include <signal.h>
#include "upnp/upnp.h"
#include "gateway.h"
#include "ipcon.h"
//#include "sample_util.h"
#include "portmap.h"
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "pmlist.h"
#include "gate.h"
#include <sys/types.h>
#include <sys/stat.h>
// The global GATE object
//Gate gate;
struct Gate gate;
// Callback Function wrapper. This is needed because ISO forbids a pointer to a bound
// member function. This corrects the issue.
int CallbackEventHandler(Upnp_EventType EventType, void *Event, void *Cookie)
{
// return gate.GateDeviceCallbackEventHandler(EventType, Event, Cookie);
return GateDeviceCallbackEventHandler(&gate, EventType, Event, Cookie);
}
int substr(char *docpath, char *infile, char *outfile, char *str_from, char *str_to);
int main (int argc, char** argv)
{
char *desc_doc_name=NULL, *conf_dir_path=NULL;
char lan_ip_address[16];
char desc_doc_url[200];
int sig;
sigset_t sigs_to_catch;
int port;
int ret;
char *address;
// pid_t pid,sid;
// Log startup of daemon
// syslog(LOG_INFO, "The Linux UPnP Internet Gateway Device Ver 0.92 by Dime ([email protected])");
// syslog(LOG_INFO, "Special Thanks for Intel's Open Source SDK and original author Genmei Mori's work.");
if (argc != 3)
{
printf("Usage: upnpd <external ifname> <internal ifname>\n");
printf("Example: upnpd ppp0 eth0\n");
printf("Example: upnpd eth1 eth0\n");
exit(0);
}
if (geteuid()) {
fprintf(stderr, "upnpd must be run as root\n");
exit(EXIT_FAILURE);
}
#if 0
pid = fork();
if (pid < 0)
{
perror("Error forking a new process.");
exit(EXIT_FAILURE);
}
if (pid > 0)
exit(EXIT_SUCCESS);
if ((sid = setsid()) < 0)
{
perror("Error running setsid");
exit(EXIT_FAILURE);
}
#endif
if ((chdir("/")) < 0)
{
perror("Error setting root directory");
exit(EXIT_FAILURE);
}
umask(0);
//close (STDOUT_FILENO);
//close (STDERR_FILENO);
/* Zero out the gate structure */
memset(&gate, 0, sizeof(struct Gate));
// gate.m_ipcon = new IPCon(argv[2]);
gate.m_ipcon = (struct IPCon *)malloc(sizeof(struct IPCon));
IPCon_Construct(gate.m_ipcon, argv[2]);
// address = gate.m_ipcon->IPCon_GetIpAddrStr();
address = IPCon_GetIpAddrStr(gate.m_ipcon);
strcpy(lan_ip_address, address);
if (address) free(address);
IPCon_Destruct(gate.m_ipcon);
free(gate.m_ipcon);
port = INIT_PORT;
desc_doc_name=INIT_DESC_DOC;
conf_dir_path=INIT_CONF_DIR;
sprintf(desc_doc_url, "http://%s:%d/%s.xml", lan_ip_address, port,desc_doc_name);
// syslog(LOG_DEBUG, "Intializing UPnP with desc_doc_url=%s\n",desc_doc_url);
// syslog(LOG_DEBUG, "ipaddress=%s port=%d\n", lan_ip_address, port);
// syslog(LOG_DEBUG, "conf_dir_path=%s\n", conf_dir_path);
substr(conf_dir_path, "gatedesc.skl", "gatedesc.xml", "!ADDR!",lan_ip_address);
if ((ret = UpnpInit(lan_ip_address, port)) != UPNP_E_SUCCESS)
{
// syslog(LOG_ERR, "Error with UpnpInit -- %d\n", ret);
UpnpFinish();
exit(1);
}
// syslog(LOG_DEBUG, "UPnP Initialization Completed");
// syslog(LOG_DEBUG, "Setting webserver root directory -- %s\n",conf_dir_path);
if ((ret = UpnpSetWebServerRootDir(conf_dir_path)) != UPNP_E_SUCCESS)
{
// syslog(LOG_ERR, "Error setting webserver root directory -- %s: %d\n",
// conf_dir_path, ret);
UpnpFinish();
exit(1);
}
// gate.m_ipcon = new IPCon(argv[1]);
gate.m_ipcon = (struct IPCon *) malloc(sizeof(struct IPCon));
IPCon_Construct(gate.m_ipcon, argv[1]);
// syslog(LOG_DEBUG, "Registering the root device\n");
if ((ret = UpnpRegisterRootDevice(desc_doc_url, CallbackEventHandler,
&gate.device_handle, &gate.device_handle)) != UPNP_E_SUCCESS)
{
// syslog(LOG_ERR, "Error registering the rootdevice : %d\n", ret);
UpnpFinish();
exit(1);
}
else
{
// syslog(LOG_DEBUG, "RootDevice Registered\n");
// syslog(LOG_DEBUG, "Initializing State Table\n");
// gate.GateDeviceStateTableInit(desc_doc_url);
GateDeviceStateTableInit(&gate, desc_doc_url);
// syslog(LOG_DEBUG, "State Table Initialized\n");
if ((ret = UpnpSendAdvertisement(gate.device_handle, 1800))
!= UPNP_E_SUCCESS)
{
// syslog(LOG_ERR, "Error sending advertisements : %d\n", ret);
UpnpFinish();
exit(1);
}
// syslog(LOG_DEBUG, "Advertisements Sent\n");
}
gate.startup_time = time(NULL);
//Start The Command Loop
sigemptyset(&sigs_to_catch);
sigaddset(&sigs_to_catch, SIGINT);
sigaddset(&sigs_to_catch, SIGTERM);
sigwait(&sigs_to_catch, &sig);
// syslog(LOG_INFO, "Shutting down on signal %d...\n", sig);
UpnpUnRegisterRootDevice(gate.device_handle);
UpnpFinish();
/* Clean up the Gate object */
GateDeviceDestruct(&gate);
exit(0);
}
int substr(char *docpath, char *infile, char *outfile, char *str_from, char *str_to)
{
FILE *fpi, *fpo;
char pathi[256], patho[256];
char buffi[4096], buffo[4096];
int len_buff, len_from, len_to;
int i, j;
sprintf(pathi, "%s%s", docpath, infile);
if ((fpi = fopen(pathi,"r")) == NULL)
{
printf("input file can not open\n");
return (-1);
}
sprintf(patho, "%s%s", docpath, outfile);
if ((fpo = fopen(patho,"w")) == NULL) {
printf("output file can not open\n");
fclose(fpi);
return (-1);
}
len_from = strlen(str_from);
len_to = strlen(str_to);
while (fgets(buffi, 4096, fpi) != NULL)
{
len_buff = strlen(buffi);
for (i=0, j=0; i <= len_buff-len_from; i++, j++)
{
if (strncmp(buffi+i, str_from, len_from)==0)
{
strcpy (buffo+j, str_to);
i += len_from - 1;
j += len_to - 1;
} else
*(buffo + j) = *(buffi + i);
}
strcpy(buffo + j, buffi + i);
fputs(buffo, fpo);
}
fclose(fpo);
fclose(fpi);
return (0);
}
| C | CL | ed8675028e4b64f737e55a47a533d3ef4ff13f5ff2fa16575d026ad80057f17b |
#ifndef OBJ_VYLE2_H
#define OBJ_VYLE2_H
#include "obj.h"
typedef enum Vyle2State
{
VYLE2_STATE_INIT,
// Introduction states.
VYLE2_STATE_LYLE_WALK_ANGRY,
VYLE2_STATE_CAMERA_PAN_TO_MACHINE,
VYLE2_STATE_KEDDUMS_MEOW,
VYLE2_STATE_CAMERA_PAN_TO_LYLE,
VYLE2_STATE_LYLE_APPROACH_MACHINE,
VYLE2_STATE_VYLE_ACTIVATE_MACHINE,
VYLE2_STATE_VYLE_APPROACH_MACHINE,
VYLE2_STATE_VYLE_GROW_1,
VYLE2_STATE_VYLE_GROW_2,
VYLE2_STATE_VYLE_GROW_3,
VYLE2_STATE_VYLE_GROW_4,
VYLE2_STATE_ENTER_ARENA,
VYLE2_STATE_START_DELAY,
// Fight states.
VYLE2_STATE_PRE_JUMP,
VYLE2_STATE_JUMP,
VYLE2_STATE_LAND, // --> PRE_JUMP, or SHOOTING
VYLE2_STATE_SHOOTING,
VYLE2_STATE_EDGE_PRE_JUMP,
VYLE2_STATE_EDGE_JUMP,
VYLE2_STATE_EDGE_LAND, // --> EDGE_PRE_JUMP or PRE_BELCH
VYLE2_STATE_PRE_BELCH,
VYLE2_STATE_BELCH, // --> PRE_BELCH or PRE_CHARGE
VYLE2_STATE_PRE_CHARGE,
VYLE2_STATE_CHARGE,
VYLE2_STATE_ZAP,
VYLE2_STATE_ZAP_RECOIL,
VYLE2_STATE_ZAP_RECOIL_BOUNCED,
VYLE2_STATE_VULNERABLE,
VYLE2_STATE_CENTER_PRE_JUMP,
VYLE2_STATE_CENTER_JUMP,
VYLE2_STATE_CENTER_LAND, // --> JUMP_TO_CENTER or PRE_SUPERJUMP
VYLE2_STATE_PRE_SUPERJUMP,
VYLE2_STATE_SUPERJUMP_UP,
VYLE2_STATE_SUPERJUMP_HOVER,
VYLE2_STATE_SUPERJUMP_DOWN, // --> VYLE2_STATE_LAND or VYLE2_STATE_SUPERJUMP_EXIT
VYLE2_STATE_SUPERJUMP_EXIT,
// Ending (part 1)
VYLE2_STATE_END1_FALL_REPEAT,
VYLE2_STATE_END1_FALL_DOWN,
VYLE2_STATE_END1_LYLE_LANDED,
VYLE2_STATE_END1_EXPLODING,
VYLE2_STATE_END1_EXPLODED,
// Ending (part 2)
VYLE2_STATE_END2_LYLE_RISE_UP,
VYLE2_STATE_END2_LYLE_LANDED,
VYLE2_STATE_END2_LYLE_CAT_LAUNCHED,
VYLE2_STATE_END2_LYLE_ESCAPE,
// Ending (part 3)
VYLE2_STATE_END3_LYLE_ENTER,
VYLE2_STATE_END3_LYLE_HOP_DOWN,
VYLE2_STATE_END3_LYLE_APPROACH,
VYLE2_STATE_END3_LYLE_HOP_UP,
VYLE2_STATE_END3_LYLE_TAKEOFF,
} Vyle2State;
typedef struct O_Vyle2
{
Obj head;
// Position for the camera.
fix32_t xscroll;
fix32_t yscroll;
int16_t lyle_anim_cnt;
int16_t lyle_anim_frame;
Vyle2State first_state;
Vyle2State state;
int16_t state_elapsed;
uint16_t anim_cnt;
uint16_t anim_frame;
int16_t metaframe;
// jump logic
int16_t jump_count;
bool shot_at_lyle;
fix32_t jump_tx;
// shot phase
int16_t shots_remaining;
int16_t shot_cnt;
// superjump phase
int16_t crumble_cnt;
int16_t ground_slams;
bool shaking;
// endinng pt1
int16_t fall_cycles;
} O_Vyle2;
void o_load_vyle2(Obj *o, uint16_t data);
void o_unload_vyle2(void);
#endif // OBJ_VYLE2_H
| C | CL | 0b144a098a14bc9fb060cd19f84f53dcbe3ed64a03606c8b7be07f7cae886be7 |
/*
Author: Debbie Nuttall <[email protected]>
Copyright (c) 2015 Cromulence LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "libcgc.h"
#include "cgc_stdlib.h"
#include "cgc_stdint.h"
#include "cgc_canvas.h"
#include "cgc_paint.h"
// Get the RGB color at a particular location in the canvas
RGB_Color *cgc_GetColor(Canvas *c, uint16_t y, uint16_t x, uint8_t layer) {
uint8_t *current_layer = c->layers[layer];
int color = current_layer[y * c->x_size + x];
return &c->colors[color];
}
// Get the color index at a particular location in the canvas
int cgc_GetColorIndex(Canvas *c, uint16_t y, uint16_t x, uint8_t layer) {
uint8_t *current_layer = c->layers[layer];
return current_layer[y * c->x_size + x];
}
// Set the color index at a particular location in the canvas
void cgc_SetColor(Canvas *c, uint16_t y, uint16_t x, uint8_t layer, uint8_t color) {
uint8_t *current_layer = c->layers[layer];
if ( current_layer == NULL ) {
return;
}
#ifdef PATCHED
if (y >= c->y_size || x >= c->x_size) {
return;
}
#endif
current_layer[y * c->x_size + x] = color;
}
void cgc_PaintTriangle(Canvas *c, uint8_t layer, uint8_t color, uint8_t fill, VGF_Triangle *triangle) {
if (triangle->x0 >= c->x_size || triangle->x1 >= c->x_size || triangle->x2 >= c->x_size) {
return;
}
if (triangle->y0 >= c->y_size || triangle->y1 >= c->y_size || triangle->y2 >= c->y_size) {
return;
}
if (fill == 0) {
// Draw outline
cgc_ConnectPoints(c, layer, color, triangle->x0, triangle->y0, triangle->x1, triangle->y1);
cgc_ConnectPoints(c, layer, color, triangle->x2, triangle->y2, triangle->x0, triangle->y0);
cgc_ConnectPoints(c, layer, color, triangle->x1, triangle->y1, triangle->x2, triangle->y2);
} else {
// Fill triangle
// Sort points top to bottom
uint16_t *x0, *y0, *x1, *y1, *x2, *y2;
if (triangle->y0 > triangle->y1) {
x0 = &triangle->x1;
y0 = &triangle->y1;
x1 = &triangle->x0;
y1 = &triangle->y0;
} else {
x0 = &triangle->x0;
y0 = &triangle->y0;
x1 = &triangle->x1;
y1 = &triangle->y1;
}
if (*y1 > triangle->y2) {
x2 = x1;
y2 = y1;
if (*y0 > triangle->y2) {
x1 = x0;
y1 = y0;
x0 = &triangle->x2;
y0 = &triangle->y2;
}
else {
x1 = &triangle->x2;
y1 = &triangle->y2;
}
} else {
x2 = &triangle->x2;
y2 = &triangle->y2;
}
// ...
uint32_t last_y, x_low, x_high;
uint32_t y;
x_low = *x0;
x_high = *x0;
if (*x1 < x_low) {
x_low = *x1;
} else if (*x1 > x_high) {
x_high = *x1;
}
if (*x2 < x_low) {
x_low = *x2;
} else if (*x2 > x_high) {
x_high = *x2;
}
// Flat triangle
if (*y2 == *y0) {
if (x_high > x_low) {
cgc_ConnectPoints(c, layer, color, x_low, *y0, x_high - 1, *y0);
}
return;
}
if (*y1 == *y2) {
last_y = *y1;
} else {
last_y = *y1 - 1;
}
int step_low, step_high;
step_low = 0;
step_high = 0;
if (*y0 == *y1) {
// Draw base of triangle
x_low = *x0;
x_high = *x1;
if (x_low > x_high) {
x_high = *x0;
x_low = *x1;
}
if (x_high > x_low) {
cgc_ConnectPoints(c, layer, color, x_low, *y0, x_high - 1, *y0);
}
y = *y1;
} else {
y = *y0;
while (y <= last_y) {
x_high = *x0 + step_high / (*y2 - *y0);
x_low = *x0 + step_low / (*y1 - *y0);
step_high += *x2 - *x0;
step_low += *x1 - *x0;
if (x_low > x_high) {
int swap = x_low;
x_low = x_high;
x_high = swap;
}
if (x_high > x_low) {
cgc_ConnectPoints(c, layer, color, x_low, y, x_high - 1, y);
}
y++;
}
}
step_high = (*x2 - *x0) * (y - *y0);
step_low = (*x2 - *x1) * (y - *y1);
while (y <= *y2) {
x_high = *x0 + step_high / (*y2 - *y0);
x_low = *x1 + step_low / (*y2 - *y1);
step_high += *x2 - *x0;
step_low += *x2 - *x1;
if (x_low > x_high) {
int swap = x_low;
x_low = x_high;
x_high = swap;
}
if (x_high > x_low) {
cgc_ConnectPoints(c, layer, color, x_low, y, x_high - 1, y);
}
y++;
}
}
}
void cgc_PaintRectangle(Canvas *c, uint8_t layer, uint8_t color, uint8_t fill, VGF_Rectangle *rectangle) {
if ((rectangle->x_start >= c->x_size) || (rectangle->y_start >= c->y_size)) {
return;
}
if (rectangle->x_start + rectangle->x_len >= c->x_size) {
return;
}
if (rectangle->y_start + rectangle->y_len >= c->y_size) {
return;
}
if (rectangle->x_len == 0 && rectangle->y_len == 0) {
return;
}
cgc_ConnectPoints(c, layer, color, rectangle->x_start, rectangle->y_start, rectangle->x_start, rectangle->y_start + rectangle->y_len);
cgc_ConnectPoints(c, layer, color, rectangle->x_start, rectangle->y_start + rectangle->y_len, rectangle->x_start + rectangle->x_len, rectangle->y_start + rectangle->y_len);
cgc_ConnectPoints(c, layer, color, rectangle->x_start + rectangle->x_len, rectangle->y_start, rectangle->x_start + rectangle->x_len, rectangle->y_start + rectangle->y_len);
cgc_ConnectPoints(c, layer, color, rectangle->x_start, rectangle->y_start, rectangle->x_start + rectangle->x_len, rectangle->y_start );
// Fill if necessary
if ((fill == 1) && (rectangle->x_len > 1)) {
for (uint16_t y_position = 1; y_position < rectangle->y_len; y_position++) {
cgc_ConnectPoints(c, layer, color, rectangle->x_start + 1, rectangle->y_start + y_position, rectangle->x_start + rectangle->x_len - 1, rectangle->y_start + y_position);
}
}
}
void cgc_PaintSquare(Canvas *c, uint8_t layer, uint8_t color, uint8_t fill, VGF_Square *square) {
if ((square->x_start >= c->x_size) || (square->y_start >= c->y_size)) {
return;
}
if (square->x_start + square->x_len >= c->x_size) {
return;
}
if (square->y_start + square->x_len >= c->y_size) {
return;
}
if (square->x_len == 0) {
return;
}
cgc_ConnectPoints(c, layer, color, square->x_start, square->y_start, square->x_start, square->y_start + square->x_len);
cgc_ConnectPoints(c, layer, color, square->x_start, square->y_start + square->x_len, square->x_start + square->x_len, square->y_start + square->x_len);
cgc_ConnectPoints(c, layer, color, square->x_start + square->x_len, square->y_start, square->x_start + square->x_len, square->y_start + square->x_len);
cgc_ConnectPoints(c, layer, color, square->x_start, square->y_start, square->x_start + square->x_len, square->y_start );
// Fill if necessary
if ((fill == 1) && (square->x_len > 1)) {
for (uint16_t y_position = 1; y_position < square->x_len; y_position++) {
cgc_ConnectPoints(c, layer, color, square->x_start + 1, square->y_start + y_position, square->x_start + square->x_len - 1, square->y_start + y_position);
}
}
}
void cgc_ConnectPoints(Canvas *c, uint8_t layer, uint8_t color, uint16_t x_start, uint16_t y_start, uint16_t x_end, uint16_t y_end) {
int width, height, dots, x_dir, y_dir;
if (x_end > x_start) {
width = x_end - x_start;
x_dir = 1;
} else {
width = x_start - x_end;
x_dir = -1;
}
if (y_end > y_start) {
height = y_end - y_start;
y_dir = 1;
} else {
height = y_start - y_end;
y_dir = -1;
}
if (height > width) {
dots = height;
} else {
dots = width;
}
int x = x_start;
int y = y_start;
int x_inc = 0;
int y_inc = 0;
int count = 0;
while (count <= dots + 1) {
cgc_SetColor(c, y, x, layer, color);
x_inc += width;
y_inc += height;
if (x_inc > dots) {
x+=x_dir;
x_inc -= dots;
}
if (y_inc > dots) {
y+=y_dir;
y_inc -= dots;
}
count++;
}
}
void cgc_PaintLine(Canvas *c, uint8_t layer, uint8_t color, uint8_t fill, VGF_Line *line) {
if ((line->x_start >= c->x_size) || (line->x_start > line->x_end)) {
return;
}
if ((line->y_start >= c->y_size) || (line->y_start > line->y_end)) {
return;
}
if ((line->y_end >= c->y_size) || (line->x_end >= c->x_size)) {
return;
}
cgc_ConnectPoints(c, layer, color, line->x_start, line->y_start, line->x_end, line->y_end);
}
void cgc_PaintCircle(Canvas *c, uint8_t layer, uint8_t color, uint8_t fill, VGF_Circle *circle) {
if ((circle->x_start >= c->x_size) || (circle->y_start >= c->y_size)) {
return;
}
if ((circle->x_start + circle->radius >= c->x_size) ||
(circle->y_start + circle->radius >= c->y_size)) {
return;
}
if ((circle->x_start - circle->radius < 0) ||
(circle->y_start - circle->radius < 0)) {
return;
}
int x, y, x_pos, y_pos;
x = 0;
y = circle->radius;
int radius_error = 1 - circle->radius;
int ddf_x, ddf_y;
ddf_x = 1;
ddf_y = -2 * circle->radius;
x_pos = circle->x_start;
y_pos = circle->y_start;
if (fill == 0) {
cgc_SetColor(c, y_pos + circle->radius, x_pos, layer, color);
cgc_SetColor(c, y_pos - circle->radius, x_pos, layer, color);
cgc_SetColor(c, y_pos, x_pos + circle->radius, layer, color);
cgc_SetColor(c, y_pos, x_pos - circle->radius, layer, color);
} else {
cgc_ConnectPoints(c, layer, color, x_pos, y_pos - y, x_pos, y_pos + y - 1);
}
while (x < y) {
if (radius_error >= 0) {
y--;
ddf_y += 2;
radius_error += ddf_y;
}
x++;
ddf_x += 2;
radius_error += ddf_x;
if (fill == 0) {
// Draw outline
cgc_SetColor(c, y_pos + y, x_pos + x, layer, color);
cgc_SetColor(c, y_pos + y, x_pos - x, layer, color);
cgc_SetColor(c, y_pos - y, x_pos + x, layer, color);
cgc_SetColor(c, y_pos - y, x_pos - x, layer, color);
cgc_SetColor(c, y_pos + x, x_pos + y, layer, color);
cgc_SetColor(c, y_pos + x, x_pos - y, layer, color);
cgc_SetColor(c, y_pos - x, x_pos + y, layer, color);
cgc_SetColor(c, y_pos - x, x_pos - y, layer, color);
} else {
// Fill circle
if (y > 0) {
cgc_ConnectPoints(c, layer, color, x_pos + x, y_pos - y, x_pos + x, y_pos + y - 1);
cgc_ConnectPoints(c, layer, color, x_pos - x, y_pos - y, x_pos - x, y_pos + y - 1);
}
if (x > 0) {
cgc_ConnectPoints(c, layer, color, x_pos + y, y_pos - x, x_pos + y, y_pos + x - 1);
cgc_ConnectPoints(c, layer, color, x_pos - y, y_pos - x, x_pos - y, y_pos + x - 1);
}
}
}
}
void cgc_PaintSpray(Canvas *c, uint8_t layer, uint8_t color, uint8_t fill, VGF_Spray *spray) {
if ((spray->x_start >= c->x_size) || (spray->y_start >= c->y_size)) {
return;
}
if (spray->magic != 0x59745974) {
return;
}
if (spray->density > 100 || spray->density == 0) {
return;
}
int step = 100 / spray->density;
if (step <= 0) {
return;
}
int x_pos = spray->x_start;
int y_pos = spray->y_start;
int width = spray->width;
while ((x_pos < spray->x_start + width) && (x_pos < c->x_size)) {
cgc_SetColor(c, y_pos, x_pos, layer, color);
x_pos += step;
}
x_pos = spray->x_start;
while ((x_pos > spray->x_start - width) && (x_pos >= 0)) {
cgc_SetColor(c, y_pos, x_pos, layer, color);
x_pos -= step;
}
x_pos = spray->x_start;
while ((y_pos < spray->y_start + width) && (y_pos < c->y_size)) {
cgc_SetColor(c, y_pos, x_pos, layer, color);
y_pos += step;
}
y_pos = spray->y_start;
while ((y_pos > spray->y_start - width) && (y_pos >= 0)) {
cgc_SetColor(c, y_pos, x_pos, layer, color);
y_pos -= step;
}
cgc_SetColor(c, spray->y_start, spray->x_start + width, layer, color);
cgc_SetColor(c, spray->y_start, spray->x_start - width, layer, color);
cgc_SetColor(c, spray->y_start + width, spray->x_start, layer, color);
cgc_SetColor(c, spray->y_start - width, spray->x_start, layer, color);
}
| C | CL | bd63310bddd8b5f2821f78a03a56a9af0bc28d3e42216d248173f8636f4f91f8 |
#include "pcm.h"
static volatile uint32_t * pcmMap = 0;
static bool pcmInitialized;
static bool pcmRunning;
static uint32_t * buffer;
static int32_t syncWait;
static VirtToBusPages bufferPages;
//static DMAControlBlock * rxCtrlBlk;
//static DMAControlBlock * txCtrlBlk;
//static unsigned * rxtxRAMptr;
// TODO
static bool checkFrameAndChannelWidth(pcmExternInterface * ext) {
return 0;
}
static void checkInitParams(pcmExternInterface * ext, uint8_t thresh, uint8_t panicThresh) {
if (!ext->isMasterDevice && checkFrameAndChannelWidth(ext))
FATAL_ERROR("incompatible frame lengths and data widths.")
if (ext->numChannels < 1 || ext->numChannels > 2)
FATAL_ERROR("valid number of channels are 1 or 2.");
if (ext->dataWidth > 32) {
FATAL_ERROR("maximum data width available is 32 bits.");
} else if (ext->dataWidth % 8) {
FATAL_ERROR("please set data width to be a multiple of 8 bits.");
}
if (thresh >= 128 || panicThresh >= 128)
FATAL_ERROR("thresholds must be six-bit values for DMA mode.")
}
/*
determine the delay (in microseconds) between writing to SYNC in PCM CTRL reg
and reading back the value written. This corresponds to ~2 PCM clk cycles
should only need to call once to get an idea of how long to delay the program
*/
static int32_t getSyncDelay() {
char sync, notSync;
struct timeval initTime, endTime;
// get current sync value
sync = (pcmMap[PCM_CTRL_REG] >> 24) & 1;
notSync = sync^1;
// write opposite value back to reg
pcmMap[PCM_CTRL_REG] ^= 1<<24;
// time
gettimeofday(&initTime, NULL);
while ((pcmMap[PCM_CTRL_REG] >> 24) ^ notSync); // wait until values are the same of each other (this will equate to 0)
gettimeofday(&endTime, NULL);
uint32_t usElapsed = ((endTime.tv_sec - initTime.tv_sec)*1000000) + (endTime.tv_usec - initTime.tv_usec);
DEBUG_VAL("2-cycle PCM clk delay in micros", (usElapsed + (10 - (usElapsed % 10))));
// round up
return usElapsed + (10 - (usElapsed % 10));
}
static void initRXTXControlRegisters(pcmExternInterface * ext, bool packedMode) {
uint8_t widthBits, widthExtension, ch2Enable;
uint16_t channel1Bits, channel2Bits;
uint32_t txrxInitBits;
ch2Enable = 0;
if (ext->numChannels==2) {
ch2Enable = 1;
// truncate to 16b data if necessary
if (packedMode && ext->dataWidth > 16) {
printf("\nTruncating channel width to 16 bits...\n");
ext->dataWidth = 16;
}
}
widthBits = (ext->dataWidth > 24) ? ext->dataWidth - 24: ext->dataWidth - 8;
widthExtension = (ext->dataWidth > 24) ? 1: 0;
channel1Bits = (widthExtension << 15) | (ext->ch1Pos << 4) | widthBits; // start @ clk 1 of frame
channel2Bits = channel1Bits | (32 << 4); // start 32 bits after ch1 (assuming SCLK/LRCLK == 64)
//enable channels
channel1Bits |= (1 << 14);
channel2Bits |= (ch2Enable << 14);
txrxInitBits = (channel1Bits << 16) | channel2Bits;
pcmMap[PCM_RXC_REG] = txrxInitBits;
pcmMap[PCM_TXC_REG] = txrxInitBits;
DEBUG_REG("RX reg", pcmMap[PCM_RXC_REG]);
}
static void initDMAMode(uint8_t dataWidth, uint8_t thresh, uint8_t panicThresh, bool packedMode) {
// set DMAEN to enable DREQ generation and set RX/TXREQ, RX/TXPANIC
pcmMap[PCM_CTRL_REG] |= (1 << 9); // DMAEN
usleep(1000);
// TODO: separate panic thresholds from dreq thresholds
pcmMap[PCM_DREQ_REG] = (panicThresh << 24) | (panicThresh<<16) | (thresh << 8) | thresh;
// read from FIFO to here, and write from here to FIFO
bufferPages = initUncachedMemView(BCM_PAGESIZE, USE_DIRECT_UNCACHED);
void * virtBufferPages = bufferPages.virtAddr;
void * busBufferPages = (void *)bufferPages.busAddr;
DEBUG_PTR("virtual buffer page", virtBufferPages);
DEBUG_PTR("bus buffer page", busBufferPages);
// peripheral addresses must be physical
//uint32_t bcm_base = getBCMBase();
uint32_t fifoPhysAddr = BUS_BASE + PCM_BASE_OFFSET + (PCM_FIFO_REG<<2); // PCM_FIFO_REG is macro defined by int offset, need byte offset
uint32_t csPhysAddr = BUS_BASE + PCM_BASE_OFFSET + (PCM_CTRL_REG<<2);
if (DEBUG) printf("FIFO physical address = %x\n", fifoPhysAddr);
// these bytes are the sources for two DMA control blocks, whose destinations are the PCM_CTRL_REG. This way the DMA can automatically
// update TXON and RXON each time it switches between reading from the FIFO and writing to the FIFO
uint8_t dmaRxOnByte = (uint8_t)(pcmMap[PCM_CTRL_REG] & 0xF9) | RXON;
uint8_t dmaTxOnByte = (uint8_t)(pcmMap[PCM_CTRL_REG] & 0xF9) | TXON;
uint32_t lastByteIdx = sizeof(virtBufferPages) - 1;
((char *)virtBufferPages)[lastByteIdx - 1] = dmaRxOnByte;
((char *)virtBufferPages)[lastByteIdx] = dmaTxOnByte;
// TODO: verify transfer length line
// if using packed mode, then a single data transfer is 2-channel, therefore twice the data width
uint32_t transferLength = packedMode ? dataWidth >> 1 : dataWidth >> 2; // represented in bytes
uint32_t rxTransferInfo = (PERMAP(RXPERMAP) | SRC_DREQ | SRC_INC | DEST_INC);
uint32_t txTransferInfo = (PERMAP(TXPERMAP) | DEST_DREQ | SRC_INC | DEST_INC);
DMAControlPageWrapper cbWrapper = initDMAControlPage(4);
/*
4 DMA Control blocks:
CB0: write from buffer pages to FIFO (when TXDREQ high)
CB1: set TX OFF and RX ON in the PCM CTRL REG
CB2: read from FIFO to buffer pages (when RXDREQ high)
CB3: set TX ON and RX OFF in the PCM CTRL REG
(repeat)
*/
// for now, insertDMAControlBlock() is an internally inconsistent function, and I would not use it.
/*insertDMAControlBlock (&cbWrapper, txTransferInfo, (uint32_t)busBufferPages, fifoPhysAddr, transferLength, 0);
insertDMAControlBlock (&cbWrapper, 0, (uint32_t)&(((char *)busBufferPages)[lastByteIdx-1]), csPhysAddr, 1, 1);
insertDMAControlBlock (&cbWrapper, rxTransferInfo, fifoPhysAddr, (uint32_t)busBufferPages, transferLength, 2);
insertDMAControlBlock (&cbWrapper, 0, (uint32_t)&(((char *)busBufferPages)[lastByteIdx]), csPhysAddr, 1, 3);*/
initDMAControlBlock(&cbWrapper, txTransferInfo, (uint32_t)busBufferPages, fifoPhysAddr, transferLength);
initDMAControlBlock(&cbWrapper, 0, (uint32_t)&(((char *)busBufferPages)[lastByteIdx-1]), csPhysAddr, 1);
initDMAControlBlock(&cbWrapper, rxTransferInfo, fifoPhysAddr, (uint32_t)busBufferPages, transferLength);
initDMAControlBlock(&cbWrapper, 0, (uint32_t)&(((char *)busBufferPages)[lastByteIdx]), csPhysAddr, 1);
VERBOSE_MSG("Control blocks set.\n");
// create loop
linkDMAControlBlocks(&cbWrapper, 0, 1);
linkDMAControlBlocks(&cbWrapper, 1, 0);//2);
linkDMAControlBlocks(&cbWrapper, 2, 3);
linkDMAControlBlocks(&cbWrapper, 3, 0);
VERBOSE_MSG("Control block loop(s) set.\n");
initDMAChannel((DMAControlBlock *)(cbWrapper.pages.busAddr), PCM_DMA_CHANNEL);
VERBOSE_MSG("Control blocks loaded into DMA registers.\nDMA mode successfully initialized.\n");
buffer = (uint32_t*)virtBufferPages;
}
// TODO: add params to determine if packedMode
/*
ext: pointer to a struct that defines the settings of the off-board device for PCM and how our code should interact with it
thresh: threshold for TX and RX registers. Interpretation depends on mode
for DMA mode:
value of TX & RX request levelext (in DREQ_A reg). When the FIFO data level is above this the PCM will assert its DMA DREQ
signal to request that some more data is read out of the FIFO
packedMode: (for 2 channel data)
1: use packed mode, where each word to FIFO reg is two 16b signals together, 1 representing each channel
*/
void initPCM(pcmExternInterface * ext, uint8_t thresh, uint8_t panicThresh, bool packedMode) {
if (!pcmMap) {
if(!(pcmMap = initMemMap(PCM_BASE_OFFSET, PCM_BASE_MAPSIZE)))
return;
}
if (pcmRunning) {
printf("ERROR: PCM interface is currently running.\nAborting...\n");
return;
}
checkInitParams(ext, thresh, panicThresh);
if (packedMode && ext->numChannels != 2)
packedMode = 0;
printf("Initializing PCM interface...");
// enable PCM
VERBOSE_MSG("Enabling PCM...\n");
pcmMap[PCM_CTRL_REG] = 1;
usleep(1000);
// set all operational values to define frame and channel settings
// CLKM == FSM
uint8_t flen = ext->frameLength >> 1;
pcmMap[PCM_MODE_REG] = (3*packedMode << 24) | (ext->isMasterDevice << 23) | (!ext->inputOnFallingEdge << 22) | (ext->isMasterDevice << 21) | (flen << 10) | flen;
usleep(1000);
DEBUG_REG("Mode reg", pcmMap[PCM_MODE_REG]);
initRXTXControlRegisters(ext, packedMode);
usleep(1000);
// assert RXCLR & TXCLR, wait 2 PCM clk cycles
pcmMap[PCM_CTRL_REG] |= TXCLR | RXCLR;
usleep(1000);//syncWait = getSyncDelay();
// RAMs should be released from standby before receive/transmit ops
pcmMap[PCM_CTRL_REG] |= STBY;
usleep(2000);//syncWait*2); // allow for at least 4 pcm clock cycles after clearing
initDMAMode(ext->dataWidth, thresh, panicThresh, packedMode);
DEBUG_REG("Mode reg at end of init", pcmMap[PCM_MODE_REG]);
DEBUG_REG("Control reg at end of init", pcmMap[PCM_CTRL_REG]);
for (int i = 18; i <= 21; i++) {
setPinMode(i, 4);
if (DEBUG) printf("pin %d set to ALT0\n", i);
}
uint32_t mClkFreq, pcmClkFreq;
pcmClkFreq = (uint32_t)ext->sampleFreq * ext->frameLength;
mClkFreq = ext->isDoubleSpeedMode ? (pcmClkFreq << 2): (pcmClkFreq << 1);
// initialize clock(s)
initClock(0, mClkFreq, 1, PLLD);
if (!ext->isMasterDevice)
initClock(PCM_CLK_CTL_IDX, pcmClkFreq, 1, OSC); // can both sources use PLLD?
pcmInitialized = 1;
printf("done.\n");
}
void startPCM() {
if (!pcmInitialized)
FATAL_ERROR("PCM interface was not initialized.")
pcmRunning = 1;
VERBOSE_MSG("Starting PCM...\n");
startDMAChannel((uint8_t)PCM_DMA_CHANNEL);
startClock(0);
if (~(pcmMap[PCM_MODE_REG] >> 23) & 1) // if PCM is master mode, need to start PCM CLK
startClock(PCM_CLK_CTL_IDX);
pcmMap[PCM_CTRL_REG] |= TXON;
DEBUG_REG("PCM ctrl reg w/ tx and rx on", pcmMap[PCM_CTRL_REG]);
VERBOSE_MSG("Running...\n");
if (DEBUG) {
for (int i = 0; i < 50; i++) {
printf("Buffer (%p) = %x; PCM CTRL reg = %x; DMA debug reg = %x\n", buffer, *buffer, pcmMap[PCM_CTRL_REG], debugDMA((uint8_t)PCM_DMA_CHANNEL));
}
}
}
void freePCM() {
clearMemMap((void*)pcmMap, PCM_BASE_MAPSIZE);
clearUncachedMemView(&bufferPages);
freeDMA();
freeClocks();
freeGPIO();
}
| C | CL | 535f0d3911042ef37005357dfcbed9f2574fc4fcdaca8b11bd41e8f8ddbb2433 |
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by Aggreg.rc
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Classes Reference and related electronic
// documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft C++ Libraries products.
#define IDS_AGG_DESC 1
#define IDS_AGGBLIND_DESC 2
#define IDS_AUTOAGG_DESC 3
#define IDS_AUTOAGGB_DESC 4
#define IDS_SERVICENAME 100
#define IDR_Agg 1
#define IDR_AggBlind 2
#define IDR_AutoAgg 3
#define IDR_AutoAggB 4
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 201
#define _APS_NEXT_COMMAND_VALUE 32768
#define _APS_NEXT_CONTROL_VALUE 201
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| C | CL | 15cc9708afb333cab983ae62259581b479ff907d4915340bdc1a0f1e121ef62f |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* raycast_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rprieto- <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/29 15:22:48 by rprieto- #+# #+# */
/* Updated: 2021/01/03 02:07:14 by rprieto- ### ########.fr */
/* */
/* ************************************************************************** */
#include "cub3d.h"
#include <math.h>
/*
** Get x intercept length
*/
float get_x_intercept_length(t_ray ray, t_player_vars player)
{
float distance;
float x;
float y;
if (ray.tile_step_x == 1)
x = ray.x_intercept - player.x;
else
x = player.x - ray.x_intercept;
if (ray.tile_step_y == 1)
y = (ray.y + 1) - player.y;
else
y = player.y - ray.y;
distance = sqrtf(x * x + y * y);
return (distance);
}
/*
** Get y intercept length
*/
float get_y_intercept_length(t_ray ray, t_player_vars player)
{
float distance;
float x;
float y;
if (ray.tile_step_x == 1)
x = (ray.x + 1) - player.x;
else
x = player.x - ray.x;
if (ray.tile_step_y == 1)
y = ray.y_intercept - player.y;
else
y = player.y - ray.y_intercept;
distance = sqrtf(x * x + y * y);
return (distance);
}
/*
** Check if the given angle is under 0 or over 2PI and corrects it
*/
void check_angle_overflow(float *angle)
{
if (*angle < 0)
*angle += 2 * PI;
if (*angle > 2 * PI)
*angle -= 2 * PI;
}
/*
** Sets the tile in which the shortest distance ends
*/
void set_tile_crossed(t_ray *ray, char **map)
{
if (ray->distance_hor < ray->distance_ver)
ray->tile_crossed = map[(int)ray->y + ray->tile_step_y]
[(int)ray->x_intercept];
else
ray->tile_crossed = map[(int)ray->y_intercept]
[(int)ray->x + ray->tile_step_x];
}
/*
** Checks if the ray goes throught a sprite
*/
void check_sprite_crossed(t_ray ray, char tile_crossed, t_vars *vars)
{
if (tile_crossed == '2')
{
if (ray.direction == horizontal)
add_sprite_coords(floorf(ray.x_intercept) + 0.5,
ray.y + ray.tile_step_y + 0.5, vars);
else if (ray.direction == vertical)
add_sprite_coords((int)ray.x + ray.tile_step_x + 0.5,
floorf(ray.y_intercept) + 0.5, vars);
}
}
| C | CL | c9bdba6651362976077b549cdb4d95e466e799feec5a9db1dc19e225655e6ef3 |
/*
TITLE : Analog Output using PWM
DATE : 2019/11/12
AUTHOR : e-Yantra Team
AIM: To decrease the brightness of Led and simultaneously increase the brightness of Led,
and repeat this cyclically, for this program a led needs to connected to PB3.
*/
#define F_CPU 16000000UL // Define Crystal Frequency of Uno Board
#include <avr/io.h> // Standard AVR IO Library
#include <util/delay.h> // Standard AVR Delay Library
#include <avr/interrupt.h> // Standard AVR Interrupt Library
#define PIN_LED_RED PB3
void led_init(void){
DDRB |= (1 << PIN_LED_RED);
PORTB |= (1 << PIN_LED_RED);
}
// Timer 2 initialized in PWM mode for brightness control
// Prescale:64
// PWM 8bit fast, TOP=0x00FF
// Timer Frequency:225.000Hz
void timer2_init()
{
cli(); //disable all interrupts
TCCR2B = 0x00; //Stop
TCNT2 = 0xFF; //Counter higher 8-bit value to which OCR2A value is compared with
OCR2A = 0xFF; //Output compare register low value for Led
// Clear OC2A, on compare match (set output to low level)
TCCR2A |= (1 << COM2A1);
TCCR2A &= ~(1 << COM2A0);
// FAST PWM 8-bit Mode
TCCR2A |= (1 << WGM20);
TCCR2A |= (1 << WGM21);
TCCR2B &= ~(1 << WGM22);
// Set Prescalar to 64
TCCR2B &= ~((1 << CS21) | (1 << CS20));
TCCR2B |= (1 << CS22);
sei(); //re-enable interrupts
}
// Function for brightness control of all LED
void brightness (unsigned char red_led){
OCR2A = 255 - (unsigned char)red_led; // active low thats why subtracting by 255
}
//use this function to initialize all devices
void init_devices (void) {
led_init();
timer2_init();
}
//Main Function
int main(){
init_devices();
int step = 0;
while(1){
// decrease led brightness
for (step = 0; step < 256; step++){
brightness(255 - step);
_delay_ms(10);
}
}
}
| C | CL | dafc5860d14bb5a84ce45a6775b143e68a24b14110f730cf55ba21cfb482fd81 |
#ifndef _PLUGIN_MAIN_H_
#define _PLUGIN_MAIN_H_
#ifdef __cplusplus
#define C_LINKAGE "C"
#else
#define C_LINKAGE
#endif /* __cplusplus */
/** The prototype for the application's Plugin_main() function */
extern C_LINKAGE int Plugin_main(Plugin* plugin);
#endif /* _PLUGIN_MAIN_H_ */ | C | CL | b83cf51e4fd61324ad44934854f0646b323621f4025b0bb33cdfca3e5f85ada1 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_5__ TYPE_1__ ;
/* Type definitions */
struct TYPE_5__ {int id; int /*<<< orphan*/ * h; struct TYPE_5__* next; } ;
typedef TYPE_1__ hb_work_object_t ;
typedef int /*<<< orphan*/ hb_handle_t ;
/* Variables and functions */
TYPE_1__* hb_objects ;
TYPE_1__* malloc (int) ;
hb_work_object_t * hb_get_work( hb_handle_t *h, int id )
{
hb_work_object_t * w;
for( w = hb_objects; w; w = w->next )
{
if( w->id == id )
{
hb_work_object_t *wc = malloc( sizeof(*w) );
*wc = *w;
wc->h = h;
return wc;
}
}
return NULL;
} | C | CL | 9ce814f06b84a1ee31dd7010c84e9ee57ad972f855f0aa5632663f17c6d75a8c |
#include "stinger.h"
#include "stinger-shared.h"
#include "stinger-physmap-new.h"
#include "csv.h"
#include "xmalloc.h"
#include "timer.h"
/* BC */
#include "main.h"
#include "bcTreeDS.h"
#include "bcAlgorithms.h"
#include "dsUtils.h"
#include "dsAccum.h"
#include "timing_util.h"
/* GTRI-2 */
#include "clustering.h"
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
* EDGE AND VERTEX TYPES
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#define ETYPES \
TYPE(ETYPE_MENTION), \
TYPE(MAX_ETYPE)
#define TYPE(X) X
typedef enum {
ETYPES
} etype_t;
#undef TYPE
#define TYPE(X) #X
const char * etype_strings [] = {
ETYPES
};
#undef TYPE
#define VTYPES \
TYPE(VTYPE_NONE), \
TYPE(VTYPE_USER), \
TYPE(MAX_VTYPE)
#define TYPE(X) X
typedef enum {
VTYPES
} vtype_t;
#undef TYPE
#define TYPE(X) #X
const char * vtype_strings [] = {
VTYPES
};
#undef TYPE
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
* Structs
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
typedef struct config {
int64_t initial_size;
int64_t batch_size;
int64_t max_batches;
char * path;
} config_t;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
* Function protos
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
void
parse_config(int argc, char ** argv, config_t * config);
void
histogram(struct stinger * S, uint64_t * labels, char * name, int64_t iteration);
void
histogram_float(struct stinger * S, float * scores, char * name, int64_t iteration);
void
REDUCTION(float_t** finalResultArray,float_t** parallelArray,int32_t threadCount);
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
* MAIN
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#define BC_ROOTS 256
int main(int argc, char *argv[]) {
config_t config;
parse_config(argc, argv, &config);
struct stinger * S, * S_cluster;
struct stinger_shared * S_shared, * S_cluster_shared;
char * name = "/testing";
S = stinger_shared_new(&S_shared, &name);
S_cluster = stinger_shared_private(&S_cluster_shared, name);
char comp_base[1024];
char comm_base[1024];
char betc_base[1024];
sprintf(comp_base, "%s/components", config.path ? config.path : "");
sprintf(comm_base, "%s/communities", config.path ? config.path : "");
sprintf(betc_base, "%s/bc", config.path ? config.path : "");
uint64_t threadCount = 1;
#if defined(_OPENMP)
OMP("omp parallel")
{
OMP("omp master")
{
threadCount = omp_get_num_threads();
}
}
#endif
/* set up data structures for algorithms */
uint64_t * matches;
uint64_t num_components;
uint64_t * components = xmalloc(sizeof(uint64_t) * STINGER_MAX_LVERTICES);
bcTree** parallelForest = createParallelForest(threadCount,STINGER_MAX_LVERTICES);
float** totalBCSS = createParallelBetweennessArray(threadCount,STINGER_MAX_LVERTICES);
float** finalBC = createParallelBetweennessArray(1,STINGER_MAX_LVERTICES);
uint32_t** parallelSingleQueue = (uint32_t**)malloc(sizeof(uint32_t*)*threadCount);
for(int i=0;i<threadCount;i++)
parallelSingleQueue[i] = (uint32_t*)malloc(sizeof(uint32_t)*STINGER_MAX_LVERTICES);
float timePerThread[threadCount];
int rootsPerThread = BC_ROOTS/threadCount;
uint32_t*** ppArray = createParallelParentArrayStinger(S ,STINGER_MAX_LVERTICES,threadCount);
/* parsing structures */
char * buf = NULL;
uint64_t bufSize = 0;
char ** fields = NULL;
uint64_t * lengths = NULL;
uint64_t fieldsSize = 0;
uint64_t count = 0;
int64_t src, dest;
/* begin parsing initial graph */
{
for(uint64_t e = 0; e < config.initial_size && !feof(stdin); e++) {
readCSVLineDynamic(',', stdin, &buf, &bufSize, &fields, &lengths, &fieldsSize, &count);
if(stinger_new_physID_to_vtx_mapping(S, fields[0], lengths[0], &src) == 1) {
stinger_set_vtype(S, src, VTYPE_USER);
}
if(stinger_new_physID_to_vtx_mapping(S, fields[1], lengths[1], &dest) == 1) {
stinger_set_vtype(S, dest, VTYPE_USER);
}
if(src != -1 && dest != -1) {
stinger_insert_edge_pair(S, ETYPE_MENTION, src, dest, 1, e);
}
}
}
/* do first round of algorithms */
printf("Clustering...\n");
tic();
static_multi_contract_clustering(&matches, STINGER_MAX_LVERTICES, S_cluster, S);
printf("\tDone... %lf seconds \n", toc());
histogram(S, matches, comm_base, 0);
free(matches);
printf("Components...\n");
tic();
num_components = connected_components(S, components, STINGER_MAX_LVERTICES);
printf("\tDone... %lf seconds \n", toc());
histogram(S, components, comp_base, 0);
{
printf("\tPicking roots\n");
tic();
int64_t* selectedRoots=(int64_t*)malloc(sizeof(int64_t)*BC_ROOTS);
int64_t r1 = 0;
for(int64_t v = 0; v < STINGER_MAX_LVERTICES && r1 < BC_ROOTS; v++) {
if(stinger_outdegree(S,v)) {
selectedRoots[r1++] = v;
}
}
printf("\tDone... %lf seconds \n", toc());
printf("Starting BC...\n");
tic();
for(int v=0;v<STINGER_MAX_LVERTICES;v++)
finalBC[0][v]=0;
GO(bfsBrandes,STINGER,SINGLE,PA)(parallelForest,S,totalBCSS,(void**)parallelSingleQueue,
ppArray,timePerThread,selectedRoots,rootsPerThread);
REDUCTION(finalBC,totalBCSS,threadCount);
printf("\tDone... %lf seconds \n", toc());
histogram_float(S, finalBC[0], betc_base, 0);
}
/* start batching */
for(uint64_t b = 0; b < config.max_batches && !feof(stdin); b++) {
printf("*** STARTING BATCH %ld ***\n", b+1);
{
for(uint64_t e = 0; e < config.batch_size && !feof(stdin); e++) {
readCSVLineDynamic(',', stdin, &buf, &bufSize, &fields, &lengths, &fieldsSize, &count);
if(stinger_new_physID_to_vtx_mapping(S, fields[0], lengths[0], &src) == 1) {
stinger_set_vtype(S, src, VTYPE_USER);
}
if(stinger_new_physID_to_vtx_mapping(S, fields[1], lengths[1], &dest) == 1) {
stinger_set_vtype(S, dest, VTYPE_USER);
}
if(src != -1 && dest != -1) {
stinger_insert_edge_pair(S, ETYPE_MENTION, src, dest, 1, e);
}
}
}
/* do algorithms */
S_cluster = stinger_new();
printf("Clustering...\n");
tic();
STINGER_PARALLEL_FORALL_EDGES_BEGIN(S, ETYPE_MENTION) {
stinger_insert_edge(S_cluster, STINGER_EDGE_TYPE, STINGER_EDGE_SOURCE, STINGER_EDGE_DEST, STINGER_EDGE_WEIGHT, STINGER_EDGE_TIME_RECENT);
} STINGER_PARALLEL_FORALL_EDGES_END();
static_multi_contract_clustering(&matches, STINGER_MAX_LVERTICES, S_cluster, S);
printf("\tDone... %lf seconds \n", toc());
histogram(S, matches, comm_base, b+1);
free(matches);
stinger_free_all(S_cluster);
printf("Components...\n");
tic();
num_components = connected_components(S, components, STINGER_MAX_LVERTICES);
printf("\tDone... %lf seconds \n", toc());
histogram(S, components, comp_base, b+1);
{
printf("BC: Picking roots\n");
tic();
int64_t* selectedRoots=(int64_t*)malloc(sizeof(int64_t)*BC_ROOTS);
int64_t r1 = 0;
for(int64_t v = 0; v < STINGER_MAX_LVERTICES && r1 < BC_ROOTS; v++) {
if(stinger_outdegree(S,v)) {
selectedRoots[r1++] = v;
}
}
printf("\tDone... %lf seconds \n", toc());
printf("BC: Starting ...\n");
tic();
for(int v=0;v<STINGER_MAX_LVERTICES;v++)
finalBC[0][v]=0;
GO(bfsBrandes,STINGER,SINGLE,PA)(parallelForest,S,totalBCSS,(void**)parallelSingleQueue,
ppArray,timePerThread,selectedRoots,rootsPerThread);
REDUCTION(finalBC,totalBCSS,threadCount);
printf("\tDone... %lf seconds \n", toc());
histogram_float(S, finalBC[0], betc_base, b+1);
}
}
}
void
parse_config(int argc, char ** argv, config_t * config) {
config->path = NULL;
config->initial_size = 1000;
config->batch_size = 1000;
config->max_batches = 1000;
for(uint64_t i = 1; i < argc; i+=2) {
char * str = argv[i];
int len = strlen(argv[i]);
/* GENERATED WITH stringset.c */
if(!strncmp(str, "-", 1)) {
str += 1; len -= 1;
if(len) switch(*str) {
case '-':
{
str++; len--;
if(len) switch(*str) {
case 'b':
{
str++; len--;
if(!strncmp(str, "atchsize", len)) {
str += 8; len -= 8;
if(len == 0) {
/* --batchsize */
config->batch_size = atol(argv[i+1]);
}
}
} break;
case 'i':
{
str++; len--;
if(!strncmp(str, "nitialsize", len)) {
str += 10; len -= 10;
if(len == 0) {
/* --initialsize */
config->initial_size = atol(argv[i+1]);
}
}
} break;
case 'n':
{
str++; len--;
if(!strncmp(str, "umbatches", len)) {
str += 9; len -= 9;
if(len == 0) {
/* --numbatches */
config->max_batches = atol(argv[i+1]);
}
}
} break;
case 'p':
{
str++; len--;
if(!strncmp(str, "ath", len)) {
str += 3; len -= 3;
if(len == 0) {
/* --path */
config->path = argv[i+1];
}
}
} break;
}
} break;
case 'b':
{
str++; len--;
if(len == 0) {
/* -b */
config->batch_size = atol(argv[i+1]);
}
} break;
case 'i':
{
str++; len--;
if(len == 0) {
/* -i */
config->initial_size = atol(argv[i+1]);
}
} break;
case 'n':
{
str++; len--;
if(len == 0) {
/* -n */
config->max_batches = atol(argv[i+1]);
}
} break;
case 'p':
{
str++; len--;
if(len == 0) {
/* -p */
config->path = argv[i+1];
}
} break;
}
}
if(!strncmp(str, "-", 1)) {
str += 1; len -= 1;
if(len) switch(*str) {
case '-':
{
str++; len--;
if(len) switch(*str) {
case 'b':
{
str++; len--;
if(!strncmp(str, "atchsize", len)) {
str += 8; len -= 8;
if(len == 0) {
/* --batchsize */
config->batch_size = atol(argv[i+1]);
}
}
} break;
case 'i':
{
str++; len--;
if(!strncmp(str, "nitialsize", len)) {
str += 10; len -= 10;
if(len == 0) {
/* --initialsize */
config->initial_size = atol(argv[i+1]);
}
}
} break;
case 'n':
{
str++; len--;
if(!strncmp(str, "umbatches", len)) {
str += 9; len -= 9;
if(len == 0) {
/* --numbatches */
config->max_batches = atol(argv[i+1]);
}
}
} break;
}
} break;
case 'b':
{
str++; len--;
if(len == 0) {
/* -b */
config->batch_size = atol(argv[i+1]);
}
} break;
case 'i':
{
str++; len--;
if(len == 0) {
/* -i */
config->initial_size = atol(argv[i+1]);
}
} break;
case 'n':
{
str++; len--;
if(len == 0) {
/* -n */
config->max_batches = atol(argv[i+1]);
}
} break;
}
}
}
}
void
histogram(struct stinger * S, uint64_t * labels, char * name, int64_t iteration) {
uint64_t * histogram = xcalloc(sizeof(uint64_t), STINGER_MAX_LVERTICES);
uint64_t * sizes = xcalloc(sizeof(uint64_t), STINGER_MAX_LVERTICES);
for(uint64_t v = 0; v < STINGER_MAX_LVERTICES; v++) {
if(stinger_vtype(S, v) != VTYPE_NONE) {
sizes[labels[v]]++;
}
}
for(uint64_t v = 1; v < STINGER_MAX_LVERTICES; v++) {
histogram[sizes[v]]++;
}
free(sizes);
char filename[1024];
sprintf(filename, "%s.%ld.csv", name, iteration);
FILE * fp = fopen(filename, "w");
for(uint64_t v = 1; v < STINGER_MAX_LVERTICES; v++) {
if(histogram[v]) {
fprintf(fp, "%ld, %ld\n", v, histogram[v]);
}
}
fclose(fp);
free(histogram);
}
void
histogram_float(struct stinger * S, float * scores, char * name, int64_t iteration) {
int64_t max = 0;
for(uint64_t v = 0; v < STINGER_MAX_LVERTICES; v++) {
if(stinger_vtype(S, v) != VTYPE_NONE) {
if((int64_t)(scores[v]) > max) {
max = (int64_t) (scores[v]);
}
}
}
uint64_t * histogram = xcalloc(sizeof(uint64_t), (max+2));
if(histogram) {
for(uint64_t v = 0; v < STINGER_MAX_LVERTICES; v++) {
histogram[(int64_t)(scores[v])]++;
}
char filename[1024];
sprintf(filename, "%s.%ld.csv", name, iteration);
FILE * fp = fopen(filename, "w");
for(uint64_t v = 0; v < max+2; v++) {
if(histogram[v]) {
fprintf(fp, "%ld, %ld\n", v, histogram[v]);
}
}
fclose(fp);
free(histogram);
} else {
printf(" FAIL \n"); fflush(stdout);
}
}
void REDUCTION(float_t** finalResultArray,float_t** parallelArray,int32_t threadCount) {
#pragma parallel for
for(int v=0;v<STINGER_MAX_LVERTICES;v++) {
for(int t=0;t<threadCount;t++)
finalResultArray[0][v]+=parallelArray[t][v];
}
}
| C | CL | 891fbebd123e7d46f8ddd0f83ab93366cdb82b6a7316788ca69fb579989d5063 |
typedef struct point { int x, y; } point;
/* Global variables */
char char_global = 'A';
int int_global = 1;
float flt_global = 1.0F;
double dbl_global = 1.0;
point struct_global = { 1, 3 };
int tab_global[10] = { 0, 1, 1, 2, 3, 5 };
int int_funct(int param) { return param+3; }
/* char_funct:
* - the char argument will be received as an int,
* so the frontend then converts it (in place) to a char.
* Then the addition converts the char to an int...
* The result of the addition is then converted to the function type,
* however it's char so it is then finally converted to int again!!!
* => better to never use char params, nor char return type.
*/
char char_funct(char param) { return 3+param; }
/*
* flt_funct:
* - the frontend adds float values without converting them to double!
*/
float flt_funct(float param) { return param+3.0F; }
double dbl_funct(double param) { return param+3.0; }
/*
* struct_funct:
* - a void return is generated by the frontend,
* and the structure for the result is given by the caller.
* Before the void return, the frontend gives an ASGNB node that
* aims to copy the structure given by the return instruction to the
* structure given by the caller.
*/
point struct_funct(point param) { point p2; p2.x = p2.y = param.y+3; return p2; }
/*
* char_ptr_funct, int_ptr_funt and struct_ptr_funct:
* - the frontend wants to convert the returned pointer to unsigned
*/
char* char_ptr_funct(char* param) { return param+3; }
int* int_ptr_funct(int param[]) { return param+3; }
point* struct_ptr_funct(point *param) { param->y += 3; return param; }
/* Global pointer variables */
char* char_ptr_global = &char_global;
int* int_ptr_global = &tab_global[2]+2;
float* flt_ptr_global = &flt_global;
point* struct_ptr_global = &struct_global;
int (*fct_ptr_global)(int) = int_funct;
void check(int result, int expected, char *msg) {
if (result == expected) // putchar('.');
printf("%s test ok\n", msg);
else printf("%s test fails\n-> result is %d, expecting %d\n", msg, result, expected);
}
void simple_tests() {
int int_local;
char char_local;
float flt_local;
double dbl_local=1.0;
check(int_global, 1, "int funct0");
int_local = int_funct(int_global);
check(int_local, 4, "int funct1");
check(int_global, 1, "int funct1");
int_global = int_funct(int_global);
check(int_global, 4, "int funct2");
char_local = char_funct(char_global);
check(char_local, 'D' , "char funct");
flt_local = flt_funct(flt_global);
check((int)flt_local, 4, "flt funct");
dbl_global = dbl_funct(dbl_local);
check((int)int_global, 4, "dbl funct");
}
void simple_ptr_tests() {
/*
* NB: ASGNB is used to initialize tab_local from a global constant...
*/
int tab_local[] = { 1, 1, 2, 3, 5, 8 };
int * int_ptr_local = &tab_local[1]+1;
char char_local[] = "hello";
char * char_ptr_local = &char_local[2]+1;
int_ptr_local = int_ptr_funct(tab_global);
check((int)int_ptr_local, (int)(tab_global+3), "int ptr funct1");
int_ptr_global = int_ptr_funct(tab_local);
check((int)int_ptr_global, (int)(tab_local+3), "int ptr funct2");
char_ptr_global = char_ptr_funct(char_ptr_local+2);
check((int)char_ptr_global, (int)(char_ptr_local+5), "char ptr funct1");
char_ptr_local = char_ptr_funct("world");
check(char_ptr_local[0], 'l', "char ptr funct2");
}
void fct_ptr_tests() {
int int_local;
int (*fct_ptr_local)(int) = int_funct;
int_local = (*fct_ptr_global)(int_global);
check(int_local, int_global+3, "fct ptr1");
int_global = (*fct_ptr_local)(int_local);
check(int_global, int_local+3, "fct ptr2");
}
void struct_tests() {
point struct_local;
point* struct_ptr_local = &struct_local;
struct_ptr_global->y = 1;
check(struct_global.y, 1, "struct funct0");
struct_local = struct_funct(struct_global);
check(struct_local.y, 4, "struct funct1");
struct_global = struct_funct(struct_local);
check(struct_global.y, 7, "struct funct2");
struct_ptr_local = struct_ptr_funct(struct_ptr_global);
check((int)struct_ptr_local, (int)struct_ptr_global, "struct ptr funct");
check(struct_ptr_local->y, 10, "struct ptr funct");
}
void addr_tests()
{
int a = 1, b;
b = a + (int)&a;
b = (int)&a + a;
b = a - (int)&a;
b = (int)&a - a;
b = a * (int)&a;
b = (int)&a * a;
b = (int)&a / a;
b = a / (int)&a;
b = a & (int)&a;
b = (int)&a & a;
}
int main(void)
{
simple_tests();
simple_ptr_tests();
fct_ptr_tests();
struct_tests();
printf("\nAll tests done\n");
}
| C | CL | 31fe5161ae553b1390ba0479f16d792ea381c29b70b12062a31f947ce1981961 |
#include <types.h>
#include <yaos/init.h>
#include <yaos/time.h>
#include <yaos/printk.h>
#include <yaos/smp.h>
#include <yaos/cpupm.h>
#include <yaos/tasklet.h>
#include <yaos/sched.h>
#include <asm/current.h>
extern __thread ulong msec_count;
static void test_nsec (u64 nownsec,void *param)
{
pthread p = current;
pthread powner = (pthread)param;
set_timeout_nsec(10000000000,test_nsec,param);
printk("test_nsec timeout uptime:%ld,cpu:%d,current_thread:%s,owner:%s\n",
hrt_uptime()/1000000000,smp_processor_id(),p->name,powner->name);
}
static void test_sleep()
{
while(1) {
pthread p = current;
sleep(10);
printk("test_sleep uptime:%ld,cpu:%d,current_thread:%s\n",
hrt_uptime()/1000000000,smp_processor_id(),p->name);
}
}
int test_should_run(unsigned int cpu)
{
return 1;
}
static int run_test_thread(unsigned long cpu)
{
test_sleep();
return 0;
}
DEFINE_PER_CPU(struct task_struct, test_task);
static struct smp_percpu_thread test_threads = {
.task = &test_task,
.thread_should_run = test_should_run,
.thread_fn = run_test_thread,
.thread_comm = "test",
.lvl = THREAD_LVL_USER,
.stack_size = 0x1000
};
static int test_init(bool isbp)
{
set_timeout_nsec(10000000000,test_nsec,current);
struct task_struct *tsk = this_cpu_ptr(&test_task);
wake_up_thread(&tsk->mainthread);
return 0;
}
static int test_init_early(bool isbp)
{
if(isbp){
struct task_struct *tsk = this_cpu_ptr(&test_task);
memset(tsk, 0, sizeof(*tsk));
smpboot_register_percpu_thread(&test_threads);
}
return 0;
}
early_initcall(test_init_early);
late_initcall(test_init);
| C | CL | ba3f4342c13fe3d7a4c4e6e928490b23984d29605d13a39360c0eddb91468156 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ test_post ;
typedef int /*<<< orphan*/ post_data ;
typedef int /*<<< orphan*/ disable ;
typedef int /*<<< orphan*/ context ;
typedef int /*<<< orphan*/ buffer ;
typedef char WCHAR ;
typedef int /*<<< orphan*/ * HINTERNET ;
typedef int DWORD_PTR ;
typedef scalar_t__ DWORD ;
typedef char CHAR ;
typedef int BOOL ;
/* Variables and functions */
int ERROR_INVALID_PARAMETER ;
int ERROR_NO_TOKEN ;
int ERROR_SUCCESS ;
scalar_t__ ERROR_WINHTTP_CANNOT_CONNECT ;
int ERROR_WINHTTP_NAME_NOT_RESOLVED ;
scalar_t__ ERROR_WINHTTP_TIMEOUT ;
int GetLastError () ;
int /*<<< orphan*/ INTERNET_DEFAULT_HTTP_PORT ;
int /*<<< orphan*/ SetLastError (int) ;
int TRUE ;
int /*<<< orphan*/ WINHTTP_ACCESS_TYPE_DEFAULT_PROXY ;
int /*<<< orphan*/ WINHTTP_DEFAULT_ACCEPT_TYPES ;
scalar_t__ WINHTTP_DISABLE_KEEP_ALIVE ;
int /*<<< orphan*/ WINHTTP_FLAG_BYPASS_PROXY_CACHE ;
int /*<<< orphan*/ WINHTTP_NO_PROXY_BYPASS ;
int /*<<< orphan*/ WINHTTP_NO_PROXY_NAME ;
int /*<<< orphan*/ WINHTTP_NO_REFERER ;
int /*<<< orphan*/ WINHTTP_OPTION_CONTEXT_VALUE ;
int /*<<< orphan*/ WINHTTP_OPTION_DISABLE_FEATURE ;
int WinHttpCloseHandle (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ * WinHttpConnect (int /*<<< orphan*/ *,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ * WinHttpOpen (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ * WinHttpOpenRequest (int /*<<< orphan*/ *,char const*,char const*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int WinHttpQueryOption (int /*<<< orphan*/ *,int /*<<< orphan*/ ,int*,scalar_t__*) ;
int WinHttpReadData (int /*<<< orphan*/ *,char*,int,scalar_t__*) ;
int WinHttpReceiveResponse (int /*<<< orphan*/ *,int /*<<< orphan*/ *) ;
int WinHttpSendRequest (int /*<<< orphan*/ *,char const*,scalar_t__,char*,scalar_t__,scalar_t__,int) ;
int WinHttpSetOption (int /*<<< orphan*/ *,int /*<<< orphan*/ ,...) ;
int WinHttpWriteData (int /*<<< orphan*/ *,char*,int,scalar_t__*) ;
scalar_t__ broken (int) ;
int /*<<< orphan*/ memcmp (char*,char const*,int) ;
int /*<<< orphan*/ memset (char*,int,int) ;
int /*<<< orphan*/ ok (int,char*,...) ;
int /*<<< orphan*/ skip (char*) ;
int /*<<< orphan*/ test_useragent ;
int /*<<< orphan*/ test_winehq ;
__attribute__((used)) static void test_SendRequest (void)
{
static const WCHAR content_type[] =
{'C','o','n','t','e','n','t','-','T','y','p','e',':',' ','a','p','p','l','i','c','a','t','i','o','n',
'/','x','-','w','w','w','-','f','o','r','m','-','u','r','l','e','n','c','o','d','e','d',0};
static const WCHAR test_file[] = {'t','e','s','t','s','/','p','o','s','t','.','p','h','p',0};
static const WCHAR test_verb[] = {'P','O','S','T',0};
static CHAR post_data[] = "mode=Test";
static const char test_post[] = "mode => Test\0\n";
HINTERNET session, request, connection;
DWORD header_len, optional_len, total_len, bytes_rw, size, err, disable;
DWORD_PTR context;
BOOL ret;
CHAR buffer[256];
int i;
header_len = -1L;
total_len = optional_len = sizeof(post_data);
memset(buffer, 0xff, sizeof(buffer));
session = WinHttpOpen(test_useragent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
ok(session != NULL, "WinHttpOpen failed to open session.\n");
connection = WinHttpConnect (session, test_winehq, INTERNET_DEFAULT_HTTP_PORT, 0);
ok(connection != NULL, "WinHttpConnect failed to open a connection, error: %u.\n", GetLastError());
request = WinHttpOpenRequest(connection, test_verb, test_file, NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_BYPASS_PROXY_CACHE);
if (request == NULL && GetLastError() == ERROR_WINHTTP_NAME_NOT_RESOLVED)
{
skip("Network unreachable, skipping.\n");
goto done;
}
ok(request != NULL, "WinHttpOpenrequest failed to open a request, error: %u.\n", GetLastError());
if (!request) goto done;
context = 0xdeadbeef;
ret = WinHttpSetOption(request, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(context));
ok(ret, "WinHttpSetOption failed: %u\n", GetLastError());
/* writing more data than promised by the content-length header causes an error when the connection
is resued, so disable keep-alive */
disable = WINHTTP_DISABLE_KEEP_ALIVE;
ret = WinHttpSetOption(request, WINHTTP_OPTION_DISABLE_FEATURE, &disable, sizeof(disable));
ok(ret, "WinHttpSetOption failed: %u\n", GetLastError());
context++;
ret = WinHttpSendRequest(request, content_type, header_len, post_data, optional_len, total_len, context);
err = GetLastError();
if (!ret && (err == ERROR_WINHTTP_CANNOT_CONNECT || err == ERROR_WINHTTP_TIMEOUT))
{
skip("connection failed, skipping\n");
goto done;
}
ok(ret == TRUE, "WinHttpSendRequest failed: %u\n", GetLastError());
context = 0;
size = sizeof(context);
ret = WinHttpQueryOption(request, WINHTTP_OPTION_CONTEXT_VALUE, &context, &size);
ok(ret, "WinHttpQueryOption failed: %u\n", GetLastError());
ok(context == 0xdeadbef0, "expected 0xdeadbef0, got %lx\n", context);
for (i = 3; post_data[i]; i++)
{
bytes_rw = -1;
SetLastError(0xdeadbeef);
ret = WinHttpWriteData(request, &post_data[i], 1, &bytes_rw);
if (ret)
{
ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS got %u.\n", GetLastError());
ok(bytes_rw == 1, "WinHttpWriteData failed, wrote %u bytes instead of 1 byte.\n", bytes_rw);
}
else /* Since we already passed all optional data in WinHttpSendRequest Win7 fails our WinHttpWriteData call */
{
ok(GetLastError() == ERROR_INVALID_PARAMETER, "Expected ERROR_INVALID_PARAMETER got %u.\n", GetLastError());
ok(bytes_rw == -1, "Expected bytes_rw to remain unchanged.\n");
}
}
SetLastError(0xdeadbeef);
ret = WinHttpReceiveResponse(request, NULL);
ok(GetLastError() == ERROR_SUCCESS || broken(GetLastError() == ERROR_NO_TOKEN) /* < win7 */,
"Expected ERROR_SUCCESS got %u.\n", GetLastError());
ok(ret == TRUE, "WinHttpReceiveResponse failed: %u.\n", GetLastError());
bytes_rw = -1;
ret = WinHttpReadData(request, buffer, sizeof(buffer) - 1, &bytes_rw);
ok(ret == TRUE, "WinHttpReadData failed: %u.\n", GetLastError());
ok(bytes_rw == sizeof(test_post) - 1, "Read %u bytes\n", bytes_rw);
ok(!memcmp(buffer, test_post, sizeof(test_post) - 1), "Data read did not match.\n");
done:
ret = WinHttpCloseHandle(request);
ok(ret == TRUE, "WinHttpCloseHandle failed on closing request, got %d.\n", ret);
ret = WinHttpCloseHandle(connection);
ok(ret == TRUE, "WinHttpCloseHandle failed on closing connection, got %d.\n", ret);
ret = WinHttpCloseHandle(session);
ok(ret == TRUE, "WinHttpCloseHandle failed on closing session, got %d.\n", ret);
} | C | CL | 4d389b7e80019ffd79f7a3935da4af311b143099c917851b29dbfc54673b664f |
/*
vblo.c = rutinas de bloqueo para codigo complejo
de acceso a disco en ambiente multi-usuario.
Sintaxis dentro de VPG:
Ba; * activar sistema de bloque en multi-usuario *
Bc; * cerrar o desactivar sistema de bloqueo *
Bb; * bloquear o preparar para codigo complejo *
Bu; * desbloquear o liberar para codigo complejo *
por Franz J Fortuny - Mayo 28 de 1989
Adapted for Watcom C 386 QNX 4.2 Jan 14 1995
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#define CENTFILE "/vpgblock"
struct flock fbk;
void vblo(act) char act;
{
time_t sec;
static int fb = -1;
fbk.l_whence = SEEK_SET; fbk.l_start = 0l; fbk.l_len = 0l;
switch(act) {
case 'a': /* set blocking active */
if((fb=open(CENTFILE,O_RDWR | O_CREAT,S_IRWXU | S_IRWXG | S_IRWXO)) == -1) {
perror("Problems opening or creating the file"); exit(0);
}
time(&sec);
if(write(fb,&sec,sizeof(time_t)) != sizeof(time_t))
{ perror("Can't write blocking record of file /vpgblock"); exit(0); }
if(lseek(fb,0L,0) == -1L)
{ perror("Can not seek to pos 0 of vpgblock file."); exit(0); }
break;
case 'c': /* close blocking file */
if(fb != -1) {close(fb); fb = -1;}
break;
case 'b': /* block file */
fbk.l_type = F_WRLCK;
if(fcntl(fb,F_SETLKW,&fbk) == -1)
{perror("Complex Disk Access Code Lock is failing"); exit(0); }
break;
case 'u':/* unblock file */
fbk.l_type = F_UNLCK;
if(fcntl(fb,F_SETLK,&fbk) == -1)
{perror("Complex Disk Access Code UnLock is failing"); exit(0); }
break;
}
}
| C | CL | 27e032acf87cc107d92ff7379fe59e7403425942395072c3538979f19eb502af |
/**
* Copyright (C) 2013-2015
*
* @author [email protected]
* @date 2013-11-19
*
* @file XcpwsClient.c
*
* @remark
*
*/
#include <tiny_log.h>
#include <channel/SocketChannel.h>
#include <channel/ChannelIdleStateHandler.h>
#include <channel/stream/StreamClientChannel.h>
#include <codec-http/HttpMessageCodec.h>
#include <client/handler/XcpwsClientHandlerContext.h>
#include "handler/XcpwsClientHandler.h"
#include "hook/XcpwsClientLoopHook.h"
#include "XcpwsClient.h"
#define TAG "XcpwsClient"
TINY_LOR
static void XcpwsClientInitializer(Channel *channel, void *ctx)
{
LOG_D(TAG, "XcpwsClientInitializer: %s", channel->id);
SocketChannel_AddLast(channel, ChannelIdleStateHandler(20, 50, 0));
SocketChannel_AddLast(channel, HttpMessageCodec());
SocketChannel_AddLast(channel, XcpwsClientHandler((Product *)ctx));
}
TINY_LOR
Channel * XcpwsClient_New(Product *product, const char *ip, uint16_t port)
{
Channel *thiz = NULL;
do
{
thiz = StreamClientChannel_New(XcpwsClientLoopHook, product);
if (thiz == NULL)
{
break;
}
if (RET_FAILED(StreamClientChannel_Initialize(thiz, XcpwsClientInitializer, product)))
{
thiz->_onRemove(thiz);
break;
}
if (RET_FAILED(StreamClientChannel_Connect(thiz, ip, port, 10)))
{
thiz->_onRemove(thiz);
break;
}
} while (false);
return thiz;
}
TINY_LOR
TinyRet XcpwsClient_SendQuery(Channel *thiz, XcpMessage *query, XcpMessageHandler handler, void *ctx)
{
TinyRet ret = TINY_RET_OK;
do
{
ChannelHandler *h = SocketChannel_GetHandler(thiz, XcpwsClientHandler_Name);
if (h == NULL)
{
LOG_E(TAG, "SocketChannel_GetHandler FAILED: %s", XcpwsClientHandler_Name);
ret = TINY_RET_E_INTERNAL;
break;
}
ret = XcpwsClientHandlerContext_SendQuery(h->context, query, handler, ctx);
if (RET_FAILED(ret))
{
LOG_E(TAG, "XcpwsClientHandlerContext_SendQuery FAILED");
break;
}
} while (false);
return ret;
} | C | CL | 9ca8cd6ee9960851a2278c94b3fa263df80f9584f84f9977b282f317b91f87dc |
#include <proc.h>
#include <error.h>
#include <assert.h>
#include "vc4_drv.h"
#include "vc4_drm.h"
#include "vc4_regs.h"
static void submit_cl(struct device *dev, uint32_t thread, uint32_t start,
uint32_t end)
{
/* Set the current and end address of the control list.
* Writing the end register is what starts the job.
*/
// stop the thread
V3D_WRITE(V3D_CTNCS(thread), 0x20);
// Wait for thread to stop
while (V3D_READ(V3D_CTNCS(thread)) & 0x20);
V3D_WRITE(V3D_CTNCA(thread), start);
V3D_WRITE(V3D_CTNEA(thread), end);
}
static void vc4_flush_caches(struct device *dev)
{
/* Flush the GPU L2 caches. These caches sit on top of system
* L3 (the 128kb or so shared with the CPU), and are
* non-allocating in the L3.
*/
V3D_WRITE(V3D_L2CACTL, V3D_L2CACTL_L2CCLR);
V3D_WRITE(V3D_SLCACTL, VC4_SET_FIELD(0xf, V3D_SLCACTL_T1CC) |
VC4_SET_FIELD(0xf, V3D_SLCACTL_T0CC) |
VC4_SET_FIELD(0xf, V3D_SLCACTL_UCC) |
VC4_SET_FIELD(0xf, V3D_SLCACTL_ICC));
}
static void vc4_submit_next_bin_job(struct device *dev,
struct vc4_exec_info *exec)
{
if (!exec)
return;
vc4_flush_caches(dev);
/* Either put the job in the binner if it uses the binner, or
* immediately move it to the to-be-rendered queue.
*/
if (exec->ct0ca == exec->ct0ea) {
return;
}
// reset binning frame count
V3D_WRITE(V3D_BFC, 1);
submit_cl(dev, 0, exec->ct0ca, exec->ct0ea);
// wait for binning to finish
while (V3D_READ(V3D_BFC) == 0);
}
static void vc4_submit_next_render_job(struct device *dev,
struct vc4_exec_info *exec)
{
if (!exec)
return;
// reset rendering frame count
V3D_WRITE(V3D_RFC, 1);
submit_cl(dev, 1, exec->ct1ca, exec->ct1ea);
// wait for render to finish
while (V3D_READ(V3D_RFC) == 0);
}
/* Queues a struct vc4_exec_info for execution. If no job is
* currently executing, then submits it.
*
* Unlike most GPUs, our hardware only handles one command list at a
* time. To queue multiple jobs at once, we'd need to edit the
* previous command list to have a jump to the new one at the end, and
* then bump the end address. That's a change for a later date,
* though.
*/
static void vc4_queue_submit(struct device *dev, struct vc4_exec_info *exec)
{
// TODO
vc4_submit_next_bin_job(dev, exec);
vc4_submit_next_render_job(dev, exec);
}
/**
* vc4_cl_lookup_bos() - Sets up exec->bo[] with the GEM objects
* referenced by the job.
* @dev: device
* @exec: V3D job being set up
*
* The command validator needs to reference BOs by their index within
* the submitted job's BO list. This does the validation of the job's
* BO list and reference counting for the lifetime of the job.
*
* Note that this function doesn't need to unreference the BOs on
* failure, because that will happen at vc4_complete_exec() time.
*/
static int vc4_cl_lookup_bos(struct device *dev, struct vc4_exec_info *exec)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
struct drm_vc4_submit_cl *args = exec->args;
struct mm_struct *mm = current->mm;
uint32_t *handles;
int ret = 0;
int i;
assert(mm);
exec->bo_count = args->bo_handle_count;
if (!exec->bo_count) {
return 0;
}
exec->fb_bo = vc4->fb_bo;
exec->bo = (struct vc4_bo **)kmalloc(exec->bo_count *
sizeof(struct vc4_bo *));
if (!exec->bo) {
kprintf("vc4: Failed to allocate validated BO pointers\n");
return -E_NOMEM;
}
handles = (uint32_t *)kmalloc(exec->bo_count, sizeof(uint32_t));
if (!handles) {
ret = -E_NOMEM;
kprintf("vc4: Failed to allocate incoming GEM handles\n");
goto fail;
}
if (!copy_from_user(mm, handles, (uintptr_t)args->bo_handles,
exec->bo_count * sizeof(uint32_t), 0)) {
ret = -E_FAULT;
kprintf("vc4: Failed to copy in GEM handles\n");
goto fail;
}
for (i = 0; i < exec->bo_count; i++) {
struct vc4_bo *bo = vc4_lookup_bo(dev, handles[i]);
if (!bo) {
kprintf("vc4: Failed to look up GEM BO %d: %d\n", i,
handles[i]);
ret = -E_INVAL;
goto fail;
}
exec->bo[i] = bo;
}
fail:
kfree(handles);
return ret;
}
static int vc4_get_bcl(struct device *dev, struct vc4_exec_info *exec)
{
struct drm_vc4_submit_cl *args = exec->args;
void *temp = NULL;
void *bin;
int ret = 0;
struct mm_struct *mm = current->mm;
assert(mm);
uint32_t bin_offset = 0;
uint32_t shader_rec_offset =
ROUNDUP(bin_offset + args->bin_cl_size, 16);
uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size;
uint32_t exec_size = uniforms_offset + args->uniforms_size;
uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) *
args->shader_rec_count);
struct vc4_bo *bo;
if (shader_rec_offset < args->bin_cl_size ||
uniforms_offset < shader_rec_offset ||
exec_size < uniforms_offset ||
args->shader_rec_count >=
((~0U) / sizeof(struct vc4_shader_state)) ||
temp_size < exec_size) {
kprintf("vc4: overflow in exec arguments\n");
ret = -E_INVAL;
goto fail;
}
temp = (void *)kmalloc(temp_size);
if (!temp) {
kprintf("vc4: Failed to allocate storage for copying "
"in bin/render CLs.\n");
ret = -E_NOMEM;
goto fail;
}
bin = temp + bin_offset;
exec->shader_rec_u = temp + shader_rec_offset;
exec->shader_state = temp + exec_size;
exec->shader_state_size = args->shader_rec_count;
if (args->bin_cl_size &&
!copy_from_user(mm, bin, (uintptr_t)args->bin_cl, args->bin_cl_size,
0)) {
ret = -E_FAULT;
goto fail;
}
if (args->shader_rec_size &&
!copy_from_user(mm, exec->shader_rec_u, (uintptr_t)args->shader_rec,
args->shader_rec_size, 0)) {
ret = -E_FAULT;
goto fail;
}
bo = vc4_bo_create(dev, exec_size, VC4_BO_TYPE_BCL);
if (bo == NULL) {
kprintf("vc4: Couldn't allocate BO for binning\n");
ret = -E_NOMEM;
goto fail;
}
exec->exec_bo = bo;
list_add_before(&exec->unref_list, &exec->exec_bo->unref_head);
exec->ct0ca = exec->exec_bo->paddr + bin_offset;
exec->bin_u = bin;
exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset;
exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset;
exec->shader_rec_size = args->shader_rec_size;
ret = vc4_validate_bin_cl(dev, exec->exec_bo->vaddr + bin_offset, bin,
exec);
if (ret)
goto fail;
ret = vc4_validate_shader_recs(dev, exec);
if (ret)
goto fail;
fail:
kfree(temp);
return ret;
}
static void vc4_complete_exec(struct device *dev, struct vc4_exec_info *exec)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
if (exec->bo) {
kfree(exec->bo);
}
while (!list_empty(&exec->unref_list)) {
list_entry_t *le = list_next(&exec->unref_list);
struct vc4_bo *bo = le2bo(le, unref_head);
list_del(&bo->unref_head);
vc4_bo_destroy(dev, bo);
}
kfree(exec);
}
/**
* vc4_submit_cl_ioctl() - Submits a job (frame) to the VC4.
* @dev: vc4 device
* @data: ioctl argument
*
* This is the main entrypoint for userspace to submit a 3D frame to
* the GPU. Userspace provides the binner command list (if
* applicable), and the kernel sets up the render command list to draw
* to the framebuffer described in the ioctl, using the command lists
* that the 3D engine's binner will produce.
*/
int vc4_submit_cl_ioctl(struct device *dev, void *data)
{
struct drm_vc4_submit_cl *args = data;
struct vc4_exec_info *exec;
int ret = 0;
exec = (struct vc4_exec_info *)kmalloc(sizeof(struct vc4_exec_info));
if (!exec) {
kprintf("vc4: malloc failure on exec struct\n");
return -E_NOMEM;
}
memset(exec, 0, sizeof(struct vc4_exec_info));
exec->args = args;
list_init(&exec->unref_list);
ret = vc4_cl_lookup_bos(dev, exec);
if (ret)
goto fail;
if (exec->args->bin_cl_size != 0) {
ret = vc4_get_bcl(dev, exec);
if (ret)
goto fail;
} else {
exec->ct0ca = 0;
exec->ct0ea = 0;
}
ret = vc4_get_rcl(dev, exec);
if (ret)
goto fail;
/* Clear this out of the struct we'll be putting in the queue,
* since it's part of our stack.
*/
exec->args = NULL;
vc4_queue_submit(dev, exec);
fail:
vc4_complete_exec(dev, exec);
return ret;
}
| C | CL | cc310b6f4163bfa797cceaa716f424aab66837a5c72f67a23b28691cbeb6324b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.