hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b68507a26029553a31e9ccdbfa5bfc237c4ff856 | 986 | h | C | MainPart/Classess/Mine/Vendor/AwardARView/vendor/Classes/BGRenderer.h | visualVk/Main_Part | 7705f93f2667f141a34bd8d96a8d8585b8f1e207 | [
"MIT"
] | null | null | null | MainPart/Classess/Mine/Vendor/AwardARView/vendor/Classes/BGRenderer.h | visualVk/Main_Part | 7705f93f2667f141a34bd8d96a8d8585b8f1e207 | [
"MIT"
] | null | null | null | MainPart/Classess/Mine/Vendor/AwardARView/vendor/Classes/BGRenderer.h | visualVk/Main_Part | 7705f93f2667f141a34bd8d96a8d8585b8f1e207 | [
"MIT"
] | null | null | null | //================================================================================================================================
//
// Copyright (c) 2015-2019 VisionStar Information Technology (Shanghai) Co., Ltd. All Rights Reserved.
// EasyAR is the registered trademark or trademark of VisionStar Information Technology (Shanghai) Co., Ltd in China
// and other countries for the augmented reality technology developed by VisionStar Information Technology (Shanghai) Co., Ltd.
//
//================================================================================================================================
#import <easyar/matrix.oc.h>
#import <easyar/image.oc.h>
// all methods of this class can only be called on one thread with the same OpenGLES
@interface BGRenderer : NSObject
+ (instancetype)create;
- (void)upload:(easyar_PixelFormat)format width:(int)width height:(int)height bufferData:(void *)bufferData;
- (void)render:(easyar_Matrix44F *)imageProjection;
@end
| 46.952381 | 130 | 0.566937 | [
"render"
] |
b6878301a26cf5769ecfddb4986bec1cd1fcd091 | 223,553 | c | C | wireshark-2.0.13/epan/dissectors/packet-zbee-zcl-general.c | mahrukhfida/mi | 7187765aa225e71983969ef5285771ac77c8309a | [
"Apache-2.0"
] | null | null | null | wireshark-2.0.13/epan/dissectors/packet-zbee-zcl-general.c | mahrukhfida/mi | 7187765aa225e71983969ef5285771ac77c8309a | [
"Apache-2.0"
] | null | null | null | wireshark-2.0.13/epan/dissectors/packet-zbee-zcl-general.c | mahrukhfida/mi | 7187765aa225e71983969ef5285771ac77c8309a | [
"Apache-2.0"
] | null | null | null | /* packet-zbee-zcl-general.c
* Dissector routines for the ZigBee ZCL General clusters like
* Basic, Identify, OnOff ...
* By Fabio Tarabelloni <fabio.tarabelloni@reloc.it>
* Copyright 2013 RELOC s.r.l.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 Gerald Combs
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/* Include Files */
#include "config.h"
#include <epan/packet.h>
#include <epan/to_str.h>
#include "packet-zbee.h"
#include "packet-zbee-aps.h"
#include "packet-zbee-zcl.h"
/* ########################################################################## */
/* #### (0x0000) BASIC CLUSTER ############################################## */
/* ########################################################################## */
/*************************/
/* Defines */
/*************************/
#define ZBEE_ZCL_BASIC_NUM_GENERIC_ETT 3
#define ZBEE_ZCL_BASIC_NUM_ETT ZBEE_ZCL_BASIC_NUM_GENERIC_ETT
/* Attributes */
#define ZBEE_ZCL_ATTR_ID_BASIC_ZCL_VERSION 0x0000 /* ZCL Version */
#define ZBEE_ZCL_ATTR_ID_BASIC_APPL_VERSION 0x0001 /* Application Version */
#define ZBEE_ZCL_ATTR_ID_BASIC_STACK_VERSION 0x0002 /* Stack Version */
#define ZBEE_ZCL_ATTR_ID_BASIC_HW_VERSION 0x0003 /* HW Version */
#define ZBEE_ZCL_ATTR_ID_BASIC_MANUFACTURER_NAME 0x0004 /* Manufacturer Name */
#define ZBEE_ZCL_ATTR_ID_BASIC_MODEL_ID 0x0005 /* Model Identifier */
#define ZBEE_ZCL_ATTR_ID_BASIC_DATE_CODE 0x0006 /* Date Code */
#define ZBEE_ZCL_ATTR_ID_BASIC_POWER_SOURCE 0x0007 /* Power Source */
#define ZBEE_ZCL_ATTR_ID_BASIC_LOCATION_DESCR 0x0010 /* Location Description */
#define ZBEE_ZCL_ATTR_ID_BASIC_PHY_ENVIRONMENT 0x0011 /* Physical Environment */
#define ZBEE_ZCL_ATTR_ID_BASIC_DEVICE_ENABLED 0x0012 /* Device Enabled */
#define ZBEE_ZCL_ATTR_ID_BASIC_ALARM_MASK 0x0013 /* Alarm Mask */
#define ZBEE_ZCL_ATTR_ID_BASIC_DISABLE_LOCAL_CFG 0x0014 /* Disable Local Config */
/* Server Commands Received */
#define ZBEE_ZCL_CMD_ID_BASIC_RESET_FACTORY_DEFAULTS 0x00 /* Reset to Factory Defaults */
/* Server Commands Generated - None */
/* Power Source Id */
#define ZBEE_ZCL_BASIC_PWR_SRC_UNKNOWN 0x00 /* Unknown */
#define ZBEE_ZCL_BASIC_PWR_SRC_MAINS_1PH 0x01 /* Mains (single phase) */
#define ZBEE_ZCL_BASIC_PWR_SRC_MAINS_3PH 0x02 /* Mains (3 phase) */
#define ZBEE_ZCL_BASIC_PWR_SRC_BATTERY 0x03 /* Battery */
#define ZBEE_ZCL_BASIC_PWR_SRC_DC_SRC 0x04 /* DC source */
#define ZBEE_ZCL_BASIC_PWR_SRC_EMERGENCY_1 0x05 /* Emergency mains constantly powered */
#define ZBEE_ZCL_BASIC_PWR_SRC_EMERGENCY_2 0x06 /* Emergency mains and tranfer switch */
/* Device Enable Values */
#define ZBEE_ZCL_BASIC_DISABLED 0x00 /* Disabled */
#define ZBEE_ZCL_BASIC_ENABLED 0x01 /* Enabled */
/* Alarm Mask bit-mask */
#define ZBEE_ZCL_BASIC_ALARM_GEN_HW_FAULT 0x01 /* General hardware fault */
#define ZBEE_ZCL_BASIC_ALARM_GEN_SW_FAULT 0x02 /* General software fault */
#define ZBEE_ZCL_BASIC_ALARM_RESERVED 0xfc /* Reserved */
/* Disable Local Config bit-mask */
#define ZBEE_ZCL_BASIC_DIS_LOC_CFG_RESET 0x01 /* Reset (to factory defaults) */
#define ZBEE_ZCL_BASIC_DIS_LOC_CFG_DEV_CFG 0x02 /* Device configuration */
#define ZBEE_ZCL_BASIC_DIS_LOC_CFG_RESERVED 0xfc /* Reserved */
/*************************/
/* Function Declarations */
/*************************/
void proto_register_zbee_zcl_basic(void);
void proto_reg_handoff_zbee_zcl_basic(void);
/* Command Dissector Helpers */
static void dissect_zcl_basic_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type);
/* Private functions prototype */
/*************************/
/* Global Variables */
/*************************/
/* Initialize the protocol and registered fields */
static int proto_zbee_zcl_basic = -1;
static int hf_zbee_zcl_basic_attr_id = -1;
static int hf_zbee_zcl_basic_pwr_src = -1;
static int hf_zbee_zcl_basic_dev_en = -1;
static int hf_zbee_zcl_basic_alarm_mask = -1;
static int hf_zbee_zcl_basic_alarm_mask_gen_hw_fault = -1;
static int hf_zbee_zcl_basic_alarm_mask_gen_sw_fault = -1;
static int hf_zbee_zcl_basic_alarm_mask_reserved = -1;
static int hf_zbee_zcl_basic_disable_local_cfg = -1;
static int hf_zbee_zcl_basic_disable_local_cfg_reset = -1;
static int hf_zbee_zcl_basic_disable_local_cfg_device_cfg = -1;
static int hf_zbee_zcl_basic_disable_local_cfg_reserved = -1;
static int hf_zbee_zcl_basic_srv_rx_cmd_id = -1;
/* Initialize the subtree pointers */
static gint ett_zbee_zcl_basic = -1;
static gint ett_zbee_zcl_basic_alarm_mask = -1;
static gint ett_zbee_zcl_basic_dis_local_cfg = -1;
/* Attributes */
static const value_string zbee_zcl_basic_attr_names[] = {
{ ZBEE_ZCL_ATTR_ID_BASIC_ZCL_VERSION, "ZCL Version" },
{ ZBEE_ZCL_ATTR_ID_BASIC_APPL_VERSION, "Application Version" },
{ ZBEE_ZCL_ATTR_ID_BASIC_STACK_VERSION, "Stack Version" },
{ ZBEE_ZCL_ATTR_ID_BASIC_HW_VERSION, "HW Version" },
{ ZBEE_ZCL_ATTR_ID_BASIC_MANUFACTURER_NAME, "Manufacturer Name" },
{ ZBEE_ZCL_ATTR_ID_BASIC_MODEL_ID, "Model Identifier" },
{ ZBEE_ZCL_ATTR_ID_BASIC_DATE_CODE, "Date Code" },
{ ZBEE_ZCL_ATTR_ID_BASIC_POWER_SOURCE, "Power Source" },
{ ZBEE_ZCL_ATTR_ID_BASIC_LOCATION_DESCR, "Location Description" },
{ ZBEE_ZCL_ATTR_ID_BASIC_PHY_ENVIRONMENT, "Physical Environment" },
{ ZBEE_ZCL_ATTR_ID_BASIC_DEVICE_ENABLED, "Device Enabled" },
{ ZBEE_ZCL_ATTR_ID_BASIC_ALARM_MASK, "Alarm Mask" },
{ ZBEE_ZCL_ATTR_ID_BASIC_DISABLE_LOCAL_CFG, "Disable Local Config" },
{ 0, NULL }
};
/* Server Commands Received */
static const value_string zbee_zcl_basic_srv_rx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_BASIC_RESET_FACTORY_DEFAULTS, "Reset to Factory Defaults" },
{ 0, NULL }
};
/* Power Source Names */
static const value_string zbee_zcl_basic_pwr_src_names[] = {
{ ZBEE_ZCL_BASIC_PWR_SRC_UNKNOWN, "Unknown" },
{ ZBEE_ZCL_BASIC_PWR_SRC_MAINS_1PH, "Mains (single phase)" },
{ ZBEE_ZCL_BASIC_PWR_SRC_MAINS_3PH, "Mains (3 phase)" },
{ ZBEE_ZCL_BASIC_PWR_SRC_BATTERY, "Battery" },
{ ZBEE_ZCL_BASIC_PWR_SRC_DC_SRC, "DC source" },
{ ZBEE_ZCL_BASIC_PWR_SRC_EMERGENCY_1, "Emergency mains constantly powered" },
{ ZBEE_ZCL_BASIC_PWR_SRC_EMERGENCY_2, "Emergency mains and transfer switch" },
{ 0, NULL }
};
/* Device Enable Names */
static const value_string zbee_zcl_basic_dev_en_names[] = {
{ ZBEE_ZCL_BASIC_DISABLED, "Disabled" },
{ ZBEE_ZCL_BASIC_ENABLED, "Enabled" },
{ 0, NULL }
};
/*************************/
/* Function Bodies */
/*************************/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zbee_zcl_basic
* DESCRIPTION
* ZigBee ZCL Basic cluster dissector for wireshark.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* void *data - pointer to ZCL packet structure.
* RETURNS
* int - length of parsed data.
*---------------------------------------------------------------
*/
static int
dissect_zbee_zcl_basic(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
zbee_zcl_packet *zcl;
guint offset = 0;
guint8 cmd_id;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
zcl = (zbee_zcl_packet *)data;
cmd_id = zcl->cmd_id;
/* Create a subtree for the ZCL Command frame, and add the command ID to it. */
if (zcl->direction == ZBEE_ZCL_FCF_TO_SERVER) {
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_basic_srv_rx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
if (tree) {
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_basic_srv_rx_cmd_id, tvb, offset, 1, cmd_id);
}
/*offset++;*/
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_BASIC_RESET_FACTORY_DEFAULTS:
/* No payload */
break;
default:
break;
}
}
return tvb_captured_length(tvb);
} /*dissect_zbee_zcl_basic*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_basic_attr_data
* DESCRIPTION
* this function is called by ZCL foundation dissector in order to decode
* specific cluster attributes data.
* PARAMETERS
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* guint *offset - pointer to buffer offset
* guint16 attr_id - attribute identifier
* guint data_type - attribute data type
* RETURNS
* none
*---------------------------------------------------------------
*/
void
dissect_zcl_basic_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type)
{
static const int * alarm_mask[] = {
&hf_zbee_zcl_basic_alarm_mask_gen_hw_fault,
&hf_zbee_zcl_basic_alarm_mask_gen_sw_fault,
&hf_zbee_zcl_basic_alarm_mask_reserved,
NULL
};
static const int * local_cfg[] = {
&hf_zbee_zcl_basic_disable_local_cfg_reset,
&hf_zbee_zcl_basic_disable_local_cfg_device_cfg,
&hf_zbee_zcl_basic_disable_local_cfg_reserved,
NULL
};
/* Dissect attribute data type and data */
switch (attr_id) {
case ZBEE_ZCL_ATTR_ID_BASIC_POWER_SOURCE:
proto_tree_add_item(tree, hf_zbee_zcl_basic_pwr_src, tvb, *offset, 1, ENC_NA);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_BASIC_DEVICE_ENABLED:
proto_tree_add_item(tree, hf_zbee_zcl_basic_dev_en, tvb, *offset, 1, ENC_NA);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_BASIC_ALARM_MASK:
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_basic_alarm_mask , ett_zbee_zcl_basic_alarm_mask, alarm_mask, ENC_NA);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_BASIC_DISABLE_LOCAL_CFG:
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_basic_disable_local_cfg , ett_zbee_zcl_basic_dis_local_cfg, local_cfg, ENC_NA);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_BASIC_ZCL_VERSION:
case ZBEE_ZCL_ATTR_ID_BASIC_APPL_VERSION:
case ZBEE_ZCL_ATTR_ID_BASIC_STACK_VERSION:
case ZBEE_ZCL_ATTR_ID_BASIC_HW_VERSION:
case ZBEE_ZCL_ATTR_ID_BASIC_MANUFACTURER_NAME:
case ZBEE_ZCL_ATTR_ID_BASIC_MODEL_ID:
case ZBEE_ZCL_ATTR_ID_BASIC_DATE_CODE:
case ZBEE_ZCL_ATTR_ID_BASIC_PHY_ENVIRONMENT:
case ZBEE_ZCL_ATTR_ID_BASIC_LOCATION_DESCR:
default:
dissect_zcl_attr_data(tvb, tree, offset, data_type);
break;
}
} /*dissect_zcl_basic_attr_data*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_register_zbee_zcl_basic
* DESCRIPTION
* ZigBee ZCL Basic cluster protocol registration routine.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void
proto_register_zbee_zcl_basic(void)
{
/* Setup list of header fields */
static hf_register_info hf[] = {
{ &hf_zbee_zcl_basic_attr_id,
{ "Attribute", "zbee_zcl_general.basic.attr_id", FT_UINT16, BASE_HEX, VALS(zbee_zcl_basic_attr_names),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_basic_pwr_src,
{ "Power Source", "zbee_zcl_general.basic.attr.pwr_src", FT_UINT8, BASE_HEX, VALS(zbee_zcl_basic_pwr_src_names),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_basic_dev_en,
{ "Device Enabled", "zbee_zcl_general.basic.attr.dev_en", FT_UINT8, BASE_HEX, VALS(zbee_zcl_basic_dev_en_names),
0x00, NULL, HFILL } },
/* start Alarm Mask fields */
{ &hf_zbee_zcl_basic_alarm_mask,
{ "Alarm Mask", "zbee_zcl_general.basic.attr.alarm_mask", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_basic_alarm_mask_gen_hw_fault,
{ "General hardware fault", "zbee_zcl_general.basic.attr.alarm_mask.gen_hw_fault", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_BASIC_ALARM_GEN_HW_FAULT, NULL, HFILL } },
{ &hf_zbee_zcl_basic_alarm_mask_gen_sw_fault,
{ "General software fault", "zbee_zcl_general.basic.attr.alarm_mask.gen_sw_fault", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_BASIC_ALARM_GEN_SW_FAULT, NULL, HFILL } },
{ &hf_zbee_zcl_basic_alarm_mask_reserved,
{ "Reserved", "zbee_zcl_general.basic.attr.alarm_mask.reserved", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_BASIC_ALARM_RESERVED, NULL, HFILL } },
/* end Alarm Mask fields */
/* start Disable Local Config fields */
{ &hf_zbee_zcl_basic_disable_local_cfg,
{ "Disable Local Config", "zbee_zcl_general.basic.attr.dis_loc_cfg", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_basic_disable_local_cfg_reset,
{ "Reset (to factory defaults)", "zbee_zcl_general.basic.attr.dis_loc_cfg.reset", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_BASIC_DIS_LOC_CFG_RESET , NULL, HFILL } },
{ &hf_zbee_zcl_basic_disable_local_cfg_device_cfg,
{ "Device configuration", "zbee_zcl_general.basic.attr.dis_loc_cfg.dev_cfg", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_BASIC_DIS_LOC_CFG_DEV_CFG , NULL, HFILL } },
{ &hf_zbee_zcl_basic_disable_local_cfg_reserved,
{ "Reserved", "zbee_zcl_general.basic.attr.dis_loc_cfg.reserved", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_BASIC_DIS_LOC_CFG_RESERVED , NULL, HFILL } },
/* end Disable Local Config fields */
{ &hf_zbee_zcl_basic_srv_rx_cmd_id,
{ "Command", "zbee_zcl_general.basic.cmd.srv_rx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_basic_srv_rx_cmd_names),
0x00, NULL, HFILL } }
};
/* ZCL Basic subtrees */
static gint *ett[ZBEE_ZCL_BASIC_NUM_ETT];
ett[0] = &ett_zbee_zcl_basic;
ett[1] = &ett_zbee_zcl_basic_alarm_mask;
ett[2] = &ett_zbee_zcl_basic_dis_local_cfg;
/* Register the ZigBee ZCL Basic cluster protocol name and description */
proto_zbee_zcl_basic = proto_register_protocol("ZigBee ZCL Basic", "ZCL Basic", ZBEE_PROTOABBREV_ZCL_BASIC);
proto_register_field_array(proto_zbee_zcl_basic, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
/* Register the ZigBee ZCL Basic dissector. */
new_register_dissector(ZBEE_PROTOABBREV_ZCL_BASIC, dissect_zbee_zcl_basic, proto_zbee_zcl_basic);
} /*proto_register_zbee_zcl_basic*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_reg_handoff_zbee_zcl_basic
* DESCRIPTION
* Hands off the ZCL Basic dissector.
* PARAMETERS
* none
* RETURNS
* none
*---------------------------------------------------------------
*/
void
proto_reg_handoff_zbee_zcl_basic(void)
{
dissector_handle_t basic_handle;
/* Register our dissector with the ZigBee application dissectors. */
basic_handle = find_dissector(ZBEE_PROTOABBREV_ZCL_BASIC);
dissector_add_uint("zbee.zcl.cluster", ZBEE_ZCL_CID_BASIC, basic_handle);
zbee_zcl_init_cluster( proto_zbee_zcl_basic,
ett_zbee_zcl_basic,
ZBEE_ZCL_CID_BASIC,
hf_zbee_zcl_basic_attr_id,
hf_zbee_zcl_basic_srv_rx_cmd_id,
-1,
(zbee_zcl_fn_attr_data)dissect_zcl_basic_attr_data
);
} /*proto_reg_handoff_zbee_zcl_basic*/
/* ########################################################################## */
/* #### (0x0001) POWER CONFIGURATION CLUSTER ################################ */
/* ########################################################################## */
/*************************/
/* Defines */
/*************************/
/* Attributes */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE 0x0000 /* Mains voltage */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_FREQUENCY 0x0001 /* Mains frerquency */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_ALARM_MASK 0x0010 /* Mains Alarm Mask */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE_MIN_THR 0x0011 /* Mains Voltage Min Threshold */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE_MAX_THR 0x0012 /* Mains Voltage Max Threshold */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE_DWELL_TP 0x0013 /* Mains Voltage Dwell Trip Point */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_VOLTAGE 0x0020 /* Battery Voltage */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_MANUFACTURER 0x0030 /* Battery Manufacturer */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_SIZE 0x0031 /* Battery Size */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_AH_RATING 0x0032 /* Battery AHr Rating */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_QUANTITY 0x0033 /* Battery Quantity */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_RATED_VOLTAGE 0x0034 /* Battery Rated Voltage */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_ALARM_MASK 0x0035 /* Battery Alarm Mask */
#define ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_VOLTAGE_MIN_THR 0x0036 /* Battery Voltage Min Threshold */
/* Server Commands Received - None */
/* Server Commands Generated - None */
/* Mains Alarm Mask bit-mask */
#define ZBEE_ZCL_POWER_CONF_MAINS_ALARM_LOW 0x01 /* Mains voltage too low */
#define ZBEE_ZCL_POWER_CONF_MAINS_ALARM_HIGH 0x02 /* Mains voltage too high */
#define ZBEE_ZCL_POWER_CONF_MAINS_ALARM_RESERVED 0xfc /* Reserved */
/* Battery Size values */
#define ZBEE_ZCL_POWER_CONF_BAT_TYPE_NO_BAT 0x00 /* No battery */
#define ZBEE_ZCL_POWER_CONF_BAT_TYPE_BUILT_IN 0x01 /* Built in */
#define ZBEE_ZCL_POWER_CONF_BAT_TYPE_OTHER 0x02 /* Other */
#define ZBEE_ZCL_POWER_CONF_BAT_TYPE_AA 0x03 /* AA */
#define ZBEE_ZCL_POWER_CONF_BAT_TYPE_AAA 0x04 /* AAA */
#define ZBEE_ZCL_POWER_CONF_BAT_TYPE_C 0x05 /* C */
#define ZBEE_ZCL_POWER_CONF_BAT_TYPE_D 0x06 /* D */
#define ZBEE_ZCL_POWER_CONF_BAT_TYPE_UNKNOWN 0xFF /* Unknown */
/* Battery alarm mask bit-mask */
#define ZBEE_ZCL_POWER_CONF_BATTERY_ALARM_LOW 0x01 /* Battery voltage too low */
#define ZBEE_ZCL_POWER_CONF_BATTERY_ALARM_RESERVED 0xfe /* Reserved */
/*************************/
/* Function Declarations */
/*************************/
void proto_register_zbee_zcl_power_config(void);
void proto_reg_handoff_zbee_zcl_power_config(void);
/* Command Dissector Helpers */
static void dissect_zcl_power_config_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type);
/* Private functions prototype */
/*************************/
/* Global Variables */
/*************************/
/* Initialize the protocol and registered fields */
static int proto_zbee_zcl_power_config = -1;
static int hf_zbee_zcl_power_config_attr_id = -1;
static int hf_zbee_zcl_power_config_batt_type = -1;
static int hf_zbee_zcl_power_config_mains_alarm_mask = -1;
static int hf_zbee_zcl_power_config_mains_alarm_mask_low = -1;
static int hf_zbee_zcl_power_config_mains_alarm_mask_high = -1;
static int hf_zbee_zcl_power_config_mains_alarm_mask_reserved = -1;
static int hf_zbee_zcl_power_config_batt_alarm_mask = -1;
static int hf_zbee_zcl_power_config_batt_alarm_mask_low = -1;
static int hf_zbee_zcl_power_config_batt_alarm_mask_reserved = -1;
static int hf_zbee_zcl_power_config_mains_voltage = -1;
static int hf_zbee_zcl_power_config_mains_frequency = -1;
static int hf_zbee_zcl_power_config_mains_voltage_min_thr = -1;
static int hf_zbee_zcl_power_config_mains_voltage_max_thr = -1;
static int hf_zbee_zcl_power_config_mains_voltage_dwell_tp = -1;
static int hf_zbee_zcl_power_config_batt_voltage = -1;
static int hf_zbee_zcl_power_config_batt_ah_rating = -1;
static int hf_zbee_zcl_power_config_batt_rated_voltage = -1;
static int hf_zbee_zcl_power_config_batt_voltage_min_thr = -1;
/* Initialize the subtree pointers */
static gint ett_zbee_zcl_power_config = -1;
static gint ett_zbee_zcl_power_config_mains_alarm_mask = -1;
static gint ett_zbee_zcl_power_config_batt_alarm_mask = -1;
/* Attributes */
static const value_string zbee_zcl_power_config_attr_names[] = {
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE, "Mains Voltage" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_FREQUENCY, "Mains Frequency" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_ALARM_MASK, "Mains Alarm Mask" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE_MIN_THR, "Mains Voltage Min Threshold" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE_MAX_THR, "Mains Voltage Max Threshold" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE_DWELL_TP, "Mains Voltage Dwell Trip Point" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_VOLTAGE, "Battery Voltage" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_MANUFACTURER, "Battery Manufacturer" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_SIZE, "Battery Size" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_AH_RATING, "Battery AHr Rating" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_QUANTITY, "Battery Quantity" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_RATED_VOLTAGE, "Battery Rated Voltage" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_ALARM_MASK, "Battery Alarm Mask" },
{ ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_VOLTAGE_MIN_THR, "Battery Voltage Minimum Threshold" },
{ 0, NULL }
};
/* Battery size Names */
static const value_string zbee_zcl_power_config_batt_type_names[] = {
{ ZBEE_ZCL_POWER_CONF_BAT_TYPE_NO_BAT, "No battery" },
{ ZBEE_ZCL_POWER_CONF_BAT_TYPE_BUILT_IN, "Built in" },
{ ZBEE_ZCL_POWER_CONF_BAT_TYPE_OTHER, "Other" },
{ ZBEE_ZCL_POWER_CONF_BAT_TYPE_AA, "AA" },
{ ZBEE_ZCL_POWER_CONF_BAT_TYPE_AAA, "AAA" },
{ ZBEE_ZCL_POWER_CONF_BAT_TYPE_C, "C" },
{ ZBEE_ZCL_POWER_CONF_BAT_TYPE_D, "D" },
{ ZBEE_ZCL_POWER_CONF_BAT_TYPE_UNKNOWN, "Unknown" },
{ 0, NULL }
};
/*************************/
/* Function Bodies */
/*************************/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zbee_zcl_power_config
* DESCRIPTION
* ZigBee ZCL power configuration cluster dissector for wireshark.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zbee_zcl_power_config(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_)
{
return;
} /*dissect_zbee_zcl_power_config*/
/*FUNCTION:------------------------------------------------------
* NAME
* decode_power_conf_voltage
* DESCRIPTION
* this function decodes voltage values
* PARAMETERS
* guint *s - string to display
* guint32 value - value to decode
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_power_conf_voltage(gchar *s, guint32 value)
{
g_snprintf(s, ITEM_LABEL_LENGTH, "%d.%d [V]", value/10, value%10);
return;
} /*decode_power_conf_voltage*/
/*FUNCTION:------------------------------------------------------
* NAME
* decode_power_conf_frequency
* DESCRIPTION
* this function decodes mains frequency values
* PARAMETERS
* guint *s - string to display
* guint32 value - value to decode
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_power_conf_frequency(gchar *s, guint32 value)
{
if(value == 0x00)
g_snprintf(s, ITEM_LABEL_LENGTH, "Frequency too low to be measured (or DC supply)");
else if(value == 0xfe)
g_snprintf(s, ITEM_LABEL_LENGTH, "Frequency too high to be measured");
else if (value == 0xff)
g_snprintf(s, ITEM_LABEL_LENGTH, "Frequency could not be measured");
else
g_snprintf(s, ITEM_LABEL_LENGTH, "%d [Hz]", value*2);
return;
} /*decode_power_conf_frequency*/
/*FUNCTION:------------------------------------------------------
* NAME
* decode_power_conf_batt_AHr
* DESCRIPTION
* this function decodes battery capacity values
* PARAMETERS
* guint *s - string to display
* guint32 value - value to decode
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_power_conf_batt_AHr(gchar *s, guint32 value)
{
g_snprintf(s, ITEM_LABEL_LENGTH, "%d [mAHr]", value*10);
return;
} /*decode_power_conf_batt_AHr*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_power_config_attr_data
* DESCRIPTION
* this function is called by ZCL foundation dissector in order to decode
* specific cluster attributes data.
* PARAMETERS
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* guint *offset - pointer to buffer offset
* guint16 attr_id - attribute identifier
* guint data_type - attribute data type
* RETURNS
* none
*---------------------------------------------------------------
*/
void
dissect_zcl_power_config_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type)
{
proto_item *it;
static const int * mains_alarm_mask[] = {
&hf_zbee_zcl_power_config_mains_alarm_mask_low,
&hf_zbee_zcl_power_config_mains_alarm_mask_high,
&hf_zbee_zcl_power_config_mains_alarm_mask_reserved,
NULL
};
static const int * batt_alarm_mask[] = {
&hf_zbee_zcl_power_config_batt_alarm_mask_low,
&hf_zbee_zcl_power_config_batt_alarm_mask_reserved,
NULL
};
/* Dissect attribute data type and data */
switch (attr_id) {
case ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE:
proto_tree_add_item(tree, hf_zbee_zcl_power_config_mains_voltage, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_FREQUENCY:
proto_tree_add_item(tree, hf_zbee_zcl_power_config_mains_frequency, tvb, *offset, 1, ENC_LITTLE_ENDIAN);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_ALARM_MASK:
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_power_config_mains_alarm_mask, ett_zbee_zcl_power_config_mains_alarm_mask, mains_alarm_mask, ENC_LITTLE_ENDIAN);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE_MIN_THR:
proto_tree_add_item(tree, hf_zbee_zcl_power_config_mains_voltage_min_thr, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE_MAX_THR:
proto_tree_add_item(tree, hf_zbee_zcl_power_config_mains_voltage_max_thr, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_MAINS_VOLTAGE_DWELL_TP:
it = proto_tree_add_item(tree, hf_zbee_zcl_power_config_mains_voltage_dwell_tp, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
proto_item_append_text(it, " [s]");
*offset += 2;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_SIZE:
proto_tree_add_item(tree, hf_zbee_zcl_power_config_batt_type, tvb, *offset, 1, ENC_LITTLE_ENDIAN);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_VOLTAGE:
proto_tree_add_item(tree, hf_zbee_zcl_power_config_batt_voltage, tvb, *offset, 1, ENC_LITTLE_ENDIAN);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_AH_RATING:
proto_tree_add_item(tree, hf_zbee_zcl_power_config_batt_ah_rating, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_RATED_VOLTAGE:
proto_tree_add_item(tree, hf_zbee_zcl_power_config_batt_rated_voltage, tvb, *offset, 1, ENC_LITTLE_ENDIAN);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_ALARM_MASK:
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_power_config_batt_alarm_mask, ett_zbee_zcl_power_config_batt_alarm_mask, batt_alarm_mask, ENC_LITTLE_ENDIAN);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_VOLTAGE_MIN_THR:
proto_tree_add_item(tree, hf_zbee_zcl_power_config_batt_voltage_min_thr, tvb, *offset, 1, ENC_LITTLE_ENDIAN);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_MANUFACTURER:
case ZBEE_ZCL_ATTR_ID_POWER_CONF_BATTERY_QUANTITY:
default:
dissect_zcl_attr_data(tvb, tree, offset, data_type);
break;
}
} /*dissect_zcl_power_config_attr_data*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_register_zbee_zcl_power_config
* DESCRIPTION
* ZigBee ZCL power configuration cluster protocol registration routine.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void
proto_register_zbee_zcl_power_config(void)
{
/* Setup list of header fields */
static hf_register_info hf[] = {
{ &hf_zbee_zcl_power_config_attr_id,
{ "Attribute", "zbee_zcl_general.power_config.attr_id", FT_UINT16, BASE_HEX, VALS(zbee_zcl_power_config_attr_names),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_batt_type,
{ "Battery Type", "zbee_zcl_general.power_config.attr.batt_type", FT_UINT8, BASE_HEX, VALS(zbee_zcl_power_config_batt_type_names),
0x00, NULL, HFILL } },
/* start mains Alarm Mask fields */
{ &hf_zbee_zcl_power_config_mains_alarm_mask,
{ "Mains Alarm Mask", "zbee_zcl_general.power_config.attr.mains_alarm_mask", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_mains_alarm_mask_low,
{ "Mains Voltage too low", "zbee_zcl_general.power_config.attr.mains_alarm_mask.mains_too_low", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_POWER_CONF_MAINS_ALARM_LOW, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_mains_alarm_mask_high,
{ "Mains Voltage too high", "zbee_zcl_general.power_config.attr.mains_alarm_mask.mains_too_high", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_POWER_CONF_MAINS_ALARM_HIGH, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_mains_alarm_mask_reserved,
{ "Reserved", "zbee_zcl_general.power_config.attr.mains_alarm_mask.reserved", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_POWER_CONF_MAINS_ALARM_RESERVED, NULL, HFILL } },
/* end mains Alarm Mask fields */
/* start battery Alarm Mask fields */
{ &hf_zbee_zcl_power_config_batt_alarm_mask,
{ "Battery Alarm Mask", "zbee_zcl_general.power_config.attr.batt_alarm_mask", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_batt_alarm_mask_low,
{ "Battery Voltage too low", "zbee_zcl_general.power_config.batt_attr.alarm_mask.batt_too_low", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_POWER_CONF_BATTERY_ALARM_LOW, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_batt_alarm_mask_reserved,
{ "Reserved", "zbee_zcl_general.power_config.attr.batt_alarm_mask.reserved", FT_UINT8, BASE_DEC, NULL,
ZBEE_ZCL_POWER_CONF_BATTERY_ALARM_RESERVED, NULL, HFILL } },
/* end battery Alarm Mask fields */
{ &hf_zbee_zcl_power_config_mains_voltage,
{ "Measured Mains Voltage", "zbee_zcl_general.power_config.attr.mains_voltage", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_power_conf_voltage),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_mains_frequency,
{ "Measured Mains Frequency", "zbee_zcl_general.power_config.attr.mains_frequency", FT_UINT8, BASE_CUSTOM, CF_FUNC(decode_power_conf_frequency),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_mains_voltage_min_thr,
{ "Mains Voltage Minimum Threshold", "zbee_zcl_general.power_config.attr.mains_volt_min", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_power_conf_voltage),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_mains_voltage_max_thr,
{ "Mains Voltage Maximum Threshold", "zbee_zcl_general.power_config.attr.mains_volt_max", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_power_conf_voltage),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_batt_voltage,
{ "Measured Battey Voltage", "zbee_zcl_general.power_config.attr.batt_voltage", FT_UINT8, BASE_CUSTOM, CF_FUNC(decode_power_conf_voltage),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_batt_ah_rating,
{ "Battery Capacity", "zbee_zcl_general.power_config.attr.batt_AHr", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_power_conf_batt_AHr),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_batt_rated_voltage,
{ "Battery Rated Voltage", "zbee_zcl_general.power_config.attr.batt_rated_voltage", FT_UINT8, BASE_CUSTOM, CF_FUNC(decode_power_conf_voltage),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_batt_voltage_min_thr,
{ "Battery Voltage Minimum Threshold", "zbee_zcl_general.power_config.attr.batt_voltage_min_thr", FT_UINT8, BASE_CUSTOM, CF_FUNC(decode_power_conf_voltage),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_power_config_mains_voltage_dwell_tp,
{ "Mains Voltage Dwell Trip Point", "zbee_zcl_general.power_config.attr.mains_dwell_tp", FT_UINT16, BASE_DEC, NULL,
0x00, NULL, HFILL } },
};
/* ZCL power configuration subtrees */
static gint *ett[] = {
&ett_zbee_zcl_power_config,
&ett_zbee_zcl_power_config_mains_alarm_mask,
&ett_zbee_zcl_power_config_batt_alarm_mask
};
/* Register the ZigBee ZCL power configuration cluster protocol name and description */
proto_zbee_zcl_power_config = proto_register_protocol("ZigBee ZCL Power Configuration", "ZCL Power Configuration", ZBEE_PROTOABBREV_ZCL_POWER_CONFIG);
proto_register_field_array(proto_zbee_zcl_power_config, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
/* Register the ZigBee ZCL power configuration dissector. */
register_dissector(ZBEE_PROTOABBREV_ZCL_POWER_CONFIG, dissect_zbee_zcl_power_config, proto_zbee_zcl_power_config);
} /*proto_register_zbee_zcl_power_config*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_reg_handoff_zbee_zcl_power_config
* DESCRIPTION
* Hands off the ZCL power configuration dissector.
* PARAMETERS
* none
* RETURNS
* none
*---------------------------------------------------------------
*/
void
proto_reg_handoff_zbee_zcl_power_config(void)
{
dissector_handle_t handle;
/* Register our dissector with the ZigBee application dissectors. */
handle = find_dissector(ZBEE_PROTOABBREV_ZCL_POWER_CONFIG);
dissector_add_uint("zbee.zcl.cluster", ZBEE_ZCL_CID_POWER_CONFIG, handle);
zbee_zcl_init_cluster( proto_zbee_zcl_power_config,
ett_zbee_zcl_power_config,
ZBEE_ZCL_CID_POWER_CONFIG,
hf_zbee_zcl_power_config_attr_id,
-1, -1,
(zbee_zcl_fn_attr_data)dissect_zcl_power_config_attr_data
);
} /*proto_reg_handoff_zbee_zcl_power_config*/
/* ########################################################################## */
/* #### (0x0003) IDENTIFY CLUSTER ########################################### */
/* ########################################################################## */
/*************************/
/* Defines */
/*************************/
#define ZBEE_ZCL_IDENTIFY_NUM_GENERIC_ETT 1
#define ZBEE_ZCL_IDENTIFY_NUM_ETT ZBEE_ZCL_IDENTIFY_NUM_GENERIC_ETT
/* Attributes */
#define ZBEE_ZCL_ATTR_ID_IDENTIFY_IDENTIFY_TIME 0x0000 /* Identify Time */
/* Server Commands Received */
#define ZBEE_ZCL_CMD_ID_IDENTIFY_IDENTITY 0x00 /* Identify */
#define ZBEE_ZCL_CMD_ID_IDENTIFY_IDENTITY_QUERY 0x01 /* Identify Query */
/* Server Commands Generated */
#define ZBEE_ZCL_CMD_ID_IDENTIFY_IDENTITY_QUERY_RSP 0x00 /* Identify Query Response */
/*************************/
/* Function Declarations */
/*************************/
void proto_register_zbee_zcl_identify(void);
void proto_reg_handoff_zbee_zcl_identify(void);
/* Command Dissector Helpers */
static void dissect_zcl_identify_identify (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_identify_identifyqueryrsp (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_identify_attr_data (proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type);
/* Private functions prototype */
/*************************/
/* Global Variables */
/*************************/
/* Initialize the protocol and registered fields */
static int proto_zbee_zcl_identify = -1;
static int hf_zbee_zcl_identify_attr_id = -1;
static int hf_zbee_zcl_identify_identify_time = -1;
static int hf_zbee_zcl_identify_identify_timeout = -1;
static int hf_zbee_zcl_identify_srv_rx_cmd_id = -1;
static int hf_zbee_zcl_identify_srv_tx_cmd_id = -1;
/* Initialize the subtree pointers */
static gint ett_zbee_zcl_identify = -1;
/* Attributes */
static const value_string zbee_zcl_identify_attr_names[] = {
{ ZBEE_ZCL_ATTR_ID_IDENTIFY_IDENTIFY_TIME, "Identify Time" },
{ 0, NULL }
};
/* Server Commands Received */
static const value_string zbee_zcl_identify_srv_rx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_IDENTIFY_IDENTITY, "Identify" },
{ ZBEE_ZCL_CMD_ID_IDENTIFY_IDENTITY_QUERY, "Identify Query" },
{ 0, NULL }
};
/* Server Commands Generated */
static const value_string zbee_zcl_identify_srv_tx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_IDENTIFY_IDENTITY_QUERY_RSP, "Identify Query Response" },
{ 0, NULL }
};
/*************************/
/* Function Bodies */
/*************************/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zbee_zcl_identify
* DESCRIPTION
* ZigBee ZCL Identify cluster dissector for wireshark.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* void *data - pointer to ZCL packet structure.
* RETURNS
* int - length of parsed data.
*---------------------------------------------------------------
*/
static int
dissect_zbee_zcl_identify(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
proto_tree *payload_tree;
zbee_zcl_packet *zcl;
guint offset = 0;
guint8 cmd_id;
gint rem_len;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
zcl = (zbee_zcl_packet *)data;
cmd_id = zcl->cmd_id;
/* Create a subtree for the ZCL Command frame, and add the command ID to it. */
if (zcl->direction == ZBEE_ZCL_FCF_TO_SERVER) {
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_identify_srv_rx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_identify_srv_rx_cmd_id, tvb, offset, 1, cmd_id);
/* Check is this command has a payload, than add the payload tree */
rem_len = tvb_reported_length_remaining(tvb, ++offset);
if (rem_len > 0) {
payload_tree = proto_tree_add_subtree(tree, tvb, offset, rem_len, ett_zbee_zcl_identify, NULL, "Payload");
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_IDENTIFY_IDENTITY:
dissect_zcl_identify_identify(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_IDENTIFY_IDENTITY_QUERY:
/* without payload*/
break;
default:
break;
}
}
}
else { /* ZBEE_ZCL_FCF_TO_CLIENT */
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_identify_srv_tx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_identify_srv_tx_cmd_id, tvb, offset, 1, cmd_id);
/* Check is this command has a payload, than add the payload tree */
rem_len = tvb_reported_length_remaining(tvb, ++offset);
if (rem_len > 0) {
payload_tree = proto_tree_add_subtree(tree, tvb, offset, rem_len, ett_zbee_zcl_identify, NULL, "Payload");
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_IDENTIFY_IDENTITY_QUERY_RSP:
dissect_zcl_identify_identifyqueryrsp(tvb, payload_tree, &offset);
break;
default:
break;
}
}
}
return tvb_captured_length(tvb);
} /*dissect_zbee_zcl_identify*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_identify_identify
* DESCRIPTION
* this function decodes the Identify payload.
* PARAMETERS
* tvb - the tv buffer of the current data_type
* tree - the tree to append this item to
* offset - offset of data in tvb
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_identify_identify(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Retrieve "Identify Time" field */
proto_tree_add_item(tree, hf_zbee_zcl_identify_identify_time, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
} /*dissect_zcl_identify_identify*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_identify_identifyqueryrsp
* DESCRIPTION
* this function decodes the IdentifyQueryResponse payload.
* PARAMETERS
* tvb - the tv buffer of the current data_type
* tree - the tree to append this item to
* offset - offset of data in tvb
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_identify_identifyqueryrsp(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Retrieve "Identify Timeout" field */
proto_tree_add_item(tree, hf_zbee_zcl_identify_identify_timeout, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
} /*dissect_zcl_identify_identifyqueryrsp*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_identify_attr_data
* DESCRIPTION
* this function is called by ZCL foundation dissector in order to decode
* specific cluster attributes data.
* PARAMETERS
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* guint *offset - pointer to buffer offset
* guint16 attr_id - attribute identifier
* guint data_type - attribute data type
* RETURNS
* none
*---------------------------------------------------------------
*/
void
dissect_zcl_identify_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type)
{
/* Dissect attribute data type and data */
switch ( attr_id ) {
case ZBEE_ZCL_ATTR_ID_IDENTIFY_IDENTIFY_TIME:
proto_tree_add_item(tree, hf_zbee_zcl_identify_identify_time, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
break;
default:
dissect_zcl_attr_data(tvb, tree, offset, data_type);
break;
}
} /*dissect_zcl_identify_attr_data*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_register_zbee_zcl_identify
* DESCRIPTION
* ZigBee ZCL Identify cluster protocol registration routine.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void
proto_register_zbee_zcl_identify(void)
{
/* Setup list of header fields */
static hf_register_info hf[] = {
{ &hf_zbee_zcl_identify_attr_id,
{ "Attribute", "zbee_zcl_general.identify.attr_id", FT_UINT16, BASE_HEX, VALS(zbee_zcl_identify_attr_names),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_identify_identify_time,
{ "Identify Time", "zbee_zcl_general.identify.attr.identify_time", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_zcl_time_in_seconds),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_identify_identify_timeout,
{ "Identify Timeout", "zbee_zcl_general.identify.identify_timeout", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_zcl_time_in_seconds),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_identify_srv_rx_cmd_id,
{ "Command", "zbee_zcl_general.identify.cmd.srv_rx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_identify_srv_rx_cmd_names),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_identify_srv_tx_cmd_id,
{ "Command", "zbee_zcl_general.identify.cmd.srv_tx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_identify_srv_tx_cmd_names),
0x00, NULL, HFILL } }
};
/* ZCL Identify subtrees */
static gint *ett[ZBEE_ZCL_IDENTIFY_NUM_ETT];
ett[0] = &ett_zbee_zcl_identify;
/* Register the ZigBee ZCL Identify cluster protocol name and description */
proto_zbee_zcl_identify = proto_register_protocol("ZigBee ZCL Identify", "ZCL Identify", ZBEE_PROTOABBREV_ZCL_IDENTIFY);
proto_register_field_array(proto_zbee_zcl_identify, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
/* Register the ZigBee ZCL Identify dissector. */
new_register_dissector(ZBEE_PROTOABBREV_ZCL_IDENTIFY, dissect_zbee_zcl_identify, proto_zbee_zcl_identify);
} /*proto_register_zbee_zcl_identify*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_reg_handoff_zbee_zcl_identify
* DESCRIPTION
* Hands off the ZCL Identify dissector.
* PARAMETERS
* none
* RETURNS
* none
*---------------------------------------------------------------
*/
void
proto_reg_handoff_zbee_zcl_identify(void)
{
dissector_handle_t identify_handle;
/* Register our dissector with the ZigBee application dissectors. */
identify_handle = find_dissector(ZBEE_PROTOABBREV_ZCL_IDENTIFY);
dissector_add_uint("zbee.zcl.cluster", ZBEE_ZCL_CID_IDENTIFY, identify_handle);
zbee_zcl_init_cluster( proto_zbee_zcl_identify,
ett_zbee_zcl_identify,
ZBEE_ZCL_CID_IDENTIFY,
hf_zbee_zcl_identify_attr_id,
hf_zbee_zcl_identify_srv_rx_cmd_id,
hf_zbee_zcl_identify_srv_tx_cmd_id,
(zbee_zcl_fn_attr_data)dissect_zcl_identify_attr_data
);
} /*proto_reg_handoff_zbee_zcl_identify*/
/* ########################################################################## */
/* #### (0x0006) ON/OFF CLUSTER ############################################# */
/* ########################################################################## */
/*************************/
/* Defines */
/*************************/
/* Attributes */
#define ZBEE_ZCL_ON_OFF_ATTR_ID_ONOFF 0x0000
/* Server Commands Received */
#define ZBEE_ZCL_ON_OFF_CMD_OFF 0x00 /* Off */
#define ZBEE_ZCL_ON_OFF_CMD_ON 0x01 /* On */
#define ZBEE_ZCL_ON_OFF_CMD_TOGGLE 0x02 /* Toggle */
/*************************/
/* Function Declarations */
/*************************/
void proto_register_zbee_zcl_on_off(void);
void proto_reg_handoff_zbee_zcl_on_off(void);
/* Command Dissector Helpers */
static void dissect_zcl_on_off_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type);
/* Private functions prototype */
/*************************/
/* Global Variables */
/*************************/
/* Initialize the protocol and registered fields */
static int proto_zbee_zcl_on_off = -1;
static int hf_zbee_zcl_on_off_attr_id = -1;
static int hf_zbee_zcl_on_off_attr_onoff = -1;
static int hf_zbee_zcl_on_off_srv_rx_cmd_id = -1;
/* Initialize the subtree pointers */
static gint ett_zbee_zcl_on_off = -1;
/* Attributes */
static const value_string zbee_zcl_on_off_attr_names[] = {
{ ZBEE_ZCL_ON_OFF_ATTR_ID_ONOFF, "OnOff" },
{ 0, NULL }
};
/* Server Commands Generated */
static const value_string zbee_zcl_on_off_srv_rx_cmd_names[] = {
{ ZBEE_ZCL_ON_OFF_CMD_OFF, "Off" },
{ ZBEE_ZCL_ON_OFF_CMD_ON, "On" },
{ ZBEE_ZCL_ON_OFF_CMD_TOGGLE, "Toggle" },
{ 0, NULL }
};
/* OnOff Names */
static const value_string zbee_zcl_on_off_onoff_names[] = {
{ 0, "Off" },
{ 1, "On" },
{ 0, NULL }
};
/*************************/
/* Function Bodies */
/*************************/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zbee_zcl_onoff
* DESCRIPTION
* ZigBee ZCL OnOff cluster dissector for wireshark.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* void *data - pointer to ZCL packet structure.
* RETURNS
* int - length of parsed data.
*---------------------------------------------------------------
*/
static int
dissect_zbee_zcl_on_off(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
zbee_zcl_packet *zcl;
guint offset = 0;
guint8 cmd_id;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
zcl = (zbee_zcl_packet *)data;
cmd_id = zcl->cmd_id;
/* Create a subtree for the ZCL Command frame, and add the command ID to it. */
if (zcl->direction == ZBEE_ZCL_FCF_TO_SERVER) {
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_on_off_srv_rx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_on_off_srv_rx_cmd_id, tvb, offset, 1, cmd_id);
/*offset++;*/
}
return tvb_captured_length(tvb);
} /*dissect_zbee_zcl_on_off*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_on_off_attr_data
* DESCRIPTION
* this function is called by ZCL foundation dissector in order to decode
* specific cluster attributes data.
* PARAMETERS
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* guint *offset - pointer to buffer offset
* guint16 attr_id - attribute identifier
* guint data_type - attribute data type
* RETURNS
* none
*---------------------------------------------------------------
*/
void
dissect_zcl_on_off_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type)
{
/* Dissect attribute data type and data */
switch (attr_id) {
case ZBEE_ZCL_ON_OFF_ATTR_ID_ONOFF:
proto_tree_add_item(tree, hf_zbee_zcl_on_off_attr_onoff, tvb, *offset, 1, ENC_NA);
*offset += 1;
break;
default:
dissect_zcl_attr_data(tvb, tree, offset, data_type);
break;
}
} /*dissect_zcl_on_off_attr_data*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_register_zbee_zcl_on_off
* DESCRIPTION
* ZigBee ZCL OnOff cluster protocol registration routine.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void
proto_register_zbee_zcl_on_off(void)
{
/* Setup list of header fields */
static hf_register_info hf[] = {
{ &hf_zbee_zcl_on_off_attr_id,
{ "Attribute", "zbee_zcl_general.onoff.attr_id", FT_UINT16, BASE_HEX, VALS(zbee_zcl_on_off_attr_names),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_on_off_attr_onoff,
{ "Data Value", "zbee_zcl_general.onoff.attr.onoff", FT_UINT8, BASE_HEX, VALS(zbee_zcl_on_off_onoff_names),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_on_off_srv_rx_cmd_id,
{ "Command", "zbee_zcl_general.onoff.cmd.srv_rx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_on_off_srv_rx_cmd_names),
0x00, NULL, HFILL } }
};
/* Register the ZigBee ZCL OnOff cluster protocol name and description */
proto_zbee_zcl_on_off = proto_register_protocol("ZigBee ZCL OnOff", "ZCL OnOff", ZBEE_PROTOABBREV_ZCL_ONOFF);
proto_register_field_array(proto_zbee_zcl_on_off, hf, array_length(hf));
/* Register the ZigBee ZCL OnOff dissector. */
new_register_dissector(ZBEE_PROTOABBREV_ZCL_ONOFF, dissect_zbee_zcl_on_off, proto_zbee_zcl_on_off);
} /* proto_register_zbee_zcl_on_off */
/*FUNCTION:------------------------------------------------------
* NAME
* proto_reg_handoff_zbee_zcl_on_off
* DESCRIPTION
* Hands off the Zcl OnOff cluster dissector.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void
proto_reg_handoff_zbee_zcl_on_off(void)
{
dissector_handle_t on_off_handle;
/* Register our dissector with the ZigBee application dissectors. */
on_off_handle = find_dissector(ZBEE_PROTOABBREV_ZCL_ONOFF);
dissector_add_uint("zbee.zcl.cluster", ZBEE_ZCL_CID_ON_OFF, on_off_handle);
zbee_zcl_init_cluster( proto_zbee_zcl_on_off,
ett_zbee_zcl_on_off,
ZBEE_ZCL_CID_ON_OFF,
hf_zbee_zcl_on_off_attr_id,
hf_zbee_zcl_on_off_srv_rx_cmd_id,
-1,
(zbee_zcl_fn_attr_data)dissect_zcl_on_off_attr_data
);
} /*proto_reg_handoff_zbee_zcl_on_off*/
/* ########################################################################## */
/* #### (0x0016) PARTITION ################################################## */
/* ########################################################################## */
/*************************/
/* Defines */
/*************************/
#define ZBEE_ZCL_PART_NUM_GENERIC_ETT 3
#define ZBEE_ZCL_PART_NUM_NACK_ID_ETT 16
#define ZBEE_ZCL_PART_NUM_ATTRS_ID_ETT 16
#define ZBEE_ZCL_PART_NUM_ETT (ZBEE_ZCL_PART_NUM_GENERIC_ETT + \
ZBEE_ZCL_PART_NUM_NACK_ID_ETT + \
ZBEE_ZCL_PART_NUM_ATTRS_ID_ETT)
#define ZBEE_ZCL_PART_OPT_1_BLOCK 0x01
#define ZBEE_ZCL_PART_OPT_INDIC_LEN 0x02
#define ZBEE_ZCL_PART_OPT_RESERVED 0xc0
#define ZBEE_ZCL_PART_ACK_OPT_NACK_LEN 0x01
#define ZBEE_ZCL_PART_ACK_OPT_RESERVED 0xFE
/* Attributes */
#define ZBEE_ZCL_ATTR_ID_PART_MAX_IN_TRANSF_SIZE 0x0000 /* Maximum Incoming Transfer Size */
#define ZBEE_ZCL_ATTR_ID_PART_MAX_OUT_TRANSF_SIZE 0x0001 /* Maximum Outgoing Transfer Size */
#define ZBEE_ZCL_ATTR_ID_PART_PARTIONED_FRAME_SIZE 0x0002 /* Partioned Frame Size */
#define ZBEE_ZCL_ATTR_ID_PART_LARGE_FRAME_SIZE 0x0003 /* Large Frame Size */
#define ZBEE_ZCL_ATTR_ID_PART_ACK_FRAME_NUM 0x0004 /* Number of Ack Frame*/
#define ZBEE_ZCL_ATTR_ID_PART_NACK_TIMEOUT 0x0005 /* Nack Timeout */
#define ZBEE_ZCL_ATTR_ID_PART_INTERFRAME_DELEAY 0x0006 /* Interframe Delay */
#define ZBEE_ZCL_ATTR_ID_PART_SEND_RETRIES_NUM 0x0007 /* Number of Send Retries */
#define ZBEE_ZCL_ATTR_ID_PART_SENDER_TIMEOUT 0x0008 /* Sender Timeout */
#define ZBEE_ZCL_ATTR_ID_PART_RECEIVER_TIMEOUT 0x0009 /* Receiver Timeout */
/* Server Commands Received */
#define ZBEE_ZCL_CMD_ID_PART_TRANSF_PART_FRAME 0x00 /* Transfer Partitioned Frame */
#define ZBEE_ZCL_CMD_ID_PART_RD_HANDSHAKE_PARAM 0x01 /* Read Handshake Param */
#define ZBEE_ZCL_CMD_ID_PART_WR_HANDSHAKE_PARAM 0x02 /* Write Handshake Param */
/* Server Commands Generated */
#define ZBEE_ZCL_CMD_ID_PART_MULTI_ACK 0x00 /* Multiple Ack */
#define ZBEE_ZCL_CMD_ID_PART_RD_HANDSHAKE_PARAM_RSP 0x01 /* Read Handshake Param Response */
/*************************/
/* Function Declarations */
/*************************/
void proto_register_zbee_zcl_part(void);
void proto_reg_handoff_zbee_zcl_part(void);
/* Command Dissector Helpers */
static void dissect_zcl_part_trasfpartframe (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_part_rdhandshakeparam (tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint *offset);
static void dissect_zcl_part_wrhandshakeparam (tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint *offset);
static void dissect_zcl_part_multiack (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_part_rdhandshakeparamrsp (tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint *offset);
/* Private functions prototype */
/*************************/
/* Global Variables */
/*************************/
/* Initialize the protocol and registered fields */
static int proto_zbee_zcl_part = -1;
static int hf_zbee_zcl_part_attr_id = -1;
static int hf_zbee_zcl_part_srv_tx_cmd_id = -1;
static int hf_zbee_zcl_part_srv_rx_cmd_id = -1;
static int hf_zbee_zcl_part_opt = -1;
static int hf_zbee_zcl_part_opt_first_block = -1;
static int hf_zbee_zcl_part_opt_indic_len = -1;
static int hf_zbee_zcl_part_opt_res = -1;
static int hf_zbee_zcl_part_first_frame_id = -1;
static int hf_zbee_zcl_part_part_indicator = -1;
static int hf_zbee_zcl_part_part_frame = -1;
static int hf_zbee_zcl_part_part_frame_len = -1;
static int hf_zbee_zcl_part_partitioned_cluster_id = -1;
static int hf_zbee_zcl_part_ack_opt = -1;
static int hf_zbee_zcl_part_ack_opt_nack_id_len = -1;
static int hf_zbee_zcl_part_ack_opt_res = -1;
static int hf_zbee_zcl_part_nack_id = -1;
/* Initialize the subtree pointers */
static gint ett_zbee_zcl_part = -1;
static gint ett_zbee_zcl_part_fragm_options = -1;
static gint ett_zbee_zcl_part_ack_opts = -1;
static gint ett_zbee_zcl_part_nack_id_list[ZBEE_ZCL_PART_NUM_NACK_ID_ETT];
static gint ett_zbee_zcl_part_attrs_id_list[ZBEE_ZCL_PART_NUM_ATTRS_ID_ETT];
/* Attributes */
static const value_string zbee_zcl_part_attr_names[] = {
{ ZBEE_ZCL_ATTR_ID_PART_MAX_IN_TRANSF_SIZE, "Maximum Incoming Transfer Size" },
{ ZBEE_ZCL_ATTR_ID_PART_MAX_OUT_TRANSF_SIZE, "Maximum Outgoing Transfer Size" },
{ ZBEE_ZCL_ATTR_ID_PART_PARTIONED_FRAME_SIZE, "Partioned Frame Size" },
{ ZBEE_ZCL_ATTR_ID_PART_LARGE_FRAME_SIZE, "Large Frame Size" },
{ ZBEE_ZCL_ATTR_ID_PART_ACK_FRAME_NUM, "Number of Ack Frame" },
{ ZBEE_ZCL_ATTR_ID_PART_NACK_TIMEOUT, "Nack Timeout" },
{ ZBEE_ZCL_ATTR_ID_PART_INTERFRAME_DELEAY, "Interframe Delay" },
{ ZBEE_ZCL_ATTR_ID_PART_SEND_RETRIES_NUM, "Number of Send Retries" },
{ ZBEE_ZCL_ATTR_ID_PART_SENDER_TIMEOUT, "Sender Timeout" },
{ ZBEE_ZCL_ATTR_ID_PART_RECEIVER_TIMEOUT, "Receiver Timeout" },
{ 0, NULL }
};
/* Server Commands Received */
static const value_string zbee_zcl_part_srv_rx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_PART_TRANSF_PART_FRAME, "Transfer Partitioned Frame" },
{ ZBEE_ZCL_CMD_ID_PART_RD_HANDSHAKE_PARAM, "Read Handshake Param" },
{ ZBEE_ZCL_CMD_ID_PART_WR_HANDSHAKE_PARAM, "Write Handshake Param" },
{ 0, NULL }
};
/* Server Commands Generated */
static const value_string zbee_zcl_part_srv_tx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_PART_MULTI_ACK, "Multiple Ack" },
{ ZBEE_ZCL_CMD_ID_PART_RD_HANDSHAKE_PARAM_RSP, "Read Handshake Param Response" },
{ 0, NULL }
};
/* ID Length */
static const value_string zbee_zcl_part_id_length_names[] = {
{ 0, "1-Byte length" },
{ 1, "2-Bytes length" },
{ 0, NULL }
};
/*************************/
/* Function Bodies */
/*************************/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zbee_zcl_part
* DESCRIPTION
* ZigBee ZCL Partition cluster dissector for wireshark.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* void *data - pointer to ZCL packet structure.
* RETURNS
* int - length of parsed data.
*---------------------------------------------------------------
*/
static int
dissect_zbee_zcl_part(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
proto_tree *payload_tree;
zbee_zcl_packet *zcl;
guint offset = 0;
guint8 cmd_id;
gint rem_len;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
zcl = (zbee_zcl_packet *)data;
cmd_id = zcl->cmd_id;
/* Create a subtree for the ZCL Command frame, and add the command ID to it. */
if (zcl->direction == ZBEE_ZCL_FCF_TO_SERVER) {
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_part_srv_rx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_part_srv_rx_cmd_id, tvb, offset, 1, cmd_id);
/* Check is this command has a payload, than add the payload tree */
rem_len = tvb_reported_length_remaining(tvb, ++offset);
if (rem_len > 0) {
payload_tree = proto_tree_add_subtree(tree, tvb, offset, rem_len, ett_zbee_zcl_part, NULL, "Payload");
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_PART_TRANSF_PART_FRAME:
dissect_zcl_part_trasfpartframe(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PART_RD_HANDSHAKE_PARAM:
dissect_zcl_part_rdhandshakeparam(tvb, pinfo, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PART_WR_HANDSHAKE_PARAM:
dissect_zcl_part_wrhandshakeparam(tvb, pinfo, payload_tree, &offset);
break;
default:
break;
}
}
}
else { /* ZBEE_ZCL_FCF_TO_CLIENT */
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_part_srv_tx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_part_srv_tx_cmd_id, tvb, offset, 1, cmd_id);
/* Check is this command has a payload, than add the payload tree */
rem_len = tvb_reported_length_remaining(tvb, ++offset);
if (rem_len > 0) {
payload_tree = proto_tree_add_subtree(tree, tvb, offset, rem_len, ett_zbee_zcl_part, NULL, "Payload");
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_PART_MULTI_ACK:
dissect_zcl_part_multiack(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PART_RD_HANDSHAKE_PARAM_RSP:
dissect_zcl_part_rdhandshakeparamrsp(tvb, pinfo, payload_tree, &offset);
break;
default:
break;
}
}
}
return tvb_captured_length(tvb);
} /*dissect_zbee_zcl_part*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_part_trasfpartframe
* DESCRIPTION
* This function manages the Trasfer Partition Frame payload
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* offset - pointer of buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void dissect_zcl_part_trasfpartframe(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint8 options;
guint16 u16len;
guint8 frame_len;
static const int * part_opt[] = {
&hf_zbee_zcl_part_opt_first_block,
&hf_zbee_zcl_part_opt_indic_len,
&hf_zbee_zcl_part_opt_res,
NULL
};
/* Retrieve "Fragmentation Options" field */
options = tvb_get_guint8(tvb, *offset);
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_part_opt, ett_zbee_zcl_part_fragm_options, part_opt, ENC_NA);
*offset += 1;
/* Retrieve "PartitionIndicator" field */
if ((options & ZBEE_ZCL_PART_OPT_INDIC_LEN) == 0)
{
/* 1-byte length */
u16len = (guint16)tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_part_part_indicator, tvb, *offset, 1, (u16len & 0xFF));
*offset += 1;
}
else {
/* 2-bytes length */
u16len = tvb_get_letohs(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_part_part_indicator, tvb, *offset, 2, u16len);
*offset += 2;
}
/* Retrieve PartitionedFrame length field */
frame_len = tvb_get_guint8(tvb, *offset); /* string length */
if (frame_len == ZBEE_ZCL_INVALID_STR_LENGTH)
frame_len = 0;
proto_tree_add_item(tree, hf_zbee_zcl_part_part_frame_len, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve "PartitionedFrame" field */
proto_tree_add_item(tree, hf_zbee_zcl_part_part_frame, tvb, *offset, frame_len, ENC_NA);
*offset += frame_len;
} /*dissect_zcl_part_trasfpartframe*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_part_rdhandshakeparam
* DESCRIPTION
* This function manages the ReadHandshakeParam payload
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* offset - offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_part_rdhandshakeparam(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint *offset)
{
/* Retrieve "Partitioned Cluster ID" field */
proto_tree_add_item(tree, hf_zbee_zcl_part_partitioned_cluster_id, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Dissect the attribute id list */
dissect_zcl_read_attr(tvb, pinfo, tree, offset, ZBEE_ZCL_CID_PARTITION);
} /*dissect_zcl_part_rdhandshakeparam*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_part_wrhandshakeparam
* DESCRIPTION
* This function manages the WriteAndShakeParam payload
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* offset - offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_part_wrhandshakeparam(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint *offset)
{
/* Retrieve "Partitioned Cluster ID" field */
proto_tree_add_item(tree, hf_zbee_zcl_part_partitioned_cluster_id, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Dissect the attributes list */
dissect_zcl_write_attr(tvb, pinfo, tree, offset, ZBEE_ZCL_CID_PARTITION);
} /*dissect_zcl_part_wrhandshakeparam*/
/* Management of Cluster specific commands sent by the server */
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_part_multiack
* DESCRIPTION
* This function manages the MultipleACK payload
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo, -
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* offset - offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_part_multiack(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint tvb_len = tvb_reported_length(tvb);
guint i = 0;
guint8 options;
guint16 first_frame_id;
guint16 nack_id;
static const int * ack_opts[] = {
&hf_zbee_zcl_part_ack_opt_nack_id_len,
&hf_zbee_zcl_part_ack_opt_res,
NULL
};
/* Retrieve "Ack Options" field */
options = tvb_get_guint8(tvb, *offset);
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_part_ack_opt, ett_zbee_zcl_part_ack_opts, ack_opts, ENC_NA);
*offset += 1;
/* Retrieve "First Frame ID" field */
if ((options & ZBEE_ZCL_PART_ACK_OPT_NACK_LEN) == 0)
{
/* 1-byte length */
first_frame_id = (guint16)tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_part_first_frame_id, tvb, *offset, 1, (first_frame_id & 0xFF));
*offset += 1;
}
else {
/* 2-bytes length */
first_frame_id = tvb_get_letohs(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_part_first_frame_id, tvb, *offset, 2, first_frame_id);
*offset += 2;
}
/* Dissect the nack id list */
while ( *offset < tvb_len && i < ZBEE_ZCL_PART_NUM_NACK_ID_ETT )
{
if ((options & ZBEE_ZCL_PART_ACK_OPT_NACK_LEN) == 0)
{
/* 1-byte length */
nack_id = (guint16)tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_part_nack_id, tvb, *offset, 1, (nack_id & 0xFF));
*offset += 1;
}
else {
/* 2-bytes length */
nack_id = tvb_get_letohs(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_part_nack_id, tvb, *offset, 2, nack_id);
*offset += 2;
}
i++;
}
} /*dissect_zcl_part_multiack*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_part_rdhandshakeparamrsp
* DESCRIPTION
* This function manages the ReadHandshakeParamResponse payload
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* offset - offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_part_rdhandshakeparamrsp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint *offset)
{
/* Retrieve "Partitioned Cluster ID" field */
proto_tree_add_item(tree, hf_zbee_zcl_part_partitioned_cluster_id, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Dissect the attributes list */
dissect_zcl_read_attr_resp(tvb, pinfo, tree, offset, ZBEE_ZCL_CID_PARTITION);
} /*dissect_zcl_part_rdhandshakeparamrsp*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_register_zbee_zcl_part
* DESCRIPTION
* this function is called by ZCL foundation dissector in order to decode
* specific cluster attributes data.
* PARAMETERS
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* guint *offset - pointer to buffer offset
* guint16 attr_id - attribute identifier
* guint data_type - attribute data type
* RETURNS
* none
*---------------------------------------------------------------
*/
void proto_register_zbee_zcl_part(void)
{
guint8 i, j;
static hf_register_info hf[] = {
{ &hf_zbee_zcl_part_attr_id,
{ "Attribute", "zbee_zcl_general.part.attr_id", FT_UINT16, BASE_HEX, VALS(zbee_zcl_part_attr_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_part_srv_tx_cmd_id,
{ "Command", "zbee_zcl_general.part.cmd.srv_tx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_part_srv_tx_cmd_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_part_srv_rx_cmd_id,
{ "Command", "zbee_zcl_general.part.cmd.srv_rx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_part_srv_rx_cmd_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_part_opt,
{ "Fragmentation Options", "zbee_zcl_general.part.opt", FT_UINT8, BASE_HEX,
NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_zcl_part_opt_first_block,
{ "First Block", "zbee_zcl_general.part.opt.first_block", FT_UINT8, BASE_HEX, NULL,
ZBEE_ZCL_PART_OPT_1_BLOCK, NULL, HFILL } },
{ &hf_zbee_zcl_part_opt_indic_len,
{ "Indicator length", "zbee_zcl_general.part.opt.indic_len", FT_UINT8, BASE_DEC, VALS(zbee_zcl_part_id_length_names),
ZBEE_ZCL_PART_OPT_INDIC_LEN, NULL, HFILL } },
{ &hf_zbee_zcl_part_opt_res,
{ "Reserved", "zbee_zcl_general.part.opt.res", FT_UINT8, BASE_HEX, NULL,
ZBEE_ZCL_PART_OPT_RESERVED, NULL, HFILL } },
{ &hf_zbee_zcl_part_first_frame_id,
{ "First Frame ID", "zbee_zcl_general.part.first_frame_id", FT_UINT16, BASE_DEC, NULL,
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_part_part_indicator,
{ "Partition Indicator", "zbee_zcl_general.part.part_indicator", FT_UINT16, BASE_DEC, NULL,
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_part_part_frame_len,
{ "Partition Frame Length", "zbee_zcl_general.part.part_frame_length", FT_UINT8, BASE_DEC, NULL,
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_part_part_frame,
{ "Partition Frame", "zbee_zcl_general.part.part_frame", FT_BYTES, SEP_COLON, NULL,
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_part_partitioned_cluster_id,
{ "Partitioned Cluster ID", "zbee_zcl_general.part.part_cluster_id", FT_UINT16, BASE_HEX, VALS(zbee_aps_cid_names),
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_part_ack_opt,
{ "Ack Options", "zbee_zcl_general.ack_opt.part", FT_UINT8, BASE_HEX,
NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_zcl_part_ack_opt_nack_id_len,
{ "Nack Id Length", "zbee_zcl_general.ack_opt.part.nack_id.len", FT_UINT8, BASE_HEX, VALS(zbee_zcl_part_id_length_names),
ZBEE_ZCL_PART_ACK_OPT_NACK_LEN, NULL, HFILL } },
{ &hf_zbee_zcl_part_ack_opt_res,
{ "Reserved", "zbee_zcl_general.part.ack_opt.reserved", FT_UINT8, BASE_HEX, NULL,
ZBEE_ZCL_PART_ACK_OPT_RESERVED, NULL, HFILL } },
{ &hf_zbee_zcl_part_nack_id,
{ "Nack Id", "zbee_zcl_general.part.nack_id", FT_UINT16, BASE_DEC, NULL,
0x00, NULL, HFILL } }
};
/* ZCL Partition subtrees */
gint *ett[ZBEE_ZCL_PART_NUM_ETT];
ett[0] = &ett_zbee_zcl_part;
ett[1] = &ett_zbee_zcl_part_fragm_options;
ett[2] = &ett_zbee_zcl_part_ack_opts;
/* initialize attribute subtree types */
for ( i = 0, j = ZBEE_ZCL_PART_NUM_GENERIC_ETT; i < ZBEE_ZCL_PART_NUM_NACK_ID_ETT; i++, j++) {
ett_zbee_zcl_part_nack_id_list[i] = -1;
ett[j] = &ett_zbee_zcl_part_nack_id_list[i];
}
for ( i = 0; i < ZBEE_ZCL_PART_NUM_ATTRS_ID_ETT; i++, j++) {
ett_zbee_zcl_part_attrs_id_list[i] = -1;
ett[j] = &ett_zbee_zcl_part_attrs_id_list[i];
}
/* Register ZigBee ZCL Partition protocol with Wireshark. */
proto_zbee_zcl_part = proto_register_protocol("ZigBee ZCL Partition", "ZCL Partition", ZBEE_PROTOABBREV_ZCL_PART);
proto_register_field_array(proto_zbee_zcl_part, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
/* Register the ZigBee ZCL Partition dissector. */
new_register_dissector(ZBEE_PROTOABBREV_ZCL_PART, dissect_zbee_zcl_part, proto_zbee_zcl_part);
} /* proto_register_zbee_zcl_part */
/*FUNCTION:------------------------------------------------------
* NAME
* proto_reg_handoff_zbee_zcl_part
* DESCRIPTION
* Registers the zigbee ZCL Partition cluster dissector with Wireshark.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void proto_reg_handoff_zbee_zcl_part(void)
{
dissector_handle_t part_handle;
/* Register our dissector with the ZigBee application dissectors. */
part_handle = find_dissector(ZBEE_PROTOABBREV_ZCL_PART);
dissector_add_uint("zbee.zcl.cluster", ZBEE_ZCL_CID_PARTITION, part_handle);
zbee_zcl_init_cluster( proto_zbee_zcl_part,
ett_zbee_zcl_part,
ZBEE_ZCL_CID_PARTITION,
hf_zbee_zcl_part_attr_id,
hf_zbee_zcl_part_srv_rx_cmd_id,
hf_zbee_zcl_part_srv_tx_cmd_id,
NULL
);
} /*proto_reg_handoff_zbee_zcl_part*/
/* ########################################################################## */
/* #### (0x0019) OTA UPGRADE CLUSTER ######################################## */
/* ########################################################################## */
/*************************/
/* Defines */
/*************************/
#define ZBEE_ZCL_OTA_NUM_GENERIC_ETT 3
#define ZBEE_ZCL_OTA_NUM_ETT (ZBEE_ZCL_OTA_NUM_GENERIC_ETT)
/* Attributes */
#define ZBEE_ZCL_ATTR_ID_OTA_UPGRADE_SERVER_ID 0x0000 /* Upgrade Served ID */
#define ZBEE_ZCL_ATTR_ID_OTA_FILE_OFFSET 0x0001 /* File Offset */
#define ZBEE_ZCL_ATTR_ID_OTA_CURRENT_FILE_VERSION 0x0002 /* Current File Version */
#define ZBEE_ZCL_ATTR_ID_OTA_CURRENT_ZB_STACK_VERSION 0x0003 /* Current ZigBee Stack Version */
#define ZBEE_ZCL_ATTR_ID_OTA_DOWNLOADED_FILE_VERSION 0x0004 /* Downloaded File Version */
#define ZBEE_ZCL_ATTR_ID_OTA_DOWNLOADED_ZB_STACK_VERSION 0x0005 /* Downloaded ZigBee Stack Version */
#define ZBEE_ZCL_ATTR_ID_OTA_IMAGE_UPGRADE_STATUS 0x0006 /* Image Upgrade Status */
#define ZBEE_ZCL_ATTR_ID_OTA_MANUFACTURER_ID 0x0007 /* Manufacturer ID */
#define ZBEE_ZCL_ATTR_ID_OTA_IMAGE_TYPE_ID 0x0008 /* Image Type ID */
#define ZBEE_ZCL_ATTR_ID_OTA_MIN_BLOCK_REQ_DELAY 0x0009 /* Minimum Block Request Delay */
/* Server Commands Generated */
#define ZBEE_ZCL_CMD_ID_OTA_IMAGE_NOTIFY 0x00 /* Image Notify */
#define ZBEE_ZCL_CMD_ID_OTA_QUERY_NEXT_IMAGE_RSP 0x02 /* Query Next Image Response */
#define ZBEE_ZCL_CMD_ID_OTA_IMAGE_BLOCK_RSP 0x05 /* Image Block Response */
#define ZBEE_ZCL_CMD_ID_OTA_UPGRADE_END_RSP 0x07 /* Upgrade End Response */
#define ZBEE_ZCL_CMD_ID_OTA_QUERY_SPEC_FILE_RSP 0x09 /* Query Specific File Response */
/* Server Commands Received */
#define ZBEE_ZCL_CMD_ID_OTA_QUERY_NEXT_IMAGE_REQ 0x01 /* Query Next Image Request */
#define ZBEE_ZCL_CMD_ID_OTA_IMAGE_BLOCK_REQ 0x03 /* Image Block Request */
#define ZBEE_ZCL_CMD_ID_OTA_IMAGE_PAGE_REQ 0x04 /* Image Page Request */
#define ZBEE_ZCL_CMD_ID_OTA_UPGRADE_END_REQ 0x06 /* Upgrade End Request */
#define ZBEE_ZCL_CMD_ID_OTA_QUERY_SPEC_FILE_REQ 0x08 /* Query Specific File Request */
/* Payload Type */
#define ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ 0x00 /* Query Jitter */
#define ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ_MC 0x01 /* Query Jitter and Manufacturer Code */
#define ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ_MC_IT 0x02 /* Query Jitter, Manufacturer Code and Image Type */
#define ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ_MC_IT_FV 0x03 /* Query Jitter, Manufacturer Code, Image Type and File Version */
/* Image Type */
#define ZBEE_ZCL_OTA_IMG_TYPE_MFR_LOW 0x0000 /* Manufacturer Specific (Low value) */
#define ZBEE_ZCL_OTA_IMG_TYPE_MFR_HIGH 0xffbf /* Manufacturer Specific (High value) */
#define ZBEE_ZCL_OTA_IMG_TYPE_SECURITY 0xffc0 /* Security Credential */
#define ZBEE_ZCL_OTA_IMG_TYPE_CONFIG 0xffc1 /* Configuration */
#define ZBEE_ZCL_OTA_IMG_TYPE_LOG 0xffc2 /* Log */
#define ZBEE_ZCL_OTA_IMG_TYPE_UNASSIGNED_LOW 0xffc3 /* Reserved: Unassigned (Low value) */
#define ZBEE_ZCL_OTA_IMG_TYPE_UNASSIGNED_HIGH 0xfffe /* Reserved: Unassigned (High value) */
#define ZBEE_ZCL_OTA_IMG_TYPE_WILD_CARD 0xffff /* Reserved: Wild Card */
/* ZigBee Stack Version */
#define ZBEE_ZCL_OTA_ZB_STACK_VER_2006 0x0000 /* ZigBee 2006 */
#define ZBEE_ZCL_OTA_ZB_STACK_VER_2007 0x0001 /* ZigBee 2007 */
#define ZBEE_ZCL_OTA_ZB_STACK_VER_PRO 0x0002 /* ZigBee Pro */
#define ZBEE_ZCL_OTA_ZB_STACK_VER_IP 0x0003 /* ZigBee IP */
#define ZBEE_ZCL_OTA_ZB_STACK_VER_RESERVED_LO 0x0004 /* Reserved Low */
#define ZBEE_ZCL_OTA_ZB_STACK_VER_RESERVED_HI 0xffff /* Reserved High */
/* Image Upgrade Status */
#define ZBEE_ZCL_OTA_STATUS_NORMAL 0x00 /* Normal */
#define ZBEE_ZCL_OTA_STATUS_DOWNLOAD_IN_PROGRESS 0x01 /* Download in progress */
#define ZBEE_ZCL_OTA_STATUS_DOWNLOAD_COMPLETE 0x02 /* Download complete */
#define ZBEE_ZCL_OTA_STATUS_WAITING_TO_UPGRADE 0x03 /* Waiting to upgrade */
#define ZBEE_ZCL_OTA_STATUS_COUNT_DOWN 0x04 /* Count down */
#define ZBEE_ZCL_OTA_STATUS_WAIT_FOR_MORE 0x05 /* Wait for more */
/* 0x06-0xff - Reserved */
/* File Version mask */
#define ZBEE_ZCL_OTA_FILE_VERS_APPL_RELEASE 0x000000FF /* Application Release */
#define ZBEE_ZCL_OTA_FILE_VERS_APPL_BUILD 0x0000FF00 /* Application Build */
#define ZBEE_ZCL_OTA_FILE_VERS_STACK_RELEASE 0x00FF0000 /* Stack Release */
#define ZBEE_ZCL_OTA_FILE_VERS_STACK_BUILD 0xFF000000 /* Stack Build */
/* Field Control bitmask field list */
#define ZBEE_ZCL_OTA_FIELD_CTRL_HW_VER_PRESENT 0x01 /* bit 0 */
#define ZBEE_ZCL_OTA_FIELD_CTRL_RESERVED 0xfe /* bit 1-7 */
#define ZBEE_ZCL_OTA_FIELD_CTRL_IEEE_ADDR_PRESENT 0x01 /* bit 0 - Request nodes IEEE address Present */
/* OTA Time */
#define ZBEE_ZCL_OTA_TIME_NOW 0x00000000 /* Now */
#define ZBEE_ZCL_OTA_TIME_UTC_LO 0x00000001 /* UTC Low Boundary */
#define ZBEE_ZCL_OTA_TIME_UTC_HI 0xfffffffe /* UTC High Boundary */
#define ZBEE_ZCL_OTA_TIME_WAIT 0xffffffff /* Wait for a Upgrade command (not used for RequesTime) */
/*************************/
/* Function Declarations */
/*************************/
void proto_register_zbee_zcl_ota(void);
void proto_reg_handoff_zbee_zcl_ota(void);
/*************************/
/* Global Variables */
/*************************/
/* Initialize the protocol and registered fields */
static int proto_zbee_zcl_ota = -1;
static int hf_zbee_zcl_ota_attr_id = -1;
static int hf_zbee_zcl_ota_srv_tx_cmd_id = -1;
static int hf_zbee_zcl_ota_srv_rx_cmd_id = -1;
static int hf_zbee_zcl_ota_image_upgrade_status = -1;
static int hf_zbee_zcl_ota_zb_stack_ver = -1;
static int hf_zbee_zcl_ota_file_offset = -1;
static int hf_zbee_zcl_ota_payload_type = -1;
static int hf_zbee_zcl_ota_query_jitter = -1;
static int hf_zbee_zcl_ota_manufacturer_code = -1;
static int hf_zbee_zcl_ota_image_type = -1;
static int hf_zbee_zcl_ota_file_version = -1;
static int hf_zbee_zcl_ota_file_version_appl_release = -1;
static int hf_zbee_zcl_ota_file_version_appl_build = -1;
static int hf_zbee_zcl_ota_file_version_stack_release = -1;
static int hf_zbee_zcl_ota_file_version_stack_build = -1;
static int hf_zbee_zcl_ota_field_ctrl = -1;
static int hf_zbee_zcl_ota_field_ctrl_hw_ver_present = -1;
static int hf_zbee_zcl_ota_field_ctrl_reserved = -1;
static int hf_zbee_zcl_ota_hw_version = -1;
static int hf_zbee_zcl_ota_status = -1;
static int hf_zbee_zcl_ota_image_size = -1;
static int hf_zbee_zcl_ota_max_data_size = -1;
static int hf_zbee_zcl_ota_req_node_addr = -1;
static int hf_zbee_zcl_ota_current_time = -1;
static int hf_zbee_zcl_ota_request_time = -1;
static int hf_zbee_zcl_ota_upgrade_time = -1;
static int hf_zbee_zcl_ota_data_size = -1;
static int hf_zbee_zcl_ota_image_data = -1;
static int hf_zbee_zcl_ota_page_size = -1;
static int hf_zbee_zcl_ota_rsp_spacing = -1;
/* Initialize the subtree pointers */
static gint ett_zbee_zcl_ota = -1;
static gint ett_zbee_zcl_ota_field_ctrl = -1;
static gint ett_zbee_zcl_ota_file_version = -1;
/* Attributes */
static const value_string zbee_zcl_ota_attr_names[] = {
{ ZBEE_ZCL_ATTR_ID_OTA_UPGRADE_SERVER_ID, "Upgrade Served ID" },
{ ZBEE_ZCL_ATTR_ID_OTA_FILE_OFFSET, "File Offset" },
{ ZBEE_ZCL_ATTR_ID_OTA_CURRENT_FILE_VERSION, "Current File Version" },
{ ZBEE_ZCL_ATTR_ID_OTA_CURRENT_ZB_STACK_VERSION, "Current ZigBee Stack Version" },
{ ZBEE_ZCL_ATTR_ID_OTA_DOWNLOADED_FILE_VERSION, "Downloaded File Version" },
{ ZBEE_ZCL_ATTR_ID_OTA_DOWNLOADED_ZB_STACK_VERSION, "Downloaded ZigBee Stack Version" },
{ ZBEE_ZCL_ATTR_ID_OTA_IMAGE_UPGRADE_STATUS, "Image Upgrade Status" },
{ ZBEE_ZCL_ATTR_ID_OTA_MANUFACTURER_ID, "Manufacturer ID" },
{ ZBEE_ZCL_ATTR_ID_OTA_IMAGE_TYPE_ID, "Image Type ID" },
{ ZBEE_ZCL_ATTR_ID_OTA_MIN_BLOCK_REQ_DELAY, "Minimum Block Request Delay" },
{ 0, NULL }
};
/* Server Commands Received */
static const value_string zbee_zcl_ota_srv_rx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_OTA_QUERY_NEXT_IMAGE_REQ, "Query Next Image Request" },
{ ZBEE_ZCL_CMD_ID_OTA_IMAGE_BLOCK_REQ, "Image Block Request" },
{ ZBEE_ZCL_CMD_ID_OTA_IMAGE_PAGE_REQ, "Image Page Request" },
{ ZBEE_ZCL_CMD_ID_OTA_UPGRADE_END_REQ, "Upgrade End Request" },
{ ZBEE_ZCL_CMD_ID_OTA_QUERY_SPEC_FILE_REQ, "Query Specific File Request" },
{ 0, NULL }
};
/* Server Commands Generated */
static const value_string zbee_zcl_ota_srv_tx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_OTA_IMAGE_NOTIFY, "Image Notify" },
{ ZBEE_ZCL_CMD_ID_OTA_QUERY_NEXT_IMAGE_RSP, "Query Next Image Response" },
{ ZBEE_ZCL_CMD_ID_OTA_IMAGE_BLOCK_RSP, "Image Block Response" },
{ ZBEE_ZCL_CMD_ID_OTA_UPGRADE_END_RSP, "Upgrade End Response" },
{ ZBEE_ZCL_CMD_ID_OTA_QUERY_SPEC_FILE_RSP, "Query Specific File Response" },
{ 0, NULL }
};
/* Payload Type */
static const value_string zbee_zcl_ota_paylaod_type_names[] = {
{ ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ, "Query Jitter" },
{ ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ_MC, "Query Jitter and Manufacturer Code" },
{ ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ_MC_IT, "Query Jitter, Manufacturer Code and Image Type" },
{ ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ_MC_IT_FV, "Query Jitter, Manufacturer Code, Image Type and File Version" },
{ 0, NULL }
};
/* Image Upgrade Status */
static const value_string zbee_zcl_ota_image_upgrade_attr_status_names[] = {
{ ZBEE_ZCL_OTA_STATUS_NORMAL, "Normal" },
{ ZBEE_ZCL_OTA_STATUS_DOWNLOAD_IN_PROGRESS, "Download in progress" },
{ ZBEE_ZCL_OTA_STATUS_DOWNLOAD_COMPLETE, "Download complete" },
{ ZBEE_ZCL_OTA_STATUS_WAITING_TO_UPGRADE, "Waiting to upgrade" },
{ ZBEE_ZCL_OTA_STATUS_COUNT_DOWN, "Count down" },
{ ZBEE_ZCL_OTA_STATUS_WAIT_FOR_MORE, "Wait for more" },
{ 0, NULL }
};
/* ZigBee Stack Version */
static const range_string zbee_zcl_ota_zb_stack_ver_names[] = {
{ ZBEE_ZCL_OTA_ZB_STACK_VER_2006, ZBEE_ZCL_OTA_ZB_STACK_VER_2006, "ZigBee 2006" },
{ ZBEE_ZCL_OTA_ZB_STACK_VER_2007, ZBEE_ZCL_OTA_ZB_STACK_VER_2007, "ZigBee 2007" },
{ ZBEE_ZCL_OTA_ZB_STACK_VER_PRO, ZBEE_ZCL_OTA_ZB_STACK_VER_PRO, "ZigBee Pro" },
{ ZBEE_ZCL_OTA_ZB_STACK_VER_IP, ZBEE_ZCL_OTA_ZB_STACK_VER_IP, "ZigBee IP" },
{ ZBEE_ZCL_OTA_ZB_STACK_VER_RESERVED_LO, ZBEE_ZCL_OTA_ZB_STACK_VER_RESERVED_HI, "Reserved" },
{ 0, 0, NULL },
};
/* Image Type */
static const range_string zbee_zcl_ota_image_type_names[] = {
{ZBEE_ZCL_OTA_IMG_TYPE_MFR_LOW, ZBEE_ZCL_OTA_IMG_TYPE_MFR_HIGH, "Manufacturer Specific" },
{ZBEE_ZCL_OTA_IMG_TYPE_SECURITY, ZBEE_ZCL_OTA_IMG_TYPE_SECURITY, "Security Credential" },
{ZBEE_ZCL_OTA_IMG_TYPE_CONFIG, ZBEE_ZCL_OTA_IMG_TYPE_CONFIG, "Configuration" },
{ZBEE_ZCL_OTA_IMG_TYPE_LOG, ZBEE_ZCL_OTA_IMG_TYPE_LOG, "Log" },
{ZBEE_ZCL_OTA_IMG_TYPE_UNASSIGNED_LOW, ZBEE_ZCL_OTA_IMG_TYPE_UNASSIGNED_HIGH, "Reserved: Unassigned" },
{ZBEE_ZCL_OTA_IMG_TYPE_WILD_CARD, ZBEE_ZCL_OTA_IMG_TYPE_WILD_CARD, "Reserved: Wild Card" },
{ 0, 0, NULL }
};
/*************************/
/* Function Bodies */
/*************************/
/*FUNCTION:------------------------------------------------------
* NAME
* decode_zcl_ota_curr_time
* DESCRIPTION
* this function decode the current time field
* PARAMETERS
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_zcl_ota_curr_time(gchar *s, guint32 value)
{
if (value == ZBEE_ZCL_OTA_TIME_NOW) {
g_snprintf(s, ITEM_LABEL_LENGTH, "Now");
}
else {
gchar *tmp;
value += ZBEE_ZCL_NSTIME_UTC_OFFSET;
tmp = abs_time_secs_to_str(NULL, value, ABSOLUTE_TIME_LOCAL, 1);
g_snprintf(s, ITEM_LABEL_LENGTH, "%s", tmp);
wmem_free(NULL, tmp);
}
return;
} /*decode_zcl_ota_curr_time*/
/*FUNCTION:------------------------------------------------------
* NAME
* decode_zcl_ota_req_time
* DESCRIPTION
* this function decode the request time field
* PARAMETERS
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_zcl_ota_req_time(gchar *s, guint32 value)
{
if (value == ZBEE_ZCL_OTA_TIME_WAIT) {
g_snprintf(s, ITEM_LABEL_LENGTH, "Wrong Value");
}
else {
/* offset from now */
gchar *tmp = time_secs_to_str(NULL, value);
g_snprintf(s, ITEM_LABEL_LENGTH, "%s from now", tmp);
wmem_free(NULL, tmp);
}
return;
} /*decode_zcl_ota_req_time*/
/*FUNCTION:------------------------------------------------------
* NAME
* decode_zcl_ota_upgr_time
* DESCRIPTION
* this function decode the upgrade time field
* PARAMETERS
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_zcl_ota_upgr_time(gchar *s, guint32 value)
{
if (value == ZBEE_ZCL_OTA_TIME_WAIT) {
g_snprintf(s, ITEM_LABEL_LENGTH, "Wait for upgrade command");
}
else {
/* offset from now */
gchar *tmp = time_secs_to_str(NULL, value);
g_snprintf(s, ITEM_LABEL_LENGTH, "%s from now", tmp);
wmem_free(NULL, tmp);
}
return;
} /*decode_zcl_ota_upgr_time*/
/*FUNCTION:------------------------------------------------------
* NAME
* decode_zcl_ota_size_in_bytes
* DESCRIPTION
* this function decodes size in bytes
* PARAMETERS
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_zcl_ota_size_in_bytes(gchar *s, guint32 value)
{
g_snprintf(s, ITEM_LABEL_LENGTH, "%d [Bytes]", value);
} /*decode_zcl_ota_size_in_bytes*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_file_version_field
* DESCRIPTION
* this function is called in order to decode "FileVersion" field,
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_file_version_field(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
static const int * file_version[] = {
&hf_zbee_zcl_ota_file_version_appl_release,
&hf_zbee_zcl_ota_file_version_appl_build,
&hf_zbee_zcl_ota_file_version_stack_release,
&hf_zbee_zcl_ota_file_version_stack_build,
NULL
};
/* 'File Version' field present, retrieves it */
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_ota_file_version, ett_zbee_zcl_ota_file_version, file_version, ENC_BIG_ENDIAN);
*offset += 4;
} /*dissect_zcl_ota_file_version_field*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_field_ctrl_field
* DESCRIPTION
* this function is called in order to decode "FileVersion" field,
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static guint8
dissect_zcl_ota_field_ctrl_field(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint8 field;
static const int * field_ctrl[] = {
&hf_zbee_zcl_ota_field_ctrl_hw_ver_present,
&hf_zbee_zcl_ota_field_ctrl_reserved,
NULL
};
/* Retrieve 'Field Control' field */
field = tvb_get_guint8(tvb, *offset);
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_ota_field_ctrl, ett_zbee_zcl_ota_field_ctrl, field_ctrl, ENC_BIG_ENDIAN);
*offset += 1;
return field;
} /*dissect_zcl_ota_field_ctrl_field*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_imagenotify
* DESCRIPTION
* this function is called in order to decode "ImageNotify",
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_imagenotify(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint8 payload_type;
/* Retrieve 'Payload type' field */
payload_type = tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_ota_payload_type, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve 'Query Jitter' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_query_jitter, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Check if there are optional fields */
if (payload_type >= ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ_MC) {
/* 'Manufacturer Code' field present, retrieves it */
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
}
if (payload_type >= ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ_MC_IT) {
/* 'Image Type' field present, retrieves it */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
}
if (payload_type >= ZBEE_ZCL_OTA_PAYLOAD_TYPE_QJ_MC_IT_FV) {
/* 'File Version' field present, retrieves it */
dissect_zcl_ota_file_version_field(tvb, tree, offset);
}
} /*dissect_zcl_ota_imagenotify*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_querynextimagereq
* DESCRIPTION
* this function is called in order to decode "QueryNextImageRequest",
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_querynextimagereq(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint8 field_ctrl;
/* Retrieve 'Field Control' field */
field_ctrl = dissect_zcl_ota_field_ctrl_field(tvb, tree, offset);
/* Retrieve 'Manufacturer Code' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'Image Type' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'File Version' field */
dissect_zcl_ota_file_version_field(tvb, tree, offset);
/* Check if there are optional fields */
if (field_ctrl & ZBEE_ZCL_OTA_FIELD_CTRL_HW_VER_PRESENT) {
/* 'Hardware Version' field present, retrieves it */
proto_tree_add_item(tree, hf_zbee_zcl_ota_hw_version, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
}
} /*dissect_zcl_ota_querynextimagereq*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_querynextimagersp
* DESCRIPTION
* this function is called in order to decode "QueryNextImageResponse",
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_querynextimagersp(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint8 status;
/* Retrieve 'Status' field */
status = tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_ota_status, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Check if there are optional fields */
if (status == ZBEE_ZCL_STAT_SUCCESS) {
/* Retrieve 'Manufacturer Code' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'Image Type' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'File Version' field */
dissect_zcl_ota_file_version_field(tvb, tree, offset);
/* Retrieve 'Image Size' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_size, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
}
} /*dissect_zcl_ota_querynextimagersp*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_imageblockreq
* DESCRIPTION
* this function is called in order to decode "ImageBlockRequest",
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_imageblockreq(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint8 field_ctrl;
/* Retrieve 'Field Control' field */
field_ctrl = dissect_zcl_ota_field_ctrl_field(tvb, tree, offset);
/* Retrieve 'Manufacturer Code' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'Image Type' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'File Version' field */
dissect_zcl_ota_file_version_field(tvb, tree, offset);
/* Retrieve 'File Offset' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_file_offset, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
/* Retrieve 'Maximum Data Size' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_max_data_size, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Check if there are optional fields */
if (field_ctrl & ZBEE_ZCL_OTA_FIELD_CTRL_IEEE_ADDR_PRESENT) {
/* 'Requerst Node Address' field present, retrieves it */
proto_tree_add_item(tree, hf_zbee_zcl_ota_req_node_addr, tvb, *offset, 8, ENC_LITTLE_ENDIAN);
*offset += 8;
}
} /*dissect_zcl_ota_imageblockreq*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_imagepagereq
* DESCRIPTION
* this function is called in order to decode "ImagePageRequest",
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_imagepagereq(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint8 field_ctrl;
/* Retrieve 'Field Control' field */
field_ctrl = dissect_zcl_ota_field_ctrl_field(tvb, tree, offset);
/* Retrieve 'Manufacturer Code' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'Image Type' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'File Version' field */
dissect_zcl_ota_file_version_field(tvb, tree, offset);
/* Retrieve 'File Offset' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_file_offset, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
/* Retrieve 'Maximum Data Size' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_max_data_size, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve 'Page Size' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_page_size, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'Response Spacing' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_rsp_spacing, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Check if there are optional fields */
if (field_ctrl & ZBEE_ZCL_OTA_FIELD_CTRL_IEEE_ADDR_PRESENT) {
/* 'Requerst Node Address' field present, retrieves it */
proto_tree_add_item(tree, hf_zbee_zcl_ota_req_node_addr, tvb, *offset, 8, ENC_LITTLE_ENDIAN);
*offset += 8;
}
} /*dissect_zcl_ota_imagepagereq*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_imageblockrsp
* DESCRIPTION
* this function is called in order to decode "ImageBlockResponse",
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_imageblockrsp(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint8 status;
guint8 data_size;
/* Retrieve 'Status' field */
status = tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_ota_status, tvb, *offset, 1, ENC_NA);
*offset += 1;
if (status == ZBEE_ZCL_STAT_SUCCESS) {
/* Retrieve 'Manufacturer Code' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'Image Type' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'File Version' field */
dissect_zcl_ota_file_version_field(tvb, tree, offset);
/* Retrieve 'File Offset' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_file_offset, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
/* Retrieve 'Data Size' field */
data_size = tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_ota_data_size, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve 'Image Data' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_data, tvb, *offset, data_size, ENC_NA);
*offset += data_size;
}
else if (status == ZBEE_ZCL_STAT_OTA_WAIT_FOR_DATA) {
/* Retrieve 'Current Time' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_current_time, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
/* Retrieve 'Request Time' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_request_time, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
}
else {
/* */
}
} /*dissect_zcl_ota_imageblockrsp*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_upgradeendreq
* DESCRIPTION
* this function is called in order to decode "UpgradeEndRequest",
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_upgradeendreq(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Retrieve 'Status' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_status, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve 'Manufacturer Code' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'Image Type' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'File Version' field */
dissect_zcl_ota_file_version_field(tvb, tree, offset);
} /*dissect_zcl_ota_upgradeendreq*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_upgradeendrsp
* DESCRIPTION
* this function is called in order to decode "UpgradeEndResponse",
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_upgradeendrsp(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Retrieve 'Manufacturer Code' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'Image Type' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'File Version' field */
dissect_zcl_ota_file_version_field(tvb, tree, offset);
/* Retrieve 'Current Time' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_current_time, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
/* Retrieve 'Upgrade Time' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_upgrade_time, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
} /*dissect_zcl_ota_upgradeendrsp*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_queryspecfilereq
* DESCRIPTION
* this function is called in order to decode "QuerySpecificFileRequest",
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_queryspecfilereq(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* 'Requerst Node Address' field present, retrieves it */
proto_tree_add_item(tree, hf_zbee_zcl_ota_req_node_addr, tvb, *offset, 8, ENC_LITTLE_ENDIAN);
*offset += 8;
/* Retrieve 'Manufacturer Code' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'Image Type' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'File Version' field */
dissect_zcl_ota_file_version_field(tvb, tree, offset);
/* Retrieve 'ZigBee Stack Version' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_zb_stack_ver, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
} /*dissect_zcl_ota_queryspecfilereq*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_queryspecfilersp
* DESCRIPTION
* this function is called in order to decode "QuerySpecificFileResponse",
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_queryspecfilersp(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint8 status;
/* Retrieve 'Status' field */
status = tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_ota_status, tvb, *offset, 1, ENC_NA);
*offset += 1;
if (status == ZBEE_ZCL_STAT_SUCCESS) {
/* Retrieve 'Manufacturer Code' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'Image Type' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve 'File Version' field */
dissect_zcl_ota_file_version_field(tvb, tree, offset);
/* Retrieve 'Image Size' field */
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_size, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
}
} /*dissect_zcl_ota_queryspecfilersp*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_ota_attr_data
* DESCRIPTION
* this function is called by ZCL foundation dissector in order to decode
* specific cluster attributes data.
* PARAMETERS
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* guint *offset - pointer to buffer offset
* guint16 attr_id - attribute identifier
* guint data_type - attribute data type
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_ota_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type)
{
/* Dissect attribute data type and data */
switch ( attr_id )
{
case ZBEE_ZCL_ATTR_ID_OTA_CURRENT_FILE_VERSION:
case ZBEE_ZCL_ATTR_ID_OTA_DOWNLOADED_FILE_VERSION:
dissect_zcl_ota_file_version_field(tvb, tree, offset);
break;
case ZBEE_ZCL_ATTR_ID_OTA_CURRENT_ZB_STACK_VERSION:
case ZBEE_ZCL_ATTR_ID_OTA_DOWNLOADED_ZB_STACK_VERSION:
proto_tree_add_item(tree, hf_zbee_zcl_ota_zb_stack_ver, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
break;
case ZBEE_ZCL_ATTR_ID_OTA_IMAGE_UPGRADE_STATUS:
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_upgrade_status, tvb, *offset, 1, ENC_NA);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_OTA_MANUFACTURER_ID:
proto_tree_add_item(tree, hf_zbee_zcl_ota_manufacturer_code, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
break;
case ZBEE_ZCL_ATTR_ID_OTA_IMAGE_TYPE_ID:
proto_tree_add_item(tree, hf_zbee_zcl_ota_image_type, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
break;
case ZBEE_ZCL_ATTR_ID_OTA_MIN_BLOCK_REQ_DELAY:
default:
dissect_zcl_attr_data(tvb, tree, offset, data_type);
break;
}
} /*dissect_zcl_ota_attr_data*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zbee_zcl_ota
* DESCRIPTION
* ZigBee ZCL OTA cluster dissector for wireshark.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* void *data - pointer to ZCL packet structure.
* RETURNS
* int - length of parsed data.
*---------------------------------------------------------------
*/
static int
dissect_zbee_zcl_ota(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
proto_tree *payload_tree;
zbee_zcl_packet *zcl;
guint offset = 0;
guint8 cmd_id;
gint rem_len;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
zcl = (zbee_zcl_packet *)data;
cmd_id = zcl->cmd_id;
/* Create a subtree for the ZCL Command frame, and add the command ID to it. */
if (zcl->direction == ZBEE_ZCL_FCF_TO_SERVER) {
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_ota_srv_rx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_ota_srv_rx_cmd_id, tvb, offset, 1, cmd_id);
/* Check is this command has a payload, than add the payload tree */
rem_len = tvb_reported_length_remaining(tvb, ++offset);
if (rem_len > 0) {
payload_tree = proto_tree_add_subtree(tree, tvb, offset, rem_len, ett_zbee_zcl_ota, NULL, "Payload");
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_OTA_QUERY_NEXT_IMAGE_REQ:
dissect_zcl_ota_querynextimagereq(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_OTA_IMAGE_BLOCK_REQ:
dissect_zcl_ota_imageblockreq(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_OTA_IMAGE_PAGE_REQ:
dissect_zcl_ota_imagepagereq(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_OTA_UPGRADE_END_REQ:
dissect_zcl_ota_upgradeendreq(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_OTA_QUERY_SPEC_FILE_REQ:
dissect_zcl_ota_queryspecfilereq(tvb, payload_tree, &offset);
break;
default:
break;
}
}
}
else { /* ZBEE_ZCL_FCF_TO_CLIENT */
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_ota_srv_tx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_ota_srv_tx_cmd_id, tvb, offset, 1, cmd_id);
/* Check is this command has a payload, than add the payload tree */
rem_len = tvb_reported_length_remaining(tvb, ++offset);
if (rem_len > 0) {
payload_tree = proto_tree_add_subtree(tree, tvb, offset, rem_len, ett_zbee_zcl_ota, NULL, "Payload");
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_OTA_IMAGE_NOTIFY:
dissect_zcl_ota_imagenotify(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_OTA_QUERY_NEXT_IMAGE_RSP:
dissect_zcl_ota_querynextimagersp(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_OTA_IMAGE_BLOCK_RSP:
dissect_zcl_ota_imageblockrsp(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_OTA_UPGRADE_END_RSP:
dissect_zcl_ota_upgradeendrsp(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_OTA_QUERY_SPEC_FILE_RSP:
dissect_zcl_ota_queryspecfilersp(tvb, payload_tree, &offset);
break;
default:
break;
}
}
}
return tvb_captured_length(tvb);
} /*dissect_zbee_zcl_ota*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_register_zbee_zcl_ota
* DESCRIPTION
* this function is called by ZCL foundation dissector in order to decode
* specific cluster attributes data.
* PARAMETERS
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* guint *offset - pointer to buffer offset
* guint16 attr_id - attribute identifier
* guint data_type - attribute data type
* RETURNS
* none
*---------------------------------------------------------------
*/
void proto_register_zbee_zcl_ota(void)
{
static hf_register_info hf[] = {
{ &hf_zbee_zcl_ota_attr_id,
{ "Attribute", "zbee_zcl_general.ota.attr_id", FT_UINT16, BASE_HEX, VALS(zbee_zcl_ota_attr_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_srv_tx_cmd_id,
{ "Command", "zbee_zcl_general.ota.cmd.srv_tx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_ota_srv_tx_cmd_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_srv_rx_cmd_id,
{ "Command", "zbee_zcl_general.ota.cmd.srv_rx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_ota_srv_rx_cmd_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_image_upgrade_status,
{ "Image Upgrade Status", "zbee_zcl_general.ota.status_attr", FT_UINT8, BASE_HEX, VALS(zbee_zcl_ota_image_upgrade_attr_status_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_zb_stack_ver,
{ "ZigBee Stack Version", "zbee_zcl_general.ota.zb_stack.ver", FT_UINT16, BASE_HEX | BASE_RANGE_STRING,
RVALS(zbee_zcl_ota_zb_stack_ver_names), 0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_payload_type,
{ "Payload Type", "zbee_zcl_general.ota.payload.type", FT_UINT8, BASE_HEX, VALS(zbee_zcl_ota_paylaod_type_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_query_jitter,
{ "Query Jitter", "zbee_zcl_general.ota.query_jitter", FT_UINT8, BASE_CUSTOM, CF_FUNC(decode_zcl_time_in_seconds),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_manufacturer_code,
{ "Manufacturer Code", "zbee_zcl_general.ota.manufacturer_code", FT_UINT16, BASE_HEX, VALS(zbee_mfr_code_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_image_type,
{ "Image Type", "zbee_zcl_general.ota.image.type", FT_UINT16, BASE_HEX | BASE_RANGE_STRING,
RVALS(zbee_zcl_ota_image_type_names), 0x0, NULL, HFILL } },
/* Begin FileVersion fields */
{ &hf_zbee_zcl_ota_file_version,
{ "File Version", "zbee_zcl_general.ota.file.version", FT_UINT32, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_file_version_appl_release,
{ "Application Release", "zbee_zcl_general.ota.file.version.appl.release", FT_UINT32, BASE_DEC, NULL,
ZBEE_ZCL_OTA_FILE_VERS_APPL_RELEASE, NULL, HFILL } },
{ &hf_zbee_zcl_ota_file_version_appl_build,
{ "Application Build", "zbee_zcl_general.ota.file.version.appl.build", FT_UINT32, BASE_DEC, NULL,
ZBEE_ZCL_OTA_FILE_VERS_APPL_BUILD, NULL, HFILL } },
{ &hf_zbee_zcl_ota_file_version_stack_release,
{ "Stack Release", "zbee_zcl_general.ota.file.version.stack.release", FT_UINT32, BASE_DEC, NULL,
ZBEE_ZCL_OTA_FILE_VERS_STACK_RELEASE, NULL, HFILL } },
{ &hf_zbee_zcl_ota_file_version_stack_build,
{ "Stack Build", "zbee_zcl_general.ota.file.version.stack.build", FT_UINT32, BASE_DEC, NULL,
ZBEE_ZCL_OTA_FILE_VERS_STACK_BUILD, NULL, HFILL } },
/* End FileVersion fields */
/* Begin FieldControl fields */
{ &hf_zbee_zcl_ota_field_ctrl,
{ "Field Control", "zbee_zcl_general.ota.field_ctrl",
FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_field_ctrl_hw_ver_present,
{ "Hardware Version", "zbee_zcl_general.ota.field_ctrl_hw_ver_present",
FT_BOOLEAN, 8, TFS(&tfs_present_not_present), ZBEE_ZCL_OTA_FIELD_CTRL_HW_VER_PRESENT, NULL, HFILL } },
{ &hf_zbee_zcl_ota_field_ctrl_reserved,
{ "Reserved", "zbee_zcl_general.ota.field_ctrl_reserved", FT_UINT8, BASE_HEX, NULL,
ZBEE_ZCL_OTA_FIELD_CTRL_RESERVED, NULL, HFILL } },
/* End FieldControl fields */
{ &hf_zbee_zcl_ota_hw_version,
{ "Hardware Version", "zbee_zcl_general.ota.hw_ver", FT_UINT16, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_status,
{ "Status", "zbee_zcl_general.ota.status", FT_UINT8, BASE_HEX, VALS(zbee_zcl_status_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_image_size,
{ "Image Size", "zbee_zcl_general.ota.image.size", FT_UINT32, BASE_CUSTOM, CF_FUNC(decode_zcl_ota_size_in_bytes),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_file_offset,
{ "File Offset", "zbee_zcl_general.ota.file.offset", FT_UINT32, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_max_data_size,
{ "Max Data Size", "zbee_zcl_general.ota.max_data_size", FT_UINT8, BASE_DEC, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_req_node_addr,
{ "Ieee Address", "zbee_zcl_general.ota.ieee_addr", FT_UINT64, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_page_size,
{ "Page Size", "zbee_zcl_general.ota.page.size", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_zcl_ota_size_in_bytes),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_rsp_spacing,
{ "Response Spacing", "zbee_zcl_general.ota.rsp_spacing", FT_UINT16, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_ota_current_time,
{ "Current Time", "zbee_zcl_general.ota.current_time", FT_UINT32, BASE_CUSTOM, CF_FUNC(decode_zcl_ota_curr_time),
0x0, NULL, HFILL }},
{ &hf_zbee_zcl_ota_request_time,
{ "Request Time", "zbee_zcl_general.ota.request_time", FT_UINT32, BASE_CUSTOM, CF_FUNC(decode_zcl_ota_req_time),
0x0, NULL, HFILL }},
{ &hf_zbee_zcl_ota_upgrade_time,
{ "Upgrade Time", "zbee_zcl_general.ota.upgrade_time", FT_UINT32, BASE_CUSTOM, CF_FUNC(decode_zcl_ota_upgr_time),
0x0, NULL, HFILL }},
{ &hf_zbee_zcl_ota_data_size,
{ "Data Size", "zbee_zcl_general.ota.data_size", FT_UINT8, BASE_DEC, NULL,
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_ota_image_data,
{ "Image Data", "zbee_zcl_general.ota.image.data", FT_BYTES, SEP_COLON, NULL,
0x00, NULL, HFILL } }
};
/* ZCL OTA subtrees */
gint *ett[ZBEE_ZCL_OTA_NUM_ETT];
ett[0] = &ett_zbee_zcl_ota;
ett[1] = &ett_zbee_zcl_ota_field_ctrl;
ett[2] = &ett_zbee_zcl_ota_file_version;
/* Register ZigBee ZCL Ota protocol with Wireshark. */
proto_zbee_zcl_ota = proto_register_protocol("ZigBee ZCL OTA", "ZCL OTA", ZBEE_PROTOABBREV_ZCL_OTA);
proto_register_field_array(proto_zbee_zcl_ota, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
/* Register the ZigBee ZCL OTA dissector. */
new_register_dissector(ZBEE_PROTOABBREV_ZCL_OTA, dissect_zbee_zcl_ota, proto_zbee_zcl_ota);
} /* proto_register_zbee_zcl_ota */
/*FUNCTION:------------------------------------------------------
* NAME
* proto_reg_handoff_zbee_zcl_ota
* DESCRIPTION
* Registers the zigbee ZCL OTA cluster dissector with Wireshark.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void proto_reg_handoff_zbee_zcl_ota(void)
{
dissector_handle_t ota_handle;
/* Register our dissector with the ZigBee application dissectors. */
ota_handle = find_dissector(ZBEE_PROTOABBREV_ZCL_OTA);
dissector_add_uint("zbee.zcl.cluster", ZBEE_ZCL_CID_OTA_UPGRADE, ota_handle);
zbee_zcl_init_cluster( proto_zbee_zcl_ota,
ett_zbee_zcl_ota,
ZBEE_ZCL_CID_OTA_UPGRADE,
hf_zbee_zcl_ota_attr_id,
hf_zbee_zcl_ota_srv_rx_cmd_id,
hf_zbee_zcl_ota_srv_tx_cmd_id,
(zbee_zcl_fn_attr_data)dissect_zcl_ota_attr_data
);
} /*proto_reg_handoff_zbee_zcl_ota*/
/* ########################################################################## */
/* #### (0x001A) POWER PROFILE CLUSTER ###################################### */
/* ########################################################################## */
/*************************/
/* Defines */
/*************************/
#define ZBEE_ZCL_PWR_PROF_NUM_GENERIC_ETT 4
#define ZBEE_ZCL_PWR_PROF_NUM_PWR_PROF_ETT 5
#define ZBEE_ZCL_PWR_PROF_NUM_EN_PHS_ETT 16
#define ZBEE_ZCL_PWR_PROF_NUM_ETT (ZBEE_ZCL_PWR_PROF_NUM_GENERIC_ETT + \
ZBEE_ZCL_PWR_PROF_NUM_PWR_PROF_ETT + \
ZBEE_ZCL_PWR_PROF_NUM_EN_PHS_ETT)
/* Attributes */
#define ZBEE_ZCL_ATTR_ID_PWR_PROF_TOT_PROF_NUM 0x0000 /* Total Profile Number */
#define ZBEE_ZCL_ATTR_ID_PWR_PROF_MULTIPLE_SCHED 0x0001 /* Multiple Schedule */
#define ZBEE_ZCL_ATTR_ID_PWR_PROF_ENERGY_FORMAT 0x0002 /* Energy Formatting */
#define ZBEE_ZCL_ATTR_ID_PWR_PROF_ENERGY_REMOTE 0x0003 /* Energy Remote */
#define ZBEE_ZCL_ATTR_ID_PWR_PROF_SCHED_MODE 0x0004 /* Schedule Mode */
/* Server Commands Received */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_REQ 0x00 /* Power Profile Request */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_STATE_REQ 0x01 /* Power Profile State Request */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE_RSP 0x02 /* Get Power Profile Price Response */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_GET_OVERALL_SCHED_PRICE_RSP 0x03 /* Get Overall Schedule Price Response */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_NOTIF 0x04 /* Energy Phases Schedule Notification */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_RSP 0x05 /* Energy Phases Schedule Response */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_SCHED_CONSTRS_REQ 0x06 /* Power Profile Schedule Constraints Request */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_STATE_REQ 0x07 /* Energy Phases Schedule State Request */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE_EXT_RSP 0x08 /* Get Power Profile Price Extended Response */
/* Server Commands Generated */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_NOTIF 0x00 /* Power Profile Notification */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_RSP 0x01 /* Power Profile Response */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_STATE_RSP 0x02 /* Power Profile State Response */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE 0x03 /* Get Power Profile Price */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_STATE_NOTIF 0x04 /* Power Profile State Notification */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_GET_OVERALL_SCHED_PRICE 0x05 /* Get Overall Schedule Price */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_REQ 0x06 /* Energy Phases Schedule Request */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_STATE_RSP 0x07 /* Energy Phases Schedule State Response */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_STATE_NOITIF 0x08 /* Energy Phases Schedule State Notification */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_SCHED_CONSTRS_NOTIF 0x09 /* Power Profile Schedule Constraints Notification */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_SCHED_CONSTRS_RSP 0x0A /* Power Profile Schedule Constraints Response */
#define ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE_EXT 0x0B /* Get Power Profile Price Extended */
/* Power Profile StateId */
#define ZBEE_ZCL_PWR_PROF_STATE_ID_PWR_PROF_IDLE 0x00 /* Power Profile Idle */
#define ZBEE_ZCL_PWR_PROF_STATE_ID_PWR_PROF_PROGRAMMED 0x01 /* Power Profile Programmed */
#define ZBEE_ZCL_PWR_PROF_STATE_ID_EN_PH_RUNNING 0x03 /* Energy Phase Running */
#define ZBEE_ZCL_PWR_PROF_STATE_ID_EN_PH_PAUSE 0x04 /* Energy Phase Pause */
#define ZBEE_ZCL_PWR_PROF_STATE_ID_EN_PH_WAITING_TO_START 0x05 /* Energy Phase Waiting to Start */
#define ZBEE_ZCL_PWR_PROF_STATE_ID_EN_PH_WAITING_PAUSED 0x06 /* Energy Phase Waiting Pause */
#define ZBEE_ZCL_PWR_PROF_STATE_ID_PWR_PROF_ENDED 0x07 /* Power Profile Ended */
/* Energy Formatting bitmask field list */
#define ZBEE_ZCL_OPT_PWRPROF_NUM_R_DIGIT 0x07 /* bits 0..2 */
#define ZBEE_ZCL_OPT_PWRPROF_NUM_L_DIGIT 0x78 /* bits 3..6 */
#define ZBEE_ZCL_OPT_PWRPROF_NO_LEADING_ZERO 0x80 /* bit 7 */
/* Schedule Mode bitmask field list */
#define ZBEE_ZCL_OPT_PWRPROF_SCHED_CHEAPEST 0x01 /* bit 0 */
#define ZBEE_ZCL_OPT_PWRPROF_SCHED_GREENEST 0x02 /* bit 1 */
#define ZBEE_ZCL_OPT_PWRPROF_SCHED_RESERVED 0xfc /* bits 2..7 */
/* Options bitmask field list */
#define ZBEE_ZCL_OPT_PWRPROF_STIME_PRESENT 0x01 /* bit 0 */
#define ZBEE_ZCL_OPT_PWRPROF_RESERVED 0xfe /* bits 1..7 */
/*************************/
/* Function Declarations */
/*************************/
void proto_register_zbee_zcl_pwr_prof(void);
void proto_reg_handoff_zbee_zcl_pwr_prof(void);
/* Command Dissector Helpers */
static void dissect_zcl_pwr_prof_pwrprofreq (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_pwr_prof_getpwrprofpricersp (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_pwr_prof_getoverallschedpricersp (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_pwr_prof_enphsschednotif (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_energy_phase (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_pwr_prof_pwrprofnotif (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_power_profile (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_pwr_prof_pwrprofstatersp (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_pwr_prof_pwrprofschedcontrsnotif (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_pwr_prof_pwrprofpriceext (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_pwr_prof_attr_data (proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type);
/* Private functions prototype */
static void decode_power_profile_id (gchar *s, guint8 id);
static void decode_price_in_cents (gchar *s, guint32 value);
static void decode_power_in_watt (gchar *s, guint16 value);
static void decode_energy (gchar *s, guint16 value);
/*************************/
/* Global Variables */
/*************************/
/* Initialize the protocol and registered fields */
static int proto_zbee_zcl_pwr_prof = -1;
static int hf_zbee_zcl_pwr_prof_attr_id = -1;
static int hf_zbee_zcl_pwr_prof_tot_prof_num = -1;
static int hf_zbee_zcl_pwr_prof_multiple_sched = -1;
static int hf_zbee_zcl_pwr_prof_energy_format = -1;
static int hf_zbee_zcl_pwr_prof_energy_format_rdigit = -1;
static int hf_zbee_zcl_pwr_prof_energy_format_ldigit = -1;
static int hf_zbee_zcl_pwr_prof_energy_format_noleadingzero = -1;
static int hf_zbee_zcl_pwr_prof_energy_remote = -1;
static int hf_zbee_zcl_pwr_prof_sched_mode = -1;
static int hf_zbee_zcl_pwr_prof_sched_mode_cheapest = -1;
static int hf_zbee_zcl_pwr_prof_sched_mode_greenest = -1;
static int hf_zbee_zcl_pwr_prof_sched_mode_reserved = -1;
static int hf_zbee_zcl_pwr_prof_srv_tx_cmd_id = -1;
static int hf_zbee_zcl_pwr_prof_srv_rx_cmd_id = -1;
static int hf_zbee_zcl_pwr_prof_pwr_prof_id = -1;
static int hf_zbee_zcl_pwr_prof_currency = -1;
static int hf_zbee_zcl_pwr_prof_price = -1;
static int hf_zbee_zcl_pwr_prof_price_trailing_digit = -1;
static int hf_zbee_zcl_pwr_prof_num_of_sched_phases = -1;
static int hf_zbee_zcl_pwr_prof_scheduled_time = -1;
static int hf_zbee_zcl_pwr_prof_pwr_prof_count = -1;
static int hf_zbee_zcl_pwr_prof_num_of_trans_phases = -1;
static int hf_zbee_zcl_pwr_prof_energy_phase_id = -1;
static int hf_zbee_zcl_pwr_prof_macro_phase_id = -1;
static int hf_zbee_zcl_pwr_prof_expect_duration = -1;
static int hf_zbee_zcl_pwr_prof_peak_power = -1;
static int hf_zbee_zcl_pwr_prof_energy = -1;
static int hf_zbee_zcl_pwr_prof_max_active_delay = -1;
static int hf_zbee_zcl_pwr_prof_pwr_prof_rem_ctrl = -1;
static int hf_zbee_zcl_pwr_prof_pwr_prof_state = -1;
static int hf_zbee_zcl_pwr_prof_start_after = -1;
static int hf_zbee_zcl_pwr_prof_stop_before = -1;
static int hf_zbee_zcl_pwr_prof_options = -1;
static int hf_zbee_zcl_pwr_prof_options_01 = -1;
static int hf_zbee_zcl_pwr_prof_options_res = -1;
static int hf_zbee_zcl_pwr_prof_pwr_prof_stime = -1;
/* Initialize the subtree pointers */
static gint ett_zbee_zcl_pwr_prof = -1;
static gint ett_zbee_zcl_pwr_prof_options = -1;
static gint ett_zbee_zcl_pwr_prof_en_format = -1;
static gint ett_zbee_zcl_pwr_prof_sched_mode = -1;
static gint ett_zbee_zcl_pwr_prof_pwrprofiles[ZBEE_ZCL_PWR_PROF_NUM_PWR_PROF_ETT];
static gint ett_zbee_zcl_pwr_prof_enphases[ZBEE_ZCL_PWR_PROF_NUM_EN_PHS_ETT];
/* Attributes */
static const value_string zbee_zcl_pwr_prof_attr_names[] = {
{ ZBEE_ZCL_ATTR_ID_PWR_PROF_TOT_PROF_NUM, "Total Profile Number" },
{ ZBEE_ZCL_ATTR_ID_PWR_PROF_MULTIPLE_SCHED, "Multiple Scheduling" },
{ ZBEE_ZCL_ATTR_ID_PWR_PROF_ENERGY_FORMAT, "Energy Formatting" },
{ ZBEE_ZCL_ATTR_ID_PWR_PROF_ENERGY_REMOTE, "Energy Remote" },
{ ZBEE_ZCL_ATTR_ID_PWR_PROF_SCHED_MODE, "Schedule Mode" },
{ 0, NULL }
};
/* Server Commands Received */
static const value_string zbee_zcl_pwr_prof_srv_rx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_REQ, "Power Profile Request" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_STATE_REQ, "Power Profile State Request" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE_RSP, "Get Power Profile Price Response" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_GET_OVERALL_SCHED_PRICE_RSP, "Get Overall Schedule Price Response" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_NOTIF, "Energy Phases Schedule Notification" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_RSP, "Energy Phases Schedule Response" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_SCHED_CONSTRS_REQ, "Power Profile Schedule Constraints Request" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_STATE_REQ, "Energy Phases Schedule State Request" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE_EXT_RSP, "Get Power Profile Price Extended Response" },
{ 0, NULL }
};
/* Server Commands Generated */
static const value_string zbee_zcl_pwr_prof_srv_tx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_NOTIF, "Power Profile Notification" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_RSP, "Power Profile Response" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_STATE_RSP, "Power Profile State Response" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE, "Get Power Profile Price" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_STATE_NOTIF, "Power Profile State Notification" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_GET_OVERALL_SCHED_PRICE, "Get Overall Schedule Price" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_REQ, "Energy Phases Schedule Request" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_STATE_RSP, "Energy Phases Schedule State Response" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_STATE_NOITIF, "Energy Phases Schedule State Notification" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_SCHED_CONSTRS_NOTIF, "Power Profile Schedule Constraints Notification" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_SCHED_CONSTRS_RSP, "Power Profile Schedule Constraints Response" },
{ ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE_EXT, "Get Power Profile Price Extended" },
{ 0, NULL }
};
/* Currencies (values defined by ISO 4217) */
static const value_string zbee_zcl_currecy_names[] = {
{ 0x03D2, "EUR" },
{ 0x033A, "GBP" },
{ 0x0348, "USD" },
{ 0, NULL }
};
/* Power Profile State */
static const value_string zbee_zcl_pwr_prof_state_names[] = {
{ ZBEE_ZCL_PWR_PROF_STATE_ID_PWR_PROF_IDLE, "Power Profile Idle" },
{ ZBEE_ZCL_PWR_PROF_STATE_ID_PWR_PROF_PROGRAMMED, "Power Profile Programmed" },
{ ZBEE_ZCL_PWR_PROF_STATE_ID_EN_PH_RUNNING, "Energy Phase Running" },
{ ZBEE_ZCL_PWR_PROF_STATE_ID_EN_PH_PAUSE, "Energy Phase Pause" },
{ ZBEE_ZCL_PWR_PROF_STATE_ID_EN_PH_WAITING_TO_START, "Energy Phase Waiting to Start" },
{ ZBEE_ZCL_PWR_PROF_STATE_ID_EN_PH_WAITING_PAUSED, "Energy Phase Waiting Paused" },
{ ZBEE_ZCL_PWR_PROF_STATE_ID_PWR_PROF_ENDED, "Power Profile Ended" },
{ 0, NULL }
};
/*************************/
/* Function Bodies */
/*************************/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zbee_zcl_pwr_prof
* DESCRIPTION
* ZigBee ZCL Power Profile cluster dissector for wireshark.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* void *data - pointer to ZCL packet structure.
* RETURNS
* int - length of parsed data.
*---------------------------------------------------------------
*/
static int
dissect_zbee_zcl_pwr_prof (tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
proto_tree *payload_tree;
zbee_zcl_packet *zcl;
guint offset = 0;
guint8 cmd_id;
gint rem_len;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
zcl = (zbee_zcl_packet *)data;
cmd_id = zcl->cmd_id;
/* Create a subtree for the ZCL Command frame, and add the command ID to it. */
if (zcl->direction == ZBEE_ZCL_FCF_TO_SERVER) {
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_pwr_prof_srv_rx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_srv_rx_cmd_id, tvb, offset, 1, cmd_id);
/* Check is this command has a payload, than add the payload tree */
rem_len = tvb_reported_length_remaining(tvb, ++offset);
if (rem_len > 0) {
payload_tree = proto_tree_add_subtree(tree, tvb, offset, rem_len, ett_zbee_zcl_pwr_prof, NULL, "Payload");
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_REQ:
case ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_SCHED_CONSTRS_REQ:
case ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_STATE_REQ:
dissect_zcl_pwr_prof_pwrprofreq(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_STATE_REQ:
/* No payload */
break;
case ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE_RSP:
case ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE_EXT_RSP:
dissect_zcl_pwr_prof_getpwrprofpricersp(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PWR_PROF_GET_OVERALL_SCHED_PRICE_RSP:
dissect_zcl_pwr_prof_getoverallschedpricersp(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_NOTIF:
case ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_RSP:
dissect_zcl_pwr_prof_enphsschednotif(tvb, payload_tree, &offset);
break;
default:
break;
}
}
}
else { /* ZBEE_ZCL_FCF_TO_CLIENT */
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_pwr_prof_srv_tx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_srv_tx_cmd_id, tvb, offset, 1, cmd_id);
/* Check is this command has a payload, than add the payload tree */
rem_len = tvb_reported_length_remaining(tvb, ++offset);
if (rem_len > 0) {
payload_tree = proto_tree_add_subtree(tree, tvb, offset, rem_len, ett_zbee_zcl_pwr_prof, NULL, "Payload");
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_NOTIF:
case ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_RSP:
dissect_zcl_pwr_prof_pwrprofnotif(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_STATE_RSP:
case ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_STATE_NOTIF:
dissect_zcl_pwr_prof_pwrprofstatersp(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PWR_PROF_GET_OVERALL_SCHED_PRICE:
/* no payload */
break;
case ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_STATE_RSP:
case ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_STATE_NOITIF:
dissect_zcl_pwr_prof_enphsschednotif(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE:
case ZBEE_ZCL_CMD_ID_PWR_PROF_ENERGY_PHASES_SCHED_REQ:
dissect_zcl_pwr_prof_pwrprofreq(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_SCHED_CONSTRS_NOTIF:
case ZBEE_ZCL_CMD_ID_PWR_PROF_PWR_PROF_SCHED_CONSTRS_RSP:
dissect_zcl_pwr_prof_pwrprofschedcontrsnotif(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_PWR_PROF_GET_PWR_PROF_PRICE_EXT:
dissect_zcl_pwr_prof_pwrprofpriceext(tvb, payload_tree, &offset);
break;
default:
break;
}
}
}
return tvb_captured_length(tvb);
} /*dissect_zbee_zcl_pwr_prof*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_pwr_prof_pwrprofreq
* DESCRIPTION
* this function is called in order to decode "PowerProfileRequest",
* "PowerProfileScheduleConstraintsRequest", "EnergyPhasesScheduleStateRequest",
* "GetPowerProfilePrice" and "EnergyPhasesScheduleRequest" payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_pwr_prof_pwrprofreq(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Retrieve "Power Profile Id" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
} /*dissect_zcl_pwr_prof_pwrprofreq*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_pwr_prof_getpwrprofpricersp
* DESCRIPTION
* this function is called in order to decode "GetPowerProfilePriceResponse"
* and "PowerProfilePriceExtendedResponse" payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_pwr_prof_getpwrprofpricersp(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Retrieve "Power Profile Id" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve "Currency" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_currency, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve "Price" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_price, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
/* Retrieve "Price Trailing Digit" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_price_trailing_digit, tvb, *offset, 1, ENC_NA);
*offset += 1;
} /*dissect_zcl_pwr_prof_getpwrprofpricersp*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_pwr_prof_getoverallschedpricersp
* DESCRIPTION
* this function is called in order to decode "GetOverallSchedulePriceResponse"
* payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_pwr_prof_getoverallschedpricersp(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Retrieve "Currency" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_currency, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve "Price" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_price, tvb, *offset, 4, ENC_LITTLE_ENDIAN);
*offset += 4;
/* Retrieve "Price Trailing Digit" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_price_trailing_digit, tvb, *offset, 1, ENC_NA);
*offset += 1;
} /*dissect_zcl_pwr_prof_getoverallschedpricersp*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_sched_energy_phase
* DESCRIPTION
* this function is called in order to decode "ScheduledEnergyPhases"
* element.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_sched_energy_phase(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Energy Phase ID */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_energy_phase_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Scheduled Time */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_scheduled_time, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
} /*dissect_zcl_sched_energy_phase*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_pwr_prof_enphsschednotif
* DESCRIPTION
* this function is called in order to decode "EnergyPhasesScheduleNotification"
* and "EnergyPhasesScheduleResoponse" payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_pwr_prof_enphsschednotif(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
proto_tree *sub_tree = NULL;
guint i;
guint8 num_of_sched_phases;
/* Retrieve "Power Profile Id" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve "Number of Scheduled Phases" field */
num_of_sched_phases = tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_num_of_sched_phases, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Scheduled Energy Phases decoding */
for (i=0 ; i<num_of_sched_phases ; i++) {
/* Create subtree */
sub_tree = proto_tree_add_subtree_format(tree, tvb, *offset, 1,
ett_zbee_zcl_pwr_prof_enphases[i], NULL, "Energy Phase #%u", i);
dissect_zcl_sched_energy_phase(tvb, sub_tree, offset);
}
} /*dissect_zcl_pwr_prof_enphsschednotif*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_energy_phase
* DESCRIPTION
* this function is called in order to decode "EnergyPhases"
* element.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_energy_phase(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_energy_phase_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_macro_phase_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_expect_duration, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_peak_power, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_energy, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_max_active_delay, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
} /*dissect_zcl_energy_phase*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_pwr_prof_pwrprofnotif
* DESCRIPTION
* this function is called in order to decode "PowerProfileNotification"
* and "PowerProfileResponse" payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_pwr_prof_pwrprofnotif(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
proto_tree *sub_tree = NULL;
guint i;
guint8 total_profile_number;
guint8 num_of_transferred_phases;
/* Retrieve "Total Profile Number" field */
total_profile_number = tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_tot_prof_num, tvb, *offset, 1, ENC_NA);
*offset += 1;
if ( total_profile_number != 0 ) {
/* Retrieve "Power Profile Id" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve "Number of Transferred Phases" field */
num_of_transferred_phases = tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_num_of_trans_phases, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Energy Phases decoding */
for ( i=0 ; i<num_of_transferred_phases ; i++) {
/* Create subtree */
sub_tree = proto_tree_add_subtree_format(tree, tvb, *offset, 1,
ett_zbee_zcl_pwr_prof_enphases[i], NULL, "Energy Phase #%u", i);
dissect_zcl_energy_phase(tvb, sub_tree, offset);
}
}
}
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_power_profile
* DESCRIPTION
* this function is called in order to decode "PowerProfile"
* element.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_power_profile(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Power Profile Id */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Energy Phase Id */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_energy_phase_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Power Profile Remote Control */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_rem_ctrl, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Power Profile State */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_state, tvb, *offset, 1, ENC_NA);
*offset += 1;
} /*dissect_zcl_power_profile*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_pwr_prof_pwrprofstatersp
* DESCRIPTION
* this function is called in order to decode "PowerProfileStateResponse"
* and "PowerProfileStateNotification" payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_pwr_prof_pwrprofstatersp(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
proto_tree *sub_tree = NULL;
guint i;
guint8 power_profile_count;
/* Retrieve "Total Profile Number" field */
power_profile_count = MIN(tvb_get_guint8(tvb, *offset), ZBEE_ZCL_PWR_PROF_NUM_PWR_PROF_ETT);
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_count, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Energy Phases decoding */
for (i=0 ; i<power_profile_count ; i++) {
/* Create subtree */
sub_tree = proto_tree_add_subtree_format(tree, tvb, *offset, 1,
ett_zbee_zcl_pwr_prof_pwrprofiles[i], NULL, "Power Profile #%u", i);
dissect_zcl_power_profile(tvb, sub_tree, offset);
}
} /*dissect_zcl_pwr_prof_pwrprofstatersp*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_pwr_prof_pwrprofschedcontrsnotif
* DESCRIPTION
* this function is called in order to decode "PowerProfileScheduleConstraintsNotification"
* and "PowerProfileScheduleConstraintsResponse" payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_pwr_prof_pwrprofschedcontrsnotif(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Retrieve "Power Profile Id" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve "Start After" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_start_after, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
/* Retrieve "Stop Before" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_stop_before, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
} /*dissect_zcl_pwr_prof_pwrprofschedcontrsnotif*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_pwr_prof_pwrprofpriceext
* DESCRIPTION
* this function is called in order to decode "GetPowerProfilePriceExtended"
* and "PowerProfileScheduleConstraintsResponse" payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_pwr_prof_pwrprofpriceext(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
static const int * options[] = {
&hf_zbee_zcl_pwr_prof_options_01,
&hf_zbee_zcl_pwr_prof_options_res,
NULL
};
/* Retrieve "Options" field */
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_pwr_prof_options, ett_zbee_zcl_pwr_prof_options, options, ENC_NA);
*offset += 1;
/* Retrieve "Power Profile Id" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve "Power Profile Start Time" field */
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_pwr_prof_stime, tvb, *offset, 2, ENC_LITTLE_ENDIAN);
*offset += 2;
} /*dissect_zcl_pwr_prof_pwrprofpriceext*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_pwr_prof_attr_data
* DESCRIPTION
* this function is called by ZCL foundation dissector in order to decode
* specific cluster attributes data.
* PARAMETERS
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* guint *offset - pointer to buffer offset
* guint16 attr_id - attribute identifier
* guint data_type - attribute data type
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_pwr_prof_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type)
{
static const int * format_fields[] = {
&hf_zbee_zcl_pwr_prof_energy_format_rdigit,
&hf_zbee_zcl_pwr_prof_energy_format_ldigit,
&hf_zbee_zcl_pwr_prof_energy_format_noleadingzero,
NULL
};
static const int * modes[] = {
&hf_zbee_zcl_pwr_prof_sched_mode_cheapest,
&hf_zbee_zcl_pwr_prof_sched_mode_greenest,
&hf_zbee_zcl_pwr_prof_sched_mode_reserved,
NULL
};
/* Dissect attribute data type and data */
switch ( attr_id )
{
case ZBEE_ZCL_ATTR_ID_PWR_PROF_TOT_PROF_NUM:
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_tot_prof_num, tvb, *offset, 1, ENC_NA);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_PWR_PROF_MULTIPLE_SCHED:
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_multiple_sched, tvb, *offset, 1, ENC_NA);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_PWR_PROF_ENERGY_FORMAT:
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_pwr_prof_energy_format, ett_zbee_zcl_pwr_prof_en_format, format_fields, ENC_NA);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_PWR_PROF_ENERGY_REMOTE:
proto_tree_add_item(tree, hf_zbee_zcl_pwr_prof_energy_remote, tvb, *offset, 1, ENC_NA);
*offset += 1;
break;
case ZBEE_ZCL_ATTR_ID_PWR_PROF_SCHED_MODE:
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_pwr_prof_sched_mode, ett_zbee_zcl_pwr_prof_sched_mode, modes, ENC_NA);
*offset += 1;
break;
default:
dissect_zcl_attr_data(tvb, tree, offset, data_type);
break;
}
} /*dissect_zcl_pwr_prof_attr_data*/
/*FUNCTION:------------------------------------------------------
* NAME
* decode_power_profile_id
* DESCRIPTION
* this function decodes the power profile custom type
* PARAMETERS
* guint *s - string to display
* guint16 value - value to decode
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_power_profile_id(gchar *s, guint8 id)
{
if (id == 0) {
g_snprintf(s, ITEM_LABEL_LENGTH, "%d (All)", id);
}
else {
g_snprintf(s, ITEM_LABEL_LENGTH, "%d", id);
}
} /*decode_power_profile_id*/
/*FUNCTION:------------------------------------------------------
* NAME
* decode_price_in_cents
* DESCRIPTION
* this function decodes price type variable
* PARAMETERS
* guint *s - string to display
* guint16 value - value to decode
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_price_in_cents(gchar *s, guint32 value)
{
g_snprintf(s, ITEM_LABEL_LENGTH, "%d cents", value);
} /* decode_price_in_cents */
/*FUNCTION:------------------------------------------------------
* NAME
* decode_power_in_watt
* DESCRIPTION
* this function decodes watt power type variable
* PARAMETERS
* guint *s - string to display
* guint16 value - value to decode
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_power_in_watt(gchar *s, guint16 value)
{
g_snprintf(s, ITEM_LABEL_LENGTH, "%d Watt", value);
} /* decode_power_in_watt */
/*FUNCTION:------------------------------------------------------
* NAME
* decode_energy
* DESCRIPTION
* this function decodes energy type variable
* PARAMETERS
* guint *s - string to display
* guint16 value - value to decode
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
decode_energy(gchar *s, guint16 value)
{
g_snprintf(s, ITEM_LABEL_LENGTH, "%d Watt per hours", value);
} /* decode_energy */
/*FUNCTION:------------------------------------------------------
* NAME
* func_decode_delayinminute
* DESCRIPTION
* this function decodes minute delay type variable
* PARAMETERS
* guint *s - string to display
* guint16 value - value to decode
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
func_decode_delayinminute(gchar *s, guint16 value)
{
if (value == 0) {
g_snprintf(s, ITEM_LABEL_LENGTH, "%d minutes (Not permitted)", value);
}
else {
g_snprintf(s, ITEM_LABEL_LENGTH, "%d minutes", value);
}
} /* func_decode_delayinminute*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_register_zbee_zcl_pwr_prof
* DESCRIPTION
* ZigBee ZCL PowerProfile cluster protocol registration routine.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void
proto_register_zbee_zcl_pwr_prof(void)
{
guint i, j;
static hf_register_info hf[] = {
{ &hf_zbee_zcl_pwr_prof_tot_prof_num,
{ "Total Profile Number", "zbee_zcl_general.pwrprof.attr.totprofnum", FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_multiple_sched,
{ "Multiple Scheduling", "zbee_zcl_general.pwrprof.attr.multiplesched", FT_BOOLEAN, BASE_NONE,
TFS(&tfs_supported_not_supported), 0x0, NULL, HFILL } },
/* Begin EnergyFormatting fields */
{ &hf_zbee_zcl_pwr_prof_energy_format,
{ "Data", "zbee_zcl_general.pwrprof.attr.energyformat",
FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_energy_format_rdigit,
{ "Number of Digits to the right of the Decimal Point", "zbee_zcl_general.pwrprof.attr.energyformat.rdigit",
FT_UINT8, BASE_DEC, NULL, ZBEE_ZCL_OPT_PWRPROF_NUM_R_DIGIT, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_energy_format_ldigit,
{ "Number of Digits to the left of the Decimal Point", "zbee_zcl_general.pwrprof.attr.energyformat.ldigit",
FT_UINT8, BASE_DEC, NULL, ZBEE_ZCL_OPT_PWRPROF_NUM_L_DIGIT, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_energy_format_noleadingzero,
{ "Suppress leading zeros.", "zbee_zcl_general.pwrprof.attr.energyformat.noleadingzero",
FT_BOOLEAN, 8, TFS(&tfs_true_false), ZBEE_ZCL_OPT_PWRPROF_NO_LEADING_ZERO, NULL, HFILL } },
/* End EnergyFormatting fields */
{ &hf_zbee_zcl_pwr_prof_energy_remote,
{ "Energy Remote", "zbee_zcl_general.pwrprof.attr.energyremote", FT_BOOLEAN, BASE_NONE,
TFS(&tfs_enabled_disabled), 0x0, NULL, HFILL } },
/* Begin ScheduleMode fields */
{ &hf_zbee_zcl_pwr_prof_sched_mode,
{ "Schedule Mode", "zbee_zcl_general.pwrprof.attr.schedmode",
FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_sched_mode_cheapest,
{ "Schedule Mode Cheapest", "zbee_zcl_general.pwrprof.attr.schedmode.cheapest",
FT_BOOLEAN, 8, TFS(&tfs_active_inactive), ZBEE_ZCL_OPT_PWRPROF_SCHED_CHEAPEST, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_sched_mode_greenest,
{ "Schedule Mode Greenest", "zbee_zcl_general.pwrprof.attr.schedmode.greenest",
FT_BOOLEAN, 8, TFS(&tfs_active_inactive), ZBEE_ZCL_OPT_PWRPROF_SCHED_GREENEST, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_sched_mode_reserved,
{ "Schedule Mode Reserved", "zbee_zcl_general.pwrprof.attr.schedmode.reserved",
FT_UINT8, BASE_HEX, NULL, ZBEE_ZCL_OPT_PWRPROF_SCHED_RESERVED, NULL, HFILL } },
/* End ScheduleMode fields */
{ &hf_zbee_zcl_pwr_prof_attr_id,
{ "Attribute", "zbee_zcl_general.pwrprof.attr_id", FT_UINT16, BASE_HEX, VALS(zbee_zcl_pwr_prof_attr_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_srv_tx_cmd_id,
{ "Command", "zbee_zcl_general.pwrprof.cmd.srv_tx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_pwr_prof_srv_tx_cmd_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_srv_rx_cmd_id,
{ "Command", "zbee_zcl_general.pwrprof.cmd.srv_rx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_pwr_prof_srv_rx_cmd_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_pwr_prof_id,
{ "Power Profile ID", "zbee_zcl_general.pwrprof.pwrprofid", FT_UINT8, BASE_CUSTOM, CF_FUNC(decode_power_profile_id), 0x00,
"Identifier of the specific profile", HFILL } },
{ &hf_zbee_zcl_pwr_prof_currency,
{ "Currency", "zbee_zcl_general.pwrprof.currency", FT_UINT16, BASE_HEX, VALS(zbee_zcl_currecy_names), 0x0,
"Local unit of currency (ISO 4217) used in the price field.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_price,
{ "Price", "zbee_zcl_general.pwrprof.price", FT_UINT32, BASE_CUSTOM, CF_FUNC(decode_price_in_cents), 0x0,
"Price of the energy of a specific Power Profile.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_price_trailing_digit,
{ "Price Trailing Digit", "zbee_zcl_general.pwrprof.pricetrailingdigit", FT_UINT8, BASE_DEC, NULL, 0x0,
"Number of digits to the right of the decimal point.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_num_of_sched_phases,
{ "Number of Scheduled Phases", "zbee_zcl_general.pwrprof.numofschedphases", FT_UINT8, BASE_DEC, NULL, 0x0,
"Total number of the energy phases of the Power Profile that need to be scheduled.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_energy_phase_id,
{ "Energy Phase ID", "zbee_zcl_general.pwrprof.energyphaseid", FT_UINT8, BASE_DEC, NULL, 0x0,
"Identifier of the specific phase.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_scheduled_time,
{ "Scheduled Time", "zbee_zcl_general.pwrprof.scheduledtime", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_zcl_time_in_minutes), 0x0,
NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_macro_phase_id,
{ "Macro Phase ID", "zbee_zcl_general.pwrprof.macrophaseid", FT_UINT8, BASE_DEC, NULL, 0x0,
"Identifier of the specific energy phase.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_expect_duration,
{ "Expected Duration", "zbee_zcl_general.pwrprof.expecduration", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_zcl_time_in_minutes), 0x0,
"The estimated duration of the specific phase.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_num_of_trans_phases,
{ "Number of Transferred Phases", "zbee_zcl_general.pwrprof.numoftransphases", FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_peak_power,
{ "Peak Power", "zbee_zcl_general.pwrprof.peakpower", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_power_in_watt), 0x0,
"The estimated power for the specific phase.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_energy,
{ "Energy", "zbee_zcl_general.pwrprof.energy", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_energy), 0x0,
"The estimated energy consumption for the accounted phase.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_max_active_delay,
{ "Max Activation Delay", "zbee_zcl_general.pwrprof.maxactivdelay", FT_UINT16, BASE_CUSTOM, CF_FUNC(func_decode_delayinminute), 0x0,
"The maximum interruption time between the end of the previous phase and the beginning of the specific phase.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_pwr_prof_count,
{ "Power Profile Count", "zbee_zcl_general.pwrprof.pwrprofcount", FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_pwr_prof_rem_ctrl,
{ "Power Profile Remote Control", "zbee_zcl_general.pwrprof.pwrprofremctrl", FT_BOOLEAN, BASE_NONE, TFS(&tfs_enabled_disabled), 0x00,
"It indicates if the PowerProfile is currently remotely controllable or not.", HFILL } },
{ &hf_zbee_zcl_pwr_prof_pwr_prof_state,
{ "Power Profile State", "zbee_zcl_general.pwrprof.pwrprofstate", FT_UINT8, BASE_HEX, VALS(zbee_zcl_pwr_prof_state_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_start_after,
{ "Start After", "zbee_zcl_general.pwrprof.startafter", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_zcl_time_in_minutes), 0x0,
NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_stop_before,
{ "Stop Before", "zbee_zcl_general.pwrprof.stopbefore", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_zcl_time_in_minutes), 0x0,
NULL, HFILL } },
/* Begin Options fields */
{ &hf_zbee_zcl_pwr_prof_options,
{ "Options", "zbee_zcl_general.pwrprof.options", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_options_01,
{ "PowerProfileStartTime Field Present", "zbee_zcl_general.pwrprof.options.01", FT_BOOLEAN, 8, TFS(&tfs_true_false),
ZBEE_ZCL_OPT_PWRPROF_STIME_PRESENT, NULL, HFILL } },
{ &hf_zbee_zcl_pwr_prof_options_res,
{ "Reserved", "zbee_zcl_general.pwrprof.options.reserved", FT_UINT8, BASE_HEX, NULL,
ZBEE_ZCL_OPT_PWRPROF_RESERVED, NULL, HFILL } },
/* End Options fields */
{ &hf_zbee_zcl_pwr_prof_pwr_prof_stime,
{ "Power Profile Start Time", "zbee_zcl_general.pwrprof.pwrprofstime", FT_UINT16, BASE_CUSTOM, CF_FUNC(decode_zcl_time_in_minutes), 0x0,
NULL, HFILL } }
};
/* ZCL PowerProfile subtrees */
static gint *ett[ZBEE_ZCL_PWR_PROF_NUM_ETT];
ett[0] = &ett_zbee_zcl_pwr_prof;
ett[1] = &ett_zbee_zcl_pwr_prof_options;
ett[2] = &ett_zbee_zcl_pwr_prof_en_format;
ett[3] = &ett_zbee_zcl_pwr_prof_sched_mode;
/* initialize attribute subtree types */
for ( i = 0, j = ZBEE_ZCL_PWR_PROF_NUM_GENERIC_ETT; i < ZBEE_ZCL_PWR_PROF_NUM_PWR_PROF_ETT; i++, j++ ) {
ett_zbee_zcl_pwr_prof_pwrprofiles[i] = -1;
ett[j] = &ett_zbee_zcl_pwr_prof_pwrprofiles[i];
}
for ( i = 0; i < ZBEE_ZCL_PWR_PROF_NUM_EN_PHS_ETT; i++, j++ ) {
ett_zbee_zcl_pwr_prof_enphases[i] = -1;
ett[j] = &ett_zbee_zcl_pwr_prof_enphases[i];
}
/* Register the ZigBee ZCL PowerProfile cluster protocol name and description */
proto_zbee_zcl_pwr_prof = proto_register_protocol("ZigBee ZCL Power Profile", "ZCL Power Profile", ZBEE_PROTOABBREV_ZCL_PWRPROF);
proto_register_field_array(proto_zbee_zcl_pwr_prof, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
/* Register the ZigBee ZCL Power Profile dissector. */
new_register_dissector(ZBEE_PROTOABBREV_ZCL_PWRPROF, dissect_zbee_zcl_pwr_prof, proto_zbee_zcl_pwr_prof);
} /* proto_register_zbee_zcl_pwr_prof */
/*FUNCTION:------------------------------------------------------
* NAME
* proto_reg_handoff_zbee_zcl_pwr_prof
* DESCRIPTION
* Hands off the Zcl Power Profile cluster dissector.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void
proto_reg_handoff_zbee_zcl_pwr_prof(void)
{
dissector_handle_t pwr_prof_handle;
/* Register our dissector with the ZigBee application dissectors. */
pwr_prof_handle = find_dissector(ZBEE_PROTOABBREV_ZCL_PWRPROF);
dissector_add_uint("zbee.zcl.cluster", ZBEE_ZCL_CID_POWER_PROFILE, pwr_prof_handle);
zbee_zcl_init_cluster( proto_zbee_zcl_pwr_prof,
ett_zbee_zcl_pwr_prof,
ZBEE_ZCL_CID_POWER_PROFILE,
hf_zbee_zcl_pwr_prof_attr_id,
hf_zbee_zcl_pwr_prof_srv_rx_cmd_id,
hf_zbee_zcl_pwr_prof_srv_tx_cmd_id,
(zbee_zcl_fn_attr_data)dissect_zcl_pwr_prof_attr_data
);
} /*proto_reg_handoff_zbee_zcl_pwr_prof*/
/* ########################################################################## */
/* #### (0x001B) APPLIANCE CONTROL CLUSTER ################################## */
/* ########################################################################## */
/*************************/
/* Defines */
/*************************/
#define ZBEE_ZCL_APPL_CTRL_NUM_GENERIC_ETT 3
#define ZBEE_ZCL_APPL_CTRL_NUM_FUNC_ETT 32
#define ZBEE_ZCL_APPL_CTRL_NUM_ETT (ZBEE_ZCL_APPL_CTRL_NUM_GENERIC_ETT + \
ZBEE_ZCL_APPL_CTRL_NUM_FUNC_ETT)
/* Attributes */
#define ZBEE_ZCL_ATTR_ID_APPL_CTRL_START_TIME 0x0000 /* Start Time */
#define ZBEE_ZCL_ATTR_ID_APPL_CTRL_FINISH_TIME 0x0001 /* Finish Time */
#define ZBEE_ZCL_ATTR_ID_APPL_CTRL_REMAINING_TIME 0x0002 /* Remaining Time */
/* Server Commands Received */
#define ZBEE_ZCL_CMD_ID_APPL_CTRL_EXECUTION_CMD 0x00 /* Execution of a Command */
#define ZBEE_ZCL_CMD_ID_APPL_CTRL_SIGNAL_STATE 0x01 /* Signal State */
#define ZBEE_ZCL_CMD_ID_APPL_CTRL_WRITE_FUNCS 0x02 /* Write Functions */
#define ZBEE_ZCL_CMD_ID_APPL_CTRL_OVERLOAD_PAUSE_RESUME 0x03 /* Overload Pause Resume */
#define ZBEE_ZCL_CMD_ID_APPL_CTRL_OVERLOAD_PAUSE 0x04 /* Overload Pause */
#define ZBEE_ZCL_CMD_ID_APPL_CTRL_OVERLOAD_WARNING 0x05 /* Overload Warning */
/* Server Commands Generated */
#define ZBEE_ZCL_CMD_ID_APPL_CTRL_SIGNAL_STATE_RSP 0x00 /* Signal State Response */
#define ZBEE_ZCL_CMD_ID_APPL_CTRL_SIGNAL_STATE_NOTIF 0x01 /* Signal State Notification */
/* Execution Of a Command - Command Ids list */
#define ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_RESERVED 0x00 /* Reserved */
#define ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_START 0x01 /* Start appliance cycle */
#define ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_STOP 0x02 /* Stop appliance cycle */
#define ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_PAUSE 0x03 /* Pause appliance cycle */
#define ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_START_SUPERFREEZING 0x04 /* Start superfreezing cycle */
#define ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_STOP_SUPERFREEZING 0x05 /* Stop superfreezing cycle */
#define ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_START_SUPERCOOLING 0x06 /* Start supercooling cycle */
#define ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_STOP_SUPERCOOLING 0x07 /* Stop supercooling cycle */
#define ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_DISABLE_GAS 0x08 /* Disable gas */
#define ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_ENABLE_GAS 0x09 /* Enable gas */
/* CECED Time mask */
#define ZBEE_ZCL_APPL_CTRL_TIME_MM 0x003f /* Minutes */
#define ZBEE_ZCL_APPL_CTRL_TIME_ENCOD_TYPE 0x00c0 /* Encoding Type */
#define ZBEE_ZCL_APPL_CTRL_TIME_HH 0xff00 /* Hours */
/* Time encoding values */
#define ZBEE_ZCL_APPL_CTRL_TIME_ENCOD_REL 0x00
#define ZBEE_ZCL_APPL_CTRL_TIME_ENCOD_ABS 0x01
/* Overload Warnings */
#define ZBEE_ZCL_APPL_CTRL_ID_OVRL_WARN_1 0x00
#define ZBEE_ZCL_APPL_CTRL_ID_OVRL_WARN_2 0x01
#define ZBEE_ZCL_APPL_CTRL_ID_OVRL_WARN_3 0x02
#define ZBEE_ZCL_APPL_CTRL_ID_OVRL_WARN_4 0x03
#define ZBEE_ZCL_APPL_CTRL_ID_OVRL_WARN_5 0x04
/* Appliance Status Ids list */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_RESERVED 0x00 /* Reserved */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_OFF 0x01 /* Appliance in off state */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_STANDBY 0x02 /* Appliance in stand-by */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_PRG 0x03 /* Appliance already programmed */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_PRG_WAITING_TO_START 0x04 /* Appliance already programmed and ready to start */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_RUNNING 0x05 /* Appliance is running */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_PAUSE 0x06 /* Appliance is in pause */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_END_PRG 0x07 /* Appliance end programmed tasks */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_FAILURE 0x08 /* Appliance is in a failure state */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_PRG_INTERRUPTED 0x09 /* The appliance programmed tasks have been interrupted */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_IDLE 0x1a /* Appliance in idle state */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_RINSE_HOLD 0x1b /* Appliance rinse hold */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_SERVICE 0x1c /* Appliance in service state */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_SUPERFREEZING 0x1d /* Appliance in superfreezing state */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_SUPERCOOLING 0x1e /* Appliance in supercooling state */
#define ZBEE_ZCL_APPL_CTRL_ID_STATUS_SUPERHEATING 0x1f /* Appliance in superheating state */
/* Remote Enable Flags mask */
#define ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_FLAGS 0x0f
#define ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_STATUS2 0xf0
/* Remote Enable Flags values */
#define ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_DIS 0x00 /* Disabled */
#define ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_EN_REM_EN_CTRL 0x01 /* Enable Remote and Energy Control */
#define ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_TEMP_LOCK_DIS 0x07 /* Temporarily locked/disabled */
#define ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_EN_REM_CTRL 0x0f /* Enable Remote Control */
/* Device Status 2 values */
#define ZBEE_ZCL_APPL_CTRL_STATUS2_PROPRIETARY_0 0x00 /* Proprietary */
#define ZBEE_ZCL_APPL_CTRL_STATUS2_PROPRIETARY_1 0x01 /* Proprietary */
#define ZBEE_ZCL_APPL_CTRL_STATUS2_IRIS_SYMPTOM_CODE 0x02 /* Iris symptom code */
/*************************/
/* Function Declarations */
/*************************/
void proto_register_zbee_zcl_appl_ctrl(void);
void proto_reg_handoff_zbee_zcl_appl_ctrl(void);
/* Command Dissector Helpers */
static void dissect_zcl_appl_ctrl_exec_cmd (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_appl_ctrl_attr_func (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_appl_ctrl_wr_funcs (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_appl_ctrl_ovrl_warning (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_appl_ctrl_signal_state_rsp (tvbuff_t *tvb, proto_tree *tree, guint *offset);
static void dissect_zcl_appl_ctrl_attr_data (proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type);
/* Private functions prototype */
/*************************/
/* Global Variables */
/*************************/
/* Initialize the protocol and registered fields */
static int proto_zbee_zcl_appl_ctrl = -1;
static int hf_zbee_zcl_appl_ctrl_attr_id = -1;
static int hf_zbee_zcl_appl_ctrl_time = -1;
static int hf_zbee_zcl_appl_ctrl_time_mm = -1;
static int hf_zbee_zcl_appl_ctrl_time_encoding_type = -1;
static int hf_zbee_zcl_appl_ctrl_time_hh = -1;
static int hf_zbee_zcl_appl_ctrl_srv_tx_cmd_id = -1;
static int hf_zbee_zcl_appl_ctrl_srv_rx_cmd_id = -1;
static int hf_zbee_zcl_appl_ctrl_exec_cmd_id = -1;
static int hf_zbee_zcl_appl_ctrl_attr_func_id = -1;
static int hf_zbee_zcl_appl_ctrl_attr_func_data_type = -1;
static int hf_zbee_zcl_appl_ctrl_warning_id = -1;
static int hf_zbee_zcl_appl_ctrl_appl_status = -1;
static int hf_zbee_zcl_appl_ctrl_rem_en_flags_raw = -1;
static int hf_zbee_zcl_appl_ctrl_rem_en_flags = -1;
static int hf_zbee_zcl_appl_ctrl_status2 = -1;
static int hf_zbee_zcl_appl_ctrl_status2_array = -1;
/* Initialize the subtree pointers */
static gint ett_zbee_zcl_appl_ctrl = -1;
static gint ett_zbee_zcl_appl_ctrl_flags = -1;
static gint ett_zbee_zcl_appl_ctrl_time = -1;
static gint ett_zbee_zcl_appl_ctrl_func[ZBEE_ZCL_APPL_CTRL_NUM_FUNC_ETT];
/* Attributes */
static const value_string zbee_zcl_appl_ctrl_attr_names[] = {
{ ZBEE_ZCL_ATTR_ID_APPL_CTRL_START_TIME, "Start Time" },
{ ZBEE_ZCL_ATTR_ID_APPL_CTRL_FINISH_TIME, "Finish Time" },
{ ZBEE_ZCL_ATTR_ID_APPL_CTRL_REMAINING_TIME, "Remaining Time" },
{ 0, NULL }
};
static value_string_ext zbee_zcl_appl_ctrl_attr_names_ext = VALUE_STRING_EXT_INIT(zbee_zcl_appl_ctrl_attr_names);
/* Server Commands Received */
static const value_string zbee_zcl_appl_ctrl_srv_rx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_APPL_CTRL_EXECUTION_CMD, "Execution of a Command" },
{ ZBEE_ZCL_CMD_ID_APPL_CTRL_SIGNAL_STATE, "Signal State" },
{ ZBEE_ZCL_CMD_ID_APPL_CTRL_WRITE_FUNCS, "Write Functions" },
{ ZBEE_ZCL_CMD_ID_APPL_CTRL_OVERLOAD_PAUSE_RESUME, "Overload Pause Resume" },
{ ZBEE_ZCL_CMD_ID_APPL_CTRL_OVERLOAD_PAUSE, "Overload Pause" },
{ ZBEE_ZCL_CMD_ID_APPL_CTRL_OVERLOAD_WARNING, "Overload Warning" },
{ 0, NULL }
};
/* Server Commands Generated */
static const value_string zbee_zcl_appl_ctrl_srv_tx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_APPL_CTRL_SIGNAL_STATE_RSP, "Signal State Response" },
{ ZBEE_ZCL_CMD_ID_APPL_CTRL_SIGNAL_STATE_NOTIF, "Signal State Notification" },
{ 0, NULL }
};
/* Execution Of a Command - Command Name */
static const value_string zbee_zcl_appl_ctrl_exec_cmd_names[] = {
{ ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_RESERVED, "Reserved" },
{ ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_START, "Start" },
{ ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_STOP, "Stop" },
{ ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_PAUSE, "Pause" },
{ ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_START_SUPERFREEZING, "Start Superfreezing" },
{ ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_START_SUPERFREEZING, "Stop Superfreezing" },
{ ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_START_SUPERCOOLING, "Start Supercooling" },
{ ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_STOP_SUPERCOOLING, "Stop Supercooling" },
{ ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_DISABLE_GAS, "Disable Gas" },
{ ZBEE_ZCL_APPL_CTRL_EXEC_CMD_ID_ENABLE_GAS, "Enable Gas" },
{ 0, NULL }
};
/* Appliance Status Names list */
static const value_string zbee_zcl_appl_ctrl_appl_status_names[] = {
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_RESERVED, "Reserved" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_OFF, "Off" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_STANDBY, "Stand-by" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_PRG, "Programmed" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_PRG_WAITING_TO_START, "Waiting to Start" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_RUNNING, "Running" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_PAUSE, "Pause" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_END_PRG, "End Programmed" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_FAILURE, "Failure" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_PRG_INTERRUPTED, "Programme Interrupted" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_IDLE, "Idle" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_RINSE_HOLD, "Raise Hold" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_SERVICE, "Service" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_SUPERFREEZING, "Superfreezing" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_SUPERCOOLING, "Supercooling" },
{ ZBEE_ZCL_APPL_CTRL_ID_STATUS_SUPERHEATING, "Superheating" },
{ 0, NULL }
};
/* Remote Enable Flags Names list */
static const value_string zbee_zcl_appl_ctrl_rem_flags_names[] = {
{ ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_DIS, "Disable" },
{ ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_EN_REM_EN_CTRL, "Enable Remote and Energy Control" },
{ ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_TEMP_LOCK_DIS, "Temporarily locked/disabled" },
{ ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_EN_REM_CTRL, "Enable Remote Control" },
{ 0, NULL }
};
/* Appliance Status 2 Names list */
static const value_string zbee_zcl_appl_ctrl_status2_names[] = {
{ ZBEE_ZCL_APPL_CTRL_STATUS2_PROPRIETARY_0, "Proprietary" },
{ ZBEE_ZCL_APPL_CTRL_STATUS2_PROPRIETARY_1, "Proprietary" },
{ ZBEE_ZCL_APPL_CTRL_STATUS2_IRIS_SYMPTOM_CODE, "Iris symptom code" },
{ 0, NULL }
};
/* Overload Warning Names list */
static const value_string zbee_zcl_appl_ctrl_ovrl_warning_names[] = {
{ ZBEE_ZCL_APPL_CTRL_ID_OVRL_WARN_1, "Overall power above 'available power' level" },
{ ZBEE_ZCL_APPL_CTRL_ID_OVRL_WARN_2, "Overall power above 'power threshold' level" },
{ ZBEE_ZCL_APPL_CTRL_ID_OVRL_WARN_3, "Overall power back below the 'available power' level" },
{ ZBEE_ZCL_APPL_CTRL_ID_OVRL_WARN_4, "Overall power back below the 'power threshold' level" },
{ ZBEE_ZCL_APPL_CTRL_ID_OVRL_WARN_5, "Overall power will be potentially above 'available power' level if the appliance starts" },
{ 0, NULL }
};
/* CEDEC Time Encoding Names list */
static const value_string zbee_zcl_appl_ctrl_time_encoding_type_names[] = {
{ ZBEE_ZCL_APPL_CTRL_TIME_ENCOD_REL, "Relative" },
{ ZBEE_ZCL_APPL_CTRL_TIME_ENCOD_ABS, "Absolute" },
{ 0, NULL }
};
/*************************/
/* Function Bodies */
/*************************/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zbee_zcl_appl_ctrl
* DESCRIPTION
* ZigBee ZCL Appliance Control cluster dissector for wireshark.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* void *data - pointer to ZCL packet structure.
* RETURNS
* int - length of parsed data.
*---------------------------------------------------------------
*/
static int
dissect_zbee_zcl_appl_ctrl(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
proto_tree *payload_tree;
zbee_zcl_packet *zcl;
guint offset = 0;
guint8 cmd_id;
gint rem_len;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
zcl = (zbee_zcl_packet *)data;
cmd_id = zcl->cmd_id;
/* Create a subtree for the ZCL Command frame, and add the command ID to it. */
if (zcl->direction == ZBEE_ZCL_FCF_TO_SERVER) {
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_appl_ctrl_srv_rx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_appl_ctrl_srv_rx_cmd_id, tvb, offset, 1, cmd_id);
/* Check is this command has a payload, than add the payload tree */
rem_len = tvb_reported_length_remaining(tvb, ++offset);
if (rem_len > 0) {
payload_tree = proto_tree_add_subtree(tree, tvb, offset, rem_len, ett_zbee_zcl_appl_ctrl, NULL, "Payload");
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_APPL_CTRL_EXECUTION_CMD:
dissect_zcl_appl_ctrl_exec_cmd(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_APPL_CTRL_SIGNAL_STATE:
case ZBEE_ZCL_CMD_ID_APPL_CTRL_OVERLOAD_PAUSE_RESUME:
case ZBEE_ZCL_CMD_ID_APPL_CTRL_OVERLOAD_PAUSE:
/* No payload */
break;
case ZBEE_ZCL_CMD_ID_APPL_CTRL_WRITE_FUNCS:
dissect_zcl_appl_ctrl_wr_funcs(tvb, payload_tree, &offset);
break;
case ZBEE_ZCL_CMD_ID_APPL_CTRL_OVERLOAD_WARNING:
dissect_zcl_appl_ctrl_ovrl_warning(tvb, payload_tree, &offset);
break;
default:
break;
}
}
}
else { /* ZBEE_ZCL_FCF_TO_CLIENT */
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_appl_ctrl_srv_tx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_appl_ctrl_srv_tx_cmd_id, tvb, offset, 1, cmd_id);
/* Check is this command has a payload, than add the payload tree */
rem_len = tvb_reported_length_remaining(tvb, ++offset);
if (rem_len > 0) {
payload_tree = proto_tree_add_subtree(tree, tvb, offset, rem_len, ett_zbee_zcl_appl_ctrl, NULL, "Payload");
/* Call the appropriate command dissector */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_APPL_CTRL_SIGNAL_STATE_RSP:
case ZBEE_ZCL_CMD_ID_APPL_CTRL_SIGNAL_STATE_NOTIF:
dissect_zcl_appl_ctrl_signal_state_rsp(tvb, payload_tree, &offset);
break;
default:
break;
}
}
}
return tvb_captured_length(tvb);
}
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_appl_ctrl_exec_cmd
* DESCRIPTION
* this function is called in order to decode "ExecutionOfACommand"
* payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_appl_ctrl_exec_cmd(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Retrieve "Command Id" field */
proto_tree_add_item(tree, hf_zbee_zcl_appl_ctrl_exec_cmd_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
} /*dissect_zcl_appl_ctrl_exec_cmd*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_appl_ctrl_attr_func
* DESCRIPTION
* this function is called in order to decode "Function" element.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_appl_ctrl_attr_func(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
guint8 func_data_type;
guint16 func_id;
/* ID */
func_id = tvb_get_letohs(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_appl_ctrl_attr_func_id, tvb, *offset, 2,ENC_LITTLE_ENDIAN);
*offset += 2;
proto_item_append_text(tree, ", %s",
val_to_str_ext_const(func_id, &zbee_zcl_appl_ctrl_attr_names_ext, "Reserved"));
/* Data Type */
func_data_type = tvb_get_guint8(tvb, *offset);
proto_tree_add_item(tree, hf_zbee_zcl_appl_ctrl_attr_func_data_type, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Function Data Dissector */
dissect_zcl_appl_ctrl_attr_data(tree, tvb, offset, func_id, func_data_type);
} /*dissect_zcl_appl_ctrl_attr_func*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_appl_ctrl_wr_funcs
* DESCRIPTION
* this function is called in order to decode "WriteFunctions"
* payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_appl_ctrl_wr_funcs(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
proto_tree *sub_tree = NULL;
guint tvb_len;
guint i = 0;
tvb_len = tvb_reported_length(tvb);
while ( *offset < tvb_len && i < ZBEE_ZCL_APPL_CTRL_NUM_FUNC_ETT ) {
/* Create subtree for attribute status field */
sub_tree = proto_tree_add_subtree_format(tree, tvb, *offset, 0,
ett_zbee_zcl_appl_ctrl_func[i], NULL, "Function #%d", i);
i++;
/* Dissect the attribute identifier */
dissect_zcl_appl_ctrl_attr_func(tvb, sub_tree, offset);
}
} /*dissect_zcl_appl_ctrl_wr_funcs*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_appl_ctrl_ovrl_warning
* DESCRIPTION
* this function is called in order to decode "OverloadWarning"
* payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_appl_ctrl_ovrl_warning(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
/* Retrieve "Warning Id" field */
proto_tree_add_item(tree, hf_zbee_zcl_appl_ctrl_warning_id, tvb, *offset, 1, ENC_NA);
*offset += 1;
} /*dissect_zcl_appl_ctrl_ovrl_warning*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_appl_ctrl_signal_state_rsp
* DESCRIPTION
* this function is called in order to decode "SignalStateResponse"
* "SignalStateNotification" payload.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* guint *offset - pointer to buffer offset
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_appl_ctrl_signal_state_rsp(tvbuff_t *tvb, proto_tree *tree, guint *offset)
{
static const int * flags[] = {
&hf_zbee_zcl_appl_ctrl_rem_en_flags,
&hf_zbee_zcl_appl_ctrl_status2,
NULL
};
/* Retrieve "Appliance Status" field */
proto_tree_add_item(tree, hf_zbee_zcl_appl_ctrl_appl_status, tvb, *offset, 1, ENC_NA);
*offset += 1;
/* Retrieve "Remote Enable" field */
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_appl_ctrl_rem_en_flags_raw, ett_zbee_zcl_appl_ctrl_flags, flags, ENC_NA);
*offset += 1;
/* Retrieve "Appliance Status 2" field */
proto_tree_add_item(tree, hf_zbee_zcl_appl_ctrl_status2_array, tvb, *offset, 3, ENC_BIG_ENDIAN);
} /*dissect_zcl_appl_ctrl_signal_state_rsp*/
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_appl_ctrl_attr_data
* DESCRIPTION
* this function is called by ZCL foundation dissector in order to decode
* specific cluster attributes data.
* PARAMETERS
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* guint *offset - pointer to buffer offset
* guint16 attr_id - attribute identifier
* guint data_type - attribute data type
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_appl_ctrl_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id, guint data_type)
{
static const int * flags[] = {
&hf_zbee_zcl_appl_ctrl_time_mm,
&hf_zbee_zcl_appl_ctrl_time_encoding_type,
&hf_zbee_zcl_appl_ctrl_time_hh,
NULL
};
/* Dissect attribute data type and data */
switch (attr_id) {
case ZBEE_ZCL_ATTR_ID_APPL_CTRL_START_TIME:
case ZBEE_ZCL_ATTR_ID_APPL_CTRL_FINISH_TIME:
case ZBEE_ZCL_ATTR_ID_APPL_CTRL_REMAINING_TIME:
proto_tree_add_bitmask(tree, tvb, *offset, hf_zbee_zcl_appl_ctrl_time, ett_zbee_zcl_appl_ctrl_time, flags, ENC_LITTLE_ENDIAN);
*offset += 2;
break;
default:
dissect_zcl_attr_data(tvb, tree, offset, data_type);
break;
}
} /*dissect_zcl_appl_ctrl_attr_data*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_register_zbee_zcl_appl_ctrl
* DESCRIPTION
* this function registers the ZCL Appliance Control dissector
* and all its information.
* PARAMETERS
* none
* RETURNS
* none
*---------------------------------------------------------------
*/
void
proto_register_zbee_zcl_appl_ctrl(void)
{
guint i, j;
static hf_register_info hf[] = {
{ &hf_zbee_zcl_appl_ctrl_attr_id,
{ "Attribute", "zbee_zcl_general.applctrl.attr_id", FT_UINT16, BASE_HEX, VALS(zbee_zcl_appl_ctrl_attr_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_time,
{ "Data", "zbee_zcl_general.applctrl.time", FT_UINT16, BASE_HEX, NULL, 0x0,
NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_time_mm,
{ "Minutes", "zbee_zcl_general.applctrl.time.mm", FT_UINT16, BASE_DEC, NULL, ZBEE_ZCL_APPL_CTRL_TIME_MM,
NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_time_encoding_type,
{ "Encoding Type", "zbee_zcl_general.applctrl.time.encoding_type", FT_UINT16, BASE_HEX, VALS(zbee_zcl_appl_ctrl_time_encoding_type_names),
ZBEE_ZCL_APPL_CTRL_TIME_ENCOD_TYPE, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_time_hh,
{ "Hours", "zbee_zcl_general.applctrl.time.hh", FT_UINT16, BASE_DEC, NULL, ZBEE_ZCL_APPL_CTRL_TIME_HH,
NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_srv_tx_cmd_id,
{ "Command", "zbee_zcl_general.applctrl.cmd.srv_tx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_appl_ctrl_srv_tx_cmd_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_srv_rx_cmd_id,
{ "Command", "zbee_zcl_general.applctrl.cmd.srv_rx.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_appl_ctrl_srv_rx_cmd_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_appl_status,
{ "Appliance Status", "zbee_zcl_general.applctrl.status", FT_UINT8, BASE_HEX, VALS(zbee_zcl_appl_ctrl_appl_status_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_rem_en_flags_raw,
{ "Remote Enable Flags", "zbee_zcl_general.applctrl.remote_enable_flags", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_rem_en_flags,
{ "Remote Enable Flags", "zbee_zcl_general.applctrl.remenflags", FT_UINT8, BASE_HEX, VALS(zbee_zcl_appl_ctrl_rem_flags_names),
ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_FLAGS, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_status2,
{ "Appliance Status 2", "zbee_zcl_general.applctrl.status2", FT_UINT8, BASE_HEX, VALS(zbee_zcl_appl_ctrl_status2_names),
ZBEE_ZCL_APPL_CTRL_REM_EN_FLAGS_STATUS2, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_status2_array,
{ "Appliance Status 2", "zbee_zcl_general.applctrl.status2.array", FT_UINT24, BASE_HEX, NULL,
0x00, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_exec_cmd_id,
{ "Command", "zbee_zcl_general.applctrl.execcmd.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_appl_ctrl_exec_cmd_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_attr_func_id,
{ "ID", "zbee_zcl_general.applctrl.attr_func.id", FT_UINT16, BASE_HEX, VALS(zbee_zcl_appl_ctrl_attr_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_attr_func_data_type,
{ "Data Type", "zbee_zcl_general.applctrl.attr_func.datatype", FT_UINT8, BASE_HEX, VALS(zbee_zcl_short_data_type_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_appl_ctrl_warning_id,
{ "Warning", "zbee_zcl_general.applctrl.ovrlwarning.id", FT_UINT8, BASE_HEX, VALS(zbee_zcl_appl_ctrl_ovrl_warning_names),
0x0, NULL, HFILL } }
};
/* ZCL ApplianceControl subtrees */
gint *ett[ZBEE_ZCL_APPL_CTRL_NUM_ETT];
ett[0] = &ett_zbee_zcl_appl_ctrl;
ett[1] = &ett_zbee_zcl_appl_ctrl_flags;
ett[2] = &ett_zbee_zcl_appl_ctrl_time;
/* initialize attribute subtree types */
for ( i = 0, j = ZBEE_ZCL_APPL_CTRL_NUM_GENERIC_ETT; i < ZBEE_ZCL_APPL_CTRL_NUM_FUNC_ETT; i++, j++) {
ett_zbee_zcl_appl_ctrl_func[i] = -1;
ett[j] = &ett_zbee_zcl_appl_ctrl_func[i];
}
/* Register the ZigBee ZCL ApplianceControl cluster protocol name and description */
proto_zbee_zcl_appl_ctrl = proto_register_protocol("ZigBee ZCL Appliance Control", "ZCL Appliance Control", ZBEE_PROTOABBREV_ZCL_APPLCTRL);
proto_register_field_array(proto_zbee_zcl_appl_ctrl, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
/* Register the ZigBee ZCL Appliance Control dissector. */
new_register_dissector(ZBEE_PROTOABBREV_ZCL_APPLCTRL, dissect_zbee_zcl_appl_ctrl, proto_zbee_zcl_appl_ctrl);
} /*proto_register_zbee_zcl_appl_ctrl*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_reg_handoff_zbee_zcl_appl_ctrl
* DESCRIPTION
* Hands off the Zcl Appliance Control dissector.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void
proto_reg_handoff_zbee_zcl_appl_ctrl(void)
{
dissector_handle_t appl_ctrl_handle;
/* Register our dissector with the ZigBee application dissectors. */
appl_ctrl_handle = find_dissector(ZBEE_PROTOABBREV_ZCL_APPLCTRL);
dissector_add_uint("zbee.zcl.cluster", ZBEE_ZCL_CID_APPLIANCE_CONTROL, appl_ctrl_handle);
zbee_zcl_init_cluster( proto_zbee_zcl_appl_ctrl,
ett_zbee_zcl_appl_ctrl,
ZBEE_ZCL_CID_APPLIANCE_CONTROL,
hf_zbee_zcl_appl_ctrl_attr_id,
hf_zbee_zcl_appl_ctrl_srv_rx_cmd_id,
hf_zbee_zcl_appl_ctrl_srv_tx_cmd_id,
(zbee_zcl_fn_attr_data)dissect_zcl_appl_ctrl_attr_data
);
} /*proto_reg_handoff_zbee_zcl_appl_ctrl*/
/* ########################################################################## */
/* #### (0x0020) POLL CONTROL CLUSTER ####################################### */
/* ########################################################################## */
/*************************/
/* Defines */
/*************************/
#define ZBEE_ZCL_POLL_CTRL_NUM_ETT 1
/* Poll Control Attributes */
#define ZBEE_ZCL_ATTR_ID_POLL_CTRL_CHECK_IN 0x0000
#define ZBEE_ZCL_ATTR_ID_POLL_CTRL_LONG_POLL 0x0001
#define ZBEE_ZCL_ATTR_ID_POLL_CTRL_SHORT_POLL 0x0002
#define ZBEE_ZCL_ATTR_ID_POLL_CTRL_FAST_POLL 0x0003
#define ZBEE_ZCL_ATTR_ID_POLL_CTRL_CHECK_IN_MIN 0x0004
#define ZBEE_ZCL_ATTR_ID_POLL_CTRL_LONG_POLL_MIN 0x0005
#define ZBEE_ZCL_ATTR_ID_POLL_CTRL_FAST_POLL_TIMEOUT 0x0006
static const value_string zbee_zcl_poll_ctrl_attr_names[] = {
{ ZBEE_ZCL_ATTR_ID_POLL_CTRL_CHECK_IN, "Check-inInterval" },
{ ZBEE_ZCL_ATTR_ID_POLL_CTRL_LONG_POLL, "LongPollInterval" },
{ ZBEE_ZCL_ATTR_ID_POLL_CTRL_SHORT_POLL, "ShortPollInterval" },
{ ZBEE_ZCL_ATTR_ID_POLL_CTRL_FAST_POLL, "FastPollTimeout" },
{ ZBEE_ZCL_ATTR_ID_POLL_CTRL_CHECK_IN_MIN, "Check-inIntervalMin" },
{ ZBEE_ZCL_ATTR_ID_POLL_CTRL_LONG_POLL_MIN, "LongPollIntervalMin" },
{ ZBEE_ZCL_ATTR_ID_POLL_CTRL_FAST_POLL_TIMEOUT, "FastPollTimeoutMax" },
{ 0, NULL }
};
/* Server-to-client command IDs. */
#define ZBEE_ZCL_CMD_ID_POLL_CTRL_CHECK_IN 0x00
static const value_string zbee_zcl_poll_ctrl_srv_tx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_POLL_CTRL_CHECK_IN, "Check-in" },
{ 0, NULL }
};
/* Client-to-server command IDs. */
#define ZBEE_ZCL_CMD_ID_POLL_CTRL_CHECK_IN_RESPONSE 0x00
#define ZBEE_ZCL_CMD_ID_POLL_CTRL_FAST_POLL_STOP 0x01
#define ZBEE_ZCL_CMD_ID_POLL_CTRL_SET_LONG_POLL 0x02
#define ZBEE_ZCL_CMD_ID_POLL_CTRL_SET_SHORT_POLL 0x03
static const value_string zbee_zcl_poll_ctrl_srv_rx_cmd_names[] = {
{ ZBEE_ZCL_CMD_ID_POLL_CTRL_CHECK_IN_RESPONSE, "Check-in Response" },
{ ZBEE_ZCL_CMD_ID_POLL_CTRL_FAST_POLL_STOP, "Fast Poll Stop" },
{ ZBEE_ZCL_CMD_ID_POLL_CTRL_SET_LONG_POLL, "Set Long Poll Interval" },
{ ZBEE_ZCL_CMD_ID_POLL_CTRL_SET_SHORT_POLL, "Set Short Poll Interval" },
{ 0, NULL }
};
/*************************/
/* Global Variables */
/*************************/
/* Initialize the protocol and registered fields */
static int proto_zbee_zcl_poll_ctrl = -1;
static int hf_zbee_zcl_poll_ctrl_attr_id = -1;
static int hf_zbee_zcl_poll_ctrl_srv_rx_cmd_id = -1;
static int hf_zbee_zcl_poll_ctrl_srv_tx_cmd_id = -1;
static int hf_zbee_zcl_poll_ctrl_start_fast_polling = -1;
static int hf_zbee_zcl_poll_ctrl_fast_poll_timeout = -1;
static int hf_zbee_zcl_poll_ctrl_new_long_poll_interval = -1;
static int hf_zbee_zcl_poll_ctrl_new_short_poll_interval = -1;
static gint ett_zbee_zcl_poll_ctrl = -1;
/*************************/
/* Function Declarations */
/*************************/
void proto_register_zbee_zcl_poll_ctrl(void);
void proto_reg_handoff_zbee_zcl_poll_ctrl(void);
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zbee_zcl_poll_ctrl
* DESCRIPTION
* ZigBee ZCL Poll Control cluster dissector for wireshark.
* PARAMETERS
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* packet_info *pinfo - pointer to packet information fields
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* void *data - pointer to ZCL packet structure.
* RETURNS
* int - length of parsed data.
*---------------------------------------------------------------
*/
static int
dissect_zbee_zcl_poll_ctrl(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
zbee_zcl_packet *zcl;
guint offset = 0;
guint8 cmd_id;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
zcl = (zbee_zcl_packet *)data;
cmd_id = zcl->cmd_id;
if (zcl->direction == ZBEE_ZCL_FCF_TO_SERVER) {
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_poll_ctrl_srv_rx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_poll_ctrl_srv_rx_cmd_id, tvb, offset, 1, cmd_id);
offset++;
/* Handle the command dissection. */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_POLL_CTRL_CHECK_IN_RESPONSE:
proto_tree_add_item(tree, hf_zbee_zcl_poll_ctrl_start_fast_polling, tvb, offset, 1, ENC_NA);
offset++;
proto_tree_add_item(tree, hf_zbee_zcl_poll_ctrl_fast_poll_timeout, tvb, offset, 2, ENC_LITTLE_ENDIAN);
break;
case ZBEE_ZCL_CMD_ID_POLL_CTRL_FAST_POLL_STOP:
/* no payload. */
break;
case ZBEE_ZCL_CMD_ID_POLL_CTRL_SET_LONG_POLL:
proto_tree_add_item(tree, hf_zbee_zcl_poll_ctrl_new_long_poll_interval, tvb, offset, 4, ENC_LITTLE_ENDIAN);
break;
case ZBEE_ZCL_CMD_ID_POLL_CTRL_SET_SHORT_POLL:
proto_tree_add_item(tree, hf_zbee_zcl_poll_ctrl_new_short_poll_interval, tvb, offset, 2, ENC_LITTLE_ENDIAN);
break;
default:
break;
} /* switch */
} else {
/* Append the command name to the info column. */
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq: %u",
val_to_str_const(cmd_id, zbee_zcl_poll_ctrl_srv_tx_cmd_names, "Unknown Command"),
zcl->tran_seqno);
/* Add the command ID. */
proto_tree_add_item(tree, hf_zbee_zcl_poll_ctrl_srv_tx_cmd_id, tvb, offset, 1, ENC_NA);
offset++;
/* Handle the command dissection. */
switch (cmd_id) {
case ZBEE_ZCL_CMD_ID_POLL_CTRL_CHECK_IN:
/* No payload - fall through. */
default:
break;
} /* switch */
}
return tvb_captured_length(tvb);
} /* dissect_zbee_zcl_poll_ctrl */
/*FUNCTION:------------------------------------------------------
* NAME
* dissect_zcl_poll_ctrl_attr_data
* DESCRIPTION
* this function is called by ZCL foundation dissector in order to decode
* specific cluster attributes data.
* PARAMETERS
* proto_tree *tree - pointer to data tree Wireshark uses to display packet.
* tvbuff_t *tvb - pointer to buffer containing raw packet.
* guint *offset - pointer to buffer offset
* guint16 attr_id - attribute identifier
* guint data_type - attribute data type
* RETURNS
* none
*---------------------------------------------------------------
*/
static void
dissect_zcl_poll_ctrl_attr_data(proto_tree *tree, tvbuff_t *tvb, guint *offset, guint16 attr_id _U_, guint data_type)
{
/* Dissect attribute data type and data */
dissect_zcl_attr_data(tvb, tree, offset, data_type);
} /*dissect_zcl_poll_ctrl_attr_data*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_register_zbee_zcl_poll_ctrl
* DESCRIPTION
* ZigBee ZCL Poll Control cluster protocol registration.
* PARAMETERS
* none
* RETURNS
* void
*---------------------------------------------------------------
*/
void
proto_register_zbee_zcl_poll_ctrl(void)
{
/* Setup list of header fields */
static hf_register_info hf[] = {
{ &hf_zbee_zcl_poll_ctrl_attr_id,
{ "Attribute", "zbee_zcl_general.poll.attr_id", FT_UINT16, BASE_HEX, VALS(zbee_zcl_poll_ctrl_attr_names),
0x0, NULL, HFILL } },
{ &hf_zbee_zcl_poll_ctrl_srv_rx_cmd_id,
{ "Command", "zbee_zcl_general.poll.cmd.srv_rx.id", FT_UINT8, BASE_HEX,
VALS(zbee_zcl_poll_ctrl_srv_rx_cmd_names), 0x0, NULL, HFILL }},
{ &hf_zbee_zcl_poll_ctrl_srv_tx_cmd_id,
{ "Command", "zbee_zcl_general.poll.cmd.srv_tx.id", FT_UINT8, BASE_HEX,
VALS(zbee_zcl_poll_ctrl_srv_tx_cmd_names), 0x0, NULL, HFILL }},
{ &hf_zbee_zcl_poll_ctrl_start_fast_polling,
{ "Start Fast Polling", "zbee_zcl_general.poll.start", FT_BOOLEAN, 8, TFS(&tfs_true_false), 0x0,
NULL, HFILL }},
{ &hf_zbee_zcl_poll_ctrl_fast_poll_timeout,
{ "Fast Poll Timeout (quarterseconds)", "zbee_zcl_general.poll.fast_timeout", FT_UINT16, BASE_DEC, NULL,
0x0, NULL, HFILL }},
{ &hf_zbee_zcl_poll_ctrl_new_long_poll_interval,
{ "New Long Poll Interval", "zbee_zcl_general.poll.new_long_interval", FT_UINT32, BASE_DEC, NULL, 0x0, NULL,
HFILL }},
{ &hf_zbee_zcl_poll_ctrl_new_short_poll_interval,
{ "New Short Poll Interval", "zbee_zcl_general.poll.new_short_interval", FT_UINT16, BASE_DEC, NULL, 0x0, NULL,
HFILL }}
};
/* ZCL Poll Control subtrees */
static gint *ett[ZBEE_ZCL_POLL_CTRL_NUM_ETT];
ett[0] = &ett_zbee_zcl_poll_ctrl;
/* Register the ZigBee ZCL Poll Control cluster protocol name and description */
proto_zbee_zcl_poll_ctrl = proto_register_protocol("ZigBee ZCL Poll Control", "ZCL Poll Control", ZBEE_PROTOABBREV_ZCL_POLL);
proto_register_field_array(proto_zbee_zcl_poll_ctrl, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
/* Register the ZigBee ZCL Poll Control dissector. */
new_register_dissector(ZBEE_PROTOABBREV_ZCL_POLL, dissect_zbee_zcl_poll_ctrl, proto_zbee_zcl_poll_ctrl);
} /*proto_register_zbee_zcl_poll_ctrl*/
/*FUNCTION:------------------------------------------------------
* NAME
* proto_reg_handoff_zbee_zcl_poll_ctrl
* DESCRIPTION
* Hands off the ZCL Poll Control dissector.
* PARAMETERS
* none
* RETURNS
* none
*---------------------------------------------------------------
*/
void
proto_reg_handoff_zbee_zcl_poll_ctrl(void)
{
dissector_handle_t poll_handle;
/* Register our dissector with the ZigBee application dissectors. */
poll_handle = find_dissector(ZBEE_PROTOABBREV_ZCL_POLL);
dissector_add_uint("zbee.zcl.cluster", ZBEE_ZCL_CID_POLL_CONTROL, poll_handle);
zbee_zcl_init_cluster( proto_zbee_zcl_poll_ctrl,
ett_zbee_zcl_poll_ctrl,
ZBEE_ZCL_CID_POLL_CONTROL,
hf_zbee_zcl_poll_ctrl_attr_id,
hf_zbee_zcl_poll_ctrl_srv_rx_cmd_id,
hf_zbee_zcl_poll_ctrl_srv_tx_cmd_id,
(zbee_zcl_fn_attr_data)dissect_zcl_poll_ctrl_attr_data
);
} /*proto_reg_handoff_zbee_zcl_poll_ctrl*/
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| 42.339583 | 179 | 0.636511 | [
"model"
] |
b6908cc890ea57e58dfd65846a7078b2ad44fef9 | 491 | h | C | src/frontend/preprocessor.h | Asixa/Dragonfly | ef599c8a7f9d756159cd80a61dcc70fd128ef67f | [
"Apache-2.0"
] | 2 | 2020-10-23T08:17:47.000Z | 2020-10-25T06:36:58.000Z | src/frontend/preprocessor.h | Asixa/Dragonfly | ef599c8a7f9d756159cd80a61dcc70fd128ef67f | [
"Apache-2.0"
] | null | null | null | src/frontend/preprocessor.h | Asixa/Dragonfly | ef599c8a7f9d756159cd80a61dcc70fd128ef67f | [
"Apache-2.0"
] | null | null | null | #ifndef PREPROCESSOR_H
#define PREPROCESSOR_H
#include <vector>
#include <string>
#include "package-manager.h"
namespace frontend {
class Preprocessor {
static std::wstring LoadFile(std::string file);
public:
static std::wstring code;
static std::vector<int>file_numbers;
static std::vector<std::string>files;
static std::vector<std::wstring>lines;
static std::wstring MapFileNumber(int& number);
static void AddFile(std::string f);
static void Process();
};
}
#endif
| 24.55 | 49 | 0.735234 | [
"vector"
] |
b69148f0962b0bc7bc0afbb3a0a4d8855ecc4f6e | 998 | h | C | comp-slp/src/e_mod_comp_canvas.h | tizenorg/framework.uifw.e17-extra-modules | 9632650b16a377f80d107aaa9c7f06677799da32 | [
"BSD-2-Clause"
] | null | null | null | comp-slp/src/e_mod_comp_canvas.h | tizenorg/framework.uifw.e17-extra-modules | 9632650b16a377f80d107aaa9c7f06677799da32 | [
"BSD-2-Clause"
] | null | null | null | comp-slp/src/e_mod_comp_canvas.h | tizenorg/framework.uifw.e17-extra-modules | 9632650b16a377f80d107aaa9c7f06677799da32 | [
"BSD-2-Clause"
] | null | null | null | #ifdef E_TYPEDEFS
#else
#ifndef E_MOD_COMP_CANVAS_H
#define E_MOD_COMP_CANVAS_H
typedef struct _E_Comp_Canvas E_Comp_Canvas;
struct _E_Comp_Canvas
{
E_Comp *comp;
E_Zone *zone; // NULL if we have a single big canvas for all screens
Ecore_Evas *ee;
Ecore_X_Window ee_win;
Evas *evas;
int x, y, w, h; // geometry
int num;
struct {
Evas_Object *bg;
Evas_Object *fg;
double frametimes[122];
int frameskip;
} fps;
struct {
Eina_Bool run;
E_Comp_Win *cw;
Eina_Bool force_composite;
} nocomp;
struct {
Eina_Bool run;
int num;
} animation;
Evas_Object *bg_img;
Eina_Bool use_bg_img : 1;
E_Comp_HW_Ov_Win *ov;
};
EINTERN E_Comp_Canvas *e_mod_comp_canvas_add(E_Comp *c, E_Zone *zone);
EINTERN void e_mod_comp_canvas_del(E_Comp_Canvas *canvas);
#endif
#endif
| 23.761905 | 81 | 0.58517 | [
"geometry"
] |
b692592956e19717746d6d6a03ac549993c59480 | 1,242 | h | C | services/audiopolicy/common/managerdefinitions/include/AudioCollections.h | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | null | null | null | services/audiopolicy/common/managerdefinitions/include/AudioCollections.h | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | null | null | null | services/audiopolicy/common/managerdefinitions/include/AudioCollections.h | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | 2 | 2021-07-08T07:42:11.000Z | 2021-07-09T21:56:10.000Z | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <utils/String8.h>
#include <utils/Vector.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <system/audio.h>
#include <cutils/config_utils.h>
namespace android {
class PolicyAudioPort;
class AudioRoute;
using PolicyAudioPortVector = Vector<sp<PolicyAudioPort>>;
using AudioRouteVector = Vector<sp<AudioRoute>>;
sp<PolicyAudioPort> findByTagName(const PolicyAudioPortVector& policyAudioPortVector,
const std::string &tagName);
void dumpAudioRouteVector(const AudioRouteVector& audioRouteVector, String8 *dst, int spaces);
} // namespace android
| 31.05 | 94 | 0.743156 | [
"vector"
] |
b693daf0a471a92d69ee5c2ddc10cfef5c4341df | 70,739 | c | C | MSX Core/src/coretoolkit.c | michaeltryby/epanet-msx | 089245c0e99db0c1b9eab39fc4de8f47cfeeb614 | [
"MIT"
] | null | null | null | MSX Core/src/coretoolkit.c | michaeltryby/epanet-msx | 089245c0e99db0c1b9eab39fc4de8f47cfeeb614 | [
"MIT"
] | null | null | null | MSX Core/src/coretoolkit.c | michaeltryby/epanet-msx | 089245c0e99db0c1b9eab39fc4de8f47cfeeb614 | [
"MIT"
] | null | null | null | /******************************************************************************
** MODULE: CORETOOLKIT.C
** PROJECT: EPANET-MSX
** DESCRIPTION: Contains the exportable set of functions that comprise the
** new core MSX toolkit.
** COPYRIGHT: Copyright (C) 2007 Feng Shang, Lewis Rossman, and James Uber.
** All Rights Reserved. See license information in LICENSE.TXT.
** AUTHORS: L. Rossman, US EPA - NRMRL
** F. Shang, University of Cincinnati
** J. Uber, University of Cincinnati
** K. Arrowood, Xylem intern
** VERSION: 1.1
** LAST UPDATE: Refer to git history
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "msxtypes.h"
#include "msxobjects.h"
#include "msxdict.h"
#include "msxutils.h"
#include "coretoolkit.h"
// Imported Functions
double MSXqual_getNodeQual(MSXproject MSX, int j, int m);
double MSXqual_getLinkQual(MSXproject MSX, int k, int m);
int MSXqual_open(MSXproject MSX);
int MSXqual_init(MSXproject MSX);
int MSXqual_step(MSXproject MSX, long *t, long *tleft);
int MSXqual_close(MSXproject MSX);
//=============================================================================
int DLLEXPORT MSX_open(MSXproject *MSX)
/**
** Purpose:
** opens the MSX data struct.
**
** Input:
** MSX = the underlying MSXproject data struct.
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
struct Project *p = (struct Project *) calloc(1, sizeof(struct Project));
*MSX = p;
setDefaults(*MSX);
createHashTables();
return 0;
}
//=============================================================================
int DLLEXPORT MSX_close(MSXproject MSX)
{
// --- close all files
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( MSX->RptFile.file ) fclose(MSX->RptFile.file); //(LR-11/20/07, to fix bug 08)
if ( MSX->HydFile.file ) fclose(MSX->HydFile.file);
if ( MSX->TmpOutFile.file && MSX->TmpOutFile.file != MSX->OutFile.file )
fclose(MSX->TmpOutFile.file);
if ( MSX->OutFile.file ) fclose(MSX->OutFile.file);
// --- delete all temporary files
if ( MSX->OutFile.mode == SCRATCH_FILE ) remove(MSX->OutFile.name);
remove(MSX->TmpOutFile.name);
// --- free all allocated memory
MSX->RptFile.file = NULL; //(LR-11/20/07, to fix bug 08)
MSX->HydFile.file = NULL;
MSX->OutFile.file = NULL;
MSX->TmpOutFile.file = NULL;
if (MSX->QualityOpened) MSXqual_close(MSX);
freeIDs(MSX);
deleteObjects(MSX);
deleteHashTables();
MSX->ProjectOpened = FALSE;
free(MSX);
return 0;
}
//=============================================================================
int DLLEXPORT MSX_init(MSXproject MSX)
/**
** Purpose:
** Initializes the MSX project.
**
** Input:
** MSX = the underlying MSXproject data struct.
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
int err = 0;
err = finishInit(MSX);
if (!err) err = MSXqual_open(MSX);
if (!err) err = MSXqual_init(MSX);
return err;
}
//=============================================================================
int DLLEXPORT MSX_printQuality(MSXproject MSX, int type, char *id, char *species, char *fname)
/**
** Purpose:
** writes requested WQ simulation results to a text file or to the command line if no file given.
**
** Input:
** type = MSX_NODE (0) for a node or MSX_LINK (1) for a link.
** id = id of the node or link of interest.
** species = id of the species of interest.
** fname = filename to write or blank if supposed to print to the command line.
**
** Returns:
** an error code (or 0 for no error).
**
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
int err = 0;
double value = 0.0;
err = MSX_getQualityByID(MSX, type, id, species, &value);
if (err != 0) return err;
FILE *f = NULL;
if (fname != NULL) f = fopen(fname, "a");
int hrs = MSX->Qtime / 3600;
int mins = (MSX->Qtime % 3600) / 60;
char units[MAXLINE+1];
int i;
err = MSX_getindex(MSX, SPECIES, species, &i);
strcpy(units, MSX->Species[i].units);
strcat(units, "/");
if ( MSX->Species[i].type == BULK ) strcat(units, "L");
else strcat(units, AreaUnitsWords[MSX->AreaUnits]);
if (type == NODE) {
if (f != NULL) fprintf(f, "<<< Node: %s >>>\nTime %15s\nhr:min %15s\n"
"------- ---------------\n%4d:%02d %f\n\n", id, species, units, hrs, mins, value);
else {
printf("\r\n<<< Node: %s >>>\nTime %15s\nhr:min %15s\n"
"------- ---------------\n%4d:%02d %f\n\n", id, species, units, hrs, mins, value);
fflush(stdout);
}
}
else if (type == LINK) {
if (f != NULL) fprintf(f, "<<< Link: %s >>>\nTime %15s\nhr:min %15s\n"
"------- ---------------\n%4d:%02d %f\n\n", id, species, units, hrs, mins, value);
else {
printf("\r\n<<< Link: %s >>>\nTime %15s\nhr:min %15s\n"
"------- ---------------\n%4d:%02d %f\n\n", id, species, units, hrs, mins, value);
fflush(stdout);
}
}
else return ERR_INVALID_OBJECT_TYPE;
if (f != NULL) fclose(f);
f = NULL;
return err;
}
//=============================================================================
int DLLEXPORT MSX_addNode(MSXproject MSX, char *id)
/**
** Purpose:
** adds a node to the network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** id = The id
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
// Cannot modify network structure while solvers are active
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( findObject(NODE, id) >= 1 ) return ERR_INVALID_OBJECT_PARAMS;
int err = checkID(id);
if ( err ) return err;
if ( addObject(NODE, id, MSX->Nobjects[NODE]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
int i = MSX->Nobjects[NODE]+1;
if (i > MSX->Sizes[NODE]) err = MSX_setSize(MSX, NODE, i);
MSX->Node[i].rpt = 0;
MSX->Node[i].id = calloc(1, MAXID+1);
if (MSX->Node[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Node[i].id, id, MAXID);
MSX->Node[i].tank = 0;
MSX->Node[i].sources = NULL;
MSX->Nobjects[NODE]++;
return err;
}
//=============================================================================
int DLLEXPORT MSX_addTank(MSXproject MSX,char *id, double initialVolume, int mixModel, double volumeMix)
/**
** Purpose:
** adds a tank to the network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** id = The id
** initialVolume = initial volume of the tank
** mixModel = Mix Model type of the tank
** volumeMix = The capacity of the mixing compartment
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
// Cannot modify network structure while solvers are active
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( findObject(TANK, id) >= 1 ) return ERR_INVALID_OBJECT_PARAMS;
int err = checkID(id);
if ( err ) return err;
if ( addObject(TANK, id, MSX->Nobjects[TANK]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
if ( addObject(NODE, id, MSX->Nobjects[NODE]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
int i = MSX->Nobjects[TANK]+1;
if (i > MSX->Sizes[TANK]) err = MSX_setSize(MSX, TANK, i);
MSX->Tank[i].a = 1.0;
MSX->Tank[i].v0 = initialVolume;
MSX->Tank[i].mixModel = mixModel;
MSX->Tank[i].vMix = volumeMix;
MSX->Tank[i].id = calloc(1, MAXID+1);
if (MSX->Tank[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Tank[i].id, id, MAXID);
MSX->Tank[i].node = MSX->Nobjects[NODE]+1;
i = MSX->Nobjects[NODE]+1;
if (i > MSX->Sizes[NODE]) err = MSX_setSize(MSX, NODE, i);
MSX->Node[i].tank = MSX->Nobjects[TANK]+1;
MSX->Node[i].rpt = 0;
MSX->Node[i].id = calloc(1, MAXID+1);
if (MSX->Node[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Node[i].id, id, MAXID);
MSX->Node[i].sources = NULL;
MSX->Nobjects[NODE]++;
MSX->Nobjects[TANK]++;
return err;
}
//=============================================================================
int DLLEXPORT MSX_addReservoir(MSXproject MSX, char *id, double initialVolume, int mixModel, double volumeMix)
/**
** Purpose:
** adds a reservoir to the network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** id = The id
** initialVolume = initial volume of the tank
** mixModel = Mix Model type of the tank
** volumeMix = The capacity of the mixing compartment
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
// Cannot modify network structure while solvers are active
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( findObject(TANK, id) >= 1 ) return ERR_INVALID_OBJECT_PARAMS;
int err = checkID(id);
if ( err ) return err;
if ( addObject(TANK, id, MSX->Nobjects[TANK]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
if ( addObject(NODE, id, MSX->Nobjects[NODE]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
int i = MSX->Nobjects[TANK]+1;
if (i > MSX->Sizes[TANK]) err = MSX_setSize(MSX, TANK, i);
MSX->Tank[i].a = 0.0;
MSX->Tank[i].v0 = initialVolume;
MSX->Tank[i].mixModel = mixModel;
MSX->Tank[i].vMix = volumeMix;
MSX->Tank[i].id = calloc(1, MAXID+1);
if (MSX->Tank[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Tank[i].id, id, MAXID);
MSX->Tank[i].node = MSX->Nobjects[NODE]+1;
i = MSX->Nobjects[NODE]+1;
if (i > MSX->Sizes[NODE]) err = MSX_setSize(MSX, NODE, i);
MSX->Node[i].tank = MSX->Nobjects[TANK]+1;
MSX->Node[i].rpt = 0;
MSX->Node[i].id = calloc(1, MAXID+1);
if (MSX->Node[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Node[i].id, id, MAXID);
MSX->Node[i].sources = NULL;
MSX->Nobjects[NODE]++;
MSX->Nobjects[TANK]++;
return err;
}
//=============================================================================
int DLLEXPORT MSX_addLink(MSXproject MSX, char *id, char *startNode, char *endNode, double length, double diameter, double roughness)
/**
** Purpose:
** adds a link to the network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** id = The id
** startNode = Start node id
** endNode = End node id
** length = length of the pipe
** diameter = Diameter of the pipe
** roughness = roughness of the pipe
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
// Cannot modify network structure while solvers are active
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( findObject(LINK, id) >= 1 ) return ERR_INVALID_OBJECT_PARAMS;
int err = checkID(id);
if ( err ) return err;
if ( addObject(LINK, id, MSX->Nobjects[LINK]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
// Check that the start and end nodes exist
int x = findObject(NODE, startNode);
if ( x <= 0 ) return ERR_NAME;
int y = findObject(NODE, endNode);
if ( y <= 0 ) return ERR_NAME;
int i = MSX->Nobjects[LINK]+1;
if (i > MSX->Sizes[LINK]) err = MSX_setSize(MSX, LINK, i);
MSX->Link[i].n1 = x;
MSX->Link[i].n2 = y;
MSX->Link[i].diam = diameter;
MSX->Link[i].len = length;
MSX->Link[i].roughness = roughness;
MSX->Link[i].rpt = 0;
MSX->Link[i].id = calloc(1, MAXID+1);
if (MSX->Link[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Link[i].id, id, MAXID);
MSX->Nobjects[LINK]++;
return err;
}
//=============================================================================
int DLLEXPORT MSX_addOption(MSXproject MSX, int optionType, char *value)
/**
** Purpose:
** adds an option to the MSX data struct.
**
** Input:
** MSX = the underlying MSXproject data struct.
** optionType = the type of option
** value = the value to set the option to
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
int err = 0;
// Cannot modify network structure while solvers are active
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
int k;
switch (optionType)
{
case AREA_UNITS_OPTION:
k = MSXutils_findmatch(value, AreaUnitsWords);
if ( k < 0 ) return ERR_KEYWORD;
MSX->AreaUnits = k;
break;
case RATE_UNITS_OPTION:
k = MSXutils_findmatch(value, TimeUnitsWords);
if ( k < 0 ) return ERR_KEYWORD;
MSX->RateUnits = k;
break;
case SOLVER_OPTION:
k = MSXutils_findmatch(value, SolverTypeWords);
if ( k < 0 ) return ERR_KEYWORD;
MSX->Solver = k;
break;
case COUPLING_OPTION:
k = MSXutils_findmatch(value, CouplingWords);
if ( k < 0 ) return ERR_KEYWORD;
MSX->Coupling = k;
break;
case TIMESTEP_OPTION:
k = atoi(value);
if ( k <= 0 ) return ERR_NUMBER;
MSX->Qstep = k;
break;
case RTOL_OPTION:
if ( !MSXutils_getDouble(value, &MSX->DefRtol) ) return ERR_NUMBER;
break;
case ATOL_OPTION:
if ( !MSXutils_getDouble(value, &MSX->DefAtol) ) return ERR_NUMBER;
break;
case COMPILER_OPTION:
k = MSXutils_findmatch(value, CompilerWords);
if ( k < 0 ) return ERR_KEYWORD;
MSX->Compiler = k;
default:
return ERR_INVALID_OBJECT_TYPE;
break;
}
return err;
}
//=============================================================================
int DLLEXPORT MSX_addSpecies(MSXproject MSX, char *id, int type, int units, double aTol, double rTol)
/**
** Purpose:
** adds a species to the MSX data struct.
**
** Input:
** MSX = the underlying MSXproject data struct.
** id = the species id
** type = the species type, this will be BULK or WALL
** units = The species units code
** aTol = Absolute Tolerance
** rTol = relative Tolerance
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
if (!(type == BULK || type == WALL)) return ERR_KEYWORD;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( findObject(SPECIES, id) >= 1 ) return ERR_INVALID_OBJECT_PARAMS;
int err = checkID(id);
if ( err ) return err;
if ( addObject(SPECIES, id, MSX->Nobjects[SPECIES]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
int i = MSX->Nobjects[SPECIES]+1;
if (i > MSX->Sizes[SPECIES]) err = MSX_setSize(MSX, SPECIES, i);
MSX->Species[i].id = calloc(1, MAXID+1);
if (MSX->Species[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Species[i].id, id, MAXID);
MSX->Species[i].type = type;
switch (units)
{
case MG:
strncpy(MSX->Species[i].units, "MG", MAXUNITS);
break;
case UG:
strncpy(MSX->Species[i].units, "UG", MAXUNITS);
break;
case MOLE:
strncpy(MSX->Species[i].units, "MOLE", MAXUNITS);
break;
case MMOLE:
strncpy(MSX->Species[i].units, "MMOLE", MAXUNITS);
break;
default:
return ERR_KEYWORD;
break;
}
MSX->Species[i].aTol = aTol;
MSX->Species[i].rTol = rTol;
MSX->Species[i].pipeExpr = NULL;
MSX->Species[i].tankExpr = NULL;
MSX->Species[i].pipeExprType = NO_EXPR;
MSX->Species[i].tankExprType = NO_EXPR;
MSX->Species[i].precision = 2;
MSX->Species[i].rpt = 0;
MSX->Nobjects[SPECIES]++;
return err;
}
//=============================================================================
int DLLEXPORT MSX_addCoefficeint(MSXproject MSX, int type, char *id, double value)
/**
** Purpose:
** adds a coefficient to the MSX data struct.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = the species type, this will be PARAMETER or CONSTANT
** id = the coefficient id
** value = the coefficient value
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
int err = 0;
if (type == PARAMETER) {
if ( findObject(PATTERN, id) >= 1 ) return ERR_INVALID_OBJECT_PARAMS;
err = checkID(id);
if ( err ) return err;
if ( addObject(PARAMETER, id, MSX->Nobjects[PARAMETER]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
int i = MSX->Nobjects[PARAMETER]+1;
if (i > MSX->Sizes[PARAMETER]) err = MSX_setSize(MSX, PARAMETER, i);
MSX->Param[i].id = calloc(1, MAXID+1);
if (MSX->Param[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Param[i].id, id, MAXID);
MSX->Param[i].value = value;
MSX->Nobjects[PARAMETER]++;
}
else if (type == CONSTANT) {
if ( findObject(CONSTANT, id) >= 1 ) return ERR_INVALID_OBJECT_PARAMS;
err = checkID(id);
if ( err ) return err;
if ( addObject(CONSTANT, id, MSX->Nobjects[CONSTANT]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
int i = MSX->Nobjects[CONSTANT]+1;
if (i > MSX->Sizes[CONSTANT]) err = MSX_setSize(MSX, CONSTANT, i);
MSX->Const[i].id = calloc(1, MAXID+1);
if (MSX->Const[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Const[i].id, id, MAXID);
MSX->Const[i].value = value;
MSX->Nobjects[CONSTANT]++;
}
else err = ERR_KEYWORD;
return err;
}
//=============================================================================
int DLLEXPORT MSX_addTerm(MSXproject MSX, char *id, char *equation)
/**
** Purpose:
** adds a term to the MSX data struct.
**
** Input:
** MSX = the underlying MSXproject data struct.
** id = the term id
** equation = the term's equation
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( findObject(TERM, id) >= 1 ) return ERR_INVALID_OBJECT_PARAMS;
int err = 0;
err = checkID(id);
if ( err ) return err;
if ( addObject(TERM, id, MSX->Nobjects[TERM]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
int i = MSX->Nobjects[TERM]+1;
if (i > MSX->Sizes[TERM]) err = MSX_setSize(MSX, TERM, i);
MSX->Term[i].id = calloc(1, MAXID+1);
if (MSX->Term[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Term[i].id, id, MAXID);
MSX->Nobjects[TERM]++;
MathExpr *expr = mathexpr_create(MSX, equation, getVariableCode);
if ( expr == NULL ) return ERR_MATH_EXPR;
MSX->Term[i].expr = expr;
MSX->Term[i].equation = calloc(1, MAXLINE+1);
if (MSX->Term[i].equation == NULL) return ERR_MEMORY;
strncpy(MSX->Term[i].equation, equation, MAXLINE);
//Updates the ivar values since they are dependent on the number of terms
for (int m = 1; m < MSX->Nobjects[TERM]; m++)
{
if (MSX->Term[m].expr->ivar != -1 &&
MSX->Term[m].expr->ivar > MSX->Nobjects[SPECIES]+1)
MSX->Term[m].expr->ivar++;
}
return err;
}
//=============================================================================
int DLLEXPORT MSX_addExpression(MSXproject MSX, int classType, int expressionType, char *species, char *equation)
/**
** Purpose:
** adds a term to the MSX data struct.
**
** Input:
** MSX = the underlying MSXproject data struct.
** classType = either LINK or TANK
** expressionType = one of the types from the ExpressionType enum
** species = the expression species
** equation = the equation
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
int err = 0;
// --- determine expression type
if ( expressionType < 0 || expressionType > 3 ) return ERR_KEYWORD;
// --- determine species associated with expression
int i = findObject(SPECIES, species);
if ( i < 1 ) return ERR_NAME;
// --- check that species does not already have an expression
if ( classType == LINK )
{
if ( MSX->Species[i].pipeExprType != NO_EXPR ) return ERR_DUP_EXPR;
}
else if ( classType == TANK )
{
if ( MSX->Species[i].tankExprType != NO_EXPR ) return ERR_DUP_EXPR;
}
else return ERR_INVALID_OBJECT_PARAMS;
MathExpr *expr = mathexpr_create(MSX, equation, getVariableCode);
if ( expr == NULL ) return ERR_MATH_EXPR;
switch (classType)
{
case LINK:
MSX->Species[i].pipeExpr = expr;
MSX->Species[i].pipeExprType = expressionType;
break;
case TANK:
MSX->Species[i].tankExpr = expr;
MSX->Species[i].tankExprType = expressionType;
break;
}
return err;
}
//=============================================================================
int DLLEXPORT MSX_addSource(MSXproject MSX, int sourceType, char *nodeId, char *speciesId, double strength, char *timePattern)
/**
** Purpose:
** adds a term to the MSX data struct.
**
** Input:
** MSX = the underlying MSXproject data struct.
** sourceType = The type of source
** nodeId = Id of the node specifed
** speciesId = Id of the species specified
** strength = The strength of the source
** timePattern = The time pattern of the source
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
int err = 0;
// --- determine source type
if ( sourceType < 0 || sourceType > 3 ) return ERR_KEYWORD;
int j = findObject(NODE, nodeId);
if ( j <= 0 ) return ERR_NAME;
int m = findObject(SPECIES, speciesId);
if ( m <= 0 ) return ERR_NAME;
// --- check that species is a BULK species
if ( MSX->Species[m].type != BULK ) return 0;
// --- check if a source for this species already exists
Psource source = MSX->Node[j].sources;
while ( source )
{
if ( source->species == m ) break;
source = source->next;
}
// --- otherwise create a new source object
if ( source == NULL )
{
source = (struct Ssource *) malloc(sizeof(struct Ssource));
if ( source == NULL ) return ERR_MEMORY;
source->next = MSX->Node[j].sources;
MSX->Node[j].sources = source;
}
source->type = (char)sourceType;
source->species = m;
source->c0 = strength;
int i = 0;
i = findObject(PATTERN, timePattern);
source->pat = i;
return err;
}
//=============================================================================
int DLLEXPORT MSX_addQuality(MSXproject MSX, char *type, char *speciesId, double value, char *id)
/**
** Purpose:
** adds a term to the MSX data struct.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = The type of quality
** speciesId = Id of the species specified
** value = The value to be assigned
** id = To be used for either the node or link id, if it is global, then this field doesn't matter.
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
int err = 0;
int i = 0;
if ( MSXutils_match(type, "GLOBAL") ) i = 1;
else if ( MSXutils_match(type, "NODE") ) i = 2;
else if ( MSXutils_match(type, "LINK") ) i = 3;
else return ERR_KEYWORD;
// --- find species index
int m = findObject(SPECIES, speciesId);
if ( m <= 0 ) return ERR_NAME;
// --- for global specification, set initial quality either for
// all nodes or links depending on type of species
if ( i == 1)
{
int j;
MSX->C0[m] = value;
if ( MSX->Species[m].type == BULK )
{
for (j=1; j<=MSX->Nobjects[NODE]; j++) MSX->Node[j].c0[m] = value;
}
for (j=1; j<=MSX->Nobjects[LINK]; j++) MSX->Link[j].c0[m] = value;
}
// --- for a specific node, get its index & set its initial quality
else if ( i == 2 )
{
int j = findObject(NODE, id);
if ( j <= 0 ) return ERR_NAME;
if ( MSX->Species[m].type == BULK ) MSX->Node[j].c0[m] = value;
}
// --- for a specific link, get its index & set its initial quality
else if ( i == 3 )
{
int j = findObject(LINK, id);
if ( j <= 0 ) return ERR_NAME;
MSX->Link[j].c0[m] = value;
}
return err;
}
//=============================================================================
int DLLEXPORT MSX_addParameter(MSXproject MSX, char *type, char *paramId, double value, char *id)
/**
** Purpose:
** adds a term to the MSX data struct.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = Should be either PIPE or TANK
** paramId = Name for the parameter
** value = The value to be assigned
** id = The id of either the pipe or the tank
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
int err = 0;
// --- get parameter name
int i = findObject(PARAMETER, paramId);
// --- for pipe parameter, get pipe index and update parameter's value
if ( MSXutils_match(type, "PIPE") )
{
int j = findObject(LINK, id);
if ( j <= 0 ) return ERR_NAME;
MSX->Link[j].param[i] = value;
}
// --- for tank parameter, get tank index and update parameter's value
else if ( MSXutils_match(type, "TANK") )
{
int j = findObject(TANK, id);
if ( j <= 0 ) return ERR_NAME;
j = MSX->Node[j].tank;
if ( j > 0 ) MSX->Tank[j].param[i] = value;
}
else return ERR_KEYWORD;
return err;
}
//=============================================================================
int DLLEXPORT MSX_setReport(MSXproject MSX, char *reportType, char *id, int precision)
/**
** Purpose:
** adds a term to the MSX data struct.
**
** Input:
** MSX = the underlying MSXproject data struct.
** reportType = Specifies what is being set in the report
** id = Name for the object being set in the report
** precision = Only used with SPECIES, and if none then just put 2
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
int err = 0;
int k = MSXutils_findmatch(reportType, ReportWords);
if ( k < 0 ) return ERR_KEYWORD;
int j;
switch(k)
{
// --- keyword is NODE; parse ID names of reported nodes
case 0:
j = findObject(NODE, id);
if ( j <= 0 ) return ERR_NAME;
MSX->Node[j].rpt = 1;
break;
// --- keyword is LINK: parse ID names of reported links
case 1:
j = findObject(LINK, id);
if ( j <= 0 ) return ERR_NAME;
MSX->Link[j].rpt = 1;
break;
// --- keyword is SPECIES; get YES/NO & precision
case 2:
j = findObject(SPECIES, id);
if ( j <= 0 ) return ERR_NAME;
MSX->Species[j].rpt = 1;
MSX->Species[j].precision = precision;
break;
// --- keyword is FILE: get name of report file
case 3:
strcpy(MSX->RptFile.name, id);
break;
// --- keyword is PAGESIZE;
case 4:
if ( !MSXutils_getInt(id, &MSX->PageSize) ) return ERR_NUMBER;
break;
}
return err;
}
//=============================================================================
int DLLEXPORT MSX_setHydraulics(MSXproject MSX, float *demands, float *heads, float *flows)
/**
** Purpose:
** sets the demands, heads, and flows of in the data structure.
**
** Input:
** MSX = the underlying MSXproject data struct.
** demands = An array of the demands, one for each node
** heads = An array of the heads, one for each node
** flows = An array of the flows, one for each link
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if (MSX->D == NULL || MSX->H == NULL || MSX->Q == NULL) return ERR_INIT;
MSX->HydOffset = 1;
int err = 0;
int nNodes = MSX->Nobjects[NODE];
int nLinks = MSX->Nobjects[LINK];
int i;
//Since arrays are 0 to n-1 and the MSX arrays are indexed 1 to n
for (i=0; i<nNodes; i++) {
MSX->D[i+1] = demands[i];
MSX->H[i+1] = heads[i];
}
for (i=0; i<nLinks; i++) MSX->Q[i+1] = flows[i];
return err;
}
//=============================================================================
int DLLEXPORT MSX_setSize(MSXproject MSX, int type, int size)
/**
** Purpose:
** Sets the size of one of the MSXproject arrays.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = object type code
** size = number of objects.
**
** Output:
** None.
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
int err = 0;
if (type < 0 || type >= MAX_OBJECTS) return ERR_INVALID_OBJECT_TYPE;
if (size < 0) return ERR_INVALID_OBJECT_PARAMS;
switch (type)
{
case SPECIES:
if (MSX->Sizes[type] == 0) {
MSX->Species = (Sspecies *) calloc(size+1, sizeof(Sspecies));
if (MSX->Species == NULL) return ERR_MEMORY;
MSX->C0 = (double *) calloc(size+1, sizeof(double));
if (MSX->C0 == NULL) return ERR_MEMORY;
// Allocate space in Node, Link, and Tank objects
int i;
for (i=1; i<=MSX->Sizes[NODE]; i++) {
MSX->Node[i].c0 = (double *) calloc(size+1, sizeof(double));
if (MSX->Node[i].c0 == NULL) return ERR_MEMORY;
}
for (i=1; i<=MSX->Sizes[LINK]; i++) {
MSX->Link[i].c0 = (double *) calloc(size+1, sizeof(double));
if (MSX->Link[i].c0 == NULL) return ERR_MEMORY;
}
}
else {
MSX->Species = (Sspecies *) realloc(MSX->Species, (size+1) * sizeof(Sspecies));
if (MSX->Species == NULL) return ERR_MEMORY;
MSX->C0 = (double *) realloc(MSX->C0, (size+1) * sizeof(double));
if (MSX->C0 == NULL) return ERR_MEMORY;
for (int j=1; j<=size; j++) MSX->C0[j] = 0;
// Allocate space in Node, Link, and Tank objects
int i;
for (i=1; i<=MSX->Sizes[NODE]; i++) {
MSX->Node[i].c0 = (double *) realloc(MSX->Node[i].c0, (size+1) * sizeof(double));
if (MSX->Node[i].c0 == NULL) return ERR_MEMORY;
for (int j=1; j<=size; j++) MSX->Node[i].c0[j] = 0;
}
for (i=1; i<=MSX->Sizes[LINK]; i++) {
MSX->Link[i].c0 = (double *) realloc(MSX->Link[i].c0, (size+1) * sizeof(double));
if (MSX->Link[i].c0 == NULL) return ERR_MEMORY;
for (int j=1; j<=size; j++) MSX->Link[i].c0[j] = 0;
}
}
break;
case PARAMETER:
if (MSX->Sizes[type] == 0) {
MSX->Param = (Sparam *) calloc(size+1, sizeof(Sparam));
if (MSX->Param == NULL) return ERR_MEMORY;
// Allocate parameter in tank and link
int i;
for (i=1; i<=MSX->Sizes[TANK]; i++) {
MSX->Tank[i].param = (double *) calloc(size+1, sizeof(double));
if (MSX->Tank[i].param == NULL) return ERR_MEMORY;
}
for (i=1; i<=MSX->Sizes[LINK]; i++) {
MSX->Link[i].param = (double *) calloc(size+1, sizeof(double));
if (MSX->Link[i].param == NULL) return ERR_MEMORY;
}
}
else {
MSX->Param = (Sparam *) realloc(MSX->Param, (size+1) * sizeof(Sparam));
if (MSX->Param == NULL) return ERR_MEMORY;
// Allocate parameter in tank and link
int i;
for (i=1; i<=MSX->Sizes[TANK]; i++) {
MSX->Tank[i].param = (double *) realloc(MSX->Tank[i].param, (size+1) * sizeof(double));
if (MSX->Tank[i].param == NULL) return ERR_MEMORY;
for (int j=1; j<=size; j++) MSX->Tank[i].param[j] = 0;
}
for (i=1; i<=MSX->Sizes[LINK]; i++) {
MSX->Link[i].param = (double *) realloc(MSX->Link[i].param, (size+1) * sizeof(double));
if (MSX->Link[i].param == NULL) return ERR_MEMORY;
for (int j=1; j<=size; j++) MSX->Link[i].param[j] = 0;
}
}
break;
case CONSTANT:
if (MSX->Sizes[type] == 0) {
MSX->Const = (Sconst *) calloc(size+1, sizeof(Sconst));
if (MSX->Const == NULL) return ERR_MEMORY;
}
else {
MSX->Const = (Sconst *) realloc(MSX->Const, (size+1) * sizeof(Sconst));
if (MSX->Const == NULL) return ERR_MEMORY;
}
break;
case TERM:
if (MSX->Sizes[type] == 0) {
MSX->Term = (Sterm *) calloc(size+1, sizeof(Sterm));
if (MSX->Term == NULL) return ERR_MEMORY;
}
else {
MSX->Term = (Sterm *) realloc(MSX->Term, (size+1) * sizeof(Sterm));
if (MSX->Term == NULL) return ERR_MEMORY;
}
break;
case NODE:
if (MSX->Sizes[type] == 0) {
MSX->Node = (Snode *) calloc(size+1, sizeof(Snode));
if (MSX->Node == NULL) return ERR_MEMORY;
for (int i=1; i<size+1; i++) {
MSX->Node[i].c0 = NULL;
MSX->Node[i].c = NULL;
}
if (MSX->Sizes[SPECIES] != 0) for (int i=1; i < size+1; i++) {
if (MSX->Node[i].c0 != NULL) free(MSX->Node[i].c0);
MSX->Node[i].c0 = (double *) calloc(MSX->Sizes[SPECIES]+1, sizeof(double));
}
}
else {
MSX->Node = (Snode *) realloc(MSX->Node, (size+1) * sizeof(Snode));
if (MSX->Node == NULL) return ERR_MEMORY;
for (int i=MSX->Sizes[type]+1; i<size+1; i++) {
MSX->Node[i].c0 = NULL;
MSX->Node[i].c = NULL;
}
if (MSX->Sizes[SPECIES] != 0) for (int i=1; i < size+1; i++) {
if (MSX->Node[i].c0 != NULL) free(MSX->Node[i].c0);
MSX->Node[i].c0 = (double *) calloc(MSX->Sizes[SPECIES]+1, sizeof(double));
}
}
break;
case LINK:
if (MSX->Sizes[type] == 0) {
MSX->Link = (Slink *) calloc(size+1, sizeof(Slink));
if (MSX->Link == NULL) return ERR_MEMORY;
//Initialize the initial concentration
for (int i=1; i<size+1; i++) {
MSX->Link[i].c0 = NULL;
MSX->Link[i].reacted = NULL;
}
if (MSX->Sizes[SPECIES] != 0) for (int i=1; i < size+1; i++) {
if (MSX->Link[i].c0 != NULL) free(MSX->Link[i].c0);
MSX->Link[i].c0 = (double *) calloc(MSX->Sizes[SPECIES]+1, sizeof(double));
}
//Initialize the paramaters
for (int i=1; i<size+1; i++) MSX->Link[i].param = NULL;
if (MSX->Sizes[PARAMETER] != 0) for (int i=1; i < size+1; i++) {
if (MSX->Link[i].param != NULL) free(MSX->Link[i].param);
MSX->Link[i].param = (double *) calloc(MSX->Sizes[PARAMETER]+1, sizeof(double));
}
}
else {
MSX->Link = (Slink *) realloc(MSX->Link, (size+1) * sizeof(Slink));
if (MSX->Link == NULL) return ERR_MEMORY;
//Initialize the initial concentration
for (int i=MSX->Sizes[type]+1; i<size+1; i++) {
MSX->Link[i].c0 = NULL;
MSX->Link[i].reacted = NULL;
}
if (MSX->Sizes[SPECIES] != 0) for (int i=1; i < size+1; i++) {
if (MSX->Link[i].c0 != NULL) free(MSX->Link[i].c0);
MSX->Link[i].c0 = (double *) calloc(MSX->Sizes[SPECIES]+1, sizeof(double));
}
//Initialize the paramaters
for (int i=MSX->Sizes[type]+1; i<size+1; i++) MSX->Link[i].param = NULL;
if (MSX->Sizes[PARAMETER] != 0) for (int i=1; i < size+1; i++) {
if (MSX->Link[i].param != NULL) free(MSX->Link[i].param);
MSX->Link[i].param = (double *) calloc(MSX->Sizes[PARAMETER]+1, sizeof(double));
}
}
break;
case TANK:
if (MSX->Sizes[type] == 0) {
MSX->Tank = (Stank *) calloc(size+1, sizeof(Stank));
if (MSX->Tank == NULL) return ERR_MEMORY;
//Initialize the paramaters
for (int i=1; i<size+1; i++) {
MSX->Tank[i].param = NULL;
MSX->Tank[i].c = NULL;
}
if (MSX->Sizes[PARAMETER] != 0) for (int i=1; i < size+1; i++) {
if (MSX->Tank[i].param != NULL) free(MSX->Tank[i].param);
MSX->Tank[i].param = (double *) calloc(MSX->Sizes[PARAMETER]+1, sizeof(double));
}
}
else {
MSX->Tank = (Stank *) realloc(MSX->Tank, (size+1) * sizeof(Stank));
if (MSX->Tank == NULL) return ERR_MEMORY;
//Initialize the paramaters
for (int i=MSX->Sizes[type]+1; i<size+1; i++) {
MSX->Tank[i].param = NULL;
MSX->Tank[i].c = NULL;
}
if (MSX->Sizes[PARAMETER] != 0) for (int i=1; i < size+1; i++) {
if (MSX->Tank[i].param != NULL) free(MSX->Tank[i].param);
MSX->Tank[i].param = (double *) calloc(MSX->Sizes[PARAMETER]+1, sizeof(double));
}
}
break;
case PATTERN:
if (MSX->Sizes[type] == 0) {
MSX->Pattern = (Spattern *) calloc(size+1, sizeof(Spattern));
if (MSX->Pattern == NULL) return ERR_MEMORY;
}
else {
MSX->Pattern = (Spattern *) realloc(MSX->Pattern, (size+1) * sizeof(Spattern));
if (MSX->Pattern == NULL) return ERR_MEMORY;
}
break;
default:
return ERR_INVALID_OBJECT_TYPE;
break;
}
MSX->Sizes[type] = size;
return err;
}
//=============================================================================
int DLLEXPORT MSX_getindex(MSXproject MSX, int type, char *id, int *index)
/**
** Purpose:
** retrieves the index of a named MSX object.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = object type code
** id = name of water quality species.
**
** Output:
** index = index (base 1) in the list of all objects of the given type.
**
** Returns:
** an error code (or 0 for no error).
*/
{
int i;
*index = 0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
switch(type)
{
case SPECIES: i = findObject(SPECIES, id); break;
case CONSTANT: i = findObject(CONSTANT, id); break;
case PARAMETER: i = findObject(PARAMETER, id); break;
case PATTERN: i = findObject(PATTERN, id); break;
case LINK: i = findObject(LINK, id); break;
case NODE: i = findObject(NODE, id); break;
case TANK: i = findObject(TANK, id); break;
default: return ERR_INVALID_OBJECT_TYPE;
}
if ( i < 1 ) return ERR_UNDEFINED_OBJECT_ID;
*index = i;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getIDlen(MSXproject MSX, int type, int index, int *len)
/**
** Purpose:
** retrieves the number of characters in the ID name of an MSX object.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = object type code
** index = index (base 1) of the object in list of all objects of the
** given type.
**
** Output:
** len = number of characters in the object's ID name.
**
** Returns:
** an error code (or 0 for no error).
*/
{
int i;
*len = 0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
switch(type)
{
case SPECIES: i = SPECIES; break;
case CONSTANT: i = CONSTANT; break;
case PARAMETER: i = PARAMETER; break;
case PATTERN: i = PATTERN; break;
case LINK: i = LINK; break;
case NODE: i = NODE; break;
case TANK: i = TANK; break;
default: return ERR_INVALID_OBJECT_TYPE;
}
if ( index < 1 || index > MSX->Nobjects[i] ) return ERR_INVALID_OBJECT_INDEX;
switch(i)
{
case SPECIES: *len = (int) strlen(MSX->Species[index].id); break;
case CONSTANT: *len = (int) strlen(MSX->Const[index].id); break;
case PARAMETER: *len = (int) strlen(MSX->Param[index].id); break;
case PATTERN: *len = (int) strlen(MSX->Pattern[index].id); break;
case LINK: *len = (int) strlen(MSX->Link[index].id); break;
case NODE: *len = (int) strlen(MSX->Node[index].id); break;
case TANK: *len = (int) strlen(MSX->Tank[index].id); break;
}
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getID(MSXproject MSX, int type, int index, char *id, int len)
/**
** Purpose:
** retrieves the name of an object given its index.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = object type code
** index = index (base 1) of the object in list of all objects of the
** given type
** len = maximum number of characters that id can hold.
**
** Output:
** id = name of the object.
**
** Returns:
** an error code (or 0 for no error).
*/
{
int i;
strcpy(id, "");
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
switch(type)
{
case SPECIES: i = SPECIES; break;
case CONSTANT: i = CONSTANT; break;
case PARAMETER: i = PARAMETER; break;
case PATTERN: i = PATTERN; break;
case LINK: i = LINK; break;
case NODE: i = NODE; break;
case TANK: i = TANK; break;
default: return ERR_INVALID_OBJECT_TYPE;
}
if ( index < 1 || index > MSX->Nobjects[i] ) return ERR_INVALID_OBJECT_INDEX;
switch(i)
{
case SPECIES: strncpy(id, MSX->Species[index].id, len); break;
case CONSTANT: strncpy(id, MSX->Const[index].id, len); break;
case PARAMETER: strncpy(id, MSX->Param[index].id, len); break;
case PATTERN: strncpy(id, MSX->Pattern[index].id, len); break;
case LINK: strncpy(id, MSX->Link[index].id, len); break;
case NODE: strncpy(id, MSX->Node[index].id, len); break;
case TANK: strncpy(id, MSX->Tank[index].id, len); break;
}
id[len] = '\0'; //(L. Rossman - 11/01/10)
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getcount(MSXproject MSX, int type, int *count)
/**
** Purpose:
** retrieves the number of objects of a specific type.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = object type code
**
** Output:
** count = number of objects of the given type.
**
** Returns:
** an error code (or 0 for no error).
*/
{
*count = 0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
switch(type)
{
case SPECIES: *count = MSX->Nobjects[SPECIES]; break;
case CONSTANT: *count = MSX->Nobjects[CONSTANT]; break;
case PARAMETER: *count = MSX->Nobjects[PARAMETER]; break;
case PATTERN: *count = MSX->Nobjects[PATTERN]; break;
case LINK: *count = MSX->Nobjects[LINK]; break;
case NODE: *count = MSX->Nobjects[NODE]; break;
case TANK: *count = MSX->Nobjects[TANK]; break;
default: return ERR_INVALID_OBJECT_TYPE;
}
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getspecies(MSXproject MSX, int index, int *type, char *units,
double *aTol, double * rTol)
/**
** Purpose:
** retrieves the attributes of a chemical species.
**
** Input:
** MSX = the underlying MSXproject data struct.
** index = index (base 1) of the species in the list of all species.
**
** Output:
** type = MSX_BULK (0) for a bulk flow species or MSX_WALL (1) for a
** surface species;
** units = character string containing the mass units defined for the species -
** must be sized in the calling program to accept up to 15 bytes
** plus a null termination character
** aTol = absolute concentration tolerance (concentration units);
** rTol = relative concentration tolerance (unitless)
**
** Returns:
** an error code (or 0 for no error).
*/
{
*type = 0;
strcpy(units, "");
*aTol = 0.0;
*rTol = 0.0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( index < 1 || index > MSX->Nobjects[SPECIES] ) return ERR_INVALID_OBJECT_INDEX;
*type = MSX->Species[index].type;
strncpy(units, MSX->Species[index].units, MAXUNITS);
*aTol = MSX->Species[index].aTol;
*rTol = MSX->Species[index].rTol;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getconstant(MSXproject MSX, int index, double *value)
/**
** Purpose:
** retrieves the value of a particular reaction constant.
**
** Input:
** MSX = the underlying MSXproject data struct.
** index = index (base 1) of the constant in the list of all constants.
**
** Output:
** value = value assigned to the constant.
**
** Returns:
** an error code (or 0 for no error).
*/
{
*value = 0.0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( index < 1 || index > MSX->Nobjects[CONSTANT] ) return ERR_INVALID_OBJECT_INDEX;
*value = MSX->Const[index].value;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getparameter(MSXproject MSX, int type, int index, int param, double *value)
/**
** Purpose:
** retrieves the value of a particular reaction parameter for a given pipe
** or tank within the pipe network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = MSX_NODE (0) for a node or MSX_LINK (1) for a link;
** index = index (base 1) assigned to the node or link;
** param = index (base 1) assigned to the reaction parameter.
**
** Output:
** value = value assigned to the parameter.
**
** Returns:
** an error code (or 0 for no error).
*/
{
int j;
*value = 0.0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( param < 1 || param > MSX->Nobjects[PARAMETER] ) return ERR_INVALID_OBJECT_INDEX;
if ( type == NODE )
{
if ( index < 1 || index > MSX->Nobjects[NODE] ) return ERR_INVALID_OBJECT_INDEX;
j = MSX->Node[index].tank;
if ( j > 0 ) *value = MSX->Tank[j].param[param];
}
else if ( type == LINK )
{
if ( index < 1 || index > MSX->Nobjects[LINK] ) return ERR_INVALID_OBJECT_INDEX;
*value = MSX->Link[index].param[param];
}
else return ERR_INVALID_OBJECT_TYPE;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getsource(MSXproject MSX, int node, int species, int *type, double *level,
int *pat)
/**
** Purpose:
** retrieves information on any external source of a particular chemical
** species assigned to a specific node of the pipe network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** node = index number (base 1) assigned to the node of interest;
** species = index number (base 1) of the species of interest;
**
** Output:
** type = one of the following of external source type codes:
** NOSOURCE = -1 for no source,
** CONCEN = 0 for a concentration source,
** MASS = 1 for a mass booster source,
** SETPOINT = 2 for a setpoint source,
** FLOWPACED = 3 for a flow paced source;
** level = the baseline concentration (or mass flow rate) of the species
** in the source;
** pat = the index of the time pattern assigned to the species at the source
**
** Returns:
** an error code (or 0 for no error).
*/
{
Psource source;
*type = NOSOURCE;
*level = 0.0;
*pat = 0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( node < 1 || node > MSX->Nobjects[NODE] ) return ERR_INVALID_OBJECT_INDEX;
if ( species < 1 || species > MSX->Nobjects[SPECIES] ) return ERR_INVALID_OBJECT_INDEX;
source = MSX->Node[node].sources;
while ( source )
{
if ( source->species == species )
{
*type = source->type;
*level = source->c0;
*pat = source->pat;
break;
}
source = source->next;
}
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getpatternlen(MSXproject MSX, int pat, int *len)
/**
** Purpose:
** retrieves the number of time periods within a source time pattern.
**
** Input:
** MSX = the underlying MSXproject data struct.
** pat = the index number (base 1) of the time pattern;
**
** Output:
** len = the number of time periods that appear in the pattern.
**
** Returns:
** an error code (or 0 for no error).
*/
{
*len = 0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( pat < 1 || pat > MSX->Nobjects[PATTERN] ) return ERR_INVALID_OBJECT_INDEX;
*len = MSX->Pattern[pat].length;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getpatternvalue(MSXproject MSX, int pat, int period, double *value)
/**
** Purpose:
** retrieves the multiplier at a specific time period for a given
** source time pattern.
**
** Input:
** MSX = the underlying MSXproject data struct.
** pat = the index number (base 1) of the time pattern;
** period = the index of the time period (starting from 1) whose
** multiplier is being sought;
**
** Output:
** value = the value of the pattern's multiplier in the desired period.
**
** Returns:
** an error code (or 0 for no error).
*/
{
int n = 1;
*value = 0.0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( pat < 1 || pat > MSX->Nobjects[PATTERN] ) return ERR_INVALID_OBJECT_INDEX;
if ( period <= MSX->Pattern[pat].length )
{
MSX->Pattern[pat].current = MSX->Pattern[pat].first;
while ( MSX->Pattern[pat].current )
{
if ( n == period )
{
*value = MSX->Pattern[pat].current->value;
return 0;
}
MSX->Pattern[pat].current = MSX->Pattern[pat].current->next;
n++;
}
}
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getinitqual(MSXproject MSX, int type, int index, int species, double *value)
/**
** Purpose:
** retrieves the initial concentration of a particular chemical species
** assigned to a specific node or link of the pipe network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = MSX_NODE (0) for a node or MSX_LINK (1) for a link;
** index = index (base 1) of the node or link of interest;
** species = index (base 1) of the specie of interest.
**
** Output:
** value = initial concentration of the specie at the node or link.
**
** Returns:
** an error code (or 0 for no error).
*/
{
*value = 0.0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( species < 1 || species > MSX->Nobjects[SPECIES] ) return ERR_INVALID_OBJECT_INDEX;
if ( type == NODE )
{
if ( index < 1 || index > MSX->Nobjects[NODE] ) return ERR_INVALID_OBJECT_INDEX;
*value = MSX->Node[index].c0[species];
}
else if ( type == LINK )
{
if ( index < 1 || index > MSX->Nobjects[LINK] ) return ERR_INVALID_OBJECT_INDEX;
*value = MSX->Link[index].c0[species];
}
else return ERR_INVALID_OBJECT_TYPE;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getQualityByIndex(MSXproject MSX, int type, int index, int species, double *value)
/**
** Purpose:
** retrieves the current concentration of a species at a particular node
** or link of the pipe network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = MSX_NODE (0) for a node or MSX_LINK (1) for a link;
** index = index (base 1) of the node or link of interest;.
** species = index (base 1) of the species of interest.
**
** Output:
** value = species concentration at the node or link.
**
** Returns:
** an error code (or 0 for no error).
*/
{
*value = 0.0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( species < 1 || species > MSX->Nobjects[SPECIES] ) return ERR_INVALID_OBJECT_INDEX;
if ( type == NODE )
{
if ( index < 1 || index > MSX->Nobjects[NODE] ) return ERR_INVALID_OBJECT_INDEX;
*value = MSXqual_getNodeQual(MSX, index, species);
}
else if ( type == LINK )
{
if ( index < 1 || index > MSX->Nobjects[LINK] ) return ERR_INVALID_OBJECT_INDEX;
*value = MSXqual_getLinkQual(MSX, index, species);
}
else return ERR_INVALID_OBJECT_TYPE;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_getQualityByID(MSXproject MSX, int type, char *id, char *species, double *value)
/**
** Purpose:
** retrieves the current concentration of a species at a particular node
** or link of the pipe network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = MSX_NODE (0) for a node or MSX_LINK (1) for a link;
** id = id of the node or link of interest;.
** species = id of the species of interest.
**
** Output:
** value = species concentration at the node or link.
**
** Returns:
** an error code (or 0 for no error).
*/
{
*value = 0.0;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( type == NODE )
{
int err = 0;
int index = 0;
int speciesIndex = 0;
err = MSX_getindex(MSX, type, id, &index);
if (err != 0) return err;
err = MSX_getindex(MSX, SPECIES, species, &speciesIndex);
if (err != 0) return err;
*value = MSXqual_getNodeQual(MSX, index, speciesIndex);
}
else if ( type == LINK )
{
int err = 0;
int index = 0;
int speciesIndex = 0;
err = MSX_getindex(MSX, type, id, &index);
if (err != 0) return err;
err = MSX_getindex(MSX, SPECIES, species, &speciesIndex);
if (err != 0) return err;
*value = MSXqual_getLinkQual(MSX, index, speciesIndex);
}
else return ERR_INVALID_OBJECT_TYPE;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_setconstant(MSXproject MSX, int index, double value)
/**
** Purpose:
** assigns a new value to a specific reaction constant.
**
** Input:
** MSX = the underlying MSXproject data struct.
** index = index (base 1) of the constant in the list of all constants;
** value = the new value to be assigned to the constant.
**
** Output:
** none.
**
** Returns:
** an error code or 0 for no error.
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( index < 1 || index > MSX->Nobjects[CONSTANT] ) return ERR_INVALID_OBJECT_INDEX;
MSX->Const[index].value = value;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_setparameter(MSXproject MSX, int type, int index, int param, double value)
/**
** Purpose:
** assigns a value to a particular reaction parameter for a given pipe
** or tank within the pipe network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = MSX_NODE (0) for a node or MSX_LINK (1) for a link;
** index = index (base 1) assigned to the node or link;
** param = index (base 1) assigned to the reaction parameter;
** value = value to be assigned to the parameter.
**
** Output:
** none.
**
** Returns:
** an error code or 0 for no error.
*/
{
int j;
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( param < 1 || param > MSX->Nobjects[PARAMETER] ) return ERR_INVALID_OBJECT_INDEX;
if ( type == NODE )
{
if ( index < 1 || index > MSX->Nobjects[NODE] ) return ERR_INVALID_OBJECT_INDEX;
j = MSX->Node[index].tank;
if ( j > 0 ) MSX->Tank[j].param[param] = value;
}
else if ( type == LINK )
{
if ( index < 1 || index > MSX->Nobjects[LINK] ) return ERR_INVALID_OBJECT_INDEX;
MSX->Link[index].param[param] = value;
}
else return ERR_INVALID_OBJECT_TYPE;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_setinitqual(MSXproject MSX, int type, int index, int species, double value)
/**
** Purpose:
** assigns an initial concentration of a particular chemical species
** to a specific node or link of the pipe network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = MSX_NODE (0) for a node or MSX_LINK (1) for a link;
** index = index (base 1) of the node or link of interest;
** species = index (base 1) of the species of interest.
** value = initial concentration of the species at the node or link.
**
** Output:
** none.
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( species < 1 || species > MSX->Nobjects[SPECIES] ) return ERR_INVALID_OBJECT_INDEX;
if ( type == NODE )
{
if ( index < 1 || index > MSX->Nobjects[NODE] ) return ERR_INVALID_OBJECT_INDEX;
if ( MSX->Species[species].type == BULK )
MSX->Node[index].c0[species] = value;
}
else if ( type == LINK )
{
if ( index < 1 || index > MSX->Nobjects[LINK] ) return ERR_INVALID_OBJECT_INDEX;
MSX->Link[index].c0[species] = value;
}
else return ERR_INVALID_OBJECT_TYPE;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_setsource(MSXproject MSX, int node, int species, int type, double level,
int pat)
/**
** Purpose:
** sets the attributes of an external source of a particular chemical
** species to a specific node of the pipe network.
**
** Input:
** MSX = the underlying MSXproject data struct.
** node = index number (base 1) assigned to the node of interest;
** species = index number (base 1) of the species of interest;
** type = one of the following of external source type codes:
** NOSOURCE = -1 for no source,
** CONCEN = 0 for a concentration source,
** MASS = 1 for a mass booster source,
** SETPOINT = 2 for a setpoint source,
** FLOWPACED = 3 for a flow paced source;
** level = the baseline concentration (or mass flow rate) of the species
** in the source;
** pat = the index of the time pattern assigned to the species at the source
**
** Output:
** none.
**
** Returns:
** an error code (or 0 for no error).
*/
{
Psource source;
// --- check for valid source parameters
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( node < 1 || node > MSX->Nobjects[NODE] ) return ERR_INVALID_OBJECT_INDEX;
if ( species < 1 || species > MSX->Nobjects[SPECIES] ) return ERR_INVALID_OBJECT_INDEX;
if ( pat > MSX->Nobjects[PATTERN] ) return ERR_INVALID_OBJECT_INDEX;
if ( pat < 0 ) pat = 0;
if ( type < NOSOURCE ||
type > FLOWPACED ) return ERR_INVALID_OBJECT_PARAMS;
if ( MSX->Species[species].type != BULK ) return ERR_INVALID_OBJECT_PARAMS;
if ( level < 0.0 ) return ERR_INVALID_OBJECT_PARAMS;
// --- check if a source for this species already exists at the node
source = MSX->Node[node].sources;
while ( source )
{
if ( source->species == species ) break;
source = source->next;
}
// --- if no current source exists then create a new one
if ( source == NULL )
{
source = (struct Ssource *) malloc(sizeof(struct Ssource));
if ( source == NULL ) return ERR_MEMORY;
source->next = MSX->Node[node].sources;
MSX->Node[node].sources = source;
}
// --- assign parameters to the source
source->type = (char)type;
source->species = species;
source->c0 = level;
source->pat = pat;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_setpatternvalue(MSXproject MSX, int pat, int period, double value)
/**
** Purpose:
** assigns a new value to the multiplier for a specific time period in
** a given time pattern.
**
** Input:
** MSX = the underlying MSXproject data struct.
** pat = the index number (base 1) of the time pattern;
** period = the time period (starting from 1) whose multiplier is
** being replaced;
** value = the new value of the pattern's multiplier in the desired period.
**
** Output:
** none.
**
** Returns:
** an error code (or 0 for no error).
*/
{
int n = 1;
// --- check that pattern & period exists
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( pat < 1 || pat > MSX->Nobjects[PATTERN] ) return ERR_INVALID_OBJECT_INDEX;
if ( period <= 0 || period > MSX->Pattern[pat].length )
return ERR_INVALID_OBJECT_PARAMS;
// --- find desired time period in the pattern
MSX->Pattern[pat].current = MSX->Pattern[pat].first;
while ( MSX->Pattern[pat].current )
{
if ( n == period )
{
MSX->Pattern[pat].current->value = value;
return 0;
}
MSX->Pattern[pat].current = MSX->Pattern[pat].current->next;
n++;
}
return 0;
}
//=============================================================================
int DLLEXPORT MSX_addpattern(MSXproject MSX, char *id)
/**
** Purpose:
** adds a new MSX time pattern to the project.
**
** Input:
** MSX = the underlying MSXproject data struct.
** id = C-style character string with the ID name of the new pattern.
**
** Output:
** none.
**
** Returns:
** an error code (or 0 for no error).
**
** Notes:
** the new pattern is appended to the end of the existing patterns.
*/
{
int err = 0;
// --- check if a pattern with same id already exists
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( findObject(PATTERN, id) >= 1 ) return ERR_INVALID_OBJECT_PARAMS;
err = checkID(id);
if ( err ) return err;
if ( addObject(PATTERN, id, MSX->Nobjects[PATTERN]+1) < 0 ) err = ERR_MEMORY; // Insufficient memory
int i = MSX->Nobjects[PATTERN]+1;
if (i > MSX->Sizes[PATTERN]) err = MSX_setSize(MSX, PATTERN, i);
MSX->Pattern[i].id = calloc(1, MAXID+1);
if (MSX->Pattern[i].id == NULL) return ERR_MEMORY;
strncpy(MSX->Pattern[i].id, id, MAXID);
MSX->Pattern[i].length = 0;
MSX->Pattern[i].first = NULL;
MSX->Pattern[i].current = NULL;
MSX->Nobjects[PATTERN]++;
return err;
}
//=============================================================================
int DLLEXPORT MSX_setpattern(MSXproject MSX, int pat, double mult[], int len)
/**
** Purpose:
** Assigns a new set of multipliers to a given time pattern.
**
** Input:
** MSX = the underlying MSXproject data struct.
** pat = the index number (base 1) of the time pattern;
** mult[] = an array of multiplier values (base 0) to replace those
** previously used by the pattern;
** len = the number of entries in the multiplier array mult.
**
** Output:
** none.
**
** Returns:
** an error code (or 0 for no error).
*/
{
int i;
SnumList *listItem;
// --- check that pattern exists
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if ( pat < 1 || pat > MSX->Nobjects[PATTERN] ) return ERR_INVALID_OBJECT_INDEX;
if ( len < 0) len = 0;
// --- delete current multipliers
listItem = MSX->Pattern[pat].first;
while (listItem)
{
MSX->Pattern[pat].first = listItem->next;
free(listItem);
listItem = MSX->Pattern[pat].first;
}
MSX->Pattern[pat].first = NULL;
// --- create a new set of multipliers
MSX->Pattern[pat].length = 0;
for ( i = 0; i < len; i++ )
{
listItem = (SnumList *) malloc(sizeof(SnumList));
if ( listItem == NULL ) return ERR_MEMORY;
listItem->value = mult[i];
listItem->next = NULL;
if ( MSX->Pattern[pat].first == NULL )
{
MSX->Pattern[pat].current = listItem;
MSX->Pattern[pat].first = listItem;
}
else
{
MSX->Pattern[pat].current->next = listItem;
MSX->Pattern[pat].current = listItem;
}
MSX->Pattern[pat].length++;
}
MSX->Pattern[pat].interval = 0; //Feng Shang 04/17/2008
MSX->Pattern[pat].current = MSX->Pattern[pat].first; //Feng Shang 04/17/2008
return 0;
}
//=============================================================================
int DLLEXPORT MSX_step(MSXproject MSX, long *t, long *tleft)
/**
** Purpose:
** advances the WQ simulation over a single time step.
**
** Input:
** none
**
** Output:
** *t = current simulation time at the end of the step (sec)
** *tleft = time left in the simulation (sec)
**
** Returns:
** an error code (or 0 for no error).
*/
{
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if (MSX->HydOffset == 0) return ERR_HYD;
return MSXqual_step(MSX, t, tleft);
}
//=============================================================================
int DLLEXPORT MSX_setFlowFlag(MSXproject MSX, int flag)
/**
** Purpose:
** sets the flow flag and units flag.
**
** Input:
** MSX = the underlying MSXproject data struct.
** flag = the flag to set, for example CMH for cubic meters per hour.
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
int err = 0;
// Cannot modify network structure while solvers are active
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
if (flag > 9) return ERR_INVALID_OBJECT_TYPE;
MSX->Flowflag = flag;
if ( MSX->Flowflag >= LPS ) MSX->Unitsflag = SI;
else MSX->Unitsflag = US;
return 0;
}
//=============================================================================
int DLLEXPORT MSX_setTimeParameter(MSXproject MSX, int type, long value)
/**
** Purpose:
** sets a specified time parameter.
**
** Input:
** MSX = the underlying MSXproject data struct.
** type = the type of time parameter
** value = that actual value to set.
**
** Output:
** None
**
** Returns:
** an error code (or 0 for no error).
*/
{
int err = 0;
// Cannot modify network structure while solvers are active
if ( MSX == NULL ) return ERR_MSX_NOT_OPENED;
if ( !MSX->ProjectOpened ) return ERR_MSX_NOT_OPENED;
switch (type)
{
case DURATION:
MSX->Dur = value;
break;
case HYDSTEP:
MSX->Hstep = value;
break;
case QUALSTEP:
MSX->Qstep = value;
break;
case PATTERNSTEP:
MSX->Pstep = value;
break;
case PATTERNSTART:
MSX->Pstart = value;
break;
case REPORTSTEP:
MSX->Rstep = value;
break;
case REPORTSTART:
MSX->Rstart = value;
break;
case STATISTIC:
MSX->Statflag = value;
break;
default:
return ERR_INVALID_OBJECT_TYPE;
break;
}
return 0;
}
//============================================================================= | 32.856015 | 133 | 0.552298 | [
"object",
"model"
] |
b6ac7e63b4765ea60faa909610db1a104588712c | 8,789 | h | C | MarchingCubes/VisualDMC/src/DMC/Utils/Utilities.h | PhiliGuertler/ManifoldDMC | d9740e17ebadce0320f7cfb7dbb1cd728119a8ab | [
"MIT"
] | null | null | null | MarchingCubes/VisualDMC/src/DMC/Utils/Utilities.h | PhiliGuertler/ManifoldDMC | d9740e17ebadce0320f7cfb7dbb1cd728119a8ab | [
"MIT"
] | null | null | null | MarchingCubes/VisualDMC/src/DMC/Utils/Utilities.h | PhiliGuertler/ManifoldDMC | d9740e17ebadce0320f7cfb7dbb1cd728119a8ab | [
"MIT"
] | null | null | null | #pragma once
#include <LazyEngine/LazyEngine.h>
namespace DMC {
struct BufferInfo {
size_t elementCount;
size_t elementSize;
std::string name;
};
constexpr int INVALID_INDEX = -1;
__host__ __device__ inline size_t concatenateKeys(const int value1, const int value2) {
if (value1 < value2) {
return (static_cast<size_t>(value1) << 32) | (value2 & 0xFF'FF'FF'FF'FF'FFULL);
}
else {
return (static_cast<size_t>(value2) << 32) | (value1 & 0xFF'FF'FF'FF'FF'FFULL);
}
}
class ImGuiStyling {
public:
static void pushColors(int id, int currentlySelectedId, int maxId);
static void popColors();
static void pushTextColors(int id, int maxId);
static void popTextColors();
};
class Performance {
public:
static void resetStaticId();
public:
/**
* constructor
*/
Performance(const std::string& name = "Performance", const LazyEngine::TimeStep& time = 0.f);
/**
* Adds a single child performance
*/
void addChild(const Performance& performance);
/**
* adds a whole bunch of child performances
*/
void addChildren(const std::vector<Performance>& performances);
/**
* returns the name of this performance
*/
const std::string& getName() const;
/**
* returns the cumulative time of this performance and its children
*/
const LazyEngine::TimeStep& getTime() const;
/**
* returns the child performances
*/
const std::vector<Performance>& getChildren() const;
/**
* Returns the Memory Info Snapshot
*/
const std::vector<BufferInfo>& getMemorySnapshot() const;
// ### ImGui Things ################################################ //
void renderChildrenUntilMatch(int* currentlySelectedId, const LazyEngine::TimeStep& totalTime) const;
/**
* Renders the children as buttons in a single line, with their sizes relative
* to their time amount.
*/
void renderImguiChildrenButtons(int *currentlySelectedId) const;
/**
* Renders the children as buttons in a clickable way
*/
void renderImGuiChildrenButtonsHuge(int* currentlySelectedId) const;
/**
* renders the name, time and percentage of the total time
*/
void renderInfo(const LazyEngine::TimeStep& totalTime) const;
/**
* Returns true if any of the children (recursively) match the given id
*/
bool containsID(int id) const;
/**
* Returns true if this Performance matches the given id
*/
bool matchesID(int id) const;
std::string toString(int depth = 0) const;
protected:
void updateTime();
protected:
std::string m_name;
LazyEngine::TimeStep m_time;
LazyEngine::TimeStep m_cumulativeTime;
std::vector<Performance> m_children;
std::vector<BufferInfo> m_memorySnapshot;
int m_id;
private:
// makes sure that every new Performance has its own id
static int s_id;
};
/**
* starts timing upon construction and stops when destructed
*/
class PerformanceTimer {
public:
PerformanceTimer(const std::string& name, Performance& performances)
: m_name(name)
, m_timer()
, m_performances(performances)
{
#ifdef LAZYENGINE_DEBUG
LAZYENGINE_INFO("Start {0}", m_name);
#endif
m_timer.start();
}
~PerformanceTimer() {
cudaCheckError();
#ifdef LAZYENGINE_DEBUG
LAZYENGINE_INFO("End {0}", m_name);
#endif
m_performances.addChild({ m_name, m_timer.stop() });
}
protected:
std::string m_name;
LazyEngine::Timer m_timer;
Performance& m_performances;
};
/**
* Turns a LazyEngine::DataView into cuda kernel-start arguments
*/
#define ToCudaArgs(x) CUDA_KERNEL(x.getNumBlocks(), x.getNumThreadsPerBlock())
// ##################################################################### //
// ### Memory Profiling ################################################ //
// ##################################################################### //
/**
* A singleton class monitoring cuda-allocations (mostly of MonitoredDeviceVectors, though)
*/
class MemoryMonitor {
public:
static MemoryMonitor& getInstance();
~MemoryMonitor() = default;
/**
* registers a single buffer
* returns a handle that can be used to unregister the buffer
*/
std::shared_ptr<BufferInfo> registerBuffer(const BufferInfo& bufferInfo);
/**
* unregisters a single buffer with its handle (returned by registerBuffer.
* If no buffer with that name was registered in the first place, nothing happens
*/
void unregisterBuffer(const std::shared_ptr<BufferInfo>& handle);
/**
* renders the buffers in a percentage-like
*/
void displayPercentagesImGui();
void displayLargeButtonsImGui();
void displayDetailsImGui();
/**
* renders the memory usage of the GPU, as well as the GPU usage of registered buffers
*/
void displayGPUInfoImGui();
/**
* returns the total amount of bytes, that is used by the registered buffers
*/
inline size_t getTotalByteCount() const {
return m_totalByteCount;
}
std::vector<BufferInfo> getMemorySnapshot() const;
inline void resetMaxTotalByteCount() {
m_maxTotalByteCount = 0;
}
inline size_t getMaxTotalByteCount() {
return m_maxTotalByteCount;
}
protected:
/**
* protected constructor to ensure singleton nature
*/
MemoryMonitor();
void updateTotalByteCount();
protected:
std::vector<std::shared_ptr<BufferInfo>> m_activeBuffers;
// stores {name, byte-count} pairs of MonitoredDeviceVectors
size_t m_totalByteCount;
int m_selectedBufferIndex;
size_t m_maxTotalByteCount;
protected:
// The singleton instance
static std::unique_ptr<MemoryMonitor> s_instance;
};
/**
* A wrapper for buffers that register and unregister themselves automatically upon construction/destruction
*/
template <typename T>
class MonitoredThrustBuffer {
public:
MonitoredThrustBuffer(size_t elementCount, const std::string& name)
: m_buffer()
, m_bufferInfo(nullptr)
{
init(elementCount, name);
}
MonitoredThrustBuffer(size_t elementCount, T initialValue, const std::string& name)
: m_buffer()
, m_bufferInfo(nullptr)
{
init(elementCount, initialValue, name);
}
~MonitoredThrustBuffer() {
MemoryMonitor::getInstance().unregisterBuffer(m_bufferInfo);
}
inline void checkMemory(size_t elementCount, const std::string& name) {
size_t numBytes = elementCount * sizeof(T);
auto info = LazyEngine::cudaMemoryInfo();
if (info.free < numBytes) {
LAZYENGINE_ERROR("Attempting to reserve {0} Bytes, while only {1} Bytes are available: {2}", numBytes, info.free, name);
throw std::exception("Out of Memory!");
}
}
inline void init(size_t elementCount, const std::string& name) {
checkMemory(elementCount, name);
m_buffer = thrust::device_vector<T>(elementCount);
m_bufferInfo = MemoryMonitor::getInstance().registerBuffer({ elementCount, sizeof(T), name });
}
inline void init(size_t elementCount, T initialValue, const std::string& name) {
checkMemory(elementCount, name);
m_buffer = thrust::device_vector<T>(elementCount, initialValue);
m_bufferInfo = MemoryMonitor::getInstance().registerBuffer({ elementCount, sizeof(T), name });
}
inline operator thrust::device_vector<T>&() {
return m_buffer;
}
inline operator const thrust::device_vector<T>&() const {
return m_buffer;
}
inline operator LazyEngine::DataView<T>() {
return m_buffer;
}
inline operator const LazyEngine::DataView<T>() const {
return m_buffer;
}
inline thrust::device_vector<T>& getBuffer() {
return m_buffer;
}
inline const thrust::device_vector<T>& getBuffer() const {
return m_buffer;
}
inline decltype(std::declval<thrust::device_vector<T>>().begin()) begin() {
return m_buffer.begin();
}
inline decltype(std::declval<thrust::device_vector<T>>().end()) end() {
return m_buffer.end();
}
inline decltype(std::declval<thrust::device_vector<T> const>().begin()) begin() const {
return m_buffer.begin();
}
inline decltype(std::declval<thrust::device_vector<T> const>().end()) end() const {
return m_buffer.end();
}
inline size_t size() const {
return m_buffer.size();
}
inline void resize(size_t numElements) {
checkMemory(numElements, m_bufferInfo->name);
m_buffer.resize(numElements);
m_bufferInfo->elementCount = numElements;
}
protected:
thrust::device_vector<T> m_buffer;
//std::string m_name;
std::shared_ptr<BufferInfo> m_bufferInfo;
};
#define VECC(a) a.x, a.y
#define VECCC(a) a.x, a.y, a.z
#define VECCCC(a) a.x, a.y, a.z, a.w
// stringifys the name of a variable
#define NameOf(variable) ((void)variable, #variable)
#ifdef LAZYENGINE_DEBUG
#define DEVICE_ASSERT(x, message, ...) if (!(x)) printf("%s (%d): " message "\n", __FUNCTION__, __LINE__, __VA_ARGS__)
#else
#define DEVICE_ASSERT(x, message, ...)
#endif
}
| 25.039886 | 124 | 0.681192 | [
"vector"
] |
b6acb4b0f3b3d8d0a88fa5892f9cd4d631fe73b1 | 422 | h | C | pyg_lib/csrc/utils/cpu/convert.h | pyg-team/pyg-lib | c1656eda314cc7d161e85da96300ffeea29d0bcb | [
"MIT"
] | 13 | 2022-03-26T21:44:41.000Z | 2022-03-31T03:36:23.000Z | pyg_lib/csrc/utils/cpu/convert.h | pyg-team/pyg-lib | c1656eda314cc7d161e85da96300ffeea29d0bcb | [
"MIT"
] | null | null | null | pyg_lib/csrc/utils/cpu/convert.h | pyg-team/pyg-lib | c1656eda314cc7d161e85da96300ffeea29d0bcb | [
"MIT"
] | null | null | null | #pragma once
#include <ATen/ATen.h>
namespace pyg {
namespace utils {
template <typename scalar_t>
at::Tensor from_vector(const std::vector<scalar_t>& vec, bool inplace = false) {
const auto out = at::from_blob((scalar_t*)vec.data(), {(int64_t)vec.size()},
c10::CppTypeToScalarType<scalar_t>::value);
return inplace ? out : out.clone();
}
} // namespace utils
} // namespace pyg
| 24.823529 | 80 | 0.646919 | [
"vector"
] |
b6b0af595ace53f76e31cc238f108318bfbd0858 | 13,028 | h | C | src/ripple_app/shamap/SHAMap.h | Ziftr/stellard | 626514cbbb2c6c2b6844315ca98a2bfcbca0b43d | [
"BSL-1.0"
] | 58 | 2015-01-07T09:10:59.000Z | 2019-07-15T14:34:01.000Z | src/ripple_app/shamap/SHAMap.h | Ziftr/stellard | 626514cbbb2c6c2b6844315ca98a2bfcbca0b43d | [
"BSL-1.0"
] | 12 | 2015-01-02T00:01:45.000Z | 2018-04-25T12:35:02.000Z | src/ripple_app/shamap/SHAMap.h | Ziftr/stellard | 626514cbbb2c6c2b6844315ca98a2bfcbca0b43d | [
"BSL-1.0"
] | 23 | 2015-01-04T00:13:27.000Z | 2019-02-15T18:01:17.000Z | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef RIPPLE_SHAMAP_H
#define RIPPLE_SHAMAP_H
#include <stack>
#include <unordered_map>
#include <boost/thread/shared_mutex.hpp>
#include "../ripple/radmap/ripple_radmap.h"
#include "../main/FullBelowCache.h"
#include "../ripple_app/shamap/SHAMapNodeID.h"
#include "../ripple_app/shamap/SHAMapItem.h"
#include "../ripple_app/shamap/SHAMapTreeNode.h"
#include "../ripple_app/shamap/SHAMapMissingNode.h"
#include "../ripple_app/shamap/SHAMapSyncFilter.h"
#include "../ripple_app/shamap/SHAMapAddNode.h"
#include "../ripple_core/nodestore/api/NodeObject.h"
#include "../ripple/common/TaggedCache.h"
#include "../ripple_basics/containers/SyncUnorderedMap.h"
#include "ripple_app/misc/SerializedLedger.h"
/*
Used for:
the Ledger
the set of transaction in a ledger
Figuring the delta between two transaction sets
Looks like:
We have a hash table of all Ledger entries mTNbyID
We have a tree of entries: root
The tree just has id's which we then have to look up in mTNbyID?
there is some cache that we check when we are looking up items?
*/
namespace std {
template <>
struct hash <ripple::SHAMapNodeID>
{
std::size_t operator() (ripple::SHAMapNodeID const& value) const
{
return value.getMHash ();
}
};
}
//------------------------------------------------------------------------------
namespace boost {
template <>
struct hash <ripple::SHAMapNodeID> : std::hash <ripple::SHAMapNodeID>
{
};
}
//------------------------------------------------------------------------------
namespace ripple {
enum SHAMapState
{
smsModifying = 0, // Objects can be added and removed (like an open ledger)
smsImmutable = 1, // Map cannot be changed (like a closed ledger)
smsSynching = 2, // Map's hash is locked in, valid nodes can be added (like a peer's closing ledger)
smsFloating = 3, // Map is free to change hash (like a syncing open ledger)
smsInvalid = 4, // Map is known not to be valid (usually syncing a corrupt ledger)
};
/** A SHAMap is both a radix tree with a fan-out of 16 and a Merkle tree.
A radix tree is a tree with two properties:
1. The key for a node is represented by the node's position in the tree
(the "prefix property").
2. A node with only one child is merged with that child
(the "merge property")
These properties in a significantly smaller memory footprint for a radix tree.
And a fan-out of 16 means that each node in the tree has at most 16 children.
See https://en.wikipedia.org/wiki/Radix_tree
A Merkle tree is a tree where each non-leaf node is labeled with the hash
of the combined labels of its children nodes.
A key property of a Merkle tree is that testing for node inclusion is
O(log(N)) where N is the number of nodes in the tree.
See https://en.wikipedia.org/wiki/Merkle_tree
Here is a pretty good explanation:
https://github.com/ripple/ripple-lib-java/blob/master/ripple-core/src/main/java/com/ripple/core/types/shamap/README.md
*/
class SHAMap
{
private:
/** Function object which handles missing nodes. */
typedef std::function <void (std::uint32_t refNum)> MissingNodeHandler;
/** Default handler which calls NetworkOPs. */
struct DefaultMissingNodeHandler
{
void operator() (std::uint32_t refNUm);
};
public:
enum
{
STATE_MAP_BUCKETS = 1024
};
static char const* getCountedObjectName () { return "SHAMap"; }
typedef boost::shared_ptr<SHAMap> pointer;
typedef const boost::shared_ptr<SHAMap>& ref;
typedef std::pair<SHAMapItem::pointer, SHAMapItem::pointer> DeltaItem;
typedef std::pair<SHAMapItem::ref, SHAMapItem::ref> DeltaRef;
typedef std::map<uint256, DeltaItem> Delta;
typedef std::unordered_map<SHAMapNodeID, SHAMapTreeNode::pointer, SHAMapNodeID_hash> NodeMap;
typedef std::stack<std::pair<SHAMapTreeNode::pointer, SHAMapNodeID>> SharedPtrNodeStack;
public:
// build new map
explicit SHAMap (SHAMapType t, FullBelowCache& fullBelowCache,
std::uint32_t seq = 1, MissingNodeHandler missing_node_handler = DefaultMissingNodeHandler());
SHAMap (SHAMapType t, uint256 const& hash, FullBelowCache& fullBelowCache,
MissingNodeHandler missing_node_handler = DefaultMissingNodeHandler());
~SHAMap ();
// Returns a new map that's a snapshot of this one.
// Handles copy on write for mutable snapshots.
SHAMap::pointer snapShot (bool isMutable);
void setLedgerSeq (std::uint32_t lseq)
{
mLedgerSeq = lseq;
}
bool hasNode (const SHAMapNodeID & id);
bool fetchRoot (uint256 const & hash, SHAMapSyncFilter * filter);
// normal hash access functions
bool hasItem (uint256 const& id);
bool delItem (uint256 const& id);
bool addItem (SHAMapItem const& i, bool isTransaction, bool hasMeta);
uint256 getHash () const
{
return root->getNodeHash ();
}
uint256 getHash ()
{
return root->getNodeHash ();
}
// save a copy if you have a temporary anyway
bool updateGiveItem (SHAMapItem::ref, bool isTransaction, bool hasMeta);
bool addGiveItem (SHAMapItem::ref, bool isTransaction, bool hasMeta);
// save a copy if you only need a temporary
SHAMapItem::pointer peekItem (uint256 const & id);
SHAMapItem::pointer peekItem (uint256 const & id, uint256 & hash);
SHAMapItem::pointer peekItem (uint256 const & id, SHAMapTreeNode::TNType & type);
// traverse functions
SHAMapItem::pointer peekFirstItem ();
SHAMapItem::pointer peekFirstItem (SHAMapTreeNode::TNType & type);
SHAMapItem::pointer peekLastItem ();
SHAMapItem::pointer peekNextItem (uint256 const& );
SHAMapItem::pointer peekNextItem (uint256 const& , SHAMapTreeNode::TNType & type);
SHAMapItem::pointer peekPrevItem (uint256 const& );
void visitNodes (std::function<void (SHAMapTreeNode&)> const&);
void visitLeaves(std::function<void (SHAMapItem::ref)> const&);
// comparison/sync functions
void getMissingNodes (std::vector<SHAMapNodeID>& nodeIDs, std::vector<uint256>& hashes, int max,
SHAMapSyncFilter * filter);
bool getNodeFat (SHAMapNodeID node, std::vector<SHAMapNodeID>& nodeIDs,
std::list<Blob >& rawNode, bool fatRoot, bool fatLeaves);
bool getRootNode (Serializer & s, SHANodeFormat format);
std::vector<uint256> getNeededHashes (int max, SHAMapSyncFilter * filter);
SHAMapAddNode addRootNode (uint256 const& hash, Blob const& rootNode, SHANodeFormat format,
SHAMapSyncFilter * filter);
SHAMapAddNode addRootNode (Blob const& rootNode, SHANodeFormat format,
SHAMapSyncFilter * filter);
SHAMapAddNode addKnownNode (SHAMapNodeID const& nodeID, Blob const& rawNode,
SHAMapSyncFilter * filter);
// status functions
void setImmutable ()
{
assert (mState != smsInvalid);
mState = smsImmutable;
}
bool isImmutable ()
{
return mState == smsImmutable;
}
bool isSynching () const
{
return (mState == smsFloating) || (mState == smsSynching);
}
void setSynching ()
{
mState = smsSynching;
}
void setFloating ()
{
mState = smsFloating;
}
void clearSynching ()
{
mState = smsModifying;
}
bool isValid ()
{
return mState != smsInvalid;
}
// caution: otherMap must be accessed only by this function
// return value: true=successfully completed, false=too different
bool compare (SHAMap::ref otherMap, Delta & differences, int maxCount);
int flushDirty (NodeObjectType t, std::uint32_t seq);
int unshare ();
void walkMap (std::vector<SHAMapMissingNode>& missingNodes, int maxMissing);
bool getPath (uint256 const & index, std::vector< Blob >& nodes, SHANodeFormat format);
bool deepCompare (SHAMap & other);
virtual void dump (bool withHashes = false);
typedef std::pair <uint256, Blob> fetchPackEntry_t;
void getFetchPack (SHAMap * have, bool includeLeaves, int max, std::function<void (uint256 const&, const Blob&)>);
void setUnbacked ()
{
mBacked = false;
}
#ifdef ENABLE_SHAMAP_CACHE
static void sweep ()
{
treeNodeCache.sweep ();
}
#endif
void markAsFull();
private:
// trusted path operations - prove a particular node is in a particular ledger
std::list<Blob > getTrustedPath (uint256 const& index);
// tree node cache operations
SHAMapTreeNode::pointer getCache (uint256 const& hash);
void canonicalize (uint256 const& hash, SHAMapTreeNode::pointer&);
// database operations
SHAMapTreeNode::pointer fetchNodeFromDB (uint256 const& hash);
SHAMapTreeNode::pointer fetchNodeNT (uint256 const& hash);
SHAMapTreeNode::pointer fetchNodeNT (
SHAMapNodeID const& id,
uint256 const& hash,
SHAMapSyncFilter *filter);
SHAMapTreeNode::pointer fetchNode (uint256 const& hash);
SHAMapTreeNode::pointer checkFilter (uint256 const& hash, SHAMapNodeID const& id,
SHAMapSyncFilter* filter);
/** Update hashes up to the root */
void dirtyUp (SharedPtrNodeStack& stack,
uint256 const& target, SHAMapTreeNode::pointer terminal);
/** Get the path from the root to the specified node */
SharedPtrNodeStack
getStack (uint256 const& id, bool include_nonmatching_leaf);
/** Walk to the specified index, returning the node */
SHAMapTreeNode* walkToPointer (uint256 const& id);
/** Unshare the node, allowing it to be modified */
void unshareNode (SHAMapTreeNode::pointer&, SHAMapNodeID const& nodeID);
/** prepare a node to be modified before flushing */
void preFlushNode (SHAMapTreeNode::pointer& node);
/** write and canonicalize modified node */
void writeNode (NodeObjectType t, std::uint32_t seq,
SHAMapTreeNode::pointer& node);
SHAMapTreeNode* firstBelow (SHAMapTreeNode*);
SHAMapTreeNode* lastBelow (SHAMapTreeNode*);
// Simple descent
// Get a child of the specified node
SHAMapTreeNode* descend (SHAMapTreeNode*, int branch);
SHAMapTreeNode* descendThrow (SHAMapTreeNode*, int branch);
SHAMapTreeNode::pointer descend (SHAMapTreeNode::ref, int branch);
SHAMapTreeNode::pointer descendThrow (SHAMapTreeNode::ref, int branch);
// Descend with filter
SHAMapTreeNode* descendAsync (SHAMapTreeNode* parent, int branch,
SHAMapNodeID const& childID, SHAMapSyncFilter* filter, bool& pending);
std::pair <SHAMapTreeNode*, SHAMapNodeID>
descend (SHAMapTreeNode* parent, SHAMapNodeID const& parentID,
int branch, SHAMapSyncFilter* filter);
// Non-storing
// Does not hook the returned node to its parent
SHAMapTreeNode::pointer descendNoStore (SHAMapTreeNode::ref, int branch);
/** If there is only one leaf below this node, get its contents */
SHAMapItem::pointer onlyBelow (SHAMapTreeNode*);
bool hasInnerNode (SHAMapNodeID const& nodeID, uint256 const& hash);
bool hasLeafNode (uint256 const& tag, uint256 const& hash);
bool walkBranch (SHAMapTreeNode* node,
SHAMapItem::ref otherMapItem, bool isFirstMap,
Delta & differences, int & maxCount);
void visitLeavesInternal (std::function<void (SHAMapItem::ref item)>& function);
int walkSubTree (bool doWrite, NodeObjectType t, std::uint32_t seq);
private:
FullBelowCache& m_fullBelowCache;
std::uint32_t mSeq;
std::uint32_t mLedgerSeq; // sequence number of ledger this is part of
#ifdef ENABLE_SHAMAP_CACHE
static TreeNodeCache treeNodeCache;
#endif
SHAMapTreeNode::pointer root;
SHAMapState mState;
SHAMapType mType;
bool mBacked; // Map is backed by the database
MissingNodeHandler m_missing_node_handler;
};
}
#endif
| 33.927083 | 119 | 0.675775 | [
"object",
"vector"
] |
b6b3e0dd131799a13ad1ae371d432d70cee8e5f2 | 7,374 | h | C | engine/ChunkedList.h | zhouzhiyong18/SubgraphMatch | e34b088ed5efc67556c91ad9591dc8718a048d59 | [
"Apache-2.0"
] | 4 | 2018-11-19T08:05:41.000Z | 2018-11-19T11:55:55.000Z | engine/ChunkedList.h | ChengTsang/SSSP | 6d6680b87e0edaac5668cbf9cb4d39ee7a77d150 | [
"Apache-2.0"
] | null | null | null | engine/ChunkedList.h | ChengTsang/SSSP | 6d6680b87e0edaac5668cbf9cb4d39ee7a77d150 | [
"Apache-2.0"
] | null | null | null | /**
* @file ChunkedList.h
* @author Songjie Niu, Shimin Chen
* @version 0.1
*
* @section LICENSE
*
* Copyright 2016 Shimin Chen (chensm@ict.ac.cn) and
* Songjie Niu (niusongjie@ict.ac.cn)
*
* 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.
*
* @section DESCRIPTION
*
* This file defined ChunkedList class serving as pointer array to optimize
* visit to messages and better to prefetch.
*
* If there is no freespace on ChunkedList, we allocate a block of
* m_mem_pool_capacity size once from memory, so as to reduce request times
* for memory.
*
* Also defined ChunkedList::Iterator class, so as to provide interface for
* users to visit ChunkedList.
*
*/
#ifndef CHUNKEDLIST_H
#define CHUNKEDLIST_H
#include <vector>
#include <malloc.h>
#include <stdlib.h>
#include "Utility.h"
using namespace std;
/** Definition of ChunkedList class. */
class ChunkedList {
public:
vector<char*> m_mem_pools; /**< pointers of all memory pools */
int m_mem_pool_capacity; /**< memory pool capacity */
int m_num_ele_per_buf; /**< element number of each memory pool */
int m_cur_mem_pool; /**< current memory pool index */
char** m_pavail; /**< pointer of next element to be appended */
char** m_pavail_begin; /**< pointer of current block begin */
char** m_pavail_end; /**< pointer of whole blocks end */
public:
/** Constructor. */
ChunkedList() {
m_mem_pool_capacity = MEMPOOL_CAPACITY;
m_num_ele_per_buf = m_mem_pool_capacity / sizeof(char*);
m_cur_mem_pool = -1;
m_pavail = m_pavail_begin = m_pavail_end = NULL;
}
/**
* Allocate a new memory pool.
* Called when there is no freespace on ChunkedList to append.
*/
void allocateNewBlock() {
char* p = (char *)memalign(64, m_mem_pool_capacity); // cache line: 64B
if (!p) { perror("memalign"); exit(1); }
m_mem_pools.push_back(p);
++m_cur_mem_pool;
m_pavail = (char **)p;
m_pavail_begin = m_pavail;
m_pavail_end = m_pavail + m_num_ele_per_buf;
}
/**
* Append a new element.
* If there is no freespace on ChunkedList to append a new element, we need
* to request for a new memory pool before allocation.
* @param p pointer of the new element to be appended
* @see allocateNewBlock()
*/
void append(void* p) {
if (m_pavail == m_pavail_end) allocateNewBlock();
*m_pavail = (char *)p;
++m_pavail;
if (m_pavail == m_pavail_end) allocateNewBlock();
else if (m_pavail == m_pavail_begin + m_num_ele_per_buf) {
m_pavail_begin = (char **)m_mem_pools[++m_cur_mem_pool];
m_pavail = m_pavail_begin;
}
}
/**
* Judge whether ChunkedList is empty.
* @retval 0 not empty
* @retval 1 empty
*/
bool isEmpty() {
if ( ! m_mem_pools.size() || (m_pavail == (char **)m_mem_pools[0]) ) {
/*
Actual condition is
( ! m_mem_pools.size() || (m_mem_pools.size() && m_pavail == mem_pool[0]) ),
here cuz of "||" property.
*/
return 1;
}
return 0;
}
/**
* Get ChunkedList tail element.
* @return tail element
*/
char* getTail() {
if (m_pavail == m_pavail_begin) { // will not remove current empty block
m_pavail_begin = (char **)m_mem_pools[--m_cur_mem_pool];
m_pavail = m_pavail_begin + m_num_ele_per_buf;
}
--m_pavail;
return *m_pavail;
}
/**
* Get total number of elements on ChunkedList.
* @see isEmpty()
* @return total number of elements
*/
int64_t total() {
if ( isEmpty() ) return 0;
int64_t r = m_num_ele_per_buf;
r *= (m_cur_mem_pool + 1);
r -= (m_pavail_begin + m_num_ele_per_buf - m_pavail);
return r;
}
/**
* Destructor.
* Free requested memory of whole runtime.
*/
~ChunkedList() {
for (int i = m_mem_pools.size()-1; i>=0; i--) {
::free(m_mem_pools[i]); // system global function
m_mem_pools[i] = NULL;
}
m_mem_pools.clear();
m_pavail = m_pavail_begin = m_pavail_end = NULL;
}
public:
/** Definition of ChunkedList::Iterator class */
class Iterator {
private:
ChunkedList* m_plist; /**< pointer of ChunkedList to be iterated on */
int m_which_chunk; /**< index of chunk to be visited */
char** m_pmy_next; /**< pointer of next element on ChunkedList */
char** m_pchunk_end; /**< pointer of current chunk end */
public:
/**
* Constructor.
* @param pl pointer of ChunkedList to be iterated on
* @see init()
*/
Iterator(ChunkedList* pl) { init(pl); }
/**
* Initialization.
* @param pl pointer of ChunkedList to be iterated on
* @see startNextChunk()
*/
void init(ChunkedList* pl) {
m_plist = pl;
m_which_chunk = 0;
startNextChunk(0);
}
/**
* Set chunk state value when start to visit next chunk.
* @param which index of chunk to be visited
*/
void startNextChunk(int which) {
if ( which < (int)m_plist->m_mem_pools.size() ) {
m_pmy_next = (char **)(m_plist->m_mem_pools[which]);
m_pchunk_end = m_pmy_next + m_plist->m_num_ele_per_buf;
} else {
m_pmy_next = NULL;
}
}
/**
* Get next element on ChunkedList.
* @see startNextChunk()
* @return next element on ChunkedList
*/
void* next() {
if ( (m_pmy_next == NULL) || (m_pmy_next == m_plist->m_pavail) ) {
return NULL;
}
void* ret = *m_pmy_next;
++m_pmy_next;
if (m_pmy_next == m_pchunk_end) {
++m_which_chunk;
startNextChunk(m_which_chunk);
}
return ret;
}
}; // definition of ChunkedList::Iterator class
public:
/*
Previous implementation below leads to the case that nowhere to delete
pointer from new. To avoid this, return only the iterator pointer.
Similiar to Node::getGenericArrayIterator().
*/
// Iterator getIterator() { return *( new Iterator(this) ); }
/**
* Get pointer of Iterator.
* @see Iterator()
* @return pointer of Iterator
*/
Iterator* getIterator() { return new Iterator(this); }
/**
* Initialize Iterator.
* @param pit pointer of Iterator
* @see init()
*/
void initIterator(Iterator* pit) { pit->init(this); }
}; // definition of ChunkedList class
#endif /* CHUNKEDLIST_H */
| 30.097959 | 86 | 0.588283 | [
"vector"
] |
b6be6c06301a685fcf06220b5f9f3583387fa979 | 11,517 | h | C | modules/SofaSphFluid/ParticleSink.h | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/SofaSphFluid/ParticleSink.h | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/SofaSphFluid/ParticleSink.h | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
//
// C++ Interface: ParticleSink
//
// Description:
//
//
// Author: Jeremie Allard, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef SOFA_COMPONENT_MISC_PARTICLESINK_H
#define SOFA_COMPONENT_MISC_PARTICLESINK_H
#include "config.h"
#include <sofa/helper/system/config.h>
#include <sofa/helper/gl/template.h>
#include <sofa/core/behavior/ProjectiveConstraintSet.h>
#include <sofa/core/behavior/MechanicalState.h>
#include <sofa/core/objectmodel/Event.h>
#include <sofa/simulation/AnimateBeginEvent.h>
#include <sofa/simulation/AnimateEndEvent.h>
#include <SofaBaseTopology/TopologySubsetData.inl>
#include <SofaBaseTopology/PointSetTopologyModifier.h>
#include <sofa/core/topology/TopologyChange.h>
#include <SofaBaseMechanics/MechanicalObject.h>
#include <vector>
#include <iterator>
#include <iostream>
#include <ostream>
#include <algorithm>
namespace sofa
{
namespace component
{
namespace misc
{
template<class TDataTypes>
class ParticleSink : public core::behavior::ProjectiveConstraintSet<TDataTypes>
{
public:
SOFA_CLASS(SOFA_TEMPLATE(ParticleSink,TDataTypes), SOFA_TEMPLATE(core::behavior::ProjectiveConstraintSet,TDataTypes));
typedef TDataTypes DataTypes;
typedef typename DataTypes::Real Real;
typedef typename DataTypes::Coord Coord;
typedef typename DataTypes::VecCoord VecCoord;
typedef typename DataTypes::Deriv Deriv;
typedef typename DataTypes::VecDeriv VecDeriv;
typedef typename DataTypes::MatrixDeriv MatrixDeriv;
typedef typename DataTypes::MatrixDeriv::RowType MatrixDerivRowType;
typedef helper::vector<Real> VecDensity;
typedef core::behavior::MechanicalState<DataTypes> MechanicalModel;
typedef helper::vector<unsigned int> SetIndexArray;
typedef Data<VecCoord> DataVecCoord;
typedef Data<VecDeriv> DataVecDeriv;
typedef Data<MatrixDeriv> DataMatrixDeriv;
Data<Deriv> planeNormal;
Data<Real> planeD0;
Data<Real> planeD1;
Data<defaulttype::Vec3f> color;
Data<bool> showPlane;
sofa::component::topology::PointSubsetData< SetIndexArray > fixed;
//Data< SetIndexArray > fixed;
protected:
ParticleSink()
: planeNormal(initData(&planeNormal, "normal", "plane normal"))
, planeD0(initData(&planeD0, (Real)0, "d0", "plane d coef at which particles acceleration is constrained to 0"))
, planeD1(initData(&planeD1, (Real)0, "d1", "plane d coef at which particles are removed"))
//TODO FIXME because of: https://github.com/sofa-framework/sofa/issues/64
//This field should support the color="red" api.
, color(initData(&color, defaulttype::Vec3f(0.0f,.5f,.2f), "color", "plane color"))
, showPlane(initData(&showPlane, false, "showPlane", "enable/disable drawing of plane"))
, fixed(initData(&fixed, "fixed", "indices of fixed particles"))
{
this->f_listening.setValue(true);
Deriv n;
DataTypes::set(n, 0, 1, 0);
planeNormal.setValue(n);
}
virtual ~ParticleSink()
{
}
public:
virtual void init()
{
this->core::behavior::ProjectiveConstraintSet<TDataTypes>::init();
if (!this->mstate) return;
sout << "ParticleSink: normal="<<planeNormal.getValue()<<" d0="<<planeD0.getValue()<<" d1="<<planeD1.getValue()<<sendl;
sofa::core::topology::BaseMeshTopology* _topology;
_topology = this->getContext()->getMeshTopology();
// Initialize functions and parameters for topology data and handler
fixed.createTopologicalEngine(_topology);
fixed.registerTopologicalData();
}
virtual void animateBegin(double /*dt*/, double time)
{
//sout << "ParticleSink: animate begin time="<<time<<sendl;
if (!this->mstate) return;
const VecCoord& x = this->mstate->read(core::ConstVecCoordId::position())->getValue();
const VecDeriv& v = this->mstate->read(core::ConstVecDerivId::velocity())->getValue();
int n = x.size();
helper::vector<unsigned int> remove;
const bool log = this->f_printLog.getValue();
for (int i=n-1; i>=0; --i) // always remove points in reverse order
{
Real d = x[i]*planeNormal.getValue()-planeD1.getValue();
if (d<0)
{
if (log)
sout << "SINK particle "<<i<<" time "<<time<<" position "<<x[i]<<" velocity "<<v[i]<<sendl;
remove.push_back(i);
}
}
if (!remove.empty())
{
//sofa::core::topology::BaseMeshTopology* _topology;
//_topology = this->getContext()->getMeshTopology();
sofa::component::topology::PointSetTopologyModifier* pointMod;
this->getContext()->get(pointMod);
if (pointMod != NULL)
{
sout << "ParticleSink: remove "<<remove.size()<<" particles using PointSetTopologyModifier."<<sendl;
pointMod->removePointsWarning(remove);
pointMod->propagateTopologicalChanges();
pointMod->removePointsProcess(remove);
}
else if(container::MechanicalObject<DataTypes>* object = dynamic_cast<container::MechanicalObject<DataTypes>*>(this->mstate.get()))
{
sout << "ParticleSink: remove "<<remove.size()<<" particles using MechanicalObject."<<sendl;
// deleting the vertices
for (unsigned int i = 0; i < remove.size(); ++i)
{
--n;
object->replaceValue(n, remove[i] );
}
// resizing the state vectors
this->mstate->resize(n);
}
else
{
sout << "ERROR(ParticleSink): no external object supporting removing points!"<<sendl;
}
}
}
template <class DataDeriv>
void projectResponseT(DataDeriv& res) ///< project dx to constrained space
{
if (!this->mstate) return;
if (fixed.getValue().empty()) return;
const SetIndexArray& _fixed = fixed.getValue();
// constraint the last value
for (unsigned int s=0; s<_fixed.size(); s++)
res[_fixed[s]] = Deriv();
}
virtual void projectResponse(const sofa::core::MechanicalParams* mparams, DataVecDeriv& dx) ///< project dx to constrained space
{
VecDeriv& res = *dx.beginEdit(mparams);
projectResponseT(res);
dx.endEdit(mparams);
}
virtual void projectVelocity(const sofa::core::MechanicalParams* /* mparams */, DataVecDeriv& /* v */) ///< project dx to constrained space (dx models a velocity)
{
}
virtual void projectPosition(const sofa::core::MechanicalParams* mparams, DataVecCoord& xData) ///< project x to constrained space (x models a position)
{
if (!this->mstate) return;
VecCoord& x = *xData.beginEdit(mparams);
helper::WriteAccessor< Data< SetIndexArray > > _fixed = fixed;
_fixed.clear();
// constraint the last value
for (unsigned int i=0; i<x.size(); i++)
{
Real d = x[i]*planeNormal.getValue()-planeD0.getValue();
if (d<0)
{
_fixed.push_back(i);
}
}
xData.endEdit(mparams);
}
virtual void projectJacobianMatrix(const sofa::core::MechanicalParams* /*mparams*/, DataMatrixDeriv& /* cData */)
{
}
virtual void animateEnd(double /*dt*/, double /*time*/)
{
}
virtual void handleEvent(sofa::core::objectmodel::Event* event)
{
if(simulation::AnimateBeginEvent::checkEventType(event) )
{
simulation::AnimateBeginEvent* ev = static_cast<simulation::AnimateBeginEvent*>(event);
animateBegin(ev->getDt(), this->getContext()->getTime());
}
else if(simulation::AnimateEndEvent::checkEventType(event) )
{
simulation::AnimateEndEvent* ev = static_cast<simulation::AnimateEndEvent*>(event);
animateEnd(ev->getDt(), this->getContext()->getTime());
}
}
virtual void draw(const core::visual::VisualParams*)
{
#ifndef SOFA_NO_OPENGL
if (!showPlane.getValue()) return;
defaulttype::Vec3d normal; normal = planeNormal.getValue();
// find a first vector inside the plane
defaulttype::Vec3d v1;
if( 0.0 != normal[0] ) v1 = defaulttype::Vec3d(-normal[1]/normal[0], 1.0, 0.0);
else if ( 0.0 != normal[1] ) v1 = defaulttype::Vec3d(1.0, -normal[0]/normal[1],0.0);
else if ( 0.0 != normal[2] ) v1 = defaulttype::Vec3d(1.0, 0.0, -normal[0]/normal[2]);
v1.normalize();
// find a second vector inside the plane and orthogonal to the first
defaulttype::Vec3d v2;
v2 = v1.cross(normal);
v2.normalize();
const float size=1.0f;
defaulttype::Vec3d center = normal*planeD0.getValue();
defaulttype::Vec3d corners[4];
corners[0] = center-v1*size-v2*size;
corners[1] = center+v1*size-v2*size;
corners[2] = center+v1*size+v2*size;
corners[3] = center-v1*size+v2*size;
// glEnable(GL_LIGHTING);
glDisable(GL_LIGHTING);
glEnable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glCullFace(GL_FRONT);
glColor3f(color.getValue()[0],color.getValue()[1],color.getValue()[2]);
glBegin(GL_QUADS);
helper::gl::glVertexT(corners[0]);
helper::gl::glVertexT(corners[1]);
helper::gl::glVertexT(corners[2]);
helper::gl::glVertexT(corners[3]);
glEnd();
glDisable(GL_CULL_FACE);
glColor4f(1,0,0,1);
#endif /* SOFA_NO_OPENGL */
}
};
}
} // namespace component
} // namespace sofa
#endif
| 37.271845 | 166 | 0.591734 | [
"object",
"vector"
] |
b6cf899ed3e1e6176eae5a9504502076f82c3083 | 1,479 | h | C | sim/graph/Graph.h | xuyanwen2012/MosaicSim | f9b91c6d98725f0ba6f10172aa5e8d9e6fd1466a | [
"BSD-2-Clause"
] | 19 | 2019-12-27T22:14:14.000Z | 2022-01-10T02:44:29.000Z | sim/graph/Graph.h | xuyanwen2012/MosaicSim | f9b91c6d98725f0ba6f10172aa5e8d9e6fd1466a | [
"BSD-2-Clause"
] | 2 | 2021-09-04T16:08:56.000Z | 2021-10-09T06:55:01.000Z | sim/graph/Graph.h | xuyanwen2012/MosaicSim | f9b91c6d98725f0ba6f10172aa5e8d9e6fd1466a | [
"BSD-2-Clause"
] | 3 | 2020-12-03T21:33:34.000Z | 2021-11-29T11:11:02.000Z | #ifndef GRAPH_H
#define GRAPH_H
#include "../common.h"
//#include "../../pass/graphgen/Graph.h"
using namespace std;
typedef enum {DATA_DEP, PHI_DEP} TEdge;
class Node {
public:
int id;
TInstr typeInstr;
int bbid;
string name;
int lat;
int width;
set<Node*> dependents;
set<Node*> parents;
set<Node*> external_dependents;
set<Node*> external_parents;
set<Node*> phi_dependents;
set<Node*> phi_parents;
set<Node*> store_addr_dependents;
Node(int id, TInstr typeInstr, int bbid, string node_name, int lat):
id(id), typeInstr(typeInstr), bbid(bbid), name(node_name), lat (lat) {}
void addDependent(Node *dest, TEdge type);
void eraseDependent(Node *dest, TEdge type);
friend ostream &operator<<(ostream &os, Node &n);
};
class BasicBlock {
public:
vector<Node*> inst;
int id;
unsigned int inst_count;
unsigned int ld_count;
unsigned int st_count;
BasicBlock(int id): id(id), inst_count(0), ld_count(0), st_count(0) {}
void addInst(Node* n);
};
class Graph {
public:
map<int, Node *> nodes;
map<int, BasicBlock*> bbs;
~Graph() { eraseAllNodes(); }
void addBasicBlock(int id);
void addNode(int id, TInstr type, int bbid, string name, int lat, int vecWidth=1);
Node *getNode(int id);
void eraseNode(Node *n);
void eraseAllNodes();
void addDependent(Node *src, Node *dest, TEdge type) ;
void eraseDependent(Node *src, Node *dest, TEdge type);
friend ostream &operator<<(ostream &os, Graph &g);
};
#endif
| 24.245902 | 84 | 0.688303 | [
"vector"
] |
b6e92842fe88d32cab53c4696a2a517c7a99ea14 | 2,754 | h | C | embree-2.0/embree/builders/splitter.h | PetrVevoda/smallupbp | 15430256733938d529a2f5c7ef4cdcd940ae4208 | [
"MIT",
"Apache-2.0",
"Unlicense"
] | 107 | 2015-01-27T22:01:49.000Z | 2021-12-27T07:44:25.000Z | src/thirdparty/embree/builders/splitter.h | westlicht/tungsten | 457c65226734784cb4d03a0d4846bc6797ab9bb7 | [
"Apache-2.0",
"Unlicense"
] | 1 | 2015-03-17T18:53:59.000Z | 2015-03-17T18:53:59.000Z | src/thirdparty/embree/builders/splitter.h | westlicht/tungsten | 457c65226734784cb4d03a0d4846bc6797ab9bb7 | [
"Apache-2.0",
"Unlicense"
] | 17 | 2015-03-12T19:11:30.000Z | 2020-11-30T15:51:23.000Z | // ======================================================================== //
// Copyright 2009-2013 Intel Corporation //
// //
// 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 __EMBREE_SPLITTER_H__
#define __EMBREE_SPLITTER_H__
#include "../geometry/geometry.h"
#include "primrefalloc.h"
#include "primrefblock.h"
namespace embree
{
/*! Splits a list of build primitives into two lists using a single thread. */
template<typename Heuristic>
class Splitter
{
typedef typename Heuristic::Split Split;
typedef typename Heuristic::PrimInfo PrimInfo;
public:
/*! the constructor directly performs the split */
Splitter (size_t thread, PrimRefAlloc* alloc, const RTCGeometry* geom,
atomic_set<PrimRefBlock>& prims, const PrimInfo& pinfo, const Split& psplit);
/*! perform specified split */
void split(size_t thread, PrimRefAlloc* alloc, const RTCGeometry* geom,
atomic_set<PrimRefBlock>& prims, const PrimInfo& pinfo, const Split& split);
/*! perform specified spatial split */
void split_spatial(size_t thread, PrimRefAlloc* alloc, const RTCGeometry* geom,
atomic_set<PrimRefBlock>& prims, const PrimInfo& pinfo, const Split& split);
/* output data */
public:
atomic_set<PrimRefBlock> lprims; //!< left primitive list
atomic_set<PrimRefBlock> rprims; //!< right primitive list
PrimInfo linfo; //!< left bounding information of primitives
PrimInfo rinfo; //!< right bounding information of primitives
Split lsplit; //!< best split for left primitives
Split rsplit; //!< best split for right primitives
};
}
#endif
| 47.482759 | 99 | 0.541394 | [
"geometry"
] |
b6e9de71652a514c1db45289a3acf8c27bb6120e | 2,266 | h | C | FuGenEditor/View/FuGenWindow.h | sereslorant/fu_gen | cc75d307189e7e3d560a94d32072b97deb94b6e5 | [
"MIT"
] | 1 | 2020-05-21T06:11:18.000Z | 2020-05-21T06:11:18.000Z | FuGenEditor/View/FuGenWindow.h | sereslorant/fu_gen | cc75d307189e7e3d560a94d32072b97deb94b6e5 | [
"MIT"
] | null | null | null | FuGenEditor/View/FuGenWindow.h | sereslorant/fu_gen | cc75d307189e7e3d560a94d32072b97deb94b6e5 | [
"MIT"
] | null | null | null | #ifndef FuGenEditor_H
#define FuGenEditor_H
#include <QtWidgets/QMainWindow>
#include <View/EdgeVisualizer/FuGenGLView.h>
#include <View/NodeEditor/FuGenNodeEditor.h>
#include <View/PipelineEditor/FuGenPipelineEditor.h>
#include <Presenter/PipelinePresenter.h>
#include <iostream>
class FuGenWindow : public QMainWindow
{
Q_OBJECT
private:
FuGenPipelineEditor *PipelineEditor;
FuGenNodeEditor *NodeEditor;
FuGenGLView *EdgeVisualizer;
//
//PipelineEditorListener *EditorListener;
//
PipelinePresenter *Presenter;
//QListView *PipelineElementList;
//
class GLViewListener : public IGLViewListener
{
private:
FuGenWindow *Window = nullptr;
public:
//
virtual void OnInitialization() override
{
if(Window != nullptr)
{
//Window->EditorListener = new PipelineEditorListener(Window->PipelineEditor);
Window->Presenter = new PipelinePresenter(Window->EdgeVisualizer);
//
//Window->Presenter->AddListener(Window->EditorListener);
Window->Presenter->AddListener(Window->NodeEditor);
//
Window->PipelineEditor->SetModel(Window->Presenter);
//
Window->PipelineEditor->AddNode(60,200)->SetModel(Window->Presenter->AddAppNode());
}
}
//
virtual void OnDraw() override
{
//
}
//
GLViewListener(FuGenWindow *window)
:Window(window)
{}
//
virtual ~GLViewListener()
{}
/*
* End of class
*/
};
//
GLViewListener ViewListener;
//
private slots:
//
void Slot_New()
{
std::cout << "New" << std::endl;
}
//
void Slot_Open()
{
std::cout << "Open" << std::endl;
}
//
void Slot_Save()
{
std::cout << "Save" << std::endl;
}
//
void Slot_SaveAs()
{
std::cout << "SaveAs" << std::endl;
}
//
void Slot_Undo()
{
std::cout << "Undo" << std::endl;
}
//
void Slot_Redo()
{
std::cout << "Redo" << std::endl;
}
//
void Slot_ChangeNodeType(QString new_value)
{
if(new_value == "Turtle")
{
Presenter->SetSpawnTurtle();
}
if(new_value == "Hypergraph generator")
{
Presenter->SetSpawnHypergraph();
}
if(new_value == "Mesh generator")
{
Presenter->SetSpawnMesh();
}
}
//
public:
//
FuGenWindow();
virtual ~FuGenWindow();
};
#endif // FuGenEditor_H
| 18.422764 | 87 | 0.642542 | [
"mesh"
] |
b6ee7b9a7a2d9f3dbeea5cb8d0bb0f79c08efa6d | 399 | h | C | src/core/ball.h | crazyStewie/SimplePong | 81c7dfc2741a736ecae1d49d39313abf9d478abc | [
"MIT"
] | null | null | null | src/core/ball.h | crazyStewie/SimplePong | 81c7dfc2741a736ecae1d49d39313abf9d478abc | [
"MIT"
] | null | null | null | src/core/ball.h | crazyStewie/SimplePong | 81c7dfc2741a736ecae1d49d39313abf9d478abc | [
"MIT"
] | null | null | null | #ifndef BALL_H
#define BALL_H
#include <src/engine/gameobject.h>
#include <raylib.h>
#include "paddle.h"
class Ball: public GameObject {
public:
explicit Ball(const char* name, std::vector<Paddle*> paddles);
void update(float delta) override;
void draw() override;
private:
Vector2 _position;
Vector2 _velocity;
float _radius;
std::vector<Paddle*> _paddles;
};
#endif | 19.95 | 66 | 0.701754 | [
"vector"
] |
8e04f51f0ac2f31f55dc8f24eda1a891a63cf970 | 3,623 | h | C | packages/Win2D.0.0.2/Include/Microsoft.Graphics.Canvas.native.h | xyzzer/LissajousFlower | dee2587c476246d99adcbed0ac73f136e2f87ff6 | [
"MIT"
] | 1 | 2016-04-18T23:45:07.000Z | 2016-04-18T23:45:07.000Z | packages/Win2D.0.0.2/Include/Microsoft.Graphics.Canvas.native.h | xyzzer/LissajousFlower | dee2587c476246d99adcbed0ac73f136e2f87ff6 | [
"MIT"
] | null | null | null | packages/Win2D.0.0.2/Include/Microsoft.Graphics.Canvas.native.h | xyzzer/LissajousFlower | dee2587c476246d99adcbed0ac73f136e2f87ff6 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use these files 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.
#pragma once
#include <inspectable.h>
#include <wrl.h>
namespace ABI
{
namespace Microsoft
{
namespace Graphics
{
namespace Canvas
{
//
// Interface provided by the various Canvas factories that is
// able to get or create objects that wrap resources.
//
[uuid(6F18BC37-016D-4510-A0BC-99B523D65E6C)]
class ICanvasFactoryNative : public IInspectable
{
public:
IFACEMETHOD(GetOrCreate)(IUnknown* resource, IInspectable** wrapper) = 0;
};
//
// Interface provided by various Canvas objects that is able to
// retrieve the wrapped resource.
//
[uuid(5F10688D-EA55-4D55-A3B0-4DDB55C0C20A)]
class ICanvasResourceWrapperNative : public IUnknown
{
public:
IFACEMETHOD(GetResource)(IUnknown** resource) = 0;
};
}
}
}
}
#if defined(__cplusplus_winrt)
#include <wrl.h>
namespace Microsoft
{
namespace Graphics
{
namespace Canvas
{
template<class WRAPPER>
WRAPPER^ GetOrCreate(IUnknown* resource)
{
using namespace Microsoft::WRL;
namespace abi = ABI::Microsoft::Graphics::Canvas;
ComPtr<abi::ICanvasFactoryNative> factory;
__abi_ThrowIfFailed(Windows::Foundation::GetActivationFactory(
reinterpret_cast<HSTRING>(WRAPPER::typeid->FullName),
&factory));
ComPtr<IInspectable> inspectableWrapper;
__abi_ThrowIfFailed(factory->GetOrCreate(resource, &inspectableWrapper));
Platform::Object^ objectWrapper = reinterpret_cast<Platform::Object^>(inspectableWrapper.Get());
return safe_cast<WRAPPER^>(objectWrapper);
}
template<typename T, typename U>
Microsoft::WRL::ComPtr<T> GetWrappedResource(U^ wrapper)
{
using namespace Microsoft::WRL;
namespace abi = ABI::Microsoft::Graphics::Canvas;
Platform::Object^ objectWrapper = wrapper;
IInspectable* inspectableWrapper = reinterpret_cast<IInspectable*>(objectWrapper);
ComPtr<abi::ICanvasResourceWrapperNative> nativeWrapper;
__abi_ThrowIfFailed(inspectableWrapper->QueryInterface(nativeWrapper.GetAddressOf()));
ComPtr<IUnknown> unknownResource;
__abi_ThrowIfFailed(nativeWrapper->GetResource(&unknownResource));
ComPtr<T> resource;
__abi_ThrowIfFailed(unknownResource.As(&resource));
return resource;
}
}
}
}
#endif // __cplusplus_winrt
| 33.546296 | 112 | 0.583494 | [
"object"
] |
8e185771e9c59cd5854fc835845a174762815f71 | 11,441 | h | C | Modules/Nonunit/Review/include/itkOptImageToImageMetricsTest2.h | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | 1 | 2015-10-12T00:14:09.000Z | 2015-10-12T00:14:09.000Z | Modules/Nonunit/Review/include/itkOptImageToImageMetricsTest2.h | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | null | null | null | Modules/Nonunit/Review/include/itkOptImageToImageMetricsTest2.h | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkOptImageToImageMetricsTest2_h
#define __itkOptImageToImageMetricsTest2_h
#include "itkTimeProbe.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkImageToImageMetric.h"
namespace itk {
template <typename FixedImageType,
typename MovingImageType,
typename InterpolatorType,
typename TransformType,
typename MetricType,
typename MetricInitializerType >
class OptImageToImageMetricsTest
{
public:
OptImageToImageMetricsTest() {}
void RunTest( FixedImageType* fixed,
MovingImageType* moving,
InterpolatorType* interpolator,
TransformType* transform,
MetricType* metric,
MetricInitializerType metricInitializer)
{
typedef typename MetricType::ParametersType ParametersType;
std::cout << "-------------------------------------------------------------------" << std::endl;
std::cout << "Testing" << std::endl;
std::cout << "\tMetric : " << metric->GetNameOfClass() << std::endl;
std::cout << "\tInterpolator : " << interpolator->GetNameOfClass() << std::endl;
std::cout << "\tTransform : " << transform->GetNameOfClass() << std::endl;
std::cout << "-------------------------------------------------------------------" << std::endl;
std::cout << std::endl;
//int result = EXIT_SUCCESS;
// connect the interpolator
metric->SetInterpolator( interpolator );
// connect the transform
metric->SetTransform( transform );
// connect the images to the metric
metric->SetFixedImage( fixed );
metric->SetMovingImage( moving );
metric->GetThreader()->SetGlobalDefaultNumberOfThreads(4);
metric->GetThreader()->SetGlobalMaximumNumberOfThreads(4);
// call custom initialization for the metric
metricInitializer.Initialize();
// Always use the same seed value.
// All instances are the same since MersenneTwisterRandomVariateGenerator
// uses a singleton pattern.
itk::Statistics::MersenneTwisterRandomVariateGenerator::GetInstance()->SetSeed( 42 );
// initialize the metric
// Samples are drawn here in metric->Initialize(),
// so we seed the random number generator
// immediately before this call.
metric->Initialize();
//Verify that Initialize has properly called
//MultiThreadingInitialize() and a series of CreateAnother();
typedef typename MetricType::TransformPointer TransformPointer;
const TransformPointer *transformPtr= metric->GetThreaderTransform();
if ((transformPtr==static_cast<const TransformPointer *>(NULL))||
(transformPtr[0].IsNull()))
{
exit(EXIT_FAILURE);
}
const TransformType *firstBSpline=
static_cast<TransformType*>(transformPtr[0].GetPointer());
typedef typename TransformType::BulkTransformPointer BulkTransformPointer;
BulkTransformPointer firstBulkTransform = firstBSpline->GetBulkTransform();
// The bulk transform may be IdentityTransform, which has no parameters
if (firstBulkTransform->GetNumberOfParameters() == 0)
{
return;
}
ParametersType firstBulkParameters = firstBulkTransform->GetParameters();
double firstBulkEntry = firstBulkParameters[0];
for ( ThreadIdType i=0; i<metric->GetThreader()->GetNumberOfThreads()-1; i++)
{
//Verify that BSpline transform pointer is being copied
if (transformPtr[i].IsNull())
{
exit(EXIT_FAILURE);
}
//Verify that bulk transform matrix in BSpline pointer is being copied
const TransformType *loopBSpline=
static_cast<TransformType*>(transformPtr[i].GetPointer());
BulkTransformPointer loopBulkTransform = loopBSpline->GetBulkTransform();
// The bulk transform may be IdentityTransform, which has no parameters
if (loopBulkTransform->GetNumberOfParameters() == 0)
{
return;
}
ParametersType loopBulkParameters = loopBulkTransform->GetParameters();
double loopBulkEntry = loopBulkParameters[0];
double entryComparisonTolerance = 0.001;
if (fabs(loopBulkEntry - firstBulkEntry)>entryComparisonTolerance)
{
exit(EXIT_FAILURE);
}
}
}
//Other registration functionality tested in
//OptImageToImageTest.cxx... skip the rest
};
template <typename FixedImageType, typename MovingImageType>
class MeanSquaresMetricInitializer
{
public:
typedef itk::MeanSquaresImageToImageMetric< FixedImageType,
MovingImageType> MetricType;
MeanSquaresMetricInitializer(MetricType* metric)
{
m_Metric = metric;
}
void Initialize()
{
// Do stuff on m_Metric
m_Metric->UseAllPixelsOn();
}
protected:
MetricType* m_Metric;
};
template < class InterpolatorType,
class TransformType,
class FixedImageReaderType,
class MovingImageReaderType >
void BasicTest( FixedImageReaderType* fixedImageReader,
MovingImageReaderType* movingImageReader,
InterpolatorType* interpolator,
TransformType* transform
)
{
typedef typename FixedImageReaderType::OutputImageType FixedImageType;
typedef typename MovingImageReaderType::OutputImageType MovingImageType;
fixedImageReader->Update();
movingImageReader->Update();
typename FixedImageType::Pointer fixed = fixedImageReader->GetOutput();
typename MovingImageType::Pointer moving = movingImageReader->GetOutput();
// Mean squares
typedef itk::MeanSquaresImageToImageMetric< FixedImageType, MovingImageType > MetricType;
typedef MeanSquaresMetricInitializer< FixedImageType, MovingImageType > MetricInitializerType;
typename MetricType::Pointer msMetric = MetricType::New();
MeanSquaresMetricInitializer< FixedImageType, MovingImageType > msMetricInitializer( msMetric );
TestAMetric( fixedImageReader, movingImageReader, interpolator,
transform, msMetric.GetPointer(), msMetricInitializer );
}
template <class FixedImageReaderType,
class MovingImageReaderType,
class InterpolatorType,
class TransformType,
class MetricType,
class MetricInitializerType>
void TestAMetric(FixedImageReaderType* fixedImageReader,
MovingImageReaderType* movingImageReader,
InterpolatorType* interpolator,
TransformType* transform,
MetricType* metric,
MetricInitializerType metricInitializer)
{
typedef typename FixedImageReaderType::OutputImageType FixedImageType;
typedef typename MovingImageReaderType::OutputImageType MovingImageType;
metric->SetFixedImageRegion( fixedImageReader->GetOutput()->GetBufferedRegion() );
OptImageToImageMetricsTest< FixedImageType,
MovingImageType,
InterpolatorType,
TransformType,
MetricType,
MetricInitializerType > testMetric;
testMetric.RunTest( fixedImageReader->GetOutput(), movingImageReader->GetOutput(),
interpolator, transform, metric, metricInitializer );
}
template <class FixedImageReaderType, class MovingImageReaderType>
void BSplineLinearTest( FixedImageReaderType* fixedImageReader,
MovingImageReaderType* movingImageReader)
{
typedef typename MovingImageReaderType::OutputImageType MovingImageType;
typedef itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType;
typedef typename FixedImageReaderType::OutputImageType FixedImageType;
typedef typename MovingImageReaderType::OutputImageType MovingImageType;
fixedImageReader->Update();
movingImageReader->Update();
typename FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();
typename MovingImageType::Pointer movingImage = movingImageReader->GetOutput();
typename FixedImageType::SpacingType fixedSpacing = fixedImage->GetSpacing();
typename FixedImageType::PointType fixedOrigin = fixedImage->GetOrigin();
typename FixedImageType::DirectionType fixedDirection = fixedImage->GetDirection();
typename FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion();
typename FixedImageType::SizeType fixedSize = fixedRegion.GetSize();
const unsigned int SpaceDimension = 2;
const unsigned int VSplineOrder = 3;
typedef double CoordinateRepType;
typedef itk::BSplineDeformableTransform<
CoordinateRepType,
SpaceDimension,
VSplineOrder > TransformType;
typename TransformType::Pointer bsplineTransform = TransformType::New();
typedef typename TransformType::RegionType RegionType;
RegionType bsplineRegion;
typename RegionType::SizeType size;
const unsigned int numberOfGridNodesOutsideTheImageSupport = VSplineOrder;
const unsigned int numberOfGridNodesInsideTheImageSupport = 5;
const unsigned int numberOfGridNodes =
numberOfGridNodesInsideTheImageSupport +
numberOfGridNodesOutsideTheImageSupport;
const unsigned int numberOfGridCells =
numberOfGridNodesInsideTheImageSupport - 1;
typename InterpolatorType::Pointer interpolator = InterpolatorType::New();
size.Fill( numberOfGridNodes );
bsplineRegion.SetSize( size );
typedef typename TransformType::SpacingType SpacingType;
SpacingType spacing;
typedef typename TransformType::OriginType OriginType;
OriginType origin;
spacing[0] = fixedSpacing[0] * fixedSize[0] / numberOfGridCells;
spacing[1] = fixedSpacing[1] * fixedSize[1] / numberOfGridCells;
const unsigned int orderShift = VSplineOrder / 2;
origin[0] = fixedOrigin[0] - orderShift * spacing[0] - fixedSpacing[0] / 2.0;
origin[1] = fixedOrigin[1] - orderShift * spacing[1] - fixedSpacing[1] / 2.0;
bsplineTransform->SetGridSpacing( spacing );
bsplineTransform->SetGridOrigin( origin );
bsplineTransform->SetGridRegion( bsplineRegion );
bsplineTransform->SetGridDirection( fixedImage->GetDirection() );
typedef typename TransformType::ParametersType ParametersType;
const unsigned int numberOfParameters = bsplineTransform->GetNumberOfParameters();
ParametersType parameters( numberOfParameters );
BasicTest(fixedImageReader, movingImageReader, interpolator.GetPointer(),
bsplineTransform.GetPointer());
}
} // end namespace itk
#endif
| 37.02589 | 100 | 0.688052 | [
"transform"
] |
8e2d65b859a62a7ea1ae647d5e16419ea5eb5389 | 749 | h | C | aws-cpp-sdk-greengrassv2/include/aws/greengrassv2/model/LambdaFilesystemPermission.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-greengrassv2/include/aws/greengrassv2/model/LambdaFilesystemPermission.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-greengrassv2/include/aws/greengrassv2/model/LambdaFilesystemPermission.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-02-28T21:36:42.000Z | 2022-02-28T21:36:42.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/greengrassv2/GreengrassV2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace GreengrassV2
{
namespace Model
{
enum class LambdaFilesystemPermission
{
NOT_SET,
ro,
rw
};
namespace LambdaFilesystemPermissionMapper
{
AWS_GREENGRASSV2_API LambdaFilesystemPermission GetLambdaFilesystemPermissionForName(const Aws::String& name);
AWS_GREENGRASSV2_API Aws::String GetNameForLambdaFilesystemPermission(LambdaFilesystemPermission value);
} // namespace LambdaFilesystemPermissionMapper
} // namespace Model
} // namespace GreengrassV2
} // namespace Aws
| 23.40625 | 110 | 0.789052 | [
"model"
] |
5e17a8a4882fef8528e971d353107c432b686610 | 1,340 | h | C | Classes/BBParticleSystem.h | privet56/isw | 260c360470ccf3d4e17d3892d2e5dde1c9f99668 | [
"MIT"
] | null | null | null | Classes/BBParticleSystem.h | privet56/isw | 260c360470ccf3d4e17d3892d2e5dde1c9f99668 | [
"MIT"
] | null | null | null | Classes/BBParticleSystem.h | privet56/isw | 260c360470ccf3d4e17d3892d2e5dde1c9f99668 | [
"MIT"
] | null | null | null | #import "BBSceneObject.h"
#import "BBPoint.h"
@class BBParticle;
@interface BBParticleSystem : BBSceneObject
{
NSMutableArray * activeParticles;
NSMutableArray * objectsToRemove;
NSMutableArray * particlePool;
GLfloat * uvCoordinates;
GLfloat * vertexes;
NSString * materialKey;
NSInteger vertexIndex;
BOOL emit;
CGFloat minU;
CGFloat maxU;
CGFloat minV;
CGFloat maxV;
NSInteger emitCounter;
BBRange emissionRange;
BBRange sizeRange;
BBRange growRange;
BBRange xVelocityRange;
BBRange yVelocityRange;
BBRange lifeRange;
BBRange decayRange;
}
@property (retain) NSString * materialKey;
@property (assign) BOOL emit;
@property (assign) NSInteger emitCounter;
@property (assign) BBRange emissionRange;
@property (assign) BBRange sizeRange;
@property (assign) BBRange growRange;
@property (assign) BBRange xVelocityRange;
@property (assign) BBRange yVelocityRange;
@property (assign) BBRange lifeRange;
@property (assign) BBRange decayRange;
- (BOOL)activeParticles;
- (id)init;
- (void)dealloc;
- (void)addVertex:(CGFloat)x y:(CGFloat)y u:(CGFloat)u v:(CGFloat)v;
- (void)awake;
- (void)buildVertexArrays;
- (void)clearDeadQueue;
- (void)emitNewParticles;
- (void)removeChildParticle:(BBParticle*)particle;
- (void)render;
- (void)setDefaultSystem;
- (void)setParticle:(NSString*)atlasKey;
- (void)update;
@end
| 21.269841 | 68 | 0.764925 | [
"render"
] |
5e1900e2ab9fb69f6f680451a3135e0d7b124c8f | 21,898 | c | C | tools/mds2asm.c | superctr/MDSDRV | ab7eb00c370bcd794efbe9447bf60dd20cea9b5e | [
"Zlib"
] | 34 | 2020-10-11T22:35:56.000Z | 2022-02-23T07:53:37.000Z | tools/mds2asm.c | superctr/MDSDRV | ab7eb00c370bcd794efbe9447bf60dd20cea9b5e | [
"Zlib"
] | 5 | 2020-10-18T22:13:08.000Z | 2022-02-22T14:42:25.000Z | tools/mds2asm.c | superctr/MDSDRV | ab7eb00c370bcd794efbe9447bf60dd20cea9b5e | [
"Zlib"
] | 1 | 2021-04-06T00:34:18.000Z | 2021-04-06T00:34:18.000Z | /*
mds2asm - .MDS file disassembler
Tries to generate somewhat readable assembly code, including MML durations and
note definitions.
Compile with `gcc -o mds2asm mds2asm.c`, run with `mds2asm input.mds > output.asm`
Note: currently, PCM data blocks are not being read from the MDS file.
Some rarely used commands (lpbl for example) might not be read properly.
/ctr 2021-01-03
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "seqdef.h"
#define FAIL(msg,...) do {fprintf(stderr,"[FAIL] : " msg, ##__VA_ARGS__); exit(-1);} while(0)
#define WARN(msg,...) do {fprintf(stderr,"[WARN] : " msg, ##__VA_ARGS__);} while(0)
#if 0
#define DEBUG(msg,...) do {fprintf(stderr,"[DEBUG] : " msg, ##__VA_ARGS__);} while (0)
#else
#define DEBUG(msg,...) do {} while (0)
#endif
enum data_type
{
DATA_UNKNOWN = 0,
//----- global data offset from sdtop
DATA_FM = 1,
DATA_PSG = 2,
DATA_PCM = 3,
DATA_PEG = 4,
//----- local data offset from tbase
DATA_LOCAL = 8,
DATA_SUB = 8,
DATA_DRUM = 9,
DATA_TYPE_MASK = 15,
DATA_PARSED = 16,
DATA_IN_DRUM_MODE = 32
};
struct header_t
{
uint16_t type;
uint8_t channel_id;
uint8_t channel_flag;
uint16_t length;
uint16_t loop;
uint8_t* data;
uint32_t hash;
char alias[32];
char label[32];
};
struct song_t
{
char* filename;
uint16_t tbase;
uint8_t tvol;
uint8_t tcount;
uint8_t max_data;
struct header_t tracks[16];
struct header_t data[256];
};
struct song_t song;
char cmd_tab[256][16];
uint8_t* mds_data = NULL;
uint32_t mds_size;
uint8_t* seq_chunk = NULL;
uint32_t seq_size = 0;
uint32_t fnv1a32(uint8_t* data, uint32_t size);
void gen_tab();
void dump_tab();
int load_file(const char* path, uint8_t** data, uint32_t* size);
int read_mds_chunk(uint8_t* data, uint32_t size);
int extract_song();
int emit_song();
//=====================================================================
int main(int argc, char* argv[])
{
gen_tab();
if(argc < 2)
{
fprintf(stderr, "usage : %s <path to MDS file>\n", argv[0]);
dump_tab();
}
else
{
if(load_file(argv[1], &mds_data, &mds_size))
{
FAIL("Couldn't open file '%s'\n", argv[1]);
}
else
{
song.filename = argv[1];
int status = 0;
if(!status) status = read_mds_chunk(mds_data, mds_size);
if(!status) status = extract_song();
if(!status) status = emit_song();
free(mds_data);
return status;
}
}
return -1;
}
//=====================================================================
uint32_t fnv1a32(uint8_t* data, uint32_t size)
{
uint32_t i, d = 2166136261;
for(i = 0; i < size; i++)
{
d = d ^ data[i];
d = d * 16777619;
}
return d;
}
//=====================================================================
void add_length(char* str, int length, char* last_str, int* last_length)
{
int prev_length = (*last_length)--;
while(*last_length > length)
{
if(strlen(last_str) && (prev_length - *last_length) < (*last_length - length))
{
static char swap_sign_buf[16];
char* a = swap_sign_buf;
strcpy(swap_sign_buf, cmd_tab[prev_length - *last_length - 1]);
while(a = strpbrk(a, "+-"))
{
if(*a == '+')
*a = '-';
else
*a = '+';
a++;
}
sprintf(cmd_tab[*last_length - 1], "%s-%s", last_str, swap_sign_buf);
}
else
{
sprintf(cmd_tab[*last_length - 1], "%s+%s", str, cmd_tab[*last_length - length - 1]);
}
(*last_length)--;
}
strcpy(cmd_tab[length - 1], str);
strcpy(last_str, str);
}
//=====================================================================
void add_lengths(char prefix)
{
char str[16], last_str[16];
int i, interval = 96, last_interval = 129;
strcpy(last_str, "");
for(i = 1; i < 64; i <<= 1)
{
if(interval < 96 && (~interval & 1))
{
sprintf(str, "%c%dd", prefix, i);
add_length(str, interval + (interval >> 1), last_str, &last_interval);
}
sprintf(str, "%c%d", prefix, i);
add_length(str, interval, last_str, &last_interval);
interval >>= 1;
}
}
//=====================================================================
void gen_tab()
{
int i;
memset(cmd_tab, 0, sizeof(cmd_tab) * sizeof(char));
// note duration parameters (00-7f)
for(i = 0; i < 128; i++)
sprintf(cmd_tab[i], "%d", i + 1);
for(i = 4; i; --i)
add_lengths(i == 1 ? 'l' : 't');
for(i = 0; i < 2; i++)
sprintf(cmd_tab[i], "%d", i);
// note commands (80-df)
strcpy(cmd_tab[rest_cmd], "rest");
strcpy(cmd_tab[tie_cmd], "tie");
for(i = 0; i < 9*17; i++)
{
int note, oct, nn;
oct = i / 17;
note = i % 17;
nn = note_start + (oct * 12) + note_value[note];
if(nn <= note_end && !strlen(cmd_tab[nn]))
sprintf(cmd_tab[nn], "%s%d", note_name[note],oct+1);
}
// channel commands
for(i = 0; i < chn_cmd_cnt; i++)
{
strcpy(cmd_tab[chn_cmd_base(i)], chn_cmd[i].name);
}
// system commands
for(i = 0; i < sys_cmd_cnt; i++)
{
strcpy(cmd_tab[sys_cmd_base(i)], sys_cmd[i].name);
}
}
//=====================================================================
void dump_tab()
{
int i;
for(i = 0; i < 256; i++)
{
if(strlen(cmd_tab[i]))
DEBUG("%d => '%s'\n", i, cmd_tab[i]);
}
}
//=====================================================================
int load_file(const char* path, uint8_t** data, uint32_t* size)
{
FILE* f = fopen(path, "rb");
if(!f)
return -1;
fseek(f, 0, SEEK_END);
*size = ftell(f);
rewind(f);
*data = (uint8_t*) malloc((*size) + 128);
int res = fread(*data, 1, *size, f) != *size;
fclose(f);
if(res)
free(*data);
return res;
}
//=====================================================================
int read_list_chunk(uint8_t* data)
{
int pos = 4;
uint32_t riff_size, chunk, chunk_size;
riff_size = *(uint32_t*)(data + pos);
if(riff_size < 8)
FAIL("File size unexpectedly short\n");
pos+=4;
riff_size += pos;
if(memcmp(&data[pos], "dblk", 4))
return 0;
pos+=4;
while(pos < riff_size)
{
uint32_t data_id;
// chunks must be word aligned
if(pos & 1)
pos++;
chunk = *(uint32_t*)(data+pos);
chunk_size = *(uint32_t*)(data+pos+4);
DEBUG("Subchunk id: %c%c%c%c (%08x), size %d bytes\n",
data[pos],data[pos+1],data[pos+2],data[pos+3],chunk,chunk_size);
switch(chunk)
{
case 0x626f6c67: // 'glob'
if(chunk_size < 4)
FAIL("glob chunk is too small\n");
data_id = *(uint32_t*)(data + pos + 8);
if(data_id > 255)
FAIL("data id is too high\n");
song.data[data_id].data = data + pos + 12;
song.data[data_id].length = chunk_size - 4;
break;
default: // ignore all other chunks
break;
}
pos += chunk_size+8;
}
return 0;
}
//=====================================================================
int read_mds_chunk(uint8_t* data, uint32_t size)
{
int pos = 4;
uint32_t riff_size, chunk, chunk_size;
if(size < 13)
FAIL("File size unexpectedly short\n");
if(memcmp(&data[0],"RIFF",4))
FAIL("Riff header not found\n");
riff_size = *(uint32_t*)(data + pos);
pos+=4;
riff_size += pos;
if(size != riff_size)
{
WARN("warning: reported file size and actual file size do not match\n"
"reported = %d\nactual = %d\n", riff_size, size
);
}
if(memcmp(&data[pos], "MDS0", 4))
FAIL("Not an MDS0 format file\n");
pos+=4;
while(pos < riff_size)
{
// chunks must be word aligned
if(pos & 1)
pos++;
chunk = *(uint32_t*)(data+pos);
chunk_size = *(uint32_t*)(data+pos+4);
DEBUG("Chunk id: %c%c%c%c (%08x), size %d bytes\n",
data[pos],data[pos+1],data[pos+2],data[pos+3],chunk,chunk_size);
switch(chunk)
{
case 0x20716573: // 'seq '
seq_chunk = data + pos + 8;
seq_size = chunk_size;
break;
case 0x5453494c: // 'LIST'
read_list_chunk(data + pos);
break;
default: // ignore all other chunks
break;
}
pos += chunk_size+8;
}
return 0;
}
//=====================================================================
uint16_t read_be16(uint8_t* a)
{
return (a[0] << 8) | a[1];
}
//=====================================================================
void analyze_track(struct header_t* header, uint8_t* data, uint32_t max_size, uint16_t track_id)
{
DEBUG("analyzing track %03x, pos = %04x, max length = %04x\n", track_id, data - mds_data, max_size);
uint32_t pos = 0;
header->data = data;
while(pos < max_size)
{
uint8_t cmd = data[pos++];
if(cmd <= note_end)
{
if(cmd >= note_start && track_id & 0x200)
{
uint8_t id = cmd - note_start;
uint32_t addr = song.tbase + read_be16(seq_chunk + song.tbase + id * 2);
if(song.max_data <= id)
song.max_data = id + 1;
if(song.data[id].type != (DATA_DRUM|DATA_PARSED))
{
song.data[id].type = (DATA_DRUM|DATA_PARSED);
song.data[id].channel_id = header->channel_id;
song.data[id].channel_flag = header->channel_flag;
analyze_track(&song.data[id], seq_chunk + addr, seq_size - addr, id + 0x400);
}
}
continue;
}
else if(cmd >= chn_cmd_base(0) && (cmd - chn_cmd_base(0) < chn_cmd_cnt))
{
const struct cmd_def* def = &chn_cmd[cmd - chn_cmd_base(0)];
if(def->flag & FLG_INS_ID)
{
uint8_t id = data[pos];
if(song.max_data <= id)
song.max_data = id + 1;
song.data[id].type = (header->channel_id < 6) ? DATA_FM : DATA_PSG;
}
else if(def->flag & FLG_PEG_ID)
{
uint8_t id = data[pos];
if(id--)
{
if(song.max_data <= id)
song.max_data = id + 1;
song.data[id].type = DATA_PEG;
}
}
else if(def->flag & FLG_PCM_ID)
{
uint8_t id = data[pos];
if(song.max_data <= id)
song.max_data = id + 1;
song.data[id].type = DATA_PCM;
}
else if(def->flag & FLG_FLG_ID)
{
if(data[pos] == 0x08) // drum mode on
track_id |= 0x200;
else if(data[pos] == 0x00) // drum mode off
track_id &= ~0x200;
}
if(def->length < 0)
pos -= def->length;
else
pos += def->length;
}
else if(cmd >= sys_cmd_base(0) && (cmd - sys_cmd_base(0) < sys_cmd_cnt))
{
const struct cmd_def* def = &sys_cmd[cmd - sys_cmd_base(0)];
if(def->length == -2 && def->flag & FLG_FINISH)
{
int16_t offset = read_be16(data + pos);
header->loop = pos + offset + 3;
}
else if(def->flag & FLG_PAT_ID)
{
uint8_t id = data[pos];
uint32_t addr = song.tbase + read_be16(seq_chunk + song.tbase + id * 2);
if(song.max_data <= id)
song.max_data = id + 1;
uint16_t type = DATA_SUB | DATA_PARSED | (track_id & 0x200 ? DATA_IN_DRUM_MODE : 0);
if(song.data[id].type != type)
{
song.data[id].type = type;
song.data[id].channel_id = header->channel_id;
song.data[id].channel_flag = header->channel_flag;
analyze_track(&song.data[id], seq_chunk + addr, seq_size - addr, id + 0x100);
}
}
if(def->length < 0)
pos -= def->length;
else
pos += def->length;
if(def->flag & FLG_FINISH)
{
header->length = pos;
break;
}
}
else
{
FAIL("unknown command %02x at 0x%08x", cmd, (data - mds_data) + pos);
}
}
DEBUG("analyzed track %03x, length = %04x, loop = %04x\n", track_id, header->length, header->loop);
}
//=====================================================================
int extract_song()
{
uint32_t i = 0;
uint32_t pos = 0;
if(!seq_chunk)
FAIL("no seq chunk\n");
if(seq_size < 4)
FAIL("seq chunk too small");
song.tbase = read_be16(seq_chunk + 0);
song.tvol = seq_chunk[2];
song.tcount = seq_chunk[3];
song.max_data = 0;
pos += 4;
i = 0;
while(pos < seq_size)
{
uint32_t addr;
if(i == song.tcount)
break;
song.tracks[i].channel_id = seq_chunk[pos + 0];
song.tracks[i].channel_flag = seq_chunk[pos + 1];
addr = song.tbase + read_be16(seq_chunk + pos + 2);
analyze_track(&song.tracks[i], seq_chunk + addr, seq_size - addr, i);
pos += 4;
i++;
}
for(i = 0; i < song.max_data; i++)
{
if(!(song.data[i].type & DATA_LOCAL) && song.data[i].length)
{
song.data[i].hash = fnv1a32(song.data[i].data, song.data[i].length);
song.data[i].type |= DATA_PARSED;
}
}
return 0;
}
//=====================================================================
#define EMIT(msg,...) do {fprintf(stdout, msg, ##__VA_ARGS__); } while(0)
void emit_track(struct header_t* header, uint16_t track_id)
{
const uint32_t max_events_per_line = 8;
uint32_t event_count = 0;
uint32_t pos = 0, max_size = header->length;
uint8_t* data = header->data;
uint8_t last_cmd = 0x00;
static uint32_t lpb_pos[5];
static uint32_t lpb_id[5];
uint32_t lpb_stack = 0;
uint32_t lpb_count = 0;
while(pos < max_size)
{
uint8_t cmd = data[pos++];
if(lpb_stack && pos == lpb_pos[lpb_stack-1])
{
event_count = 0;
EMIT("\n%sB%d",header->label, lpb_id[lpb_stack-1]);
lpb_stack--;
}
if(pos == header->loop)
{
event_count = 0;
EMIT("\n%sL",header->label);
}
if(event_count++ == 0 || cmd >= sys_cmd_base(0))
EMIT("\n\tdc.b\t");
else if(last_cmd <= note_end)
EMIT(", ");
else
EMIT(",");
last_cmd = cmd;
event_count %= max_events_per_line;
if(cmd <= note_end)
{
if(cmd >= note_start && track_id & 0x200)
{
uint8_t id = cmd - note_start;
EMIT("%s",song.data[id].alias);
}
else
{
EMIT("%s",cmd_tab[cmd]);
}
// extra length parameter
if(cmd >= rest_cmd && data[pos] < 0x80)
EMIT(",%s",cmd_tab[data[pos++]]);
}
else
{
EMIT("%s",cmd_tab[cmd]);
if(cmd >= chn_cmd_base(0) && (cmd - chn_cmd_base(0) < chn_cmd_cnt))
{
const struct cmd_def* def = &chn_cmd[cmd - chn_cmd_base(0)];
if(def->flag & FLG_PEG_ID)
{
uint8_t id = data[pos++];
if(id--)
EMIT(",%s",song.data[id].alias);
else
EMIT(",0");
}
else if(def->flag & FLG_INS_ID || def->flag & FLG_PCM_ID)
{
uint8_t id = data[pos++];
EMIT(",%s",song.data[id].alias);
}
else if(def->flag & FLG_FLG_ID)
{
if(data[pos] == 0x08) // drum mode on
track_id |= 0x200;
else if(data[pos] == 0x00) // drum mode off
track_id &= ~0x200;
EMIT(",$%02x",data[pos++]);
}
else if(def->length > 0)
{
int i;
for(i = 0; i < def->length; i++)
{
EMIT(",$%02x",data[pos++]);
}
}
else if(def->length < 0)
{
FAIL("unhandled channel parameter type");
}
}
else if(cmd >= sys_cmd_base(0) && (cmd - sys_cmd_base(0) < sys_cmd_cnt))
{
const struct cmd_def* def = &sys_cmd[cmd - sys_cmd_base(0)];
if(def->flag & FLG_FINISH && def->length == -2)
{
EMIT("\n\tdc.w\t%sL-*-2", header->label);
break;
}
else if(def->flag & FLG_PAT_ID)
{
uint8_t id = data[pos++];
EMIT(",%s",song.data[id].alias);
}
else if(def->flag & FLG_LPB && def->length == -1)
{
lpb_pos[lpb_stack] = (pos + 1) + data[pos++];
lpb_id[lpb_stack] = lpb_count++;
EMIT(",%sB%d-*-2", header->label, lpb_id[lpb_stack++]);
}
else if(def->flag & FLG_LPB && def->length == -2)
{
lpb_pos[lpb_stack] = (pos + 2) + ((data[pos] << 8) | data[pos+1]);
lpb_id[lpb_stack] = lpb_count++;
EMIT("\n\tdc.w\t%sB%d-*-2", header->label, lpb_id[lpb_stack++]); //untested
pos += 2;
}
else if(def->length > 0)
{
int i;
for(i = 0; i < def->length; i++)
{
EMIT(",$%02x",data[pos++]);
}
}
else if(def->length < 0)
{
FAIL("unhandled system parameter type");
}
if(def->flag & FLG_FINISH)
{
break;
}
event_count = 0;
}
else
{
FAIL("unknown command %02x at 0x%08x", cmd, (data - mds_data) + pos);
}
}
}
}
void emit_fm(struct header_t* header)
{
const char* const comments[8] = {
" ;dt/mul",
" ;ks/ar",
" ;am/dr",
" ;sr",
" ;sl/rr",
" ;ssg-eg",
" ;tl",
" ;fb/alg, transpose",
};
uint32_t comment_id = 0;
const uint32_t max_events_per_line = 4;
uint32_t event_count = 0;
uint32_t pos = 0, max_size = header->length;
uint8_t* data = header->data;
while(pos < max_size)
{
uint8_t cmd = data[pos++];
if(event_count++ == 0)
EMIT("\n\tdc.b\t");
else
EMIT(",");
EMIT("$%02x", cmd);
if(event_count == max_events_per_line)
EMIT("%s", comments[comment_id++]);
event_count %= max_events_per_line;
}
EMIT("%s", comments[(comment_id++) % 8]);
}
void emit_psg(struct header_t* header)
{
const uint32_t max_events_per_line = 8;
uint32_t event_count = 0;
uint32_t pos = 0, max_size = header->length;
uint8_t* data = header->data;
uint32_t loop_pos = 0xffffffff;
if(max_size > 2 && data[max_size - 2] == 0x02)
{
loop_pos = data[max_size - 1] + 1;
EMIT("\n@start");
}
while(pos < max_size)
{
uint8_t cmd = data[pos++];
if(pos == loop_pos)
{
event_count = 0;
EMIT("\n@loop");
}
if(event_count++ == 0 || cmd < 0x10)
EMIT("\n\tdc.b\t");
else
EMIT(",");
EMIT("$%02x", cmd);
if(cmd == 0x00)
{
EMIT(" ;stop envelope");
break;
}
else if(cmd == 0x01)
{
event_count = 0;
EMIT(" ;sustain");
}
else if(cmd == 0x02)
{
EMIT(",@loop-@start ;loop");
break;
}
event_count %= max_events_per_line;
}
}
void emit_peg(struct header_t* header)
{
const uint32_t max_events_per_line = 2;
uint32_t event_count = 0;
uint32_t pos = 0, max_size = header->length;
uint8_t* data = header->data;
uint32_t loop_pos = 0xffffffff;
if(max_size > 2 && data[max_size - 2] == 0x7f)
{
loop_pos = (data[max_size - 1] * 4) + 2;
EMIT("\n@start");
}
while(pos < max_size)
{
uint16_t cmd = (data[pos] << 8) | (data[pos + 1]);
pos += 2;
if(pos == loop_pos)
{
event_count = 0;
EMIT("\n@loop");
}
if(event_count++ == 0)
EMIT("\n\tdc.w\t");
else
EMIT(",");
if(event_count == 1 && ((cmd & 0xff00) == 0x7f00))
{
EMIT("$7f00+((@loop-@start)/4) ; loop");
break;
}
else
{
EMIT("$%04x", cmd);
if(event_count == 2)
{
int16_t initial = (data[pos-4] << 8) | data[pos-3];
int8_t delta = data[pos-2];
uint8_t wait = data[pos-1];
EMIT(" ; from %6d add %3d", initial, delta);
if(wait == 0xff)
EMIT(" forever");
else
EMIT(" for %3d frames", wait + 1);
}
}
event_count %= max_events_per_line;
}
}
//=====================================================================
int emit_song()
{
int i;
static int data_type_count[DATA_TYPE_MASK + 1];
for(i = 0; i < DATA_TYPE_MASK + 1; i++)
{
data_type_count[i] = 0;
}
EMIT(";========================================================================\n");
EMIT("; MDSDRV sequence data file: '%s'\n", song.filename);
EMIT("; This file is autogenerated by 'mds2asm.c'\n");
EMIT(";========================================================================\n");
EMIT("@TTAB\n");
EMIT("\tdc.w\t@BASE-@TTAB\t\t;offset to song base\n");
EMIT("\tdc.w\t$%02x%02x\t\t;track volume(hi) track count(lo)\n", song.tvol, song.tcount);
for(i = 0; i < song.tcount; i++)
{
sprintf(song.tracks[i].label, "@T%c", song.tracks[i].channel_id + 'A');
EMIT("\tdc.w\t$%02x%02x,%s-@BASE\t;channel select(hi) flags(lo), position\n",
song.tracks[i].channel_id, song.tracks[i].channel_flag, song.tracks[i].label);
}
EMIT("\n");
EMIT(";========================================================================\n");
EMIT("@BASE\n");
EMIT("\trsreset\n");
for(i = 0; i < song.max_data; i++)
{
uint32_t type_index = data_type_count[song.data[i].type & DATA_TYPE_MASK]++;
uint32_t rsoffset = 0;
switch(song.data[i].type & DATA_TYPE_MASK)
{
case DATA_SUB:
sprintf(song.data[i].alias, "@PAT_%d", type_index);
sprintf(song.data[i].label, "@P%d", type_index);
break;
case DATA_DRUM:
rsoffset = note_start;
sprintf(song.data[i].alias, "@DRM_%d", type_index);
sprintf(song.data[i].label, "@D%d", type_index);
break;
case DATA_FM:
sprintf(song.data[i].alias, "@FM_%d", type_index);
sprintf(song.data[i].label, "sd_fm_%08x", song.data[i].hash);
break;
case DATA_PSG:
sprintf(song.data[i].alias, "@PSG_%d", type_index);
sprintf(song.data[i].label, "sd_psg_%08x", song.data[i].hash);
break;
case DATA_PCM:
sprintf(song.data[i].alias, "@PCM_%d", type_index);
sprintf(song.data[i].label, "sd_pcm_%08x", song.data[i].hash);
break;
case DATA_PEG:
rsoffset = 1;
sprintf(song.data[i].alias, "@PEG_%d", type_index);
sprintf(song.data[i].label, "sd_peg_%08x", song.data[i].hash);
break;
default:
sprintf(song.data[i].alias, "");
sprintf(song.data[i].label, "");
break;
}
if(strlen(song.data[i].alias))
EMIT("%s = __RS+%d\n", song.data[i].alias, rsoffset);
if(song.data[i].type & DATA_PARSED)
{
if(song.data[i].type & DATA_LOCAL)
EMIT("\tdc.w\t%s-@BASE\n", song.data[i].label);
else
EMIT("\tdc.w\t%s-sdtop\n", song.data[i].label);
}
else
{
EMIT("\tdc.w\t$0000 ; unparsed data type %04x\n", song.data[i].type);
}
EMIT("\trs.b\t1\n", song.data[i].alias);
}
for(i = 0; i < song.tcount; i++)
{
EMIT(";========================================================================\n");
EMIT("\n%s", song.tracks[i].label);
emit_track(&song.tracks[i], (song.tracks[i].type & DATA_IN_DRUM_MODE) ? 0x200 : 0);
EMIT("\n\n");
}
for(i = 0; i < song.max_data; i++)
{
if(song.data[i].type & DATA_LOCAL)
{
EMIT(";========================================================================\n");
EMIT("\n%s", song.data[i].label);
emit_track(&song.data[i], (song.data[i].type & DATA_IN_DRUM_MODE) ? 0x200 : 0);
EMIT("\n\n");
}
}
EMIT(";========================================================================\n");
for(i = 0; i < song.max_data; i++)
{
if(!(song.data[i].type & DATA_LOCAL))
{
EMIT("\n\tif ~def(%s)", song.data[i].label);
EMIT("\n%s", song.data[i].label);
switch(song.data[i].type & DATA_TYPE_MASK)
{
case DATA_FM:
emit_fm(&song.data[i]);
break;
case DATA_PSG:
emit_psg(&song.data[i]);
break;
case DATA_PCM:
break;
case DATA_PEG:
emit_peg(&song.data[i]);
break;
default:
break;
}
EMIT("\n\teven\n\tendif\n");
}
}
return 0;
}
| 22.881923 | 101 | 0.553475 | [
"3d"
] |
5e29bc0fda1c9063f02b1465fb58683f8467162e | 6,468 | h | C | dbswzsk/WzskQUsrAAccess.h | mpsitech/wzsk-Whiznium-StarterK | 94a0a8a05a0fac06c4360b8f835556a299b9425a | [
"MIT"
] | 1 | 2020-09-20T16:25:07.000Z | 2020-09-20T16:25:07.000Z | dbswzsk/WzskQUsrAAccess.h | mpsitech/wzsk-Whiznium-StarterKit | 94a0a8a05a0fac06c4360b8f835556a299b9425a | [
"MIT"
] | null | null | null | dbswzsk/WzskQUsrAAccess.h | mpsitech/wzsk-Whiznium-StarterKit | 94a0a8a05a0fac06c4360b8f835556a299b9425a | [
"MIT"
] | null | null | null | /**
* \file WzskQUsrAAccess.h
* Dbs and XML wrapper for table TblWzskQUsrAAccess (declarations)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Emily Johnson (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
#ifndef WZSKQUSRAACCESS_H
#define WZSKQUSRAACCESS_H
#include <sbecore/Xmlio.h>
#if defined(SBECORE_MAR) || defined(SBECORE_MY)
#include <sbecore/MyDbs.h>
#endif
#if defined(SBECORE_LITE)
#include <sbecore/LiteDbs.h>
#endif
/**
* WzskQUsrAAccess: record of TblWzskQUsrAAccess
*/
class WzskQUsrAAccess {
public:
WzskQUsrAAccess(const Sbecore::ubigint qref = 0, const Sbecore::ubigint jref = 0, const Sbecore::uint jnum = 0, const Sbecore::ubigint ref = 0, const Sbecore::uint x1IxWzskVFeatgroup = 0, const std::string srefX1IxWzskVFeatgroup = "", const std::string titX1IxWzskVFeatgroup = "", const std::string x2FeaSrefUix = "", const Sbecore::uint ixWzskWAccess = 0, const std::string srefsIxWzskWAccess = "", const std::string titsIxWzskWAccess = "");
public:
Sbecore::ubigint qref;
Sbecore::ubigint jref;
Sbecore::uint jnum;
Sbecore::ubigint ref;
Sbecore::uint x1IxWzskVFeatgroup;
std::string srefX1IxWzskVFeatgroup;
std::string titX1IxWzskVFeatgroup;
std::string x2FeaSrefUix;
Sbecore::uint ixWzskWAccess;
std::string srefsIxWzskWAccess;
std::string titsIxWzskWAccess;
public:
void writeJSON(Json::Value& sup, bool jnumattr = false, bool shorttags = false);
void writeXML(xmlTextWriter* wr, std::string difftag = "", bool jnumattr = false, bool shorttags = false);
};
/**
* ListWzskQUsrAAccess: recordset of TblWzskQUsrAAccess
*/
class ListWzskQUsrAAccess {
public:
ListWzskQUsrAAccess();
ListWzskQUsrAAccess(const ListWzskQUsrAAccess& src);
~ListWzskQUsrAAccess();
void clear();
unsigned int size() const;
void append(WzskQUsrAAccess* rec);
ListWzskQUsrAAccess& operator=(const ListWzskQUsrAAccess& src);
public:
std::vector<WzskQUsrAAccess*> nodes;
public:
void writeJSON(Json::Value& sup, std::string difftag = "");
void writeXML(xmlTextWriter* wr, std::string difftag = "");
};
/**
* TblWzskQUsrAAccess: C++ wrapper for table TblWzskQUsrAAccess
*/
class TblWzskQUsrAAccess {
public:
TblWzskQUsrAAccess();
virtual ~TblWzskQUsrAAccess();
public:
virtual bool loadRecBySQL(const std::string& sqlstr, WzskQUsrAAccess** rec);
virtual Sbecore::ubigint loadRstBySQL(const std::string& sqlstr, const bool append, ListWzskQUsrAAccess& rst);
virtual Sbecore::ubigint insertRec(WzskQUsrAAccess* rec);
Sbecore::ubigint insertNewRec(WzskQUsrAAccess** rec = NULL, const Sbecore::ubigint jref = 0, const Sbecore::uint jnum = 0, const Sbecore::ubigint ref = 0, const Sbecore::uint x1IxWzskVFeatgroup = 0, const std::string srefX1IxWzskVFeatgroup = "", const std::string titX1IxWzskVFeatgroup = "", const std::string x2FeaSrefUix = "", const Sbecore::uint ixWzskWAccess = 0, const std::string srefsIxWzskWAccess = "", const std::string titsIxWzskWAccess = "");
Sbecore::ubigint appendNewRecToRst(ListWzskQUsrAAccess& rst, WzskQUsrAAccess** rec = NULL, const Sbecore::ubigint jref = 0, const Sbecore::uint jnum = 0, const Sbecore::ubigint ref = 0, const Sbecore::uint x1IxWzskVFeatgroup = 0, const std::string srefX1IxWzskVFeatgroup = "", const std::string titX1IxWzskVFeatgroup = "", const std::string x2FeaSrefUix = "", const Sbecore::uint ixWzskWAccess = 0, const std::string srefsIxWzskWAccess = "", const std::string titsIxWzskWAccess = "");
virtual void insertRst(ListWzskQUsrAAccess& rst);
virtual void updateRec(WzskQUsrAAccess* rec);
virtual void updateRst(ListWzskQUsrAAccess& rst);
virtual void removeRecByQref(Sbecore::ubigint qref);
virtual void removeRstByJref(Sbecore::ubigint jref);
virtual bool loadRecByQref(Sbecore::ubigint qref, WzskQUsrAAccess** rec);
virtual Sbecore::ubigint loadRstByJref(Sbecore::ubigint jref, const bool append, ListWzskQUsrAAccess& rst);
};
#if defined(SBECORE_MAR) || defined(SBECORE_MY)
/**
* MyWzskQUsrAAccess: C++ wrapper for table TblWzskQUsrAAccess (MySQL database)
*/
class MyTblWzskQUsrAAccess : public TblWzskQUsrAAccess, public Sbecore::MyTable {
public:
MyTblWzskQUsrAAccess();
~MyTblWzskQUsrAAccess();
public:
void initStatements();
public:
MYSQL_STMT* stmtInsertRec;
MYSQL_STMT* stmtUpdateRec;
MYSQL_STMT* stmtRemoveRecByQref;
MYSQL_STMT* stmtRemoveRstByJref;
public:
bool loadRecBySQL(const std::string& sqlstr, WzskQUsrAAccess** rec);
Sbecore::ubigint loadRstBySQL(const std::string& sqlstr, const bool append, ListWzskQUsrAAccess& rst);
Sbecore::ubigint insertRec(WzskQUsrAAccess* rec);
void insertRst(ListWzskQUsrAAccess& rst);
void updateRec(WzskQUsrAAccess* rec);
void updateRst(ListWzskQUsrAAccess& rst);
void removeRecByQref(Sbecore::ubigint qref);
void removeRstByJref(Sbecore::ubigint jref);
bool loadRecByQref(Sbecore::ubigint qref, WzskQUsrAAccess** rec);
Sbecore::ubigint loadRstByJref(Sbecore::ubigint jref, const bool append, ListWzskQUsrAAccess& rst);
};
#endif
#if defined(SBECORE_LITE)
/**
* LiteWzskQUsrAAccess: C++ wrapper for table TblWzskQUsrAAccess (SQLite database)
*/
class LiteTblWzskQUsrAAccess : public TblWzskQUsrAAccess, public Sbecore::LiteTable {
public:
LiteTblWzskQUsrAAccess();
~LiteTblWzskQUsrAAccess();
public:
void initStatements();
public:
sqlite3_stmt* stmtInsertRec;
sqlite3_stmt* stmtUpdateRec;
sqlite3_stmt* stmtRemoveRecByQref;
sqlite3_stmt* stmtRemoveRstByJref;
sqlite3_stmt* stmtLoadRecByQref;
sqlite3_stmt* stmtLoadRecByJref;
sqlite3_stmt* stmtLoadRstByJref;
private:
bool loadRec(sqlite3_stmt* stmt, WzskQUsrAAccess** rec);
Sbecore::ubigint loadRst(sqlite3_stmt* stmt, const bool append, ListWzskQUsrAAccess& rst);
bool loadRecByStmt(sqlite3_stmt* stmt, WzskQUsrAAccess** rec);
Sbecore::ubigint loadRstByStmt(sqlite3_stmt* stmt, const bool append, ListWzskQUsrAAccess& rst);
public:
bool loadRecBySQL(const std::string& sqlstr, WzskQUsrAAccess** rec);
Sbecore::ubigint loadRstBySQL(const std::string& sqlstr, const bool append, ListWzskQUsrAAccess& rst);
Sbecore::ubigint insertRec(WzskQUsrAAccess* rec);
void insertRst(ListWzskQUsrAAccess& rst);
void updateRec(WzskQUsrAAccess* rec);
void updateRst(ListWzskQUsrAAccess& rst);
void removeRecByQref(Sbecore::ubigint qref);
void removeRstByJref(Sbecore::ubigint jref);
bool loadRecByQref(Sbecore::ubigint qref, WzskQUsrAAccess** rec);
Sbecore::ubigint loadRstByJref(Sbecore::ubigint jref, const bool append, ListWzskQUsrAAccess& rst);
};
#endif
#endif
| 36.134078 | 485 | 0.773346 | [
"vector"
] |
5e316b903503da9f71f2fa3c365aa6d8806be5e9 | 987 | c | C | NGSpice/ngspice-30/src/spicelib/devices/asrc/asrctemp.c | Surya-98/Snapcuit | 9789a779485d8af2426a2d4e6403a06f44acadcb | [
"MIT"
] | null | null | null | NGSpice/ngspice-30/src/spicelib/devices/asrc/asrctemp.c | Surya-98/Snapcuit | 9789a779485d8af2426a2d4e6403a06f44acadcb | [
"MIT"
] | null | null | null | NGSpice/ngspice-30/src/spicelib/devices/asrc/asrctemp.c | Surya-98/Snapcuit | 9789a779485d8af2426a2d4e6403a06f44acadcb | [
"MIT"
] | null | null | null | /**********
Copyright 1990 Regents of the University of California. All rights reserved.
Author: 1985 Thomas L. Quarles
**********/
#include "ngspice/ngspice.h"
#include "ngspice/cktdefs.h"
#include "asrcdefs.h"
#include "ngspice/sperror.h"
int
ASRCtemp(GENmodel *inModel, CKTcircuit *ckt)
{
ASRCmodel *model = (ASRCmodel *) inModel;
ASRCinstance *here;
for (; model; model = ASRCnextModel(model)) {
for (here = ASRCinstances(model); here; here = ASRCnextInstance(here)) {
/* Default Value Processing for Source Instance */
if (!here->ASRCtempGiven) {
here->ASRCtemp = ckt->CKTtemp;
if (!here->ASRCdtempGiven)
here->ASRCdtemp = 0.0;
} else {
here->ASRCdtemp = 0.0;
if (here->ASRCdtempGiven)
printf("%s: Instance temperature specified, dtemp ignored\n", here->ASRCname);
}
}
}
return(OK);
}
| 25.973684 | 98 | 0.568389 | [
"model"
] |
5e31ad7fa4316acbc550a8c2c13485df8aa708fa | 2,200 | h | C | mechanics/src/gui/IDependable.h | robindittmar/mechanics | ea62f750d3cd448cbd708dee972d5a5b9a1464a0 | [
"MIT"
] | null | null | null | mechanics/src/gui/IDependable.h | robindittmar/mechanics | ea62f750d3cd448cbd708dee972d5a5b9a1464a0 | [
"MIT"
] | null | null | null | mechanics/src/gui/IDependable.h | robindittmar/mechanics | ea62f750d3cd448cbd708dee972d5a5b9a1464a0 | [
"MIT"
] | null | null | null | #ifndef __ICONTROLDEPENDABLE_H__
#define __ICONTROLDEPENDABLE_H__
// Std Lib
#include <assert.h>
#include <vector>
#include <unordered_set>
// Source SDK
// Custom
#include "Dependency.h"
typedef void(IDependable::*EnableDependency_t)(bool);
class IDependable
{
public:
IDependable(EnableDependency_t evaluationHandler = nullptr);
virtual ~IDependable();
/// <summary>
/// Adds dependency of another IDependable
/// (For example: ChildCheckbox->AddDependency(ParentCheckbox) will result
/// in ChildCheckbox being disabled, when ParentCheckbox is disabled aswell [and vice versa ofc])
///
/// The full dependency list is checked, using && on multiple dependencies,
/// but || when having multiple conditions for a single dependency
/// </summary>
/// <param name="pDependency">Dependency</param>
/// <param name="pParam">Optional parameter to use on evaluation</param>
/// <param name="bReverse">Reverse the logic if this control will be enabled/disabled for this one dependency</param>
void AddDependency(IDependable* pDependency, void* pParam = nullptr, bool bReverse = false);
/// <summary>
/// Honestly you shouldn't invoke this, unless you explicitly want to change the Relationship between controls
///
/// this will be invoked by AddDependency, so I highly recommend you to check out AddDependency instead of this
/// </summary>
/// <param name="pDependentOne"></param>
void AddDependentOne(IDependable* pDependentOne);
/// <summary>
/// Evaluates if we want to be enabled or disabled (usually gets called from depenencies itself)
/// </summary>
void EvaluateDependencies();
/// <summary>
/// Will notify dependent ones about any changes so they'll evaluate if
/// they need to be enabled or disabled
/// </summary>
void NotifyDependentOnes();
/// <summary>
/// Evaluates if we want our dependent ones to be enabled
/// </summary>
/// <returns>Wether or not the dependent ones should be enabled</returns>
virtual bool ShouldDependentOnesBeEnabled(void* pParam) = 0;
protected:
EnableDependency_t m_pEvaluationHandler;
std::vector<CDependency> m_vDependencies;
std::vector<IDependable*> m_vDependentOnes;
};
#endif // __ICONTROLDEPENDABLE_H__ | 33.333333 | 118 | 0.745 | [
"vector"
] |
5e3a6385c18470a8d2f1faefa1761770a2cb2a28 | 1,988 | h | C | Plugins/AdvKitPlugin/Source/AdvKitRuntime/Classes/Environment/AdvKitZoneLocation.h | crimsonstrife/velorum-defunct | 1a6e1eab9057293da2aa045eff021d069df54c5e | [
"CC0-1.0"
] | null | null | null | Plugins/AdvKitPlugin/Source/AdvKitRuntime/Classes/Environment/AdvKitZoneLocation.h | crimsonstrife/velorum-defunct | 1a6e1eab9057293da2aa045eff021d069df54c5e | [
"CC0-1.0"
] | null | null | null | Plugins/AdvKitPlugin/Source/AdvKitRuntime/Classes/Environment/AdvKitZoneLocation.h | crimsonstrife/velorum-defunct | 1a6e1eab9057293da2aa045eff021d069df54c5e | [
"CC0-1.0"
] | null | null | null | // Copyright 2015 Pascal Krabbe
#pragma once
#include "Object.h"
#include "AdvKitZoneLocation.generated.h"
/**
* @brief Base class for object that defines a location inside a zone.
*
* Different zones can have different location specifiers. This class
* takes care of storing a location and all the conversion methods
* required to position the character.
*/
UCLASS()
class ADVKITRUNTIME_API UAdvKitZoneLocation : public UObject
{
GENERATED_BODY()
public:
/** Zone this location is in */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AdvKit", Replicated)
class AAdvKitZone* Zone;
/** Relative location to the zone */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AdvKit", Replicated)
FVector LocalPosition;
public:
/**
* Set all relevant values for the location
* @param InZone Zone this location is in
* @param InPosition Global position this location holds
* @return
*/
virtual void Set(class AAdvKitZone* InZone, const FVector& InPosition);
/**
* Queries the global position of this location
* @return The position in world space
*/
virtual FVector GetGlobalPosition() const;
/**
* Constrains a direction in world space to align with the zone.
* @param WorldDirection Direction to constrain.
* @return The restricted direction.
*/
UFUNCTION(BlueprintCallable, Category = "AdvKit")
virtual FVector ConstrainDirection(const FVector& WorldDirection);
/**
* Attempts to move the location inside the zone.
* @param WorldDesiredDelta Direction to move in.
* @param HalfExtent Half size of the character, describing its capsule (e.g. capsule radius and half height)
* @param ExtentWorldRotation Rotation of the character.
* @return True if the loation could be moved, false otherwise.
*/
UFUNCTION(BlueprintCallable, Category = "AdvKit")
virtual bool MoveInDirection(const FVector& WorldDesiredDelta, const FVector& HalfExtent, const FRotator& ExtentWorldRotation = FRotator::ZeroRotator);
};
| 31.555556 | 152 | 0.750503 | [
"object"
] |
5e3b2df76962738b79bd03ba010d687ca8ada7c8 | 4,312 | h | C | plugins/TopPairElectronPlusJetsSelectionFilter.h | EmyrClement/NTupleProduction | 4c1b67ac8826656e804912512f4c4dc6695c7674 | [
"Apache-2.0"
] | 1 | 2018-02-20T21:23:21.000Z | 2018-02-20T21:23:21.000Z | plugins/TopPairElectronPlusJetsSelectionFilter.h | RickeyEstes/NTupleProduction | 1319183de0ce00749c8f5841fa925479b9024b48 | [
"Apache-2.0"
] | 116 | 2015-01-09T22:38:07.000Z | 2017-05-24T08:12:48.000Z | plugins/TopPairElectronPlusJetsSelectionFilter.h | RickeyEstes/NTupleProduction | 1319183de0ce00749c8f5841fa925479b9024b48 | [
"Apache-2.0"
] | 1 | 2020-11-01T00:01:17.000Z | 2020-11-01T00:01:17.000Z | #ifndef BristolTopPairElectronPlusJetsSelectionFilter
#define BristolTopPairElectronPlusJetsSelectionFilter
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDFilter.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include "DataFormats/PatCandidates/interface/Electron.h"
#include "DataFormats/PatCandidates/interface/Jet.h"
#include "JetMETCorrections/Objects/interface/JetCorrector.h"
#include "DataFormats/PatCandidates/interface/Muon.h"
#include "PhysicsTools/SelectorUtils/interface/PFJetIDSelectionFunctor.h"
#include "HLTrigger/HLTcore/interface/HLTConfigProvider.h"
#include "DataFormats/Common/interface/TriggerResults.h"
#include <boost/array.hpp>
#include <string>
#include <vector>
namespace TTbarEPlusJetsReferenceSelection {
enum Step {
AllEvents,
EventCleaningAndTrigger,
ExactlyOneSignalElectron,
LooseMuonVeto,
LooseElectronVeto,
ConversionVeto,
AtLeastOneGoodJet,
AtLeastTwoGoodJets,
AtLeastThreeGoodJets,
AtLeastFourGoodJets,
AtLeastOneBtag,
AtLeastTwoBtags,
NUMBER_OF_SELECTION_STEPS
};
const std::string StringSteps[NUMBER_OF_SELECTION_STEPS] = { //
"AllEvents", //
"EventCleaningAndTrigger", //
"ExactlyOneSignalElectron", //
"LooseMuonVeto", //
"LooseElectronVeto", //
"ConversionVeto", //
"AtLeastOneGoodJet", //
"AtLeastTwoGoodJets", //
"AtLeastThreeGoodJets", //
"AtLeastFourGoodJets", //
"AtLeastOneBtag", //
"AtLeastTwoBtags" //
};
}
class TopPairElectronPlusJetsSelectionFilter: public edm::EDFilter {
public:
explicit TopPairElectronPlusJetsSelectionFilter(const edm::ParameterSet&);
virtual ~TopPairElectronPlusJetsSelectionFilter();
virtual void beginJob();
virtual bool filter(edm::Event&, const edm::EventSetup&);
virtual void endJob();
virtual void beginRun();
static void fillDescriptions(edm::ConfigurationDescriptions & descriptions);
// virtual bool isGoodElectron(const edm::Ptr<pat::Electron>&) const;
// virtual double electronIsolation(const pat::Electron& electron) const;
// virtual void getLooseElectrons();
// virtual void getLooseMuons();
// virtual void goodIsolatedElectrons();
// virtual void cleanedJets();
// virtual void cleanedBJets();
virtual bool passesSelectionStep(edm::Event& iEvent, unsigned int selectionStep) const;
virtual bool passesEventCleaning(edm::Event& iEvent) const;
virtual bool passesTriggerSelection() const;
virtual bool hasExactlyOneSignalElectron() const;
virtual bool passesLooseMuonVeto() const;
virtual bool passesLooseElectronVeto() const;
virtual bool passesConversionVeto() const;
virtual bool hasAtLeastOneGoodJet() const;
virtual bool hasAtLeastTwoGoodJets() const;
virtual bool hasAtLeastThreeGoodJets() const;
virtual bool hasAtLeastFourGoodJets() const;
virtual bool hasExactlyZeroGoodBJet() const;
virtual bool hasExactlyOneGoodBJet() const;
virtual bool hasAtLeastOneGoodBJet() const;
virtual bool hasAtLeastTwoGoodBJets() const;
private:
virtual void setupEventContent(edm::Event& iEvent, const edm::EventSetup& iSetup);
//config
edm::EDGetTokenT<pat::JetCollection> cleanedJetsToken_, cleanedBJetsToken_;
edm::EDGetToken vetoElectronsToken_, goodElectronsToken_, electronsToken_;
edm::EDGetTokenT<pat::MuonCollection> vetoMuonsToken_;
edm::EDGetTokenT<edm::TriggerResults> hltInputTag_;
bool tagAndProbeStudies_, dropTriggerSelection_;
std::string prefix_, MCSampleTag_;
bool taggingMode_, jetSelectionInTaggingMode_, bSelectionInTaggingMode_;
// Control region selections
bool nonIsolatedElectronSelection_;
bool invertedConversionSelection_;
//internal
boost::array<bool, TTbarEPlusJetsReferenceSelection::NUMBER_OF_SELECTION_STEPS> passes_;
unsigned int runNumber_, signalElectronIndex_;
bool isRealData_, hasSignalElectron_;
std::vector< unsigned int> cleanedJetIndex_, cleanedBJetIndex_, cleanedTightBJetIndex_;
pat::JetCollection cleanedJets_, cleanedBJets_;
pat::ElectronCollection electrons_, goodIsolatedElectrons_, vetoElectrons_;
pat::MuonCollection vetoMuons_;
pat::Electron signalElectron_;
HLTConfigProvider hltConfig_;
edm::TriggerResults triggerResults_;
};
#endif
| 33.426357 | 89 | 0.805427 | [
"vector"
] |
5e4811b80320bdb540b2dd92ce39279c08178a01 | 2,093 | h | C | include/frenet_optimal_planner/frenet.h | Forrest-Z/frenet_optimal_planner | ae6e8ac1e3fb128c4cb6bad9a463ea0af497511d | [
"Apache-2.0"
] | 5 | 2022-03-02T10:18:42.000Z | 2022-03-10T19:23:57.000Z | include/frenet_optimal_planner/frenet.h | SS47816/frenet_optimal_planner | 418f5ac718fe1b8c838a10b9ad1da48623594e25 | [
"Apache-2.0"
] | null | null | null | include/frenet_optimal_planner/frenet.h | SS47816/frenet_optimal_planner | 418f5ac718fe1b8c838a10b9ad1da48623594e25 | [
"Apache-2.0"
] | 3 | 2022-03-02T00:45:15.000Z | 2022-03-21T19:59:22.000Z | /** frenet.h
*
* Copyright (C) 2022 Shuo SUN & Advanced Robotics Center, National University of Singapore
*
* Apache License 2.0 https://www.apache.org/licenses/LICENSE-2.0
*
* Construction of frenet coordinates
* Conversion between Frenet frame and Cartesian frame
*/
#ifndef FRENET_H_
#define FRENET_H_
#include <cmath>
#include <vector>
#include <iostream>
#include "Eigen/Dense"
#include "lane.h"
#include "math_utils.h"
#include "vehicle_state.h"
namespace fop
{
class FrenetState
{
public:
// Constructor
FrenetState(){};
// Destructor
virtual ~FrenetState(){};
double s;
double s_d;
double s_dd;
double s_ddd;
double d;
double d_d;
double d_dd;
double d_ddd;
};
class FrenetPath
{
public:
// Constructor
FrenetPath() {};
// Destructor
virtual ~FrenetPath() {};
friend bool operator < (const FrenetPath& lhs, const FrenetPath& rhs);
friend bool operator > (const FrenetPath& lhs, const FrenetPath& rhs);
Eigen::Vector3i idx;
int lane_id;
// checks
bool constraint_passed;
bool collision_passed;
// costs
double fix_cost; // fixed cost term
double dyn_cost; // cost terms to be determined after generation
// double heu_cost; // heuristic cost term
// double est_cost; // cost term estimated before generation (fix_cost + heu_cost)
double final_cost; // final cost for a generated trajectory
// time list
std::vector<double> t;
// longitudinal
std::vector<double> s;
std::vector<double> s_d;
std::vector<double> s_dd;
std::vector<double> s_ddd;
// lateral
std::vector<double> d;
std::vector<double> d_d;
std::vector<double> d_dd;
std::vector<double> d_ddd;
// state
std::vector<double> x;
std::vector<double> y;
std::vector<double> yaw;
std::vector<double> ds;
std::vector<double> c;
};
// Convert the position in Cartesian coordinates to Frenet frame
FrenetState getFrenet(const VehicleState& current_state, const Lane& lane);
FrenetState getFrenet(const VehicleState& current_state, const Path& path);
} // end of namespace fop
#endif // FRENET_H_ | 22.031579 | 91 | 0.698997 | [
"vector"
] |
5e547c494a404a94864dc810b7ad4adfed8e9a2c | 4,219 | h | C | libMaths/libMaths/source/Matrix/Matrix4.h | FelixPog/AnimationEngine | f153dfc10d7db075d559cfc6a5bfae78334dfb5a | [
"Apache-2.0"
] | null | null | null | libMaths/libMaths/source/Matrix/Matrix4.h | FelixPog/AnimationEngine | f153dfc10d7db075d559cfc6a5bfae78334dfb5a | [
"Apache-2.0"
] | null | null | null | libMaths/libMaths/source/Matrix/Matrix4.h | FelixPog/AnimationEngine | f153dfc10d7db075d559cfc6a5bfae78334dfb5a | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <cstring>
#include "Core/Angle.h"
#include "Vector/Vector.h"
#include "Quaternion/Quaternion.h"
namespace LibMath
{
struct Vector3;
struct const_col
{
const_col(float const* ptr) : m_ptr(ptr) {}
float const* m_ptr;
float operator[](int idx) const { return m_ptr[idx * 4]; }
};
struct col
{
col(float* ptr) : m_ptr(ptr) {}
float* m_ptr;
float& operator[](int idx) { return m_ptr[idx * 4]; }
};
struct row
{
row(float* ptr) : m_ptr(ptr) {}
float* m_ptr;
float& operator[](int idx) { return m_ptr[idx]; }
row& operator=(const_col const& other) { for (int i = 0; i < 4; i++) (*this)[i] = other[i]; return *this; }
};
struct const_row
{
const_row(float const* ptr) : m_ptr(ptr) {}
float const* m_ptr;
float operator[](int idx) const { return m_ptr[idx]; }
};
struct GridRow
{
float values[4];
};
struct GridView
{
GridRow rows[4];
};
struct Matrix4
{
Matrix4() { Clear(); /*gridview = new(raw)GridView;*/ }
Matrix4(Matrix4 const& other) = default;
Matrix4& operator=(const Matrix4& other) = default;
Matrix4(float diagonalValue);
~Matrix4() = default;
static Matrix4 Identity() { return Matrix4(1.f); }
static Matrix4 Orthographic(float left, float right, float bottom, float top, float near, float far);
static Matrix4 Perspective(Radian fieldOfView, float aspectRatio, float near, float far);
static Matrix4 LookAt(const Vector3& eye, const Vector3& center, const Vector3& up);
static Matrix4 Rotation(Quaternion quaternion);
static Matrix4 Rotation(Radian x, Radian y, Radian z);
static Matrix4 Rotation(const Vector3& vec, bool radian);
static Matrix4 Scaling(float x, float y, float z);
static Matrix4 Scaling(const Vector3& vec);
static Matrix4 Translation(float x, float y, float z);
static Matrix4 Translation(const Vector3& vec);
//Maybe swap order of multiplication
Matrix4& Rotate(Quaternion const& quaternion) { *this = Rotation(quaternion) * (*this); return *this; }
Matrix4& Rotate(Radian x, Radian y, Radian z) { *this = Rotation(x, y, z) * (*this); return *this; }
Matrix4& Rotate(const Vector3& vec, bool radian) { *this = Rotation(vec, radian)* (*this); return *this; }
Matrix4& Scale(float x, float y, float z) { *this = Scaling(x, y, z)* (*this); return *this; }
Matrix4& Scale(const Vector3& vec) { *this = Scaling(vec)* (*this); return *this; }
Matrix4& Translate(float x, float y, float z) { *this = Translation(x, y, z)* (*this); return *this; }
Matrix4& Translate(const Vector3& vec) { *this = Translation(vec)* (*this); return *this; }
bool operator==(const Matrix4& other) const;
bool operator!=(const Matrix4& other) const { return !(*this == other); }
row operator[](int idx) { return row(&raw[idx * 4]); }
const_row operator[](int idx) const { return const_row(&raw[idx * 4]); }
LibMath::col col(int idx) { return LibMath::col(&raw[idx]); }
const_col col(int idx) const { return const_col(&raw[idx]); }
Matrix4 operator*(Matrix4 const& other) const;
Matrix4& operator*=(Matrix4 const& other);
Vector4 operator*(Vector4 const& other) const;
friend Vector4 operator*(Vector4 const& otherVec, Matrix4 const& thisMat);
float Determinant() const;
[[nodiscard]] Vector4 GetTranslation() const { return Vector4((*this)[3][0], (*this)[3][1], (*this)[3][2], (*this)[3][3]); }
static Vector4 GetTranslation(Matrix4& Matrix4) { return Matrix4.GetTranslation(); }
void Transpose() { *this = GetTranspose(); }
[[nodiscard]] Matrix4 GetTranspose() const;
static void Transpose(Matrix4& Matrix4) { Matrix4.Transpose(); }
void Inverse() { *this = GetInverse(); }
[[nodiscard]] Matrix4 GetInverse() const;
static void Inverse(Matrix4& Matrix4) { Matrix4.Inverse(); }
void Adjoint() { *this = GetAdjoint(); }
[[nodiscard]] Matrix4 GetAdjoint() const;
static void Adjoint(Matrix4& Matrix4) { Matrix4.Adjoint(); }
Matrix4 NormalMatrix4() const;
static void NormalMatrix4(Matrix4 const& Matrix4);
void Clear() { std::memset(&raw, 0, sizeof(raw)); }
float const* Data() const { return raw; }
float raw[16];
//GridView* gridview;
private:
float Determinant(int ignoredRow, int ignoredCol) const;
};
}
| 31.251852 | 126 | 0.67433 | [
"vector"
] |
5e5b720f93d56854ac4f669dab58d50ba86ae9a3 | 18,584 | c | C | mex/include/sisl-4.5.0/src/intjoinper.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | mex/include/sisl-4.5.0/src/intjoinper.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | mex/include/sisl-4.5.0/src/intjoinper.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | //===========================================================================
// SISL - SINTEF Spline Library, version 4.5.0.
// Definition and interrogation of NURBS curves and surfaces.
//
// Copyright (C) 2000-2005, 2010 SINTEF ICT, Applied Mathematics, Norway.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc.,
// 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// Contact information: E-mail: tor.dokken@sintef.no
// SINTEF ICT, Department of Applied Mathematics,
// P.O. Box 124 Blindern,
// 0314 Oslo, Norway.
//
// Other licenses are also available for this software, notably licenses
// for:
// - Building commercial software.
// - Building software whose source code you wish to keep private.
//===========================================================================
#include "sisl-copyright.h"
/*
*
* $Id: intjoinper.c,v 1.4 2001-03-19 16:13:07 afr Exp $
*
*/
#define INT_JOIN_PER
#include "sislP.h"
#if defined(SISLNEEDPROTOTYPES)
void
int_join_per (SISLIntdat ** pintdat,
SISLObject * po1,
SISLObject * po2,
double eimpli[],
int ideg,
double aepsge,
int *jstat)
#else
void
int_join_per (pintdat,
po1,
po2,
eimpli,
ideg,
aepsge,
jstat)
SISLIntdat **pintdat;
SISLObject *po1;
SISLObject *po2;
double eimpli[];
int ideg;
double aepsge;
int *jstat;
#endif
/*
*********************************************************************
*
* PURPOSE : To join intersection curves based on object space data only.
* Curves are joined if they are G1 object space.
* Single point with same object space posisition are
* made to one point.
*
*
* INPUT : pintdat - Pointer to pointer to the SISLIntdat data.
* po1 - Pointer surface object.
* po2 - Pointer surface object.
* eimpli - Array containing descr. of implicit surf
* ideg - Type of impl surf.
ang_tol - Angle control tolerance ie ??
* aepsge - Absolute tolerance
*
*
* OUTPUT : jstat - status messages
* = ? : ?
* = 0 : ok
* < 0 : error
*
*
* METHOD :
*
* USE : The function is only working i 3-D
*
* REFERENCES :
*
*-
* CALLS :
*
* WRITTEN BY : Ulf J. Krystad, SI, Oslo, Norway, July-1990
*
*********************************************************************
*/
{
int kstat; /* Local status variable. */
int kpos = 0; /* Position of error. */
int ki=0, kj=0; /* Counter */
SISLIntpt *pcurr; /* to traverse list of points. */
SISLIntpt *pnext; /* to traverse list of points. */
SISLIntpt *pother; /* to traverse list of points. */
int logtest=0; /* used for constant crv test */
SISLIntpt *pfirst_1; /* First point in a list, periodicity */
SISLIntpt *pfirst_2; /* First point in a list, periodicity */
SISLIntpt *plast_1; /* Last point in a list, periodicity */
SISLIntpt *plast_2; /* Last point in a list, periodicity */
double *curve_val_3d = SISL_NULL; /* Pos, tang and curvature ,3d */
double *curve_val_2d_1= SISL_NULL; /* Pos, tang and curvature ,2d */
double *curve_val_2d_2= SISL_NULL; /* Pos, tang and curvature ,2d */
double delta_par[4]; /* Delta vector in par space, periodicity */
double *delta_1=delta_par; /* Delta vector in par space, periodicity */
double *delta_2=delta_par+2; /* Delta vector in par space, periodicity */
double dot; /* Scalar product, periodicity */
double dist; /* Distance in 3D, periodicity */
double dist_a; /* Distance in 3D, periodicity */
double dist_b; /* Distance in 3D, periodicity */
double dist_c; /* Distance in 3D, periodicity */
double dist_d; /* Distance in 3D, periodicity */
double ang; /* Angel between tangents, periodicity */
int dimobj; /* Dimension 3, periodicity */
//int dim2=2; /* Dimension 2, periodicity */
int join=TRUE; /* Flag to kill int point, periodicity */
int const_crv_1; /* Constant parameter direction */
int const_crv_2; /* Constant parameter direction */
int same_curve; /* Flag */
int no_of_main; /* No of mainpts connected to curr pt */
int treat_2d; /* Flag, shifting of parameter values is
only done in surf/surf cases. */
int cas; /* Flag, surf surf, surf analytic, other. */
double epar[2];
double *nullp = SISL_NULL;
SISLIntpt *pturn=SISL_NULL; /* Last point in a list, periodicity */
int log_1, log_2; /* To test on an edge curve lies along
the same parameter direction. */
int kp,no_par,index_1;
double min_par[4],max_par[4],legal_min[4],legal_max[4];
SISLObject *qo=SISL_NULL;
/* -------------------------------------------------------------------- */
/* If we do not have any intersection data we just return. */
if ((*pintdat) == SISL_NULL)
goto out;
if ((*pintdat)->ipoint <=1)
goto out;
if (po1->iobj == SISLSURFACE) dimobj = po1->s1->idim;
else if (po1->iobj == SISLCURVE) dimobj = po1->c1->idim;
else goto errinp;
/* UJK, 13.08.93 : Check periodicity flag.*/
no_par = (*pintdat)->vpoint[0]->ipar;
if (no_par > 4) goto errinp;
for (kp=0;kp<4;kp++)
{
legal_min[kp] = -HUGE;
legal_max[kp] = HUGE;
}
for (ki=0,qo=po1,index_1=0;ki<2;ki++,qo=po2)
if (qo)
{
if (qo->iobj == SISLSURFACE)
{
if (qo->s1->cuopen_1 != SISL_SURF_PERIODIC)
{
legal_min[index_1] = qo->s1->et1[qo->s1->ik1-1];
legal_max[index_1] = qo->s1->et1[qo->s1->in1];
}
index_1++;
if (qo->s1->cuopen_2 != SISL_SURF_PERIODIC)
{
legal_min[index_1] = qo->s1->et2[qo->s1->ik2-1];
legal_max[index_1] = qo->s1->et2[qo->s1->in2];
}
index_1++;
}
else if (qo->iobj == SISLCURVE)
{
if (qo->c1->cuopen != SISL_CRV_PERIODIC)
{
legal_min[index_1] = qo->c1->et[qo->c1->ik-1];
legal_max[index_1] = qo->c1->et[qo->c1->in];
}
index_1++;
}
}
/*________________________________________ */
/* UJK, TESTING !!!!!!!!!!!!!!!!!!! For the moment: */
if (dimobj == 3 && po2->iobj == SISLPOINT) goto out;
/*________________________________________ */
if (po1->iobj == SISLSURFACE &&
po2->iobj == SISLSURFACE && ideg == 0)
/* Two B-spline surf's in 3D. */
cas = 1;
else if (po1->iobj == SISLSURFACE && ideg != 2000 && ideg !=0)
/* B-spline surf vs analytic. */
cas = 2;
else
cas = 0;
if (ideg != 2000 && po1->iobj == SISLSURFACE) treat_2d = TRUE;
else treat_2d = FALSE;
for (ki=1;ki<5;ki++) logtest |= 1<< ki;
/* Ensure that object space information is in place. */
for (kj = 0; kj < (*pintdat)->ipoint; kj++)
{
pcurr = (*pintdat)->vpoint[kj];
sh6evalint (po1, po2, eimpli, ideg, pcurr, aepsge,
&curve_val_3d, &curve_val_2d_1,
&curve_val_2d_2, &kstat);
if (kstat < 0)
goto error;
}
/* Check direction for const_crvs. */
if (cas)
for (ki = 0; ki < (*pintdat)->ilist; ki++)
{
pfirst_1 = (*pintdat)->vlist[ki]->pfirst;
plast_1 = (*pintdat)->vlist[ki]->plast;
if(((*pintdat)->vlist[ki]->inumb == 2) &&
(pfirst_1->curve_dir[(*pintdat)->vlist[ki]->ind_first] & logtest))
{
if (cas == 1)
{
}
else /*if (cas == 2)*/
{
/* Select midpoint. */
epar[0] = (pfirst_1->epar[0] + plast_1->epar[0])/2.0;
epar[1] = (pfirst_1->epar[1] + plast_1->epar[1])/2.0;
pturn = hp_newIntpt (2, epar, DZERO, SI_ORD,
SI_UNDEF, SI_UNDEF, SI_UNDEF, SI_UNDEF,
0, 0, nullp, nullp);
if (pturn == SISL_NULL)
goto err101;
sh6evalint (po1, po2, eimpli, ideg, pturn, aepsge,
&curve_val_3d, &curve_val_2d_1,
&curve_val_2d_2, &kstat);
if (kstat < 0)
goto error;
if (pturn->iinter == SI_ORD)
{
double dot;
dot = (plast_1->epar[0]-pfirst_1->epar[0])*curve_val_2d_1[2]+
(plast_1->epar[1]-pfirst_1->epar[1])*curve_val_2d_1[3];
if (dot < 0)
{
/* Turn direction. */
int ind_1, ind_2, dir_1, dir_2;
ind_1 = (*pintdat)->vlist[ki]->ind_first;
ind_2 = (*pintdat)->vlist[ki]->ind_last;
dir_1 = pfirst_1->curve_dir[ind_1];
dir_2 = plast_1->curve_dir[ind_2];
(*pintdat)->vlist[ki]->pfirst = plast_1;
(*pintdat)->vlist[ki]->plast = pfirst_1;
(*pintdat)->vlist[ki]->ind_first = ind_2;
(*pintdat)->vlist[ki]->ind_last = ind_1;
pfirst_1->curve_dir[ind_1] = dir_2;
plast_1->curve_dir[ind_2] = dir_1;
}
}
if (pturn) freeIntpt(pturn);
pturn = SISL_NULL;
}
}
}
/* Traverse the lists to remove doubly represented curves along
periodic edges. */
for (ki = 0; ki < (*pintdat)->ilist; ki++)
{
pfirst_1 = (*pintdat)->vlist[ki]->pfirst;
plast_1 = (*pintdat)->vlist[ki]->plast;
if(((*pintdat)->vlist[ki]->inumb == 2) &&
(pfirst_1->curve_dir[(*pintdat)->vlist[ki]->ind_first] & logtest))
const_crv_1 = TRUE;
else
const_crv_1 = FALSE;
if (pfirst_1 == plast_1) continue;
for (kj = 0; kj < (*pintdat)->ilist; kj++)
{
same_curve = (ki == kj);
pfirst_2 = (*pintdat)->vlist[kj]->pfirst;
plast_2 = (*pintdat)->vlist[kj]->plast;
if(((*pintdat)->vlist[kj]->inumb == 2) &&
(pfirst_2->curve_dir[(*pintdat)->vlist[kj]->ind_first] & logtest))
const_crv_2 = TRUE;
else
const_crv_2 = FALSE;
/* To treat the case when two curves are on an periodic edge */
if (const_crv_1 && const_crv_2 && !same_curve)
{
log_1 = pfirst_1->curve_dir[(*pintdat)->vlist[ki]->ind_first];
log_1 = log_1>>1;
log_1 &= 15;
log_2 = pfirst_2->curve_dir[(*pintdat)->vlist[kj]->ind_first];
log_2 = log_2>>1;
log_2 &= 15;
if (log_1 & log_2)
{
dist_a = s6dist(plast_1->geo_track_3d,
pfirst_2->geo_track_3d,
dimobj);
dist_b = s6dist(plast_1->geo_track_3d,
plast_2->geo_track_3d,
dimobj);
dist_c = s6dist(pfirst_1->geo_track_3d,
pfirst_2->geo_track_3d,
dimobj);
dist_d = s6dist(pfirst_1->geo_track_3d,
plast_2->geo_track_3d,
dimobj);
if ((dist_a <aepsge && dist_d < aepsge) ||
(dist_b <aepsge && dist_c < aepsge) )
{
/* Kill the two points */
sh6idkpt(pintdat, &pfirst_2, join=FALSE, &kstat);
if (kstat < 0) goto error;
sh6idkpt(pintdat, &plast_2, join=FALSE, &kstat);
if (kstat < 0) goto error;
/* Remove the curve list kj, and pack vlist array */
freeIntlist ((*pintdat)->vlist[kj]);
(*pintdat)->ilist--;
(*pintdat)->vlist[kj] =
(*pintdat)->vlist[(*pintdat)->ilist];
/* Reset to start */
ki = -1;
break; /* kj loop */
}
}
}
}
}
for (ki = 0; ki < (*pintdat)->ilist; ki++)
{
pfirst_1 = (*pintdat)->vlist[ki]->pfirst;
plast_1 = (*pintdat)->vlist[ki]->plast;
if(((*pintdat)->vlist[ki]->inumb == 2) &&
(pfirst_1->curve_dir[(*pintdat)->vlist[ki]->ind_first] & logtest))
const_crv_1 = TRUE;
else
const_crv_1 = FALSE;
if (pfirst_1 == plast_1) continue;
for (kj = 0; kj < (*pintdat)->ilist; kj++)
{
same_curve = (ki == kj);
pfirst_2 = (*pintdat)->vlist[kj]->pfirst;
plast_2 = (*pintdat)->vlist[kj]->plast;
if(((*pintdat)->vlist[kj]->inumb == 2) &&
(pfirst_2->curve_dir[(*pintdat)->vlist[kj]->ind_first] & logtest))
const_crv_2 = TRUE;
else
const_crv_2 = FALSE;
/* Joining of curves */
if (plast_1 == pfirst_2 ||
plast_1->iinter == SI_TRIM ||
plast_1->iinter == SI_SING ||
plast_1->iinter == SI_TOUCH ||
pfirst_2->iinter == SI_TRIM ||
pfirst_2->iinter == SI_SING ||
pfirst_2->iinter == SI_TOUCH)
{
/* Test on edge ? */
continue;
}
else
{
dist = s6dist(plast_1->geo_track_3d,
pfirst_2->geo_track_3d,
dimobj);
ang = s6ang(plast_1->geo_track_3d + dimobj,
pfirst_2->geo_track_3d + dimobj,
dimobj);
dot = s6scpr(plast_1->geo_track_3d + dimobj,
pfirst_2->geo_track_3d + dimobj,
dimobj);
if (dist < aepsge &&
dot > 0 &&
ang < ANGULAR_TOLERANCE)
{
/* HIT, Join the two lists of curves */
if (same_curve)
{
/*sh6connect(pfirst_1, plast_1, &kstat);
if (kstat != 0) goto error;
sh6idkpt (pintdat, &plast_1, join=TRUE, &kstat);
if (kstat < 0) goto error;
(*pintdat)->vlist[ki]->inumb -= 1;
periodic set to true !
(*pintdat)->vlist[ki]->plast =
pfirst_1; */
}
else
{
/* Move 2D values of second part */
s6diff(plast_1->epar,
pfirst_2->epar,
no_par,
delta_par);
/* Last check to see if we move outside legal area */
for(kp=0;kp<no_par;kp++)
{
min_par[kp] = HUGE;
max_par[kp] = -HUGE;
}
pcurr = pfirst_2;
pnext = pfirst_2->pnext[(*pintdat)->vlist[kj]->ind_first];
while (pcurr != plast_2 && pcurr && pnext)
{
for(kp=0;kp<no_par;kp++)
{
min_par[kp] = min(pnext->epar[kp]+delta_par[kp],min_par[kp]);
max_par[kp] = max(pnext->epar[kp]+delta_par[kp],max_par[kp]);
}
sh6getother (pnext, pcurr, &pother, &kstat);
if (kstat && pnext != plast_2) goto errinconsist;
pcurr = pnext;
pnext = pother;
}
for(kp=0;kp<no_par;kp++)
{
if (min_par[kp] < legal_min[kp] &&
DNEQUAL(min_par[kp],legal_min[kp])) break;
if (max_par[kp] > legal_max[kp] &&
DNEQUAL(max_par[kp],legal_max[kp])) break;
}
/* _______________________ */
if (kp == no_par)
{
pcurr = pfirst_2;
pnext = pfirst_2->pnext[(*pintdat)->vlist[kj]->ind_first];
while (pcurr != plast_2 && pcurr && pnext)
{
for(kp=0;kp<no_par;kp++)
pnext->epar[kp] += delta_par[kp];
if (treat_2d)
{
pnext->geo_track_2d_1[0] += delta_1[0];
pnext->geo_track_2d_1[1] += delta_1[1];
if (cas==1)
{
pnext->geo_track_2d_2[0] += delta_2[0];
pnext->geo_track_2d_2[1] += delta_2[1];
}
}
sh6getother (pnext, pcurr, &pother, &kstat);
if (kstat && pnext != plast_2) goto errinconsist;
pcurr = pnext;
pnext = pother;
}
sh6connect(plast_1, pfirst_2, &kstat);
if (kstat != 0) goto error;
sh6idkpt (pintdat, &pfirst_2, join=TRUE, &kstat);
if (kstat < 0) goto error;
if (const_crv_1 && const_crv_2)
{
sh6idkpt (pintdat, &plast_1, join=TRUE, &kstat);
if (kstat < 0) goto error;
sh6getlist(pfirst_1,plast_2,
&((*pintdat)->vlist[ki]->ind_first),
&((*pintdat)->vlist[ki]->ind_last),
&kstat);
kpos = 111;
if (kstat != 0) goto errinconsist;
(*pintdat)->vlist[ki]->inumb = 2;
(*pintdat)->vlist[ki]->plast =
plast_2;
}
else
{
(*pintdat)->vlist[ki]->inumb +=
(*pintdat)->vlist[kj]->inumb -1;
(*pintdat)->vlist[ki]->plast =
plast_2;
(*pintdat)->vlist[ki]->ind_last =
(*pintdat)->vlist[kj]->ind_last;
}
/* Remove the curve list kj, and pack vlist array */
freeIntlist ((*pintdat)->vlist[kj]);
(*pintdat)->ilist--;
(*pintdat)->vlist[kj] =
(*pintdat)->vlist[(*pintdat)->ilist];
/* Reset to start */
ki = -1;
break; /* kj loop */
}
} /* End of else not same curve */
} /* if hit */
} /* else */
} /* kj */
} /* ki */
/* Treat single points */
for (ki = 0; ki < (*pintdat)->ipoint; ki++)
{
kstat = 0;
pcurr = (*pintdat)->vpoint[ki];
if (sh6ismain(pcurr)) no_of_main = sh6nmbmain(pcurr, &kstat);
else no_of_main = -1;
if (kstat < 0) goto error;
if (no_of_main == 0)
for (kj = 0; kj < (*pintdat)->ipoint; kj++)
{
pother = (*pintdat)->vpoint[kj];
if (sh6ismain(pother) && pother != pcurr)
{
dist = s6dist(pcurr->geo_track_3d,
pother->geo_track_3d,
dimobj);
if (dist < aepsge)
{
sh6idkpt(pintdat, &pcurr, join = FALSE, &kstat);
if (kstat < 0) goto error;
ki--; /* New point in array place no ki, redo the job */
break; /* kj loop */
}
}
}
}
*jstat = 0;
goto out;
/* _________________________ EXIT ____________________________ */
/* Error in alloc */
err101:
*jstat = -101;
s6err ("int_join_per", *jstat, kpos);
goto out;
/* Error inconsistency */
errinconsist:
*jstat = -500;
s6err ("int_join_per", *jstat, kpos);
goto out;
/* Error in input */
errinp:
*jstat = -200;
s6err ("int_join_per", *jstat, kpos);
goto out;
/* Error in lower level function */
error:
*jstat = kstat;
s6err ("int_join_per", *jstat, kpos);
goto out;
out:
;
}
| 29.128527 | 78 | 0.528196 | [
"object",
"vector",
"3d"
] |
5e64eef3b03b7a0739be8b7179090ce3c71cdea1 | 786 | h | C | src/libraries/KIRK/Utils/Gui/GuiScene.h | lucashilbig/BA_Pathtracing_Fur | bed01d44ef93ff674436e002c82cb8c4663e2832 | [
"MIT"
] | null | null | null | src/libraries/KIRK/Utils/Gui/GuiScene.h | lucashilbig/BA_Pathtracing_Fur | bed01d44ef93ff674436e002c82cb8c4663e2832 | [
"MIT"
] | null | null | null | src/libraries/KIRK/Utils/Gui/GuiScene.h | lucashilbig/BA_Pathtracing_Fur | bed01d44ef93ff674436e002c82cb8c4663e2832 | [
"MIT"
] | null | null | null | #ifndef __KIRK_GUI_SCENE_H
#define __KIRK_GUI_SCENE_H
#include "Gui.h"
#include <KIRK/Common/SceneGraph.h>
#include "../../../CVK/CVK_Utils/CVK_ConverterUtils.h"
namespace KIRK {
enum SceneUpdateFlags
{
UPDATE_MATERIALS = 1 << 0,
UPDATE_GRAPH = 1 << 1
};
class GuiScene
{
public:
GuiScene(std::shared_ptr<KIRK::Gui> gui);
~GuiScene();
void buildSceneGui(std::shared_ptr<SceneGraph> graph, CVK::CVKCameraSynchronizer &sync);
void setUpdateCallback(std::function<void(unsigned)> callback, unsigned not_editable = 0);
private:
std::shared_ptr<KIRK::Gui> m_gui;
std::function<void(unsigned)> m_update_callback;
std::vector<std::shared_ptr<Camera>> m_cameras;
int m_current_camera = 0;
unsigned m_flags;
unsigned m_editable_flags;
};
}
#endif // !__KIRK_GUI_SCENE_H
| 21.243243 | 91 | 0.744275 | [
"vector"
] |
5e752057588d72fca1be613e6d1fa2176b93e0bf | 5,412 | h | C | src/saiga/vulkan/FrameTimings.h | no33fewi/saiga | edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68 | [
"MIT"
] | 114 | 2017-08-13T22:37:32.000Z | 2022-03-25T12:28:39.000Z | src/saiga/vulkan/FrameTimings.h | no33fewi/saiga | edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68 | [
"MIT"
] | 7 | 2019-10-14T18:19:11.000Z | 2021-06-11T09:41:52.000Z | src/saiga/vulkan/FrameTimings.h | no33fewi/saiga | edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68 | [
"MIT"
] | 18 | 2017-08-14T01:22:05.000Z | 2022-03-12T12:35:07.000Z | //
// Created by Peter Eichinger on 2019-03-08.
//
#pragma once
#include "saiga/vulkan/svulkan.h"
#include "FrameSync.h"
#include "memory/VulkanMemory.h"
#include <chrono>
#include <map>
#include <optional>
#include <set>
#include <string>
#include <vector>
namespace Saiga::Vulkan
{
struct FramePauses
{
std::vector<uint64_t> pauses;
FramePauses() = default;
FramePauses(size_t sections) : pauses(sections) {}
};
struct SuitablePause
{
uint64_t pauseIndex;
uint64_t length;
SuitablePause(uint64_t index, uint64_t len) : pauseIndex(index), length(len) {}
};
struct FindMinPause
{
SuitablePause findSuitablePause(const std::vector<FramePauses>& recentPauses,
std::vector<FramePauses>::const_iterator insertionPoint)
{
std::vector<uint64_t> minPerPause(recentPauses[0].pauses.size(), std::numeric_limits<uint64_t>::max());
for (auto& frame : recentPauses)
{
for (auto i = 0U; i < minPerPause.size(); ++i)
{
minPerPause[i] = std::min(minPerPause[i], frame.pauses[i]);
}
}
auto longestPause = std::max_element(minPerPause.begin(), minPerPause.end());
return SuitablePause(std::distance(minPerPause.begin(), longestPause), *longestPause);
}
};
template <typename Finder = FindMinPause>
class SAIGA_VULKAN_API FrameTimings
{
private:
using SectionTimes = std::vector<std::pair<uint64_t, uint64_t>>;
using SectionTimesIter = SectionTimes::iterator;
using Entry = std::pair<uint32_t, std::string>;
struct KeyComparator
{
bool operator()(const Entry& entry, const Entry& other) const { return entry.first < other.first; }
};
struct SAIGA_VULKAN_API Timing
{
vk::Fence fence;
SectionTimes sections;
Timing() = default;
explicit Timing(size_t numSections) : fence(nullptr), sections(numSections) {}
};
vk::CommandBuffer dummy = nullptr;
std::optional<SuitablePause> bestSection;
std::optional<SectionTimes> lastFrameSections;
std::vector<FramePauses> recentFramePauses;
std::vector<FramePauses>::iterator insertionPoint;
vk::Device device;
Saiga::Vulkan::Queue* queue;
std::vector<Timing> timings;
uint32_t numberOfFrames, next, current, running, frameWindow;
vk::QueryPool queryPool;
std::set<Entry, KeyComparator> frameSections;
std::map<std::string, uint32_t> nameToSectionMap;
Finder finder;
Memory::VulkanMemory* memory;
void destroyPool();
inline uint32_t getCount() const { return static_cast<uint32_t>(frameSections.size() * 2); }
inline uint32_t getFirst(uint32_t frame) const { return static_cast<uint32_t>(frame * getCount()); }
inline uint32_t getBegin(uint32_t index) const { return getFirst(current) + index * 2; }
inline uint32_t getEnd(uint32_t index) const { return getFirst(current) + index * 2 + 1; }
public:
FrameTimings() = default;
~FrameTimings()
{
if (device && dummy)
{
queue->commandPool.freeCommandBuffer(dummy);
}
destroyPool();
}
FrameTimings(vk::Device _device, Saiga::Vulkan::Queue* _queue, Memory::VulkanMemory* _memory)
: device(_device),
queue(_queue),
timings(0),
numberOfFrames(0),
next(0),
current(0),
running(0),
frameWindow(0),
queryPool(nullptr),
frameSections(),
finder(),
memory(_memory)
{
dummy = queue->commandPool.allocateCommandBuffer();
vk::CommandBufferBeginInfo cbbi;
cbbi.flags = vk::CommandBufferUsageFlagBits::eSimultaneousUse;
dummy.begin(cbbi);
dummy.end();
}
FrameTimings& operator=(FrameTimings&& other) noexcept
{
if (this != &other)
{
device = other.device;
timings = std::move(other.timings);
numberOfFrames = other.numberOfFrames;
next = other.next;
current = other.current;
running = other.running;
frameWindow = other.frameWindow;
queryPool = other.queryPool;
frameSections = std::move(other.frameSections);
memory = other.memory;
dummy = other.dummy;
queue = other.queue;
other.device = nullptr;
other.queryPool = nullptr;
other.memory = nullptr;
other.dummy = nullptr;
other.queue = nullptr;
}
return *this;
}
FrameTimings(FrameTimings&&) = delete;
FrameTimings(const FrameTimings&) = delete;
FrameTimings& operator=(const FrameTimings&) = delete;
void beginFrame(const FrameSync& sync);
void update();
void registerFrameSection(const std::string& name, uint32_t index);
void unregisterFrameSection(uint32_t index);
void create(uint32_t numberOfFrames, uint32_t _frameWindow = 20);
void reset();
void enterSection(const std::string& name, vk::CommandBuffer cmd);
void leaveSection(const std::string& name, vk::CommandBuffer cmd);
void resetFrame(vk::CommandBuffer cmd);
void finishFrame(vk::Semaphore semaphore);
};
} // namespace Saiga::Vulkan
| 29.413043 | 111 | 0.619919 | [
"vector"
] |
5e76a4ed83188dd7be721ce1aac3ce2a668d6c61 | 5,411 | c | C | slab_inject.c | mmenshchikov/slab_inject | 8eca80e1d898c76ded829195ed2e7874a2b13f75 | [
"MIT"
] | null | null | null | slab_inject.c | mmenshchikov/slab_inject | 8eca80e1d898c76ded829195ed2e7874a2b13f75 | [
"MIT"
] | null | null | null | slab_inject.c | mmenshchikov/slab_inject | 8eca80e1d898c76ded829195ed2e7874a2b13f75 | [
"MIT"
] | 1 | 2018-11-07T12:44:30.000Z | 2018-11-07T12:44:30.000Z | /*
* SLAB injection module.
*
* Author: Maxim Menshchikov <MaximMenshchikov@gmail.com>
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <asm/page.h>
#ifdef CONFIG_SLAB
#include <linux/slab_def.h>
#endif
#ifdef CONFIG_SLUB
#include <linux/slub_def.h>
#endif
static char *slab = NULL;
module_param(slab, charp, 0000);
MODULE_PARM_DESC(slab, "Target SLAB cache name");
unsigned int active_objs = 0;
module_param(active_objs, uint, 0);
MODULE_PARM_DESC(active_objs, "Number of active objects in SLAB");
unsigned int num_objs = 0;
module_param(num_objs, uint, 0);
MODULE_PARM_DESC(num_objs, "Total Number of objects in SLAB");
/**
* find_cache - find cache in the list of caches by name.
*
* @param slab_caches: SLAB cache list head.
* @param name: Cache name.
* @return struct kmem_cache * pointer if cache is found, NULL otherwise.
*/
static struct kmem_cache *
find_cache(struct list_head *slab_caches,
const char *name)
{
struct kmem_cache *c = NULL;
list_for_each_entry(c, slab_caches, list)
{
if (strcmp(c->name, name) == 0)
return c;
}
return NULL;
}
/**
* Free objects allocated by prefill_cache.
*
* @param cache: Cache to free objects from.
* @param objs: Pointer to array of pointers ending with NULL.
*/
static void
free_prefilled_objects(struct kmem_cache *cache, void **objs)
{
void **p = objs;
while (*p != NULL)
{
kmem_cache_free(cache, *p);
p++;
}
kfree(objs);
}
/**
* Prefill the cache to compensate the difference between total and active
* objects.
*
* @param cache: Cache to prefill.
* @return Pointer to array of pointers ending with NULL.
*/
static void **
prefill_cache(struct kmem_cache *cache)
{
void **objs;
int i;
objs = kzalloc(sizeof(void *) * (num_objs - active_objs + 1),
GFP_KERNEL);
for (i = 0; i < (num_objs - active_objs); ++i)
{
objs[i] = kmem_cache_alloc(cache, GFP_KERNEL);
if (objs[i] == NULL)
{
free_prefilled_objects(cache, objs);
kfree(objs);
return NULL;
}
}
return objs;
}
/**
* Inject single page to cache.
*
* @param cache: Target cache.
* @return Status code.
*/
static int
inject_cache_page(struct kmem_cache *cache)
{
int err;
int i;
int n;
void **objs;
int boundary;
/*
* Calculate the number of objects and the 'boundary', i.e. the number of
* objects to free up.
*/
n = PAGE_SIZE / cache->size;
boundary = n - 1;
objs = kzalloc(sizeof(void *) * n, GFP_KERNEL);
if (objs == NULL)
return -ENOMEM;
for (i = 0; i < n; ++i)
{
objs[i] = kmem_cache_alloc(cache, GFP_KERNEL);
if (objs[i] == NULL)
{
printk(KERN_ERR "Failed to allocate object for SLAB injection");
/* Change boundary to 'all' objects */
boundary = n;
err = -ENOMEM;
goto clear_objects;
}
}
err = 0;
clear_objects:
for (i = 0; i < boundary; ++i)
{
if (objs[i] != NULL)
kmem_cache_free(cache, objs[i]);
}
kfree(objs);
return err;
}
static int __init
slab_inject_init(void)
{
struct kmem_cache *test_cache;
struct kmem_cache *c;
int err = -EBUSY;
if (slab == NULL || strlen(slab) == 0)
{
printk(KERN_ERR "No SLAB to fill\n");
return -EINVAL;
}
if (active_objs > num_objs)
{
printk(KERN_ERR "Number of objects is invalid\n");
return -EINVAL;
}
test_cache = kmem_cache_create("test_cache",
100, 0, SLAB_PANIC, NULL);
if (test_cache == NULL)
{
printk(KERN_ERR "Couldn't allocate test SLAB\n");
return -ENOMEM;
}
c = find_cache(&test_cache->list, slab);
if (c != NULL)
{
void **prefilled_objs;
printk(KERN_INFO "Cache: %s\n", c->name);
printk(KERN_INFO "Object size: %u\n", c->object_size);
printk(KERN_INFO "Aligned size: %u\n", c->size);
printk(KERN_INFO "Can fit %lu objects to page (page size=%lu)\n",
PAGE_SIZE / c->size, PAGE_SIZE);
if ((PAGE_SIZE / c->size) < 2)
{
printk(KERN_INFO "SLAB inject cannot be used for objects "
"bigger than half of page");
err = -EINVAL;
goto cleanup;
}
prefilled_objs = prefill_cache(c);
if (prefilled_objs == NULL)
{
err = -ENOMEM;
goto cleanup;
}
err = inject_cache_page(c);
if (err != 0)
{
printk(KERN_ERR "Couldn't inject a page to cache: %d", err);
}
else
{
err = 0;
}
free_prefilled_objects(c, prefilled_objs);
kmem_cache_shrink(c);
}
else
{
printk(KERN_INFO "SLAB '%s' not found\n", slab);
err = -ENOENT;
}
cleanup:
kmem_cache_destroy(test_cache);
return err;
}
static void __exit slab_inject_exit(void)
{
}
module_init(slab_inject_init);
module_exit(slab_inject_exit);
MODULE_AUTHOR("Maxim Menshchikov <MaximMenshchikov@gmail.com>");
MODULE_LICENSE("MIT");
| 22.17623 | 77 | 0.578266 | [
"object"
] |
5e7cfcf78af83fb1834cbb134c330c64cf527a00 | 12,995 | h | C | ame/include/tencentcloud/ame/v20190916/model/SyncKTVRobotCommandRequest.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | ame/include/tencentcloud/ame/v20190916/model/SyncKTVRobotCommandRequest.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | ame/include/tencentcloud/ame/v20190916/model/SyncKTVRobotCommandRequest.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_AME_V20190916_MODEL_SYNCKTVROBOTCOMMANDREQUEST_H_
#define TENCENTCLOUD_AME_V20190916_MODEL_SYNCKTVROBOTCOMMANDREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/ame/v20190916/model/PlayCommandInput.h>
#include <tencentcloud/ame/v20190916/model/SetPlaylistCommandInput.h>
#include <tencentcloud/ame/v20190916/model/SeekCommandInput.h>
#include <tencentcloud/ame/v20190916/model/SetAudioParamCommandInput.h>
#include <tencentcloud/ame/v20190916/model/SendMessageCommandInput.h>
#include <tencentcloud/ame/v20190916/model/SetPlayModeCommandInput.h>
#include <tencentcloud/ame/v20190916/model/SetDestroyModeCommandInput.h>
#include <tencentcloud/ame/v20190916/model/SetVolumeCommandInput.h>
namespace TencentCloud
{
namespace Ame
{
namespace V20190916
{
namespace Model
{
/**
* SyncKTVRobotCommand请求参数结构体
*/
class SyncKTVRobotCommandRequest : public AbstractModel
{
public:
SyncKTVRobotCommandRequest();
~SyncKTVRobotCommandRequest() = default;
std::string ToJsonString() const;
/**
* 获取机器人Id。
* @return RobotId 机器人Id。
*/
std::string GetRobotId() const;
/**
* 设置机器人Id。
* @param RobotId 机器人Id。
*/
void SetRobotId(const std::string& _robotId);
/**
* 判断参数 RobotId 是否已赋值
* @return RobotId 是否已赋值
*/
bool RobotIdHasBeenSet() const;
/**
* 获取指令,取值有:
<li>Play:播放</li>
<li>Pause:暂停</li>
<li>SwitchPrevious:上一首</li>
<li>SwitchNext:下一首</li>
<li>SetPlayMode:设置播放模式</li>
<li>Seek:调整播放进度</li>
<li>SetPlaylist:歌单变更</li>
<li>SetAudioParam:音频参数变更</li>
<li>SendMessage:发送自定义消息</li>
<li>SetDestroyMode:设置销毁模式</li>
<li>SetVolume:设置音量</li>
* @return Command 指令,取值有:
<li>Play:播放</li>
<li>Pause:暂停</li>
<li>SwitchPrevious:上一首</li>
<li>SwitchNext:下一首</li>
<li>SetPlayMode:设置播放模式</li>
<li>Seek:调整播放进度</li>
<li>SetPlaylist:歌单变更</li>
<li>SetAudioParam:音频参数变更</li>
<li>SendMessage:发送自定义消息</li>
<li>SetDestroyMode:设置销毁模式</li>
<li>SetVolume:设置音量</li>
*/
std::string GetCommand() const;
/**
* 设置指令,取值有:
<li>Play:播放</li>
<li>Pause:暂停</li>
<li>SwitchPrevious:上一首</li>
<li>SwitchNext:下一首</li>
<li>SetPlayMode:设置播放模式</li>
<li>Seek:调整播放进度</li>
<li>SetPlaylist:歌单变更</li>
<li>SetAudioParam:音频参数变更</li>
<li>SendMessage:发送自定义消息</li>
<li>SetDestroyMode:设置销毁模式</li>
<li>SetVolume:设置音量</li>
* @param Command 指令,取值有:
<li>Play:播放</li>
<li>Pause:暂停</li>
<li>SwitchPrevious:上一首</li>
<li>SwitchNext:下一首</li>
<li>SetPlayMode:设置播放模式</li>
<li>Seek:调整播放进度</li>
<li>SetPlaylist:歌单变更</li>
<li>SetAudioParam:音频参数变更</li>
<li>SendMessage:发送自定义消息</li>
<li>SetDestroyMode:设置销毁模式</li>
<li>SetVolume:设置音量</li>
*/
void SetCommand(const std::string& _command);
/**
* 判断参数 Command 是否已赋值
* @return Command 是否已赋值
*/
bool CommandHasBeenSet() const;
/**
* 获取播放参数。
* @return PlayCommandInput 播放参数。
*/
PlayCommandInput GetPlayCommandInput() const;
/**
* 设置播放参数。
* @param PlayCommandInput 播放参数。
*/
void SetPlayCommandInput(const PlayCommandInput& _playCommandInput);
/**
* 判断参数 PlayCommandInput 是否已赋值
* @return PlayCommandInput 是否已赋值
*/
bool PlayCommandInputHasBeenSet() const;
/**
* 获取播放列表变更信息,当Command取SetPlaylist时,必填。
* @return SetPlaylistCommandInput 播放列表变更信息,当Command取SetPlaylist时,必填。
*/
SetPlaylistCommandInput GetSetPlaylistCommandInput() const;
/**
* 设置播放列表变更信息,当Command取SetPlaylist时,必填。
* @param SetPlaylistCommandInput 播放列表变更信息,当Command取SetPlaylist时,必填。
*/
void SetSetPlaylistCommandInput(const SetPlaylistCommandInput& _setPlaylistCommandInput);
/**
* 判断参数 SetPlaylistCommandInput 是否已赋值
* @return SetPlaylistCommandInput 是否已赋值
*/
bool SetPlaylistCommandInputHasBeenSet() const;
/**
* 获取播放进度,当Command取Seek时,必填。
* @return SeekCommandInput 播放进度,当Command取Seek时,必填。
*/
SeekCommandInput GetSeekCommandInput() const;
/**
* 设置播放进度,当Command取Seek时,必填。
* @param SeekCommandInput 播放进度,当Command取Seek时,必填。
*/
void SetSeekCommandInput(const SeekCommandInput& _seekCommandInput);
/**
* 判断参数 SeekCommandInput 是否已赋值
* @return SeekCommandInput 是否已赋值
*/
bool SeekCommandInputHasBeenSet() const;
/**
* 获取音频参数,当Command取SetAudioParam时,必填。
* @return SetAudioParamCommandInput 音频参数,当Command取SetAudioParam时,必填。
*/
SetAudioParamCommandInput GetSetAudioParamCommandInput() const;
/**
* 设置音频参数,当Command取SetAudioParam时,必填。
* @param SetAudioParamCommandInput 音频参数,当Command取SetAudioParam时,必填。
*/
void SetSetAudioParamCommandInput(const SetAudioParamCommandInput& _setAudioParamCommandInput);
/**
* 判断参数 SetAudioParamCommandInput 是否已赋值
* @return SetAudioParamCommandInput 是否已赋值
*/
bool SetAudioParamCommandInputHasBeenSet() const;
/**
* 获取自定义消息,当Command取SendMessage时,必填。
* @return SendMessageCommandInput 自定义消息,当Command取SendMessage时,必填。
*/
SendMessageCommandInput GetSendMessageCommandInput() const;
/**
* 设置自定义消息,当Command取SendMessage时,必填。
* @param SendMessageCommandInput 自定义消息,当Command取SendMessage时,必填。
*/
void SetSendMessageCommandInput(const SendMessageCommandInput& _sendMessageCommandInput);
/**
* 判断参数 SendMessageCommandInput 是否已赋值
* @return SendMessageCommandInput 是否已赋值
*/
bool SendMessageCommandInputHasBeenSet() const;
/**
* 获取播放模式,当Command取SetPlayMode时,必填。
* @return SetPlayModeCommandInput 播放模式,当Command取SetPlayMode时,必填。
*/
SetPlayModeCommandInput GetSetPlayModeCommandInput() const;
/**
* 设置播放模式,当Command取SetPlayMode时,必填。
* @param SetPlayModeCommandInput 播放模式,当Command取SetPlayMode时,必填。
*/
void SetSetPlayModeCommandInput(const SetPlayModeCommandInput& _setPlayModeCommandInput);
/**
* 判断参数 SetPlayModeCommandInput 是否已赋值
* @return SetPlayModeCommandInput 是否已赋值
*/
bool SetPlayModeCommandInputHasBeenSet() const;
/**
* 获取销毁模式,当Command取SetDestroyMode时,必填。
* @return SetDestroyModeCommandInput 销毁模式,当Command取SetDestroyMode时,必填。
*/
SetDestroyModeCommandInput GetSetDestroyModeCommandInput() const;
/**
* 设置销毁模式,当Command取SetDestroyMode时,必填。
* @param SetDestroyModeCommandInput 销毁模式,当Command取SetDestroyMode时,必填。
*/
void SetSetDestroyModeCommandInput(const SetDestroyModeCommandInput& _setDestroyModeCommandInput);
/**
* 判断参数 SetDestroyModeCommandInput 是否已赋值
* @return SetDestroyModeCommandInput 是否已赋值
*/
bool SetDestroyModeCommandInputHasBeenSet() const;
/**
* 获取音量,当Command取SetVolume时,必填。
* @return SetVolumeCommandInput 音量,当Command取SetVolume时,必填。
*/
SetVolumeCommandInput GetSetVolumeCommandInput() const;
/**
* 设置音量,当Command取SetVolume时,必填。
* @param SetVolumeCommandInput 音量,当Command取SetVolume时,必填。
*/
void SetSetVolumeCommandInput(const SetVolumeCommandInput& _setVolumeCommandInput);
/**
* 判断参数 SetVolumeCommandInput 是否已赋值
* @return SetVolumeCommandInput 是否已赋值
*/
bool SetVolumeCommandInputHasBeenSet() const;
private:
/**
* 机器人Id。
*/
std::string m_robotId;
bool m_robotIdHasBeenSet;
/**
* 指令,取值有:
<li>Play:播放</li>
<li>Pause:暂停</li>
<li>SwitchPrevious:上一首</li>
<li>SwitchNext:下一首</li>
<li>SetPlayMode:设置播放模式</li>
<li>Seek:调整播放进度</li>
<li>SetPlaylist:歌单变更</li>
<li>SetAudioParam:音频参数变更</li>
<li>SendMessage:发送自定义消息</li>
<li>SetDestroyMode:设置销毁模式</li>
<li>SetVolume:设置音量</li>
*/
std::string m_command;
bool m_commandHasBeenSet;
/**
* 播放参数。
*/
PlayCommandInput m_playCommandInput;
bool m_playCommandInputHasBeenSet;
/**
* 播放列表变更信息,当Command取SetPlaylist时,必填。
*/
SetPlaylistCommandInput m_setPlaylistCommandInput;
bool m_setPlaylistCommandInputHasBeenSet;
/**
* 播放进度,当Command取Seek时,必填。
*/
SeekCommandInput m_seekCommandInput;
bool m_seekCommandInputHasBeenSet;
/**
* 音频参数,当Command取SetAudioParam时,必填。
*/
SetAudioParamCommandInput m_setAudioParamCommandInput;
bool m_setAudioParamCommandInputHasBeenSet;
/**
* 自定义消息,当Command取SendMessage时,必填。
*/
SendMessageCommandInput m_sendMessageCommandInput;
bool m_sendMessageCommandInputHasBeenSet;
/**
* 播放模式,当Command取SetPlayMode时,必填。
*/
SetPlayModeCommandInput m_setPlayModeCommandInput;
bool m_setPlayModeCommandInputHasBeenSet;
/**
* 销毁模式,当Command取SetDestroyMode时,必填。
*/
SetDestroyModeCommandInput m_setDestroyModeCommandInput;
bool m_setDestroyModeCommandInputHasBeenSet;
/**
* 音量,当Command取SetVolume时,必填。
*/
SetVolumeCommandInput m_setVolumeCommandInput;
bool m_setVolumeCommandInputHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_AME_V20190916_MODEL_SYNCKTVROBOTCOMMANDREQUEST_H_
| 36.40056 | 118 | 0.526433 | [
"vector",
"model"
] |
5e7f58213dc8430148d552e09e07ccfd1891bd1a | 4,956 | h | C | src/libgeo/si.h | transpixel/TPQZcam | b44a97d44b49e9aa76c36efb6e4102091ff36c67 | [
"MIT"
] | 1 | 2017-06-01T00:21:16.000Z | 2017-06-01T00:21:16.000Z | src/libgeo/si.h | transpixel/TPQZcam | b44a97d44b49e9aa76c36efb6e4102091ff36c67 | [
"MIT"
] | 3 | 2017-06-01T00:26:16.000Z | 2020-05-09T21:06:27.000Z | libgeo/si.h | transpixel/tpqz | 2d8400b1be03292d0c5ab74710b87e798ae6c52c | [
"MIT"
] | null | null | null | //
//
// MIT License
//
// Copyright (c) 2020 Stellacore 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.
//
//
#ifndef geo_si_INCL_
#define geo_si_INCL_
/*! \file
\brief Declarations for geo::si
*/
#include "libgeo/Plane.h"
#include "libgeo/Ray.h"
#include <vector>
namespace geo
{
/*! \brief Space intersection operations
\par Example
\dontinclude testgeo/usi.cpp
\skip ExampleStart
\until ExampleEnd
*/
namespace si
{
using ObsWeight = double;
using WRay = std::pair<ObsWeight, geo::Ray>;
using WPlane = std::pair<ObsWeight, geo::Plane>;
//! Uncertain observation data
template <typename GeoType>
struct Obs
{
GeoType theGeoItem;
double theDirSigma;
double theStaSigma;
//! Weight for this ray based on nominal range
inline
double
obsWeight
( double const & nomRange
) const;
//! Descriptive information about this instance
inline
std::string
infoString
( std::string const & title = {}
) const;
}; // ObsRay
//! Normal system singular geometry (e.g. inverse ellipsoid axes)
struct SemiAxis
{
double theMag;
ga::Vector theDir;
//! Descriptive information about this instance
std::string
infoString
( std::string const & title = {}
) const;
//! Full vectos (product of Mag and Dir)
ga::Vector
asVector
() const;
}; // Singular Axis
//! Data container for a 3D point and uncertainty
struct PointSoln
{
ga::Vector const theLoc;
std::array<SemiAxis, 3u> const theSemiAxes;
//! Descriptive information about this instance
std::string
infoString
( std::string const & title = {}
) const;
//! Vector semi-axis (from theLoc, to ndx-th tip on stdEllipsoid)
SemiAxis
kthLargestSemiAxis
( size_t const & ndx //!< 0,1,2: smallest to largest
) const;
//! Root-Mean-Square of axes magnitudes (only valid values included)
double
rmsAxisMagnitude
() const;
//! Coordinates for endpoints of semiaxes (6 pnts)
std::vector<ga::Vector>
ellipsoidTips
() const;
}; // PointSoln
using Dyadic = std::array<double, 9u>;
using RhsVec = std::array<double, 3u>;
//! Tensor dyadic product formation - Container must have op[]() [0,1,2]
template <typename Container>
inline
Dyadic
planeDyadicFor
( Container const & dir
);
//! Tensor dyadic product formation - Container must have op[]() [0,1,2]
template <typename Container>
inline
Dyadic
rayDyadicFor
( Container const & dir
);
//! Normal equation system
class PointSystem
{
Dyadic theNormCo{};
RhsVec theNormRhs{};
size_t theNumRays{ 0u };
size_t theNumPlanes{ 0u };
private: // methods
//! Incorporate weighted dyadic observation into normal coeff matrix
inline
void
addWeightedDyadic
( double const & weightSq
, Dyadic const & bigQ
);
//! Incorporate weighted dyadic observation into RHS of normal system
inline
void
addWeightedRhs
( double const & weightSq
, Dyadic const & bigQ
, ga::Vector const & vec
);
public: // methods
//! Construct with fully zeroed accumulation buffers
PointSystem
();
//! Incorporate a collection of weighted ray observations
inline
void
addWeightedRay
( WRay const & wray
);
//! Incorporate a collection of weighted plane observations
inline
void
addWeightedPlane
( WPlane const & wplane
);
//! Incorporate a collection of weighted ray observations
void
addWeightedRays
( std::vector<WRay> const & wrays
);
//! Incorporate a collection of weighted plane observations
void
addWeightedPlanes
( std::vector<WPlane> const & wplanes
);
//! Least squares solution (or as close as it gets)
PointSoln
pointSolution
() const;
//! Descriptive information about this instance
std::string
infoString
( std::string const & title = {}
) const;
}; // PointSystem
} // si
} // geo
// Inline definitions
#include "libgeo/si.inl"
#endif // geo_si_INCL_
| 21.270386 | 73 | 0.699556 | [
"geometry",
"vector",
"3d"
] |
5e803c2b0fbb0e2a1a9acf1e45c68249772a400e | 2,375 | h | C | example-8/src/Client.h | GGolbik/basics-cpp | 37466e7fa03b428093055a269e2ee96b8e685b82 | [
"MIT"
] | null | null | null | example-8/src/Client.h | GGolbik/basics-cpp | 37466e7fa03b428093055a269e2ee96b8e685b82 | [
"MIT"
] | null | null | null | example-8/src/Client.h | GGolbik/basics-cpp | 37466e7fa03b428093055a269e2ee96b8e685b82 | [
"MIT"
] | null | null | null | #pragma once
#include <atomic>
#include <mutex>
#include <string>
#include <thread>
#ifndef _WIN32
#include "OpenSslWrapper.h"
#endif
namespace ggolbik {
namespace cpp {
namespace tls {
class Client {
private: // type definitions
typedef char byte;
public: // const
// 64KiByte
static const unsigned int MAX_BUFFER_SIZE = 65535;
public: // construction/destruction/operators
/**
* @brief Construct a new Client object
*
* @param serverAddress the interface
* @param port the port
*/
Client(std::string serverAddress, unsigned short port);
/**
* Move constructor
*/
Client(Client &&) = delete;
/**
* Move assignment operator
*/
Client &operator=(Client &&) = delete;
/**
* Copy constructor
*/
Client(const Client &) = delete;
/**
* Copy assignment operator
*/
Client &operator=(const Client &) = delete;
/**
* Destructor
*/
virtual ~Client();
public: // methods
bool open();
bool isOpen();
void close();
/**
* @brief Reads a string from the stream.
*
* @param message The read message if return value is > 0
* @return the size of the read data, if 0 there was no data, if -1 an error
* occured.
*/
int tryReadString(std::string &message);
/**
* @brief Reads a string from the stream. Blocks until data is available or an
* error occured.
*
* @param message
* @return true if data has been read. false if an error occured.
*/
bool readString(std::string &message);
/**
* @brief Writes data to the stream.
*
* @param data the data to write
* @param length the length of the array
* @return true if data has been written. false if an error occured.
*/
bool write(const byte data[], size_t length);
private:
bool closeSocket();
private:
std::mutex mutexPublicMethods;
int clientSocket;
bool enabled;
std::string serverAddress;
unsigned short port;
public: // TLS methods
int tryReadStringTls(std::string &message);
// blocks until data is available
bool readStringTls(std::string &message);
bool writeTls(const byte data[], size_t length);
private: // TLS fields
std::string keyFileName;
std::string certFileName;
#ifndef _WIN32
OpenSslWrapper::TlsContextPtr tlsContextPtr;
OpenSslWrapper::TlsPtr tlsPtr;
#endif
};
} // namespace tls
} // namespace cpp
} // namespace ggolbik
| 21.590909 | 80 | 0.665263 | [
"object"
] |
5e853398e1a40112c093aa238b4ad6229d5baf73 | 4,207 | h | C | Sources/D3D/d3d_frame_buffer_provider.h | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | Sources/D3D/d3d_frame_buffer_provider.h | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | Sources/D3D/d3d_frame_buffer_provider.h | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | /*
** ClanLib SDK
** Copyright (c) 1997-2016 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#pragma once
#include "API/Display/TargetProviders/frame_buffer_provider.h"
#include "API/Display/Render/render_buffer.h"
#include "API/Display/Render/texture_2d.h"
#include "d3d_render_buffer_provider.h"
#include "d3d_texture_provider.h"
namespace clan
{
class D3DFrameBufferProvider : public FrameBufferProvider
{
public:
D3DFrameBufferProvider(const ComPtr<ID3D11Device> &device);
~D3DFrameBufferProvider();
Size get_size() const;
FrameBufferBindTarget get_bind_target() const;
ComPtr<ID3D11Device> &get_device() { return device; }
std::vector<ID3D11RenderTargetView*> get_views(ID3D11DepthStencilView *&out_dsv);
void attach_color(int attachment_index, const RenderBuffer &render_buffer);
void attach_color(int attachment_index, const Texture1D &texture, int level);
void attach_color(int attachment_index, const Texture1DArray &texture, int array_index, int level);
void attach_color(int attachment_index, const Texture2D &texture, int level);
void attach_color(int attachment_index, const Texture2DArray &texture, int array_index, int level);
void attach_color(int attachment_index, const Texture3D &texture, int depth, int level);
void attach_color(int attachment_index, const TextureCube &texture, TextureSubtype subtype, int level);
void detach_color(int attachment_index);
void attach_stencil(const RenderBuffer &render_buffer);
void attach_stencil(const Texture2D &texture, int level);
void attach_stencil(const TextureCube &texture, TextureSubtype subtype, int level);
void detach_stencil();
void attach_depth(const RenderBuffer &render_buffer);
void attach_depth(const Texture2D &texture, int level);
void attach_depth(const TextureCube &texture, TextureSubtype subtype, int level);
void detach_depth();
void attach_depth_stencil(const RenderBuffer &render_buffer);
void attach_depth_stencil(const Texture2D &texture, int level);
void attach_depth_stencil(const TextureCube &texture, TextureSubtype subtype, int level);
void detach_depth_stencil();
void set_bind_target(FrameBufferBindTarget target);
private:
struct AttachedBuffer
{
AttachedBuffer() : level(0), slice(0), subtype() { }
AttachedBuffer(RenderBuffer render_buffer) : render_buffer(render_buffer), level(0), slice(0), subtype() { }
AttachedBuffer(Texture texture, int level = 0, int slice = 0, TextureSubtype subtype = TextureSubtype()) : texture(texture), level(level), slice(slice), subtype(subtype) { }
D3DRenderBufferProvider *get_render_buffer_provider() const { return static_cast<D3DRenderBufferProvider*>(render_buffer.get_provider()); }
D3DTextureProvider *get_texture_provider() const { return static_cast<D3DTextureProvider*>(texture.get_provider()); }
RenderBuffer render_buffer;
Texture texture;
int level;
int slice;
TextureSubtype subtype;
ComPtr<ID3D11RenderTargetView> rtv;
ComPtr<ID3D11DepthStencilView> dsv;
};
ComPtr<ID3D11Device> device;
std::vector<AttachedBuffer> color_buffers;
AttachedBuffer depth_buffer;
AttachedBuffer stencil_buffer;
FrameBufferBindTarget bind_target;
};
}
| 40.451923 | 176 | 0.771333 | [
"render",
"vector"
] |
5e87b94190c3b6a26bac67289770f6124ca30136 | 5,227 | h | C | linux/vscpl2drv_raweth.h | grodansparadis/vscpl2drv-raweth | e766c33f7c792828aaee2a9bd873451f543237a3 | [
"MIT"
] | 1 | 2022-01-24T20:20:50.000Z | 2022-01-24T20:20:50.000Z | linux/vscpl2drv_raweth.h | grodansparadis/vscpl2drv-raweth | e766c33f7c792828aaee2a9bd873451f543237a3 | [
"MIT"
] | null | null | null | linux/vscpl2drv_raweth.h | grodansparadis/vscpl2drv-raweth | e766c33f7c792828aaee2a9bd873451f543237a3 | [
"MIT"
] | null | null | null | // rawethernet.h: interface for the rawethernet class.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version
// 2 of the License, or (at your option) any later version.
//
// This file is part of the VSCP (http://www.vscp.org)
//
// Copyright (C) 2000-2019 Ake Hedman,
// Grodans Paradis AB, <akhe@grodansparadis.com>
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this file see the file COPYING. If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
#if !defined(VSCPRAWETH_H__6F5CD90E_ACF7_459A_9ACB_849A57595639__INCLUDED_)
#define VSCPRAWETH_H__6F5CD90E_ACF7_459A_9ACB_849A57595639__INCLUDED_
#include <list>
#include <string>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define _POSIX
#include <pthread.h>
#include <syslog.h>
#include <unistd.h>
#include <canal.h>
#include <canal_macro.h>
#include <guid.h>
#include <vscp.h>
#include <vscpdatetime.h>
#include <vscpremotetcpif.h>
#ifndef BOOL
typedef int BOOL;
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define VSCP_DLL_SONAME "vscpl2drv_raweth.1.2"
// This is the version info for this DLL - Change to your own value
#define VSCP_DLL_VERSION 2
// This is the vendor string - Change to your own value
#define VSCP_DLL_VENDOR \
"Grodans Paradis AB, Sweden, https://www.grodansparadis.com"
// This is the VSCP rwa ethernet frame version used by this driver
#define RAW_ETHERNET_FRAME_VERSION 1
#define VSCP_LEVEL2_DLL_RAWETHERNET_OBJ_MUTEX \
"___VSCP__DLL_L2RAWETHERNET_OBJ_MUTEX____"
#define VSCP_RAWETH_DRIVERINFO ""
// Forward declarations
class CRawEthernet;
class CWrkReadThreadObj;
class CWrkWriteThreadObj;
class VscpRemoteTcpIf;
/*!
Add a driver object
@parm plog Object to add
@return handle or 0 for error
*/
long
addDriverObject(CRawEthernet *pif);
/*!
Get a driver object from its handle
@param handle for object
@return pointer to object or NULL if invalid
handle.
*/
CRawEthernet *
getDriverObject(long handle);
/*!
Remove a driver object
@param handle for object.
*/
void
removeDriverObject(long handle);
class CRawEthernet
{
public:
/// Constructor
CRawEthernet();
/// Destructor
virtual ~CRawEthernet();
/*!
Open
@return True on success.
*/
bool open(const char *pUsername,
const char *pPassword,
const char *pHost,
short port,
const char *pPrefix,
const char *pConfig,
unsigned long flags);
/*!
Flush and close the log file
*/
void close(void);
/*!
Add event to send queue
*/
bool addEvent2SendQueue(const vscpEvent *pEvent);
public:
/// Run flag
bool m_bQuit;
/// Server supplied username
std::string m_username;
/// Server supplied password
std::string m_password;
/// server supplied prefix
std::string m_prefix;
/// server supplied host
std::string m_host;
/// Server supplied port
short m_port;
/// Ethernet interface to use
std::string m_interface;
/// Source MAC address
std::string m_strlocalMac;
uint8_t m_localMac[16];
/// Subaddr of interface
uint16_t m_subaddr;
/// Filter
vscpEventFilter m_vscpfilter;
/// Pointer to worker threads
CWrkReadThreadObj *m_preadWorkThread;
CWrkWriteThreadObj *m_pwriteWorkThread;
pthread_t *m_readWrkThread;
pthread_t *m_writeWrkThread;
/// VSCP server interface
VscpRemoteTcpIf m_srv;
// Queue
std::list<vscpEvent *> m_sendList;
std::list<vscpEvent *> m_receiveList;
/*!
Event object to indicate that there is an event in the output queue
*/
sem_t m_semSendQueue;
sem_t m_semReceiveQueue;
// Mutex to protect the output queue
pthread_mutex_t m_mutexSendQueue;
pthread_mutex_t m_mutexReceiveQueue;
};
///////////////////////////////////////////////////////////////////////////////
// Worker Treads
///////////////////////////////////////////////////////////////////////////////
class CWrkReadThreadObj
{
public:
/// Constructor
CWrkReadThreadObj();
/// Destructor
~CWrkReadThreadObj();
/// VSCP server interface
VscpRemoteTcpIf m_srv;
/// Sensor object
CRawEthernet *m_pObj;
};
class CWrkWriteThreadObj
{
public:
/// Constructor
CWrkWriteThreadObj();
/// Destructor
~CWrkWriteThreadObj();
/// VSCP server interface
VscpRemoteTcpIf m_srv;
/// Sensor object
CRawEthernet *m_pObj;
};
#endif // !defined(VSCPRAWETH_H__6F5CD90E_ACF7_459A_9ACB_849A57595639__INCLUDED_)
| 22.433476 | 81 | 0.658121 | [
"object"
] |
9983a0862e114328f3b45a12474432cee5d54563 | 2,303 | h | C | cpgf/tools/cmetagen/src/buildermodel/buildercontext.h | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | 187 | 2015-01-19T06:05:30.000Z | 2022-03-27T14:28:21.000Z | cpgf/tools/cmetagen/src/buildermodel/buildercontext.h | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | 37 | 2015-01-16T04:15:11.000Z | 2020-03-31T23:42:55.000Z | cpgf/tools/cmetagen/src/buildermodel/buildercontext.h | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | 50 | 2015-01-13T13:50:10.000Z | 2022-01-25T17:16:51.000Z | #ifndef CPGF_BUILDERCONTEXT_H
#define CPGF_BUILDERCONTEXT_H
#include "builderitem.h"
#include "buildersection.h"
#include "cpgf/gscopedptr.h"
#include "cpgf/gcallback.h"
#include "cpgf/gclassutil.h"
#include <string>
#include <vector>
#include <deque>
namespace metagen {
class CppContext;
class CppContanier;
class CppFile;
class CppSourceFile;
class BuilderContext;
class BuilderFile;
class BuilderContainer;
class BuilderSection;
class BuilderSectionList;
class BuilderFileWriter;
class Project;
class BuilderContext
{
private:
typedef std::vector<BuilderFileWriter *> BuilderFileWriterListType;
public:
typedef std::vector<BuilderItem *> ItemListType;
public:
BuilderContext(const Project * project, const CppSourceFile & sourceFile, bool overwriteEvenIfNoChange);
~BuilderContext();
void process(const CppContext * cppContext);
const Project * getProject() const;
bool shouldOverwriteEvenIfNoChange() const;
std::string getSourceFileName() const;
std::string getSourceBaseFileName() const;
ItemListType * getItemList();
BuilderSectionList * getSectionList();
private:
void doProcessFile(const CppFile * cppFile);
void doPreocessByScript();
void generateCodeSections();
void generateCreationFunctionSections();
void doGenerateCreateFunctionSection(BuilderSection * sampleSection,
BuilderSectionListType::iterator begin, BuilderSectionListType::iterator end);
void createHeaderFileWriter();
void createSourceFileWriters();
void doCollectPartialCreationFunctions(BuilderSectionListType * partialCreationSections);
void doCreateSourceFileWriters(BuilderSectionListType * partialCreationSections);
void doExtractPartialCreationFunctions(BuilderSectionListType * partialCreationSections,
BuilderSectionListType * outputSections);
void flatten(BuilderContainer * builderContainer);
BuilderItem * createItem(const CppItem * cppItem);
private:
const Project * project;
const CppSourceFile & sourceFile;
bool overwriteEvenIfNoChange;
ItemListType itemList;
cpgf::GScopedPointer<BuilderSectionList> sectionList;
BuilderFileWriterListType fileWriterList;
std::string creationFunctionNameCode;
GMAKE_NONCOPYABLE(BuilderContext)
};
} // namespace metagen
#endif
| 25.588889 | 106 | 0.783326 | [
"vector"
] |
998516e1ad6da49db934d058b0c2ac5203d5d5f4 | 3,502 | h | C | mikata_arm_toolbox/include/mikata_arm_toolbox/teach.h | ROBOTIS-JAPAN-GIT/DYNAMIXEL-MikataArm-4DOF | 076a0a6b125f2336cabc1c634508fd853801ddbc | [
"Apache-2.0"
] | 9 | 2017-10-18T09:46:18.000Z | 2019-05-31T09:28:29.000Z | mikata_arm_toolbox/include/mikata_arm_toolbox/teach.h | ROBOTIS-JAPAN-GIT/DYNAMIXEL-MikataArm-4DOF | 076a0a6b125f2336cabc1c634508fd853801ddbc | [
"Apache-2.0"
] | 2 | 2018-02-08T10:20:37.000Z | 2019-02-04T01:49:19.000Z | mikata_arm_toolbox/include/mikata_arm_toolbox/teach.h | ROBOTIS-JAPAN-GIT/DYNAMIXEL-MikataArm-4DOF | 076a0a6b125f2336cabc1c634508fd853801ddbc | [
"Apache-2.0"
] | 6 | 2017-10-31T05:08:19.000Z | 2019-11-04T08:42:45.000Z | /*******************************************************************************
* Copyright 2018 ROBOTIS CO., LTD.
*
* 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 __TEACH_H
#define __TEACH_H
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include "parameters.h"
/** Class definition for teaching sample **/
struct node {
std::string name;
std::vector<int> id_vec;
std::vector<double> q;
};
class Teach {
private:
std::vector<node> Nodes;
public:
int getSize() { return Nodes.size(); }
node* getNode(int index) { return &Nodes[index-1]; }
node* getNode(std::string name);
void addNode(std::string _name, std::vector<int> _id_vec, std::vector<double> _q);
bool deleteNode(int index);
void print();
void clearAll() { Nodes.erase(Nodes.begin(), Nodes.end()); };
};
node* Teach::getNode(std::string name) {
for (int i=0; i<Nodes.size(); i++)
if(Nodes[i].name == name)
return &Nodes[i];
return NULL;
}
void Teach::addNode(std::string _name, std::vector<int> _id_vec, std::vector<double> _q) {
node new_node;
new_node.name = _name;
new_node.id_vec = _id_vec;
new_node.q = _q;
Nodes.push_back(new_node);
}
bool Teach::deleteNode(int index) {
if (index > Nodes.size())
return false;
else {
Nodes.erase(Nodes.begin() + index-1);
return true;
}
}
void Teach::print() {
for (unsigned i=0; i<Nodes.size(); ++i)
std::cout << std::setw(2) << i+1 << ". " << Nodes[i].name << std::endl;
}
/** Read and write from file **/
template<typename Func> void read_file(std::string fileName, Func func) {
std::ifstream infile;
char data[100];
infile.open(fileName.c_str(), std::ios::in);
while (infile.getline(data,100)) {
std::istringstream iss(data);
std::string name, buffer;
std::vector<int> id_vec;
std::vector<double> q;
int SPACE_KEY = 32;
int id=0;
getline(iss, name, ',');
boost::trim(name);
if (!name.size() || name[0] == '#') continue;
while (getline(iss, buffer, ',')) {
id++;
try {
q.push_back(std::stod(buffer));
id_vec.push_back(id);
} catch (std::invalid_argument) { continue; }
}
func(name, id_vec, q);
}
infile.close();
}
void write_file (std::string fileName, Teach teaching) {
std::ofstream outfile;
outfile.open(fileName.c_str(), std::ios::out);
for(int i=1; i<=teaching.getSize(); i++) {
node* node = teaching.getNode(i);
outfile << node->name;
for(int k=1; k<=LINK_NUM_GRIPPER; k++) {
outfile << " ,";
std::vector<int>::iterator it = std::find(node->id_vec.begin(), node->id_vec.end(), k);
if (it != node->id_vec.end())
outfile << node->q[std::distance(node->id_vec.begin(), it)];
}
outfile << std::endl;
}
outfile.close();
}
/** Declare global variable **/
Teach teaching_data;
#endif
| 25.940741 | 93 | 0.616505 | [
"vector"
] |
9991349340d78913d7fa4f4b844d821e0ef99411 | 766 | h | C | himan-lib/include/interpolate.h | jrintala/fmi-data | 625f0a44919e6406440349425ee0b3f1a64a923d | [
"MIT"
] | null | null | null | himan-lib/include/interpolate.h | jrintala/fmi-data | 625f0a44919e6406440349425ee0b3f1a64a923d | [
"MIT"
] | null | null | null | himan-lib/include/interpolate.h | jrintala/fmi-data | 625f0a44919e6406440349425ee0b3f1a64a923d | [
"MIT"
] | null | null | null | /**
* @file interpolate.h
*
*/
#ifndef INTERPOLATE_H
#define INTERPOLATE_H
#include "plugin_configuration.h"
namespace himan
{
namespace interpolate
{
bool InterpolateAreaCPU(info& base, info& source, matrix<double>& targetData);
bool InterpolateArea(info& base, std::vector<info_t> infos, bool useCudaForInterpolation = true);
bool Interpolate(info& base, std::vector<info_t>& infos, bool useCudaForInterpolation = true);
bool IsVectorComponent(const std::string& paramName);
HPInterpolationMethod InterpolationMethod(const std::string& paramName, HPInterpolationMethod interpolationMethod);
void RotateVectorComponents(info& UInfo, info& VInfo, bool useCuda);
void RotateVectorComponentsCPU(info& UInfo, info& VInfo);
}
}
#endif /* INTERPOLATE_H */
| 23.9375 | 115 | 0.779373 | [
"vector"
] |
9991894726f7899933290d92ffe612f0e160c5dd | 4,985 | h | C | src/ecs/DataStream.h | amecky/ds_sandbox | f31e69f72a76c40aeb0fa3e3fbe9b651660df770 | [
"MIT"
] | 1 | 2017-09-28T19:41:04.000Z | 2017-09-28T19:41:04.000Z | src/ecs/DataStream.h | amecky/ds_sandbox | f31e69f72a76c40aeb0fa3e3fbe9b651660df770 | [
"MIT"
] | null | null | null | src/ecs/DataStream.h | amecky/ds_sandbox | f31e69f72a76c40aeb0fa3e3fbe9b651660df770 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <typeinfo>
struct BaseStream {
int size;
int capacity;
BaseStream() : size(0), capacity(0) {}
};
template<class T>
struct DataStream : BaseStream {
typedef T type;
type tt;
T* data;
DataStream() : BaseStream() , data(0) {}
~DataStream() {
if (data) {
delete[] data;
}
}
void alloc(int size) {
data = new T[size];
capacity = size;
}
void add(const T& t) {
data[size++] = t;
}
};
struct ECSContext {
};
const static uint32_t INVALID_ID = UINT32_MAX;
struct ComponentData {
uint32_t ID;
const std::type_info* typeInfo;
ComponentData(const std::type_info* type) : ID(INVALID_ID) {
typeInfo = type;
}
};
struct Position : ComponentData {
float x, y, z;
Position() : ComponentData(&typeid(Position)), x(0.0f), y(0.0f), z(0.0f) {}
};
struct Rotation : ComponentData {
float x, y, z;
Rotation() : ComponentData(&typeid(Rotation)), x(0.0f), y(0.0f), z(0.0f) {}
};
struct Velocity : ComponentData {
float x, y, z;
Velocity() : ComponentData(&typeid(Velocity)), x(0.0f), y(0.0f), z(0.0f) {}
};
struct StreamDefinition {
const std::type_info* typeInfo;
size_t size;
};
struct MyMoveComponent {
DataStream<Position> positions;
DataStream<Rotation> rotations;
DataStream<Velocity> velocities;
};
struct MyBaseSystem {
void create(StreamDefinition* definitions, int num) {
}
void create(const std::type_info** typeInfos, int num) {
}
};
struct MyMoveSystem : MyBaseSystem {
struct Data {
Position* positions;
};
void registerGroup() {
const std::type_info* typeInfos[] = { &typeid(Position), &typeid(Velocity) };
create(typeInfos,2);
}
};
struct MoveData {
float x;
float y;
float z;
float velocity;
};
struct TransformData {
int v;
};
class BaseComponent {
public:
const std::type_info* typeInfo;
};
template<class T>
class AbstractComponent : public BaseComponent {
public:
typedef T type;
type dataType;
AbstractComponent() {
typeInfo = &typeid(T);
}
virtual int add(const T& t) = 0;
virtual bool contains(int id) const = 0;
virtual T get(int id) = 0;
};
class MoveComponent : public AbstractComponent<MoveData> {
private:
DataStream<float> x;
DataStream<float> y;
DataStream<float> z;
DataStream<float> velocity;
public:
MoveComponent() {
x.alloc(1024);
y.alloc(1024);
z.alloc(1024);
velocity.alloc(1024);
}
int add(const MoveData& md) {
x.add(md.x);
y.add(md.y);
z.add(md.z);
velocity.add(md.velocity);
return x.size - 1;
}
bool contains(int id) const {
return true;
}
MoveData get(int id) {
return{ x.data[id],y.data[id],z.data[id],velocity.data[id] };
}
};
class TransformComponent : public AbstractComponent<TransformData> {
private:
DataStream<int> v;
public:
TransformComponent() {
v.alloc(1024);
}
int add(const TransformData& md) {
v.add(md.v);
return v.size - 1;
}
bool contains(int id) const {
return true;
}
TransformData get(int id) {
return{ v.data[id] };
}
};
struct Mapping {
int entity;
int component;
int component_id;
};
struct ComponentDataArray {
};
class ECS;
class BaseSystem {
public:
virtual void tick(float dt) = 0;
void addStreams(const std::type_info** typeInfos, int num) {
}
virtual void registerStreams(ECS* ecs) = 0;
template<typename U>
DataStream<U>* getStream(const std::type_info* typeInfo) {
DataStream<U>* stream = new DataStream<U>;
return stream;
}
};
class MoveSystem : public BaseSystem {
public:
struct MoveSystemData {
DataStream<MoveData> moves;
DataStream<TransformData> transforms;
};
MoveSystemData data;
void registerStreams(ECS* ecs) {
//data.moves = *ecs->getStream<MoveData>(&typeid(MoveData));
//data.transforms = *ecs->getStream<TransformData>(&typeid(TransformData));
}
void tick(float dt) {
for (int i = 0; i < data.moves.size; ++i) {
data.moves.data[i].x += data.moves.data[i].velocity * dt;
}
}
};
class ECS {
public:
template<typename U>
void setData(const U& u) {
for (size_t i = 0; i < _components.size(); ++i) {
if (typeid(U) == *_components[i]->typeInfo) {
AbstractComponent<U>* ac = (AbstractComponent<U>*)_components[i];
ac->add(u);
}
}
}
void addComponent(BaseComponent* component) {
_components.push_back(component);
}
void addComponent(BaseComponent* component, StreamDefinition* defs, int num) {
_components.push_back(component);
}
void addSystem(BaseSystem* system, const std::type_info** typeInfos, int num) {
int matches = 0;
for (int j = 0; j < num; ++j) {
for (size_t i = 0; i < _components.size(); ++i) {
if (*typeInfos[j] == *_components[i]->typeInfo) {
++matches;
}
}
}
printf("matches %d\n", matches);
system->registerStreams(this);
}
template<typename U>
DataStream<U>* getStream(const std::type_info* typeInfo) {
DataStream<U>* stream = new DataStream<U>;
return stream;
}
private:
std::vector<BaseComponent*> _components;
std::vector<BaseStream*> _streams;
}; | 16.728188 | 80 | 0.664594 | [
"vector"
] |
9998da5953192b7bef3445d1afafa773078e6e07 | 866 | h | C | CPlusPlus/cplusplus_lang/vectors/BasicVector.h | sreeise/Programming-Reference | c77f6a46abab28b8f0f4a56ebd9843310b19d489 | [
"MIT"
] | 2 | 2019-04-28T00:56:22.000Z | 2019-08-03T17:41:19.000Z | CPlusPlus/cplusplus_lang/vectors/BasicVector.h | sreeise/ProgrammingSnippets | c77f6a46abab28b8f0f4a56ebd9843310b19d489 | [
"MIT"
] | 1 | 2018-07-10T22:33:12.000Z | 2018-07-16T22:30:35.000Z | CPlusPlus/cplusplus_lang/vectors/BasicVector.h | sreeise/ProgrammingSnippets | c77f6a46abab28b8f0f4a56ebd9843310b19d489 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <vector>
#include <stdexcept>
using namespace std;
#ifndef C_REFERENCE_BASICVECTOR_H
#define C_REFERENCE_BASICVECTOR_H
class BasicVector {
public:
vector<int> &basicVector;
BasicVector(vector<int> &basicVector) : basicVector{basicVector} {}
void setBasicVector(vector<int> &output) {
BasicVector::basicVector = output;
}
vector<int> &getBasicVector() {
return basicVector;
}
void outputVector() {
for (int item : basicVector) {
cout << item << " ";
}
}
void inputVector(vector<int> &items) {
for (int &item : items) {
cin >> item;
}
}
void copyBasicVector(vector<int> ©) {
copy = basicVector;
}
void printVectorSize() {
cout << "\nBasic vector size: " << basicVector.size() << "\n" << endl;
}
};
#endif //C_REFERENCE_BASICVECTOR_H
| 18.425532 | 74 | 0.652425 | [
"vector"
] |
999f9a9ada39c247a462ac816c5a290b1514c3cf | 3,085 | c | C | sdk-6.5.20/libs/sdklt/bcmltx/bcml2/bcmltx_l2_opaque_tag_id.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/bcmltx/bcml2/bcmltx_l2_opaque_tag_id.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/bcmltx/bcml2/bcmltx_l2_opaque_tag_id.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | /*! \file bcmltx_l2_opaque_tag_id.c
*
* L2_OPAQUE_TAG Logic table fields Transform Handlers.
* This file contains field transform information for
* opaque tag id in L2_OPAQUE_TAG Logic table.
*/
/*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#include <shr/shr_debug.h>
#include <bsl/bsl.h>
#include <bcmltd/chip/bcmltd_id.h>
#include <bcmltx/bcml2/bcmltx_l2_opaque_tag_id.h>
/******************************************************************************
* Local definitions
*/
#define BSL_LOG_MODULE BSL_LS_BCMLTX_L2
/******************************************************************************
* Private functions
*/
/******************************************************************************
* Public functions
*/
/*!
* \brief opaque tag id transform
*
* \param [in] unit Unit Number.
* \param [in] in L2_OPAQUE_TAG_ID field.
* \param [out] out __TABLE_SEL fields.
* \param [in] arg Transform arguments.
*
* Transform direction is logical to physical.
*
* \retval SHR_E_NONE No errors.
* \retval !SHR_E_NONE Failure.
*/
int
bcmltx_l2_opaque_tag_id_transform(int unit,
const bcmltd_fields_t *in,
bcmltd_fields_t *out,
const bcmltd_transform_arg_t *arg)
{
uint32_t count = 0;
SHR_FUNC_ENTER(unit);
LOG_VERBOSE(BSL_LOG_MODULE,
(BSL_META_U(unit,
"\t bcml2_opaque_tag_id_transform\n")));
if (in->count == 0) {
SHR_EXIT();
}
if (in->count != 1) {
SHR_ERR_EXIT(SHR_E_PARAM);
}
out->field[count]->data = in->field[0]->data;
out->field[count]->id = arg->rfield[count];
out->count = ++count;
exit:
SHR_FUNC_EXIT();
}
/*!
* \brief opaque tag id reverse transform
*
* \param [in] unit Unit Number.
* \param [in] in __INDEX/__TABLE_SEL fields.
* \param [out] out L2_OPAQUE_TAG_ID field.
* \param [in] arg Transform arguments.
*
* Transform direction is physical to logical.
*
* \retval SHR_E_NONE No errors.
* \retval !SHR_E_NONE Failure.
*/
int
bcmltx_l2_opaque_tag_id_rev_transform(int unit,
const bcmltd_fields_t *in,
bcmltd_fields_t *out,
const bcmltd_transform_arg_t *arg)
{
uint32_t count = 0;
SHR_FUNC_ENTER(unit);
LOG_VERBOSE(BSL_LOG_MODULE,
(BSL_META_U(unit,
"\t bcml2_opaque_tag_id_rev_transform\n")));
if (in->count == 0) {
SHR_EXIT();
}
if (in->count != 1) {
SHR_ERR_EXIT(SHR_E_PARAM);
}
out->field[count]->data = in->field[count]->data;
out->field[count]->id = arg->rfield[count];
out->count = ++count;
exit:
SHR_FUNC_EXIT();
}
| 26.367521 | 134 | 0.538412 | [
"transform"
] |
99a1fcaa91d0e5a013524770e6aa28f2ea9ddf8f | 1,978 | h | C | YZLibrary/UIColor+YZLibrary.h | yichizhang/YZLibrary | a0f5033979827f94ccea621198302b0bbd7b3cff | [
"MIT"
] | 2 | 2015-11-05T17:20:27.000Z | 2016-09-23T07:04:37.000Z | YZLibrary/UIColor+YZLibrary.h | yichizhang/YZLibrary | a0f5033979827f94ccea621198302b0bbd7b3cff | [
"MIT"
] | null | null | null | YZLibrary/UIColor+YZLibrary.h | yichizhang/YZLibrary | a0f5033979827f94ccea621198302b0bbd7b3cff | [
"MIT"
] | null | null | null | //
// UIColor+YZLibrary.h
// YZLibrary
//
// Copyright (c) 2016 Yichi Zhang
// https://github.com/yichizhang
// zhang-yi-chi@hotmail.com
//
// 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.
//
#import <UIKit/UIKit.h>
@interface UIColor (YZLibrary)
/**
Returns iOS 7's system blue color
*/
+ (UIColor *)yz_iOS7BlueColor;
/**
Returns the tint color of the application's key window
*/
+ (UIColor *)yz_appKeyWindowTintColor;
/**
Returns a random bright color
*/
+ (UIColor *)yz_randomBrightColor;
/**
Creates and returns a color object that's the complement of the receiver.
*/
- (instancetype)yz_complementaryColor;
/**
Creates and returns a color object that has the component values as the receiver, but has the specified hue component.
@param hue The hue component of the new color object in the HSB color space, specified as a value from 0.0 to 1.0.
*/
- (instancetype)yz_colorWithHueComponent:(CGFloat)hue;
@end
| 32.966667 | 119 | 0.741153 | [
"object"
] |
99a697c368ffeed46a805d8d76cfb8aa64248c74 | 2,670 | h | C | src/engine/BlurEffect.h | foxostro/arbarlith2 | 820ffc8c3efcb636eb2c639487815fb9aabdc82e | [
"BSD-3-Clause"
] | 1 | 2019-04-09T18:42:00.000Z | 2019-04-09T18:42:00.000Z | src/engine/BlurEffect.h | foxostro/arbarlith2 | 820ffc8c3efcb636eb2c639487815fb9aabdc82e | [
"BSD-3-Clause"
] | null | null | null | src/engine/BlurEffect.h | foxostro/arbarlith2 | 820ffc8c3efcb636eb2c639487815fb9aabdc82e | [
"BSD-3-Clause"
] | null | null | null | /*
Original Author: Andrew Fox
E-Mail: mailto:foxostro@gmail.com
Copyright (c) 2006,2007,2009 Game Creation Society
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Game Creation Society 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 Game Creation Society ``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 Game Creation Society 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 _BLUR_EFFECT_H_
#define _BLUR_EFFECT_H_
#include "Blur.h"
#include "COLOR.h"
namespace Engine {
/** Causes the screen to become blurred and then regain focus over time */
class BlurEffect
{
public:
/** Constructs the Blur effect */
BlurEffect(void);
/**
Starts the screen blur effect
@param timePeriod The time that the screen is blurred for
@param color The color to shift the blur towards
*/
void start(float timePeriod, COLOR color);
/** Draw the blur effect */
void draw(void);
/**
Updates the timer on the blur effect
@param deltaTime The time since the last tick (milliseconds)
*/
void update(float deltaTime);
/** Release assets */
void release(void);
/** Reaquire assets */
void reaquire(void);
/**
Sets the current zone for the Blur to re-render it as necessary
@param zone the current zone
*/
void setZone(World * zone)
{
blur.setZone(zone);
}
private:
/** Screen capture */
Blur blur;
/** The length of the action */
float timeLimit;
/** The age of the blur effect */
float myAge;
};
} // namespace Engine
#endif
| 29.340659 | 77 | 0.752809 | [
"render"
] |
99a768afd8059969b081a819c49da495741278c9 | 24,373 | c | C | third_party/mesa/MesaLib/src/gallium/drivers/llvmpipe/lp_bld_depth.c | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 212 | 2015-01-31T11:55:58.000Z | 2022-02-22T06:35:11.000Z | third_party/mesa/MesaLib/src/gallium/drivers/llvmpipe/lp_bld_depth.c | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 5 | 2015-03-27T14:29:23.000Z | 2019-09-25T13:23:12.000Z | third_party/mesa/MesaLib/src/gallium/drivers/llvmpipe/lp_bld_depth.c | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 221 | 2015-01-07T06:21:24.000Z | 2022-02-11T02:51:12.000Z | /**************************************************************************
*
* Copyright 2009 VMware, Inc.
* All Rights Reserved.
*
* 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, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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
* Depth/stencil testing to LLVM IR translation.
*
* To be done accurately/efficiently the depth/stencil test must be done with
* the same type/format of the depth/stencil buffer, which implies massaging
* the incoming depths to fit into place. Using a more straightforward
* type/format for depth/stencil values internally and only convert when
* flushing would avoid this, but it would most likely result in depth fighting
* artifacts.
*
* We are free to use a different pixel layout though. Since our basic
* processing unit is a quad (2x2 pixel block) we store the depth/stencil
* values tiled, a quad at time. That is, a depth buffer containing
*
* Z11 Z12 Z13 Z14 ...
* Z21 Z22 Z23 Z24 ...
* Z31 Z32 Z33 Z34 ...
* Z41 Z42 Z43 Z44 ...
* ... ... ... ... ...
*
* will actually be stored in memory as
*
* Z11 Z12 Z21 Z22 Z13 Z14 Z23 Z24 ...
* Z31 Z32 Z41 Z42 Z33 Z34 Z43 Z44 ...
* ... ... ... ... ... ... ... ... ...
*
*
* Stencil test:
* Two-sided stencil test is supported but probably not as efficient as
* it could be. Currently, we use if/then/else constructs to do the
* operations for front vs. back-facing polygons. We could probably do
* both the front and back arithmetic then use a Select() instruction to
* choose the result depending on polyon orientation. We'd have to
* measure performance both ways and see which is better.
*
* @author Jose Fonseca <jfonseca@vmware.com>
*/
#include "pipe/p_state.h"
#include "util/u_format.h"
#include "gallivm/lp_bld_type.h"
#include "gallivm/lp_bld_arit.h"
#include "gallivm/lp_bld_const.h"
#include "gallivm/lp_bld_logic.h"
#include "gallivm/lp_bld_flow.h"
#include "gallivm/lp_bld_intr.h"
#include "gallivm/lp_bld_debug.h"
#include "gallivm/lp_bld_swizzle.h"
#include "lp_bld_depth.h"
/** Used to select fields from pipe_stencil_state */
enum stencil_op {
S_FAIL_OP,
Z_FAIL_OP,
Z_PASS_OP
};
/**
* Do the stencil test comparison (compare FB stencil values against ref value).
* This will be used twice when generating two-sided stencil code.
* \param stencil the front/back stencil state
* \param stencilRef the stencil reference value, replicated as a vector
* \param stencilVals vector of stencil values from framebuffer
* \return vector mask of pass/fail values (~0 or 0)
*/
static LLVMValueRef
lp_build_stencil_test_single(struct lp_build_context *bld,
const struct pipe_stencil_state *stencil,
LLVMValueRef stencilRef,
LLVMValueRef stencilVals)
{
const unsigned stencilMax = 255; /* XXX fix */
struct lp_type type = bld->type;
LLVMValueRef res;
assert(type.sign);
assert(stencil->enabled);
if (stencil->valuemask != stencilMax) {
/* compute stencilRef = stencilRef & valuemask */
LLVMValueRef valuemask = lp_build_const_int_vec(type, stencil->valuemask);
stencilRef = LLVMBuildAnd(bld->builder, stencilRef, valuemask, "");
/* compute stencilVals = stencilVals & valuemask */
stencilVals = LLVMBuildAnd(bld->builder, stencilVals, valuemask, "");
}
res = lp_build_cmp(bld, stencil->func, stencilRef, stencilVals);
return res;
}
/**
* Do the one or two-sided stencil test comparison.
* \sa lp_build_stencil_test_single
* \param face an integer indicating front (+) or back (-) facing polygon.
* If NULL, assume front-facing.
*/
static LLVMValueRef
lp_build_stencil_test(struct lp_build_context *bld,
const struct pipe_stencil_state stencil[2],
LLVMValueRef stencilRefs[2],
LLVMValueRef stencilVals,
LLVMValueRef face)
{
LLVMValueRef res;
assert(stencil[0].enabled);
if (stencil[1].enabled && face) {
/* do two-sided test */
struct lp_build_flow_context *flow_ctx;
struct lp_build_if_state if_ctx;
LLVMValueRef front_facing;
LLVMValueRef zero = LLVMConstReal(LLVMFloatType(), 0.0);
LLVMValueRef result = bld->undef;
flow_ctx = lp_build_flow_create(bld->builder);
lp_build_flow_scope_begin(flow_ctx);
lp_build_flow_scope_declare(flow_ctx, &result);
/* front_facing = face > 0.0 */
front_facing = LLVMBuildFCmp(bld->builder, LLVMRealUGT, face, zero, "");
lp_build_if(&if_ctx, flow_ctx, bld->builder, front_facing);
{
result = lp_build_stencil_test_single(bld, &stencil[0],
stencilRefs[0], stencilVals);
}
lp_build_else(&if_ctx);
{
result = lp_build_stencil_test_single(bld, &stencil[1],
stencilRefs[1], stencilVals);
}
lp_build_endif(&if_ctx);
lp_build_flow_scope_end(flow_ctx);
lp_build_flow_destroy(flow_ctx);
res = result;
}
else {
/* do single-side test */
res = lp_build_stencil_test_single(bld, &stencil[0],
stencilRefs[0], stencilVals);
}
return res;
}
/**
* Apply the stencil operator (add/sub/keep/etc) to the given vector
* of stencil values.
* \return new stencil values vector
*/
static LLVMValueRef
lp_build_stencil_op_single(struct lp_build_context *bld,
const struct pipe_stencil_state *stencil,
enum stencil_op op,
LLVMValueRef stencilRef,
LLVMValueRef stencilVals,
LLVMValueRef mask)
{
const unsigned stencilMax = 255; /* XXX fix */
struct lp_type type = bld->type;
LLVMValueRef res;
LLVMValueRef max = lp_build_const_int_vec(type, stencilMax);
unsigned stencil_op;
assert(type.sign);
switch (op) {
case S_FAIL_OP:
stencil_op = stencil->fail_op;
break;
case Z_FAIL_OP:
stencil_op = stencil->zfail_op;
break;
case Z_PASS_OP:
stencil_op = stencil->zpass_op;
break;
default:
assert(0 && "Invalid stencil_op mode");
stencil_op = PIPE_STENCIL_OP_KEEP;
}
switch (stencil_op) {
case PIPE_STENCIL_OP_KEEP:
res = stencilVals;
/* we can return early for this case */
return res;
case PIPE_STENCIL_OP_ZERO:
res = bld->zero;
break;
case PIPE_STENCIL_OP_REPLACE:
res = stencilRef;
break;
case PIPE_STENCIL_OP_INCR:
res = lp_build_add(bld, stencilVals, bld->one);
res = lp_build_min(bld, res, max);
break;
case PIPE_STENCIL_OP_DECR:
res = lp_build_sub(bld, stencilVals, bld->one);
res = lp_build_max(bld, res, bld->zero);
break;
case PIPE_STENCIL_OP_INCR_WRAP:
res = lp_build_add(bld, stencilVals, bld->one);
res = LLVMBuildAnd(bld->builder, res, max, "");
break;
case PIPE_STENCIL_OP_DECR_WRAP:
res = lp_build_sub(bld, stencilVals, bld->one);
res = LLVMBuildAnd(bld->builder, res, max, "");
break;
case PIPE_STENCIL_OP_INVERT:
res = LLVMBuildNot(bld->builder, stencilVals, "");
res = LLVMBuildAnd(bld->builder, res, max, "");
break;
default:
assert(0 && "bad stencil op mode");
res = NULL;
}
if (stencil->writemask != stencilMax) {
/* mask &= stencil->writemask */
LLVMValueRef writemask = lp_build_const_int_vec(type, stencil->writemask);
mask = LLVMBuildAnd(bld->builder, mask, writemask, "");
/* res = (res & mask) | (stencilVals & ~mask) */
res = lp_build_select_bitwise(bld, writemask, res, stencilVals);
}
else {
/* res = mask ? res : stencilVals */
res = lp_build_select(bld, mask, res, stencilVals);
}
return res;
}
/**
* Do the one or two-sided stencil test op/update.
*/
static LLVMValueRef
lp_build_stencil_op(struct lp_build_context *bld,
const struct pipe_stencil_state stencil[2],
enum stencil_op op,
LLVMValueRef stencilRefs[2],
LLVMValueRef stencilVals,
LLVMValueRef mask,
LLVMValueRef face)
{
assert(stencil[0].enabled);
if (stencil[1].enabled && face) {
/* do two-sided op */
struct lp_build_flow_context *flow_ctx;
struct lp_build_if_state if_ctx;
LLVMValueRef front_facing;
LLVMValueRef zero = LLVMConstReal(LLVMFloatType(), 0.0);
LLVMValueRef result = bld->undef;
flow_ctx = lp_build_flow_create(bld->builder);
lp_build_flow_scope_begin(flow_ctx);
lp_build_flow_scope_declare(flow_ctx, &result);
/* front_facing = face > 0.0 */
front_facing = LLVMBuildFCmp(bld->builder, LLVMRealUGT, face, zero, "");
lp_build_if(&if_ctx, flow_ctx, bld->builder, front_facing);
{
result = lp_build_stencil_op_single(bld, &stencil[0], op,
stencilRefs[0], stencilVals, mask);
}
lp_build_else(&if_ctx);
{
result = lp_build_stencil_op_single(bld, &stencil[1], op,
stencilRefs[1], stencilVals, mask);
}
lp_build_endif(&if_ctx);
lp_build_flow_scope_end(flow_ctx);
lp_build_flow_destroy(flow_ctx);
return result;
}
else {
/* do single-sided op */
return lp_build_stencil_op_single(bld, &stencil[0], op,
stencilRefs[0], stencilVals, mask);
}
}
/**
* Return a type appropriate for depth/stencil testing.
*/
struct lp_type
lp_depth_type(const struct util_format_description *format_desc,
unsigned length)
{
struct lp_type type;
unsigned swizzle;
assert(format_desc->colorspace == UTIL_FORMAT_COLORSPACE_ZS);
assert(format_desc->block.width == 1);
assert(format_desc->block.height == 1);
swizzle = format_desc->swizzle[0];
assert(swizzle < 4);
memset(&type, 0, sizeof type);
type.width = format_desc->block.bits;
if(format_desc->channel[swizzle].type == UTIL_FORMAT_TYPE_FLOAT) {
type.floating = TRUE;
assert(swizzle == 0);
assert(format_desc->channel[swizzle].size == format_desc->block.bits);
}
else if(format_desc->channel[swizzle].type == UTIL_FORMAT_TYPE_UNSIGNED) {
assert(format_desc->block.bits <= 32);
if(format_desc->channel[swizzle].normalized)
type.norm = TRUE;
}
else
assert(0);
assert(type.width <= length);
type.length = length / type.width;
return type;
}
/**
* Compute bitmask and bit shift to apply to the incoming fragment Z values
* and the Z buffer values needed before doing the Z comparison.
*
* Note that we leave the Z bits in the position that we find them
* in the Z buffer (typically 0xffffff00 or 0x00ffffff). That lets us
* get by with fewer bit twiddling steps.
*/
static boolean
get_z_shift_and_mask(const struct util_format_description *format_desc,
unsigned *shift, unsigned *mask)
{
const unsigned total_bits = format_desc->block.bits;
unsigned z_swizzle;
unsigned chan;
unsigned padding_left, padding_right;
assert(format_desc->colorspace == UTIL_FORMAT_COLORSPACE_ZS);
assert(format_desc->block.width == 1);
assert(format_desc->block.height == 1);
z_swizzle = format_desc->swizzle[0];
if (z_swizzle == UTIL_FORMAT_SWIZZLE_NONE)
return FALSE;
padding_right = 0;
for (chan = 0; chan < z_swizzle; ++chan)
padding_right += format_desc->channel[chan].size;
padding_left =
total_bits - (padding_right + format_desc->channel[z_swizzle].size);
if (padding_left || padding_right) {
unsigned long long mask_left = (1ULL << (total_bits - padding_left)) - 1;
unsigned long long mask_right = (1ULL << (padding_right)) - 1;
*mask = mask_left ^ mask_right;
}
else {
*mask = 0xffffffff;
}
*shift = padding_left;
return TRUE;
}
/**
* Compute bitmask and bit shift to apply to the framebuffer pixel values
* to put the stencil bits in the least significant position.
* (i.e. 0x000000ff)
*/
static boolean
get_s_shift_and_mask(const struct util_format_description *format_desc,
unsigned *shift, unsigned *mask)
{
unsigned s_swizzle;
unsigned chan, sz;
s_swizzle = format_desc->swizzle[1];
if (s_swizzle == UTIL_FORMAT_SWIZZLE_NONE)
return FALSE;
*shift = 0;
for (chan = 0; chan < s_swizzle; chan++)
*shift += format_desc->channel[chan].size;
sz = format_desc->channel[s_swizzle].size;
*mask = (1U << sz) - 1U;
return TRUE;
}
/**
* Perform the occlusion test and increase the counter.
* Test the depth mask. Add the number of channel which has none zero mask
* into the occlusion counter. e.g. maskvalue is {-1, -1, -1, -1}.
* The counter will add 4.
*
* \param type holds element type of the mask vector.
* \param maskvalue is the depth test mask.
* \param counter is a pointer of the uint32 counter.
*/
static void
lp_build_occlusion_count(LLVMBuilderRef builder,
struct lp_type type,
LLVMValueRef maskvalue,
LLVMValueRef counter)
{
LLVMValueRef countmask = lp_build_const_int_vec(type, 1);
LLVMValueRef countv = LLVMBuildAnd(builder, maskvalue, countmask, "countv");
LLVMTypeRef i8v16 = LLVMVectorType(LLVMInt8Type(), 16);
LLVMValueRef counti = LLVMBuildBitCast(builder, countv, i8v16, "counti");
LLVMValueRef maskarray[4] = {
LLVMConstInt(LLVMInt32Type(), 0, 0),
LLVMConstInt(LLVMInt32Type(), 4, 0),
LLVMConstInt(LLVMInt32Type(), 8, 0),
LLVMConstInt(LLVMInt32Type(), 12, 0),
};
LLVMValueRef shufflemask = LLVMConstVector(maskarray, 4);
LLVMValueRef shufflev = LLVMBuildShuffleVector(builder, counti, LLVMGetUndef(i8v16), shufflemask, "shufflev");
LLVMValueRef shuffle = LLVMBuildBitCast(builder, shufflev, LLVMInt32Type(), "shuffle");
LLVMValueRef count = lp_build_intrinsic_unary(builder, "llvm.ctpop.i32", LLVMInt32Type(), shuffle);
LLVMValueRef orig = LLVMBuildLoad(builder, counter, "orig");
LLVMValueRef incr = LLVMBuildAdd(builder, orig, count, "incr");
LLVMBuildStore(builder, incr, counter);
}
/**
* Generate code for performing depth and/or stencil tests.
* We operate on a vector of values (typically a 2x2 quad).
*
* \param depth the depth test state
* \param stencil the front/back stencil state
* \param type the data type of the fragment depth/stencil values
* \param format_desc description of the depth/stencil surface
* \param mask the alive/dead pixel mask for the quad (vector)
* \param stencil_refs the front/back stencil ref values (scalar)
* \param z_src the incoming depth/stencil values (a 2x2 quad)
* \param zs_dst_ptr pointer to depth/stencil values in framebuffer
* \param facing contains float value indicating front/back facing polygon
*/
void
lp_build_depth_stencil_test(LLVMBuilderRef builder,
const struct pipe_depth_state *depth,
const struct pipe_stencil_state stencil[2],
struct lp_type type,
const struct util_format_description *format_desc,
struct lp_build_mask_context *mask,
LLVMValueRef stencil_refs[2],
LLVMValueRef z_src,
LLVMValueRef zs_dst_ptr,
LLVMValueRef face,
LLVMValueRef counter)
{
struct lp_build_context bld;
struct lp_build_context sbld;
struct lp_type s_type;
LLVMValueRef zs_dst, z_dst = NULL;
LLVMValueRef stencil_vals = NULL;
LLVMValueRef z_bitmask = NULL, stencil_shift = NULL;
LLVMValueRef z_pass = NULL, s_pass_mask = NULL;
LLVMValueRef orig_mask = mask->value;
/* Sanity checking */
{
const unsigned z_swizzle = format_desc->swizzle[0];
const unsigned s_swizzle = format_desc->swizzle[1];
assert(z_swizzle != UTIL_FORMAT_SWIZZLE_NONE ||
s_swizzle != UTIL_FORMAT_SWIZZLE_NONE);
assert(depth->enabled || stencil[0].enabled);
assert(format_desc->colorspace == UTIL_FORMAT_COLORSPACE_ZS);
assert(format_desc->block.width == 1);
assert(format_desc->block.height == 1);
if (stencil[0].enabled) {
assert(format_desc->format == PIPE_FORMAT_Z24_UNORM_S8_USCALED ||
format_desc->format == PIPE_FORMAT_S8_USCALED_Z24_UNORM);
}
assert(z_swizzle < 4);
assert(format_desc->block.bits == type.width);
if (type.floating) {
assert(z_swizzle == 0);
assert(format_desc->channel[z_swizzle].type ==
UTIL_FORMAT_TYPE_FLOAT);
assert(format_desc->channel[z_swizzle].size ==
format_desc->block.bits);
}
else {
assert(format_desc->channel[z_swizzle].type ==
UTIL_FORMAT_TYPE_UNSIGNED);
assert(format_desc->channel[z_swizzle].normalized);
assert(!type.fixed);
assert(!type.sign);
assert(type.norm);
}
}
/* Setup build context for Z vals */
lp_build_context_init(&bld, builder, type);
/* Setup build context for stencil vals */
s_type = lp_type_int_vec(type.width);
lp_build_context_init(&sbld, builder, s_type);
/* Load current z/stencil value from z/stencil buffer */
zs_dst = LLVMBuildLoad(builder, zs_dst_ptr, "");
lp_build_name(zs_dst, "zsbufval");
/* Compute and apply the Z/stencil bitmasks and shifts.
*/
{
unsigned z_shift, z_mask;
unsigned s_shift, s_mask;
if (get_z_shift_and_mask(format_desc, &z_shift, &z_mask)) {
if (z_shift) {
LLVMValueRef shift = lp_build_const_int_vec(type, z_shift);
z_src = LLVMBuildLShr(builder, z_src, shift, "");
}
if (z_mask != 0xffffffff) {
LLVMValueRef mask = lp_build_const_int_vec(type, z_mask);
z_src = LLVMBuildAnd(builder, z_src, mask, "");
z_dst = LLVMBuildAnd(builder, zs_dst, mask, "");
z_bitmask = mask; /* used below */
}
else {
z_dst = zs_dst;
}
lp_build_name(z_dst, "zsbuf.z");
}
if (get_s_shift_and_mask(format_desc, &s_shift, &s_mask)) {
if (s_shift) {
LLVMValueRef shift = lp_build_const_int_vec(type, s_shift);
stencil_vals = LLVMBuildLShr(builder, zs_dst, shift, "");
stencil_shift = shift; /* used below */
}
else {
stencil_vals = zs_dst;
}
if (s_mask != 0xffffffff) {
LLVMValueRef mask = lp_build_const_int_vec(type, s_mask);
stencil_vals = LLVMBuildAnd(builder, stencil_vals, mask, "");
}
lp_build_name(stencil_vals, "stencil");
}
}
if (stencil[0].enabled) {
/* convert scalar stencil refs into vectors */
stencil_refs[0] = lp_build_broadcast_scalar(&bld, stencil_refs[0]);
stencil_refs[1] = lp_build_broadcast_scalar(&bld, stencil_refs[1]);
s_pass_mask = lp_build_stencil_test(&sbld, stencil,
stencil_refs, stencil_vals, face);
/* apply stencil-fail operator */
{
LLVMValueRef s_fail_mask = lp_build_andc(&bld, orig_mask, s_pass_mask);
stencil_vals = lp_build_stencil_op(&sbld, stencil, S_FAIL_OP,
stencil_refs, stencil_vals,
s_fail_mask, face);
}
}
if (depth->enabled) {
/* compare src Z to dst Z, returning 'pass' mask */
z_pass = lp_build_cmp(&bld, depth->func, z_src, z_dst);
if (!stencil[0].enabled) {
/* We can potentially skip all remaining operations here, but only
* if stencil is disabled because we still need to update the stencil
* buffer values. Don't need to update Z buffer values.
*/
lp_build_mask_update(mask, z_pass);
}
if (depth->writemask) {
LLVMValueRef zselectmask = mask->value;
/* mask off bits that failed Z test */
zselectmask = LLVMBuildAnd(builder, zselectmask, z_pass, "");
/* mask off bits that failed stencil test */
if (s_pass_mask) {
zselectmask = LLVMBuildAnd(builder, zselectmask, s_pass_mask, "");
}
/* if combined Z/stencil format, mask off the stencil bits */
if (z_bitmask) {
zselectmask = LLVMBuildAnd(builder, zselectmask, z_bitmask, "");
}
/* Mix the old and new Z buffer values.
* z_dst[i] = (zselectmask[i] & z_src[i]) | (~zselectmask[i] & z_dst[i])
*/
z_dst = lp_build_select_bitwise(&bld, zselectmask, z_src, z_dst);
}
if (stencil[0].enabled) {
/* update stencil buffer values according to z pass/fail result */
LLVMValueRef z_fail_mask, z_pass_mask;
/* apply Z-fail operator */
z_fail_mask = lp_build_andc(&bld, orig_mask, z_pass);
stencil_vals = lp_build_stencil_op(&sbld, stencil, Z_FAIL_OP,
stencil_refs, stencil_vals,
z_fail_mask, face);
/* apply Z-pass operator */
z_pass_mask = LLVMBuildAnd(bld.builder, orig_mask, z_pass, "");
stencil_vals = lp_build_stencil_op(&sbld, stencil, Z_PASS_OP,
stencil_refs, stencil_vals,
z_pass_mask, face);
}
}
else {
/* No depth test: apply Z-pass operator to stencil buffer values which
* passed the stencil test.
*/
s_pass_mask = LLVMBuildAnd(bld.builder, orig_mask, s_pass_mask, "");
stencil_vals = lp_build_stencil_op(&sbld, stencil, Z_PASS_OP,
stencil_refs, stencil_vals,
s_pass_mask, face);
}
/* The Z bits are already in the right place but we may need to shift the
* stencil bits before ORing Z with Stencil to make the final pixel value.
*/
if (stencil_vals && stencil_shift)
stencil_vals = LLVMBuildShl(bld.builder, stencil_vals,
stencil_shift, "");
/* Finally, merge/store the z/stencil values */
if ((depth->enabled && depth->writemask) ||
(stencil[0].enabled && stencil[0].writemask)) {
if (z_dst && stencil_vals)
zs_dst = LLVMBuildOr(bld.builder, z_dst, stencil_vals, "");
else if (z_dst)
zs_dst = z_dst;
else
zs_dst = stencil_vals;
LLVMBuildStore(builder, zs_dst, zs_dst_ptr);
}
if (s_pass_mask)
lp_build_mask_update(mask, s_pass_mask);
if (depth->enabled && stencil[0].enabled)
lp_build_mask_update(mask, z_pass);
if (counter)
lp_build_occlusion_count(builder, type, mask->value, counter);
}
| 33.525447 | 114 | 0.630041 | [
"vector"
] |
99ab42ed5782e0bb799ad3de9c28a15797d5a634 | 16,494 | c | C | QP/v5.4.2/qpn/ports/posix-qv/qfn_posix.c | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpn/ports/posix-qv/qfn_posix.c | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpn/ports/posix-qv/qfn_posix.c | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | /*****************************************************************************
* Product: QF-nano emulation for Win32 with cooperative QV kernel
* Last updated for version 5.4.2
* Last updated on 2015-06-12
*
* Q u a n t u m L e a P s
* ---------------------------
* innovating embedded systems
*
* Copyright (C) Quantum Leaps, www.state-machine.com.
*
* This program is open source software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alternatively, this program may be distributed and modified under the
* terms of Quantum Leaps commercial licenses, which expressly supersede
* the GNU General Public License and are specifically designed for
* licensees interested in retaining the proprietary status of their code.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact information:
* Web: www.state-machine.com
* Email: info@state-machine.com
*****************************************************************************/
#include "qpn.h" /* QP-nano */
#include <pthread.h> /* POSIX-thread API */
#include <sys/select.h> /* for the select() API */
#ifdef QK_PREEMPTIVE
#error "This QP-nano port does not support QK_PREEMPTIVE configuration"
#endif
Q_DEFINE_THIS_MODULE("qfn_posix")
/* Global objects ==========================================================*/
uint_fast8_t volatile QF_readySet_; /* ready-set of QF-nano */
#ifdef QF_TIMEEVT_USAGE
uint_fast8_t volatile QF_timerSetX_[QF_MAX_TICK_RATE]; /* timer-set */
#endif
#ifndef QF_LOG2
uint8_t const Q_ROM QF_log2Lkup[16] = {
(uint8_t)0, (uint8_t)1, (uint8_t)2, (uint8_t)2,
(uint8_t)3, (uint8_t)3, (uint8_t)3, (uint8_t)3,
(uint8_t)4, (uint8_t)4, (uint8_t)4, (uint8_t)4,
(uint8_t)4, (uint8_t)4, (uint8_t)4, (uint8_t)4
};
#endif /* QF_LOG2 */
uint8_t const Q_ROM QF_invPow2Lkup[9] = {
(uint8_t)0xFF,
(uint8_t)0xFE, (uint8_t)0xFD, (uint8_t)0xFB, (uint8_t)0xF7,
(uint8_t)0xEF, (uint8_t)0xDF, (uint8_t)0xBF, (uint8_t)0x7F
};
/* Local objects ===========================================================*/
static uint8_t const Q_ROM l_pow2Lkup[] = {
(uint8_t)0x00,
(uint8_t)0x01, (uint8_t)0x02, (uint8_t)0x04, (uint8_t)0x08,
(uint8_t)0x10, (uint8_t)0x20, (uint8_t)0x40, (uint8_t)0x80
};
/* mutex for QF critical section */
static pthread_mutex_t l_pThreadMutex_ = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t l_condVar; /* cond var to signal when AOs are ready */
static long int l_tickUsec = 10000UL; /* clock tick in usec (for tv_usec) */
static bool l_isRunning; /* flag indicating when QF is running */
/* "fudged" event queues for AOs, see NOTE2 */
#define QF_FUDGED_QUEUE_LEN 0xFFU
static QEvt l_fudgedQueue[QF_MAX_ACTIVE][QF_FUDGED_QUEUE_LEN];
#define QF_FUDGED_QUEUE_AT_(ao_, i_) (l_fudgedQueue[(ao_)->prio - 1U][(i_)])
static void *tickerThread(void *par); /* the expected P-Thread signature */
/****************************************************************************/
/****************************************************************************/
#ifndef Q_NMSM
void QMActive_ctor(QMActive * const me, QStateHandler initial) {
static QMActiveVtbl const vtbl = { /* QMActive virtual table */
{ &QMsm_init_,
&QMsm_dispatch_ },
&QActive_postX_,
&QActive_postXISR_
};
QMsm_ctor(&me->super, initial);
me->super.vptr = &vtbl.super;/* hook the vptr to QMActive virtual table */
}
#endif /* Q_NMSM */
/****************************************************************************/
#ifndef Q_NHSM
void QActive_ctor(QActive * const me, QStateHandler initial) {
static QActiveVtbl const vtbl = { /* QActive virtual table */
{ &QHsm_init_,
&QHsm_dispatch_ },
&QActive_postX_,
&QActive_postXISR_
};
QHsm_ctor(&me->super, initial);
me->super.vptr = &vtbl.super; /* hook the vptr to QActive virtual table */
}
#endif /* Q_NHSM */
/****************************************************************************/
#if (Q_PARAM_SIZE != 0)
bool QActive_postX_(QMActive * const me, uint_fast8_t margin,
enum_t const sig, QParam const par)
#else
bool QActive_postX_(QMActive * const me, uint_fast8_t margin,
enum_t const sig)
#endif
{
QF_INT_DISABLE();
/* margin available? */
if (((uint_fast8_t)QF_FUDGED_QUEUE_LEN - me->nUsed) > margin) {
/* insert event into the ring buffer (FIFO) */
QF_FUDGED_QUEUE_AT_(me, me->head).sig = (QSignal)sig;
#if (Q_PARAM_SIZE != 0)
QF_FUDGED_QUEUE_AT_(me, me->head).par = par;
#endif
if (me->head == (uint_fast8_t)0) {
me->head = (uint_fast8_t)QF_FUDGED_QUEUE_LEN; /* wrap the head */
}
--me->head;
++me->nUsed;
/* is this the first event? */
if (me->nUsed == (uint_fast8_t)1) {
/* set the corresponding bit in the ready set */
QF_readySet_ |= (uint_fast8_t)Q_ROM_BYTE(l_pow2Lkup[me->prio]);
pthread_cond_signal(&l_condVar); /* unblock the event loop */
}
margin = (uint_fast8_t)true; /* posting successful */
}
else {
/* can tolerate dropping evts? */
Q_ASSERT_ID(310, margin != (uint_fast8_t)0);
margin = (uint_fast8_t)false; /* posting failed */
}
QF_INT_ENABLE();
return (bool)margin;
}
/****************************************************************************/
#if (Q_PARAM_SIZE != 0)
bool QActive_postXISR_(QMActive * const me, uint_fast8_t margin,
enum_t const sig, QParam const par)
#else
bool QActive_postXISR_(QMActive * const me, uint_fast8_t margin,
enum_t const sig)
#endif
{
/* margin available? */
if (((uint_fast8_t)QF_FUDGED_QUEUE_LEN - me->nUsed) > margin) {
/* insert event into the ring buffer (FIFO) */
QF_FUDGED_QUEUE_AT_(me, me->head).sig = (QSignal)sig;
#if (Q_PARAM_SIZE != 0)
QF_FUDGED_QUEUE_AT_(me, me->head).par = par;
#endif
if (me->head == (uint_fast8_t)0) {
me->head = (uint_fast8_t)QF_FUDGED_QUEUE_LEN; /* wrap the head */
}
--me->head;
++me->nUsed;
/* is this the first event? */
if (me->nUsed == (uint_fast8_t)1) {
/* set the bit */
QF_readySet_ |= (uint_fast8_t)Q_ROM_BYTE(l_pow2Lkup[me->prio]);
pthread_cond_signal(&l_condVar); /* unblock the event loop */
}
margin = (uint_fast8_t)true; /* posting successful */
}
else {
/* can tolerate dropping evts? */
Q_ASSERT_ID(410, margin != (uint_fast8_t)0);
margin = (uint_fast8_t)false; /* posting failed */
}
return (bool)margin;
}
/****************************************************************************/
/****************************************************************************/
#if (QF_TIMEEVT_CTR_SIZE != 0)
void QF_tickXISR(uint_fast8_t const tickRate) {
uint_fast8_t p = (uint_fast8_t)QF_MAX_ACTIVE;
do {
QMActive *a = QF_ROM_ACTIVE_GET_(p);
QTimer *t = &a->tickCtr[tickRate];
if (t->nTicks != (QTimeEvtCtr)0) {
--t->nTicks;
if (t->nTicks == (QTimeEvtCtr)0) {
#ifdef QF_TIMEEVT_PERIODIC
if (t->interval != (QTimeEvtCtr)0) {
t->nTicks = t->interval; /* re-arm the periodic timer */
}
#endif /* QF_TIMEEVT_PERIODIC */
#ifdef QF_TIMEEVT_USAGE
QF_timerSetX_[tickRate] &=
(uint_fast8_t)Q_ROM_BYTE(QF_invPow2Lkup[p]);
#endif /* QF_TIMEEVT_USAGE */
#if (Q_PARAM_SIZE != 0)
QACTIVE_POST_ISR(a, (enum_t)Q_TIMEOUT_SIG + (enum_t)tickRate,
(QParam)0);
#else
QACTIVE_POST_ISR(a, (enum_t)Q_TIMEOUT_SIG + (enum_t)tickRate);
#endif /* (Q_PARAM_SIZE != 0) */
}
}
--p;
} while (p != (uint_fast8_t)0);
}
/****************************************************************************/
#ifdef QF_TIMEEVT_PERIODIC
void QActive_armX(QMActive * const me, uint_fast8_t const tickRate,
QTimeEvtCtr const nTicks, QTimeEvtCtr const interval)
#else
void QActive_armX(QActive * const me, uint_fast8_t const tickRate,
QTimeEvtCtr const nTicks)
#endif
{
QF_INT_DISABLE();
me->tickCtr[tickRate].nTicks = nTicks;
#ifdef QF_TIMEEVT_PERIODIC
me->tickCtr[tickRate].interval = interval;
#endif /* QF_TIMEEVT_PERIODIC */
#ifdef QF_TIMEEVT_USAGE
/* set a bit in QF_timerSetX_[] to rememer that the timer is running */
QF_timerSetX_[tickRate] |= (uint_fast8_t)Q_ROM_BYTE(l_pow2Lkup[me->prio]);
#endif
QF_INT_ENABLE();
}
/****************************************************************************/
void QActive_disarmX(QActive * const me, uint_fast8_t const tickRate) {
QF_INT_DISABLE();
me->tickCtr[tickRate].nTicks = (QTimeEvtCtr)0;
#ifdef QF_TIMEEVT_PERIODIC
me->tickCtr[tickRate].interval = (QTimeEvtCtr)0;
#endif /* QF_TIMEEVT_PERIODIC */
#ifdef QF_TIMEEVT_USAGE
/* clear a bit in QF_timerSetX_[] to rememer that timer is not running */
QF_timerSetX_[tickRate] &=
(uint_fast8_t)Q_ROM_BYTE(QF_invPow2Lkup[me->prio]);
#endif
QF_INT_ENABLE();
}
#endif /* #if (QF_TIMEEVT_CTR_SIZE != 0) */
/* QF functions ============================================================*/
/****************************************************************************/
void QF_enterCriticalSection_(void) {
pthread_mutex_lock(&l_pThreadMutex_);
}
/****************************************************************************/
void QF_leaveCriticalSection_(void) {
pthread_mutex_unlock(&l_pThreadMutex_);
}
/****************************************************************************/
int_t QF_run(void) {
uint_fast8_t p;
QMActive *a;
pthread_t thread;
pthread_cond_init(&l_condVar, 0);
/* set priorities all registered active objects... */
for (p = (uint_fast8_t)1; p <= (uint_fast8_t)QF_MAX_ACTIVE; ++p) {
a = QF_ROM_ACTIVE_GET_(p);
/* QF_active[p] must be initialized */
Q_ASSERT_ID(810, a != (QMActive *)0);
a->prio = p; /* set the priority of the active object */
}
/* trigger initial transitions in all registered active objects... */
for (p = (uint_fast8_t)1; p <= (uint_fast8_t)QF_MAX_ACTIVE; ++p) {
a = QF_ROM_ACTIVE_GET_(p);
QMSM_INIT(&a->super); /* take the initial transition in the SM */
}
QF_onStartup(); /* invoke startup callback */
l_isRunning = true;
Q_ALLEGE_ID(810, pthread_create(&thread, (pthread_attr_t *)0,
&tickerThread, (void *)0) == 0); /* ticker thread must be created */
/* the event loop of the vanilla kernel... */
while (l_isRunning) {
QF_INT_DISABLE();
if (QF_readySet_ != (uint_fast8_t)0) {
QMActiveCB const Q_ROM *acb;
#if (QF_MAX_ACTIVE > 4)
/* hi nibble non-zero? */
if ((QF_readySet_ & (uint_fast8_t)0xF0) != (uint_fast8_t)0) {
p = (uint_fast8_t)(
(uint_fast8_t)Q_ROM_BYTE(QF_log2Lkup[QF_readySet_ >> 4])
+ (uint_fast8_t)4);
}
/* hi nibble of QF_readySet_ is zero */
else
#endif
{
p = (uint_fast8_t)Q_ROM_BYTE(QF_log2Lkup[QF_readySet_]);
}
acb = &QF_active[p];
a = QF_ROM_ACTIVE_GET_(p);
/* some unsuded events must be available */
Q_ASSERT_ID(820, a->nUsed > (uint_fast8_t)0);
--a->nUsed;
/* queue becoming empty? */
if (a->nUsed == (uint_fast8_t)0) {
/* clear the bit corresponding to 'p' */
QF_readySet_ &= (uint_fast8_t)Q_ROM_BYTE(QF_invPow2Lkup[p]);
}
Q_SIG(a) = QF_FUDGED_QUEUE_AT_(a, a->tail).sig;
#if (Q_PARAM_SIZE != 0)
Q_PAR(a) = QF_FUDGED_QUEUE_AT_(a, a->tail).par;
#endif
if (a->tail == (uint_fast8_t)0) { /* wrap around? */
a->tail = (uint_fast8_t)QF_FUDGED_QUEUE_LEN;
}
--a->tail;
QF_INT_ENABLE();
QMSM_DISPATCH(&a->super); /* dispatch to the SM */
}
else {
/* yield the CPU until new event(s) arrive */
pthread_cond_wait(&l_condVar, &l_pThreadMutex_);
QF_INT_ENABLE();
}
}
QF_onCleanup(); /* cleanup callback */
pthread_cond_destroy(&l_condVar); /* cleanup the condition variable */
pthread_mutex_destroy(&l_pThreadMutex_);
return (int_t)0; /* success */
}
/****************************************************************************/
void QF_stop(void) {
l_isRunning = false; /* cause exit from the event loop */
/* unblock the event loop so it can terminate */
pthread_cond_signal(&l_condVar);
}
/****************************************************************************/
void QF_setTickRate(uint32_t ticksPerSec) {
l_tickUsec = 1000000UL / ticksPerSec;
}
/*..........................................................................*/
static void *tickerThread(void *par) { /* the expected P-Thread signature */
struct timeval timeout = { 0U, 0U }; /* timeout for select() */
(void)par; /* unused parameter */
while (l_isRunning) {
timeout.tv_usec = l_tickUsec; /* set the desired tick interval */
select(0, 0, 0, 0, &timeout); /* sleep for the desired tick, NOTE1 */
QF_INT_DISABLE();
QF_onClockTickISR(); /* call back to the app, see NOTE02 */
QF_INT_ENABLE();
}
return (void *)0; /* return success */
}
/* NOTES: ********************************************************************
*
* NOTE1:
* The select() system call seems to deliver the finest time granularity of
* 1 clock tick. The timeout value passed to select() is rounded up to the
* nearest tick (10 ms on desktop Linux). The timeout cannot be too short,
* because the system might choose to busy-wait for very short timeouts.
* An alternative, POSIX nanosleep() system call seems to deliver only 20ms
* granularity.
*
* Here the select() call is used not just as a fairly portable way to sleep
* with subsecond precision. The select() call is also used to detect any
* characters typed on the console.
*
* Also according to man pages, on Linux, the function select() modifies
* timeout to reflect the amount of time not slept; most other implementations
* do not do this. This causes problems both when Linux code which reads
* timeout is ported to other operating systems, and when code is ported to
* Linux that reuses a struct timeval for multiple selects in a loop without
* reinitializing it. Here the microsecond part of the structure is re-
* initialized before each select() call.
*
* NOTE2:
* POSIX is not necessariliy a deterministic real-time system, which means
* that the system can occasionally and unexpectedly "choke and freeze" for
* a number of seconds. The designers of POSIX have dealt with these sort
* of issues by massively oversizing the resources available to the
* applications. For example, the the stacks of POSIX-threads can dynamically
* grow to several megabytes.
*
* In contrast, the event queues, event pools, and stack size inside the
* real-time embedded (RTE) systems can be (and must be) much smaller,
* because you typically can put an upper bound on the real-time behavior
* and the resulting delays.
*
* To be able to run the unmodified applications designed originally for
* RTE systems on POSIX, and to reduce the odds of resource shortages in
* this case, the event queues of all Active Objects are "fudged" to the
* maximum dynamic range of uint_fast8_t data type, which is 0xFF
* (see QF_FUDGED_QUEUE_LEN).
*
* NOTE3:
* The callback QF_onClockTickISR() is invoked with interupts disabled
* to emulate the ISR level. This means that only the ISR-level APIs are
* available inside the QF_onClockTickISR() callback.
*/
| 36.250549 | 78 | 0.584758 | [
"object"
] |
99c5af3a2f5c3b5354521e1287a41c8e4e0b2c9b | 6,214 | h | C | motoman_driver/include/motoman_driver/industrial_robot_client/joint_feedback_relay_handler.h | lights0123/motoman | 763ca99b521b14dd889897f68300b2daf6454631 | [
"Apache-2.0",
"BSD-3-Clause"
] | 112 | 2015-01-20T22:14:02.000Z | 2022-02-07T11:02:10.000Z | motoman_driver/include/motoman_driver/industrial_robot_client/joint_feedback_relay_handler.h | lights0123/motoman | 763ca99b521b14dd889897f68300b2daf6454631 | [
"Apache-2.0",
"BSD-3-Clause"
] | 406 | 2015-01-10T08:58:51.000Z | 2022-03-31T07:13:39.000Z | motoman_driver/include/motoman_driver/industrial_robot_client/joint_feedback_relay_handler.h | lights0123/motoman | 763ca99b521b14dd889897f68300b2daf6454631 | [
"Apache-2.0",
"BSD-3-Clause"
] | 170 | 2015-04-05T16:18:37.000Z | 2022-03-30T09:44:11.000Z | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Southwest Research Institute
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Southwest Research Institute, nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MOTOMAN_DRIVER_INDUSTRIAL_ROBOT_CLIENT_JOINT_FEEDBACK_RELAY_HANDLER_H
#define MOTOMAN_DRIVER_INDUSTRIAL_ROBOT_CLIENT_JOINT_FEEDBACK_RELAY_HANDLER_H
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include "motoman_driver/industrial_robot_client/joint_relay_handler.h"
#include "simple_message/messages/joint_feedback_message.h"
#include "motoman_msgs/DynamicJointsGroup.h"
namespace industrial_robot_client
{
namespace joint_feedback_relay_handler
{
using industrial::joint_feedback_message::JointFeedbackMessage;
using industrial::simple_message::SimpleMessage;
using industrial::smpl_msg_connection::SmplMsgConnection;
using industrial_robot_client::joint_relay_handler::JointRelayHandler;
using trajectory_msgs::JointTrajectoryPoint;
using motoman_msgs::DynamicJointsGroup;
/**
* \brief Message handler that relays joint positions (converts simple message
* types to ROS message types and publishes them)
*
* THIS CLASS IS NOT THREAD-SAFE
*
*/
class JointFeedbackRelayHandler : public industrial_robot_client::joint_relay_handler::JointRelayHandler
{
public:
/**
* \brief Constructor
*/
explicit JointFeedbackRelayHandler(int robot_id = -1) : robot_id_(robot_id) {}
/**
* \brief Class initializer
*
* \param connection simple message connection that will be used to send replies.
* \param joint_names list of joint-names for msg-publishing.
* - Count and order should match data from robot connection.
* - Use blank-name to exclude a joint from publishing.
*
* \return true on success, false otherwise (an invalid message type)
*/
virtual bool init(SmplMsgConnection* connection,
std::vector<std::string> &joint_names);
virtual bool init(SmplMsgConnection* connection,
std::map<int, RobotGroup> &robot_groups);
protected:
int robot_id_;
bool version_0_;
/**
* \brief Convert joint message into intermediate message-type
*
* \param[in] msg_in Message from robot connection
* \param[out] joint_state JointTrajectoryPt message for intermediate processing
*/
virtual bool convert_message(SimpleMessage& msg_in, JointTrajectoryPoint* joint_state);
/**
* \brief Convert joint message into intermediate message-type
*
* \param[in] msg_in Message from robot connection
* \param[out] joint_state JointTrajectoryPt message for intermediate processing
*/
virtual bool convert_message(SimpleMessage& msg_in, DynamicJointsGroup* joint_state, int robot_id);
// override JointRelayHandler::create_messages, to check robot_id w/o error msg
bool create_messages(SimpleMessage& msg_in,
control_msgs::FollowJointTrajectoryFeedback* control_state,
sensor_msgs::JointState* sensor_state);
bool create_messages(SimpleMessage& msg_in,
control_msgs::FollowJointTrajectoryFeedback* control_state,
sensor_msgs::JointState* sensor_state, int robot_id);
// Overriding some functions to get it to work now inside of the Motoman package
virtual bool transform(const DynamicJointsGroup& state_in, DynamicJointsGroup* state_out)
{
*state_out = state_in; // by default, no transform is applied
return true;
}
virtual bool select(const DynamicJointsGroup& all_joint_state, const std::vector<std::string>& all_joint_names,
DynamicJointsGroup* pub_joint_state, std::vector<std::string>* pub_joint_names);
private:
static bool JointDataToVector(const industrial::joint_data::JointData &joints,
std::vector<double> &vec, int len);
/**
* \brief Convert joint feedback message into intermediate message-type
*
* \param[in] msg_in JointFeedbackMessage from robot connection
* \param[out] joint_state JointTrajectoryPt message for intermediate processing
*/
bool convert_message(JointFeedbackMessage& msg_in, JointTrajectoryPoint* joint_state);
/**
* \brief Convert joint feedback message into intermediate message-type
*
* \param[in] msg_in JointFeedbackMessage from robot connection
* \param[out] joint_state JointTrajectoryPt message for intermediate processing
*/
bool convert_message(JointFeedbackMessage& msg_in, DynamicJointsGroup* joint_state, int robot_id);
}; // class JointFeedbackRelayHandler
} // namespace joint_feedback_relay_handler
} // namespace industrial_robot_client
#endif // MOTOMAN_DRIVER_INDUSTRIAL_ROBOT_CLIENT_JOINT_FEEDBACK_RELAY_HANDLER_H
| 40.614379 | 113 | 0.754908 | [
"vector",
"transform"
] |
99df90974538a42807183e87cf1f1b8f2e4e7bd4 | 830 | h | C | util/include/string_helper.h | readex-eu/readex-ptf | 011ef4bf133476a10482c8c248027bcb651d4d57 | [
"BSD-3-Clause"
] | 1 | 2022-03-10T09:59:37.000Z | 2022-03-10T09:59:37.000Z | util/include/string_helper.h | readex-eu/readex-ptf | 011ef4bf133476a10482c8c248027bcb651d4d57 | [
"BSD-3-Clause"
] | 3 | 2020-04-21T07:57:32.000Z | 2020-10-14T08:05:41.000Z | util/include/string_helper.h | readex-eu/readex-ptf | 011ef4bf133476a10482c8c248027bcb651d4d57 | [
"BSD-3-Clause"
] | 1 | 2020-11-20T03:04:32.000Z | 2020-11-20T03:04:32.000Z | /**
@file string_helper.h
@brief String modification utilities header
@author Madhura Kumaraswamy
@verbatim
Revision: $Revision$
Revision date: $Date$
Committed by: $Author$
This file is part of the Periscope performance measurement tool.
See http://www.lrr.in.tum.de/periscope for details.
Copyright (c) 2015-2016, Technische Universitaet Muenchen, Germany
See the COPYING file in the base directory of the package for details.
@endverbatim
*/
#ifndef STRING_HELPER_H_
#define STRING_HELPER_H_
#include <string>
#include <vector>
#include <boost/regex.hpp>
std::string formatString( std::string &str,
std::vector<boost::regex> reg_expr, std::vector<std::string> format);
#endif /* STRING_HELPER_H_ */
| 26.774194 | 102 | 0.660241 | [
"vector"
] |
99e185ea104afa1267c5b4d3685ef407d7c8b233 | 5,450 | h | C | OptFrame/Scanner++/Scanner.h | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 4 | 2019-06-02T10:59:57.000Z | 2021-11-29T08:40:47.000Z | OptFrame/Scanner++/Scanner.h | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | null | null | null | OptFrame/Scanner++/Scanner.h | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 1 | 2019-06-06T16:57:49.000Z | 2019-06-06T16:57:49.000Z | // Scanner Class for C++ - Scanner++
// Copyright (C) 2009-2017
// scannerpp.sourceforge.net
//
// This file is part of the Scanner++ Library v0.98. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License v3 as published by the
// Free Software Foundation.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License v3 for more details.
// You should have received a copy of the GNU Lesser General Public License v3
// along with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#ifndef SCANNERPP_H_
#define SCANNERPP_H_
#include<iostream>
#include<istream>
#include<string>
#include<sstream>
#include<algorithm>
#include<vector>
#include<map>
#include <stdlib.h>
#include "File.h"
namespace scannerpp
{
class ConversionError
{
private:
bool whatInfo;
std::string what;
std::string type;
public:
ConversionError(std::string _type) :
whatInfo(false), what(""), type(_type)
{
}
ConversionError(std::string _what, std::string _type) :
whatInfo(true), what(_what), type(_type)
{
}
std::string getType() const
{
return type;
}
std::string getWhat() const
{
return what;
}
std::string getMessage() const
{
stringstream ss;
if(whatInfo)
ss << "value '" << what << "' is not of '" << type << "' type";
else
ss << "conversion error for '" << type << "' type";
return ss.str();
}
};
class Scanner
{
private:
istream *input;
File* inputfile;
string sep;
bool isString;
string discarded;
string contentString;
private:
char nextChar(istream& _input) const
{
int x = _input.get();
if (x <= 0)
throw ConversionError("char");
return x;
}
void put_back(istream** input, string back) const
{
if((*input)->eof())
{
// change internal pointer to a renewed istream
delete (*input);
(*input) = new istringstream(back);
}
else
{
// just return everything back!
for(int i = ((int) back.length()) - 1; i >= 0; i--)
{
(*input)->putback(back[i]);
if((*input)->fail())
{
cout << "SCANNER ERROR PUTTING BACK CHAR '" << back[i] << "'" << endl;
cout << "eof bit: '" << (*input)->eof() << "'" << endl;
cout << "bad bit: '" << (*input)->bad() << "'" << endl;
cout << "fail bit: '" << (*input)->fail() << "'" << endl;
exit(1);
}
}
}
}
public:
string getDiscarded() const
{
return discarded;
}
bool hasNextChar() const;
char nextChar();
bool nextCharIs(char c) const;
bool nextCharIn(string s) const;
void trimInput();
Scanner(File* inputfile);
Scanner(istream* input);
Scanner(string input);
Scanner(const Scanner& scanner);
virtual ~Scanner();
virtual Scanner& operator=(const Scanner& scanner);
// useDefaultSeparators: chama o useSeparators para os caracteres:
// espaco, quebra de linha (\n), tabulacao (\t) e retorno de carro (\r)
void useDefaultSeparators();
// useSeparators: equivalente ao useDelimiter de Java
// a diferenca e que Java trata a string como uma
// expressao regular, e neste caso o useSeparators
// apenas considera cada caractere da string separadamente
// como um separador.
void useSeparators(string s);
bool inSeparators(char c) const;
std::string peekNext() const;
std::string next();
std::string nextLine();
int nextInt();
long nextLong();
float nextFloat();
double nextDouble();
static int parseInt(string s)
{
Scanner scanner(s);
return scanner.nextInt();
}
static double parseDouble(string s)
{
Scanner scanner(s);
return scanner.nextDouble();
}
static bool trimChar(char c)
{
return (c==' ') || (c=='\t') || (c=='\n');
}
static string trim(string word)
{
if(word.length()==0)
return "";
int i = 0;
char c = word.at(i);
string aux_word = "";
//removing initial spaces
while( trimChar(c) && (i < ((int) word.length())-1) )
{
i++;
c = word.at(i);
}
if(trimChar(c)) // last char
i++;
while (i < ((int) word.length()))
{
aux_word += word.at(i);
i++;
}
word = aux_word;
// may be empty at this point
if(word.length()==0)
return "";
//removing final spaces
i = ((int)word.length()) - 1;
c = word.at(i);
while (trimChar(c) && (i > 0))
{
i--;
c = word.at(i);
}
aux_word = "";
for(int j=0; j<=i; j++)
aux_word += word.at(j);
return aux_word;
}
pair<string, map<string, string> > nextXMLTag();
bool hasNext() const;
bool hasNextLine() const
{
return hasNext();
}
bool hasNextInt() const
{
int x;
if(hasNextX(x))
{
double d;
if(hasNextX(d))
return (x == d);
}
return false;
}
bool hasNextLong() const
{
long x;
if(hasNextX(x))
{
double d;
if(hasNextX(d))
return (x == d);
}
return false;
}
bool hasNextFloat() const
{
float x;
return hasNextX(x);
}
bool hasNextDouble() const
{
double x;
return hasNextX(x);
}
template<class X>
inline bool hasNextX(X& x) const
{
string s = peekNext();
if(s == "")
return false;
std::istringstream ss(s);
return bool(ss >> x);
}
string rest(); // Returns the rest of the input as string
};
} // end namespace scannerpp
#endif /*SCANNERPP_H_*/
| 17.752443 | 79 | 0.629908 | [
"vector"
] |
99e8465baf411ad203eb992bfdc8a37147d88026 | 4,041 | h | C | modules/core/include/lagrange/utils/SmallVector.h | LaudateCorpus1/lagrange | 2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40 | [
"Apache-2.0"
] | 156 | 2021-01-08T19:53:06.000Z | 2022-03-25T18:32:52.000Z | modules/core/include/lagrange/utils/SmallVector.h | LaudateCorpus1/lagrange | 2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40 | [
"Apache-2.0"
] | 2 | 2021-01-11T20:18:07.000Z | 2021-08-04T15:53:57.000Z | modules/core/include/lagrange/utils/SmallVector.h | LaudateCorpus1/lagrange | 2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40 | [
"Apache-2.0"
] | 10 | 2021-01-11T21:03:54.000Z | 2022-01-24T06:27:44.000Z | /*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
#pragma once
#include <lagrange/utils/la_assert.h>
#include <algorithm>
#include <array>
#include <initializer_list>
namespace lagrange {
///
/// Stack-allocated vector with a maximum size.
///
/// @tparam T Value type.
/// @tparam N Maximum size.
///
template <typename T, size_t N>
struct SmallVector
{
private:
std::array<T, N> m_array;
size_t m_size = 0;
public:
SmallVector() = default;
SmallVector(std::initializer_list<T> init)
: m_size(init.size())
{
LA_ASSERT(m_size <= N);
auto it = init.begin();
for (size_t i = 0; i < m_size; ++i) {
m_array[i] = std::move(*it);
++it;
}
}
size_t size() const { return m_size; }
void clear() { m_size = 0; }
void resize(const size_t i)
{
LA_ASSERT(i <= m_array.size());
m_size = i;
}
void push_back(const T& v)
{
LA_ASSERT(m_size < m_array.size());
m_array[m_size++] = v;
}
template <class... Args>
void emplace_back(Args&&... args)
{
LA_ASSERT(m_size < m_array.size());
m_array[m_size++] = T(std::forward<Args>(args)...);
}
void pop_back()
{
LA_ASSERT(m_size > 0);
--m_size;
}
T* data() { return m_array.data(); }
const T* data() const { return m_array.data(); }
T& front()
{
LA_ASSERT(m_size > 0);
return m_array.front();
}
const T& front() const
{
LA_ASSERT(m_size > 0);
return m_array.front();
}
T& back()
{
LA_ASSERT(m_size > 0);
return m_array.at(m_size - 1);
}
const T& back() const
{
LA_ASSERT(m_size > 0);
return m_array.at(m_size - 1);
}
T& at(const size_t i)
{
LA_ASSERT(i < m_size);
return m_array.at(i);
}
const T& at(const size_t i) const
{
LA_ASSERT(i < m_size);
return m_array.at(i);
}
T& operator[](const size_t i)
{
LA_ASSERT(i < m_size);
return m_array[i];
}
const T& operator[](const size_t i) const
{
LA_ASSERT(i < m_size);
return m_array[i];
}
template <typename U, class UnaryOperation>
auto transformed(UnaryOperation op) {
SmallVector<U, N> result;
result.resize(size());
for (size_t i = 0; i < size(); ++i) {
result[i] = op(at(i));
}
return result;
}
template <size_t D>
auto to_tuple() {
assert(D == m_size);
static_assert(D <= N, "Invalid size");
return to_tuple_helper(std::make_index_sequence<D>());
}
private:
template <size_t... Indices>
auto to_tuple_helper(std::index_sequence<Indices...>) {
return std::make_tuple(m_array[Indices]...);
}
public:
using iterator = typename std::array<T, N>::iterator;
using const_iterator = typename std::array<T, N>::const_iterator;
iterator begin() { return m_array.begin(); }
iterator end() { return m_array.begin() + m_size; }
const_iterator begin() const { return m_array.begin(); }
const_iterator end() const { return m_array.begin() + m_size; }
};
template <class T, size_t N>
bool operator==(const SmallVector<T, N>& lhs, const SmallVector<T, N>& rhs)
{
return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin()));
}
} // namespace lagrange
| 23.911243 | 89 | 0.584014 | [
"vector"
] |
99f188cacc4ec1a515266fbbe34c97379247e8c1 | 582 | c | C | d/shadow/city/storage/ass_scroll_storage.c | guille-valencia/shadowgate | a5c63b535e50020b58435d6fbb5b4f60d8f25639 | [
"MIT"
] | 1 | 2021-06-10T00:35:51.000Z | 2021-06-10T00:35:51.000Z | d/shadow/city/storage/ass_scroll_storage.c | guille-valencia/shadowgate | a5c63b535e50020b58435d6fbb5b4f60d8f25639 | [
"MIT"
] | null | null | null | d/shadow/city/storage/ass_scroll_storage.c | guille-valencia/shadowgate | a5c63b535e50020b58435d6fbb5b4f60d8f25639 | [
"MIT"
] | null | null | null | #include <std.h>
#include "/d/common/common.h"
inherit "/std/room";
void create() {
::create();
set_property("no teleport",1);
set_exits( (["up" : "/d/shadow/city/room/assassinscrolls"]) );
}
void reset() {
int i;
object scroll;
for (i = 0; i < 13; i++)
if(!present("parchment "+i))
new("/d/tharis/obj/parchment")->move(TO);
for (i = 0; i < 100; i++)
if(!present("scroll "+i))
{
scroll = new("/d/magic/safe_scroll");
scroll->move(TO);
scroll->set_spell(random(9)+1);
}
}
| 22.384615 | 66 | 0.505155 | [
"object"
] |
82025b69aad3704df3ad6359e1511520de8eccb4 | 2,517 | h | C | engine/src/engine/public/ecs/entity.h | brass-suzume/orb-engine | b26e63d6f8c2fc2036c9ea558b873f9e29b608f6 | [
"MIT"
] | null | null | null | engine/src/engine/public/ecs/entity.h | brass-suzume/orb-engine | b26e63d6f8c2fc2036c9ea558b873f9e29b608f6 | [
"MIT"
] | null | null | null | engine/src/engine/public/ecs/entity.h | brass-suzume/orb-engine | b26e63d6f8c2fc2036c9ea558b873f9e29b608f6 | [
"MIT"
] | null | null | null | #pragma once
namespace core
{
class Component;
class PositionComponent;
class GameInstance;
class Entity;
//////////////////////////////////////////////////////////////////////////////////////////////////
//
struct EntityInitContext
{
Vector2 m_initialPosition;
float m_initialRotation = 0.0f;
EntityID m_entityId = c_invalidEntityID;
const GameInstance* m_gameInstance = nullptr;
std::weak_ptr< Entity > m_owner;
};
//////////////////////////////////////////////////////////////////////////////////////////////////
//
class Entity : public Serializable, public std::enable_shared_from_this< Entity >
{
ORB_DECLARE_TYPE( Entity );
ORB_SUPER_CLASS( Serializable );
private:
friend class EntitySystem;
public:
virtual ~Entity();
void Init( const EntityInitContext& initCtx );
void Uninit();
EntityID GetEntityID() const { return m_entityId; }
std::shared_ptr< Entity > GetOwner() const { return m_owner.lock(); }
Vector2 GetPosition() const { return m_position; }
float GetRotation() const { return m_rotation; }
Matrix GetWorldTransform() const;
Vector2 GetForward() const;
Vector2 GetRight() const;
const GameInstance* GetGameInstance() const { return m_gameInstance; }
virtual bool Deserialize( const json& data ) override;
template< class TComponent >
std::shared_ptr< TComponent > FindFirstComponentOfType() const
{
for( const std::shared_ptr< Component >& c : m_allComponents )
{
if( auto casted = std::dynamic_pointer_cast< TComponent >( c ) )
{
return casted;
}
}
return nullptr;
}
template< class TComponent, class TFunctor >
void ForEachComponentOfType( const TFunctor& functor ) const
{
for( const std::shared_ptr< Component >& c : m_allComponents )
{
if( auto casted = std::dynamic_pointer_cast< TComponent >( c ) )
{
functor( casted );
}
}
}
protected:
virtual void OnInit( const EntityInitContext& initCtx );
virtual void OnUninit();
private:
void Internal_RefreshHierarchy();
void Internal_UpdateTransformHierarchy( const Vector2& position, float rotation );
private:
EntityID m_entityId = c_invalidEntityID;
std::weak_ptr< Entity > m_owner;
const GameInstance* m_gameInstance = nullptr;
Vector2 m_position;
float m_rotation = 0.0f;
std::vector< std::shared_ptr< Component > > m_components;
std::vector< std::shared_ptr< PositionComponent > > m_positionComponents;
std::vector< std::shared_ptr< Component > > m_allComponents;
};
} | 25.683673 | 99 | 0.657132 | [
"vector"
] |
820b4ce8db4a98fd02609b5031db8304b4ddbd6e | 4,104 | h | C | applications/LinearSolversApplication/custom_solvers/eigen_dense_eigenvalue_solver.h | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | applications/LinearSolversApplication/custom_solvers/eigen_dense_eigenvalue_solver.h | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | applications/LinearSolversApplication/custom_solvers/eigen_dense_eigenvalue_solver.h | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | /* KRATOS _ _ ____ _
// | | (_)_ __ ___ __ _ _ __/ ___| ___ | |_ _____ _ __ ___
// | | | | '_ \ / _ \/ _` | '__\___ \ / _ \| \ \ / / _ \ '__/ __|
// | |___| | | | | __/ (_| | | ___) | (_) | |\ V / __/ | \__ |
// |_____|_|_| |_|\___|\__,_|_| |____/ \___/|_| \_/ \___|_| |___/ Application
//
// Author: Manuel Messmer
*/
#if !defined(KRATOS_EIGEN_DENSE_EIGENVALUE_SOLVER_H_INCLUDED)
#define KRATOS_EIGEN_DENSE_EIGENVALUE_SOLVER_H_INCLUDED
// External includes
#include <Eigen/Core>
#include <Eigen/Eigenvalues>
// Project includes
#include "includes/define.h"
#include "linear_solvers_define.h"
#include "spaces/ublas_space.h"
#include "utilities/builtin_timer.h"
#include "linear_solvers/linear_solver.h"
namespace Kratos {
template <typename TScalar = double,
class TSparseSpaceType = TUblasDenseSpace<TScalar>,
class TDenseSpaceType = TUblasDenseSpace<TScalar>>
class DenseEigenvalueSolver :
public LinearSolver<TSparseSpaceType, TDenseSpaceType>
{
Parameters mParam;
int mEchoLevel;
public:
KRATOS_CLASS_POINTER_DEFINITION(DenseEigenvalueSolver);
typedef typename TDenseSpaceType::MatrixType DenseMatrixType;
typedef typename TDenseSpaceType::VectorType DenseVectorType;
DenseEigenvalueSolver( Parameters param) : mParam(param){
Parameters default_params(R"(
{
"solver_type" : "dense_eigensolver",
"ascending_order" : true,
"echo_level" : 0
})");
mParam.ValidateAndAssignDefaults(default_params);
mEchoLevel = mParam["echo_level"].GetInt();
}
~DenseEigenvalueSolver() override {}
/**
* @brief Dense eigenvalue solver
* @details Computes eigenvalues and eigenvectors of selfadjoint matrices.
* @param rA System matrix
* @param rDummy Dummy matrix
* @param rEigenvalues Eigenvalue vector
* @param rEigenvectors Eigenvector matrix
*/
void Solve( DenseMatrixType& rA,
DenseMatrixType& rDummy,
DenseVectorType& rEigenvalues,
DenseMatrixType& rEigenvectors) override
{
BuiltinTimer eigensolver_timer;
KRATOS_INFO_IF("DenseEigenvalueSolver", mEchoLevel > 0) << "Start" << std::endl;
using vector_t = Kratos::EigenDynamicVector<TScalar>;
using matrix_t = Kratos::EigenDynamicMatrix<TScalar>;
Eigen::Map<matrix_t> A(rA.data().begin(), rA.size1(), rA.size2());
Eigen::SelfAdjointEigenSolver<matrix_t> solver;
solver.compute(A, Eigen::ComputeEigenvectors);
rEigenvalues.resize(rA.size1());
rEigenvectors.resize(rA.size1(), rA.size1());
Eigen::Map<vector_t> eigvals (rEigenvalues.data().begin(), rEigenvalues.size());
Eigen::Map<matrix_t> eigvecs (rEigenvectors.data().begin(), rEigenvectors.size1(), rEigenvectors.size2());
if( mParam["ascending_order"].GetBool() ){
eigvals = solver.eigenvalues();
eigvecs = solver.eigenvectors();
}
else{
eigvals = solver.eigenvalues().reverse();
eigvecs = solver.eigenvectors().rowwise().reverse();
}
const bool success = solver.info() == Eigen::Success;
if( success ){
KRATOS_INFO_IF("DenseEigenvalueSolver", mEchoLevel > 0) << "Completed in "
<< eigensolver_timer.ElapsedSeconds() << " seconds" << std::endl;
Eigen::IOFormat fmt(Eigen::StreamPrecision, Eigen::DontAlignCols, ", ", ", ", "", "", "[ ", " ]");
KRATOS_INFO_IF("", mEchoLevel > 1)
<< " Eigenvalues = " << eigvals.transpose().format(fmt) << std::endl;
}
else{
KRATOS_WARNING("DenseEigenvalueSolver") << "Decomposition failed!" << std::endl;
}
}
void PrintInfo(std::ostream &rOStream) const override
{
rOStream << "DenseEigenvalueSolver";
}
};
} // namespace Kratos
#endif // defined(KRATOS_EIGEN_DENSE_EIGENVALUE_SOLVER_H_INCLUDED) | 32.832 | 114 | 0.616715 | [
"vector"
] |
820f9428bf459181e45737502431a7f3bb7ee19b | 4,942 | h | C | src/camera/CameraParams.h | huskyroboticsteam/PY2020 | cd6368d85866204dbdca6aefacac69059e780aa2 | [
"Apache-2.0"
] | 11 | 2019-10-03T01:17:16.000Z | 2020-10-25T02:38:32.000Z | src/camera/CameraParams.h | huskyroboticsteam/PY2020 | cd6368d85866204dbdca6aefacac69059e780aa2 | [
"Apache-2.0"
] | 53 | 2019-10-03T02:11:04.000Z | 2021-06-05T03:11:55.000Z | src/camera/CameraParams.h | huskyroboticsteam/Resurgence | 649f78103b6d76709fdf55bb38d08c0ff50da140 | [
"Apache-2.0"
] | 3 | 2019-09-20T04:09:29.000Z | 2020-08-18T22:25:20.000Z | #pragma once
#include <opencv2/core.hpp>
namespace cam {
/**
@addtogroup camera
@{
*/
/**
@name Configuration File Keys
The following are constants for the keys used in the camera configuration files. See @ref
cameraconfig for more details.
*/
/**@{*/
/**
Config file key for image width.
*/
const std::string KEY_IMAGE_WIDTH = "image_width";
/**
Config file key for image height.
*/
const std::string KEY_IMAGE_HEIGHT = "image_height";
/**
Config file key for the camera matrix.
*/
const std::string KEY_CAMERA_MATRIX = "camera_matrix";
/**
Config file key for the distortion coefficients.
*/
const std::string KEY_DIST_COEFFS = "distortion_coefficients";
/**@}*/
/**
@brief Represents a set of intrinsic camera parameters.
Camera parameters (also called "intrinsic parameters") are obtained from
camera calibration and are unique to and constant for every camera. They
define how the camera projects a 3D space onto a 2D image plane.
Each set of CameraParams contains a camera matrix which defines how points in
3D space are linearly projected to the 2D image plane of the camera, and a
set of distortion coefficients which can be used to correct for radial
distortion in the image. The projection is linear which means that projected
points are unique only up to scaling.
@warning Note that camera parameters are different for different resolutions
of the camera! It is often not enough to simply scale the image centers/focal
lengths for different resolutions because many cameras have different fields
of view (and therefore different projections/distortion) at different
resolutions. For this reason, a CameraParams object has an associated
cv::Size which contains the image size the parameters are valid for.
*/
class CameraParams {
private:
cv::Mat _camera_matrix;
cv::Mat _dist_coeff;
cv::Size _image_size;
void init(const cv::Mat& camera_matrix, const cv::Mat& dist_coeff, cv::Size image_size);
public:
/**
Constructs a default or empty set of camera parameters.
@warning Empty sets of camera parameters are not suitable for actual use! Check to make
sure they are non-empty with empty().
*/
CameraParams();
/**
Constructs a set of camera parameters with the given camera matrix, distortion
coefficients, and image size.
@param camera_matrix A 3x3 matrix defining the projection of the camera.
@param dist_coeff A set of distortion coefficients defining the lens distortion of the
camera. Must be a 1xN or Nx1 matrix where N is the number of coefficients. N must be 4,
5, 8, 12, or 14.
@param image_size The size of the image the parameters are calibrated for. Defaults to
640x480 as this is the default resolution of many webcams.
*/
CameraParams(const cv::Mat& camera_matrix, const cv::Mat& dist_coeff,
cv::Size image_size = cv::Size(640, 480));
/**
@brief Copy constructor.
Constructs a set of camera parameters by copying another. Underlying data like the
camera matrix and distortion coefficients are actually copied, so the copy may be
modified without affecting the original.
*/
CameraParams(const CameraParams& other);
bool empty() const;
/**
Gets the camera matrix associated with this set of camera parameters.
*/
cv::Mat getCameraMatrix() const;
/**
Gets the distortion coefficients (as a column vector) associated with
this set of camera parameters.
*/
cv::Mat getDistCoeff() const;
/**
Gets the image size this set of intrinsic parameters was calibrated for.
*/
cv::Size getImageSize() const;
/**
@brief Reads the data for this CameraParams object from the given cv::FileNode object.
Used for serialization - you should not need to call this method directly but should
instead use the >> operator on a cv::FileNode object.
*/
void readFromFileNode(const cv::FileNode& file_node);
/**
@brief Writes the data for this CameraParams object to the given cv::FileStorage
object.
Used for serialization - you should not need to call this method directly but should
instead use the << operator on a cv::FileStorage object.
*/
void writeToFileStorage(cv::FileStorage& file_storage) const;
};
/**
@brief Reads a CameraParams object from the given cv::FileNode object.
Used for serialization - you should not need to call this method directly but should
instead use the >> operator on a cv::FileNode object.
*/
void read(const cv::FileNode& node, CameraParams& params,
const CameraParams& default_value = CameraParams());
/**
@brief Writes the given CameraParams object to the given cv::FileStorage object.
Used for serialization - you should not need to call this method directly but should
instead use the << operator on a cv::FileStorage object.
*/
void write(cv::FileStorage& fs, const std::string& name, const CameraParams& params);
/** @} */
} // namespace cam
| 33.849315 | 91 | 0.73452 | [
"object",
"vector",
"3d"
] |
8210d4752b367dfea6564783cbddd0f87ff77f0a | 1,468 | h | C | include/websms/dto.h | websms-com/websmscom-cpp | a9214bd7dcc02c0e058a345e353d7417597f77c9 | [
"MIT"
] | null | null | null | include/websms/dto.h | websms-com/websmscom-cpp | a9214bd7dcc02c0e058a345e353d7417597f77c9 | [
"MIT"
] | null | null | null | include/websms/dto.h | websms-com/websmscom-cpp | a9214bd7dcc02c0e058a345e353d7417597f77c9 | [
"MIT"
] | null | null | null | /**
* Copyright (C) 2012, sms.at mobile internet services gmbh
*
* @author Markus Opitz
* @file serialization.h
* @brief Contains wrapper template class for data transfer objects.
*/
#ifndef WEBSMS_DTO_H_
#define WEBSMS_DTO_H_
namespace websms {
/**
* @class DtoWrapper
* @brief Base class for data transfer object wrappers.
* @see DtoSupport
*
* Handles creation, destruction and deserialization of the embedded data
* transfer object.
*/
template<class T>
class DtoWrapper {
public:
/**
* Constructor
* @brief Creates internal object.
*/
DtoWrapper()
: dto_(T::Create()) {
}
/**
* Destructor
* @brief Destroys internal object
*/
virtual ~DtoWrapper() {
T::Destroy(dto_);
}
DtoWrapper(const DtoWrapper& source)
: dto_(T::Copy(source.dto_)) {
}
/**
* Assignment operator
* @param[in] source Source
*/
DtoWrapper& operator=(const DtoWrapper& source) {
T::Destroy(dto_);
dto_ = T::Copy(source.dto_);
return *this;
}
/**
* Serialize internal object.
* @return Serialized object
*/
const char* Serialize() const {
return T::Serialize(dto_);
}
/**
* Deserialize input string and store result in internal object.
* @param[in] data Serialized string
* @return True on success
*/
bool Deserialize(const char* data) {
return T::Deserialize(data, dto_);
}
protected:
T* dto_;
};
} /* namespace websms */
#endif /* WEBSMS_DTO_H_ */
| 18.582278 | 73 | 0.645095 | [
"object"
] |
82117c8690a3430d5126ae9209b38e03f8958c49 | 280,584 | c | C | sdk-6.5.16/src/bcmx/field.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.16/src/bcmx/field.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.16/src/bcmx/field.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | /*
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2019 Broadcom Inc. All rights reserved.
*/
#include <bcm/types.h>
#include <sal/core/alloc.h>
#include <bcmx/field.h>
#include <bcmx/lport.h>
#include <bcmx/bcmx.h>
#include <bcmx/lplist.h>
#include "bcmx_int.h"
#define BCMX_FIELD_INIT_CHECK BCMX_READY_CHECK
#define BCMX_FIELD_ERROR_CHECK(_unit, _check, _rv) \
BCMX_ERROR_CHECK(_unit, _check, _rv)
#define BCMX_FIELD_SET_ERROR_CHECK(_unit, _check, _rv) \
BCMX_SET_ERROR_CHECK(_unit, _check, _rv)
#define BCMX_FIELD_DELETE_ERROR_CHECK(_unit, _check, _rv) \
BCMX_DELETE_ERROR_CHECK(_unit, _check, _rv)
#define BCMX_FIELD_GET_IS_VALID(_unit, _rv) \
BCMX_ERROR_IS_VALID(_unit, _rv)
static uint32 _bcmx_group_id;
static uint32 _bcmx_entry_id;
static uint32 _bcmx_range_id;
static uint32 _bcmx_stat_id;
/*
* BCMX uses a range of numbers starting at a high value for,
* Group Id, Entry Id, Range Id
*/
#define GROUP_ID_ALLOC (('X'<<24) + (++_bcmx_group_id))
#define ENTRY_ID_ALLOC (('Y'<<24) + (++_bcmx_entry_id))
#define RANGE_ID_ALLOC (('Z'<<24) + (++_bcmx_range_id))
#define STAT_ID_ALLOC (( 1 <<16) + (++_bcmx_stat_id))
/*
* Function:
* bcmx_field_init
* Purpose:
* Initialize field software subsystem
* Parameters:
* None
* Returns:
* BCM_E_EXISTS Field Processor previously initialized
* BCM_E_MEMORY Allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_init(void)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
_bcmx_group_id = 0;
_bcmx_entry_id = 0;
_bcmx_range_id = 0;
_bcmx_stat_id = 0;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_init(bcm_unit);
BCM_IF_ERROR_RETURN(BCMX_FIELD_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_control_set
* Purpose:
* Set control status.
* Parameters:
* control - Control element to set
* status - Status for field module
* Returns:
* BCM_E_INIT - BCM unit not initialized
* BCM_E_NONE - Success
*/
int
bcmx_field_control_set(bcm_field_control_t control,
uint32 state)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_control_set(bcm_unit, control, state);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_control_get
* Purpose:
* Get control status info.
* Parameters:
* control - Control element to get
* status - (OUT) Status of field element
* Returns:
* BCM_E_INIT - BCM unit not initialized
* BCM_E_PARAM - *state pointing to NULL
* BCM_E_NONE - Success
* Notes:
* Get value from first successful call
*/
int
bcmx_field_control_get(bcm_field_control_t control,
uint32 *state)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(state);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_control_get(bcm_unit, control, state);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_group_traverse
* Purpose:
* Traverse all the fp groups in the system, calling a specified
* callback for each one
* Parameters:
* callback - (IN) A pointer to the callback function to call for each fp group
* user_data - (IN) Pointer to user data to supply in the callback
* Returns:
* BCM_E_xxx
* Notes:
*/
int
bcmx_field_group_traverse(bcm_field_group_traverse_cb callback, void *user_data)
{
int unit_cntr; /* Number of devices counter. */
int bcm_unit; /* bcm device iterator. */
int rv; /* Overall operation result. */
BCMX_FIELD_INIT_CHECK;
BCMX_LOCAL_UNIT_ITER(bcm_unit, unit_cntr) {
rv = bcm_field_group_traverse (bcm_unit, callback, user_data);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_group_create
* Purpose:
* Create a field group based on the field group selector flags.
* Parameters:
* qset - Field qualifier set
* pri - Priority within allowable range
* or BCM_FIELD_GROUP_PRIO_ANY to automatically assign a
* priority; each priority value may be used only once
* group - (OUT) Field group ID
* Returns:
* BCM_E_RESOURCE No unused group/slices left OR qset doesn't work on
* hardware
* BCM_E_PARAM Priority out of range (0-15 for FB & ER)
* BCM_E_MEMORY Group memory allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_create(bcm_field_qset_t qset,
int pri,
bcm_field_group_t *group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_field_group_t gid;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(group);
gid = GROUP_ID_ALLOC;
*group = gid;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_create_id(bcm_unit, qset, pri, gid);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_create_id
* Purpose:
* Create a field group based on the field group selector flags
* with a requested ID.
* Parameters:
* qset - Field qualifier set
* pri - Priority within allowable range
* or BCM_FIELD_GROUP_PRIO_ANY to automatically assign a
* priority; each priority value may be used only once
* group - Requested field group ID
* Returns:
* BCM_E_RESOURCE No unused group/slices left
* BCM_E_PARAM Priority out of range (0-15 for FB & ER)
* BCM_E_MEMORY Group memory allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_create_id(bcm_field_qset_t qset,
int pri,
bcm_field_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_create_id(bcm_unit, qset, pri, group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_wlan_create_mode
* Purpose:
* Create a wlan field group based on the field group selector flags
* and the given group mode.
* Parameters:
* qset - Field qualifier set
* pri - Priority within allowable range
* or BCM_FIELD_GROUP_PRIO_ANY to automatically assign a
* priority; each priority value may be used only once
* mode - Group mode (single, double, triple or Auto-wide)
* group - (OUT) Field group ID
* Returns:
* BCM_E_RESOURCE No unused group/slices left OR qset doesn't work on
* hardware
* BCM_E_PARAM Priority out of range (0-15 for FB & ER)
* BCM_E_MEMORY Group memory allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_wlan_create_mode(bcm_field_qset_t qset,
int pri,
bcm_field_group_mode_t mode,
bcm_field_group_t *group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_field_group_t gid;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(group);
gid = GROUP_ID_ALLOC;
*group = gid;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_wlan_create_mode_id(bcm_unit, qset,
pri, mode, gid);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_wlan_create_mode_id
* Purpose:
* Create a wlan field group based on the field group selector flags,
* the given group mode, and the requested group ID.
* Parameters:
* qset - Field qualifier set
* pri - Priority within allowable range
* or BCM_FIELD_GROUP_PRIO_ANY to automatically assign a
* priority; each priority value may be used only once
* mode - Group mode (single, double, triple or Auto-wide)
* group - Requested field group ID
* Returns:
* BCM_E_RESOURCE No unused group/slices left
* BCM_E_PARAM Priority out of range (0-15 for FB & ER)
* BCM_E_MEMORY Group memory allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_wlan_create_mode_id(bcm_field_qset_t qset,
int pri,
bcm_field_group_mode_t mode,
bcm_field_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_wlan_create_mode_id(bcm_unit, qset,
pri, mode, group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_create_mode
* Purpose:
* Create a field group based on the field group selector flags
* and the given group mode.
* Parameters:
* qset - Field qualifier set
* pri - Priority within allowable range
* or BCM_FIELD_GROUP_PRIO_ANY to automatically assign a
* priority; each priority value may be used only once
* mode - Group mode (single, double, triple or Auto-wide)
* group - (OUT) Field group ID
* Returns:
* BCM_E_RESOURCE No unused group/slices left OR qset doesn't work on
* hardware
* BCM_E_PARAM Priority out of range (0-15 for FB & ER)
* BCM_E_MEMORY Group memory allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_create_mode(bcm_field_qset_t qset,
int pri,
bcm_field_group_mode_t mode,
bcm_field_group_t *group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_field_group_t gid;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(group);
gid = GROUP_ID_ALLOC;
*group = gid;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_create_mode_id(bcm_unit, qset,
pri, mode, gid);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_create_mode_id
* Purpose:
* Create a field group based on the field group selector flags,
* the given group mode, and the requested group ID.
* Parameters:
* qset - Field qualifier set
* pri - Priority within allowable range
* or BCM_FIELD_GROUP_PRIO_ANY to automatically assign a
* priority; each priority value may be used only once
* mode - Group mode (single, double, triple or Auto-wide)
* group - Requested field group ID
* Returns:
* BCM_E_RESOURCE No unused group/slices left
* BCM_E_PARAM Priority out of range (0-15 for FB & ER)
* BCM_E_MEMORY Group memory allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_create_mode_id(bcm_field_qset_t qset,
int pri,
bcm_field_group_mode_t mode,
bcm_field_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_create_mode_id(bcm_unit, qset,
pri, mode, group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_port_create_mode
* Purpose:
* Create a field group based on the field group selector flags,
* given group mode and the given logical port.
* Parameters:
* port - Logical port number where group is defined
* qset - Field qualifier set
* pri - Priority within allowable range
* or BCM_FIELD_GROUP_PRIO_ANY to automatically assign a
* priority; each priority value may be used only once
* mode - Group mode (single, double, triple or Auto-wide)
* group - (OUT) Field group ID
* Returns:
* BCM_E_RESOURCE No unused group/slices left OR qset doesn't work on
* hardware
* BCM_E_PARAM Priority out of range (0-15 for FB & ER)
* BCM_E_MEMORY Group memory allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_port_create_mode(bcmx_lport_t port,
bcm_field_qset_t qset,
int pri,
bcm_field_group_mode_t mode,
bcm_field_group_t *group)
{
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(group);
*group = GROUP_ID_ALLOC;
return bcmx_field_group_port_create_mode_id(port, qset, pri, mode, *group);
}
/*
* Function:
* bcmx_field_group_port_create_mode_id
* Purpose:
* Create a field group based on the field group selector flags,
* given group mode, logical port, and requested group ID.
* Parameters:
* port - Logical port number where group is defined
* qset - Field qualifier set
* pri - Priority within allowable range
* or BCM_FIELD_GROUP_PRIO_ANY to automatically assign a
* priority; each priority value may be used only once
* mode - Group mode (single, double, triple or Auto-wide)
* group - Requested field group ID
* Returns:
* BCM_E_RESOURCE No unused group/slices left
* BCM_E_PARAM Priority out of range (0-15 for FB & ER)
* BCM_E_MEMORY Group memory allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_port_create_mode_id(bcmx_lport_t port,
bcm_field_qset_t qset,
int pri,
bcm_field_group_mode_t mode,
bcm_field_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int bcm_unit;
bcm_port_t bcm_port;
bcm_pbmp_t pbmp;
int i, unit;
BCMX_FIELD_INIT_CHECK;
BCM_IF_ERROR_RETURN
(_bcmx_dest_to_unit_port(port, &bcm_unit, &bcm_port,
BCMX_DEST_CONVERT_DEFAULT));
/* Create group in unit where given port resides */
tmp_rv = bcm_field_group_port_create_mode_id(bcm_unit, bcm_port, qset,
pri, mode, group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
/* Create group with null ports on rest of units */
BCM_PBMP_CLEAR(pbmp);
BCMX_UNIT_ITER(unit, i) {
if (unit == bcm_unit) {
continue;
}
tmp_rv = bcm_field_group_ports_create_mode_id(unit, pbmp, qset,
pri, mode, group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_ports_create_mode
* Purpose:
* Create a field group based on the field group selector flags,
* given group mode and the given logical port list.
* Parameters:
* lplist - Logical port list for which the group is defined
* qset - Field qualifier set
* pri - Priority within allowable range
* or BCM_FIELD_GROUP_PRIO_ANY to automatically assign a
* priority; each priority value may be used only once
* mode - Group mode (single, double, triple or Auto-wide)
* group - (OUT) Field group ID
* Returns:
* BCM_E_RESOURCE No unused group/slices left OR qset doesn't work on
* hardware
* BCM_E_PARAM Priority out of range (0-15 for FB & ER)
* BCM_E_MEMORY Group memory allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_ports_create_mode(bcmx_lplist_t lplist,
bcm_field_qset_t qset,
int pri,
bcm_field_group_mode_t mode,
bcm_field_group_t *group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_pbmp_t pbmp;
bcm_field_group_t gid;
BCMX_FIELD_INIT_CHECK;
if (bcmx_lplist_is_null(&lplist)) {
return BCM_E_PARAM;
}
BCMX_PARAM_NULL_CHECK(group);
gid = GROUP_ID_ALLOC;
*group = gid;
BCMX_UNIT_ITER(bcm_unit, i) {
BCMX_LPLIST_TO_PBMP(lplist, bcm_unit, pbmp);
tmp_rv = bcm_field_group_ports_create_mode_id(bcm_unit, pbmp, qset,
pri, mode, gid);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_ports_create_mode_id
* Purpose:
* Create a field group based on the field group selector flags,
* given group mode, logical port list, and requested group ID.
* Parameters:
* lplist - Logical port list for which the group is defined
* qset - Field qualifier set
* pri - Priority within allowable range
* or BCM_FIELD_GROUP_PRIO_ANY to automatically assign a
* priority; each priority value may be used only once
* mode - Group mode (single, double, triple or Auto-wide)
* group - Requested field group ID
* Returns:
* BCM_E_RESOURCE No unused group/slices left OR qset doesn't work on
* hardware
* BCM_E_PARAM Priority out of range (0-15 for FB & ER)
* BCM_E_MEMORY Group memory allocation failure
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_ports_create_mode_id(bcmx_lplist_t lplist,
bcm_field_qset_t qset,
int pri,
bcm_field_group_mode_t mode,
bcm_field_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_pbmp_t pbmp;
BCMX_FIELD_INIT_CHECK;
if (bcmx_lplist_is_null(&lplist)) {
return BCM_E_PARAM;
}
BCMX_UNIT_ITER(bcm_unit, i) {
BCMX_LPLIST_TO_PBMP(lplist, bcm_unit, pbmp);
tmp_rv = bcm_field_group_ports_create_mode_id(bcm_unit, pbmp, qset,
pri, mode, group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_mode_get
* Purpose:
* Get the mode for the specified field group
* Parameters:
* group - Field group ID
* mode - (OUT) Field group mode
* Returns:
* BCM_E_NOT_FOUND Field Group ID not found
* BCM_E_PARAM mode is NULL
* BCM_E_XXX Error code
* BCM_E_NONE
* Notes:
* Get value from first successful call
*/
int
bcmx_field_group_mode_get(bcm_field_group_t group,
bcm_field_group_mode_t *mode)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(mode);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_group_mode_get(bcm_unit, group, mode);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_group_set
* Purpose:
* Update a previously created field group based on the field
* group selector flags
* Parameters:
* group - Field group ID
* qset - Field qualifier set
* Returns:
* BCM_E_NOT_FOUND Group ID not found
* BCM_E_XXX Error code
* BCM_E_NONE
* Notes:
* If no entry exist that use this group then updates are always
* permitted.
* If entries exist that use this group then updates are permitted
* only if it can be satisfied with the current selection of
* (f0, f1, f2, f3) field selector encodings.
*/
int
bcmx_field_group_set(bcm_field_group_t group,
bcm_field_qset_t qset)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_set(bcm_unit, group, qset);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_get
* Purpose:
* Get the qualifier set for a previously created field group
* Parameters:
* group - Field group ID
* qset - (OUT) Field qualifier set
* Returns:
* BCM_E_NOT_FOUND Field Group ID not found
* BCM_E_PARAM qset is NULL
* BCM_E_NONE
* Notes:
* Get value from first successful call
*/
int
bcmx_field_group_get(bcm_field_group_t group,
bcm_field_qset_t *qset)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(qset);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_group_get(bcm_unit, group, qset);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_group_destroy
* Purpose:
* Delete a field group
* Parameters:
* group - Field group ID
* Returns:
* BCM_E_FAIL Entries not destroyed yet
* BCM_E_NONE
* Notes:
* All entries that uses this group should have been destroyed
* before calling this routine.
* Operation will fail if entries exist that uses this template
*/
int
bcmx_field_group_destroy(bcm_field_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_destroy(bcm_unit, group);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_enable_set
* Purpose:
* Enable or disable packet lookup on the given group.
* Parameters:
* group - Field group ID
* enable - Packet lookup is enable(if !=0) or disable(if == 0) on group
* Returns:
* BCM_E_NOT_FOUND Field Group ID not found
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_enable_set(bcm_field_group_t group,
int enable)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_enable_set(bcm_unit, group, enable);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_enable_get
* Purpose:
* Get the packet lookup enable/disable state on the given group.
* Parameters:
* group - Field group ID
* enable - (OUT) Packet lookup enable/disable state of group
* Returns:
* BCM_E_NOT_FOUND Field Group ID not found
* BCM_E_XXX Error code
* BCM_E_NONE
* Notes:
* Get value from first successful call
*/
int
bcmx_field_group_enable_get(bcm_field_group_t group,
int *enable)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(enable);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_group_enable_get(bcm_unit, group, enable);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_group_install
* Purpose:
* Install all entries of a field group into the hardware tables.
* Parameters:
* group - Field group ID
* Returns:
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_group_install(bcm_field_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_install(bcm_unit, group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_remove
* Purpose:
* Remove all entries of a field group from the hardware table.
* Parameters:
* group - Field group ID
* Returns:
* BCM_E_XXX
* BCM_E_NONE
* Notes:
* This does not destroy the group or its entries; it uninstalls them from
* the hardware tables.
* Destroy a group using bcmx_field_group_destroy()
*/
int
bcmx_field_group_remove(bcm_field_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_remove(bcm_unit, group);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_range_create
* Purpose:
* Allocate a port range checker
* Parameters:
* range - (OUT) Range ID
* flags - One or more of BCM_FIELD_RANGE_xxx flags
* min - Lower bounds of range to be checked
* max - Upper bounds of range to be checked
* Returns:
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_range_create(bcm_field_range_t *range,
uint32 flags,
bcm_l4_port_t min,
bcm_l4_port_t max)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_field_range_t range_id;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(range);
range_id = RANGE_ID_ALLOC;
*range = range_id;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_range_create_id(bcm_unit, range_id,
flags, min, max);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_range_create_id
* Purpose:
* Allocate a port range checker with requested ID.
* Parameters:
* range - Range check ID to use
* flags - One or more of BCM_FIELD_RANGE_xxx flags
* min - Lower bounds of range to be checked
* max - Upper bounds of range to be checked
* Returns:
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_range_create_id(bcm_field_range_t range,
uint32 flags,
bcm_l4_port_t min,
bcm_l4_port_t max)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_range_create_id(bcm_unit, range,
flags, min, max);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function: bcmx_field_range_group_create
*
* Purpose:
* Allocate an interface group range checker and set its parameters.
*
* Parameters:
* range - (OUT) Range check ID, will not be zero
* flags - One or more of BCM_FIELD_RANGE_* flags
* min - Lower bounds of range to be checked, inclusive
* max - Upper bounds of range to be checked, inclusive
* group - L3 interface group number
*
* Returns:
* BCM_E_XXX - Error code
* BCM_E_NONE - Success
*/
int
bcmx_field_range_group_create(bcm_field_range_t *range,
uint32 flags,
bcm_l4_port_t min,
bcm_l4_port_t max,
bcm_if_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(range);
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_range_group_create(bcm_unit, range,
flags, min, max, group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function: bcmx_field_range_group_create_id
*
* Purpose:
* Allocate an interface group range checker with requested ID
* and set its parameters.
*
* Parameters:
* range - Range check ID to use
* flags - One or more of BCM_FIELD_RANGE_* flags
* min - Lower bounds of range to be checked, inclusive
* max - Upper bounds of range to be checked, inclusive
* group - L3 interface group number
*
* Returns:
* BCM_E_XXX - Error code
* BCM_E_NONE - Success
*/
int
bcmx_field_range_group_create_id(bcm_field_range_t range,
uint32 flags,
bcm_l4_port_t min,
bcm_l4_port_t max,
bcm_if_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_range_group_create_id(bcm_unit, range,
flags, min, max, group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_range_get
* Purpose:
* Get the TCP/UDP port range check setup
* Parameters:
* range - Range ID
* flags - (OUT) One or more of BCM_FIELD_RANGE_xxx flags
* min - (OUT) Lower bounds of range to be checked
* max - (OUT) Upper bounds of range to be checked
* Returns:
* BCM_E_XXX Error code
* BCM_E_NONE
* Notes:
* Get value from first successful call
*/
int
bcmx_field_range_get(bcm_field_range_t range,
uint32 *flags,
bcm_l4_port_t *min,
bcm_l4_port_t *max)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(flags);
BCMX_PARAM_NULL_CHECK(min);
BCMX_PARAM_NULL_CHECK(max);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_range_get(bcm_unit, range, flags, min, max);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_range_destroy
* Purpose:
* Deallocate a range
* Parameters:
* range - Range ID
* Returns:
* BCM_E_XXX Error code
* BCM_E_NONE
* Notes:
* Get value from first successful call
*/
int
bcmx_field_range_destroy(bcm_field_range_t range)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_range_destroy(bcm_unit, range);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_create
* Purpose:
* Create a blank entry group based on a group.
* Parameters:
* group - Field group ID
* entry - (OUT) New entry ID
* Returns:
* BCM_E_EXISTS Entry ID already in use
* BCM_E_NOT_FOUND Group ID not found
* BCM_E_MEMORY allocation failure
* BCM_E_NONE
*/
int
bcmx_field_entry_create(bcm_field_group_t group,
bcm_field_entry_t *entry)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_field_entry_t eid;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(entry);
eid = ENTRY_ID_ALLOC;
*entry = eid;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_create_id(bcm_unit, group, eid);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_create_id
* Purpose:
* Create a blank entry group with requested ID based on a group.
* Parameters:
* group - Field group ID
* entry - Requested entry ID
* Returns:
* BCM_E_EXISTS Entry ID already in use
* BCM_E_NOT_FOUND Group ID not found
* BCM_E_MEMORY allocation failure
* BCM_E_NONE
*/
int
bcmx_field_entry_create_id(bcm_field_group_t group,
bcm_field_entry_t entry)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_create_id(bcm_unit, group, entry);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_multi_get
* Purpose:
* Gets an array of a group's entry IDs
* Parameters:
* group - Field group ID.
* entry_size - Maximum number of entries to return. Set to 0
* to get the number of entries available.
* entry_array - (OUT) Pointer to a buffer to fill with the array of
* entry IDs. Ignored if entry_size is 0.
* entry_count - (OUT) Returns the number of entries returned in the
* array, or if entry_size was 0, the number of
* entries available.
* Returns:
* BCM_E_INIT - Unit not initialized
* BCM_E_NOT_FOUND - Group ID not found
* BCM_E_NONE - Success
* Notes:
* Assumes homogeneuous systems and all devices in stack
* has the same field groups/entries successfully installed.
*/
int
bcmx_field_entry_multi_get(bcm_field_group_t group,
int entry_size,
bcm_field_entry_t *entry_array,
int *entry_count)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(entry_count);
/*
* No need to gather entries from all units. BCMX assumes
* that field groups/entries were created with BCMX APIs.
*/
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_entry_multi_get(bcm_unit, group, entry_size,
entry_array, entry_count);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_entry_destroy
* Purpose:
* Destroy an entry
* Parameters:
* entry - Entry ID
* Returns:
* BCM_E_INTERNAL Null group found
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_entry_destroy(bcm_field_entry_t entry)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_destroy(bcm_unit, entry);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_destroy_all
* Purpose:
* Destroy all entries
* Parameters:
* None
* Returns:
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_entry_destroy_all(void)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_destroy_all(bcm_unit);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_copy
* Purpose:
* Create a copy of an existing entry
* Parameters:
* src_entry - Entry to copy
* dst_entry - (OUT) New entry
* Returns:
* BCM_E_NOT_FOUND Source entry not found
* BCM_E_INTERNAL Newly created entry not found.
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_entry_copy(bcm_field_entry_t src_entry,
bcm_field_entry_t *dst_entry)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_field_entry_t eid;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(dst_entry);
eid = ENTRY_ID_ALLOC;
*dst_entry = eid;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_copy_id(bcm_unit, src_entry, eid);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_install
* Purpose:
* Install entry into the hardware tables
* Parameters:
* entry - Entry to install
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_INTERNAL No group for entry ID
* BCM_E_XXX Error code
* BCM_E_NONE
* Notes:
* Qualifications should be made and actions should be added
* prior to installing the entry.
* The bcm_field_entry_t object is not consumed or destroyed.
* It can be used to remove or update the entry.
*/
int
bcmx_field_entry_install(bcm_field_entry_t entry)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_install(bcm_unit, entry);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_reinstall
* Purpose:
* Re-install entry into the hardware tables
* Parameters:
* entry - Entry to install
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_INTERNAL No group for entry ID
* BCM_E_XXX Error code
* BCM_E_NONE
*
* Notes:
* Reinstallation may only be used to change the actions for
* an installed entry without having to remove and re-add the
* entry.
*/
int
bcmx_field_entry_reinstall(bcm_field_entry_t entry)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_reinstall(bcm_unit, entry);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_remove
* Purpose:
* Remove entry from the hardware tables
* Parameters:
* entry - Entry to remove
* Returns:
* BCM_E_XXX
* BCM_E_NONE
* Notes:
* This does not destroy the entry; it uninstalls it from
* the hardware tables.
* Destroy a entry using bcmx_field_entry_destroy()
*/
int
bcmx_field_entry_remove(bcm_field_entry_t entry)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_remove(bcm_unit, entry);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function: bcmx_field_entry_prio_get
*
* Purpose:
* Gets the priority within the group of the entry.
*
* Parameters:
* entry - Field entry to operate on
* prio - (OUT) priority of entry
*
* Returns:
* BCM_E_NONE - Success
* BCM_E_PARAM - prio pointing to NULL
* BCM_E_NOT_FOUND - Entry ID not found
*/
int
bcmx_field_entry_prio_get(bcm_field_entry_t entry,
int *prio)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(prio);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_entry_prio_get(bcm_unit, entry, prio);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function: bcmx_field_entry_prio_set
*
* Purpose:
* Sets the priority for the given entry.
*
* Parameters:
* entry - Field entry to operate on
* prio - Priority of entry
*
* Returns:
* BCM_E_NONE Success
*/
int
bcmx_field_entry_prio_set(bcm_field_entry_t entry,
int prio)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_prio_set(bcm_unit, entry, prio);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_policer_attach
*/
int
bcmx_field_entry_policer_attach(bcm_field_entry_t entry_id, int level,
bcm_policer_t policer_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_policer_attach(bcm_unit, entry_id,
level, policer_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_policer_detach
*/
int
bcmx_field_entry_policer_detach(bcm_field_entry_t entry_id, int level)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_policer_detach(bcm_unit, entry_id,
level);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_policer_detach_all
*/
int
bcmx_field_entry_policer_detach_all(bcm_field_entry_t entry_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_policer_detach_all(bcm_unit, entry_id);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_policer_get
*/
int
bcmx_field_entry_policer_get(bcm_field_entry_t entry_id, int level,
bcm_policer_t *policer_id)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(policer_id);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_entry_policer_get(bcm_unit, entry_id, level,
policer_id);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_resync
* Purpose:
* Invalidate HW FP entries that have not been replayed after warm boot.
* Can be used in general to clear entries that are in HW but not in SW.
* Parameters:
* None
* Returns:
* BCM_E_INIT - Unit not initialized
* BCM_E_XXX - Other errors
* BCM_E_NONE - Success
*/
int
bcmx_field_resync(void)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_resync(bcm_unit);
BCM_IF_ERROR_RETURN(BCMX_FIELD_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_clear
* Purpose:
* Remove all field qualifications from a filter entry
* Parameters:
* entry - Field entry to operate on
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_XXX Error code
* BCM_E_NONE
*/
int
bcmx_field_qualify_clear(bcm_field_entry_t entry)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_clear(bcm_unit, entry);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InPort
* Purpose:
* Add single logical port qualification to a filter entry
* Parameters:
* entry - Field entry to operate on
* port - Logical port
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_INTERNAL No group exists for entry ID
* BCM_E_XXX
*/
int
bcmx_field_qualify_InPort(bcm_field_entry_t entry,
bcmx_lport_t port)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit, unit;
bcm_port_t data, in_port;
bcm_port_t mask;
BCMX_FIELD_INIT_CHECK;
BCM_IF_ERROR_RETURN
(_bcmx_dest_to_unit_port(port, &unit, &in_port,
BCMX_DEST_CONVERT_DEFAULT));
mask = BCM_FIELD_EXACT_MATCH_MASK;
/*
* Set data to zero in devices that do not contain port
* in order to override default value (which would match all ports)
*/
BCMX_UNIT_ITER(bcm_unit, i) {
if (bcm_unit == unit) {
data = in_port;
} else {
data = 0;
}
tmp_rv = bcm_field_qualify_InPort(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_OutPort
* Purpose:
* Add single logical output port qualification to a filter entry
* Parameters:
* entry - Field entry to operate on
* port - Logical port
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_INTERNAL No group exists for entry ID
* BCM_E_XXX
*/
int
bcmx_field_qualify_OutPort(bcm_field_entry_t entry,
bcmx_lport_t port)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit, unit;
bcm_port_t data, out_port;
bcm_port_t mask;
BCMX_FIELD_INIT_CHECK;
BCM_IF_ERROR_RETURN
(_bcmx_dest_to_unit_port(port, &unit, &out_port,
BCMX_DEST_CONVERT_DEFAULT));
mask = BCM_FIELD_EXACT_MATCH_MASK;
/*
* Set data to zero in devices that do not contain port
* in order to override default value (which would match all ports)
*/
BCMX_UNIT_ITER(bcm_unit, i) {
if (bcm_unit == unit) {
data = out_port;
} else {
data = 0;
}
tmp_rv = bcm_field_qualify_OutPort(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InPorts
* Purpose:
* Add the ingress ports qualification to a filter entry
* Parameters:
* entry - Field entry to operate on
* lplist - Logical ingress port list
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_INTERNAL No group exists for entry ID
* BCM_E_XXX
*/
int
bcmx_field_qualify_InPorts(bcm_field_entry_t entry,
bcmx_lplist_t lplist)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_pbmp_t data;
bcm_pbmp_t mask;
BCMX_FIELD_INIT_CHECK;
BCM_PBMP_CLEAR(mask);
BCM_PBMP_NEGATE(mask, mask);
BCMX_UNIT_ITER(bcm_unit, i) {
BCMX_LPLIST_TO_PBMP(lplist, bcm_unit, data);
tmp_rv = bcm_field_qualify_InPorts(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_OutPorts
*/
int
bcmx_field_qualify_OutPorts(bcm_field_entry_t entry,
bcmx_lplist_t lplist)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_pbmp_t data;
bcm_pbmp_t mask;
BCMX_FIELD_INIT_CHECK;
BCM_PBMP_CLEAR(mask);
BCM_PBMP_NEGATE(mask, mask);
BCMX_UNIT_ITER(bcm_unit, i) {
BCMX_LPLIST_TO_PBMP(lplist, bcm_unit, data);
tmp_rv = bcm_field_qualify_OutPorts(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Drop
*/
int
bcmx_field_qualify_Drop(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Drop(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcPort
* Purpose:
* Add the source logical port qualification to a filter entry
* Parameters:
* entry - Field entry to operate on
* port - Source logical port
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_INTERNAL No group exists for entry ID
* BCM_E_XXX
*/
int
bcmx_field_qualify_SrcPort(bcm_field_entry_t entry,
bcmx_lport_t port)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_module_t data_modid, mask_modid;
bcm_port_t data_port, mask_port;
BCMX_FIELD_INIT_CHECK;
BCM_IF_ERROR_RETURN
(_bcmx_dest_to_modid_port(port,
&data_modid, &data_port,
BCMX_DEST_CONVERT_DEFAULT));
mask_modid = mask_port = BCM_FIELD_EXACT_MATCH_MASK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcPort(bcm_unit, entry,
data_modid, mask_modid,
data_port, mask_port);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcTrunk
* Purpose:
* Add the source trunk group ID qualification to a filter entry
* Parameters:
* entry - Field entry to operate on
* tid - Source trunk group ID
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_INTERNAL No group exists for entry ID
* BCM_E_XXX
*/
int
bcmx_field_qualify_SrcTrunk(bcm_field_entry_t entry,
bcm_trunk_t tid)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_port_t data;
bcm_port_t mask;
BCMX_FIELD_INIT_CHECK;
data = tid;
mask = BCM_FIELD_EXACT_MATCH_MASK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcTrunk(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstPort
* Purpose:
* Add the destination logical port qualification to a filter entry
* Parameters:
* entry - Field entry to operate on
* port - Destination logical port
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_INTERNAL No group exists for entry ID
* BCM_E_XXX
*/
int
bcmx_field_qualify_DstPort(bcm_field_entry_t entry,
bcmx_lport_t port)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_module_t data_modid, mask_modid;
bcm_port_t data_port, mask_port;
BCMX_FIELD_INIT_CHECK;
BCM_IF_ERROR_RETURN
(_bcmx_dest_to_modid_port(port,
&data_modid, &data_port,
BCMX_DEST_CONVERT_DEFAULT));
mask_modid = mask_port = BCM_FIELD_EXACT_MATCH_MASK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstPort(bcm_unit, entry,
data_modid, mask_modid,
data_port, mask_port);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstTrunk
* Purpose:
* Add the destination trunk group ID qualification to a filter entry
* Parameters:
* entry - Field entry to operate on
* tid - Destination trunk group ID
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_INTERNAL No group exists for entry ID
* BCM_E_XXX
*/
int
bcmx_field_qualify_DstTrunk(bcm_field_entry_t entry,
bcm_trunk_t tid)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_port_t data;
bcm_port_t mask;
BCMX_FIELD_INIT_CHECK;
data = tid;
mask = BCM_FIELD_EXACT_MATCH_MASK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstTrunk(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_XXX (class of routines)
* Purpose:
* Add a field qualification to a filter entry.
* Parameters:
* entry - Field entry to operate on
* data - Data to qualify with (type varies)
* mask - Mask to qualify with (type is same as for data)
* Returns:
* BCM_E_NOT_FOUND Entry ID not found.
* BCM_E_INTERNAL No group exists for entry ID.
* BCM_E_XXX
*/
/*
* Function:
* bcmx_field_qualify_L4SrcPort
*/
int
bcmx_field_qualify_L4SrcPort(bcm_field_entry_t entry,
bcm_l4_port_t data, bcm_l4_port_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L4SrcPort(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L4DstPort
*/
int
bcmx_field_qualify_L4DstPort(bcm_field_entry_t entry,
bcm_l4_port_t data, bcm_l4_port_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L4DstPort(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_OuterVlan
*/
int
bcmx_field_qualify_OuterVlan(bcm_field_entry_t entry,
bcm_vlan_t data, bcm_vlan_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_OuterVlan(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_OuterVlanId
*/
int
bcmx_field_qualify_OuterVlanId(bcm_field_entry_t entry,
bcm_vlan_t data, bcm_vlan_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_OuterVlanId(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_ForwardingVlanId
*/
int
bcmx_field_qualify_ForwardingVlanId(bcm_field_entry_t entry,
bcm_vlan_t data, bcm_vlan_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_ForwardingVlanId(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_OuterVlanPri
*/
int
bcmx_field_qualify_OuterVlanPri(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_OuterVlanPri(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_OuterVlanCfi
*/
int
bcmx_field_qualify_OuterVlanCfi(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_OuterVlanCfi(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerVlan
*/
int
bcmx_field_qualify_InnerVlan(bcm_field_entry_t entry,
bcm_vlan_t data, bcm_vlan_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerVlan(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerVlanId
*/
int
bcmx_field_qualify_InnerVlanId(bcm_field_entry_t entry,
bcm_vlan_t data, bcm_vlan_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerVlanId(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerVlanPri
*/
int
bcmx_field_qualify_InnerVlanPri(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerVlanPri(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerVlanCfi
*/
int
bcmx_field_qualify_InnerVlanCfi(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerVlanCfi(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_EtherType
*/
int
bcmx_field_qualify_EtherType(bcm_field_entry_t entry,
uint16 data, uint16 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_EtherType(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_IpProtocol
*/
int
bcmx_field_qualify_IpProtocol(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_IpProtocol(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_IpInfo
*/
int
bcmx_field_qualify_IpInfo(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_IpInfo(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_PacketRes
*/
int
bcmx_field_qualify_PacketRes(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_PacketRes(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcIp
*/
int
bcmx_field_qualify_SrcIp(bcm_field_entry_t entry,
bcm_ip_t data, bcm_ip_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcIp(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstIp
*/
int
bcmx_field_qualify_DstIp(bcm_field_entry_t entry,
bcm_ip_t data, bcm_ip_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstIp(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DSCP
*/
int
bcmx_field_qualify_DSCP(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DSCP(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Tos
*/
int
bcmx_field_qualify_Tos(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Tos(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_IpFlags
*/
int
bcmx_field_qualify_IpFlags(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_IpFlags(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_TcpControl
*/
int
bcmx_field_qualify_TcpControl(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_TcpControl(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Ttl
*/
int
bcmx_field_qualify_Ttl(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Ttl(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_RangeCheck
*/
int
bcmx_field_qualify_RangeCheck(bcm_field_entry_t entry,
int range, int result)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_RangeCheck(bcm_unit, entry, range, result);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcIp6
*/
int
bcmx_field_qualify_SrcIp6(bcm_field_entry_t entry,
bcm_ip6_t data, bcm_ip6_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcIp6(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstIp6
*/
int
bcmx_field_qualify_DstIp6(bcm_field_entry_t entry,
bcm_ip6_t data, bcm_ip6_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstIp6(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcIp6High
*/
int
bcmx_field_qualify_SrcIp6High(bcm_field_entry_t entry,
bcm_ip6_t data, bcm_ip6_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcIp6High(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstIp6High
*/
int
bcmx_field_qualify_DstIp6High(bcm_field_entry_t entry,
bcm_ip6_t data, bcm_ip6_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstIp6High(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstIp6Low
*/
int
bcmx_field_qualify_DstIp6Low(bcm_field_entry_t entry,
bcm_ip6_t data, bcm_ip6_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstIp6Low(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcIp6Low
*/
int
bcmx_field_qualify_SrcIp6Low(bcm_field_entry_t entry,
bcm_ip6_t data, bcm_ip6_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcIp6Low(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Ip6NextHeader
*/
int
bcmx_field_qualify_Ip6NextHeader(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Ip6NextHeader(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Ip6TrafficClass
*/
int
bcmx_field_qualify_Ip6TrafficClass(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Ip6TrafficClass(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Ip6FlowLabel
*/
int
bcmx_field_qualify_Ip6FlowLabel(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Ip6FlowLabel(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Ip6HopLimit
*/
int
bcmx_field_qualify_Ip6HopLimit(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Ip6HopLimit(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcMac
*/
int
bcmx_field_qualify_SrcMac(bcm_field_entry_t entry,
bcm_mac_t data, bcm_mac_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcMac(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstMac
*/
int
bcmx_field_qualify_DstMac(bcm_field_entry_t entry,
bcm_mac_t data, bcm_mac_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstMac(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstClassL2
*/
int
bcmx_field_qualify_DstClassL2(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstClassL2(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstClassL3
*/
int
bcmx_field_qualify_DstClassL3(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstClassL3(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstClassField
*/
int
bcmx_field_qualify_DstClassField(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstClassField(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcClassL2
*/
int
bcmx_field_qualify_SrcClassL2(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcClassL2(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcClassL3
*/
int
bcmx_field_qualify_SrcClassL3(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcClassL3(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcClassField
*/
int
bcmx_field_qualify_SrcClassField(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcClassField(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_IpType
*/
int
bcmx_field_qualify_IpType(bcm_field_entry_t entry,
bcm_field_IpType_t type)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_IpType(bcm_unit, entry, type);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerIpType
*/
int
bcmx_field_qualify_InnerIpType(bcm_field_entry_t entry,
bcm_field_IpType_t type)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerIpType(bcm_unit, entry, type);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_ForwardingType
*/
int
bcmx_field_qualify_ForwardingType(bcm_field_entry_t entry,
bcm_field_ForwardingType_t type)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_ForwardingType(bcm_unit, entry, type);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L2Format
*/
int
bcmx_field_qualify_L2Format(bcm_field_entry_t entry,
bcm_field_L2Format_t type)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L2Format(bcm_unit, entry, type);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_VlanFormat
*/
int
bcmx_field_qualify_VlanFormat(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_VlanFormat(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_TranslatedVlanFormat
*/
int
bcmx_field_qualify_TranslatedVlanFormat(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_TranslatedVlanFormat(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_MHOpcode
*/
int
bcmx_field_qualify_MHOpcode(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_MHOpcode(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Decap
*/
int
bcmx_field_qualify_Decap(bcm_field_entry_t entry,
bcm_field_decap_t decap)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Decap(bcm_unit, entry, decap);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_HiGig
*/
int
bcmx_field_qualify_HiGig(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_HiGig(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstHiGig
* Purpose:
* Qualify on packets destined to higig port.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (IN) Qualifier match data.
* mask - (IN) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstHiGig(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstHiGig(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InterfaceClassL2
*/
int
bcmx_field_qualify_InterfaceClassL2(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InterfaceClassL2(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InterfaceClassL3
*/
int
bcmx_field_qualify_InterfaceClassL3(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InterfaceClassL3(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InterfaceClassPort
*/
int
bcmx_field_qualify_InterfaceClassPort(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InterfaceClassPort(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_IpProtocolCommon
*/
int
bcmx_field_qualify_IpProtocolCommon(bcm_field_entry_t entry,
bcm_field_IpProtocolCommon_t protocol)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_IpProtocolCommon(bcm_unit, entry,
protocol);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerIpProtocolCommon
*/
int
bcmx_field_qualify_InnerIpProtocolCommon(bcm_field_entry_t entry,
bcm_field_IpProtocolCommon_t protocol)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerIpProtocolCommon(bcm_unit, entry,
protocol);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Snap
*/
int
bcmx_field_qualify_Snap(bcm_field_entry_t entry,
bcm_field_snap_header_t data,
bcm_field_snap_header_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Snap(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Llc
*/
int
bcmx_field_qualify_Llc(bcm_field_entry_t entry,
bcm_field_llc_header_t data,
bcm_field_llc_header_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Llc(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerTpid
*/
int
bcmx_field_qualify_InnerTpid(bcm_field_entry_t entry,
uint16 tpid)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerTpid(bcm_unit, entry, tpid);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_OuterTpid
*/
int
bcmx_field_qualify_OuterTpid(bcm_field_entry_t entry,
uint16 tpid)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_OuterTpid(bcm_unit, entry, tpid);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L3Routable
*/
int
bcmx_field_qualify_L3Routable(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L3Routable(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_IpFrag
*/
int bcmx_field_qualify_IpFrag(bcm_field_entry_t entry,
bcm_field_IpFrag_t frag_info)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_IpFrag(bcm_unit, entry, frag_info);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Vrf
*/
int
bcmx_field_qualify_Vrf(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Vrf(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L3Ingress
*/
int
bcmx_field_qualify_L3Ingress(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L3Ingress(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Vpn
*/
int
bcmx_field_qualify_Vpn(bcm_field_entry_t entry,
bcm_vpn_t data, bcm_vpn_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Vpn(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_ExtensionHeaderType
*/
int
bcmx_field_qualify_ExtensionHeaderType(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_ExtensionHeaderType(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_ExtensionHeaderSubCode
*/
int
bcmx_field_qualify_ExtensionHeaderSubCode(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_ExtensionHeaderSubCode(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_ExtensionHeader2Type
*/
int
bcmx_field_qualify_ExtensionHeader2Type(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_ExtensionHeader2Type(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L4Ports
*/
int bcmx_field_qualify_L4Ports(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L4Ports(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_MirrorCopy
*/
int
bcmx_field_qualify_MirrorCopy(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_MirrorCopy(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_TunnelTerminated
*/
int
bcmx_field_qualify_TunnelTerminated(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_TunnelTerminated(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_MplsTerminated
*/
int
bcmx_field_qualify_MplsTerminated(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_MplsTerminated(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerSrcIp
*/
int
bcmx_field_qualify_InnerSrcIp(bcm_field_entry_t entry,
bcm_ip_t data, bcm_ip_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerSrcIp(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerDstIp
*/
int
bcmx_field_qualify_InnerDstIp(bcm_field_entry_t entry,
bcm_ip_t data, bcm_ip_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerDstIp(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerSrcIp6
*/
int
bcmx_field_qualify_InnerSrcIp6(bcm_field_entry_t entry,
bcm_ip6_t data, bcm_ip6_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerSrcIp6(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerDstIp6
*/
int bcmx_field_qualify_InnerDstIp6(bcm_field_entry_t entry,
bcm_ip6_t data, bcm_ip6_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerDstIp6(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerSrcIp6High
*/
int
bcmx_field_qualify_InnerSrcIp6High(bcm_field_entry_t entry,
bcm_ip6_t data, bcm_ip6_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerSrcIp6High(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerDstIp6High
*/
int
bcmx_field_qualify_InnerDstIp6High(bcm_field_entry_t entry,
bcm_ip6_t data, bcm_ip6_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerDstIp6High(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerTtl
*/
int
bcmx_field_qualify_InnerTtl(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerTtl(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerTos
*/
int
bcmx_field_qualify_InnerTos(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerTos(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerDSCP
*/
int
bcmx_field_qualify_InnerDSCP(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerDSCP(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerIpProtocol
*/
int
bcmx_field_qualify_InnerIpProtocol(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerIpProtocol(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerIpFrag
*/
int
bcmx_field_qualify_InnerIpFrag(bcm_field_entry_t entry,
bcm_field_IpFrag_t frag_info)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerIpFrag(bcm_unit, entry, frag_info);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DosAttack
*/
int
bcmx_field_qualify_DosAttack(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DosAttack(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_IpmcStarGroupHit
*/
int
bcmx_field_qualify_IpmcStarGroupHit(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_IpmcStarGroupHit(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_MyStationHit
*/
int
bcmx_field_qualify_MyStationHit(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_MyStationHit(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L2PayloadFirstEightBytes
*/
int
bcmx_field_qualify_L2PayloadFirstEightBytes(bcm_field_entry_t entry,
uint32 data1, uint32 data2,
uint32 mask1, uint32 mask2)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L2PayloadFirstEightBytes(bcm_unit, entry,
data1, data2,
mask1, mask2);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L3DestRouteHit
*/
int
bcmx_field_qualify_L3DestRouteHit(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L3DestRouteHit(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L3DestHostHit
*/
int
bcmx_field_qualify_L3DestHostHit(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L3DestHostHit(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L3SrcHostHit
*/
int
bcmx_field_qualify_L3SrcHostHit(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L3SrcHostHit(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L2CacheHit
*/
int
bcmx_field_qualify_L2CacheHit(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L2CacheHit(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L2StationMove
*/
int
bcmx_field_qualify_L2StationMove(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L2StationMove(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L2DestHit
*/
int
bcmx_field_qualify_L2DestHit(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L2DestHit(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L2SrcStatic
*/
int
bcmx_field_qualify_L2SrcStatic(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L2SrcStatic(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_L2SrcHit
*/
int
bcmx_field_qualify_L2SrcHit(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_L2SrcHit(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_IngressStpState
*/
int
bcmx_field_qualify_IngressStpState(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_IngressStpState(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_ForwardingVlanValid
*/
int
bcmx_field_qualify_ForwardingVlanValid(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_ForwardingVlanValid(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcVirtualPortValid
*/
int
bcmx_field_qualify_SrcVirtualPortValid(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcVirtualPortValid(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_VlanTranslationHit
*/
int
bcmx_field_qualify_VlanTranslationHit(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_VlanTranslationHit(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerIp6FlowLabel
*/
int
bcmx_field_qualify_InnerIp6FlowLabel(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerIp6FlowLabel(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerL4DstPort
*/
int
bcmx_field_qualify_InnerL4DstPort(bcm_field_entry_t entry,
bcm_l4_port_t data,
bcm_l4_port_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerL4DstPort(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_InnerL4SrcPort
*/
int
bcmx_field_qualify_InnerL4SrcPort(bcm_field_entry_t entry,
bcm_l4_port_t data,
bcm_l4_port_t mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_InnerL4SrcPort(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Loopback
* Purpose:
* Add loopback field qualification to a field entry.
* Parameters:
* entry - (IN) Field entry id.
* data - (IN) Data to qualify with.
* mask - (IN) Mask to qualify with.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Loopback(bcm_field_entry_t entry,
uint8 data,
uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Loopback(bcm_unit, entry,
data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_LoopbackType
* Purpose:
* Add loopback type field qualification to a field entry.
* Parameters:
* entry - (IN) Field entry id.
* loopback_type - (IN) Loopback type.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_LoopbackType(bcm_field_entry_t entry,
bcm_field_LoopbackType_t loopback_type)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_LoopbackType(bcm_unit, entry,
loopback_type);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_TunnelType
* Purpose:
* Add tunnel type field qualification to a field entry.
* Parameters:
* entry - (IN) Field entry id.
* tunnel_type - (IN) Data to qualify with.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_TunnelType(bcm_field_entry_t entry,
bcm_field_TunnelType_t tunnel_type)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_TunnelType(bcm_unit, entry,
tunnel_type);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstL3Egress
* Purpose:
* Add a destination egress object field qualification to a field entry.
* Parameters:
* entry - (IN) Field Entry id.
* if_id - (IN) Egress object id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstL3Egress(bcm_field_entry_t entry,
bcm_if_t if_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstL3Egress(bcm_unit, entry,
if_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstMulticastGroup
* Purpose:
* Add a destination multicast group field qualification to a field entry.
* Parameters:
* entry - (IN) Field Entry id.
* group - (IN) Multicast group id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstMulticastGroup(bcm_field_entry_t entry,
bcm_multicast_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstMulticastGroup(bcm_unit, entry,
group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcMplsGport
* Purpose:
* Add source mpls port field qualification to a field entry.
* Parameters:
* entry - (IN) Field Entry id.
* mpls_port_id - (IN) Mpls virtual port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcMplsGport(bcm_field_entry_t entry,
bcm_gport_t mpls_port_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcMplsGport(bcm_unit, entry,
mpls_port_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstMplsGport
* Purpose:
* Add destination mpls port field qualification to a field entry.
* Parameters:
* entry - (IN) Field Entry id.
* mpls_port_id - (IN) Mpls virtual port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstMplsGport(bcm_field_entry_t entry,
bcm_gport_t mpls_port_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstMplsGport(bcm_unit, entry,
mpls_port_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcMimGport
* Purpose:
* Add source mac in mac port field qualification to a field entry.
* Parameters:
* entry - (IN) Field Entry id.
* mim_port_id - (IN) Mim virtual port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcMimGport(bcm_field_entry_t entry,
bcm_gport_t mim_port_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcMimGport(bcm_unit, entry,
mim_port_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstMimGport
* Purpose:
* Add destination mac in mac port field qualification to a field entry.
* Parameters:
* entry - (IN) Field Entry id.
* mim_port_id - (IN) Mim virtual port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstMimGport(bcm_field_entry_t entry,
bcm_gport_t mim_port_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstMimGport(bcm_unit, entry,
mim_port_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcWlanGport
* Purpose:
* Add source wlan port field qualification to a field entry.
* Parameters:
* entry - (IN) Field Entry id.
* wlan_port_id - (IN) Wlan virtual port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcWlanGport(bcm_field_entry_t entry,
bcm_gport_t wlan_port_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcWlanGport(bcm_unit, entry,
wlan_port_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstWlanGport
* Purpose:
* Add destination wlan port field qualification to a field entry.
* Parameters:
* entry - (IN) Field Entry id.
* wlan_port_id - (IN) Wlan virtual port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstWlanGport(bcm_field_entry_t entry,
bcm_gport_t wlan_port_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstWlanGport(bcm_unit, entry,
wlan_port_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcModPortGport
* Purpose:
* Add source mod/port field qualification to a field entry.
* Parameters:
* entry - (IN) Field Entry id.
* data - (IN) Wlan virtual port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcModPortGport(bcm_field_entry_t entry,
bcm_gport_t data)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcModPortGport(bcm_unit, entry,
data);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_SrcModuleGport
* Purpose:
* Add source mod/port field qualification to a field entry.
* Parameters:
* entry - (IN) Field Entry id.
* data - (IN) Wlan virtual port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcModuleGport(bcm_field_entry_t entry,
bcm_gport_t data)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_SrcModuleGport(bcm_unit, entry,
data);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_Color
* Purpose:
* Set match criteria for bcmFieldQualifyColor
* qualifier in the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* color - (IN) Qualifier match color.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Color(bcm_field_entry_t entry, uint8 color)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_Color(bcm_unit, entry, color);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_IntPriority
* Purpose:
* Set match criteria for bcmFieldQualifyColor
* qualifier in the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (IN) Qualifier match data.
* mask - (IN) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IntPriority(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_IntPriority(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_FibreChanOuter
* Purpose:
* Add Fibre Channel outer header type field qualification to
* field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* fibre_chan_type - (IN) Data to qualify with.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_FibreChanOuter(bcm_field_entry_t entry,
bcm_field_FibreChan_t fibre_chan_type)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_FibreChanOuter(bcm_unit, entry,
fibre_chan_type);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_FibreChanInner
* Purpose:
* Add Fibre Channel inner header type field qualification to
* field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* fibre_chan_type - (IN) Data to qualify with.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_FibreChanInner(bcm_field_entry_t entry,
bcm_field_FibreChan_t fibre_chan_type)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_FibreChanInner(bcm_unit, entry,
fibre_chan_type);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_VnTag
* Purpose:
* Add NIV VN tag field qualification to field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (IN) Qualifier match data.
* mask - (IN) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_VnTag(bcm_field_entry_t entry, uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_VnTag(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_CnTag
* Purpose:
* Add QCN CN tag field qualification to field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (IN) Qualifier match data.
* mask - (IN) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_CnTag(bcm_field_entry_t entry, uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_CnTag(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_FabricQueueTag
* Purpose:
* Add Fabric Queue tag field qualification to field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (IN) Qualifier match data.
* mask - (IN) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_FabricQueueTag(bcm_field_entry_t entry,
uint32 data, uint32 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_FabricQueueTag(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_DstMultipath
* Purpose:
* Add a multipath egress object field qualification to a field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* mpintf - (IN) Multipath egress object id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstMultipath(bcm_field_entry_t entry, bcm_if_t mpintf)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_DstMultipath(bcm_unit, entry, mpintf);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_action_add
* Purpose:
* Add action performed when entry rule is matched for a packet
* Parameters:
* entry - Entry ID
* action - Action to perform (bcmFieldActionXXX)
* param0 - Action parameter (use 0 if not required)
* param1 - Action parameter (use 0 if not required)
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_MEMORY Allocation failure
* BCM_E_RESOURCE Counter not previously created for entry
* BCM_E_PARAM param0 not an even index for counter
* BCM_E_NONE
* Notes:
* For port related actions, param0 is a BCMX logical port or
* other GPORT type.
*/
int
bcmx_field_action_add(bcm_field_entry_t entry,
bcm_field_action_t action,
uint32 param0,
uint32 param1)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
/*
* For port related actions, param0 can be either:
* - A BCMX lport, then translate to modid/port
* - Another gport type, such as trunk
*/
if ((action == bcmFieldActionRedirectPort) ||
(action == bcmFieldActionRedirect) ||
(action == bcmFieldActionMirrorIngress) ||
(action == bcmFieldActionMirrorEgress)) {
bcm_module_t modid;
bcm_port_t modport;
/*
* When param0 is a valid GPORT, but it is NOT of of MODPORT type,
* the conversion to modid/port will fail. However, the GPORT
* value may be a valid data for certain devices (such as ESW)
* where a trunk (in gport format) is being passed in.
*
* NOTE that the BCM API expects the gport data in the
* place where the 'port' parameter is normally passed in.
*
* This is a bit uggly,
* but we must accomodate different architectures and
* the partial support of gport formats.
*/
if (BCM_SUCCESS(_bcmx_dest_to_modid_port((bcmx_lport_t)param0,
&modid, &modport,
BCMX_DEST_CONVERT_DEFAULT))) {
param0 = (uint32)modid;
param1 = (uint32)modport;
} else {
/* Assign gport value to expected 'param1' in BCM */
param1 = param0;
}
}
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_action_add(bcm_unit, entry, action,
param0, param1);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_action_delete
* Purpose:
* Delete an action performed when entry rule is matched for a packet
* Parameters:
* entry - Entry ID
* action - Action to perform (bcmFieldActionXXX)
* param0 - Action parameter (use 0 if not required)
* param1 - Action parameter (use 0 if not required)
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_MEMORY Allocation failure
* BCM_E_RESOURCE Counter not previously created for entry
* BCM_E_PARAM param0 not an even index for counter
* BCM_E_NONE
* Notes:
* For port related actions, param0 is a BCMX logical port or
* other GPORT type.
*/
int
bcmx_field_action_delete(bcm_field_entry_t entry,
bcm_field_action_t action,
uint32 param0,
uint32 param1)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
/*
* For port related actions, param0 can be either:
* - A BCMX lport, then translate to modid/port
* - Another gport type, such as trunk
*/
if ((action == bcmFieldActionRedirectPort) ||
(action == bcmFieldActionRedirect) ||
(action == bcmFieldActionMirrorIngress) ||
(action == bcmFieldActionMirrorEgress)) {
int modid;
bcm_port_t modport;
/*
* When param0 is a valid GPORT, but it is NOT of of MODPORT type,
* the conversion to modid/port will fail. However, the GPORT
* value may be a valid data for certain devices (such as ESW)
* where a trunk (in gport format) is being passed in.
*
* NOTE that the BCM API expects the gport data in the
* place where the 'port' parameter is normally passed in.
*
* This is a bit uggly,
* but we must accomodate different architectures and
* the partial support of gport formats.
*/
if (BCM_SUCCESS(_bcmx_dest_to_modid_port((bcmx_lport_t)param0,
&modid, &modport,
BCMX_DEST_CONVERT_DEFAULT))) {
param0 = (uint32)modid;
param1 = (uint32)modport;
} else {
/* Assign gport value to expected argument 'param1' for BCM */
param1 = param0;
}
}
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_action_delete(bcm_unit, entry, action,
param0, param1);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_action_mac_add
* Purpose:
* Add mac related actions to field entry.
* Parameters:
* entry - Entry ID
* action - Action (bcmFieldActionSrcMacNew or
* bcmFieldActionDstMacNew
* mac - Mac address.
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_MEMORY Allocation failure
* BCM_E_RESOURCE
* BCM_E_PARAM
* BCM_E_NONE
*/
int
bcmx_field_action_mac_add(bcm_field_entry_t entry,
bcm_field_action_t action,
bcm_mac_t mac)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_action_mac_add(bcm_unit, entry, action, mac);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_action_mac_get
* Purpose:
* Get field action SrcMacNew/DstMacNew parameters.
* Parameters:
* entry - Entry ID
* action - Action (bcmFieldActionSrcMacNew or
* bcmFieldActionDstMacNew
* mac - (OUT) Mac address.
* Returns:
* BCM_E_INIT - BCM Unit not initialized
* BCM_E_NOT_FOUND - Entry ID not found
* BCM_E_NOT_FOUND - No matching Action for entry
* BCM_E_PARAM - incorrect action OR pbmp is NULL
* BCM_E_NONE - Success
*/
int
bcmx_field_action_mac_get(bcm_field_entry_t entry,
bcm_field_action_t action,
bcm_mac_t *mac)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(mac);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_action_mac_get(bcm_unit, entry, action, mac);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_action_ports_add
* Purpose:
* Add PBMP related actions, when entry rule is matched for a packet
* Parameters:
* entry - Entry ID
* action - Action to perform (bcmFieldActionRedirectPbmp or
* bcmFieldActionEgressMask
* lplist - Logical Port list
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_MEMORY Allocation failure
* BCM_E_RESOURCE
* BCM_E_PARAM
* BCM_E_NONE
* Notes:
* This API has limitations when dealing with remote ports
* for certain topologies.
* FP action is applied to ports from given list that are
* local to the devices where packets are ingressing.
*/
int
bcmx_field_action_ports_add(bcm_field_entry_t entry,
bcm_field_action_t action,
bcmx_lplist_t lplist)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_pbmp_t pbmp;
BCMX_FIELD_INIT_CHECK;
if (bcmx_lplist_is_null(&lplist)) {
return BCM_E_PARAM;
}
BCMX_UNIT_ITER(bcm_unit, i) {
BCMX_LPLIST_TO_PBMP(lplist, bcm_unit, pbmp);
tmp_rv = bcm_field_action_ports_add(bcm_unit, entry, action, pbmp);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_action_ports_get
* Purpose:
* Get parameters associated with port list related entry actions
* Parameters:
* entry - Entry ID
* action - Action (bcmFieldActionRedirectPbmp or
* bcmFieldActionEgressMask
* lplist - (OUT) Logical Port list
* Returns:
* BCM_E_INIT - BCM Unit not initialized
* BCM_E_NOT_FOUND - Entry ID not found
* BCM_E_NOT_FOUND - No matching Action for entry
* BCM_E_PARAM - incorrect action OR pbmp is NULL
* BCM_E_NONE - Success
*/
int
bcmx_field_action_ports_get(bcm_field_entry_t entry,
bcm_field_action_t action,
bcmx_lplist_t *lplist)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
bcm_pbmp_t pbmp;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(lplist);
BCMX_UNIT_ITER(bcm_unit, i) {
BCM_PBMP_CLEAR(pbmp);
tmp_rv = bcm_field_action_ports_get(bcm_unit, entry, action, &pbmp);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, tmp_rv)) {
rv = tmp_rv;
if (BCM_SUCCESS(tmp_rv)) {
BCMX_LPLIST_PBMP_ADD(lplist, bcm_unit, pbmp);
} else {
break;
}
}
}
return rv;
}
/*
* Function:
* bcmx_field_action_get
* Purpose:
* Get parameters associated with an entry action
* Parameters:
* entry - Entry ID
* action - Action to perform (bcmFieldActionXXX)
* param0 - (OUT) Action parameter
* param1 - (OUT) Action parameter
* Returns:
* BCM_E_NOT_FOUND Entry ID or action not found
* BCM_E_PARAM paramX is NULL
* BCM_E_NONE
* Notes:
* Get value from first successful call.
* For port related actions, param0 returns a BCMX logical port.
*/
int
bcmx_field_action_get(bcm_field_entry_t entry,
bcm_field_action_t action,
uint32 *param0,
uint32 *param1)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(param0);
BCMX_PARAM_NULL_CHECK(param1);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_action_get(bcm_unit, entry, action,
param0, param1);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
if (BCM_SUCCESS(rv)) {
/*
* For port related actions, param0 returns an lport,
* translate modid/port to lport
*/
if ((action == bcmFieldActionRedirectPort) ||
(action == bcmFieldActionRedirect) ||
(action == bcmFieldActionMirrorIngress) ||
(action == bcmFieldActionMirrorEgress)) {
bcmx_lport_t port;
BCM_IF_ERROR_RETURN
(_bcmx_dest_from_modid_port(&port,
(bcm_module_t)(*param0),
(bcm_port_t)(*param1),
BCMX_DEST_CONVERT_DEFAULT));
*param0 = (uint32)port;
*param1 = 0;
}
}
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_action_remove
* Purpose:
* Remove an action performed when entry rule is matched for
* a packet
* Parameters:
* entry - Entry ID
* action - Action to remove (bcmFieldActionXXX)
* Returns:
* BCM_E_NOT_FOUND Entry ID or action not found
* BCM_E_PARAM Action out of valid range
* BCM_E_NONE
*/
int
bcmx_field_action_remove(bcm_field_entry_t entry,
bcm_field_action_t action)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_action_remove(bcm_unit, entry, action);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_action_remove_all
* Purpose:
* Remove all actions from an entry rule
* Parameters:
* entry - Entry ID
* Returns:
* BCM_E_NOT_FOUND Entry ID not found
* BCM_E_NONE
*/
int
bcmx_field_action_remove_all(bcm_field_entry_t entry)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_action_remove_all(bcm_unit, entry);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_stat_create
* Description:
* Create statistics collection entity.
* Parameters:
* group - Field group id.
* nstat - Number of elements in stat array.
* stat_arr - Collected statistics descriptors array.
* stat_id - (OUT) Statistics entity id.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_create(bcm_field_group_t group, int nstat,
bcm_field_stat_t *stat_arr, int *stat_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
int id;
BCMX_FIELD_INIT_CHECK;
if (nstat != 0) {
BCMX_PARAM_NULL_CHECK(stat_arr);
}
BCMX_PARAM_NULL_CHECK(stat_id);
id = STAT_ID_ALLOC;
*stat_id = id;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_create_id(bcm_unit, group,
nstat, stat_arr, id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_stat_create_id
* Description:
* Create statistics collection entity with given id.
* Parameters:
* group - Field group id.
* nstat - Number of elements in stat array.
* stat_arr - Collected statistics descriptors array.
* stat_id - Statistics entity id.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_create_id(bcm_field_group_t group, int nstat,
bcm_field_stat_t *stat_arr, int stat_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
if (nstat != 0) {
BCMX_PARAM_NULL_CHECK(stat_arr);
}
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_create_id(bcm_unit, group,
nstat, stat_arr, stat_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_stat_destroy
* Description:
* Destroy statistics collection entity.
* Parameters:
* stat_id - Statistics entity id.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_destroy(int stat_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_destroy(bcm_unit, stat_id);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_stat_size
* Description:
* Get number of different statistics associated with statistics
* collection entity.
* Parameters:
* stat_id - Statistics entity id.
* stat_size - (OUT) Number of collected statistics
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_size(int stat_id, int *stat_size)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(stat_size);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_stat_size(bcm_unit, stat_id, stat_size);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_stat_config_get
* Description:
* Get enabled statistics for specific collection entity.
* Parameters:
* stat_id - Statistics entity id.
* nstat - Number of elements in stat array.
* stat_arr - (OUT) Collected statistics descriptors array.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_config_get(int stat_id, int nstat, bcm_field_stat_t *stat_arr)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
if (nstat != 0) {
BCMX_PARAM_NULL_CHECK(stat_arr);
}
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_stat_config_get(bcm_unit, stat_id, nstat, stat_arr);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_stat_set
* Description:
* Set 64 bit counter value for specific statistic type.
* Parameters:
* stat_id - Statistics entity id.
* stat - Collected statistics descriptor.
* value - Value to set.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_set(int stat_id, bcm_field_stat_t stat, uint64 value)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_set(bcm_unit, stat_id, stat, value);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_stat_set32
* Description:
* Set lower 32 bit counter value for specific statistic type.
* Parameters:
* stat_id - Statistics entity id.
* stat - Collected statistics descriptor.
* value - Value to set.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_set32(int stat_id, bcm_field_stat_t stat, uint32 value)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_set32(bcm_unit, stat_id, stat, value);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_stat_all_set
* Description:
* Set 64 bit counter values for all statistic types.
* Parameters:
* stat_id - Statistics entity id.
* value - Value to set.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_all_set(int stat_id, uint64 value)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_all_set(bcm_unit, stat_id, value);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_stat_all_set32
* Description:
* Set lower 32 bit counter values for all statistic types.
* Parameters:
* stat_id - Statistics entity id.
* value - Value to set.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_all_set32(int stat_id, uint32 value)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_all_set32(bcm_unit, stat_id, value);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_stat_get
* Description:
* Get 64 bit counter value for specific statistic type.
* Parameters:
* stat_id - Statistics entity id.
* stat - Collected statistics descriptor.
* value - (OUT) Collected counters value.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_get(int stat_id, bcm_field_stat_t stat, uint64 *value)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
uint64 tmp_val;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(value);
COMPILER_64_ZERO(*value);
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_get(bcm_unit, stat_id, stat, &tmp_val);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, tmp_rv)) {
rv = tmp_rv;
if (BCM_SUCCESS(tmp_rv)) {
COMPILER_64_ADD_64(*value, tmp_val);
} else {
break;
}
}
}
return rv;
}
/*
* Function:
* bcmx_field_stat_get32
* Description:
* Get lower 32 bit counter value for specific statistic type.
* Parameters:
* stat_id - Statistics entity id.
* stat - Collected statistics descriptor.
* value - (OUT) Collected counters value.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_get32(int stat_id, bcm_field_stat_t stat, uint32 *value)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
uint32 tmp_val;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(value);
*value = 0;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_get32(bcm_unit, stat_id, stat, &tmp_val);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, tmp_rv)) {
rv = tmp_rv;
if (BCM_SUCCESS(tmp_rv)) {
*value += tmp_val;
} else {
break;
}
}
}
return rv;
}
/*
* Function:
* bcmx_field_stat_multi_get
* Description:
* Get 64 bit counter values for multiple statistic types.
* Parameters:
* stat_id - Statistics entity id.
* nstat - Number of elements in stat array.
* stat_arr - Collected statistics descriptors array.
* value_arr - (OUT) Collected counters values.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_multi_get(int stat_id, int nstat,
bcm_field_stat_t *stat_arr, uint64 *value_arr)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
int j;
uint64 *tmp_value_arr;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(stat_arr);
BCMX_PARAM_NULL_CHECK(value_arr);
tmp_value_arr = sal_alloc(sizeof(uint64) * nstat, "BCMX field stat");
if (tmp_value_arr == NULL) {
return BCM_E_MEMORY;
}
for (j = 0; j < nstat; j++) {
COMPILER_64_ZERO(value_arr[j]);
}
/* Gather statistic values from all units */
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_multi_get(bcm_unit, stat_id, nstat,
stat_arr, tmp_value_arr);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, tmp_rv)) {
rv = tmp_rv;
if (BCM_SUCCESS(tmp_rv)) {
for (j = 0; j < nstat; j++) {
COMPILER_64_ADD_64(value_arr[j], tmp_value_arr[j]);
}
} else {
break;
}
}
}
sal_free(tmp_value_arr);
return rv;
}
/*
* Function:
* bcmx_field_stat_multi_get32
* Description:
* Get lower 32 bit counter values for multiple statistic types.
* Parameters:
* stat_id - Statistics entity id.
* nstat - Number of elements in stat array.
* stat_arr - Collected statistics descriptors array.
* value_arr - (OUT) Collected counters values.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_stat_multi_get32(int stat_id, int nstat,
bcm_field_stat_t *stat_arr, uint32 *value_arr)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
int j;
uint32 *tmp_value_arr;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(stat_arr);
BCMX_PARAM_NULL_CHECK(value_arr);
tmp_value_arr = sal_alloc(sizeof(uint32) * nstat, "BCMX field stat");
if (tmp_value_arr == NULL) {
return BCM_E_MEMORY;
}
for (j = 0; j < nstat; j++) {
value_arr[j] = 0;
}
/* Gather statistic values from all units */
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_stat_multi_get32(bcm_unit, stat_id, nstat,
stat_arr, tmp_value_arr);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, tmp_rv)) {
rv = tmp_rv;
if (BCM_SUCCESS(tmp_rv)) {
for (j = 0; j < nstat; j++) {
value_arr[j] += tmp_value_arr[j];
}
} else {
break;
}
}
}
sal_free(tmp_value_arr);
return rv;
}
/*
* Function:
* bcmx_field_entry_stat_attach
* Description:
* Attach statistics entity to Field Processor entry.
* Parameters:
* entry - Field entry id.
* stat_id - Statistics entity id.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_entry_stat_attach(bcm_field_entry_t entry, int stat_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_stat_attach(bcm_unit, entry, stat_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_stat_detach
* Description:
* Detach statistics entity from Field Processor entry.
* Parameters:
* entry - Field entry id.
* stat_id - Statistics entity id.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_entry_stat_detach(bcm_field_entry_t entry, int stat_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_entry_stat_detach(bcm_unit, entry, stat_id);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_entry_stat_get
* Description:
* Get statistics entity attached to Field Processor entry.
* Parameters:
* entry - Field entry id.
* stat_id - (OUT) Statistics entity id.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_entry_stat_get(bcm_field_entry_t entry, int *stat_id)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(stat_id);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_entry_stat_get(bcm_unit, entry, stat_id);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_group_compress
* Description:
* Compresses field group entries.
* Parameters:
* group - Field group ID
* Returns:
* BCM_E_XXX - some error
* BCM_E_NONE
*/
int
bcmx_field_group_compress(bcm_field_group_t group)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_compress(bcm_unit, group);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_priority_set
* Description:
* Set the group priority.
* Parameters:
* group - Group ID
* Returns:
* BCM_E_XXX
* BCM_E_NONE
*/
int
bcmx_field_group_priority_set(bcm_field_group_t group, int priority)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_group_priority_set(bcm_unit, group, priority);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_group_priority_get
* Description:
* Get the group priority.
* Parameters:
* group - Group ID
* Returns:
* BCM_E_XXX
* BCM_E_NONE
* Notes:
* Get value from first successful call
*/
int
bcmx_field_group_priority_get(bcm_field_group_t group, int *priority)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(priority);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_group_priority_get(bcm_unit, group, priority);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
void bcmx_field_data_qualifier_t_init(bcmx_field_data_qualifier_t *data_qual)
{
bcm_field_data_qualifier_t_init((bcm_field_data_qualifier_t *)data_qual);
}
void bcmx_field_data_ethertype_t_init(bcmx_field_data_ethertype_t *etype)
{
bcm_field_data_ethertype_t_init((bcm_field_data_ethertype_t *)etype);
}
void bcmx_field_data_ip_protocol_t_init(bcmx_field_data_ip_protocol_t
*ip_protocol)
{
bcm_field_data_ip_protocol_t_init
((bcm_field_data_ip_protocol_t *)ip_protocol);
}
void bcmx_field_data_packet_format_t_init(bcmx_field_data_packet_format_t
*packet_format)
{
bcm_field_data_packet_format_t_init
((bcm_field_data_packet_format_t *)packet_format);
}
int bcmx_field_data_qualifier_create(bcmx_field_data_qualifier_t
*data_qualifier)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i;
int bcm_unit;
uint32 flags_orig;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data_qualifier);
/* Store original 'xxx_WITH_ID' flag bit */
flags_orig = data_qualifier->flags & BCM_FIELD_DATA_QUALIFIER_WITH_ID;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_data_qualifier_create(bcm_unit,data_qualifier);
if (BCM_FAILURE(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv))) {
break;
}
/*
* If qualifier id is not specified, use returned id from
* first successful 'create' for remaining units.
*/
if (!(data_qualifier->flags & BCM_FIELD_DATA_QUALIFIER_WITH_ID)) {
if (BCM_SUCCESS(tmp_rv)) {
data_qualifier->flags |= BCM_FIELD_DATA_QUALIFIER_WITH_ID;
}
}
}
/* Restore 'xxx_WITH_ID' flag bit */
data_qualifier->flags &= ~BCM_FIELD_DATA_QUALIFIER_WITH_ID;
data_qualifier->flags |= flags_orig;
return rv;
}
/*
* Function:
* bcmx_field_data_qualifier_multi_get
* Purpose:
* Return list of ids of defined data qualifiers.
* Parameters:
* qual_size - (IN) Size of given qualifier id array; if 0, indicates
* return count of data qualifiers only.
* qual_array - (OUT) Base of array where to store returned data qualifier
* ids.
* qual_count - (OUT) Number of qualifier ids stored in above array; if
* qual_size was given as 0, then number of defined
* qualifiers.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_data_qualifier_multi_get(int qual_size,
int *qual_array, int *qual_count)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_ARRAY_NULL_CHECK(qual_size, qual_array);
BCMX_PARAM_NULL_CHECK(qual_count);
/*
* No need to gather qualifier ids from all units. BCMX assumes
* that field qualifier ids were created with BCMX APIs.
*/
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_data_qualifier_multi_get(bcm_unit, qual_size,
qual_array, qual_count);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_data_qualifier_get
* Purpose:
* Return configuration of given data qualifier.
* Parameters:
* qual_id - (IN) Id of data qualifier.
* qual - (OUT) Attributes of given data qualifier.
* Returns:
* BCM_E_XXX
*/
int
bcmx_field_data_qualifier_get(int qual_id,
bcmx_field_data_qualifier_t *qual)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(qual);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_data_qualifier_get(bcm_unit, qual_id,
(bcm_field_data_qualifier_t *)qual);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
int bcmx_field_data_qualifier_destroy(int qual_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_data_qualifier_destroy(bcm_unit, qual_id);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
int bcmx_field_data_qualifier_destroy_all(void)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_data_qualifier_destroy_all(bcm_unit);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
int bcmx_field_data_qualifier_ethertype_add(int qual_id,
bcmx_field_data_ethertype_t *etype)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(etype);
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_data_qualifier_ethertype_add
(bcm_unit, qual_id, (bcm_field_data_ethertype_t *)etype);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
int bcmx_field_data_qualifier_ethertype_delete(int qual_id,
bcmx_field_data_ethertype_t
*etype)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(etype);
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_data_qualifier_ethertype_delete
(bcm_unit, qual_id, (bcm_field_data_ethertype_t *)etype);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
int bcmx_field_data_qualifier_ip_protocol_add(int qual_id,
bcmx_field_data_ip_protocol_t
*ip_protocol)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(ip_protocol);
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_data_qualifier_ip_protocol_add
(bcm_unit, qual_id, (bcm_field_data_ip_protocol_t *)ip_protocol);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
int bcmx_field_data_qualifier_ip_protocol_delete(int qual_id,
bcmx_field_data_ip_protocol_t
*ip_protocol)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(ip_protocol);
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_data_qualifier_ip_protocol_delete
(bcm_unit, qual_id, (bcm_field_data_ip_protocol_t *)ip_protocol);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
int bcmx_field_data_qualifier_packet_format_add(int qual_id,
bcmx_field_data_packet_format_t
*packet_format)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(packet_format);
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_data_qualifier_packet_format_add
(bcm_unit, qual_id,
(bcm_field_data_packet_format_t *)packet_format);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
int bcmx_field_data_qualifier_packet_format_delete(int qual_id,
bcmx_field_data_packet_format_t *packet_format)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(packet_format);
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_data_qualifier_packet_format_delete
(bcm_unit, qual_id,
(bcm_field_data_packet_format_t *)packet_format);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
int bcmx_field_qset_data_qualifier_add(bcm_field_qset_t *qset, int qual_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(qset);
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qset_data_qualifier_add(bcm_unit, qset, qual_id);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
int bcmx_field_qualify_data(bcm_field_entry_t eid, int qual_id,
uint8 *data, uint8 *mask, uint16 length)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_data(bcm_unit, eid, qual_id,
data, mask, length);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qset_data_qualifier_get
*/
int
bcmx_field_qset_data_qualifier_get(bcm_field_qset_t *qset,
int qual_max, int *qual_arr,
int *qual_count)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(qset);
BCMX_PARAM_NULL_CHECK(qual_count);
BCMX_PARAM_ARRAY_NULL_CHECK(qual_max, qual_arr);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qset_data_qualifier_get(bcm_unit, *qset,
qual_max, qual_arr,
qual_count);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_LoopbackType_get
* Purpose:
* Get loopback type field qualification from a field entry.
* Parameters:
* entry - (IN) Field entry id.
* loopback_type - (OUT) Loopback type.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_LoopbackType_get(bcm_field_entry_t entry,
bcm_field_LoopbackType_t *loopback_type)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(loopback_type);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_LoopbackType_get(bcm_unit, entry, loopback_type);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_TunnelType_get
* Purpose:
* Get tunnel type field qualification from a field entry.
* Parameters:
* entry - (IN) Field entry id.
* tunnel_type - (OUT) Tunnel type.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_TunnelType_get(bcm_field_entry_t entry,
bcm_field_TunnelType_t *tunnel_type)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(tunnel_type);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_TunnelType_get(bcm_unit, entry, tunnel_type);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstL3Egress_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstL3Egress
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* if_id - (OUT) L3 forwarding object.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstL3Egress_get(bcm_field_entry_t entry,
bcm_if_t *if_id)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(if_id);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstL3Egress_get(bcm_unit, entry, if_id);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstMulticastGroup_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstMulticastGroup
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* group - (OUT) Multicast group id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstMulticastGroup_get(bcm_field_entry_t entry,
bcm_multicast_t *group)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(group);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstMulticastGroup_get(bcm_unit, entry, group);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Color_get
* Purpose:
* Get match criteria for bcmFieldQualifyColor
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* color - (OUT) Qualifier match color.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Color_get(bcm_field_entry_t entry, uint8 *color)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(color);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Color_get(bcm_unit, entry, color);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_IntPriority_get
* Purpose:
* Get match criteria for bcmFieldQualifyIntPriority
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IntPriority_get(bcm_field_entry_t entry,
uint8 *data, uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_IntPriority_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcModPortGport_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcModPortGport
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Mod/port gport id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcModPortGport_get(bcm_field_entry_t entry,
bcm_gport_t *data)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcModPortGport_get(bcm_unit, entry, data);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcModuleGport_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcModuleGport
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Mod/port gport id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcModuleGport_get(bcm_field_entry_t entry,
bcm_gport_t *data)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcModuleGport_get(bcm_unit, entry, data);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcMplsGport_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcMplsGport
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* mpls_port_id - (OUT) Mpls port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcMplsGport_get(bcm_field_entry_t entry,
bcm_gport_t *mpls_port_id)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(mpls_port_id);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcMplsGport_get(bcm_unit, entry, mpls_port_id);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstMplsGport_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstMplsGport
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* mpls_port_id - (OUT) Mpls port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstMplsGport_get(bcm_field_entry_t entry,
bcm_gport_t *mpls_port_id)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(mpls_port_id);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstMplsGport_get(bcm_unit, entry, mpls_port_id);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcMimGport_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcMimGport
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* mim_port_id - (OUT) Mim port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcMimGport_get(bcm_field_entry_t entry,
bcm_gport_t *mim_port_id)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(mim_port_id);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcMimGport_get(bcm_unit, entry, mim_port_id);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstMimGport_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstMimGport
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* mim_port_id - (OUT) Mim port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstMimGport_get(bcm_field_entry_t entry,
bcm_gport_t *mim_port_id)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(mim_port_id);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstMimGport_get(bcm_unit, entry, mim_port_id);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcWlanGport_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcWlanGport
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* wlan_port_id - (OUT) Wlan port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcWlanGport_get(bcm_field_entry_t entry,
bcm_gport_t *wlan_port_id)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(wlan_port_id);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcWlanGport_get(bcm_unit, entry, wlan_port_id);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstWlanGport_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstWlanGport
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* wlan_port_id - (OUT) Wlan port id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstWlanGport_get(bcm_field_entry_t entry,
bcm_gport_t *wlan_port_id)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(wlan_port_id);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstWlanGport_get(bcm_unit, entry, wlan_port_id);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Loopback_get
* Purpose:
* Get loopback field qualification from a field entry.
* Parameters:
* entry - (IN) Field entry id.
* data - (OUT) Data to qualify with.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Loopback_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Loopback_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InPort_get
* Purpose:
* Get match criteria for bcmFieldQualifyInPort
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InPort_get(bcm_field_entry_t entry,
bcm_port_t *data,
bcm_port_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InPort_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_OutPort_get
* Purpose:
* Get match criteria for bcmFieldQualifyOutPort
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_OutPort_get(bcm_field_entry_t entry,
bcm_port_t *data,
bcm_port_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_OutPort_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InPorts_get
* Purpose:
* Get match criteria for bcmFieldQualifyInPorts
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InPorts_get(bcm_field_entry_t entry,
bcm_pbmp_t *data,
bcm_pbmp_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InPorts_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_OutPorts_get
* Purpose:
* Get match criteria for bcmFieldQualifyOutPorts
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_OutPorts_get(bcm_field_entry_t entry,
bcm_pbmp_t *data,
bcm_pbmp_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_OutPorts_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Drop_get
* Purpose:
* Get match criteria for bcmFieldQualifyDrop
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Drop_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Drop_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcPort_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcPort
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data_modid - (OUT) Qualifier module id.
* mask_modid - (OUT) Qualifier module id mask.
* data_port - (OUT) Qualifier port id.
* mask_port - (OUT) Qualifier port id mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcPort_get(bcm_field_entry_t entry,
bcm_module_t *data_modid,
bcm_module_t *mask_modid,
bcm_port_t *data_port,
bcm_port_t *mask_port)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data_modid);
BCMX_PARAM_NULL_CHECK(mask_modid);
BCMX_PARAM_NULL_CHECK(data_port);
BCMX_PARAM_NULL_CHECK(mask_port);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcPort_get(bcm_unit, entry, data_modid, mask_modid, data_port, mask_port);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcTrunk_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcTrunk
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcTrunk_get(bcm_field_entry_t entry,
bcm_trunk_t *data,
bcm_trunk_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcTrunk_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstPort_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstPort
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data_modid - (OUT) Qualifier module id.
* mask_modid - (OUT) Qualifier module id mask.
* data_port - (OUT) Qualifier port id.
* mask_port - (OUT) Qualifier port id mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstPort_get(bcm_field_entry_t entry,
bcm_module_t *data_modid,
bcm_module_t *mask_modid,
bcm_port_t *data_port,
bcm_port_t *mask_port)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data_modid);
BCMX_PARAM_NULL_CHECK(mask_modid);
BCMX_PARAM_NULL_CHECK(data_port);
BCMX_PARAM_NULL_CHECK(mask_port);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstPort_get(bcm_unit, entry, data_modid, mask_modid, data_port, mask_port);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstTrunk_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstTrunk
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstTrunk_get(bcm_field_entry_t entry,
bcm_trunk_t *data,
bcm_trunk_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstTrunk_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerL4SrcPort_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerL4SrcPort
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerL4SrcPort_get(bcm_field_entry_t entry,
bcm_l4_port_t *data,
bcm_l4_port_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerL4SrcPort_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerL4DstPort_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerL4DstPort
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerL4DstPort_get(bcm_field_entry_t entry,
bcm_l4_port_t *data,
bcm_l4_port_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerL4DstPort_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L4SrcPort_get
* Purpose:
* Get match criteria for bcmFieldQualifyL4SrcPort
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L4SrcPort_get(bcm_field_entry_t entry,
bcm_l4_port_t *data,
bcm_l4_port_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L4SrcPort_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L4DstPort_get
* Purpose:
* Get match criteria for bcmFieldQualifyL4DstPort
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L4DstPort_get(bcm_field_entry_t entry,
bcm_l4_port_t *data,
bcm_l4_port_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L4DstPort_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_OuterVlan_get
* Purpose:
* Get match criteria for bcmFieldQualifyOuterVlan
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_OuterVlan_get(bcm_field_entry_t entry,
bcm_vlan_t *data,
bcm_vlan_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_OuterVlan_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_OuterVlanId_get
* Purpose:
* Get match criteria for bcmFieldQualifyOuterVlanId
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_OuterVlanId_get(bcm_field_entry_t entry,
bcm_vlan_t *data,
bcm_vlan_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_OuterVlanId_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_ForwardingVlanId_get
* Purpose:
* Get match criteria for bcmFieldQualifyForwardingVlanId
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_ForwardingVlanId_get(bcm_field_entry_t entry,
bcm_vlan_t *data,
bcm_vlan_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_ForwardingVlanId_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_OuterVlanCfi_get
* Purpose:
* Get match criteria for bcmFieldQualifyOuterVlanCfi
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_OuterVlanCfi_get(bcm_field_entry_t entry,
uint8 *data, uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_OuterVlanCfi_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_OuterVlanPri_get
* Purpose:
* Get match criteria for bcmFieldQualifyOuterVlanPri
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_OuterVlanPri_get(bcm_field_entry_t entry,
uint8 *data, uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_OuterVlanPri_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerVlan_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerVlan
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerVlan_get(bcm_field_entry_t entry,
bcm_vlan_t *data,
bcm_vlan_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerVlan_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerVlanId_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerVlanId
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerVlanId_get(bcm_field_entry_t entry,
bcm_vlan_t *data,
bcm_vlan_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerVlanId_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerVlanPri_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerVlanPri
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerVlanPri_get(bcm_field_entry_t entry,
uint8 *data, uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerVlanPri_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerVlanCfi_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerVlanCfi
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerVlanCfi_get(bcm_field_entry_t entry,
uint8 *data, uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerVlanCfi_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_EtherType_get
* Purpose:
* Get match criteria for bcmFieldQualifyEtherType
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_EtherType_get(bcm_field_entry_t entry,
uint16 *data,
uint16 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_EtherType_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_IpProtocol_get
* Purpose:
* Get match criteria for bcmFieldQualifyIpProtocol
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IpProtocol_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_IpProtocol_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_IpInfo_get
* Purpose:
* Get match criteria for bcmFieldQualifyIpInfo
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IpInfo_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_IpInfo_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_PacketRes_get
* Purpose:
* Get match criteria for bcmFieldQualifyPacketRes
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_PacketRes_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_PacketRes_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcIp_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcIp
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcIp_get(bcm_field_entry_t entry,
bcm_ip_t *data,
bcm_ip_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcIp_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstIp_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstIp
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstIp_get(bcm_field_entry_t entry,
bcm_ip_t *data,
bcm_ip_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstIp_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DSCP_get
* Purpose:
* Get match criteria for bcmFieldQualifyDSCP
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DSCP_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DSCP_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Tos_get
* Purpose:
* Get match criteria for bcmFieldQualifyTos
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Tos_get(bcm_field_entry_t entry, uint8 *data, uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Tos_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_IpFlags_get
* Purpose:
* Get match criteria for bcmFieldQualifyIpFlags
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IpFlags_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_IpFlags_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_TcpControl_get
* Purpose:
* Get match criteria for bcmFieldQualifyTcpControl
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_TcpControl_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_TcpControl_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_TcpSequenceZero_get
* Purpose:
* Get match criteria for bcmFieldQualifyTcpSequenceZero
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* flag - (OUT) Qualifier match flags.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_TcpSequenceZero_get(bcm_field_entry_t entry,
uint32 *flag)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(flag);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_TcpSequenceZero_get(bcm_unit, entry, flag);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_TcpHeaderSize_get
* Purpose:
* Get match criteria for bcmFieldQualifyTcpHeaderSize
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_TcpHeaderSize_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_TcpHeaderSize_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Ttl_get
* Purpose:
* Get match criteria for bcmFieldQualifyTtl
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Ttl_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Ttl_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_RangeCheck_get
* Purpose:
* Get match criteria for bcmFieldQualifyRangeCheck
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* max_count - (IN) Max entries to fill.
* range - (OUT) Range checkers array.
* invert - (OUT) Range checkers invert array.
* count - (OUT) Number of filled range checkers.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_RangeCheck_get(bcm_field_entry_t entry,
int max_count,
bcm_field_range_t *range,
int *invert,
int *count)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(count);
BCMX_PARAM_ARRAY_NULL_CHECK(max_count, range);
BCMX_PARAM_ARRAY_NULL_CHECK(max_count, invert);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_RangeCheck_get(bcm_unit, entry, max_count, range, invert, count);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcIp6_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcIp6
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcIp6_get(bcm_field_entry_t entry,
bcm_ip6_t *data,
bcm_ip6_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcIp6_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstIp6_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstIp6
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstIp6_get(bcm_field_entry_t entry,
bcm_ip6_t *data,
bcm_ip6_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstIp6_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcIp6High_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcIp6High
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcIp6High_get(bcm_field_entry_t entry,
bcm_ip6_t *data,
bcm_ip6_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcIp6High_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcIp6Low_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcIp6Low
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcIp6Low_get(bcm_field_entry_t entry,
bcm_ip6_t *data,
bcm_ip6_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcIp6Low_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstIp6Low_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstIp6Low
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstIp6Low_get(bcm_field_entry_t entry,
bcm_ip6_t *data,
bcm_ip6_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstIp6Low_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstIp6High_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstIp6High
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstIp6High_get(bcm_field_entry_t entry,
bcm_ip6_t *data,
bcm_ip6_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstIp6High_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Ip6NextHeader_get
* Purpose:
* Get match criteria for bcmFieldQualifyIp6NextHeader
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Ip6NextHeader_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Ip6NextHeader_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Ip6TrafficClass_get
* Purpose:
* Get match criteria for bcmFieldQualifyIp6TrafficClass
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Ip6TrafficClass_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Ip6TrafficClass_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerIp6FlowLabel_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerIp6FlowLabel
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerIp6FlowLabel_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerIp6FlowLabel_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Ip6FlowLabel_get
* Purpose:
* Get match criteria for bcmFieldQualifyIp6FlowLabel
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Ip6FlowLabel_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Ip6FlowLabel_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Ip6HopLimit_get
* Purpose:
* Get match criteria for bcmFieldQualifyIp6HopLimit
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Ip6HopLimit_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Ip6HopLimit_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcMac_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcMac
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcMac_get(bcm_field_entry_t entry,
bcm_mac_t *data,
bcm_mac_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcMac_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstMac_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstMac
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstMac_get(bcm_field_entry_t entry,
bcm_mac_t *data,
bcm_mac_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstMac_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerIpType_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerIpType
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* type - (OUT) Inner ip header ip type.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerIpType_get(bcm_field_entry_t entry,
bcm_field_IpType_t *type)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(type);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerIpType_get(bcm_unit, entry, type);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_ForwardingType_get
* Purpose:
* Get match criteria for bcmFieldQualifyForwardingType
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* type - (OUT) Qualifier match forwarding type.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_ForwardingType_get(bcm_field_entry_t entry,
bcm_field_ForwardingType_t *type)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(type);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_ForwardingType_get(bcm_unit, entry, type);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_IpType_get
* Purpose:
* Get match criteria for bcmFieldQualifyIpType
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* type - (OUT) Qualifier match ip type.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IpType_get(bcm_field_entry_t entry,
bcm_field_IpType_t *type)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(type);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_IpType_get(bcm_unit, entry, type);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L2Format_get
* Purpose:
* Get match criteria for bcmFieldQualifyL2Format
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* type - (OUT) Qualifier match l2 format.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L2Format_get(bcm_field_entry_t entry,
bcm_field_L2Format_t *type)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(type);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L2Format_get(bcm_unit, entry, type);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_VlanFormat_get
* Purpose:
* Get match criteria for bcmFieldQualifyVlanFormat
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_VlanFormat_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_VlanFormat_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_TranslatedVlanFormat_get
* Purpose:
* Get match criteria for bcmFieldQualifyTranslatedVlanFormat
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_TranslatedVlanFormat_get(bcm_field_entry_t entry,
uint8 *data, uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_TranslatedVlanFormat_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_MHOpcode_get
* Purpose:
* Get match criteria for bcmFieldQualifyMHOpcode
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_MHOpcode_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_MHOpcode_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_HiGig_get
* Purpose:
* Qualify on HiGig packets.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_HiGig_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_HiGig_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstHiGig_get
* Purpose:
* Qualify on packets destined to higig port.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstHiGig_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstHiGig_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InterfaceClassPort_get
* Purpose:
* Get match criteria for bcmFieldQualifyInterfaceClassPort
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InterfaceClassPort_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InterfaceClassPort_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InterfaceClassL2_get
* Purpose:
* Get match criteria for bcmFieldQualifyInterfaceClassL2
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InterfaceClassL2_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InterfaceClassL2_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InterfaceClassL3_get
* Purpose:
* Get match criteria for bcmFieldQualifyInterfaceClassL3
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InterfaceClassL3_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InterfaceClassL3_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcClassL2_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcClassL2
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcClassL2_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcClassL2_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcClassL3_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcClassL3
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcClassL3_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcClassL3_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcClassField_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcClassField
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcClassField_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcClassField_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstClassL2_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstClassL2
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstClassL2_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstClassL2_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstClassL3_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstClassL3
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstClassL3_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstClassL3_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstClassField_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstClassField
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstClassField_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstClassField_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_IpProtocolCommon_get
* Purpose:
* Get match criteria for bcmFieldQualifyIpProtocolCommon
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* protocol - (OUT) Qualifier protocol encoding.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IpProtocolCommon_get(bcm_field_entry_t entry,
bcm_field_IpProtocolCommon_t *protocol)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(protocol);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_IpProtocolCommon_get(bcm_unit, entry, protocol);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerIpProtocolCommon_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerIpProtocolCommon
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* protocol - (OUT) Qualifier inner ip protocol encodnig.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerIpProtocolCommon_get(bcm_field_entry_t entry,
bcm_field_IpProtocolCommon_t *protocol)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(protocol);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerIpProtocolCommon_get(bcm_unit, entry, protocol);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Snap_get
* Purpose:
* Get match criteria for bcmFieldQualifySnap
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Snap_get(bcm_field_entry_t entry,
bcm_field_snap_header_t *data,
bcm_field_snap_header_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Snap_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Llc_get
* Purpose:
* Get match criteria for bcmFieldQualifyLlc
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Llc_get(bcm_field_entry_t entry,
bcm_field_llc_header_t *data,
bcm_field_llc_header_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Llc_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerTpid_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerTpid
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* tpid - (OUT) Qualifier tpid.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerTpid_get(bcm_field_entry_t entry,
uint16 *tpid)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(tpid);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerTpid_get(bcm_unit, entry, tpid);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_OuterTpid_get
* Purpose:
* Get match criteria for bcmFieldQualifyOuterTpid
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* tpid - (OUT) Qualifier tpid.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_OuterTpid_get(bcm_field_entry_t entry,
uint16 *tpid)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(tpid);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_OuterTpid_get(bcm_unit, entry, tpid);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L3Routable_get
* Purpose:
* Get match criteria for bcmFieldQualifyL3Routable
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L3Routable_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L3Routable_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_IpFrag_get
* Purpose:
* Get match criteria for bcmFieldQualifyIpFrag
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* frag_info - (OUT) Qualifier ip framentation encoding.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IpFrag_get(bcm_field_entry_t entry,
bcm_field_IpFrag_t *frag_info)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(frag_info);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_IpFrag_get(bcm_unit, entry, frag_info);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Vrf_get
* Purpose:
* Get match criteria for bcmFieldQualifyVrf
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Vrf_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Vrf_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L3Ingress_get
* Purpose:
* Get match criteria for bcmFieldQualifyL3Ingress
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L3Ingress_get(bcm_field_entry_t entry,
uint32 *data,
uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L3Ingress_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_Vpn_get
* Purpose:
* Get match criteria for bcmFieldQualifyVpn
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_Vpn_get(bcm_field_entry_t entry,
bcm_vpn_t *data,
bcm_vpn_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_Vpn_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_ExtensionHeaderType_get
* Purpose:
* Get match criteria for bcmFieldQualifyExtensionHeaderType
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_ExtensionHeaderType_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_ExtensionHeaderType_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_ExtensionHeaderSubCode_get
* Purpose:
* Get match criteria for bcmFieldQualifyExtensionHeaderSubCode
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_ExtensionHeaderSubCode_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_ExtensionHeaderSubCode_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_ExtensionHeader2Type_get
* Purpose:
* Get match criteria for bcmFieldQualifyExtensionHeader2Type
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_ExtensionHeader2Type_get(bcm_field_entry_t entry,
uint8 *data, uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_ExtensionHeader2Type_get(bcm_unit, entry,
data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L4Ports_get
* Purpose:
* Get match criteria for bcmFieldQualifyL4Ports
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L4Ports_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L4Ports_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_MirrorCopy_get
* Purpose:
* Get match criteria for bcmFieldQualifyMirrorCopy
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_MirrorCopy_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_MirrorCopy_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_TunnelTerminated_get
* Purpose:
* Get match criteria for bcmFieldQualifyTunnelTerminated
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_TunnelTerminated_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_TunnelTerminated_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_MplsTerminated_get
* Purpose:
* Get match criteria for bcmFieldQualifyMplsTerminated
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_MplsTerminated_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_MplsTerminated_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerSrcIp_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerSrcIp
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerSrcIp_get(bcm_field_entry_t entry,
bcm_ip_t *data,
bcm_ip_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerSrcIp_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerDstIp_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerDstIp
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerDstIp_get(bcm_field_entry_t entry,
bcm_ip_t *data,
bcm_ip_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerDstIp_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerSrcIp6_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerSrcIp6
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerSrcIp6_get(bcm_field_entry_t entry,
bcm_ip6_t *data,
bcm_ip6_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerSrcIp6_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerDstIp6_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerDstIp6
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerDstIp6_get(bcm_field_entry_t entry,
bcm_ip6_t *data,
bcm_ip6_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerDstIp6_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerSrcIp6High_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerSrcIp6High
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerSrcIp6High_get(bcm_field_entry_t entry,
bcm_ip6_t *data,
bcm_ip6_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerSrcIp6High_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerDstIp6High_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerDstIp6High
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerDstIp6High_get(bcm_field_entry_t entry,
bcm_ip6_t *data,
bcm_ip6_t *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerDstIp6High_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerTtl_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerTtl
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerTtl_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerTtl_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerTos_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerDSCP
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerTos_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerTos_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerDSCP_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerDSCP
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerDSCP_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerDSCP_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerIpProtocol_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerIpProtocol
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerIpProtocol_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerIpProtocol_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_InnerIpFrag_get
* Purpose:
* Get match criteria for bcmFieldQualifyInnerIpFrag
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* frag_info - (OUT) Inner ip header fragmentation info.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_InnerIpFrag_get(bcm_field_entry_t entry,
bcm_field_IpFrag_t *frag_info)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(frag_info);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_InnerIpFrag_get(bcm_unit, entry, frag_info);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DosAttack_get
* Purpose:
* Get match criteria for bcmFieldQualifyDosAttack
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DosAttack_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DosAttack_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_IpmcStarGroupHit_get
* Purpose:
* Get match criteria for bcmFieldQualifyIpmcStarGroupHit
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IpmcStarGroupHit_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_IpmcStarGroupHit_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_MyStationHit_get
* Purpose:
* Get match criteria for bcmFieldQualifyMyStationHit
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_MyStationHit_get(bcm_field_entry_t entry,
uint8 *data, uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_MyStationHit_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L2PayloadFirstEightBytes_get
* Purpose:
* Get match criteria for bcmFieldQualifyL2PayloadFirstEightBytes
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data1 - (OUT) Qualifier first four bytes of match data.
* data2 - (OUT) Qualifier last four bytes of match data.
* mask1 - (OUT) Qualifier first four bytes of match mask.
* mask2 - (OUT) Qualifier last four bytes of match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L2PayloadFirstEightBytes_get(bcm_field_entry_t entry,
uint32 *data1, uint32 *data2,
uint32 *mask1, uint32 *mask2)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data1);
BCMX_PARAM_NULL_CHECK(data2);
BCMX_PARAM_NULL_CHECK(mask1);
BCMX_PARAM_NULL_CHECK(mask2);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L2PayloadFirstEightBytes_get(bcm_unit, entry,
data1, data2,
mask1, mask2);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L3DestRouteHit_get
* Purpose:
* Get match criteria for bcmFieldQualifyL3DestRouteHit
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L3DestRouteHit_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L3DestRouteHit_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L3DestHostHit_get
* Purpose:
* Get match criteria for bcmFieldQualifyL3DestHostHit
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L3DestHostHit_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L3DestHostHit_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L3SrcHostHit_get
* Purpose:
* Get match criteria for bcmFieldQualifyL3SrcHostHit
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L3SrcHostHit_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L3SrcHostHit_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L2CacheHit_get
* Purpose:
* Get match criteria for bcmFieldQualifyL2CacheHit
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L2CacheHit_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L2CacheHit_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L2StationMove_get
* Purpose:
* Get match criteria for bcmFieldQualifyL2StationMove
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L2StationMove_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L2StationMove_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L2DestHit_get
* Purpose:
* Get match criteria for bcmFieldQualifyL2DestHit
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L2DestHit_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L2DestHit_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L2SrcStatic_get
* Purpose:
* Get match criteria for bcmFieldQualifyL2SrcStatic
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L2SrcStatic_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L2SrcStatic_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_L2SrcHit_get
* Purpose:
* Get match criteria for bcmFieldQualifyL2SrcHit
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_L2SrcHit_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_L2SrcHit_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_IngressStpState_get
* Purpose:
* Get match criteria for bcmFieldQualifyIngressStpState
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IngressStpState_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_IngressStpState_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_ForwardingVlanValid_get
* Purpose:
* Get match criteria for bcmFieldQualifyForwardingVlanValid
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_ForwardingVlanValid_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_ForwardingVlanValid_get(bcm_unit, entry,
data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_SrcVirtualPortValid_get
* Purpose:
* Get match criteria for bcmFieldQualifySrcVirtualPortValid
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_SrcVirtualPortValid_get(bcm_field_entry_t entry,
uint8 *data, uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_SrcVirtualPortValid_get(bcm_unit, entry,
data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_VlanTranslationHit_get
* Purpose:
* Get match criteria for bcmFieldQualifyVlanTranslationHit
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_VlanTranslationHit_get(bcm_field_entry_t entry,
uint8 *data,
uint8 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_VlanTranslationHit_get(bcm_unit, entry,
data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_IcmpTypeCode_get
* Purpose:
* Get match criteria for bcmFieldQualifyIcmpTypeCode
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_IcmpTypeCode_get(bcm_field_entry_t entry,
uint16 *data,
uint16 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_IcmpTypeCode_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_FibreChanOuter_get
* Purpose:
* Get Fibre Channel outer header type field qualification from
* field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* fibre_chan_type - (OUT) Fibre Channel header type.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_FibreChanOuter_get(bcm_field_entry_t entry,
bcm_field_FibreChan_t *fibre_chan_type)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(fibre_chan_type);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_FibreChanOuter_get(bcm_unit, entry,
fibre_chan_type);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_FibreChanInner_get
* Purpose:
* Get Fibre Channel inner header type field qualification from
* field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* fibre_chan_type - (OUT) Fibre Channel header type.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_FibreChanInner_get(bcm_field_entry_t entry,
bcm_field_FibreChan_t *fibre_chan_type)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(fibre_chan_type);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_FibreChanInner_get(bcm_unit, entry,
fibre_chan_type);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_VnTag_get
* Purpose:
* Get match criteria for bcmFieldQualifyVnTag
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_VnTag_get(bcm_field_entry_t entry,
uint32 *data, uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_VnTag_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_CnTag_get
* Purpose:
* Get match criteria for bcmFieldQualifyCnTag
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_CnTag_get(bcm_field_entry_t entry,
uint32 *data, uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_CnTag_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_FabricQueueTag_get
* Purpose:
* Get match criteria for bcmFieldQualifyFabricQueueTag
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (OUT) Qualifier match data.
* mask - (OUT) Qualifier match mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_FabricQueueTag_get(bcm_field_entry_t entry,
uint32 *data, uint32 *mask)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(data);
BCMX_PARAM_NULL_CHECK(mask);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_FabricQueueTag_get(bcm_unit, entry, data, mask);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualify_DstMultipath_get
* Purpose:
* Get match criteria for bcmFieldQualifyDstMultipath
* qualifier from the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* mpintf - (OUT) Multipath egress object id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_DstMultipath_get(bcm_field_entry_t entry, bcm_if_t *mpintf)
{
int rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_PARAM_NULL_CHECK(mpintf);
BCMX_UNIT_ITER(bcm_unit, i) {
rv = bcm_field_qualify_DstMultipath_get(bcm_unit, entry, mpintf);
if (BCMX_FIELD_GET_IS_VALID(bcm_unit, rv)) {
return rv;
}
}
return BCM_E_UNAVAIL;
}
/*
* Function:
* bcmx_field_qualifier_delete
* Purpose:
* Remove match criteria from a field processor entry.
* Parameters:
* entry - (IN) BCM field entry id.
* qual_id - (IN) BCM field qualifier id.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualifier_delete(bcm_field_entry_t entry,
bcm_field_qualify_t qual_id)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualifier_delete(bcm_unit, entry, qual_id);
BCM_IF_ERROR_RETURN
(BCMX_FIELD_DELETE_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_TcpSequenceZero
* Purpose:
* Set match criteria for bcmFieldQualifyTcpSequenceZero
* qualifier to the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* flag - (IN) Flag.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_TcpSequenceZero(bcm_field_entry_t entry,
uint32 flag)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_TcpSequenceZero(bcm_unit, entry, flag);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
/*
* Function:
* bcmx_field_qualify_TcpHeaderSize
* Purpose:
* Set match criteria for bcmFieldQualifyTcpHeaderSize
* qualifier to the field entry.
* Parameters:
* entry - (IN) BCM field entry id.
* data - (IN) Qualifier match data.
* mask - (IN) Qualifier match data mask.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
bcmx_field_qualify_TcpHeaderSize(bcm_field_entry_t entry,
uint8 data, uint8 mask)
{
int rv = BCM_E_UNAVAIL, tmp_rv;
int i, bcm_unit;
BCMX_FIELD_INIT_CHECK;
BCMX_UNIT_ITER(bcm_unit, i) {
tmp_rv = bcm_field_qualify_TcpHeaderSize(bcm_unit, entry, data, mask);
BCM_IF_ERROR_RETURN(BCMX_FIELD_SET_ERROR_CHECK(bcm_unit, tmp_rv, &rv));
}
return rv;
}
| 24.751588 | 134 | 0.612972 | [
"object"
] |
16cb990dd0b295fb340e9f1c762b7b4b1bf7a2a8 | 1,442 | h | C | rooms/room.h | partouf/mytextadventureeditor | 905bef0a8d0fce44a1770c5514f150693767e45e | [
"Apache-2.0"
] | null | null | null | rooms/room.h | partouf/mytextadventureeditor | 905bef0a8d0fce44a1770c5514f150693767e45e | [
"Apache-2.0"
] | null | null | null | rooms/room.h | partouf/mytextadventureeditor | 905bef0a8d0fce44a1770c5514f150693767e45e | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "../stdafx.h"
#include "../items/item.h"
namespace MyTextAdventure
{
struct path_t
{
double Room;
string Title;
};
class CRoomData
{
public:
double Id;
string Title;
string Description;
vector<itemid_t> Items;
vector<path_t> Paths;
string Entry;
string UseItem;
};
class CRoom: public CRoomData
{
protected:
public:
void RemoveItem(itemid_t id);
};
}
/*
* Id: 5,
Title: "The smell of happiness",
Description: "",
Items: [],
Paths: [
{Room: 5.1, Title: "Order a beer"}
],
Entry: function(Player) {
if (Player.HasItem(4)) {
this.Description = "An angry bartender looks at you and immediately shouts: 'HEY YOU, GIVE ME THAT REMOTE!'";
this.Paths = [{Room: 2, Title: "Run out as fast as you can"}];
} else {
this.Description = "A bartender looks grumpy and distracted, but seems ready to take your order nonetheless.";
this.Paths = [{Room: 5.1, Title: "Order a beer"}];
}
},
UseItem: function(Player, ItemId, UI) {
if (ItemId == 4) {
UI.Info("Well done.");
Player.EarnPoints(1);
return 5
} else {
UI.Info("So yeah, you shouldn't have done that.");
return 2;
}
}
*/
| 21.522388 | 126 | 0.518724 | [
"vector"
] |
16ccf3a24d8cf86a4a7054a659fd0dc51de9f1a6 | 6,567 | h | C | src/HTTP2_Frame.h | MITRECND/bro-http2 | 7dc14042d1602065d60601d193b99b005f08fe34 | [
"MIT"
] | 30 | 2018-03-01T01:03:04.000Z | 2022-02-07T11:37:16.000Z | src/HTTP2_Frame.h | MITRECND/bro-http2 | 7dc14042d1602065d60601d193b99b005f08fe34 | [
"MIT"
] | 12 | 2018-04-18T09:24:46.000Z | 2022-01-28T20:36:33.000Z | src/HTTP2_Frame.h | MITRECND/bro-http2 | 7dc14042d1602065d60601d193b99b005f08fe34 | [
"MIT"
] | 17 | 2018-07-20T14:20:40.000Z | 2021-09-26T02:27:42.000Z | #ifndef ANALYZER_PROTOCOL_HTTP2_HTTP2_FRAME_H
#define ANALYZER_PROTOCOL_HTTP2_HTTP2_FRAME_H
static constexpr size_t MAX_FRAME_SIZE = 16777215;
#include "zeek/util.h"
namespace analyzer { namespace mitrecnd {
struct RawFrameHeader
{
uint8_t len[3];
uint8_t typ;
uint8_t flags;
uint8_t streamId[4]; //MSB is reserved bit.
};
static constexpr size_t FRAME_HEADER_LENGTH = (sizeof(RawFrameHeader)/sizeof(uint8_t));
static constexpr uint8_t HTTP2_FRAME_UNDEFINED = 255;
/**
* Class HTTP2_FrameHeader
*
* Description: Represents a frame header, provides easy processing
* of http 2 frame header information including processing of flags
*
*/
class HTTP2_FrameHeader {
public:
HTTP2_FrameHeader(uint8_t* data);
~HTTP2_FrameHeader(void)=default;
// Frame Header Info API
const uint32_t getLen(void) const{return len;};
const uint8_t getType(void) const{return typ;};
const uint8_t getFlags(void) const{return flags;};
const uint32_t getStreamId(void) const{return streamId;};
// Flag functions
bool isEndHeaders(void);
bool isEndStream(void);
bool isPadded(void);
bool isPriority(void);
bool isAck(void);
private:
uint32_t len;
uint8_t typ;
uint8_t flags;
uint32_t streamId;
};
class HTTP2_Frame{
public:
HTTP2_Frame(HTTP2_FrameHeader* h);
virtual ~HTTP2_Frame(void);
const HTTP2_FrameHeader* getHeader(void) const {return this->header;};
const uint8_t getType(void) const {return this->header->getType();};
const uint32_t getStreamId(void) const {return this->header->getStreamId();};
const std::string errorToText(uint32_t error);
bool validate(void){return this->valid;};
protected:
HTTP2_FrameHeader* header;
// Convenience Function to check for padding
bool checkPadding(uint8_t* payload, uint32_t len, uint8_t &padLength);
bool valid;
};
class HTTP2_Data_Frame : public HTTP2_Frame {
public:
HTTP2_Data_Frame(HTTP2_FrameHeader* h, uint8_t* payload, uint32_t len);
~HTTP2_Data_Frame(void);
const uint8_t* getData(uint32_t& len);
bool isEndStream(void){return this->header->isEndStream();};
private:
int dataLength;
uint8_t* dataMsg;
};
class HTTP2_Header_Frame_Base: public HTTP2_Frame {
public:
HTTP2_Header_Frame_Base(HTTP2_FrameHeader* h);
~HTTP2_Header_Frame_Base(void);
const uint8_t* getHeaderBlock(uint32_t& len);
bool isEndHeaders(void){return this->header->isEndHeaders();};
virtual bool isEndStream(void){return this->header->isEndStream();};
protected:
uint8_t* headerBlock;
uint32_t headerBlockLen;
};
class HTTP2_Header_Frame : public HTTP2_Header_Frame_Base {
public:
HTTP2_Header_Frame(HTTP2_FrameHeader* h, uint8_t* payload, uint32_t len);
~HTTP2_Header_Frame(void);
bool isEndStream(void){return this->header->isEndStream();};
};
class HTTP2_Priority_Frame : public HTTP2_Frame {
public:
HTTP2_Priority_Frame(HTTP2_FrameHeader* h, uint8_t* payload, uint32_t len);
~HTTP2_Priority_Frame(void);
uint32_t getDependentStream(void){return dependentStream;};
bool getExclusive(void){return exclusive;};
uint8_t getWeight(void){return weight;};
private:
uint32_t dependentStream;
bool exclusive;
uint8_t weight;
};
class HTTP2_RstStream_Frame : public HTTP2_Frame {
public:
HTTP2_RstStream_Frame(HTTP2_FrameHeader* h, uint8_t* payload, uint32_t len);
~HTTP2_RstStream_Frame(void);
uint32_t getErrorCode(void){return errorCode;};
const std::string getErrorText(void) {return this->errorToText(this->errorCode);};
private:
uint32_t errorCode;
};
class HTTP2_Settings_Frame : public HTTP2_Frame {
public:
HTTP2_Settings_Frame(HTTP2_FrameHeader* h, uint8_t* payload, uint32_t len);
~HTTP2_Settings_Frame(void);
bool getHeaderTableSize(uint32_t& size);
bool getEnablePush(uint32_t& push);
bool getMaxConcurrentStreams(uint32_t& streams);
bool getInitialWindowSize(uint32_t& size);
bool getMaxFrameSize(uint32_t& size);
bool getMaxHeaderListSize(uint32_t& size);
bool unrecognizedSettings(void){return this->unrecognized_settings;};
const std::vector<std::pair<uint16_t, uint32_t>>& getUnrecognizedSettings(void){return (this->unrec_settings);};
bool isAck(void){return this->header->isAck();};
private:
bool header_table_size_set;
bool enable_push_set;
bool max_concurrent_streams_set;
bool initial_window_size_set;
bool max_frame_size_set;
bool max_header_list_size_set;
bool unrecognized_settings;
uint32_t header_table_size;
uint32_t enable_push;
uint32_t max_concurrent_streams;
uint32_t initial_window_size;
uint32_t max_frame_size;
uint32_t max_header_list_size;
std::vector<std::pair<uint16_t, uint32_t>> unrec_settings;
};
class HTTP2_PushPromise_Frame : public HTTP2_Header_Frame_Base {
public:
HTTP2_PushPromise_Frame(HTTP2_FrameHeader* h, uint8_t* payload, uint32_t len);
~HTTP2_PushPromise_Frame(void);
uint32_t getPromisedStreamId(void){return this->promisedStream;};
private:
uint32_t promisedStream;
};
static constexpr size_t PING_OPAQUE_DATA_LENGTH = 8;
class HTTP2_Ping_Frame : public HTTP2_Frame {
public:
HTTP2_Ping_Frame(HTTP2_FrameHeader* h, uint8_t* payload, uint32_t len);
~HTTP2_Ping_Frame(void);
const uint8_t* getData(void){return data;};
bool isAck(void){return this->header->isAck();};
private:
uint8_t data[PING_OPAQUE_DATA_LENGTH];
};
class HTTP2_GoAway_Frame : public HTTP2_Frame {
public:
HTTP2_GoAway_Frame(HTTP2_FrameHeader* h, uint8_t* payload, uint32_t len);
~HTTP2_GoAway_Frame(void);
uint32_t getLastStreamId(void){return lastStreamId;};
uint32_t getErrorCode(void){return errorCode;};
const uint8_t* getDebugData(uint32_t& len);
const std::string getErrorText(void) {return this->errorToText(this->errorCode);};
private:
uint32_t lastStreamId;
uint32_t errorCode;
uint8_t* debugData;
uint32_t debugDataLength;
};
class HTTP2_WindowUpdate_Frame : public HTTP2_Frame {
public:
HTTP2_WindowUpdate_Frame(HTTP2_FrameHeader* h, uint8_t* payload, uint32_t len);
~HTTP2_WindowUpdate_Frame(void);
const uint32_t getSizeIncrement(void) const {return sizeIncrement;};
private:
uint32_t sizeIncrement;
};
class HTTP2_Continuation_Frame : public HTTP2_Header_Frame {
public:
HTTP2_Continuation_Frame(HTTP2_FrameHeader* h, uint8_t* payload, uint32_t len);
~HTTP2_Continuation_Frame(void);
private:
};
} } // namespace analyzer::*
#endif
| 27.476987 | 116 | 0.747069 | [
"vector"
] |
16d8ac584ccf6db8233de39f6ab8aa5c18f76dee | 2,067 | h | C | Models/Core Data Model Entity Subclasses/Entity Subclass Utils/Song+Utilities.h | mzgaljic/mzgaljic | 9918a92bcfae140fcb52d849423b06624acc502b | [
"MIT"
] | 7 | 2017-05-10T15:46:28.000Z | 2021-04-26T04:25:01.000Z | Models/Core Data Model Entity Subclasses/Entity Subclass Utils/Song+Utilities.h | mzgaljic/mzgaljic | 9918a92bcfae140fcb52d849423b06624acc502b | [
"MIT"
] | 1 | 2017-08-07T15:44:12.000Z | 2017-08-10T01:48:13.000Z | Models/Core Data Model Entity Subclasses/Entity Subclass Utils/Song+Utilities.h | mzgaljic/mzgaljic | 9918a92bcfae140fcb52d849423b06624acc502b | [
"MIT"
] | null | null | null | //
// Song+Utilities.h
// Muzic
//
// Created by Mark Zgaljic on 8/16/14.
// Copyright (c) 2014 Mark Zgaljic. All rights reserved.
//
#import "Song.h"
#import "Artist.h"
#import "Album.h"
#import "Album+Utilities.h"
#import "Artist.h"
#import "Artist+Utilities.h"
#import "NSObject+ObjectUUID.h"
#import "NSString+smartSort.h"
@interface Song (Utilities)
/**
@Description Creates a new song given the arguments provided. All are optional except songName and genreCode.
*note: The GenreConstants class contains a convenience method to obtain a 'no genre code selected' int value. Use
this if required. Genre constant will be set to 'no genre code selected' if the provided genre code is invalid.
@param songName name for the created song; required field.
@param albumOrAlbumName an Album object (if the created song should be a part of that album), or an NSString
object (with the albums name) if an album should be created for this song. nil if not desired.
@param artistOrArtistName an Artist object (if the created song should be a part of that artist), or an NSString
object (with the artists name) if an artist should be created for this song. nil if not desired.
@param context An NSManagedObjectContext object, which is requied for the backing core data store. If this
parameter is nil, nil shall be returned. Optional (but crucial) argument.
@param durationInSeconds An NSUInteger specifying the duration in seconds of the song to be created.
*/
+ (Song *)createNewSongWithName:(NSString *)songName
inNewOrExistingAlbum:(id)albumOrAlbumName
byNewOrExistingArtist:(id)artistOrArtistName
inManagedContext:(NSManagedObjectContext *)context
withDuration:(NSInteger)durationInSeconds;
/**
Creates a song object which has no name (ie: it is in the process of user creation).
*/
+ (Song *)createNewSongWithNoNameAndManagedContext:(NSManagedObjectContext *)context;
+ (BOOL)isSong:(Song *)song1 equalToSong:(Song *)song2;
- (BOOL)isEqualToSong:(Song *)aSong;
@end
| 42.183673 | 120 | 0.740203 | [
"object"
] |
16db9878cbde3149a8903211384f5e51a8b4fa3c | 5,942 | h | C | Engine/include/render/RenderTarget.h | katoun/kg_engine | fdcc6ec01b191d07cedf7a8d6c274166e25401a8 | [
"Unlicense"
] | 2 | 2015-04-21T05:36:12.000Z | 2017-04-16T19:31:26.000Z | Engine/include/render/RenderTarget.h | katoun/kg_engine | fdcc6ec01b191d07cedf7a8d6c274166e25401a8 | [
"Unlicense"
] | null | null | null | Engine/include/render/RenderTarget.h | katoun/kg_engine | fdcc6ec01b191d07cedf7a8d6c274166e25401a8 | [
"Unlicense"
] | null | null | null | /*
-----------------------------------------------------------------------------
KG game engine (http://katoun.github.com/kg_engine) is made available under the MIT License.
Copyright (c) 2006-2013 Catalin Alexandru Nastase
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef _RENDER_TARGET_H_
#define _RENDER_TARGET_H_
#include <EngineConfig.h>
#include <platform/PlatformManager.h>
#include <render/RenderTargetEventReceiver.h>
#include <list>
namespace render
{
class Camera;
class Viewport;
struct RenderTargetEvent;
class RenderTargetViewportEvent;
//! A 'canvas' which can receive the results of a rendering
//! operation.
//!
//! This abstract class defines a common root to all targets of rendering operations.
//! A render target could be a window on a screen, or another off screen surface like a texture or bump map etc.
class ENGINE_PUBLIC_EXPORT RenderTarget
{
public:
struct FrameStats
{
float lastFPS;
float avgFPS;
float bestFPS;
float worstFPS;
int triangleCount;
};
RenderTarget();
virtual ~RenderTarget();
//! Returns the id of the resource.
const unsigned int& getID() const;
//! Retrieve information about the render target.
virtual unsigned int getWidth() const;
virtual unsigned int getHeight() const;
virtual unsigned int getColorDepth() const;
//! Create a viewport to the rendering target.
//!
//! A viewport is the rectangle into which redering output is sent. This method adds
//! a viewport to the render target, rendering from the supplied camera. The
//! rest of the parameters are only required if you wish to add more than one viewport
//! to a single rendering target. Note that size information passed to this method is
//! passed as a parametric, i.e. it is relative rather than absolute. This is to allow
//! viewports to automatically resize along with the target.
//! \param cam: The camera from which the viewport contents will be rendered (mandatory)
//! viewports i.e. picture-in-picture). Higher ZOrders are on top of lower ones. The actual number
//! is irrelevant, only the relative ZOrder matters (you can leave gaps in the numbering)
//! \param top: The relative position of the top of the viewport on the target, as a value between 0 and 1.
//! \param left: The relative position of the left of the viewport on the target, as a value between 0 and 1.
//! \param width: The relative width of the viewport on the target, as a value between 0 and 1.
//! \param height: The relative height of the viewport on the target, as a value between 0 and 1.
virtual Viewport* createViewport(Camera* cam, float top = 0.0f, float left = 0.0f, float width = 1.0f, float height = 1.0f);
//! Removes a viewport from the rendering target.
virtual void removeViewport(Viewport* viewport);
//! Removes all viewports on this target.
virtual void removeAllViewports();
virtual const FrameStats& getStatistics() const;
//! Individual stats access - gets the number of frames per second (FPS) based on the last frame rendered.
virtual float getLastFPS() const;
//! Individual stats access - gets the average frames per second (FPS) since call to RenderSystem::startRendering.
virtual float getAverageFPS() const;
//! Individual stats access - gets the best frames per second (FPS) since call to RenderSystem::startRendering.
virtual float getBestFPS() const;
//! Individual stats access - gets the worst frames per second (FPS) since call to RenderSystem::startRendering.
virtual float getWorstFPS() const;
//! Gets the number of triangles rendered in the last update() call.
virtual int getTriangleCount() const;
//! Resets saved frame-rate statistices.
virtual void resetStatistics();
//! Used to retrieve or set the active state of the render target.
virtual bool isActive() const;
//! Used to set the active state of the render target.
virtual void setActive(bool state);
void update(float elapsedTime);
void addRenderTargetEventReceiver(RenderTargetEventReceiver* newEventReceiver);
void removeRenderTargetEventReceiver(RenderTargetEventReceiver* oldEventReceiver);
std::list<Viewport*>& getViewports();
protected:
unsigned int mID;
// Incremented count for next index
static unsigned int mIndexCounter;
virtual void updateImpl(float elapsedTime);
//! Central list of viewports - for easy memory management and lookup.
std::list<Viewport*> mViewports;
unsigned int mWidth;
unsigned int mHeight;
unsigned int mColorDepth;
bool mIsDepthBuffered;
// Stats
FrameStats mStats;
int mFrameCount;
float mLastElapsedTime;
bool mActive;
RenderTargetEvent* mRenderTargetEvent;
std::list<RenderTargetEventReceiver*> mRenderTargetEventReceivers;
void updateStats();
//! internal method for firing events.
virtual void firePreUpdate();
//! internal method for firing events.
virtual void firePostUpdate();
};
} // end namespace render
#endif | 36.231707 | 125 | 0.74655 | [
"render"
] |
16def06a4c2ba80a5e5d2d091c73e6e40ee18e7e | 3,458 | h | C | src/r3.endlesss/endlesss/live.stem.h | Unbundlesss/OUROVEON | 34dda511eda2a28b8522a724cfc9500a7914ea03 | [
"MIT"
] | 6 | 2022-01-27T20:33:17.000Z | 2022-02-16T18:29:43.000Z | src/r3.endlesss/endlesss/live.stem.h | Unbundlesss/OUROVEON | 34dda511eda2a28b8522a724cfc9500a7914ea03 | [
"MIT"
] | 4 | 2022-01-30T16:16:53.000Z | 2022-02-20T20:07:25.000Z | src/r3.endlesss/endlesss/live.stem.h | Unbundlesss/OUROVEON | 34dda511eda2a28b8522a724cfc9500a7914ea03 | [
"MIT"
] | null | null | null | // _______ _______ ______ _______ ___ ___ _______ _______ _______
// | | | | __ \ | | | ___| | | |
// | - | | | < - | | | ___| - | |
// |_______|_______|___|__|_______|\_____/|_______|_______|__|____|
// ishani.org 2022 e.t.c. MIT License
//
//
//
#pragma once
#include "endlesss/api.h"
#include "core.types.h"
namespace config { namespace endlesss { struct API; } }
namespace endlesss {
namespace live {
// ---------------------------------------------------------------------------------------------------------------------
struct Stem
{
enum class State
{
Empty,
WorkEnqueued,
Complete,
Failed_Http,
Failed_DataUnderflow,
Failed_DataOverflow,
Failed_Vorbis,
Failed_CacheDirectory,
};
Stem( const types::Stem& stemData, const uint32_t targetSampleRate );
~Stem();
void fetch( const api::NetConfiguration& ncfg, const fs::path& cachePath );
void fft();
// stem needs a copy of the analysis task future to ensure that in the unlikely case
// of destruction arriving before the task is done, we wait to avoid the analysis working with a deleted object
inline void keepFuture( std::shared_future<void>& analysisFuture )
{
assert( !m_analysisFuture.valid() );
m_analysisFuture = analysisFuture;
}
inline bool isAnalysisComplete() const
{
return m_hasValidAnalysis;
}
constexpr bool hasFailed() const
{
return ( m_state == State::Failed_Http ||
m_state == State::Failed_DataUnderflow ||
m_state == State::Failed_DataOverflow ||
m_state == State::Failed_Vorbis ||
m_state == State::Failed_CacheDirectory );
}
private:
struct RawAudioMemory
{
RawAudioMemory( size_t size );
~RawAudioMemory();
void allocate( size_t newSize );
size_t m_rawLength;
size_t m_rawReceived;
uint8_t* m_rawAudio;
};
// make an attempt to download the stem from the Endlesss CDN; this may fail and that may be because the CDN
// hasn't actually got the data yet - so we can call this function repeatedly to see if success is possible
// after a little delay
// returns false if something broke; sets the m_state appropriately in that case
bool attemptRemoteFetch( const api::NetConfiguration& ncfg, const uint32_t attemptUID, RawAudioMemory& audioMemory );
size_t computeMemoryUsage() const;
std::shared_future<void> m_analysisFuture;
std::atomic_bool m_hasValidAnalysis; // set in async analysis if analysis data is to be trusted
public:
const types::Stem m_data;
ImU32 m_colourU32; // converted from m_data and cached
State m_state;
uint32_t m_sampleRate;
int32_t m_sampleCount;
std::array<float*, 2> m_channel;
std::vector< double > m_detectedBeatTimes;
std::vector< float > m_sampleEnergy;
std::vector< uint64_t > m_sampleBeat;
};
using StemPtr = std::shared_ptr<Stem>;
} // namespace live
} // namespace endlesss
| 31.436364 | 121 | 0.560729 | [
"object",
"vector"
] |
16e2294466e39c4da881b18955329cf4fd5fab81 | 15,815 | h | C | include/smp_lib.h | xiphmont/smp_utils | 909b789aef2b7304b980507319e358cce8fdec63 | [
"BSD-3-Clause"
] | 8 | 2018-02-23T07:12:51.000Z | 2021-06-25T18:11:32.000Z | include/smp_lib.h | xiphmont/smp_utils | 909b789aef2b7304b980507319e358cce8fdec63 | [
"BSD-3-Clause"
] | 2 | 2021-06-16T03:44:39.000Z | 2021-09-13T00:56:10.000Z | include/smp_lib.h | xiphmont/smp_utils | 909b789aef2b7304b980507319e358cce8fdec63 | [
"BSD-3-Clause"
] | 2 | 2020-10-08T01:28:35.000Z | 2021-03-11T21:36:48.000Z | #ifndef SMP_LIB_H
#define SMP_LIB_H
/*
* Copyright (c) 2006-2018 Douglas Gilbert.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
/*
* Version: see version_str in smp_lib.c
*/
/* This header file contains defines and function declarations that may
* be useful to Linux applications that communicate with devices that
* use the Serial Attached SCSI (SAS) Management Protocol (SMP).
* Reference: SCSI: http://www.t10.org and the most recent SAS Protocol
* Layer draft SPL-4 (revision 2).
*/
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* SAS transport frame types associated with SMP */
#define SMP_FRAME_TYPE_REQ 0x40
#define SMP_FRAME_TYPE_RESP 0x41
/* SMP function codes */
#define SMP_FN_REPORT_GENERAL 0x0
#define SMP_FN_REPORT_MANUFACTURER 0x1
#define SMP_FN_READ_GPIO_REG 0x2
#define SMP_FN_REPORT_SELF_CONFIG 0x3
#define SMP_FN_REPORT_ZONE_PERMISSION_TBL 0x4
#define SMP_FN_REPORT_ZONE_MANAGER_PASS 0x5
#define SMP_FN_REPORT_BROADCAST 0x6
#define SMP_FN_READ_GPIO_REG_ENH 0x7
#define SMP_FN_DISCOVER 0x10
#define SMP_FN_REPORT_PHY_ERR_LOG 0x11
#define SMP_FN_REPORT_PHY_SATA 0x12
#define SMP_FN_REPORT_ROUTE_INFO 0x13
#define SMP_FN_REPORT_PHY_EVENT 0x14
/* #define SMP_FN_REPORT_PHY_BROADCAST 0x15 removed in sas2r13 */
#define SMP_FN_DISCOVER_LIST 0x20 /* was 0x16 in sas2r10 */
#define SMP_FN_REPORT_PHY_EVENT_LIST 0x21
#define SMP_FN_REPORT_EXP_ROUTE_TBL_LIST 0x22 /* was 0x17 in sas2r10 */
#define SMP_FN_CONFIG_GENERAL 0x80
#define SMP_FN_ENABLE_DISABLE_ZONING 0x81
#define SMP_FN_WRITE_GPIO_REG 0x82
#define SMP_FN_WRITE_GPIO_REG_ENH 0x83
#define SMP_FN_ZONED_BROADCAST 0x85
#define SMP_FN_ZONE_LOCK 0x86
#define SMP_FN_ZONE_ACTIVATE 0x87
#define SMP_FN_ZONE_UNLOCK 0x88
#define SMP_FN_CONFIG_ZONE_MANAGER_PASS 0x89
#define SMP_FN_CONFIG_ZONE_PHY_INFO 0x8a
#define SMP_FN_CONFIG_ZONE_PERMISSION_TBL 0x8b
#define SMP_FN_CONFIG_ROUTE_INFO 0x90
#define SMP_FN_PHY_CONTROL 0x91
#define SMP_FN_PHY_TEST_FUNCTION 0x92
#define SMP_FN_CONFIG_PHY_EVENT 0x93
/* SMP function result values */
#define SMP_FRES_FUNCTION_ACCEPTED 0x0
#define SMP_FRES_UNKNOWN_FUNCTION 0x1
#define SMP_FRES_FUNCTION_FAILED 0x2
#define SMP_FRES_INVALID_REQUEST_LEN 0x3
#define SMP_FRES_INVALID_EXP_CHANGE_COUNT 0x4
#define SMP_FRES_BUSY 0x5
#define SMP_FRES_INCOMPLETE_DESCRIPTOR_LIST 0x6
#define SMP_FRES_NO_PHY 0x10
#define SMP_FRES_NO_INDEX 0x11
#define SMP_FRES_NO_SATA_SUPPORT 0x12
#define SMP_FRES_UNKNOWN_PHY_OP 0x13
#define SMP_FRES_UNKNOWN_PHY_TEST_FN 0x14
#define SMP_FRES_PHY_TEST_IN_PROGRESS 0x15
#define SMP_FRES_PHY_VACANT 0x16
#define SMP_FRES_UNKNOWN_PHY_EVENT_SRC 0x17
#define SMP_FRES_UNKNOWN_DESCRIPTOR_TYPE 0x18
#define SMP_FRES_UNKNOWN_PHY_FILTER 0x19
#define SMP_FRES_AFFILIATION_VIOLATION 0x1a
#define SMP_FRES_SMP_ZONE_VIOLATION 0x20
#define SMP_FRES_NO_MANAGEMENT_ACCESS 0x21
#define SMP_FRES_UNKNOWN_EN_DIS_ZONING_VAL 0x22
#define SMP_FRES_ZONE_LOCK_VIOLATION 0x23
#define SMP_FRES_NOT_ACTIVATED 0x24
#define SMP_FRES_ZONE_GROUP_OUT_OF_RANGE 0x25
#define SMP_FRES_NO_PHYSICAL_PRESENCE 0x26
#define SMP_FRES_SAVING_NOT_SUPPORTED 0x27
#define SMP_FRES_SOURCE_ZONE_GROUP 0x28
#define SMP_FRES_DIS_PASSWORD_NOT_SUPPORTED 0x29
#define SMP_FRES_INVALID_FIELD_IN_REQUEST 0x2a
/* Utilities can use these process status values for syntax errors and
file (device node) problems (e.g. not found or permissions). Numbers
between 1 and 32 are reserved for SMP function result values */
#define SMP_LIB_SYNTAX_ERROR 91
#define SMP_LIB_FILE_ERROR 92
#define SMP_LIB_RESOURCE_ERROR 93
#define SMP_LIB_CAT_MALFORMED 97
#define SMP_LIB_CAT_OTHER 99
#define SMP_MAX_DEVICE_NAME 256
#ifdef SMP_UTILS_LINUX
#define SMP_SUBVALUE_SEPARATOR ','
#elif defined(SMP_UTILS_SOLARIS)
#define SMP_SUBVALUE_SEPARATOR '^'
#else
#define SMP_SUBVALUE_SEPARATOR ','
#endif
struct smp_target_obj {
char device_name[SMP_MAX_DEVICE_NAME];
int subvalue; /* adapter number (opt) */
unsigned char sas_addr[8]; /* target SMP (opt) */
int interface_selector;
int opened;
int fd;
void * vp; /* opaque for pass-through (e.g. CAM) */
};
/* SAS standards include a 4 byte CRC at the end of each SMP request
and response framesl. All current pass-throughs calculate and check
the CRC in the driver, but some pass-throughs want the space allocated.
*/
struct smp_req_resp {
int request_len; /* [i] in bytes, includes space for 4 byte
CRC */
unsigned char * request; /* [*i], includes space for CRC */
int max_response_len; /* [i] in bytes, includes space for CRC */
unsigned char * response; /* [*o] */
int act_response_len; /* [o] -1 implies don't know */
int transport_err; /* [o] 0 implies no error */
};
#if (__STDC_VERSION__ >= 199901L) /* C99 or later */
typedef uintptr_t smp_uintptr_t;
#else
typedef unsigned long smp_uintptr_t;
#endif
/* Open device_name (perhaps using associated subvalue, i_params, and sa
* fields) and if successful places context information in the object pointed
* to by tobj . Returns 0 on success, else -1 . */
int smp_initiator_open(const char * device_name, int subvalue,
const char * i_params, uint64_t sa,
struct smp_target_obj * tobj, int verbose);
/* Send a SMP request to the SMP target referred to by tobj. The request
* and space for the response (including the CRC even if it is not sent
* or returned) are in the object pointed to by rresp. Returns 0 on
* success. */
int smp_send_req(const struct smp_target_obj * tobj,
struct smp_req_resp * rresp, int verbose);
/* Closes the context to the SMP target referred to by tobj. Returns 0
* on success, else -1 . */
int smp_initiator_close(struct smp_target_obj * tobj);
/* Given an SMP function response code in func_res, places the associated
* string (most likely an error if func_res > 0) in the area pointed to
* by buffer. That string will not exceed buff_len bytes. Returns buff
* as its result. */
char * smp_get_func_res_str(int func_res, int buff_len, char * buff);
/* Returns the request length in dwords associated with func_code in SAS-1.
* The dword count excludes the 4 byte header and the 4 byte CRC (i.e.
* eight bytes or two dwords). Returns -2 for no default (e.g. functions
* found in SAS-2 or later) and -3 for a different format (e.g. READ GPIO
* REGISTER). */
int smp_get_func_def_req_len(int func_code);
/* Returns the expected response length in dwords associated with func_code
* in SAS-1. The dword count excludes the 4 byte header and the 4 byte CRC.
* Returns -2 for no default and -3 for a different format (e.g. READ GPIO
* REGISTER). */
int smp_get_func_def_resp_len(int func_code);
/* spl5r04.pdf says a valid SAS address can be NAA-5 or NAA-3 (locally
* assigned). It prefers NAA-5 . Returns true if is, else false. */
bool smp_is_sas_naa(uint64_t addr);
/* SAS addresses are NAA-5 and should have 5 in their most significant
* nibble. Returns true if NAA-5 format, else false. Use smp_is_sas_naa() */
bool smp_is_naa5(uint64_t addr);
/* Connector names are taken from the most recent SES draft; in this case
* ses4r01. If plink is true the "(<maximum >physical links: <n>)" is
* appended to connector type string. <n> is 0 if conn_type is 0 or not
* found. <maximum > only prints "maximum " when <n> is greater than 1 .
* Returns buff as its result and its length (including a trailing null
* character) will not exceed buff_len. */
char * smp_get_connector_type_str(int conn_type, bool plink, int buff_len,
char * buff);
/* Returns pointer to phy power condition string or "illegal" if the
* 'phy_pwr_cond' value is out of range. Pointer value returned is same
* as 'buff'. String placed in 'buff' is null terminated and its length
* (including terminator) does not exceed 'buff_len'. Does nothing if
*'buff' is NULL or 'buff_len' less than 1. If 'buff_len' is 1 then just
* puts null character in 'buff'. */
char * smp_get_phy_pwr_cond_str(int phy_pwr_cond, int buff_len, char * buff);
/* Returns pointer to pwr_dis signal string or "illegal" if the
* 'pwr_dis_signal' value is out of range. Pointer value returned is same
* as 'buff'. String placed in 'buff' is null terminated and its length
* (including terminator) does not exceed 'buff_len'. Does nothing if
*'buff' is NULL or 'buff_len' less than 1. If 'buff_len' is 1 then just
* puts null character in 'buff'. */
char * smp_get_pwr_dis_signal_str(int pwr_dis_signal,
int buff_len, char * buff);
const char * smp_lib_version();
struct smp_val_name {
int value;
const char * name;
};
/* <<< General purpose (i.e. not SMP specific) utility functions >>> */
/* Always returns valid string even if errnum is wild (or library problem).
If errnum is negative, flip its sign. */
char * safe_strerror(int errnum);
/* Print (to stdout) 'str' of bytes in hex, 16 bytes per line optionally
followed at the right hand side of the line with an ASCII interpretation.
Each line is prefixed with an address, starting at 0 for str[0]..str[15].
All output numbers are in hex. 'no_ascii' allows for 3 output types:
> 0 each line has address then up to 16 ASCII-hex bytes
= 0 in addition, the bytes are listed in ASCII to the right
< 0 only the ASCII-hex bytes are listed (i.e. without address)
*/
void dStrHex(const char* str, int len, int no_ascii);
/* Print (to stderr) 'str' of bytes in hex, 16 bytes per line optionally
* followed at right by its ASCII interpretation. Same logic as dStrHex()
* with different output stream (i.e. stderr). */
void dStrHexErr(const char * str, int len, int no_ascii);
/* Read 'len' bytes from 'str' and output as ASCII-Hex bytes (space
* separated) to 'b' not to exceed 'b_len' characters. Each line
* starts with 'leadin' (NULL for no leadin) and there are 16 bytes
* per line with an extra space between the 8th and 9th bytes. 'format'
* is 0 for repeat in printable ASCII ('.' for non printable chars) to
* right of each line; 1 don't (so just output ASCII hex). Returns
* number of bytes written to 'b' excluding the trailing '\0'. */
int dStrHexStr(const char * str, int len, const char * leadin, int format,
int b_len, char * b);
/* The following 3 functions are equivalent to dStrHex(), dStrHexErr() and
* dStrHexStr() respectively. The difference is the type of the first of
* argument: uint8_t instead of char. The name of the argument is changed
* to b_str to stress it is a pointer to the start of a binary string. */
void hex2stdout(const uint8_t * b_str, int len, int no_ascii);
void hex2stderr(const uint8_t * b_str, int len, int no_ascii);
int hex2str(const uint8_t * b_str, int len, const char * leadin, int format,
int cb_len, char * cbp);
/* Returns pointer to heap (or NULL) that is aligned to a align_to byte
* boundary. Sends back *buff_to_free pointer in third argument that may be
* different from the return value. If it is different then the *buff_to_free
* pointer should be freed (rather than the returned value) when the heap is
* no longer needed. If align_to is 0 then aligns to OS's page size. Sets all
* returned heap to zeros. If num_bytes is 0 then set to page size. */
uint8_t * smp_memalign(uint32_t num_bytes, uint32_t align_to,
uint8_t ** buff_to_free, bool vb);
/* Returns OS page size in bytes. If uncertain returns 4096. */
uint32_t smp_get_page_size(void);
/* If byte_count is 0 or less then the OS page size is used. Returns true
* if the remainder of ((unsigned)pointer % byte_count) is 0, else returns
* false. */
bool smp_is_aligned(const void * pointer, int byte_count);
/* Returns true when executed on big endian machine; else returns false.
* Useful for displaying ATA identify words (which need swapping on a
* big endian machine).
*/
bool smp_is_big_endian();
/* Returns true if byte sequence starting at bp with a length of b_len is
* all zeros (for smp_all_zeros()) or all 0xff_s (for smp_all_ffs());
* otherwise returns false. If bp is NULL ir b_len <= 0 returns false. */
bool smp_all_zeros(const uint8_t * bp, int b_len);
bool smp_all_ffs(const uint8_t * bp, int b_len);
/* If the number in 'buf' can not be decoded or the multiplier is unknown
then -1 is returned. Accepts a hex prefix (0x or 0X) or a 'h' (or 'H')
suffix. Otherwise a decimal multiplier suffix may be given. Recognised
multipliers: c C *1; w W *2; b B *512; k K KiB *1,024;
KB *1,000; m M MiB *1,048,576; MB *1,000,000; g G GiB *1,073,741,824;
GB *1,000,000,000 and <n>x<m> which multiplies <n> by <m> . */
int smp_get_num(const char * buf);
/* If the number in 'buf' can not be decoded then -1 is returned. Accepts a
* hex prefix (0x or 0X) or a 'h' (or 'H') suffix; otherwise decimal is
* assumed. Does not accept multipliers. Accept a comma (","), hyphen ("-"),
* a whitespace or newline as terminator. Only decimal numbers can represent
* negative numbers and '-1' must be treated separately. */
int smp_get_num_nomult(const char * buf);
/* If the number in 'buf' can not be decoded or the multiplier is unknown
then -1LL is returned. Accepts a hex prefix (0x or 0X) or a 'h' (or 'H')
suffix. Otherwise a decimal multiplier suffix may be given. In addition
to supporting the multipliers of smp_get_num(), this function supports:
t T TiB *(2**40); TB *(10**12); p P PiB *(2**50); PB *(10**15) . */
int64_t smp_get_llnum(const char * buf);
/* If the number in 'buf' can not be decoded then -1 is returned. Accepts a
* hex prefix (0x or 0X) or a 'h' (or 'H') suffix; otherwise decimal is
* assumed. Does not accept multipliers. Accept a comma (","), hyphen ("-"),
* a whitespace or newline as terminator. Only decimal numbers can represent
* negative numbers and '-1' must be treated separately. */
int64_t smp_get_llnum_nomult(const char * buf);
/* If the non-negative number in 'buf' can be decoded in decimal (default)
* or hex then it is returned, else -1 is returned. Skips leading and
* trailing spaces, tabs and commas. Hex numbers are indicated by a "0x"
* or "0X" prefix, or by a 'h' or 'H' suffix. */
int smp_get_dhnum(const char * buf);
#ifdef __cplusplus
}
#endif
#endif
| 43.567493 | 77 | 0.738476 | [
"object"
] |
16e5dd82340472f227abf3272df463739cd0cc47 | 767 | h | C | aws-cpp-sdk-mediaconvert/include/aws/mediaconvert/model/DvbSubtitleStylePassthrough.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-mediaconvert/include/aws/mediaconvert/model/DvbSubtitleStylePassthrough.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-mediaconvert/include/aws/mediaconvert/model/DvbSubtitleStylePassthrough.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/mediaconvert/MediaConvert_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace MediaConvert
{
namespace Model
{
enum class DvbSubtitleStylePassthrough
{
NOT_SET,
ENABLED,
DISABLED
};
namespace DvbSubtitleStylePassthroughMapper
{
AWS_MEDIACONVERT_API DvbSubtitleStylePassthrough GetDvbSubtitleStylePassthroughForName(const Aws::String& name);
AWS_MEDIACONVERT_API Aws::String GetNameForDvbSubtitleStylePassthrough(DvbSubtitleStylePassthrough value);
} // namespace DvbSubtitleStylePassthroughMapper
} // namespace Model
} // namespace MediaConvert
} // namespace Aws
| 23.96875 | 112 | 0.794003 | [
"model"
] |
16f41e35c79325a663b709b636a31aaa4285814c | 9,379 | c | C | src/AStrCArray_object.c | 2kranki/libCmn | 4f9db4c9c8e2dff64e1c741dc1c11e9f3b5d07ce | [
"Unlicense"
] | 2 | 2017-03-23T15:23:56.000Z | 2021-03-04T09:54:54.000Z | src/AStrCArray_object.c | 2kranki/libCmn | 4f9db4c9c8e2dff64e1c741dc1c11e9f3b5d07ce | [
"Unlicense"
] | null | null | null | src/AStrCArray_object.c | 2kranki/libCmn | 4f9db4c9c8e2dff64e1c741dc1c11e9f3b5d07ce | [
"Unlicense"
] | null | null | null | // vi: nu:noai:ts=4:sw=4
// Class Object Metods and Tables for 'AStrCArray'
// Generated 11/07/2019 08:58:19
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org/>
*/
#define ASTRCARRAY_OBJECT_C 1
#include <AStrCArray_internal.h>
#ifdef ASTRCARRAY_SINGLETON
#include <psxLock.h>
#endif
//===========================================================
// Class Object Definition
//===========================================================
struct AStrCArray_class_data_s {
// Warning - OBJ_DATA must be first in this object!
OBJ_DATA super;
// Common Data
#ifdef ASTRCARRAY_SINGLETON
volatile
ASTRCARRAY_DATA *pSingleton;
#endif
//uint32_t misc;
//OBJ_ID pObjCatalog;
};
//-----------------------------------------------------------
// Class Methods
//-----------------------------------------------------------
static
void * AStrCArrayClass_QueryInfo (
OBJ_ID objId,
uint32_t type,
void *pData
);
static
const
OBJ_INFO AStrCArray_Info; // Forward Reference
static
bool AStrCArrayClass_IsKindOf (
uint16_t classID
)
{
if (OBJ_IDENT_ASTRCARRAY_CLASS == classID) {
return true;
}
if (OBJ_IDENT_OBJ_CLASS == classID) {
return true;
}
return false;
}
static
uint16_t AStrCArrayClass_WhoAmI (
void
)
{
return OBJ_IDENT_ASTRCARRAY_CLASS;
}
//===========================================================
// Class Object Vtbl Definition
//===========================================================
static
const
ASTRCARRAY_CLASS_VTBL class_Vtbl = {
{
&AStrCArray_Info,
AStrCArrayClass_IsKindOf,
obj_RetainNull,
obj_ReleaseNull,
NULL,
AStrCArray_Class,
AStrCArrayClass_WhoAmI,
(P_OBJ_QUERYINFO)AStrCArrayClass_QueryInfo,
NULL // AStrCArrayClass_ToDebugString
},
};
//-----------------------------------------------------------
// Class Object
//-----------------------------------------------------------
ASTRCARRAY_CLASS_DATA AStrCArray_ClassObj = {
{
(const OBJ_IUNKNOWN *)&class_Vtbl, // pVtbl
sizeof(ASTRCARRAY_CLASS_DATA), // cbSize
0, // cbFlags
1, // cbRetainCount
{0} // cbMisc
},
//0
};
//---------------------------------------------------------------
// S i n g l e t o n M e t h o d s
//---------------------------------------------------------------
#ifdef ASTRCARRAY_SINGLETON
ASTRCARRAY_DATA * AStrCArray_getSingleton (
void
)
{
return (OBJ_ID)(AStrCArray_ClassObj.pSingleton);
}
bool AStrCArray_setSingleton (
ASTRCARRAY_DATA *pValue
)
{
PSXLOCK_DATA *pLock = OBJ_NIL;
bool fRc;
pLock = psxLock_New( );
if (OBJ_NIL == pLock) {
DEBUG_BREAK();
return false;
}
fRc = psxLock_Lock(pLock);
if (!fRc) {
DEBUG_BREAK();
obj_Release(pLock);
pLock = OBJ_NIL;
return false;
}
obj_Retain(pValue);
if (AStrCArray_ClassObj.pSingleton) {
obj_Release((OBJ_ID)(AStrCArray_ClassObj.pSingleton));
}
AStrCArray_ClassObj.pSingleton = pValue;
fRc = psxLock_Unlock(pLock);
obj_Release(pLock);
pLock = OBJ_NIL;
return true;
}
ASTRCARRAY_DATA * AStrCArray_Shared (
void
)
{
ASTRCARRAY_DATA *this = (OBJ_ID)(AStrCArray_ClassObj.pSingleton);
if (NULL == this) {
this = AStrCArray_New( );
AStrCArray_setSingleton(this);
obj_Release(this); // Shared controls object retention now.
// AStrCArray_ClassObj.pSingleton = OBJ_NIL;
}
return this;
}
void AStrCArray_SharedReset (
void
)
{
ASTRCARRAY_DATA *this = (OBJ_ID)(AStrCArray_ClassObj.pSingleton);
if (this) {
obj_Release(this);
AStrCArray_ClassObj.pSingleton = OBJ_NIL;
}
}
#endif
//---------------------------------------------------------------
// Q u e r y I n f o
//---------------------------------------------------------------
static
void * AStrCArrayClass_QueryInfo (
OBJ_ID objId,
uint32_t type,
void *pData
)
{
ASTRCARRAY_CLASS_DATA *this = objId;
const
char *pStr = pData;
if (OBJ_NIL == this) {
return NULL;
}
switch (type) {
case OBJ_QUERYINFO_TYPE_OBJECT_SIZE:
return (void *)sizeof(ASTRCARRAY_DATA);
break;
case OBJ_QUERYINFO_TYPE_CLASS_OBJECT:
return this;
break;
// Query for an address to specific data within the object.
// This should be used very sparingly since it breaks the
// object's encapsulation.
case OBJ_QUERYINFO_TYPE_DATA_PTR:
switch (*pStr) {
case 'C':
if (str_Compare("ClassInfo", (char *)pStr) == 0) {
return (void *)&AStrCArray_Info;
}
break;
default:
break;
}
break;
case OBJ_QUERYINFO_TYPE_INFO:
return (void *)obj_getInfo(this);
break;
case OBJ_QUERYINFO_TYPE_METHOD:
switch (*pStr) {
case 'N':
if (str_Compare("New", (char *)pStr) == 0) {
return AStrCArray_New;
}
break;
case 'W':
if (str_Compare("WhoAmI", (char *)pStr) == 0) {
return AStrCArrayClass_WhoAmI;
}
break;
default:
break;
}
break;
default:
break;
}
return NULL;
}
static
bool AStrCArray_IsKindOf (
uint16_t classID
)
{
if (OBJ_IDENT_ASTRCARRAY == classID) {
return true;
}
if (OBJ_IDENT_OBJ == classID) {
return true;
}
return false;
}
// Dealloc() should be put into the Internal Header as well
// for classes that get inherited from.
void AStrCArray_Dealloc (
OBJ_ID objId
);
OBJ_ID AStrCArray_Class (
void
)
{
return (OBJ_ID)&AStrCArray_ClassObj;
}
static
uint16_t AStrCArray_WhoAmI (
void
)
{
return OBJ_IDENT_ASTRCARRAY;
}
//===========================================================
// Object Vtbl Definition
//===========================================================
const
ASTRCARRAY_VTBL AStrCArray_Vtbl = {
{
&AStrCArray_Info,
AStrCArray_IsKindOf,
#ifdef ASTRCARRAY_IS_SINGLETON
obj_RetainNull,
obj_ReleaseNull,
#else
obj_RetainStandard,
obj_ReleaseStandard,
#endif
AStrCArray_Dealloc,
AStrCArray_Class,
AStrCArray_WhoAmI,
(P_OBJ_QUERYINFO)AStrCArray_QueryInfo,
(P_OBJ_TOSTRING)AStrCArray_ToDebugString,
NULL, // AStrCArray_Enable,
NULL, // AStrCArray_Disable,
(P_OBJ_ASSIGN)AStrCArray_Assign,
NULL, // (P_OBJ_COMPARE)AStrCArray_Compare,
(P_OBJ_PTR)AStrCArray_Copy,
NULL, // (P_OBJ_PTR)AStrCArray_DeepCopy,
NULL // (P_OBJ_HASH)AStrCArray_Hash,
},
// Put other object method names below this.
// Properties:
// Methods:
//AStrCArray_IsEnabled,
};
static
const
OBJ_INFO AStrCArray_Info = {
"AStrCArray",
"Array of AStrC objects",
(OBJ_DATA *)&AStrCArray_ClassObj,
(OBJ_DATA *)&obj_ClassObj,
(OBJ_IUNKNOWN *)&AStrCArray_Vtbl,
sizeof(ASTRCARRAY_DATA)
};
| 22.87561 | 76 | 0.516899 | [
"object"
] |
16f42ce942c76b68dede6cb4724770297830a7e0 | 3,707 | h | C | src/apollota/triangulation_queries.h | kliment-olechnovic/voronota | 4e3063aa86b44f1f2e7b088ec9976f3e12047549 | [
"MIT"
] | 9 | 2019-08-23T10:46:18.000Z | 2022-03-11T12:20:27.000Z | src/apollota/triangulation_queries.h | kliment-olechnovic/voronota | 4e3063aa86b44f1f2e7b088ec9976f3e12047549 | [
"MIT"
] | null | null | null | src/apollota/triangulation_queries.h | kliment-olechnovic/voronota | 4e3063aa86b44f1f2e7b088ec9976f3e12047549 | [
"MIT"
] | 3 | 2020-09-17T19:07:47.000Z | 2021-04-29T01:19:38.000Z | #ifndef APOLLOTA_TRIANGULATION_QUERIES_H_
#define APOLLOTA_TRIANGULATION_QUERIES_H_
#include "triangulation.h"
namespace voronota
{
namespace apollota
{
class TriangulationQueries
{
public:
#if USE_TR1 > 0
typedef std::tr1::unordered_map<std::size_t, std::set<std::size_t> > IDsMap;
typedef std::tr1::unordered_map<Pair, std::set<std::size_t>, Pair::HashFunctor> PairsMap;
typedef std::tr1::unordered_map<Triple, std::set<std::size_t>, Triple::HashFunctor> TriplesMap;
#else
typedef std::unordered_map<std::size_t, std::set<std::size_t> > IDsMap;
typedef std::unordered_map<Pair, std::set<std::size_t>, Pair::HashFunctor> PairsMap;
typedef std::unordered_map<Triple, std::set<std::size_t>, Triple::HashFunctor> TriplesMap;
#endif
typedef std::vector< std::vector<std::size_t> > IDsGraph;
template<typename QuadruplesMapType>
static IDsMap collect_neighbors_map_from_quadruples_map(const QuadruplesMapType& quadruples_map)
{
IDsMap neighbors_map;
for(typename QuadruplesMapType::const_iterator it=quadruples_map.begin();it!=quadruples_map.end();++it)
{
const Quadruple& quadruple=it->first;
for(int a=0;a<4;a++)
{
for(int b=a+1;b<4;b++)
{
neighbors_map[quadruple.get(a)].insert(quadruple.get(b));
neighbors_map[quadruple.get(b)].insert(quadruple.get(a));
}
}
}
return neighbors_map;
}
static IDsGraph collect_ids_graph_from_ids_map(const IDsMap& neighbors_map, const std::size_t number_of_vertices)
{
IDsGraph neighbors_graph(number_of_vertices);
for(IDsMap::const_iterator it=neighbors_map.begin();it!=neighbors_map.end();++it)
{
if((it->first)<neighbors_graph.size())
{
neighbors_graph[it->first].insert(neighbors_graph[it->first].end(), it->second.begin(), it->second.end());
}
}
return neighbors_graph;
}
static IDsMap collect_vertices_map_from_vertices_vector(const Triangulation::VerticesVector& vertices_vector)
{
IDsMap ids_vertices_map;
for(std::size_t i=0;i<vertices_vector.size();i++)
{
const Quadruple& quadruple=vertices_vector[i].first;
for(int a=0;a<4;a++)
{
ids_vertices_map[quadruple.get(a)].insert(i);
}
}
return ids_vertices_map;
}
static PairsMap collect_pairs_vertices_map_from_vertices_vector(const Triangulation::VerticesVector& vertices_vector)
{
PairsMap pairs_vertices_map;
for(std::size_t i=0;i<vertices_vector.size();i++)
{
const Quadruple& quadruple=vertices_vector[i].first;
for(int a=0;a<4;a++)
{
for(int b=a+1;b<4;b++)
{
pairs_vertices_map[Pair(quadruple.get(a), quadruple.get(b))].insert(i);
}
}
}
return pairs_vertices_map;
}
static TriplesMap collect_triples_vertices_map_from_vertices_vector(const Triangulation::VerticesVector& vertices_vector)
{
TriplesMap triples_vertices_map;
for(std::size_t i=0;i<vertices_vector.size();i++)
{
const Quadruple& quadruple=vertices_vector[i].first;
for(int a=0;a<4;a++)
{
triples_vertices_map[quadruple.exclude(a)].insert(i);
}
}
return triples_vertices_map;
}
template<typename QuadruplesMapType>
static PairsMap collect_pairs_neighbors_map_from_quadruples_map(const QuadruplesMapType& quadruples_map)
{
PairsMap pairs_neighbors_map;
for(typename QuadruplesMapType::const_iterator it=quadruples_map.begin();it!=quadruples_map.end();++it)
{
const Quadruple& quadruple=it->first;
for(int a=0;a<4;a++)
{
for(int b=a+1;b<4;b++)
{
const Pair p(quadruple.get(a), quadruple.get(b));
for(int c=0;c<4;c++)
{
if(c!=a && c!=b)
{
pairs_neighbors_map[p].insert(quadruple.get(c));
}
}
}
}
}
return pairs_neighbors_map;
}
};
}
}
#endif /* APOLLOTA_TRIANGULATION_QUERIES_H_ */
| 27.257353 | 122 | 0.71891 | [
"vector"
] |
e50077a7fc997d97f6052c8960819da05f9d595e | 2,030 | h | C | ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_mediator.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_mediator.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_mediator.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_AUTOFILL_MANUAL_FILL_MANUAL_FILL_CARD_MEDIATOR_H_
#define IOS_CHROME_BROWSER_UI_AUTOFILL_MANUAL_FILL_MANUAL_FILL_CARD_MEDIATOR_H_
#import <UIKit/UIKit.h>
#include "base/memory/ref_counted.h"
#import "ios/chrome/browser/ui/autofill/manual_fill/full_card_request_result_delegate_bridge.h"
@protocol BrowserCoordinatorCommands;
namespace autofill {
class CreditCard;
} // namespace autofill
@protocol ManualFillContentInjector;
@protocol ManualFillCardConsumer;
@protocol CardListDelegate;
namespace manual_fill {
extern NSString* const ManageCardsAccessibilityIdentifier;
extern NSString* const kAddCreditCardsAccessibilityIdentifier;
} // namespace manual_fill
// Object in charge of getting the cards relevant for the manual fill
// cards UI.
@interface ManualFillCardMediator
: NSObject <FullCardRequestResultDelegateObserving>
// The consumer for cards updates. Setting it will trigger the consumer
// methods with the current data.
@property(nonatomic, weak) id<ManualFillCardConsumer> consumer;
// The delegate in charge of using the content selected by the user.
@property(nonatomic, weak) id<ManualFillContentInjector> contentInjector;
// The delegate in charge of navigation.
@property(nonatomic, weak) id<CardListDelegate> navigationDelegate;
// The designated initializer. |cards| must not be nil.
- (instancetype)initWithCards:(std::vector<autofill::CreditCard*>)cards
NS_DESIGNATED_INITIALIZER;
// Unavailable. Use |initWithCards:|.
- (instancetype)init NS_UNAVAILABLE;
// Finds the original autofill::CreditCard from given |GUID|.
- (const autofill::CreditCard*)findCreditCardfromGUID:(NSString*)GUID;
// Updates the |cards| being presented.
- (void)reloadWithCards:(std::vector<autofill::CreditCard*>)cards;
@end
#endif // IOS_CHROME_BROWSER_UI_AUTOFILL_MANUAL_FILL_MANUAL_FILL_CARD_MEDIATOR_H_
| 35 | 95 | 0.812808 | [
"object",
"vector"
] |
e5057c178fe62d806e0009f69f1fcdbb5aacf77a | 8,007 | h | C | RcsPySim/src/cpp/core/ExperimentConfig.h | jacarvalho/SimuRLacra | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | [
"BSD-3-Clause"
] | null | null | null | RcsPySim/src/cpp/core/ExperimentConfig.h | jacarvalho/SimuRLacra | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | [
"BSD-3-Clause"
] | null | null | null | RcsPySim/src/cpp/core/ExperimentConfig.h | jacarvalho/SimuRLacra | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | [
"BSD-3-Clause"
] | null | null | null | #ifndef _EXPERIMENTCONFIG_H_
#define _EXPERIMENTCONFIG_H_
#include "config/PropertySource.h"
#include "util/nocopy.h"
#include <Rcs_graph.h>
namespace Rcs
{
class ActionModel;
class ObservationModel;
class InitStateSetter;
class PhysicsParameterManager;
class PhysicsBase;
class ForceDisturber;
class HUD;
class Viewer;
/**
* Create a collision model using the settings from the given RcsPySim config.
*
* @param graph graph to observe
* @param config collision configuration
* @return new collision model
* @throw std::invalid_argument if the collision model could not be created.
*/
RcsCollisionMdl* RcsCollisionModel_createFromConfig(RcsGraph* graph, Rcs::PropertySource* config);
/**
* Defines the experiment setup.
* There should be one subclass per experiment type, IE BallOnPlate or QuanserQube.
*/
class ExperimentConfig
{
// experiment catalog management
public:
typedef ExperimentConfig* (* ExperimentConfigCreateFunction)();
/**
* Register a named experiment.
* @param name experiment name
* @param creator ExperimentConfig factory function
*/
static void registerType(const char* name, ExperimentConfigCreateFunction creator);
/**
* Create the experiment configuration from the given property source.
* This will load the "type" property, use that to select a ExperimentConfig implementation, and then call init()
* to populate it.
* @param properties property source to read configuration from. Takes ownership, even on error.
* @return a new experiment config object.
*/
static ExperimentConfig* create(PropertySource* properties);
public:
ExperimentConfig();
virtual ~ExperimentConfig();
// not copy- or movable RCSPYSIM_NOCOPY_NOMOVE(ExperimentConfig)
protected:
/**
* Called to load data from the given properties.
* You can override this to load additional data, but be sure to call the parent implementation.
* @param properties property source to read configuration from. Takes ownership.
*/
virtual void load(PropertySource* properties);
/**
* Create the action model. Read any configuration from this->properties.
* @return the new action model
*/
virtual ActionModel* createActionModel() = 0;
/**
* Create the observation model. Read any configuration from this->properties.
* @return the new observation model
*/
virtual ObservationModel* createObservationModel() = 0;
public:
/**
* Create the init state setter. Read any configuration from this->properties.
* Since the init state setter is only needed for the simulation, it is not stored in the ExperimentConfig.
* Instead, the simulation calls this method and manages the object on it's own.
* The default implementation returns NULL to use the state from the graph file.
* @return the new init state setter
*/
virtual InitStateSetter* createInitStateSetter();
/**
* Create a model for artificial external disturbing forces.
* The default implementation returns NULL to ignore this.
* @return the new force disturber
*/
virtual ForceDisturber* createForceDisturber();
/**
* Create the physics parameter manager. Read any configuration from this->properties.
* Since the physics parameter manager is only needed for the simulation, it is not stored in the ExperimentConfig.
* Instead, the simulation calls this method and manages the object on it's own.
* This method calls populatePhysicsParameters to populate the parameter descriptors.
* @return the new physics parameter manager
*/
PhysicsParameterManager* createPhysicsParameterManager();
/**
* Called to update the HUD text for the viewer.
* The default implementation will show the physics engine name, the current time and the last step reward.
* @param[out] linesOut vector of HUD lines. initially empty.
* @param[in] currentTime simulation time
* @param[in] currentObservation latest observation
* @param[in] currentAction latest action
* @param[in] simulator physics simulator or NULL if none
* @param[in] physicsManager physics parameter manager or NULL if none
* @param[in] forceDisturber distruber which applies the forces to a given body
* @return concatenated HUD lines
*/
virtual void getHUDText(std::vector<std::string>& linesOut, double currentTime, const MatNd* currentObservation,
const MatNd* currentAction, PhysicsBase* simulator,
PhysicsParameterManager* physicsManager, ForceDisturber* forceDisturber);
/**
* Returns the concatenated HUD lines.
* @param[in] currentTime simulation time
* @param[in] currentObservation latest observation
* @param[in] currentAction latest action
* @param[in] simulator physics simulator or NULL if none
* @param[in] physicsManager physics parameter manager or NULL if none
* @param[in] forceDisturber distruber which applies the forces to a given body
* @return concatenated HUD lines
*/
std::string getHUDText(double currentTime, const MatNd* currentObservation, const MatNd* currentAction,
PhysicsBase* simulator, PhysicsParameterManager* physicsManager,
ForceDisturber* forceDisturber);
/**
* Perform additional initialization on the viewer.
* This could, for example, change the camera position or add additional visualization.
* The default implementation does nothing.
*/
virtual void initViewer(Rcs::Viewer* viewer);
protected:
/**
* Add the physics parameter descriptors to the given physics parameter manager.
* @param manager parameter manager to populate.
*/
virtual void populatePhysicsParameters(PhysicsParameterManager* manager);
public:
//! Property source (owned)
PropertySource* properties;
//! Graph description
RcsGraph* graph;
//! Action model (pluggable).
ActionModel* actionModel;
//! Observation model (pluggable) used to create the observation which will be returned from step()
ObservationModel* observationModel;
//! Collision model to use. Is based on the graph, so take care when using with IK etc.
RcsCollisionMdl* collisionMdl;
//! The time step [s]
double dt;
//! Flag to enable joint limit checking
bool checkJointLimits;
};
/**
* Create a static field of this type to register an experiment config type.
*/
template<class Config>
class ExperimentConfigRegistration
{
public:
/**
* Register the template type under the given name.
* @param name experiment name
*/
explicit ExperimentConfigRegistration(const char* name)
{
ExperimentConfig::registerType(name, ExperimentConfigRegistration::create);
}
/**
* Creator function passed to ExperimentConfig::registerType.
*/
static ExperimentConfig* create()
{
return new Config();
}
};
} /* namespace Rcs */
#endif /* _EXPERIMENTCONFIG_H_ */
| 36.898618 | 123 | 0.630948 | [
"object",
"vector",
"model"
] |
e505d5d3546b61b8ee0440e4c047e70ec99a1cb4 | 4,262 | h | C | Project 19-/37 Tile-Based Deferred Rendering/GameApp.h | MKXJun/DX11-Without-DirectX-SDK | 31756de150248fc8f4ccb6ce0c5e2837da718c2d | [
"MIT"
] | 3 | 2018-05-29T12:18:08.000Z | 2018-06-20T16:14:13.000Z | Project 19-/37 Tile-Based Deferred Rendering/GameApp.h | MKXJun/DX11-Without-DirectX-SDK | 31756de150248fc8f4ccb6ce0c5e2837da718c2d | [
"MIT"
] | null | null | null | Project 19-/37 Tile-Based Deferred Rendering/GameApp.h | MKXJun/DX11-Without-DirectX-SDK | 31756de150248fc8f4ccb6ce0c5e2837da718c2d | [
"MIT"
] | null | null | null | #ifndef GAMEAPP_H
#define GAMEAPP_H
#include <random>
#include <WinMin.h>
#include "d3dApp.h"
#include "Effects.h"
#include <CameraController.h>
#include <RenderStates.h>
#include <GameObject.h>
#include <Texture2D.h>
#include <Buffer.h>
#include <Collision.h>
#include <ModelManager.h>
#include <TextureManager.h>
#include "Shaders/ShaderDefines.h"
// 需要与着色器中的PointLight对应
struct PointLight
{
DirectX::XMFLOAT3 posV;
float attenuationBegin;
DirectX::XMFLOAT3 color;
float attenuationEnd;
};
// 初始变换数据(柱面坐标系)
struct PointLightInitData
{
float radius;
float angle;
float height;
float animationSpeed;
};
struct TileInfo
{
UINT numLights;
UINT lightIndices[MAX_LIGHT_INDICES];
};
class GameApp : public D3DApp
{
public:
// 光源裁剪技术
enum class LightCullTechnique {
CULL_FORWARD_NONE = 0, // 前向渲染,无光照裁剪
CULL_FORWARD_PREZ_NONE, // 前向渲染,预写入深度,无光照裁剪
CULL_FORWARD_COMPUTE_SHADER_TILE, // 前向渲染,预写入深度,Tile-Based光照裁剪
CULL_DEFERRED_NONE, // 传统延迟渲染
CULL_DEFERRED_COMPUTE_SHADER_TILE // Tile-Based延迟渲染
};
public:
GameApp(HINSTANCE hInstance, const std::wstring& windowName, int initWidth = 1280, int initHeight = 720);
~GameApp();
bool Init();
void OnResize();
void UpdateScene(float dt);
void DrawScene();
private:
bool InitResource();
void InitLightParams();
DirectX::XMFLOAT3 HueToRGB(float hue);
void ResizeLights(UINT activeLights);
void UpdateLights(float dt);
// 需要在更新帧资源后进行
void XM_CALLCONV SetupLights(DirectX::XMMATRIX viewMatrix);
void ResizeBuffers(UINT width, UINT height, UINT msaaSamples);
void RenderForward(bool doPreZ);
void RenderGBuffer();
void RenderSkybox();
private:
// GPU计时
GpuTimer m_GpuTimer_PreZ;
GpuTimer m_GpuTimer_LightCulling;
GpuTimer m_GpuTimer_Geometry;
GpuTimer m_GpuTimer_Lighting;
GpuTimer m_GpuTimer_Skybox;
// 设置
LightCullTechnique m_LightCullTechnique = LightCullTechnique::CULL_DEFERRED_COMPUTE_SHADER_TILE;
bool m_AnimateLights = false;
bool m_LightingOnly = false;
bool m_FaceNormals = false;
bool m_VisualizeLightCount = false;
bool m_VisualizeShadingFreq = false;
bool m_ClearGBuffers = false;
float m_LightHeightScale = 0.25f;
// 各种资源
TextureManager m_TextureManager; // 纹理读取管理
ModelManager m_ModelManager; // 模型读取管理
UINT m_MsaaSamples = 1;
bool m_MsaaSamplesChanged = false;
std::unique_ptr<Texture2DMS> m_pLitBuffer; // 场景渲染缓冲区
std::unique_ptr<StructuredBuffer<DirectX::XMUINT2>> m_pFlatLitBuffer; // 场景渲染缓冲区(TBDR)
std::unique_ptr<Depth2DMS> m_pDepthBuffer; // 深度缓冲区
ComPtr<ID3D11DepthStencilView> m_pDepthBufferReadOnlyDSV; // 只读深度模板视图
std::vector<std::unique_ptr<Texture2DMS>> m_pGBuffers; // G-Buffers
std::unique_ptr<Texture2D> m_pDebugNormalGBuffer; // 调试显示用的法线缓冲区
std::unique_ptr<Texture2D> m_pDebugPosZGradGBuffer; // 调试显示用的Z梯度缓冲区
std::unique_ptr<Texture2D> m_pDebugAlbedoGBuffer; // 调试显示用的颜色缓冲区
// 用于一次性传递
std::vector<ID3D11RenderTargetView*> m_pGBufferRTVs;
std::vector<ID3D11ShaderResourceView*> m_pGBufferSRVs;
// 光照
UINT m_ActiveLights = (MAX_LIGHTS >> 3);
std::vector<PointLightInitData> m_PointLightInitDatas;
std::vector<PointLight> m_PointLightParams;
std::vector<DirectX::XMFLOAT3> m_PointLightPosWorlds;
std::unique_ptr<StructuredBuffer<PointLight>> m_pLightBuffer; // 点光源缓冲区
std::unique_ptr<StructuredBuffer<TileInfo>> m_pTileBuffer; // 点光源光源索引缓冲区
// 模型
GameObject m_Sponza; // 场景模型
GameObject m_Skybox; // 天空盒模型
// 特效
ForwardEffect m_ForwardEffect; // 前向渲染特效
DeferredEffect m_DeferredEffect; // 延迟渲染特效
SkyboxEffect m_SkyboxEffect; // 天空盒特效
// 摄像机
std::shared_ptr<Camera> m_pCamera; // 摄像机
FirstPersonCameraController m_FPSCameraController; // 摄像机控制器
};
#endif | 29.597222 | 109 | 0.661192 | [
"vector"
] |
e5261e140a2e83af50c5bb42d495bf5aaae8b3ba | 3,019 | h | C | SRC/common/threadstate.h | usnistgov/OOF3D | 4fd423a48aea9c5dc207520f02de53ae184be74c | [
"X11"
] | 31 | 2015-04-01T15:59:36.000Z | 2022-03-18T20:21:47.000Z | SRC/common/threadstate.h | usnistgov/OOF3D | 4fd423a48aea9c5dc207520f02de53ae184be74c | [
"X11"
] | 3 | 2015-02-06T19:30:24.000Z | 2017-05-25T14:14:31.000Z | SRC/common/threadstate.h | usnistgov/OOF3D | 4fd423a48aea9c5dc207520f02de53ae184be74c | [
"X11"
] | 7 | 2015-01-23T15:19:22.000Z | 2021-06-09T09:03:59.000Z | // -*- C++ -*-
/* This software was produced by NIST, an agency of the U.S. government,
* and by statute is not subject to copyright in the United States.
* Recipients of this software assume all responsibilities associated
* with its operation, modification and maintenance. However, to
* facilitate maintenance we ask that before distributing modified
* versions of this software, you first contact the authors at
* oof_manager@nist.gov.
*/
#include <oofconfig.h>
// Objects and functions for storing and retrieving thread
// information. There is exactly one OOFThreadState object per thread.
// There can be more than one OOFThreadID object for one thread, but
// they are all equal. The OOFThreadID is used by findThreadState to
// retrieve the thread's OOFThreadState.
#ifndef THREADSTATE
#define THREADSTATE
#include "common/lock.h"
#include "common/progress.h"
#include <pthread.h>
#include <vector>
class OOFThreadID {
private:
pthread_t _ID;
public:
OOFThreadID();
const pthread_t & get_ID() const { return _ID; }
};
std::ostream &operator<<(std::ostream&, const OOFThreadID&);
bool operator==(const OOFThreadID&, const OOFThreadID&);
bool operator!=(const OOFThreadID&, const OOFThreadID&);
class OOFThreadState {
private:
OOFThreadID _ID; // May be re-used. Depends on pthread implementation.
int _id; // Unique among all threads for all time.
typedef std::vector<Progress*> ProgressList;
ProgressList progressList;
ProgressList::iterator findProgressIterator(const std::string&);
mutable SLock progressLock;
public:
OOFThreadState();
~OOFThreadState();
int id() const { return _id; }
const OOFThreadID & get_thread_ID() const { return _ID; }
// getProgress returns an existing Progress object with the given
// name, or creates a new one with the given type if there isn't an
// existing object.
Progress *getProgress(const std::string &name, ProgressType ptype);
// findProgress returns an existing Progress object with the given
// name, or raises an exception.
Progress *findProgress(const std::string &name);
void impedeProgress(); // set the 'stopped' flag on all Progress objs.
std::vector<std::string> *getProgressNames() const;
void acquireProgressLock();
void releaseProgressLock();
private:
OOFThreadState(const OOFThreadState&); // prohibited
};
int operator==(const OOFThreadState&, const OOFThreadState&);
std::ostream &operator<<(std::ostream&, const OOFThreadState&);
//void make_thread_main(); // Make the calling thread the new "main" thread.
void initThreadState();
int findThreadNumber();
OOFThreadState *findThreadState();
int nThreadStates();
bool mainthread_query(); // returns true on main thread, false on others.
void mainthread_delete();
// void cleanThreadList();
void cancelThread(OOFThreadState &tobecancelled);
void testcancel();
void textMode();
// OOFThreadState *make_thread_main();
// void restore_main_thread(OOFThreadState*);
extern bool threading_enabled;
#endif // THREADSTATE
| 30.494949 | 76 | 0.747599 | [
"object",
"vector"
] |
e526215aeddfddf42c4d0408a91bd1653aaf1ccd | 874 | h | C | App/TrainingDataGenerator/Scan2CADObjectLoader.h | Bovey0809/SCFusion | 1d4a8f4eb0f330f5a69efd89fbf28686c1405471 | [
"BSD-2-Clause"
] | 30 | 2020-11-06T09:11:55.000Z | 2022-03-11T06:56:57.000Z | App/TrainingDataGenerator/Scan2CADObjectLoader.h | ShunChengWu/SCFusion | 1d4a8f4eb0f330f5a69efd89fbf28686c1405471 | [
"BSD-2-Clause"
] | 1 | 2021-12-17T07:03:01.000Z | 2021-12-17T07:03:01.000Z | App/TrainingDataGenerator/Scan2CADObjectLoader.h | Bovey0809/SCFusion | 1d4a8f4eb0f330f5a69efd89fbf28686c1405471 | [
"BSD-2-Clause"
] | 1 | 2021-12-17T07:02:47.000Z | 2021-12-17T07:02:47.000Z | #pragma once
#include "../../ORUtils/Logging.h"
#include "Scan2CADAnnotionLoader.h"
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/PolygonMesh.h>
#include <Eigen/Core>
class Scan2CADObjectLoader {
typedef pcl::PointXYZRGB PointT;
public:
struct Scan2CADMeshHolder{
unsigned int id, label;
pcl::PolygonMeshPtr mesh;
pcl::PointCloud<PointT>::Ptr cloud;
};
Scan2CADObjectLoader(std::string pth_scannet,std::string pth_shapenet, std::string pth_alignments);
std::vector<std::shared_ptr<Scan2CADMeshHolder>> GetMeshes(const std::string &scan_id);
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
private:
std::string msPathScanNet, msPathShapeNet, msPathAlignments;
Scan2CADAnnotionLoader mScan2CadAnnotionLoader;
Eigen::Matrix4d mExtrinsics;
pcl::PolygonMeshPtr loadCloud(const std::string &pth_ply);
}; | 32.37037 | 103 | 0.745995 | [
"mesh",
"vector"
] |
e53d1b72d55d1b409f5a807584c407b29f9ddc25 | 113,295 | c | C | fst/src/do_hpfs.c | nepx/hpfsutils | ceeb8170a88a11d11e00a5a75deb97f7e2eda93e | [
"BSD-3-Clause"
] | null | null | null | fst/src/do_hpfs.c | nepx/hpfsutils | ceeb8170a88a11d11e00a5a75deb97f7e2eda93e | [
"BSD-3-Clause"
] | null | null | null | fst/src/do_hpfs.c | nepx/hpfsutils | ceeb8170a88a11d11e00a5a75deb97f7e2eda93e | [
"BSD-3-Clause"
] | null | null | null | /* do_hpfs.c -- HPFS-specific code for fst
Copyright (c) 1995-2008 by Eberhard Mattes
This file is part of fst.
fst is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
fst 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 fst; see the file COPYING. If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
#define INCL_DOSDEVIOCTL
#define INCL_DOSNLS
#define INCL_DOSERRORS
#include "os2.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stddef.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include "fst.h"
#include "crc.h"
#include "diskio.h"
#include "hpfs.h"
/* Return a non-zero value if sector X is allocated. */
#define ALLOCATED(x) !BITSETP (alloc_vector, (x))
ULONG DosMapCase (ULONG ulLength, const PCOUNTRYCODE pCountryCode, PCHAR pchString) {
return ERROR_NLS_NO_COUNTRY_FILE;
}
/* Our own representation of a code page. */
typedef struct
{
CPINFOENTRY info;
char hit;
BYTE case_map[256];
BYTE case_map_changed[256];
} MYCP;
/* This structure is used for checking whether DIRENTs are arranged in
ascending order by file name. */
typedef struct
{
BYTE name[256]; /* Previous file name */
ULONG cpindex; /* Code page index for previous file name */
} SORT;
/* This structure is used for counting extents. */
typedef struct
{
ULONG size; /* Number of elements in `counts' */
ULONG *counts; /* counts[i] = # of objects with i extents */
} EXTENTS;
static ULONG total_sectors; /* Total number of sectors of HPFS volume */
static ULONG total_alloc; /* # of bytes allocated for �alloc_vector' */
static BYTE *usage_vector; /* One byte per sector, indicating usage */
static BYTE *seen_vector; /* One byte per sector, to avoid loops */
static BYTE *alloc_vector; /* One bit per sector, indicating allocation */
static const path_chain **path_vector; /* One path name chain per sector */
static BYTE alloc_ready; /* TRUE if alloc_vector contents valid */
static ULONG code_page_count; /* Number of code pages */
static MYCP *code_pages; /* All code pages of the HPFS volume */
static ULONG cpdata_count; /* Number of code page data sectors */
static ULONG *cpdata_visited; /* Sector numbers of visited cp data sectors */
static ULONG min_time; /* Minimum valid time stamp */
static ULONG dirband_start; /* First sector of DIRBLK band */
static ULONG dirband_end; /* Last sector of DIRBLK band */
static ULONG dirblk_total; /* Total number of DIRBLKs */
static ULONG dirblk_outside; /* Number of DIRBLKs outside DIRBLK band */
static ULONG alsec_count; /* Number of ALSECs */
static ULONG file_count; /* Number of files */
static ULONG dir_count; /* Number of directories */
static ULONG sectors_per_block; /* Block size (in sectors) for `multimedia' */
static EXTENTS file_extents; /* Number of extents for files */
static EXTENTS ea_extents; /* Number of extents for EAs */
static char no_country_sys; /* COUNTRY.SYS not available */
static char alsec_number[100]; /* Formatted ALSEC number */
static char find_comp[256]; /* Current component of `find_path' */
static char copy_buf[512]; /* Buffer for `copy' action */
static void dirblk_warning (int level, const char *fmt, ULONG secno,
const path_chain *path, ...) ATTR_PRINTF (2, 5);
static void dirent_warning (int level, const char *fmt, ULONG secno,
const path_chain *path, int dirent_no,
const char *fname, ...) ATTR_PRINTF (2, 7);
static void alsec_warning (int level, const char *fmt, ULONG secno,
const path_chain *path, ...) ATTR_PRINTF (2, 5);
static void alloc_warning (int level, const char *fmt, ULONG secno,
const path_chain *path,
int fnode_flag, ...) ATTR_PRINTF (2, 6);
static void fnode_warning (int level, const char *fmt, ULONG secno,
const path_chain *path, ...) ATTR_PRINTF (2, 5);
/* Compute the checksum for SIZE bytes at P. */
static ULONG chksum (const BYTE *p, size_t size)
{
ULONG sum;
sum = 0;
while (size != 0)
{
sum += *p++;
sum = (sum << 7) | (sum >> 25); /* Rotate left by 7 bits */
--size;
}
return sum;
}
/* Return a pointer to a string containing a formatted time stamp.
Note that the pointer points to static memory; do not use
format_time() more than once in one expression! */
static const char *format_time (ULONG x)
{
static char buf[100];
time_t t;
struct tm *tm;
if (x == 0)
strcpy (buf, "never");
else if (x < min_time)
sprintf (buf, "0x" LX_FMT "", x);
else
{
t = (time_t)x;
tm = gmtime (&t);
sprintf (buf, "0x" LX_FMT " (%d-%.2d-%.2d %.2d:%.2d:%.2d)",
x, tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
}
return buf;
}
/* Return a pointer to a string containing a formatted time stamp for
the `dir' action. Note that the pointer points to static memory;
do not use format_dir_time() more than once in one expression! */
static const char *format_dir_time (ULONG x)
{
static char buf[100];
time_t t;
struct tm *tm;
if (x < min_time)
return "????-??-?? ??:??:??";
else
{
t = (time_t)x;
tm = gmtime (&t);
sprintf (buf, "%d-%.2d-%.2d %.2d:%.2d:%.2d",
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
return buf;
}
}
/* Return TRUE iff the file name pointed to by NAME would be a valid
file name on a FAT file system. HPFS.IFS seems to treat the space
character (0x20) as being valid on FAT. */
static int is_fat_name (const BYTE *name)
{
int n, len;
const BYTE *p;
if (name[0] == '.')
return name[1] == 0 || (name[1] == '.' && name[2] == 0);
len = strlen ((const char *)name);
p = (const BYTE *)strchr ((const char *)name, '.');
if (p == NULL)
n = len;
else
n = p - name;
if (n > 8)
return FALSE;
if (p != NULL)
{
if (p[-1] == ' ') /* (p > name) is guaranteed */
return FALSE;
if (len - (n + 1) > 3)
return FALSE;
if (strchr ((const char *)p + 1, '.') != NULL)
return FALSE;
}
for (p = name; *p != 0; ++p)
if (*p < 0x20 || strchr ("\"*+,/;:<=>?[\\]|", *p) != NULL)
return FALSE;
return TRUE;
}
/* Return TRUE iff the file name pointed to by NAME is a valid HPFS
file name. "." and ".." are considered invalid by this
function. */
static int is_hpfs_name (const BYTE *name)
{
const BYTE *p;
for (p = name; *p != 0; ++p)
if (*p < 0x20 || strchr ("\"*/:<>?\\|", *p) != NULL)
return FALSE;
if (p == name)
return FALSE;
if (p[-1] == '.' || p[-1] == ' ')
return FALSE;
return TRUE;
}
/* Initialize an EXTENTS structure. */
static void extents_init (EXTENTS *e)
{
e->size = 0;
e->counts = NULL;
}
/* Free any resources of an EXTENTS structure. */
static void extents_exit (EXTENTS *e)
{
e->size = 0;
free (e->counts);
e->counts = NULL;
}
/* Add an object to an EXTENTS structure. The object has COUNT
extents. */
static void extents_stat (EXTENTS *e, ULONG count)
{
if (count >= e->size)
{
ULONG new_size, i;
new_size = (count | 0xff) + 1;
e->counts = realloc (e->counts, new_size * sizeof (*e->counts));
for (i = e->size; i < new_size; ++i)
e->counts[i] = 0;
e->size = new_size;
}
e->counts[count] += 1;
}
/* Show the statistics collected in an EXTENTS structure. */
static void extents_show (const EXTENTS *e, const char *msg)
{
ULONG i;
info ("\nFragmentation of %s:\n", msg);
info ("Extents | Number\n");
info ("--------+-------\n");
for (i = 0; i < e->size; ++i)
if (e->counts[i] != 0)
info ("%7lu | " LU_FMT "\n", i, e->counts[i]);
}
/* Bits in seen_vector[]. */
#define SEEN_FNODE 0x01
#define SEEN_DIRBLK 0x02
#define SEEN_ALSEC 0x04
#define SEEN_BADLIST 0x08
#define SEEN_CPINFOSEC 0x10
/* Set and check a `have seen' bit. Return TRUE if any of the COUNT
sectors starting at SECNO has been interpreted as WHAT. MSG is a
string describing the type of sector. This function is used to
avoid infinite loops. */
static int have_seen (ULONG secno, ULONG count, BYTE what, const char *msg)
{
int seen;
ULONG i;
seen = FALSE;
for (i = 0; i < count && secno < total_sectors; ++i, ++secno)
if (seen_vector[secno] & what)
{
seen = TRUE;
warning (1, "Sector #" LU_FMT " already used for %s", secno, msg);
}
else
seen_vector[secno] |= what;
return seen;
}
/* Types of sectors. */
#define USE_EMPTY 0
#define USE_SUPER 1
#define USE_SPARE 2
#define USE_BITMAPIND 3
#define USE_BITMAP 4
#define USE_DIRBLKBITMAP 5
#define USE_SPAREDIRBLK 6
#define USE_BANDDIRBLK 7
#define USE_DIRBLK 8
#define USE_FNODE 9
#define USE_SID 10
#define USE_CPINFOSEC 11
#define USE_CPDATASEC 12
#define USE_BAD 13
#define USE_HOTFIXLIST 14
#define USE_HOTFIX 15
#define USE_BADLIST 16
#define USE_FILE 17
#define USE_ALSEC 18
#define USE_EA 19
#define USE_BOOT 20
#define USE_LOADER 21
#define USE_ACL 22
/* Return a pointer to a string containing a description of a sector
type. */
static const char *sec_usage (BYTE what)
{
switch (what)
{
case USE_EMPTY:
return "empty";
case USE_SUPER:
return "super block";
case USE_SPARE:
return "spare block";
case USE_BITMAPIND:
return "bitmap indirect block";
case USE_BITMAP:
return "bitmap";
case USE_DIRBLKBITMAP:
return "DIRBLK band bitmap";
case USE_SPAREDIRBLK:
return "spare DIRBLK";
case USE_BANDDIRBLK:
return "DIRBLK band";
case USE_DIRBLK:
return "DIRBLK";
case USE_FNODE:
return "FNODE";
case USE_SID:
return "SID";
case USE_CPINFOSEC:
return "code page info";
case USE_CPDATASEC:
return "code page data";
case USE_BAD:
return "bad sector";
case USE_HOTFIXLIST:
return "hotfix list";
case USE_HOTFIX:
return "hotfix sector";
case USE_BADLIST:
return "bad block list";
case USE_FILE:
return "file data";
case USE_ALSEC:
return "allocation sector";
case USE_EA:
return "extended attributes";
case USE_BOOT:
return "boot sector";
case USE_LOADER:
return "loader";
case USE_ACL:
return "ACL";
default:
return "INTERNAL_ERROR";
}
}
/* Use COUNT sectors starting at SECNO for WHAT. PATH points to the
path name chain for the file or directory and can be NULL for
sectors not used by a file or directory. */
static void use_sectors (ULONG secno, ULONG count, BYTE what,
const path_chain *path)
{
BYTE old;
/* Handle the sectors one by one. */
while (count > 0)
{
/* Before indexing any array with SECNO, check if SECNO is
valid. */
if (secno >= total_sectors)
{
if (path == NULL)
warning (1, "Sector number #" LU_FMT " (%s) is too big",
secno, sec_usage (what));
else
warning (1, "Sector number #" LU_FMT " (%s for \"%s\") is too big",
secno, sec_usage (what), format_path_chain (path, NULL));
}
else
{
/* Check usage of the sector. A previously unused sector
(USE_EMPTY) can be turned into any type of sector, Spare
DIRBLKs and sectors in the DIRBLK band can be turned into
DIRBLK sectors. Note that reusing a code page data
sector as code page data sector is ignored here as
do_cpdatasec() can be called more than once for a single
sector. */
old = usage_vector[secno];
if (old != USE_EMPTY
&& !(what == USE_DIRBLK
&& (old == USE_SPAREDIRBLK || old == USE_BANDDIRBLK))
&& !(what == USE_CPDATASEC && old == USE_CPDATASEC))
{
warning (1, "Sector #" LU_FMT " usage conflict: %s vs. %s",
secno, sec_usage (usage_vector[secno]),
sec_usage (what));
/* Display path names, if possible. */
if (path_vector != NULL && path_vector[secno] != NULL)
warning_cont ("File 1: \"%s\"",
format_path_chain (path_vector[secno], NULL));
if (path != NULL)
warning_cont ("File 2: \"%s\"",
format_path_chain (path, NULL));
}
else
{
usage_vector[secno] = what;
if (path_vector != NULL)
path_vector[secno] = path;
}
/* Check if the sector is marked as allocated. Don't check
if the allocation bitmap has not yet been read completely
into memory. */
if (alloc_ready && !ALLOCATED (secno))
{
warning (1, "Sector #" LU_FMT " used (%s) but not marked as allocated",
secno, sec_usage (what));
if (path != NULL)
warning_cont ("File: \"%s\"",
format_path_chain (path, NULL));
}
}
++secno; --count;
}
}
/* Process the bad block list starting in sector SECNO. The list has
TOTAL entries. */
static void do_bad (DISKIO *d, ULONG secno, ULONG total)
{
ULONG list[512];
ULONG rest, used, i, what_index = 0;
/* The bad block list consists of one or more 4-sector blocks. The
first 32-bit word of such a block points to the next 4-sector
block. The end of the chain is marked by a zero sector number.
The remaining 511 32-bit words of the blocks contain the sector
numbers of bad sectors. Entries which are zero do not point to
bad sectors. */
used = 0; rest = total;
while (secno != 0)
{
if (a_info)
{
info ("Sectors #" LU_FMT "-#" LU_FMT ": Bad block list\n", secno, secno+3);
info (" Sector number of next bad block: #" LU_FMT "\n", list[0]);
}
else if (a_what && IN_RANGE (what_sector, secno, 4))
{
info ("Sector #" LU_FMT ": Bad block list (+" LU_FMT ")\n",
what_sector, what_sector - secno);
if (secno + 0 == what_sector)
info (" Next sector in list: #" LU_FMT "\n", list[0]);
what_index = (secno - what_sector) / 4;
}
if (have_seen (secno, 4, SEEN_BADLIST, "bad block list"))
break;
use_sectors (secno, 4, USE_BADLIST, NULL);
read_sec (d, list, secno, 4, TRUE);
for (i = 1; i < 512 && i <= rest; ++i)
if (list[i] != 0)
{
++used;
if (a_info || (a_what && IN_RANGE (i, what_index, 512/4)))
info (" Bad sector: #" LU_FMT "\n", list[i]);
else if (a_what && list[i] == what_sector)
info ("Sector #" LU_FMT ": Bad sector\n", list[i]);
use_sectors (list[i], 1, USE_BAD, NULL);
}
secno = list[0];
if (rest > 511)
rest -= 511;
else
rest = 0;
}
if (rest != 0 || secno != 0)
warning (1, "Wrong length of bad block list");
if (used != total)
warning (1, "Wrong number of bad blocks");
}
/* Process the hotfix list starting at sector SECNO. The list has
TOTAL entries. */
static void do_hotfix_list (DISKIO *d, ULONG secno, ULONG total)
{
ULONG list[512]; /* 4 Sectors */
ULONG i, hsecno;
if (total > 512 / 3)
{
warning (1, "Maximum number of hotfixes is too big");
total = 512 / 3;
}
if (a_info)
info ("Sectors #" LU_FMT "-#" LU_FMT ": Hotfix list\n", secno, secno + 3);
else if (a_what && IN_RANGE (what_sector, secno, 4))
info ("Sector #" LU_FMT ": Hotfix list (+" LU_FMT ")\n",
what_sector, what_sector - secno);
use_sectors (secno, 4, USE_HOTFIXLIST, NULL);
read_sec (d, list, secno, 4, TRUE);
for (i = 0; i < total; ++i)
{
hsecno = list[i+total];
if (hsecno == 0)
warning (1, "Hotfix sector number is zero");
else if (hsecno >= total_sectors)
warning (1, "Hotfix sector number #" LU_FMT " is too big", hsecno);
else if (usage_vector[hsecno] == USE_EMPTY)
{
if (a_info)
info (" Hotfix sector: #" LU_FMT " for #" LU_FMT ", FNODE #" LU_FMT "\n",
hsecno, list[i], list[i+2*total]);
if (a_what && hsecno == what_sector)
info ("Sector #" LU_FMT ": Hotfix sector for #" LU_FMT ", FNODE #" LU_FMT "\n",
hsecno, list[i], list[i+2*total]);
use_sectors (hsecno, 1, USE_HOTFIX, NULL);
if (alloc_vector != NULL && !ALLOCATED (hsecno))
warning (1, "Hotfix sector #" LU_FMT " not marked as allocated", hsecno);
}
}
if (a_what && IN_RANGE (what_sector, secno, 4))
{
for (i = 0; i < total; ++i)
if (list[i] != 0 && what_sector == secno + i / (512 / 4))
info (" Bad sector: #" LU_FMT "\n", list[i]);
for (i = 0; i < total; ++i)
if (what_sector == secno + (i + total) / (512 / 4))
info (" Hotfix sector: #" LU_FMT "\n", list[i+total]);
}
}
/* One band has 8 MBytes, a run of free sectors may not span more than
two bands. Therefore, there are at most 32768 successive free
sectors. */
#define MAX_FREE_SIZE 32768
/* Show fragmentation of free space. */
static void do_free_frag (void)
{
ULONG *counts, count, start, end, j, k;
counts = xmalloc (MAX_FREE_SIZE * sizeof (*counts));
for (j = 0; j < MAX_FREE_SIZE; ++j)
counts[j] = 0;
count = 0;
for (j = 0; j < total_sectors; ++j)
if (!ALLOCATED (j))
++count;
else if (count != 0)
{
if (count < MAX_FREE_SIZE)
counts[count] += 1;
count = 0;
}
if (count != 0)
{
if (count < MAX_FREE_SIZE)
counts[count] += 1;
}
info ("\nFragmentation of free space:\n");
info ("Fragment size | Number of fragments of that size\n");
info ("--------------+---------------------------------\n");
for (j = 0; (1 << j) < MAX_FREE_SIZE; ++j)
{
start = 1 << j;
end = 2 * start;
if (end > MAX_FREE_SIZE)
end = MAX_FREE_SIZE;
count = 0;
for (k = start; k < end; ++k)
count += counts[k];
info (" %5lu-%-5lu | " LU_FMT "\n", start, end - 1, count);
}
info ("\n");
}
/* Show a range of COUNT free sectors starting at sector START. */
static void do_bitmap_show (ULONG start, ULONG count)
{
if (count == 1)
info (" Unallocated: 1 sector #" LU_FMT "\n", start);
else
info (" Unallocated: " LU_FMT " sectors #" LU_FMT "-#" LU_FMT "\n",
count, start, start + count - 1);
}
/* Show free sectors in the bitmap pointed to by BITMAP. BASE is the
number of the first sector mapped by the bitmap. SIZE is the
number of bits in the bitmap. Return the number of free
sectors. */
static ULONG do_bitmap2 (const BYTE *bitmap, ULONG base, ULONG size)
{
ULONG start, count, j, total;
start = count = total = 0;
for (j = 0; j < size; ++j)
if (BITSETP (bitmap, j))
{
if (count == 0)
start = j + base;
++count;
}
else if (count != 0)
{
do_bitmap_show (start, count);
total += count;
count = 0;
}
if (count != 0)
{
do_bitmap_show (start, count);
total += count;
}
return total;
}
/* Process the bitmap block starting in sector SECNO for band BAND. */
static void do_bitmap (DISKIO *d, ULONG secno, ULONG band, int show)
{
BYTE bitmap[2048];
ULONG pos, total, first_sec, rel_sec;
if (a_info || show)
info ("Bitmap for band " LU_FMT " is in sectors #" LU_FMT "-#" LU_FMT "\n",
band, secno, secno + 3);
if (a_what && IN_RANGE (what_sector, secno, 4))
info ("Sector #" LU_FMT ": Bitmap for band " LU_FMT " (+" LU_FMT ")\n",
what_sector, band, what_sector - secno);
use_sectors (secno, 4, USE_BITMAP, NULL);
read_sec (d, bitmap, secno, 4, TRUE);
pos = band * 2048;
first_sec = band * 2048 * 8;
if (a_info || a_check || a_what)
{
if (pos + 2048 <= total_alloc)
memcpy (alloc_vector + pos, bitmap, 2048);
else if (pos < total_alloc)
memcpy (alloc_vector + pos, bitmap, total_alloc - pos);
}
if (a_info && show_unused)
{
total = do_bitmap2 (bitmap, first_sec, 2048 * 8);
info (" Unallocated sectors in band " LU_FMT ": " LU_FMT "\n", band, total);
}
else if (a_what && IN_RANGE (what_sector, secno, 4))
do_bitmap2 (bitmap + (what_sector - secno) * 512,
(band * 2048 + (what_sector - secno) * 512) * 8,
512 * 8);
if (a_what && IN_RANGE (what_sector, first_sec, 2048 * 8))
{
rel_sec = what_sector - first_sec;
info ("Allocation bit for sector #" LU_FMT " (%s) is in sector #" LU_FMT ",\n"
" byte 0x" LX_FMT ", bit " LU_FMT "\n",
what_sector,
(BITSETP (bitmap, rel_sec) ? "unallocated" : "allocated"),
secno + rel_sec / (512 * 8),
(rel_sec % (512 * 8)) / 8, rel_sec % 8);
}
}
/* Process the bitmap indirect block starting in sector SECNO. */
static void do_bitmap_indirect (DISKIO *d, ULONG secno)
{
BYTE bit_count[256];
ULONG *list;
ULONG i, bsecno, nfree, resvd, bands, blocks;
bands = DIVIDE_UP (total_sectors, 2048 * 8);
blocks = DIVIDE_UP (bands, 512);
if (a_info)
info ("Sectors #" LU_FMT "-#" LU_FMT ": Bitmap indirect block\n",
secno, secno + 4 * blocks - 1);
else if (a_what && IN_RANGE (what_sector, secno, 4 * blocks))
info ("Sector #" LU_FMT ": Bitmap indirect block (+" LU_FMT ")\n",
what_sector, what_sector - secno);
use_sectors (secno, 4 * blocks, USE_BITMAPIND, NULL);
list = xmalloc (2048 * blocks);
read_sec (d, list, secno, 4 * blocks, TRUE);
for (i = 0; i < bands; ++i)
{
bsecno = list[i];
if (bsecno == 0)
{
warning (1, "Bitmap indirect block starting at #" LU_FMT ": "
"Entry " LU_FMT " is zero", secno, i);
break;
}
do_bitmap (d, bsecno, i,
(a_what && what_sector == secno + i / (512 / 4)));
}
if (a_check)
{
for (i = bands; i < blocks * 512; ++i)
if (list[i] != 0)
{
warning (1, "Bitmap indirect block starting at #" LU_FMT ": "
"Too many entries", secno);
break;
}
}
free (list); list = NULL;
if (a_check || a_info)
{
for (i = 0; i < 256; ++i)
{
bit_count[i] = 0;
if (i & 0x01) ++bit_count[i];
if (i & 0x02) ++bit_count[i];
if (i & 0x04) ++bit_count[i];
if (i & 0x08) ++bit_count[i];
if (i & 0x10) ++bit_count[i];
if (i & 0x20) ++bit_count[i];
if (i & 0x40) ++bit_count[i];
if (i & 0x80) ++bit_count[i];
}
nfree = 0;
for (i = 0; i < total_alloc; ++i)
nfree += bit_count[alloc_vector[i]];
resvd = total_sectors / 50;
if (resvd > 4096) resvd = 4096;
if (a_info)
info ("Number of reserved sectors: " LU_FMT " (" LU_FMT " used)\n",
resvd, resvd > nfree ? resvd - nfree : 0);
if (resvd > nfree)
{
if (a_check)
warning (0, "Reserved sectors are in used (" LU_FMT ")", resvd - nfree);
resvd = 0;
}
if (a_info)
info ("Number of unallocated sectors: " LU_FMT " (" LU_FMT " available)\n",
nfree, nfree - resvd);
}
if (alloc_vector != NULL)
alloc_ready = TRUE;
}
/* Compare two file names pointed to by P1 and P2. CPIDX1 and CPIDX2
are the code page indices of the files. If a code page index is
out of range, the current code page will be used. */
static int compare_fname (const BYTE *p1, const BYTE *p2,
ULONG cpidx1, ULONG cpidx2)
{
const BYTE *map1, *map2;
map1 = (cpidx1 >= code_page_count
? cur_case_map : code_pages[cpidx1].case_map);
map2 = (cpidx2 >= code_page_count
? cur_case_map : code_pages[cpidx2].case_map);
for (;;)
{
if (*p1 == 0 && *p2 == 0)
return 0;
if (*p2 == 0)
return 1;
if (*p1 == 0)
return -1;
if (map1[*p1] > map2[*p2])
return 1;
if (map1[*p1] < map2[*p2])
return -1;
++p1; ++p2;
}
}
/* Process one entry of a code page data sector. The entry is in
sector SECNO (used for messages, only). PD points to the code page
entry. The length of the entry is LEN bytes. CS is the expected
checksum for the entry. Update our code page entry pointed to by
DST. */
static void do_cpdata (ULONG secno, const CPDATAENTRY *pd, ULONG len,
ULONG cs, MYCP *dst)
{
ULONG rc, i, diffs, cs2;
COUNTRYCODE cc;
BYTE map[128], c;
BYTE dbcs[12];
memcpy (dst->case_map + 128, pd->bCaseMapTable, 128);
for (c = 0; c < 128; ++c)
map[c] = (BYTE)(c + 128);
cc.country = READ_USHORT (&pd->usCountryCode);
cc.codepage = READ_USHORT (&pd->usCodePageID);
rc = DosMapCase (128, &cc, (PCHAR)map);
if (rc == ERROR_NLS_NO_COUNTRY_FILE)
{
if (!no_country_sys)
warning (0, "COUNTRY.SYS not found -- "
"cannot check case mapping tables");
no_country_sys = TRUE;
}
if (!no_country_sys)
{
if (rc != 0)
warning (1, "DosMapCase failed for " LU_FMT "/" LU_FMT ", rc=" LU_FMT "",
cc.country, cc.codepage, rc);
else
{
diffs = 0;
for (i = 0; i < 128; ++i)
if (map[i] != pd->bCaseMapTable[i])
{
++diffs;
dst->case_map_changed[i+128] = TRUE;
}
/* Don't complain about up to 2 differences in a case
mapping table unless -p is given. */
if (diffs != 0 && (check_pedantic || diffs > 2))
warning (diffs > 2 ? 1 : 0,
"CPDATASEC #" LU_FMT ": Case mapping table does not match "
"DosMapCase for " LU_FMT "/" LU_FMT " (" LU_FMT " difference%s)",
secno, cc.country, cc.codepage, diffs,
diffs == 1 ? "" : "s");
}
rc = DosQueryDBCSEnv (sizeof (dbcs), &cc, (PCHAR)&dbcs);
if (rc != 0)
warning (1, "DosQueryDBCSEnv failed for " LU_FMT "/" LU_FMT ", rc=" LU_FMT "",
cc.country, cc.codepage, rc);
else
{
for (i = 0; i < 6; ++i)
if (dbcs[2*i+0] == 0 && dbcs[2*i+1] == 0)
break;
if (i != READ_USHORT (&pd->cDBCSRange))
warning (1, "CPDATASEC #" LU_FMT ": Number of DBCS ranges does not match "
"DosQueryDBCSEnv for " LU_FMT "/" LU_FMT "",
secno, cc.country, cc.codepage);
else if (memcmp (dbcs, (const char *)pd->DBCSRange, 2 * i) != 0)
warning (1, "CPDATASEC #" LU_FMT ": DBCS ranges does not match "
"DosQueryDBCSEnv for " LU_FMT "/" LU_FMT "",
secno, cc.country, cc.codepage);
}
}
cs2 = chksum ((const BYTE *)pd, len);
if (cs != cs2)
warning (1, "CPDATASEC #" LU_FMT ": Incorrect checksum for " LU_FMT "/" LU_FMT "",
secno, cc.country, cc.codepage);
}
/* Process a code page data sector. DI is an index into
code_pages[]. */
static void do_cpdatasec (DISKIO *d, ULONG di)
{
ULONG secno, dcount, index, offset, len, j, c;
HPFS_SECTOR cpdatasec;
char used[512];
const CPDATAENTRY *pd;
secno = READ_ULONG (&code_pages[di].info.lsnCPData);
for (j = 0; j < cpdata_count; ++j)
if (cpdata_visited[j] == secno)
return;
cpdata_visited[cpdata_count++] = secno;
if (a_info || (a_what && secno == what_sector))
info ("Sector #" LU_FMT ": Code page data sector\n", secno);
use_sectors (secno, 1, USE_CPDATASEC, NULL);
read_sec (d, &cpdatasec, secno, 1, TRUE);
if (READ_ULONG (&cpdatasec.cpdatasec.sig) != CPDATA_SIG1)
{
warning (1, "CPDATASEC #" LU_FMT ": Bad signature", secno);
return;
}
dcount = READ_USHORT (&cpdatasec.cpdatasec.cCodePage);
if (dcount > 3)
{
warning (1, "CPDATASEC #" LU_FMT ": Too many code pages", secno);
dcount = 3;
}
memset (used, FALSE, 512);
for (j = 0; j < dcount; ++j)
{
index = READ_USHORT (&cpdatasec.cpdatasec.iFirstCP) + j;
if (index >= code_page_count)
warning (1, "CPDATASEC #" LU_FMT ": Index too big", secno);
else
{
code_pages[index].hit = TRUE;
for (c = 0; c < 256; ++c)
{
code_pages[index].case_map[c] = (BYTE)c;
code_pages[index].case_map_changed[c] = FALSE;
}
for (c = 'a'; c <= 'z'; ++c)
code_pages[index].case_map[c] = (BYTE)toupper (c);
if (READ_ULONG (&cpdatasec.cpdatasec.cksCP[j])
!= READ_ULONG (&code_pages[index].info.cksCP))
warning (1, "CPDATASEC #" LU_FMT ": Wrong checksum for code page " LU_FMT "",
secno, index);
offset = READ_USHORT (&cpdatasec.cpdatasec.offCPData[j]);
len = sizeof (CPDATAENTRY) - sizeof (DBCSRG);
if (offset < sizeof (cpdatasec.cpdatasec) || offset + len > 512)
warning (1, "CPDATASEC #" LU_FMT ": Invalid offset: " LU_FMT "", secno, offset);
else
{
pd = (const CPDATAENTRY *)(cpdatasec.raw + offset);
if (READ_USHORT (&pd->cDBCSRange)
!= READ_USHORT (&code_pages[index].info.cDBCSRange))
warning (1, "CPDATASEC #" LU_FMT ": Incorrect number of DBCS ranges",
secno);
else
{
len += ((READ_USHORT (&pd->cDBCSRange) + 1)
* sizeof (DBCSRG));
if (offset + len > 512)
warning (1, "CPDATASEC #" LU_FMT ": Invalid offset: " LU_FMT "",
secno, offset);
else if (memchr (used + offset, TRUE, len) != NULL)
warning (1, "CPDATASEC #" LU_FMT ": Overlapping data", secno);
else
{
memset (used + offset, TRUE, len);
do_cpdata (secno, pd, len,
READ_ULONG (&cpdatasec.cpdatasec.cksCP[j]),
&code_pages[index]);
}
}
}
}
}
}
/* Process one code page information sector. PSECNO points to an
object containing the sector number of the code page information
sector. The object will be modified to contain the sector number
of the next code page information sector. The object pointed to by
PCOUNT contains the number of code pages. The object will be
updated. Return TRUE iff successful. */
static int do_one_cpinfosec (DISKIO *d, ULONG *psecno, ULONG *pcount)
{
ULONG secno, i, n, next;
HPFS_SECTOR cpinfosec;
const CPINFOENTRY *pi;
secno = *psecno;
if (a_info || (a_what && secno == what_sector))
info ("Sector #" LU_FMT ": Code page information sector\n", secno);
if (have_seen (secno, 1, SEEN_CPINFOSEC, "code page information"))
return FALSE;
use_sectors (secno, 1, USE_CPINFOSEC, NULL);
read_sec (d, &cpinfosec, secno, 1, TRUE);
if (READ_ULONG (&cpinfosec.cpinfosec.sig) != CPINFO_SIG1)
{
warning (1, "CPINFOSEC #" LU_FMT ": Bad signature", secno);
return FALSE;
}
if (READ_ULONG (&cpinfosec.cpinfosec.iFirstCP) != *pcount)
warning (1, "CPINFOSEC #" LU_FMT ": Wrong code page index", secno);
n = READ_ULONG (&cpinfosec.cpinfosec.cCodePage);
if (n > 31)
{
warning (1, "CPINFOSEC #" LU_FMT ": Too many code pages", secno);
n = 31;
}
for (i = 0; i < n; ++i)
{
pi = &cpinfosec.cpinfosec.CPInfoEnt[i];
code_pages[*pcount].info = *pi;
code_pages[*pcount].hit = FALSE;
if (a_info || (a_what && what_sector == secno))
info (" Code page index " LU_FMT ": code page %u, country %u\n",
i, READ_USHORT (&pi->usCodePageID),
READ_USHORT (&pi->usCountryCode));
if (READ_USHORT (&pi->iCPVol) != *pcount)
warning (1, "CPINFOSEC #" LU_FMT ": Incorrect index", secno);
++*pcount;
}
next = READ_ULONG (&cpinfosec.cpinfosec.lsnNext);
if (next == 0)
return FALSE;
*psecno = next;
return TRUE;
}
/* Process the list of code page information sectors starting in
sector SECNO. */
static void do_cpinfosec (DISKIO *d, ULONG secno)
{
ULONG count, i;
code_pages = xmalloc (code_page_count * sizeof (MYCP));
count = 0;
while (do_one_cpinfosec (d, &secno, &count))
;
if (count != code_page_count)
{
warning (1, "Wrong number of code pages in code page information "
"sectors");
if (count < code_page_count)
code_page_count = count;
}
cpdata_count = 0;
cpdata_visited = xmalloc (code_page_count * sizeof (*cpdata_visited));
for (i = 0; i < code_page_count; ++i)
do_cpdatasec (d, i);
free (cpdata_visited); cpdata_visited = NULL;
for (i = 0; i < code_page_count; ++i)
if (!code_pages[i].hit)
warning (1, "No code page data for code page index " LU_FMT "", i);
/* TODO: check for duplicate code pages */
}
static void do_fnode (DISKIO *d, ULONG secno, const path_chain *path,
int dir_flag, ULONG parent_fnode, ULONG file_size,
ULONG ea_size, int check_ea_size, int need_eas,
int list);
static int do_storage (DISKIO *d, ULONG secno, const ALBLK *header,
ULONG leaf_count, const path_chain *path,
ULONG *pexp_file_sec, ULONG *pnext_disk_sec,
ULONG total_sectors, ULONG parent_fnode,
int alsec_level, BYTE what, ULONG *pextents,
int show, ULONG copy_size, BYTE *buf, ULONG buf_size);
static void do_dirblk (DISKIO *d, ULONG secno, const path_chain *path,
ULONG parent_fnode, ULONG parent, SORT *psort,
int *down_ptr, int level, int *pglobal_dirent_index,
int *pdotdot, int list);
/* Display a warning message for the DIRBLK starting in sector SECNO.
PATH points to the path name chain of the directory. */
static void dirblk_warning (int level, const char *fmt, ULONG secno,
const path_chain *path, ...)
{
va_list arg_ptr;
warning_prolog (level);
my_fprintf (diag_file, "DIRBLK #" LU_FMT " (\"%s\"): ",
secno, format_path_chain (path, NULL));
va_start (arg_ptr, path);
my_vfprintf (diag_file, fmt, arg_ptr);
va_end (arg_ptr);
fputc ('\n', diag_file);
warning_epilog ();
}
/* Display a warning message for directory entry number DIRENT_NO of
the DIRBLK starting in sector SECNO. PATH points to the path name
chain of the directory, FNAME is the file name in the directory
entry. */
static void dirent_warning (int level, const char *fmt, ULONG secno,
const path_chain *path, int dirent_no,
const char *fname, ...)
{
va_list arg_ptr;
warning_prolog (level);
my_fprintf (diag_file, "DIRBLK #" LU_FMT " (\"%s\"): ",
secno, format_path_chain (path, NULL));
if (fname == NULL)
my_fprintf (diag_file, "DIRENT %d: ", dirent_no);
else
my_fprintf (diag_file, "DIRENT %d (\"%s\"): ", dirent_no, fname);
va_start (arg_ptr, fname);
my_vfprintf (diag_file, fmt, arg_ptr);
va_end (arg_ptr);
fputc ('\n', diag_file);
warning_epilog ();
}
/* Show the directory entry pointed to by P. Indent with INDENT
spaces. */
static void show_dirent (const DIRENT *p, int indent)
{
ULONG cpindex, length, gap_size, ace_size, i;
const BYTE *pb;
length = READ_USHORT (&p->cchThisEntry);
infoi ("Length: " LU_FMT "\n", indent, length);
infoi ("Flags: 0x%.2x", indent, p->bFlags);
if (p->bFlags & DF_SPEC) info (" ..");
if (p->bFlags & DF_END) info (" end");
if (p->bFlags & DF_ATTR) info (" EA");
if (p->bFlags & DF_NEEDEAS) info (" need-EA");
if (p->bFlags & DF_PERM) info (" perms");
if (p->bFlags & DF_ACL) info (" ACL");
if (p->bFlags & DF_XACL) info (" explicit-ACL");
info ("\n");
if (!(p->bFlags & DF_END))
{
infoi ("Attributes: 0x%.2x", indent, p->bAttr);
if (p->bAttr & ATTR_DIR)
info (" dir");
if (p->bAttr & ATTR_READONLY)
info (" r/o");
if (p->bAttr & ATTR_HIDDEN)
info (" hidden");
if (p->bAttr & ATTR_SYSTEM)
info (" system");
if (p->bAttr & ATTR_LABEL)
info (" label");
if (p->bAttr & ATTR_ARCHIVED)
info (" arch");
if (p->bAttr & ATTR_NONFAT)
info (" non-FAT");
info ("\n");
infoi ("FNODE: #" LU_FMT "\n", indent,
READ_ULONG (&p->lsnFNode));
infoi ("Time of creation: %s\n", indent,
format_time (READ_ULONG (&p->timCreate)));
infoi ("Time of last modification: %s\n", indent,
format_time (READ_ULONG (&p->timLastMod)));
infoi ("Time of last access: %s\n", indent,
format_time (READ_ULONG (&p->timLastAccess)));
infoi ("Size of file: " LU_FMT "\n", indent,
READ_ULONG (&p->cchFSize));
infoi ("Size of extended attributes: " LU_FMT "\n", indent,
READ_ULONG (&p->ulEALen));
infoi ("Number of ACEs: %u\n", indent, p->bFlex & 7);
cpindex = p->bCodePage & 0x7f;
if (cpindex >= code_page_count)
infoi ("Code page index: " LU_FMT "\n", indent, cpindex);
else
infoi ("Code page: %u\n", indent,
READ_USHORT (&code_pages[cpindex].info.usCodePageID));
if (p->bCodePage & 0x80)
infoi ("Name contains DBCS characters\n", indent);
if (p->bFlags & DF_ACL)
{
gap_size = length - (sizeof (DIRENT) + p->cchName - 1);
if (p->bFlags & DF_BTP)
gap_size -= sizeof (ULONG);
ace_size = (p->bFlex & 7) * 4;
pb = p->bName + p->cchName;
for (i = 0; i < gap_size; ++i)
{
if (i % 16 == 0)
{
if (i != 0)
info ("\n");
infoi ("ACE data: ", indent);
}
info ("%c%.2x",
i == ace_size ? '|' : i > 0 && i % 4 == 0 ? '.' : ' ',
pb[i]);
}
if (gap_size != 0)
info ("\n");
}
}
if (p->bFlags & DF_BTP)
infoi ("Down pointer: #" LU_FMT "\n", indent,
((ULONG *)((const char *)p + length))[-1]);
}
/* Show the directory entry pointed to by P, formatted for the `dir'
action. */
static void show_dir (const DIRENT *p, const char *name)
{
info ("%s ", format_dir_time (READ_ULONG (&p->timLastMod)));
if (p->bAttr & ATTR_DIR)
info (" <DIR> ");
else
info ("%10lu %c%c%c%c%c",
READ_ULONG (&p->cchFSize),
(p->bAttr & ATTR_READONLY) ? 'R' : '-',
(p->bAttr & ATTR_HIDDEN) ? 'H' : '-',
(p->bAttr & ATTR_SYSTEM) ? 'S' : '-',
(p->bAttr & ATTR_LABEL) ? 'V' : '-',
(p->bAttr & ATTR_ARCHIVED) ? 'A' : '-');
info (" \"%s\"\n", name);
}
/* Perform basic checks for the DIRENT at offset POS of the DIRBLK
pointed to by PDIR. Return a pointer to the DIRENT if it looks
reasonably good. Return NULL if it looks bad. Store the name to
NAME, which points to an array of 256 characters. Print warnings
if WARN is TRUE. The remaining arguments are passed to
dirent_warning(). */
const DIRENT *check_dirent (const DIRBLK *pdir, size_t pos, char *name,
int warn, ULONG secno, const path_chain *path,
int index)
{
const DIRENT *p;
ULONG length;
*name = 0;
p = (const DIRENT *)((const char *)pdir + pos);
if (pos + sizeof (DIRENT) > 2048)
{
if (warn)
dirent_warning (1, "Extends beyond end of DIRBLK",
secno, path, index, NULL);
return NULL;
}
length = READ_USHORT (&p->cchThisEntry);
if (pos + length > 2048)
{
if (warn)
dirent_warning (1, "Extends beyond end of DIRBLK",
secno, path, index, NULL);
return NULL;
}
if (length < sizeof (DIRENT))
{
if (warn)
dirent_warning (1, "Length too small (case 1)",
secno, path, index, NULL);
return NULL;
}
if (length < (ROUND_UP (sizeof (DIRENT) + p->cchName - 1, 4)
+ ((p->bFlags & DF_BTP) ? sizeof (ULONG) : 0)))
{
if (warn)
dirent_warning (1, "Length too small (case 2)",
secno, path, index, NULL);
return NULL;
}
if (length & 3)
{
if (warn)
dirent_warning (1, "Length is not a multiple of 4",
secno, path, index, NULL);
return NULL;
}
if (p->bFlags & DF_END)
{
strcpy (name, "[END]");
if (a_check && (p->cchName != 1 || memcmp (p->bName, "\377", 1) != 0))
dirent_warning (0, "Wrong name for end entry",
secno, path, index, NULL);
#if 0
/* This error(?) seems to be quite normal with HPFS386. */
if (a_check && (p->bFlags & DF_SPEC))
dirent_warning (1, "Both DF_END and DF_SPEC are set",
secno, path, index, NULL);
#endif
}
else if (p->bFlags & DF_SPEC)
{
strcpy (name, "..");
if (a_check && (p->cchName != 2 || memcmp (p->bName, "\1\1", 2) != 0))
dirent_warning (0, "Wrong name for \"..\" entry",
secno, path, index, NULL);
}
else
{
memcpy (name, p->bName, p->cchName);
name[p->cchName] = 0;
}
return p;
}
/* Show DIRENTs for the `info <number>' action. */
static void do_dirblk_what (DISKIO *d, const DIRBLK *pdir, ULONG secno,
const path_chain *path)
{
const DIRENT *p;
char name[256];
int dirent_index;
size_t pos;
ULONG length;
if (what_sector == secno)
{
info (" Change count(?): " LU_FMT "\n",
READ_ULONG (&pdir->dirblk.culChange) >> 1);
info (" Offset to first free byte: 0x" LX_FMT "\n",
READ_ULONG (&pdir->dirblk.offulFirstFree));
info (" Pointer to parent: #" LU_FMT "\n",
READ_ULONG (&pdir->dirblk.lsnParent));
info (" Pointer to this directory: #" LU_FMT "\n",
READ_ULONG (&pdir->dirblk.lsnThisDir));
}
pos = offsetof (DIRBLK, dirblk.dirent);
for (dirent_index = 0;; ++dirent_index)
{
p = check_dirent (pdir, pos, name, FALSE, secno, path, dirent_index);
if (p == NULL)
break;
length = READ_USHORT (&p->cchThisEntry);
if (secno + pos / 512 <= what_sector
&& secno + (pos + length - 1) / 512 >= what_sector)
{
info (" ");
if (secno + pos / 512 != what_sector
|| secno + (pos + length - 1) / 512 != what_sector)
info ("Partial ");
info ("DIRENT %d (offset 0x" LX_FMT "):\n", dirent_index, pos);
info (" Name: \"%s\"\n", name);
show_dirent (p, 4);
}
pos += length;
if (p->bFlags & DF_END)
break;
}
}
/* Handle actions which search for a file: Search the DIRBLK for the
current path name component. If found, either show information
about the path name (for `info <path>') or recurse. */
static void do_dirblk_find (DISKIO *d, const DIRBLK *pdir, ULONG secno,
const path_chain *path, ULONG parent_fnode)
{
const DIRENT *p;
char name[256];
int dirent_index, cmp, list;
ULONG cpindex, length;
size_t pos;
path_chain link, *plink;
pos = offsetof (DIRBLK, dirblk.dirent);
for (dirent_index = 0;; ++dirent_index)
{
p = check_dirent (pdir, pos, name, TRUE, secno, path, dirent_index);
if (p == NULL)
break;
length = READ_USHORT (&p->cchThisEntry);
if (p->bFlags & DF_END)
cmp = 1;
else if (p->bFlags & DF_SPEC)
cmp = -1;
else
{
cpindex = p->bCodePage & 0x7f;
cmp = compare_fname ((const BYTE *)name,
(const BYTE *)find_comp,
cpindex, code_page_count);
}
if (cmp < 0)
{
/* The DIRENT's name is less than the name we are looking
for. Examine the next DIRENT. This is the only case in
which the loop is continued. */
pos += length;
}
else if (cmp == 0)
{
/* We found the name. If it's the last component of the
path name we are looking for, show information about the
DIRENT. */
if (*find_path == 0)
{
if (a_where)
{
info ("Directory entry %d of DIRBLK #" LU_FMT "+" LU_FMT " (#" LU_FMT ")\n",
dirent_index, secno, pos / 512, secno + pos / 512);
show_dirent (p, 2);
}
list = FALSE;
if (a_dir)
{
if (p->bAttr & ATTR_DIR)
list = TRUE;
else
{
show_dir (p, name);
quit (0, FALSE);
}
}
if (!(p->bFlags & DF_SPEC))
{
plink = PATH_CHAIN_NEW (&link, path, name);
do_fnode (d, READ_ULONG (&p->lsnFNode), plink,
(p->bAttr & ATTR_DIR), parent_fnode,
READ_ULONG (&p->cchFSize),
READ_ULONG (&p->ulEALen), TRUE,
p->bFlags & DF_NEEDEAS, list);
}
quit (0, FALSE);
}
/* There is at least one more component in the path name, so
this DIRENT must be a directory. */
if (!(p->bAttr & ATTR_DIR))
error ("\"%s\" is not a directory",
format_path_chain (path, name));
/* Recurse into the directory. */
plink = PATH_CHAIN_NEW (&link, path, name);
do_fnode (d, READ_ULONG (&p->lsnFNode), plink, TRUE,
parent_fnode, 0, READ_ULONG (&p->ulEALen), TRUE,
p->bFlags & DF_NEEDEAS, FALSE);
return;
}
else
{
/* The DIRENT's name is greater than the name we are looking
for. If there is a down pointer, recurse into the next
level of the B-tree. Otherwise, there is no such
name. */
if (!(p->bFlags & DF_BTP))
break;
do_dirblk (d, ((ULONG *)((const char *)p + length))[-1],
path, parent_fnode, secno,
NULL, NULL, 0, NULL, NULL, FALSE);
return;
}
}
error ("\"%s\" not found in \"%s\"",
find_comp, format_path_chain (path, NULL));
}
#define MAX_DIRBLK_LEVELS 32
/* Check the down pointer of a DIRENT. INDEX is the index of the
DIRENT, FLAG is zero for a leaf, one for a node. See do_dirblk()
for the remaining arguments. */
static void check_dirent_down (int *down_ptr, int level, ULONG secno,
const path_chain *path, int index, int flag)
{
if (level < MAX_DIRBLK_LEVELS)
{
if (down_ptr[level] == -1)
down_ptr[level] = flag;
else if (down_ptr[level] != flag)
dirent_warning (1, "%s down pointer",
secno, path, index, NULL,
flag == 0 ? "Undesired" : "Missing");
}
}
/* Recurse into the next DIRBLK level for `check' action etc. See
do_dirbkl() for a description of the arguments. */
static void do_dirblk_recurse (DISKIO *d, const DIRBLK *pdir, ULONG secno,
const path_chain *path, ULONG parent_fnode,
ULONG parent, SORT *psort, int *down_ptr,
int level, int *pglobal_dirent_index,
int *pdotdot, int list)
{
const DIRENT *p;
const char *pname;
char name[256];
int dirent_index;
ULONG cpindex, length;
size_t pos;
path_chain link, *plink;
pos = offsetof (DIRBLK, dirblk.dirent);
for (dirent_index = 0;; ++dirent_index)
{
p = check_dirent (pdir, pos, name, TRUE, secno, path, dirent_index);
if (p == NULL)
break;
length = READ_USHORT (&p->cchThisEntry);
if (p->bFlags & DF_BTP)
{
do_dirblk (d, ((ULONG *)((const char *)p + length))[-1],
path, parent_fnode, secno, psort,
down_ptr, level + 1, pglobal_dirent_index, pdotdot,
list);
check_dirent_down (down_ptr, level, secno, path,
dirent_index, 1);
}
else
check_dirent_down (down_ptr, level, secno, path, dirent_index, 0);
if (!(p->bFlags & DF_END))
{
if (p->bFlags & DF_SPEC)
{
pname = "";
if (*pdotdot)
dirent_warning (1, "More than one \"..\" entry",
secno, path, dirent_index, name);
else if (*pglobal_dirent_index != 0)
dirent_warning (1, "\"..\" entry is not the first entry",
secno, path, dirent_index, name);
*pdotdot = TRUE;
}
else
pname = name;
if (verbose)
my_fprintf (prog_file, "%s\n", format_path_chain (path, name));
if (a_check && strlen (name) + path_chain_len (path) > 255)
dirent_warning (1, "Path name too long",
secno, path, dirent_index, name);
cpindex = p->bCodePage & 0x7f;
if (cpindex >= code_page_count)
dirent_warning (1, "Code page index too big",
secno, path, dirent_index, name);
else if (check_pedantic)
{
const BYTE *s;
int changed;
changed = FALSE;
for (s = (const BYTE *)pname; *s != 0; ++s)
if (code_pages[cpindex].case_map_changed[*s])
changed = TRUE;
if (changed)
dirent_warning (0, "Case mapping changed",
secno, path, dirent_index, name);
}
if (compare_fname (psort->name, (const BYTE *)pname,
psort->cpindex, cpindex) > 0)
dirent_warning (1, "File names are not in ascending order "
"(\"%s\" vs \"%s\")",
secno, path, dirent_index, NULL,
psort->name, pname);
strcpy ((char *)psort->name, pname);
psort->cpindex = cpindex;
if (a_check)
{
ULONG t, gap, ace_size, temp_size;
t = READ_ULONG (&p->timLastMod);
if (t != 0 && t < min_time)
dirent_warning (1, "Modification time is out of range (" LU_FMT ")",
secno, path, dirent_index, name, t);
t = READ_ULONG (&p->timLastAccess);
if (t != 0 && t < min_time)
dirent_warning (1, "Access time is out of range (" LU_FMT ")",
secno, path, dirent_index, name, t);
t = READ_ULONG (&p->timCreate);
if (t != 0 && t < min_time)
dirent_warning (1, "Creation time is out of range (" LU_FMT ")",
secno, path, dirent_index, name, t);
if (!(p->bFlags & DF_SPEC))
{
if (!is_hpfs_name ((const BYTE *)name))
dirent_warning (1, "Invalid character in file name",
secno, path, dirent_index, name);
else if (!is_fat_name ((const BYTE *)name)
!= !!(p->bAttr & ATTR_NONFAT))
dirent_warning (1, "Incorrect FAT compatibility bit",
secno, path, dirent_index, name);
}
if (p->bAttr & (0x80 | ATTR_LABEL))
dirent_warning (0, "Undefined attribute bit is set",
secno, path, dirent_index, name);
/* The following ACL stuff is based on a few examples;
the meaning of all this is quite unknown. */
if (p->bFlags & DF_PERM)
dirent_warning (0, "DF_PERM bit is set -- meaning unknown",
secno, path, dirent_index, name);
if ((p->bFlags & (DF_ACL|DF_XACL)) == DF_XACL)
dirent_warning (0, "DF_XACL is set without DF_ACL",
secno, path, dirent_index, name);
gap = READ_USHORT (&p->cchThisEntry);
gap -= (sizeof (DIRENT) + p->cchName - 1);
if (p->bFlags & DF_BTP)
gap -= sizeof (ULONG);
if (gap > 3 && !(p->bFlags & DF_ACL))
dirent_warning (0, "DF_ACL should be set "
"(up to " LU_FMT " bytes of ACEs)",
secno, path, dirent_index, name, gap);
if ((p->bFlex & 7) && !(p->bFlags & DF_ACL))
dirent_warning (0, "DF_ACL should be set (ACE count: %u)",
secno, path, dirent_index, name, p->bFlex & 7);
ace_size = (p->bFlex & 7) * 4;
temp_size = ROUND_UP (sizeof (DIRENT) + p->cchName - 1
+ ace_size, 4);
if (p->bFlags & DF_BTP)
temp_size += sizeof (ULONG);
if (temp_size != READ_USHORT (&p->cchThisEntry))
dirent_warning (0, "ACE count/size mismatch (%u/" LU_FMT ")",
secno, path, dirent_index, name,
p->bFlex & 7, gap);
if (p->bFlex & ~7)
dirent_warning (0, "Bits with unknown meaning are set "
"in bFlex (0x%.2x)",
secno, path, dirent_index, name,
p->bFlex & ~7);
}
if (list)
show_dir (p, name);
else if (!(p->bFlags & DF_SPEC))
{
plink = PATH_CHAIN_NEW (&link, path, name);
do_fnode (d, READ_ULONG (&p->lsnFNode), plink,
(p->bAttr & ATTR_DIR), parent_fnode,
READ_ULONG (&p->cchFSize),
READ_ULONG (&p->ulEALen), TRUE,
p->bFlags & DF_NEEDEAS, list);
}
}
pos += length;
if (p->bFlags & DF_END)
break;
*pglobal_dirent_index += 1;
}
if (pos != READ_ULONG (&pdir->dirblk.offulFirstFree))
dirblk_warning (1, "Wrong offset to first free byte", secno, path);
}
/* Process the DIRBLK starting in sector SECNO. PATH points to the
path name chain of the file or directory. PARENT_FNODE is the
sector number of the FNODE of the directory containing the DIRBLK.
PARENT is the sector number of the parent DIRBLK or (for a DIRBLK
in the top level) of the directory's FNODE. PATH points to the
path name chain of the directory. PSORT points to a structure
containing a file name which must compare less than (or equal to,
for "") the first DIRENT of the current DIRBLK sub-tree. The
structure will be updated to contain the file name of the last
DIRENT of this DIRBLK. DOWN_PTR points to an array recording
down-pointer usage. The array has LEVEL entries.
PGLOBAL_DIRENT_INDEX points to an object containing the index of
the first DIRENT entry of this DIRBLK sub-tree, relative to the
directory. The object will be updated. PDOTDOT points to an
object recording presence of the ".." entry. The object will be
updated. List the directory if LIST is true. */
static void do_dirblk (DISKIO *d, ULONG secno, const path_chain *path,
ULONG parent_fnode, ULONG parent, SORT *psort,
int *down_ptr, int level, int *pglobal_dirent_index,
int *pdotdot, int list)
{
DIRBLK dir;
if (a_what && IN_RANGE (what_sector, secno, 4))
info ("Sector #" LU_FMT ": DIRBLK of \"%s\" (+" LU_FMT ")\n",
what_sector, format_path_chain (path, NULL), what_sector - secno);
if (have_seen (secno, 4, SEEN_DIRBLK, "DIRBLK"))
return;
use_sectors (secno, 4, USE_DIRBLK, path);
if (secno & 3)
dirblk_warning (1, "Sector number is not a multiple of 4", secno, path);
read_sec (d, &dir, secno, 4, TRUE);
if (READ_ULONG (&dir.dirblk.sig) != DIRBLK_SIG1)
{
dirblk_warning (1, "Bad signature", secno, path);
return;
}
++dirblk_total;
if (secno < dirband_start || secno > dirband_end)
++dirblk_outside;
if (READ_ULONG (&dir.dirblk.lsnThisDir) != secno)
dirblk_warning (1, "Wrong self pointer", secno, path);
if (READ_ULONG (&dir.dirblk.lsnParent) != parent)
dirblk_warning (1, "Wrong parent pointer", secno, path);
if (a_check)
{
if (!(READ_ULONG (&dir.dirblk.culChange) & 1) != (level != 0))
dirblk_warning (1, "`top-most' bit is incorrect", secno, path);
}
/* Show DIRENTs for the `info <number>' action. */
if (a_what && IN_RANGE (what_sector, secno, 4))
do_dirblk_what (d, &dir, secno, path);
/* Handle action which search for a file. */
if (a_find && !list)
{
do_dirblk_find (d, &dir, secno, path, parent_fnode);
return;
}
/* Recurse into the next level of the B-tree. */
do_dirblk_recurse (d, &dir, secno, path, parent_fnode, parent, psort,
down_ptr, level, pglobal_dirent_index, pdotdot, list);
}
/* Display a warning message for the ALSEC in sector SECNO. PATH
points to the path name chain of the file or directory. */
static void alsec_warning (int level, const char *fmt, ULONG secno,
const path_chain *path, ...)
{
va_list arg_ptr;
warning_prolog (level);
my_fprintf (diag_file, "ALSEC #" LU_FMT " (\"%s\"): ",
secno, format_path_chain (path, NULL));
va_start (arg_ptr, path);
my_vfprintf (diag_file, fmt, arg_ptr);
va_end (arg_ptr);
fputc ('\n', diag_file);
warning_epilog ();
}
/* Process the ALSEC in sector SECNO. PATH points to the path name
chain of the file or directory. PEXP_FILE_SEC points to an object
containing the first logical sector number mapped by the ALSEC.
The object's value will be incremented by the number of sectors
mapped by the ALSEC. The sector number of the sector following the
previous run is passed in the object pointed to by PNEXT_DISK_SEC.
The object will be updated to contain the sector number of the
sector following the last run. TOTAL_SECTORS is the number of
sectors expected for the object. PARENT_FNODE is the sector number
of the FNODE of the directory containing the object. PARENT_ALBLK
is the sector number of the parent ALSEC or FNODE. ALSEC_LEVEL
contains the current level in the ALSEC tree. WHAT is USE_FILE,
USE_EA, or USE_ACL for file data, extended attributes, or ACL,
respectively. PEXTENTS points to an object counting the number of
extents. The value of that object will be updated. Show
information if SHOW is non-zero. Copy up to COPY_SIZE bytes of
data to the save file. Read sectors to BUF (of BUF_SIZE bytes) if
BUF is non-NULL.
Return the height of the ALSEC sub-tree. */
static int do_alsec (DISKIO *d, ULONG secno, const path_chain *path,
ULONG *pexp_file_sec, ULONG *pnext_disk_sec,
ULONG total_sectors, ULONG parent_fnode,
ULONG parent_alblk, int alsec_level, BYTE what,
ULONG *pextents, int show, ULONG copy_size,
BYTE *buf, ULONG buf_size)
{
HPFS_SECTOR alsec;
int height;
if (show)
info ("ALSEC(%s): #" LU_FMT "\n", alsec_number, secno);
if (a_what && secno == what_sector)
info ("Sector #" LU_FMT ": Allocation sector (ALSEC) for \"%s\"\n",
secno, format_path_chain (path, NULL));
if (have_seen (secno, 1, SEEN_ALSEC, "ALSEC"))
return 1;
use_sectors (secno, 1, USE_ALSEC, path);
read_sec (d, &alsec, secno, 1, TRUE);
if (READ_ULONG (&alsec.alsec.sig) != ALSEC_SIG1)
{
alsec_warning (1, "Bad signature", secno, path);
return 1;
}
++alsec_count;
if (READ_ULONG (&alsec.alsec.lsnSelf) != secno)
alsec_warning (1, "Incorrect self pointer", secno, path);
if (READ_ULONG (&alsec.alsec.lsnRent) != parent_alblk)
alsec_warning (1, "Incorrect parent pointer", secno, path);
height = do_storage (d, secno, &alsec.alsec.alb, 40, path,
pexp_file_sec, pnext_disk_sec, total_sectors,
parent_fnode, alsec_level + 1, what, pextents,
show, copy_size, buf, buf_size);
return height + 1;
}
/* Display a warning message for the allocation structure in sector
SECNO. PATH points to the path name chain of the file or
directory. */
static void alloc_warning (int level, const char *fmt, ULONG secno,
const path_chain *path, int fnode_flag, ...)
{
va_list arg_ptr;
warning_prolog (level);
my_fprintf (diag_file, "%s #" LU_FMT " (\"%s\"): ",
fnode_flag ? "FNODE" : "ALSEC",
secno, format_path_chain (path, NULL));
va_start (arg_ptr, path);
my_vfprintf (diag_file, fmt, arg_ptr);
va_end (arg_ptr);
fputc ('\n', diag_file);
warning_epilog ();
}
/* Process the allocation structure pointed to by HEADER. It is in
sector SECNO (used for messages only). The structure contains
LEAF_COUNT leaves (the number of nodes is computed from
LEAF_COUNT). PATH points to the path name chain of the file or
directory. PEXP_FILE_SEC points to an object containing the first
logical sector number mapped by the allocation structure. The
object's value will be incremented by the number of sectors mapped
by the allocation strcuture. The sector number of the sector
following the previous run is passed in the object pointed to by
PNEXT_DISK_SEC. The object will be updated to contain the sector
number of the sector following the last run. TOTAL_SECTORS is the
number of sectors expected for the object. PARENT_FNODE is the
sector number of the FNODE of the directory containing the object.
ALSEC_LEVEL contains the current level in the ALSEC tree. WHAT is
USE_FILE, USE_EA, or USE_ACL for file data, extended attributes, or
ACL, respectively. PEXTENTS points to an object counting the
number of extents. The value of that object will be updated. Show
information if SHOW is non-zero. Copy up to COPY_SIZE bytes of
data to the save file. Read sectors to BUF (of BUF_SIZE bytes) if
BUF is non-NULL.
Return the height of the ALSEC tree. */
static int do_storage (DISKIO *d, ULONG secno, const ALBLK *header,
ULONG leaf_count, const path_chain *path,
ULONG *pexp_file_sec, ULONG *pnext_disk_sec,
ULONG total_sectors, ULONG parent_fnode,
int alsec_level, BYTE what, ULONG *pextents,
int show, ULONG copy_size, BYTE *buf, ULONG buf_size)
{
const ALLEAF *pleaf = (ALLEAF *)((char *)header + sizeof (ALBLK));
const ALNODE *pnode = (ALNODE *)((char *)header + sizeof (ALBLK));
ULONG i, j, n, start, count, pos;
const char *what_text;
int fnode_flag = (leaf_count == 8);
if (show)
info (" %s count: %u\n",
(header->bFlag & ABF_NODE) ? "Node" : "Leaf", header->cUsed);
/* Note: Do not check for underflow -- as the root node has a
smaller maximum node/leaf count than the other nodes of the tree,
it's impossible to make all (non-root) nodes at least half
filled. */
switch (what)
{
case USE_EA:
what_text = "EA data";
break;
case USE_FILE:
what_text = "file data";
break;
case USE_ACL:
what_text = "ACL";
break;
default:
what_text = "???";
break;
}
if (!(header->bFlag & ABF_FNP) != !(alsec_level == 1))
alloc_warning (1, "ABF_FNP bit is wrong (%d)", secno, path, fnode_flag,
!!(header->bFlag & ABF_FNP));
n = header->cUsed;
if (header->bFlag & ABF_NODE)
{
ULONG node_count = leaf_count + leaf_count / 2;
size_t nlen;
int height, max_height;
if ((ULONG)header->cFree + (ULONG)header->cUsed != node_count)
{
alloc_warning (1, "Wrong number of ALNODEs",
secno, path, fnode_flag);
if (n > node_count)
n = node_count;
}
if (n * sizeof (ALNODE) + sizeof (ALBLK)
!= READ_USHORT (&header->oFree))
alloc_warning (1, "Offset to free entry is wrong",
secno, path, fnode_flag);
nlen = strlen (alsec_number);
max_height = 0;
for (i = 0; i < n; ++i)
{
sprintf (alsec_number + nlen, "." LU_FMT "", i);
height = do_alsec (d, READ_ULONG (&pnode[i].lsnPhys), path,
pexp_file_sec, pnext_disk_sec, total_sectors,
parent_fnode, secno, alsec_level, what,
pextents, show, copy_size, buf, buf_size);
if (READ_ULONG (&pnode[i].lsnLog)
!= (i + 1 == n ? 0xffffffff : *pexp_file_sec))
alloc_warning (1, "Wrong file sector in ALNODE (" LU_FMT " vs. " LU_FMT ")",
secno, path, fnode_flag,
READ_ULONG (&pnode[i].lsnLog),
(i + 1 == n ? 0xffffffff : *pexp_file_sec));
if (i == 0)
max_height = height;
else
{
if (height != max_height)
alloc_warning (1, "Unbalanced allocation tree",
secno, path, fnode_flag);
if (height > max_height)
max_height = height;
}
}
alsec_number[nlen] = 0;
return max_height;
}
else
{
if ((ULONG)header->cFree + (ULONG)header->cUsed != leaf_count)
{
alloc_warning (1, "Wrong number of ALLEAFs",
secno, path, fnode_flag);
if (n > leaf_count)
n = leaf_count;
}
if (n * sizeof (ALLEAF) + sizeof (ALBLK)
!= READ_USHORT (&header->oFree))
alloc_warning (1, "Offset to free entry is wrong",
secno, path, fnode_flag);
*pextents += n;
for (i = 0; i < n; ++i)
{
start = READ_ULONG (&pleaf[i].lsnPhys);
count = READ_ULONG (&pleaf[i].csecRun);
if (READ_ULONG (&pleaf[i].lsnLog) != *pexp_file_sec)
alloc_warning (1, "Wrong file sector (" LU_FMT " vs. " LU_FMT ")",
secno, path, fnode_flag,
READ_ULONG (&pleaf[i].lsnLog), *pexp_file_sec);
if (check_pedantic && *pnext_disk_sec != 0
&& start == *pnext_disk_sec)
alloc_warning (0, "Contiguous runs of disk sectors",
secno, path, fnode_flag);
*pnext_disk_sec = start + count;
if (show)
info (" %c%s in %s (file sector " LU_FMT ")\n",
toupper (what_text[0]), what_text+1,
format_sector_range (start, count),
READ_ULONG (&pleaf[i].lsnLog));
if (a_what && IN_RANGE (what_sector, start, count))
info ("Sector #" LU_FMT ": Sector " LU_FMT " of %s for \"%s\" (+" LU_FMT ")\n",
what_sector,
*pexp_file_sec + what_sector - start,
what_text, format_path_chain (path, NULL),
what_sector - start);
if (a_check && sectors_per_block > 1 && what == USE_FILE)
{
/* These criterions have been guessed... */
if (count < sectors_per_block
&& *pexp_file_sec + count < total_sectors)
alloc_warning (1, "Too fragmented for the `multimedia format'",
secno, path, fnode_flag);
if (start & 3)
alloc_warning (1, "Run not properly aligned for the "
"`multimedia format'", secno, path, fnode_flag);
}
use_sectors (start, count, what, path);
pos = *pexp_file_sec * 512;
if (buf != NULL)
{
if ((*pexp_file_sec + count) * 512 > buf_size)
abort ();
read_sec (d, buf + pos, start, count, TRUE);
}
for (j = 0; j < count && pos < copy_size; ++j)
{
read_sec (d, copy_buf, start, 1, FALSE);
fwrite (copy_buf, MIN (copy_size - pos, 512), 1, save_file);
if (ferror (save_file))
save_error ();
++start; pos += 512;
}
*pexp_file_sec += count;
}
return 0;
}
}
/* Display a warning message for the FNODE in sector SECNO. PATH
points to the path name chain of the file or directory. */
static void fnode_warning (int level, const char *fmt, ULONG secno,
const path_chain *path, ...)
{
va_list arg_ptr;
warning_prolog (level);
my_fprintf (diag_file, "FNODE #" LU_FMT " (\"%s\"): ",
secno, format_path_chain (path, NULL));
va_start (arg_ptr, path);
my_vfprintf (diag_file, fmt, arg_ptr);
va_end (arg_ptr);
fputc ('\n', diag_file);
warning_epilog ();
}
/* Process extended attributes. BUF points to a buffer containing
BUF_SIZE bytes of data. SECNO is the sector number of the FNODE.
PATH is the path name chain for the file or directory. EA_SIZE is
the expected size of the extended attributes. Ignore EA_SIZE if
CHECK_EA_SIZE is FALSE. EA_NEED is the expected number of `need'
EAs. Display information if SHOW is true. */
static void do_auxinfo_ea (DISKIO *d, const BYTE *buf, ULONG buf_size,
ULONG secno, const path_chain *path,
ULONG ea_size, int check_ea_size, ULONG ea_need,
int show)
{
ULONG pos, size, need_ea_count, start, count, bytes;
ULONG value_size, file_sec, disk_sec, extents;
const FEA *pfea;
const SPTR *psptr;
/* BUF points to a list of FEA structures. Process them one by
one. */
pos = 0; size = 0; need_ea_count = 0;
while (pos < buf_size)
{
/* Stop if the FEA structure is not completely inside the
buffer. */
if (pos + sizeof (FEA) > buf_size)
{
fnode_warning (1, "Truncated FEA structure", secno, path);
break;
}
pfea = (FEA *)(buf + pos);
value_size = READ_USHORT (&pfea->cbValue);
if (pos + sizeof (FEA) + pfea->cbName + 1 + value_size > buf_size)
{
fnode_warning (1, "Truncated FEA structure", secno, path);
break;
}
/* The name of an EA must be terminated by a null character. */
if (buf[pos + sizeof (FEA) + pfea->cbName] != 0)
fnode_warning (1, "Name of extended attribute not terminated by "
"a null character", secno, path);
/* Count the number of `need' EAs. After processing all FEA
structures, we'll compare the actual count to the expected
count (from the FNODE). */
if (pfea->fEA & FEA_NEEDEA)
++need_ea_count;
/* There are three methods for storing the value of an extended
attribute. The fEA member of the FEA structure tells us
which one is used for the current EA. Note that bit 7
(FEA_NEEDEA) is used to mark `need' EAs. */
if ((pfea->fEA & 0x7f) == 0x00)
{
/* Method 1: The EA value is stored inline, directly
following the FEA structure. */
if (show_eas >= 1)
info (" Extended attribute %s (" LU_FMT " bytes) is stored inline\n",
format_ea_name (pfea), value_size);
size += sizeof (FEA) + pfea->cbName + 1 + value_size;
if (show_frag)
extents_stat (&ea_extents, 0);
}
else if ((pfea->fEA & 0x7f) == 0x01)
{
/* Method 2: The EA value is stored externally, in one run
of sectors pointed to by a SPTR structure directly
following the FEA structure. */
if (value_size != sizeof (SPTR))
fnode_warning (1, "Incorrect size of FEA structure", secno, path);
else
{
psptr = (const SPTR *)(buf + pos + sizeof (FEA)
+ pfea->cbName + 1);
start = READ_ULONG (&psptr->lsn);
bytes = READ_ULONG (&psptr->cbRun);
count = DIVIDE_UP (bytes, 512);
if (show_eas >= 1)
info (" Extended attribute %s (" LU_FMT " bytes) is stored "
"in %s\n",
format_ea_name (pfea), bytes,
format_sector_range (start, count));
else if (show)
info (" Extended attributes in %s\n",
format_sector_range (start, count));
if (a_what && IN_RANGE (what_sector, start, count))
info ("Sector #" LU_FMT ": EA data for \"%s\"\n",
what_sector, format_path_chain (path, NULL));
use_sectors (start, count, USE_EA, path);
size += sizeof (FEA) + pfea->cbName + 1 + bytes;
if (show_frag)
extents_stat (&ea_extents, 1);
}
}
else if ((pfea->fEA & 0x7f) == 0x03)
{
/* Method 3: The EA value is stored externally, in several
runs of sectors, mapped by an ALSEC which is pointed to
by a SPTR structure directly following the FEA
structure. */
if (value_size != sizeof (SPTR))
fnode_warning (1, "Incorrect size of FEA structure", secno, path);
else
{
psptr = (const SPTR *)(buf + pos + sizeof (FEA)
+ pfea->cbName + 1);
start = READ_ULONG (&psptr->lsn);
bytes = READ_ULONG (&psptr->cbRun);
if (show_eas >= 1)
info (" Extended attribute %s (" LU_FMT " bytes) is stored in "
"sectors mapped by ALSEC #" LU_FMT "\n",
format_ea_name (pfea), bytes, start);
/* Process the ALSEC. */
file_sec = 0; disk_sec = 0; extents = 0;
strcpy (alsec_number, "0");
do_alsec (d, start, path, &file_sec, &disk_sec,
DIVIDE_UP (bytes, 512), secno, secno,
0, USE_EA, &extents, show, 0, NULL, 0);
if (show_eas >= 1)
info (" Number of sectors for this EA: " LU_FMT "\n", file_sec);
/* Check the number of sectors. There is a bug in
HPFS.IFS: It never assigns more than 40 extents (that
is, one ALSEC), truncating EAs. */
if (file_sec * 512 < bytes)
fnode_warning (1, "Not enough sectors allocated for EA %s",
secno, path, format_ea_name (pfea));
if (file_sec > DIVIDE_UP (bytes, 512))
fnode_warning (1, "Too many sectors allocated for EA %s (" LU_FMT ")",
secno, path, format_ea_name (pfea),
file_sec - DIVIDE_UP (bytes, 512));
size += sizeof (FEA) + pfea->cbName + 1 + bytes;
if (show_frag)
extents_stat (&ea_extents, extents);
}
}
else
{
/* No other methods are known. */
fnode_warning (1, "Invalid FEA flag 0x%.2x for extended "
"attribute %s", secno, path, pfea->fEA,
format_ea_name (pfea));
break;
}
pos += sizeof (FEA) + pfea->cbName + 1 + value_size;
}
/* Compare the actual EA size and `need' EA count to the values
stored in the FNODE. */
if (check_ea_size && size != ea_size)
fnode_warning (1, "Incorrect EA size (" LU_FMT " vs. " LU_FMT ")",
secno, path, size, ea_size);
if (need_ea_count != ea_need)
fnode_warning (1, "Incorrect number of `need' EAs (" LU_FMT " vs. " LU_FMT ")",
secno, path, need_ea_count, ea_need);
}
/* Process the data pointed to by an AUXINFO structure (for EAs or
ACL). BUF points to a buffer containing BUF_SIZE bytes of data.
WHAT indicates whether the AUXINFO structure is for EAs or an ACL.
SECNO is the sector number of the FNODE. PATH is the path name
chain for the file or directory. EA_SIZE is the expected size of
the extended attributes. Ignore EA_SIZE if CHECK_EA_SIZE is FALSE.
EA_NEED is the expected number of `need' EAs. Display information
if SHOW is true. */
static void do_auxinfo_buf (DISKIO *d, const BYTE *buf, ULONG buf_size,
BYTE what, ULONG secno, const path_chain *path,
ULONG ea_size, int check_ea_size, ULONG ea_need,
int show)
{
switch (what)
{
case USE_EA:
do_auxinfo_ea (d, buf, buf_size, secno, path, ea_size, check_ea_size,
ea_need, show);
break;
case USE_ACL:
/* I do not yet know anything about ACLs. */
break;
}
}
/* Process the AUXINFO structure (for EAs or ACL) pointed to by PAI.
If the structure indicates that the data is stored inside the
FNODE, take the data from PFNODE, starting at offset BASE. SECNO
is the sector number of the FNODE. PATH is the path name chain for
the file or directory. WHAT indicates whether the AUXINFO
structure is for EAs or an ACL. EA_SIZE is the expected size of
the extended attributes, EA_NEED is the expected number of `need'
EAs. Display information if SHOW is true. */
static void do_auxinfo (DISKIO *d, const FNODE *pfnode, const AUXINFO *pai,
unsigned base, ULONG secno, const path_chain *path,
BYTE what, ULONG ea_size, int check_ea_size,
ULONG ea_need, int show)
{
BYTE *buf;
ULONG buf_size, file_sec, disk_sec, extents, run_length, start, fnode_length;
/* Fetch some values from the AUXINFO structure. */
run_length = READ_ULONG (&pai->sp.cbRun);
start = READ_ULONG (&pai->sp.lsn);
fnode_length = READ_USHORT (&pai->usFNL);
/* EAs and ACLs are either stored entirely inside the FNODE or
entirely externally. Having data both inside the FNODE and
externally is an error. */
if (run_length != 0 && fnode_length != 0)
fnode_warning (1, "Both internal and external %s",
secno, path, (what == USE_EA ? "EA" : "ACL"));
/* No buffer has been allocated so far. */
buf = NULL; buf_size = 0;
/* Data is stored outside the FNODE if pai->sp.cbRun is non-zero. */
if (run_length != 0)
{
buf_size = run_length;
/* If pai->bDat is non-zero, pai->sp.lsn points to an ALSEC.
Otherwise it directly points to the first data sector. */
if (pai->bDat)
{
/* The data is mapped by an ALSEC. */
if (a_where)
{
if (what == USE_EA)
info (" Extended attributes (FEA structures, " LU_FMT " bytes) "
"in sectors mapped by ALSEC #" LU_FMT "\n",
run_length, start);
else
info (" ACL (" LU_FMT " bytes) in sectors mapped by ALSEC #" LU_FMT "\n",
run_length, start);
}
if (buf_size <= 0x100000)
buf = malloc (ROUND_UP (buf_size, 512));
if (buf != NULL)
memset (buf, 0, buf_size);
file_sec = 0; disk_sec = 0; extents = 0;
strcpy (alsec_number, "0");
do_alsec (d, start, path, &file_sec, &disk_sec,
DIVIDE_UP (run_length, 512), secno, secno, 0,
what, &extents, show, 0, buf, ROUND_UP (buf_size, 512));
if (file_sec * 512 < run_length)
fnode_warning (1, "Not enough sectors allocated for %s",
secno, path, (what == USE_EA ? "EAs" : "ACLs"));
if (file_sec > DIVIDE_UP (run_length, 512))
fnode_warning (1, "Too many sectors allocated for %s (" LU_FMT ")",
secno, path, (what == USE_EA ? "EAs" : "ACLs"),
file_sec - DIVIDE_UP (run_length, 512));
}
else
{
/* The data is stored in one run of sectors. */
ULONG count;
count = DIVIDE_UP (run_length, 512);
if (a_where)
{
if (what == USE_EA)
info (" Extended attributes (FEA structures, " LU_FMT " bytes) "
"in %s\n",
run_length, format_sector_range (start, count));
else
info (" ACL (" LU_FMT " bytes) in %s\n",
run_length, format_sector_range (start, count));
}
if (a_what && IN_RANGE (what_sector, start, count))
{
if (what == USE_EA)
info ("Sector #" LU_FMT ": Extended attributes (FEA structures) for "
"\"%s\" (+" LU_FMT ")\n",
what_sector, format_path_chain (path, NULL),
what_sector - start);
else
info ("Sector #" LU_FMT ": ACL for \"%s\" (+" LU_FMT ")\n",
what_sector, format_path_chain (path, NULL),
what_sector - start);
}
use_sectors (start, count, what, path);
if (buf_size <= 0x100000)
{
buf = xmalloc (count * 512);
read_sec (d, buf, start, count, TRUE);
}
}
}
else if (fnode_length != 0)
{
/* The data is stored inside the FNODE. */
if (a_where)
{
if (what == USE_EA)
info (" Extended attributes (FEA structures, " LU_FMT " bytes at 0x%x) "
"in FNODE #" LU_FMT "\n", fnode_length, base, secno);
else
info (" ACL (" LU_FMT " bytes at 0x%x) in FNODE #" LU_FMT "\n",
fnode_length, base, secno);
}
if (base < offsetof (FNODE, abFree))
fnode_warning (1, "%s offset invalid", secno, path,
(what == USE_EA ? "EA" : "ACL"));
else if (base + fnode_length > 512)
fnode_warning (1, "%s beyond end of FNODE", secno, path,
(what == USE_EA ? "EA list" : "ACL"));
else
do_auxinfo_buf (d, (const BYTE *)pfnode + base, fnode_length,
what, secno, path, ea_size, check_ea_size, ea_need,
show);
}
/* If we have copied the data to a buffer, call do_auxinfo_buf() on
that buffer. (For data stored inside the FNODE, do_auxinfo_buf()
has already been called above, without allocating a buffer.) */
if (buf_size != 0)
{
if (buf == NULL)
fnode_warning (1, "%s too big for examination", secno, path,
(what == USE_EA ? "EAs" : "ACL"));
else
{
do_auxinfo_buf (d, buf, buf_size, what, secno, path,
ea_size, check_ea_size, ea_need, show);
free (buf);
}
}
}
/* Process the FNODE in sector SECNO. PATH points to the path name
chain for the file or directory. DIR_FLAG is true if the FNODE
belongs to a directory. PARENT_FNODE is the sector number of the
FNODE of the directory containing the object. FILE_SIZE is the
size of the file. EA_SIZE is the total size of the extended
attributes of the file or directory. Ignore EA_SIZE if
CHECK_EA_SIZE is FALSE (the root directory is the only object for
which EA_SIZE is unknown). NEED_EAS is non-zero if the object has
`need' EAs. List the directory if LIST is true. */
static void do_fnode (DISKIO *d, ULONG secno, const path_chain *path,
int dir_flag, ULONG parent_fnode, ULONG file_size,
ULONG ea_size, int check_ea_size, int need_eas, int list)
{
HPFS_SECTOR fnode;
ULONG file_sec, disk_sec, extents, fn_fsize, i;
size_t name_len;
int show, found, height;
found = (a_find && *find_path == 0);
show = (found && a_where);
if (show)
info ("FNODE: #" LU_FMT "\n", secno);
if (a_what && secno == what_sector)
{
info ("Sector #" LU_FMT ": FNODE for \"%s\"\n",
secno, format_path_chain (path, NULL));
show = TRUE;
}
if (have_seen (secno, 1, SEEN_FNODE, "FNODE"))
return;
use_sectors (secno, 1, USE_FNODE, path);
read_sec (d, &fnode, secno, 1, TRUE);
if (READ_ULONG (&fnode.fnode.sig) != FNODE_SIG1)
{
fnode_warning (1, "Bad signature", secno, path);
if (found)
quit (0, FALSE);
return;
}
if (dir_flag)
++dir_count;
else
++file_count;
fn_fsize = READ_ULONG (&fnode.fnode.fst.ulVLen);
if (!(fnode.fnode.bFlag & FNF_DIR) != !dir_flag)
fnode_warning (1, "Incorrect directory bit", secno, path);
if (READ_ULONG (&fnode.fnode.lsnContDir) != parent_fnode)
fnode_warning (1, "Wrong pointer to containing directory", secno, path);
if (a_check)
{
if ((READ_ULONG (&fnode.fnode.ulRefCount) == 0) != !need_eas)
fnode_warning (1, "Need-EA bit of DIRENT is wrong", secno, path);
name_len = strlen (path->name);
if (fnode.fnode.achName[0] != name_len
&& memcmp (fnode.fnode.achName, path->name, MIN (name_len, 16)) == 0)
fnode_warning (0, "Truncated name mangled by OS/2 2.0 bug",
secno, path);
else if (fnode.fnode.achName[0] != name_len)
fnode_warning (1, "Wrong full name length (" LU_FMT " vs. " LU_FMT ")",
secno, path, (ULONG)fnode.fnode.achName[0],
(ULONG)name_len);
else if (memcmp (fnode.fnode.achName+1, path->name,
MIN (name_len, 15)) != 0)
fnode_warning (1, "Wrong truncated name", secno, path);
if (!dir_flag && file_size != fn_fsize)
fnode_warning (1, "File size does not match DIRENT", secno, path);
if (check_pedantic)
{
for (i = 0; i < sizeof (fnode.fnode.abSpare); ++i)
if (fnode.fnode.abSpare[i] != 0)
fnode_warning (0, "abSpare[" LU_FMT "] is 0x%.2x", secno, path,
i, fnode.fnode.abSpare[i]);
}
}
if (show)
{
info (" Flags: 0x%.2x", fnode.fnode.bFlag);
if (fnode.fnode.bFlag & FNF_DIR)
info (" dir");
info ("\n");
info (" Size of file: " LU_FMT "\n", fn_fsize);
info (" Number of `need' EAs: " LU_FMT "\n",
READ_ULONG (&fnode.fnode.ulRefCount));
info (" Offset of first ACE: %u\n",
READ_USHORT (&fnode.fnode.usACLBase));
info (" ACL size in FNODE: %u\n",
READ_USHORT (&fnode.fnode.aiACL.usFNL));
info (" External ACL size: " LU_FMT "\n",
READ_ULONG (&fnode.fnode.aiACL.sp.cbRun));
}
if (dir_flag)
{
if (show)
info (" Root DIRBLK sector: #" LU_FMT "\n",
READ_ULONG (&fnode.fnode.fst.a.aall[0].lsnPhys));
if (a_copy && found)
error ("Directories cannot be copied");
if (a_find && !found && !list)
{
const char *pdelim;
size_t len;
pdelim = strpbrk (find_path, SEPS);
if (pdelim == NULL)
len = strlen (find_path);
else
len = pdelim - find_path;
if (len > 255)
error ("Path name component too long");
memcpy (find_comp, find_path, len);
find_comp[len] = 0;
find_path += len;
if (ISSEP (*find_path))
{
++find_path;
if (*find_path == 0)
error ("Trailing directory separator");
}
}
if (!found || list)
{
SORT sort;
int index, dotdot, i;
int down_ptr[MAX_DIRBLK_LEVELS];
sort.name[0] = 0;
sort.cpindex = code_page_count;
index = 0; dotdot = FALSE;
for (i = 0; i < MAX_DIRBLK_LEVELS; ++i)
down_ptr[i] = -1; /* Existence of down pointer is unknown */
do_dirblk (d,
READ_ULONG (&fnode.fnode.fst.a.aall[0].lsnPhys),
path, secno, secno, &sort, down_ptr, 0, &index, &dotdot,
list);
if (!dotdot)
warning (1, "Missing \"..\" entry in directory \"%s\"",
format_path_chain (path, NULL));
}
if (a_find && !found)
error ("\"%s\" not found in \"%s\"",
find_comp, format_path_chain (path, NULL));
}
else
{
file_sec = 0; disk_sec = 0; extents = 0;
alsec_number[0] = 0;
height = do_storage (d, secno, &fnode.fnode.fst.alb, 8, path,
&file_sec, &disk_sec, DIVIDE_UP (fn_fsize, 512),
secno, 0, USE_FILE, &extents,
show, found && a_copy ? fn_fsize : 0, NULL, 0);
if (show)
{
info (" Allocation tree height: %d\n", height);
info (" Number of sectors: " LU_FMT "\n", file_sec);
info (" Number of extents: " LU_FMT "\n", extents);
}
if (show_frag)
extents_stat (&file_extents, extents);
if (file_sec * 512 < fn_fsize)
fnode_warning (1, "Not enough sectors allocated", secno, path);
if (file_sec > DIVIDE_UP (fn_fsize, 512))
fnode_warning (1, "Too many sectors allocated (" LU_FMT ")",
secno, path, file_sec - DIVIDE_UP (fn_fsize, 512));
}
/* Extended attributes are stored in the FNODE. ACL entries are
stored first (at offset usACLBase), followed by the extended
attributes. */
do_auxinfo (d, &fnode.fnode, &fnode.fnode.aiEA,
(READ_USHORT (&fnode.fnode.usACLBase)
+ READ_USHORT (&fnode.fnode.aiACL.usFNL)),
secno, path, USE_EA, ea_size, check_ea_size,
READ_ULONG (&fnode.fnode.ulRefCount), show);
do_auxinfo (d, &fnode.fnode, &fnode.fnode.aiACL,
READ_USHORT (&fnode.fnode.usACLBase),
secno, path, USE_ACL, 0, FALSE, 0, show);
if (found)
{
if (a_copy)
save_close ();
quit (0, TRUE);
}
}
/* Complain about sectors which are used but marked unallocated.
Optionally complain about sectors which are not in use but marked
allocated. */
static void check_alloc (void)
{
ULONG i, start, count;
BYTE start_what, first;
const path_chain *start_path;
/* List used sectors not marked as allocated. */
i = 0; first = TRUE;
while (i < total_sectors)
{
if (usage_vector[i] != USE_EMPTY && !ALLOCATED (i))
{
start = i; start_what = usage_vector[i];
start_path = path_vector != NULL ? path_vector[i] : NULL;
do
{
++i;
} while (i < total_sectors
&& usage_vector[i] != USE_EMPTY && !ALLOCATED (i)
&& usage_vector[i] == start_what
&& ((path_vector != NULL ? path_vector[i] : NULL)
== start_path));
if (first)
{
warning (1, "There are used sectors which are not marked "
"as allocated:");
first = FALSE;
}
warning (1, "Used (%s) but not marked as allocated: %s",
sec_usage (start_what),
format_sector_range (start, i - start));
if (start_path != NULL)
warning_cont ("File: \"%s\"",
format_path_chain (start_path, NULL));
}
else
++i;
}
/* List unused sectors marked as allocated. */
i = 0; count = 0;
while (i < total_sectors)
{
if (usage_vector[i] == USE_EMPTY && ALLOCATED (i))
{
start = i;
do
{
++i;
} while (i < total_sectors
&& usage_vector[i] == USE_EMPTY && ALLOCATED (i));
if (check_unused)
warning (0, "Unused but marked as allocated: %s",
format_sector_range (start, i - start));
count += i - start;
if (IN_RANGE (18, start, i - start))
count -= 1;
if (IN_RANGE (19, start, i - start))
count -= 1;
}
else
++i;
}
if (count == 1)
warning (0, "The file system has 1 lost sector");
else if (count > 1)
warning (0, "The file system has " LU_FMT " lost sectors", count);
}
/* Process the DIRBLK band bitmap starting in sector BSECNO. The
bitmap describes COUNT DIRBLKs starting at sector number START. */
static void do_dirblk_bitmap (DISKIO *d, ULONG bsecno, ULONG start,
ULONG count)
{
ULONG sectors, i, dsecno;
BYTE bitmap[2048];
/* Compute the number of sectors used for the DIRBLK bitmap. */
sectors = DIVIDE_UP (count, 512 * 8);
/* The DIRBLK band bitmap always occupies 4 sectors. */
if (sectors > 4)
{
warning (1, "DIRBLK band too big\n");
sectors = 4;
}
read_sec (d, bitmap, bsecno, sectors, TRUE);
/* Compare the bitmap to our usage_vector[]. */
dsecno = start;
for (i = 0; i < count; ++i)
{
if (BITSETP (bitmap, i))
{
if (usage_vector[dsecno] != USE_BANDDIRBLK)
warning (1, "Sector #" LU_FMT " is marked available in the "
"DIRBLK bitmap, but is used as %s\n",
dsecno, sec_usage (usage_vector[dsecno]));
}
else
{
if (usage_vector[dsecno] != USE_DIRBLK)
warning (1, "Sector #" LU_FMT " is marked used in the DIRBLK bitmap, "
"but is used as %s\n",
dsecno, sec_usage (usage_vector[dsecno]));
}
dsecno += 4;
}
}
/* Check the spare DIRBLKs. LIST points to an array of COUNT sector
numbers (in HPFS representation). */
static void check_sparedirblk (const ULONG *list, ULONG total, ULONG free)
{
ULONG i, secno;
for (i = free; i < total; ++i)
{
secno = READ_ULONG (&list[i]);
if (secno < total_sectors && usage_vector[secno] != USE_DIRBLK)
warning (1, "Spare DIRBLK #" LU_FMT " is not used for a DIRBLK", secno);
}
}
/* Build a time stamp for year D, month M, day D. */
static ULONG make_time (int y, int m, int d)
{
struct tm tm;
tm.tm_sec = 0; tm.tm_min = 0; tm.tm_hour = 0;
tm.tm_mday = d; tm.tm_mon = m - 1; tm.tm_year = y - 1900;
tm.tm_isdst = 0;
return (ULONG)mktime (&tm);
}
/* Process an HPFS volume. */
void do_hpfs (DISKIO *d)
{
HPFS_SECTOR superb;
HPFS_SECTOR spareb, spareb_tmp;
ULONG i, n, superb_chksum, spareb_chksum;
ULONG dirband_sectors;
if (a_what && what_cluster_flag)
error ("Cluster numbers not supported on HPFS");
if (fix_zero_ends_dir)
error ("-fix=z not supported for HPFS");
if (a_copy_fat)
error ("`copy-fat' not supported for HPFS");
if (a_get)
error ("`get' not supported for HPFS");
if (a_set)
error ("`set' not supported for HPFS");
if (a_set)
error ("`set' not supported for HPFS");
if (a_set_data)
error ("`set-data' not supported for HPFS");
min_time = make_time (1980, 1, 1);
alloc_ready = FALSE;
/* All structures of HPFS are anchored in the Superblock (LSN 16)
and Spare block (LSN 17) sectors. */
/* Superblock. */
read_sec (d, &superb, 16, 1, TRUE);
if (READ_ULONG (&superb.superb.sig1) != SUPER_SIG1
|| READ_ULONG (&superb.superb.sig2) != SUPER_SIG2)
error ("Invalid signature of superblock -- this is not an HPFS partition");
/* Spare block. */
read_sec (d, &spareb, 17, 1, TRUE);
if (READ_ULONG (&spareb.spareb.sig1) != SPARE_SIG1
|| READ_ULONG (&spareb.spareb.sig2) != SPARE_SIG2)
error ("Invalid signature of spare block");
/* Compute and check the total number of sectors. */
total_sectors = READ_ULONG (&superb.superb.culSectsOnVol);
if (a_what && what_sector >= total_sectors)
warning (0, "Sector number #" LU_FMT " is too big", what_sector);
if (diskio_type (d) == DIO_DISK && total_sectors > diskio_total_sectors (d))
warning (1, "HPFS extends beyond end of partition indicated by BPB");
/* Set the block size. The meaning of bAlign[1] is guessed. */
sectors_per_block = 1;
if (superb.superb.bFuncVersion == 4)
sectors_per_block = 1 << spareb.spareb.bAlign[1];
/* Allocate usage vector. Initially, all sectors are unused. */
usage_vector = (BYTE *)xmalloc (total_sectors);
memset (usage_vector, USE_EMPTY, total_sectors);
/* Allocate `have seen' vector which is used for avoiding loops.
Initially, no sector has been seen. */
seen_vector = (BYTE *)xmalloc (total_sectors);
memset (seen_vector, 0, total_sectors);
/* Allocate vector of path chains for improving error messages.
Note that the following condition must match the condition in the
PATH_CHAIN_NEW macro! */
if (a_check && plenty_memory)
{
path_vector = xmalloc (total_sectors * sizeof (*path_vector));
for (i = 0; i < total_sectors; ++i)
path_vector[i] = NULL;
}
else
path_vector = NULL;
code_page_count = READ_ULONG (&spareb.spareb.culCP);
/* Compute the checksums. */
superb_chksum = chksum (superb.raw, 512);
spareb_tmp = spareb;
spareb_tmp.spareb.bFlag &= (SPF_VER | SPF_FASTFMT);
spareb_tmp.spareb.aulExtra[1] = 0; /* TODO: ULONG_TO_HPFS */
spareb_chksum = chksum (spareb_tmp.raw, 512);
/* Boot sector. */
if (a_what && what_sector == 0)
info ("Sector #" LU_FMT ": Boot sector\n", what_sector);
use_sectors (0, 1, USE_BOOT, NULL);
/* Boot loader. */
if (a_what && IN_RANGE (what_sector, 1, 15))
info ("Sector #" LU_FMT ": Boot loader\n", what_sector);
use_sectors (1, 15, USE_LOADER, NULL);
/* Superblock. */
use_sectors (16, 1, USE_SUPER, NULL);
if (a_info || (a_what && what_sector == 16))
{
info ("Sector #" LU_FMT ": Super block\n", (ULONG)16);
info (" HPFS Version: %d\n",
superb.superb.bVersion);
info (" Functional version: %d",
superb.superb.bFuncVersion);
if (superb.superb.bFuncVersion == 2)
info (" (<=4GB)\n");
else if (superb.superb.bFuncVersion == 3)
info (" (>4GB)\n");
else if (superb.superb.bFuncVersion == 4)
info (" (multimedia)\n");
else
info ("\n");
info (" Root directory FNODE at: #" LU_FMT "\n",
READ_ULONG (&superb.superb.lsnRootFNode));
info (" Total number of sectors: " LU_FMT "\n",
READ_ULONG (&superb.superb.culSectsOnVol));
if (sector_number_format != 0
&& READ_ULONG (&superb.superb.culSectsOnVol) != 0)
info ( "Last sector: #" LU_FMT "\n",
READ_ULONG (&superb.superb.culSectsOnVol) - 1);
info (" Number of bad sectors: " LU_FMT "\n",
READ_ULONG (&superb.superb.culNumBadSects));
info (" Bitmap indirect block at: #" LU_FMT "\n",
READ_ULONG (&superb.superb.rspBitMapIndBlk.lsnMain));
info (" Bad block list starts at: #" LU_FMT "\n",
READ_ULONG (&superb.superb.rspBadBlkList.lsnMain));
info (" Time of last chkdsk: %s\n",
format_time (READ_ULONG (&superb.superb.datLastChkdsk)));
info (" Time of last optimization: %s\n",
format_time (READ_ULONG (&superb.superb.datLastOptimize)));
info (" Number of sectors in DIRBLK band: " LU_FMT "\n",
READ_ULONG (&superb.superb.clsnDirBlkBand));
info (" First sector in DIRBLK band: #" LU_FMT "\n",
READ_ULONG (&superb.superb.lsnFirstDirBlk));
info (" Last sector in DIRBLK band: #" LU_FMT "\n",
READ_ULONG (&superb.superb.lsnLastDirBlk));
info (" First sector of DIRBLK band bitmap: #" LU_FMT "\n",
READ_ULONG (&superb.superb.lsnDirBlkMap));
info (" Sector number of user ID table: #" LU_FMT "\n",
READ_ULONG (&superb.superb.lsnSidTab));
info (" Check sum (computed): 0x" LU_8X_FMT "\n", superb_chksum);
}
/* The Superblock points to the DIRBLK band. */
dirband_sectors = READ_ULONG (&superb.superb.clsnDirBlkBand);
dirband_start = READ_ULONG (&superb.superb.lsnFirstDirBlk);
dirband_end = READ_ULONG (&superb.superb.lsnLastDirBlk);
dirblk_total = 0; dirblk_outside = 0;
/* Spare block. */
use_sectors (17, 1, USE_SPARE, NULL);
if (a_info || (a_what && what_sector == 17))
{
info ("Sector #" LU_FMT ": Spare block\n", (ULONG)17);
info (" Spare block flags: 0x%.2x (",
spareb.spareb.bFlag);
if (spareb.spareb.bFlag & SPF_DIRT)
info ("dirty");
else
info ("clean");
if (spareb.spareb.bFlag & SPF_SPARE) info (" spare");
if (spareb.spareb.bFlag & SPF_HFUSED) info (" hotfix");
if (spareb.spareb.bFlag & SPF_BADSEC) info (" badsec");
if (spareb.spareb.bFlag & SPF_BADBM) info (" badbmp");
if (spareb.spareb.bFlag & SPF_FASTFMT) info (" fastfmt");
if (spareb.spareb.bFlag & SPF_VER) info (" version");
info (")\n");
info (" Block size: " LU_FMT "\n",
sectors_per_block * 512);
info (" Hotfix sector mapping table at: #" LU_FMT "\n",
READ_ULONG (&spareb.spareb.lsnHotFix));
info (" Number of hotfixes used: " LU_FMT "\n",
READ_ULONG (&spareb.spareb.culHotFixes));
info (" Maximum number of hotfixes: " LU_FMT "\n",
READ_ULONG (&spareb.spareb.culMaxHotFixes));
info (" Number of free spare DIRBLKs: " LU_FMT "\n",
READ_ULONG (&spareb.spareb.cdbSpares));
info (" Total number of spare DIRBLKs: " LU_FMT "\n",
READ_ULONG (&spareb.spareb.cdbMaxSpare));
info (" Code page information sector at: #" LU_FMT "\n",
READ_ULONG (&spareb.spareb.lsnCPInfo));
info (" Number of code pages: " LU_FMT "\n",
READ_ULONG (&spareb.spareb.culCP));
info (" Checksum of Super block: 0x" LU_8X_FMT "\n",
READ_ULONG (&spareb.spareb.aulExtra[0]));
info (" Checksum of Spare block: 0x" LU_8X_FMT "\n",
READ_ULONG (&spareb.spareb.aulExtra[1]));
info (" Check sum (computed): 0x" LU_8X_FMT "\n", spareb_chksum);
n = READ_ULONG (&spareb.spareb.cdbMaxSpare);
for (i = 0; i < n; ++i)
info (" Spare DIRBLK at #" LU_FMT "\n",
READ_ULONG (&spareb.spareb.alsnSpareDirBlks[i]));
}
/* DIRBLK band. This is where DIRBLK preferably live. If there is
not enough space in the DIRBLK band, HPFS puts DIRBLKs in other
available sectors (starting at a 4-sector boundary). */
i = dirband_end - dirband_start + 1;
if (a_what && IN_RANGE (what_sector, dirband_start, i))
info ("Sector #" LU_FMT " is in the DIRBLK band\n", what_sector);
use_sectors (dirband_start, i, USE_BANDDIRBLK, NULL);
/* The DIRBLK band has its own allocation bitmap. Each bit maps one
DIRBLK, that is, 4 sectors. */
i = READ_ULONG (&superb.superb.lsnDirBlkMap);
if (a_info)
info ("Sectors #" LU_FMT "-#" LU_FMT ": DIRBLK band bitmap\n", i, i + 3);
if (a_what && IN_RANGE (what_sector, i, 4))
info ("Sector #" LU_FMT " is in the DIRBLK band bitmap (+" LU_FMT ")\n",
what_sector, what_sector - i);
use_sectors (i, 4, USE_DIRBLKBITMAP, NULL);
/* 8 sectors are reserved for storing user IDs. Currently
unused. */
i = READ_ULONG (&superb.superb.lsnSidTab);
if (a_what && IN_RANGE (what_sector, i, 8))
info ("Sector #" LU_FMT ": User ID\n", what_sector);
use_sectors (i, 8, USE_SID, NULL);
/* Spare DIRBLKs. If HPFS runs out of disk space for DIRBLKs in a
split operation, it will use preallocated Spare DIRBLKs. */
n = READ_ULONG (&spareb.spareb.cdbMaxSpare);
for (i = 0; i < n; ++i)
{
if (a_what
&& IN_RANGE (what_sector,
READ_ULONG (&spareb.spareb.alsnSpareDirBlks[i]), 4))
info ("Sector #" LU_FMT ": Spare DIRBLK (+" LU_FMT ")\n",
what_sector,
what_sector
- READ_ULONG (&spareb.spareb.alsnSpareDirBlks[i]));
use_sectors (READ_ULONG (&spareb.spareb.alsnSpareDirBlks[i]),
4, USE_SPAREDIRBLK, NULL);
}
/* Allocate the allocation vector which contains one bit per sector,
indicating whether the sector is in use (0) or available (1).
The vector will be filled in by do_bitmap(), called by
do_bitmap_indirect(). */
if (a_check || a_info || a_what)
{
total_alloc = DIVIDE_UP (total_sectors, 8);
alloc_vector = (BYTE *)xmalloc (total_alloc);
memset (alloc_vector, 0, total_alloc);
}
/* Check the Superblock and the Spare block. */
if (a_check)
{
if (dirband_start > dirband_end)
warning (1, "SUPERBLK #" LU_FMT ": DIRBLK band start greater than "
"DIRBLK band end", (ULONG)16);
if (dirband_sectors & 3)
warning (1, "SUPERBLK #" LU_FMT ": Number of DIRBLK band sectors is "
"not a multiple of 4", (ULONG)16);
if (dirband_start + dirband_sectors - 1 != dirband_end)
warning (1, "SUPERBLK #" LU_FMT ": Wrong DIRBLK band size", (ULONG)16);
if (READ_ULONG (&superb.superb.lsnDirBlkMap) & 3)
warning (1, "SUPERBLK #" LU_FMT ": DIRBLK band bitmap not on a 2K boundary",
(ULONG)16);
if (!(spareb.spareb.bFlag & SPF_HFUSED)
!= (READ_ULONG (&spareb.spareb.culHotFixes) == 0))
warning (1, "SPAREBLK #" LU_FMT ": Hotfix bit is wrong", (ULONG)17);
if (!(spareb.spareb.bFlag & SPF_BADSEC)
!= (READ_ULONG (&superb.superb.culNumBadSects) == 0))
warning (1, "SPAREBLK #" LU_FMT ": Bad sector bit is wrong", (ULONG)17);
if (!(spareb.spareb.bFlag & SPF_SPARE)
!= (READ_ULONG (&spareb.spareb.cdbSpares)
== READ_ULONG (&spareb.spareb.cdbMaxSpare)))
warning (1, "SPAREBLK #" LU_FMT ": Spare DIRBLK bit is wrong", (ULONG)17);
if (READ_ULONG (&spareb.spareb.cdbSpares)
> READ_ULONG (&spareb.spareb.cdbMaxSpare))
warning (1, "SPAREBLK #" LU_FMT ": Number of free spare DIRBLKs exceeds "
"maximum number", (ULONG)17);
if (READ_ULONG (&spareb.spareb.aulExtra[0]) != superb_chksum)
warning (1, "SPAREBLK #" LU_FMT ": Incorrect checksum for Super block",
(ULONG)17);
if (READ_ULONG (&spareb.spareb.aulExtra[1]) != spareb_chksum)
warning (1, "SPAREBLK #" LU_FMT ": Incorrect checksum for Spare block",
(ULONG)17);
if (superb.superb.bFuncVersion == 4)
{
/* `Multimedia format'. To collect more samples for
.bAlign, we display warnings if the values differ from
those on my test partition. I guess that .bAlign[0] is a
set of flag bits and .bAlign[1] indicates the block size
(1 << .bAlign[1] sectors per block). .bAlign[2] is still
unused. */
if (spareb.spareb.bAlign[0] != 8)
warning (0, "SPAREBLK #" LU_FMT ": .bAlign[0] is %u", (ULONG)17,
spareb.spareb.bAlign[0]);
if (spareb.spareb.bAlign[1] != 9)
warning (0, "SPAREBLK #" LU_FMT ": .bAlign[1] is %u", (ULONG)17,
spareb.spareb.bAlign[1]);
}
if (check_pedantic)
{
if (spareb.spareb.bAlign[2] != 0)
warning (0, "SPAREBLK #" LU_FMT ": .bAlign[2] is %u", (ULONG)17,
spareb.spareb.bAlign[2]);
}
}
if (a_check || a_info || a_save || a_what)
{
/* Process the bad block list. */
do_bad (d, READ_ULONG (&superb.superb.rspBadBlkList.lsnMain),
READ_ULONG (&superb.superb.culNumBadSects));
/* Process the hotfix list. */
do_hotfix_list (d, READ_ULONG (&spareb.spareb.lsnHotFix),
READ_ULONG (&spareb.spareb.culMaxHotFixes));
}
/* Process the allocation bitmaps. This fills in alloc_vector. */
if (a_check || a_info || a_save || a_what)
do_bitmap_indirect (d, READ_ULONG (&superb.superb.rspBitMapIndBlk.lsnMain));
/* Process the list of code page sectors. */
if (a_check || a_info || a_save || a_what || a_find)
do_cpinfosec (d, READ_ULONG (&spareb.spareb.lsnCPInfo));
/* Now comes the most interesting part: Walk through all directories
and files, starting in the root directory. */
file_count = 0; dir_count = 0;
extents_init (&file_extents);
extents_init (&ea_extents);
if (a_check || a_save || a_what || a_find)
{
path_chain link, *plink;
plink = PATH_CHAIN_NEW (&link, NULL, "");
do_fnode (d, READ_ULONG (&superb.superb.lsnRootFNode), plink,
TRUE, READ_ULONG (&superb.superb.lsnRootFNode),
0, 0, FALSE, FALSE, (a_dir && *find_path == 0));
}
/* Process the DIRBLK bitmap. */
if (a_check || a_save)
do_dirblk_bitmap (d, READ_ULONG (&superb.superb.lsnDirBlkMap),
dirband_start, dirband_sectors / 4);
if (a_check)
{
/* Check the Spare DIRBLKs. */
check_sparedirblk (spareb.spareb.alsnSpareDirBlks,
READ_ULONG (&spareb.spareb.cdbMaxSpare),
READ_ULONG (&spareb.spareb.cdbSpares));
/* Check allocation bits. */
check_alloc ();
/* Show a summary. */
if (show_summary)
{
info ("Number of directories: " LU_FMT "\n", dir_count);
info ("Number of files: " LU_FMT "\n", file_count);
info ("Number of DIRBLKs: " LU_FMT " (" LU_FMT " outside DIRBLK band)\n",
dirblk_total, dirblk_outside);
info ("Number of ALSECs: " LU_FMT "\n", alsec_count);
}
}
/* Show fragmentation of free space. */
if (a_info && show_free_frag)
do_free_frag ();
/* Show fragmentation of files and extended attributes. */
if (show_frag)
{
extents_show (&file_extents, "file data");
extents_show (&ea_extents, "extended attributes");
}
/* Clean up. */
extents_exit (&file_extents);
extents_exit (&ea_extents);
}
| 35.683465 | 94 | 0.551737 | [
"object",
"vector"
] |
e53f48f2e817935a0ffc9103cbde31178b02dea7 | 9,817 | c | C | animation.c | mmhobi7/oguri | 6937fee10a9b0ef3ad8f94f606c0e0d9e7dec564 | [
"MIT"
] | 257 | 2018-06-17T20:42:41.000Z | 2022-03-31T12:55:55.000Z | animation.c | mmhobi7/oguri | 6937fee10a9b0ef3ad8f94f606c0e0d9e7dec564 | [
"MIT"
] | 46 | 2018-06-17T20:41:10.000Z | 2022-03-06T16:46:53.000Z | animation.c | mmhobi7/oguri | 6937fee10a9b0ef3ad8f94f606c0e0d9e7dec564 | [
"MIT"
] | 8 | 2018-10-14T18:44:31.000Z | 2022-03-06T16:49:12.000Z | #define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sys/timerfd.h>
#include "oguri.h"
#include "buffers.h"
#include "output.h"
#include "animation.h"
static bool set_timer_milliseconds(int timer_fd, unsigned int delay) {
struct itimerspec spec = {
.it_value = (struct timespec) {
.tv_sec = delay / 1000,
.tv_nsec = (delay % 1000) * (long)1000000,
},
};
int ret = timerfd_settime(timer_fd, 0, &spec, NULL);
if (ret < 0) {
fprintf(stderr, "Timer error (fd %d): %s\n", timer_fd, strerror(errno));
return false;
}
return true;
}
static void scale_image_onto(
cairo_t * cairo,
cairo_surface_t * source,
struct oguri_output * output) {
// TODO: Store scaled width/height on buffer so we only need to pass config
int32_t buffer_width = output->width * output->scale;
int32_t buffer_height = output->height * output->scale;
int anchor = output->config->anchor;
cairo_filter_t filter = output->config->filter;
double width = cairo_image_surface_get_width(source);
double height = cairo_image_surface_get_height(source);
double window_ratio = (double)buffer_width / buffer_height;
double bg_ratio = width / height;
cairo_save(cairo);
cairo_matrix_t matrix;
cairo_matrix_init_identity(&matrix);
cairo_pattern_t * pattern = cairo_pattern_create_for_surface(source);
double scale_x = 0.0;
double scale_y = 0.0;
double offset_x = 0.0;
double offset_y = 0.0;
switch (output->config->scaling_mode) {
case SCALING_MODE_FILL:
if (window_ratio > bg_ratio) {
scale_x = scale_y = (double)buffer_width / width;
if (anchor & ANCHOR_TOP) {
offset_y = 0.0;
}
else if (anchor & ANCHOR_BOTTOM) {
offset_y = ((double)buffer_height / scale_y) - height;
}
else { // ANCHOR_CENTER
offset_y = ((double)buffer_height / 2 / scale_y) - (height / 2);
}
} else {
scale_x = scale_y = (double)buffer_height / height;
if (anchor & ANCHOR_LEFT) {
offset_x = 0.0;
}
else if (anchor & ANCHOR_RIGHT) {
offset_x = ((double)buffer_width / scale_x) - width;
}
else { // ANCHOR_CENTER
offset_x = ((double)buffer_width / 2 / scale_x) - (width / 2);
}
}
break;
case SCALING_MODE_STRETCH:
scale_x = (double)buffer_width / width;
scale_y = (double)buffer_height / height;
break;
case SCALING_MODE_TILE:
scale_x = scale_y = (double)output->scale;
cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
if (anchor & ANCHOR_LEFT) {
offset_x = 0.0;
}
else if (anchor & ANCHOR_RIGHT) {
offset_x = ((double)buffer_width / scale_x) - width;
}
else { // ANCHOR_CENTER
offset_x = ((double)buffer_width / 2 / scale_x) - (width / 2);
}
if (anchor & ANCHOR_TOP) {
offset_y = 0.0;
}
else if (anchor & ANCHOR_BOTTOM) {
offset_y = ((double)buffer_height / scale_y) - height;
}
else { // ANCHOR_CENTER
offset_y = ((double)buffer_height / 2 / scale_y) - (height / 2);
}
break;
}
cairo_matrix_translate(&matrix, -offset_x, -offset_y);
cairo_matrix_scale(&matrix, 1 / scale_x, 1 / scale_y);
cairo_pattern_set_matrix(pattern, &matrix);
cairo_pattern_set_filter(pattern, filter);
cairo_set_source(cairo, pattern);
cairo_paint(cairo);
cairo_pattern_destroy(pattern);
cairo_restore(cairo);
}
int oguri_render_frame(struct oguri_animation * anim) {
bool advanced = gdk_pixbuf_animation_iter_advance(anim->frame_iter, NULL);
GdkPixbuf * image = gdk_pixbuf_animation_iter_get_pixbuf(anim->frame_iter);
// If we've got another frame to display, update our timer. Note that while
// it isn't documented, the various implementations of this function take
// into account the elapsed time of the current frame. This means we can
// safely schedule frames early to redraw when new outputs appear without
// worrying about the timing of the next frame being wrong.
int delay = gdk_pixbuf_animation_iter_get_delay_time(anim->frame_iter);
oguri_animation_schedule_frame(anim, delay);
// Only count a frame if we actually advanced. If a new output was added,
// we may have been called early to render the previous frame again.
if (advanced && anim->first_cycle) {
++anim->frame_count;
}
// It's important to set this _after_ we increment the frame_count for the
// final time.
bool last_frame = gdk_pixbuf_animation_iter_on_currently_loading_frame(
anim->frame_iter);
if (last_frame) {
anim->first_cycle = false;
}
struct oguri_output * output;
wl_list_for_each(output, &anim->outputs, link) {
struct oguri_buffer * buffer = oguri_next_buffer(output);
if (output->cached_frames < anim->frame_count) {
if (!anim->first_cycle) {
// When we're past the first cycle, we want to have as many
// buffers as the animation has frames, because then we can
// keep each resized frame in a buffer instead of re-scaling it
// each time. However, we don't know which frame we started on,
// so just attempt to resize every frame until we've cached
// them all.
if (!oguri_allocate_buffers(output, anim->frame_count)) {
// TODO: This will freeze us at the current frame, probably
// should quit instead.
fprintf(stderr, "Unable to allocate %d frame buffers\n",
anim->frame_count);
return -1;
}
}
// Draw the frame into our source surface, at its native size.
oguri_cairo_surface_paint_pixbuf(anim->source_surface, image);
// Then scale it into the buffer.
scale_image_onto(buffer->cairo, anim->source_surface, output);
wl_surface_set_buffer_scale(output->surface, output->scale);
if (!anim->first_cycle) {
// We count the number of frames we've cached to know when
// we've cached them all, even if we didn't start at the first
// frame of the animation. On the first cycle, however, we
// don't want to cache because we don't know how many there
// will be (or if the animation is even finite, technically).
++output->cached_frames;
}
}
// TODO: This should mark the buffer as busy, but we're not actually
// checking for that anyway.
wl_surface_attach(output->surface, buffer->backing, 0, 0);
wl_surface_damage(output->surface, 0, 0, output->width, output->height);
wl_surface_commit(output->surface);
}
return delay;
}
bool oguri_animation_schedule_frame(
struct oguri_animation * anim, unsigned int delay) {
if (delay > 0) {
return set_timer_milliseconds(anim->timerfd, (unsigned int)delay);
}
else {
return true;
}
}
struct oguri_animation * oguri_animation_create(
struct oguri_state * oguri, char * image_path) {
int event_index = -1;
for (size_t i = OGURI_FIRST_ANIM_EVENT; i < OGURI_EVENT_COUNT; ++i) {
if (oguri->events[i].fd == -1) {
event_index = i;
break;
}
}
if (event_index == -1) {
fprintf(stderr, "No event slots available, too many animations!\n");
return NULL;
}
GError * error = NULL;
GdkPixbufAnimation * image = gdk_pixbuf_animation_new_from_file(
image_path, &error);
if (error || !image) {
fprintf(stderr, "Could not open image '%s': %s\n", image_path, error->message);
return NULL;
}
struct oguri_animation * anim = calloc(1, sizeof(struct oguri_animation));
wl_list_init(&anim->outputs);
anim->oguri = oguri;
anim->path = strdup(image_path);
anim->image = image;
anim->frame_iter = gdk_pixbuf_animation_get_iter(image, NULL);
// There's no way to directly ask for the number of frames in an animation,
// because gdk-pixbuf is designed to work with possibly streaming sources.
// However, when loading from a file, the final frame is always marked as
// the "loading frame". We use this, in combination with the following
// flag, to count the frames ourselves. Once we know how many there are, we
// can start caching the scaled buffers instead of rescaling each time we
// draw. We have to track the total length so we don't allocate an infinite
// number of buffers.
anim->first_cycle = true;
// The first frame drawn does not advance, so we can't count it. Instead,
// just start at 1.
anim->frame_count = 1;
// We're going to make the wild assumption that every frame in the
// animation has the same number of channels.
GdkPixbuf * first = gdk_pixbuf_animation_iter_get_pixbuf(anim->frame_iter);
int channel_count = gdk_pixbuf_get_n_channels(first);
// We need a cairo surface of the image's size to draw each frame into
// while scaling them up. This is as good a place for it as any.
anim->source_surface = cairo_image_surface_create(
(channel_count == 3) ? CAIRO_FORMAT_RGB24 : CAIRO_FORMAT_ARGB32,
gdk_pixbuf_animation_get_width(image),
gdk_pixbuf_animation_get_height(image));
anim->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
oguri->events[event_index] = (struct pollfd) {
.fd = anim->timerfd,
.events = POLLIN,
};
anim->event_index = event_index;
if (!oguri_animation_schedule_frame(anim, 1)) { // Show first frame ASAP.
fprintf(stderr, "Unable to schedule first timer\n");
}
wl_list_insert(oguri->animations.prev, &anim->link);
return anim;
}
void oguri_animation_destroy(struct oguri_animation * anim) {
wl_list_remove(&anim->link);
// Disable the pollfd entry so that another animation can reuse it later.
close(anim->timerfd);
anim->oguri->events[anim->event_index] = (struct pollfd) {
.fd = -1,
.events = 0, // Not strictly necessary, but eases debugging.
};
cairo_surface_destroy(anim->source_surface);
g_object_unref(anim->image);
g_object_unref(anim->frame_iter);
free(anim->path);
// Put all of the associated outputs back into the idle list, in case we
// want to reassign them to a new animation later. Destroying them doesn't
// happen until they are removed from the display, or we are told to exit.
wl_list_insert_list(&anim->oguri->idle_outputs, &anim->outputs);
anim->oguri = NULL;
free(anim);
}
| 31.977199 | 81 | 0.712743 | [
"render"
] |
e540cb6e851f09d09911436f9093cb635499b3e8 | 3,734 | h | C | src/tests/ras/unsafe_shutdown/unsafe_shutdown.h | lukaszstolarczuk/pmdk-tests | 5b0e122f30a181baa077828069b0c2289f3e6905 | [
"BSD-3-Clause"
] | 6 | 2017-12-12T10:57:47.000Z | 2021-09-15T07:43:09.000Z | src/tests/ras/unsafe_shutdown/unsafe_shutdown.h | lukaszstolarczuk/pmdk-tests | 5b0e122f30a181baa077828069b0c2289f3e6905 | [
"BSD-3-Clause"
] | 65 | 2017-12-12T14:28:53.000Z | 2021-03-31T18:47:16.000Z | src/tests/ras/unsafe_shutdown/unsafe_shutdown.h | lukaszstolarczuk/pmdk-tests | 5b0e122f30a181baa077828069b0c2289f3e6905 | [
"BSD-3-Clause"
] | 20 | 2017-12-12T10:55:32.000Z | 2022-01-03T20:27:59.000Z | /*
* Copyright 2018, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of 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
* 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.
*/
#ifndef UNSAFE_SHUTDOWN_H
#define UNSAFE_SHUTDOWN_H
#include "configXML/local_dimm_configuration.h"
#include "gtest/gtest.h"
#include "libpmempool.h"
#include "pool_data/pool_data.h"
#include "poolset/poolset_management.h"
#include "shell/i_shell.h"
#include "test_phase/local_test_phase.h"
class UnsafeShutdown : public ::testing::Test {
public:
UnsafeShutdown() {
this->close_pools_at_end_ = !test_phase_.HasInjectAtEnd();
}
IShell shell_;
LocalTestPhase& test_phase_ = LocalTestPhase::GetInstance();
PMEMobjpool* pop_ = nullptr;
PMEMblkpool* pbp_ = nullptr;
PMEMlogpool* plp_ = nullptr;
/* Test values used for checking data consistency on obj/log/blk pools. */
std::vector<int> obj_data_ = {-2, 0, 12345, 1412, 1231, 23, 432, 34, 3};
std::vector<int> blk_data_ = {-2, 0, 12345, 1412, 1231, 23, 432, 34, 3};
std::string log_data_ =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim "
"veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea "
"commodo consequat. Duis aute irure dolor in reprehenderit in voluptate "
"velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint "
"occaecat cupidatat non proident, sunt in culpa qui officia deserunt "
"mollit anim id est laborum.";
bool PassedOnPreviousPhase() const;
std::string GetNormalizedTestName() const;
int PmempoolRepair(std::string pool_file_path) const;
~UnsafeShutdown() {
StampPassedResult();
if (close_pools_at_end_) {
if (pop_) {
pmemobj_close(pop_);
}
if (plp_) {
pmemlog_close(plp_);
}
if (pbp_) {
pmemblk_close(pbp_);
}
}
}
protected:
bool close_pools_at_end_ = true;
private:
const ::testing::TestInfo& GetTestInfo() const {
return *::testing::UnitTest::GetInstance()->current_test_info();
}
std::string GetPassedStamp() const {
return test_phase_.GetTestDir() + GetNormalizedTestName() + "_passed";
}
void StampPassedResult() const;
};
#endif // UNSAFE_SHUTDOWN_H
| 36.970297 | 80 | 0.719068 | [
"vector"
] |
4aedf2086e9afb8abc9f8f582c613801e7bc28f3 | 1,785 | c | C | mud/bldg/road/road.c | shentino/simud | 644b7d4f56bf8d4695442b8efcfd56e0a561fe21 | [
"Apache-2.0"
] | 3 | 2015-07-18T00:19:51.000Z | 2016-02-20T17:25:37.000Z | mud/bldg/road/road.c | shentino/simud | 644b7d4f56bf8d4695442b8efcfd56e0a561fe21 | [
"Apache-2.0"
] | 2 | 2021-03-04T19:24:03.000Z | 2021-03-08T10:17:34.000Z | mud/bldg/road/road.c | shentino/simud | 644b7d4f56bf8d4695442b8efcfd56e0a561fe21 | [
"Apache-2.0"
] | 2 | 2015-12-22T06:16:53.000Z | 2016-11-18T16:32:50.000Z | inherit "/bldg/wall/wall";
NAME( "road" )
DISTANT( "a road" )
SPECIFIC( "the road" )
LOOK( "The road is a carefully cleared path across the landscape." )
PHRASE( "There is a stone road here." )
int query_tile_width() {
return 5;
}
int query_tile_height() {
return 3;
}
// Edge of road is the surface of the road when you walk to it...
mapping query_border() {
return query_shape();
}
nosave string *road_tiles = ({
// 0000
" ... "
" ::: "
" ''' ",
// 0001
" ..."
" ::::"
" '::",
// 0010
" ::: "
" ::: "
" ''' ",
// 0011
" :::."
" ::::"
" ':::",
// 0100
"... "
":::: "
"::' ",
// 0101
"....."
":::::"
":::::",
// 0110 = 0100
".::: "
":::: "
":::' ",
// 0111 = 0101
".:::."
":::::"
":::::",
// 1000
" ... "
" ::: "
" ::: ",
// 1001
" ..."
" ::::"
" ::::",
// 1010
" ::: "
" ::: "
" ::: ",
// 1011
" :::."
" ::::"
" ::::",
// 1100
"... "
":::: "
":::: ",
// 1101
"....."
":::::"
":::::",
// 1110
".::: "
":::: "
":::: ",
// 1111
".:::."
":::::"
":::::",
});
void on_map_paint( object painter ) {
int point, ix, iy;
mapping wallmap;
wallmap = query_spots();
foreach( point : wallmap ) {
string shape_pattern;
int ch, col;
if( CX(point) > environment()->query_map_xdim() ||
CY(point) > environment()->query_map_ydim() ) {
remove_spot(point);
continue;
}
shape_pattern = road_tiles[get_mask(point, wallmap)];
for( ix = 0; ix < 5; ix++ )
for( iy = 0; iy < 3; iy++ ) {
ch = shape_pattern[ix + iy * 5];
if( ch == ' ' )
continue;
if( ch != ':' )
painter->paint( ix + CX(point), iy + CY(point), ch, 0x88, LAYER_TERRAIN );
else
painter->paint( ix + CX(point), iy + CY(point), ch, 0x38, LAYER_TERRAIN );
}
}
}
| 15 | 86 | 0.433613 | [
"object"
] |
4af04da0124e209fb0d2aa89f1de249913a306d8 | 726 | h | C | Include/MammutQOR/Action.h | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Include/MammutQOR/Action.h | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Include/MammutQOR/Action.h | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //Action.h
#ifdef __QCMP_OPTIMIZEINCLUDE
#pragma __QCMP_OPTIMIZEINCLUDE
#endif//__QCMP_OPTIMIZEINCLUDE
#ifndef _MAMMUTQOR_MODEL_ACTION_H_
#define _MAMMUTQOR_MODEL_ACTION H_
#include "SystemQOR.h"
//------------------------------------------------------------------------------
namespace nsMammut
{
class __MAMMUT_INTERFACE CModel;
//------------------------------------------------------------------------------
//Base class for Actions
class __MAMMUT_INTERFACE CAction
{
public:
CAction();
CAction( CModel& model );
virtual ~CAction();
virtual int Apply( CModel& model );
virtual CModel& Detach( void );
virtual int Do( void );
virtual int Undo( void );
};
};
#endif//_MAMMUTQOR_MODEL_ACTION_H_
| 20.166667 | 81 | 0.582645 | [
"model"
] |
4af39239212e7cfa7ac6e82e99f7f6b0a0f892c4 | 3,613 | h | C | dev/vrpv.h | 22427/oflibs | 9e84ad98835799584f88d117bf06116cedd68068 | [
"MIT"
] | 2 | 2018-09-03T13:40:39.000Z | 2020-08-25T15:16:48.000Z | dev/vrpv.h | 22427/oflibs | 9e84ad98835799584f88d117bf06116cedd68068 | [
"MIT"
] | null | null | null | dev/vrpv.h | 22427/oflibs | 9e84ad98835799584f88d117bf06116cedd68068 | [
"MIT"
] | 1 | 2020-08-25T15:16:52.000Z | 2020-08-25T15:16:52.000Z | #pragma once
#include <map>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include "vmath.h"
namespace ofl {
/**
* @brief The Screen class is basically an area in world space you want to
* render to. This might be a powerwall or the side of a cave or a segment
* in a segmented display.
*/
class Screen
{
vec4 m_corners[3];
mat4 m_wall_space;
mat4 m_inv_wall_space;
public:
enum CORNER
{
BL=0,
BR,
TL
} ;
vec4 corner(const int i) const;
/**
* @brief Screen Constructor. Consumes three corners of the Screen area
* The last corner is implied.
* @param blc Bottom left corner.
* @param trc Top right corner.
* @param tlc Top left corner.
*/
Screen(const vec4 blc,const vec4 brc, const vec4& tlc);
/**
* @brief calculate_projection_and_view Calculates a projection- and a view
* matrix for a given eye position.
* Note for stereo rendering you have to call this twice, once per eye.
* @param eye The postition of the eye.
* @param near The near distance.
* @param far The far distance.
* @param projection output where the projection matrix will be written to
* @param view output where the view matrix will be written to
*/
void calculate_projection_and_view(
const vec4& eye,
const float near,
const float far,
mat4& projection_matrix,
mat4& view_matrix) const;
};
/**
* @brief The ScreenArrangement class groups Screens together. This might be use
* full for a cave or a multi-segment-display. Each Screen is accessible via
* its name or its id, or you just store a pointer to the screen you are
* interested in. In that case this class is only usefull for loading and
* storing ScreenArrangements
*/
class ScreenArrangement
{
std::vector<Screen> m_screens;
std::map<std::string,Screen*> m_by_name;
public:
/**
* @brief addScreen Adds a Screen to the arrangement.
* @param scrn The screen you wish to add (will be copied).
* @param name The name of the screen.
* @return a pointer to the interal screen, which can be accessed as long
* as this Object exists.
*/
Screen* addScreen(const Screen scrn, const std::string& name);
/**
* @brief getScreen Provides access to a screen via its id. If there is
* no screen with this id a nullptr is returned.
* @param id The id of the screen.
* @return The Screen you asked for or nullptr if it does not exist.
*/
const Screen* getScreen(const int id)const;
/**
* @brief getScreen Provides access to a screen via its name. If there is
* no screen with this name a nullptr is returned.
* @param name name of the screen.
* @return The Screen you asked for or nullptr if it does not exist.
*/
const Screen* getScreen(const std::string& name);
/**
* @brief count_screens Returns the number of screens in this
* ScreenArrangement
* @return #Screens
*/
unsigned int countScreens() const;
/**
* @brief addScreens Adds screens from a file to this arrangement.
* The format of the file should be:
* <name0> (blx,bly,blz,blw) (brx,bry,brz,brw) (tlx,tly,tlz,tlw)
* <name1> (blx,bly,blz,blw) (brx,bry,brz,brw) (tlx,tly,tlz,tlw)
* # ...
* # a line starting with # is a comment line.
* @param path to the file.
* @return true if everything went well. false if there was a problem with
* the file.
*/
bool loadScreens(const std::string& path);
/**
* @brief saveScreens saves this ScreenArrangement to the disk
* @param path where you want to store this.
* @return true if ecerything went well, false if there was a problem with
* the file.
*/
bool saveScreens(const std::string& path);
};
}
| 28.448819 | 80 | 0.70191 | [
"render",
"object",
"vector"
] |
ab04c07a0676e065d6d4943aefb4630844cf3c29 | 6,884 | c | C | sdk-6.5.20/libs/sdklt/bcmcth/port/bcmcth_port_system.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/bcmcth/port/bcmcth_port_system.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/bcmcth/port/bcmcth_port_system.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | /*! \file bcmcth_port_system.c
*
* This file contains Port system
* software state related intialization and
* cleanup routines.
*/
/*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#include <shr/shr_debug.h>
#include <shr/shr_ha.h>
#include <bsl/bsl.h>
#include <bcmmgmt/bcmmgmt_sysm.h>
#include <bcmltd/chip/bcmltd_id.h>
#include <bcmlrd/bcmlrd_types.h>
#include <bcmlrd/bcmlrd_table.h>
#include <bcmdrd/bcmdrd_types.h>
#include <bcmdrd/bcmdrd_pt.h>
#include <bcmcth/bcmcth_port_util.h>
#include <bcmcth/bcmcth_port_system_table_commit.h>
#include <bcmcth/bcmcth_port_system.h>
#define BSL_LOG_MODULE BSL_LS_BCMCTH_PORT
/*******************************************************************************
* Local definitions
*/
static bcmcth_port_system_state_t port_system_state[BCMDRD_CONFIG_MAX_UNITS];
/*******************************************************************************
* Public functions
*/
/*!
* \brief Get port system state pointer.
*
* Get port system state pointer for the unit.
*
* \param [in] unit Unit Number.
* \param [out] state Returned state pointer.
*
* \retval SHR_E_NONE No errors.
* \retval !SHR_E_NONE Failure.
*/
int
bcmcth_port_system_state_get(int unit, bcmcth_port_system_state_t **state)
{
(*state) = &(port_system_state[unit]);
return SHR_E_NONE;
}
/*!
* \brief Port system sw resources init.
*
* Initialize Port system SW data structures for this unit.
*
* \param [in] unit Unit Number.
* \param [in] warm Cold/Warm boot.
*
* \retval SHR_E_NONE No errors.
* \retval !SHR_E_NONE Failure.
*/
int
bcmcth_port_system_sw_state_init(int unit,
bool warm)
{
uint32_t tbl_sz = 0;
uint32_t ha_alloc_sz = 0, ha_req_sz = 0;
uint32_t size = 0;
SHR_FUNC_ENTER(unit);
SHR_IF_ERR_VERBOSE_EXIT
(bcmlrd_table_size_get(unit, PORT_SYSTEMt, &size));
tbl_sz = size;
if (tbl_sz == 0) {
SHR_EXIT();
}
/* Allocate backup HA memory for port system sw state. */
ha_req_sz = (tbl_sz * sizeof(bcmcth_port_system_t));
ha_alloc_sz = ha_req_sz;
port_system_state[unit].info_ha =
shr_ha_mem_alloc(unit,
BCMMGMT_PORT_COMP_ID,
BCMPORT_SYSTEM_SUB_COMP_ID,
"bcmcthPortSystemState",
&ha_alloc_sz);
SHR_NULL_CHECK(port_system_state[unit].info_ha, SHR_E_MEMORY);
SHR_IF_ERR_VERBOSE_EXIT((ha_alloc_sz < ha_req_sz) ?
SHR_E_MEMORY : SHR_E_NONE);
if (!warm) {
sal_memset(port_system_state[unit].info_ha, 0, ha_alloc_sz);
}
/* Allocate memory for port system sw state. */
SHR_ALLOC(port_system_state[unit].info,
ha_alloc_sz,
"bcmcthtnlL3EgrIntf");
SHR_NULL_CHECK(port_system_state[unit].info, SHR_E_MEMORY);
sal_memset(port_system_state[unit].info, 0, ha_alloc_sz);
port_system_state[unit].tbl_sz = ha_alloc_sz;
/* Copy backup sw state to active sw state. */
sal_memcpy(port_system_state[unit].info,
port_system_state[unit].info_ha,
ha_alloc_sz);
exit:
if (SHR_FUNC_ERR()) {
SHR_FREE(port_system_state[unit].info);
port_system_state[unit].info = NULL;
if (port_system_state[unit].info_ha != NULL) {
shr_ha_mem_free(unit, port_system_state[unit].info_ha);
port_system_state[unit].info_ha = NULL;
}
port_system_state[unit].tbl_sz = 0;
}
SHR_FUNC_EXIT();
}
/*!
* \brief Port system sw resources cleanup.
*
* Cleanup Port system SW data structures allocated for this unit.
*
* \param [in] unit Unit Number.
*
* \retval SHR_E_NONE No errors.
* \retval !SHR_E_NONE Failure.
*/
int
bcmcth_port_system_sw_state_cleanup(int unit)
{
SHR_FUNC_ENTER(unit);
SHR_FREE(port_system_state[unit].info);
port_system_state[unit].info = NULL;
port_system_state[unit].tbl_sz = 0;
SHR_FUNC_EXIT();
}
/*!
* \brief Port system id prepare
*
* \param [in] unit Unit Number.
* \param [in] trans_id LT transaction ID.
* \param [in] arg Transform arguments.
*
* \retval SHR_E_NONE No errors.
* \retval !SHR_E_NONE Failure.
*/
int
bcmcth_port_system_table_prepare(int unit,
uint32_t trans_id,
const bcmltd_generic_arg_t *arg)
{
SHR_FUNC_ENTER(unit);
SHR_FUNC_EXIT();
}
/*!
* \brief Port system id commit
*
* Discard the backup state and copy current state
* to backup state as the current
* transaction is getting committed.
*
* \param [in] unit Unit Number.
* \param [in] trans_id LT transaction ID.
* \param [in] arg Transform arguments.
*
* \retval SHR_E_NONE No errors.
* \retval !SHR_E_NONE Failure.
*/
int
bcmcth_port_system_table_commit(int unit,
uint32_t trans_id,
const bcmltd_generic_arg_t *arg)
{
uint32_t alloc_sz = 0;
bcmcth_port_system_t *bkp_ptr = NULL;
bcmcth_port_system_t *active_ptr = NULL;
SHR_FUNC_ENTER(unit);
alloc_sz = port_system_state[unit].tbl_sz;
bkp_ptr = port_system_state[unit].info_ha;
active_ptr = port_system_state[unit].info;
if ((bkp_ptr == NULL) || (active_ptr == NULL)) {
SHR_ERR_EXIT(SHR_E_FAIL);
}
/* Copy active sw state to backup sw state. */
sal_memcpy(bkp_ptr, active_ptr, alloc_sz);
exit:
SHR_FUNC_EXIT();
}
/*!
* \brief Port system id abort
*
* Rollback the current state to backup state
* as the current transaction is getting aborted.
*
* \param [in] unit Unit Number.
* \param [in] trans_id LT transaction ID.
* \param [in] arg Transform arguments.
*
* \retval SHR_E_NONE No errors.
* \retval !SHR_E_NONE Failure.
*/
int
bcmcth_port_system_table_abort(int unit,
uint32_t trans_id,
const bcmltd_generic_arg_t *arg)
{
uint32_t alloc_sz = 0;
bcmcth_port_system_t *bkp_ptr = NULL;
bcmcth_port_system_t *active_ptr = NULL;
SHR_FUNC_ENTER(unit);
alloc_sz = port_system_state[unit].tbl_sz;
bkp_ptr = port_system_state[unit].info_ha;
active_ptr = port_system_state[unit].info;
if ((bkp_ptr == NULL) || (active_ptr == NULL)) {
SHR_ERR_EXIT(SHR_E_FAIL);
}
/* Copy backup sw state to active sw state. */
sal_memcpy(active_ptr, bkp_ptr, alloc_sz);
exit:
SHR_FUNC_EXIT();
}
| 27.102362 | 134 | 0.616793 | [
"transform"
] |
ab1c9a9256211ff190533498f6007d858e5cbe30 | 4,288 | h | C | include/fasta.h | ruolin/Strawberry | d8ec735675fabab65cf117b1c7798f6df4dd09d5 | [
"MIT"
] | 27 | 2017-05-03T04:49:46.000Z | 2022-02-03T16:17:51.000Z | include/fasta.h | ruolin/strawberry | d8ec735675fabab65cf117b1c7798f6df4dd09d5 | [
"MIT"
] | 30 | 2017-03-29T06:09:21.000Z | 2021-08-06T05:45:27.000Z | include/fasta.h | ruolin/Strawberry | d8ec735675fabab65cf117b1c7798f6df4dd09d5 | [
"MIT"
] | 3 | 2017-12-03T17:03:02.000Z | 2019-04-28T08:44:14.000Z |
/*
* Created on: Jan 23, 2015
* Author: Ruolin Liu
*/
#ifndef FASTA_H_
#define FASTA_H_
#include<unordered_map>
#include<memory>
class FaRecord{
/*
* * FASTA format: https://en.wikipedia.org/wiki/FASTA_format
*
* >gi|31563518|ref|NP_852610.1| microtubule-associated proteins 1A/1B light chain 3A isoform b [Homo sapiens]
MKMRFFSSPCGKAAVDPADRCKEVQQIRDQHPSKIPVIIERYKGEKQLPVLDKTKFLVPDHVNMSELVKI
IRRRLQLNPTQAFFLLVNQHSMVSVSTPIADIYEQEKDEDGFLYMVYASQETFGFIRENE.
*
* The sequence can be multiple lines.
*
* One FaRecord is such an entry.
*/
public:
std::string _seq_name; // e.g. gi|31563518|ref|NP_852610.1|
uint _seq_len = 0;
off_t _fpos = 0; // seq fpos in the file
int _line_len = 0; //effective line length (without EoL)
int _line_blen = 0; //length of line including EoL characters
FaRecord(std::string name, uint len, off_t fpos, int llen, int blen):
_seq_name(name),
_seq_len(len),
_fpos(fpos),
_line_len(llen),
_line_blen(blen){}
FaRecord() = default;
};
class FaIndex{
/*
* Class represents a single fasta file.
* In some cases, it is one fasta file per chromosome, therefore multiple objects.
* In other cases, it is one fasta file contains all chromosomes, therefore one object.
*/
std::string _fa_name; // fasta file name
std::string _fai_name; // fasta index file name
bool _haveFai;
public:
std::unordered_map<std::string, FaRecord> _records; // map seq name to record.
using FaRecord_p = std::unordered_map<std::string, FaRecord>::const_iterator;
FaIndex(const char* fname, const char* finame=NULL);
bool add_record(std::string seqname, const uint seqlen, const off_t fpos, const int linelen, const int lineblen);
bool getRecord(const std::string& seqname, FaRecord &got) const;
const std::string get_faidx_name() const;
bool hasIndex();
int loadIndex(); //return the number of record loaded
int buildIndex(); //this function has not been implemented //return the number of record
int writeIndex(); // return number of record which is stored
int num_records() const;
};
class SubSeq{
public:
uint _subseq_start;
uint _subseq_len;
char* _sequence;
SubSeq():
_subseq_start(1),
_subseq_len(0),
_sequence(nullptr){}
~SubSeq(){
delete []_sequence;
_sequence = nullptr;
}
SubSeq& operator=(const SubSeq &rhs) = delete;
SubSeq(const SubSeq &other) = delete;
SubSeq(SubSeq &&rhs):
_subseq_start(rhs._subseq_start),
_subseq_len(rhs._subseq_len),
_sequence(rhs._sequence)
{
rhs._sequence = nullptr;
}
SubSeq& operator=(SubSeq &&rhs){
if(this != &rhs){
delete []_sequence;
_subseq_start = rhs._subseq_start;
_subseq_len = rhs._subseq_len;
_sequence = rhs._sequence;
rhs._sequence = nullptr;
}
return *this;
}
void setup(uint s, uint l);
};
class FaSeqGetter{
/*
* One seq at a time in memory
*/
std::string _fname;
FILE* _fh = nullptr;
SubSeq _my_subseq;
FaRecord _my_record;
public:
const static int MAX_LEN_TO_READ = 0x20000000;
FaSeqGetter() = default;
void initiate(const std::string fname, const FaRecord &rec);
std::string get_fname() const;
// Default parameters mean loading a whole sequence
// for the first time.
uint loadSeq(uint start = 1, uint len = 0);
std::string fetchSeq(uint start, uint len);
~FaSeqGetter();
FaSeqGetter(const FaSeqGetter &other) = delete;
FaSeqGetter& operator=(const FaSeqGetter &other) = delete;
FaSeqGetter(FaSeqGetter &&other) = delete;
FaSeqGetter& operator=(FaSeqGetter &&other) = delete;
};
class FaInterface{
bool _has_load = false;
public:
std::string _fa_path;
std::unordered_map<std::string, std::unique_ptr<FaIndex>> _fa_indexes; //map fasta file name to faidx
std::unordered_map<std::string, std::string> _seqname_2_fafile; // map seq name to fasta file name.
using ItFaidx = std::unordered_map<std::string, std::unique_ptr<FaIndex>>::iterator;
void initiate(const char* fpath=nullptr);
void load2FaSeqGetter(FaSeqGetter &getter, const std::string seqname);
bool hasLoad() const{
return _has_load;
}
};
#endif /* FASTA_H_ */
| 30.848921 | 116 | 0.683069 | [
"object"
] |
ab1deda78ee0f46623cc62e480421bfbe08a0a3a | 2,154 | c | C | nitan/kungfu/special/haina.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/kungfu/special/haina.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/kungfu/special/haina.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null |
#include <ansi.h>
#include <combat.h>
int is_scborn() { return 1; }
string name() { return HIC "海納百川" NOR; }
int perform(object me, string skill, string arg)
{
int joblv, armor, damage, attack;
joblv = me->query_joblv();
if (me->query_temp("special2/haina/joblv"))
return notify_fail("你已經在運功中了。\n");
if (me->query("yhjob/job") != "隱士")
return notify_fail("你的職業錯誤,無法施展。\n");
if (me->query("neili") < 1000)
return notify_fail("你的內力不足,無法施展。\n");
if (joblv < 20)
return notify_fail("你的職業等級不足,無法施展。\n");
if (me->is_busy())return notify_fail("等你忙完再説吧!\n");
message_vision(HIM "$N" HIM "臉色微變,深吸一口氣,然後緩緩吐出,頃刻間,周身瀰漫着陣陣薄霧。\n" NOR, me);
me->add("neili", -1000);
me->start_busy(1);
joblv = joblv + me->query("lhpoint/special/haina") * 7;
me->set_temp("special2/haina/joblv", joblv);
armor = me->query_temp("apply/armor");
damage = me->query_temp("apply/damage");
attack = 1;//me->query_temp("apply/attack"); 在 combatd.c裏做處理
armor = armor * (10 + (joblv - 20) / 2) / 100;
attack = 1;//attack * (10 + (joblv - 20) / 2) / 100;
damage = damage * (10 + (joblv - 20) / 2) / 100;
if (damage <= 0)damage = 0;
me->add_temp("apply/armor", armor);
me->add_temp("apply/damage", damage);
me->add_temp("apply/attack", attack);
me->start_call_out( (: call_other, __FILE__, "remove_effect", me, joblv, armor, damage, attack :), joblv * 10);
return 1;
}
void remove_effect(object me, int joblv, int armor, int damage, int attack)
{
if (! objectp(me))return;
if ((int)me->query_temp("special2/haina/joblv"))
{
me->add_temp("apply/armor", -1 * armor);
me->add_temp("apply/damage", -1 * damage);
me->add_temp("apply/attack", -1 * attack);
me->delete_temp("special2/haina/joblv");
tell_object(me, "你海納百川運功完畢。\n");
}
}
| 31.676471 | 127 | 0.524141 | [
"object"
] |
ab1fa6278072551dcade7f2b109f534ec571dca6 | 9,179 | c | C | core/expr-vector.c | nvt/veloxvm | fed68b307d3607b24f2c089e8c67cf052451c58f | [
"BSD-3-Clause"
] | 14 | 2018-01-10T01:26:56.000Z | 2021-10-24T00:14:00.000Z | core/expr-vector.c | nvt/veloxvm | fed68b307d3607b24f2c089e8c67cf052451c58f | [
"BSD-3-Clause"
] | null | null | null | core/expr-vector.c | nvt/veloxvm | fed68b307d3607b24f2c089e8c67cf052451c58f | [
"BSD-3-Clause"
] | 2 | 2018-02-22T12:12:46.000Z | 2018-04-16T03:08:52.000Z | /*
* Copyright (c) 2012-2017, RISE SICS AB
* 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 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.
*
* Author: Nicolas Tsiftes <nvt@acm.org>
*/
#include "vm-functions.h"
#include "vm-list.h"
VM_FUNCTION(make_vector)
{
vm_vector_t *vector;
vm_integer_t i;
if(argv[0].type != VM_TYPE_INTEGER) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_TYPES);
return;
}
vector = vm_vector_create(&thread->result, argv[0].value.integer,
VM_VECTOR_FLAG_REGULAR);
if(vector == NULL) {
vm_signal_error(thread, VM_ERROR_HEAP);
return;
}
if(argc == 2) {
for(i = 0; i < vector->length; i++) {
memcpy(&vector->elements[i], &argv[1], sizeof(vm_obj_t));
}
} else {
for(i = 0; i < vector->length; i++) {
vector->elements[i].type = VM_TYPE_NONE;
}
}
}
VM_FUNCTION(vector)
{
vm_vector_t *vector;
vector = vm_vector_create(&thread->result, argc, VM_VECTOR_FLAG_REGULAR);
if(vector == NULL) {
vm_signal_error(thread, VM_ERROR_HEAP);
return;
}
memcpy(vector->elements, argv, sizeof(vm_obj_t) * argc);
}
VM_FUNCTION(vectorp)
{
VM_PUSH_BOOLEAN(argv[0].type == VM_TYPE_VECTOR);
}
VM_FUNCTION(bufferp)
{
VM_PUSH_BOOLEAN(argv[0].type == VM_TYPE_VECTOR &&
IS_SET(argv[0].value.vector->flags, VM_VECTOR_FLAG_BUFFER));
}
VM_FUNCTION(vector_merge)
{
vm_vector_t *vector;
int i;
int j;
int k;
unsigned element_count;
element_count = 0;
for(i = 0; i < argc; i++) {
element_count += argv[i].type == VM_TYPE_VECTOR ?
argv[i].value.vector->length : 1;
}
vector = vm_vector_create(&thread->result, element_count,
VM_VECTOR_FLAG_REGULAR);
if(vector == NULL) {
vm_signal_error(thread, VM_ERROR_HEAP);
return;
}
for(i = 0, j = 0; i < argc; i++) {
if(argv[i].type == VM_TYPE_VECTOR) {
if(IS_SET(argv[i].value.vector->flags, VM_VECTOR_FLAG_BUFFER)) {
for(k = 0; k < argv[i].value.vector->length; k++) {
vector->elements[j + k].type = VM_TYPE_INTEGER;
vector->elements[j + k].value.integer = argv[i].value.vector->bytes[k];
}
} else {
memcpy(&vector->elements[j], argv[i].value.vector->elements,
sizeof(vm_obj_t) * argv[i].value.vector->length);
}
j += argv[i].value.vector->length;
} else {
memcpy(&vector->elements[j], &argv[i], sizeof(vm_obj_t));
j++;
}
}
}
VM_FUNCTION(vector_length)
{
VM_PUSH_INTEGER(argv[0].value.vector->length);
}
VM_FUNCTION(vector_ref)
{
vm_vector_t *vector;
vm_integer_t k;
if(argv[0].type != VM_TYPE_VECTOR || argv[1].type != VM_TYPE_INTEGER) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_TYPES);
return;
}
vector = argv[0].value.vector;
k = argv[1].value.integer;
if(k < 0 || k >= vector->length) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_VALUE);
vm_set_error_object(thread, &argv[1]);
} else {
if(IS_SET(vector->flags, VM_VECTOR_FLAG_BUFFER)) {
VM_PUSH_CHARACTER(vector->bytes[k]);
} else {
VM_PUSH(&vector->elements[k]);
}
}
}
VM_FUNCTION(vector_set)
{
vm_integer_t k;
int r;
if(argv[0].type != VM_TYPE_VECTOR || argv[1].type != VM_TYPE_INTEGER) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_TYPES);
return;
}
k = argv[1].value.integer;
r = vm_vector_set(&argv[0], k, &argv[2]);
if(r < 0) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_VALUE);
if(r == -1) {
vm_set_error_object(thread, &argv[1]);
} else {
vm_set_error_string(thread, "buffer element must be integer or character type");
}
}
}
VM_FUNCTION(vector_to_list)
{
vm_vector_t *vector;
vm_list_t *list;
vm_integer_t i;
vm_obj_t ch;
vector = argv[0].value.vector;
list = vm_list_create();
if(list == NULL) {
vm_signal_error(thread, VM_ERROR_HEAP);
return;
}
if(IS_SET(vector->flags, VM_VECTOR_FLAG_BUFFER)) {
ch.type = VM_TYPE_CHARACTER;
for(i = 0; i < vector->length; i++) {
ch.value.character = vector->bytes[i];
if(!vm_list_insert_tail(list, &ch)) {
vm_signal_error(thread, VM_ERROR_HEAP);
return;
}
}
} else {
for(i = 0; i < vector->length; i++) {
if(!vm_list_insert_tail(list, vector->elements + i)) {
vm_signal_error(thread, VM_ERROR_HEAP);
return;
}
}
}
VM_PUSH_LIST(list);
}
VM_FUNCTION(list_to_vector)
{
vm_list_t *list;
vm_integer_t i;
vm_list_item_t *item;
list = argv[0].value.list;
if(vm_vector_create(&thread->result, list->length,
VM_VECTOR_FLAG_REGULAR) == NULL) {
vm_signal_error(thread, VM_ERROR_HEAP);
} else {
for(i = 0, item = list->head; item != NULL; i++, item = item->next) {
if(vm_vector_set(&thread->result, i, &item->obj) < 0) {
vm_signal_error(thread, VM_ERROR_INTERNAL);
return;
}
}
}
}
VM_FUNCTION(vector_fill)
{
vm_vector_t *vector;
vm_integer_t i;
int r;
if(argv[0].type != VM_TYPE_VECTOR) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_TYPES);
return;
}
vector = argv[0].value.vector;
for(i = 0; i < vector->length; i++) {
r = vm_vector_set(&argv[0], i, &argv[1]);
if(r < 0) {
vm_signal_error(thread,
r == -1 ? VM_ERROR_INTERNAL : VM_ERROR_ARGUMENT_VALUE);
return;
}
}
}
VM_FUNCTION(make_buffer)
{
vm_vector_t *vector;
if(argv[0].type != VM_TYPE_INTEGER) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_TYPES);
return;
}
vector = vm_vector_create(&thread->result, argv[0].value.integer,
VM_VECTOR_FLAG_BUFFER);
if(vector == NULL) {
vm_signal_error(thread, VM_ERROR_HEAP);
return;
}
}
VM_FUNCTION(buffer_append)
{
vm_vector_t *dst_vector;
vm_vector_t *vector;
vm_string_t *string;
vm_integer_t index;
unsigned byte_count;
uint8_t byte_value;
if(argv[0].type != VM_TYPE_VECTOR || argv[1].type != VM_TYPE_INTEGER) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_TYPES);
return;
}
dst_vector = argv[0].value.vector;
if(IS_CLEAR(dst_vector->flags, VM_VECTOR_FLAG_BUFFER)) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_TYPES);
return;
}
index = argv[1].value.integer;
/* Check whether there is room for one more byte in the buffer. */
byte_count = 1;
if(index < 0 || index + byte_count > (unsigned)dst_vector->length) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_VALUE);
return;
}
switch(argv[2].type) {
case VM_TYPE_CHARACTER:
byte_value = (unsigned)argv[2].value.character & 0xff;
dst_vector->bytes[index] = byte_value;
break;
case VM_TYPE_INTEGER:
byte_value = (unsigned)argv[2].value.integer & 0xff;
dst_vector->bytes[index] = byte_value;
break;
case VM_TYPE_VECTOR:
vector = argv[2].value.vector;
if(IS_CLEAR(vector->flags, VM_VECTOR_FLAG_BUFFER)) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_VALUE);
return;
}
byte_count = vector->length;
/* Check buffer boundary. */
if(index + byte_count > (unsigned)dst_vector->length) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_VALUE);
return;
}
memcpy(&dst_vector->bytes[index], vector->bytes, byte_count);
break;
case VM_TYPE_STRING:
string = argv[2].value.string;
byte_count = string->length;
/* Check buffer boundary. */
if(index + byte_count > (unsigned)dst_vector->length) {
vm_signal_error(thread, VM_ERROR_ARGUMENT_VALUE);
return;
}
memcpy(&dst_vector->bytes[index], string->str, byte_count);
break;
default:
vm_signal_error(thread, VM_ERROR_ARGUMENT_TYPES);
return;
}
VM_PUSH_INTEGER(byte_count);
}
| 26.225714 | 86 | 0.658133 | [
"vector"
] |
ab28a013004c29f3bc7c94d5ea4e74e8e490642f | 3,880 | h | C | include/absolutePoseEstimation/translationAveraging/TranslationAverager.h | leoneed03/reconstrutor | 5e6417ed2b090617202cad1a10010141e4ce6615 | [
"MIT"
] | null | null | null | include/absolutePoseEstimation/translationAveraging/TranslationAverager.h | leoneed03/reconstrutor | 5e6417ed2b090617202cad1a10010141e4ce6615 | [
"MIT"
] | null | null | null | include/absolutePoseEstimation/translationAveraging/TranslationAverager.h | leoneed03/reconstrutor | 5e6417ed2b090617202cad1a10010141e4ce6615 | [
"MIT"
] | null | null | null | //
// Copyright (c) Leonid Seniukov. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
//
#ifndef GDR_TRANSLATIONAVERAGER_H
#define GDR_TRANSLATIONAVERAGER_H
#include "parametrization/SE3.h"
#include <Eigen/Eigen>
#include <vector>
#include <map>
#include "TranslationMeasurement.h"
#include "parametrization/Vectors3d.h"
namespace gdr {
class TranslationAverager {
static SparseMatrixd constructSparseMatrix(const std::vector<TranslationMeasurement> &relativeTranslations,
const std::vector<SE3> &absolutePoses,
int indexPoseFixed);
static Vectors3d
constructColumnTermB(const std::vector<TranslationMeasurement> &relativeTranslations,
const std::vector<SE3> &absolutePoses);
static Vectors3d
findLeastSquaresSolution(const SparseMatrixd &anyMatrixA,
const Vectors3d &b,
bool &success,
const SparseMatrixd &weightDiagonalMatrix,
bool useInitialGuess = false,
Vectors3d initialGuessX = Vectors3d());
static SparseMatrixd getWeightMatrixRaw(const std::vector<double> &weights,
double epsilonWeightMin);
static Vectors3d
IRLS(const SparseMatrixd &systemMatrix,
const Vectors3d &b,
SparseMatrixd &weightDiagonalMatrix,
const Vectors3d &translationsGuess,
bool &success,
int numOfIterations,
double epsilonIRLS);
static std::vector<TranslationMeasurement> getInversedTranslationMeasurements(
const std::vector<TranslationMeasurement> &relativeTranslations,
const std::vector<SE3> &absolutePoses);
public:
/**
* Compute IRLS solution for sparse linear system
*
* @param relativeTranslations contains given relative translations between poses
* @param absolutePoses contains precomputed SE3 poses where SO3 rotations are already fixed
* and translations are not currently utilized
* @param absoluteTranslations initial solution guess
* @param indexPoseFixed is the number of pose with zero coordinates
* @param successIRLS[out] is true if IRLS did converge
* @param numOfIterations max number of iterations
* @param epsilonWeightIRLS is a value w such that all weights in weight matrix are less than 1/w
* @returns IRLS solution
*/
static Vectors3d
recoverTranslationsIRLS(const std::vector<TranslationMeasurement> &relativeTranslations,
const std::vector<SE3> &absolutePoses,
const Vectors3d &absoluteTranslations,
int indexPoseFixed,
bool &successIRLS,
int numOfIterations = 5,
double epsilonWeightIRLS = 1e-6);
/**
* Compute L2-solution for sparse linear problem
*
* @param relativeTranslations contains given relative translations between poses
* @param absolutePoses contains precomputed SE3 poses where SO3 rotations are already fixed
* and translations are not currently utilized
*
* @returns L2 solution
*/
static Vectors3d
recoverTranslations(const std::vector<TranslationMeasurement> &relativeTranslations,
const std::vector<SE3> &absolutePoses,
int indexPoseFixed);
};
}
#endif
| 40.416667 | 115 | 0.599742 | [
"vector"
] |
ab2a0d440bc4cb65fbfca16d8d7985cf8d7bd1bb | 2,454 | c | C | src/symbolic_eval/whatif_algo.c | lordpretzel/gprom | 143b8e950a843ceac8585c31156ae174295a5315 | [
"Apache-2.0"
] | 5 | 2017-02-01T16:27:47.000Z | 2021-04-23T16:02:03.000Z | src/symbolic_eval/whatif_algo.c | lordpretzel/gprom | 143b8e950a843ceac8585c31156ae174295a5315 | [
"Apache-2.0"
] | 82 | 2016-11-30T15:57:48.000Z | 2022-03-04T21:35:03.000Z | src/symbolic_eval/whatif_algo.c | lordpretzel/gprom | 143b8e950a843ceac8585c31156ae174295a5315 | [
"Apache-2.0"
] | 4 | 2017-02-09T20:53:13.000Z | 2022-02-10T22:01:35.000Z | /*-----------------------------------------------------------------------------
*
* whatif_algo.c
*
*
* AUTHOR: lord_pretzel
*
*
*
*-----------------------------------------------------------------------------
*/
// only include cplex headers if the library is available
//TODO why this was included?
//#ifdef HAVE_LIBCPLEX
//#include <ilcplex/cplex.h>
//#endif
#include "common.h"
#include "log/logger.h"
#include "mem_manager/mem_mgr.h"
#include "model/node/nodetype.h"
#include "model/query_block/query_block.h"
#include "model/list/list.h"
#include "model/set/set.h"
#include "model/expression/expression.h"
#include "parser/parser.h"
#include "symbolic_eval/expr_to_constraint.h"
#include "symbolic_eval/whatif_algo.h"
#include "model/set/hashmap.h"
#include "model/relation/relation.h"
#include "model/query_operator/query_operator.h"
static List *cond = NIL; // global pointer to the list of conditions
static List *tables = NIL; // global pointer to the list of tables
static void initWhatif(Node *update, Node *wUpdate);
static void addTBToList(List *list, Node *n);
//initialize whatif algo and set the original update and the whatifquery
static void initWhatif(Node *update, Node *wUpdate) {
cond = appendToTailOfList(cond, update);
cond = appendToTailOfList(cond, wUpdate);
addTBToList(tables, update);
addTBToList(tables, wUpdate);
}
static void addTBToList(List *list, Node *n) {
switch (n->type) {
case T_Update:
list = appendToTailOfList(list, ((Update *) n)->updateTableName);
break;
case T_Delete:
list = appendToTailOfList(list, ((Delete *) n)->deleteTableName);
break;
case T_Insert:
list = appendToTailOfList(list, ((Insert *) n)->insertTableName);
break;
default:
break;
}
}
List *dependAlgo(List *exprs) {
Node *up = popHeadOfListP(exprs);
Node *wUp = popHeadOfListP(exprs);
initWhatif(up, wUp);
char *tbName = NULL;
FOREACH(Node,e,exprs)
{
switch (e->type) {
case T_Update:
tbName = ((Update *) e)->updateTableName;
break;
case T_Delete:
tbName = ((Delete *) e)->deleteTableName;
break;
case T_Insert:
tbName = ((Insert *) e)->insertTableName;
break;
default:
break;
}
if (searchListString(tables, tbName)) {
FOREACH(Node,u,cond)
{
if (exprToSat(u, TRUE, e, FALSE)) {
cond = appendToTailOfList(cond, e);
//if (!searchListString(tables, tbName))
//addTBToList(tables, e);
}
}
}
}
return cond;
}
| 23.371429 | 79 | 0.646292 | [
"model"
] |
ab38dd2facbe3713a08798553d86d8e758928326 | 3,771 | c | C | targets/TARGET_Silicon_Labs/TARGET_EFM32/us_ticker.c | pattyolanterns/mbed-os | f05af9a870580a0a81688e4d8f94cf72ca17a4d6 | [
"Apache-2.0"
] | 3,897 | 2015-09-04T13:42:23.000Z | 2022-03-30T16:53:07.000Z | targets/TARGET_Silicon_Labs/TARGET_EFM32/us_ticker.c | pattyolanterns/mbed-os | f05af9a870580a0a81688e4d8f94cf72ca17a4d6 | [
"Apache-2.0"
] | 13,030 | 2015-09-17T10:30:05.000Z | 2022-03-31T13:36:44.000Z | targets/TARGET_Silicon_Labs/TARGET_EFM32/us_ticker.c | pattyolanterns/mbed-os | f05af9a870580a0a81688e4d8f94cf72ca17a4d6 | [
"Apache-2.0"
] | 2,950 | 2015-09-08T19:07:05.000Z | 2022-03-31T13:37:23.000Z | /***************************************************************************//**
* @file us_ticker.c
*******************************************************************************
* @section License
* <b>(C) Copyright 2016 Silicon Labs, http://www.silabs.com</b>
*******************************************************************************
*
* 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.
*
******************************************************************************/
#include <stddef.h>
#include "us_ticker_api.h"
#include "device.h"
#include "mbed_assert.h"
#include "em_cmu.h"
#include "em_timer.h"
#include "clocking.h"
#define TICKER_FREQUENCY ((REFERENCE_FREQUENCY > 24000000) ? REFERENCE_FREQUENCY / 16 : REFERENCE_FREQUENCY / 8)
const ticker_info_t* us_ticker_get_info(void)
{
static const ticker_info_t info = {
TICKER_FREQUENCY,
16
};
return &info;
}
static bool us_ticker_inited = false; // Is ticker initialized yet
void us_ticker_init(void)
{
if (us_ticker_inited) {
/* calling init again should cancel current interrupt */
us_ticker_disable_interrupt();
return;
}
us_ticker_inited = true;
/* Enable clock for TIMERs */
CMU_ClockEnable(US_TICKER_TIMER_CLOCK, true);
if (REFERENCE_FREQUENCY > 24000000) {
US_TICKER_TIMER->CTRL = (US_TICKER_TIMER->CTRL & ~_TIMER_CTRL_PRESC_MASK) | (4 << _TIMER_CTRL_PRESC_SHIFT);
} else {
US_TICKER_TIMER->CTRL = (US_TICKER_TIMER->CTRL & ~_TIMER_CTRL_PRESC_MASK) | (3 << _TIMER_CTRL_PRESC_SHIFT);
}
/* Clear TIMER counter value */
TIMER_CounterSet(US_TICKER_TIMER, 0);
/* Start TIMER */
TIMER_Enable(US_TICKER_TIMER, true);
/* Select Compare Channel parameters */
TIMER_InitCC_TypeDef timerCCInit = TIMER_INITCC_DEFAULT;
timerCCInit.mode = timerCCModeCompare;
/* Configure Compare Channel 0 */
TIMER_InitCC(US_TICKER_TIMER, 0, &timerCCInit);
/* Enable interrupt vector in NVIC */
TIMER_IntClear(US_TICKER_TIMER, TIMER_IEN_CC0);
NVIC_SetVector(US_TICKER_TIMER_IRQ, (uint32_t) us_ticker_irq_handler);
NVIC_EnableIRQ(US_TICKER_TIMER_IRQ);
}
void us_ticker_free(void)
{
if (us_ticker_inited) {
us_ticker_disable_interrupt();
NVIC_DisableIRQ(US_TICKER_TIMER_IRQ);
TIMER_Enable(US_TICKER_TIMER, false);
CMU_ClockEnable(US_TICKER_TIMER_CLOCK, false);
us_ticker_inited = false;
}
}
uint32_t us_ticker_read()
{
if (!us_ticker_inited) {
us_ticker_init();
}
return US_TICKER_TIMER->CNT;
}
void us_ticker_set_interrupt(timestamp_t timestamp)
{
TIMER_IntDisable(US_TICKER_TIMER, TIMER_IEN_CC0);
TIMER_IntClear(US_TICKER_TIMER, TIMER_IEN_CC0);
TIMER_CompareSet(US_TICKER_TIMER, 0, timestamp);
TIMER_IntEnable(US_TICKER_TIMER, TIMER_IEN_CC0);
}
void us_ticker_fire_interrupt(void)
{
NVIC_SetPendingIRQ(US_TICKER_TIMER_IRQ);
}
void us_ticker_disable_interrupt(void)
{
/* Disable compare channel interrupts */
TIMER_IntDisable(US_TICKER_TIMER, TIMER_IEN_CC0);
}
void us_ticker_clear_interrupt(void)
{
/* Clear compare channel interrupts */
TIMER_IntClear(US_TICKER_TIMER, TIMER_IFC_CC0);
}
| 28.568182 | 115 | 0.65659 | [
"vector"
] |
ab38ec6003bec7b9cc5c1f9e16b1a0dc7b6db8d8 | 11,207 | h | C | pdetk/GerhardKueper2p.h | davidbrochart/daetk | 66b2a69d3f3df77f766d3d3eeb5c28d31587e278 | [
"MIT"
] | 9 | 2018-06-17T13:54:24.000Z | 2021-05-06T11:22:10.000Z | pdetk/GerhardKueper2p.h | davidbrochart/daetk | 66b2a69d3f3df77f766d3d3eeb5c28d31587e278 | [
"MIT"
] | 2 | 2019-02-13T18:50:05.000Z | 2019-10-19T00:13:35.000Z | pdetk/GerhardKueper2p.h | davidbrochart/daetk | 66b2a69d3f3df77f766d3d3eeb5c28d31587e278 | [
"MIT"
] | 4 | 2016-12-18T08:07:13.000Z | 2017-01-20T21:49:17.000Z | #ifndef GERHARD_KUEPER2P_H
#define GERHARD_KUEPER2P_H
#include "Definitions.h"
#include "Psk2p.h"
#include "Psk2pSpline.h"
#include "ParameterDatabase.h"
#include "PetscSecondOrderFd.h"
#include "VecOperators.h"
namespace Daetk
{
class GerhardKueper2p : public Psk2p
{
/***********************************************************************
implement a subset of the Gerhard and Kueper psk relations from
their WRR 2003 papers. I am interested initially only in getting a
reasonable estimate of nonwetting phase residual, rather than full
hysteresis.
To incorporate residual formation or "trapping," they use a linear
relationship between the reversal saturation (from drainage to
imbibition) and the extinctiction saturation.
S^X_W = (1-S^{X,\ast}_W)(S^'_S-1) + 1
S^'_W : current reversal point from drainage to imbibition which
I will define as the minimum wetting phase saturation
'seen' by a location up to the current time.
S^X_W : extinction saturation, wetting phase saturation when
nonwetting phase becomes immobile.
S^{X,\ast}_W : wetting phase saturation at maximum complete
nonwetting phase residual
To implement the residual "trapping," the only extra parameter
that is needed is S^{X,\ast}_W. I will attempt to lag the
calculation of S^'_W a time step, so that the constitutive
relations and derivatives are still essentially
Brooks-Corey. Specifically, I'll use
P_C = P_DS_e^{-1/lambda_d}, P_N >= P_D
S_e = (S_W-S_{W,r})/(S^X_W-S_{W,r}) where
S^{X,\ast}_W <= S^X_W <= 1.0 and
S^X_W = 0 for primary drainage (S^{min}_{W} = 1.0)
P_D = displacement pressure (entry pressure at S_W=1?)
\lambda_d = drainage pore-size distribution index
For secondary imbibition, the basic capillary pressure relationship is
P_C = P_T(\tilde{S}_e)^{-1/lambda_i}
for
\tilde{S}_e = (S_W - S^f_W)/(S^X_W-S^f_W)
where
P_T : terminal capillary pressure (at S^X_W).
lambda_i : imbibition pore-size distribution index
S^f_W : wetting phase saturation value that the imbition curve
approaches at infinite capillary pressure. For main
imbibition, S^f_W = S_r, and S^X_W = S^{X,\ast}_W. In
general, Gerhard and Kueper define it so that the
imbibition and drainage curves intersect at a reversal
point. This requires solving a local nonlinear problem
according to Gerhard and Kueper, but I think in some
cases at least you can solve it directly (see ghPSK.py).
Wetting phase relative permeability is the standard brooks corey
relationship
k_{r,W} = S_e^{(2+3\lambda_d)/\lambda_d}
S_e = (S_W-S^k_r)/(1.0 - S^k_r)
The nonwetting phase relative permeability is a little more
complicated. The full Gerhard and Kueper model for drainage is
k_{r,N} = k^{max}_{r,N}(1-\bar{S}^{\ast,d}_e)^{2\tau_d}
(1-\bar{S}^{\ast,d}_e^{(2+\lambda_d)/\lambda_d}
where
k^{max}_{r,N} : maximum nonwetting phase permeability
\tau_d : nonwetting phase relative tortuosity coefficient
\bar{S}^{\ast,d}_e : effective saturation for drainage
= (S_W-S^k_r)/[(S^M_W + \Delta S^{\ast,d}_W) - S^k_r]
for S^k_r <= S_W <= S^M_W
= 1 for S^M_W < S_W <= 1
\S^M_W : emergence saturation, wetting phase saturation at
which nonwetting phase flow begins (k_{r,N} >0).
Corresponds to entry pressure
\Delta S^{\ast,d}_W : jump fitting parameter to allow
nonwetting phase relative permeability to go from 0
to a finite positive value at the emergence
saturation, S^{M}_W
For secondary imbibition, Gerhard and Kueper use
k_{r,N} = k^'_{r,N}(1-\hat{S}^{\ast,i}_e)^{2\tau_i}
(1-\hat{S}^{\ast,i}_e^{(2+\lambda_i)/\lambda_i}
where
k^'_{r,N} : nonwetting phase relative permeability at reversal
point
\tau_i : nonwetting phase relative tortuosity coefficient for
imbibition
\hat{S}^{\ast,i}_e : effective saturation for imbibition
= (S_W-S^'_W)/[(S^X_W + \Delta S^{\ast,i}_W) - S^'_W]
for S^'_W <= S_W <= S^X_W
= 1 for S^X_W = S_W
S^'_W : wetting phase saturation at reversal point from
drainage to imbibition
\Delta S^{\ast,i}_W : jump fitting parameter to allow
nonwetting phase relative permeability to go from
a finite positive value at the extinction
saturation, S^{X}_W, to zero
Their are a number of new parameters that the model
introduces. Fortunately, there are defaults that reduce almost
everything back to Brooks Corey.
\tau_d = \tau_i = 1.0
\Delta S^{\ast,d}_W = \Delta S^{\ast,i}_W = 0
k^{max}_{r,N} = 1.0
S^M_W = 1.0
If I ignore hysteresis, I can drop the distinctions between
\lambda_i --- \lambda_d, and P_D -- P_T
----------------------------------------------------------------------
To summarize, the initial version of these psk relations will use
k_{r,W} = S_e^{(2+3\lambda)/\lambda}
S_e = (S_W-S^k_r)/(1.0 - S^k_r)
k_{r,N} = k^{max}_{r,N}(1-S^{\ast}_e)^{2}
(1-S^{\ast}_e^{(2+\lambda)/\lambda}
S^{\ast}_e = (S_W-S^k_r)/(S^{\ast}_W-S^k_r)
S^{\ast}_W : wetting phase saturation at which nonwetting phase
flow initiates or ceases. In other words, it
corresponds to the emergence saturation on drainage
and extinction saturation on imbibition
S^{\ast}_W = (1. - S^{X,\ast}_{W})(S^'_W - 1) + 1
S^{X,\ast}_W : wetting phase saturation at maximum complete
nonwetting phase residual
S^'_W = min_{a \in [0,t]} S_W
P_C = P_DS^{\ast}_e^{-1/lambda}, P_N >= P_D
Note that in general, Gerhard and Kueper include a different
residual saturation, S_r, for the capillary pressure relationship
S_e = (S_W - S_r)/(S^{\ast}_W - S_r)
However, I will use S^k_r := S_r
**********************************************************************/
public:
GerhardKueper2p();
virtual ~GerhardKueper2p();
void readParameters(ParameterDatabase& pd);
void readZones(ParameterDatabase& pd, Petsc::SecondOrderFd& node);
inline void setHeads(int node,real psiWIn, real psiNIn=0);
inline void setVFraction(const real& thetaWIn, int node);
inline void calculateDerivatives();
inline void calculateDerivativesVFraction();
virtual void setHeads(const Vec& psiW_vec, const Vec& psiN_vec);
virtual void setVFraction(const Vec& thetaW_vec);
virtual void calculateDerivativesHead(const Vec& psiW_vec, const Vec& psiN_vec);
virtual void calculateDerivativesVFraction(const Vec& thetaW_vec);
void millerSimilarScaling(Vec& delta);
friend class Psk2pSpline<GerhardKueper2p>;
//try to incorporate residual history
virtual void setThetaS (Vec &thetaSIn);
//set initial wetting phase volume fraction
virtual void setInitialConditions(const Vec& local_thw);
//set historical minimum volume fraction
virtual void updateHistory();
//mwf for debugging
//private:
public:
Vec global_psiD,global_lambda;
Vec psiD,lambda;
//keep track of different effective saturation scaling for wetting phase
real sBar_krW;
Vec global_thetaWmaxResidual;
Vec thetaWmaxResidual;
//mwf add for residual calculation
// leave thetaS as maximum available saturation corresponding to S_W=1
Vec thetaSeff,thetaSReff;
//mwf saturation history
Vec thetaWminSoFar, thetaWsave; //start out at thetaS
};
inline void GerhardKueper2p::setHeads(int node,real psiWIn, real psiNIn)
{
psiC = psiNIn - psiWIn;
i = node;
sBar = pow(psiC/psiD[i],-lambda[i]);
thetaW = thetaSReff[i]*sBar + thetaR[i];
DsBar_DpC = -(lambda[i]/psiD[i])*pow(psiC/psiD[i],-lambda[i]-1);
DthetaW_DpC = thetaSReff[i] * DsBar_DpC;
//scale relative permeability for wetting phase differently
sBar_krW = (thetaW-thetaR[i])/thetaSR[i];
sBar_krW = std::max(0.0,std::min(sBar_krW,1.0));
krW = pow(sBar_krW,(2.+3.*lambda[i])/lambda[i]);
KW = KWs[i]*krW;
krN = (1.-sBar)*(1-sBar)*(1.-pow(sBar,(2.0 + lambda[i])/lambda[i]));
KN = KWs[i]*muW_by_muN*krN;
if(psiC < psiD[i])
{
sBar = 1.0;
sBar_krW = 1.0;
thetaW = thetaSeff[i];
DsBar_DpC = 0.0;
DthetaW_DpC = 0.0;
krW = 1.0;
KW = KWs[i];
krN = 0.0;
KN = 0.0;
}
//keep most recent thetaW?
thetaWsave[i] = thetaW;
}
inline void GerhardKueper2p::setVFraction(const real& thetaWIn, int node)
{
i = node;
sBar = (thetaWIn - thetaR[i])/thetaSReff[i];
sBar= std::min(std::max(sBar,0.0),1.0);
thetaW = thetaSReff[i]*sBar + thetaR[i];
psiC = psiD[i]*pow(sBar,-1./lambda[i]);
//std::cout<<psiC<<'\t'<<psiD[i]<<'\t'<<lambda[i]<<'\t'<<sBar<<'\t'<<i<<std::endl;
DsBar_DpC = -(lambda[i]/psiD[i])*pow(psiC/psiD[i],-lambda[i]-1.);
DthetaW_DpC = thetaSReff[i] * DsBar_DpC;
//use different scaling for wetting phase relative perm
sBar_krW = (thetaWIn - thetaR[i])/thetaSR[i];
sBar_krW = std::max(0.0,std::min(sBar_krW,1.0));
//what about DsBar_DpC?
krW = pow(sBar_krW,(2.+3.*lambda[i])/lambda[i]);
KW = KWs[i]*krW;
krN = (1.0-sBar)*(1.0-sBar)*(1.0-pow(sBar,(2.+lambda[i])/lambda[i]));
KN = KWs[i]*muW_by_muN*krN;
if (psiC < psiD[i])
{
DsBar_DpC = 0.0;
DthetaW_DpC = 0.0;
krW = 1.0;
KW = KWs[i];
krN = 0.0;
KN = 0.0;
}
//keep most recent thetaW?
thetaWsave[i] = thetaW;
}
inline void GerhardKueper2p::calculateDerivatives()
{
//probably not right
//mwf add some decimals
DDsBar_DDpC = -(lambda[i]/psiD[i])*((-lambda[i]-1.)/psiD[i])*pow(psiC/psiD[i],-lambda[i]-2.);
DDthetaW_DDpC = thetaSReff[i]*DDsBar_DDpC;
//mwf use different scaling for wetting phase relative perm
real dthetaSREffdthetaSR = thetaSReff[i]/thetaSR[i];
//real dthetaSREffdthetaSR = 1.0;
DkrW_DpC = ((2.+3.*lambda[i])/lambda[i])*pow(sBar_krW,(2.+3.*lambda[i])/lambda[i]-1.)*
DsBar_DpC*dthetaSREffdthetaSR;//include scaling to get this to be correct
DKW_DpC = KWs[i]*DkrW_DpC;
DkrN_DpC =-2.0*(1.-sBar)*DsBar_DpC*(1.-pow(sBar,(2.+lambda[i])/lambda[i]))
-(1.-sBar)*(1.-sBar)*pow(sBar,2./lambda[i])*(2.+lambda[i])/lambda[i]
*DsBar_DpC;
DKN_DpC = KWs[i]*muW_by_muN*DkrN_DpC;
if (psiC < psiD[i])
{
DDsBar_DDpC = 0.0;
DDthetaW_DDpC = 0.0;
DkrW_DpC = 0.0;
DKW_DpC = 0.0;
DkrN_DpC = 0.0;
DKN_DpC = 0.0;
}
//mwf debug
//std::cout<<"BC calcDerivs psiC= "<<psiC<<" psiD["<<i<<"]= "<<psiD[i]
// <<" DkrN_DpC= "<<DkrN_DpC<<std::endl;
}
inline void GerhardKueper2p::calculateDerivativesVFraction()
{
calculateDerivatives();
}
}//Daetk
#endif
| 32.390173 | 95 | 0.611314 | [
"model"
] |
ab43c367cb9976f4207071562b3c94bdd8184b31 | 2,029 | h | C | src/phyx-1.01/src/rate_model.h | jlanga/smsk_selection | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 4 | 2021-07-18T05:20:20.000Z | 2022-01-03T10:22:33.000Z | src/phyx-1.01/src/rate_model.h | jlanga/smsk_selection | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 1 | 2017-08-21T07:26:13.000Z | 2018-11-08T13:59:48.000Z | src/phyx-1.01/src/rate_model.h | jlanga/smsk_orthofinder | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 2 | 2021-07-18T05:20:26.000Z | 2022-03-31T18:23:31.000Z | #ifndef _RATE_MODEL_H_
#define _RATE_MODEL_H_
#include <map>
using namespace std;
#include <armadillo>
using namespace arma;
class RateModel{
private:
mat Q;
vector<mat> Qs;
vector<string> labels;
vector< vector<double> > Q_mask;
bool sameQ;
cx_mat lasteigval;
cx_mat lasteigvec;
cx_mat eigval;
cx_mat eigvec;
mat lasteigval_simple;
mat lasteigvec_simple;
mat eigval_simple;
mat eigvec_simple;
bool lastImag;
int fortran_iexph;
double * fortran_wsp;
int fortran_m;
public:
RateModel(int);
/*
storing once optimization has occurred
map of bl and p matrix
map<branch length,p matrix>
*/
int selection_model; //0,2 = 2a
int nstates;
map<double, cx_mat> stored_p_matrices;
bool neg_p;
void set_n_qs(int number);
void set_Q_which(mat & inQ, int which);
void set_Q(mat & inQ);
void set_Q_diag();
void set_Q_cell(int,int,double);
void setup_Q();
void setup_Q(vector<vector<double> > & inQ);
void setup_Q(mat & inQ);
mat & get_Q();
void set_sameQ(bool);
cx_mat setup_P(double,bool);
void setup_P_simple(mat & p,double,bool);
void setup_fortran_P_whichQ(int which, mat & P, double t);
void setup_fortran_P(mat & P, double t, bool store_p_matrices);
/*
* get things from stmap
*/
//this should be used for getting the eigenvectors and eigenvalues
bool get_eigenvec_eigenval_from_Q(cx_mat * eigenvalues, cx_mat * eigenvectors);
void get_eigenvec_eigenval_from_Q_simple(mat * eigenvalues, mat * eigenvectors);
};
void update_simple_goldman_yang_q(mat * inm, double K, double w, mat & bigpibf,mat &bigpiK, mat & bigpiw);
bool test_transition(char a, char b);
void generate_bigpibf_K_w(mat * bf, mat * K, mat * w,map<string, string> & codon_dict, map<string, vector<int> > & codon_index, vector<string> & codon_list);
void convert_matrix_to_single_row_for_fortran(mat & inmatrix, double t, double * H);
#endif /* _RATE_MODEL_H_ */
| 28.577465 | 157 | 0.687531 | [
"vector"
] |
ab55a09a5c11d6fd6b3554a47035ef1b42db42e4 | 3,005 | c | C | MyOS_1/Interrupts/PIC.c | coderTrevor/MyOS | 35bed9c44bf164bcaec1801d7253e88164829d4c | [
"MIT"
] | 8 | 2020-07-09T20:36:02.000Z | 2022-03-22T05:48:51.000Z | MyOS_1/Interrupts/PIC.c | coderTrevor/MyOS | 35bed9c44bf164bcaec1801d7253e88164829d4c | [
"MIT"
] | null | null | null | MyOS_1/Interrupts/PIC.c | coderTrevor/MyOS | 35bed9c44bf164bcaec1801d7253e88164829d4c | [
"MIT"
] | 1 | 2021-08-28T06:58:51.000Z | 2021-08-28T06:58:51.000Z | #include "Interrupts.h"
#include "PIC.h"
#include "../System_Specific.h"
#include <stdint.h>
void IRQ_Enable_Line(unsigned char IRQline)
{
uint16_t port;
uint8_t value;
if (IRQline < 8)
{
port = PIC1_DATA;
}
else
{
port = PIC2_DATA;
IRQline -= 8;
// Make sure IRQ2 of PIC1 is enabled or we'll never receive the interrupt from PIC2
value = inb(PIC1_DATA) & ~(1 << 2);
outb(PIC1_DATA, value);
io_wait();
}
value = inb(port) & ~(1 << IRQline);
outb(port, value);
}
void IRQ_Disable_Line(unsigned char IRQline)
{
uint16_t port;
uint8_t value;
if (IRQline < 8)
{
port = PIC1_DATA;
}
else
{
port = PIC2_DATA;
IRQline -= 8;
}
value = inb(port) | (1 << IRQline);
outb(port, value);
}
void PIC_sendEOI(unsigned char irq)
{
if (irq >= 8 + HARDWARE_INTERRUPTS_BASE)
outb(PIC2_COMMAND, PIC_EOI);
outb(PIC1_COMMAND, PIC_EOI);
}
/*
Reinitialize the PIC controllers, giving them specified vector offsets
rather than 8h and 70h, as configured by default
arguments:
offset1 - vector offset for master PIC
vectors on the master become offset1..offset1+7
offset2 - same for slave PIC: offset2..offset2+7
*/
void PIC_remap(unsigned char offset1, unsigned char offset2)
{
unsigned char a1, a2;
a1 = inb(PIC1_DATA); // save masks
a2 = inb(PIC2_DATA);
outb(PIC1_COMMAND, ICW1_INIT | ICW1_ICW4); // starts the initialization sequence (in cascade mode)
io_wait();
outb(PIC2_COMMAND, ICW1_INIT | ICW1_ICW4);
io_wait();
outb((unsigned char)PIC1_DATA, offset1); // ICW2: Master PIC vector offset
io_wait();
outb(PIC2_DATA, offset2); // ICW2: Slave PIC vector offset
io_wait();
outb(PIC1_DATA, 4); // ICW3: tell Master PIC that there is a slave PIC at IRQ2 (0000 0100)
io_wait();
outb(PIC2_DATA, 2); // ICW3: tell Slave PIC its cascade identity (0000 0010)
io_wait();
outb(PIC1_DATA, ICW4_8086);
io_wait();
outb(PIC2_DATA, ICW4_8086);
io_wait();
outb(PIC1_DATA, a1); // restore saved masks.
outb(PIC2_DATA, a2);
}
/* Helper func */
inline uint16_t pic_get_irq_reg(unsigned char ocw3)
{
/* OCW3 to PIC CMD to get the register values. PIC2 is chained, and
* represents IRQs 8-15. PIC1 is IRQs 0-7, with 2 being the chain */
outb(PIC1_COMMAND, ocw3);
outb(PIC2_COMMAND, ocw3);
return (inb(PIC2_COMMAND) << 8) | inb(PIC1_COMMAND);
}
/* Returns the combined value of the cascaded PICs irq request register */
uint16_t pic_get_irr(void)
{
return pic_get_irq_reg(PIC_READ_IRR);
}
/* Returns the combined value of the cascaded PICs in-service register */
uint16_t pic_get_isr(void)
{
return pic_get_irq_reg(PIC_READ_ISR);
} | 26.830357 | 117 | 0.607321 | [
"vector"
] |
ab6253bc03b3bcbbe0ef43da7e94c0723b552b34 | 4,025 | h | C | libs/qCC_io/PDMS/PdmsParser.h | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | null | null | null | libs/qCC_io/PDMS/PdmsParser.h | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | null | null | null | libs/qCC_io/PDMS/PdmsParser.h | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | 1 | 2019-02-03T12:19:42.000Z | 2019-02-03T12:19:42.000Z | //##########################################################################
//# #
//# CLOUDCOMPARE #
//# #
//# This program is free software; you can redistribute it and/or modify #
//# it under the terms of the GNU General Public License as published by #
//# the Free Software Foundation; version 2 or later of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI) #
//# #
//##########################################################################
#ifndef PDMS_PARSER_HEADER
#define PDMS_PARSER_HEADER
#include "PdmsTools.h"
//system
#include <map>
#include <string>
using namespace PdmsTools;
//! PDMS Lexer
/** PDMS sessions are made to provide an input stream to the parser (file, keyboard, pipe, ...)
**/
class PdmsLexer
{
public:
PdmsLexer();
virtual ~PdmsLexer() {}
virtual bool initializeSession();
bool gotoNextToken();
void finish() {stop = true;}
virtual void closeSession(bool destroyLoadedObject=false);
PointCoordinateType valueFromBuffer();
const char* nameFromBuffer() const;
virtual void printWarning(const char* str) = 0;
Token getCurrentToken() const {return currentToken;}
PdmsObjects::GenericItem* getLoadedObject() const {return loadedObject;}
const char* getBufferContent() const {return tokenBuffer;}
void setLoadedObject(PdmsObjects::GenericItem *o) {loadedObject = o;}
protected:
/** \warning Never pass a 'constant initializer' by reference
**/
static const int c_max_buff_size = 2048;
PdmsObjects::GenericItem *loadedObject;
Token currentToken;
char tokenBuffer[c_max_buff_size];
char nextBuffer[c_max_buff_size];
std::map<std::string, Token> dictionary;
bool stop;
char metaGroupMask;
void pushIntoDictionary(const char *str, Token token, int minSize=0);
virtual void parseCurrentToken();
virtual void skipComment() = 0;
virtual void skipHandleCommand() = 0;
virtual bool moveForward();
};
//Pdms file session
class PdmsFileSession : public PdmsLexer
{
protected:
std::string m_filename;
int m_currentLine;
bool m_eol;
bool m_eof;
FILE* m_file;
public:
PdmsFileSession(const std::string &filename);
virtual ~PdmsFileSession() {closeSession();}
virtual bool initializeSession() override;
virtual void closeSession(bool destroyLoadedObject=false) override;
virtual void printWarning(const char* str) override;
protected:
virtual void parseCurrentToken() override;
virtual bool moveForward() override;
virtual void skipComment() override;
virtual void skipHandleCommand() override;
};
//PDMS Parser
/** Use this parser the following way:
1- create any Pdms session
2- link parser with the session
3- parse the current session content. if the session content changes, you can parse it as many
times as you wish (the loaded object is overwritten each time)
4- get the result (either in session or in parser)
**/
class PdmsParser
{
public:
//! Default constructor
PdmsParser();
~PdmsParser();
void reset();
void linkWithSession(PdmsLexer *s);
bool parseSessionContent();
PdmsObjects::GenericItem *getLoadedObject(bool forgetIt = true);
protected:
bool processCurrentToken();
PdmsLexer *session;
PdmsCommands::Command *currentCommand;
PdmsObjects::GenericItem *currentItem;
PdmsObjects::GenericItem *root;
};
#endif //PDMS_PARSER_HEADER
| 31.20155 | 95 | 0.629068 | [
"object"
] |
ab675a911888e0c4e7ed260c844d30ff7e544415 | 23,355 | h | C | orly/client/program/translate_expr.h | orlyatomics/orly | d413f999f51a8e553832dab4e3baa7ca68928840 | [
"Apache-2.0"
] | 69 | 2015-01-06T05:12:57.000Z | 2021-11-06T20:34:10.000Z | orly/client/program/translate_expr.h | waderly/orly | 9d7660ea9d07591f8cc6b1b92d8e6c3b8b78eeee | [
"Apache-2.0"
] | 5 | 2015-07-09T02:21:50.000Z | 2021-08-13T11:10:26.000Z | orly/client/program/translate_expr.h | waderly/orly | 9d7660ea9d07591f8cc6b1b92d8e6c3b8b78eeee | [
"Apache-2.0"
] | 15 | 2015-01-23T13:34:05.000Z | 2020-06-15T16:46:50.000Z | /* <orly/client/program/translate_expr.h>
TODO
Copyright 2010-2014 OrlyAtomics, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <cassert>
#include <cstdint>
#include <string>
#include <vector>
#include <orly/atom/kit2.h>
#include <orly/client/program/program.program.cst.h>
#include <orly/sabot/state.h>
#include <orly/sabot/type.h>
namespace Orly {
namespace Client {
namespace Program {
/* Convert a Package Name expression into a vector of strings and a version number */
void TranslatePackage(std::vector<std::string> &package_name, uint64_t &version_number, const TPackageName *expr);
/* Convert a Name List expression into a vector of string. */
void TranslatePathName(std::vector<std::string> &path_name, const TNameList *expr);
/* TODO */
Sabot::Type::TAny *NewTypeSabot(const TType *type, void *alloc);
/* TODO */
Sabot::Type::TAny *NewTypeSabot(const TExpr *expr, void *alloc);
/* TODO */
Sabot::State::TAny *NewStateSabot(const TExpr *expr, void *alloc);
/* TODO */
Atom::TCore *TranslateExpr(Atom::TCore::TExtensibleArena *arena, void *core_alloc, const TExpr *expr);
namespace Type {
/* TODO */
template <typename TBase>
class TUnaryExpr final
: public TBase {
public:
/* TODO */
using TBasePin = typename TBase::TPin;
/* TODO */
class TPin final
: public TBasePin {
public:
/* TODO */
TPin(const TUnaryExpr *unary)
: UnaryExpr(unary) {
assert(unary);
}
/* TODO */
virtual Sabot::Type::TAny *NewElem(void *type_alloc) const override {
return NewTypeSabot(UnaryExpr->Expr, type_alloc);
}
private:
/* TODO */
const TUnaryExpr *UnaryExpr;
}; // TUnaryExpr<TCst, TBase>::TPin
/* TODO */
TUnaryExpr(const TExpr *expr)
: Expr(expr) {
assert(expr);
}
/* Pin the array into memory. */
virtual TBasePin *Pin(void *pin_alloc) const override {
return new (pin_alloc) TPin(this);
}
private:
/* TODO */
const TExpr *Expr;
}; // Type::TUnaryExpr<TBase>
/* TODO */
template <typename TBase>
class TUnaryType final
: public TBase {
public:
/* TODO */
using TBasePin = typename TBase::TPin;
/* TODO */
class TPin final
: public TBasePin {
public:
/* TODO */
TPin(const TUnaryType *unary)
: UnaryType(unary) {
assert(unary);
}
/* TODO */
virtual Sabot::Type::TAny *NewElem(void *type_alloc) const override {
return NewTypeSabot(UnaryType->Type, type_alloc);
}
private:
/* TODO */
const TUnaryType *UnaryType;
}; // TUnaryType<TCst, TBase>::TPin
/* TODO */
TUnaryType(const TType *type)
: Type(type) {
assert(type);
}
/* Pin the array into memory. */
virtual TBasePin *Pin(void *pin_alloc) const override {
return new (pin_alloc) TPin(this);
}
private:
/* TODO */
const TType *Type;
}; // Type::TUnaryType<TBase>
/* TODO */
template <typename TBase>
class TBinaryExpr final
: public TBase {
public:
/* TODO */
using TBasePin = typename TBase::TPin;
/* TODO */
class TPin final
: public TBasePin {
public:
/* TODO */
TPin(const TBinaryExpr *binary)
: BinaryExpr(binary) {
assert(binary);
}
/* TODO */
virtual Sabot::Type::TAny *NewLhs(void *type_alloc) const override {
return NewTypeSabot(BinaryExpr->Lhs, type_alloc);
}
/* TODO */
virtual Sabot::Type::TAny *NewRhs(void *type_alloc) const override {
return NewTypeSabot(BinaryExpr->Rhs, type_alloc);
}
private:
/* TODO */
const TBinaryExpr *BinaryExpr;
}; // TBinaryExpr<TCst, TBase>::TPin
/* TODO */
TBinaryExpr(const TExpr *lhs, const TExpr *rhs)
: Lhs(lhs), Rhs(rhs) {
assert(lhs);
assert(rhs);
}
/* Pin the array into memory. */
virtual TBasePin *Pin(void *pin_alloc) const override {
return new (pin_alloc) TPin(this);
}
private:
/* TODO */
const TExpr *Lhs, *Rhs;
}; // Type::TBinaryExpr<TBase>
/* TODO */
template <typename TBase>
class TBinaryType final
: public TBase {
public:
/* TODO */
using TBasePin = typename TBase::TPin;
/* TODO */
class TPin final
: public TBasePin {
public:
/* TODO */
TPin(const TBinaryType *binary)
: BinaryType(binary) {
assert(binary);
}
/* TODO */
virtual Sabot::Type::TAny *NewLhs(void *type_alloc) const override {
return NewTypeSabot(BinaryType->Lhs, type_alloc);
}
/* TODO */
virtual Sabot::Type::TAny *NewRhs(void *type_alloc) const override {
return NewTypeSabot(BinaryType->Rhs, type_alloc);
}
private:
/* TODO */
const TBinaryType *BinaryType;
}; // TBinaryType<TCst, TBase>::TPin
/* TODO */
TBinaryType(const TType *lhs, const TType *rhs)
: Lhs(lhs), Rhs(rhs) {
assert(lhs);
assert(rhs);
}
/* Pin the array into memory. */
virtual TBasePin *Pin(void *pin_alloc) const override {
return new (pin_alloc) TPin(this);
}
private:
/* TODO */
const TType *Lhs, *Rhs;
}; // Type::TBinaryType<TBase>
/* TODO */
class TRecordType final
: public Sabot::Type::TRecord {
public:
/* TODO */
using TPinBase = Sabot::Type::TRecord::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TRecordType *record_type);
/* TODO */
virtual Sabot::Type::TAny *NewElem(size_t elem_idx, std::string &name, void *type_alloc) const override;
/* TODO */
virtual Sabot::Type::TAny *NewElem(
size_t elem_idx, void *&out_field_name_sabot_state, void *field_name_state_alloc, void *type_alloc) const override;
/* TODO */
virtual Sabot::Type::TAny *NewElem(size_t elem_idx, void *type_alloc) const override;
private:
/* TODO */
const TRecordType *RecordType;
}; // TRecordType::TPin
/* TODO */
TRecordType(const TObjType *type);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
std::vector<const TObjTypeMember *> Members;
}; // Type::TRecordType
/* TODO */
class TRecordExpr final
: public Sabot::Type::TRecord {
public:
/* TODO */
using TPinBase = Sabot::Type::TRecord::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TRecordExpr *record_expr);
/* TODO */
virtual Sabot::Type::TAny *NewElem(size_t elem_idx, std::string &name, void *type_alloc) const override;
/* TODO */
virtual Sabot::Type::TAny *NewElem(
size_t elem_idx, void *&out_field_name_sabot_state, void *field_name_state_alloc, void *type_alloc) const override;
/* TODO */
virtual Sabot::Type::TAny *NewElem(size_t elem_idx, void *type_alloc) const override;
private:
/* TODO */
const TRecordExpr *RecordExpr;
}; // TRecordExpr::TPin
/* TODO */
TRecordExpr(const TObjExpr *expr);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
std::vector<const TObjMember *> Members;
}; // Type::TRecordExpr
/* TODO */
class TTupleType final
: public Sabot::Type::TTuple {
public:
/* TODO */
using TPinBase = Sabot::Type::TTuple::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TTupleType *tuple_type);
/* TODO */
virtual Sabot::Type::TAny *NewElem(size_t elem_idx, void *type_alloc) const override;
private:
/* TODO */
const TTupleType *TupleType;
}; // TTupleType::TPin
/* TODO */
TTupleType(const TAddrType *type);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
std::vector<const TAddrTypeMember *> Members;
}; // Type::TTupleType
/* TODO */
class TTupleExpr final
: public Sabot::Type::TTuple {
public:
/* TODO */
using TPinBase = Sabot::Type::TTuple::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TTupleExpr *tuple_expr);
/* TODO */
virtual Sabot::Type::TAny *NewElem(size_t elem_idx, void *type_alloc) const override;
private:
/* TODO */
const TTupleExpr *TupleExpr;
}; // TTupleExpr::TPin
/* TODO */
TTupleExpr(const TAddrExpr *expr);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
std::vector<const TAddrMember *> Members;
}; // Type::TTupleExpr
} // Type
namespace State {
/* TODO */
class TBool final
: public Sabot::State::TBool {
public:
/* TODO */
TBool(const TTrueExpr *);
/* TODO */
TBool(const TFalseExpr *);
/* TODO */
virtual const bool &Get() const override;
/* TODO */
virtual Sabot::Type::TBool *GetBoolType(void *type_alloc) const override;
private:
/* TODO */
bool Val;
}; // State::TBool
/* TODO */
class TInt final
: public Sabot::State::TInt64 {
public:
/* TODO */
TInt(const TIntExpr *expr);
/* TODO */
virtual const int64_t &Get() const override;
/* TODO */
virtual Sabot::Type::TInt64 *GetInt64Type(void *type_alloc) const override;
private:
/* TODO */
int64_t Val;
}; // State::TInt
/* TODO */
class TReal final
: public Sabot::State::TDouble {
public:
/* TODO */
TReal(const TRealExpr *expr);
/* TODO */
virtual const double &Get() const override;
/* TODO */
virtual Sabot::Type::TDouble *GetDoubleType(void *type_alloc) const override;
private:
/* TODO */
double Val;
}; // State::TReal
/* TODO */
class TId final
: public Sabot::State::TUuid {
public:
/* TODO */
TId(const TIdExpr *expr);
/* TODO */
virtual const Base::TUuid &Get() const override;
/* TODO */
virtual Sabot::Type::TUuid *GetUuidType(void *type_alloc) const override;
private:
/* TODO */
Base::TUuid Val;
}; // State::TId
/* TODO */
class TTimePnt final
: public Sabot::State::TTimePoint {
public:
/* TODO */
TTimePnt(const TTimePntExpr *expr);
/* TODO */
virtual const Sabot::TStdTimePoint &Get() const override;
/* TODO */
virtual Sabot::Type::TTimePoint *GetTimePointType(void *type_alloc) const override;
private:
/* TODO */
Sabot::TStdTimePoint Val;
}; // State::TTimePnt
/* TODO */
class TTimeDiff final
: public Sabot::State::TDuration {
public:
/* TODO */
TTimeDiff(const TTimeDiffExpr *expr);
/* TODO */
virtual const Sabot::TStdDuration &Get() const override;
/* TODO */
virtual Sabot::Type::TDuration *GetDurationType(void *type_alloc) const override;
private:
/* TODO */
Sabot::TStdDuration Val;
}; // State::TTimeDiff
/* TODO */
class TStr final
: public Sabot::State::TStr {
public:
/* TODO */
using TPinBase = Sabot::State::TStr::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TStr *str);
}; // TStr::TPin
/* TODO */
TStr(const TSingleQuotedStrExpr *expr);
/* TODO */
TStr(const TDoubleQuotedStrExpr *expr);
/* TODO */
TStr(const TSingleQuotedRawStrExpr *expr);
/* TODO */
TStr(const TDoubleQuotedRawStrExpr *expr);
/* TODO */
virtual size_t GetSize() const override;
/* TODO */
virtual Sabot::Type::TStr *GetStrType(void *type_alloc) const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
std::string Val;
}; // State::TStr
/* TODO */
class TOpt final
: public Sabot::State::TOpt {
public:
/* TODO */
using TPinBase = Sabot::State::TOpt::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TOpt *opt);
private:
/* TODO */
virtual Sabot::State::TAny *NewElemInRange(size_t elem_idx, void *state_alloc) const override;
/* TODO */
const TExpr *Expr;
}; // TOpt::TPin
/* TODO */
TOpt(const TOptExpr *expr);
/* TODO */
TOpt(const TUnknownExpr *expr);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual Sabot::Type::TOpt *GetOptType(void *type_alloc) const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
const TExpr *Expr;
/* TODO */
const TType *Type;
}; // State::TOpt
/* TODO */
class TDesc final
: public Sabot::State::TDesc {
public:
/* TODO */
using TPinBase = Sabot::State::TDesc::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TDesc *set);
private:
/* TODO */
virtual Sabot::State::TAny *NewElemInRange(size_t elem_idx, void *state_alloc) const override;
/* TODO */
const TDesc *Desc;
}; // TDesc::TPin
/* TODO */
TDesc(const TExpr *expr);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual Sabot::Type::TDesc *GetDescType(void *type_alloc) const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
const TExpr *Expr;
}; // State::TDesc
/* TODO */
class TSet final
: public Sabot::State::TSet {
public:
/* TODO */
using TPinBase = Sabot::State::TSet::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TSet *set);
private:
/* TODO */
virtual Sabot::State::TAny *NewElemInRange(size_t elem_idx, void *state_alloc) const override;
/* TODO */
const TSet *Set;
}; // TSet::TPin
/* TODO */
TSet(const TSetExpr *expr);
/* TODO */
TSet(const TSetType *type);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual Sabot::Type::TSet *GetSetType(void *type_alloc) const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
std::vector<const TExpr *> Members;
/* TODO */
const TType *Type;
}; // State::TSet
/* TODO */
class TList final
: public Sabot::State::TVector {
public:
/* TODO */
using TPinBase = Sabot::State::TVector::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TList *list);
private:
/* TODO */
virtual Sabot::State::TAny *NewElemInRange(size_t elem_idx, void *state_alloc) const override;
/* TODO */
const TList *List;
}; // TList::TPin
/* TODO */
TList(const TListExpr *expr);
/* TODO */
TList(const TListType *type);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual Sabot::Type::TVector *GetVectorType(void *type_alloc) const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
std::vector<const TExpr *> Members;
/* TODO */
const TType *Type;
}; // State::TList
/* TODO */
class TDict final
: public Sabot::State::TMap {
public:
/* TODO */
using TPinBase = Sabot::State::TMap::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TDict *list);
private:
/* TODO */
virtual Sabot::State::TAny *NewLhsInRange(size_t elem_idx, void *state_alloc) const override;
/* TODO */
virtual Sabot::State::TAny *NewRhsInRange(size_t elem_idx, void *state_alloc) const override;
/* TODO */
const TDict *Dict;
}; // TDict::TPin
/* TODO */
TDict(const TDictExpr *expr);
/* TODO */
TDict(const TDictType *type);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual Sabot::Type::TMap *GetMapType(void *type_alloc) const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
std::vector<const TDictMember *> Members;
/* TODO */
const TType *LhsType, *RhsType;
}; // State::TDict
/* TODO */
class TObj final
: public Sabot::State::TRecord {
public:
/* TODO */
using TPinBase = Sabot::State::TRecord::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TObj *obj);
private:
/* TODO */
virtual Sabot::State::TAny *NewElemInRange(size_t elem_idx, void *state_alloc) const override;
/* TODO */
const TObj *Obj;
}; // TObj::TPin
/* TODO */
TObj(const TObjExpr *expr);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual Sabot::Type::TRecord *GetRecordType(void *type_alloc) const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
const TObjExpr *Expr;
/* TODO */
std::vector<const TObjMember *> Members;
}; // State::TObj
/* TODO */
class TAddr final
: public Sabot::State::TTuple {
public:
/* TODO */
using TPinBase = Sabot::State::TTuple::TPin;
/* TODO */
class TPin final
: public TPinBase {
public:
/* TODO */
TPin(const TAddr *addr);
private:
/* TODO */
virtual Sabot::State::TAny *NewElemInRange(size_t elem_idx, void *state_alloc) const override;
/* TODO */
const TAddr *Addr;
}; // TAddr::TPin
/* TODO */
TAddr(const TAddrExpr *expr);
/* TODO */
virtual size_t GetElemCount() const override;
/* TODO */
virtual Sabot::Type::TTuple *GetTupleType(void *type_alloc) const override;
/* TODO */
virtual TPinBase *Pin(void *alloc) const override;
private:
/* TODO */
const TAddrExpr *Expr;
/* TODO */
std::vector<const TAddrMember *> Members;
}; // State::TAddr
} // State
} // Program
} // Client
} // Orly
| 23.71066 | 131 | 0.486277 | [
"vector"
] |
ab6d7b4e0666c5d8553fcc72befc165c793dd733 | 922 | h | C | nnet/Client/ClientsManager.h | b4rtaz/nnet-distributed-conv-net | 771a59d1c61433d4e5de2b3605f549479df816a8 | [
"MIT"
] | null | null | null | nnet/Client/ClientsManager.h | b4rtaz/nnet-distributed-conv-net | 771a59d1c61433d4e5de2b3605f549479df816a8 | [
"MIT"
] | null | null | null | nnet/Client/ClientsManager.h | b4rtaz/nnet-distributed-conv-net | 771a59d1c61433d4e5de2b3605f549479df816a8 | [
"MIT"
] | null | null | null | #pragma once
#include "../Transfer/TransferClient.h"
#include "../Transfer/TransferPacket.h"
#include <Windows.h>
#include <vector>
using namespace std;
using namespace Transfer;
namespace Client {
typedef void (*ClientInfoDataHandler)(void* handlerUserParam, int clientIndex, TransferPacket *header, TransferClient *client);
class ClientInfo {
public:
TransferClient *client;
HANDLE thread;
HANDLE jobLock;
HANDLE doneLock;
int index;
bool error;
char action;
int dataCountPerClient;
int *dataLengths;
char **datas;
void *handlerUserParam;
ClientInfoDataHandler handler;
};
class ClientsManager {
private:
vector<ClientInfo*> _clients;
public:
~ClientsManager();
void AddClient(TransferClient *client);
int GetClientCount();
void SendData(char action, int dataCountPerClient, int *dataLengths, char **datas, void *handlerUserParam, ClientInfoDataHandler handler);
};
}
| 20.488889 | 140 | 0.749458 | [
"vector"
] |
ab7fa3805366f6da86661681bbfe8ee2b10723da | 2,065 | h | C | src/DepthQueue.h | flipcoder/bitplanes | 6d37b261929bac815cd97b09b00baa60dc55b950 | [
"MIT"
] | 5 | 2015-08-14T15:27:35.000Z | 2019-07-08T07:06:22.000Z | src/DepthQueue.h | flipcoder/bitplanes | 6d37b261929bac815cd97b09b00baa60dc55b950 | [
"MIT"
] | null | null | null | src/DepthQueue.h | flipcoder/bitplanes | 6d37b261929bac815cd97b09b00baa60dc55b950 | [
"MIT"
] | null | null | null | #ifndef _DEPTHQUEUE_H
#define _DEPTHQUEUE_H
#include <queue>
#include <memory>
#include "Util.h"
#include "IDepthSortable.h"
#include "IMovable.h"
class DepthQueue
{
public:
class DepthCompare
{
public:
bool operator() (
const std::weak_ptr<const IDepthSortable>& s,
const std::weak_ptr<const IDepthSortable>& s2) const
{
std::shared_ptr<const IDepthSortable> sp = s.lock();
std::shared_ptr<const IDepthSortable> sp2 = s2.lock();
if(sp && sp2){
// if the same depth, sort by y pos instead (to prevent z-fighting)
if(floatcmp(sp->depth(), sp2->depth()))
{
const IMovable* m = dynamic_cast<const IMovable*>(sp.get());
const IMovable* m2= dynamic_cast<const IMovable*>(sp2.get());
if(m && m2)
return m->y() < m2->y();
else
return false;
// sort by y pos instead
}
return sp->depth() < sp2->depth();
}
else
return false;
}
};
private:
std::priority_queue<std::weak_ptr<const IDepthSortable>, std::vector<std::weak_ptr<const IDepthSortable>>, DepthCompare> m_pqQueue;
public:
DepthQueue() {}
virtual ~DepthQueue() {}
void enqueue(const std::shared_ptr<const IDepthSortable>& s) {
m_pqQueue.push(std::weak_ptr<const IDepthSortable>(s));
}
virtual void render() {
while(!m_pqQueue.empty()) {
std::shared_ptr<const IDepthSortable> s;
if((s = m_pqQueue.top().lock()))
s->render();
m_pqQueue.pop();
}
}
};
#endif
| 30.820896 | 139 | 0.4523 | [
"render",
"vector"
] |
22816d655c5b1cdf69817842b009c36bd7ac18dc | 1,051 | h | C | include/generic_obstacle_detection/detector.h | cogsys-tuebingen/csapex_generic_obstacle_detection | bf076db25030bca76b2dc87248937f3d5a0db748 | [
"BSD-3-Clause"
] | 14 | 2017-06-15T02:01:04.000Z | 2022-01-08T09:57:04.000Z | include/generic_obstacle_detection/detector.h | jiaquan301/csapex_generic_obstacle_detection | bf076db25030bca76b2dc87248937f3d5a0db748 | [
"BSD-3-Clause"
] | 2 | 2019-05-14T14:24:10.000Z | 2019-05-26T08:41:22.000Z | include/generic_obstacle_detection/detector.h | jiaquan301/csapex_generic_obstacle_detection | bf076db25030bca76b2dc87248937f3d5a0db748 | [
"BSD-3-Clause"
] | 13 | 2017-07-25T01:05:10.000Z | 2021-12-07T09:19:15.000Z | #ifndef DETECTOR_H
#define DETECTOR_H
/// COMPONENT
#include <generic_obstacle_detection/point.h>
/// SYSTEM
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/PointIndices.h>
namespace od
{
template <class PointT>
class ObstacleDetector3D
{
public:
void classify(const typename pcl::PointCloud<PointT>::ConstPtr &cloud,
const std::vector<Point> &data,
const std::vector<float>& heat,
pcl::PointIndices& obstacles,
pcl::PointIndices& floor);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr
generateHeatCloud(const typename pcl::PointCloud<PointT>::ConstPtr &cloud,
const std::vector<float>& heat);
pcl::PointCloud<pcl::PointXYZL>::Ptr
generateClassifiedCloud(const typename pcl::PointCloud<PointT>::ConstPtr &cloud,
const pcl::PointIndices& ground_indices,
const pcl::PointIndices& floor_indices);
public:
double heat_threshold_;
};
}
#endif // DETECTOR_H
| 25.634146 | 84 | 0.646051 | [
"vector"
] |
2289628dbcff475997d852fe8497627654fce076 | 84,775 | h | C | aprinter/fs/FatFs.h | ambrop72/aprinter | b97c3111dad96aedf653c40b976317d73ac91715 | [
"BSD-2-Clause"
] | 133 | 2015-02-02T04:20:19.000Z | 2021-02-28T22:21:49.000Z | aprinter/fs/FatFs.h | ambrop72/aprinter | b97c3111dad96aedf653c40b976317d73ac91715 | [
"BSD-2-Clause"
] | 20 | 2015-01-06T08:41:26.000Z | 2019-07-25T07:10:26.000Z | aprinter/fs/FatFs.h | ambrop72/aprinter | b97c3111dad96aedf653c40b976317d73ac91715 | [
"BSD-2-Clause"
] | 46 | 2015-01-05T11:26:21.000Z | 2020-06-22T04:58:23.000Z | /*
* Copyright (c) 2015 Ambroz Bizjak
* 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 THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef AMBROLIB_FAT_FS_H
#define AMBROLIB_FAT_FS_H
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <aprinter/meta/MinMax.h>
#include <aprinter/meta/ChooseInt.h>
#include <aprinter/meta/BasicMetaUtils.h>
#include <aprinter/meta/FunctionIf.h>
#include <aprinter/meta/StructIf.h>
#include <aprinter/meta/ServiceUtils.h>
#include <aprinter/base/Object.h>
#include <aprinter/base/DebugObject.h>
#include <aprinter/base/Callback.h>
#include <aprinter/base/Assert.h>
#include <aprinter/base/BinaryTools.h>
#include <aprinter/base/TransferVector.h>
#include <aprinter/base/LoopUtils.h>
#include <aprinter/misc/Utf8Encoder.h>
#include <aprinter/misc/StringTools.h>
#include <aprinter/structure/DoubleEndedList.h>
#include <aprinter/fs/BlockCache.h>
#include <aprinter/fs/BlockRange.h>
namespace APrinter {
template <typename Arg>
class FatFs {
using Context = typename Arg::Context;
using ParentObject = typename Arg::ParentObject;
using TheBlockAccess = typename Arg::TheBlockAccess;
using InitHandler = typename Arg::InitHandler;
using WriteMountHandler = typename Arg::WriteMountHandler;
using Params = typename Arg::Params;
public:
struct Object;
static bool const FsWritable = Params::Writable;
static bool const EnableReadHinting = Params::EnableReadHinting;
static int const MaxFileNameSize = Params::MaxFileNameSize;
private:
static_assert(Params::NumCacheEntries >= 1, "");
static_assert(Params::MaxFileNameSize >= 12, "");
using TheDebugObject = DebugObject<Context, Object>;
APRINTER_MAKE_INSTANCE(TheBlockCache, (BlockCacheArg<Context, Object, TheBlockAccess, Params::NumCacheEntries, Params::NumIoUnits, Params::MaxIoBlocks, FsWritable>))
using BlockAccessUser = typename TheBlockAccess::User;
using BlockIndexType = typename TheBlockAccess::BlockIndexType;
static size_t const BlockSize = TheBlockAccess::BlockSize;
using DataWordType = typename TheBlockAccess::DataWordType;
using CacheBlockRef = typename TheBlockCache::CacheRef;
using CacheFlushRequest = typename TheBlockCache::template FlushRequest<>;
static_assert(BlockSize >= 0x47, "BlockSize not enough for EBPB");
static_assert(BlockSize % 32 == 0, "BlockSize not a multiple of 32");
static_assert(BlockSize >= 512, "BlockSize not enough for FS Information Sector");
static size_t const FatEntriesPerBlock = BlockSize / 4;
static size_t const DirEntriesPerBlock = BlockSize / 32;
using ClusterIndexType = uint32_t;
using ClusterBlockIndexType = uint16_t;
using DirEntriesPerBlockType = ChooseIntForMax<DirEntriesPerBlock, false>;
using FileNameLenType = ChooseIntForMax<Params::MaxFileNameSize, false>;
static size_t const EbpbStatusBitsOffset = 0x41;
static uint8_t const StatusBitsDirty = 0x01;
static ClusterIndexType const EndOfChainMarker = UINT32_C(0x0FFFFFFF);
static ClusterIndexType const FreeClusterMarker = UINT32_C(0x00000000);
static ClusterIndexType const EmptyFileMarker = UINT32_C(0x00000000);
static ClusterIndexType const NormalClusterIndexEnd = UINT32_C(0x0FFFFFF8);
static size_t const DirEntrySizeOffset = 0x1C;
static size_t const FsInfoSig1Offset = 0x0;
static size_t const FsInfoSig2Offset = 0x1E4;
static size_t const FsInfoFreeClustersOffset = 0x1E8;
static size_t const FsInfoAllocatedClusterOffset = 0x1EC;
static size_t const FsInfoSig3Offset = 0x1FC;
enum class FsState : uint8_t {INIT, READY, FAILED};
enum class WriteMountState : uint8_t {NOT_MOUNTED, MOUNT_META, MOUNT_FSINFO, MOUNT_FLUSH, MOUNTED, UMOUNT_FLUSH1, UMOUNT_META, UMOUNT_FLUSH2};
enum class AllocationState : uint8_t {IDLE, CHECK_EVENT, REQUESTING_BLOCK};
template <bool Writable> class ClusterChain;
template <bool Writable> class DirEntryRef;
class DirectoryIterator;
template <bool Writable> class WriteReference;
APRINTER_STRUCT_IF_TEMPLATE(FsEntryExtra) {
BlockIndexType dir_entry_block_index;
DirEntriesPerBlockType dir_entry_block_offset;
};
public:
static size_t const TheBlockSize = BlockSize;
enum class EntryType : uint8_t {DIR_TYPE, FILE_TYPE};
class FsEntry : private FsEntryExtra<FsWritable> {
friend FatFs;
public:
inline EntryType getType () const { return type; }
inline uint32_t getFileSize () const { return file_size; }
private:
EntryType type;
uint32_t file_size;
ClusterIndexType cluster_index;
};
static bool isPartitionTypeSupported (uint8_t type)
{
return (type == 0xB || type == 0xC);
}
static void init (Context c, BlockRange<BlockIndexType> block_range)
{
auto *o = Object::self(c);
TheBlockCache::init(c);
o->block_range = block_range;
o->state = FsState::INIT;
o->init_block_ref.init(c, APRINTER_CB_STATFUNC_T(&FatFs::init_block_ref_handler));
o->init_block_ref.requestBlock(c, get_abs_block_index(c, 0), 0, 1, CacheBlockRef::FLAG_NO_IMMEDIATE_COMPLETION);
fs_writable_init(c);
TheDebugObject::init(c);
}
static void deinit (Context c)
{
auto *o = Object::self(c);
TheDebugObject::deinit(c);
fs_writable_deinit(c);
if (o->state == FsState::INIT) {
o->init_block_ref.deinit(c);
}
TheBlockCache::deinit(c);
}
static FsEntry getRootEntry (Context c)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(o->state == FsState::READY)
FsEntry entry;
entry.type = EntryType::DIR_TYPE;
entry.file_size = 0;
entry.cluster_index = o->root_cluster;
set_fs_entry_extra(&entry, 0, 0);
return entry;
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, startWriteMount (Context c))
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(o->state == FsState::READY)
AMBRO_ASSERT(o->write_mount_state == WriteMountState::NOT_MOUNTED)
// implies
AMBRO_ASSERT(o->num_write_references == 0)
AMBRO_ASSERT(o->alloc_state == AllocationState::IDLE)
o->write_mount_state = WriteMountState::MOUNT_META;
o->write_block_ref.requestBlock(c, get_abs_block_index(c, 0), 0, 1, CacheBlockRef::FLAG_NO_IMMEDIATE_COMPLETION);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, startWriteUnmount (Context c))
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(o->state == FsState::READY)
AMBRO_ASSERT(o->write_mount_state == WriteMountState::MOUNTED)
AMBRO_ASSERT(o->num_write_references == 0)
// implies
AMBRO_ASSERT(o->alloc_state == AllocationState::IDLE)
o->write_mount_state = WriteMountState::UMOUNT_FLUSH1;
o->flush_request.requestFlush(c);
}
class DirLister {
public:
using DirListerHandler = Callback<void(Context c, bool is_error, char const *name, FsEntry entry)>;
void init (Context c, FsEntry dir_entry, DirListerHandler handler)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(o->state == FsState::READY)
AMBRO_ASSERT(dir_entry.type == EntryType::DIR_TYPE)
m_dir_iter.init(c, dir_entry.cluster_index, handler);
}
void deinit (Context c)
{
TheDebugObject::access(c);
m_dir_iter.deinit(c);
}
void requestEntry (Context c)
{
TheDebugObject::access(c);
m_dir_iter.requestEntry(c);
}
private:
DirectoryIterator m_dir_iter;
};
class Opener {
enum class State : uint8_t {NO_NAMES, REQUESTING_ENTRY, COMPLETED};
public:
enum class OpenerStatus : uint8_t {SUCCESS, NOT_FOUND, ERROR};
using OpenerHandler = Callback<void(Context c, OpenerStatus status, FsEntry entry)>;
void init (Context c, FsEntry dir_entry, EntryType entry_type, char const *path, OpenerHandler handler)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(o->state == FsState::READY)
AMBRO_ASSERT(dir_entry.type == EntryType::DIR_TYPE)
AMBRO_ASSERT(path)
m_entry_type = entry_type;
m_handler = handler;
m_path_comp = path;
find_name_component_length();
if (m_path_comp_len == 0) {
m_state = State::NO_NAMES;
m_no_names_event.init(c, APRINTER_CB_OBJFUNC_T(&Opener::no_names_event_handler, this));
m_no_names_event.prependNowNotAlready(c);
m_no_names_entry = dir_entry;
} else {
m_state = State::REQUESTING_ENTRY;
m_dir_iter.init(c, dir_entry.cluster_index, APRINTER_CB_OBJFUNC_T(&Opener::dir_iter_handler, this));
m_dir_iter.requestEntry(c);
}
}
void deinit (Context c)
{
TheDebugObject::access(c);
if (m_state == State::NO_NAMES) {
m_no_names_event.deinit(c);
}
else if (m_state == State::REQUESTING_ENTRY) {
m_dir_iter.deinit(c);
}
}
private:
bool find_name_component_length ()
{
bool skipped_slashes = false;
while (*m_path_comp == '/') {
m_path_comp++;
skipped_slashes = true;
}
m_path_comp_len = 0;
while (m_path_comp[m_path_comp_len] != '\0' && m_path_comp[m_path_comp_len] != '/') {
m_path_comp_len++;
}
return skipped_slashes;
}
void no_names_event_handler (Context c)
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::NO_NAMES)
m_state = State::COMPLETED;
m_no_names_event.deinit(c);
if (m_no_names_entry.type == m_entry_type) {
return m_handler(c, OpenerStatus::SUCCESS, m_no_names_entry);
} else {
return m_handler(c, OpenerStatus::NOT_FOUND, FsEntry{});
}
}
void dir_iter_handler (Context c, bool is_error, char const *name, FsEntry entry)
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::REQUESTING_ENTRY)
if (is_error || !name) {
m_state = State::COMPLETED;
m_dir_iter.deinit(c);
OpenerStatus status = is_error ? OpenerStatus::ERROR : OpenerStatus::NOT_FOUND;
return m_handler(c, status, FsEntry{});
}
if (!compare_filename_equal(name, m_path_comp, m_path_comp_len)) {
m_dir_iter.requestEntry(c);
return;
}
m_dir_iter.deinit(c);
m_path_comp += m_path_comp_len;
bool skipped_slashes = find_name_component_length();
if (m_path_comp_len > 0) {
if (entry.type != EntryType::DIR_TYPE) {
m_state = State::COMPLETED;
return m_handler(c, OpenerStatus::NOT_FOUND, FsEntry{});
}
m_dir_iter.init(c, entry.cluster_index, APRINTER_CB_OBJFUNC_T(&Opener::dir_iter_handler, this));
m_dir_iter.requestEntry(c);
return;
}
m_state = State::COMPLETED;
if (entry.type == m_entry_type && !skipped_slashes) {
return m_handler(c, OpenerStatus::SUCCESS, entry);
} else {
return m_handler(c, OpenerStatus::NOT_FOUND, FsEntry{});
}
}
static bool compare_filename_equal (char const *str1, char const *str2, size_t str2_len)
{
return Params::CaseInsens ? AsciiCaseInsensStringEqualToMem(str1, str2, str2_len) : (strlen(str1) == str2_len && !memcmp(str1, str2, str2_len));
}
EntryType m_entry_type;
State m_state;
char const *m_path_comp;
size_t m_path_comp_len;
OpenerHandler m_handler;
union {
struct {
typename Context::EventLoop::QueuedEvent m_no_names_event;
FsEntry m_no_names_entry;
};
DirectoryIterator m_dir_iter;
};
};
APRINTER_STRUCT_IF_TEMPLATE(FileWritableMembers) {
DirEntryRef<true> m_dir_entry;
size_t m_write_bytes_in_block;
BlockIndexType m_dir_entry_block_index;
DirEntriesPerBlockType m_dir_entry_block_offset;
bool m_no_need_to_read_for_write;
WriteReference<true> m_write_ref;
};
APRINTER_STRUCT_IF_TEMPLATE(FileHintingMembers) {
BlockIndexType m_hint_block_pos;
};
template <bool Writable>
class File : public FileWritableMembers<Writable>, public FileHintingMembers<EnableReadHinting> {
static_assert(!Writable || FsWritable, "");
enum class State : uint8_t {
IDLE,
READ_EVENT, READ_NEXT_CLUSTER, READ_BLOCK, READ_READY,
OPENWR_EVENT, OPENWR_DIR_ENTRY,
WRITE_EVENT, WRITE_NEXT_CLUSTER, WRITE_BLOCK, WRITE_READY,
TRUNC_EVENT, TRUNC_CHAIN
};
public:
enum class IoMode : uint8_t {USER_BUFFER, FS_BUFFER};
using FileHandler = Callback<void(Context c, bool error, size_t length)>;
void init (Context c, FsEntry file_entry, FileHandler handler, IoMode io_mode=IoMode::USER_BUFFER)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(o->state == FsState::READY)
AMBRO_ASSERT(file_entry.type == EntryType::FILE_TYPE)
AMBRO_ASSERT(io_mode == IoMode::USER_BUFFER || io_mode == IoMode::FS_BUFFER)
m_event.init(c, APRINTER_CB_OBJFUNC_T(&File::event_handler, this));
m_chain.init(c, file_entry.cluster_index, APRINTER_CB_OBJFUNC_T(&File::chain_handler, this));
if (io_mode == IoMode::USER_BUFFER) {
m_user_buffer_mode.block_user.init(c, APRINTER_CB_OBJFUNC_T(&File::block_user_block_ref_handler, this));
} else {
m_fs_buffer_mode.block_ref.init(c, APRINTER_CB_OBJFUNC_T(&File::block_user_block_ref_handler, this));
}
m_handler = handler;
m_file_size = file_entry.file_size;
m_state = State::IDLE;
m_io_mode = io_mode;
m_file_pos = 0;
m_block_in_cluster = o->blocks_per_cluster;
writable_init(c, file_entry);
}
// NOTE: Not allowed when reader is busy, except when deiniting the whole FatFs and underlying storage!
void deinit (Context c)
{
TheDebugObject::access(c);
writable_deinit(c);
if (m_io_mode == IoMode::USER_BUFFER) {
m_user_buffer_mode.block_user.deinit(c);
} else {
m_fs_buffer_mode.block_ref.deinit(c);
}
m_chain.deinit(c);
m_event.deinit(c);
}
void rewind (Context c)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::IDLE)
m_chain.rewind(c);
m_file_pos = 0;
m_block_in_cluster = o->blocks_per_cluster;
}
void startReadUserBuf (Context c, DataWordType *buf)
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::IDLE)
AMBRO_ASSERT(m_io_mode == IoMode::USER_BUFFER)
m_user_buffer_mode.transfer_desc = TransferDescriptor<DataWordType>{buf, BlockSize/sizeof(DataWordType)};
m_state = State::READ_EVENT;
m_event.prependNowNotAlready(c);
}
void startRead (Context c)
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::IDLE)
AMBRO_ASSERT(m_io_mode == IoMode::FS_BUFFER)
m_state = State::READ_EVENT;
m_event.prependNowNotAlready(c);
}
char const * getReadPointer (Context c)
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::READ_READY)
AMBRO_ASSERT(m_io_mode == IoMode::FS_BUFFER)
return m_fs_buffer_mode.block_ref.getData(c, WrapBool<false>());
}
void finishRead (Context c)
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::READ_READY)
AMBRO_ASSERT(m_io_mode == IoMode::FS_BUFFER)
finish_read(c, get_bytes_in_block(c));
m_fs_buffer_mode.block_ref.reset(c);
m_state = State::IDLE;
}
APRINTER_FUNCTION_IF(Writable, void, startOpenWritable (Context c))
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::IDLE)
AMBRO_ASSERT(!this->m_write_ref.isTaken(c))
m_state = State::OPENWR_EVENT;
m_event.prependNowNotAlready(c);
}
APRINTER_FUNCTION_IF(Writable, void, closeWritable (Context c))
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::IDLE)
clean_up_writability(c);
}
APRINTER_FUNCTION_IF(Writable, void, startWrite (Context c, bool no_need_to_read))
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::IDLE)
AMBRO_ASSERT(m_file_pos % BlockSize == 0)
AMBRO_ASSERT(m_io_mode == IoMode::FS_BUFFER)
this->m_no_need_to_read_for_write = no_need_to_read;
m_state = State::WRITE_EVENT;
m_event.prependNowNotAlready(c);
}
APRINTER_FUNCTION_IF(Writable, char *, getWritePointer (Context c))
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::WRITE_READY)
AMBRO_ASSERT(m_io_mode == IoMode::FS_BUFFER)
return m_fs_buffer_mode.block_ref.getData(c, WrapBool<true>());
}
APRINTER_FUNCTION_IF(Writable, void, finishWrite (Context c, size_t bytes_in_block))
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::WRITE_READY)
AMBRO_ASSERT(m_io_mode == IoMode::FS_BUFFER)
AMBRO_ASSERT(bytes_in_block >= 0)
AMBRO_ASSERT(bytes_in_block <= BlockSize)
if (bytes_in_block > 0) {
finish_write(c, bytes_in_block);
m_fs_buffer_mode.block_ref.markDirty(c);
}
m_fs_buffer_mode.block_ref.reset(c);
m_state = State::IDLE;
}
APRINTER_FUNCTION_IF(Writable, void, startTruncate (Context c))
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::IDLE)
m_state = State::TRUNC_EVENT;
m_event.prependNowNotAlready(c);
}
private:
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, writable_init (Context c, FsEntry file_entry))
{
this->m_dir_entry.init(c, APRINTER_CB_OBJFUNC_T(&File::dir_entry_handler<>, this));
this->m_write_ref.init(c);
this->m_dir_entry_block_index = file_entry.dir_entry_block_index;
this->m_dir_entry_block_offset = file_entry.dir_entry_block_offset;
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, writable_deinit (Context c))
{
this->m_write_ref.deinit(c);
this->m_dir_entry.deinit(c);
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, handle_event_openwr (Context c))
{
if (!this->m_write_ref.take(c)) {
return complete_open_writable_request(c, true);
}
m_state = State::OPENWR_DIR_ENTRY;
this->m_dir_entry.requestEntryRef(c, this->m_dir_entry_block_index, this->m_dir_entry_block_offset);
}
void handle_event_read (Context c)
{
auto *o = Object::self(c);
if (m_file_pos >= m_file_size) {
return complete_request(c, false);
}
if (m_block_in_cluster == o->blocks_per_cluster) {
m_state = State::READ_NEXT_CLUSTER;
m_chain.requestNext(c);
return;
}
if (!is_cluster_idx_valid_for_data(c, m_chain.getCurrentCluster(c))) {
return complete_request(c, true);
}
m_state = State::READ_BLOCK;
BlockIndexType abs_block_idx = get_cluster_data_abs_block_index(c, m_chain.getCurrentCluster(c), m_block_in_cluster);
if (m_io_mode == IoMode::USER_BUFFER) {
m_user_buffer_mode.block_user.startReadOrWrite(c, false, abs_block_idx, 1, TransferVector<DataWordType>{&m_user_buffer_mode.transfer_desc, 1});
} else {
m_fs_buffer_mode.block_ref.requestBlock(c, abs_block_idx, 0, 1, CacheBlockRef::FLAG_NO_IMMEDIATE_COMPLETION);
do_read_hinting(c, abs_block_idx);
}
}
APRINTER_FUNCTION_IF_OR_EMPTY(EnableReadHinting, void, do_read_hinting (Context c, BlockIndexType abs_block_idx))
{
auto *o = Object::self(c);
if (m_block_in_cluster == 0 || abs_block_idx >= this->m_hint_block_pos) {
BlockIndexType cluster_start_block = abs_block_idx - m_block_in_cluster;
BlockIndexType cluster_end_block = cluster_start_block + o->blocks_per_cluster;
if (m_block_in_cluster == 0) {
this->m_hint_block_pos = cluster_start_block + 1;
}
if (m_block_in_cluster == 0 || abs_block_idx >= this->m_hint_block_pos) {
this->m_hint_block_pos = TheBlockCache::hintBlocks(c, this->m_hint_block_pos, this->m_hint_block_pos, cluster_end_block, 0, 1);
}
}
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, handle_event_write (Context c))
{
auto *o = Object::self(c);
AMBRO_ASSERT(m_io_mode == IoMode::FS_BUFFER)
if (!this->m_write_ref.isTaken(c)) {
return complete_request(c, true);
}
if (m_block_in_cluster == o->blocks_per_cluster) {
this->m_no_need_to_read_for_write = true;
m_state = State::WRITE_NEXT_CLUSTER;
m_chain.requestNext(c);
return;
}
if (!is_cluster_idx_valid_for_data(c, m_chain.getCurrentCluster(c))) {
return complete_request(c, true);
}
m_state = State::WRITE_BLOCK;
BlockIndexType abs_block_idx = get_cluster_data_abs_block_index(c, m_chain.getCurrentCluster(c), m_block_in_cluster);
uint8_t flags = CacheBlockRef::FLAG_NO_IMMEDIATE_COMPLETION;
if (this->m_no_need_to_read_for_write) {
flags |= CacheBlockRef::FLAG_NO_NEED_TO_READ;
}
m_fs_buffer_mode.block_ref.requestBlock(c, abs_block_idx, 0, 1, flags);
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, handle_event_trunc (Context c))
{
if (!this->m_write_ref.isTaken(c)) {
return complete_request(c, true);
}
if (m_file_size > m_file_pos) {
m_file_size = m_file_pos;
this->m_dir_entry.setFileSize(c, m_file_size);
}
m_state = State::TRUNC_CHAIN;
m_chain.startTruncate(c);
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, extra_first_cluster_update (Context c, bool first_cluster_changed))
{
AMBRO_ASSERT(!first_cluster_changed || this->m_write_ref.isTaken(c))
if (first_cluster_changed) {
AMBRO_ASSERT(m_state == State::WRITE_NEXT_CLUSTER || m_state == State::TRUNC_CHAIN)
this->m_dir_entry.setFirstCluster(c, m_chain.getFirstCluster(c));
}
}
void handle_chain_read_next (Context c, bool error)
{
auto *o = Object::self(c);
AMBRO_ASSERT(m_block_in_cluster == o->blocks_per_cluster)
if (error || m_chain.endReached(c)) {
return complete_request(c, true);
}
m_block_in_cluster = 0;
m_state = State::READ_EVENT;
m_event.prependNowNotAlready(c);
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, handle_chain_write_next (Context c, bool error))
{
auto *o = Object::self(c);
AMBRO_ASSERT(m_block_in_cluster == o->blocks_per_cluster)
if (error) {
return complete_request(c, true);
}
if (m_chain.endReached(c)) {
m_chain.requestNew(c);
return;
}
m_block_in_cluster = 0;
m_state = State::WRITE_EVENT;
m_event.prependNowNotAlready(c);
}
void handle_block_read (Context c, bool error)
{
if (error) {
return complete_request(c, true);
}
size_t bytes_in_block = get_bytes_in_block(c);
AMBRO_ASSERT(bytes_in_block > 0)
if (m_io_mode == IoMode::USER_BUFFER) {
finish_read(c, bytes_in_block);
return complete_request(c, false, bytes_in_block);
} else {
return complete_request(c, false, bytes_in_block, State::READ_READY);
}
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, handle_block_write (Context c, bool error))
{
AMBRO_ASSERT(m_io_mode == IoMode::FS_BUFFER)
if (error) {
return complete_request(c, true);
}
return complete_request(c, false, 0, State::WRITE_READY);
}
void complete_request (Context c, bool error, size_t length=0, State new_state=State::IDLE)
{
m_state = new_state;
return m_handler(c, error, length);
}
APRINTER_FUNCTION_IF(Writable, void, complete_open_writable_request (Context c, bool error))
{
if (error) {
clean_up_writability(c);
}
return complete_request(c, error);
}
APRINTER_FUNCTION_IF(Writable, void, clean_up_writability (Context c))
{
this->m_write_ref.release(c);
this->m_dir_entry.reset(c);
}
void event_handler (Context c)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(m_block_in_cluster <= o->blocks_per_cluster)
if (m_state == State::READ_EVENT) {
handle_event_read(c);
}
else if (Writable && m_state == State::OPENWR_EVENT) {
handle_event_openwr(c);
}
else if (Writable && m_state == State::WRITE_EVENT) {
handle_event_write(c);
}
else if (Writable && m_state == State::TRUNC_EVENT) {
handle_event_trunc(c);
}
else {
AMBRO_ASSERT(false);
}
}
void chain_handler (Context c, bool error, bool first_cluster_changed)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
extra_first_cluster_update(c, first_cluster_changed);
if (m_state == State::READ_NEXT_CLUSTER) {
handle_chain_read_next(c, error);
}
else if (Writable && m_state == State::WRITE_NEXT_CLUSTER) {
handle_chain_write_next(c, error);
}
else if (Writable && m_state == State::TRUNC_CHAIN) {
return complete_request(c, error);
}
else {
AMBRO_ASSERT(false);
}
}
void block_user_block_ref_handler (Context c, bool error)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(m_block_in_cluster < o->blocks_per_cluster)
if (m_state == State::READ_BLOCK) {
handle_block_read(c, error);
}
else if (Writable && m_state == State::WRITE_BLOCK) {
handle_block_write(c, error);
}
else {
AMBRO_ASSERT(false);
}
}
APRINTER_FUNCTION_IF(Writable, void, dir_entry_handler (Context c, bool error))
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::OPENWR_DIR_ENTRY)
if (error) {
return complete_open_writable_request(c, true);
}
if (this->m_dir_entry.getFirstCluster(c) != m_chain.getFirstCluster(c)) {
return complete_open_writable_request(c, true);
}
if (this->m_dir_entry.getFileSize(c) != m_file_size) {
return complete_open_writable_request(c, true);
}
return complete_open_writable_request(c, false);
}
size_t get_bytes_in_block (Context c)
{
return MinValue((uint32_t)BlockSize, (uint32_t)(m_file_size - m_file_pos));
}
void finish_read (Context c, size_t bytes_in_block)
{
m_file_pos += bytes_in_block;
m_block_in_cluster++;
}
APRINTER_FUNCTION_IF(Writable, void, finish_write (Context c, size_t bytes_in_block))
{
m_file_pos += bytes_in_block;
if (m_file_size < m_file_pos) {
m_file_size = m_file_pos;
this->m_dir_entry.setFileSize(c, m_file_size);
}
m_block_in_cluster++;
}
typename Context::EventLoop::QueuedEvent m_event;
ClusterChain<Writable> m_chain;
FileHandler m_handler;
uint32_t m_file_size;
uint32_t m_file_pos;
State m_state;
IoMode m_io_mode;
ClusterBlockIndexType m_block_in_cluster;
union {
struct {
BlockAccessUser block_user;
TransferDescriptor<DataWordType> transfer_desc;
} m_user_buffer_mode;
struct {
CacheBlockRef block_ref;
} m_fs_buffer_mode;
};
};
template <typename Dummy=void>
using FlushRequest = CacheFlushRequest;
using CacheRefForUser = CacheBlockRef;
private:
APRINTER_FUNCTION_IF_OR_EMPTY_EXT(FsWritable, static, void, fs_writable_init (Context c))
{
auto *o = Object::self(c);
o->alloc_event.init(c, APRINTER_CB_STATFUNC_T(&FatFs::alloc_event_handler<>));
o->write_block_ref.init(c, APRINTER_CB_STATFUNC_T(&FatFs::write_block_ref_handler<>));
o->fs_info_block_ref.init(c, APRINTER_CB_STATFUNC_T(&FatFs::fs_info_block_ref_handler<>));
o->flush_request.init(c, APRINTER_CB_STATFUNC_T(&FatFs::flush_request_handler<>));
}
APRINTER_FUNCTION_IF_OR_EMPTY_EXT(FsWritable, static, void, fs_writable_deinit (Context c))
{
auto *o = Object::self(c);
o->flush_request.deinit(c);
o->fs_info_block_ref.deinit(c);
o->write_block_ref.deinit(c);
o->alloc_event.deinit(c);
}
APRINTER_FUNCTION_IF_OR_EMPTY_EXT(FsWritable, static, void, fs_writable_init_completed (Context c, BlockIndexType fs_info_block))
{
auto *o = Object::self(c);
o->write_mount_state = WriteMountState::NOT_MOUNTED;
o->alloc_state = AllocationState::IDLE;
o->fs_info_block = fs_info_block;
o->allocating_chains_list.init();
o->num_write_references = 0;
}
APRINTER_FUNCTION_IF_OR_EMPTY_EXT(FsWritable, static, void, write_block_ref_handler (Context c, bool error))
{
auto *o = Object::self(c);
if (o->state == FsState::READY) {
if (o->write_mount_state == WriteMountState::MOUNT_META) {
return write_mount_metablock_ref_handler(c, error);
} else if (o->write_mount_state == WriteMountState::UMOUNT_META) {
return write_unmount_metablock_ref_handler(c, error);
} else if (o->alloc_state == AllocationState::REQUESTING_BLOCK) {
return alloc_block_ref_handler(c, error);
}
}
AMBRO_ASSERT(false)
}
static void init_block_ref_handler (Context c, bool error)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(o->state == FsState::INIT)
uint8_t error_code = 99;
do {
if (error) {
o->init_block_ref.deinit(c);
error_code = 20;
goto error;
}
char const *buffer = o->init_block_ref.getData(c, WrapBool<false>());
uint16_t sector_size = ReadBinaryInt<uint16_t, BinaryLittleEndian>(buffer + 0xB);
uint8_t sectors_per_cluster = ReadBinaryInt<uint8_t, BinaryLittleEndian>(buffer + 0xD);
uint16_t num_reserved_sectors = ReadBinaryInt<uint16_t, BinaryLittleEndian>(buffer + 0xE);
uint8_t num_fats = ReadBinaryInt<uint8_t, BinaryLittleEndian>(buffer + 0x10);
uint16_t max_root = ReadBinaryInt<uint16_t, BinaryLittleEndian>(buffer + 0x11);
uint32_t sectors_per_fat = ReadBinaryInt<uint32_t, BinaryLittleEndian>(buffer + 0x24);
uint32_t root_cluster = ReadBinaryInt<uint32_t, BinaryLittleEndian>(buffer + 0x2C);
uint16_t fs_info_sector = ReadBinaryInt<uint16_t, BinaryLittleEndian>(buffer + 0x30);
uint8_t sig = ReadBinaryInt<uint8_t, BinaryLittleEndian>(buffer + 0x42);
o->init_block_ref.deinit(c);
if (sector_size == 0 || sector_size % BlockSize != 0) {
error_code = 22;
goto error;
}
uint16_t blocks_per_sector = sector_size / BlockSize;
if (sectors_per_cluster > UINT16_MAX / blocks_per_sector) {
error_code = 23;
goto error;
}
o->blocks_per_cluster = blocks_per_sector * sectors_per_cluster;
if ((uint32_t)num_reserved_sectors * sector_size < 0x47) {
error_code = 24;
goto error;
}
if (num_fats != 1 && num_fats != 2) {
error_code = 25;
goto error;
}
o->num_fats = num_fats;
if (sig != 0x28 && sig != 0x29) {
error_code = 26;
goto error;
}
if (max_root != 0) {
error_code = 27;
goto error;
}
o->root_cluster = mask_cluster_entry(root_cluster);
if (o->root_cluster < 2) {
error_code = 28;
goto error;
}
uint16_t entries_per_sector = sector_size / 4;
if (sectors_per_fat == 0 || sectors_per_fat > UINT32_MAX / entries_per_sector) {
error_code = 29;
goto error;
}
o->num_fat_entries = (ClusterIndexType)sectors_per_fat * entries_per_sector;
uint64_t fat_end_sectors_calc = (uint64_t)num_reserved_sectors + (uint64_t)o->num_fats * sectors_per_fat;
if (fat_end_sectors_calc > o->block_range.getLength() / blocks_per_sector) {
error_code = 29;
goto error;
}
BlockIndexType num_reserved_blocks = (BlockIndexType)num_reserved_sectors * blocks_per_sector;
o->fat_end_blocks = fat_end_sectors_calc * blocks_per_sector;
BlockIndexType fs_info_block;
if (fs_info_sector == 0 || fs_info_sector == UINT16_C(0xFFFF)) {
fs_info_block = 0;
} else {
uint32_t fs_info_block_calc = fs_info_sector * (uint32_t)blocks_per_sector;
if (fs_info_block_calc >= num_reserved_blocks) {
error_code = 31;
goto error;
}
fs_info_block = fs_info_block_calc;
}
ClusterIndexType valid_clusters_for_capacity = (o->block_range.getLength() - o->fat_end_blocks) / o->blocks_per_cluster;
if (valid_clusters_for_capacity < 1) {
error_code = 30;
goto error;
}
o->num_valid_clusters = MinValue(valid_clusters_for_capacity, MinValue((ClusterIndexType)(o->num_fat_entries - 2), NormalClusterIndexEnd - 2));
fs_writable_init_completed(c, fs_info_block);
error_code = 0;
} while (0);
error:
o->state = error_code ? FsState::FAILED : FsState::READY;
return InitHandler::call(c, error_code);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, complete_write_mount_request (Context c, bool error))
{
auto *o = Object::self(c);
o->write_block_ref.reset(c);
o->flush_request.reset(c);
if (error) {
o->fs_info_block_ref.reset(c);
o->write_mount_state = WriteMountState::NOT_MOUNTED;
} else {
o->write_mount_state = WriteMountState::MOUNTED;
}
return WriteMountHandler::call(c, error);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, complete_write_unmount_request (Context c, bool error))
{
auto *o = Object::self(c);
o->write_block_ref.reset(c);
o->flush_request.reset(c);
if (error) {
o->write_mount_state = WriteMountState::MOUNTED;
} else {
o->fs_info_block_ref.reset(c);
o->write_mount_state = WriteMountState::NOT_MOUNTED;
}
return WriteMountHandler::call(c, error);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, write_mount_metablock_ref_handler (Context c, bool error))
{
auto *o = Object::self(c);
AMBRO_ASSERT(o->state == FsState::READY)
AMBRO_ASSERT(o->write_mount_state == WriteMountState::MOUNT_META)
if (error) {
return complete_write_mount_request(c, true);
}
if (get_fs_dirty_bit(c, &o->write_block_ref)) {
return complete_write_mount_request(c, true);
}
if (!TheBlockAccess::isWritable(c)) {
return complete_write_mount_request(c, true);
}
if (o->fs_info_block == 0) {
return complete_write_mount_request(c, true);
}
o->write_mount_state = WriteMountState::MOUNT_FSINFO;
o->fs_info_block_ref.requestBlock(c, get_abs_block_index(c, o->fs_info_block), 0, 1, CacheBlockRef::FLAG_NO_IMMEDIATE_COMPLETION);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, flush_request_handler (Context c, bool error))
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(o->state == FsState::READY)
switch (o->write_mount_state) {
case WriteMountState::MOUNT_FLUSH: {
if (error) {
update_fs_dirty_bit(c, &o->write_block_ref, false);
return complete_write_mount_request(c, true);
}
return complete_write_mount_request(c, false);
} break;
case WriteMountState::UMOUNT_FLUSH1: {
if (error) {
return complete_write_unmount_request(c, true);
}
o->write_mount_state = WriteMountState::UMOUNT_META;
o->write_block_ref.requestBlock(c, get_abs_block_index(c, 0), 0, 1, CacheBlockRef::FLAG_NO_IMMEDIATE_COMPLETION);
} break;
case WriteMountState::UMOUNT_FLUSH2: {
return complete_write_unmount_request(c, error);
} break;
default: AMBRO_ASSERT(false);
}
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, fs_info_block_ref_handler (Context c, bool error))
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(o->state == FsState::READY)
AMBRO_ASSERT(o->write_mount_state == WriteMountState::MOUNT_FSINFO)
if (error) {
return complete_write_mount_request(c, true);
}
char const *buffer = o->fs_info_block_ref.getData(c, WrapBool<false>());
uint32_t sig1 = ReadBinaryInt<uint32_t, BinaryLittleEndian>(buffer + FsInfoSig1Offset);
uint32_t sig2 = ReadBinaryInt<uint32_t, BinaryLittleEndian>(buffer + FsInfoSig2Offset);
uint32_t sig3 = ReadBinaryInt<uint32_t, BinaryLittleEndian>(buffer + FsInfoSig3Offset);
uint32_t alloc_cluster = ReadBinaryInt<uint32_t, BinaryLittleEndian>(buffer + FsInfoAllocatedClusterOffset);
if (sig1 != UINT32_C(0x41615252) || sig2 != UINT32_C(0x61417272) || sig3 != UINT32_C(0xAA550000)) {
return complete_write_mount_request(c, true);
}
o->alloc_position = 0;
if (alloc_cluster >= 2 && alloc_cluster < 2 + o->num_valid_clusters) {
o->alloc_position = alloc_cluster - 2;
}
update_fs_dirty_bit(c, &o->write_block_ref, true);
o->write_mount_state = WriteMountState::MOUNT_FLUSH;
o->flush_request.requestFlush(c);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, write_unmount_metablock_ref_handler (Context c, bool error))
{
auto *o = Object::self(c);
AMBRO_ASSERT(o->state == FsState::READY)
AMBRO_ASSERT(o->write_mount_state == WriteMountState::UMOUNT_META)
if (error) {
return complete_write_unmount_request(c, true);
}
if (!get_fs_dirty_bit(c, &o->write_block_ref)) {
return complete_write_unmount_request(c, true);
}
update_fs_dirty_bit(c, &o->write_block_ref, false);
o->write_mount_state = WriteMountState::UMOUNT_FLUSH2;
o->flush_request.requestFlush(c);
}
static ClusterIndexType mask_cluster_entry (uint32_t entry_value)
{
return (entry_value & UINT32_C(0x0FFFFFFF));
}
static uint32_t update_cluster_entry (uint32_t entry_value, ClusterIndexType new_value)
{
return (entry_value & UINT32_C(0xF0000000)) | new_value;
}
static bool is_cluster_idx_normal (ClusterIndexType cluster_idx)
{
return (cluster_idx >= 2 && cluster_idx < NormalClusterIndexEnd);
}
static bool is_cluster_idx_valid_for_fat (Context c, ClusterIndexType cluster_idx)
{
auto *o = Object::self(c);
return cluster_idx < o->num_fat_entries;
}
static BlockIndexType get_abs_block_index_for_fat_entry (Context c, ClusterIndexType cluster_idx)
{
auto *o = Object::self(c);
BlockIndexType num_reserved_blocks = o->fat_end_blocks - o->num_fats * (o->num_fat_entries / FatEntriesPerBlock);
return get_abs_block_index(c, num_reserved_blocks + (cluster_idx / FatEntriesPerBlock));
}
static bool request_fat_cache_block (Context c, CacheBlockRef *block_ref, ClusterIndexType cluster_idx, bool disable_immediate_completion)
{
auto *o = Object::self(c);
AMBRO_ASSERT(is_cluster_idx_valid_for_fat(c, cluster_idx))
BlockIndexType abs_block_idx = get_abs_block_index_for_fat_entry(c, cluster_idx);
BlockIndexType num_blocks_per_fat = o->num_fat_entries / FatEntriesPerBlock;
return block_ref->requestBlock(c, abs_block_idx, num_blocks_per_fat, o->num_fats, disable_immediate_completion ? CacheBlockRef::FLAG_NO_IMMEDIATE_COMPLETION : 0);
}
template <bool ForWriting>
static If<ForWriting, char, char const> * get_fat_ptr_in_cache_block (Context c, CacheBlockRef *block_ref, ClusterIndexType cluster_idx)
{
AMBRO_ASSERT(is_cluster_idx_valid_for_fat(c, cluster_idx))
AMBRO_ASSERT(block_ref->getAvailableBlock(c) == get_abs_block_index_for_fat_entry(c, cluster_idx))
return block_ref->getData(c, WrapBool<ForWriting>()) + ((size_t)4 * (cluster_idx % FatEntriesPerBlock));
}
static ClusterIndexType read_fat_entry_in_cache_block (Context c, CacheBlockRef *block_ref, ClusterIndexType cluster_idx)
{
AMBRO_ASSERT(is_cluster_idx_valid_for_fat(c, cluster_idx))
char const *entry_ptr = get_fat_ptr_in_cache_block<false>(c, block_ref, cluster_idx);
return mask_cluster_entry(ReadBinaryInt<uint32_t, BinaryLittleEndian>(entry_ptr));
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, update_fat_entry_in_cache_block (Context c, CacheBlockRef *block_ref, ClusterIndexType cluster_idx, ClusterIndexType value))
{
AMBRO_ASSERT(is_cluster_idx_valid_for_fat(c, cluster_idx))
char *entry_ptr = get_fat_ptr_in_cache_block<true>(c, block_ref, cluster_idx);
uint32_t new_entry_value = update_cluster_entry(ReadBinaryInt<uint32_t, BinaryLittleEndian>(entry_ptr), value);
WriteBinaryInt<uint32_t, BinaryLittleEndian>(new_entry_value, entry_ptr);
block_ref->markDirty(c);
}
static bool is_cluster_idx_valid_for_data (Context c, ClusterIndexType cluster_idx)
{
auto *o = Object::self(c);
return cluster_idx >= 2 && cluster_idx - 2 < o->num_valid_clusters;
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, bool, release_cluster (Context c, CacheBlockRef *block_ref, ClusterIndexType cluster_index, ClusterIndexType *out_next_cluster=nullptr))
{
ClusterIndexType next_cluster = read_fat_entry_in_cache_block(c, block_ref, cluster_index);
if (out_next_cluster) {
*out_next_cluster = next_cluster;
}
if (!is_cluster_idx_valid_for_data(c, cluster_index) || next_cluster == FreeClusterMarker) {
return false;
}
update_fat_entry_in_cache_block(c, block_ref, cluster_index, FreeClusterMarker);
update_fs_info_free_clusters(c, true);
return true;
}
static BlockIndexType get_cluster_data_block_index (Context c, ClusterIndexType cluster_idx, ClusterBlockIndexType cluster_block_idx)
{
auto *o = Object::self(c);
AMBRO_ASSERT(is_cluster_idx_valid_for_data(c, cluster_idx))
AMBRO_ASSERT(cluster_block_idx < o->blocks_per_cluster)
return o->fat_end_blocks + ((BlockIndexType)(cluster_idx - 2) * o->blocks_per_cluster) + cluster_block_idx;
}
static BlockIndexType get_cluster_data_abs_block_index (Context c, ClusterIndexType cluster_idx, ClusterBlockIndexType cluster_block_idx)
{
return get_abs_block_index(c, get_cluster_data_block_index(c, cluster_idx, cluster_block_idx));
}
static BlockIndexType get_abs_block_index (Context c, BlockIndexType rel_block)
{
auto *o = Object::self(c);
AMBRO_ASSERT(rel_block < o->block_range.getLength())
return o->block_range.getAbsBlockIndex(rel_block);
}
static uint32_t read_dir_entry_first_cluster (Context c, char const *entry_ptr)
{
return
((uint32_t)ReadBinaryInt<uint16_t, BinaryLittleEndian>(entry_ptr + 0x1A) << 0) |
((uint32_t)ReadBinaryInt<uint16_t, BinaryLittleEndian>(entry_ptr + 0x14) << 16);
}
static void write_dir_entry_first_cluster (Context c, uint32_t value, char *entry_ptr)
{
WriteBinaryInt<uint16_t, BinaryLittleEndian>(value >> 0, entry_ptr + 0x1A);
WriteBinaryInt<uint16_t, BinaryLittleEndian>(value >> 16, entry_ptr + 0x14);
}
static bool get_fs_dirty_bit (Context c, CacheBlockRef *block_ref)
{
char const *status_bits_ptr = block_ref->getData(c, WrapBool<false>()) + EbpbStatusBitsOffset;
uint8_t status_bits = ReadBinaryInt<uint8_t, BinaryLittleEndian>(status_bits_ptr);
return (status_bits & StatusBitsDirty);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, update_fs_dirty_bit (Context c, CacheBlockRef *block_ref, bool set_else_clear))
{
char *status_bits_ptr = block_ref->getData(c, WrapBool<true>()) + EbpbStatusBitsOffset;
uint8_t status_bits = ReadBinaryInt<uint8_t, BinaryLittleEndian>(status_bits_ptr);
if (set_else_clear) {
status_bits |= StatusBitsDirty;
} else {
status_bits &= ~StatusBitsDirty;
}
WriteBinaryInt<uint8_t, BinaryLittleEndian>(status_bits, status_bits_ptr);
block_ref->markDirty(c);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, update_fs_info_allocated_cluster (Context c))
{
auto *o = Object::self(c);
ClusterIndexType value = 2 + o->alloc_position;
char *buffer = o->fs_info_block_ref.getData(c, WrapBool<true>());
WriteBinaryInt<uint32_t, BinaryLittleEndian>(value, buffer + FsInfoAllocatedClusterOffset);
o->fs_info_block_ref.markDirty(c);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, update_fs_info_free_clusters (Context c, bool inc_else_dec))
{
auto *o = Object::self(c);
char *buffer = o->fs_info_block_ref.getData(c, WrapBool<true>());
uint32_t free_clusters = ReadBinaryInt<uint32_t, BinaryLittleEndian>(buffer + FsInfoFreeClustersOffset);
if (free_clusters <= o->num_valid_clusters) {
if (inc_else_dec) {
free_clusters++;
} else {
free_clusters--;
}
WriteBinaryInt<uint32_t, BinaryLittleEndian>(free_clusters, buffer + FsInfoFreeClustersOffset);
o->fs_info_block_ref.markDirty(c);
}
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, allocation_request_added (Context c))
{
auto *o = Object::self(c);
AMBRO_ASSERT(!o->allocating_chains_list.isEmpty())
AMBRO_ASSERT(o->write_mount_state == WriteMountState::MOUNTED)
if (o->alloc_state == AllocationState::IDLE) {
start_new_allocation(c);
}
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, allocation_request_removed (Context c))
{
auto *o = Object::self(c);
if (o->alloc_state != AllocationState::IDLE && o->allocating_chains_list.isEmpty()) {
o->alloc_state = AllocationState::IDLE;
o->alloc_event.unset(c);
o->write_block_ref.reset(c);
}
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, start_new_allocation (Context c))
{
auto *o = Object::self(c);
o->alloc_state = AllocationState::CHECK_EVENT;
o->alloc_start = o->alloc_position;
o->alloc_event.prependNowNotAlready(c);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, complete_allocation (Context c, bool error, ClusterIndexType cluster_index=0))
{
auto *o = Object::self(c);
AMBRO_ASSERT(o->alloc_state != AllocationState::IDLE)
AMBRO_ASSERT(!o->allocating_chains_list.isEmpty())
ClusterChain<true> *complete_request = nullptr;
bool have_more_requests = false;
for (ClusterChain<true> *chain = o->allocating_chains_list.first(); chain; chain = o->allocating_chains_list.next(chain)) {
AMBRO_ASSERT(chain->m_state == ClusterChain<true>::State::NEW_ALLOCATING)
if (!complete_request) {
complete_request = chain;
} else {
have_more_requests = true;
}
}
AMBRO_ASSERT(complete_request)
if (have_more_requests) {
start_new_allocation(c);
} else {
o->alloc_state = AllocationState::IDLE;
o->write_block_ref.reset(c);
}
complete_request->allocation_result(c, error, cluster_index);
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, alloc_event_handler (Context c))
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(o->alloc_state == AllocationState::CHECK_EVENT)
AMBRO_ASSERT(o->write_mount_state == WriteMountState::MOUNTED)
while (true) {
ClusterIndexType current_cluster = 2 + o->alloc_position;
if (!request_fat_cache_block(c, &o->write_block_ref, current_cluster, false)) {
o->alloc_state = AllocationState::REQUESTING_BLOCK;
return;
}
o->alloc_position++;
if (o->alloc_position == o->num_valid_clusters) {
o->alloc_position = 0;
}
ClusterIndexType fat_value = read_fat_entry_in_cache_block(c, &o->write_block_ref, current_cluster);
if (fat_value == FreeClusterMarker) {
update_fat_entry_in_cache_block(c, &o->write_block_ref, current_cluster, EndOfChainMarker);
update_fs_info_free_clusters(c, false);
update_fs_info_allocated_cluster(c);
return complete_allocation(c, false, current_cluster);
}
if (o->alloc_position == o->alloc_start) {
return complete_allocation(c, true);
}
}
}
APRINTER_FUNCTION_IF_EXT(FsWritable, static, void, alloc_block_ref_handler (Context c, bool error))
{
auto *o = Object::self(c);
AMBRO_ASSERT(o->alloc_state == AllocationState::REQUESTING_BLOCK)
if (error) {
return complete_allocation(c, true);
}
o->alloc_state = AllocationState::CHECK_EVENT;
o->alloc_event.prependNowNotAlready(c);
}
APRINTER_FUNCTION_IF_OR_EMPTY_EXT(FsWritable, static, void, set_fs_entry_extra (FsEntry *entry, BlockIndexType dir_entry_block_index, DirEntriesPerBlockType dir_entry_block_offset))
{
entry->dir_entry_block_index = dir_entry_block_index;
entry->dir_entry_block_offset = dir_entry_block_offset;
}
APRINTER_STRUCT_IF_TEMPLATE(ClusterChainExtraMembers) {
CacheBlockRef m_fat_cache_ref2;
DoubleEndedListNode<ClusterChain<true>> m_allocating_chains_node;
ClusterIndexType m_prev_cluster;
};
template <bool Writable>
class ClusterChain : public ClusterChainExtraMembers<Writable> {
static_assert(!Writable || FsWritable, "");
enum class State : uint8_t {
IDLE,
NEXT_CHECK, NEXT_REQUESTING_FAT,
NEW_CHECK, NEW_REQUESTING_FAT, NEW_ALLOCATING,
TRUNCATE_CHECK, TRUNCATE_REQUESTING_FAT, TRUNCATE_REQUESTING_FAT2
};
enum class IterState : uint8_t {START, CLUSTER, END};
public:
using ClusterChainHandler = Callback<void(Context c, bool error, bool first_cluster_changed)>;
void init (Context c, ClusterIndexType first_cluster, ClusterChainHandler handler)
{
m_event.init(c, APRINTER_CB_OBJFUNC_T(&ClusterChain::event_handler, this));
m_fat_cache_ref1.init(c, APRINTER_CB_OBJFUNC_T(&ClusterChain::fat_cache_ref_handler, this));
m_handler = handler;
m_state = State::IDLE;
m_first_cluster = first_cluster;
extra_init(c);
rewind_internal(c);
}
void deinit (Context c)
{
extra_deinit(c);
m_fat_cache_ref1.deinit(c);
m_event.deinit(c);
}
void rewind (Context c)
{
AMBRO_ASSERT(m_state == State::IDLE)
rewind_internal(c);
}
void requestNext (Context c)
{
AMBRO_ASSERT(m_state == State::IDLE)
m_state = State::NEXT_CHECK;
m_event.prependNowNotAlready(c);
}
bool endReached (Context c)
{
AMBRO_ASSERT(m_state == State::IDLE)
return m_iter_state == IterState::END;
}
ClusterIndexType getCurrentCluster (Context c)
{
AMBRO_ASSERT(m_state == State::IDLE)
AMBRO_ASSERT(m_iter_state == IterState::CLUSTER)
return m_current_cluster;
}
APRINTER_FUNCTION_IF(Writable, void, requestNew (Context c))
{
auto *o = Object::self(c);
AMBRO_ASSERT(o->write_mount_state == WriteMountState::MOUNTED)
AMBRO_ASSERT(m_state == State::IDLE)
AMBRO_ASSERT(m_iter_state == IterState::END)
m_state = State::NEW_CHECK;
m_event.prependNowNotAlready(c);
}
ClusterIndexType getFirstCluster (Context c)
{
AMBRO_ASSERT(m_state == State::IDLE)
return m_first_cluster;
}
APRINTER_FUNCTION_IF(Writable, void, startTruncate (Context c))
{
AMBRO_ASSERT(m_state == State::IDLE)
m_state = State::TRUNCATE_CHECK;
m_event.prependNowNotAlready(c);
}
private:
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, extra_init (Context c))
{
this->m_fat_cache_ref2.init(c, APRINTER_CB_OBJFUNC_T(&ClusterChain::fat_cache_ref_handler, this));
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, extra_deinit (Context c))
{
auto *o = Object::self(c);
if (m_state == State::NEW_ALLOCATING) {
o->allocating_chains_list.remove(this);
allocation_request_removed(c);
}
this->m_fat_cache_ref2.deinit(c);
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, extra_complete_request (Context c))
{
this->m_fat_cache_ref2.reset(c);
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, handle_event_new_check (Context c))
{
auto *o = Object::self(c);
if (is_cluster_idx_normal(this->m_prev_cluster)) {
AMBRO_ASSERT(is_cluster_idx_valid_for_fat(c, this->m_prev_cluster))
if (!request_fat_cache_block(c, &m_fat_cache_ref1, this->m_prev_cluster, false)) {
m_state = State::NEW_REQUESTING_FAT;
return;
}
}
m_state = State::NEW_ALLOCATING;
o->allocating_chains_list.append(this);
allocation_request_added(c);
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, handle_event_truncate_check (Context c))
{
if (!is_cluster_idx_normal(m_current_cluster)) {
return complete_request(c, false);
}
AMBRO_ASSERT(m_iter_state != IterState::END)
if (!is_cluster_idx_valid_for_fat(c, m_current_cluster)) {
return complete_request(c, true);
}
if (!request_fat_cache_block(c, &m_fat_cache_ref1, m_current_cluster, false)) {
m_state = State::TRUNCATE_REQUESTING_FAT;
return;
}
ClusterIndexType next_cluster = read_fat_entry_in_cache_block(c, &m_fat_cache_ref1, m_current_cluster);
if (!is_cluster_idx_normal(next_cluster)) {
bool changing_first_cluster = false;
if (m_iter_state == IterState::START) {
if (!release_cluster(c, &m_fat_cache_ref1, m_current_cluster)) {
return complete_request(c, true);
}
m_first_cluster = EmptyFileMarker;
m_current_cluster = m_first_cluster;
changing_first_cluster = true;
}
return complete_request(c, false, changing_first_cluster);
}
if (!is_cluster_idx_valid_for_fat(c, next_cluster)) {
return complete_request(c, true);
}
if (!request_fat_cache_block(c, &this->m_fat_cache_ref2, next_cluster, false)) {
m_state = State::TRUNCATE_REQUESTING_FAT2;
return;
}
ClusterIndexType after_next_cluster;
if (!release_cluster(c, &this->m_fat_cache_ref2, next_cluster, &after_next_cluster)) {
return complete_request(c, true);
}
update_fat_entry_in_cache_block(c, &m_fat_cache_ref1, m_current_cluster, after_next_cluster);
m_event.prependNowNotAlready(c);
}
APRINTER_FUNCTION_IF_OR_EMPTY(Writable, void, extra_set_prev_cluster (Context c, ClusterIndexType value))
{
this->m_prev_cluster = value;
}
void rewind_internal (Context c)
{
m_iter_state = IterState::START;
m_current_cluster = m_first_cluster;
extra_set_prev_cluster(c, 0);
}
void complete_request (Context c, bool error, bool first_cluster_changed=false)
{
m_state = State::IDLE;
m_fat_cache_ref1.resetWeak(c);
extra_complete_request(c);
return m_handler(c, error, first_cluster_changed);
}
void event_handler (Context c)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
if (m_state == State::NEXT_CHECK) {
if (m_iter_state == IterState::CLUSTER) {
if (!is_cluster_idx_valid_for_fat(c, m_current_cluster)) {
return complete_request(c, true);
}
if (!request_fat_cache_block(c, &m_fat_cache_ref1, m_current_cluster, false)) {
m_state = State::NEXT_REQUESTING_FAT;
return;
}
extra_set_prev_cluster(c, m_current_cluster);
m_current_cluster = read_fat_entry_in_cache_block(c, &m_fat_cache_ref1, m_current_cluster);
}
if (m_iter_state != IterState::END) {
m_iter_state = is_cluster_idx_normal(m_current_cluster) ? IterState::CLUSTER : IterState::END;
}
return complete_request(c, false);
}
else if (Writable && m_state == State::NEW_CHECK) {
handle_event_new_check(c);
}
else if (Writable && m_state == State::TRUNCATE_CHECK) {
handle_event_truncate_check(c);
}
else {
AMBRO_ASSERT(false);
}
}
void fat_cache_ref_handler (Context c, bool error)
{
TheDebugObject::access(c);
State success_state;
switch (m_state) {
case State::NEXT_REQUESTING_FAT: success_state = State::NEXT_CHECK; break;
case State::NEW_REQUESTING_FAT: success_state = State::NEW_CHECK; break;
case State::TRUNCATE_REQUESTING_FAT: success_state = State::TRUNCATE_CHECK; break;
case State::TRUNCATE_REQUESTING_FAT2: success_state = State::TRUNCATE_CHECK; break;
default: AMBRO_ASSERT(false);
}
if (error) {
return complete_request(c, true);
}
m_state = success_state;
m_event.prependNowNotAlready(c);
}
APRINTER_FUNCTION_IF(Writable, void, allocation_result (Context c, bool error, ClusterIndexType new_cluster_index))
{
auto *o = Object::self(c);
AMBRO_ASSERT(m_state == State::NEW_ALLOCATING)
AMBRO_ASSERT(error || is_cluster_idx_valid_for_fat(c, new_cluster_index))
AMBRO_ASSERT(error || is_cluster_idx_normal(new_cluster_index))
AMBRO_ASSERT(m_iter_state == IterState::END)
AMBRO_ASSERT(!is_cluster_idx_normal(m_current_cluster))
AMBRO_ASSERT(is_cluster_idx_normal(m_first_cluster) == is_cluster_idx_normal(this->m_prev_cluster))
o->allocating_chains_list.remove(this);
if (error) {
return complete_request(c, error);
}
m_current_cluster = new_cluster_index;
bool changing_first_cluster = !is_cluster_idx_normal(this->m_prev_cluster);
if (changing_first_cluster) {
m_first_cluster = m_current_cluster;
} else {
update_fat_entry_in_cache_block(c, &m_fat_cache_ref1, this->m_prev_cluster, m_current_cluster);
}
m_iter_state = IterState::CLUSTER;
return complete_request(c, false, changing_first_cluster);
}
typename Context::EventLoop::QueuedEvent m_event;
CacheBlockRef m_fat_cache_ref1;
ClusterChainHandler m_handler;
State m_state;
IterState m_iter_state;
ClusterIndexType m_first_cluster;
ClusterIndexType m_current_cluster;
};
template <bool Writable>
class DirEntryRef {
static_assert(Writable && FsWritable, "");
enum class State : uint8_t {INVALID, REQUESTING_BLOCK, READY};
public:
using DirEntryRefHandler = Callback<void(Context c, bool error)>;
void init (Context c, DirEntryRefHandler handler)
{
m_block_ref.init(c, APRINTER_CB_OBJFUNC_T(&DirEntryRef::block_ref_handler, this));
m_handler = handler;
m_state = State::INVALID;
}
void deinit (Context c)
{
m_block_ref.deinit(c);
}
void reset (Context c)
{
m_block_ref.reset(c);
m_state = State::INVALID;
}
void requestEntryRef (Context c, BlockIndexType block_index, DirEntriesPerBlockType block_offset)
{
AMBRO_ASSERT(m_state == State::INVALID)
m_state = State::REQUESTING_BLOCK;
m_block_offset = block_offset;
m_block_ref.requestBlock(c, get_abs_block_index(c, block_index), 0, 1, CacheBlockRef::FLAG_NO_IMMEDIATE_COMPLETION);
}
ClusterIndexType getFirstCluster (Context c)
{
AMBRO_ASSERT(m_state == State::READY)
return mask_cluster_entry(read_dir_entry_first_cluster(c, get_entry_ptr<false>(c)));
}
void setFirstCluster (Context c, ClusterIndexType value)
{
AMBRO_ASSERT(m_state == State::READY)
char *buffer = get_entry_ptr<true>(c);
uint32_t write_value = update_cluster_entry(read_dir_entry_first_cluster(c, buffer), value);
write_dir_entry_first_cluster(c, write_value, buffer);
m_block_ref.markDirty(c);
}
uint32_t getFileSize (Context c)
{
AMBRO_ASSERT(m_state == State::READY)
return ReadBinaryInt<uint32_t, BinaryLittleEndian>(get_entry_ptr<false>(c) + DirEntrySizeOffset);
}
void setFileSize (Context c, uint32_t value)
{
AMBRO_ASSERT(m_state == State::READY)
WriteBinaryInt<uint32_t, BinaryLittleEndian>(value, get_entry_ptr<true>(c) + DirEntrySizeOffset);
m_block_ref.markDirty(c);
}
private:
void block_ref_handler (Context c, bool error)
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::REQUESTING_BLOCK)
m_state = error ? State::INVALID : State::READY;
return m_handler(c, error);
}
template <bool ForWriting>
If<ForWriting, char, char const> * get_entry_ptr (Context c)
{
return m_block_ref.getData(c, WrapBool<ForWriting>()) + ((size_t)m_block_offset * 32);
}
CacheBlockRef m_block_ref;
DirEntryRefHandler m_handler;
State m_state;
DirEntriesPerBlockType m_block_offset;
};
class DirectoryIterator {
enum class State : uint8_t {WAIT_REQUEST, CHECK_NEXT_EVENT, REQUESTING_CLUSTER, REQUESTING_BLOCK};
public:
using DirectoryIteratorHandler = Callback<void(Context c, bool is_error, char const *name, FsEntry entry)>;
void init (Context c, ClusterIndexType first_cluster, DirectoryIteratorHandler handler)
{
auto *o = Object::self(c);
m_event.init(c, APRINTER_CB_OBJFUNC_T(&DirectoryIterator::event_handler, this));
m_chain.init(c, first_cluster, APRINTER_CB_OBJFUNC_T(&DirectoryIterator::chain_handler, this));
m_dir_block_ref.init(c, APRINTER_CB_OBJFUNC_T(&DirectoryIterator::dir_block_ref_handler, this));
m_handler = handler;
m_state = State::WAIT_REQUEST;
m_block_in_cluster = o->blocks_per_cluster;
m_block_entry_pos = DirEntriesPerBlock;
m_vfat_seq = -1;
}
void deinit (Context c)
{
m_dir_block_ref.deinit(c);
m_chain.deinit(c);
m_event.deinit(c);
}
void requestEntry (Context c)
{
AMBRO_ASSERT(m_state == State::WAIT_REQUEST)
schedule_event(c);
}
private:
void complete_request (Context c, bool error, char const *name=nullptr, FsEntry entry=FsEntry{})
{
m_state = State::WAIT_REQUEST;
return m_handler(c, error, name, entry);
}
void schedule_event (Context c)
{
m_state = State::CHECK_NEXT_EVENT;
m_event.prependNowNotAlready(c);
}
void event_handler (Context c)
{
auto *o = Object::self(c);
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::CHECK_NEXT_EVENT)
if (m_block_entry_pos == DirEntriesPerBlock) {
if (m_block_in_cluster == o->blocks_per_cluster) {
m_dir_block_ref.reset(c);
m_chain.requestNext(c);
m_state = State::REQUESTING_CLUSTER;
return;
}
if (!is_cluster_idx_valid_for_data(c, m_chain.getCurrentCluster(c))) {
return complete_request(c, true);
}
BlockIndexType abs_block_idx = get_cluster_data_abs_block_index(c, m_chain.getCurrentCluster(c), m_block_in_cluster);
if (!m_dir_block_ref.requestBlock(c, abs_block_idx, 0, 1, 0)) {
m_state = State::REQUESTING_BLOCK;
return;
}
m_block_in_cluster++;
m_block_entry_pos = 0;
}
char const *entry_ptr = m_dir_block_ref.getData(c, WrapBool<false>()) + ((size_t)m_block_entry_pos * 32);
uint8_t first_byte = ReadBinaryInt<uint8_t, BinaryLittleEndian>(entry_ptr + 0x0);
uint8_t attrs = ReadBinaryInt<uint8_t, BinaryLittleEndian>(entry_ptr + 0xB);
uint8_t type_byte = ReadBinaryInt<uint8_t, BinaryLittleEndian>(entry_ptr + 0xC);
uint8_t checksum_byte = ReadBinaryInt<uint8_t, BinaryLittleEndian>(entry_ptr + 0xD);
uint32_t file_size = ReadBinaryInt<uint32_t, BinaryLittleEndian>(entry_ptr + DirEntrySizeOffset);
if (first_byte == 0) {
return complete_request(c, false);
}
m_block_entry_pos++;
// VFAT entry
if (first_byte != 0xE5 && attrs == 0xF && type_byte == 0 && file_size != 0) {
int8_t entry_vfat_seq = first_byte & 0x1F;
if ((first_byte & 0x60) == 0x40) {
// Start collection.
m_vfat_seq = entry_vfat_seq;
m_vfat_csum = checksum_byte;
m_filename_pos = Params::MaxFileNameSize;
}
if (entry_vfat_seq > 0 && m_vfat_seq != -1 && entry_vfat_seq == m_vfat_seq && checksum_byte == m_vfat_csum) {
// Collect entry.
char name_data[26];
memcpy(name_data + 0, entry_ptr + 0x1, 10);
memcpy(name_data + 10, entry_ptr + 0xE, 12);
memcpy(name_data + 22, entry_ptr + 0x1C, 4);
size_t chunk_len = 0;
for (size_t i = 0; i < sizeof(name_data); i += 2) {
uint16_t ch = ReadBinaryInt<uint16_t, BinaryLittleEndian>(name_data + i);
if (ch == 0) {
break;
}
char enc_buf[4];
int enc_len = Utf8EncodeChar(ch, enc_buf);
if (enc_len > m_filename_pos - chunk_len) {
goto cancel_vfat;
}
memcpy(m_filename + chunk_len, enc_buf, enc_len);
chunk_len += enc_len;
}
memmove(m_filename + (m_filename_pos - chunk_len), m_filename, chunk_len);
m_filename_pos -= chunk_len;
m_vfat_seq--;
} else {
cancel_vfat:
// Cancel any collection.
m_vfat_seq = -1;
}
// Go on reading directory entries.
return schedule_event(c);
}
// Forget VFAT state but remember for use in this entry.
int8_t cur_vfat_seq = m_vfat_seq;
m_vfat_seq = -1;
// Free marker.
if (first_byte == 0xE5) {
return schedule_event(c);
}
// Ignore: volume label or device.
if ((attrs & 0x8) || (attrs & 0x40)) {
return schedule_event(c);
}
bool is_dir = (attrs & 0x10);
bool is_dot_entry = (first_byte == (uint8_t)'.');
ClusterIndexType first_cluster = mask_cluster_entry(read_dir_entry_first_cluster(c, entry_ptr));
if (is_dot_entry && first_cluster == 0) {
first_cluster = o->root_cluster;
}
char const *filename;
if (!is_dot_entry && cur_vfat_seq == 0 && vfat_checksum(entry_ptr) == m_vfat_csum) {
filename = m_filename + m_filename_pos;
m_filename[Params::MaxFileNameSize] = 0;
} else {
char name_temp[8];
memcpy(name_temp, entry_ptr + 0, 8);
if (name_temp[0] == 0x5) {
name_temp[0] = 0xE5;
}
size_t name_len = fixup_83_name(name_temp, 8, bool(type_byte & 0x8));
char ext_temp[3];
memcpy(ext_temp, entry_ptr + 8, 3);
size_t ext_len = fixup_83_name(ext_temp, 3, bool(type_byte & 0x10));
size_t filename_len = 0;
memcpy(m_filename + filename_len, name_temp, name_len);
filename_len += name_len;
if (ext_len > 0) {
m_filename[filename_len++] = '.';
memcpy(m_filename + filename_len, ext_temp, ext_len);
filename_len += ext_len;
}
m_filename[filename_len] = '\0';
filename = m_filename;
}
FsEntry entry;
entry.type = is_dir ? EntryType::DIR_TYPE : EntryType::FILE_TYPE;
entry.file_size = file_size;
entry.cluster_index = first_cluster;
set_fs_entry_extra(&entry,
get_cluster_data_block_index(c, m_chain.getCurrentCluster(c), m_block_in_cluster - 1),
m_block_entry_pos - 1);
return complete_request(c, false, filename, entry);
}
void chain_handler (Context c, bool error, bool first_cluster_changed)
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::REQUESTING_CLUSTER)
if (error || m_chain.endReached(c)) {
return complete_request(c, error);
}
m_block_in_cluster = 0;
schedule_event(c);
}
void dir_block_ref_handler (Context c, bool error)
{
TheDebugObject::access(c);
AMBRO_ASSERT(m_state == State::REQUESTING_BLOCK)
if (error) {
return complete_request(c, error);
}
schedule_event(c);
}
static uint8_t vfat_checksum (char const *data)
{
uint8_t csum = 0;
for (auto i : LoopRange<int>(11)) {
csum = (uint8_t)((uint8_t)((csum & 1) << 7) + (csum >> 1)) + (uint8_t)data[i];
}
return csum;
}
static size_t fixup_83_name (char *data, size_t length, bool lowercase)
{
while (length > 0 && data[length - 1] == ' ') {
length--;
}
if (lowercase) {
for (auto i : LoopRange<size_t>(length)) {
if (data[i] >= 'A' && data[i] <= 'Z') {
data[i] += 32;
}
}
}
return length;
}
typename Context::EventLoop::QueuedEvent m_event;
ClusterChain<false> m_chain;
CacheBlockRef m_dir_block_ref;
DirectoryIteratorHandler m_handler;
ClusterBlockIndexType m_block_in_cluster;
DirEntriesPerBlockType m_block_entry_pos;
State m_state;
int8_t m_vfat_seq;
uint8_t m_vfat_csum;
FileNameLenType m_filename_pos;
char m_filename[Params::MaxFileNameSize + 1];
};
template <bool Writable>
class WriteReference {
static_assert(Writable && FsWritable, "");
public:
void init (Context c)
{
m_taken = false;
}
void deinit (Context c)
{
release(c);
}
bool isTaken (Context c)
{
return m_taken;
}
bool take (Context c)
{
auto *o = Object::self(c);
if (!m_taken) {
if (o->write_mount_state != WriteMountState::MOUNTED) {
return false;
}
o->num_write_references++;
m_taken = true;
}
return true;
}
void release (Context c)
{
auto *o = Object::self(c);
if (m_taken) {
AMBRO_ASSERT(o->num_write_references > 0)
o->num_write_references--;
m_taken = false;
}
}
private:
bool m_taken;
};
APRINTER_STRUCT_IF_TEMPLATE(FsWritableMembers) {
typename Context::EventLoop::QueuedEvent alloc_event;
CacheBlockRef write_block_ref;
CacheBlockRef fs_info_block_ref;
CacheFlushRequest flush_request;
WriteMountState write_mount_state;
AllocationState alloc_state;
BlockIndexType fs_info_block;
DoubleEndedListForBase<ClusterChain<true>, ClusterChainExtraMembers<true>, &ClusterChain<true>::m_allocating_chains_node> allocating_chains_list;
ClusterIndexType alloc_position;
ClusterIndexType alloc_start;
size_t num_write_references;
};
public:
struct Object : public ObjBase<FatFs, ParentObject, MakeTypeList<
TheDebugObject,
TheBlockCache
>>, public FsWritableMembers<FsWritable> {
BlockRange<BlockIndexType> block_range;
FsState state;
union {
CacheBlockRef init_block_ref;
struct {
uint8_t num_fats;
ClusterBlockIndexType blocks_per_cluster;
ClusterIndexType root_cluster;
ClusterIndexType num_fat_entries;
BlockIndexType fat_end_blocks;
ClusterIndexType num_valid_clusters;
};
};
};
};
APRINTER_ALIAS_STRUCT_EXT(FatFsService, (
APRINTER_AS_VALUE(int, MaxFileNameSize),
APRINTER_AS_VALUE(int, NumCacheEntries),
APRINTER_AS_VALUE(int, NumIoUnits),
APRINTER_AS_VALUE(int, MaxIoBlocks),
APRINTER_AS_VALUE(bool, CaseInsens),
APRINTER_AS_VALUE(bool, Writable),
APRINTER_AS_VALUE(bool, EnableReadHinting)
), (
APRINTER_ALIAS_STRUCT_EXT(Fs, (
APRINTER_AS_TYPE(Context),
APRINTER_AS_TYPE(ParentObject),
APRINTER_AS_TYPE(TheBlockAccess),
APRINTER_AS_TYPE(InitHandler),
APRINTER_AS_TYPE(WriteMountHandler)
), (
using Params = FatFsService;
APRINTER_DEF_INSTANCE(Fs, FatFs)
))
))
}
#endif
| 38.959099 | 185 | 0.584382 | [
"object"
] |
22944e1e93ff458e668924a9526c62771c9f30dc | 1,927 | h | C | src/InfiniDEX/userconnection.h | bonkingbob/BH21 | 4218e5f035c23188f1ec1c49047c26b6eed255a7 | [
"MIT"
] | 9 | 2018-03-04T00:58:47.000Z | 2020-02-13T15:51:14.000Z | src/InfiniDEX/userconnection.h | bonkingbob/BH21 | 4218e5f035c23188f1ec1c49047c26b6eed255a7 | [
"MIT"
] | 13 | 2018-05-20T06:28:55.000Z | 2019-05-29T18:28:15.000Z | src/InfiniDEX/userconnection.h | bonkingbob/BH21 | 4218e5f035c23188f1ec1c49047c26b6eed255a7 | [
"MIT"
] | 17 | 2018-02-10T23:16:54.000Z | 2019-08-16T19:28:34.000Z | // Copyright (c) 2017-2018 The Infinex Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef USERCONNECTION_H
#define USERCONNECTION_H
#include <iostream>
#include <vector>
#include <map>
#include "hash.h"
#include "net.h"
#include "utilstrencodings.h"
class CUserConnection;
class CUserConnectionManager;
extern std::map<std::string, std::vector<CUserConnection>> mapUserConnections; //user public key & connection info
extern std::map<std::string, CUserConnection> mapMNConnection; //MN IP address & connection info
extern CUserConnectionManager userConnectionManager;
extern std::string MNPubKey; //temp
extern std::string DEXKey;
class CUserConnection
{
public:
CNode* nNode;
std::string nUserPubKey;
std::string nIP;
std::string nPort;
uint64_t nLastSeenTime;
CUserConnection(CNode* Node, std::string nUserPubKey, std::string nIP, std::string nPort, uint64_t nLastSeenTime) :
nNode(Node),
nUserPubKey(nUserPubKey),
nIP(nIP),
nPort(nPort),
nLastSeenTime(nLastSeenTime)
{}
CUserConnection() :
nUserPubKey(""),
nIP(""),
nPort(""),
nLastSeenTime(0)
{}
};
class CUserConnectionManager
{
private:
bool IsUserInList(std::string PubKey);
public:
CUserConnectionManager() {}
void ProcessUserConnection(CNode* node, std::string& strCommand, CDataStream& vRecv, CConnman& connman);
void AddUserConnection(CNode* node, std::string IP, std::string port, std::string PubKey); //to remove IP & port on actual implementation
bool GetUserConnection(std::string PubKey, std::vector<CUserConnection>& nodes);
bool GetUsersBroadcastList();
void UserDisconnected(std::string PubKey, std::string IPAddress);
void MNDisconnected(std::string IPAddress);
};
#endif
| 29.646154 | 139 | 0.713025 | [
"vector"
] |
22964546b0081a33976f702fe7dac0324e2a17a3 | 1,059 | h | C | nimbro_apc/hardware/apc_interface/include/apc_interface/apc_controller.h | warehouse-picking-automation-challenges/nimbro_picking | 857eee602beea9eebee45bbb67fce423b28f9db6 | [
"BSD-3-Clause"
] | 19 | 2017-11-02T03:05:51.000Z | 2020-12-02T19:40:15.000Z | nimbro_apc/hardware/apc_interface/include/apc_interface/apc_controller.h | warehouse-picking-automation-challenges/nimbro_picking | 857eee602beea9eebee45bbb67fce423b28f9db6 | [
"BSD-3-Clause"
] | null | null | null | nimbro_apc/hardware/apc_interface/include/apc_interface/apc_controller.h | warehouse-picking-automation-challenges/nimbro_picking | 857eee602beea9eebee45bbb67fce423b28f9db6 | [
"BSD-3-Clause"
] | 9 | 2017-09-16T02:20:39.000Z | 2020-05-24T14:06:35.000Z | // Communication controller for APC
// Author: Sebastian Schüller<schuell1@cs.uni-bonn.de>
#ifndef APC_CONTROLLER_H
#define APC_CONTROLLER_H
#include <string>
#include <vector>
#include <memory>
#include "controller_types.h"
struct UARTBuffer;
namespace apc_interface
{
class Controller
{
public:
Controller();
~Controller();
bool initUART(std::string filename);
bool connect();
bool initializeServos(std::vector<uint16_t> ids);
bool initializeServoOffset(uint16_t id);
bool rebootController();
bool dimLEDs(uint8_t duty);
bool switchVacuum(bool on);
bool switchVacuumPower(bool on);
bool sendPositionCmds(const ControllerStatus& status);
bool sendTorqueEnable(const ControllerStatus& status);
bool sendMaxTorque(const ControllerStatus& status);
bool updateStatus(ControllerStatus* status);
bool updateEEPROM(ControllerStatus* status);
bool getDbgStatus(ControllerDebugStatus* status);
private:
int m_fd;
bool sendBuffer();
bool readMsg(unsigned int timeout_usec = 1000000);
std::unique_ptr<UARTBuffer> m_buffer;
};
}
#endif
| 19.981132 | 55 | 0.779037 | [
"vector"
] |
229a4d175302aa79f35767d60440f684c9dcdd21 | 1,945 | h | C | NetMessage.h | bycicleashphae/socketforioswinandroid | c5245b547c30ef8b2719564b35a04d7d5657b255 | [
"BSD-2-Clause"
] | 1 | 2018-02-22T23:49:24.000Z | 2018-02-22T23:49:24.000Z | NetMessage.h | bycicleashphae/socketforioswinandroid | c5245b547c30ef8b2719564b35a04d7d5657b255 | [
"BSD-2-Clause"
] | null | null | null | NetMessage.h | bycicleashphae/socketforioswinandroid | c5245b547c30ef8b2719564b35a04d7d5657b255 | [
"BSD-2-Clause"
] | null | null | null | #ifndef _NETMESSAGE_LKAJSLDFJASLDFJKLASDF_H__
#define _NETMESSAGE_LKAJSLDFJASLDFJKLASDF_H__
#include "string.h"
#include "assert.h"
#include "vector"
#include "stdio.h"
typedef unsigned char UInt8;
typedef signed char Int8;
#ifndef WIN32
typedef long long Int64;
#else
typedef __int64 Int64;
#endif
class MemBuffer;
class NetMessage
{
void checkBufSize(int size);
// -1 : unknown
// -2 : need 4 byte HeadSize
// >=0 : size known
int m_size;
int m_headSize; //2 or 4
int m_bufStartPos;
public:
NetMessage(int size = 512);
~NetMessage();
int getSize() const { return m_size; }
int getHeadSize() const { return m_headSize; }
void createBuf(int bufSize = 0);
char* getBuf(int pos);
char* getReadBuf();
int getReadCap();
int getSendCap();
void onReceive(int size);
void onSend(int size);
int getCurrentPos() const { return m_curPos; }
char* getCurrentBuf() { return getBuf(m_curPos); }
bool isEnd() const;
void ResetForSend() { m_curPos = m_bufStartPos; }
void ResetForRead() { m_curPos = m_bufStartPos + m_headSize; }
void wFloat(float v);
float rFloat();
void wShort(short v);
short rShort();
void wUShort(unsigned short v);
unsigned short rUShort();
void wInt(int v);
int rInt();
void wUInt(unsigned int v);
unsigned int rUInt();
void wInt8(Int8 v);
Int8 rInt8();
void wUInt8(UInt8 v);
UInt8 rUInt8();
void wInt64(Int64 v);
Int64 rInt64();
void wDouble(double v);
double rDouble();
void wBoolean(bool v);
bool rBoolean();
void wChar(char v);
char rChar();
void wString(const char* str, int sz);
const char* rString(int& sz);
void wRaw(const char* buf, int sz);
const char* rRaw(int sz);
void dump();
void beginForWrite();
void endForWrite();
private:
int m_curPos;
MemBuffer* m_buffer;
void setBufValue(char value);
char getBufValue();
};
#endif | 21.853933 | 70 | 0.660668 | [
"vector"
] |
22a1c5826f3ea675b0d384c5900190a7a9a42621 | 4,244 | h | C | include/Set/Algebraic/VectorSpace/Category/Diagonal/Diagonal.h | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/Set/Algebraic/VectorSpace/Category/Diagonal/Diagonal.h | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/Set/Algebraic/VectorSpace/Category/Diagonal/Diagonal.h | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | // Diagonal.h: interface for the Diagonal class.
// Copyright (c) 2017-2018 Extreme Computation Technology and Solutions, LLC
// All rights reserved
// see file License.txt for license details
//////////////////////////////////////////////////////////////////////
#if !defined(SET_VECTORSPACE_CATEGORY_DIAGONAL_H__INCLUDED_)
#define SET_VECTORSPACE_CATEGORY_DIAGONAL_H__INCLUDED_
#pragma once
#include <math.h>
#include <stdlib.h>
#include <cassert>
#include "../Category.h"
#include "../../Vector/Vector.h"
namespace Set
{
namespace VectorSpace
{
//////////////////////////////////////////////////////////////////////
// Class Diagonal
//////////////////////////////////////////////////////////////////////
class Diagonal : public Set::VectorSpace::Vector
{
public:
Diagonal();
Diagonal(const unsigned int &);
Diagonal(const unsigned int &, double * const &);
virtual ~Diagonal();
Diagonal(const Diagonal &);
Diagonal(const Set::VectorSpace::Vector &);
Diagonal(const Set::VectorSpace::Hom &);
Diagonal & operator = (const Diagonal &);
Diagonal & operator = (const Set::VectorSpace::Vector &);
Set::VectorSpace::Vector
operator () (const Set::VectorSpace::Vector &) const;
double operator () (const Set::VectorSpace::Vector &,
const Set::VectorSpace::Vector &) const;
double operator () (const Diagonal &) const;
double operator () (const Set::VectorSpace::Hom &) const;
Set::VectorSpace::Hom Embed() const;
};
}
}
//////////////////////////////////////////////////////////////////////
// Operators
//////////////////////////////////////////////////////////////////////
/*
bool
operator != (const Set::VectorSpace::Diagonal &,
const Set::VectorSpace::Hom &);
bool
operator != (const Set::VectorSpace::Hom &,
const Set::VectorSpace::Diagonal &);
bool
operator == (const Set::VectorSpace::Diagonal &,
const Set::VectorSpace::Hom &);
bool
operator == (const Set::VectorSpace::Hom &,
const Set::VectorSpace::Diagonal &);
*/
void Random(Set::VectorSpace::Diagonal &);
Set::VectorSpace::Diagonal
operator + (const Set::VectorSpace::Diagonal &,
const Set::VectorSpace::Diagonal &);
Set::VectorSpace::Hom
operator + (const Set::VectorSpace::Diagonal &,
const Set::VectorSpace::Hom &);
Set::VectorSpace::Hom
operator + (const Set::VectorSpace::Hom &,
const Set::VectorSpace::Diagonal &);
Set::VectorSpace::Diagonal
operator - (const Set::VectorSpace::Diagonal &,
const Set::VectorSpace::Diagonal &);
Set::VectorSpace::Hom
operator - (const Set::VectorSpace::Diagonal &,
const Set::VectorSpace::Hom &);
Set::VectorSpace::Hom
operator - (const Set::VectorSpace::Hom &,
const Set::VectorSpace::Diagonal &);
Set::VectorSpace::Diagonal
operator - (const Set::VectorSpace::Diagonal &);
void Null(Set::VectorSpace::Diagonal &);
Set::VectorSpace::Diagonal
operator * (const Set::VectorSpace::Diagonal &,
const double &);
Set::VectorSpace::Diagonal
operator * (const double &,
const Set::VectorSpace::Diagonal &);
Set::VectorSpace::Diagonal
operator / (const Set::VectorSpace::Diagonal &,
const double &);
Set::VectorSpace::Vector
operator * (const Set::VectorSpace::Diagonal &,
const Set::VectorSpace::Vector &);
Set::VectorSpace::Diagonal
operator * (const Set::VectorSpace::Diagonal &,
const Set::VectorSpace::Diagonal &);
Set::VectorSpace::Hom
operator * (const Set::VectorSpace::Diagonal &,
const Set::VectorSpace::Hom &);
Set::VectorSpace::Hom
operator * (const Set::VectorSpace::Hom &,
const Set::VectorSpace::Diagonal &);
Set::VectorSpace::Diagonal
Adjoint(const Set::VectorSpace::Diagonal &);
double Norm(const Set::VectorSpace::Diagonal &);
Set::VectorSpace::Diagonal
Exp(const Set::VectorSpace::Diagonal &);
Set::VectorSpace::Diagonal
Log(const Set::VectorSpace::Diagonal &);
Set::VectorSpace::Diagonal
Inverse(const Set::VectorSpace::Diagonal &);
void Identity(Set::VectorSpace::Diagonal &);
double Jacobian(const Set::VectorSpace::Diagonal &);
double Trace(const Set::VectorSpace::Diagonal &);
#endif // !defined(SET_VECTORSPACE_CATEGORY_DIAGONAL_H__INCLUDED_)
| 27.738562 | 77 | 0.629359 | [
"vector"
] |
22a1f91ef768a704317f0a2d0d9713cb069ccc19 | 2,034 | h | C | include/def_davidson_subspace.h | ak-ustutt/GeCCo-public | 8d43a6c9323aeba7eb54625b95553bfd4b2418c6 | [
"MIT"
] | null | null | null | include/def_davidson_subspace.h | ak-ustutt/GeCCo-public | 8d43a6c9323aeba7eb54625b95553bfd4b2418c6 | [
"MIT"
] | null | null | null | include/def_davidson_subspace.h | ak-ustutt/GeCCo-public | 8d43a6c9323aeba7eb54625b95553bfd4b2418c6 | [
"MIT"
] | null | null | null |
type vector_t
integer::
& len=0
type(me_list_array),pointer::
& me_lists(:) => null()
end type
type vector_space_t
integer::
& maxvec, !maximum dimension of the subspace
& nvec, !current dimension of the subspace
& nlists, !number of lists a vector consists of
& ivec ! currently active vector == current_record for all associated files (hopefully)
type(me_list_array),dimension(:),pointer::
& me_lists=>null() ! saves information about the shapeof the vectors (do not have to be associated to the files)
type(file_array),dimension(:),pointer::
& vectors=>null() ! Note: a vector may consist of multiple lists. the vector number is the requested record.
!the index in vectors is only the actual list requested as part of this vector
end type
! { (c)_1 (c)_2 ...} <- vectors(1)
! U={ (t1)_1 (t1)_2 ...} <- vectors(2)
! { (t2)_1 (t2)_2 ...} <- vectors(3)
type davidson_subspace_t
integer::
& nmaxsub, !maximum number of vectors
& ncursub, ! current number of vectors
& icursub, ! last updated vectors (if new vectors are added after nmaxsub is reached, vectors are overridden)
& lcursub !
logical::
& with_metric
logical, dimension(:),pointer::
& use_metric
real(8),dimension(:),pointer::
& vMv_mat=>null(), ! matrix of all vMv products it is a maxsub x maxsub matrix with ncursub xncursub elements !=0
& vSv_mat=>null()
! (vMv_mat)_{i,j} = (v)_i*(Mv)_j
type(vector_space_t)::
& vspace, ! vector space
& Svspace, ! metric-vector product space (only used if a metric is available)
& Mvspace ! matrix-vector product space
end type
| 40.68 | 134 | 0.545723 | [
"vector"
] |
22ba3530e313b18f75ddd76e6433f9c994ab3902 | 1,131 | h | C | Engine_Networking/include/NetworkEventHandler.h | subr3v/s-engine | d77b9ccd0fff3982a303f14ce809691a570f61a3 | [
"MIT"
] | 2 | 2016-04-01T21:10:33.000Z | 2018-02-26T19:36:56.000Z | Engine_Networking/include/NetworkEventHandler.h | subr3v/s-engine | d77b9ccd0fff3982a303f14ce809691a570f61a3 | [
"MIT"
] | 1 | 2017-04-05T01:33:08.000Z | 2017-04-05T01:33:08.000Z | Engine_Networking/include/NetworkEventHandler.h | subr3v/s-engine | d77b9ccd0fff3982a303f14ce809691a570f61a3 | [
"MIT"
] | null | null | null | #ifndef NetworkEventHandler_h__
#define NetworkEventHandler_h__
#include <WinSock2.h>
#include "WindowsEventHandler.h"
#include "Vector.h"
enum class ESocketMessageType : char
{
None = 0,
Read = 1,
Write = 2,
Accept = 4,
Connect = 8,
Close = 16
};
inline ESocketMessageType operator|(ESocketMessageType A, ESocketMessageType B)
{
return (ESocketMessageType)((char)A | (char)B);
}
inline bool operator&(ESocketMessageType A, ESocketMessageType B)
{
return ((char)A & (char)B) != 0;
}
class IAsyncSocket
{
public:
virtual void OnMessage(ESocketMessageType MessageType, int ErrorCode) = 0;
virtual SOCKET GetSocket() = 0;
};
class FNetworkEventHandler : public IWindowsEventHandler
{
public:
virtual void HandleMessage(MSG Message) override;
void RegisterSocket(IAsyncSocket* Socket, ESocketMessageType MessageType);
void UnregisterSocket(IAsyncSocket* Socket);
static const int kSocketMessageID = WM_USER + 1;
private:
static ESocketMessageType MessageTypeFromID(int ID);
static int IDFromMessageType(ESocketMessageType MessageType);
TVector<IAsyncSocket*> Sockets;
};
#endif // NetworkEventHandler_h__
| 20.563636 | 79 | 0.770115 | [
"vector"
] |
22bd2ded57813c254ecbfd5fd97884a59124cb77 | 3,341 | h | C | Src/Orbiter/CSphereMgr.h | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 1,040 | 2021-07-27T12:12:06.000Z | 2021-08-02T14:24:49.000Z | Src/Orbiter/CSphereMgr.h | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 20 | 2021-07-27T12:25:22.000Z | 2021-08-02T12:22:19.000Z | Src/Orbiter/CSphereMgr.h | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 71 | 2021-07-27T14:19:49.000Z | 2021-08-02T05:51:52.000Z | // Copyright (c) Martin Schweiger
// Licensed under the MIT License
// =======================================================================
// CSphereMgr: Rendering of the celestial sphere background at variable
// resolutions.
// =======================================================================
#ifndef __CSPHEREMGR_H
#define __CSPHEREMGR_H
#define STRICT 1
#include "TileMgr.h"
// =======================================================================
// Class CSphereManager
class CSphereManager {
public:
CSphereManager ();
~CSphereManager ();
static void CreateDeviceObjects (LPDIRECT3D7 d3d, LPDIRECT3DDEVICE7 dev);
static void DestroyDeviceObjects ();
void Render (LPDIRECT3DDEVICE7 dev, int level, int bglvl);
protected:
bool LoadPatchData ();
bool LoadTileData ();
void LoadTextures ();
void ProcessTile (int lvl, int hemisp, int ilat, int nlat, int ilng, int nlng, TILEDESC *tile,
const TEXCRDRANGE &range, LPDIRECTDRAWSURFACE7 tex, LPDIRECTDRAWSURFACE7 ltex, DWORD flag,
const TEXCRDRANGE &bkp_range, LPDIRECTDRAWSURFACE7 bkp_tex, LPDIRECTDRAWSURFACE7 bkp_ltex, DWORD bkp_flag);
void RenderTile (int lvl, int hemisp, int ilat, int nlat, int ilng, int nlng,
TILEDESC *tile, const TEXCRDRANGE &range, LPDIRECTDRAWSURFACE7 tex, LPDIRECTDRAWSURFACE7 ltex, DWORD flag);
MATRIX4 WorldMatrix (int ilng, int nlng, int ilat, int nlat);
void SetWorldMatrix (const MATRIX4 &W);
Vector TileCentre (int hemisp, int ilat, int nlat, int ilng, int nlng);
// returns the direction of the tile centre from the planet centre in local
// planet coordinates
void TileExtents (int hemisp, int ilat, int nlat, int ilg, int nlng, double &lat1, double &lat2, double &lng1, double &lng2);
bool TileInView (int lvl, int ilat);
// Check if specified tile intersects viewport
private:
char texname[64];
float intensity; // opacity of background image
bool disabled; // background image disabled?
DWORD maxlvl; // max. patch resolution level
DWORD maxbaselvl; // max. resolution level, capped at 8
DWORD ntex; // total number of loaded textures for levels <= 8
DWORD nhitex; // number of textures for levels > 8
DWORD nhispec; // number of specular reflection masks (level > 8)
TILEDESC *tiledesc; // tile descriptors for levels 1-8
LPDIRECTDRAWSURFACE7 *texbuf; // texture buffer for surface textures (level <= 8)
bool bPreloadTile; // preload high-resolution tile textures
Matrix ecl2gal; // rotates from ecliptic to galactic frame
MATRIX4 trans; // transformation from ecliptic to galactic frame
TileBuffer *tilebuf;
struct RENDERPARAM {
LPDIRECT3DDEVICE7 dev; // render device
int tgtlvl; // target resolution level
MATRIX4 transform; // full transformation matrix (for frustum checks)
MATRIX4 viewproj; // view+projection matrix
MATRIX4 dwmat; // world matrix
Vector camdir; // camera direction in galactic frame
double viewap; // viewport aperture (semi-diagonal)
} RenderParam;
static DWORD vpX0, vpX1, vpY0, vpY1; // viewport boundaries
static double diagscale;
};
#endif // !__CSPHEREMGR_H | 40.743902 | 126 | 0.64352 | [
"render",
"vector",
"transform"
] |
22ca30946c8099d3f8a534a2ee5c453c1df23011 | 7,977 | c | C | init/init_klte.c | ktoonsez/android_device_samsung_klte | 649e2c35be9906aee8ce836049751ed8d7c52662 | [
"FTL"
] | 2 | 2016-04-18T10:49:17.000Z | 2021-11-17T11:50:58.000Z | init/init_klte.c | nuclearmistake/android_device_samsung_klte | 1e9877c132977416c04df5d01d18bb9b66ff97d4 | [
"FTL"
] | null | null | null | init/init_klte.c | nuclearmistake/android_device_samsung_klte | 1e9877c132977416c04df5d01d18bb9b66ff97d4 | [
"FTL"
] | null | null | null | /*
Copyright (c) 2013, The Linux Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
ARE 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 <stdlib.h>
#include "vendor_init.h"
#include "property_service.h"
#include "log.h"
#include "util.h"
#include "init_msm.h"
void init_msm_properties(unsigned long msm_id, unsigned long msm_ver, char *board_type)
{
char platform[PROP_VALUE_MAX];
char bootloader[PROP_VALUE_MAX];
char device[PROP_VALUE_MAX];
char devicename[PROP_VALUE_MAX];
int rc;
UNUSED(msm_id);
UNUSED(msm_ver);
UNUSED(board_type);
rc = property_get("ro.board.platform", platform);
if (!rc || !ISMATCH(platform, ANDROID_TARGET))
return;
property_get("ro.bootloader", bootloader);
if (strstr(bootloader, "G900W8")) {
/* kltecan */
property_set("ro.build.fingerprint", "samsung/kltevl/kltecan:4.3/JSS15J/N900W8VLUBMJ4:user/release-keys");
property_set("ro.build.description", "kltevl-user 4.3 JSS15J N900W8VLUBMJ4 release-keys");property_set("ro.product.model", "SM-G900W8");
property_set("ro.product.device", "kltecan");
gsm_properties();
} else if (strstr(bootloader, "G900P")) {
/* kltespr */
property_set("ro.build.fingerprint", "samsung/kltespr/kltespr:4.4.2/KOT49H/G900PVPU1ANCB:user/release-keys");
property_set("ro.build.description", "kltespr-user 4.4.2 KOT49H G900PVPU1ANCB release-keys");
property_set("ro.product.model", "SM-G900P");
property_set("ro.product.device", "kltespr");
cdma_properties();
} else if (strstr(bootloader, "G900R4")) {
/* klteusc */
property_set("ro.build.fingerprint", "samsung/klteusc/klteusc:4.4.2/KOT49H/G900R4VXU1ANCF:user/release-keys");
property_set("ro.build.description", "klteusc-user 4.4.2 KOT49H G900R4VXU1ANCF release-keys");
property_set("ro.product.model", "SM-G900R4");
property_set("ro.product.device", "klteusc");
cdma_properties();
} else if (strstr(bootloader, "G900T")) {
/* kltetmo */
property_set("ro.build.fingerprint", "samsung/kltetmo/kltetmo:4.4.2/KOT49H/G900TUVU1ANCH:user/release-keys");
property_set("ro.build.description", "kltetmo-user 4.4.2 KOT49H G900TUVU1ANCH release-keys");
property_set("ro.product.model", "SM-G900T");
property_set("ro.product.device", "kltetmo");
gsm_properties();
} else if (strstr(bootloader, "G900D")) {
/* kltedcm */
property_set("ro.build.fingerprint", "samsung/SC-04F/SC-04F:4.4.2/KOT49H/SC04FOMU1ANCO:user/release-keys");
property_set("ro.build.description", "kltedcm-user 4.4.2 KOT49H SC04FOMU1ANCO release-keys");
property_set("ro.product.model", "SM-G900D");
property_set("ro.product.device", "kltedcm");
gsm_properties();
} else if (strstr(bootloader, "G900I")) {
/* kltedv */
property_set("ro.build.fingerprint", "samsung/kltedv/klte:4.4.2/KOT49H/G900IDVU1ANC6:user/release-keys");
property_set("ro.build.description", "kltedv-user 4.4.2 KOT49H G900IDVU1ANC6 release-keys");
property_set("ro.product.model", "SM-G900I");
property_set("ro.product.device", "kltedv");
gsm_properties();
} else if (strstr(bootloader, "G900M")) {
/* klteub */
property_set("ro.build.fingerprint", "samsung/klteub/klte:4.4.2/KOT49H/G900MUBU1ANCE:user/release-keys");
property_set("ro.build.description", "klteub-user 4.4.2 KOT49H G900MUBU1ANCE release-keys");
property_set("ro.product.model", "SM-G900M");
property_set("ro.product.device", "klteub");
gsm_properties();
} else if (strstr(bootloader, "G900A")) {
/* klteatt */
property_set("ro.build.fingerprint", "samsung/klteatt/klte:4.4.2/KOT49H/G900AUCU2AND3:user/release-keys");
property_set("ro.build.description", "klteatt-user 4.4.2 KOT49H G900AUCU2AND3 release-keys");
property_set("ro.product.model", "SM-G900A");
property_set("ro.product.device", "klteatt");
gsm_properties();
} else if (strstr(bootloader, "G900R6")) {
/* kltelra */
property_set("ro.build.fingerprint", "samsung/kltelra/kltelra:4.4.2/KOT49H/G900R6WWU2AND7:user/release-keys");
property_set("ro.build.description", "kltelra-user 4.4.2 KOT49H G900R6WWU2AND7 release-keys");
property_set("ro.product.model", "SM-G900R6");
property_set("ro.product.device", "kltelra");
cdma_properties();
} else if (strstr(bootloader, "G900R7")) {
/* klteacg */
property_set("ro.build.fingerprint", "samsung/klteacg/klteacg:4.4.2/KOT49H/G900R7WWU2AND8:user/release-keys");
property_set("ro.build.description", "klteacg-user 4.4.2 KOT49H G900R7WWU2AND8 release-keys");
property_set("ro.product.model", "SM-G900R7");
property_set("ro.product.device", "klteacg");
cdma_properties();
} else if (strstr(bootloader, "G900V")) {
/* hltevzw */
property_set("ro.build.fingerprint", "Verizon/kltevzw/kltevzw:4.4.2/KOT49H/G900VVRU1ANCG:user/release-keys");
property_set("ro.build.description", "kltevzw-user 4.4.2 KOT49H G900VVRU1ANCG release-keys");
property_set("ro.product.model", "SM-G900V");
property_set("ro.product.device", "hltevzw");
cdma_properties();
property_set("ro.telephony.default_cdma_sub", "0");
property_set("ro.cdma.home.operator.alpha", "Verizon");
property_set("ro.cdma.home.operator.numeric", "311480");
} else {
/* kltexx */
property_set("ro.build.fingerprint", "samsung/kltexx/klte:4.4.2/KOT49H/G900FXXU1ANCE:user/release-keys");
property_set("ro.build.description", "kltexx-user 4.4.2 KOT49H G900FXXU1ANCE release-keys");
property_set("ro.product.model", "SM-G900F");
property_set("ro.product.device", "kltexx");
gsm_properties();
}
property_get("ro.product.device", device);
strlcpy(devicename, device, sizeof(devicename));
ERROR("Found bootloader id %s setting build properties for %s device\n", bootloader, devicename);
}
void gsm_properties()
{
property_set("telephony.lteOnGsmDevice", "1");
property_set("ro.telephony.default_network", "9");
property_set("ro.telephony.ril.v3", "newDialCode");
}
void cdma_properties()
{
property_set("ro.telephony.ril.v3", "newDriverCallU,newDialCode");
property_set("telephony.lteOnCdmaDevice", "1");
property_set("ro.telephony.default_network", "10");
}
| 48.93865 | 144 | 0.684969 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.