hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | 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 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
681febd6e819a9b358998f30af1ad34984effd9e | 613 | h | C | SharedLib/ScreenCutShareLib/include/oeamplifier.h | telecommai/macos | 18f6af19ffcc49e4ce7b03f5fc7dac826b27d6db | [
"BSD-3-Clause"
] | 3 | 2019-04-14T13:17:47.000Z | 2019-04-19T08:06:32.000Z | SharedLib/ScreenCutShareLib/include/oeamplifier.h | telecommai/macos | 18f6af19ffcc49e4ce7b03f5fc7dac826b27d6db | [
"BSD-3-Clause"
] | 7 | 2021-03-09T02:41:49.000Z | 2022-02-26T10:26:00.000Z | SharedLib/ScreenCutShareLib/include/oeamplifier.h | telecommai/macos | 18f6af19ffcc49e4ce7b03f5fc7dac826b27d6db | [
"BSD-3-Clause"
] | null | null | null | #ifndef OEAMPLIFIER_H
#define OEAMPLIFIER_H
#include <memory>
#include <QWidget>
class OEAmplifier : public QWidget
{
Q_OBJECT
public:
explicit OEAmplifier(std::shared_ptr<QPixmap> originPainting, QWidget *parent = 0);
signals:
public slots:
void onSizeChange(int w, int h);
void onPostionChange(int x, int y);
protected:
virtual void paintEvent(QPaintEvent *);
private:
QSize screenSize_;
QPoint cursorPoint_;
int sideLength_;
int imageHeight_;
std::shared_ptr<QPixmap> originPainting_;
};
#endif /// OEAMPLIFIER_H
| 15.717949 | 88 | 0.665579 |
a9906a9453734cc6eaf27166dd2ce59f38e42dab | 2,705 | h | C | Base64.h | harshmalhan/keylogger | 796f61f71b7fb9c37fc8a6970b684f8eb9bfbfdb | [
"Apache-2.0"
] | null | null | null | Base64.h | harshmalhan/keylogger | 796f61f71b7fb9c37fc8a6970b684f8eb9bfbfdb | [
"Apache-2.0"
] | null | null | null | Base64.h | harshmalhan/keylogger | 796f61f71b7fb9c37fc8a6970b684f8eb9bfbfdb | [
"Apache-2.0"
] | null | null | null | #ifndef BASE64_H
#define BASE64_H
#include <vector>
#include <string>
using std::string;
using std::vector;
namespace Base64
{
std::string base64_encode(const std::string &);
std::string base64_decode(const std::string &);
const std::string &SALT1 = "LM::TB::BB";
const std::string &SALT2 = "__:/__77";
const std::string &SALT3 = "line=wowC++";
std::string EncryptB64 (std::string s)
{
s = SALT1 + s + SALT2 + SALT3;
s = base64_encode (s);
s.insert (7, SALT3);
s += SALT1;
s = base64_encode (s);
s = SALT2 + SALT3 + s + SALT1;
s = base64_encode (s);
s.insert (1, "L");
s.insert (7, "M");
return s;
}
std::string DecryptB64 (std::string s)
{
s = s.erase (7, 1);
s = s.erase (1, 1);
s = base64_decode (s);
s = s.substr (SALT2.length() + SALT3.length());
s = s.substr (0, s.length() - SALT1.length());
s = base64_decode (s);
s = s.substr (0, s.length() - SALT1.length());
s = s.erase (7, SALT3.length());
s = base64_decode (s);
s = s.substr (SALT1.length());
s = s.substr (0, s.length() - SALT2.length() - SALT3.length());
return s;
}
const std::string &BASE64_CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string base64_encode (const std::string &s)
{
std::string ret;
int val = 0;
int bits = -6;
const unsigned int b63 = 0x3F;
for (const auto &c : s)
{
val = (val << 8) + c;
bits += 8;
while (bits >= 0)
{
ret.push_back(BASE64_CODES[(val >> bits) & b63]);
bits -= 6;
}
}
if (bits > -6)
ret.push_back(BASE64_CODES[((val << 8) >> (bits + 8)) & b63]);
while (ret.size() % 4)
ret.push_back('=');
return ret;
}
std::string base64_decode(const std::string &s)
{
std::string ret;
std::vector<int> vec(256, -1);
for (int i = 0; i < 64; i++)
vec [BASE64_CODES[i]] = i;
int val = 0, bits = -8;
for (const auto &c : s)
{
if (vec[c] == -1) break;
val = (val << 6) + vec[c];
bits += 6;
if (bits >= 0)
{
ret.push_back(char((val >> bits) & 0xFF));
bits -= 8;
}
}
return ret;
}
}
#endif
| 27.602041 | 102 | 0.439556 |
658b9c07470443668bba4ad125e66d07bfe635ee | 1,151 | h | C | src/graph/InterlockSDChecking.h | KIKI007/FrameInterlock | 4ea831169432949982a4bc07fb9df1f31717b8e8 | [
"MIT"
] | null | null | null | src/graph/InterlockSDChecking.h | KIKI007/FrameInterlock | 4ea831169432949982a4bc07fb9df1f31717b8e8 | [
"MIT"
] | null | null | null | src/graph/InterlockSDChecking.h | KIKI007/FrameInterlock | 4ea831169432949982a4bc07fb9df1f31717b8e8 | [
"MIT"
] | null | null | null | //
// Created by ziqwang on 01.03.18.
//
#ifndef TI_STABLE_ASSEMBLYINTERLOCK_H
#define TI_STABLE_ASSEMBLYINTERLOCK_H
#include "../Assembly.h"
#include <Eigen/Dense>
#include "DirectedGraphSSC.h"
using Eigen::MatrixXi;
enum InterlockingStatus
{
NOT_INTERLOCKING = 0,
HAS_KEY = 1,
HAS_NO_KEY = 2
};
struct InterlockSDData
{
InterlockingStatus status;
vector< vector<int> > ssc_groups;
};
//InterlockingSDChecking
//construct a directed graph when checking in single direction
//the edge i->j means in this direction, the translation value has: V_i >= V_j
class InterlockSDChecking{
public:
InterlockSDChecking()
{
eps_ = 1e-5;
}
/* single direction checking */
public:
InterlockSDData check_interlock_sd(Vector3d dv, const Assembly &assembly);
std::shared_ptr<DirectedGraph> init_sd_graph(Vector3d dv, const Assembly &assembly);
public:
std::shared_ptr<DirectedGraph> simplified_sd_graph(Vector3d dv, const Assembly &assembly);
public:
std::shared_ptr<DirectedGraph> blocking_graph_, simpified_graph_;
private:
double eps_;
};
#endif //TI_STABLE_ASSEMBLYINTERLOCK_H
| 18.868852 | 94 | 0.732407 |
45747c0f215076cbc476b304fd9a80c8afc33134 | 290 | h | C | Eager/cs270/freelist.h | UCSB-CS-RACELab/eager-appscale | d58fe64bb867ef58af19c1d84a5e1ec68ecddd3d | [
"Apache-2.0"
] | 3 | 2016-06-12T01:18:49.000Z | 2018-07-16T18:20:23.000Z | Eager/cs270/freelist.h | UCSB-CS-RACELab/eager-appscale | d58fe64bb867ef58af19c1d84a5e1ec68ecddd3d | [
"Apache-2.0"
] | null | null | null | Eager/cs270/freelist.h | UCSB-CS-RACELab/eager-appscale | d58fe64bb867ef58af19c1d84a5e1ec68ecddd3d | [
"Apache-2.0"
] | 1 | 2020-05-25T02:59:15.000Z | 2020-05-25T02:59:15.000Z | #ifndef _FREE_LIST_H
#define _FREE_LIST_H
#include "block_io.h"
#define TRUE 1
void init_free_list(block_id head, block_count blocks);
int check_free_list(block_id head, block_count blocks);
block_id allocate_block(block_id head);
void free_block(block_id head, block_id block);
#endif
| 20.714286 | 55 | 0.810345 |
a9cd5fe134417d2fb0effed48750e6916744cb9e | 3,266 | h | C | sources/drivers/misc/mediatek/teei/V1.0/tz_driver/teei_client.h | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 2 | 2018-03-09T23:59:27.000Z | 2018-04-01T07:58:39.000Z | sources/drivers/misc/mediatek/teei/V1.0/tz_driver/teei_client.h | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | null | null | null | sources/drivers/misc/mediatek/teei/V1.0/tz_driver/teei_client.h | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 3 | 2017-06-24T20:23:09.000Z | 2018-03-25T04:30:11.000Z | #ifndef __TEEI_CLIENT_H_
#define __TEEI_CLIENT_H_
#define TEEI_CLIENT_FULL_PATH_DEV_NAME "/dev/teei_client"
#define TEEI_CLIENT_DEV "teei_client"
#define TEEI_CLIENT_IOC_MAGIC 0x775B777F /* "TEEI Client" */
/** IOCTL request */
/**
* @brief Encode command structure
*/
struct teei_client_encode_cmd {
unsigned int len;
unsigned int data;
/* unsigned long data; */
int offset;
int flags;
int param_type;
int encode_id;/* 命令参数编码数据块索引 */
/* int service_id; */
int session_id;
unsigned int cmd_id;
int value_flag;
int param_pos;
int param_pos_type;
int return_value;
int return_origin;
};
struct TEEC_UUID {
uint32_t timeLow;
uint16_t timeMid;
uint16_t timeHiAndVersion;
uint8_t clockSeqAndNode[8];
};
/**
* @brief Session details structure
*/
struct ser_ses_id {
/* int service_id; */
int session_id;
struct TEEC_UUID uuid;
int return_value;
int return_origin;
int paramtype;
int params[8];
};
/**
* @brief Session details structure
*/
struct user_ses_init {
int session_id;
};
struct ctx_data {
char name[255]; /* context name */
int ctx_ret; /* context return */
};
/**
* @brief Shared memory information for the session
*/
struct teei_session_shared_mem_info {
/* unsigned long service_id; */
unsigned int session_id;
u32 user_mem_addr;
};
/**
* @brief Shared memory used for smc processing
*/
struct teei_smc_cdata {
int cmd_addr;
int size;
int valid_flag;
int ret_val;
};
/* For general service */
#define TEEI_CLIENT_IOCTL_SEND_CMD_REQ \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 3, struct teei_client_encode_cmd)
#define TEEI_CLIENT_IOCTL_SES_OPEN_REQ \
_IOW(TEEI_CLIENT_IOC_MAGIC, 4, struct ser_ses_id)
#define TEEI_CLIENT_IOCTL_SES_CLOSE_REQ \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 5, struct ser_ses_id)
#define TEEI_CLIENT_IOCTL_SHR_MEM_FREE_REQ \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 6, struct teei_session_shared_mem_info)
#define TEEI_CLIENT_IOCTL_ENC_UINT32 \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 7, struct teei_client_encode_cmd)
#define TEEI_CLIENT_IOCTL_ENC_ARRAY \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 8, struct teei_client_encode_cmd)
#define TEEI_CLIENT_IOCTL_ENC_ARRAY_SPACE \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 9, struct teei_client_encode_cmd)
#define TEEI_CLIENT_IOCTL_ENC_MEM_REF \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 10, struct teei_client_encode_cmd)
#define TEEI_CLIENT_IOCTL_DEC_UINT32 \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 11, struct teei_client_encode_cmd)
#define TEEI_CLIENT_IOCTL_DEC_ARRAY_SPACE \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 12, struct teei_client_encode_cmd)
#define TEEI_CLIENT_IOCTL_OPERATION_RELEASE \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 13, struct teei_client_encode_cmd)
#define TEEI_CLIENT_IOCTL_SHR_MEM_ALLOCATE_REQ \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 14, struct teei_session_shared_mem_info)
#define TEEI_CLIENT_IOCTL_GET_DECODE_TYPE \
_IOWR(TEEI_CLIENT_IOC_MAGIC, 15, struct teei_client_encode_cmd)
/* add by lodovico */
#define TEEI_CLIENT_IOCTL_INITCONTEXT_REQ \
_IOW(TEEI_CLIENT_IOC_MAGIC, 16, struct ctx_data)
#define TEEI_CLIENT_IOCTL_CLOSECONTEXT_REQ \
_IOW(TEEI_CLIENT_IOC_MAGIC, 17, struct ctx_data)
/* add end */
#define TEEI_CLIENT_IOCTL_SES_INIT_REQ \
_IOW(TEEI_CLIENT_IOC_MAGIC, 18, struct user_ses_init)
#define TEEI_GET_TEEI_CONFIG_STAT \
_IO(TEEI_CLIENT_IOC_MAGIC, 0x1001)
#endif /* __TEEI_CLIENT_H_ */
| 26.33871 | 70 | 0.79455 |
8024e30e861b85e84c4411432c6b8424435da71f | 17,957 | h | C | Library/UsbHostLib/INCLUDE/inc_mass/UmasScsi.h | TeYenWu/AD5933_Keil | 41024aa9a84a90f90b855afde0526e25efafedf5 | [
"Apache-2.0"
] | 1 | 2020-12-26T13:24:56.000Z | 2020-12-26T13:24:56.000Z | Library/UsbHostLib/INCLUDE/inc_mass/UmasScsi.h | TeYenWu/AD5933_Keil | 41024aa9a84a90f90b855afde0526e25efafedf5 | [
"Apache-2.0"
] | null | null | null | Library/UsbHostLib/INCLUDE/inc_mass/UmasScsi.h | TeYenWu/AD5933_Keil | 41024aa9a84a90f90b855afde0526e25efafedf5 | [
"Apache-2.0"
] | null | null | null | /*
* scsi.h Copyright (C) 1992 Drew Eckhardt
* Copyright (C) 1993, 1994, 1995, 1998, 1999 Eric Youngdale
* generic SCSI package header file by
* Initial versions: Drew Eckhardt
* Subsequent revisions: Eric Youngdale
*
* <drew@colorado.edu>
*
* Modified by Eric Youngdale eric@andante.org to
* add scatter-gather, multiple outstanding request, and other
* enhancements.
*/
#ifndef _SCSI_H_
#define _SCSI_H_
/// @cond HIDDEN_SYMBOLS
/*
* Some of the public constants are being moved to this file.
* We include it here so that what came from where is transparent.
*/
/*
* SCSI opcodes
*/
#define TEST_UNIT_READY 0x00
#define REZERO_UNIT 0x01
#define REQUEST_SENSE 0x03
#define FORMAT_UNIT 0x04
#define READ_BLOCK_LIMITS 0x05
#define REASSIGN_BLOCKS 0x07
#define READ_6 0x08
#define WRITE_6 0x0a
#define SEEK_6 0x0b
#define READ_REVERSE 0x0f
#define WRITE_FILEMARKS 0x10
#define SPACE 0x11
#define INQUIRY 0x12
#define RECOVER_BUFFERED_DATA 0x14
#define MODE_SELECT 0x15
#define RESERVE 0x16
#define RELEASE 0x17
#define COPY 0x18
#define ERASE 0x19
#define MODE_SENSE 0x1a
#define START_STOP 0x1b
#define RECEIVE_DIAGNOSTIC 0x1c
#define SEND_DIAGNOSTIC 0x1d
#define ALLOW_MEDIUM_REMOVAL 0x1e
#define SET_WINDOW 0x24
#define READ_CAPACITY 0x25
#define READ_10 0x28
#define WRITE_10 0x2a
#define SEEK_10 0x2b
#define WRITE_VERIFY 0x2e
#define VERIFY 0x2f
#define SEARCH_HIGH 0x30
#define SEARCH_EQUAL 0x31
#define SEARCH_LOW 0x32
#define SET_LIMITS 0x33
#define PRE_FETCH 0x34
#define READ_POSITION 0x34
#define SYNCHRONIZE_CACHE 0x35
#define LOCK_UNLOCK_CACHE 0x36
#define READ_DEFECT_DATA 0x37
#define MEDIUM_SCAN 0x38
#define COMPARE 0x39
#define COPY_VERIFY 0x3a
#define WRITE_BUFFER 0x3b
#define READ_BUFFER 0x3c
#define UPDATE_BLOCK 0x3d
#define READ_LONG 0x3e
#define WRITE_LONG 0x3f
#define CHANGE_DEFINITION 0x40
#define WRITE_SAME 0x41
#define READ_TOC 0x43
#define LOG_SELECT 0x4c
#define LOG_SENSE 0x4d
#define MODE_SELECT_10 0x55
#define RESERVE_10 0x56
#define RELEASE_10 0x57
#define MODE_SENSE_10 0x5a
#define PERSISTENT_RESERVE_IN 0x5e
#define PERSISTENT_RESERVE_OUT 0x5f
#define MOVE_MEDIUM 0xa5
#define READ_12 0xa8
#define WRITE_12 0xaa
#define WRITE_VERIFY_12 0xae
#define SEARCH_HIGH_12 0xb0
#define SEARCH_EQUAL_12 0xb1
#define SEARCH_LOW_12 0xb2
#define READ_ELEMENT_STATUS 0xb8
#define SEND_VOLUME_TAG 0xb6
#define WRITE_LONG_2 0xea
/*
* Status codes
*/
#define GOOD 0x00
#define CHECK_CONDITION 0x01
#define CONDITION_GOOD 0x02
#define BUSY 0x04
#define INTERMEDIATE_GOOD 0x08
#define INTERMEDIATE_C_GOOD 0x0a
#define RESERVATION_CONFLICT 0x0c
#define COMMAND_TERMINATED 0x11
#define QUEUE_FULL 0x14
#define STATUS_MASK 0x3e
/*
* SENSE KEYS
*/
#define NO_SENSE 0x00
#define RECOVERED_ERROR 0x01
#define NOT_READY 0x02
#define MEDIUM_ERROR 0x03
#define HARDWARE_ERROR 0x04
#define ILLEGAL_REQUEST 0x05
#define UNIT_ATTENTION 0x06
#define DATA_PROTECT 0x07
#define BLANK_CHECK 0x08
#define COPY_ABORTED 0x0a
#define ABORTED_COMMAND 0x0b
#define VOLUME_OVERFLOW 0x0d
#define MISCOMPARE 0x0e
/*
* DEVICE TYPES
*/
#define TYPE_DISK 0x00
#define TYPE_TAPE 0x01
#define TYPE_PROCESSOR 0x03 /* HP scanners use this */
#define TYPE_WORM 0x04 /* Treated as ROM by our system */
#define TYPE_CDROM 0x05
#define TYPE_SCANNER 0x06
#define TYPE_MOD 0x07 /* Magneto-optical disk -
* - treated as TYPE_DISK */
#define TYPE_MEDIUM_CHANGER 0x08
#define TYPE_COMM 0x09 /* Communications device */
#define TYPE_ENCLOSURE 0x0d /* Enclosure Services Device */
#define TYPE_NO_LUN 0x7f
/*
* MESSAGE CODES
*/
#define COMMAND_COMPLETE 0x00
#define EXTENDED_MESSAGE 0x01
#define EXTENDED_MODIFY_DATA_POINTER 0x00
#define EXTENDED_SDTR 0x01
#define EXTENDED_EXTENDED_IDENTIFY 0x02 /* SCSI-I only */
#define EXTENDED_WDTR 0x03
#define SAVE_POINTERS 0x02
#define RESTORE_POINTERS 0x03
#define DISCONNECT 0x04
#define INITIATOR_ERROR 0x05
#define ABORT 0x06
#define MESSAGE_REJECT 0x07
#define NOP 0x08
#define MSG_PARITY_ERROR 0x09
#define LINKED_CMD_COMPLETE 0x0a
#define LINKED_FLG_CMD_COMPLETE 0x0b
#define BUS_DEVICE_RESET 0x0c
#define INITIATE_RECOVERY 0x0f /* SCSI-II only */
#define RELEASE_RECOVERY 0x10 /* SCSI-II only */
#define SIMPLE_QUEUE_TAG 0x20
#define HEAD_OF_QUEUE_TAG 0x21
#define ORDERED_QUEUE_TAG 0x22
/*
* Here are some scsi specific ioctl commands which are sometimes useful.
*/
/* These are a few other constants only used by scsi devices */
#define SCSI_IOCTL_GET_IDLUN 0x5382
/* Used to turn on and off tagged queuing for scsi devices */
#define SCSI_IOCTL_TAGGED_ENABLE 0x5383
#define SCSI_IOCTL_TAGGED_DISABLE 0x5384
/* Used to obtain the host number of a device. */
#define SCSI_IOCTL_PROBE_HOST 0x5385
/* Used to get the bus number for a device */
#define SCSI_IOCTL_GET_BUS_NUMBER 0x5386
/* copied from scatterlist.h, and remove scatterlist.h */
typedef struct scatterlist
{
char *address; /* Location data is to be transferred to */
char *alt_address; /* Location of actual if address is a
* dma indirect buffer. NULL otherwise */
uint32_t length;
} SCATTER_LIST_T;
#define ISA_DMA_THRESHOLD (0x00ffffff)
/*
* These are the values that the SCpnt->sc_data_direction and
* SRpnt->sr_data_direction can take. These need to be set
* The SCSI_DATA_UNKNOWN value is essentially the default.
* In the event that the command creator didn't bother to
* set a value, you will see SCSI_DATA_UNKNOWN.
*/
#define SCSI_DATA_UNKNOWN 0
#define SCSI_DATA_WRITE 1
#define SCSI_DATA_READ 2
#define SCSI_DATA_NONE 3
/*
* Some defs, in case these are not defined elsewhere.
*/
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifdef DEBUG
#define SCSI_TIMEOUT (5*HZ)
#else
#define SCSI_TIMEOUT (2*HZ)
#endif
/*
* Use these to separate status msg and our bytes
*
* These are set by:
*
* status byte = set from target device
* msg_byte = return status from host adapter itself.
* host_byte = set by low-level driver to indicate status.
* driver_byte = set by mid-level.
*/
#define status_byte(result) (((result) >> 1) & 0x1f)
#define msg_byte(result) (((result) >> 8) & 0xff)
#define host_byte(result) (((result) >> 16) & 0xff)
#define driver_byte(result) (((result) >> 24) & 0xff)
#define suggestion(result) (driver_byte(result) & SUGGEST_MASK)
#define sense_class(sense) (((sense) >> 4) & 0x7)
#define sense_error(sense) ((sense) & 0xf)
#define sense_valid(sense) ((sense) & 0x80);
#define NEEDS_RETRY 0x2001
#define SUCCESS 0x2002
#define FAILED 0x2003
#define QUEUED 0x2004
#define SOFT_ERROR 0x2005
#define ADD_TO_MLQUEUE 0x2006
/*
* These are the values that scsi_cmd->state can take.
*/
#define SCSI_STATE_TIMEOUT 0x1000
#define SCSI_STATE_FINISHED 0x1001
#define SCSI_STATE_FAILED 0x1002
#define SCSI_STATE_QUEUED 0x1003
#define SCSI_STATE_UNUSED 0x1006
#define SCSI_STATE_DISCONNECTING 0x1008
#define SCSI_STATE_INITIALIZING 0x1009
#define SCSI_STATE_BHQUEUE 0x100a
#define SCSI_STATE_MLQUEUE 0x100b
/*
* These are the values that the owner field can take.
* They are used as an indication of who the command belongs to.
*/
#define SCSI_OWNER_HIGHLEVEL 0x100
#define SCSI_OWNER_MIDLEVEL 0x101
#define SCSI_OWNER_LOWLEVEL 0x102
#define SCSI_OWNER_ERROR_HANDLER 0x103
#define SCSI_OWNER_BH_HANDLER 0x104
#define SCSI_OWNER_NOBODY 0x105
#define COMMAND_SIZE(opcode) scsi_command_size[((opcode) >> 5) & 7]
#define IDENTIFY_BASE 0x80
#define IDENTIFY(can_disconnect, lun) (IDENTIFY_BASE |\
((can_disconnect) ? 0x40 : 0) |\
((lun) & 0x07))
/*
* the return of the status word will be in the following format :
* The low byte is the status returned by the SCSI command,
* with vendor specific bits masked.
*
* The next byte is the message which followed the SCSI status.
* This allows a stos to be used, since the Intel is a little
* endian machine.
*
* The final byte is a host return code, which is one of the following.
*
* IE
* lsb msb
* status msg host code
*
* Our errors returned by OUR driver, NOT SCSI message. Or'd with
* SCSI message passed back to driver <IF any>.
*/
#define DID_OK 0x00 /* NO error */
#define DID_NO_CONNECT 0x01 /* Couldn't connect before timeout period */
#define DID_BUS_BUSY 0x02 /* BUS stayed busy through time out period */
#define DID_TIME_OUT 0x03 /* TIMED OUT for other reason */
#define DID_BAD_TARGET 0x04 /* BAD target. */
#define DID_ABORT 0x05 /* Told to abort for some other reason */
#define DID_PARITY 0x06 /* Parity error */
#define DID_ERROR 0x07 /* Internal error */
#define DID_RESET 0x08 /* Reset by somebody. */
#define DID_BAD_INTR 0x09 /* Got an interrupt we weren't expecting. */
#define DID_PASSTHROUGH 0x0a /* Force command past mid-layer */
#define DID_SOFT_ERROR 0x0b /* The low level driver just wish a retry */
#define DRIVER_OK 0x00 /* Driver status */
/*
* These indicate the error that occurred, and what is available.
*/
#define DRIVER_BUSY 0x01
#define DRIVER_SOFT 0x02
#define DRIVER_MEDIA 0x03
#define DRIVER_ERROR 0x04
#define DRIVER_INVALID 0x05
#define DRIVER_TIMEOUT 0x06
#define DRIVER_HARD 0x07
#define DRIVER_SENSE 0x08
#define SUGGEST_RETRY 0x10
#define SUGGEST_ABORT 0x20
#define SUGGEST_REMAP 0x30
#define SUGGEST_DIE 0x40
#define SUGGEST_SENSE 0x80
#define SUGGEST_IS_OK 0xff
#define DRIVER_MASK 0x0f
#define SUGGEST_MASK 0xf0
#define MAX_COMMAND_SIZE 12
#define SCSI_SENSE_BUFFERSIZE 64
/*
* SCSI command sets
*/
#define SCSI_UNKNOWN 0
#define SCSI_1 1
#define SCSI_1_CCS 2
#define SCSI_2 3
#define SCSI_3 4
/*
* Every SCSI command starts with a one byte OP-code.
* The next byte's high three bits are the LUN of the
* device. Any multi-byte quantities are stored high byte
* first, and may have a 5 bit MSB in the same byte
* as the LUN.
*/
/*
* As the scsi do command functions are intelligent, and may need to
* redo a command, we need to keep track of the last command
* executed on each one.
*/
#define WAS_RESET 0x01
#define WAS_TIMEDOUT 0x02
#define WAS_SENSE 0x04
#define IS_RESETTING 0x08
#define IS_ABORTING 0x10
#define ASKED_FOR_SENSE 0x20
#define SYNC_RESET 0x40
/*
* Add some typedefs so that we can prototyope a bunch of the functions.
*/
struct scsi_cmnd;
struct scsi_request;
struct umas_data;
#define SCSI_CMND_MAGIC 0xE25C23A5
#define SCSI_REQ_MAGIC 0x75F6D354
#define RQ_INACTIVE (-1)
#define RQ_ACTIVE 1
#define RQ_SCSI_BUSY 0xffff
#define RQ_SCSI_DONE 0xfffe
#define RQ_SCSI_DISCONNECTING 0xffe0
/*
* Ok, this is an expanded form so that we can use the same
* request for paging requests when that is implemented. In
* paging, 'bh' is NULL, and the semaphore is used to wait
* for read/write completion.
*/
struct request
{
int cmd; /* READ or WRITE */
int errors;
uint32_t start_time;
uint32_t sector;
uint32_t nr_sectors;
uint32_t hard_sector, hard_nr_sectors;
uint32_t nr_segments;
uint32_t nr_hw_segments;
uint32_t current_nr_sectors;
void *special;
char *buffer;
struct buffer_head *bh;
struct buffer_head *bhtail;
};
/*
* The SCSI_CMD_T structure is used by scsi.c internally, and for communication
* with low level drivers that support multiple outstanding commands.
*/
typedef struct scsi_pointer
{
char *ptr; /* data pointer */
int this_residual; /* left in this buffer */
struct scatterlist *buffer; /* which buffer */
int buffers_residual; /* how many buffers left */
volatile int Status;
volatile int Message;
volatile int have_data_in;
volatile int sent_command;
volatile int phase;
} Scsi_Pointer;
/*
* FIXME(eric) - one of the great regrets that I have is that I failed to define
* these structure elements as something like sc_foo instead of foo. This would
* make it so much easier to grep through sources and so forth. I propose that
* all new elements that get added to these structures follow this convention.
* As time goes on and as people have the stomach for it, it should be possible to
* go back and retrofit at least some of the elements here with with the prefix.
*/
typedef struct scsi_cmnd
{
struct umas_data *umas;
/*
* A SCSI Command is assigned a nonzero serial_number when internal_cmnd
* passes it to the driver's queue command function. The serial_number
* is cleared when scsi_done is entered indicating that the command has
* been completed. If a timeout occurs, the serial number at the moment
* of timeout is copied into serial_number_at_timeout. By subsequently
* comparing the serial_number and serial_number_at_timeout fields
* during abort or reset processing, we can detect whether the command
* has already completed. This also detects cases where the command has
* completed and the SCSI Command structure has already being reused
* for another command, so that we can avoid incorrectly aborting or
* resetting the new command.
*/
uint32_t serial_number;
uint32_t target;
uint32_t lun;
uint32_t channel;
uint8_t cmd_len;
uint8_t old_cmd_len;
uint8_t sc_data_direction;
uint8_t sc_old_data_direction;
/* These elements define the operation we are about to perform */
uint8_t cmnd[MAX_COMMAND_SIZE];
uint32_t request_bufflen; /* Actual request size */
uint8_t *request_buff; /* Actual requested buffer */
/* These elements define the operation we ultimately want to perform */
uint8_t data_cmnd[MAX_COMMAND_SIZE];
uint16_t old_use_sg; /* We save use_sg here when requesting sense info */
uint16_t use_sg; /* Number of pieces of scatter-gather */
uint16_t sglist_len; /* size of malloc'd scatter-gather list */
uint32_t bufflen; /* Size of data buffer */
void *buffer; /* Data buffer */
uint32_t transfersize; /* How much we are guaranteed to transfer
* with each SCSI transfer (ie, between
* disconnect reconnects.
* Probably == sector size */
struct request request; /* A copy of the command we are working on */
uint8_t sense_buffer[SCSI_SENSE_BUFFERSIZE];
/* obtained by REQUEST SENSE when CHECK
* CONDITION is received on original
* command (auto-sense) */
int result; /* Status code from lower level driver */
} SCSI_CMD_T;
/*
* Flag bit for the internal_timeout array
*/
#define NORMAL_TIMEOUT 0
/*
* Definitions and prototypes used for scsi mid-level queue.
*/
#define SCSI_MLQUEUE_HOST_BUSY 0x1055
#define SCSI_MLQUEUE_DEVICE_BUSY 0x1056
/* old style reset request from external source (private to sg.c and
* scsi_error.c, supplied by scsi_obsolete.c)
* */
#define SCSI_TRY_RESET_DEVICE 1
#define SCSI_TRY_RESET_BUS 2
#define SCSI_TRY_RESET_HOST 3
/// @endcond HIDDEN_SYMBOLS
#endif /* _SCSI_H_ */
| 33.753759 | 91 | 0.620816 |
b791336b568654f12f101c43e255c99ced512125 | 4,287 | c | C | shared-bindings/displayio/__init__.c | Nicell/circuitpython | 3cf96a554df1a5b473650c3230861d44bafa6d9f | [
"MIT"
] | 1 | 2020-09-28T19:03:58.000Z | 2020-09-28T19:03:58.000Z | shared-bindings/displayio/__init__.c | Nicell/circuitpython | 3cf96a554df1a5b473650c3230861d44bafa6d9f | [
"MIT"
] | null | null | null | shared-bindings/displayio/__init__.c | Nicell/circuitpython | 3cf96a554df1a5b473650c3230861d44bafa6d9f | [
"MIT"
] | 1 | 2021-08-03T23:03:42.000Z | 2021-08-03T23:03:42.000Z | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Scott Shawcroft for Adafruit Industries
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdint.h>
#include "py/obj.h"
#include "py/runtime.h"
#include "shared-bindings/displayio/__init__.h"
#include "shared-bindings/displayio/Bitmap.h"
#include "shared-bindings/displayio/ColorConverter.h"
#include "shared-bindings/displayio/Display.h"
#include "shared-bindings/displayio/EPaperDisplay.h"
#include "shared-bindings/displayio/FourWire.h"
#include "shared-bindings/displayio/Group.h"
#include "shared-bindings/displayio/I2CDisplay.h"
#include "shared-bindings/displayio/OnDiskBitmap.h"
#include "shared-bindings/displayio/Palette.h"
#include "shared-bindings/displayio/ParallelBus.h"
#include "shared-bindings/displayio/Shape.h"
#include "shared-bindings/displayio/TileGrid.h"
//| """Native helpers for driving displays
//|
//| The `displayio` module contains classes to manage display output
//| including synchronizing with refresh rates and partial updating."""
//|
//| def release_displays() -> Any:
//| """Releases any actively used displays so their busses and pins can be used again. This will also
//| release the builtin display on boards that have one. You will need to reinitialize it yourself
//| afterwards. This may take seconds to complete if an active EPaperDisplay is refreshing.
//|
//| Use this once in your code.py if you initialize a display. Place it right before the
//| initialization so the display is active as long as possible."""
//| ...
//|
STATIC mp_obj_t displayio_release_displays(void) {
common_hal_displayio_release_displays();
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_0(displayio_release_displays_obj, displayio_release_displays);
STATIC const mp_rom_map_elem_t displayio_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_displayio) },
{ MP_ROM_QSTR(MP_QSTR_Bitmap), MP_ROM_PTR(&displayio_bitmap_type) },
{ MP_ROM_QSTR(MP_QSTR_ColorConverter), MP_ROM_PTR(&displayio_colorconverter_type) },
{ MP_ROM_QSTR(MP_QSTR_Display), MP_ROM_PTR(&displayio_display_type) },
{ MP_ROM_QSTR(MP_QSTR_EPaperDisplay), MP_ROM_PTR(&displayio_epaperdisplay_type) },
{ MP_ROM_QSTR(MP_QSTR_Group), MP_ROM_PTR(&displayio_group_type) },
{ MP_ROM_QSTR(MP_QSTR_OnDiskBitmap), MP_ROM_PTR(&displayio_ondiskbitmap_type) },
{ MP_ROM_QSTR(MP_QSTR_Palette), MP_ROM_PTR(&displayio_palette_type) },
{ MP_ROM_QSTR(MP_QSTR_Shape), MP_ROM_PTR(&displayio_shape_type) },
{ MP_ROM_QSTR(MP_QSTR_TileGrid), MP_ROM_PTR(&displayio_tilegrid_type) },
{ MP_ROM_QSTR(MP_QSTR_FourWire), MP_ROM_PTR(&displayio_fourwire_type) },
{ MP_ROM_QSTR(MP_QSTR_I2CDisplay), MP_ROM_PTR(&displayio_i2cdisplay_type) },
{ MP_ROM_QSTR(MP_QSTR_ParallelBus), MP_ROM_PTR(&displayio_parallelbus_type) },
{ MP_ROM_QSTR(MP_QSTR_release_displays), MP_ROM_PTR(&displayio_release_displays_obj) },
};
STATIC MP_DEFINE_CONST_DICT(displayio_module_globals, displayio_module_globals_table);
const mp_obj_module_t displayio_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&displayio_module_globals,
};
| 46.096774 | 105 | 0.770236 |
a264003715f77505689fbb9c0f032d90bf82a1ec | 52,788 | c | C | cefore-0.8.3a/src/lib/cef_pit.c | Marie673/ICN_Proxy | 25bcdf1b7fe34d323b0bf4b8b48ad7787e3d16ef | [
"MIT"
] | 3 | 2021-06-28T08:39:04.000Z | 2022-01-12T08:38:52.000Z | cefore-0.8.3a/src/lib/cef_pit.c | Marie673/ICN_Proxy | 25bcdf1b7fe34d323b0bf4b8b48ad7787e3d16ef | [
"MIT"
] | 3 | 2021-07-22T00:48:21.000Z | 2021-08-05T09:45:52.000Z | cefore-0.8.3a/src/lib/cef_pit.c | Marie673/ICN_Proxy | 25bcdf1b7fe34d323b0bf4b8b48ad7787e3d16ef | [
"MIT"
] | 6 | 2021-06-28T08:39:26.000Z | 2022-02-24T10:10:10.000Z | /*
* Copyright (c) 2016-2021, National Institute of Information and Communications
* Technology (NICT). 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 NICT 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 NICT 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 NICT 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.
*/
/*
* cef_pit.c
*/
#define __CEF_PIT_SOURECE__
//#define __PIT_DEBUG__
//#define __RESTRICT__
//#define __INTEREST__
//#define __PIT_CLEAN__
/****************************************************************************************
Include Files
****************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <sys/time.h>
#include <cefore/cef_pit.h>
#include <cefore/cef_face.h>
#include <cefore/cef_client.h>
#include <cefore/cef_log.h>
/****************************************************************************************
Macros
****************************************************************************************/
#define CefC_Pit_False 1 /* False */
#define CefC_Pit_True 1 /* True */
#define CefC_Maximum_Lifetime 16000 /* Maximum lifetime [ms] */
/****************************************************************************************
Structures Declaration
****************************************************************************************/
/****************************************************************************************
State Variables
****************************************************************************************/
#ifdef CefC_Debug
static char pit_dbg_msg[2048];
#endif // CefC_Debug
#ifdef CefC_Dtc
CefT_Dtc_Pit_List* dtc_pit = NULL;
#endif // CefC_Dtc
#ifdef __PIT_DEBUG__
//static char pit_dbg[2048];
#endif
static uint32_t ccninfo_reply_timeout = CefC_Default_CcninfoReplyTimeout;
//0.8.3
static uint32_t symbolic_max_lifetime;
static uint32_t regular_max_lifetime;
#define CefC_IR_SUPPORT_NUM 3
uint8_t IR_PRIORITY_TBL[CefC_IR_SUPPORT_NUM] = {
CefC_IR_HOPLIMIT_EXCEEDED,
CefC_IR_NO_ROUTE,
CefC_IR_CONGESION
};
/****************************************************************************************
Static Function Declaration
****************************************************************************************/
/*--------------------------------------------------------------------------------------
Looks up and creates the specified Down Face entry
----------------------------------------------------------------------------------------*/
static int /* Returns 1 if the return entry is new */
cef_pit_entry_down_face_lookup (
CefT_Pit_Entry* entry, /* PIT entry */
uint16_t faceid, /* Face-ID */
CefT_Down_Faces** rt_dnface, /* Down Face entry to return */
uint64_t nonce, /* Nonce */
uint8_t longlife_f /* Long Life Interest */
);
/*--------------------------------------------------------------------------------------
Looks up and creates the specified Up Face entry
----------------------------------------------------------------------------------------*/
static int /* Returns 1 if the return entry is new */
cef_pit_entry_up_face_lookup (
CefT_Pit_Entry* entry, /* PIT entry */
uint16_t faceid, /* Face-ID */
CefT_Up_Faces** rt_face /* Up Face entry to return */
);
/*--------------------------------------------------------------------------------------
Cleanups PIT entry which expires the lifetime
----------------------------------------------------------------------------------------*/
static CefT_Pit_Entry*
cef_pit_cleanup (
CefT_Hash_Handle pit, /* PIT */
CefT_Pit_Entry* entry /* PIT entry */
);
#if 0
/*--------------------------------------------------------------------------------------
Cleanups PIT entry which expires the lifetime for Cefore-Router
----------------------------------------------------------------------------------------*/
static CefT_Pit_Entry*
cefrt_pit_cleanup (
CefT_Hash_Handle pit, /* PIT */
CefT_Pit_Entry* entry /* PIT entry */
);
#endif
/****************************************************************************************
****************************************************************************************/
/*--------------------------------------------------------------------------------------
Initialize the PIT module
----------------------------------------------------------------------------------------*/
void
cef_pit_init (
uint32_t reply_timeout, /* PIT lifetime(seconds) at "full discovery request" */
uint32_t symbolic_max_lt, /* Symbolic Interest max Lifetime 0.8.3 */
uint32_t regular_max_lt /* Regular Interest max Lifetime 0.8.3 */
){
ccninfo_reply_timeout = reply_timeout;
symbolic_max_lifetime = symbolic_max_lt;
regular_max_lifetime = regular_max_lt;
return;
}
/*--------------------------------------------------------------------------------------
Looks up and creates a PIT entry matching the specified Name
----------------------------------------------------------------------------------------*/
CefT_Pit_Entry* /* a PIT entry */
cef_pit_entry_lookup (
CefT_Hash_Handle pit, /* PIT */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh /* Parsed Option Header */
, unsigned char* ccninfo_pit, /* pit name for ccninfo ccninfo-03 */
int ccninfo_pit_len /* ccninfo pit length */
) {
CefT_Pit_Entry* entry;
unsigned char* tmp_name = NULL;
uint16_t tmp_name_len = 0;
#ifdef __PIT_DEBUG__
fprintf (stderr, "[%s] IN\n",
"cef_pit_entry_lookup" );
#endif
if (pm->top_level_type == CefC_T_DISCOVERY) { /* for CCNINFO */
/* KEY: Name + NodeIdentifier + RequestID */
tmp_name_len = ccninfo_pit_len;
tmp_name = (unsigned char*)malloc( sizeof(char) * tmp_name_len );
memcpy( tmp_name, ccninfo_pit, tmp_name_len );
} else {
tmp_name = pm->name;
tmp_name_len = pm->name_len;
}
/* Searches a PIT entry */
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (pit, tmp_name, tmp_name_len);
#ifdef __PIT_DEBUG__
fprintf (stderr, "\t %p\n",
(void*)entry );
#endif
/* Creates a new PIT entry, if it dose not match */
if (entry == NULL) {
if(cef_hash_tbl_item_num_get(pit) == cef_hash_tbl_def_max_get(pit)) {
cef_log_write (CefC_Log_Warn,
"PIT table is full(PIT_SIZE = %d)\n", cef_hash_tbl_def_max_get(pit));
return (NULL);
}
entry = (CefT_Pit_Entry*) malloc (sizeof (CefT_Pit_Entry));
memset (entry, 0, sizeof (CefT_Pit_Entry));
entry->key = (unsigned char*) malloc (sizeof (char) * tmp_name_len);
entry->klen = tmp_name_len;
memcpy (entry->key, tmp_name, tmp_name_len);
entry->hashv = cef_hash_tbl_hashv_get (pit, entry->key, entry->klen);
entry->clean_us = cef_client_present_timeus_get () + 1000000;
cef_hash_tbl_item_set (pit, entry->key, entry->klen, entry);
entry->tp_variant = poh->tp_variant;
entry->nonce = 0;
entry->adv_lifetime_us = 0;
entry->drp_lifetime_us = 0;
//0.8.3
entry->hoplimit = 0;
entry->PitType = pm->InterestType;
entry->Last_chunk_num = 0;
entry->KIDR_len = pm->KeyIdRester_sel_len;
if ( entry->KIDR_len == 0 ) {
entry->KIDR_selector = NULL;
} else {
entry->KIDR_selector = (unsigned char*)malloc( entry->KIDR_len );
memcpy( entry->KIDR_selector, pm->KeyIdRester_selector, entry->KIDR_len );
}
entry->COBHR_len = pm->ObjHash_len;
if ( entry->COBHR_len == 0 ) {
entry->COBHR_selector = NULL;
} else {
entry->COBHR_selector = (unsigned char*)malloc( entry->COBHR_len );
memcpy( entry->COBHR_selector, pm->ObjHash, entry->COBHR_len );
}
#ifdef __RESTRICT__
printf( "%s entry->KIDR_len:%d entry->COBHR_len:%d\n", __func__, entry->KIDR_len, entry->COBHR_len );
#endif
}
#ifdef CefC_Debug
#if 0
{
int dbg_x;
sprintf (pit_dbg_msg, "[pit] Lookup the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
sprintf (pit_dbg_msg, "%s %02X", pit_dbg_msg, entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#else
{
int dbg_x;
int len = 0;
len = sprintf (pit_dbg_msg, "[pit] Lookup the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#endif
#endif // CefC_Debug
#ifdef __PIT_DEBUG__
{
int dbg_xx;
fprintf (stderr, "[" );
for (dbg_xx = 0 ; dbg_xx < entry->klen ; dbg_xx++) {
fprintf (stderr, "%02X ", entry->key[dbg_xx]);
}
fprintf (stderr, "]\n" );
}
#endif // __PIT_DEBUG__
if (pm->top_level_type == CefC_T_DISCOVERY) { /* for CCNINFO */
free (tmp_name);
}
return (entry);
}
/*--------------------------------------------------------------------------------------
Searches a PIT entry matching the specified Name
----------------------------------------------------------------------------------------*/
CefT_Pit_Entry* /* a PIT entry */
cef_pit_entry_search (
CefT_Hash_Handle pit, /* PIT */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh /* Parsed Option Header */
, unsigned char* ccninfo_pit, /* pit name for ccninfo ccninfo-03 */
int ccninfo_pit_len /* ccninfo pit length */
) {
CefT_Pit_Entry* entry;
uint16_t name_len = pm->name_len;
unsigned char* tmp_name = NULL;
uint16_t tmp_name_len;
uint64_t now;
if (poh->symbolic_code_f) {
memcpy (&pm->name[name_len], &poh->symbolic_code, sizeof (struct value32x2_tlv));
name_len += sizeof (struct value32x2_tlv);
}
if (pm->top_level_type == CefC_T_DISCOVERY) { /* for CCNINFO */
/* KEY: Name + NodeIdentifier + RequestID */
tmp_name_len = ccninfo_pit_len;
tmp_name = (unsigned char*)malloc( sizeof(char) * tmp_name_len );
memcpy( tmp_name, ccninfo_pit, tmp_name_len );
} else {
tmp_name = pm->name;
tmp_name_len = pm->name_len;
}
#ifdef CefC_Debug
#if 0
{
int dbg_x;
sprintf (pit_dbg_msg, "[pit] Search the entry [");
for (dbg_x = 0 ; dbg_x < tmp_name_len ; dbg_x++) {
sprintf (pit_dbg_msg, "%s %02X", pit_dbg_msg, tmp_name[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#else
{
int dbg_x;
int len = 0;
len = sprintf (pit_dbg_msg, "[pit] Search the entry [");
for (dbg_x = 0 ; dbg_x < tmp_name_len ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", tmp_name[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#endif
#endif // CefC_Debug
/* Searches a PIT entry */
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (pit, tmp_name, tmp_name_len);
now = cef_client_present_timeus_get ();
if (entry != NULL) {
if (!entry->symbolic_f) {
entry->stole_f = 1;
}
/* for ccninfo "full discovery" */
if (poh->ccninfo_flag & CefC_CtOp_FullDisCover) {
entry->stole_f = 0;
}
#ifdef CefC_Debug
#if 0
{
int dbg_x;
sprintf (pit_dbg_msg, "[pit] Exact matched to the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
sprintf (pit_dbg_msg, "%s %02X", pit_dbg_msg, entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#else
{
int dbg_x;
int len = 0;
len = sprintf (pit_dbg_msg, "[pit] Exact matched to the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#endif
#endif // CefC_Debug
if (pm->top_level_type == CefC_T_DISCOVERY) { /* for CCNINFO */
free (tmp_name);
}
/* if (now > entry->adv_lifetime_us) { 20190822*/
if ((now > entry->adv_lifetime_us) && (poh->app_reg_f != CefC_App_DeRegPit)){ //20190822
return (NULL);
}
return (entry);
}
if (pm->chnk_num_f) {
uint16_t name_len_wo_chunk;
name_len_wo_chunk = tmp_name_len - (CefC_S_Type + CefC_S_Length + CefC_S_ChunkNum);
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (pit, tmp_name, name_len_wo_chunk);
if (entry != NULL) {
if (entry->symbolic_f) {
entry = cef_pit_cleanup (pit, entry);
#ifdef CefC_Debug
#if 0
{
int dbg_x;
if (entry) {
sprintf (pit_dbg_msg, "[pit] Partial matched to the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
sprintf (pit_dbg_msg,
"%s %02X", pit_dbg_msg, entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
} else {
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
}
}
#else
{
int dbg_x;
int len = 0;
if (entry) {
len = sprintf (pit_dbg_msg, "[pit] Partial matched to the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
} else {
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
}
}
#endif
#endif // CefC_Debug
if (pm->top_level_type == CefC_T_DISCOVERY) { /* for CCNINFO */
free (tmp_name);
}
if (now > entry->adv_lifetime_us) {
return (NULL);
}
return (entry);
}
}
}
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
#endif // CefC_Debug
if (pm->top_level_type == CefC_T_DISCOVERY) { /* for CCNINFO */
free (tmp_name);
}
return (NULL);
}
/*--------------------------------------------------------------------------------------
Searches a PIT entry matching the specified Name
----------------------------------------------------------------------------------------*/
CefT_Pit_Entry* /* a PIT entry */
cef_pit_entry_search_specified_name (
CefT_Hash_Handle pit, /* PIT */
unsigned char* sp_name, /* specified Name */
uint16_t sp_name_len, /* length of Name */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh, /* Parsed Option Header */
int match_type /* 0:Exact, 1:Prefix */
) {
CefT_Pit_Entry* entry;
uint16_t name_len = sp_name_len;
if (poh->symbolic_code_f) {
memcpy (&sp_name[name_len], &poh->symbolic_code, sizeof (struct value32x2_tlv));
name_len += sizeof (struct value32x2_tlv);
}
#ifdef CefC_Debug
#if 0
{
int dbg_x;
sprintf (pit_dbg_msg, "[pit] Search the entry [");
for (dbg_x = 0 ; dbg_x < name_len ; dbg_x++) {
sprintf (pit_dbg_msg, "%s %02X", pit_dbg_msg, sp_name[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#else
{
int dbg_x;
int len;
len = sprintf (pit_dbg_msg, "[pit] Search the entry [");
for (dbg_x = 0 ; dbg_x < name_len ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", sp_name[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#endif
#endif // CefC_Debug
/* Searches a PIT entry */
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (pit, sp_name, name_len);
if (entry != NULL) {
if (match_type) {
/* PrefixMatch */
if (pm->chnk_num_f) {
if (entry->symbolic_f) {
entry = cef_pit_cleanup (pit, entry);
}
}
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest, "[pit] Partial matched to the entry\n");
#endif // CefC_Debug
return (entry);
} else {
/* ExactMatch */
if (!entry->symbolic_f) {
entry->stole_f = 1;
}
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest, "[pit] Exact matched to the entry\n");
#endif // CefC_Debug
return (entry);
}
}
if (pm->chnk_num_f) {
uint16_t name_len_wo_chunk;
name_len_wo_chunk = name_len - (CefC_S_Type + CefC_S_Length + CefC_S_ChunkNum);
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (pit, pm->name, name_len_wo_chunk);
if (entry != NULL) {
if (entry->symbolic_f) {
entry = cef_pit_cleanup (pit, entry);
#ifdef CefC_Debug
#if 0
{
int dbg_x;
if (entry) {
sprintf (pit_dbg_msg, "[pit] Partial matched to the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
sprintf (pit_dbg_msg,
"%s %02X", pit_dbg_msg, entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
} else {
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
}
}
#else
{
int dbg_x;
int len = 0;
if (entry) {
len = sprintf (pit_dbg_msg, "[pit] Partial matched to the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
} else {
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
}
}
#endif
#endif // CefC_Debug
return (entry);
}
}
}
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
#endif // CefC_Debug
return (NULL);
}
/*--------------------------------------------------------------------------------------
Searches a PIT(for App) entry matching the specified Name --- Prefix(Longest) Match
----------------------------------------------------------------------------------------*/
CefT_Pit_Entry* /* a PIT entry */
cef_pit_entry_search_specified_name_for_app (
CefT_Hash_Handle pit, /* PIT */
unsigned char* sp_name, /* specified Name */
uint16_t sp_name_len, /* length of Name */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh /* Parsed Option Header */
) {
CefT_Pit_Entry* entry;
uint16_t name_len = sp_name_len;
unsigned char* msp;
unsigned char* mep;
uint16_t length;
if (poh->symbolic_code_f) {
memcpy (&sp_name[name_len], &poh->symbolic_code, sizeof (struct value32x2_tlv));
name_len += sizeof (struct value32x2_tlv);
}
#ifdef CefC_Debug
#if 0
{
int dbg_x;
sprintf (pit_dbg_msg, "[pit] Search the entry [");
for (dbg_x = 0 ; dbg_x < name_len ; dbg_x++) {
sprintf (pit_dbg_msg, "%s %02X", pit_dbg_msg, sp_name[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#else
{
int dbg_x;
int len = 0;
len = sprintf (pit_dbg_msg, "[pit] Search the entry [");
for (dbg_x = 0 ; dbg_x < name_len ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", sp_name[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#endif
#endif // CefC_Debug
/* Searches a PIT entry */
while (name_len > 0) {
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (pit, sp_name, name_len);
if (entry != NULL) {
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest, "[pit] Matched to the entry\n");
#endif // CefC_Debug
return (entry);
}
msp = sp_name;
mep = sp_name + name_len - 1;
while (msp < mep) {
memcpy (&length, &msp[CefC_S_Length], CefC_S_Length);
length = ntohs (length);
if (msp + CefC_S_Type + CefC_S_Length + length < mep) {
msp += CefC_S_Type + CefC_S_Length + length;
} else {
break;
}
}
name_len = msp - sp_name;
}
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
#endif // CefC_Debug
return (NULL);
}
#ifdef CefC_Debug
void
cef_pit_entry_print (
CefT_Hash_Handle pit /* PIT */
) {
int pit_num, cnt, index;
CefT_Pit_Entry* entry;
int pit_max = cef_hash_tbl_item_max_idx_get (pit);
pit_num = cef_hash_tbl_item_num_get (pit);
fprintf(stderr,"===== PIT (entry=%d) =====\n", pit_num);
for (index = 0, cnt = 0; (cnt < pit_num && index < pit_max); index++) {
entry = (CefT_Pit_Entry*)cef_hash_tbl_item_get_from_index (pit, index);
if (entry != NULL) {
if (entry->klen != -1) {
fprintf(stderr," (%d)(%d) len=%d [", index, cnt, entry->klen);
{
int dbg_x;
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
fprintf (stderr, "%02x ", entry->key[dbg_x]);
}
fprintf (stderr, "]\n");
}
cnt++;
} else {
fprintf(stderr," (%d) len=-1 **************************************\n", index);
}
}
}
fprintf(stderr,"==============================\n");
return;
}
#endif // CefC_Debug
#if 0
/*--------------------------------------------------------------------------------------
Searches a PIT entry matching the specified Name for Cefore-Router
----------------------------------------------------------------------------------------*/
CefT_Pit_Entry* /* a PIT entry */
cefrt_pit_entry_search (
CefT_Hash_Handle pit, /* PIT */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh /* Parsed Option Header */
) {
CefT_Pit_Entry* entry;
uint16_t name_len = pm->name_len;
/* Searches a PIT entry */
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (pit, pm->name, name_len);
if (entry != NULL) {
entry->stole_f = CefC_Pit_True;
return (entry);
}
if (pm->chnk_num_f) {
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (
pit, pm->name, name_len - (CefC_S_Type + CefC_S_Length + CefC_S_ChunkNum));
if (entry != NULL) {
if (entry->symbolic_f) {
entry = cefrt_pit_cleanup (pit, entry);
return (entry);
}
}
}
return (NULL);
}
#endif
/*--------------------------------------------------------------------------------------
Looks up and creates the specified Down Face entry
----------------------------------------------------------------------------------------*/
int /* Returns 1 if the return entry is new */
cef_pit_entry_down_face_update (
CefT_Pit_Entry* entry, /* PIT entry */
uint16_t faceid, /* Face-ID */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh, /* Parsed Option Header */
unsigned char* msg, /* cefore packet */
int Resend_method /* Resend method 0.8.3 */
) {
CefT_Down_Faces* face;
#ifdef __PIT_DEBUG__
fprintf (stderr, "[%s] IN faceid=%d\n",
"cef_pit_entry_down_face_update", faceid );
#endif
int new_downface_f = 0;
int forward_interest_f = 0;
struct timeval now;
uint64_t nowt_us;
uint64_t max_lifetime_us;
uint64_t prev_lifetime_us;
uint64_t extent_us;
uint16_t nw_lifetime_ms;
uint16_t new_lifetime_ms;
gettimeofday (&now, NULL);
nowt_us = now.tv_sec * 1000000llu + now.tv_usec;
/* Looks up a Down Face entry */
new_downface_f = cef_pit_entry_down_face_lookup (
entry, faceid, &face, pm->nonce, pm->org.longlife_f);
#ifdef __PIT_DEBUG__
fprintf (stderr, "\t new_downface_f=%d (1:NEW)\n",
new_downface_f );
fprintf (stderr, "\t face->lifetime_us= "FMTU64"\n", face->lifetime_us / 1000 );
#endif
/* Checks flags */
if (new_downface_f) {
face->nonce = pm->nonce;
} else {
if ((pm->nonce) && (pm->nonce == face->nonce)) {
#ifdef __PIT_DEBUG__
fprintf (stderr, "[%s] return(0) ((pm->nonce) && (pm->nonce == face->nonce))\n",
"cef_pit_entry_down_face_update" );
#endif
return (0);
}
face->nonce = pm->nonce;
}
if (pm->org.longlife_f) {
if (new_downface_f) {
entry->symbolic_f++;
}
}
#ifdef __PIT_DEBUG__
fprintf (stderr, "\t entry->symbolic_f=%d\n",
entry->symbolic_f );
#endif
#ifdef CefC_Ccninfo
/* for ccninfo */
if (pm->top_level_type == CefC_T_DISCOVERY) {
if (poh->ccninfo_flag & CefC_CtOp_FullDisCover)
poh->lifetime = ccninfo_reply_timeout * 1000;
else
poh->lifetime = CefC_Default_CcninfoReplyTimeout * 1000;
poh->lifetime_f = 1;
}
#endif //CefC_Ccninfo
/* Checks whether the life time is smaller than the limit */
#ifndef CefC_Nwproc
if ( entry->PitType != CefC_PIT_TYPE_Reg ) { //0.8.3
if (poh->lifetime > symbolic_max_lifetime) {
poh->lifetime = symbolic_max_lifetime;
}
} else {
if (poh->lifetime > regular_max_lifetime) {
poh->lifetime = regular_max_lifetime;
}
}
#else // CefC_Nwproc
if (!poh->nwproc_f) {
if ( entry->PitType != CefC_PIT_TYPE_Reg ) { //0.8.3
if (poh->lifetime > symbolic_max_lifetime) {
poh->lifetime = symbolic_max_lifetime;
}
} else {
if (poh->lifetime > regular_max_lifetime) {
poh->lifetime = regular_max_lifetime;
}
}
}
#endif // CefC_Nwproc
/* Updates Interest Lifetime of this PIT entry */
if (poh->lifetime_f) {
#ifdef CefC_Dtc
if (pm->app_comp == CefC_T_APP_DTC) {
extent_us = (uint64_t)poh->lifetime * 1000000llu;
} else {
extent_us = poh->lifetime * 1000;
}
#else // CefC_Dtc
extent_us = poh->lifetime * 1000;
#endif // CefC_Dtc
} else {
extent_us = CefC_Default_LifetimeUs;
}
prev_lifetime_us = face->lifetime_us;
face->lifetime_us = nowt_us + extent_us;
#ifdef __PIT_DEBUG__
fprintf (stderr, "\t Before\n" );
fprintf (stderr, "\t extent_us= "FMTU64"\n", extent_us / 1000 );
fprintf (stderr, "\t prev_lifetime_us= "FMTU64"\n", prev_lifetime_us / 1000 );
fprintf (stderr, "\t face->lifetime_us= "FMTU64"\n", face->lifetime_us / 1000 );
fprintf (stderr, "\t entry->drp_lifetime_us= "FMTU64"\n", entry->drp_lifetime_us / 1000 );
fprintf (stderr, "\t entry->adv_lifetime_us= "FMTU64"\n", entry->adv_lifetime_us / 1000 );
#endif
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest, "[pit] Lifetime = "FMTU64"\n", extent_us / 1000);
#endif // CefC_Debug
/* Checks the advertised lifetime to upstream */
if (face->lifetime_us > entry->drp_lifetime_us) {
#ifdef __PIT_DEBUG__
fprintf (stderr, "\t (face->lifetime_us > entry->drp_lifetime_us)\n" );
#endif
forward_interest_f = 1;
#ifndef CefC_Nwproc
entry->drp_lifetime_us = face->lifetime_us + 1000000;
#else // CefC_Nwproc
entry->drp_lifetime_us = face->lifetime_us + extent_us;
#endif // CefC_Nwproc
entry->adv_lifetime_us = face->lifetime_us;
} else {
#ifdef __PIT_DEBUG__
fprintf (stderr, "\t !(face->lifetime_us > entry->drp_lifetime_us)\n" );
#endif
#ifdef CefC_Ccninfo
if (pm->top_level_type == CefC_T_DISCOVERY) {
return (forward_interest_f);
}
#endif //CefC_Ccninfo
if (face->lifetime_us < prev_lifetime_us) {
#ifdef __PIT_DEBUG__
fprintf (stderr, "\t (face->lifetime_us < prev_lifetime_us)\n" );
#endif
face = &(entry->dnfaces);
max_lifetime_us = face->lifetime_us;
while (face->next) {
face = face->next;
if (face->lifetime_us > max_lifetime_us) {
max_lifetime_us = face->lifetime_us;
}
}
if (max_lifetime_us < entry->adv_lifetime_us) {
forward_interest_f = 1;
if (poh->lifetime_f) {
new_lifetime_ms = (max_lifetime_us - nowt_us) / 1000;
nw_lifetime_ms = htons (new_lifetime_ms);
memcpy (&msg[poh->lifetime_f], &nw_lifetime_ms, CefC_S_Lifetime);
#ifdef __PIT_DEBUG__
fprintf (stderr, "\t Lifetime (update)= %d\n", new_lifetime_ms );
#endif
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest,
"[pit] Lifetime (update) = "FMTU64"\n", nw_lifetime_ms);
#endif // CefC_Debug
}
entry->adv_lifetime_us = max_lifetime_us;
entry->drp_lifetime_us = max_lifetime_us + 1000000;
}
/* If the other down stream node exists, we do not forward */
/* the Interest with lifetime. */
if ((poh->lifetime_f) && (poh->lifetime == 0)) {
cef_pit_down_faceid_remove (entry, face->faceid);
}
}
}
#ifdef __PIT_DEBUG__
fprintf (stderr, "[%s] Before (%d) forward (yes=1/no=0)\n",
"cef_pit_entry_down_face_update", forward_interest_f );
fprintf (stderr, "\t Resend_method:%s\n",
(Resend_method == CefC_IntRetrans_Type_RFC) ? "RFC":"SUP");
#endif
#if 1
//0.8.3 RFC
// forward_interest_f=0
// new_downface_f=0 Same Face:Retransmit
// new_downface_f=1 Not Same Face: Check HopLimit
// forward_interest_f=1
if ( Resend_method == CefC_IntRetrans_Type_RFC ) {
if ( forward_interest_f == 0 ) {
if ( new_downface_f == 0 ) {
forward_interest_f = 1;
} else {
if ( pm->hoplimit > entry->hoplimit ) {
forward_interest_f = 1;
}
}
} else { /* ( forward_interest_f == 1 ) */
if ( new_downface_f == 0 ) {
/* NOP */
} else { /* */
if ( pm->hoplimit <= entry->hoplimit ) {
forward_interest_f = 0;
}
}
}
}
/* Update HopLimit */
if ( (forward_interest_f == 1) && (pm->hoplimit > entry->hoplimit) ) {
entry->hoplimit = pm->hoplimit;
}
#endif
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest,
"[pit] forward (yes=1/no=0) = %d\n", forward_interest_f);
#endif
#ifdef __PIT_DEBUG__
fprintf (stderr, "\t After\n" );
fprintf (stderr, "\t extent_us= "FMTU64"\n", extent_us / 1000 );
fprintf (stderr, "\t prev_lifetime_us= "FMTU64"\n", prev_lifetime_us / 1000 );
fprintf (stderr, "\t face->lifetime_us= "FMTU64"\n", face->lifetime_us / 1000 );
fprintf (stderr, "\t entry->drp_lifetime_us= "FMTU64"\n", entry->drp_lifetime_us / 1000 );
fprintf (stderr, "\t entry->adv_lifetime_us= "FMTU64"\n", entry->adv_lifetime_us / 1000 );
fprintf (stderr, "[%s] OUT return(%d) forward (yes=1/no=0)\n",
"cef_pit_entry_down_face_update", forward_interest_f );
#endif
return (forward_interest_f);
}
/*--------------------------------------------------------------------------------------
Looks up and creates the specified Up Face entry
----------------------------------------------------------------------------------------*/
int /* Returns 1 if the return entry is new */
cef_pit_entry_up_face_update (
CefT_Pit_Entry* entry, /* PIT entry */
uint16_t faceid, /* Face-ID */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh /* Parsed Option Header */
) {
CefT_Up_Faces* face;
int new_create_f;
/* Looks up an Up Face entry */
new_create_f = cef_pit_entry_up_face_lookup (entry, faceid, &face);
/* If this entry has Symbolic Interest, always it forwards the Interest */
if (entry->symbolic_f) {
new_create_f = 1;
}
return (new_create_f);
}
/*--------------------------------------------------------------------------------------
Free the specified PIT entry
----------------------------------------------------------------------------------------*/
void
cef_pit_entry_free (
CefT_Hash_Handle pit, /* PIT */
CefT_Pit_Entry* entry /* PIT entry */
) {
CefT_Up_Faces* upface_next;
CefT_Up_Faces* upface = entry->upfaces.next;
CefT_Down_Faces* dnface_next;
CefT_Down_Faces* dnface = entry->dnfaces.next;
#ifdef __PIT_CLEAN__
fprintf( stderr, "[%s] IN entry->dnfacenum:%d\n", __func__, entry->dnfacenum );
#endif
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_remove (pit, entry->key, entry->klen);
#ifdef CefC_Debug
#if 0
{
int dbg_x;
sprintf (pit_dbg_msg, "[pit] Free the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
sprintf (pit_dbg_msg, "%s %02X", pit_dbg_msg, entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#else
{
int dbg_x;
int len = 0;
len = sprintf (pit_dbg_msg, "[pit] Free the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#endif
#endif // CefC_Debug
while (upface) {
upface_next = upface->next;
free (upface);
upface = upface_next;
}
while (dnface) {
dnface_next = dnface->next;
if ( dnface->IR_len > 0 ) {
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t dnface->IR_len:%d Type:%d\n", dnface->IR_len, dnface->IR_Type );
#endif
free( dnface->IR_msg );
}
free (dnface);
dnface = dnface_next;
}
dnface = entry->clean_dnfaces.next;
while (dnface) {
dnface_next = dnface->next;
if ( dnface->IR_len > 0 ) {
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t clean dnface->IR_len:%d Type:%d\n", dnface->IR_len, dnface->IR_Type );
#endif
free( dnface->IR_msg );
}
free (dnface);
dnface = dnface_next;
}
#if CefC_Dtc
if (entry->dtc_f) {
cef_pit_dtc_entry_delete (&entry->dtc_entry);
}
#endif // CefC_Dtc
//0.8.3
if ( entry->KIDR_len > 0 ) {
free( entry->KIDR_selector );
}
if ( entry->COBHR_len > 0 ) {
free( entry->COBHR_selector );
}
free (entry->key);
free (entry);
return;
}
/*--------------------------------------------------------------------------------------
Cleanups PIT entry which expires the lifetime
----------------------------------------------------------------------------------------*/
void
cef_pit_clean (
CefT_Hash_Handle pit, /* PIT */
CefT_Pit_Entry* entry /* PIT entry */
) {
CefT_Down_Faces* dnface;
CefT_Down_Faces* dnface_prv;
uint64_t now;
CefT_Down_Faces* clean_dnface;
now = cef_client_present_timeus_get ();
#ifdef __PIT_CLEAN__
fprintf( stderr, "[%s] IN entry->dnfacenum:%d\n", __func__, entry->dnfacenum );
#endif
if (now > entry->adv_lifetime_us) {
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t(now > entry->adv_lifetime_us)\n" );
#endif
clean_dnface = &(entry->clean_dnfaces);
while (clean_dnface->next) {
clean_dnface = clean_dnface->next;
}
dnface = &(entry->dnfaces);
while (dnface->next) {
dnface = dnface->next;
clean_dnface->next = dnface;
clean_dnface = dnface;
clean_dnface->next = NULL;
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t move to clean\n" );
#endif
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t clean dnface->IR_len:%d Type:%d\n", dnface->IR_len, dnface->IR_Type );
#endif
if (cef_face_check_active (dnface->faceid) > 0) {
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t Send IR\n" );
#endif
cef_face_frame_send_forced (dnface->faceid, dnface->IR_msg, dnface->IR_len);
}
}
entry->dnfaces.next = NULL;
entry->dnfacenum = 0;
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t entry->dnfacenum:%d\n", entry->dnfacenum );
#endif
return;
}
if (now < entry->clean_us) {
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t(now < entry->clean_us) RETURN\n" );
#endif
return;
}
entry->clean_us = now + 1000000;
dnface = &(entry->dnfaces);
dnface_prv = dnface;
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t Before while\n" );
#endif
while (dnface->next) {
dnface = dnface->next;
if (now > dnface->lifetime_us) {
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t(now > dnface->lifetime_us)\n" );
#endif
dnface_prv->next = dnface->next;
clean_dnface = &(entry->clean_dnfaces);
while (clean_dnface->next) {
clean_dnface = clean_dnface->next;
}
clean_dnface->next = dnface;
clean_dnface->next->next = NULL;
dnface = dnface_prv;
entry->dnfacenum--;
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t move to clean\n" );
#endif
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t dnface->IR_len:%d Type:%d\n", dnface->IR_len, dnface->IR_Type );
#endif
if (cef_face_check_active (dnface->faceid) > 0) {
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t Send IR\n" );
#endif
cef_face_frame_send_forced (dnface->faceid, dnface->IR_msg, dnface->IR_len);
}
} else {
dnface_prv = dnface;
}
}
#ifdef __PIT_CLEAN__
fprintf( stderr, "\t After while RETURN entry->dnfacenum:%d\n", entry->dnfacenum );
#endif
return;
}
/*--------------------------------------------------------------------------------------
Looks up and creates the specified Down Face entry
----------------------------------------------------------------------------------------*/
static int /* Returns 1 if the return entry is new */
cef_pit_entry_down_face_lookup (
CefT_Pit_Entry* entry, /* PIT entry */
uint16_t faceid, /* Face-ID */
CefT_Down_Faces** rt_dnface, /* Down Face entry to return */
uint64_t nonce, /* Nonce */
uint8_t longlife_f /* Long Life Interest */
) {
CefT_Down_Faces* dnface = &(entry->dnfaces);
while (dnface->next) {
dnface = dnface->next;
if (longlife_f) {
if (dnface->faceid == faceid) {
*rt_dnface = dnface;
return (0);
}
} else {
if ((dnface->faceid == faceid) && (dnface->nonce == nonce)) {
*rt_dnface = dnface;
return (0);
}
}
}
entry->dnfacenum++;
dnface->next = (CefT_Down_Faces*) malloc (sizeof (CefT_Down_Faces));
memset (dnface->next, 0, sizeof (CefT_Down_Faces));
dnface->next->faceid = faceid;
dnface->next->nonce = nonce;
*rt_dnface = dnface->next;
//0.8.3
dnface->next->IR_Type = 0;
dnface->next->IR_len = 0;
dnface->next->IR_msg = NULL;
#ifdef __INTEREST__
fprintf (stderr, "%s New DnFace id:%d\n", __func__, faceid );
#endif
return (1);
}
/*--------------------------------------------------------------------------------------
Removes the specified FaceID from the specified PIT entry
----------------------------------------------------------------------------------------*/
void
cef_pit_down_faceid_remove (
CefT_Pit_Entry* entry, /* PIT entry */
uint16_t faceid /* Face-ID */
) {
CefT_Down_Faces* dnface = &(entry->dnfaces);
CefT_Down_Faces* prev = dnface;
CefT_Down_Faces* clean_dnface;
while (dnface->next) {
dnface = dnface->next;
if (dnface->faceid == faceid) {
prev->next = dnface->next;
clean_dnface = &(entry->clean_dnfaces);
while (clean_dnface->next) {
clean_dnface = clean_dnface->next;
}
clean_dnface->next = dnface;
clean_dnface->next->next = NULL;
dnface = prev;
entry->dnfacenum--;
break;
}
prev = dnface;
}
return;
}
/*--------------------------------------------------------------------------------------
Looks up and creates a Up Face entry
----------------------------------------------------------------------------------------*/
static int /* Returns 1 if the return entry is new */
cef_pit_entry_up_face_lookup (
CefT_Pit_Entry* entry, /* PIT entry */
uint16_t faceid, /* Face-ID */
CefT_Up_Faces** rt_face /* Up Face entry to return */
) {
CefT_Up_Faces* face = &(entry->upfaces);
while (face->next) {
face = face->next;
if (face->faceid == faceid) {
*rt_face = face;
return (0);
}
}
face->next = (CefT_Up_Faces*) malloc (sizeof (CefT_Up_Faces));
face->next->faceid = faceid;
face->next->next = NULL;
*rt_face = face->next;
return (1);
}
/*--------------------------------------------------------------------------------------
Cleanups PIT entry which expires the lifetime
----------------------------------------------------------------------------------------*/
static CefT_Pit_Entry*
cef_pit_cleanup (
CefT_Hash_Handle pit, /* PIT */
CefT_Pit_Entry* entry /* PIT entry */
) {
CefT_Down_Faces* dnface;
CefT_Down_Faces* dnface_prv;
int fd;
uint64_t now;
CefT_Down_Faces* clean_dnface;
now = cef_client_present_timeus_get ();
if (now < entry->clean_us) {
return (entry);
}
entry->clean_us = now + 1000000;
dnface = &(entry->dnfaces);
dnface_prv = dnface;
while (dnface->next) {
dnface = dnface->next;
fd = cef_face_get_fd_from_faceid (dnface->faceid);
if ((now > dnface->lifetime_us) || (fd < 3)) {
dnface_prv->next = dnface->next;
clean_dnface = &(entry->clean_dnfaces);
while (clean_dnface->next) {
clean_dnface = clean_dnface->next;
}
clean_dnface->next = dnface;
clean_dnface->next->next = NULL;
dnface = dnface_prv;
entry->dnfacenum--;
} else {
dnface_prv = dnface;
}
}
return (entry);
}
#if 0
/*--------------------------------------------------------------------------------------
Cleanups PIT entry which expires the lifetime
----------------------------------------------------------------------------------------*/
static CefT_Pit_Entry*
cefrt_pit_cleanup (
CefT_Hash_Handle pit, /* PIT */
CefT_Pit_Entry* entry /* PIT entry */
) {
CefT_Down_Faces* dnface;
CefT_Down_Faces* dnface_prv;
uint64_t now;
struct timeval t;
gettimeofday (&t, NULL);
now = t.tv_sec * 1000000llu + t.tv_usec;
if (now < entry->clean_us) {
return (entry);
}
entry->clean_us = now + 1000000;
dnface = &(entry->dnfaces);
dnface_prv = dnface;
while (dnface->next) {
dnface = dnface->next;
if (now > dnface->lifetime_us) {
dnface_prv->next = dnface->next;
free (dnface);
dnface = dnface_prv;
entry->dnfacenum--;
} else {
dnface_prv = dnface;
}
}
if (entry->dnfacenum > 0) {
return (entry);
}
cef_pit_entry_free (pit, entry);
return (NULL);
}
#endif
#ifdef CefC_Dtc
/*--------------------------------------------------------------------------------------
Create Cefore-DTC PIT List
----------------------------------------------------------------------------------------*/
int
cef_pit_dtc_init (
void
) {
if (dtc_pit) {
free (dtc_pit);
dtc_pit = NULL;
}
dtc_pit = (CefT_Dtc_Pit_List*)malloc (sizeof (CefT_Dtc_Pit_List));
if (dtc_pit) {
dtc_pit->top = NULL;
dtc_pit->end = NULL;
dtc_pit->work = NULL;
return (0);
}
return (-1);
}
/*--------------------------------------------------------------------------------------
Destroy Cefore-DTC PIT List
----------------------------------------------------------------------------------------*/
void
cef_pit_dtc_destroy (
void
) {
CefT_Dtc_Pit_Entry* entry;
CefT_Dtc_Pit_Entry* next;
if (!dtc_pit) {
return;
}
entry = dtc_pit->top;
while (entry) {
next = entry->next;
free (entry);
entry = next;
}
free (dtc_pit);
dtc_pit = NULL;
return;
}
/*--------------------------------------------------------------------------------------
Create Cefore-DTC PIT Entry
----------------------------------------------------------------------------------------*/
CefT_Dtc_Pit_Entry*
cef_pit_dtc_entry_create (
unsigned char* msg,
uint16_t msg_len
) {
CefT_Dtc_Pit_Entry* entry;
entry = (CefT_Dtc_Pit_Entry*)malloc (sizeof (CefT_Dtc_Pit_Entry));
if (entry) {
entry->prev = NULL;
entry->next = NULL;
entry->msg_len = msg_len;
memcpy (entry->msg, msg, msg_len);
} else {
cef_log_write (CefC_Log_Warn, "Cannot allocate memory (DTC PIT entry)");
}
return (entry);
}
/*--------------------------------------------------------------------------------------
Delete Cefore-DTC PIT Entry
----------------------------------------------------------------------------------------*/
int
cef_pit_dtc_entry_delete (
CefT_Dtc_Pit_Entry** entry_p
) {
CefT_Dtc_Pit_Entry* entry = *entry_p;
/* Delete entry */
if (dtc_pit->top == dtc_pit->end) {
/* Entry is last one */
dtc_pit->top = NULL;
dtc_pit->end = NULL;
} else if (dtc_pit->top == entry) {
/* The entry is the top of the dtc_pit */
dtc_pit->top = entry->next;
dtc_pit->top->prev = NULL;
} else if (dtc_pit->end == entry) {
/* The entry is the end of the dtc_pit */
dtc_pit->end = entry->prev;
dtc_pit->end->next = NULL;
} else {
/* Other */
entry->prev->next = entry->next;
entry->next->prev = entry->prev;
}
/* Move working entry */
if (dtc_pit->work == entry) {
if (dtc_pit->work->next) {
dtc_pit->work = dtc_pit->work->next;
} else {
dtc_pit->work = dtc_pit->top;
}
}
free (entry);
*entry_p = NULL;
return (0);
}
/*--------------------------------------------------------------------------------------
Insert Cefore-DTC PIT Entry
----------------------------------------------------------------------------------------*/
void
cef_pit_dtc_entry_insert (
CefT_Dtc_Pit_Entry* entry
) {
if (entry == NULL) {
return;
}
if (dtc_pit->end) {
/* DTC-PIT has some entry */
entry->prev = dtc_pit->end;
dtc_pit->end->next = entry;
dtc_pit->end = entry;
} else if (dtc_pit->top) {
/* DTC-PIT has single entry */
entry->prev = dtc_pit->top;
dtc_pit->top->next = entry;
dtc_pit->end = entry;
} else {
/* DTC-PIT has no entry */
dtc_pit->top = entry;
dtc_pit->end = entry;
dtc_pit->work = entry;
}
return;
}
/*--------------------------------------------------------------------------------------
Read Current Cefore-DTC PIT Entry
----------------------------------------------------------------------------------------*/
CefT_Dtc_Pit_Entry*
cef_pit_dtc_entry_read (
void
) {
if (dtc_pit->work == NULL) {
/* DTC Entry is empty */
return (NULL);
}
/* Move next */
if (dtc_pit->work->next) {
dtc_pit->work = dtc_pit->work->next;
} else {
/* The entry is the end of the dtc_pit */
dtc_pit->work = dtc_pit->top;
}
return (dtc_pit->work);
}
#endif // CefC_Dtc
//0.8.3
/*--------------------------------------------------------------------------------------
Symbolic PIT Check
----------------------------------------------------------------------------------------*/
int
cef_pit_symbolic_pit_check (
CefT_Hash_Handle pit, /* PIT */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh /* Parsed Option Header */
) {
CefT_Pit_Entry* entry;
#ifdef __INTEREST__
fprintf (stderr, "%s IN\n", __func__ );
#endif
/* Searches a PIT entry */
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (pit, pm->name, pm->name_len);
if ( entry == NULL ) {
#ifdef __INTEREST__
fprintf (stderr, "%s Return(0) ( entry == NULL )\n", __func__ );
#endif
return (0);
}
if ( entry->PitType == pm->InterestType ) {
#ifdef __INTEREST__
fprintf (stderr, "%s Return(0) ( entry->PitType == pm->InterestType )\n", __func__ );
#endif
return (0);
} else {
#ifdef __INTEREST__
fprintf (stderr, "%s Return(-0) ( entry->PitType != pm->InterestType )\n", __func__ );
#endif
return (-1);
}
}
/*--------------------------------------------------------------------------------------
Searches a PIT entry matching the specified Name with chunk number
----------------------------------------------------------------------------------------*/
CefT_Pit_Entry* /* a PIT entry */
cef_pit_entry_search_with_chunk (
CefT_Hash_Handle pit, /* PIT */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh /* Parsed Option Header */
) {
CefT_Pit_Entry* entry;
uint64_t now;
#ifdef CefC_Debug
#if 0
{
int dbg_x;
sprintf (pit_dbg_msg, "[pit] Search the entry [");
for (dbg_x = 0 ; dbg_x < pm->name_len ; dbg_x++) {
sprintf (pit_dbg_msg, "%s %02X", pit_dbg_msg, pm->name[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#else
{
int dbg_x;
int len = 0;
len = sprintf (pit_dbg_msg, "[pit] Search the entry [");
for (dbg_x = 0 ; dbg_x < pm->name_len ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", pm->name[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#endif
#endif // CefC_Debug
/* Searches a PIT entry */
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (pit, pm->name, pm->name_len);
now = cef_client_present_timeus_get ();
if (entry != NULL) {
if (!entry->symbolic_f) {
entry->stole_f = 1;
}
#ifdef CefC_Debug
#if 0
{
int dbg_x;
sprintf (pit_dbg_msg, "[pit] Exact matched to the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
sprintf (pit_dbg_msg, "%s %02X", pit_dbg_msg, entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#else
{
int dbg_x;
int len = 0;
len = sprintf (pit_dbg_msg, "[pit] Exact matched to the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#endif
#endif // CefC_Debug
if ((now > entry->adv_lifetime_us) && (poh->app_reg_f != CefC_App_DeRegPit)){ //20190822
return (NULL);
}
return (entry);
}
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
#endif // CefC_Debug
return (NULL);
}
/*--------------------------------------------------------------------------------------
Searches a PIT entry matching the specified Name without chunk number
----------------------------------------------------------------------------------------*/
CefT_Pit_Entry* /* a PIT entry */
cef_pit_entry_search_without_chunk (
CefT_Hash_Handle pit, /* PIT */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh /* Parsed Option Header */
) {
CefT_Pit_Entry* entry;
uint16_t tmp_name_len;
uint64_t now;
tmp_name_len = pm->name_len;
#ifdef CefC_Debug
#if 0
{
int dbg_x;
sprintf (pit_dbg_msg, "[pit] Search the entry [");
for (dbg_x = 0 ; dbg_x < tmp_name_len ; dbg_x++) {
sprintf (pit_dbg_msg, "%s %02X", pit_dbg_msg, pm->name[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#else
{
int dbg_x;
int len = 0;
len = sprintf (pit_dbg_msg, "[pit] Search the entry [");
for (dbg_x = 0 ; dbg_x < tmp_name_len ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", pm->name[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
}
#endif
#endif // CefC_Debug
now = cef_client_present_timeus_get ();
if (pm->chnk_num_f) {
uint16_t name_len_wo_chunk;
name_len_wo_chunk = tmp_name_len - (CefC_S_Type + CefC_S_Length + CefC_S_ChunkNum);
entry = (CefT_Pit_Entry*) cef_hash_tbl_item_get (pit, pm->name, name_len_wo_chunk);
if (entry != NULL) {
if (entry->symbolic_f) {
entry = cef_pit_cleanup (pit, entry);
#ifdef CefC_Debug
#if 0
{
int dbg_x;
if (entry) {
sprintf (pit_dbg_msg, "[pit] Partial matched to the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
sprintf (pit_dbg_msg,
"%s %02X", pit_dbg_msg, entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
} else {
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
}
}
#else
{
int dbg_x;
int len = 0;
if (entry) {
len = sprintf (pit_dbg_msg, "[pit] Partial matched to the entry [");
for (dbg_x = 0 ; dbg_x < entry->klen ; dbg_x++) {
len = len + sprintf (pit_dbg_msg + len, " %02X", entry->key[dbg_x]);
}
cef_dbg_write (CefC_Dbg_Finest, "%s ]\n", pit_dbg_msg);
} else {
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
}
}
#endif
#endif // CefC_Debug
if (now > entry->adv_lifetime_us) {
return (NULL);
}
return (entry);
}
}
}
#ifdef CefC_Debug
cef_dbg_write (CefC_Dbg_Finest, "[pit] Mismatched\n");
#endif // CefC_Debug
return (NULL);
}
/*--------------------------------------------------------------------------------------
Set InterestReturn Info to DownFace
----------------------------------------------------------------------------------------*/
int
cef_pit_interest_return_set (
CefT_Pit_Entry* entry, /* PIT entry */
CefT_Parsed_Message* pm, /* Parsed CEFORE message */
CefT_Parsed_Opheader* poh, /* Parsed Option Header */
uint16_t faceid, /* Face-ID */
uint8_t IR_Type, /* InterestReturn Type */
unsigned int IR_len, /* Length of IR_msg */
unsigned char* IR_msg /* InterestReturn msg */
) {
CefT_Down_Faces* dnface = &(entry->dnfaces);
while (dnface->next) {
dnface = dnface->next;
if (dnface->faceid == faceid) {
break;
}
}
if ( dnface != NULL ) {
if ( dnface->IR_Type != 0 ) {
if ( dnface->IR_Type == IR_Type ) {
/* Same set input */
free(dnface->IR_msg);
} else {
if ( dnface->IR_Type == IR_PRIORITY_TBL[2] ) {
/* Low set input */
free(dnface->IR_msg);
} else if ( dnface->IR_Type == IR_PRIORITY_TBL[1] ) {
/* Middle set input */
free(dnface->IR_msg);
} else {
/* High not set */
return(0);
}
}
}
dnface->IR_Type = IR_Type;
dnface->IR_len = IR_len;
dnface->IR_msg = (unsigned char*)malloc(sizeof(char)*IR_len);
memcpy( dnface->IR_msg, IR_msg, IR_len );
return(0);
}
return(-1);
}
| 29.589686 | 105 | 0.569978 |
ec97c40277faf3a410cf2c7ee5bae919611ceb6a | 24,152 | h | C | src/util.h | cvlvxi/delly | 8e3ccee9aab62101fb9f573d75b51b64f0aacf10 | [
"BSD-3-Clause"
] | 234 | 2016-11-15T08:05:01.000Z | 2022-03-31T09:44:47.000Z | src/util.h | cvlvxi/delly | 8e3ccee9aab62101fb9f573d75b51b64f0aacf10 | [
"BSD-3-Clause"
] | 206 | 2016-11-10T11:43:41.000Z | 2022-02-08T07:54:00.000Z | src/util.h | cvlvxi/delly | 8e3ccee9aab62101fb9f573d75b51b64f0aacf10 | [
"BSD-3-Clause"
] | 131 | 2016-11-17T07:40:02.000Z | 2022-02-22T02:49:31.000Z | #ifndef UTIL_H
#define UTIL_H
#include <boost/multi_array.hpp>
#include <boost/unordered_map.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <htslib/sam.h>
#include <sstream>
#include <math.h>
#include "tags.h"
namespace torali
{
#ifndef LAST_BIN
#define LAST_BIN 65535
#endif
#ifndef MAX_CN
#define MAX_CN 10
#endif
struct LibraryInfo {
int32_t rs;
int32_t median;
int32_t mad;
int32_t minNormalISize;
int32_t minISizeCutoff;
int32_t maxNormalISize;
int32_t maxISizeCutoff;
uint32_t abnormal_pairs;
LibraryInfo() : rs(0), median(0), mad(0), minNormalISize(0), minISizeCutoff(0), maxNormalISize(0), maxISizeCutoff(0), abnormal_pairs(0) {}
};
struct CNV {
int32_t chr;
int32_t start;
int32_t end;
int32_t ciposlow;
int32_t ciposhigh;
int32_t ciendlow;
int32_t ciendhigh;
int32_t qval;
double cn;
double mappable;
double sd;
CNV() : chr(0), start(0), end(0), ciposlow(0), ciposhigh(0), ciendlow(0), ciendhigh(0), qval(0), cn(-1), mappable(0), sd(1) {}
CNV(int32_t const c, int32_t const s, int32_t const e, int32_t const cil, int32_t const cih, int32_t const cel, int32_t ceh, double const estcn, double const mp) : chr(c), start(s), end(e), ciposlow(cil), ciposhigh(cih), ciendlow(cel), ciendhigh(ceh), qval(0), cn(estcn), mappable(mp), sd(1) {}
};
template<typename TCNV>
struct SortCNVs : public std::binary_function<TCNV, TCNV, bool>
{
inline bool operator()(TCNV const& sv1, TCNV const& sv2) {
return ((sv1.chr<sv2.chr) || ((sv1.chr==sv2.chr) && (sv1.start<sv2.start)) || ((sv1.chr==sv2.chr) && (sv1.start==sv2.start) && (sv1.end<sv2.end)) || ((sv1.chr==sv2.chr) && (sv1.start==sv2.start) && (sv1.end==sv2.end) && (sv1.cn < sv2.cn)));
}
};
// Read count struct
struct ReadCount {
int32_t leftRC;
int32_t rc;
int32_t rightRC;
ReadCount() {}
ReadCount(int32_t l, int32_t m, int32_t r) : leftRC(l), rc(m), rightRC(r) {}
};
inline bool
nContent(std::string const& s) {
for(uint32_t i = 0; i < s.size(); ++i) {
if ((s[i] == 'N') || (s[i] == 'n')) return true;
}
return false;
}
// Decode Orientation
inline int32_t
_decodeOrientation(std::string const& value) {
if (value=="3to3") return 0;
else if (value=="5to5") return 1;
else if (value=="3to5") return 2;
else if (value=="5to3") return 3;
else return 4;
}
// Decode Orientation
inline int32_t
_decodeOrientation(std::string const& value, std::string const& svt) {
if (svt == "BND") {
if (value=="3to3") return DELLY_SVT_TRANS + 0;
else if (value=="5to5") return DELLY_SVT_TRANS + 1;
else if (value=="3to5") return DELLY_SVT_TRANS + 2;
else if (value=="5to3") return DELLY_SVT_TRANS + 3;
else return -1;
} else if (svt == "CNV") {
return 9;
} else {
if (value=="3to3") return 0;
else if (value=="5to5") return 1;
else if (value=="3to5") return 2;
else if (value=="5to3") return 3;
else return 4;
}
}
// Deletions
inline std::string
_addID(int32_t const svt) {
if (svt == 0) return "INV";
else if (svt == 1) return "INV";
else if (svt == 2) return "DEL";
else if (svt == 3) return "DUP";
else if (svt == 4) return "INS";
else if (svt == 9) return "CNV";
else return "BND";
}
inline std::string
_addAlleles(std::string const& ref, std::string const& alt) {
return ref + "," + alt;
}
inline std::string
_addAlleles(std::string const& ref, std::string const& chr2, StructuralVariantRecord const& sv, int32_t const svt) {
if (_translocation(svt)) {
uint8_t ct = _getSpanOrientation(svt);
if (ct == 0) {
return ref + "," + ref + "]" + chr2 + ":" + boost::lexical_cast<std::string>(sv.svEnd) + "]";
} else if (ct == 1) {
return ref + "," + "[" + chr2 + ":" + boost::lexical_cast<std::string>(sv.svEnd) + "[" + ref;
} else if (ct == 2) {
return ref + "," + ref + "[" + chr2 + ":" + boost::lexical_cast<std::string>(sv.svEnd) + "[";
} else if (ct == 3) {
return ref + "," + "]" + chr2 + ":" + boost::lexical_cast<std::string>(sv.svEnd) + "]" + ref;
} else {
return ref + ",<" + _addID(svt) + ">";
}
} else return ref + ",<" + _addID(svt) + ">";
}
// Add Orientation
inline std::string
_addOrientation(int32_t const svt) {
uint8_t ct = _getSpanOrientation(svt);
if (ct==0) return "3to3";
else if (ct==1) return "5to5";
else if (ct==2) return "3to5";
else if (ct==3) return "5to3";
else return "NtoN";
}
// Output directory/file checks
inline bool
_outfileValid(boost::filesystem::path const& outfile) {
try {
boost::filesystem::path outdir;
if (outfile.has_parent_path()) outdir = outfile.parent_path();
else outdir = boost::filesystem::current_path();
if (!boost::filesystem::exists(outdir)) {
std::cerr << "Output directory does not exist: " << outdir << std::endl;
return false;
} else {
boost::filesystem::file_status s = boost::filesystem::status(outdir);
boost::filesystem::ofstream file(outfile.string());
file.close();
if (!(boost::filesystem::exists(outfile) && boost::filesystem::is_regular_file(outfile))) {
std::cerr << "Fail to open output file " << outfile.string() << std::endl;
std::cerr << "Output directory permissions: " << s.permissions() << std::endl;
return false;
} else {
boost::filesystem::remove(outfile.string());
}
}
} catch (boost::filesystem::filesystem_error const& e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
template<typename TConfig>
inline void
_svTypesToCompute(TConfig& c, std::string const& svtype, bool const specified) {
c.svtcmd = false;
if (specified) {
c.svtcmd = true;
if (svtype == "DEL") {
c.svtset.insert(2);
} else if (svtype == "INS") {
c.svtset.insert(4);
} else if (svtype == "DUP") {
c.svtset.insert(3);
} else if (svtype == "INV") {
c.svtset.insert(0);
c.svtset.insert(1);
} else if (svtype == "INV_3to3") {
c.svtset.insert(0);
} else if (svtype == "INV_5to5") {
c.svtset.insert(1);
} else if (svtype == "BND") {
c.svtset.insert(DELLY_SVT_TRANS + 0);
c.svtset.insert(DELLY_SVT_TRANS + 1);
c.svtset.insert(DELLY_SVT_TRANS + 2);
c.svtset.insert(DELLY_SVT_TRANS + 3);
} else if (svtype == "BND_3to3") {
c.svtset.insert(DELLY_SVT_TRANS + 0);
} else if (svtype == "BND_5to5") {
c.svtset.insert(DELLY_SVT_TRANS + 1);
} else if (svtype == "BND_3to5") {
c.svtset.insert(DELLY_SVT_TRANS + 2);
} else if (svtype == "BND_5to3") {
c.svtset.insert(DELLY_SVT_TRANS + 3);
} else {
c.svtcmd = false;
}
}
}
inline uint32_t sequenceLength(bam1_t const* rec) {
uint32_t* cigar = bam_get_cigar(rec);
uint32_t slen = 0;
for (uint32_t i = 0; i < rec->core.n_cigar; ++i)
if ((bam_cigar_op(cigar[i]) == BAM_CMATCH) || (bam_cigar_op(cigar[i]) == BAM_CEQUAL) || (bam_cigar_op(cigar[i]) == BAM_CDIFF) || (bam_cigar_op(cigar[i]) == BAM_CINS) || (bam_cigar_op(cigar[i]) == BAM_CSOFT_CLIP) || (bam_cigar_op(cigar[i]) == BAM_CHARD_CLIP)) slen += bam_cigar_oplen(cigar[i]);
return slen;
}
inline int32_t
readLength(bam1_t const* rec) {
//int32_t slen = rec->core.l_qseq; # Incorrect for seq. with hard-clips
return sequenceLength(rec);
}
inline uint32_t alignmentLength(bam1_t const* rec) {
uint32_t* cigar = bam_get_cigar(rec);
uint32_t alen = 0;
for (uint32_t i = 0; i < rec->core.n_cigar; ++i)
if ((bam_cigar_op(cigar[i]) == BAM_CMATCH) || (bam_cigar_op(cigar[i]) == BAM_CEQUAL) || (bam_cigar_op(cigar[i]) == BAM_CDIFF) || (bam_cigar_op(cigar[i]) == BAM_CDEL) || (bam_cigar_op(cigar[i]) == BAM_CREF_SKIP)) alen += bam_cigar_oplen(cigar[i]);
return alen;
}
inline uint32_t halfAlignmentLength(bam1_t const* rec) {
return (alignmentLength(rec) / 2);
}
inline uint32_t
lastAlignedPosition(bam1_t const* rec) {
return rec->core.pos + alignmentLength(rec);
}
inline std::size_t hash_lr(bam1_t* rec) {
boost::hash<std::string> string_hash;
std::string qname = bam_get_qname(rec);
std::size_t seed = hash_string(qname.c_str());
boost::hash_combine(seed, string_hash(qname));
return seed;
}
inline std::size_t hash_pair(bam1_t* rec) {
std::size_t seed = hash_string(bam_get_qname(rec));
boost::hash_combine(seed, rec->core.tid);
boost::hash_combine(seed, rec->core.pos);
boost::hash_combine(seed, rec->core.mtid);
boost::hash_combine(seed, rec->core.mpos);
return seed;
}
inline std::size_t hash_pair_mate(bam1_t* rec) {
std::size_t seed = hash_string(bam_get_qname(rec));
boost::hash_combine(seed, rec->core.mtid);
boost::hash_combine(seed, rec->core.mpos);
boost::hash_combine(seed, rec->core.tid);
boost::hash_combine(seed, rec->core.pos);
return seed;
}
inline void
reverseComplement(std::string& sequence) {
std::string rev = boost::to_upper_copy(std::string(sequence.rbegin(), sequence.rend()));
std::size_t i = 0;
for(std::string::iterator revIt = rev.begin(); revIt != rev.end(); ++revIt, ++i) {
switch (*revIt) {
case 'A': sequence[i]='T'; break;
case 'C': sequence[i]='G'; break;
case 'G': sequence[i]='C'; break;
case 'T': sequence[i]='A'; break;
case 'N': sequence[i]='N'; break;
default: break;
}
}
}
inline std::string
compressStr(std::string const& data) {
std::stringstream compressed;
std::stringstream origin(data);
boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
out.push(boost::iostreams::gzip_compressor(boost::iostreams::gzip_params(boost::iostreams::gzip::best_speed)));
out.push(origin);
boost::iostreams::copy(out, compressed);
return compressed.str();
}
inline std::string
decompressStr(std::string const& data) {
std::stringstream compressed(data);
std::stringstream decompressed;
boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
out.push(boost::iostreams::gzip_decompressor());
out.push(compressed);
boost::iostreams::copy(out, decompressed);
return decompressed.str();
}
inline double
entropy(std::string const& st) {
typedef double TPrecision;
std::vector<char> stvec(st.begin(), st.end());
std::set<char> alphabet(stvec.begin(), stvec.end());
TPrecision ent = 0;
for(std::set<char>::const_iterator c = alphabet.begin(); c != alphabet.end(); ++c) {
int ctr = 0;
for (std::vector<char>::const_iterator s = stvec.begin(); s != stvec.end(); ++s)
if (*s == *c) ++ctr;
TPrecision freq = (TPrecision) ctr / (TPrecision) stvec.size();
ent += (freq) * log(freq)/log(2);
}
return -ent;
}
inline uint32_t
setMinChrLen(bam_hdr_t const* hdr, double const xx) {
uint32_t minChrLen = 0;
std::vector<uint32_t> chrlen(hdr->n_targets, 0);
uint64_t genomelen = 0;
for(int32_t refIndex = 0; refIndex < hdr->n_targets; ++refIndex) {
chrlen[refIndex] = hdr->target_len[refIndex];
genomelen += hdr->target_len[refIndex];
}
std::sort(chrlen.begin(), chrlen.end(), std::greater<uint32_t>());
uint64_t cumsum = 0;
for(uint32_t i = 0; i < chrlen.size(); ++i) {
cumsum += chrlen[i];
minChrLen = chrlen[i];
if (cumsum > genomelen * xx) break;
}
return minChrLen;
}
template<typename TConfig>
inline bool
chrNoData(TConfig const& c, uint32_t const refIndex, hts_idx_t const* idx) {
// Check we have mapped reads on this chromosome
std::string suffix("cram");
std::string str(c.bamFile.string());
if ((str.size() >= suffix.size()) && (str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0)) return false;
uint64_t mapped = 0;
uint64_t unmapped = 0;
hts_idx_get_stat(idx, refIndex, &mapped, &unmapped);
if (mapped) return false;
else return true;
}
inline std::size_t hash_se(bam1_t* rec) {
std::size_t seed = hash_string(bam_get_qname(rec));
boost::hash_combine(seed, rec->core.tid);
boost::hash_combine(seed, rec->core.pos);
return seed;
}
inline void
getSMTag(std::string const& header, std::string const& fileName, std::string& sampleName) {
std::set<std::string> smIdentifiers;
std::string delimiters("\n");
typedef std::vector<std::string> TStrParts;
TStrParts lines;
boost::split(lines, header, boost::is_any_of(delimiters));
TStrParts::const_iterator itH = lines.begin();
TStrParts::const_iterator itHEnd = lines.end();
bool rgPresent = false;
for(;itH!=itHEnd; ++itH) {
if (itH->find("@RG")==0) {
std::string delim("\t");
TStrParts keyval;
boost::split(keyval, *itH, boost::is_any_of(delim));
TStrParts::const_iterator itKV = keyval.begin();
TStrParts::const_iterator itKVEnd = keyval.end();
for(;itKV != itKVEnd; ++itKV) {
size_t sp = itKV->find(":");
if (sp != std::string::npos) {
std::string field = itKV->substr(0, sp);
if (field == "SM") {
rgPresent = true;
std::string rgSM = itKV->substr(sp+1);
smIdentifiers.insert(rgSM);
}
}
}
}
}
if (!rgPresent) {
sampleName = fileName;
} else if (smIdentifiers.size() == 1) {
sampleName = *(smIdentifiers.begin());
} else if (smIdentifiers.size() > 1) {
sampleName = *(smIdentifiers.begin());
std::cerr << "Warning: Multiple sample names (@RG:SM) present in the BAM file!" << std::endl;
}
}
template<typename TConfig, typename TRegionsGenome>
inline int32_t
_parseExcludeIntervals(TConfig const& c, bam_hdr_t* hdr, TRegionsGenome& validRegions) {
typedef typename TRegionsGenome::value_type TChrIntervals;
typedef typename TChrIntervals::interval_type TIVal;
validRegions.resize(hdr->n_targets);
TRegionsGenome exclg;
exclg.resize(hdr->n_targets);
std::vector<bool> validChr;
validChr.resize(hdr->n_targets, true);
if (c.hasExcludeFile) {
std::ifstream chrFile(c.exclude.string().c_str(), std::ifstream::in);
if (chrFile.is_open()) {
while (chrFile.good()) {
std::string chrFromFile;
getline(chrFile, chrFromFile);
typedef boost::tokenizer< boost::char_separator<char> > Tokenizer;
boost::char_separator<char> sep(" \t,;");
Tokenizer tokens(chrFromFile, sep);
Tokenizer::iterator tokIter = tokens.begin();
if (tokIter!=tokens.end()) {
std::string chrName = *tokIter++;
int32_t tid = bam_name2id(hdr, chrName.c_str());
if (tid >= 0) {
if (tokIter!=tokens.end()) {
int32_t start = 0;
try {
start = boost::lexical_cast<int32_t>(*tokIter++);
} catch (boost::bad_lexical_cast&) {
std::cerr << "Exclude file needs to be in tab-delimited format: chr, start, end" << std::endl;
std::cerr << "Offending line: " << chrFromFile << std::endl;
return false;
}
if (tokIter!=tokens.end()) {
int32_t end = start + 1;
try {
end = boost::lexical_cast<int32_t>(*tokIter++);
} catch (boost::bad_lexical_cast&) {
std::cerr << "Exclude file needs to be in tab-delimited format: chr, start, end" << std::endl;
std::cerr << "Offending line: " << chrFromFile << std::endl;
return false;
}
if (start < end) {
exclg[tid].insert(TIVal::right_open(start, end));
} else {
std::cerr << "Exclude file needs to be in tab-delimited format (chr, start, end) and start < end." << std::endl;
std::cerr << "Offending line: " << chrFromFile << std::endl;
return false;
}
} else {
std::cerr << "Exclude file needs to be in tab-delimited format: chr, start, end" << std::endl;
std::cerr << "Offending line: " << chrFromFile << std::endl;
return false;
}
} else validChr[tid] = false; // Exclude entire chromosome
}
}
}
chrFile.close();
}
}
// Create the valid regions
for (int32_t i = 0; i<hdr->n_targets; ++i) {
if (!validChr[i]) continue;
uint32_t istart = 0;
for(typename TChrIntervals::iterator it = exclg[i].begin(); it != exclg[i].end(); ++it) {
if (istart + 1 < it->lower()) validRegions[i].insert(TIVal::right_open(istart, it->lower() - 1));
istart = it->upper();
}
if (istart + 1 < hdr->target_len[i]) validRegions[i].insert(TIVal::right_open(istart, hdr->target_len[i]));
}
exclg.clear();
return true;
}
template<typename TIterator, typename TValue>
inline void
getMedian(TIterator begin, TIterator end, TValue& median)
{
std::nth_element(begin, begin + (end - begin) / 2, end);
median = *(begin + (end - begin) / 2);
}
template<typename TVector, typename TPercentile, typename TValue>
inline void
getPercentile(TVector& vec, TPercentile p, TValue& percentile)
{
std::nth_element(vec.begin(), vec.begin() + int((vec.size() * p)), vec.end());
percentile = *(vec.begin() + int(vec.size() * p));
}
template<typename TConfig>
inline int32_t
getVariability(TConfig const&, std::vector<LibraryInfo> const& lib) {
int32_t overallVariability = 0;
for(uint32_t libIdx = 0; libIdx < lib.size(); ++libIdx) {
if (lib[libIdx].maxNormalISize > overallVariability) overallVariability = lib[libIdx].maxNormalISize;
if (lib[libIdx].rs > overallVariability) overallVariability = lib[libIdx].rs;
}
return overallVariability;
}
template<typename TIterator, typename TValue>
inline void
getMAD(TIterator begin, TIterator end, TValue median, TValue& mad)
{
std::vector<TValue> absDev;
for(;begin<end;++begin)
absDev.push_back(std::abs((TValue)*begin - median));
getMedian(absDev.begin(), absDev.end(), mad);
}
template<typename TIterator, typename TValue>
inline void
getMean(TIterator begin, TIterator end, TValue& mean)
{
mean = 0;
unsigned int count = 0;
for(; begin<end; ++begin,++count) mean += *begin;
mean /= count;
}
template<typename TIterator, typename TValue>
inline void
getStdDev(TIterator begin, TIterator end, TValue mean, TValue& stdDev)
{
stdDev = 0;
unsigned int count = 0;
for(;begin<end;++begin,++count) stdDev += ((TValue)*begin - mean) * ((TValue)*begin - mean);
stdDev = sqrt(stdDev / (TValue) count);
}
template<typename TConfig, typename TValidRegion, typename TSampleLibrary>
inline void
getLibraryParams(TConfig const& c, TValidRegion const& validRegions, TSampleLibrary& sampleLib) {
typedef typename TValidRegion::value_type TChrIntervals;
// Open file handles
typedef std::vector<samFile*> TSamFile;
typedef std::vector<hts_idx_t*> TIndex;
typedef std::vector<bam_hdr_t*> TSamHeader;
TSamFile samfile(c.files.size());
TIndex idx(c.files.size());
TSamHeader hdr(c.files.size());
for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
samfile[file_c] = sam_open(c.files[file_c].string().c_str(), "r");
hts_set_fai_filename(samfile[file_c], c.genome.string().c_str());
idx[file_c] = sam_index_load(samfile[file_c], c.files[file_c].string().c_str());
hdr[file_c] = sam_hdr_read(samfile[file_c]);
}
// Iterate all samples
for(uint32_t file_c = 0; file_c < c.files.size(); ++file_c) {
uint32_t maxAlignmentsScreened=10000000;
uint32_t maxNumAlignments=1000000;
uint32_t minNumAlignments=1000;
uint32_t alignmentCount=0;
uint32_t processedNumPairs = 0;
uint32_t processedNumReads = 0;
uint32_t rplus = 0;
uint32_t nonrplus = 0;
typedef std::vector<uint32_t> TSizeVector;
TSizeVector vecISize;
TSizeVector readSize;
// Collect insert sizes
bool libCharacterized = false;
for(uint32_t refIndex=0; refIndex < (uint32_t) hdr[0]->n_targets; ++refIndex) {
if (validRegions[refIndex].empty()) continue;
for(typename TChrIntervals::const_iterator vRIt = validRegions[refIndex].begin(); ((vRIt != validRegions[refIndex].end()) && (!libCharacterized)); ++vRIt) {
hts_itr_t* iter = sam_itr_queryi(idx[file_c], refIndex, vRIt->lower(), vRIt->upper());
bam1_t* rec = bam_init1();
while (sam_itr_next(samfile[file_c], iter, rec) >= 0) {
if (!(rec->core.flag & BAM_FREAD2) && (rec->core.l_qseq < 65000)) {
if (rec->core.flag & (BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP | BAM_FSUPPLEMENTARY | BAM_FUNMAP)) continue;
if ((alignmentCount > maxAlignmentsScreened) || ((processedNumReads >= maxNumAlignments) && (processedNumPairs == 0)) || (processedNumPairs >= maxNumAlignments)) {
// Paired-end library with enough pairs
libCharacterized = true;
break;
}
++alignmentCount;
// Single-end
if (processedNumReads < maxNumAlignments) {
readSize.push_back(rec->core.l_qseq);
++processedNumReads;
}
// Paired-end
if ((rec->core.flag & BAM_FPAIRED) && !(rec->core.flag & BAM_FMUNMAP) && (rec->core.tid==rec->core.mtid)) {
if (processedNumPairs < maxNumAlignments) {
vecISize.push_back(abs(rec->core.isize));
if (getSVType(rec->core) == 2) ++rplus;
else ++nonrplus;
++processedNumPairs;
}
}
}
}
bam_destroy1(rec);
hts_itr_destroy(iter);
if (libCharacterized) break;
}
if (libCharacterized) break;
}
// Get library parameters
if (processedNumReads >= minNumAlignments) {
std::sort(readSize.begin(), readSize.end());
sampleLib[file_c].rs = readSize[readSize.size() / 2];
}
if (processedNumPairs >= minNumAlignments) {
std::sort(vecISize.begin(), vecISize.end());
int32_t median = vecISize[vecISize.size() / 2];
std::vector<uint32_t> absDev;
for(uint32_t i = 0; i < vecISize.size(); ++i) absDev.push_back(std::abs((int32_t) vecISize[i] - median));
std::sort(absDev.begin(), absDev.end());
int32_t mad = absDev[absDev.size() / 2];
// Get default library orientation
if ((median >= 50) && (median<=100000)) {
if (rplus < nonrplus) {
std::cerr << "Warning: Sample has a non-default paired-end layout! File: " << c.files[file_c].string() << std::endl;
std::cerr << "The expected paired-end orientation is ---Read1---> <---Read2--- which is the default illumina paired-end layout." << std::endl;
} else {
sampleLib[file_c].median = median;
sampleLib[file_c].mad = mad;
sampleLib[file_c].maxNormalISize = median + (c.madNormalCutoff * mad);
sampleLib[file_c].minNormalISize = median - (c.madNormalCutoff * mad);
if (sampleLib[file_c].minNormalISize < 0) sampleLib[file_c].minNormalISize=0;
sampleLib[file_c].maxISizeCutoff = median + (c.madCutoff * mad);
sampleLib[file_c].minISizeCutoff = median - (c.madCutoff * mad);
// Deletion insert-size sanity checks
sampleLib[file_c].maxISizeCutoff = std::max(sampleLib[file_c].maxISizeCutoff, 2*sampleLib[file_c].rs);
sampleLib[file_c].maxISizeCutoff = std::max(sampleLib[file_c].maxISizeCutoff, 500);
if (sampleLib[file_c].minISizeCutoff < 0) sampleLib[file_c].minISizeCutoff=0;
}
}
}
}
// Clean-up
for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
bam_hdr_destroy(hdr[file_c]);
hts_idx_destroy(idx[file_c]);
sam_close(samfile[file_c]);
}
}
template<typename TAlign>
inline uint32_t
_trimAlignedSequences(TAlign const& align, std::string& s0, std::string& s1) {
int32_t s = -1;
int32_t e = -1;
uint32_t leadCrop = 0;
for(uint32_t j = 0; j<align.shape()[1]; ++j) {
if (align[0][j] != '-') {
if (align[1][j] != '-') {
if (s == -1) s = j;
e = j + 1;
}
if (s == -1) ++leadCrop;
}
}
s0.clear();
s1.clear();
for(int32_t j = s; j < e; ++j) {
if (align[0][j] != '-') s0.push_back(align[0][j]);
if (align[1][j] != '-') s1.push_back(align[1][j]);
}
return leadCrop;
}
}
#endif
| 33.873773 | 299 | 0.630548 |
bd359daaefae200fe249d1a8afb00a9089ea8c4d | 217 | c | C | tests/gcc-torture/pr33631.c | daejunpark/c-semantics | e3fd72bdb8cece8279dbffb86feecdb76e0990e2 | [
"MIT"
] | 1 | 2016-08-10T15:41:53.000Z | 2016-08-10T15:41:53.000Z | tests/gcc-torture/pr33631.c | daejunpark/c-semantics | e3fd72bdb8cece8279dbffb86feecdb76e0990e2 | [
"MIT"
] | null | null | null | tests/gcc-torture/pr33631.c | daejunpark/c-semantics | e3fd72bdb8cece8279dbffb86feecdb76e0990e2 | [
"MIT"
] | 1 | 2021-07-31T21:55:35.000Z | 2021-07-31T21:55:35.000Z | #include <stdlib.h>
typedef union
{
int __lock;
} pthread_mutex_t;
extern void abort (void);
int main()
{
struct { int c; pthread_mutex_t m; } r = { .m = 0 };
if (r.c != 0)
abort ();
return 0;
}
| 13.5625 | 56 | 0.562212 |
bd7727aea0fb6d396476c082b3e0bcfd9315afb0 | 1,201 | c | C | release/src/router/iproute2/lib/dnet_pton.c | enfoTek/tomato.linksys.e2000.nvram-mod | 2ce3a5217def49d6df7348522e2bfda702b56029 | [
"FSFAP"
] | 278 | 2015-11-03T03:01:20.000Z | 2022-01-20T18:21:05.000Z | release/src/router/iproute2/lib/dnet_pton.c | unforgiven512/tomato | 96f09fab4929c6ddde5c9113f1b2476ad37133c4 | [
"FSFAP"
] | 374 | 2015-11-03T12:37:22.000Z | 2021-12-17T14:18:08.000Z | release/src/router/iproute2/lib/dnet_pton.c | unforgiven512/tomato | 96f09fab4929c6ddde5c9113f1b2476ad37133c4 | [
"FSFAP"
] | 96 | 2015-11-22T07:47:26.000Z | 2022-01-20T19:52:19.000Z | #include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "utils.h"
static __inline__ u_int16_t dn_htons(u_int16_t addr)
{
union {
u_int8_t byte[2];
u_int16_t word;
} u;
u.word = addr;
return ((u_int16_t)u.byte[0]) | (((u_int16_t)u.byte[1]) << 8);
}
static int dnet_num(const char *src, u_int16_t * dst)
{
int rv = 0;
int tmp;
*dst = 0;
while ((tmp = *src++) != 0) {
tmp -= '0';
if ((tmp < 0) || (tmp > 9))
return rv;
rv++;
(*dst) *= 10;
(*dst) += tmp;
}
return rv;
}
static int dnet_pton1(const char *src, struct dn_naddr *dna)
{
u_int16_t area = 0;
u_int16_t node = 0;
int pos;
pos = dnet_num(src, &area);
if ((pos == 0) || (area > 63) || (*(src + pos) != '.'))
return 0;
pos = dnet_num(src + pos + 1, &node);
if ((pos == 0) || (node > 1023))
return 0;
dna->a_len = 2;
*(u_int16_t *)dna->a_addr = dn_htons((area << 10) | node);
return 1;
}
int dnet_pton(int af, const char *src, void *addr)
{
int err;
switch (af) {
case AF_DECnet:
errno = 0;
err = dnet_pton1(src, (struct dn_naddr *)addr);
break;
default:
errno = EAFNOSUPPORT;
err = -1;
}
return err;
}
| 16.680556 | 70 | 0.550375 |
d6c538b3391184a349dfaa18c0f2fa33d6b27e07 | 1,764 | h | C | src/half_bridge.h | Melissabenford30/charge-controller-firmware | 3c9a6e49f1dd97848c826207f729c04b82d47b2b | [
"Apache-2.0"
] | 1 | 2021-08-17T07:57:50.000Z | 2021-08-17T07:57:50.000Z | src/half_bridge.h | mulles/charge-controller-firmware | 76ee3dc28ff0007ff973c9d782cada90117a9309 | [
"Apache-2.0"
] | null | null | null | src/half_bridge.h | mulles/charge-controller-firmware | 76ee3dc28ff0007ff973c9d782cada90117a9309 | [
"Apache-2.0"
] | null | null | null | /*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright (c) 2016 Martin Jäger / Libre Solar
*/
#ifndef HALF_BRIDGE_H_
#define HALF_BRIDGE_H_
#include <stdint.h>
/**
* @file
*
* @brief PWM timer functions for half bridge of DC/DC converter
*/
/**
* Initiatializes the registers to generate the PWM signal and sets duty
* cycle limits
*
* @param freq_kHz Switching frequency in kHz
* @param deadtime_ns Deadtime in ns between switching the two FETs on/off
* @param min_duty Minimum duty cycle (e.g. 0.5 for limiting input voltage)
* @param max_duty Maximum duty cycle (e.g. 0.97 for charge pump)
*/
void half_bridge_init(int freq_kHz, int deadtime_ns, float min_duty, float max_duty);
/**
* Set raw timer capture/compare register
*
* This function allows to change the PWM with minimum step size.
*
* @param ccr Timer CCR value (between 0 and ARR)
*/
void half_bridge_set_ccr(uint16_t ccr);
/**
* Get raw timer capture/compare register
*
* @returns Timer CCR value (between 0 and ARR)
*/
uint16_t half_bridge_get_ccr();
/**
* Get raw timer auto-reload register
*
* @returns Timer ARR value
*/
uint16_t half_bridge_get_arr();
/**
* Set the duty cycle of the PWM signal
*
* @param duty Duty cycle between 0.0 and 1.0
*/
void half_bridge_set_duty_cycle(float duty);
/**
* Read the currently set duty cycle
*
* @returns Duty cycle between 0.0 and 1.0
*/
float half_bridge_get_duty_cycle();
/**
* Start the PWM generation
*
* Important: Valid duty cycle / CCR has to be set before starting
*/
void half_bridge_start();
/**
* Stop the PWM generation
*/
void half_bridge_stop();
/**
* Get status of the PWM output
*
* @returns True if PWM output enabled
*/
bool half_bridge_enabled();
#endif /* HALF_BRIDGE_H_ */
| 20.511628 | 85 | 0.70805 |
d91d1b6f1b6b5707dc0d462f78aaac4bc433a791 | 34,905 | h | C | 3rdparty/openbw/openbw/sync.h | ratiotile/StardustDevEnvironment | 15c512b81579d8bd663db3fa8e0847d4c27f17e8 | [
"MIT"
] | 8 | 2020-09-29T17:11:15.000Z | 2022-01-29T20:41:33.000Z | 3rdparty/openbw/openbw/sync.h | ratiotile/StardustDevEnvironment | 15c512b81579d8bd663db3fa8e0847d4c27f17e8 | [
"MIT"
] | 1 | 2021-03-08T17:43:05.000Z | 2021-03-09T06:35:04.000Z | 3rdparty/openbw/openbw/sync.h | ratiotile/StardustDevEnvironment | 15c512b81579d8bd663db3fa8e0847d4c27f17e8 | [
"MIT"
] | 1 | 2021-03-01T04:31:30.000Z | 2021-03-01T04:31:30.000Z | #ifndef BWGAME_SYNC_H
#define BWGAME_SYNC_H
#include "bwgame.h"
#include "actions.h"
#include "replay.h"
#include "replay_saver.h"
#include <chrono>
#include <random>
#include <thread>
#include <functional>
#include <type_traits>
#include <typeinfo>
namespace bwgame {
struct sync_state {
struct scheduled_action {
uint8_t frame;
size_t data_begin;
size_t data_end;
};
int latency = 2;
bool is_first_bwapi_compatible_frame = true;
int game_starting_countdown = 0;
uint32_t start_game_seed = 0;
bool game_started = false;
struct uid_t {
std::array<uint32_t, 8> vals{};
static uid_t generate() {
uid_t r;
std::array<uint32_t, 8> arr;
arr[0] = 42;
arr[1] = (uint32_t)std::chrono::high_resolution_clock::now().time_since_epoch().count();
arr[2] = (uint32_t)std::hash<std::thread::id>()(std::this_thread::get_id());
arr[3] = (uint32_t)std::chrono::high_resolution_clock::now().time_since_epoch().count();
arr[4] = (uint32_t)std::chrono::steady_clock::now().time_since_epoch().count();
arr[5] = (uint32_t)std::chrono::high_resolution_clock::now().time_since_epoch().count();
arr[6] = (uint32_t)std::chrono::system_clock::now().time_since_epoch().count();
arr[7] = 1;
std::seed_seq seq(arr.begin(), arr.end());
seq.generate(r.vals.begin(), r.vals.end());
data_loading::crc32_t crc32;
const uint8_t* c = (const uint8_t*)arr.data();
size_t n = 32;
for (auto& v : r.vals) {
v ^= crc32(c, n);
c += 2;
n -= 2;
}
return r;
}
bool operator<(const uid_t& n) const {
return vals > n.vals;
}
bool operator==(const uid_t& n) const {
return vals == n.vals;
}
bool operator!=(const uid_t& n) const {
return vals != n.vals;
}
a_string str() {
a_string r;
for (auto& v : vals) r += format(r.empty() ? "%08x" : "-%08x", v);
return r;
}
};
struct client_t {
uid_t uid;
bool has_uid = false;
int local_id = 0;
int player_slot = -1;
const void* h = nullptr;
a_vector<uint8_t> buffer;
size_t buffer_begin = 0;
size_t buffer_end = 0;
a_circular_vector<scheduled_action> scheduled_actions;
uint8_t frame = 0;
a_string name;
bool game_started = false;
bool has_greeted = false;
std::chrono::steady_clock::time_point last_synced;
};
a_list<client_t> clients = {{uid_t::generate(), true}};
int next_client_id = 1;
client_t* local_client = &clients.front();
int sync_frame = 0;
bool has_initialized = false;
std::array<race_t, 12> initial_slot_races;
std::array<int, 12> initial_slot_controllers;
std::array<race_t, 12> picked_races;
bool game_type_melee = false;
game_load_functions::setup_info_t* setup_info = nullptr;
replay_saver_state* save_replay = nullptr;
std::array<a_string, 12> player_names;
int successful_action_count = 0;
int failed_action_count = 0;
std::array<uint32_t, 4> insync_hash{};
uint8_t insync_hash_index = 0;
};
struct sync_server_noop {
struct guard_t {
~guard_t() {
t.timeout_function = nullptr;
}
sync_server_noop& t;
};
struct message_t {
template<typename T>
void put(T v) {}
void put(const void* data, size_t size) {}
};
message_t new_message() {return {};}
void send_message(const message_t& d, const void* h) {}
void allow_send(const void* h, bool allow) {}
void kill_client(const void* h) {}
template<typename F>
void set_on_kill(const void* h, F&& f) {}
template<typename F>
void set_on_message(const void* h, F&& f) {}
std::chrono::steady_clock::time_point timeout_time;
std::function<void()> timeout_function;
template<typename duration_T, typename callback_F>
guard_t set_timeout_guarded(duration_T&& duration, callback_F&& callback) {
timeout_time = std::chrono::steady_clock::now() + duration;
timeout_function = std::forward<callback_F>(callback);
return guard_t{*this};
}
template<typename duration_T, typename callback_F>
void set_timeout(duration_T&& duration, callback_F&& callback) {
timeout_time = std::chrono::steady_clock::now() + duration;
timeout_function = std::forward<callback_F>(callback);
}
template<typename on_new_client_F>
void poll(on_new_client_F&& on_new_client) {
if (timeout_function && std::chrono::steady_clock::now() >= timeout_time) {
auto f = std::move(timeout_function);
timeout_function = nullptr;
f();
}
}
template<typename on_new_client_F>
void run_one(on_new_client_F&& on_new_client) {
if (timeout_function) {
while (std::chrono::steady_clock::now() < timeout_time) {
std::this_thread::sleep_until(timeout_time);
}
auto f = std::move(timeout_function);
timeout_function = nullptr;
f();
} else error("sync_server_noop::run_one: can't wait without a timeout");
}
template<typename on_new_client_F, typename pred_F>
void run_until(on_new_client_F&& on_new_client, pred_F&& pred) {
while (!pred()) {
run_one(on_new_client);
}
}
};
struct sync_functions: action_functions {
sync_state& sync_st;
explicit sync_functions(state& st, action_state& action_st, sync_state& sync_st) : action_functions(st, action_st), sync_st(sync_st) {}
std::function<void(int player_slot, data_loading::data_reader_le&)> on_custom_action;
template<typename action_F>
void execute_scheduled_actions(action_F&& action_f) {
for (auto i = sync_st.clients.begin(); i != sync_st.clients.end();) {
sync_state::client_t* c = &*i;
++i;
while (!c->scheduled_actions.empty() && (uint8_t)sync_st.sync_frame == c->scheduled_actions.front().frame) {
auto act = c->scheduled_actions.front();
c->scheduled_actions.pop_front();
c->buffer_begin = act.data_end;
const uint8_t* data = c->buffer.data();
if (data + act.data_end > data + c->buffer.size()) error("data beyond end");
data_loading::data_reader_le r(data + act.data_begin, data + act.data_end);
if (!action_f(c, r)) break;
}
}
}
void next_frame() = delete;
template<typename server_T>
void next_frame(server_T& server) {
sync(server);
action_functions::next_frame();
}
template<typename server_T>
void bwapi_compatible_next_frame(server_T& server) {
if (sync_st.is_first_bwapi_compatible_frame) sync_st.is_first_bwapi_compatible_frame = false;
else action_functions::next_frame();
sync(server);
}
template<typename reader_T>
bool schedule_action(sync_state::client_t* client, reader_T&& r) {
size_t n = r.left();
auto& buffer = client->buffer;
auto& buffer_begin = client->buffer_begin;
auto& buffer_end = client->buffer_end;
size_t pos = buffer_end;
size_t new_end = pos + n;
auto grow_buffer = [&]() {
const size_t max_size = 1024u * 4 * sync_st.latency;
size_t new_size = buffer.size() + buffer.size() / 2;
if (new_size > max_size) new_size = max_size;
size_t required_size = n;
for (auto& v : client->scheduled_actions) {
required_size += v.data_end - v.data_begin;
}
if (new_size < required_size) new_size = required_size;
//if (new_size >= max_size) error("action buffer is full for client (%d-%s)", client->local_id, client->uid.str());
if (new_size >= max_size) return false;
a_vector<uint8_t> new_buffer(new_size);
buffer_begin = 0;
size_t end = 0;
const uint8_t* src = buffer.data();
uint8_t* dst = new_buffer.data();
for (auto& v : client->scheduled_actions) {
size_t vn = v.data_end - v.data_begin;
std::memcpy(dst + end, src + v.data_begin, vn);
v.data_begin = end;
v.data_end = end + vn;
end += vn;
}
buffer = std::move(new_buffer);
buffer_end = end;
return true;
};
if (buffer_end < buffer_begin) {
if (new_end >= buffer_begin) {
if (!grow_buffer()) return false;
pos = buffer_end;
new_end = pos + n;
}
} else if (new_end > buffer.size()) {
if (n < buffer_begin) {
pos = 0;
new_end = n;
} else {
if (buffer.size() < new_end) {
if (!grow_buffer()) return false;
pos = buffer_end;
new_end = pos + n;
}
}
}
buffer_end = new_end;
r.get_bytes(buffer.data() + pos, n);
a_string str;
for (size_t i = 0; i != n; ++i) str += format("%02x", (buffer.data() + pos)[i]);
client->scheduled_actions.push_back({(uint8_t)(client->frame + sync_st.latency), pos, buffer_end});
return true;
}
bool schedule_action(sync_state::client_t* client, const uint8_t* data, size_t data_size) {
data_loading::data_reader_le r(data, data + data_size);
return schedule_action(client, r);
}
template<size_t max_size, bool default_little_endian = true>
struct writer {
std::array<uint8_t, max_size> arr;
size_t pos = 0;
template<typename T, bool little_endian = default_little_endian>
void put(T v) {
static_assert(std::is_integral<T>::value, "don't know how to write this type");
size_t n = pos;
skip(sizeof(T));
data_loading::set_value_at<little_endian>(data() + n, v);
}
void skip(size_t n) {
pos += n;
if (pos > arr.size()) error("sync_functions::writer: attempt to write past end");
}
void put_bytes(const uint8_t* src, size_t n) {
skip(n);
memcpy(data() + pos - n, src, n);
}
size_t size() const {
return pos;
}
const uint8_t* data() const {
return arr.data();
}
uint8_t* data() {
return arr.data();
}
};
template<bool default_little_endian = true>
struct dynamic_writer {
std::vector<uint8_t> vec;
size_t pos = 0;
dynamic_writer() = default;
dynamic_writer(size_t initial_size) : vec(initial_size) {}
template<typename T, bool little_endian = default_little_endian>
void put(T v) {
static_assert(std::is_integral<T>::value, "don't know how to write this type");
size_t n = pos;
skip(sizeof(T));
data_loading::set_value_at<little_endian>(data() + n, v);
}
void skip(size_t n) {
pos += n;
if (pos >= vec.size()) {
if (vec.size() < 2048) vec.resize(std::max(pos, vec.size() + vec.size()));
else vec.resize(std::max(pos, std::max(vec.size() + vec.size() / 2, (size_t)32)));
}
}
void put_bytes(const uint8_t* src, size_t n) {
skip(n);
memcpy(data() + pos - n, src, n);
}
size_t size() const {
return pos;
}
const uint8_t* data() const {
return vec.data();
}
uint8_t* data() {
return vec.data();
}
};
template<typename server_T>
struct syncer_t {
sync_functions& funcs;
server_T& server;
state& st;
sync_state& sync_st;
syncer_t(sync_functions& funcs, server_T& server) : funcs(funcs), server(server), st(funcs.st), sync_st(funcs.sync_st) {}
const uint32_t greeting_value = 0x39e25069;
void send(const uint8_t* data, size_t size, const void* h = nullptr) {
if (size == 0) error("attempt to send no data");
auto d = server.new_message();
d.put(data, size);
server.send_message(d, h);
if (!h || h == sync_st.local_client) recv(sync_st.local_client, data, size);
}
template<typename data_T>
void send(data_T&& data, const void* h = nullptr) {
send(data.data(), data.size(), h);
}
template<typename reader_T>
void recv(sync_state::client_t* client, reader_T&& r) {
auto t = r.tell();
int id = r.template get<uint8_t>();
switch (id) {
case sync_messages::id_client_frame:
client->frame = r.template get<uint8_t>();
break;
case sync_messages::id_client_uid: {
sync_state::uid_t uid;
for (auto& v : uid.vals) v = r.template get<uint32_t>();
if (get_client(uid)) {
this->kill_client(client);
} else {
size_t clients_with_uid = 0;
for (auto* c : ptr(sync_st.clients)) {
if (c->has_uid) ++clients_with_uid;
}
if (clients_with_uid >= 2) {
this->kill_client(client);
} else {
client->uid = uid;
client->has_uid = true;
client->name.clear();
client->name.reserve(31);
while (client->name.size() < 31) {
char c = r.template get<uint8_t>();
if (!c) break;
client->name += c;
}
for (int i = 0; i != 12; ++i) {
st.players[i].controller = sync_st.initial_slot_controllers[i];
st.players[i].race = sync_st.initial_slot_races[i];
}
for (auto* c : ptr(sync_st.clients)) {
c->player_slot = -1;
clear_scheduled_actions(c);
c->frame = 0;
}
sync_st.sync_frame = 0;
if (client->h) {
server.allow_send(client->h, true);
}
sync_st.clients.sort([&](auto& a, auto& b) {
return a.uid < b.uid;
});
}
}
break;
}
default:
if (!client->has_uid) kill_client(client);
else {
r.seek(t);
funcs.schedule_action(client, r);
}
}
}
void recv(sync_state::client_t* client, const uint8_t* data, size_t data_size) {
data_loading::data_reader_le r(data, data + data_size);
return recv(client, r);
}
void send_greeting(const void* h) {
auto d = server.new_message();
d.template put<uint32_t>(greeting_value);
d.template put<uint8_t>(sync_st.sync_frame);
server.send_message(d, h);
}
sync_state::client_t* get_client(const sync_state::uid_t& uid) {
for (auto& c : sync_st.clients) {
if (c.uid == uid) return &c;
}
return nullptr;
}
auto get_player_left_action(bool player_left) {
writer<2> w;
w.put<uint8_t>(87);
w.put<uint8_t>(player_left ? 0 : 6);
return w;
}
void kill_client(sync_state::client_t* client, bool player_left = false) {
if (client->player_slot != -1) {
if (sync_st.game_started) {
auto w = get_player_left_action(player_left);
data_loading::data_reader_le r(w.data(), w.data() + w.size());
if (sync_st.save_replay) replay_saver_functions(*sync_st.save_replay).add_action(st.current_frame, client->player_slot, w.data(), w.size());
if (funcs.read_action(client->player_slot, r)) ++sync_st.successful_action_count;
else ++sync_st.failed_action_count;
} else {
st.players[client->player_slot].controller = player_t::controller_open;
}
client->player_slot = -1;
}
if (client == sync_st.local_client) error("attempt to kill local client");
if (client->h) server.kill_client(client->h);
for (auto i = sync_st.clients.begin(); i != sync_st.clients.end(); ++i) {
if (&*i == client) {
sync_st.clients.erase(i);
break;
}
}
}
sync_state::client_t* new_client(const void* h) {
sync_st.clients.emplace_back();
sync_st.clients.back().local_id = sync_st.next_client_id++;
sync_st.clients.back().h = h;
sync_st.clients.back().last_synced = std::chrono::steady_clock::now();
return &sync_st.clients.back();
}
void send_uid(const void* h) {
writer<1 + 32 + 32> w;
w.put<uint8_t>(sync_messages::id_client_uid);
for (auto& v : sync_st.local_client->uid.vals) w.put<uint32_t>(v);
size_t n = 0;
for (char c : sync_st.local_client->name) {
if (n >= 31) break;
++n;
w.put<uint8_t>(c);
}
w.put<uint8_t>(0);
send(w, h);
}
void send_start_game() {
writer<5> w;
w.put<uint8_t>(sync_messages::id_start_game);
uint32_t seed = st.lcg_rand_state;
if (seed == 0) {
seed = 42;
for (uint32_t v : sync_state::uid_t::generate().vals) {
seed ^= v;
}
}
w.put<uint32_t>(seed);
send(w);
}
void send_switch_to_slot(int n) {
writer<3> w;
if (sync_st.game_started) w.put<uint8_t>(sync_messages::id_game_started_escape);
w.put<uint8_t>(sync_messages::id_occupy_slot);
w.put<uint8_t>(n);
send(w);
}
void send_set_race(race_t race) {
writer<2> w;
w.put<uint8_t>(sync_messages::id_set_race);
w.put<uint8_t>((int)race);
send(w);
}
void send_create_unit(const unit_type_t* unit_type, xy pos, int owner) {
writer<15> w;
if (sync_st.game_started) w.put<uint8_t>(sync_messages::id_game_started_escape);
w.put<uint8_t>(sync_messages::id_create_unit);
w.put<uint32_t>((int)unit_type->id);
w.put<int32_t>(pos.x);
w.put<int32_t>(pos.y);
w.put<uint8_t>(owner);
send(w);
}
void send_kill_unit(unit_t* u) {
writer<6> w;
if (sync_st.game_started) w.put<uint8_t>(sync_messages::id_game_started_escape);
w.put<uint8_t>(sync_messages::id_kill_unit);
w.put<uint32_t>(funcs.get_unit_id_32(u).raw_value);
send(w);
}
void send_remove_unit(unit_t* u) {
writer<6> w;
if (sync_st.game_started) w.put<uint8_t>(sync_messages::id_game_started_escape);
w.put<uint8_t>(sync_messages::id_remove_unit);
w.put<uint32_t>(funcs.get_unit_id_32(u).raw_value);
send(w);
}
void clear_scheduled_actions(sync_state::client_t* client) {
client->buffer.clear();
client->buffer_begin = 0;
client->buffer_end = 0;
client->scheduled_actions.clear();
}
void send_game_info(const void* h) {
dynamic_writer<> w(0x100);
w.put<uint8_t>(sync_messages::id_game_info);
for (sync_state::client_t* c : ptr(sync_st.clients)) {
if (c->uid == sync_state::uid_t{}) continue;
w.put<uint8_t>(1);
for (auto& v : c->uid.vals) w.put<uint32_t>(v);
w.put<int8_t>(c->player_slot);
if (c->player_slot == -1) w.put<int8_t>(-1);
else w.put<int8_t>((int)st.players.at(c->player_slot).race);
size_t n = std::min(c->name.size(), (size_t)0x20);
w.put<uint8_t>(n);
for (size_t i = 0; i != n; ++i) w.put<uint8_t>((uint8_t)*(c->name.data() + i));
}
w.put<uint8_t>(0);
send(w, h);
}
void on_new_client(const void* h) {
if (sync_st.game_started || sync_st.game_starting_countdown) {
server.kill_client(h);
return;
}
auto* c = new_client(h);
send_greeting(h);
send_uid(h);
auto frame = sync_st.sync_frame;
sync_st.sync_frame = 0;
sync_st.sync_frame = frame;
server.allow_send(h, false);
server.set_on_message(h, std::bind(&syncer_t::on_message, this, c, std::placeholders::_1, std::placeholders::_2));
server.set_on_kill(h, std::bind(&syncer_t::kill_client, this, c, false));
}
void on_message(sync_state::client_t* client, const void* data, size_t size) {
data_loading::data_reader_le r((const uint8_t*)data, (const uint8_t*)data + size);
if (!client->has_greeted) {
auto v = r.get<uint32_t>();
if (v != greeting_value) {
kill_client(client);
} else client->has_greeted = true;
return;
}
recv(client, (const uint8_t*)data, size);
}
void send_client_frame() {
writer<2> w;
w.put<uint8_t>(sync_messages::id_client_frame);
w.put<uint8_t>(sync_st.sync_frame);
send(w);
}
void timeout_func() {
auto now = std::chrono::steady_clock::now();
for (auto i = sync_st.clients.begin(); i != sync_st.clients.end();) {
auto* c = &*i;
++i;
if (now - c->last_synced >= std::chrono::seconds(60)) {
if ((int8_t)(sync_st.sync_frame - c->frame) >= (int8_t)sync_st.latency) {
kill_client(c);
}
}
}
server.set_timeout(std::chrono::seconds(1), std::bind(&syncer_t::timeout_func, this));
}
void update_insync_hash() {
uint32_t hash = 2166136261u;
auto add = [&](auto v) {
hash ^= (uint32_t)v;
hash *= 16777619u;
};
add(sync_st.successful_action_count);
add(sync_st.failed_action_count);
add(st.lcg_rand_state);
for (auto v : st.current_minerals) add(v);
for (auto v : st.current_gas) add(v);
for (auto v : st.total_minerals_gathered) add(v);
for (auto v : st.total_gas_gathered) add(v);
add(st.active_orders_size);
add(st.active_bullets_size);
add(st.active_thingies_size);
for (unit_t* u : ptr(st.visible_units)) {
add((u->shield_points + u->hp).raw_value);
add(u->exact_position.x.raw_value);
add(u->exact_position.y.raw_value);
}
if (sync_st.insync_hash_index == sync_st.insync_hash.size() - 1) sync_st.insync_hash_index = 0;
else ++sync_st.insync_hash_index;
sync_st.insync_hash[sync_st.insync_hash_index] = hash;
}
void send_insync_check() {
writer<7> w;
if (sync_st.game_started) w.put<uint8_t>(sync_messages::id_game_started_escape);
w.put<uint8_t>(sync_messages::id_insync_check);
w.put<uint8_t>(sync_st.insync_hash_index);
w.put<uint32_t>(sync_st.insync_hash[sync_st.insync_hash_index]);
send(w);
}
void send_game_started() {
writer<1> w;
w.put<uint8_t>(sync_messages::id_game_started);
send(w);
}
void send_leave_game() {
if (!sync_st.game_started) {
writer<1> w;
w.put<uint8_t>(sync_messages::id_leave_game);
send(w);
} else {
send(get_player_left_action(true));
}
}
void send_custom_action(const uint8_t* data, size_t size) {
if (size == 0) error("attempt to send no data");
dynamic_writer<> w;
if (sync_st.game_started) w.template put<uint8_t>(sync_messages::id_game_started_escape);
w.template put<uint8_t>(sync_messages::id_custom_action);
w.put_bytes(data, size);
send(w);
}
void start_game(uint32_t seed) {
// a_string seed_str;
// for (auto& v : sync_st.clients) seed_str += v.uid.str();
// uint32_t rand_state = seed ^ data_loading::crc32_t()((const uint8_t*)seed_str.data(), seed_str.size());
// st.lcg_rand_state = rand_state;
st.lcg_rand_state = seed;
for (int i = 0; i != 12; ++i) {
auto& v = st.players[i];
if (v.controller == player_t::controller_computer) {
v.controller = player_t::controller_occupied;
}
sync_st.picked_races[i] = v.race;
if (!funcs.player_slot_active(i)) {
v.controller = player_t::controller_inactive;
} else {
if ((int)v.race > 2) v.race = (bwgame::race_t)funcs.lcg_rand(144, 0, 2);
}
}
auto slot_available = [&](size_t index) {
auto c = sync_st.initial_slot_controllers[index];
if (c == player_t::controller_open) return true;
if (c == player_t::controller_computer) return true;
if (c == player_t::controller_rescue_passive) return true;
if (c == player_t::controller_unused_rescue_active) return true;
if (c == player_t::controller_neutral) return true;
return false;
};
auto randomize_slots = [&](auto pred) {
bwgame::static_vector<size_t, 12> available_slots;
for (auto& v : st.players) {
size_t index = (size_t)(&v - st.players.data());
if (slot_available(index) && pred(index)) {
size_t index = (size_t)(&v - st.players.data());
if (index < 8) available_slots.push_back(index);
}
}
for (size_t i = available_slots.size(); i > 1;) {
--i;
size_t old_index = available_slots[i];
size_t new_index = available_slots[funcs.lcg_rand(33, 0, i)];
if (old_index == new_index) continue;
std::swap(st.players[old_index], st.players[new_index]);
std::swap(sync_st.picked_races[old_index], sync_st.picked_races[new_index]);
for (auto* c : ptr(sync_st.clients)) {
if ((int)old_index == c->player_slot) c->player_slot = new_index;
else if ((int)new_index == c->player_slot) c->player_slot = old_index;
}
}
};
if (sync_st.game_type_melee) {
randomize_slots([](size_t){return true;});
} else {
for (int force = 1; force <= 4; ++force) {
randomize_slots([&](size_t index){return st.players.at(index).force == force;});
}
}
sync_st.game_started = true;
sync_st.clients.sort([&](auto& a, auto& b) {
if ((unsigned)a.player_slot != (unsigned)b.player_slot) return (unsigned)a.player_slot < (unsigned)b.player_slot;
return a.uid < b.uid;
});
send_game_started();
for (auto* c : ptr(sync_st.clients)) {
if (c->player_slot != -1) sync_st.player_names.at(c->player_slot) = c->name;
}
if (sync_st.save_replay) {
auto& r = *sync_st.save_replay;
r.random_seed = seed;
r.player_name = sync_st.local_client->name;
r.map_tile_width = st.game->map_tile_width;
r.map_tile_height = st.game->map_tile_height;
r.active_player_count = 1;
r.slot_count = range_size(funcs.active_players());
r.game_type = sync_st.game_type_melee ? 2 : 10;
r.tileset = st.game->tileset_index;
r.game_name = "openbw game";
r.map_name = st.game->scenario_name;
r.setup_info = *sync_st.setup_info;
r.players = st.players;
r.player_names = sync_st.player_names;
}
}
void process_messages() {
if (sync_st.game_starting_countdown) {
--sync_st.game_starting_countdown;
if (sync_st.game_starting_countdown == 0) {
start_game(sync_st.start_game_seed);
}
}
if (sync_st.game_started) {
funcs.execute_scheduled_actions([this](sync_state::client_t* client, auto& r) {
if (client->game_started) {
if (client->player_slot != -1) {
size_t begin_pos = r.tell();
int sync_message_id = r.template get<uint8_t>();
if (sync_message_id == sync_messages::id_game_started_escape) {
int id = r.template get<uint8_t>();
bool handled = true;
switch (id) {
case sync_messages::id_insync_check: {
uint8_t index = r.template get<uint8_t>();
uint32_t hash = r.template get<uint32_t>();
if (hash != sync_st.insync_hash.at(index)) {
this->kill_client(client);
}
break;
}
case sync_messages::id_custom_action: {
if (funcs.on_custom_action) funcs.on_custom_action(client->player_slot, r);
break;
}
case sync_messages::id_create_unit:
case sync_messages::id_kill_unit:
case sync_messages::id_remove_unit:
handled = false;
break;
}
if (handled)
return true;
}
r.seek(begin_pos);
if (sync_st.save_replay) {
size_t t = r.tell();
r.seek(begin_pos);
size_t n = r.left();
replay_saver_functions(*sync_st.save_replay).add_action(st.current_frame, client->player_slot, r.get_n(n), n);
r.seek(t);
}
funcs.read_action(client->player_slot, r);
if (st.players.at(client->player_slot).controller != player_t::controller_occupied) {
if (client != sync_st.local_client) this->kill_client(client);
else this->clear_scheduled_actions(client);
return false;
}
}
} else {
int id = r.template get<uint8_t>();
if (id == sync_messages::id_game_started) {
client->game_started = true;
}
}
return true;
});
} else {
funcs.execute_scheduled_actions([this](sync_state::client_t* client, auto& r) {
int id = r.template get<uint8_t>();
switch (id) {
case sync_messages::id_game_info:
while (r.template get<uint8_t>() != 0) {
sync_state::uid_t uid;
for (auto& v : uid.vals) v = r.template get<uint32_t>();
sync_state::client_t* c = this->get_client(uid);
if (!c) {
c = this->new_client(nullptr);
c->uid = uid;
}
c->player_slot = r.template get<int8_t>();
if (c->player_slot < 0 || c->player_slot >= 12) c->player_slot = -1;
int race = r.template get<int8_t>();
if (c->player_slot != -1) {
for (auto* c2 : ptr(sync_st.clients)) {
if (c != c2 && c2->player_slot == c->player_slot) c2->player_slot = -1;
}
st.players[c->player_slot].controller = player_t::controller_occupied;
st.players[c->player_slot].race = (bwgame::race_t)race;
}
size_t n = r.template get<uint8_t>();
c->name.resize(std::min(n, (size_t)0x20));
for (size_t i = 0; i != n; ++i) {
if (i < c->name.size()) c->name[i] = (char)r.template get<uint8_t>();
}
}
break;
case sync_messages::id_occupy_slot: {
int n = r.template get<uint8_t>();
for (int i = 0; i != 12; ++i) {
if (i == n && st.players[i].controller == player_t::controller_open) {
race_t race = sync_st.initial_slot_races[i];
if (client->player_slot != -1) {
race = st.players[client->player_slot].race;
st.players[client->player_slot].controller = player_t::controller_open;
st.players[client->player_slot].race = sync_st.initial_slot_races[client->player_slot];
}
client->player_slot = i;
st.players[i].controller = player_t::controller_occupied;
if (sync_st.initial_slot_races[i] == (bwgame::race_t)5) {
st.players[i].race = race;
}
break;
}
}
break;
}
case sync_messages::id_set_race: {
race_t race = (race_t)r.template get<uint8_t>();
if (client->player_slot != -1) {
if (sync_st.initial_slot_races[client->player_slot] == (bwgame::race_t)5) {
st.players[client->player_slot].race = race;
}
}
break;
}
case sync_messages::id_start_game:
if (!sync_st.game_starting_countdown) {
sync_st.game_starting_countdown = 10;
sync_st.start_game_seed = r.template get<uint32_t>();
}
break;
case sync_messages::id_leave_game:
if (client != sync_st.local_client) this->kill_client(client);
else this->clear_scheduled_actions(client);
return false;
default: error("unknown pre game message id %d", id);
}
return true;
});
}
}
void sync_next_frame() {
if (!sync_st.has_initialized) {
if (!sync_st.setup_info) error("sync_state::setup_info is null");
sync_st.has_initialized = true;
for (int i = 0; i != 12; ++i) {
sync_st.initial_slot_races[i] = st.players[i].race;
sync_st.initial_slot_controllers[i] = st.players[i].controller;
sync_st.picked_races[i] = st.players[i].race;
}
}
++sync_st.sync_frame;
send_client_frame();
if (sync_st.game_started && sync_st.sync_frame % 32 == 0) {
update_insync_hash();
send_insync_check();
}
}
bool all_clients_in_sync() {
for (auto* c : ptr(sync_st.clients)) {
if ((int8_t)(sync_st.sync_frame - c->frame) >= (int8_t)sync_st.latency) {
return false;
}
}
return true;
}
void sync() {
sync_next_frame();
server.poll(std::bind(&syncer_t::on_new_client, this, std::placeholders::_1));
auto pred = [this]() {
return all_clients_in_sync();
};
if (!sync_st.game_started && !sync_st.game_starting_countdown && pred()) {
auto any_scheduled_actions = [&]() {
for (auto& c : sync_st.clients) {
if (!c.scheduled_actions.empty()) return true;
}
return false;
};
{
bool timed_out = false;
auto g = server.set_timeout_guarded(std::chrono::milliseconds(50), [&]{
timed_out = true;
});
while (!any_scheduled_actions() && !timed_out) {
server.run_one(std::bind(&syncer_t::on_new_client, this, std::placeholders::_1));
}
}
if (!pred()) {
server.set_timeout(std::chrono::seconds(1), std::bind(&syncer_t::timeout_func, this));
server.run_until(std::bind(&syncer_t::on_new_client, this, std::placeholders::_1), pred);
}
} else {
server.set_timeout(std::chrono::seconds(1), std::bind(&syncer_t::timeout_func, this));
server.run_until(std::bind(&syncer_t::on_new_client, this, std::placeholders::_1), pred);
}
auto now = std::chrono::steady_clock::now();
for (auto& c : sync_st.clients) {
c.last_synced = now;
}
process_messages();
}
void final_sync() {
bool timed_out = false;
auto g = server.set_timeout_guarded(std::chrono::milliseconds(250), [&]{
timed_out = true;
});
while (!sync_st.local_client->scheduled_actions.empty() && !timed_out) {
sync_next_frame();
server.poll(std::bind(&syncer_t::on_new_client, this, std::placeholders::_1));
while (!all_clients_in_sync() && !timed_out) {
server.run_one(std::bind(&syncer_t::on_new_client, this, std::placeholders::_1));
}
if (!timed_out) process_messages();
}
}
void leave_game() {
send_leave_game();
final_sync();
}
};
struct syncer_container_t {
static const size_t size = 0x40;
static const size_t alignment = alignof(std::max_align_t);
const std::type_info* type = nullptr;
const void* server_ptr = nullptr;
std::aligned_storage<size, alignment>::type obj;
void (syncer_container_t::* destroy_f)();
syncer_container_t() = default;
syncer_container_t(const syncer_container_t&) = delete;
syncer_container_t& operator=(const syncer_container_t&) = delete;
~syncer_container_t() {
destroy();
}
void destroy() {
if (type) (this->*destroy_f)();
}
template<typename T, typename server_T>
void construct(sync_functions& funcs, server_T& server) {
static_assert(sizeof(T) <= size || alignof(T) <= alignment, "syncer_container_t size or alignment too small");
new ((T*)&obj) T(funcs, server);
type = &typeid(T);
server_ptr = &server;
destroy_f = &syncer_container_t::destroy<T>;
}
template<typename T>
void destroy() {
as<T>().~T();
type = nullptr;
}
template<typename T>
T& as() {
static_assert(sizeof(T) <= size || alignof(T) <= alignment, "syncer_container_t size or alignment too small");
return (T&)obj;
}
template<typename T, typename server_T>
T& get(sync_functions& funcs, server_T& server) {
if (type) {
if (type == &typeid(T) || *type == typeid(T)) {
if (server_ptr == &server) return as<T>();
}
error("sync_functions::syncer_container_t: attempt to use multiple servers in the same instance");
}
construct<T>(funcs, server);
return as<T>();
}
};
syncer_container_t syncer_container;
template<typename server_T>
syncer_t<server_T>& get_syncer(server_T& server) {
return syncer_container.get<syncer_t<server_T>>(*this, server);
}
template<typename server_T>
void sync(server_T& server) {
get_syncer(server).sync();
}
template<typename server_T>
void start_game(server_T& server) {
if (sync_st.game_started) return;
get_syncer(server).send_start_game();
}
template<typename server_T>
void switch_to_slot(server_T& server, int n) {
get_syncer(server).send_switch_to_slot(n);
}
void set_local_client_name(a_string name) {
if (sync_st.game_started) return;
sync_st.local_client->name = std::move(name);
}
template<typename server_T>
void set_local_client_race(server_T& server, race_t race) {
if (sync_st.game_started) return;
get_syncer(server).send_set_race(race);
}
template<typename server_T>
void input_action(server_T& server, const uint8_t* data, size_t size) {
get_syncer(server).send(data, size);
}
template<typename server_T>
void leave_game(server_T& server) {
get_syncer(server).leave_game();
}
int connected_player_count() {
int clients_with_uid = 0;
for (auto* c : ptr(sync_st.clients)) {
if (c->has_uid) ++clients_with_uid;
}
return clients_with_uid;
}
template<typename server_T>
void create_unit(server_T& server, const unit_type_t* unit_type, xy pos, int owner) {
get_syncer(server).send_create_unit(unit_type, pos, owner);
}
template<typename server_T>
void kill_unit(server_T& server, unit_t* u) {
get_syncer(server).send_kill_unit(u);
}
template<typename server_T>
void remove_unit(server_T& server, unit_t* u) {
get_syncer(server).send_remove_unit(u);
}
template<typename server_T>
void send_custom_action(server_T& server, const void* data, size_t size) {
get_syncer(server).send_custom_action((const uint8_t*)data, size);
}
};
}
#endif
| 30.834806 | 145 | 0.65091 |
d95f28301a7a092b178c654014c4aace6b7d9cbe | 1,199 | h | C | Resources/WC_7_0_5_Headers/WCPayLQTTransSuccessViewController.h | shuangwei-Ye/WeChat_tweak | 0f496f38f0336908258d606dcbef7067a096926a | [
"MIT"
] | 2 | 2021-05-30T07:50:20.000Z | 2022-02-23T15:42:53.000Z | Resources/WC_7_0_5_Headers/WCPayLQTTransSuccessViewController.h | LP36911/WeChat_tweak | 0f496f38f0336908258d606dcbef7067a096926a | [
"MIT"
] | null | null | null | Resources/WC_7_0_5_Headers/WCPayLQTTransSuccessViewController.h | LP36911/WeChat_tweak | 0f496f38f0336908258d606dcbef7067a096926a | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "WCPayBaseViewController.h"
#import "ILinkEventExt.h"
@class NSString;
@interface WCPayLQTTransSuccessViewController : WCPayBaseViewController <ILinkEventExt>
{
_Bool _hasResportGuideCell;
id <WCPayLQTTransSuccessViewControllerDelegate> _delegate;
}
- (void).cxx_destruct;
- (void)confirmBtnClick;
- (void)dealloc;
@property(nonatomic) __weak id <WCPayLQTTransSuccessViewControllerDelegate> delegate; // @synthesize delegate=_delegate;
- (_Bool)hasLQTCell;
@property(nonatomic) _Bool hasResportGuideCell; // @synthesize hasResportGuideCell=_hasResportGuideCell;
- (_Bool)hasUpgradeLink;
- (id)navigationBarBackgroundColor;
- (void)onLinkClicked:(id)arg1 withRect:(struct CGRect)arg2;
- (void)reportGuideCellExposureInfo;
- (void)setupContentView;
- (void)tapOnPlanCell;
- (void)viewDidLayoutSubviews;
- (void)viewDidLoad;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 28.547619 | 120 | 0.778982 |
269da32d6dfed74fe39e9c9fb97eb472337c05fa | 3,971 | h | C | src/vt/sequence/seq_state.h | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 26 | 2019-11-26T08:36:15.000Z | 2022-02-15T17:13:21.000Z | src/vt/sequence/seq_state.h | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 1,215 | 2019-09-09T14:31:33.000Z | 2022-03-30T20:20:14.000Z | src/vt/sequence/seq_state.h | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 12 | 2019-09-08T00:03:05.000Z | 2022-02-23T21:28:35.000Z | /*
//@HEADER
// *****************************************************************************
//
// seq_state.h
// DARMA/vt => Virtual Transport
//
// Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// 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.
//
// Questions? Contact darma@sandia.gov
//
// *****************************************************************************
//@HEADER
*/
#if !defined INCLUDED_VT_SEQUENCE_SEQ_STATE_H
#define INCLUDED_VT_SEQUENCE_SEQ_STATE_H
#include <list>
#include <unordered_map>
#include "vt/config.h"
#include "vt/sequence/seq_common.h"
#include "vt/sequence/seq_action.h"
namespace vt { namespace seq {
template <typename MessageT, ActiveTypedFnType<MessageT>* f>
struct SeqMsgState {
using ActionType = Action<MessageT>;
template <typename T>
using TagContainerType = std::unordered_map<TagType, T>;
template <typename T>
using ContainerType = std::list<T>;
using ActionContainerType = ContainerType<ActionType>;
using TaggedActionContainerType = TagContainerType<ActionContainerType>;
using MsgContainerType = ContainerType<MsgSharedPtr<MessageT>>;
using TaggedMsgContainerType = TagContainerType<std::list<MsgSharedPtr<MessageT>>>;
// waiting actions on matching message arrival
static ActionContainerType seq_action;
static TaggedActionContainerType seq_action_tagged;
// waiting messages on matching action arrival
static MsgContainerType seq_msg;
static TaggedMsgContainerType seq_msg_tagged;
};
template <typename MessageT, ActiveTypedFnType<MessageT>* f>
using SeqStateType = SeqMsgState<MessageT, f>;
template <typename MessageT, ActiveTypedFnType<MessageT>* f>
typename SeqMsgState<MessageT, f>::ActionContainerType SeqMsgState<MessageT, f>::seq_action;
template <typename MessageT, ActiveTypedFnType<MessageT>* f>
typename SeqMsgState<MessageT, f>::TaggedActionContainerType SeqMsgState<MessageT, f>::seq_action_tagged;
template <typename MessageT, ActiveTypedFnType<MessageT>* f>
typename SeqMsgState<MessageT, f>::MsgContainerType SeqMsgState<MessageT, f>::seq_msg;
template <typename MessageT, ActiveTypedFnType<MessageT>* f>
typename SeqMsgState<MessageT, f>::TaggedMsgContainerType SeqMsgState<MessageT, f>::seq_msg_tagged;
}} //end namespace vt::seq
#endif /* INCLUDED_VT_SEQUENCE_SEQ_STATE_H*/
| 40.111111 | 105 | 0.740116 |
143b77d6aa5df8cc35282a2fe03954edc2180f3f | 62,165 | h | C | DDKInclude/wiadef.h | MSDN-WhiteKnight/DiskView | 49f488a074e1318494409dab003ddd1a40cc3ed5 | [
"WTFPL"
] | 1 | 2019-05-27T02:10:54.000Z | 2019-05-27T02:10:54.000Z | DDKInclude/wiadef.h | MSDN-WhiteKnight/DiskView | 49f488a074e1318494409dab003ddd1a40cc3ed5 | [
"WTFPL"
] | null | null | null | DDKInclude/wiadef.h | MSDN-WhiteKnight/DiskView | 49f488a074e1318494409dab003ddd1a40cc3ed5 | [
"WTFPL"
] | null | null | null | /****************************************************************************
*
* (C) COPYRIGHT 1998-2000, MICROSOFT CORP.
*
* FILE: wiadef.h
*
* VERSION: 2.0
*
* DATE: 7/27/2000
*
* DESCRIPTION:
* Defines WIA constants.
*
*****************************************************************************/
#ifndef _WIADEF_H_
#define _WIADEF_H_
//
// Set packing
//
#include <pshpack8.h>
//
// Include COM definitions
//
#ifndef _NO_COM
#include <objbase.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/**************************************************************************
*
* WIA Errors
*
***************************************************************************/
//
// Define the facility code. Move this to sdk\inc???
//
#define FACILITY_WIA 33
//
// Definitions for WIA_ERRORs and WIA_STATUSs. Applications can test for these returns
// on API return, to keep users informed of conditions which a user
// could correct.
//
#define BASE_VAL_WIA_ERROR 0x00000000
#define BASE_VAL_WIA_SUCCESS 0x00000000
#define WIA_ERROR_GENERAL_ERROR MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 1))
#define WIA_ERROR_PAPER_JAM MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 2))
#define WIA_ERROR_PAPER_EMPTY MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 3))
#define WIA_ERROR_PAPER_PROBLEM MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 4))
#define WIA_ERROR_OFFLINE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 5))
#define WIA_ERROR_BUSY MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 6))
#define WIA_ERROR_WARMING_UP MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 7))
#define WIA_ERROR_USER_INTERVENTION MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 8))
#define WIA_ERROR_ITEM_DELETED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 9))
#define WIA_ERROR_DEVICE_COMMUNICATION MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 10))
#define WIA_ERROR_INVALID_COMMAND MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 11))
#define WIA_ERROR_INCORRECT_HARDWARE_SETTING MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 12))
#define WIA_ERROR_DEVICE_LOCKED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 13))
#define WIA_ERROR_EXCEPTION_IN_DRIVER MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 14))
#define WIA_ERROR_INVALID_DRIVER_RESPONSE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 15))
#define WIA_STATUS_END_OF_MEDIA MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_WIA, (BASE_VAL_WIA_SUCCESS + 1))
//
// Returned by SelectDeviceDlg and SelectDeviceDlgId when there are no devices avaiable
//
#define WIA_S_NO_DEVICE_AVAILABLE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIA, (BASE_VAL_WIA_ERROR + 21))
//
// SelectDeviceDlg & GetImageDlg flags
//
#define WIA_SELECT_DEVICE_NODEFAULT 0x00000001
//
// GetImageDlg & DeviceDlg flags
//
#define WIA_DEVICE_DIALOG_SINGLE_IMAGE 0x00000002 // Only allow one image to be selected
#define WIA_DEVICE_DIALOG_USE_COMMON_UI 0x00000004 // Give preference to the system-provided UI, if available
//**************************************************************************
//
// Image types
//
//**************************************************************************
DEFINE_GUID(WiaImgFmt_UNDEFINED, 0xb96b3ca9,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_RAWRGB, 0xbca48b55,0xf272,0x4371,0xb0,0xf1,0x4a,0x15,0xd,0x5,0x7b,0xb4);
DEFINE_GUID(WiaImgFmt_MEMORYBMP, 0xb96b3caa,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_BMP, 0xb96b3cab,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_EMF, 0xb96b3cac,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_WMF, 0xb96b3cad,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_JPEG, 0xb96b3cae,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_PNG, 0xb96b3caf,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_GIF, 0xb96b3cb0,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_TIFF, 0xb96b3cb1,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_EXIF, 0xb96b3cb2,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_PHOTOCD, 0xb96b3cb3,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_FLASHPIX, 0xb96b3cb4,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(WiaImgFmt_ICO, 0xb96b3cb5,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
// Canon Image File Format
DEFINE_GUID(WiaImgFmt_CIFF,0x9821a8ab,0x3a7e,0x4215,0x94,0xe0,0xd2,0x7a,0x46,0x0c,0x03,0xb2);
// Quickdraw Image Format
DEFINE_GUID(WiaImgFmt_PICT,0xa6bc85d8,0x6b3e,0x40ee,0xa9,0x5c,0x25,0xd4,0x82,0xe4,0x1a,0xdc);
// JPEG 2000 baseline file format
DEFINE_GUID(WiaImgFmt_JPEG2K,0x344ee2b2,0x39db,0x4dde,0x81,0x73,0xc4,0xb7,0x5f,0x8f,0x1e,0x49);
// JPEG 2000 extended file format
DEFINE_GUID(WiaImgFmt_JPEG2KX,0x43e14614,0xc80a,0x4850,0xba,0xf3,0x4b,0x15,0x2d,0xc8,0xda,0x27);
//**************************************************************************
//
// Document and other types
//
// Note: HTML, AVI, and MPEG used to have different GUIDs. Use the GUIDs
// defined below from now on.
//
//**************************************************************************
DEFINE_GUID(WiaImgFmt_RTF, 0x573dd6a3,0x4834,0x432d,0xa9,0xb5,0xe1,0x98,0xdd,0x9e,0x89,0xd);
DEFINE_GUID(WiaImgFmt_XML, 0xb9171457,0xdac8,0x4884,0xb3,0x93,0x15,0xb4,0x71,0xd5,0xf0,0x7e);
DEFINE_GUID(WiaImgFmt_HTML, 0xc99a4e62,0x99de,0x4a94,0xac,0xca,0x71,0x95,0x6a,0xc2,0x97,0x7d);
DEFINE_GUID(WiaImgFmt_TXT, 0xfafd4d82,0x723f,0x421f,0x93,0x18,0x30,0x50,0x1a,0xc4,0x4b,0x59);
DEFINE_GUID(WiaImgFmt_MPG, 0xecd757e4,0xd2ec,0x4f57,0x95,0x5d,0xbc,0xf8,0xa9,0x7c,0x4e,0x52);
DEFINE_GUID(WiaImgFmt_AVI, 0x32f8ca14,0x87c,0x4908,0xb7,0xc4,0x67,0x57,0xfe,0x7e,0x90,0xab);
DEFINE_GUID(WiaImgFmt_ASF, 0x8d948ee9,0xd0aa,0x4a12,0x9d,0x9a,0x9c,0xc5,0xde,0x36,0x19,0x9b);
DEFINE_GUID(WiaImgFmt_SCRIPT, 0xfe7d6c53,0x2dac,0x446a,0xb0,0xbd,0xd7,0x3e,0x21,0xe9,0x24,0xc9);
DEFINE_GUID(WiaImgFmt_EXEC, 0x485da097,0x141e,0x4aa5,0xbb,0x3b,0xa5,0x61,0x8d,0x95,0xd0,0x2b);
DEFINE_GUID(WiaImgFmt_UNICODE16,0x1b7639b6,0x6357,0x47d1,0x9a,0x07,0x12,0x45,0x2d,0xc0,0x73,0xe9);
DEFINE_GUID(WiaImgFmt_DPOF,0x369eeeab,0xa0e8,0x45ca,0x86,0xa6,0xa8,0x3c,0xe5,0x69,0x7e,0x28);
//**************************************************************************
//
// Audio types
//
//**************************************************************************
DEFINE_GUID(WiaAudFmt_WAV, 0xf818e146,0x07af,0x40ff,0xae,0x55,0xbe,0x8f,0x2c,0x06,0x5d,0xbe);
DEFINE_GUID(WiaAudFmt_MP3, 0x0fbc71fb,0x43bf,0x49f2,0x91,0x90,0xe6,0xfe,0xcf,0xf3,0x7e,0x54);
DEFINE_GUID(WiaAudFmt_AIFF, 0x66e2bf4f,0xb6fc,0x443f,0x94,0xc8,0x2f,0x33,0xc8,0xa6,0x5a,0xaf);
DEFINE_GUID(WiaAudFmt_WMA, 0xd61d6413,0x8bc2,0x438f,0x93,0xad,0x21,0xbd,0x48,0x4d,0xb6,0xa1);
//**************************************************************************
//
// WIA Events
//
//**************************************************************************
//
// Event registration flags, used by RegisterEventLaunch,
// RegisterEventCallbackInterface and RegisterEventCallbackCLSID.
//
#define WIA_REGISTER_EVENT_CALLBACK 0x00000001
#define WIA_UNREGISTER_EVENT_CALLBACK 0x00000002
#define WIA_SET_DEFAULT_HANDLER 0x00000004
//
// Event type : individual bits of the possible event type combinations
//
#define WIA_NOTIFICATION_EVENT 0x00000001
#define WIA_ACTION_EVENT 0x00000002
//
// Flag to indicate the corresponding persistent handler is default
//
#define WIA_IS_DEFAULT_HANDLER 0x00000001
//
// Event GUIDs
//
DEFINE_GUID(WIA_EVENT_DEVICE_DISCONNECTED, 0x143e4e83, 0x6497, 0x11d2, 0xa2, 0x31, 0x0, 0xc0, 0x4f, 0xa3, 0x18, 0x9);
DEFINE_GUID(WIA_EVENT_DEVICE_CONNECTED, 0xa28bbade, 0x64b6, 0x11d2, 0xa2, 0x31, 0x0, 0xc0, 0x4f, 0xa3, 0x18, 0x9);
DEFINE_GUID(WIA_EVENT_ITEM_DELETED, 0x1d22a559, 0xe14f, 0x11d2, 0xb3, 0x26, 0x00, 0xc0, 0x4f, 0x68, 0xce, 0x61);
DEFINE_GUID(WIA_EVENT_ITEM_CREATED, 0x4c8f4ef5, 0xe14f, 0x11d2, 0xb3, 0x26, 0x00, 0xc0, 0x4f, 0x68, 0xce, 0x61);
DEFINE_GUID(WIA_EVENT_TREE_UPDATED, 0xc9859b91, 0x4ab2, 0x4cd6, 0xa1, 0xfc, 0x58, 0x2e, 0xec, 0x55, 0xe5, 0x85);
DEFINE_GUID(WIA_EVENT_VOLUME_INSERT, 0x9638bbfd, 0xd1bd, 0x11d2, 0xb3, 0x1f, 0x00, 0xc0, 0x4f, 0x68, 0xce, 0x61);
DEFINE_GUID(WIA_EVENT_SCAN_IMAGE, 0xa6c5a715, 0x8c6e, 0x11d2, 0x97, 0x7a, 0x0, 0x0, 0xf8, 0x7a, 0x92, 0x6f);
DEFINE_GUID(WIA_EVENT_SCAN_PRINT_IMAGE, 0xb441f425, 0x8c6e, 0x11d2, 0x97, 0x7a, 0x0, 0x0, 0xf8, 0x7a, 0x92, 0x6f);
DEFINE_GUID(WIA_EVENT_SCAN_FAX_IMAGE, 0xc00eb793, 0x8c6e, 0x11d2, 0x97, 0x7a, 0x0, 0x0, 0xf8, 0x7a, 0x92, 0x6f);
DEFINE_GUID(WIA_EVENT_SCAN_OCR_IMAGE, 0x9d095b89, 0x37d6, 0x4877, 0xaf, 0xed, 0x62, 0xa2, 0x97, 0xdc, 0x6d, 0xbe);
DEFINE_GUID(WIA_EVENT_SCAN_EMAIL_IMAGE, 0xc686dcee, 0x54f2, 0x419e, 0x9a, 0x27, 0x2f, 0xc7, 0xf2, 0xe9, 0x8f, 0x9e);
DEFINE_GUID(WIA_EVENT_SCAN_FILM_IMAGE, 0x9b2b662c, 0x6185, 0x438c, 0xb6, 0x8b, 0xe3, 0x9e, 0xe2, 0x5e, 0x71, 0xcb);
DEFINE_GUID(WIA_EVENT_SCAN_IMAGE2, 0xfc4767c1, 0xc8b3, 0x48a2, 0x9c, 0xfa, 0x2e, 0x90, 0xcb, 0x3d, 0x35, 0x90);
DEFINE_GUID(WIA_EVENT_SCAN_IMAGE3, 0x154e27be, 0xb617, 0x4653, 0xac, 0xc5, 0xf, 0xd7, 0xbd, 0x4c, 0x65, 0xce);
DEFINE_GUID(WIA_EVENT_SCAN_IMAGE4, 0xa65b704a, 0x7f3c, 0x4447, 0xa7, 0x5d, 0x8a, 0x26, 0xdf, 0xca, 0x1f, 0xdf);
DEFINE_GUID(WIA_EVENT_STORAGE_CREATED, 0x353308b2, 0xfe73, 0x46c8, 0x89, 0x5e, 0xfa, 0x45, 0x51, 0xcc, 0xc8, 0x5a);
DEFINE_GUID(WIA_EVENT_STORAGE_DELETED, 0x5e41e75e, 0x9390, 0x44c5, 0x9a, 0x51, 0xe4, 0x70, 0x19, 0xe3, 0x90, 0xcf);
DEFINE_GUID(WIA_EVENT_STI_PROXY, 0xd711f81f, 0x1f0d, 0x422d, 0x86, 0x41, 0x92, 0x7d, 0x1b, 0x93, 0xe5, 0xe5);
DEFINE_GUID(WIA_EVENT_CANCEL_IO, 0xc860f7b8, 0x9ccd, 0x41ea, 0xbb, 0xbf, 0x4d, 0xd0, 0x9c, 0x5b, 0x17, 0x95);
//
// Power management event GUIDs, sent by the WIA service to drivers
//
DEFINE_GUID(WIA_EVENT_POWER_SUSPEND, 0xa0922ff9, 0xc3b4, 0x411c, 0x9e, 0x29, 0x03, 0xa6, 0x69, 0x93, 0xd2, 0xbe);
DEFINE_GUID(WIA_EVENT_POWER_RESUME, 0x618f153e, 0xf686, 0x4350, 0x96, 0x34, 0x41, 0x15, 0xa3, 0x04, 0x83, 0x0c);
//
// No action handler and prompt handler
//
DEFINE_GUID(WIA_EVENT_HANDLER_NO_ACTION, 0xe0372b7d, 0xe115, 0x4525, 0xbc, 0x55, 0xb6, 0x29, 0xe6, 0x8c, 0x74, 0x5a);
DEFINE_GUID(WIA_EVENT_HANDLER_PROMPT, 0x5f4baad0, 0x4d59, 0x4fcd, 0xb2, 0x13, 0x78, 0x3c, 0xe7, 0xa9, 0x2f, 0x22);
#define WIA_EVENT_DEVICE_DISCONNECTED_STR L"Device Disconnected"
#define WIA_EVENT_DEVICE_CONNECTED_STR L"Device Connected"
//**************************************************************************
//
// WIA Commands
//
//**************************************************************************
DEFINE_GUID(WIA_CMD_SYNCHRONIZE, 0x9b26b7b2, 0xacad, 0x11d2, 0xa0, 0x93, 0x00, 0xc0, 0x4f, 0x72, 0xdc, 0x3c);
DEFINE_GUID(WIA_CMD_TAKE_PICTURE, 0xaf933cac, 0xacad, 0x11d2, 0xa0, 0x93, 0x00, 0xc0, 0x4f, 0x72, 0xdc, 0x3c);
DEFINE_GUID(WIA_CMD_DELETE_ALL_ITEMS, 0xe208c170, 0xacad, 0x11d2, 0xa0, 0x93, 0x00, 0xc0, 0x4f, 0x72, 0xdc, 0x3c);
DEFINE_GUID(WIA_CMD_CHANGE_DOCUMENT, 0x04e725b0, 0xacae, 0x11d2, 0xa0, 0x93, 0x00, 0xc0, 0x4f, 0x72, 0xdc, 0x3c);
DEFINE_GUID(WIA_CMD_UNLOAD_DOCUMENT, 0x1f3b3d8e, 0xacae, 0x11d2, 0xa0, 0x93, 0x00, 0xc0, 0x4f, 0x72, 0xdc, 0x3c);
DEFINE_GUID(WIA_CMD_DIAGNOSTIC, 0x10ff52f5, 0xde04, 0x4cf0, 0xa5, 0xad, 0x69, 0x1f, 0x8d, 0xce, 0x01, 0x41);
//
// The following are private commands for debugging use only.
//
DEFINE_GUID(WIA_CMD_DELETE_DEVICE_TREE, 0x73815942, 0xdbea, 0x11d2, 0x84, 0x16, 0x00, 0xc0, 0x4f, 0xa3, 0x61, 0x45);
DEFINE_GUID(WIA_CMD_BUILD_DEVICE_TREE, 0x9cba5ce0, 0xdbea, 0x11d2, 0x84, 0x16, 0x00, 0xc0, 0x4f, 0xa3, 0x61, 0x45);
//**************************************************************************
//
// WIA Icons
//
// Event : -1000 to -1499 (Standard), -1500 to -1999 (Custom)
// Command : -2000 to -2499 (Standard), -2500 to -2999 (Custom)
//
//**************************************************************************
#define WIA_ICON_DEVICE_DISCONNECTED (L"sti.dll,-1001")
#define WIA_ICON_DEVICE_CONNECTED (L"sti.dll,-1001")
#define WIA_ICON_ITEM_DELETED (L"sti.dll,-1001")
#define WIA_ICON_ITEM_CREATED (L"sti.dll,-1001")
#define WIA_ICON_VOLUME_INSERT (L"sti.dll,-1001")
#define WIA_ICON_SCAN_BUTTON_PRESS (L"sti.dll,-1001")
#define WIA_ICON_SYNCHRONIZE (L"sti.dll,-2000")
#define WIA_ICON_TAKE_PICTURE (L"sti.dll,-2001")
#define WIA_ICON_DELETE_ALL_ITEMS (L"sti.dll,-2002")
#define WIA_ICON_CHANGE_DOCUMENT (L"sti.dll,-2003")
#define WIA_ICON_UNLOAD_DOCUMENT (L"sti.dll,-2004")
#define WIA_ICON_DELETE_DEVICE_TREE (L"sti.dll,-2005")
#define WIA_ICON_BUILD_DEVICE_TREE (L"sti.dll,-2006")
//**************************************************************************
//
// WIA Callbacks
//
//**************************************************************************
//
// IImageTransfer TYMED
//
#define TYMED_CALLBACK 128
#define TYMED_MULTIPAGE_FILE 256
#define TYMED_MULTIPAGE_CALLBACK 512
//
// IImageTransfer Callback Status. Messages must be a single value
//
#define IT_MSG_DATA_HEADER 0x0001
#define IT_MSG_DATA 0x0002
#define IT_MSG_STATUS 0x0003
#define IT_MSG_TERMINATION 0x0004
#define IT_MSG_NEW_PAGE 0x0005
#define IT_MSG_FILE_PREVIEW_DATA 0x0006
#define IT_MSG_FILE_PREVIEW_DATA_HEADER 0x0007
//
// Flags may be bit field combinations
//
#define IT_STATUS_TRANSFER_FROM_DEVICE 0x0001
#define IT_STATUS_PROCESSING_DATA 0x0002
#define IT_STATUS_TRANSFER_TO_CLIENT 0x0004
//
// IWIAEventCallback codes
//
#define WIA_MAJOR_EVENT_DEVICE_CONNECT 0x01
#define WIA_MAJOR_EVENT_DEVICE_DISCONNECT 0x02
#define WIA_MAJOR_EVENT_PICTURE_TAKEN 0x03
#define WIA_MAJOR_EVENT_PICTURE_DELETED 0x04
//
// Device connection status
//
#define WIA_DEVICE_NOT_CONNECTED 0
#define WIA_DEVICE_CONNECTED 1
//**************************************************************************
//
// WIA Enumeration Flags
//
//**************************************************************************
//
// EnumDeviceCapabilities flags
//
#define WIA_DEVICE_COMMANDS 1
#define WIA_DEVICE_EVENTS 2
//
// EnumDeviceInfo Flags
//
#define WIA_DEVINFO_ENUM_LOCAL 0x00000010
//**************************************************************************
//
// WIA Item constants
//
//**************************************************************************
//
// Item Types
//
#define WiaItemTypeFree 0x00000000
#define WiaItemTypeImage 0x00000001
#define WiaItemTypeFile 0x00000002
#define WiaItemTypeFolder 0x00000004
#define WiaItemTypeRoot 0x00000008
#define WiaItemTypeAnalyze 0x00000010
#define WiaItemTypeAudio 0x00000020
#define WiaItemTypeDevice 0x00000040
#define WiaItemTypeDeleted 0x00000080
#define WiaItemTypeDisconnected 0x00000100
#define WiaItemTypeHPanorama 0x00000200
#define WiaItemTypeVPanorama 0x00000400
#define WiaItemTypeBurst 0x00000800
#define WiaItemTypeStorage 0x00001000
#define WiaItemTypeTransfer 0x00002000
#define WiaItemTypeGenerated 0x00004000
#define WiaItemTypeHasAttachments 0x00008000
#define WiaItemTypeVideo 0x00010000
//
// 0x00020000 has been reserved for the TWAIN compatiblity layer
// pass-through feature.
//
#define WiaItemTypeRemoved 0x80000000
#define WiaItemTypeMask 0x8003FFFF
//
// Big max device specific item context
//
#define WIA_MAX_CTX_SIZE 0x01000000
//**************************************************************************
//
// WIA Properties
//
//**************************************************************************
//
// Property access flags
//
#define WIA_PROP_READ 0x01
#define WIA_PROP_WRITE 0x02
#define WIA_PROP_RW (WIA_PROP_READ | WIA_PROP_WRITE)
#define WIA_PROP_SYNC_REQUIRED 0x04
#define WIA_PROP_NONE 0x08
#define WIA_PROP_RANGE 0x10
#define WIA_PROP_LIST 0x20
#define WIA_PROP_FLAG 0x40
#define WIA_PROP_CACHEABLE 0x10000
//
// Item access flags
//
#define WIA_ITEM_CAN_BE_DELETED 0x80
#define WIA_ITEM_READ WIA_PROP_READ
#define WIA_ITEM_WRITE WIA_PROP_WRITE
#define WIA_ITEM_RD (WIA_ITEM_READ | WIA_ITEM_CAN_BE_DELETED)
#define WIA_ITEM_RWD (WIA_ITEM_READ | WIA_ITEM_WRITE | WIA_ITEM_CAN_BE_DELETED)
#ifndef __WIAPROP_H_INCLUDED
#define __WIAPROP_H_INCLUDED
//
// Device information properties
//
#define WIA_RESERVED_FOR_SMALL_NEW_PROPS 256
#define WIA_RESERVED_FOR_NEW_PROPS 1024
#define WIA_RESERVED_FOR_ALL_MS_PROPS (1024*32)
#define WIA_DIP_FIRST 2
#define WIA_DIP_DEV_ID 2
#define WIA_DIP_VEND_DESC 3
#define WIA_DIP_DEV_DESC 4
#define WIA_DIP_DEV_TYPE 5
#define WIA_DIP_PORT_NAME 6
#define WIA_DIP_DEV_NAME 7
#define WIA_DIP_SERVER_NAME 8
#define WIA_DIP_REMOTE_DEV_ID 9
#define WIA_DIP_UI_CLSID 10
#define WIA_DIP_HW_CONFIG 11
#define WIA_DIP_BAUDRATE 12
#define WIA_DIP_STI_GEN_CAPABILITIES 13
#define WIA_DIP_WIA_VERSION 14
#define WIA_DIP_DRIVER_VERSION 15
#define WIA_DIP_LAST 15
#define WIA_NUM_DIP 1 + WIA_DIP_LAST - WIA_DIP_FIRST
#define WIA_DIP_DEV_ID_STR L"Unique Device ID"
#define WIA_DIP_VEND_DESC_STR L"Manufacturer"
#define WIA_DIP_DEV_DESC_STR L"Description"
#define WIA_DIP_DEV_TYPE_STR L"Type"
#define WIA_DIP_PORT_NAME_STR L"Port"
#define WIA_DIP_DEV_NAME_STR L"Name"
#define WIA_DIP_SERVER_NAME_STR L"Server"
#define WIA_DIP_REMOTE_DEV_ID_STR L"Remote Device ID"
#define WIA_DIP_UI_CLSID_STR L"UI Class ID"
#define WIA_DIP_HW_CONFIG_STR L"Hardware Configuration"
#define WIA_DIP_BAUDRATE_STR L"BaudRate"
#define WIA_DIP_STI_GEN_CAPABILITIES_STR L"STI Generic Capabilities"
#define WIA_DIP_WIA_VERSION_STR L"WIA Version"
#define WIA_DIP_DRIVER_VERSION_STR L"Driver Version"
//
// Constant arrays for device information property init
//
#ifdef WIA_DECLARE_DEVINFO_PROP_ARRAY
PROPSPEC g_psDeviceInfo[WIA_NUM_DIP] =
{
{PRSPEC_PROPID, WIA_DIP_DEV_ID},
{PRSPEC_PROPID, WIA_DIP_VEND_DESC},
{PRSPEC_PROPID, WIA_DIP_DEV_DESC},
{PRSPEC_PROPID, WIA_DIP_DEV_TYPE},
{PRSPEC_PROPID, WIA_DIP_PORT_NAME},
{PRSPEC_PROPID, WIA_DIP_DEV_NAME},
{PRSPEC_PROPID, WIA_DIP_SERVER_NAME},
{PRSPEC_PROPID, WIA_DIP_REMOTE_DEV_ID},
{PRSPEC_PROPID, WIA_DIP_UI_CLSID},
{PRSPEC_PROPID, WIA_DIP_HW_CONFIG},
{PRSPEC_PROPID, WIA_DIP_BAUDRATE},
{PRSPEC_PROPID, WIA_DIP_STI_GEN_CAPABILITIES},
{PRSPEC_PROPID, WIA_DIP_WIA_VERSION},
{PRSPEC_PROPID, WIA_DIP_DRIVER_VERSION},
};
PROPID g_piDeviceInfo[WIA_NUM_DIP] =
{
WIA_DIP_DEV_ID,
WIA_DIP_VEND_DESC,
WIA_DIP_DEV_DESC,
WIA_DIP_DEV_TYPE,
WIA_DIP_PORT_NAME,
WIA_DIP_DEV_NAME,
WIA_DIP_SERVER_NAME,
WIA_DIP_REMOTE_DEV_ID,
WIA_DIP_UI_CLSID,
WIA_DIP_HW_CONFIG,
WIA_DIP_BAUDRATE,
WIA_DIP_STI_GEN_CAPABILITIES,
WIA_DIP_WIA_VERSION,
WIA_DIP_DRIVER_VERSION,
};
LPOLESTR g_pszDeviceInfo[WIA_NUM_DIP] =
{
WIA_DIP_DEV_ID_STR,
WIA_DIP_VEND_DESC_STR,
WIA_DIP_DEV_DESC_STR,
WIA_DIP_DEV_TYPE_STR,
WIA_DIP_PORT_NAME_STR,
WIA_DIP_DEV_NAME_STR,
WIA_DIP_SERVER_NAME_STR,
WIA_DIP_REMOTE_DEV_ID_STR,
WIA_DIP_UI_CLSID_STR,
WIA_DIP_HW_CONFIG_STR,
WIA_DIP_BAUDRATE_STR,
WIA_DIP_STI_GEN_CAPABILITIES_STR,
WIA_DIP_WIA_VERSION_STR,
WIA_DIP_DRIVER_VERSION_STR,
};
#else
extern PROPSPEC g_psDeviceInfo[WIA_NUM_DIP];
extern PROPID g_piDeviceInfo[WIA_NUM_DIP];
extern LPOLESTR g_pszDeviceInfo[WIA_NUM_DIP];
#endif
//
// Common device properties
//
#define WIA_DPA_FIRST WIA_DIP_FIRST + WIA_RESERVED_FOR_NEW_PROPS
#define WIA_DPA_FIRMWARE_VERSION WIA_DPA_FIRST + 0
#define WIA_DPA_CONNECT_STATUS WIA_DPA_FIRST + 1
#define WIA_DPA_DEVICE_TIME WIA_DPA_FIRST + 2
#define WIA_DPA_LAST WIA_DPA_FIRST + 3
#define WIA_DPA_FIRMWARE_VERSION_STR L"Firmware Version"
#define WIA_DPA_CONNECT_STATUS_STR L"Connect Status"
#define WIA_DPA_DEVICE_TIME_STR L"Device Time"
#define WIA_NUM_DPA (1 + WIA_DPA_LAST - WIA_DPA_FIRST)
//
// Camera device properties
//
#define WIA_DPC_FIRST WIA_DPA_FIRST + WIA_RESERVED_FOR_NEW_PROPS
#define WIA_DPC_PICTURES_TAKEN WIA_DPC_FIRST + 0
#define WIA_DPC_PICTURES_REMAINING WIA_DPC_FIRST + 1
#define WIA_DPC_EXPOSURE_MODE WIA_DPC_FIRST + 2
#define WIA_DPC_EXPOSURE_COMP WIA_DPC_FIRST + 3
#define WIA_DPC_EXPOSURE_TIME WIA_DPC_FIRST + 4
#define WIA_DPC_FNUMBER WIA_DPC_FIRST + 5
#define WIA_DPC_FLASH_MODE WIA_DPC_FIRST + 6
#define WIA_DPC_FOCUS_MODE WIA_DPC_FIRST + 7
#define WIA_DPC_FOCUS_MANUAL_DIST WIA_DPC_FIRST + 8
#define WIA_DPC_ZOOM_POSITION WIA_DPC_FIRST + 9
#define WIA_DPC_PAN_POSITION WIA_DPC_FIRST + 10
#define WIA_DPC_TILT_POSITION WIA_DPC_FIRST + 11
#define WIA_DPC_TIMER_MODE WIA_DPC_FIRST + 12
#define WIA_DPC_TIMER_VALUE WIA_DPC_FIRST + 13
#define WIA_DPC_POWER_MODE WIA_DPC_FIRST + 14
#define WIA_DPC_BATTERY_STATUS WIA_DPC_FIRST + 15
#define WIA_DPC_THUMB_WIDTH WIA_DPC_FIRST + 16
#define WIA_DPC_THUMB_HEIGHT WIA_DPC_FIRST + 17
#define WIA_DPC_PICT_WIDTH WIA_DPC_FIRST + 18
#define WIA_DPC_PICT_HEIGHT WIA_DPC_FIRST + 19
#define WIA_DPC_DIMENSION WIA_DPC_FIRST + 20
#define WIA_DPC_COMPRESSION_SETTING WIA_DPC_FIRST + 21
#define WIA_DPC_FOCUS_METERING WIA_DPC_FIRST + 22
#define WIA_DPC_TIMELAPSE_INTERVAL WIA_DPC_FIRST + 23
#define WIA_DPC_TIMELAPSE_NUMBER WIA_DPC_FIRST + 24
#define WIA_DPC_BURST_INTERVAL WIA_DPC_FIRST + 25
#define WIA_DPC_BURST_NUMBER WIA_DPC_FIRST + 26
#define WIA_DPC_EFFECT_MODE WIA_DPC_FIRST + 27
#define WIA_DPC_DIGITAL_ZOOM WIA_DPC_FIRST + 28
#define WIA_DPC_SHARPNESS WIA_DPC_FIRST + 29
#define WIA_DPC_CONTRAST WIA_DPC_FIRST + 30
#define WIA_DPC_CAPTURE_MODE WIA_DPC_FIRST + 31
#define WIA_DPC_CAPTURE_DELAY WIA_DPC_FIRST + 32
#define WIA_DPC_EXPOSURE_INDEX WIA_DPC_FIRST + 33
#define WIA_DPC_EXPOSURE_METERING_MODE WIA_DPC_FIRST + 34
#define WIA_DPC_FOCUS_METERING_MODE WIA_DPC_FIRST + 35
#define WIA_DPC_FOCUS_DISTANCE WIA_DPC_FIRST + 36
#define WIA_DPC_FOCAL_LENGTH WIA_DPC_FIRST + 37
#define WIA_DPC_RGB_GAIN WIA_DPC_FIRST + 38
#define WIA_DPC_WHITE_BALANCE WIA_DPC_FIRST + 39
#define WIA_DPC_UPLOAD_URL WIA_DPC_FIRST + 40
#define WIA_DPC_ARTIST WIA_DPC_FIRST + 41
#define WIA_DPC_COPYRIGHT_INFO WIA_DPC_FIRST + 42
#define WIA_DPC_LAST WIA_DPC_FIRST + 42
#define WIA_DPC_PICTURES_TAKEN_STR L"Pictures Taken"
#define WIA_DPC_PICTURES_REMAINING_STR L"Pictures Remaining"
#define WIA_DPC_EXPOSURE_MODE_STR L"Exposure Mode"
#define WIA_DPC_EXPOSURE_COMP_STR L"Exposure Compensation"
#define WIA_DPC_EXPOSURE_TIME_STR L"Exposure Time"
#define WIA_DPC_FNUMBER_STR L"F Number"
#define WIA_DPC_FLASH_MODE_STR L"Flash Mode"
#define WIA_DPC_FOCUS_MODE_STR L"Focus Mode"
#define WIA_DPC_FOCUS_MANUAL_DIST_STR L"Focus Manual Dist"
#define WIA_DPC_ZOOM_POSITION_STR L"Zoom Position"
#define WIA_DPC_PAN_POSITION_STR L"Pan Position"
#define WIA_DPC_TILT_POSITION_STR L"Tilt Position"
#define WIA_DPC_TIMER_MODE_STR L"Timer Mode"
#define WIA_DPC_TIMER_VALUE_STR L"Timer Value"
#define WIA_DPC_POWER_MODE_STR L"Power Mode"
#define WIA_DPC_BATTERY_STATUS_STR L"Battery Status"
#define WIA_DPC_THUMB_WIDTH_STR L"Thumbnail Width"
#define WIA_DPC_THUMB_HEIGHT_STR L"Thumbnail Height"
#define WIA_DPC_PICT_WIDTH_STR L"Picture Width"
#define WIA_DPC_PICT_HEIGHT_STR L"Picture Height"
#define WIA_DPC_DIMENSION_STR L"Dimension"
#define WIA_DPC_COMPRESSION_SETTING_STR L"Compression Setting"
#define WIA_DPC_FOCUS_METERING_MODE_STR L"Focus Metering Mode"
#define WIA_DPC_TIMELAPSE_INTERVAL_STR L"Timelapse Interval"
#define WIA_DPC_TIMELAPSE_NUMBER_STR L"Timelapse Number"
#define WIA_DPC_BURST_INTERVAL_STR L"Burst Interval"
#define WIA_DPC_BURST_NUMBER_STR L"Burst Number"
#define WIA_DPC_EFFECT_MODE_STR L"Effect Mode"
#define WIA_DPC_DIGITAL_ZOOM_STR L"Digital Zoom"
#define WIA_DPC_SHARPNESS_STR L"Sharpness"
#define WIA_DPC_CONTRAST_STR L"Contrast"
#define WIA_DPC_CAPTURE_MODE_STR L"Capture Mode"
#define WIA_DPC_CAPTURE_DELAY_STR L"Capture Delay"
#define WIA_DPC_EXPOSURE_INDEX_STR L"Exposure Index"
#define WIA_DPC_EXPOSURE_METERING_MODE_STR L"Exposure Metering Mode"
#define WIA_DPC_FOCUS_DISTANCE_STR L"Focus Distance"
#define WIA_DPC_FOCAL_LENGTH_STR L"Focus Length"
#define WIA_DPC_RGB_GAIN_STR L"RGB Gain"
#define WIA_DPC_WHITE_BALANCE_STR L"White Balance"
#define WIA_DPC_UPLOAD_URL_STR L"Upload URL"
#define WIA_DPC_ARTIST_STR L"Artist"
#define WIA_DPC_COPYRIGHT_INFO_STR L"Copyright Info"
#define WIA_NUM_DPC (1 + WIA_DPC_LAST - WIA_DPC_FIRST)
//
// Scanner device properties
//
#define WIA_DPS_FIRST WIA_DPC_FIRST + WIA_RESERVED_FOR_NEW_PROPS
#define WIA_DPS_HORIZONTAL_BED_SIZE WIA_DPS_FIRST + 0
#define WIA_DPS_VERTICAL_BED_SIZE WIA_DPS_FIRST + 1
#define WIA_DPS_HORIZONTAL_SHEET_FEED_SIZE WIA_DPS_FIRST + 2
#define WIA_DPS_VERTICAL_SHEET_FEED_SIZE WIA_DPS_FIRST + 3
#define WIA_DPS_SHEET_FEEDER_REGISTRATION WIA_DPS_FIRST + 4
#define WIA_DPS_HORIZONTAL_BED_REGISTRATION WIA_DPS_FIRST + 5
#define WIA_DPS_VERTICAL_BED_REGISTRATION WIA_DPS_FIRST + 6
#define WIA_DPS_PLATEN_COLOR WIA_DPS_FIRST + 7
#define WIA_DPS_PAD_COLOR WIA_DPS_FIRST + 8
#define WIA_DPS_FILTER_SELECT WIA_DPS_FIRST + 9
#define WIA_DPS_DITHER_SELECT WIA_DPS_FIRST + 10
#define WIA_DPS_DITHER_PATTERN_DATA WIA_DPS_FIRST + 11
#define WIA_DPS_DOCUMENT_HANDLING_CAPABILITIES WIA_DPS_FIRST + 12
#define WIA_DPS_DOCUMENT_HANDLING_STATUS WIA_DPS_FIRST + 13
#define WIA_DPS_DOCUMENT_HANDLING_SELECT WIA_DPS_FIRST + 14
#define WIA_DPS_DOCUMENT_HANDLING_CAPACITY WIA_DPS_FIRST + 15
#define WIA_DPS_OPTICAL_XRES WIA_DPS_FIRST + 16
#define WIA_DPS_OPTICAL_YRES WIA_DPS_FIRST + 17
#define WIA_DPS_ENDORSER_CHARACTERS WIA_DPS_FIRST + 18
#define WIA_DPS_ENDORSER_STRING WIA_DPS_FIRST + 19
#define WIA_DPS_SCAN_AHEAD_PAGES WIA_DPS_FIRST + 20
#define WIA_DPS_MAX_SCAN_TIME WIA_DPS_FIRST + 21
#define WIA_DPS_PAGES WIA_DPS_FIRST + 22
#define WIA_DPS_PAGE_SIZE WIA_DPS_FIRST + 23
#define WIA_DPS_PAGE_WIDTH WIA_DPS_FIRST + 24
#define WIA_DPS_PAGE_HEIGHT WIA_DPS_FIRST + 25
#define WIA_DPS_PREVIEW WIA_DPS_FIRST + 26
#define WIA_DPS_TRANSPARENCY WIA_DPS_FIRST + 27
#define WIA_DPS_TRANSPARENCY_SELECT WIA_DPS_FIRST + 28
#define WIA_DPS_SHOW_PREVIEW_CONTROL WIA_DPS_FIRST + 29
#define WIA_DPS_MIN_HORIZONTAL_SHEET_FEED_SIZE WIA_DPS_FIRST + 30
#define WIA_DPS_MIN_VERTICAL_SHEET_FEED_SIZE WIA_DPS_FIRST + 31
#define WIA_DPS_LAST WIA_DPS_FIRST + 31
#define WIA_DPS_HORIZONTAL_BED_SIZE_STR L"Horizontal Bed Size"
#define WIA_DPS_VERTICAL_BED_SIZE_STR L"Vertical Bed Size"
#define WIA_DPS_HORIZONTAL_SHEET_FEED_SIZE_STR L"Horizontal Sheet Feed Size"
#define WIA_DPS_VERTICAL_SHEET_FEED_SIZE_STR L"Vertical Sheet Feed Size"
#define WIA_DPS_SHEET_FEEDER_REGISTRATION_STR L"Sheet Feeder Registration"
#define WIA_DPS_HORIZONTAL_BED_REGISTRATION_STR L"Horizontal Bed Registration"
#define WIA_DPS_VERTICAL_BED_REGISTRATION_STR L"Vertical Bed Registration"
#define WIA_DPS_PLATEN_COLOR_STR L"Platen Color"
#define WIA_DPS_PAD_COLOR_STR L"Pad Color"
#define WIA_DPS_FILTER_SELECT_STR L"Filter Select"
#define WIA_DPS_DITHER_SELECT_STR L"Dither Select"
#define WIA_DPS_DITHER_PATTERN_DATA_STR L"Dither Pattern Data"
#define WIA_DPS_DOCUMENT_HANDLING_CAPABILITIES_STR L"Document Handling Capabilities"
#define WIA_DPS_DOCUMENT_HANDLING_STATUS_STR L"Document Handling Status"
#define WIA_DPS_DOCUMENT_HANDLING_SELECT_STR L"Document Handling Select"
#define WIA_DPS_DOCUMENT_HANDLING_CAPACITY_STR L"Document Handling Capacity"
#define WIA_DPS_OPTICAL_XRES_STR L"Horizontal Optical Resolution"
#define WIA_DPS_OPTICAL_YRES_STR L"Vertical Optical Resolution"
#define WIA_DPS_ENDORSER_CHARACTERS_STR L"Endorser Characters"
#define WIA_DPS_ENDORSER_STRING_STR L"Endorser String"
#define WIA_DPS_SCAN_AHEAD_PAGES_STR L"Scan Ahead Pages"
#define WIA_DPS_MAX_SCAN_TIME_STR L"Max Scan Time"
#define WIA_DPS_PAGES_STR L"Pages"
#define WIA_DPS_PAGE_SIZE_STR L"Page Size"
#define WIA_DPS_PAGE_WIDTH_STR L"Page Width"
#define WIA_DPS_PAGE_HEIGHT_STR L"Page Height"
#define WIA_DPS_PREVIEW_STR L"Preview"
#define WIA_DPS_TRANSPARENCY_STR L"Transparency Adapter"
#define WIA_DPS_TRANSPARENCY_SELECT_STR L"Transparency Adapter Select"
#define WIA_DPS_SHOW_PREVIEW_CONTROL_STR L"Show preview control"
#define WIA_DPS_MIN_HORIZONTAL_SHEET_FEED_SIZE_STR L"Minimum Horizontal Sheet Feed Size"
#define WIA_DPS_MIN_VERTICAL_SHEET_FEED_SIZE_STR L"Minimum Vertical Sheet Feed Size"
#define WIA_NUM_DPS (1 + WIA_DPS_LAST - WIA_DPS_FIRST)
//
// File System Properties
//
#define WIA_DPF_FIRST WIA_DPS_FIRST + WIA_RESERVED_FOR_SMALL_NEW_PROPS
#define WIA_DPF_MOUNT_POINT WIA_DPF_FIRST + 0
#define WIA_DPF_LAST WIA_DPF_FIRST + 0
#define WIA_DPF_MOUNT_POINT_STR L"Directory mount point"
#define WIA_NUM_DPF (1 + WIA_DPF_LAST - WIA_DPF_FIRST)
//
// Video Camera properties.
//
//
#define WIA_DPV_FIRST WIA_DPF_FIRST + WIA_RESERVED_FOR_SMALL_NEW_PROPS
#define WIA_DPV_LAST_PICTURE_TAKEN WIA_DPV_FIRST + 0
#define WIA_DPV_IMAGES_DIRECTORY WIA_DPV_FIRST + 1
#define WIA_DPV_DSHOW_DEVICE_PATH WIA_DPV_FIRST + 2
#define WIA_DPV_LAST WIA_DPV_FIRST + 2
#define WIA_DPV_LAST_PICTURE_TAKEN_STR L"Last Picture Taken"
#define WIA_DPV_IMAGES_DIRECTORY_STR L"Images Directory"
#define WIA_DPV_DSHOW_DEVICE_PATH_STR L"Directshow Device Path"
#define WIA_NUM_DPV (1 + WIA_DPV_LAST - WIA_DPV_FIRST)
//
// Common item properties
//
#define WIA_IPA_FIRST WIA_DPS_FIRST + WIA_RESERVED_FOR_NEW_PROPS
#define WIA_IPA_ITEM_NAME WIA_IPA_FIRST + 0
#define WIA_IPA_FULL_ITEM_NAME WIA_IPA_FIRST + 1
#define WIA_IPA_ITEM_TIME WIA_IPA_FIRST + 2
#define WIA_IPA_ITEM_FLAGS WIA_IPA_FIRST + 3
#define WIA_IPA_ACCESS_RIGHTS WIA_IPA_FIRST + 4
#define WIA_IPA_DATATYPE WIA_IPA_FIRST + 5
#define WIA_IPA_DEPTH WIA_IPA_FIRST + 6
#define WIA_IPA_PREFERRED_FORMAT WIA_IPA_FIRST + 7
#define WIA_IPA_FORMAT WIA_IPA_FIRST + 8
#define WIA_IPA_COMPRESSION WIA_IPA_FIRST + 9
#define WIA_IPA_TYMED WIA_IPA_FIRST + 10
#define WIA_IPA_CHANNELS_PER_PIXEL WIA_IPA_FIRST + 11
#define WIA_IPA_BITS_PER_CHANNEL WIA_IPA_FIRST + 12
#define WIA_IPA_PLANAR WIA_IPA_FIRST + 13
#define WIA_IPA_PIXELS_PER_LINE WIA_IPA_FIRST + 14
#define WIA_IPA_BYTES_PER_LINE WIA_IPA_FIRST + 15
#define WIA_IPA_NUMBER_OF_LINES WIA_IPA_FIRST + 16
#define WIA_IPA_GAMMA_CURVES WIA_IPA_FIRST + 17
#define WIA_IPA_ITEM_SIZE WIA_IPA_FIRST + 18
#define WIA_IPA_COLOR_PROFILE WIA_IPA_FIRST + 19
#define WIA_IPA_MIN_BUFFER_SIZE WIA_IPA_FIRST + 20
// Note: BUFFER_SIZE and MIN_BUFFER_SIZE have the same propids
#define WIA_IPA_BUFFER_SIZE WIA_IPA_FIRST + 20
#define WIA_IPA_REGION_TYPE WIA_IPA_FIRST + 21
#define WIA_IPA_ICM_PROFILE_NAME WIA_IPA_FIRST + 22
#define WIA_IPA_APP_COLOR_MAPPING WIA_IPA_FIRST + 23
#define WIA_IPA_PROP_STREAM_COMPAT_ID WIA_IPA_FIRST + 24
#define WIA_IPA_FILENAME_EXTENSION WIA_IPA_FIRST + 25
#define WIA_IPA_SUPPRESS_PROPERTY_PAGE WIA_IPA_FIRST + 26
#define WIA_IPA_LAST WIA_IPA_FIRST + 26
#define WIA_IPA_ITEM_NAME_STR L"Item Name"
#define WIA_IPA_FULL_ITEM_NAME_STR L"Full Item Name"
#define WIA_IPA_ITEM_TIME_STR L"Item Time Stamp"
#define WIA_IPA_ITEM_FLAGS_STR L"Item Flags"
#define WIA_IPA_ACCESS_RIGHTS_STR L"Access Rights"
#define WIA_IPA_DATATYPE_STR L"Data Type"
#define WIA_IPA_DEPTH_STR L"Bits Per Pixel"
#define WIA_IPA_PREFERRED_FORMAT_STR L"Preferred Format"
#define WIA_IPA_FORMAT_STR L"Format"
#define WIA_IPA_COMPRESSION_STR L"Compression"
#define WIA_IPA_TYMED_STR L"Media Type"
#define WIA_IPA_CHANNELS_PER_PIXEL_STR L"Channels Per Pixel"
#define WIA_IPA_BITS_PER_CHANNEL_STR L"Bits Per Channel"
#define WIA_IPA_PLANAR_STR L"Planar"
#define WIA_IPA_PIXELS_PER_LINE_STR L"Pixels Per Line"
#define WIA_IPA_BYTES_PER_LINE_STR L"Bytes Per Line"
#define WIA_IPA_NUMBER_OF_LINES_STR L"Number of Lines"
#define WIA_IPA_GAMMA_CURVES_STR L"Gamma Curves"
#define WIA_IPA_ITEM_SIZE_STR L"Item Size"
#define WIA_IPA_COLOR_PROFILE_STR L"Color Profiles"
#define WIA_IPA_MIN_BUFFER_SIZE_STR L"Buffer Size"
#define WIA_IPA_REGION_TYPE_STR L"Region Type"
#define WIA_IPA_ICM_PROFILE_NAME_STR L"Color Profile Name"
#define WIA_IPA_APP_COLOR_MAPPING_STR L"Application Applies Color Mapping"
#define WIA_IPA_PROP_STREAM_COMPAT_ID_STR L"Stream Compatibility ID"
#define WIA_IPA_FILENAME_EXTENSION_STR L"Filename extension"
#define WIA_IPA_SUPPRESS_PROPERTY_PAGE_STR L"Suppress a property page"
#define WIA_NUM_IPA (1 + WIA_IPA_LAST - WIA_IPA_FIRST)
//
// Camera item properties
//
#define WIA_IPC_FIRST WIA_IPA_FIRST + WIA_RESERVED_FOR_NEW_PROPS
#define WIA_IPC_THUMBNAIL WIA_IPC_FIRST + 0
#define WIA_IPC_THUMB_WIDTH WIA_IPC_FIRST + 1
#define WIA_IPC_THUMB_HEIGHT WIA_IPC_FIRST + 2
#define WIA_IPC_AUDIO_AVAILABLE WIA_IPC_FIRST + 3
#define WIA_IPC_AUDIO_DATA_FORMAT WIA_IPC_FIRST + 4
#define WIA_IPC_AUDIO_DATA WIA_IPC_FIRST + 5
#define WIA_IPC_NUM_PICT_PER_ROW WIA_IPC_FIRST + 6
#define WIA_IPC_SEQUENCE WIA_IPC_FIRST + 7
#define WIA_IPC_TIMEDELAY WIA_IPC_FIRST + 8
#define WIA_IPC_LAST WIA_IPC_FIRST + 8
#define WIA_IPC_THUMBNAIL_STR L"Thumbnail Data"
#define WIA_IPC_THUMB_WIDTH_STR L"Thumbnail Width"
#define WIA_IPC_THUMB_HEIGHT_STR L"Thumbnail Height"
#define WIA_IPC_AUDIO_AVAILABLE_STR L"Audio Available"
#define WIA_IPC_AUDIO_DATA_FORMAT_STR L"Audio Format"
#define WIA_IPC_AUDIO_DATA_STR L"Audio Data"
#define WIA_IPC_NUM_PICT_PER_ROW_STR L"Pictures per Row"
#define WIA_IPC_SEQUENCE_STR L"Sequence Number"
#define WIA_IPC_TIMEDELAY_STR L"Time Delay"
#define WIA_NUM_IPC (1 + WIA_IPC_LAST - WIA_IPC_FIRST)
//
// Scanner item properties
//
#define WIA_IPS_FIRST WIA_IPC_FIRST + WIA_RESERVED_FOR_NEW_PROPS
#define WIA_IPS_CUR_INTENT WIA_IPS_FIRST + 0
#define WIA_IPS_XRES WIA_IPS_FIRST + 1
#define WIA_IPS_YRES WIA_IPS_FIRST + 2
#define WIA_IPS_XPOS WIA_IPS_FIRST + 3
#define WIA_IPS_YPOS WIA_IPS_FIRST + 4
#define WIA_IPS_XEXTENT WIA_IPS_FIRST + 5
#define WIA_IPS_YEXTENT WIA_IPS_FIRST + 6
#define WIA_IPS_PHOTOMETRIC_INTERP WIA_IPS_FIRST + 7
#define WIA_IPS_BRIGHTNESS WIA_IPS_FIRST + 8
#define WIA_IPS_CONTRAST WIA_IPS_FIRST + 9
#define WIA_IPS_ORIENTATION WIA_IPS_FIRST + 10
#define WIA_IPS_ROTATION WIA_IPS_FIRST + 11
#define WIA_IPS_MIRROR WIA_IPS_FIRST + 12
#define WIA_IPS_THRESHOLD WIA_IPS_FIRST + 13
#define WIA_IPS_INVERT WIA_IPS_FIRST + 14
#define WIA_IPS_WARM_UP_TIME WIA_IPS_FIRST + 15
#define WIA_IPS_LAST WIA_IPS_FIRST + 15
#define WIA_IPS_CUR_INTENT_STR L"Current Intent"
#define WIA_IPS_XRES_STR L"Horizontal Resolution"
#define WIA_IPS_YRES_STR L"Vertical Resolution"
#define WIA_IPS_XPOS_STR L"Horizontal Start Position"
#define WIA_IPS_YPOS_STR L"Vertical Start Position"
#define WIA_IPS_XEXTENT_STR L"Horizontal Extent"
#define WIA_IPS_YEXTENT_STR L"Vertical Extent"
#define WIA_IPS_PHOTOMETRIC_INTERP_STR L"Photometric Interpretation"
#define WIA_IPS_BRIGHTNESS_STR L"Brightness"
#define WIA_IPS_CONTRAST_STR L"Contrast"
#define WIA_IPS_ORIENTATION_STR L"Orientation"
#define WIA_IPS_ROTATION_STR L"Rotation"
#define WIA_IPS_MIRROR_STR L"Mirror"
#define WIA_IPS_THRESHOLD_STR L"Threshold"
#define WIA_IPS_INVERT_STR L"Invert"
#define WIA_IPS_WARM_UP_TIME_STR L"Lamp Warm up Time"
#define WIA_NUM_IPS (1 + WIA_IPS_LAST - WIA_IPS_FIRST)
//**************************************************************************
//
// Vendor defined property area
//
//**************************************************************************
#define WIA_PRIVATE_DEVPROP (WIA_IPS_FIRST + WIA_RESERVED_FOR_ALL_MS_PROPS)
#define WIA_PRIVATE_ITEMPROP (WIA_PRIVATE_DEVPROP + WIA_RESERVED_FOR_ALL_MS_PROPS)
//**************************************************************************
//
// WIA Property Constants
//
//**************************************************************************
//
// WIA_DPC_WHITE_BALANCE constants
//
#define WHITEBALANCE_MANUAL 1
#define WHITEBALANCE_AUTO 2
#define WHITEBALANCE_ONEPUSH_AUTO 3
#define WHITEBALANCE_DAYLIGHT 4
#define WHITEBALANCE_FLORESCENT 5
#define WHITEBALANCE_TUNGSTEN 6
#define WHITEBALANCE_FLASH 7
//
// WIA_DPC_FOCUS_MODE constants
//
#define FOCUSMODE_MANUAL 1
#define FOCUSMODE_AUTO 2
#define FOCUSMODE_MACROAUTO 3
//
// WIA_DPC_EXPOSURE_METERING_MODE constants
//
#define EXPOSUREMETERING_AVERAGE 1
#define EXPOSUREMETERING_CENTERWEIGHT 2
#define EXPOSUREMETERING_MULTISPOT 3
#define EXPOSUREMETERING_CENTERSPOT 4
//
// WIA_DPC_FLASH_MODE constants
//
#define FLASHMODE_AUTO 1
#define FLASHMODE_OFF 2
#define FLASHMODE_FILL 3
#define FLASHMODE_REDEYE_AUTO 4
#define FLASHMODE_REDEYE_FILL 5
#define FLASHMODE_EXTERNALSYNC 6
//
// WIA_DPC_EXPOSURE_MODE constants
//
#define EXPOSUREMODE_MANUAL 1
#define EXPOSUREMODE_AUTO 2
#define EXPOSUREMODE_APERTURE_PRIORITY 3
#define EXPOSUREMODE_SHUTTER_PRIORITY 4
#define EXPOSUREMODE_PROGRAM_CREATIVE 5
#define EXPOSUREMODE_PROGRAM_ACTION 6
#define EXPOSUREMODE_PORTRAIT 7
//
// WIA_DPC_CAPTURE_MODE constants
//
#define CAPTUREMODE_NORMAL 1
#define CAPTUREMODE_BURST 2
#define CAPTUREMODE_TIMELAPSE 3
//
// WIA_DPC_EFFECT_MODE constants
//
#define EFFECTMODE_STANDARD 1
#define EFFECTMODE_BW 2
#define EFFECTMODE_SEPIA 3
//
// WIA_DPC_FOCUS_METERING_MODE constants
//
#define FOCUSMETERING_CENTERSPOT 1
#define FOCUSMETERING_MULTISPOT 2
//
// WIA_DPC_POWER_MODE constants
//
#define POWERMODE_LINE 1
#define POWERMODE_BATTERY 2
//
// WIA_DPS_SHEET_FEEDER_REGISTRATION and
// WIA_DPS_HORIZONTAL_BED_REGISTRATION constants
//
#define LEFT_JUSTIFIED 0
#define CENTERED 1
#define RIGHT_JUSTIFIED 2
//
// WIA_DPS_VERTICAL_BED_REGISTRATION constants
//
#define TOP_JUSTIFIED 0
#define CENTERED 1
#define BOTTOM_JUSTIFIED 2
//
// WIA_DPS_ORIENTATION and WIA_DPS_ROTATION constants
//
#define PORTRAIT 0
#define LANSCAPE 1
#define ROT180 2
#define ROT270 3
//
// WIA_DPS_MIRROR flags
//
#define MIRRORED 0x01
//
// WIA_DPS_DOCUMENT_HANDLING_CAPABILITIES flags
//
#define FEED 0x01
#define FLAT 0x02
#define DUP 0x04
#define DETECT_FLAT 0x08
#define DETECT_SCAN 0x10
#define DETECT_FEED 0x20
#define DETECT_DUP 0x40
#define DETECT_FEED_AVAIL 0x80
#define DETECT_DUP_AVAIL 0x100
//
// WIA_DPS_DOCUMENT_HANDLING_STATUS flags
//
#define FEED_READY 0x01
#define FLAT_READY 0x02
#define DUP_READY 0x04
#define FLAT_COVER_UP 0x08
#define PATH_COVER_UP 0x10
#define PAPER_JAM 0x20
//
// WIA_DPS_DOCUMENT_HANDLING_SELECT flags
//
#define FEEDER 0x001
#define FLATBED 0x002
#define DUPLEX 0x004
#define FRONT_FIRST 0x008
#define BACK_FIRST 0x010
#define FRONT_ONLY 0x020
#define BACK_ONLY 0x040
#define NEXT_PAGE 0x080
#define PREFEED 0x100
#define AUTO_ADVANCE 0x200
//
// WIA_DPS_TRANSPARENCY flags
//
#define LIGHT_SOURCE_PRESENT_DETECT 0x01
#define LIGHT_SOURCE_PRESENT 0x02
#define LIGHT_SOURCE_DETECT_READY 0x04
#define LIGHT_SOURCE_READY 0x08
//
// WIA_DPS_TRANSPARENCY_SELECT flags
//
#define LIGHT_SOURCE_SELECT 0x001
//
// WIA_DPS_SCAN_AHEAD_PAGES constants
//
#define WIA_SCAN_AHEAD_ALL 0
//
// WIA_DPS_PAGES constants
//
#define ALL_PAGES 0
//
// WIA_DPS_PREVIEW constants
//
#define WIA_FINAL_SCAN 0
#define WIA_PREVIEW_SCAN 1
//
// WIA_DPS_SHOW_PREVIEW_CONTROL constants
//
#define WIA_SHOW_PREVIEW_CONTROL 0
#define WIA_DONT_SHOW_PREVIEW_CONTROL 1
//
// Predefined strings for WIA_DPS_ENDORSER_STRING
//
#define WIA_ENDORSER_TOK_DATE L"$DATE$"
#define WIA_ENDORSER_TOK_TIME L"$TIME$"
#define WIA_ENDORSER_TOK_PAGE_COUNT L"$PAGE_COUNT$"
#define WIA_ENDORSER_TOK_DAY L"$DAY$"
#define WIA_ENDORSER_TOK_MONTH L"$MONTH$"
#define WIA_ENDORSER_TOK_YEAR L"$YEAR$"
//
// WIA_DPS_PAGE_SIZE constants
//
#define WIA_PAGE_A4 0
#define WIA_PAGE_LETTER 1
#define WIA_PAGE_CUSTOM 2
//
// WIA_IPA_COMPRESSION constants
//
#define WIA_COMPRESSION_NONE 0
#define WIA_COMPRESSION_BI_RLE4 1
#define WIA_COMPRESSION_BI_RLE8 2
#define WIA_COMPRESSION_G3 3
#define WIA_COMPRESSION_G4 4
#define WIA_COMPRESSION_JPEG 5
//
// WIA_IPA_PLANAR constants
//
#define WIA_PACKED_PIXEL 0
#define WIA_PLANAR 1
//
// WIA_IPA_DATATYPE constants
//
#define WIA_DATA_THRESHOLD 0
#define WIA_DATA_DITHER 1
#define WIA_DATA_GRAYSCALE 2
#define WIA_DATA_COLOR 3
#define WIA_DATA_COLOR_THRESHOLD 4
#define WIA_DATA_COLOR_DITHER 5
//
// WIA_IPA_SUPPRESS_PROPERTY_PAGE flags
//
#define WIA_PROPPAGE_SCANNER_ITEM_GENERAL 0x00000001
#define WIA_PROPPAGE_CAMERA_ITEM_GENERAL 0x00000002
//
// WIA_IPS_CUR_INTENT flags
//
#define WIA_INTENT_NONE 0x00000000
#define WIA_INTENT_IMAGE_TYPE_COLOR 0x00000001
#define WIA_INTENT_IMAGE_TYPE_GRAYSCALE 0x00000002
#define WIA_INTENT_IMAGE_TYPE_TEXT 0x00000004
#define WIA_INTENT_IMAGE_TYPE_MASK 0x0000000F
#define WIA_INTENT_MINIMIZE_SIZE 0x00010000
#define WIA_INTENT_MAXIMIZE_QUALITY 0x00020000
#define WIA_INTENT_BEST_PREVIEW 0x00040000
#define WIA_INTENT_SIZE_MASK 0x000F0000
//
// WIA_IPS_PHOTOMETRIC_INTERP constants
//
#define WIA_PHOTO_WHITE_1 0 // default, white is 1, black is 0
#define WIA_PHOTO_WHITE_0 1 // default, white is 0, black is 1
//**************************************************************************
//
// WIA Extended Property Identifiers
//
//**************************************************************************
#define WIA_RANGE_MIN 0
#define WIA_RANGE_NOM 1
#define WIA_RANGE_MAX 2
#define WIA_RANGE_STEP 3
#define WIA_RANGE_NUM_ELEMS 4
#define WIA_LIST_COUNT 0
#define WIA_LIST_NOM 1
#define WIA_LIST_VALUES 2
#define WIA_LIST_NUM_ELEMS 2
#define WIA_FLAG_NOM 0
#define WIA_FLAG_VALUES 1
#define WIA_FLAG_NUM_ELEMS 2
//**************************************************************************
//
// Property id to string mapping
//
//**************************************************************************
#ifdef DEFINE_WIA_PROPID_TO_NAME
WIA_PROPID_TO_NAME g_wiaPropIdToName[] =
{
{WIA_DIP_DEV_ID, WIA_DIP_DEV_ID_STR},
{WIA_DIP_VEND_DESC, WIA_DIP_VEND_DESC_STR},
{WIA_DIP_DEV_DESC, WIA_DIP_DEV_DESC_STR},
{WIA_DIP_DEV_TYPE, WIA_DIP_DEV_TYPE_STR},
{WIA_DIP_PORT_NAME, WIA_DIP_PORT_NAME_STR},
{WIA_DIP_DEV_NAME, WIA_DIP_DEV_NAME_STR},
{WIA_DIP_SERVER_NAME, WIA_DIP_SERVER_NAME_STR},
{WIA_DIP_REMOTE_DEV_ID, WIA_DIP_REMOTE_DEV_ID_STR},
{WIA_DIP_UI_CLSID, WIA_DIP_UI_CLSID_STR},
{WIA_DIP_HW_CONFIG, WIA_DIP_HW_CONFIG_STR},
{WIA_DIP_BAUDRATE, WIA_DIP_BAUDRATE_STR},
{WIA_DIP_STI_GEN_CAPABILITIES, WIA_DIP_STI_GEN_CAPABILITIES_STR},
{WIA_DIP_WIA_VERSION, WIA_DIP_WIA_VERSION_STR},
{WIA_DIP_DRIVER_VERSION, WIA_DIP_DRIVER_VERSION_STR},
{WIA_DPA_FIRMWARE_VERSION, WIA_DPA_FIRMWARE_VERSION_STR},
{WIA_DPA_CONNECT_STATUS, WIA_DPA_CONNECT_STATUS_STR},
{WIA_DPA_DEVICE_TIME, WIA_DPA_DEVICE_TIME_STR},
{WIA_DPC_PICTURES_TAKEN, WIA_DPC_PICTURES_TAKEN_STR},
{WIA_DPC_PICTURES_REMAINING, WIA_DPC_PICTURES_REMAINING_STR},
{WIA_DPC_EXPOSURE_MODE, WIA_DPC_EXPOSURE_MODE_STR},
{WIA_DPC_EXPOSURE_COMP, WIA_DPC_EXPOSURE_COMP_STR},
{WIA_DPC_EXPOSURE_TIME, WIA_DPC_EXPOSURE_TIME_STR},
{WIA_DPC_FNUMBER, WIA_DPC_FNUMBER_STR},
{WIA_DPC_FLASH_MODE, WIA_DPC_FLASH_MODE_STR},
{WIA_DPC_FOCUS_MODE, WIA_DPC_FOCUS_MODE_STR},
{WIA_DPC_FOCUS_MANUAL_DIST, WIA_DPC_FOCUS_MANUAL_DIST_STR},
{WIA_DPC_ZOOM_POSITION, WIA_DPC_ZOOM_POSITION_STR},
{WIA_DPC_PAN_POSITION, WIA_DPC_PAN_POSITION_STR},
{WIA_DPC_TILT_POSITION, WIA_DPC_TILT_POSITION_STR},
{WIA_DPC_TIMER_MODE, WIA_DPC_TIMER_MODE_STR},
{WIA_DPC_TIMER_VALUE, WIA_DPC_TIMER_VALUE_STR},
{WIA_DPC_POWER_MODE, WIA_DPC_POWER_MODE_STR},
{WIA_DPC_BATTERY_STATUS, WIA_DPC_BATTERY_STATUS_STR},
{WIA_DPC_DIMENSION, WIA_DPC_DIMENSION_STR},
{WIA_DPS_HORIZONTAL_BED_SIZE, WIA_DPS_HORIZONTAL_BED_SIZE_STR},
{WIA_DPS_VERTICAL_BED_SIZE, WIA_DPS_VERTICAL_BED_SIZE_STR},
{WIA_DPS_HORIZONTAL_SHEET_FEED_SIZE, WIA_DPS_HORIZONTAL_SHEET_FEED_SIZE_STR},
{WIA_DPS_VERTICAL_SHEET_FEED_SIZE, WIA_DPS_VERTICAL_SHEET_FEED_SIZE_STR},
{WIA_DPS_SHEET_FEEDER_REGISTRATION, WIA_DPS_SHEET_FEEDER_REGISTRATION_STR},
{WIA_DPS_HORIZONTAL_BED_REGISTRATION, WIA_DPS_HORIZONTAL_BED_REGISTRATION_STR},
{WIA_DPS_VERTICAL_BED_REGISTRATION, WIA_DPS_VERTICAL_BED_REGISTRATION_STR},
{WIA_DPS_PLATEN_COLOR, WIA_DPS_PLATEN_COLOR_STR},
{WIA_DPS_PAD_COLOR, WIA_DPS_PAD_COLOR_STR},
{WIA_DPS_FILTER_SELECT, WIA_DPS_FILTER_SELECT_STR},
{WIA_DPS_DITHER_SELECT, WIA_DPS_DITHER_SELECT_STR},
{WIA_DPS_DITHER_PATTERN_DATA, WIA_DPS_DITHER_PATTERN_DATA_STR},
{WIA_DPS_DOCUMENT_HANDLING_CAPABILITIES, WIA_DPS_DOCUMENT_HANDLING_CAPABILITIES_STR},
{WIA_DPS_DOCUMENT_HANDLING_STATUS, WIA_DPS_DOCUMENT_HANDLING_STATUS_STR},
{WIA_DPS_DOCUMENT_HANDLING_SELECT, WIA_DPS_DOCUMENT_HANDLING_SELECT_STR},
{WIA_DPS_DOCUMENT_HANDLING_CAPACITY, WIA_DPS_DOCUMENT_HANDLING_CAPACITY_STR},
{WIA_DPS_OPTICAL_XRES, WIA_DPS_OPTICAL_XRES_STR},
{WIA_DPS_OPTICAL_YRES, WIA_DPS_OPTICAL_YRES_STR},
{WIA_DPS_ENDORSER_CHARACTERS, WIA_DPS_ENDORSER_CHARACTERS_STR},
{WIA_DPS_ENDORSER_STRING, WIA_DPS_ENDORSER_STRING_STR},
{WIA_DPS_SCAN_AHEAD_PAGES, WIA_DPS_SCAN_AHEAD_PAGES_STR},
{WIA_DPS_MAX_SCAN_TIME, WIA_DPS_MAX_SCAN_TIME_STR},
{WIA_DPS_PAGES, WIA_DPS_PAGES_STR},
{WIA_DPS_PAGE_SIZE, WIA_DPS_PAGE_SIZE_STR},
{WIA_DPS_PAGE_WIDTH, WIA_DPS_PAGE_WIDTH_STR},
{WIA_DPS_PAGE_HEIGHT, WIA_DPS_PAGE_HEIGHT_STR},
{WIA_DPS_PREVIEW, WIA_DPS_PREVIEW_STR},
{WIA_DPS_TRANSPARENCY, WIA_DPS_TRANSPARENCY_STR},
{WIA_DPS_TRANSPARENCY_SELECT, WIA_DPS_TRANSPARENCY_SELECT_STR},
{WIA_DPS_SHOW_PREVIEW_CONTROL, WIA_DPS_SHOW_PREVIEW_CONTROL_STR},
{WIA_DPS_MIN_HORIZONTAL_SHEET_FEED_SIZE, WIA_DPS_MIN_HORIZONTAL_SHEET_FEED_SIZE_STR},
{WIA_DPS_MIN_VERTICAL_SHEET_FEED_SIZE, WIA_DPS_MIN_VERTICAL_SHEET_FEED_SIZE_STR},
{WIA_DPV_LAST_PICTURE_TAKEN, WIA_DPV_LAST_PICTURE_TAKEN_STR},
{WIA_DPV_IMAGES_DIRECTORY, WIA_DPV_IMAGES_DIRECTORY_STR},
{WIA_DPV_DSHOW_DEVICE_PATH, WIA_DPV_DSHOW_DEVICE_PATH_STR},
{WIA_DPF_MOUNT_POINT, WIA_DPF_MOUNT_POINT_STR},
{WIA_IPA_ITEM_NAME, WIA_IPA_ITEM_NAME_STR},
{WIA_IPA_FULL_ITEM_NAME, WIA_IPA_FULL_ITEM_NAME_STR},
{WIA_IPA_ITEM_TIME, WIA_IPA_ITEM_TIME_STR},
{WIA_IPA_ITEM_FLAGS, WIA_IPA_ITEM_FLAGS_STR},
{WIA_IPA_ACCESS_RIGHTS, WIA_IPA_ACCESS_RIGHTS_STR},
{WIA_IPA_DATATYPE, WIA_IPA_DATATYPE_STR},
{WIA_IPA_DEPTH, WIA_IPA_DEPTH_STR},
{WIA_IPA_PREFERRED_FORMAT, WIA_IPA_PREFERRED_FORMAT_STR},
{WIA_IPA_FORMAT, WIA_IPA_FORMAT_STR},
{WIA_IPA_COMPRESSION, WIA_IPA_COMPRESSION_STR},
{WIA_IPA_TYMED, WIA_IPA_TYMED_STR},
{WIA_IPA_CHANNELS_PER_PIXEL, WIA_IPA_CHANNELS_PER_PIXEL_STR},
{WIA_IPA_BITS_PER_CHANNEL, WIA_IPA_BITS_PER_CHANNEL_STR},
{WIA_IPA_PLANAR, WIA_IPA_PLANAR_STR},
{WIA_IPA_PIXELS_PER_LINE, WIA_IPA_PIXELS_PER_LINE_STR},
{WIA_IPA_BYTES_PER_LINE, WIA_IPA_BYTES_PER_LINE_STR},
{WIA_IPA_NUMBER_OF_LINES, WIA_IPA_NUMBER_OF_LINES_STR},
{WIA_IPA_GAMMA_CURVES, WIA_IPA_GAMMA_CURVES_STR},
{WIA_IPA_ITEM_SIZE, WIA_IPA_ITEM_SIZE_STR},
{WIA_IPA_COLOR_PROFILE, WIA_IPA_COLOR_PROFILE_STR},
{WIA_IPA_MIN_BUFFER_SIZE, WIA_IPA_MIN_BUFFER_SIZE_STR},
{WIA_IPA_REGION_TYPE, WIA_IPA_REGION_TYPE_STR},
{WIA_IPA_ICM_PROFILE_NAME, WIA_IPA_ICM_PROFILE_NAME_STR},
{WIA_IPA_APP_COLOR_MAPPING, WIA_IPA_APP_COLOR_MAPPING_STR},
{WIA_IPA_PROP_STREAM_COMPAT_ID, WIA_IPA_PROP_STREAM_COMPAT_ID_STR},
{WIA_IPA_FILENAME_EXTENSION, WIA_IPA_FILENAME_EXTENSION_STR},
{WIA_IPA_SUPPRESS_PROPERTY_PAGE, WIA_IPA_SUPPRESS_PROPERTY_PAGE_STR},
{WIA_IPC_THUMBNAIL, WIA_IPC_THUMBNAIL_STR},
{WIA_IPC_THUMB_WIDTH, WIA_IPC_THUMB_WIDTH_STR},
{WIA_IPC_THUMB_HEIGHT, WIA_IPC_THUMB_HEIGHT_STR},
{WIA_IPC_AUDIO_AVAILABLE, WIA_IPC_AUDIO_AVAILABLE_STR},
{WIA_IPC_AUDIO_DATA_FORMAT, WIA_IPC_AUDIO_DATA_FORMAT_STR},
{WIA_IPC_AUDIO_DATA, WIA_IPC_AUDIO_DATA_STR},
{WIA_IPC_NUM_PICT_PER_ROW, WIA_IPC_NUM_PICT_PER_ROW_STR},
{WIA_IPC_SEQUENCE, WIA_IPC_SEQUENCE_STR},
{WIA_IPC_TIMEDELAY, WIA_IPC_TIMEDELAY_STR},
{WIA_IPS_CUR_INTENT, WIA_IPS_CUR_INTENT_STR},
{WIA_IPS_XRES, WIA_IPS_XRES_STR},
{WIA_IPS_YRES, WIA_IPS_YRES_STR},
{WIA_IPS_XPOS, WIA_IPS_XPOS_STR},
{WIA_IPS_YPOS, WIA_IPS_YPOS_STR},
{WIA_IPS_XEXTENT, WIA_IPS_XEXTENT_STR},
{WIA_IPS_YEXTENT, WIA_IPS_YEXTENT_STR},
{WIA_IPS_PHOTOMETRIC_INTERP, WIA_IPS_PHOTOMETRIC_INTERP_STR},
{WIA_IPS_BRIGHTNESS, WIA_IPS_BRIGHTNESS_STR},
{WIA_IPS_CONTRAST, WIA_IPS_CONTRAST_STR},
{WIA_IPS_ORIENTATION, WIA_IPS_ORIENTATION_STR},
{WIA_IPS_ROTATION, WIA_IPS_ROTATION_STR},
{WIA_IPS_MIRROR, WIA_IPS_MIRROR_STR},
{WIA_IPS_THRESHOLD, WIA_IPS_THRESHOLD_STR},
{WIA_IPS_INVERT, WIA_IPS_INVERT_STR},
{WIA_IPS_WARM_UP_TIME, WIA_IPS_WARM_UP_TIME_STR},
{0, L"Not a WIA property"}
};
#else
extern WIA_PROPID_TO_NAME g_wiaPropIdToName[];
#endif
#endif //WIAPROP_H_INCLUDED
//
// Macro Helpers
//
#define WIA_PROP_LIST_COUNT(ppv) (((PROPVARIANT*)ppv)->cal.cElems - WIA_LIST_VALUES)
#define WIA_PROP_LIST_VALUE(ppv, index) \\
((index > ((PROPVARIANT*) ppv)->cal.cElems - WIA_LIST_VALUES) || (index < -WIA_LIST_NOM)) ?\\
NULL : \\
(((PROPVARIANT*) ppv)->vt == VT_UI1) ? \\
((PROPVARIANT*) ppv)->caub.pElems[WIA_LIST_VALUES + index] : \\
(((PROPVARIANT*) ppv)->vt == VT_UI2) ? \\
((PROPVARIANT*) ppv)->caui.pElems[WIA_LIST_VALUES + index] : \\
(((PROPVARIANT*) ppv)->vt == VT_UI4) ? \\
((PROPVARIANT*) ppv)->caul.pElems[WIA_LIST_VALUES + index] : \\
(((PROPVARIANT*) ppv)->vt == VT_I2) ? \\
((PROPVARIANT*) ppv)->cai.pElems[WIA_LIST_VALUES + index] : \\
(((PROPVARIANT*) ppv)->vt == VT_I4) ? \\
((PROPVARIANT*) ppv)->cal.pElems[WIA_LIST_VALUES + index] : \\
(((PROPVARIANT*) ppv)->vt == VT_R4) ? \\
((PROPVARIANT*) ppv)->caflt.pElems[WIA_LIST_VALUES + index] : \\
(((PROPVARIANT*) ppv)->vt == VT_R8) ? \\
((PROPVARIANT*) ppv)->cadbl.pElems[WIA_LIST_VALUES + index] : \\
(((PROPVARIANT*) ppv)->vt == VT_BSTR) ? \\
(LONG)(((PROPVARIANT*) ppv)->cabstr.pElems[WIA_LIST_VALUES + index]) : \\
NULL
//
// End of Macro Helpers
//
#ifdef __cplusplus
};
#endif
//
// Reset packing
//
#include <poppack.h>
#endif // _WIADEF_H_
| 44.852092 | 121 | 0.618403 |
96959cf34f0b57793668b75b433dd146c7ad2512 | 914 | c | C | C/code case/code case 198.c | amazing-2020/pdf | 8cd3f5f510a1c1ed89b51b1354f4f8c000c5b24d | [
"Apache-2.0"
] | 3 | 2021-01-01T13:08:24.000Z | 2021-02-03T09:27:56.000Z | C/code case/code case 198.c | amazing-2020/pdf | 8cd3f5f510a1c1ed89b51b1354f4f8c000c5b24d | [
"Apache-2.0"
] | null | null | null | C/code case/code case 198.c | amazing-2020/pdf | 8cd3f5f510a1c1ed89b51b1354f4f8c000c5b24d | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
int main(void) {
int blank, number, column, n;
printf("Please enter the number of digital pyramid levels(less than 50): ");
scanf("%d", &n);
int count=0;
int x=0;
x = 2*n-1;
while (x != 0) {
x /= 10;
++count;
}
for (column=1; column<=n; column++) {
for (blank=1; blank<(n-column)*(column+1)+count; blank++) {
printf(" ");
}
for (number=column; number<(2*column); number++) {
if (number< 10&&count != 1) {
printf(" %d", number);
} else {
printf(" %d", number);
}
}
for (number-=2; number>=column; number--) {
if (number < 10&&count!=1) {
printf(" %d", number);
} else {
printf(" %d", number);
}
}
printf("\n");
}
return 0;
} | 24.052632 | 80 | 0.413567 |
1b0a4ce5ab3a439bbeb4a067c6d614678aa2fd0f | 8,868 | h | C | include/elsNoise.h | ethereal-sheep/elsMath | 6faf4b4b49e5617556625479d3489acf1a82bfc0 | [
"MIT"
] | null | null | null | include/elsNoise.h | ethereal-sheep/elsMath | 6faf4b4b49e5617556625479d3489acf1a82bfc0 | [
"MIT"
] | null | null | null | include/elsNoise.h | ethereal-sheep/elsMath | 6faf4b4b49e5617556625479d3489acf1a82bfc0 | [
"MIT"
] | null | null | null |
#ifndef ELS_NOISE
#define ELS_NOISE
#include "elsHeader.h"
#include "elsMath.h"
#include "elsRandom.h"
namespace els
{
// noise using perlin noise
// note*: change to simplex
template <typename T>
class PerlinNoise
{
public:
using Scalar = T;
private:
// using original 1983 permutation as default
inline static uint8_t p[] = { 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,
103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,
26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,
87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,
46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,
187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,
198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,
255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,
170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,
172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,
104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,
241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,
157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,
93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180,
151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,
103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,
26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,
87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,
46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,
187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,
198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,
255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,
170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,
172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,
104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,
241, 81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,
157,184, 84,204,176,115,121,50,45,127,4,150,254,138,236,205,
93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 };
static constexpr Scalar fade(Scalar t)
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
static constexpr Scalar grad(uint8_t hash, Scalar x, Scalar y, Scalar z)
{
const uint8_t h = hash & 0b1111U;
const Scalar u = h < 0b1000U ? x : y;
const Scalar v = h < 0b0100U ? y : h == 0b1100U || h == 0b1110U ? x : z;
return ((h & 0b0001U) == 0 ? u : -u) + ((h & 0b0010U) == 0 ? v : -v);
}
static constexpr Scalar weight(uint32_t octaves)
{
Scalar amp = 1;
Scalar value = 0;
for (size_t i = 0; i < octaves; ++i)
{
value += amp;
amp /= 2;
}
return value;
}
static constexpr Scalar noise(Scalar x, Scalar y, Scalar z)
{
const int32_t X = static_cast<int32_t>(els::floor(x)) & 255;
const int32_t Y = static_cast<int32_t>(els::floor(y)) & 255;
const int32_t Z = static_cast<int32_t>(els::floor(z)) & 255;
x -= els::floor(x);
y -= els::floor(y);
z -= els::floor(z);
const Scalar u = fade(x);
const Scalar v = fade(y);
const Scalar w = fade(z);
const std::int32_t A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z;
const std::int32_t B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z;
return
lerp(
lerp(
lerp(
grad(p[AA], x, y, z),
grad(p[BA], x - 1, y, z),
u
),
lerp(
grad(p[AB], x, y - 1, z),
grad(p[BB], x - 1, y - 1, z),
u
),
v
),
lerp(
lerp(
grad(p[AA + 1], x, y, z - 1),
grad(p[BA + 1], x - 1, y, z - 1),
u
),
lerp(
grad(p[AB + 1], x, y - 1, z - 1),
grad(p[BB + 1], x - 1, y - 1, z - 1),
u
),
v
),
w
);
}
static constexpr Scalar octave_noise(Scalar x, Scalar y, Scalar z, uint32_t octaves)
{
Scalar result = 0;
Scalar amp = 1;
for (uint32_t i = 0; i < octaves; ++i)
{
result += noise(x, y, z) * amp;
x *= 2;
amp /= 2;
}
return result; // unnormalized
}
static constexpr Scalar normalised_octave_noise(Scalar x, Scalar y, Scalar z, uint32_t octaves)
{
return octave_noise(x, y, z, octaves) / weight(octaves);
}
public:
static uint32_t reseed(uint32_t seed = random::device())
{
for (size_t i = 0; i < 256; ++i) p[i] = static_cast<std::uint8_t>(i);
std::shuffle(std::begin(p), std::begin(p) + 256, random::defaultPRNG(seed));
for (size_t i = 0; i < 256; ++i) p[256 + i] = p[i];
return seed;
}
template <typename Vec2>
static constexpr Scalar noise2D(const Vec2& v) { return noise(static_cast<Scalar>(v.x), static_cast<Scalar>(v.y), 0); }
template <typename Vec3>
static constexpr Scalar noise3D(const Vec3& v) { return noise(static_cast<Scalar>(v.x), static_cast<Scalar>(v.y), static_cast<Scalar>(v.z)); }
template <typename S>
static constexpr Scalar noise1D(S x) { return noise(static_cast<Scalar>(x), 0, 0); }
template <typename S>
static constexpr Scalar noise2D(S x, S y) { return noise(static_cast<Scalar>(x), static_cast<Scalar>(y), 0); }
template <typename S>
static constexpr Scalar noise3D(S x, S y, S z) { return noise(static_cast<Scalar>(x), static_cast<Scalar>(y), static_cast<Scalar>(z)); }
template <typename Vec2, typename Ti, typename = std::enable_if_t<std::is_integral<Ti>::value>>
static constexpr Scalar octave_noise2D(const Vec2& v, Ti octaves)
{
return octave_noise(
static_cast<Scalar>(v.x),
static_cast<Scalar>(v.y),
0,
static_cast<uint32_t>(octaves));
}
template <typename Vec3, typename Ti, typename = std::enable_if_t<std::is_integral<Ti>::value>>
static constexpr Scalar octave_noise3D(const Vec3& v, Ti octaves)
{
return octave_noise(
static_cast<Scalar>(v.x),
static_cast<Scalar>(v.y),
static_cast<Scalar>(v.z),
static_cast<uint32_t>(octaves));
}
template <typename S, typename Ti, typename = std::enable_if_t<std::is_integral<Ti>::value>>
static constexpr Scalar octave_noise1D(S x, Ti octaves)
{
return octave_noise(
static_cast<Scalar>(x),
0,
0,
static_cast<uint32_t>(octaves));
}
template <typename S, typename Ti, typename = std::enable_if_t<std::is_integral<Ti>::value>>
static constexpr Scalar octave_noise2D(S x, S y, Ti octaves)
{
return octave_noise(
static_cast<Scalar>(x),
static_cast<Scalar>(y),
0,
static_cast<uint32_t>(octaves));
}
template <typename S, typename Ti, typename = std::enable_if_t<std::is_integral<Ti>::value>>
static constexpr Scalar octave_noise3D(S x, S y, S z, Ti octaves)
{
return octave_noise(
static_cast<Scalar>(x),
static_cast<Scalar>(y),
static_cast<Scalar>(z),
static_cast<uint32_t>(octaves));
}
template <typename Vec2, typename Ti, typename = std::enable_if_t<std::is_integral<Ti>::value>>
static constexpr Scalar normalised_octave_noise2D(const Vec2& v, Ti octaves)
{
return normalised_octave_noise(
static_cast<Scalar>(v.x),
static_cast<Scalar>(v.y),
0,
static_cast<uint32_t>(octaves));
}
template <typename Vec3, typename Ti, typename = std::enable_if_t<std::is_integral<Ti>::value>>
static constexpr Scalar normalised_octave_noise3D(const Vec3& v, Ti octaves)
{
return normalised_octave_noise(
static_cast<Scalar>(v.x),
static_cast<Scalar>(v.y),
static_cast<Scalar>(v.z),
static_cast<uint32_t>(octaves));
}
template <typename S, typename Ti, typename = std::enable_if_t<std::is_integral<Ti>::value>>
static constexpr Scalar normalised_octave_noise1D(S x, Ti octaves)
{
return normalised_octave_noise(
static_cast<Scalar>(x),
0,
0,
static_cast<uint32_t>(octaves));
}
template <typename S, typename Ti, typename = std::enable_if_t<std::is_integral<Ti>::value>>
static constexpr Scalar normalised_octave_noise2D(S x, S y, Ti octaves)
{
return normalised_octave_noise(
static_cast<Scalar>(x),
static_cast<Scalar>(y),
0,
static_cast<uint32_t>(octaves));
}
template <typename S, typename Ti, typename = std::enable_if_t<std::is_integral<Ti>::value>>
static constexpr Scalar normalised_octave_noise3D(S x, S y, S z, Ti octaves)
{
return normalised_octave_noise(
static_cast<Scalar>(x),
static_cast<Scalar>(y),
static_cast<Scalar>(z),
static_cast<uint32_t>(octaves));
}
};
using defaultNoise = PerlinNoise<defaultType>;
using noise = defaultNoise;
}
#endif | 33.590909 | 144 | 0.628101 |
aab3bd61bf323c03bf9fb2fea1148cc1a47aee15 | 1,163 | h | C | Pods/PINRemoteImage/Source/Classes/PINRemoteImageDownloadTask.h | kiethandsome/LouStagram | f18ddf49b808381947b8963d35cbd29cf99e4471 | [
"MIT"
] | 30 | 2017-05-05T10:21:31.000Z | 2019-06-18T01:46:09.000Z | Pods/PINRemoteImage/Source/Classes/PINRemoteImageDownloadTask.h | kiethandsome/LouStagram | f18ddf49b808381947b8963d35cbd29cf99e4471 | [
"MIT"
] | 1 | 2017-10-12T09:06:25.000Z | 2018-11-07T03:04:47.000Z | Pods/PINRemoteImage/Source/Classes/PINRemoteImageDownloadTask.h | kiethandsome/LouStagram | f18ddf49b808381947b8963d35cbd29cf99e4471 | [
"MIT"
] | 6 | 2017-05-05T11:03:49.000Z | 2019-06-18T01:46:12.000Z | //
// PINRemoteImageDownloadTask.h
// Pods
//
// Created by Garrett Moon on 3/9/15.
//
//
#import <PINOperation/PINOperation.h>
#import "PINRemoteImageManager+Private.h"
#import "PINRemoteImageTask.h"
#import "PINProgressiveImage.h"
#import "PINResume.h"
@interface PINRemoteImageDownloadTask : PINRemoteImageTask
@property (nonatomic, strong, nullable) NSURL *URL;
@property (nonatomic, copy, nullable) NSString *ifRange;
@property (nonatomic, copy, readonly, nullable) NSData *data;
@property (nonatomic, readonly) float bytesPerSecond;
@property (nonatomic, readonly) float startAdjustedBytesPerSecond;
@property (nonatomic, readonly) CFTimeInterval estimatedRemainingTime;
- (void)scheduleDownloadWithRequest:(nonnull NSURLRequest *)request
resume:(nullable PINResume *)resume
skipRetry:(BOOL)skipRetry
priority:(PINRemoteImageManagerPriority)priority
completionHandler:(nonnull PINRemoteImageManagerDataCompletion)completionHandler;
- (void)didReceiveData:(nonnull NSData *)data;
- (void)didReceiveResponse:(nonnull NSURLResponse *)response;
@end
| 32.305556 | 99 | 0.732588 |
a9553ef1b0d00bab18e6173648b2f69d349f32c1 | 726 | h | C | Examples/Example1/Example1/Message.h | brurend/MXRMessenger | 28edd94413cafb7f5bbb66cececd37419abb8596 | [
"MIT"
] | null | null | null | Examples/Example1/Example1/Message.h | brurend/MXRMessenger | 28edd94413cafb7f5bbb66cececd37419abb8596 | [
"MIT"
] | null | null | null | Examples/Example1/Example1/Message.h | brurend/MXRMessenger | 28edd94413cafb7f5bbb66cececd37419abb8596 | [
"MIT"
] | null | null | null | //
// Message.h
// Example1
//
// Created by Scott Kensell on 5/1/17.
// Copyright © 2017 Scott Kensell. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <MXRMessenger/MXRMessengerMedium.h>
@class MessageMedium;
@interface Message : NSObject
@property (nonatomic, assign) NSInteger senderID;
@property (nonatomic, assign) NSTimeInterval timestamp;
@property (nonatomic, strong) NSString* text;
@property (nonatomic, strong) NSArray<MessageMedium*>* media;
+ (instancetype)randomMessage;
@end
@interface MessageMedium : NSObject <MXRMessengerMedium>
@property (nonatomic, strong) NSURL* photoURL;
@property (nonatomic, strong) NSURL* videoURL;
@property (nonatomic, strong) NSURL* audioURL;
@end
| 22 | 61 | 0.753444 |
6583bef5da61d61f75a79ce3b625a323fc4a031e | 81,184 | c | C | ffmpeg/libavcodec/mips/hevcdsp_mmi.c | GustavoGalo/discord-bot-1 | 031cd3397697e9273198712db18b662a31d63d15 | [
"MIT"
] | null | null | null | ffmpeg/libavcodec/mips/hevcdsp_mmi.c | GustavoGalo/discord-bot-1 | 031cd3397697e9273198712db18b662a31d63d15 | [
"MIT"
] | null | null | null | ffmpeg/libavcodec/mips/hevcdsp_mmi.c | GustavoGalo/discord-bot-1 | 031cd3397697e9273198712db18b662a31d63d15 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2019 Shiyou Yin (yinshiyou-hf@loongson.cn)
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavcodec/hevcdec.h"
#include "libavcodec/bit_depth_template.c"
#include "libavcodec/mips/hevcdsp_mips.h"
#include "libavutil/mips/mmiutils.h"
#define PUT_HEVC_QPEL_H(w, x_step, src_step, dst_step) \
void ff_hevc_put_hevc_qpel_h##w##_8_mmi(int16_t *dst, uint8_t *_src, \
ptrdiff_t _srcstride, \
int height, intptr_t mx, \
intptr_t my, int width) \
{ \
int x, y; \
pixel *src = (pixel*)_src - 3; \
ptrdiff_t srcstride = _srcstride / sizeof(pixel); \
double ftmp[15]; \
uint64_t rtmp[1]; \
const int8_t *filter = ff_hevc_qpel_filters[mx - 1]; \
DECLARE_VAR_ALL64; \
\
x = x_step; \
y = height; \
__asm__ volatile( \
MMI_LDC1(%[ftmp1], %[filter], 0x00) \
"li %[rtmp0], 0x08 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpckhbh %[ftmp2], %[ftmp0], %[ftmp1] \n\t" \
"punpcklbh %[ftmp1], %[ftmp0], %[ftmp1] \n\t" \
"psrah %[ftmp1], %[ftmp1], %[ftmp0] \n\t" \
"psrah %[ftmp2], %[ftmp2], %[ftmp0] \n\t" \
"pxor %[ftmp0], %[ftmp0], %[ftmp0] \n\t" \
\
"1: \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp3], %[src], 0x00) \
MMI_ULDC1(%[ftmp4], %[src], 0x01) \
MMI_ULDC1(%[ftmp5], %[src], 0x02) \
MMI_ULDC1(%[ftmp6], %[src], 0x03) \
"punpcklbh %[ftmp7], %[ftmp3], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp3], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp3], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp4], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp4], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp4], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp5], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp5], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp5], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp6], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp6], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp6], %[ftmp7], %[ftmp8] \n\t" \
TRANSPOSE_4H(%[ftmp3], %[ftmp4], %[ftmp5], %[ftmp6], \
%[ftmp7], %[ftmp8], %[ftmp9], %[ftmp10]) \
"paddh %[ftmp3], %[ftmp3], %[ftmp4] \n\t" \
"paddh %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"paddh %[ftmp3], %[ftmp3], %[ftmp5] \n\t" \
MMI_ULDC1(%[ftmp3], %[dst], 0x00) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[src], %[src], 0x04 \n\t" \
PTR_ADDIU "%[dst], %[dst], 0x08 \n\t" \
"bnez %[x], 2b \n\t" \
\
"daddi %[y], %[y], -0x01 \n\t" \
"li %[x], " #x_step " \n\t" \
PTR_ADDIU "%[src], %[src], " #src_step " \n\t" \
PTR_ADDIU "%[dst], %[dst], " #dst_step " \n\t" \
PTR_ADDU "%[src], %[src], %[stride] \n\t" \
PTR_ADDIU "%[dst], %[dst], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_ALL64 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[ftmp10]"=&f"(ftmp[10]), [rtmp0]"=&r"(rtmp[0]), \
[src]"+&r"(src), [dst]"+&r"(dst), [y]"+&r"(y), \
[x]"+&r"(x) \
: [filter]"r"(filter), [stride]"r"(srcstride) \
: "memory" \
); \
}
PUT_HEVC_QPEL_H(4, 1, -4, -8);
PUT_HEVC_QPEL_H(8, 2, -8, -16);
PUT_HEVC_QPEL_H(12, 3, -12, -24);
PUT_HEVC_QPEL_H(16, 4, -16, -32);
PUT_HEVC_QPEL_H(24, 6, -24, -48);
PUT_HEVC_QPEL_H(32, 8, -32, -64);
PUT_HEVC_QPEL_H(48, 12, -48, -96);
PUT_HEVC_QPEL_H(64, 16, -64, -128);
#define PUT_HEVC_QPEL_HV(w, x_step, src_step, dst_step) \
void ff_hevc_put_hevc_qpel_hv##w##_8_mmi(int16_t *dst, uint8_t *_src, \
ptrdiff_t _srcstride, \
int height, intptr_t mx, \
intptr_t my, int width) \
{ \
int x, y; \
const int8_t *filter; \
pixel *src = (pixel*)_src; \
ptrdiff_t srcstride = _srcstride / sizeof(pixel); \
int16_t tmp_array[(MAX_PB_SIZE + QPEL_EXTRA) * MAX_PB_SIZE]; \
int16_t *tmp = tmp_array; \
double ftmp[15]; \
uint64_t rtmp[1]; \
DECLARE_VAR_ALL64; \
\
src -= (QPEL_EXTRA_BEFORE * srcstride + 3); \
filter = ff_hevc_qpel_filters[mx - 1]; \
x = x_step; \
y = height + QPEL_EXTRA; \
__asm__ volatile( \
MMI_LDC1(%[ftmp1], %[filter], 0x00) \
"li %[rtmp0], 0x08 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpckhbh %[ftmp2], %[ftmp0], %[ftmp1] \n\t" \
"punpcklbh %[ftmp1], %[ftmp0], %[ftmp1] \n\t" \
"psrah %[ftmp1], %[ftmp1], %[ftmp0] \n\t" \
"psrah %[ftmp2], %[ftmp2], %[ftmp0] \n\t" \
"pxor %[ftmp0], %[ftmp0], %[ftmp0] \n\t" \
\
"1: \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp3], %[src], 0x00) \
MMI_ULDC1(%[ftmp4], %[src], 0x01) \
MMI_ULDC1(%[ftmp5], %[src], 0x02) \
MMI_ULDC1(%[ftmp6], %[src], 0x03) \
"punpcklbh %[ftmp7], %[ftmp3], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp3], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp3], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp4], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp4], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp4], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp5], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp5], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp5], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp6], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp6], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp6], %[ftmp7], %[ftmp8] \n\t" \
TRANSPOSE_4H(%[ftmp3], %[ftmp4], %[ftmp5], %[ftmp6], \
%[ftmp7], %[ftmp8], %[ftmp9], %[ftmp10]) \
"paddh %[ftmp3], %[ftmp3], %[ftmp4] \n\t" \
"paddh %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"paddh %[ftmp3], %[ftmp3], %[ftmp5] \n\t" \
MMI_ULDC1(%[ftmp3], %[tmp], 0x00) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[src], %[src], 0x04 \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x08 \n\t" \
"bnez %[x], 2b \n\t" \
\
"daddi %[y], %[y], -0x01 \n\t" \
"li %[x], " #x_step " \n\t" \
PTR_ADDIU "%[src], %[src], " #src_step " \n\t" \
PTR_ADDIU "%[tmp], %[tmp], " #dst_step " \n\t" \
PTR_ADDU "%[src], %[src], %[stride] \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_ALL64 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[ftmp10]"=&f"(ftmp[10]), [rtmp0]"=&r"(rtmp[0]), \
[src]"+&r"(src), [tmp]"+&r"(tmp), [y]"+&r"(y), \
[x]"+&r"(x) \
: [filter]"r"(filter), [stride]"r"(srcstride) \
: "memory" \
); \
\
tmp = tmp_array + QPEL_EXTRA_BEFORE * 4 -12; \
filter = ff_hevc_qpel_filters[my - 1]; \
x = x_step; \
y = height; \
__asm__ volatile( \
MMI_LDC1(%[ftmp1], %[filter], 0x00) \
"li %[rtmp0], 0x08 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpckhbh %[ftmp2], %[ftmp0], %[ftmp1] \n\t" \
"punpcklbh %[ftmp1], %[ftmp0], %[ftmp1] \n\t" \
"psrah %[ftmp1], %[ftmp1], %[ftmp0] \n\t" \
"psrah %[ftmp2], %[ftmp2], %[ftmp0] \n\t" \
"li %[rtmp0], 0x06 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
\
"1: \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp3], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp4], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp5], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp6], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp7], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp8], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp9], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp10], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], -0x380 \n\t" \
TRANSPOSE_4H(%[ftmp3], %[ftmp4], %[ftmp5], %[ftmp6], \
%[ftmp11], %[ftmp12], %[ftmp13], %[ftmp14]) \
TRANSPOSE_4H(%[ftmp7], %[ftmp8], %[ftmp9], %[ftmp10], \
%[ftmp11], %[ftmp12], %[ftmp13], %[ftmp14]) \
"pmaddhw %[ftmp11], %[ftmp3], %[ftmp1] \n\t" \
"pmaddhw %[ftmp12], %[ftmp7], %[ftmp2] \n\t" \
"pmaddhw %[ftmp13], %[ftmp4], %[ftmp1] \n\t" \
"pmaddhw %[ftmp14], %[ftmp8], %[ftmp2] \n\t" \
"paddw %[ftmp11], %[ftmp11], %[ftmp12] \n\t" \
"paddw %[ftmp13], %[ftmp13], %[ftmp14] \n\t" \
TRANSPOSE_2W(%[ftmp11], %[ftmp13], %[ftmp3], %[ftmp4]) \
"paddw %[ftmp3], %[ftmp3], %[ftmp4] \n\t" \
"psraw %[ftmp3], %[ftmp3], %[ftmp0] \n\t" \
"pmaddhw %[ftmp11], %[ftmp5], %[ftmp1] \n\t" \
"pmaddhw %[ftmp12], %[ftmp9], %[ftmp2] \n\t" \
"pmaddhw %[ftmp13], %[ftmp6], %[ftmp1] \n\t" \
"pmaddhw %[ftmp14], %[ftmp10], %[ftmp2] \n\t" \
"paddw %[ftmp11], %[ftmp11], %[ftmp12] \n\t" \
"paddw %[ftmp13], %[ftmp13], %[ftmp14] \n\t" \
TRANSPOSE_2W(%[ftmp11], %[ftmp13], %[ftmp5], %[ftmp6]) \
"paddw %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[ftmp0] \n\t" \
"packsswh %[ftmp3], %[ftmp3], %[ftmp5] \n\t" \
MMI_USDC1(%[ftmp3], %[dst], 0x00) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[dst], %[dst], 0x08 \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x08 \n\t" \
"bnez %[x], 2b \n\t" \
\
"daddi %[y], %[y], -0x01 \n\t" \
"li %[x], " #x_step " \n\t" \
PTR_ADDIU "%[dst], %[dst], " #dst_step " \n\t" \
PTR_ADDIU "%[tmp], %[tmp], " #dst_step " \n\t" \
PTR_ADDIU "%[dst], %[dst], 0x80 \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_ALL64 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[ftmp10]"=&f"(ftmp[10]), [ftmp11]"=&f"(ftmp[11]), \
[ftmp12]"=&f"(ftmp[12]), [ftmp13]"=&f"(ftmp[13]), \
[ftmp14]"=&f"(ftmp[14]), [rtmp0]"=&r"(rtmp[0]), \
[dst]"+&r"(dst), [tmp]"+&r"(tmp), [y]"+&r"(y), \
[x]"+&r"(x) \
: [filter]"r"(filter), [stride]"r"(srcstride) \
: "memory" \
); \
}
PUT_HEVC_QPEL_HV(4, 1, -4, -8);
PUT_HEVC_QPEL_HV(8, 2, -8, -16);
PUT_HEVC_QPEL_HV(12, 3, -12, -24);
PUT_HEVC_QPEL_HV(16, 4, -16, -32);
PUT_HEVC_QPEL_HV(24, 6, -24, -48);
PUT_HEVC_QPEL_HV(32, 8, -32, -64);
PUT_HEVC_QPEL_HV(48, 12, -48, -96);
PUT_HEVC_QPEL_HV(64, 16, -64, -128);
#define PUT_HEVC_QPEL_BI_H(w, x_step, src_step, src2_step, dst_step) \
void ff_hevc_put_hevc_qpel_bi_h##w##_8_mmi(uint8_t *_dst, \
ptrdiff_t _dststride, \
uint8_t *_src, \
ptrdiff_t _srcstride, \
int16_t *src2, int height, \
intptr_t mx, intptr_t my, \
int width) \
{ \
int x, y; \
pixel *src = (pixel*)_src - 3; \
ptrdiff_t srcstride = _srcstride / sizeof(pixel); \
pixel *dst = (pixel *)_dst; \
ptrdiff_t dststride = _dststride / sizeof(pixel); \
const int8_t *filter = ff_hevc_qpel_filters[mx - 1]; \
double ftmp[20]; \
uint64_t rtmp[1]; \
union av_intfloat64 shift; \
union av_intfloat64 offset; \
DECLARE_VAR_ALL64; \
DECLARE_VAR_LOW32; \
shift.i = 7; \
offset.i = 64; \
\
x = width >> 2; \
y = height; \
__asm__ volatile( \
MMI_LDC1(%[ftmp1], %[filter], 0x00) \
"li %[rtmp0], 0x08 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpckhbh %[ftmp2], %[ftmp0], %[ftmp1] \n\t" \
"punpcklbh %[ftmp1], %[ftmp0], %[ftmp1] \n\t" \
"psrah %[ftmp1], %[ftmp1], %[ftmp0] \n\t" \
"psrah %[ftmp2], %[ftmp2], %[ftmp0] \n\t" \
"pxor %[ftmp0], %[ftmp0], %[ftmp0] \n\t" \
"punpcklhw %[offset], %[offset], %[offset] \n\t" \
"punpcklwd %[offset], %[offset], %[offset] \n\t" \
\
"1: \n\t" \
"li %[x], " #x_step " \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp3], %[src], 0x00) \
MMI_ULDC1(%[ftmp4], %[src], 0x01) \
MMI_ULDC1(%[ftmp5], %[src], 0x02) \
MMI_ULDC1(%[ftmp6], %[src], 0x03) \
"punpcklbh %[ftmp7], %[ftmp3], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp3], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp3], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp4], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp4], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp4], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp5], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp5], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp5], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp6], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp6], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp6], %[ftmp7], %[ftmp8] \n\t" \
TRANSPOSE_4H(%[ftmp3], %[ftmp4], %[ftmp5], %[ftmp6], \
%[ftmp7], %[ftmp8], %[ftmp9], %[ftmp10]) \
"paddh %[ftmp3], %[ftmp3], %[ftmp4] \n\t" \
"paddh %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"paddh %[ftmp3], %[ftmp3], %[ftmp5] \n\t" \
"paddh %[ftmp3], %[ftmp3], %[offset] \n\t" \
MMI_ULDC1(%[ftmp4], %[src2], 0x00) \
"li %[rtmp0], 0x10 \n\t" \
"dmtc1 %[rtmp0], %[ftmp8] \n\t" \
"punpcklhw %[ftmp5], %[ftmp0], %[ftmp3] \n\t" \
"punpckhhw %[ftmp6], %[ftmp0], %[ftmp3] \n\t" \
"punpckhhw %[ftmp3], %[ftmp0], %[ftmp4] \n\t" \
"punpcklhw %[ftmp4], %[ftmp0], %[ftmp4] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[ftmp8] \n\t" \
"psraw %[ftmp6], %[ftmp6], %[ftmp8] \n\t" \
"psraw %[ftmp3], %[ftmp3], %[ftmp8] \n\t" \
"psraw %[ftmp4], %[ftmp4], %[ftmp8] \n\t" \
"paddw %[ftmp5], %[ftmp5], %[ftmp4] \n\t" \
"paddw %[ftmp6], %[ftmp6], %[ftmp3] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[shift] \n\t" \
"psraw %[ftmp6], %[ftmp6], %[shift] \n\t" \
"packsswh %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"pcmpgth %[ftmp7], %[ftmp5], %[ftmp0] \n\t" \
"pand %[ftmp3], %[ftmp5], %[ftmp7] \n\t" \
"packushb %[ftmp3], %[ftmp3], %[ftmp3] \n\t" \
MMI_USWC1(%[ftmp3], %[dst], 0x00) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[src], %[src], 0x04 \n\t" \
PTR_ADDIU "%[dst], %[dst], 0x04 \n\t" \
PTR_ADDIU "%[src2], %[src2], 0x08 \n\t" \
"bnez %[x], 2b \n\t" \
\
"daddi %[y], %[y], -0x01 \n\t" \
PTR_ADDIU "%[src], %[src], " #src_step " \n\t" \
PTR_ADDIU "%[dst], %[dst], " #dst_step " \n\t" \
PTR_ADDIU "%[src2], %[src2], " #src2_step " \n\t" \
PTR_ADDU "%[src], %[src], %[src_stride] \n\t" \
PTR_ADDU "%[dst], %[dst], %[dst_stride] \n\t" \
PTR_ADDIU "%[src2], %[src2], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_ALL64 RESTRICT_ASM_LOW32 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[ftmp10]"=&f"(ftmp[10]), [ftmp11]"=&f"(ftmp[11]), \
[ftmp12]"=&f"(ftmp[12]), [src2]"+&r"(src2), \
[dst]"+&r"(dst), [src]"+&r"(src), [y]"+&r"(y), [x]"=&r"(x), \
[offset]"+&f"(offset.f), [rtmp0]"=&r"(rtmp[0]) \
: [src_stride]"r"(srcstride), [dst_stride]"r"(dststride), \
[filter]"r"(filter), [shift]"f"(shift.f) \
: "memory" \
); \
}
PUT_HEVC_QPEL_BI_H(4, 1, -4, -8, -4);
PUT_HEVC_QPEL_BI_H(8, 2, -8, -16, -8);
PUT_HEVC_QPEL_BI_H(12, 3, -12, -24, -12);
PUT_HEVC_QPEL_BI_H(16, 4, -16, -32, -16);
PUT_HEVC_QPEL_BI_H(24, 6, -24, -48, -24);
PUT_HEVC_QPEL_BI_H(32, 8, -32, -64, -32);
PUT_HEVC_QPEL_BI_H(48, 12, -48, -96, -48);
PUT_HEVC_QPEL_BI_H(64, 16, -64, -128, -64);
#define PUT_HEVC_QPEL_BI_HV(w, x_step, src_step, src2_step, dst_step) \
void ff_hevc_put_hevc_qpel_bi_hv##w##_8_mmi(uint8_t *_dst, \
ptrdiff_t _dststride, \
uint8_t *_src, \
ptrdiff_t _srcstride, \
int16_t *src2, int height, \
intptr_t mx, intptr_t my, \
int width) \
{ \
int x, y; \
const int8_t *filter; \
pixel *src = (pixel*)_src; \
ptrdiff_t srcstride = _srcstride / sizeof(pixel); \
pixel *dst = (pixel *)_dst; \
ptrdiff_t dststride = _dststride / sizeof(pixel); \
int16_t tmp_array[(MAX_PB_SIZE + QPEL_EXTRA) * MAX_PB_SIZE]; \
int16_t *tmp = tmp_array; \
double ftmp[20]; \
uint64_t rtmp[1]; \
union av_intfloat64 shift; \
union av_intfloat64 offset; \
DECLARE_VAR_ALL64; \
DECLARE_VAR_LOW32; \
shift.i = 7; \
offset.i = 64; \
\
src -= (QPEL_EXTRA_BEFORE * srcstride + 3); \
filter = ff_hevc_qpel_filters[mx - 1]; \
x = width >> 2; \
y = height + QPEL_EXTRA; \
__asm__ volatile( \
MMI_LDC1(%[ftmp1], %[filter], 0x00) \
"li %[rtmp0], 0x08 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpckhbh %[ftmp2], %[ftmp0], %[ftmp1] \n\t" \
"punpcklbh %[ftmp1], %[ftmp0], %[ftmp1] \n\t" \
"psrah %[ftmp1], %[ftmp1], %[ftmp0] \n\t" \
"psrah %[ftmp2], %[ftmp2], %[ftmp0] \n\t" \
"pxor %[ftmp0], %[ftmp0], %[ftmp0] \n\t" \
\
"1: \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp3], %[src], 0x00) \
MMI_ULDC1(%[ftmp4], %[src], 0x01) \
MMI_ULDC1(%[ftmp5], %[src], 0x02) \
MMI_ULDC1(%[ftmp6], %[src], 0x03) \
"punpcklbh %[ftmp7], %[ftmp3], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp3], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp3], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp4], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp4], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp4], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp5], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp5], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp5], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp6], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp6], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp6], %[ftmp7], %[ftmp8] \n\t" \
TRANSPOSE_4H(%[ftmp3], %[ftmp4], %[ftmp5], %[ftmp6], \
%[ftmp7], %[ftmp8], %[ftmp9], %[ftmp10]) \
"paddh %[ftmp3], %[ftmp3], %[ftmp4] \n\t" \
"paddh %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"paddh %[ftmp3], %[ftmp3], %[ftmp5] \n\t" \
MMI_USDC1(%[ftmp3], %[tmp], 0x00) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[src], %[src], 0x04 \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x08 \n\t" \
"bnez %[x], 2b \n\t" \
\
"daddi %[y], %[y], -0x01 \n\t" \
"li %[x], " #x_step " \n\t" \
PTR_ADDIU "%[src], %[src], " #src_step " \n\t" \
PTR_ADDIU "%[tmp], %[tmp], " #src2_step " \n\t" \
PTR_ADDU "%[src], %[src], %[stride] \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_ALL64 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[ftmp10]"=&f"(ftmp[10]), [rtmp0]"=&r"(rtmp[0]), \
[src]"+&r"(src), [tmp]"+&r"(tmp), [y]"+&r"(y), \
[x]"+&r"(x) \
: [filter]"r"(filter), [stride]"r"(srcstride) \
: "memory" \
); \
\
tmp = tmp_array; \
filter = ff_hevc_qpel_filters[my - 1]; \
x = width >> 2; \
y = height; \
__asm__ volatile( \
MMI_LDC1(%[ftmp1], %[filter], 0x00) \
"li %[rtmp0], 0x08 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpckhbh %[ftmp2], %[ftmp0], %[ftmp1] \n\t" \
"punpcklbh %[ftmp1], %[ftmp0], %[ftmp1] \n\t" \
"psrah %[ftmp1], %[ftmp1], %[ftmp0] \n\t" \
"psrah %[ftmp2], %[ftmp2], %[ftmp0] \n\t" \
"li %[rtmp0], 0x06 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpcklwd %[offset], %[offset], %[offset] \n\t" \
\
"1: \n\t" \
"li %[x], " #x_step " \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp3], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp4], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp5], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp6], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp7], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp8], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp9], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp10], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], -0x380 \n\t" \
TRANSPOSE_4H(%[ftmp3], %[ftmp4], %[ftmp5], %[ftmp6], \
%[ftmp11], %[ftmp12], %[ftmp13], %[ftmp14]) \
TRANSPOSE_4H(%[ftmp7], %[ftmp8], %[ftmp9], %[ftmp10], \
%[ftmp11], %[ftmp12], %[ftmp13], %[ftmp14]) \
"pmaddhw %[ftmp11], %[ftmp3], %[ftmp1] \n\t" \
"pmaddhw %[ftmp12], %[ftmp7], %[ftmp2] \n\t" \
"pmaddhw %[ftmp13], %[ftmp4], %[ftmp1] \n\t" \
"pmaddhw %[ftmp14], %[ftmp8], %[ftmp2] \n\t" \
"paddw %[ftmp11], %[ftmp11], %[ftmp12] \n\t" \
"paddw %[ftmp13], %[ftmp13], %[ftmp14] \n\t" \
TRANSPOSE_2W(%[ftmp11], %[ftmp13], %[ftmp3], %[ftmp4]) \
"paddw %[ftmp3], %[ftmp3], %[ftmp4] \n\t" \
"psraw %[ftmp3], %[ftmp3], %[ftmp0] \n\t" \
"pmaddhw %[ftmp11], %[ftmp5], %[ftmp1] \n\t" \
"pmaddhw %[ftmp12], %[ftmp9], %[ftmp2] \n\t" \
"pmaddhw %[ftmp13], %[ftmp6], %[ftmp1] \n\t" \
"pmaddhw %[ftmp14], %[ftmp10], %[ftmp2] \n\t" \
"paddw %[ftmp11], %[ftmp11], %[ftmp12] \n\t" \
"paddw %[ftmp13], %[ftmp13], %[ftmp14] \n\t" \
TRANSPOSE_2W(%[ftmp11], %[ftmp13], %[ftmp5], %[ftmp6]) \
"paddw %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[ftmp0] \n\t" \
"packsswh %[ftmp3], %[ftmp3], %[ftmp5] \n\t" \
MMI_ULDC1(%[ftmp4], %[src2], 0x00) \
"pxor %[ftmp7], %[ftmp7], %[ftmp7] \n\t" \
"li %[rtmp0], 0x10 \n\t" \
"dmtc1 %[rtmp0], %[ftmp8] \n\t" \
"punpcklhw %[ftmp5], %[ftmp7], %[ftmp3] \n\t" \
"punpckhhw %[ftmp6], %[ftmp7], %[ftmp3] \n\t" \
"punpckhhw %[ftmp3], %[ftmp7], %[ftmp4] \n\t" \
"punpcklhw %[ftmp4], %[ftmp7], %[ftmp4] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[ftmp8] \n\t" \
"psraw %[ftmp6], %[ftmp6], %[ftmp8] \n\t" \
"psraw %[ftmp3], %[ftmp3], %[ftmp8] \n\t" \
"psraw %[ftmp4], %[ftmp4], %[ftmp8] \n\t" \
"paddw %[ftmp5], %[ftmp5], %[ftmp4] \n\t" \
"paddw %[ftmp6], %[ftmp6], %[ftmp3] \n\t" \
"paddw %[ftmp5], %[ftmp5], %[offset] \n\t" \
"paddw %[ftmp6], %[ftmp6], %[offset] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[shift] \n\t" \
"psraw %[ftmp6], %[ftmp6], %[shift] \n\t" \
"packsswh %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"pcmpgth %[ftmp7], %[ftmp5], %[ftmp7] \n\t" \
"pand %[ftmp3], %[ftmp5], %[ftmp7] \n\t" \
"packushb %[ftmp3], %[ftmp3], %[ftmp3] \n\t" \
MMI_USWC1(%[ftmp3], %[dst], 0x00) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[src2], %[src2], 0x08 \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x08 \n\t" \
PTR_ADDIU "%[dst], %[dst], 0x04 \n\t" \
"bnez %[x], 2b \n\t" \
\
"daddi %[y], %[y], -0x01 \n\t" \
PTR_ADDIU "%[src2], %[src2], " #src2_step " \n\t" \
PTR_ADDIU "%[tmp], %[tmp], " #src2_step " \n\t" \
PTR_ADDIU "%[dst], %[dst], " #dst_step " \n\t" \
PTR_ADDIU "%[src2], %[src2], 0x80 \n\t" \
PTR_ADDU "%[dst], %[dst], %[stride] \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_ALL64 RESTRICT_ASM_LOW32 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[ftmp10]"=&f"(ftmp[10]), [ftmp11]"=&f"(ftmp[11]), \
[ftmp12]"=&f"(ftmp[12]), [ftmp13]"=&f"(ftmp[13]), \
[ftmp14]"=&f"(ftmp[14]), [src2]"+&r"(src2), \
[dst]"+&r"(dst), [tmp]"+&r"(tmp), [y]"+&r"(y), [x]"=&r"(x), \
[offset]"+&f"(offset.f), [rtmp0]"=&r"(rtmp[0]) \
: [filter]"r"(filter), [stride]"r"(dststride), \
[shift]"f"(shift.f) \
: "memory" \
); \
}
PUT_HEVC_QPEL_BI_HV(4, 1, -4, -8, -4);
PUT_HEVC_QPEL_BI_HV(8, 2, -8, -16, -8);
PUT_HEVC_QPEL_BI_HV(12, 3, -12, -24, -12);
PUT_HEVC_QPEL_BI_HV(16, 4, -16, -32, -16);
PUT_HEVC_QPEL_BI_HV(24, 6, -24, -48, -24);
PUT_HEVC_QPEL_BI_HV(32, 8, -32, -64, -32);
PUT_HEVC_QPEL_BI_HV(48, 12, -48, -96, -48);
PUT_HEVC_QPEL_BI_HV(64, 16, -64, -128, -64);
#define PUT_HEVC_EPEL_BI_HV(w, x_step, src_step, src2_step, dst_step) \
void ff_hevc_put_hevc_epel_bi_hv##w##_8_mmi(uint8_t *_dst, \
ptrdiff_t _dststride, \
uint8_t *_src, \
ptrdiff_t _srcstride, \
int16_t *src2, int height, \
intptr_t mx, intptr_t my, \
int width) \
{ \
int x, y; \
pixel *src = (pixel *)_src; \
ptrdiff_t srcstride = _srcstride / sizeof(pixel); \
pixel *dst = (pixel *)_dst; \
ptrdiff_t dststride = _dststride / sizeof(pixel); \
const int8_t *filter = ff_hevc_epel_filters[mx - 1]; \
int16_t tmp_array[(MAX_PB_SIZE + EPEL_EXTRA) * MAX_PB_SIZE]; \
int16_t *tmp = tmp_array; \
double ftmp[12]; \
uint64_t rtmp[1]; \
union av_intfloat64 shift; \
union av_intfloat64 offset; \
DECLARE_VAR_ALL64; \
DECLARE_VAR_LOW32; \
shift.i = 7; \
offset.i = 64; \
\
src -= (EPEL_EXTRA_BEFORE * srcstride + 1); \
x = width >> 2; \
y = height + EPEL_EXTRA; \
__asm__ volatile( \
MMI_LWC1(%[ftmp1], %[filter], 0x00) \
"li %[rtmp0], 0x08 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpcklbh %[ftmp1], %[ftmp0], %[ftmp1] \n\t" \
"psrah %[ftmp1], %[ftmp1], %[ftmp0] \n\t" \
"pxor %[ftmp0], %[ftmp0], %[ftmp0] \n\t" \
\
"1: \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp3], %[src], 0x00) \
MMI_ULDC1(%[ftmp4], %[src], 0x01) \
MMI_ULDC1(%[ftmp5], %[src], 0x02) \
MMI_ULDC1(%[ftmp6], %[src], 0x03) \
"punpcklbh %[ftmp2], %[ftmp2], %[ftmp0] \n\t" \
"pmullh %[ftmp2], %[ftmp2], %[ftmp1] \n\t" \
"punpcklbh %[ftmp3], %[ftmp3], %[ftmp0] \n\t" \
"pmullh %[ftmp3], %[ftmp3], %[ftmp1] \n\t" \
"punpcklbh %[ftmp4], %[ftmp4], %[ftmp0] \n\t" \
"pmullh %[ftmp4], %[ftmp4], %[ftmp1] \n\t" \
"punpcklbh %[ftmp5], %[ftmp5], %[ftmp0] \n\t" \
"pmullh %[ftmp5], %[ftmp5], %[ftmp1] \n\t" \
TRANSPOSE_4H(%[ftmp2], %[ftmp3], %[ftmp4], %[ftmp5], \
%[ftmp6], %[ftmp7], %[ftmp8], %[ftmp9]) \
"paddh %[ftmp2], %[ftmp2], %[ftmp3] \n\t" \
"paddh %[ftmp4], %[ftmp4], %[ftmp5] \n\t" \
"paddh %[ftmp2], %[ftmp2], %[ftmp4] \n\t" \
MMI_ULDC1(%[ftmp2], %[tmp], 0x00) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[src], %[src], 0x04 \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x08 \n\t" \
"bnez %[x], 2b \n\t" \
\
"daddi %[y], %[y], -0x01 \n\t" \
"li %[x], " #x_step " \n\t" \
PTR_ADDIU "%[src], %[src], " #src_step " \n\t" \
PTR_ADDIU "%[tmp], %[tmp], " #src2_step " \n\t" \
PTR_ADDU "%[src], %[src], %[stride] \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_ALL64 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[rtmp0]"=&r"(rtmp[0]), \
[src]"+&r"(src), [tmp]"+&r"(tmp), [y]"+&r"(y), \
[x]"+&r"(x) \
: [filter]"r"(filter), [stride]"r"(srcstride) \
: "memory" \
); \
\
tmp = tmp_array; \
filter = ff_hevc_epel_filters[my - 1]; \
x = width >> 2; \
y = height; \
__asm__ volatile( \
MMI_LWC1(%[ftmp1], %[filter], 0x00) \
"li %[rtmp0], 0x08 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpcklbh %[ftmp1], %[ftmp0], %[ftmp1] \n\t" \
"psrah %[ftmp1], %[ftmp1], %[ftmp0] \n\t" \
"li %[rtmp0], 0x06 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpcklwd %[offset], %[offset], %[offset] \n\t" \
"pxor %[ftmp2], %[ftmp2], %[ftmp2] \n\t" \
\
"1: \n\t" \
"li %[x], " #x_step " \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp3], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp4], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp5], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp6], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], -0x180 \n\t" \
TRANSPOSE_4H(%[ftmp3], %[ftmp4], %[ftmp5], %[ftmp6], \
%[ftmp7], %[ftmp8], %[ftmp9], %[ftmp10]) \
"pmaddhw %[ftmp7], %[ftmp3], %[ftmp1] \n\t" \
"pmaddhw %[ftmp8], %[ftmp4], %[ftmp1] \n\t" \
TRANSPOSE_2W(%[ftmp7], %[ftmp8], %[ftmp3], %[ftmp4]) \
"paddw %[ftmp3], %[ftmp3], %[ftmp4] \n\t" \
"psraw %[ftmp3], %[ftmp3], %[ftmp0] \n\t" \
"pmaddhw %[ftmp7], %[ftmp5], %[ftmp1] \n\t" \
"pmaddhw %[ftmp8], %[ftmp6], %[ftmp1] \n\t" \
TRANSPOSE_2W(%[ftmp7], %[ftmp8], %[ftmp5], %[ftmp6]) \
"paddw %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[ftmp0] \n\t" \
"packsswh %[ftmp3], %[ftmp3], %[ftmp5] \n\t" \
MMI_ULDC1(%[ftmp4], %[tmp], 0x02) \
"li %[rtmp0], 0x10 \n\t" \
"dmtc1 %[rtmp0], %[ftmp8] \n\t" \
"punpcklhw %[ftmp5], %[ftmp2], %[ftmp3] \n\t" \
"punpckhhw %[ftmp6], %[ftmp2], %[ftmp3] \n\t" \
"punpckhhw %[ftmp3], %[ftmp2], %[ftmp4] \n\t" \
"punpcklhw %[ftmp4], %[ftmp2], %[ftmp4] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[ftmp8] \n\t" \
"psraw %[ftmp6], %[ftmp6], %[ftmp8] \n\t" \
"psraw %[ftmp3], %[ftmp3], %[ftmp8] \n\t" \
"psraw %[ftmp4], %[ftmp4], %[ftmp8] \n\t" \
"paddw %[ftmp5], %[ftmp5], %[ftmp4] \n\t" \
"paddw %[ftmp6], %[ftmp6], %[ftmp3] \n\t" \
"paddw %[ftmp5], %[ftmp5], %[offset] \n\t" \
"paddw %[ftmp6], %[ftmp6], %[offset] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[shift] \n\t" \
"psraw %[ftmp6], %[ftmp6], %[shift] \n\t" \
"packsswh %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"pcmpgth %[ftmp7], %[ftmp5], %[ftmp2] \n\t" \
"pand %[ftmp3], %[ftmp5], %[ftmp7] \n\t" \
"packushb %[ftmp3], %[ftmp3], %[ftmp3] \n\t" \
MMI_USWC1(%[ftmp3], %[dst], 0x0) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[src2], %[src2], 0x08 \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x08 \n\t" \
PTR_ADDIU "%[dst], %[dst], 0x04 \n\t" \
"bnez %[x], 2b \n\t" \
\
"daddi %[y], %[y], -0x01 \n\t" \
PTR_ADDIU "%[src2], %[src2], " #src2_step " \n\t" \
PTR_ADDIU "%[tmp], %[tmp], " #src2_step " \n\t" \
PTR_ADDIU "%[dst], %[dst], " #dst_step " \n\t" \
PTR_ADDIU "%[src2], %[src2], 0x80 \n\t" \
PTR_ADDU "%[dst], %[dst], %[stride] \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_LOW32 RESTRICT_ASM_ALL64 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[ftmp10]"=&f"(ftmp[10]), [src2]"+&r"(src2), \
[dst]"+&r"(dst), [tmp]"+&r"(tmp), [y]"+&r"(y), [x]"=&r"(x), \
[offset]"+&f"(offset.f), [rtmp0]"=&r"(rtmp[0]) \
: [filter]"r"(filter), [stride]"r"(dststride), \
[shift]"f"(shift.f) \
: "memory" \
); \
}
PUT_HEVC_EPEL_BI_HV(4, 1, -4, -8, -4);
PUT_HEVC_EPEL_BI_HV(8, 2, -8, -16, -8);
PUT_HEVC_EPEL_BI_HV(12, 3, -12, -24, -12);
PUT_HEVC_EPEL_BI_HV(16, 4, -16, -32, -16);
PUT_HEVC_EPEL_BI_HV(24, 6, -24, -48, -24);
PUT_HEVC_EPEL_BI_HV(32, 8, -32, -64, -32);
#define PUT_HEVC_PEL_BI_PIXELS(w, x_step, src_step, dst_step, src2_step) \
void ff_hevc_put_hevc_pel_bi_pixels##w##_8_mmi(uint8_t *_dst, \
ptrdiff_t _dststride, \
uint8_t *_src, \
ptrdiff_t _srcstride, \
int16_t *src2, int height, \
intptr_t mx, intptr_t my, \
int width) \
{ \
int x, y; \
pixel *src = (pixel *)_src; \
ptrdiff_t srcstride = _srcstride / sizeof(pixel); \
pixel *dst = (pixel *)_dst; \
ptrdiff_t dststride = _dststride / sizeof(pixel); \
double ftmp[12]; \
uint64_t rtmp[1]; \
union av_intfloat64 shift; \
DECLARE_VAR_ALL64; \
shift.i = 7; \
\
y = height; \
x = width >> 3; \
__asm__ volatile( \
"pxor %[ftmp0], %[ftmp0], %[ftmp0] \n\t" \
"li %[rtmp0], 0x06 \n\t" \
"dmtc1 %[rtmp0], %[ftmp1] \n\t" \
"li %[rtmp0], 0x10 \n\t" \
"dmtc1 %[rtmp0], %[ftmp10] \n\t" \
"li %[rtmp0], 0x40 \n\t" \
"dmtc1 %[rtmp0], %[offset] \n\t" \
"punpcklhw %[offset], %[offset], %[offset] \n\t" \
"punpcklwd %[offset], %[offset], %[offset] \n\t" \
\
"1: \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp5], %[src], 0x00) \
MMI_ULDC1(%[ftmp2], %[src2], 0x00) \
MMI_ULDC1(%[ftmp3], %[src2], 0x08) \
"punpcklbh %[ftmp4], %[ftmp5], %[ftmp0] \n\t" \
"punpckhbh %[ftmp5], %[ftmp5], %[ftmp0] \n\t" \
"psllh %[ftmp4], %[ftmp4], %[ftmp1] \n\t" \
"psllh %[ftmp5], %[ftmp5], %[ftmp1] \n\t" \
"paddh %[ftmp4], %[ftmp4], %[offset] \n\t" \
"paddh %[ftmp5], %[ftmp5], %[offset] \n\t" \
"punpcklhw %[ftmp6], %[ftmp4], %[ftmp0] \n\t" \
"punpckhhw %[ftmp7], %[ftmp4], %[ftmp0] \n\t" \
"punpcklhw %[ftmp8], %[ftmp5], %[ftmp0] \n\t" \
"punpckhhw %[ftmp9], %[ftmp5], %[ftmp0] \n\t" \
"punpcklhw %[ftmp4], %[ftmp0], %[ftmp3] \n\t" \
"punpckhhw %[ftmp5], %[ftmp0], %[ftmp3] \n\t" \
"punpckhhw %[ftmp3], %[ftmp0], %[ftmp2] \n\t" \
"punpcklhw %[ftmp2], %[ftmp0], %[ftmp2] \n\t" \
"psraw %[ftmp2], %[ftmp2], %[ftmp10] \n\t" \
"psraw %[ftmp3], %[ftmp3], %[ftmp10] \n\t" \
"psraw %[ftmp4], %[ftmp4], %[ftmp10] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[ftmp10] \n\t" \
"paddw %[ftmp2], %[ftmp2], %[ftmp6] \n\t" \
"paddw %[ftmp3], %[ftmp3], %[ftmp7] \n\t" \
"paddw %[ftmp4], %[ftmp4], %[ftmp8] \n\t" \
"paddw %[ftmp5], %[ftmp5], %[ftmp9] \n\t" \
"psraw %[ftmp2], %[ftmp2], %[shift] \n\t" \
"psraw %[ftmp3], %[ftmp3], %[shift] \n\t" \
"psraw %[ftmp4], %[ftmp4], %[shift] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[shift] \n\t" \
"packsswh %[ftmp2], %[ftmp2], %[ftmp3] \n\t" \
"packsswh %[ftmp4], %[ftmp4], %[ftmp5] \n\t" \
"pcmpgth %[ftmp3], %[ftmp2], %[ftmp0] \n\t" \
"pcmpgth %[ftmp5], %[ftmp4], %[ftmp0] \n\t" \
"pand %[ftmp2], %[ftmp2], %[ftmp3] \n\t" \
"pand %[ftmp4], %[ftmp4], %[ftmp5] \n\t" \
"packushb %[ftmp2], %[ftmp2], %[ftmp4] \n\t" \
MMI_USDC1(%[ftmp2], %[dst], 0x0) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[src], %[src], 0x08 \n\t" \
PTR_ADDIU "%[dst], %[dst], 0x08 \n\t" \
PTR_ADDIU "%[src2], %[src2], 0x10 \n\t" \
"bnez %[x], 2b \n\t" \
\
PTR_ADDIU "%[src], %[src], " #src_step " \n\t" \
PTR_ADDIU "%[dst], %[dst], " #dst_step " \n\t" \
PTR_ADDIU "%[src2], %[src2], " #src2_step " \n\t" \
"li %[x], " #x_step " \n\t" \
"daddi %[y], %[y], -0x01 \n\t" \
PTR_ADDU "%[src], %[src], %[srcstride] \n\t" \
PTR_ADDU "%[dst], %[dst], %[dststride] \n\t" \
PTR_ADDIU "%[src2], %[src2], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_ALL64 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[ftmp10]"=&f"(ftmp[10]), [offset]"=&f"(ftmp[11]), \
[src2]"+&r"(src2), [dst]"+&r"(dst), [src]"+&r"(src), \
[x]"+&r"(x), [y]"+&r"(y), [rtmp0]"=&r"(rtmp[0]) \
: [dststride]"r"(dststride), [shift]"f"(shift.f), \
[srcstride]"r"(srcstride) \
: "memory" \
); \
} \
PUT_HEVC_PEL_BI_PIXELS(8, 1, -8, -8, -16);
PUT_HEVC_PEL_BI_PIXELS(16, 2, -16, -16, -32);
PUT_HEVC_PEL_BI_PIXELS(24, 3, -24, -24, -48);
PUT_HEVC_PEL_BI_PIXELS(32, 4, -32, -32, -64);
PUT_HEVC_PEL_BI_PIXELS(48, 6, -48, -48, -96);
PUT_HEVC_PEL_BI_PIXELS(64, 8, -64, -64, -128);
#define PUT_HEVC_QPEL_UNI_HV(w, x_step, src_step, dst_step, tmp_step) \
void ff_hevc_put_hevc_qpel_uni_hv##w##_8_mmi(uint8_t *_dst, \
ptrdiff_t _dststride, \
uint8_t *_src, \
ptrdiff_t _srcstride, \
int height, \
intptr_t mx, intptr_t my, \
int width) \
{ \
int x, y; \
const int8_t *filter; \
pixel *src = (pixel*)_src; \
ptrdiff_t srcstride = _srcstride / sizeof(pixel); \
pixel *dst = (pixel *)_dst; \
ptrdiff_t dststride = _dststride / sizeof(pixel); \
int16_t tmp_array[(MAX_PB_SIZE + QPEL_EXTRA) * MAX_PB_SIZE]; \
int16_t *tmp = tmp_array; \
double ftmp[20]; \
uint64_t rtmp[1]; \
union av_intfloat64 shift; \
union av_intfloat64 offset; \
DECLARE_VAR_ALL64; \
DECLARE_VAR_LOW32; \
shift.i = 6; \
offset.i = 32; \
\
src -= (QPEL_EXTRA_BEFORE * srcstride + 3); \
filter = ff_hevc_qpel_filters[mx - 1]; \
x = width >> 2; \
y = height + QPEL_EXTRA; \
__asm__ volatile( \
MMI_LDC1(%[ftmp1], %[filter], 0x00) \
"li %[rtmp0], 0x08 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpckhbh %[ftmp2], %[ftmp0], %[ftmp1] \n\t" \
"punpcklbh %[ftmp1], %[ftmp0], %[ftmp1] \n\t" \
"psrah %[ftmp1], %[ftmp1], %[ftmp0] \n\t" \
"psrah %[ftmp2], %[ftmp2], %[ftmp0] \n\t" \
"pxor %[ftmp0], %[ftmp0], %[ftmp0] \n\t" \
\
"1: \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp3], %[src], 0x00) \
MMI_ULDC1(%[ftmp4], %[src], 0x01) \
MMI_ULDC1(%[ftmp5], %[src], 0x02) \
MMI_ULDC1(%[ftmp6], %[src], 0x03) \
"punpcklbh %[ftmp7], %[ftmp3], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp3], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp3], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp4], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp4], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp4], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp5], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp5], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp5], %[ftmp7], %[ftmp8] \n\t" \
"punpcklbh %[ftmp7], %[ftmp6], %[ftmp0] \n\t" \
"punpckhbh %[ftmp8], %[ftmp6], %[ftmp0] \n\t" \
"pmullh %[ftmp7], %[ftmp7], %[ftmp1] \n\t" \
"pmullh %[ftmp8], %[ftmp8], %[ftmp2] \n\t" \
"paddh %[ftmp6], %[ftmp7], %[ftmp8] \n\t" \
TRANSPOSE_4H(%[ftmp3], %[ftmp4], %[ftmp5], %[ftmp6], \
%[ftmp7], %[ftmp8], %[ftmp9], %[ftmp10]) \
"paddh %[ftmp3], %[ftmp3], %[ftmp4] \n\t" \
"paddh %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"paddh %[ftmp3], %[ftmp3], %[ftmp5] \n\t" \
MMI_USDC1(%[ftmp3], %[tmp], 0x0) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[src], %[src], 0x04 \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x08 \n\t" \
"bnez %[x], 2b \n\t" \
\
"daddi %[y], %[y], -0x01 \n\t" \
"li %[x], " #x_step " \n\t" \
PTR_ADDIU "%[src], %[src], " #src_step " \n\t" \
PTR_ADDIU "%[tmp], %[tmp], " #tmp_step " \n\t" \
PTR_ADDU "%[src], %[src], %[stride] \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_ALL64 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[ftmp10]"=&f"(ftmp[10]), [rtmp0]"=&r"(rtmp[0]), \
[src]"+&r"(src), [tmp]"+&r"(tmp), [y]"+&r"(y), \
[x]"+&r"(x) \
: [filter]"r"(filter), [stride]"r"(srcstride) \
: "memory" \
); \
\
tmp = tmp_array; \
filter = ff_hevc_qpel_filters[my - 1]; \
x = width >> 2; \
y = height; \
__asm__ volatile( \
MMI_LDC1(%[ftmp1], %[filter], 0x00) \
"li %[rtmp0], 0x08 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpckhbh %[ftmp2], %[ftmp0], %[ftmp1] \n\t" \
"punpcklbh %[ftmp1], %[ftmp0], %[ftmp1] \n\t" \
"psrah %[ftmp1], %[ftmp1], %[ftmp0] \n\t" \
"psrah %[ftmp2], %[ftmp2], %[ftmp0] \n\t" \
"li %[rtmp0], 0x06 \n\t" \
"dmtc1 %[rtmp0], %[ftmp0] \n\t" \
"punpcklhw %[offset], %[offset], %[offset] \n\t" \
"punpcklwd %[offset], %[offset], %[offset] \n\t" \
\
"1: \n\t" \
"li %[x], " #x_step " \n\t" \
"2: \n\t" \
MMI_ULDC1(%[ftmp3], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp4], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp5], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp6], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp7], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp8], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp9], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
MMI_ULDC1(%[ftmp10], %[tmp], 0x00) \
PTR_ADDIU "%[tmp], %[tmp], -0x380 \n\t" \
TRANSPOSE_4H(%[ftmp3], %[ftmp4], %[ftmp5], %[ftmp6], \
%[ftmp11], %[ftmp12], %[ftmp13], %[ftmp14]) \
TRANSPOSE_4H(%[ftmp7], %[ftmp8], %[ftmp9], %[ftmp10], \
%[ftmp11], %[ftmp12], %[ftmp13], %[ftmp14]) \
"pmaddhw %[ftmp11], %[ftmp3], %[ftmp1] \n\t" \
"pmaddhw %[ftmp12], %[ftmp7], %[ftmp2] \n\t" \
"pmaddhw %[ftmp13], %[ftmp4], %[ftmp1] \n\t" \
"pmaddhw %[ftmp14], %[ftmp8], %[ftmp2] \n\t" \
"paddw %[ftmp11], %[ftmp11], %[ftmp12] \n\t" \
"paddw %[ftmp13], %[ftmp13], %[ftmp14] \n\t" \
TRANSPOSE_2W(%[ftmp11], %[ftmp13], %[ftmp3], %[ftmp4]) \
"paddw %[ftmp3], %[ftmp3], %[ftmp4] \n\t" \
"psraw %[ftmp3], %[ftmp3], %[ftmp0] \n\t" \
"pmaddhw %[ftmp11], %[ftmp5], %[ftmp1] \n\t" \
"pmaddhw %[ftmp12], %[ftmp9], %[ftmp2] \n\t" \
"pmaddhw %[ftmp13], %[ftmp6], %[ftmp1] \n\t" \
"pmaddhw %[ftmp14], %[ftmp10], %[ftmp2] \n\t" \
"paddw %[ftmp11], %[ftmp11], %[ftmp12] \n\t" \
"paddw %[ftmp13], %[ftmp13], %[ftmp14] \n\t" \
TRANSPOSE_2W(%[ftmp11], %[ftmp13], %[ftmp5], %[ftmp6]) \
"paddw %[ftmp5], %[ftmp5], %[ftmp6] \n\t" \
"psraw %[ftmp5], %[ftmp5], %[ftmp0] \n\t" \
"packsswh %[ftmp3], %[ftmp3], %[ftmp5] \n\t" \
"paddh %[ftmp3], %[ftmp3], %[offset] \n\t" \
"psrah %[ftmp3], %[ftmp3], %[shift] \n\t" \
"pxor %[ftmp7], %[ftmp7], %[ftmp7] \n\t" \
"pcmpgth %[ftmp7], %[ftmp3], %[ftmp7] \n\t" \
"pand %[ftmp3], %[ftmp3], %[ftmp7] \n\t" \
"packushb %[ftmp3], %[ftmp3], %[ftmp3] \n\t" \
MMI_USWC1(%[ftmp3], %[dst], 0x00) \
\
"daddi %[x], %[x], -0x01 \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x08 \n\t" \
PTR_ADDIU "%[dst], %[dst], 0x04 \n\t" \
"bnez %[x], 2b \n\t" \
\
"daddi %[y], %[y], -0x01 \n\t" \
PTR_ADDIU "%[tmp], %[tmp], " #tmp_step " \n\t" \
PTR_ADDIU "%[dst], %[dst], " #dst_step " \n\t" \
PTR_ADDU "%[dst], %[dst], %[stride] \n\t" \
PTR_ADDIU "%[tmp], %[tmp], 0x80 \n\t" \
"bnez %[y], 1b \n\t" \
: RESTRICT_ASM_ALL64 RESTRICT_ASM_LOW32 \
[ftmp0]"=&f"(ftmp[0]), [ftmp1]"=&f"(ftmp[1]), \
[ftmp2]"=&f"(ftmp[2]), [ftmp3]"=&f"(ftmp[3]), \
[ftmp4]"=&f"(ftmp[4]), [ftmp5]"=&f"(ftmp[5]), \
[ftmp6]"=&f"(ftmp[6]), [ftmp7]"=&f"(ftmp[7]), \
[ftmp8]"=&f"(ftmp[8]), [ftmp9]"=&f"(ftmp[9]), \
[ftmp10]"=&f"(ftmp[10]), [ftmp11]"=&f"(ftmp[11]), \
[ftmp12]"=&f"(ftmp[12]), [ftmp13]"=&f"(ftmp[13]), \
[ftmp14]"=&f"(ftmp[14]), \
[dst]"+&r"(dst), [tmp]"+&r"(tmp), [y]"+&r"(y), [x]"=&r"(x), \
[offset]"+&f"(offset.f), [rtmp0]"=&r"(rtmp[0]) \
: [filter]"r"(filter), [stride]"r"(dststride), \
[shift]"f"(shift.f) \
: "memory" \
); \
}
PUT_HEVC_QPEL_UNI_HV(4, 1, -4, -4, -8);
PUT_HEVC_QPEL_UNI_HV(8, 2, -8, -8, -16);
PUT_HEVC_QPEL_UNI_HV(12, 3, -12, -12, -24);
PUT_HEVC_QPEL_UNI_HV(16, 4, -16, -16, -32);
PUT_HEVC_QPEL_UNI_HV(24, 6, -24, -24, -48);
PUT_HEVC_QPEL_UNI_HV(32, 8, -32, -32, -64);
PUT_HEVC_QPEL_UNI_HV(48, 12, -48, -48, -96);
PUT_HEVC_QPEL_UNI_HV(64, 16, -64, -64, -128);
| 70.841187 | 79 | 0.28194 |
30ed41313886ecb39a69ee3f173b5aba013c4b4e | 19,665 | c | C | usr/src/usr.sbin/bgpd/pfkey.c | sizeofvoid/ifconfigd | bdff4b2cec6d572c1450cb44f32c0bdab1b49e5f | [
"BSD-2-Clause"
] | 2 | 2020-04-15T13:39:01.000Z | 2020-08-28T01:27:00.000Z | usr/src/usr.sbin/bgpd/pfkey.c | sizeofvoid/ifconfigd | bdff4b2cec6d572c1450cb44f32c0bdab1b49e5f | [
"BSD-2-Clause"
] | null | null | null | usr/src/usr.sbin/bgpd/pfkey.c | sizeofvoid/ifconfigd | bdff4b2cec6d572c1450cb44f32c0bdab1b49e5f | [
"BSD-2-Clause"
] | 1 | 2020-08-28T01:25:41.000Z | 2020-08-28T01:25:41.000Z | /* $OpenBSD: pfkey.c,v 1.41 2010/12/09 13:50:41 claudio Exp $ */
/*
* Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
* Copyright (c) 2003, 2004 Markus Friedl <markus@openbsd.org>
*
* Permission to use, copy, modify, and 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.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <net/pfkeyv2.h>
#include <netinet/ip_ipsp.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "bgpd.h"
#include "session.h"
#define PFKEY2_CHUNK sizeof(u_int64_t)
#define ROUNDUP(x) (((x) + (PFKEY2_CHUNK - 1)) & ~(PFKEY2_CHUNK - 1))
#define IOV_CNT 20
static u_int32_t sadb_msg_seq = 0;
static u_int32_t pid = 0; /* should pid_t but pfkey needs u_int32_t */
static int fd;
int pfkey_reply(int, u_int32_t *);
int pfkey_send(int, uint8_t, uint8_t, uint8_t,
struct bgpd_addr *, struct bgpd_addr *,
u_int32_t, uint8_t, int, char *, uint8_t, int, char *,
uint16_t, uint16_t);
int pfkey_sa_add(struct bgpd_addr *, struct bgpd_addr *, u_int8_t, char *,
u_int32_t *);
int pfkey_sa_remove(struct bgpd_addr *, struct bgpd_addr *, u_int32_t *);
int pfkey_md5sig_establish(struct peer *);
int pfkey_md5sig_remove(struct peer *);
int pfkey_ipsec_establish(struct peer *);
int pfkey_ipsec_remove(struct peer *);
#define pfkey_flow(fd, satype, cmd, dir, from, to, sport, dport) \
pfkey_send(fd, satype, cmd, dir, from, to, \
0, 0, 0, NULL, 0, 0, NULL, sport, dport)
int
pfkey_send(int sd, uint8_t satype, uint8_t mtype, uint8_t dir,
struct bgpd_addr *src, struct bgpd_addr *dst, u_int32_t spi,
uint8_t aalg, int alen, char *akey, uint8_t ealg, int elen, char *ekey,
uint16_t sport, uint16_t dport)
{
struct sadb_msg smsg;
struct sadb_sa sa;
struct sadb_address sa_src, sa_dst, sa_peer, sa_smask, sa_dmask;
struct sadb_key sa_akey, sa_ekey;
struct sadb_spirange sa_spirange;
struct sadb_protocol sa_flowtype, sa_protocol;
struct iovec iov[IOV_CNT];
ssize_t n;
int len = 0;
int iov_cnt;
struct sockaddr_storage ssrc, sdst, speer, smask, dmask;
struct sockaddr *saptr;
if (!pid)
pid = getpid();
/* we need clean sockaddr... no ports set */
bzero(&ssrc, sizeof(ssrc));
bzero(&smask, sizeof(smask));
if ((saptr = addr2sa(src, 0)))
memcpy(&ssrc, saptr, sizeof(ssrc));
switch (src->aid) {
case AID_INET:
memset(&((struct sockaddr_in *)&smask)->sin_addr, 0xff, 32/8);
break;
case AID_INET6:
memset(&((struct sockaddr_in6 *)&smask)->sin6_addr, 0xff,
128/8);
break;
case AID_UNSPEC:
ssrc.ss_len = sizeof(struct sockaddr);
break;
default:
return (-1);
}
smask.ss_family = ssrc.ss_family;
smask.ss_len = ssrc.ss_len;
bzero(&sdst, sizeof(sdst));
bzero(&dmask, sizeof(dmask));
if ((saptr = addr2sa(dst, 0)))
memcpy(&sdst, saptr, sizeof(sdst));
switch (dst->aid) {
case AID_INET:
memset(&((struct sockaddr_in *)&dmask)->sin_addr, 0xff, 32/8);
break;
case AID_INET6:
memset(&((struct sockaddr_in6 *)&dmask)->sin6_addr, 0xff,
128/8);
break;
case AID_UNSPEC:
sdst.ss_len = sizeof(struct sockaddr);
break;
default:
return (-1);
}
dmask.ss_family = sdst.ss_family;
dmask.ss_len = sdst.ss_len;
bzero(&smsg, sizeof(smsg));
smsg.sadb_msg_version = PF_KEY_V2;
smsg.sadb_msg_seq = ++sadb_msg_seq;
smsg.sadb_msg_pid = pid;
smsg.sadb_msg_len = sizeof(smsg) / 8;
smsg.sadb_msg_type = mtype;
smsg.sadb_msg_satype = satype;
switch (mtype) {
case SADB_GETSPI:
bzero(&sa_spirange, sizeof(sa_spirange));
sa_spirange.sadb_spirange_exttype = SADB_EXT_SPIRANGE;
sa_spirange.sadb_spirange_len = sizeof(sa_spirange) / 8;
sa_spirange.sadb_spirange_min = 0x100;
sa_spirange.sadb_spirange_max = 0xffffffff;
sa_spirange.sadb_spirange_reserved = 0;
break;
case SADB_ADD:
case SADB_UPDATE:
case SADB_DELETE:
bzero(&sa, sizeof(sa));
sa.sadb_sa_exttype = SADB_EXT_SA;
sa.sadb_sa_len = sizeof(sa) / 8;
sa.sadb_sa_replay = 0;
sa.sadb_sa_spi = spi;
sa.sadb_sa_state = SADB_SASTATE_MATURE;
break;
case SADB_X_ADDFLOW:
case SADB_X_DELFLOW:
bzero(&sa_flowtype, sizeof(sa_flowtype));
sa_flowtype.sadb_protocol_exttype = SADB_X_EXT_FLOW_TYPE;
sa_flowtype.sadb_protocol_len = sizeof(sa_flowtype) / 8;
sa_flowtype.sadb_protocol_direction = dir;
sa_flowtype.sadb_protocol_proto = SADB_X_FLOW_TYPE_REQUIRE;
bzero(&sa_protocol, sizeof(sa_protocol));
sa_protocol.sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
sa_protocol.sadb_protocol_len = sizeof(sa_protocol) / 8;
sa_protocol.sadb_protocol_direction = 0;
sa_protocol.sadb_protocol_proto = 6;
break;
}
bzero(&sa_src, sizeof(sa_src));
sa_src.sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
sa_src.sadb_address_len = (sizeof(sa_src) + ROUNDUP(ssrc.ss_len)) / 8;
bzero(&sa_dst, sizeof(sa_dst));
sa_dst.sadb_address_exttype = SADB_EXT_ADDRESS_DST;
sa_dst.sadb_address_len = (sizeof(sa_dst) + ROUNDUP(sdst.ss_len)) / 8;
sa.sadb_sa_auth = aalg;
sa.sadb_sa_encrypt = SADB_X_EALG_AES; /* XXX */
switch (mtype) {
case SADB_ADD:
case SADB_UPDATE:
bzero(&sa_akey, sizeof(sa_akey));
sa_akey.sadb_key_exttype = SADB_EXT_KEY_AUTH;
sa_akey.sadb_key_len = (sizeof(sa_akey) +
((alen + 7) / 8) * 8) / 8;
sa_akey.sadb_key_bits = 8 * alen;
bzero(&sa_ekey, sizeof(sa_ekey));
sa_ekey.sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
sa_ekey.sadb_key_len = (sizeof(sa_ekey) +
((elen + 7) / 8) * 8) / 8;
sa_ekey.sadb_key_bits = 8 * elen;
break;
case SADB_X_ADDFLOW:
case SADB_X_DELFLOW:
/* sa_peer always points to the remote machine */
if (dir == IPSP_DIRECTION_IN) {
speer = ssrc;
sa_peer = sa_src;
} else {
speer = sdst;
sa_peer = sa_dst;
}
sa_peer.sadb_address_exttype = SADB_EXT_ADDRESS_DST;
sa_peer.sadb_address_len =
(sizeof(sa_peer) + ROUNDUP(speer.ss_len)) / 8;
/* for addflow we also use src/dst as the flow destination */
sa_src.sadb_address_exttype = SADB_X_EXT_SRC_FLOW;
sa_dst.sadb_address_exttype = SADB_X_EXT_DST_FLOW;
bzero(&smask, sizeof(smask));
switch (src->aid) {
case AID_INET:
smask.ss_len = sizeof(struct sockaddr_in);
smask.ss_family = AF_INET;
memset(&((struct sockaddr_in *)&smask)->sin_addr,
0xff, 32/8);
if (sport) {
((struct sockaddr_in *)&ssrc)->sin_port =
htons(sport);
((struct sockaddr_in *)&smask)->sin_port =
htons(0xffff);
}
break;
case AID_INET6:
smask.ss_len = sizeof(struct sockaddr_in6);
smask.ss_family = AF_INET6;
memset(&((struct sockaddr_in6 *)&smask)->sin6_addr,
0xff, 128/8);
if (sport) {
((struct sockaddr_in6 *)&ssrc)->sin6_port =
htons(sport);
((struct sockaddr_in6 *)&smask)->sin6_port =
htons(0xffff);
}
break;
}
bzero(&dmask, sizeof(dmask));
switch (dst->aid) {
case AID_INET:
dmask.ss_len = sizeof(struct sockaddr_in);
dmask.ss_family = AF_INET;
memset(&((struct sockaddr_in *)&dmask)->sin_addr,
0xff, 32/8);
if (dport) {
((struct sockaddr_in *)&sdst)->sin_port =
htons(dport);
((struct sockaddr_in *)&dmask)->sin_port =
htons(0xffff);
}
break;
case AID_INET6:
dmask.ss_len = sizeof(struct sockaddr_in6);
dmask.ss_family = AF_INET6;
memset(&((struct sockaddr_in6 *)&dmask)->sin6_addr,
0xff, 128/8);
if (dport) {
((struct sockaddr_in6 *)&sdst)->sin6_port =
htons(dport);
((struct sockaddr_in6 *)&dmask)->sin6_port =
htons(0xffff);
}
break;
}
bzero(&sa_smask, sizeof(sa_smask));
sa_smask.sadb_address_exttype = SADB_X_EXT_SRC_MASK;
sa_smask.sadb_address_len =
(sizeof(sa_smask) + ROUNDUP(smask.ss_len)) / 8;
bzero(&sa_dmask, sizeof(sa_dmask));
sa_dmask.sadb_address_exttype = SADB_X_EXT_DST_MASK;
sa_dmask.sadb_address_len =
(sizeof(sa_dmask) + ROUNDUP(dmask.ss_len)) / 8;
break;
}
iov_cnt = 0;
/* msghdr */
iov[iov_cnt].iov_base = &smsg;
iov[iov_cnt].iov_len = sizeof(smsg);
iov_cnt++;
switch (mtype) {
case SADB_ADD:
case SADB_UPDATE:
case SADB_DELETE:
/* SA hdr */
iov[iov_cnt].iov_base = &sa;
iov[iov_cnt].iov_len = sizeof(sa);
smsg.sadb_msg_len += sa.sadb_sa_len;
iov_cnt++;
break;
case SADB_GETSPI:
/* SPI range */
iov[iov_cnt].iov_base = &sa_spirange;
iov[iov_cnt].iov_len = sizeof(sa_spirange);
smsg.sadb_msg_len += sa_spirange.sadb_spirange_len;
iov_cnt++;
break;
case SADB_X_ADDFLOW:
/* sa_peer always points to the remote machine */
iov[iov_cnt].iov_base = &sa_peer;
iov[iov_cnt].iov_len = sizeof(sa_peer);
iov_cnt++;
iov[iov_cnt].iov_base = &speer;
iov[iov_cnt].iov_len = ROUNDUP(speer.ss_len);
smsg.sadb_msg_len += sa_peer.sadb_address_len;
iov_cnt++;
/* FALLTHROUGH */
case SADB_X_DELFLOW:
/* add flow type */
iov[iov_cnt].iov_base = &sa_flowtype;
iov[iov_cnt].iov_len = sizeof(sa_flowtype);
smsg.sadb_msg_len += sa_flowtype.sadb_protocol_len;
iov_cnt++;
/* add protocol */
iov[iov_cnt].iov_base = &sa_protocol;
iov[iov_cnt].iov_len = sizeof(sa_protocol);
smsg.sadb_msg_len += sa_protocol.sadb_protocol_len;
iov_cnt++;
/* add flow masks */
iov[iov_cnt].iov_base = &sa_smask;
iov[iov_cnt].iov_len = sizeof(sa_smask);
iov_cnt++;
iov[iov_cnt].iov_base = &smask;
iov[iov_cnt].iov_len = ROUNDUP(smask.ss_len);
smsg.sadb_msg_len += sa_smask.sadb_address_len;
iov_cnt++;
iov[iov_cnt].iov_base = &sa_dmask;
iov[iov_cnt].iov_len = sizeof(sa_dmask);
iov_cnt++;
iov[iov_cnt].iov_base = &dmask;
iov[iov_cnt].iov_len = ROUNDUP(dmask.ss_len);
smsg.sadb_msg_len += sa_dmask.sadb_address_len;
iov_cnt++;
break;
}
/* dest addr */
iov[iov_cnt].iov_base = &sa_dst;
iov[iov_cnt].iov_len = sizeof(sa_dst);
iov_cnt++;
iov[iov_cnt].iov_base = &sdst;
iov[iov_cnt].iov_len = ROUNDUP(sdst.ss_len);
smsg.sadb_msg_len += sa_dst.sadb_address_len;
iov_cnt++;
/* src addr */
iov[iov_cnt].iov_base = &sa_src;
iov[iov_cnt].iov_len = sizeof(sa_src);
iov_cnt++;
iov[iov_cnt].iov_base = &ssrc;
iov[iov_cnt].iov_len = ROUNDUP(ssrc.ss_len);
smsg.sadb_msg_len += sa_src.sadb_address_len;
iov_cnt++;
switch (mtype) {
case SADB_ADD:
case SADB_UPDATE:
if (alen) {
/* auth key */
iov[iov_cnt].iov_base = &sa_akey;
iov[iov_cnt].iov_len = sizeof(sa_akey);
iov_cnt++;
iov[iov_cnt].iov_base = akey;
iov[iov_cnt].iov_len = ((alen + 7) / 8) * 8;
smsg.sadb_msg_len += sa_akey.sadb_key_len;
iov_cnt++;
}
if (elen) {
/* encryption key */
iov[iov_cnt].iov_base = &sa_ekey;
iov[iov_cnt].iov_len = sizeof(sa_ekey);
iov_cnt++;
iov[iov_cnt].iov_base = ekey;
iov[iov_cnt].iov_len = ((elen + 7) / 8) * 8;
smsg.sadb_msg_len += sa_ekey.sadb_key_len;
iov_cnt++;
}
break;
}
len = smsg.sadb_msg_len * 8;
do {
n = writev(sd, iov, iov_cnt);
} while (n == -1 && (errno == EAGAIN || errno == EINTR));
if (n == -1) {
log_warn("writev (%d/%d)", iov_cnt, len);
return (-1);
}
return (0);
}
int
pfkey_read(int sd, struct sadb_msg *h)
{
struct sadb_msg hdr;
if (recv(sd, &hdr, sizeof(hdr), MSG_PEEK) != sizeof(hdr)) {
log_warn("pfkey peek");
return (-1);
}
/* XXX: Only one message can be outstanding. */
if (hdr.sadb_msg_seq == sadb_msg_seq &&
hdr.sadb_msg_pid == pid) {
if (h)
bcopy(&hdr, h, sizeof(hdr));
return (0);
}
/* not ours, discard */
if (read(sd, &hdr, sizeof(hdr)) == -1) {
log_warn("pfkey read");
return (-1);
}
return (1);
}
int
pfkey_reply(int sd, u_int32_t *spip)
{
struct sadb_msg hdr, *msg;
struct sadb_ext *ext;
struct sadb_sa *sa;
u_int8_t *data;
ssize_t len;
int rv;
do {
rv = pfkey_read(sd, &hdr);
if (rv == -1)
return (-1);
} while (rv);
if (hdr.sadb_msg_errno != 0) {
errno = hdr.sadb_msg_errno;
if (errno == ESRCH)
return (0);
else {
log_warn("pfkey");
return (-1);
}
}
len = hdr.sadb_msg_len * PFKEY2_CHUNK;
if ((data = malloc(len)) == NULL) {
log_warn("pfkey malloc");
return (-1);
}
if (read(sd, data, len) != len) {
log_warn("pfkey read");
bzero(data, len);
free(data);
return (-1);
}
if (hdr.sadb_msg_type == SADB_GETSPI) {
if (spip == NULL) {
bzero(data, len);
free(data);
return (0);
}
msg = (struct sadb_msg *)data;
for (ext = (struct sadb_ext *)(msg + 1);
(size_t)((u_int8_t *)ext - (u_int8_t *)msg) <
msg->sadb_msg_len * PFKEY2_CHUNK;
ext = (struct sadb_ext *)((u_int8_t *)ext +
ext->sadb_ext_len * PFKEY2_CHUNK)) {
if (ext->sadb_ext_type == SADB_EXT_SA) {
sa = (struct sadb_sa *) ext;
*spip = sa->sadb_sa_spi;
break;
}
}
}
bzero(data, len);
free(data);
return (0);
}
int
pfkey_sa_add(struct bgpd_addr *src, struct bgpd_addr *dst, u_int8_t keylen,
char *key, u_int32_t *spi)
{
if (pfkey_send(fd, SADB_X_SATYPE_TCPSIGNATURE, SADB_GETSPI, 0,
src, dst, 0, 0, 0, NULL, 0, 0, NULL, 0, 0) < 0)
return (-1);
if (pfkey_reply(fd, spi) < 0)
return (-1);
if (pfkey_send(fd, SADB_X_SATYPE_TCPSIGNATURE, SADB_UPDATE, 0,
src, dst, *spi, 0, keylen, key, 0, 0, NULL, 0, 0) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
return (0);
}
int
pfkey_sa_remove(struct bgpd_addr *src, struct bgpd_addr *dst, u_int32_t *spi)
{
if (pfkey_send(fd, SADB_X_SATYPE_TCPSIGNATURE, SADB_DELETE, 0,
src, dst, *spi, 0, 0, NULL, 0, 0, NULL, 0, 0) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
*spi = 0;
return (0);
}
int
pfkey_md5sig_establish(struct peer *p)
{
sleep(1);
if (!p->auth.spi_out)
if (pfkey_sa_add(&p->auth.local_addr, &p->conf.remote_addr,
p->conf.auth.md5key_len, p->conf.auth.md5key,
&p->auth.spi_out) == -1)
return (-1);
if (!p->auth.spi_in)
if (pfkey_sa_add(&p->conf.remote_addr, &p->auth.local_addr,
p->conf.auth.md5key_len, p->conf.auth.md5key,
&p->auth.spi_in) == -1)
return (-1);
p->auth.established = 1;
return (0);
}
int
pfkey_md5sig_remove(struct peer *p)
{
if (p->auth.spi_out)
if (pfkey_sa_remove(&p->auth.local_addr, &p->conf.remote_addr,
&p->auth.spi_out) == -1)
return (-1);
if (p->auth.spi_in)
if (pfkey_sa_remove(&p->conf.remote_addr, &p->auth.local_addr,
&p->auth.spi_in) == -1)
return (-1);
p->auth.established = 0;
return (0);
}
int
pfkey_ipsec_establish(struct peer *p)
{
uint8_t satype = SADB_SATYPE_ESP;
switch (p->auth.method) {
case AUTH_IPSEC_IKE_ESP:
satype = SADB_SATYPE_ESP;
break;
case AUTH_IPSEC_IKE_AH:
satype = SADB_SATYPE_AH;
break;
case AUTH_IPSEC_MANUAL_ESP:
case AUTH_IPSEC_MANUAL_AH:
satype = p->auth.method == AUTH_IPSEC_MANUAL_ESP ?
SADB_SATYPE_ESP : SADB_SATYPE_AH;
if (pfkey_send(fd, satype, SADB_ADD, 0,
&p->auth.local_addr, &p->conf.remote_addr,
p->auth.spi_out,
p->conf.auth.auth_alg_out,
p->conf.auth.auth_keylen_out,
p->conf.auth.auth_key_out,
p->conf.auth.enc_alg_out,
p->conf.auth.enc_keylen_out,
p->conf.auth.enc_key_out,
0, 0) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
if (pfkey_send(fd, satype, SADB_ADD, 0,
&p->conf.remote_addr, &p->auth.local_addr,
p->auth.spi_in,
p->conf.auth.auth_alg_in,
p->conf.auth.auth_keylen_in,
p->conf.auth.auth_key_in,
p->conf.auth.enc_alg_in,
p->conf.auth.enc_keylen_in,
p->conf.auth.enc_key_in,
0, 0) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
break;
default:
return (-1);
break;
}
if (pfkey_flow(fd, satype, SADB_X_ADDFLOW, IPSP_DIRECTION_OUT,
&p->auth.local_addr, &p->conf.remote_addr, 0, BGP_PORT) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
if (pfkey_flow(fd, satype, SADB_X_ADDFLOW, IPSP_DIRECTION_OUT,
&p->auth.local_addr, &p->conf.remote_addr, BGP_PORT, 0) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
if (pfkey_flow(fd, satype, SADB_X_ADDFLOW, IPSP_DIRECTION_IN,
&p->conf.remote_addr, &p->auth.local_addr, 0, BGP_PORT) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
if (pfkey_flow(fd, satype, SADB_X_ADDFLOW, IPSP_DIRECTION_IN,
&p->conf.remote_addr, &p->auth.local_addr, BGP_PORT, 0) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
p->auth.established = 1;
return (0);
}
int
pfkey_ipsec_remove(struct peer *p)
{
uint8_t satype;
switch (p->auth.method) {
case AUTH_IPSEC_IKE_ESP:
satype = SADB_SATYPE_ESP;
break;
case AUTH_IPSEC_IKE_AH:
satype = SADB_SATYPE_AH;
break;
case AUTH_IPSEC_MANUAL_ESP:
case AUTH_IPSEC_MANUAL_AH:
satype = p->auth.method == AUTH_IPSEC_MANUAL_ESP ?
SADB_SATYPE_ESP : SADB_SATYPE_AH;
if (pfkey_send(fd, satype, SADB_DELETE, 0,
&p->auth.local_addr, &p->conf.remote_addr,
p->auth.spi_out, 0, 0, NULL, 0, 0, NULL,
0, 0) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
if (pfkey_send(fd, satype, SADB_DELETE, 0,
&p->conf.remote_addr, &p->auth.local_addr,
p->auth.spi_in, 0, 0, NULL, 0, 0, NULL,
0, 0) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
break;
default:
return (-1);
break;
}
if (pfkey_flow(fd, satype, SADB_X_DELFLOW, IPSP_DIRECTION_OUT,
&p->auth.local_addr, &p->conf.remote_addr, 0, BGP_PORT) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
if (pfkey_flow(fd, satype, SADB_X_DELFLOW, IPSP_DIRECTION_OUT,
&p->auth.local_addr, &p->conf.remote_addr, BGP_PORT, 0) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
if (pfkey_flow(fd, satype, SADB_X_DELFLOW, IPSP_DIRECTION_IN,
&p->conf.remote_addr, &p->auth.local_addr, 0, BGP_PORT) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
if (pfkey_flow(fd, satype, SADB_X_DELFLOW, IPSP_DIRECTION_IN,
&p->conf.remote_addr, &p->auth.local_addr, BGP_PORT, 0) < 0)
return (-1);
if (pfkey_reply(fd, NULL) < 0)
return (-1);
p->auth.established = 0;
return (0);
}
int
pfkey_establish(struct peer *p)
{
/*
* make sure we keep copies of everything we need to
* remove SAs and flows later again, even if the
* info in p->conf changed due to reload.
* We need: SPIs, method, local_addr, remote_addr.
* remote_addr cannot change, so no copy.
*/
memcpy(&p->auth.local_addr, &p->conf.local_addr,
sizeof(p->auth.local_addr));
p->auth.method = p->conf.auth.method;
p->auth.spi_in = p->conf.auth.spi_in;
p->auth.spi_out = p->conf.auth.spi_out;
if (!p->auth.method)
return (0);
else if (p->auth.method == AUTH_MD5SIG)
return (pfkey_md5sig_establish(p));
else
return (pfkey_ipsec_establish(p));
}
int
pfkey_remove(struct peer *p)
{
if (!p->auth.established)
return (0);
else if (p->auth.method == AUTH_MD5SIG)
return (pfkey_md5sig_remove(p));
else
return (pfkey_ipsec_remove(p));
}
int
pfkey_init(struct bgpd_sysdep *sysdep)
{
if ((fd = socket(PF_KEY, SOCK_RAW, PF_KEY_V2)) == -1) {
if (errno == EPROTONOSUPPORT) {
log_warnx("PF_KEY not available, disabling ipsec");
sysdep->no_pfkey = 1;
return (-1);
} else
fatal("pfkey setup failed");
}
return (fd);
}
| 26.325301 | 77 | 0.668192 |
a60d08368cdb3d8c25a71db9343fd544f1d6300e | 1,072 | c | C | gtk/src/rbgtkgamma.c | pkorenev/ruby-gnome2 | 08011d8535529a3866f877817f29361b1b0703d7 | [
"Ruby"
] | 2 | 2016-05-08T20:57:12.000Z | 2017-07-28T21:00:42.000Z | gtk/src/rbgtkgamma.c | pkorenev/ruby-gnome2 | 08011d8535529a3866f877817f29361b1b0703d7 | [
"Ruby"
] | null | null | null | gtk/src/rbgtkgamma.c | pkorenev/ruby-gnome2 | 08011d8535529a3866f877817f29361b1b0703d7 | [
"Ruby"
] | 2 | 2016-07-23T09:53:08.000Z | 2021-07-13T07:21:05.000Z | /* -*- c-file-style: "ruby"; indent-tabs-mode: nil -*- */
/************************************************
rbgtkgamma.c -
$Author: mutoh $
$Date: 2003/02/01 16:46:23 $
Copyright (C) 2002,2003 Ruby-GNOME2 Project Team
Copyright (C) 1998-2000 Yukihiro Matsumoto,
Daisuke Kanda,
Hiroshi Igarashi
************************************************/
#include "global.h"
static VALUE
gamma_initialize(self)
VALUE self;
{
RBGTK_INITIALIZE(self, gtk_gamma_curve_new());
return Qnil;
}
static VALUE
gamma_gamma(self)
VALUE self;
{
return rb_float_new(GTK_GAMMA_CURVE(RVAL2GOBJ(self))->gamma);
}
static VALUE
gamma_curve(self)
VALUE self;
{
return GOBJ2RVAL(GTK_GAMMA_CURVE(RVAL2GOBJ(self))->curve);
}
void
Init_gtk_gamma_curve()
{
VALUE gGamma = G_DEF_CLASS(GTK_TYPE_GAMMA_CURVE, "GammaCurve", mGtk);
rb_define_method(gGamma, "initialize", gamma_initialize, 0);
rb_define_method(gGamma, "gamma", gamma_gamma, 0);
rb_define_method(gGamma, "curve", gamma_curve, 0);
}
| 22.333333 | 73 | 0.607276 |
2c260d7342e72907b9c89615f770f1f3ed693570 | 2,270 | c | C | cmd/sh/ctype.c | JetStarBlues/xv6-freebsd-Notes | f30bb11229d3d09babd19676d491b3fc986435a0 | [
"BSD-4-Clause-UC"
] | 40 | 2016-08-02T18:43:30.000Z | 2021-12-27T08:24:05.000Z | cmd/sh/ctype.c | JetStarBlues/xv6-freebsd-Notes | f30bb11229d3d09babd19676d491b3fc986435a0 | [
"BSD-4-Clause-UC"
] | 4 | 2017-01-31T07:33:23.000Z | 2021-04-13T08:46:31.000Z | cmd/sh/ctype.c | JetStarBlues/xv6-freebsd-Notes | f30bb11229d3d09babd19676d491b3fc986435a0 | [
"BSD-4-Clause-UC"
] | 13 | 2017-04-22T23:16:05.000Z | 2022-03-25T12:47:18.000Z | /*
* UNIX shell
*
* S. R. Bourne
* Bell Telephone Laboratories
*/
#include "defs.h"
/* changed _HAT to 0; In original sh '^' == '|' ; Nikola Vladov */
#ifdef WANT_HAT_AS_PIPE
#define X_HAT _HAT
#else
#define X_HAT 0
#endif
char _ctype1[] = {
/* 000 001 002 003 004 005 006 007 */
_EOF, 0, 0, 0, 0, 0, 0, 0,
/* bs ht nl vt np cr so si */
0, _TAB, _EOR, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
/* sp ! " # $ % & ' */
_SPC, 0, _DQU, 0, _DOL1, 0, _AMP, 0,
/* ( ) * + , - . / */
_BRA, _KET, 0, 0, 0, 0, 0, 0,
/* 0 1 2 3 4 5 6 7 */
0, 0, 0, 0, 0, 0, 0, 0,
/* 8 9 : ; < = > ? */
0, 0, 0, _SEM, _LT, 0, _GT, 0,
/* @ A B C D E F G */
0, 0, 0, 0, 0, 0, 0, 0,
/* H I J K L M N O */
0, 0, 0, 0, 0, 0, 0, 0,
/* P Q R S T U V W */
0, 0, 0, 0, 0, 0, 0, 0,
/* X Y Z [ \ ] ^ _ */
0, 0, 0, 0, _BSL, 0, X_HAT, 0,
/* ` a b c d e f g */
_LQU, 0, 0, 0, 0, 0, 0, 0,
/* h i j k l m n o */
0, 0, 0, 0, 0, 0, 0, 0,
/* p q r s t u v w */
0, 0, 0, 0, 0, 0, 0, 0,
/* x y z { | } ~ del */
0, 0, 0, 0, _BAR, 0, 0, 0
};
char _ctype2[] = {
/* 000 001 002 003 004 005 006 007 */
0, 0, 0, 0, 0, 0, 0, 0,
/* bs ht nl vt np cr so si */
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
/* sp ! " # $ % & ' */
0, _PCS, 0, _NUM, _DOL2, 0, 0, 0,
/* ( ) * + , - . / */
0, 0, _AST, _PLS, 0, _MIN, 0, 0,
/* 0 1 2 3 4 5 6 7 */
_DIG, _DIG, _DIG, _DIG, _DIG, _DIG, _DIG, _DIG,
/* 8 9 : ; < = > ? */
_DIG, _DIG, 0, 0, 0, _EQ, 0, _QU,
/* @ A B C D E F G */
_AT, _UPC, _UPC, _UPC, _UPC, _UPC, _UPC, _UPC,
/* H I J K L M N O */
_UPC, _UPC, _UPC, _UPC, _UPC, _UPC, _UPC, _UPC,
/* P Q R S T U V W */
_UPC, _UPC, _UPC, _UPC, _UPC, _UPC, _UPC, _UPC,
/* X Y Z [ \ ] ^ _ */
_UPC, _UPC, _UPC, _SQB, 0, 0, 0, _UPC,
/* ` a b c d e f g */
0, _LPC, _LPC, _LPC, _LPC, _LPC, _LPC, _LPC,
/* h i j k l m n o */
_LPC, _LPC, _LPC, _LPC, _LPC, _LPC, _LPC, _LPC,
/* p q r s t u v w */
_LPC, _LPC, _LPC, _LPC, _LPC, _LPC, _LPC, _LPC,
/* x y z { | } ~ del */
_LPC, _LPC, _LPC, _CBR, 0, _CKT, 0, 0
};
| 20.267857 | 67 | 0.402643 |
0868dff06288687ce4db6d445b708ec788e09516 | 2,665 | h | C | Classes/BombKitReleaseModel.h | darkcl/BombKit | 395d552382ff2a7db28337da4e1d72348a0950fb | [
"MIT"
] | null | null | null | Classes/BombKitReleaseModel.h | darkcl/BombKit | 395d552382ff2a7db28337da4e1d72348a0950fb | [
"MIT"
] | null | null | null | Classes/BombKitReleaseModel.h | darkcl/BombKit | 395d552382ff2a7db28337da4e1d72348a0950fb | [
"MIT"
] | null | null | null | //
// BombKitReleaseModel.h
// BombKit
//
// Created by Yeung Yiu Hung on 14/4/2016.
// Copyright © 2016 darkcl. All rights reserved.
//
#import "BombBaseModel.h"
#import "BombKitConstant.h"
@interface BombKitReleaseModel : BombBaseModel
/*
api_detail_url URL pointing to the release detail resource.
date_added Date the release was added to Giant Bomb.
date_last_updated Date the release was last updated on Giant Bomb.
deck Brief summary of the release.
description Description of the release.
developers Companies who developed the release.
expected_release_day Expected day the release will be released. The month is represented numerically. Combine with 'expected_release_month', 'expected_release_year' and 'expected_release_quarter' for Giant Bomb's best guess release date of the release. These fields will be empty if the 'release_date' field is set.
expected_release_month Expected month the release will be released. The month is represented numerically. Combine with 'expected_release_day', expected_release_quarter' and 'expected_release_year' for Giant Bomb's best guess release date of the release. These fields will be empty if the 'release_date' field is set.
expected_release_quarter Expected quarter release will be released. The quarter is represented numerically, where 1 = Q1, 2 = Q2, 3 = Q3, and 4 = Q4. Combine with 'expected_release_day', 'expected_release_month' and 'expected_release_year' for Giant Bomb's best guess release date of the release. These fields will be empty if the 'release_date' field is set.
expected_release_year Expected year release will be released. Combine with 'expected_release_day', 'expected_release_month' and 'expected_release_quarter' for Giant Bomb's best guess release date of the game. These fields will be empty if the 'release_date' field is set.
game Game the release is for.
game_rating Rating of the release.
id Unique ID of the release.
image Main image of the release.
images List of images associated to the release.
maximum_players Maximum players
minimum_players Minimum players
multiplayer_features Multiplayer features
name Name of the release.
platform Platform of the release.
product_code_type The type of product code the release has (ex. UPC/A, ISBN-10, EAN-13).
product_code_value The release's product code.
publishers Companies who published the release.
region Region the release is responsible for.
release_date Date of the release.
resolutions Resolutions available
singleplayer_features Singleplayer features
sound_systems Sound systems
site_detail_url URL pointing to the release on Giant Bomb.
widescreen_support Widescreen support
*/
@end
| 55.520833 | 360 | 0.806004 |
83a71e7b3cf49466d6a9257e22e15f234fc90a65 | 7,443 | h | C | contrib/tcpdump/sctpHeader.h | TrustedBSD/sebsd | fd5de6f587183087cf930779701d5713e8ca64cc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 4 | 2017-04-06T21:39:15.000Z | 2019-10-09T17:34:14.000Z | contrib/tcpdump/sctpHeader.h | TrustedBSD/sebsd | fd5de6f587183087cf930779701d5713e8ca64cc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | contrib/tcpdump/sctpHeader.h | TrustedBSD/sebsd | fd5de6f587183087cf930779701d5713e8ca64cc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-01-04T06:36:39.000Z | 2020-01-04T06:36:39.000Z | /* @(#) $Header$ (LBL) */
/* SCTP reference Implementation Copyright (C) 1999 Cisco And Motorola
*
* 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.
*
* 4. Neither the name of Cisco nor of Motorola may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
*
* This file is part of the SCTP reference Implementation
*
*
* Please send any bug reports or fixes you make to one of the following email
* addresses:
*
* rstewar1@email.mot.com
* kmorneau@cisco.com
* qxie1@email.mot.com
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorperated into the next SCTP release.
*/
#ifndef __sctpHeader_h__
#define __sctpHeader_h__
#include <sctpConstants.h>
#ifdef __cplusplus
extern "C" {
#endif
/* the sctp common header */
#ifdef TRU64
#define _64BITS 1
#endif
struct sctpHeader{
u_int16_t source;
u_int16_t destination;
u_int32_t verificationTag;
u_int32_t adler32;
};
/* various descriptor parsers */
struct sctpChunkDesc{
u_int8_t chunkID;
u_int8_t chunkFlg;
u_int16_t chunkLength;
};
struct sctpParamDesc{
u_int16_t paramType;
u_int16_t paramLength;
};
struct sctpRelChunkDesc{
struct sctpChunkDesc chk;
u_int32_t serialNumber;
};
struct sctpVendorSpecificParam {
struct sctpParamDesc p; /* type must be 0xfffe */
u_int32_t vendorId; /* vendor ID from RFC 1700 */
u_int16_t vendorSpecificType;
u_int16_t vendorSpecificLen;
};
/* Structures for the control parts */
/* Sctp association init request/ack */
/* this is used for init ack, too */
struct sctpInitiation{
u_int32_t initTag; /* tag of mine */
u_int32_t rcvWindowCredit; /* rwnd */
u_int16_t NumPreopenStreams; /* OS */
u_int16_t MaxInboundStreams; /* MIS */
u_int32_t initialTSN;
/* optional param's follow in sctpParamDesc form */
};
struct sctpV4IpAddress{
struct sctpParamDesc p; /* type is set to SCTP_IPV4_PARAM_TYPE, len=10 */
u_int32_t ipAddress;
};
struct sctpV6IpAddress{
struct sctpParamDesc p; /* type is set to SCTP_IPV6_PARAM_TYPE, len=22 */
u_int8_t ipAddress[16];
};
struct sctpDNSName{
struct sctpParamDesc param;
u_int8_t name[1];
};
struct sctpCookiePreserve{
struct sctpParamDesc p; /* type is set to SCTP_COOKIE_PRESERVE, len=8 */
u_int32_t extraTime;
};
struct sctpTimeStamp{
u_int32_t ts_sec;
u_int32_t ts_usec;
};
/* wire structure of my cookie */
struct cookieMessage{
u_int32_t TieTag_curTag; /* copied from assoc if present */
u_int32_t TieTag_hisTag; /* copied from assoc if present */
int32_t cookieLife; /* life I will award this cookie */
struct sctpTimeStamp timeEnteringState; /* the time I built cookie */
struct sctpInitiation initAckISent; /* the INIT-ACK that I sent to my peer */
u_int32_t addressWhereISent[4]; /* I make this 4 ints so I get 128bits for future */
int32_t addrtype; /* address type */
u_int16_t locScope; /* V6 local scope flag */
u_int16_t siteScope; /* V6 site scope flag */
/* at the end is tacked on the INIT chunk sent in
* its entirety and of course our
* signature.
*/
};
/* this guy is for use when
* I have a initiate message gloming the
* things together.
*/
struct sctpUnifiedInit{
struct sctpChunkDesc uh;
struct sctpInitiation initm;
};
struct sctpSendableInit{
struct sctpHeader mh;
struct sctpUnifiedInit msg;
};
/* Selective Acknowledgement
* has the following structure with
* a optional ammount of trailing int's
* on the last part (based on the numberOfDesc
* field).
*/
struct sctpSelectiveAck{
u_int32_t highestConseqTSN;
u_int32_t updatedRwnd;
u_int16_t numberOfdesc;
u_int16_t numDupTsns;
};
struct sctpSelectiveFrag{
u_int16_t fragmentStart;
u_int16_t fragmentEnd;
};
struct sctpUnifiedSack{
struct sctpChunkDesc uh;
struct sctpSelectiveAck sack;
};
/* for both RTT request/response the
* following is sent
*/
struct sctpHBrequest {
u_int32_t time_value_1;
u_int32_t time_value_2;
};
/* here is what I read and respond with to. */
struct sctpHBunified{
struct sctpChunkDesc hdr;
struct sctpParamDesc hb;
};
/* here is what I send */
struct sctpHBsender{
struct sctpChunkDesc hdr;
struct sctpParamDesc hb;
struct sctpHBrequest rtt;
int8_t addrFmt[SCTP_ADDRMAX];
u_int16_t userreq;
};
/* for the abort and shutdown ACK
* we must carry the init tag in the common header. Just the
* common header is all that is needed with a chunk descriptor.
*/
struct sctpUnifiedAbort{
struct sctpChunkDesc uh;
};
struct sctpUnifiedAbortLight{
struct sctpHeader mh;
struct sctpChunkDesc uh;
};
struct sctpUnifiedAbortHeavy{
struct sctpHeader mh;
struct sctpChunkDesc uh;
u_int16_t causeCode;
u_int16_t causeLen;
};
/* For the graceful shutdown we must carry
* the tag (in common header) and the highest consequitive acking value
*/
struct sctpShutdown {
u_int32_t TSN_Seen;
};
struct sctpUnifiedShutdown{
struct sctpChunkDesc uh;
struct sctpShutdown shut;
};
/* in the unified message we add the trailing
* stream id since it is the only message
* that is defined as a operation error.
*/
struct sctpOpErrorCause{
u_int16_t cause;
u_int16_t causeLen;
};
struct sctpUnifiedOpError{
struct sctpChunkDesc uh;
struct sctpOpErrorCause c;
};
struct sctpUnifiedStreamError{
struct sctpHeader mh;
struct sctpChunkDesc uh;
struct sctpOpErrorCause c;
u_int16_t strmNum;
u_int16_t reserved;
};
struct staleCookieMsg{
struct sctpHeader mh;
struct sctpChunkDesc uh;
struct sctpOpErrorCause c;
u_int32_t moretime;
};
/* the following is used in all sends
* where nothing is needed except the
* chunk/type i.e. shutdownAck Abort */
struct sctpUnifiedSingleMsg{
struct sctpHeader mh;
struct sctpChunkDesc uh;
};
struct sctpDataPart{
u_int32_t TSN;
u_int16_t streamId;
u_int16_t sequence;
u_int32_t payloadtype;
};
struct sctpUnifiedDatagram{
struct sctpChunkDesc uh;
struct sctpDataPart dp;
};
struct sctpECN_echo{
struct sctpChunkDesc uh;
u_int32_t Lowest_TSN;
};
struct sctpCWR{
struct sctpChunkDesc uh;
u_int32_t TSN_reduced_at;
};
#ifdef __cplusplus
}
#endif
#endif
| 22.972222 | 86 | 0.741502 |
036413673918e4672a0340954809cd12a87e58e3 | 66,775 | h | C | adrunio/BGLib_stub_slave/BGLib.h | mrchaarlie/proxima | 3012c35058e461ef058b1f6da1e862127a43d58e | [
"Apache-2.0"
] | null | null | null | adrunio/BGLib_stub_slave/BGLib.h | mrchaarlie/proxima | 3012c35058e461ef058b1f6da1e862127a43d58e | [
"Apache-2.0"
] | null | null | null | adrunio/BGLib_stub_slave/BGLib.h | mrchaarlie/proxima | 3012c35058e461ef058b1f6da1e862127a43d58e | [
"Apache-2.0"
] | null | null | null | // Arduino BGLib code library header file
#ifndef __BGLIB_H__
#define __BGLIB_H__
#include <Arduino.h>
#include "BGLibConfig.h"
// uncomment this line for Serial.println() debug output
//#define DEBUG
#define BGLIB_SYSTEM_ENDPOINT_API 0
#define BGLIB_SYSTEM_ENDPOINT_TEST 1
#define BGLIB_SYSTEM_ENDPOINT_SCRIPT 2
#define BGLIB_SYSTEM_ENDPOINT_USB 3
#define BGLIB_SYSTEM_ENDPOINT_UART0 4
#define BGLIB_SYSTEM_ENDPOINT_UART1 5
#define BGLIB_ATTRIBUTES_ATTRIBUTE_CHANGE_REASON_WRITE_REQUEST 0
#define BGLIB_ATTRIBUTES_ATTRIBUTE_CHANGE_REASON_WRITE_COMMAND 1
#define BGLIB_ATTRIBUTES_ATTRIBUTE_CHANGE_REASON_WRITE_REQUEST_USER 2
#define BGLIB_ATTRIBUTES_ATTRIBUTE_STATUS_FLAG_NOTIFY 1
#define BGLIB_ATTRIBUTES_ATTRIBUTE_STATUS_FLAG_INDICATE 2
#define BGLIB_CONNECTION_CONNECTED 1
#define BGLIB_CONNECTION_ENCRYPTED 2
#define BGLIB_CONNECTION_COMPLETED 4
#define BGLIB_CONNECTION_PARAMETERS_CHANGE 8
#define BGLIB_ATTCLIENT_ATTRIBUTE_VALUE_TYPE_READ 0
#define BGLIB_ATTCLIENT_ATTRIBUTE_VALUE_TYPE_NOTIFY 1
#define BGLIB_ATTCLIENT_ATTRIBUTE_VALUE_TYPE_INDICATE 2
#define BGLIB_ATTCLIENT_ATTRIBUTE_VALUE_TYPE_READ_BY_TYPE 3
#define BGLIB_ATTCLIENT_ATTRIBUTE_VALUE_TYPE_READ_BLOB 4
#define BGLIB_ATTCLIENT_ATTRIBUTE_VALUE_TYPE_INDICATE_RSP_REQ 5
#define BGLIB_SM_BONDING_KEY_LTK 0x01
#define BGLIB_SM_BONDING_KEY_ADDR_PUBLIC 0x02
#define BGLIB_SM_BONDING_KEY_ADDR_STATIC 0x04
#define BGLIB_SM_BONDING_KEY_IRK 0x08
#define BGLIB_SM_BONDING_KEY_EDIVRAND 0x10
#define BGLIB_SM_BONDING_KEY_CSRK 0x20
#define BGLIB_SM_BONDING_KEY_MASTERID 0x40
#define BGLIB_SM_IO_CAPABILITY_DISPLAYONLY 0
#define BGLIB_SM_IO_CAPABILITY_DISPLAYYESNO 1
#define BGLIB_SM_IO_CAPABILITY_KEYBOARDONLY 2
#define BGLIB_SM_IO_CAPABILITY_NOINPUTNOOUTPUT 3
#define BGLIB_SM_IO_CAPABILITY_KEYBOARDDISPLAY 4
#define BGLIB_GAP_ADDRESS_TYPE_PUBLIC 0
#define BGLIB_GAP_ADDRESS_TYPE_RANDOM 1
#define BGLIB_GAP_NON_DISCOVERABLE 0
#define BGLIB_GAP_LIMITED_DISCOVERABLE 1
#define BGLIB_GAP_GENERAL_DISCOVERABLE 2
#define BGLIB_GAP_BROADCAST 3
#define BGLIB_GAP_USER_DATA 4
#define BGLIB_GAP_NON_CONNECTABLE 0
#define BGLIB_GAP_DIRECTED_CONNECTABLE 1
#define BGLIB_GAP_UNDIRECTED_CONNECTABLE 2
#define BGLIB_GAP_SCANNABLE_CONNECTABLE 3
#define BGLIB_GAP_DISCOVER_LIMITED 0
#define BGLIB_GAP_DISCOVER_GENERIC 1
#define BGLIB_GAP_DISCOVER_OBSERVATION 2
#define BGLIB_GAP_AD_TYPE_NONE 0
#define BGLIB_GAP_AD_TYPE_FLAGS 1
#define BGLIB_GAP_AD_TYPE_SERVICES_16BIT_MORE 2
#define BGLIB_GAP_AD_TYPE_SERVICES_16BIT_ALL 3
#define BGLIB_GAP_AD_TYPE_SERVICES_32BIT_MORE 4
#define BGLIB_GAP_AD_TYPE_SERVICES_32BIT_ALL 5
#define BGLIB_GAP_AD_TYPE_SERVICES_128BIT_MORE 6
#define BGLIB_GAP_AD_TYPE_SERVICES_128BIT_ALL 7
#define BGLIB_GAP_AD_TYPE_LOCALNAME_SHORT 8
#define BGLIB_GAP_AD_TYPE_LOCALNAME_COMPLETE 9
#define BGLIB_GAP_AD_TYPE_TXPOWER 10
#define BGLIB_GAP_ADV_POLICY_ALL 0
#define BGLIB_GAP_ADV_POLICY_WHITELIST_SCAN 1
#define BGLIB_GAP_ADV_POLICY_WHITELIST_CONNECT 2
#define BGLIB_GAP_ADV_POLICY_WHITELIST_ALL 3
#define BGLIB_GAP_SCAN_POLICY_ALL 0
#define BGLIB_GAP_SCAN_POLICY_WHITELIST 1
#define BGLIB_GAP_SCAN_HEADER_ADV_IND 0
#define BGLIB_GAP_SCAN_HEADER_ADV_DIRECT_IND 1
#define BGLIB_GAP_SCAN_HEADER_ADV_NONCONN_IND 2
#define BGLIB_GAP_SCAN_HEADER_SCAN_REQ 3
#define BGLIB_GAP_SCAN_HEADER_SCAN_RSP 4
#define BGLIB_GAP_SCAN_HEADER_CONNECT_REQ 5
#define BGLIB_GAP_SCAN_HEADER_ADV_DISCOVER_IND 6
#define BGLIB_GAP_AD_FLAG_LIMITED_DISCOVERABLE 0x01
#define BGLIB_GAP_AD_FLAG_GENERAL_DISCOVERABLE 0x02
#define BGLIB_GAP_AD_FLAG_BREDR_NOT_SUPPORTED 0x04
#define BGLIB_GAP_AD_FLAG_SIMULTANEOUS_LEBREDR_CTRL 0x10
#define BGLIB_GAP_AD_FLAG_SIMULTANEOUS_LEBREDR_HOST 0x20
#define BGLIB_GAP_AD_FLAG_MASK 0x1f
#define PACKED __attribute__((packed))
#define ALIGNED __attribute__((aligned(0x4)))
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef int16_t int16;
typedef uint32_t uint32;
typedef int8_t int8;
typedef struct bd_addr_t {
uint8 addr[6];
} bd_addr;
typedef bd_addr hwaddr;
typedef struct {
uint8 len;
uint8 data[];
} uint8array;
typedef struct {
uint8 len;
int8 data[];
} string;
struct ble_header {
uint8 type_hilen;
uint8 lolen;
uint8 cls;
uint8 command;
};
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_RESET
struct ble_msg_system_reset_cmd_t {
uint8 boot_in_dfu;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ADDRESS_GET
struct ble_msg_system_address_get_rsp_t {
bd_addr address;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_REG_WRITE
struct ble_msg_system_reg_write_cmd_t {
uint16 address;
uint8 value;
} PACKED;
struct ble_msg_system_reg_write_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_REG_READ
struct ble_msg_system_reg_read_cmd_t {
uint16 address;
} PACKED;
struct ble_msg_system_reg_read_rsp_t {
uint16 address;
uint8 value;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_GET_COUNTERS
struct ble_msg_system_get_counters_rsp_t {
uint8 txok;
uint8 txretry;
uint8 rxok;
uint8 rxfail;
uint8 mbuf;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_GET_CONNECTIONS
struct ble_msg_system_get_connections_rsp_t {
uint8 maxconn;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_READ_MEMORY
struct ble_msg_system_read_memory_cmd_t {
uint32 address;
uint8 length;
} PACKED;
struct ble_msg_system_read_memory_rsp_t {
uint32 address;
uint8array data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_GET_INFO
struct ble_msg_system_get_info_rsp_t {
uint16 major;
uint16 minor;
uint16 patch;
uint16 build;
uint16 ll_version;
uint8 protocol_version;
uint8 hw;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ENDPOINT_TX
struct ble_msg_system_endpoint_tx_cmd_t {
uint8 endpoint;
uint8 data_len;
const uint8 *data_data;
} PACKED;
struct ble_msg_system_endpoint_tx_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_WHITELIST_APPEND
struct ble_msg_system_whitelist_append_cmd_t {
bd_addr address;
uint8 address_type;
} PACKED;
struct ble_msg_system_whitelist_append_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_WHITELIST_REMOVE
struct ble_msg_system_whitelist_remove_cmd_t {
bd_addr address;
uint8 address_type;
} PACKED;
struct ble_msg_system_whitelist_remove_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ENDPOINT_RX
struct ble_msg_system_endpoint_rx_cmd_t {
uint8 endpoint;
uint8 size;
} PACKED;
struct ble_msg_system_endpoint_rx_rsp_t {
uint16 result;
uint8array data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ENDPOINT_SET_WATERMARKS
struct ble_msg_system_endpoint_set_watermarks_cmd_t {
uint8 endpoint;
uint8 rx;
uint8 tx;
} PACKED;
struct ble_msg_system_endpoint_set_watermarks_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_BOOT
struct ble_msg_system_boot_evt_t {
uint16 major;
uint16 minor;
uint16 patch;
uint16 build;
uint16 ll_version;
uint8 protocol_version;
uint8 hw;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_DEBUG
struct ble_msg_system_debug_evt_t {
uint8array data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_ENDPOINT_WATERMARK_RX
struct ble_msg_system_endpoint_watermark_rx_evt_t {
uint8 endpoint;
uint8 data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_ENDPOINT_WATERMARK_TX
struct ble_msg_system_endpoint_watermark_tx_evt_t {
uint8 endpoint;
uint8 data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_SCRIPT_FAILURE
struct ble_msg_system_script_failure_evt_t {
uint16 address;
uint16 reason;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_SAVE
struct ble_msg_flash_ps_save_cmd_t {
uint16 key;
uint8 value_len;
const uint8 *value_data;
} PACKED;
struct ble_msg_flash_ps_save_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_LOAD
struct ble_msg_flash_ps_load_cmd_t {
uint16 key;
} PACKED;
struct ble_msg_flash_ps_load_rsp_t {
uint16 result;
uint8array value;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_ERASE
struct ble_msg_flash_ps_erase_cmd_t {
uint16 key;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_ERASE_PAGE
struct ble_msg_flash_erase_page_cmd_t {
uint8 page;
} PACKED;
struct ble_msg_flash_erase_page_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_WRITE_WORDS
struct ble_msg_flash_write_words_cmd_t {
uint16 address;
uint8 words_len;
const uint8 *words_data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_FLASH_PS_KEY
struct ble_msg_flash_ps_key_evt_t {
uint16 key;
uint8array value;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_WRITE
struct ble_msg_attributes_write_cmd_t {
uint16 handle;
uint8 offset;
uint8 value_len;
const uint8 *value_data;
} PACKED;
struct ble_msg_attributes_write_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_READ
struct ble_msg_attributes_read_cmd_t {
uint16 handle;
uint16 offset;
} PACKED;
struct ble_msg_attributes_read_rsp_t {
uint16 handle;
uint16 offset;
uint16 result;
uint8array value;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_READ_TYPE
struct ble_msg_attributes_read_type_cmd_t {
uint16 handle;
} PACKED;
struct ble_msg_attributes_read_type_rsp_t {
uint16 handle;
uint16 result;
uint8array value;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_USER_READ_RESPONSE
struct ble_msg_attributes_user_read_response_cmd_t {
uint8 connection;
uint8 att_error;
uint8 value_len;
const uint8 *value_data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_USER_WRITE_RESPONSE
struct ble_msg_attributes_user_write_response_cmd_t {
uint8 connection;
uint8 att_error;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTRIBUTES_VALUE
struct ble_msg_attributes_value_evt_t {
uint8 connection;
uint8 reason;
uint16 handle;
uint16 offset;
uint8array value;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTRIBUTES_USER_READ_REQUEST
struct ble_msg_attributes_user_read_request_evt_t {
uint8 connection;
uint16 handle;
uint16 offset;
uint8 maxsize;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTRIBUTES_STATUS
struct ble_msg_attributes_status_evt_t {
uint16 handle;
uint8 flags;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_DISCONNECT
struct ble_msg_connection_disconnect_cmd_t {
uint8 connection;
} PACKED;
struct ble_msg_connection_disconnect_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_GET_RSSI
struct ble_msg_connection_get_rssi_cmd_t {
uint8 connection;
} PACKED;
struct ble_msg_connection_get_rssi_rsp_t {
uint8 connection;
int8 rssi;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_UPDATE
struct ble_msg_connection_update_cmd_t {
uint8 connection;
uint16 interval_min;
uint16 interval_max;
uint16 latency;
uint16 timeout;
} PACKED;
struct ble_msg_connection_update_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_VERSION_UPDATE
struct ble_msg_connection_version_update_cmd_t {
uint8 connection;
} PACKED;
struct ble_msg_connection_version_update_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_CHANNEL_MAP_GET
struct ble_msg_connection_channel_map_get_cmd_t {
uint8 connection;
} PACKED;
struct ble_msg_connection_channel_map_get_rsp_t {
uint8 connection;
uint8array map;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_CHANNEL_MAP_SET
struct ble_msg_connection_channel_map_set_cmd_t {
uint8 connection;
uint8 map_len;
const uint8 *map_data;
} PACKED;
struct ble_msg_connection_channel_map_set_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_FEATURES_GET
struct ble_msg_connection_features_get_cmd_t {
uint8 connection;
} PACKED;
struct ble_msg_connection_features_get_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_GET_STATUS
struct ble_msg_connection_get_status_cmd_t {
uint8 connection;
} PACKED;
struct ble_msg_connection_get_status_rsp_t {
uint8 connection;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_RAW_TX
struct ble_msg_connection_raw_tx_cmd_t {
uint8 connection;
uint8 data_len;
const uint8 *data_data;
} PACKED;
struct ble_msg_connection_raw_tx_rsp_t {
uint8 connection;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_CONNECTION_STATUS
struct ble_msg_connection_status_evt_t {
uint8 connection;
uint8 flags;
bd_addr address;
uint8 address_type;
uint16 conn_interval;
uint16 timeout;
uint16 latency;
uint8 bonding;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_CONNECTION_VERSION_IND
struct ble_msg_connection_version_ind_evt_t {
uint8 connection;
uint8 vers_nr;
uint16 comp_id;
uint16 sub_vers_nr;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_CONNECTION_FEATURE_IND
struct ble_msg_connection_feature_ind_evt_t {
uint8 connection;
uint8array features;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_CONNECTION_RAW_RX
struct ble_msg_connection_raw_rx_evt_t {
uint8 connection;
uint8array data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_CONNECTION_DISCONNECTED
struct ble_msg_connection_disconnected_evt_t {
uint8 connection;
uint16 reason;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_FIND_BY_TYPE_VALUE
struct ble_msg_attclient_find_by_type_value_cmd_t {
uint8 connection;
uint16 start;
uint16 end;
uint16 uuid;
uint8 value_len;
const uint8 *value_data;
} PACKED;
struct ble_msg_attclient_find_by_type_value_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_BY_GROUP_TYPE
struct ble_msg_attclient_read_by_group_type_cmd_t {
uint8 connection;
uint16 start;
uint16 end;
uint8 uuid_len;
const uint8 *uuid_data;
} PACKED;
struct ble_msg_attclient_read_by_group_type_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_BY_TYPE
struct ble_msg_attclient_read_by_type_cmd_t {
uint8 connection;
uint16 start;
uint16 end;
uint8 uuid_len;
const uint8 *uuid_data;
} PACKED;
struct ble_msg_attclient_read_by_type_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_FIND_INFORMATION
struct ble_msg_attclient_find_information_cmd_t {
uint8 connection;
uint16 start;
uint16 end;
} PACKED;
struct ble_msg_attclient_find_information_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_BY_HANDLE
struct ble_msg_attclient_read_by_handle_cmd_t {
uint8 connection;
uint16 chrhandle;
} PACKED;
struct ble_msg_attclient_read_by_handle_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_ATTRIBUTE_WRITE
struct ble_msg_attclient_attribute_write_cmd_t {
uint8 connection;
uint16 atthandle;
uint8 data_len;
const uint8 *data_data;
} PACKED;
struct ble_msg_attclient_attribute_write_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_WRITE_COMMAND
struct ble_msg_attclient_write_command_cmd_t {
uint8 connection;
uint16 atthandle;
uint8 data_len;
const uint8 *data_data;
} PACKED;
struct ble_msg_attclient_write_command_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_INDICATE_CONFIRM
struct ble_msg_attclient_indicate_confirm_cmd_t {
uint8 connection;
} PACKED;
struct ble_msg_attclient_indicate_confirm_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_LONG
struct ble_msg_attclient_read_long_cmd_t {
uint8 connection;
uint16 chrhandle;
} PACKED;
struct ble_msg_attclient_read_long_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_PREPARE_WRITE
struct ble_msg_attclient_prepare_write_cmd_t {
uint8 connection;
uint16 atthandle;
uint16 offset;
uint8 data_len;
const uint8 *data_data;
} PACKED;
struct ble_msg_attclient_prepare_write_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_EXECUTE_WRITE
struct ble_msg_attclient_execute_write_cmd_t {
uint8 connection;
uint8 commit;
} PACKED;
struct ble_msg_attclient_execute_write_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_MULTIPLE
struct ble_msg_attclient_read_multiple_cmd_t {
uint8 connection;
uint8 handles_len;
const uint8 *handles_data;
} PACKED;
struct ble_msg_attclient_read_multiple_rsp_t {
uint8 connection;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_INDICATED
struct ble_msg_attclient_indicated_evt_t {
uint8 connection;
uint16 attrhandle;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_PROCEDURE_COMPLETED
struct ble_msg_attclient_procedure_completed_evt_t {
uint8 connection;
uint16 result;
uint16 chrhandle;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_GROUP_FOUND
struct ble_msg_attclient_group_found_evt_t {
uint8 connection;
uint16 start;
uint16 end;
uint8array uuid;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_ATTRIBUTE_FOUND
struct ble_msg_attclient_attribute_found_evt_t {
uint8 connection;
uint16 chrdecl;
uint16 value;
uint8 properties;
uint8array uuid;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_FIND_INFORMATION_FOUND
struct ble_msg_attclient_find_information_found_evt_t {
uint8 connection;
uint16 chrhandle;
uint8array uuid;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_ATTRIBUTE_VALUE
struct ble_msg_attclient_attribute_value_evt_t {
uint8 connection;
uint16 atthandle;
uint8 type;
uint8array value;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_READ_MULTIPLE_RESPONSE
struct ble_msg_attclient_read_multiple_response_evt_t {
uint8 connection;
uint8array handles;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_ENCRYPT_START
struct ble_msg_sm_encrypt_start_cmd_t {
uint8 handle;
uint8 bonding;
} PACKED;
struct ble_msg_sm_encrypt_start_rsp_t {
uint8 handle;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_SET_BONDABLE_MODE
struct ble_msg_sm_set_bondable_mode_cmd_t {
uint8 bondable;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_DELETE_BONDING
struct ble_msg_sm_delete_bonding_cmd_t {
uint8 handle;
} PACKED;
struct ble_msg_sm_delete_bonding_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_SET_PARAMETERS
struct ble_msg_sm_set_parameters_cmd_t {
uint8 mitm;
uint8 min_key_size;
uint8 io_capabilities;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_PASSKEY_ENTRY
struct ble_msg_sm_passkey_entry_cmd_t {
uint8 handle;
uint32 passkey;
} PACKED;
struct ble_msg_sm_passkey_entry_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_GET_BONDS
struct ble_msg_sm_get_bonds_rsp_t {
uint8 bonds;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_SET_OOB_DATA
struct ble_msg_sm_set_oob_data_cmd_t {
uint8 oob_len;
const uint8 *oob_data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_SM_SMP_DATA
struct ble_msg_sm_smp_data_evt_t {
uint8 handle;
uint8 packet;
uint8array data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_SM_BONDING_FAIL
struct ble_msg_sm_bonding_fail_evt_t {
uint8 handle;
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_SM_PASSKEY_DISPLAY
struct ble_msg_sm_passkey_display_evt_t {
uint8 handle;
uint32 passkey;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_SM_PASSKEY_REQUEST
struct ble_msg_sm_passkey_request_evt_t {
uint8 handle;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_SM_BOND_STATUS
struct ble_msg_sm_bond_status_evt_t {
uint8 bond;
uint8 keysize;
uint8 mitm;
uint8 keys;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_PRIVACY_FLAGS
struct ble_msg_gap_set_privacy_flags_cmd_t {
uint8 peripheral_privacy;
uint8 central_privacy;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_MODE
struct ble_msg_gap_set_mode_cmd_t {
uint8 discover;
uint8 connect;
} PACKED;
struct ble_msg_gap_set_mode_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_DISCOVER
struct ble_msg_gap_discover_cmd_t {
uint8 mode;
} PACKED;
struct ble_msg_gap_discover_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_CONNECT_DIRECT
struct ble_msg_gap_connect_direct_cmd_t {
bd_addr address;
uint8 addr_type;
uint16 conn_interval_min;
uint16 conn_interval_max;
uint16 timeout;
uint16 latency;
} PACKED;
struct ble_msg_gap_connect_direct_rsp_t {
uint16 result;
uint8 connection_handle;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_END_PROCEDURE
struct ble_msg_gap_end_procedure_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_CONNECT_SELECTIVE
struct ble_msg_gap_connect_selective_cmd_t {
uint16 conn_interval_min;
uint16 conn_interval_max;
uint16 timeout;
uint16 latency;
} PACKED;
struct ble_msg_gap_connect_selective_rsp_t {
uint16 result;
uint8 connection_handle;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_FILTERING
struct ble_msg_gap_set_filtering_cmd_t {
uint8 scan_policy;
uint8 adv_policy;
uint8 scan_duplicate_filtering;
} PACKED;
struct ble_msg_gap_set_filtering_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_SCAN_PARAMETERS
struct ble_msg_gap_set_scan_parameters_cmd_t {
uint16 scan_interval;
uint16 scan_window;
uint8 active;
} PACKED;
struct ble_msg_gap_set_scan_parameters_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_ADV_PARAMETERS
struct ble_msg_gap_set_adv_parameters_cmd_t {
uint16 adv_interval_min;
uint16 adv_interval_max;
uint8 adv_channels;
} PACKED;
struct ble_msg_gap_set_adv_parameters_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_ADV_DATA
struct ble_msg_gap_set_adv_data_cmd_t {
uint8 set_scanrsp;
uint8 adv_data_len;
const uint8 *adv_data_data;
} PACKED;
struct ble_msg_gap_set_adv_data_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_DIRECTED_CONNECTABLE_MODE
struct ble_msg_gap_set_directed_connectable_mode_cmd_t {
bd_addr address;
uint8 addr_type;
} PACKED;
struct ble_msg_gap_set_directed_connectable_mode_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_GAP_SCAN_RESPONSE
struct ble_msg_gap_scan_response_evt_t {
int8 rssi;
uint8 packet_type;
bd_addr sender;
uint8 address_type;
uint8 bond;
uint8array data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_GAP_MODE_CHANGED
struct ble_msg_gap_mode_changed_evt_t {
uint8 discover;
uint8 connect;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_IRQ
struct ble_msg_hardware_io_port_config_irq_cmd_t {
uint8 port;
uint8 enable_bits;
uint8 falling_edge;
} PACKED;
struct ble_msg_hardware_io_port_config_irq_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SET_SOFT_TIMER
struct ble_msg_hardware_set_soft_timer_cmd_t {
uint32 time;
uint8 handle;
uint8 single_shot;
} PACKED;
struct ble_msg_hardware_set_soft_timer_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_ADC_READ
struct ble_msg_hardware_adc_read_cmd_t {
uint8 input;
uint8 decimation;
uint8 reference_selection;
} PACKED;
struct ble_msg_hardware_adc_read_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_DIRECTION
struct ble_msg_hardware_io_port_config_direction_cmd_t {
uint8 port;
uint8 direction;
} PACKED;
struct ble_msg_hardware_io_port_config_direction_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_FUNCTION
struct ble_msg_hardware_io_port_config_function_cmd_t {
uint8 port;
uint8 function;
} PACKED;
struct ble_msg_hardware_io_port_config_function_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_PULL
struct ble_msg_hardware_io_port_config_pull_cmd_t {
uint8 port;
uint8 tristate_mask;
uint8 pull_up;
} PACKED;
struct ble_msg_hardware_io_port_config_pull_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_WRITE
struct ble_msg_hardware_io_port_write_cmd_t {
uint8 port;
uint8 mask;
uint8 data;
} PACKED;
struct ble_msg_hardware_io_port_write_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_READ
struct ble_msg_hardware_io_port_read_cmd_t {
uint8 port;
uint8 mask;
} PACKED;
struct ble_msg_hardware_io_port_read_rsp_t {
uint16 result;
uint8 port;
uint8 data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SPI_CONFIG
struct ble_msg_hardware_spi_config_cmd_t {
uint8 channel;
uint8 polarity;
uint8 phase;
uint8 bit_order;
uint8 baud_e;
uint8 baud_m;
} PACKED;
struct ble_msg_hardware_spi_config_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SPI_TRANSFER
struct ble_msg_hardware_spi_transfer_cmd_t {
uint8 channel;
uint8 data_len;
const uint8 *data_data;
} PACKED;
struct ble_msg_hardware_spi_transfer_rsp_t {
uint16 result;
uint8 channel;
uint8array data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_I2C_READ
struct ble_msg_hardware_i2c_read_cmd_t {
uint8 address;
uint8 stop;
uint8 length;
} PACKED;
struct ble_msg_hardware_i2c_read_rsp_t {
uint16 result;
uint8array data;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_I2C_WRITE
struct ble_msg_hardware_i2c_write_cmd_t {
uint8 address;
uint8 stop;
uint8 data_len;
const uint8 *data_data;
} PACKED;
struct ble_msg_hardware_i2c_write_rsp_t {
uint8 written;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SET_TXPOWER
struct ble_msg_hardware_set_txpower_cmd_t {
uint8 power;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_TIMER_COMPARATOR
struct ble_msg_hardware_timer_comparator_cmd_t {
uint8 timer;
uint8 channel;
uint8 mode;
uint16 comparator_value;
} PACKED;
struct ble_msg_hardware_timer_comparator_rsp_t {
uint16 result;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_HARDWARE_IO_PORT_STATUS
struct ble_msg_hardware_io_port_status_evt_t {
uint32 timestamp;
uint8 port;
uint8 irq;
uint8 state;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_HARDWARE_SOFT_TIMER
struct ble_msg_hardware_soft_timer_evt_t {
uint8 handle;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_EVENT_HARDWARE_ADC_RESULT
struct ble_msg_hardware_adc_result_evt_t {
uint8 input;
int16 value;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_TX
struct ble_msg_test_phy_tx_cmd_t {
uint8 channel;
uint8 length;
uint8 type;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_RX
struct ble_msg_test_phy_rx_cmd_t {
uint8 channel;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_END
struct ble_msg_test_phy_end_rsp_t {
uint16 counter;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_GET_CHANNEL_MAP
struct ble_msg_test_get_channel_map_rsp_t {
uint8array channel_map;
} PACKED;
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_DEBUG
struct ble_msg_test_debug_cmd_t {
uint8 input_len;
const uint8 *input_data;
} PACKED;
struct ble_msg_test_debug_rsp_t {
uint8array output;
} PACKED;
#endif
class BGLib {
public:
BGLib(HardwareSerial *module=0, HardwareSerial *output=0, uint8_t pMode=0);
uint8_t checkActivity(uint16_t timeout=0);
uint8_t checkError();
uint8_t checkTimeout();
void setBusy(bool busyEnabled);
uint8_t *getLastCommand();
uint8_t *getLastResponse();
uint8_t *getLastEvent();
void *getLastRXPayload();
// set/update UART port objects
void setModuleUART(HardwareSerial *module);
void setOutputUART(HardwareSerial *debug);
uint8_t parse(uint8_t ch, uint8_t packetMode=0);
uint8_t sendCommand(uint16_t len, uint8_t commandClass, uint8_t commandId, void *payload=0);
void (*onBusy)(); // special function to run when entering a "busy" state (e.g. mid-packet)
void (*onIdle)(); // special function to run when returning to idle mode
void (*onTimeout)(); // special function to run when the parser times out waiting for expected data
void (*onBeforeTXCommand)(); // special function to run immediately before sending a command
void (*onTXCommandComplete)(); // special function to run immediately after command transmission is complete
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_RESET
uint8_t ble_cmd_system_reset(uint8 boot_in_dfu);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_HELLO
uint8_t ble_cmd_system_hello();
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ADDRESS_GET
uint8_t ble_cmd_system_address_get();
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_REG_WRITE
uint8_t ble_cmd_system_reg_write(uint16 address, uint8 value);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_REG_READ
uint8_t ble_cmd_system_reg_read(uint16 address);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_GET_COUNTERS
uint8_t ble_cmd_system_get_counters();
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_GET_CONNECTIONS
uint8_t ble_cmd_system_get_connections();
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_READ_MEMORY
uint8_t ble_cmd_system_read_memory(uint32 address, uint8 length);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_GET_INFO
uint8_t ble_cmd_system_get_info();
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ENDPOINT_TX
uint8_t ble_cmd_system_endpoint_tx(uint8 endpoint, uint8 data_len, const uint8 *data_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_WHITELIST_APPEND
uint8_t ble_cmd_system_whitelist_append(bd_addr address, uint8 address_type);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_WHITELIST_REMOVE
uint8_t ble_cmd_system_whitelist_remove(bd_addr address, uint8 address_type);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_WHITELIST_CLEAR
uint8_t ble_cmd_system_whitelist_clear();
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ENDPOINT_RX
uint8_t ble_cmd_system_endpoint_rx(uint8 endpoint, uint8 size);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ENDPOINT_SET_WATERMARKS
uint8_t ble_cmd_system_endpoint_set_watermarks(uint8 endpoint, uint8 rx, uint8 tx);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_DEFRAG
uint8_t ble_cmd_flash_ps_defrag();
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_DUMP
uint8_t ble_cmd_flash_ps_dump();
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_ERASE_ALL
uint8_t ble_cmd_flash_ps_erase_all();
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_SAVE
uint8_t ble_cmd_flash_ps_save(uint16 key, uint8 value_len, const uint8 *value_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_LOAD
uint8_t ble_cmd_flash_ps_load(uint16 key);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_ERASE
uint8_t ble_cmd_flash_ps_erase(uint16 key);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_ERASE_PAGE
uint8_t ble_cmd_flash_erase_page(uint8 page);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_WRITE_WORDS
uint8_t ble_cmd_flash_write_words(uint16 address, uint8 words_len, const uint8 *words_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_WRITE
uint8_t ble_cmd_attributes_write(uint16 handle, uint8 offset, uint8 value_len, const uint8 *value_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_READ
uint8_t ble_cmd_attributes_read(uint16 handle, uint16 offset);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_READ_TYPE
uint8_t ble_cmd_attributes_read_type(uint16 handle);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_USER_READ_RESPONSE
uint8_t ble_cmd_attributes_user_read_response(uint8 connection, uint8 att_error, uint8 value_len, const uint8 *value_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_USER_WRITE_RESPONSE
uint8_t ble_cmd_attributes_user_write_response(uint8 connection, uint8 att_error);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_DISCONNECT
uint8_t ble_cmd_connection_disconnect(uint8 connection);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_GET_RSSI
uint8_t ble_cmd_connection_get_rssi(uint8 connection);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_UPDATE
uint8_t ble_cmd_connection_update(uint8 connection, uint16 interval_min, uint16 interval_max, uint16 latency, uint16 timeout);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_VERSION_UPDATE
uint8_t ble_cmd_connection_version_update(uint8 connection);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_CHANNEL_MAP_GET
uint8_t ble_cmd_connection_channel_map_get(uint8 connection);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_CHANNEL_MAP_SET
uint8_t ble_cmd_connection_channel_map_set(uint8 connection, uint8 map_len, const uint8 *map_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_FEATURES_GET
uint8_t ble_cmd_connection_features_get(uint8 connection);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_GET_STATUS
uint8_t ble_cmd_connection_get_status(uint8 connection);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_RAW_TX
uint8_t ble_cmd_connection_raw_tx(uint8 connection, uint8 data_len, const uint8 *data_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_FIND_BY_TYPE_VALUE
uint8_t ble_cmd_attclient_find_by_type_value(uint8 connection, uint16 start, uint16 end, uint16 uuid, uint8 value_len, const uint8 *value_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_BY_GROUP_TYPE
uint8_t ble_cmd_attclient_read_by_group_type(uint8 connection, uint16 start, uint16 end, uint8 uuid_len, const uint8 *uuid_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_BY_TYPE
uint8_t ble_cmd_attclient_read_by_type(uint8 connection, uint16 start, uint16 end, uint8 uuid_len, const uint8 *uuid_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_FIND_INFORMATION
uint8_t ble_cmd_attclient_find_information(uint8 connection, uint16 start, uint16 end);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_BY_HANDLE
uint8_t ble_cmd_attclient_read_by_handle(uint8 connection, uint16 chrhandle);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_ATTRIBUTE_WRITE
uint8_t ble_cmd_attclient_attribute_write(uint8 connection, uint16 atthandle, uint8 data_len, const uint8 *data_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_WRITE_COMMAND
uint8_t ble_cmd_attclient_write_command(uint8 connection, uint16 atthandle, uint8 data_len, const uint8 *data_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_INDICATE_CONFIRM
uint8_t ble_cmd_attclient_indicate_confirm(uint8 connection);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_LONG
uint8_t ble_cmd_attclient_read_long(uint8 connection, uint16 chrhandle);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_PREPARE_WRITE
uint8_t ble_cmd_attclient_prepare_write(uint8 connection, uint16 atthandle, uint16 offset, uint8 data_len, const uint8 *data_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_EXECUTE_WRITE
uint8_t ble_cmd_attclient_execute_write(uint8 connection, uint8 commit);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_MULTIPLE
uint8_t ble_cmd_attclient_read_multiple(uint8 connection, uint8 handles_len, const uint8 *handles_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_ENCRYPT_START
uint8_t ble_cmd_sm_encrypt_start(uint8 handle, uint8 bonding);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_SET_BONDABLE_MODE
uint8_t ble_cmd_sm_set_bondable_mode(uint8 bondable);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_DELETE_BONDING
uint8_t ble_cmd_sm_delete_bonding(uint8 handle);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_SET_PARAMETERS
uint8_t ble_cmd_sm_set_parameters(uint8 mitm, uint8 min_key_size, uint8 io_capabilities);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_PASSKEY_ENTRY
uint8_t ble_cmd_sm_passkey_entry(uint8 handle, uint32 passkey);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_GET_BONDS
uint8_t ble_cmd_sm_get_bonds();
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_SET_OOB_DATA
uint8_t ble_cmd_sm_set_oob_data(uint8 oob_len, const uint8 *oob_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_PRIVACY_FLAGS
uint8_t ble_cmd_gap_set_privacy_flags(uint8 peripheral_privacy, uint8 central_privacy);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_MODE
uint8_t ble_cmd_gap_set_mode(uint8 discover, uint8 connect);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_DISCOVER
uint8_t ble_cmd_gap_discover(uint8 mode);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_CONNECT_DIRECT
uint8_t ble_cmd_gap_connect_direct(bd_addr address, uint8 addr_type, uint16 conn_interval_min, uint16 conn_interval_max, uint16 timeout, uint16 latency);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_END_PROCEDURE
uint8_t ble_cmd_gap_end_procedure();
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_CONNECT_SELECTIVE
uint8_t ble_cmd_gap_connect_selective(uint16 conn_interval_min, uint16 conn_interval_max, uint16 timeout, uint16 latency);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_FILTERING
uint8_t ble_cmd_gap_set_filtering(uint8 scan_policy, uint8 adv_policy, uint8 scan_duplicate_filtering);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_SCAN_PARAMETERS
uint8_t ble_cmd_gap_set_scan_parameters(uint16 scan_interval, uint16 scan_window, uint8 active);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_ADV_PARAMETERS
uint8_t ble_cmd_gap_set_adv_parameters(uint16 adv_interval_min, uint16 adv_interval_max, uint8 adv_channels);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_ADV_DATA
uint8_t ble_cmd_gap_set_adv_data(uint8 set_scanrsp, uint8 adv_data_len, const uint8 *adv_data_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_DIRECTED_CONNECTABLE_MODE
uint8_t ble_cmd_gap_set_directed_connectable_mode(bd_addr address, uint8 addr_type);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_IRQ
uint8_t ble_cmd_hardware_io_port_config_irq(uint8 port, uint8 enable_bits, uint8 falling_edge);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SET_SOFT_TIMER
uint8_t ble_cmd_hardware_set_soft_timer(uint32 time, uint8 handle, uint8 single_shot);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_ADC_READ
uint8_t ble_cmd_hardware_adc_read(uint8 input, uint8 decimation, uint8 reference_selection);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_DIRECTION
uint8_t ble_cmd_hardware_io_port_config_direction(uint8 port, uint8 direction);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_FUNCTION
uint8_t ble_cmd_hardware_io_port_config_function(uint8 port, uint8 function);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_PULL
uint8_t ble_cmd_hardware_io_port_config_pull(uint8 port, uint8 tristate_mask, uint8 pull_up);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_WRITE
uint8_t ble_cmd_hardware_io_port_write(uint8 port, uint8 mask, uint8 data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_READ
uint8_t ble_cmd_hardware_io_port_read(uint8 port, uint8 mask);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SPI_CONFIG
uint8_t ble_cmd_hardware_spi_config(uint8 channel, uint8 polarity, uint8 phase, uint8 bit_order, uint8 baud_e, uint8 baud_m);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SPI_TRANSFER
uint8_t ble_cmd_hardware_spi_transfer(uint8 channel, uint8 data_len, const uint8 *data_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_I2C_READ
uint8_t ble_cmd_hardware_i2c_read(uint8 address, uint8 stop, uint8 length);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_I2C_WRITE
uint8_t ble_cmd_hardware_i2c_write(uint8 address, uint8 stop, uint8 data_len, const uint8 *data_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SET_TXPOWER
uint8_t ble_cmd_hardware_set_txpower(uint8 power);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_TIMER_COMPARATOR
uint8_t ble_cmd_hardware_timer_comparator(uint8 timer, uint8 channel, uint8 mode, uint16 comparator_value);
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_TX
uint8_t ble_cmd_test_phy_tx(uint8 channel, uint8 length, uint8 type);
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_RX
uint8_t ble_cmd_test_phy_rx(uint8 channel);
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_END
uint8_t ble_cmd_test_phy_end();
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_RESET
uint8_t ble_cmd_test_phy_reset();
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_GET_CHANNEL_MAP
uint8_t ble_cmd_test_get_channel_map();
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_DEBUG
uint8_t ble_cmd_test_debug(uint8 input_len, const uint8 *input_data);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_RESET
void (*ble_rsp_system_reset)(const struct ble_msg_system_reset_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_HELLO
void (*ble_rsp_system_hello)(const struct ble_msg_system_hello_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ADDRESS_GET
void (*ble_rsp_system_address_get)(const struct ble_msg_system_address_get_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_REG_WRITE
void (*ble_rsp_system_reg_write)(const struct ble_msg_system_reg_write_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_REG_READ
void (*ble_rsp_system_reg_read)(const struct ble_msg_system_reg_read_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_GET_COUNTERS
void (*ble_rsp_system_get_counters)(const struct ble_msg_system_get_counters_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_GET_CONNECTIONS
void (*ble_rsp_system_get_connections)(const struct ble_msg_system_get_connections_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_READ_MEMORY
void (*ble_rsp_system_read_memory)(const struct ble_msg_system_read_memory_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_GET_INFO
void (*ble_rsp_system_get_info)(const struct ble_msg_system_get_info_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ENDPOINT_TX
void (*ble_rsp_system_endpoint_tx)(const struct ble_msg_system_endpoint_tx_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_WHITELIST_APPEND
void (*ble_rsp_system_whitelist_append)(const struct ble_msg_system_whitelist_append_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_WHITELIST_REMOVE
void (*ble_rsp_system_whitelist_remove)(const struct ble_msg_system_whitelist_remove_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_WHITELIST_CLEAR
void (*ble_rsp_system_whitelist_clear)(const struct ble_msg_system_whitelist_clear_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ENDPOINT_RX
void (*ble_rsp_system_endpoint_rx)(const struct ble_msg_system_endpoint_rx_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SYSTEM_ENDPOINT_SET_WATERMARKS
void (*ble_rsp_system_endpoint_set_watermarks)(const struct ble_msg_system_endpoint_set_watermarks_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_DEFRAG
void (*ble_rsp_flash_ps_defrag)(const struct ble_msg_flash_ps_defrag_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_DUMP
void (*ble_rsp_flash_ps_dump)(const struct ble_msg_flash_ps_dump_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_ERASE_ALL
void (*ble_rsp_flash_ps_erase_all)(const struct ble_msg_flash_ps_erase_all_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_SAVE
void (*ble_rsp_flash_ps_save)(const struct ble_msg_flash_ps_save_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_LOAD
void (*ble_rsp_flash_ps_load)(const struct ble_msg_flash_ps_load_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_PS_ERASE
void (*ble_rsp_flash_ps_erase)(const struct ble_msg_flash_ps_erase_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_ERASE_PAGE
void (*ble_rsp_flash_erase_page)(const struct ble_msg_flash_erase_page_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_FLASH_WRITE_WORDS
void (*ble_rsp_flash_write_words)(const struct ble_msg_flash_write_words_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_WRITE
void (*ble_rsp_attributes_write)(const struct ble_msg_attributes_write_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_READ
void (*ble_rsp_attributes_read)(const struct ble_msg_attributes_read_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_READ_TYPE
void (*ble_rsp_attributes_read_type)(const struct ble_msg_attributes_read_type_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_USER_READ_RESPONSE
void (*ble_rsp_attributes_user_read_response)(const struct ble_msg_attributes_user_read_response_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTRIBUTES_USER_WRITE_RESPONSE
void (*ble_rsp_attributes_user_write_response)(const struct ble_msg_attributes_user_write_response_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_DISCONNECT
void (*ble_rsp_connection_disconnect)(const struct ble_msg_connection_disconnect_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_GET_RSSI
void (*ble_rsp_connection_get_rssi)(const struct ble_msg_connection_get_rssi_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_UPDATE
void (*ble_rsp_connection_update)(const struct ble_msg_connection_update_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_VERSION_UPDATE
void (*ble_rsp_connection_version_update)(const struct ble_msg_connection_version_update_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_CHANNEL_MAP_GET
void (*ble_rsp_connection_channel_map_get)(const struct ble_msg_connection_channel_map_get_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_CHANNEL_MAP_SET
void (*ble_rsp_connection_channel_map_set)(const struct ble_msg_connection_channel_map_set_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_FEATURES_GET
void (*ble_rsp_connection_features_get)(const struct ble_msg_connection_features_get_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_GET_STATUS
void (*ble_rsp_connection_get_status)(const struct ble_msg_connection_get_status_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_CONNECTION_RAW_TX
void (*ble_rsp_connection_raw_tx)(const struct ble_msg_connection_raw_tx_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_FIND_BY_TYPE_VALUE
void (*ble_rsp_attclient_find_by_type_value)(const struct ble_msg_attclient_find_by_type_value_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_BY_GROUP_TYPE
void (*ble_rsp_attclient_read_by_group_type)(const struct ble_msg_attclient_read_by_group_type_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_BY_TYPE
void (*ble_rsp_attclient_read_by_type)(const struct ble_msg_attclient_read_by_type_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_FIND_INFORMATION
void (*ble_rsp_attclient_find_information)(const struct ble_msg_attclient_find_information_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_BY_HANDLE
void (*ble_rsp_attclient_read_by_handle)(const struct ble_msg_attclient_read_by_handle_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_ATTRIBUTE_WRITE
void (*ble_rsp_attclient_attribute_write)(const struct ble_msg_attclient_attribute_write_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_WRITE_COMMAND
void (*ble_rsp_attclient_write_command)(const struct ble_msg_attclient_write_command_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_INDICATE_CONFIRM
void (*ble_rsp_attclient_indicate_confirm)(const struct ble_msg_attclient_indicate_confirm_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_LONG
void (*ble_rsp_attclient_read_long)(const struct ble_msg_attclient_read_long_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_PREPARE_WRITE
void (*ble_rsp_attclient_prepare_write)(const struct ble_msg_attclient_prepare_write_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_EXECUTE_WRITE
void (*ble_rsp_attclient_execute_write)(const struct ble_msg_attclient_execute_write_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_ATTCLIENT_READ_MULTIPLE
void (*ble_rsp_attclient_read_multiple)(const struct ble_msg_attclient_read_multiple_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_ENCRYPT_START
void (*ble_rsp_sm_encrypt_start)(const struct ble_msg_sm_encrypt_start_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_SET_BONDABLE_MODE
void (*ble_rsp_sm_set_bondable_mode)(const struct ble_msg_sm_set_bondable_mode_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_DELETE_BONDING
void (*ble_rsp_sm_delete_bonding)(const struct ble_msg_sm_delete_bonding_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_SET_PARAMETERS
void (*ble_rsp_sm_set_parameters)(const struct ble_msg_sm_set_parameters_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_PASSKEY_ENTRY
void (*ble_rsp_sm_passkey_entry)(const struct ble_msg_sm_passkey_entry_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_GET_BONDS
void (*ble_rsp_sm_get_bonds)(const struct ble_msg_sm_get_bonds_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_SM_SET_OOB_DATA
void (*ble_rsp_sm_set_oob_data)(const struct ble_msg_sm_set_oob_data_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_PRIVACY_FLAGS
void (*ble_rsp_gap_set_privacy_flags)(const struct ble_msg_gap_set_privacy_flags_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_MODE
void (*ble_rsp_gap_set_mode)(const struct ble_msg_gap_set_mode_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_DISCOVER
void (*ble_rsp_gap_discover)(const struct ble_msg_gap_discover_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_CONNECT_DIRECT
void (*ble_rsp_gap_connect_direct)(const struct ble_msg_gap_connect_direct_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_END_PROCEDURE
void (*ble_rsp_gap_end_procedure)(const struct ble_msg_gap_end_procedure_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_CONNECT_SELECTIVE
void (*ble_rsp_gap_connect_selective)(const struct ble_msg_gap_connect_selective_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_FILTERING
void (*ble_rsp_gap_set_filtering)(const struct ble_msg_gap_set_filtering_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_SCAN_PARAMETERS
void (*ble_rsp_gap_set_scan_parameters)(const struct ble_msg_gap_set_scan_parameters_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_ADV_PARAMETERS
void (*ble_rsp_gap_set_adv_parameters)(const struct ble_msg_gap_set_adv_parameters_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_ADV_DATA
void (*ble_rsp_gap_set_adv_data)(const struct ble_msg_gap_set_adv_data_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_GAP_SET_DIRECTED_CONNECTABLE_MODE
void (*ble_rsp_gap_set_directed_connectable_mode)(const struct ble_msg_gap_set_directed_connectable_mode_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_IRQ
void (*ble_rsp_hardware_io_port_config_irq)(const struct ble_msg_hardware_io_port_config_irq_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SET_SOFT_TIMER
void (*ble_rsp_hardware_set_soft_timer)(const struct ble_msg_hardware_set_soft_timer_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_ADC_READ
void (*ble_rsp_hardware_adc_read)(const struct ble_msg_hardware_adc_read_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_DIRECTION
void (*ble_rsp_hardware_io_port_config_direction)(const struct ble_msg_hardware_io_port_config_direction_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_FUNCTION
void (*ble_rsp_hardware_io_port_config_function)(const struct ble_msg_hardware_io_port_config_function_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_CONFIG_PULL
void (*ble_rsp_hardware_io_port_config_pull)(const struct ble_msg_hardware_io_port_config_pull_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_WRITE
void (*ble_rsp_hardware_io_port_write)(const struct ble_msg_hardware_io_port_write_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_IO_PORT_READ
void (*ble_rsp_hardware_io_port_read)(const struct ble_msg_hardware_io_port_read_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SPI_CONFIG
void (*ble_rsp_hardware_spi_config)(const struct ble_msg_hardware_spi_config_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SPI_TRANSFER
void (*ble_rsp_hardware_spi_transfer)(const struct ble_msg_hardware_spi_transfer_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_I2C_READ
void (*ble_rsp_hardware_i2c_read)(const struct ble_msg_hardware_i2c_read_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_I2C_WRITE
void (*ble_rsp_hardware_i2c_write)(const struct ble_msg_hardware_i2c_write_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_SET_TXPOWER
void (*ble_rsp_hardware_set_txpower)(const struct ble_msg_hardware_set_txpower_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_HARDWARE_TIMER_COMPARATOR
void (*ble_rsp_hardware_timer_comparator)(const struct ble_msg_hardware_timer_comparator_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_TX
void (*ble_rsp_test_phy_tx)(const struct ble_msg_test_phy_tx_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_RX
void (*ble_rsp_test_phy_rx)(const struct ble_msg_test_phy_rx_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_END
void (*ble_rsp_test_phy_end)(const struct ble_msg_test_phy_end_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_PHY_RESET
void (*ble_rsp_test_phy_reset)(const struct ble_msg_test_phy_reset_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_GET_CHANNEL_MAP
void (*ble_rsp_test_get_channel_map)(const struct ble_msg_test_get_channel_map_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_COMMAND_TEST_DEBUG
void (*ble_rsp_test_debug)(const struct ble_msg_test_debug_rsp_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_BOOT
void (*ble_evt_system_boot)(const struct ble_msg_system_boot_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_DEBUG
void (*ble_evt_system_debug)(const struct ble_msg_system_debug_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_ENDPOINT_WATERMARK_RX
void (*ble_evt_system_endpoint_watermark_rx)(const struct ble_msg_system_endpoint_watermark_rx_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_ENDPOINT_WATERMARK_TX
void (*ble_evt_system_endpoint_watermark_tx)(const struct ble_msg_system_endpoint_watermark_tx_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_SCRIPT_FAILURE
void (*ble_evt_system_script_failure)(const struct ble_msg_system_script_failure_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SYSTEM_NO_LICENSE_KEY
void (*ble_evt_system_no_license_key)(const struct ble_msg_system_no_license_key_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_FLASH_PS_KEY
void (*ble_evt_flash_ps_key)(const struct ble_msg_flash_ps_key_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTRIBUTES_VALUE
void (*ble_evt_attributes_value)(const struct ble_msg_attributes_value_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTRIBUTES_USER_READ_REQUEST
void (*ble_evt_attributes_user_read_request)(const struct ble_msg_attributes_user_read_request_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTRIBUTES_STATUS
void (*ble_evt_attributes_status)(const struct ble_msg_attributes_status_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_CONNECTION_STATUS
void (*ble_evt_connection_status)(const struct ble_msg_connection_status_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_CONNECTION_VERSION_IND
void (*ble_evt_connection_version_ind)(const struct ble_msg_connection_version_ind_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_CONNECTION_FEATURE_IND
void (*ble_evt_connection_feature_ind)(const struct ble_msg_connection_feature_ind_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_CONNECTION_RAW_RX
void (*ble_evt_connection_raw_rx)(const struct ble_msg_connection_raw_rx_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_CONNECTION_DISCONNECTED
void (*ble_evt_connection_disconnected)(const struct ble_msg_connection_disconnected_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_INDICATED
void (*ble_evt_attclient_indicated)(const struct ble_msg_attclient_indicated_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_PROCEDURE_COMPLETED
void (*ble_evt_attclient_procedure_completed)(const struct ble_msg_attclient_procedure_completed_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_GROUP_FOUND
void (*ble_evt_attclient_group_found)(const struct ble_msg_attclient_group_found_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_ATTRIBUTE_FOUND
void (*ble_evt_attclient_attribute_found)(const struct ble_msg_attclient_attribute_found_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_FIND_INFORMATION_FOUND
void (*ble_evt_attclient_find_information_found)(const struct ble_msg_attclient_find_information_found_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_ATTRIBUTE_VALUE
void (*ble_evt_attclient_attribute_value)(const struct ble_msg_attclient_attribute_value_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_ATTCLIENT_READ_MULTIPLE_RESPONSE
void (*ble_evt_attclient_read_multiple_response)(const struct ble_msg_attclient_read_multiple_response_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SM_SMP_DATA
void (*ble_evt_sm_smp_data)(const struct ble_msg_sm_smp_data_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SM_BONDING_FAIL
void (*ble_evt_sm_bonding_fail)(const struct ble_msg_sm_bonding_fail_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SM_PASSKEY_DISPLAY
void (*ble_evt_sm_passkey_display)(const struct ble_msg_sm_passkey_display_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SM_PASSKEY_REQUEST
void (*ble_evt_sm_passkey_request)(const struct ble_msg_sm_passkey_request_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_SM_BOND_STATUS
void (*ble_evt_sm_bond_status)(const struct ble_msg_sm_bond_status_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_GAP_SCAN_RESPONSE
void (*ble_evt_gap_scan_response)(const struct ble_msg_gap_scan_response_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_GAP_MODE_CHANGED
void (*ble_evt_gap_mode_changed)(const struct ble_msg_gap_mode_changed_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_HARDWARE_IO_PORT_STATUS
void (*ble_evt_hardware_io_port_status)(const struct ble_msg_hardware_io_port_status_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_HARDWARE_SOFT_TIMER
void (*ble_evt_hardware_soft_timer)(const struct ble_msg_hardware_soft_timer_evt_t *msg);
#endif
#ifdef BGLIB_ENABLE_EVENT_HARDWARE_ADC_RESULT
void (*ble_evt_hardware_adc_result)(const struct ble_msg_hardware_adc_result_evt_t *msg);
#endif
private:
// incoming packet buffer vars
uint8_t *bgapiRXBuffer;
uint8_t bgapiRXBufferSize;
uint8_t bgapiRXBufferPos;
uint16_t bgapiRXDataLen;
// outgoing package buffer vars
uint8_t *bgapiTXBuffer;
uint8_t bgapiTXBufferSize;
uint8_t bgapiTXBufferPos;
// BGAPI packet structure representation
const struct ble_msg *packetMessage;
struct ble_header packetHeader;
uint8_t *packetData;
HardwareSerial *uModule; // required UART object with module connection
HardwareSerial *uOutput; // optional UART object for host/debug connection
bool busy;
uint8_t packetMode;
uint8_t lastCommand[2];
uint8_t lastResponse[2];
uint8_t lastEvent[2];
uint32_t timeoutStart;
bool lastError;
bool lastTimeout;
};
#endif
| 37.704687 | 165 | 0.743437 |
239c093c215c6c82035b10db1fee51cc2b5ffdf0 | 254 | h | C | Demo/Demo/zujian/AssemblySubview3.h | WZAYJ/WZDemo | b71239695a3a64b1a48594323a04453e6dc0c180 | [
"MIT"
] | null | null | null | Demo/Demo/zujian/AssemblySubview3.h | WZAYJ/WZDemo | b71239695a3a64b1a48594323a04453e6dc0c180 | [
"MIT"
] | null | null | null | Demo/Demo/zujian/AssemblySubview3.h | WZAYJ/WZDemo | b71239695a3a64b1a48594323a04453e6dc0c180 | [
"MIT"
] | null | null | null | //
// AssemblySubview3.h
// Demo
//
// Created by apple on 2019/4/4.
// Copyright © 2019 SRT. All rights reserved.
//
#import "BaseAssemblyView.h"
NS_ASSUME_NONNULL_BEGIN
@interface AssemblySubview3 : BaseAssemblyView
@end
NS_ASSUME_NONNULL_END
| 14.111111 | 46 | 0.73622 |
c10478816f16419769f071a6981f37c780784072 | 17,189 | c | C | ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_PacketEncoder.c | parc-ccnx-archive/Libccnx-common | 69d39e04b528ae703c1061bd597ce92bf8ea3b57 | [
"BSD-2-Clause"
] | null | null | null | ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_PacketEncoder.c | parc-ccnx-archive/Libccnx-common | 69d39e04b528ae703c1061bd597ce92bf8ea3b57 | [
"BSD-2-Clause"
] | null | null | null | ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_PacketEncoder.c | parc-ccnx-archive/Libccnx-common | 69d39e04b528ae703c1061bd597ce92bf8ea3b57 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2014-2015, Xerox Corporation (Xerox) and Palo Alto Research Center, Inc (PARC)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL XEROX OR PARC 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.
*
* ################################################################################
* #
* # PATENT NOTICE
* #
* # This software is distributed under the BSD 2-clause License (see LICENSE
* # file). This BSD License does not make any patent claims and as such, does
* # not act as a patent grant. The purpose of this section is for each contributor
* # to define their intentions with respect to intellectual property.
* #
* # Each contributor to this source code is encouraged to state their patent
* # claims and licensing mechanisms for any contributions made. At the end of
* # this section contributors may each make their own statements. Contributor's
* # claims and grants only apply to the pieces (source code, programs, text,
* # media, etc) that they have contributed directly to this software.
* #
* # There is no guarantee that this section is complete, up to date or accurate. It
* # is up to the contributors to maintain their portion of this section and up to
* # the user of the software to verify any claims herein.
* #
* # Do not remove this header notification. The contents of this section must be
* # present in all distributions of the software. You may only modify your own
* # intellectual property statements. Please provide contact information.
*
* - Palo Alto Research Center, Inc
* This software distribution does not grant any rights to patents owned by Palo
* Alto Research Center, Inc (PARC). Rights to these patents are available via
* various mechanisms. As of January 2016 PARC has committed to FRAND licensing any
* intellectual property used by its contributions to this software. You may
* contact PARC at cipo@parc.com for more information or visit http://www.ccnx.org
*/
/**
* @author Marc Mosko, Palo Alto Research Center (Xerox PARC)
* @copyright (c) 2014-2015, Xerox Corporation (Xerox) and Palo Alto Research Center, Inc (PARC). All rights reserved.
*/
#include <config.h>
#include <stdio.h>
#include <sys/time.h>
#include <inttypes.h>
#include <LongBow/runtime.h>
#include <parc/algol/parc_Memory.h>
#include <ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_Types.h>
#include <ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_PacketEncoder.h>
#include <ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_FixedHeaderEncoder.h>
#include <ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_OptionalHeadersEncoder.h>
#include <ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_MessageEncoder.h>
#include <ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_ValidationEncoder.h>
#include <ccnx/common/internal/ccnx_InterestDefault.h>
#include <ccnx/common/internal/ccnx_ValidationFacadeV1.h>
#include <ccnx/common/internal/ccnx_WireFormatMessageInterface.h>
// =====================================================
// Private API
static uint8_t
_getHopLimit(CCNxTlvDictionary *packetDictionary)
{
uint8_t hoplimit = (uint8_t) CCNxInterestDefault_HopLimit;
if (ccnxTlvDictionary_IsValueInteger(packetDictionary, CCNxCodecSchemaV1TlvDictionary_MessageFastArray_HOPLIMIT)) {
hoplimit = (uint8_t) ccnxTlvDictionary_GetInteger(packetDictionary, CCNxCodecSchemaV1TlvDictionary_MessageFastArray_HOPLIMIT);
}
return hoplimit;
}
static uint8_t
_getInterestReturnCode(CCNxTlvDictionary *packetDictionary)
{
uint8_t returnCode = (uint8_t) 0;
if (ccnxTlvDictionary_IsValueInteger(packetDictionary,
CCNxCodecSchemaV1TlvDictionary_HeadersFastArray_InterestReturnCode)) {
returnCode =
(uint8_t) ccnxTlvDictionary_GetInteger(packetDictionary,
CCNxCodecSchemaV1TlvDictionary_HeadersFastArray_InterestReturnCode);
}
return returnCode;
}
/**
* Creates a fixed header from the given parameters and encodes in network byte order
*
* All parameters in host byte order.
*
* @param [<#in out in,out#>] <#name#> <#description#>
*
* @return non-negative The total bytes appended to the encode buffer
* @return -1 An error
*
* Example:
* @code
* <#example#>
* @endcode
*/
static ssize_t
_encodeFixedHeader(CCNxCodecTlvEncoder *fixedHeaderEncoder,
CCNxTlvDictionary *packetDictionary,
int packetType,
ssize_t headerLength,
ssize_t packetLength)
{
CCNxCodecSchemaV1FixedHeader fixedHeader;
memset(&fixedHeader, 0, sizeof(fixedHeader));
fixedHeader.version = 1;
fixedHeader.packetType = packetType;
fixedHeader.packetLength = packetLength;
fixedHeader.headerLength = headerLength;
if ((packetType == CCNxCodecSchemaV1Types_PacketType_Interest) ||
(packetType == CCNxCodecSchemaV1Types_PacketType_InterestReturn)) {
CCNxCodecSchemaV1InterestHeader *interestHeader = (CCNxCodecSchemaV1InterestHeader *) &fixedHeader;
interestHeader->hopLimit = _getHopLimit(packetDictionary);
if (packetType == CCNxCodecSchemaV1Types_PacketType_InterestReturn) {
interestHeader->returnCode = _getInterestReturnCode(packetDictionary);
}
}
return ccnxCodecSchemaV1FixedHeaderEncoder_EncodeHeader(fixedHeaderEncoder, &fixedHeader);
}
static ssize_t
_encodeOptionalHeaders(CCNxCodecTlvEncoder *optionalHeaderEncoder, CCNxTlvDictionary *packetDictionary)
{
// Optional Headers do not have a container, so just append them right to the buffer
size_t optionalHeadersLength = 0;
optionalHeadersLength = ccnxCodecSchemaV1OptionalHeadersEncoder_Encode(optionalHeaderEncoder, packetDictionary);
return optionalHeadersLength;
}
/**
* CPI payload is simply a dump of the PAYLOAD dictionary entry.
*
* There are no inner TLVs of this message, so it is not encoded like a normal message
* with a call to ccnxCodecSchemaV1MessageEncoder_Encode(). Rather it is written here.
*
* @param [<#in#> | <#out#> | <#in,out#>] <#name#> <#description#>
*
* @return non-negative The number of bytes appended to the buffer
* @return negative An error
*
* Example:
* @code
* {
* <#example#>
* }
* @endcode
*/
static ssize_t
_encodeCPI(CCNxCodecTlvEncoder *cpiEncoder, CCNxTlvDictionary *packetDictionary)
{
// Optional Headers do not have a container, so just append them right to the buffer
size_t payloadLength = 0;
if (ccnxTlvDictionary_IsValueJson(packetDictionary,
CCNxCodecSchemaV1TlvDictionary_MessageFastArray_PAYLOAD)) {
PARCJSON *json = ccnxTlvDictionary_GetJson(packetDictionary,
CCNxCodecSchemaV1TlvDictionary_MessageFastArray_PAYLOAD);
if (json) {
char *jsonString = parcJSON_ToCompactString(json);
payloadLength = strlen(jsonString);
ccnxCodecTlvEncoder_AppendRawArray(cpiEncoder, payloadLength, (uint8_t * ) jsonString);
parcMemory_Deallocate((void **) &jsonString);
}
} else {
PARCBuffer *payload = ccnxTlvDictionary_GetBuffer(packetDictionary,
CCNxCodecSchemaV1TlvDictionary_MessageFastArray_PAYLOAD);
payloadLength = parcBuffer_Remaining(payload);
uint8_t *overlay = parcBuffer_Overlay(payload, 0);
ccnxCodecTlvEncoder_AppendRawArray(cpiEncoder, payloadLength, overlay);
}
return payloadLength;
}
/**
* Encode the CCNx Message
*
* <#Paragraphs Of Explanation#>
*
* @param [out] packetTypePtr The type to use for the PacketType based on the message type
*
* @retval non-negative the bytes appended to the encoder
* @retval negative An error
*
* Example:
* @code
* <#example#>
* @endcode
*/
static ssize_t
_encodeMessage(CCNxCodecTlvEncoder *packetEncoder, CCNxTlvDictionary *packetDictionary, CCNxCodecSchemaV1Types_PacketType *packetTypePtr)
{
ssize_t startPosition = ccnxCodecTlvEncoder_Position(packetEncoder);
ssize_t innerLength = -1;
// what kind of message is it? need this to set the packetTypePtr
if (ccnxTlvDictionary_IsInterest(packetDictionary)) {
*packetTypePtr = CCNxCodecSchemaV1Types_PacketType_Interest;
ccnxCodecTlvEncoder_AppendContainer(packetEncoder, CCNxCodecSchemaV1Types_MessageType_Interest, 0);
innerLength = ccnxCodecSchemaV1MessageEncoder_Encode(packetEncoder, packetDictionary);
} else if (ccnxTlvDictionary_IsInterestReturn(packetDictionary)) {
*packetTypePtr = CCNxCodecSchemaV1Types_PacketType_InterestReturn;
ccnxCodecTlvEncoder_AppendContainer(packetEncoder, CCNxCodecSchemaV1Types_MessageType_Interest, 0);
innerLength = ccnxCodecSchemaV1MessageEncoder_Encode(packetEncoder, packetDictionary);
} else if (ccnxTlvDictionary_IsContentObject(packetDictionary)) {
*packetTypePtr = CCNxCodecSchemaV1Types_PacketType_ContentObject;
ccnxCodecTlvEncoder_AppendContainer(packetEncoder, CCNxCodecSchemaV1Types_MessageType_ContentObject, 0);
innerLength = ccnxCodecSchemaV1MessageEncoder_Encode(packetEncoder, packetDictionary);
} else if (ccnxTlvDictionary_IsControl(packetDictionary)) {
*packetTypePtr = CCNxCodecSchemaV1Types_PacketType_Control;
ccnxCodecTlvEncoder_AppendContainer(packetEncoder, CCNxCodecSchemaV1Types_MessageType_Control, 0);
innerLength = _encodeCPI(packetEncoder, packetDictionary);
} else if (ccnxTlvDictionary_IsManifest(packetDictionary)) {
*packetTypePtr = CCNxCodecSchemaV1Types_PacketType_ContentObject;
ccnxCodecTlvEncoder_AppendContainer(packetEncoder, CCNxCodecSchemaV1Types_MessageType_Manifest, 0);
innerLength = ccnxCodecSchemaV1MessageEncoder_Encode(packetEncoder, packetDictionary);
}
if (innerLength >= 0) {
// For a 0 length message, we do not backup and erase the TLV container.
ccnxCodecTlvEncoder_SetContainerLength(packetEncoder, startPosition, innerLength);
ssize_t endPosition = ccnxCodecTlvEncoder_Position(packetEncoder);
innerLength = endPosition - startPosition;
} else {
CCNxCodecError *error = ccnxCodecError_Create(TLV_MISSING_MANDATORY, __func__, __LINE__, ccnxCodecTlvEncoder_Position(packetEncoder));
ccnxCodecTlvEncoder_SetError(packetEncoder, error);
ccnxCodecError_Release(&error);
}
return innerLength;
}
static ssize_t
_encodeValidationAlg(CCNxCodecTlvEncoder *encoder, CCNxTlvDictionary *packetDictionary)
{
ssize_t innerLength = 0;
// There must be a CryptoSuite in the packet to sign it.
// Temporary exception for Content Objects, which are all signed if the codec has a signer.
if (ccnxValidationFacadeV1_HasCryptoSuite(packetDictionary) || ccnxTlvDictionary_IsContentObject(packetDictionary)) {
ssize_t startPosition = ccnxCodecTlvEncoder_Position(encoder);
ccnxCodecTlvEncoder_AppendContainer(encoder, CCNxCodecSchemaV1Types_MessageType_ValidationAlg, 0);
innerLength = ccnxCodecSchemaV1ValidationEncoder_EncodeAlg(encoder, packetDictionary);
if (innerLength == 0) {
// backup and erase the container
ccnxCodecTlvEncoder_SetPosition(encoder, startPosition);
} else if (innerLength >= 0) {
ccnxCodecTlvEncoder_SetContainerLength(encoder, startPosition, innerLength);
ssize_t endPosition = ccnxCodecTlvEncoder_Position(encoder);
return endPosition - startPosition;
}
}
return innerLength;
}
static ssize_t
_encodeValidationPayload(CCNxCodecTlvEncoder *encoder, CCNxTlvDictionary *packetDictionary)
{
ssize_t startPosition = ccnxCodecTlvEncoder_Position(encoder);
ccnxCodecTlvEncoder_AppendContainer(encoder, CCNxCodecSchemaV1Types_MessageType_ValidationPayload, 0);
ssize_t innerLength = ccnxCodecSchemaV1ValidationEncoder_EncodePayload(encoder, packetDictionary);
if (innerLength == 0) {
// backup and erase the container
ccnxCodecTlvEncoder_SetPosition(encoder, startPosition);
} else if (innerLength > 0) {
ccnxCodecTlvEncoder_SetContainerLength(encoder, startPosition, innerLength);
ssize_t endPosition = ccnxCodecTlvEncoder_Position(encoder);
return endPosition - startPosition;
}
return innerLength;
}
// =====================================================
// Public API
CCNxCodecNetworkBufferIoVec *
ccnxCodecSchemaV1PacketEncoder_DictionaryEncode(CCNxTlvDictionary *packetDictionary, PARCSigner *signer)
{
CCNxCodecNetworkBufferIoVec *outputBuffer = NULL;
CCNxCodecTlvEncoder *packetEncoder = ccnxCodecTlvEncoder_Create();
if (signer) {
// ccnxCodecTlvEncoder_SetSigner(packetEncoder, signer);
}
ssize_t encodedLength = ccnxCodecSchemaV1PacketEncoder_Encode(packetEncoder, packetDictionary);
if (encodedLength > 0) {
ccnxCodecTlvEncoder_Finalize(packetEncoder);
outputBuffer = ccnxCodecTlvEncoder_CreateIoVec(packetEncoder);
}
trapUnexpectedStateIf(encodedLength < 0 && !ccnxCodecTlvEncoder_HasError(packetEncoder),
"Got error length but no error set");
assertFalse(ccnxCodecTlvEncoder_HasError(packetEncoder), "ENCODING ERROR")
{
printf("ERROR: %s\n", ccnxCodecError_ToString(ccnxCodecTlvEncoder_GetError(packetEncoder)));
ccnxTlvDictionary_Display(packetDictionary, 3);
}
ccnxCodecTlvEncoder_Destroy(&packetEncoder);
// return a reference counted copy so it won't be destroyed by ccnxCodecTlvEncoder_Destroy
return outputBuffer;
}
ssize_t
ccnxCodecSchemaV1PacketEncoder_Encode(CCNxCodecTlvEncoder *packetEncoder, CCNxTlvDictionary *packetDictionary)
{
ssize_t length = -1;
// We will need to go back and fixedup the headers
ssize_t fixedHeaderPosition = ccnxCodecTlvEncoder_Position(packetEncoder);
ssize_t fixedHeaderLength = _encodeFixedHeader(packetEncoder, packetDictionary, -1, 0, 0);
ssize_t optionalHeadersLength = _encodeOptionalHeaders(packetEncoder, packetDictionary);
if (optionalHeadersLength >= 0) {
ccnxCodecTlvEncoder_MarkSignatureStart(packetEncoder);
CCNxCodecSchemaV1Types_PacketType messageType = -1;
ssize_t messageLength = _encodeMessage(packetEncoder, packetDictionary, &messageType);
if (messageLength >= 0) {
// validation is optional, so it's ok if its 0 length
ssize_t validationAlgLength = _encodeValidationAlg(packetEncoder, packetDictionary);
ssize_t validationPayloadLength = 0;
if (validationAlgLength > 0) {
ccnxCodecTlvEncoder_MarkSignatureEnd(packetEncoder);
validationPayloadLength = _encodeValidationPayload(packetEncoder, packetDictionary);
}
if (validationAlgLength >= 0 && validationPayloadLength >= 0) {
// now fix up the fixed header
size_t endPosition = ccnxCodecTlvEncoder_Position(packetEncoder);
size_t headerLength = fixedHeaderLength + optionalHeadersLength;
size_t packetLength = headerLength + messageLength + validationAlgLength + validationPayloadLength;
// Will this work for InterestReturn? As long as _encodeMessage returns InterestReturn it
// will be ok.
int packetType = messageType;
ccnxCodecTlvEncoder_SetPosition(packetEncoder, fixedHeaderPosition);
_encodeFixedHeader(packetEncoder, packetDictionary, packetType, headerLength, packetLength);
ccnxCodecTlvEncoder_SetPosition(packetEncoder, endPosition);
length = endPosition - fixedHeaderPosition;
trapUnexpectedStateIf(packetLength != length, "packet length %zu not equal to measured length %zd", packetLength, length);
}
}
}
return length;
}
| 43.516456 | 142 | 0.731107 |
26853655ada1b18175bed55dd7fa18efe4ff1b54 | 1,339 | h | C | Pods/RHSocketKit/RHSocketKit/Core/Channel/RHSocketChannel.h | smithgoo/BaseProjectFrameWork | bfe69a564ba5398bf93a78c71929d04aa09e3a96 | [
"MIT"
] | null | null | null | Pods/RHSocketKit/RHSocketKit/Core/Channel/RHSocketChannel.h | smithgoo/BaseProjectFrameWork | bfe69a564ba5398bf93a78c71929d04aa09e3a96 | [
"MIT"
] | null | null | null | Pods/RHSocketKit/RHSocketKit/Core/Channel/RHSocketChannel.h | smithgoo/BaseProjectFrameWork | bfe69a564ba5398bf93a78c71929d04aa09e3a96 | [
"MIT"
] | null | null | null | //
// RHSocketChannel.h
// RHSocketKitDemo
//
// Created by zhuruhong on 15/12/15.
// Copyright © 2015年 zhuruhong. All rights reserved.
//
#import "RHSocketConnection.h"
#import "RHSocketCodecProtocol.h"
@class RHSocketChannel;
@protocol RHSocketChannelDelegate <NSObject>
- (void)channelOpened:(RHSocketChannel *)channel host:(NSString *)host port:(int)port;
- (void)channelClosed:(RHSocketChannel *)channel error:(NSError *)error;
- (void)channel:(RHSocketChannel *)channel received:(id<RHDownstreamPacket>)packet;
@end
/**
* 在RHSocketConnection基础上做封装,负责对socket中的二进制通讯数据做缓存、编码、解码处理。
*
* 1-需要有一个编码解码器,对数据块做封包和解包。很多人不理解这个,其实很简单。
* 比如一句话里面没有标点符号你怎么知道什么时候是结束什么时候开始呢
* 2-内部带有一个数据缓存,用于对数据的拼包。
* 发送网络数据时,一条数据会被切成多个网络包[不是我们上层协议中的概念],需要对收到的数据做合并,完整后才能正常解码。
*/
@interface RHSocketChannel : RHSocketConnection
@property (nonatomic, strong) id<RHSocketEncoderProtocol> encoder;
@property (nonatomic, strong) id<RHSocketDecoderProtocol> decoder;
/**
* socket connection的回调代理,查看RHSocketConnectionDelegate
*/
@property (nonatomic, weak) id<RHSocketChannelDelegate> delegate;
- (void)openConnection;
- (void)closeConnection;
- (void)asyncSendPacket:(id<RHUpstreamPacket>)packet;
- (void)writeInt8:(int8_t)param;
- (void)writeInt16:(int16_t)param;
- (void)writeInt32:(int32_t)param;
- (void)writeInt64:(int64_t)param;
@end
| 26.254902 | 86 | 0.769231 |
1e09c5fdde75d7605041258630a5577e60eb4ccc | 4,942 | c | C | tests/pam-util/fakepam-t.c | jhutz/rra-c-util | d32ac5ef4293989456a920503b0285f281cd1d3f | [
"MIT",
"Unlicense"
] | 5 | 2016-09-23T21:05:30.000Z | 2021-02-19T10:50:51.000Z | tests/pam-util/fakepam-t.c | jhutz/rra-c-util | d32ac5ef4293989456a920503b0285f281cd1d3f | [
"MIT",
"Unlicense"
] | 6 | 2018-09-11T01:51:57.000Z | 2022-01-17T16:22:00.000Z | tests/pam-util/fakepam-t.c | jhutz/rra-c-util | d32ac5ef4293989456a920503b0285f281cd1d3f | [
"MIT",
"Unlicense"
] | 3 | 2018-09-10T11:35:10.000Z | 2021-10-01T17:42:33.000Z | /*
* Fake PAM library test suite.
*
* This is not actually a test for the pam-util layer, but rather is a test
* for the trickier components of the fake PAM library that in turn is used to
* test the pam-util layer and PAM modules.
*
* The canonical version of this file is maintained in the rra-c-util package,
* which can be found at <https://www.eyrie.org/~eagle/software/rra-c-util/>.
*
* Written by Russ Allbery <eagle@eyrie.org>
* Copyright 2010, 2013
* The Board of Trustees of the Leland Stanford Junior University
*
* 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.
*
* SPDX-License-Identifier: MIT
*/
#include <config.h>
#include <portable/pam.h>
#include <portable/system.h>
#include <tests/fakepam/pam.h>
#include <tests/tap/basic.h>
int
main(void)
{
pam_handle_t *pamh;
struct pam_conv conv = {NULL, NULL};
char **env;
size_t i;
/*
* Skip this test if the native PAM library doesn't support a PAM
* environment, since we "break" pam_putenv to mirror the native behavior
* in that case.
*/
#ifndef HAVE_PAM_GETENV
skip_all("system doesn't support PAM environment");
#endif
plan(33);
/* Basic environment manipulation. */
if (pam_start("test", NULL, &conv, &pamh) != PAM_SUCCESS)
sysbail("Fake PAM initialization failed");
is_int(PAM_BAD_ITEM, pam_putenv(pamh, "TEST"), "delete when NULL");
ok(pam_getenv(pamh, "TEST") == NULL, "getenv when NULL");
env = pam_getenvlist(pamh);
ok(env != NULL, "getenvlist when NULL returns non-NULL");
if (env == NULL)
bail("pam_getenvlist returned NULL");
is_string(NULL, env[0], "...but first element is NULL");
for (i = 0; env[i] != NULL; i++)
free(env[i]);
free(env);
/* putenv and getenv. */
is_int(PAM_SUCCESS, pam_putenv(pamh, "TEST=foo"), "putenv TEST");
is_string("foo", pam_getenv(pamh, "TEST"), "getenv TEST");
is_int(PAM_SUCCESS, pam_putenv(pamh, "FOO=bar"), "putenv FOO");
is_int(PAM_SUCCESS, pam_putenv(pamh, "BAR=baz"), "putenv BAR");
is_string("foo", pam_getenv(pamh, "TEST"), "getenv TEST");
is_string("bar", pam_getenv(pamh, "FOO"), "getenv FOO");
is_string("baz", pam_getenv(pamh, "BAR"), "getenv BAR");
ok(pam_getenv(pamh, "BAZ") == NULL, "getenv BAZ is NULL");
/* Replacing and deleting environment variables. */
is_int(PAM_BAD_ITEM, pam_putenv(pamh, "BAZ"), "putenv nonexistent delete");
is_int(PAM_SUCCESS, pam_putenv(pamh, "FOO=foo"), "putenv replace");
is_int(PAM_SUCCESS, pam_putenv(pamh, "FOON=bar=n"), "putenv prefix");
is_string("foo", pam_getenv(pamh, "FOO"), "getenv FOO");
is_string("bar=n", pam_getenv(pamh, "FOON"), "getenv FOON");
is_int(PAM_BAD_ITEM, pam_putenv(pamh, "FO"), "putenv delete FO");
is_int(PAM_SUCCESS, pam_putenv(pamh, "FOO"), "putenv delete FOO");
ok(pam_getenv(pamh, "FOO") == NULL, "getenv FOO is NULL");
is_string("bar=n", pam_getenv(pamh, "FOON"), "getenv FOON");
is_string("baz", pam_getenv(pamh, "BAR"), "getenv BAR");
/* pam_getenvlist. */
env = pam_getenvlist(pamh);
ok(env != NULL, "getenvlist not NULL");
if (env == NULL)
bail("pam_getenvlist returned NULL");
is_string("TEST=foo", env[0], "getenvlist TEST");
is_string("BAR=baz", env[1], "getenvlist BAR");
is_string("FOON=bar=n", env[2], "getenvlist FOON");
ok(env[3] == NULL, "getenvlist length");
for (i = 0; env[i] != NULL; i++)
free(env[i]);
free(env);
is_int(PAM_SUCCESS, pam_putenv(pamh, "FOO=foo"), "putenv FOO");
is_string("TEST=foo", pamh->environ[0], "pamh environ TEST");
is_string("BAR=baz", pamh->environ[1], "pamh environ BAR");
is_string("FOON=bar=n", pamh->environ[2], "pamh environ FOON");
is_string("FOO=foo", pamh->environ[3], "pamh environ FOO");
ok(pamh->environ[4] == NULL, "pamh environ length");
pam_end(pamh, 0);
return 0;
}
| 40.508197 | 79 | 0.67159 |
d82ac3918d0476c12d6d03c64d701304aecd3cbc | 804 | h | C | FCB.h | DennisEgan/mobile_filesystem | 89f5b615f9c56783a8fc64c637a24e04b3e2d031 | [
"MIT"
] | null | null | null | FCB.h | DennisEgan/mobile_filesystem | 89f5b615f9c56783a8fc64c637a24e04b3e2d031 | [
"MIT"
] | null | null | null | FCB.h | DennisEgan/mobile_filesystem | 89f5b615f9c56783a8fc64c637a24e04b3e2d031 | [
"MIT"
] | null | null | null | /*
* Directory.h
*
* Header file for ATOS FS File Control Block class
*
* Lead author:
* Justin Lesko
*
* Contributors:
* Dennis Egan
*/
#include <string>
#include <iostream>
using namespace std;
// using std::string;
#ifndef FCB_H
#define FCB_H
class FCB{
public:
FCB();
FCB(string name);
FCB(const FCB &);
~FCB();
const FCB& operator=(const FCB &);
FCB(int, int, string);
string getFileName();
int getBlockPointer();
void setBlockPointer(int);
int getSize();
void setSize(int);
int getBlockSize();
void setBlockSize(int);
int getFileEnd();
void setFileEnd(int);
bool setMode(char);
char getMode();
void setFileName(string);
void print();
private:
char mode;
int size;
int blockSize;
int blockPointer;
int fileEnd;
string fileName;
};
#endif
| 12.761905 | 51 | 0.666667 |
1b42b5d82bb8ed755cd33eee569490f7578e47f5 | 320 | h | C | MTKit/MTKit/Category/UIKit/UIBarButtonItem/UIBarButtonItem+MTExt.h | michaelyht/MTKit | ba44f5e9c77980fc45234783f4d1c0cecd637995 | [
"MIT"
] | null | null | null | MTKit/MTKit/Category/UIKit/UIBarButtonItem/UIBarButtonItem+MTExt.h | michaelyht/MTKit | ba44f5e9c77980fc45234783f4d1c0cecd637995 | [
"MIT"
] | null | null | null | MTKit/MTKit/Category/UIKit/UIBarButtonItem/UIBarButtonItem+MTExt.h | michaelyht/MTKit | ba44f5e9c77980fc45234783f4d1c0cecd637995 | [
"MIT"
] | null | null | null | //
// UIBarButtonItem+MTExt.h
// MTKit
//
// Created by Michael on 2018/1/17.
// Copyright © 2018年 michaelyu. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIBarButtonItem (MTExt)
@property (nullable, nonatomic, copy) void (^mt_actionBlock)(id);
@end
NS_ASSUME_NONNULL_END
| 16 | 65 | 0.728125 |
18b4fcb8de1aa70426875f81eca6d7892611c819 | 773 | h | C | Example/Pods/Headers/Public/ABMSoundCloudAPI/SoundCloudLoginWebViewController.h | andresbrun/ABMSoundCloudAPI | 2276c54a5f82116769fe1d734b1a631a16ccc4b9 | [
"MIT"
] | 57 | 2015-03-15T18:59:58.000Z | 2020-06-18T13:52:18.000Z | Example/Pods/Headers/Private/ABMSoundCloudAPI/SoundCloudLoginWebViewController.h | andresbrun/ABMSoundCloudAPI | 2276c54a5f82116769fe1d734b1a631a16ccc4b9 | [
"MIT"
] | 9 | 2015-03-24T19:25:28.000Z | 2016-10-12T11:01:17.000Z | Example/Pods/Headers/Public/ABMSoundCloudAPI/SoundCloudLoginWebViewController.h | andresbrun/ABMSoundCloudAPI | 2276c54a5f82116769fe1d734b1a631a16ccc4b9 | [
"MIT"
] | 25 | 2015-03-23T16:47:26.000Z | 2021-05-15T14:56:21.000Z | //
// SoundCloudLoginWebViewController.h
// ABMSoundCloudAPI
//
// Created by Andres Brun on 08/03/15.
// Copyright (c) 2015 Brun's Software. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SoundCloudLoginWebViewController: UIViewController
+ (nonnull UINavigationController *)instantiateWithLoginURL:(nonnull NSString *)loginURL
redirectURL:(nonnull NSString *)redirectURL
resultBlock:(void (^)(BOOL result, NSString *code))resultBlock;
@property (strong, nonatomic, nonnull) NSString *scLoginURL;
@property (strong, nonatomic, nonnull) NSString *redirectURL;
@property (copy, nonatomic) void (^resultBlock)(BOOL success, NSString * _Nullable code);
@end
| 35.136364 | 111 | 0.675291 |
49fccebfaa2b928c0c1513c7ab2a039748e0d8a9 | 3,094 | h | C | applications/physbam/physbam-lib/External_Libraries/Archives/glux/include/glux_GL_EXT_paletted_texture.h | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 20 | 2017-07-03T19:09:09.000Z | 2021-09-10T02:53:56.000Z | applications/physbam/physbam-lib/External_Libraries/Archives/glux/include/glux_GL_EXT_paletted_texture.h | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | null | null | null | applications/physbam/physbam-lib/External_Libraries/Archives/glux/include/glux_GL_EXT_paletted_texture.h | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 9 | 2017-09-17T02:05:06.000Z | 2020-01-31T00:12:01.000Z |
// --------------------------------------------------------
// Generated by glux perl script (Wed Mar 31 17:19:32 2004)
//
// Sylvain Lefebvre - 2002 - Sylvain.Lefebvre@imag.fr
// --------------------------------------------------------
#include "glux_no_redefine.h"
#include "glux_ext_defs.h"
#include "gluxLoader.h"
#include "gluxPlugin.h"
// --------------------------------------------------------
// Plugin creation
// --------------------------------------------------------
#ifndef __GLUX_GL_EXT_paletted_texture__
#define __GLUX_GL_EXT_paletted_texture__
GLUX_NEW_PLUGIN(GL_EXT_paletted_texture);
// --------------------------------------------------------
// Extension conditions
// --------------------------------------------------------
// --------------------------------------------------------
// Extension defines
// --------------------------------------------------------
#ifndef GL_COLOR_INDEX1_EXT
# define GL_COLOR_INDEX1_EXT 0x80E2
#endif
#ifndef GL_COLOR_INDEX2_EXT
# define GL_COLOR_INDEX2_EXT 0x80E3
#endif
#ifndef GL_COLOR_INDEX4_EXT
# define GL_COLOR_INDEX4_EXT 0x80E4
#endif
#ifndef GL_COLOR_INDEX8_EXT
# define GL_COLOR_INDEX8_EXT 0x80E5
#endif
#ifndef GL_COLOR_INDEX12_EXT
# define GL_COLOR_INDEX12_EXT 0x80E6
#endif
#ifndef GL_COLOR_INDEX16_EXT
# define GL_COLOR_INDEX16_EXT 0x80E7
#endif
#ifndef GL_TEXTURE_INDEX_SIZE_EXT
# define GL_TEXTURE_INDEX_SIZE_EXT 0x80ED
#endif
// --------------------------------------------------------
// Extension gl function typedefs
// --------------------------------------------------------
#ifndef __GLUX__GLFCT_glColorTableEXT
typedef void (APIENTRYP PFNGLUXCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
#endif
#ifndef __GLUX__GLFCT_glGetColorTableEXT
typedef void (APIENTRYP PFNGLUXGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *data);
#endif
#ifndef __GLUX__GLFCT_glGetColorTableParameterivEXT
typedef void (APIENTRYP PFNGLUXGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
#endif
#ifndef __GLUX__GLFCT_glGetColorTableParameterfvEXT
typedef void (APIENTRYP PFNGLUXGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
#endif
// --------------------------------------------------------
// Extension gl functions
// --------------------------------------------------------
namespace glux {
#ifndef __GLUX__GLFCT_glColorTableEXT
extern PFNGLUXCOLORTABLEEXTPROC glColorTableEXT;
#endif
#ifndef __GLUX__GLFCT_glGetColorTableEXT
extern PFNGLUXGETCOLORTABLEEXTPROC glGetColorTableEXT;
#endif
#ifndef __GLUX__GLFCT_glGetColorTableParameterivEXT
extern PFNGLUXGETCOLORTABLEPARAMETERIVEXTPROC glGetColorTableParameterivEXT;
#endif
#ifndef __GLUX__GLFCT_glGetColorTableParameterfvEXT
extern PFNGLUXGETCOLORTABLEPARAMETERFVEXTPROC glGetColorTableParameterfvEXT;
#endif
} // namespace glux
// --------------------------------------------------------
#endif
// --------------------------------------------------------
| 38.197531 | 153 | 0.606012 |
638e0cd4cd12cb5f5109accae14f2fe295054862 | 6,004 | h | C | components/safe_browsing/base_ui_manager.h | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | components/safe_browsing/base_ui_manager.h | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | components/safe_browsing/base_ui_manager.h | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2016 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 COMPONENTS_SAFE_BROWSING_BASE_UI_MANAGER_H_
#define COMPONENTS_SAFE_BROWSING_BASE_UI_MANAGER_H_
#include <string>
#include <vector>
#include "base/bind_helpers.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/time/time.h"
#include "components/security_interstitials/content/unsafe_resource.h"
class GURL;
namespace content {
class NavigationEntry;
class WebContents;
} // namespace content
namespace history {
class HistoryService;
} // namespace history
namespace safe_browsing {
// Construction needs to happen on the main thread.
class BaseUIManager
: public base::RefCountedThreadSafe<BaseUIManager> {
public:
typedef security_interstitials::UnsafeResource UnsafeResource;
BaseUIManager();
// Called to stop or shutdown operations on the io_thread. This may be called
// multiple times during the life of the UIManager. Should be called
// on IO thread. If shutdown is true, the manager is disabled permanently.
// This currently is a no-op in the base class.
virtual void StopOnIOThread(bool shutdown);
// Called on the UI thread to display an interstitial page.
// |url| is the url of the resource that matches a safe browsing list.
// If the request contained a chain of redirects, |url| is the last url
// in the chain, and |original_url| is the first one (the root of the
// chain). Otherwise, |original_url| = |url|.
virtual void DisplayBlockingPage(const UnsafeResource& resource);
// Log the user perceived delay caused by SafeBrowsing. This delay is the time
// delta starting from when we would have started reading data from the
// network, and ending when the SafeBrowsing check completes indicating that
// the current page is 'safe'.
virtual void LogPauseDelay(base::TimeDelta time);
// This is a no-op in the base class, but should be overridden to send threat
// details. Called on the IO thread by the ThreatDetails with the serialized
// protocol buffer.
virtual void SendSerializedThreatDetails(const std::string& serialized);
// This is a no-op in the base class, but should be overridden to report hits
// to the unsafe contents (malware, phishing, unsafe download URL)
// to the server. Can only be called on UI thread.
virtual void MaybeReportSafeBrowsingHit(
const safe_browsing::HitReport& hit_report);
// A convenience wrapper method for IsUrlWhitelistedOrPendingForWebContents.
virtual bool IsWhitelisted(const UnsafeResource& resource);
// Checks if we already displayed or are displaying an interstitial
// for the top-level site |url| in a given WebContents. If
// |whitelist_only|, it returns true only if the user chose to ignore
// the interstitial. Otherwise, it returns true if an interstitial for
// |url| is already displaying *or* if the user has seen an
// interstitial for |url| before in this WebContents and proceeded
// through it. Called on the UI thread.
//
// If the resource was found in the whitelist or pending for the
// whitelist, |threat_type| will be set to the SBThreatType for which
// the URL was first whitelisted.
virtual bool IsUrlWhitelistedOrPendingForWebContents(
const GURL& url,
bool is_subresource,
content::NavigationEntry* entry,
content::WebContents* web_contents,
bool whitelist_only,
SBThreatType* threat_type);
// The blocking page for |web_contents| on the UI thread has
// completed, with |proceed| set to true if the user has chosen to
// proceed through the blocking page and false
// otherwise. |web_contents| is the WebContents that was displaying
// the blocking page. |main_frame_url| is the top-level URL on which
// the blocking page was displayed. If |proceed| is true,
// |main_frame_url| is whitelisted so that the user will not see
// another warning for that URL in this WebContents.
virtual void OnBlockingPageDone(const std::vector<UnsafeResource>& resources,
bool proceed,
content::WebContents* web_contents,
const GURL& main_frame_url);
virtual const std::string app_locale() const;
virtual history::HistoryService* history_service(
content::WebContents* web_contents);
// The default safe page when there is no entry in the history to go back to.
// e.g. about::blank page, or chrome's new tab page.
virtual const GURL default_safe_page() const;
protected:
virtual ~BaseUIManager();
// Updates the whitelist URL set for |web_contents|. Called on the UI thread.
void AddToWhitelistUrlSet(const GURL& whitelist_url,
content::WebContents* web_contents,
bool is_pending,
SBThreatType threat_type);
// This is a no-op that should be overridden to call protocol manager on IO
// thread to report hits of unsafe contents.
virtual void ReportSafeBrowsingHitOnIOThread(
const safe_browsing::HitReport& hit_report);
// Removes |whitelist_url| from the pending whitelist for
// |web_contents|. Called on the UI thread.
void RemoveFromPendingWhitelistUrlSet(const GURL& whitelist_url,
content::WebContents* web_contents);
// Ensures that |web_contents| has its whitelist set in its userdata
static void EnsureWhitelistCreated(content::WebContents* web_contents);
// Returns the URL that should be used in a WhitelistUrlSet for the given
// |resource|.
static GURL GetMainFrameWhitelistUrlForResource(
const security_interstitials::UnsafeResource& resource);
private:
friend class base::RefCountedThreadSafe<BaseUIManager>;
DISALLOW_COPY_AND_ASSIGN(BaseUIManager);
};
} // namespace safe_browsing
#endif // COMPONENTS_SAFE_BROWSING_BASE_UI_MANAGER_H_
| 40.567568 | 80 | 0.730513 |
6f9e4fb8d3f46a68cf7e7a6590e9511492e72b34 | 424 | h | C | src/make/bibutils_6.10/lib/title.h | Proximify/bibutils | b5a99706cc5903e4bdf949c47772b34fad6cf940 | [
"MIT"
] | null | null | null | src/make/bibutils_6.10/lib/title.h | Proximify/bibutils | b5a99706cc5903e4bdf949c47772b34fad6cf940 | [
"MIT"
] | null | null | null | src/make/bibutils_6.10/lib/title.h | Proximify/bibutils | b5a99706cc5903e4bdf949c47772b34fad6cf940 | [
"MIT"
] | null | null | null | /*
* title.h
*
* process titles into title/subtitle pairs for MODS
*
* Copyright (c) Chris Putnam 2004-2019
*
* Source code released under the GPL verison 2
*
*/
#ifndef TITLE_H
#define TITLE_H
#include "str.h"
#include "fields.h"
int title_process( fields *info, const char *tag, const char *value, int level, unsigned char nosplittitle );
void title_combine( str *fullttl, str *mainttl, str *subttl );
#endif
| 20.190476 | 110 | 0.707547 |
9d98ade64855455bca930d23b23248970c56e4bc | 668 | c | C | RAVL2/CCMath/cfit/pplsq.c | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/CCMath/cfit/pplsq.c | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/CCMath/cfit/pplsq.c | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | /* pplsq.c CCMATH mathematics library source code.
*
* Copyright (C) 2000 Daniel A. Atkinson All rights reserved.
* This code may be redistributed under the terms of the GNU library
* public license (LGPL). ( See the lgpl.license file for details.)
* ------------------------------------------------------------------------
*/
#include <stdlib.h>
#include "ccmath/orpol.h"
#include "ccmath/ccmath.h"
double pplsq(double *x,double *y,int n,double *bc,int m)
{ Opol *c; double *ss,sq;
c=(Opol *)calloc(m,sizeof(Opol));
ss=(double *)calloc(m,sizeof(double));
plsq(x,y,n,c,ss,m);
psqcf(bc,c,m);
sq=ss[m-1];
free(c); free(ss);
return sq;
}
| 31.809524 | 75 | 0.585329 |
c4c79ad75b190184bd0278284ef485835ff3de30 | 3,188 | h | C | src/theory/arith/callbacks.h | HasibShakur/CVC4 | 7a303390a65fd395a53085833d504acc312dc6a6 | [
"BSL-1.0"
] | null | null | null | src/theory/arith/callbacks.h | HasibShakur/CVC4 | 7a303390a65fd395a53085833d504acc312dc6a6 | [
"BSL-1.0"
] | null | null | null | src/theory/arith/callbacks.h | HasibShakur/CVC4 | 7a303390a65fd395a53085833d504acc312dc6a6 | [
"BSL-1.0"
] | null | null | null | /********************* */
/*! \file callbacks.h
** \verbatim
** Original author: Tim King
** Major contributors: none
** Minor contributors (to current version): none
** This file is part of the CVC4 project.
** Copyright (c) 2009-2013 New York University and The University of Iowa
** See the file COPYING in the top-level source directory for licensing
** information.\endverbatim
**
** \brief [[ Add one-line brief description here ]]
**
** [[ Add lengthier description here ]]
** \todo document this file
**/
#pragma once
#include "expr/node.h"
#include "util/rational.h"
#include "theory/arith/theory_arith_private_forward.h"
#include "theory/arith/arithvar.h"
#include "theory/arith/bound_counts.h"
#include "theory/arith/constraint_forward.h"
namespace CVC4 {
namespace theory {
namespace arith {
/**
* ArithVarCallBack provides a mechanism for agreeing on callbacks while
* breaking mutual recursion inclusion order problems.
*/
class ArithVarCallBack {
public:
virtual void operator()(ArithVar x) = 0;
};
/**
* Requests arithmetic variables for internal use,
* and releases arithmetic variables that are no longer being used.
*/
class ArithVarMalloc {
public:
virtual ArithVar request() = 0;
virtual void release(ArithVar v) = 0;
};
class TNodeCallBack {
public:
virtual void operator()(TNode n) = 0;
};
class NodeCallBack {
public:
virtual void operator()(Node n) = 0;
};
class RationalCallBack {
public:
virtual Rational operator()() const = 0;
};
class SetupLiteralCallBack : public TNodeCallBack {
private:
TheoryArithPrivate& d_arith;
public:
SetupLiteralCallBack(TheoryArithPrivate& ta);
void operator()(TNode lit);
};
class DeltaComputeCallback : public RationalCallBack {
private:
const TheoryArithPrivate& d_ta;
public:
DeltaComputeCallback(const TheoryArithPrivate& ta);
Rational operator()() const;
};
class BasicVarModelUpdateCallBack : public ArithVarCallBack{
private:
TheoryArithPrivate& d_ta;
public:
BasicVarModelUpdateCallBack(TheoryArithPrivate& ta);
void operator()(ArithVar x);
};
class TempVarMalloc : public ArithVarMalloc {
private:
TheoryArithPrivate& d_ta;
public:
TempVarMalloc(TheoryArithPrivate& ta);
ArithVar request();
void release(ArithVar v);
};
class RaiseConflict {
private:
TheoryArithPrivate& d_ta;
ConstraintCPVec& d_construction;
public:
RaiseConflict(TheoryArithPrivate& ta, ConstraintCPVec& d_construction);
/* Adds a constraint to the constraint under construction. */
void addConstraint(ConstraintCP c);
/* Turns the vector under construction into a conflict */
void commitConflict();
void sendConflict(const ConstraintCPVec& vec);
/* If you are not an equality engine, don't use this! */
void blackBoxConflict(Node n);
};
class BoundCountingLookup {
private:
TheoryArithPrivate& d_ta;
public:
BoundCountingLookup(TheoryArithPrivate& ta);
const BoundsInfo& boundsInfo(ArithVar basic) const;
BoundCounts atBounds(ArithVar basic) const;
BoundCounts hasBounds(ArithVar basic) const;
};
}/* CVC4::theory::arith namespace */
}/* CVC4::theory namespace */
}/* CVC4 namespace */
| 24.335878 | 80 | 0.726474 |
8b03b9b0fca0d75378ff0a5fa4773516400a9a86 | 247 | c | C | reverse.c | Galaxies99/VST-Tutorial | 8af993ec6342b84dd916fb79ad39e9543c979397 | [
"MIT"
] | 1 | 2020-02-23T04:10:28.000Z | 2020-02-23T04:10:28.000Z | reverse.c | Galaxies99/VST-Tutorial | 8af993ec6342b84dd916fb79ad39e9543c979397 | [
"MIT"
] | null | null | null | reverse.c | Galaxies99/VST-Tutorial | 8af993ec6342b84dd916fb79ad39e9543c979397 | [
"MIT"
] | null | null | null | #include <stddef.h>
struct list {unsigned head; struct list *tail;};
struct list *reverse (struct list *p) {
struct list *w, *t, *v;
w = NULL;
v = p;
while (v) {
t = v->tail;
v->tail = w;
w = v;
v = t;
}
return w;
}
| 13.722222 | 48 | 0.51417 |
a06bd62914b2d07f0793403a83dd63fcad92f410 | 693 | h | C | MYKLine_Demo/MYKLine_Demo/MYKLine/MYKLineModel/MYIndexModel/MYMainIndexModel/MY_BOLL_Model.h | swift-joking/KLine | 534b73e40a604f3836dbf463a039198fe25af99e | [
"MIT"
] | 2 | 2017-12-20T09:47:14.000Z | 2018-09-01T12:07:04.000Z | MYKLine_Demo/MYKLine_Demo/MYKLine/MYKLineModel/MYIndexModel/MYMainIndexModel/MY_BOLL_Model.h | swift-joking/KLine | 534b73e40a604f3836dbf463a039198fe25af99e | [
"MIT"
] | null | null | null | MYKLine_Demo/MYKLine_Demo/MYKLine/MYKLineModel/MYIndexModel/MYMainIndexModel/MY_BOLL_Model.h | swift-joking/KLine | 534b73e40a604f3836dbf463a039198fe25af99e | [
"MIT"
] | null | null | null | //
// MY_BOLL_Model.h
// XinShengInternational
//
// Created by michelle on 2017/9/27.
// Copyright © 2017年 michelle. All rights reserved.
//
#import <Foundation/Foundation.h>
/*
布林线(Boll)指标是通过计算股价的“标准差”,再求股价的“信赖区间”。该指标在图形上画出三条线,其中上下两条线可以分别看成是股价的压力线和支撑线,而在两条线之间还有一条股价平均线,布林线指标的参数最好设为20。一般来说,股价会运行在压力线和支撑线所形成的通道中。
*/
@interface MY_BOLL_Model : NSObject
@property (nonatomic, assign) double MID;
@property (nonatomic, assign) double UPPER;
@property (nonatomic, assign) double LOWER;
@property (nonatomic, assign) double MID_Height;
@property (nonatomic, assign) double UPPER_Height;
@property (nonatomic, assign) double LOWER_Height;
@property (nonatomic, assign) double Width;
@end
| 26.653846 | 134 | 0.770563 |
6ab84fe0b7b219ba6a99b40afe2a2e338856f0b1 | 2,910 | h | C | src/base/databases_file.h | eido5/cubrid | f32dbe7cb90f096035c255d7b5f348438bbb5830 | [
"Apache-2.0",
"BSD-3-Clause"
] | 253 | 2016-03-12T01:03:42.000Z | 2022-03-14T08:24:39.000Z | src/base/databases_file.h | eido5/cubrid | f32dbe7cb90f096035c255d7b5f348438bbb5830 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1,124 | 2016-03-31T03:48:58.000Z | 2022-03-31T23:44:04.000Z | src/base/databases_file.h | eido5/cubrid | f32dbe7cb90f096035c255d7b5f348438bbb5830 | [
"Apache-2.0",
"BSD-3-Clause"
] | 268 | 2016-03-02T06:48:44.000Z | 2022-03-04T05:17:24.000Z | /*
* Copyright 2008 Search Solution Corporation
* Copyright 2016 CUBRID 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.
*
*/
/*
* databases_file.h - Configuration file parser
*
*/
#ifndef _DATABASES_FILE_H_
#define _DATABASES_FILE_H_
#ident "$Id$"
#if !defined (DO_NOT_USE_CUBRIDENV)
/* Name of the environment variable pointing to database file */
#define DATABASES_ENVNAME "DATABASES"
#endif
#if defined(WINDOWS)
#define SECTION_START_CHAR '['
#define SECTION_END_CHAR ']'
#endif /* WINDOWS */
/* name of the database file */
#define DATABASES_FILENAME "databases.txt"
/* max num of db-hosts */
#define MAX_NUM_DB_HOSTS 32
/*
* DB_INFO
*
* Note: This is a descriptor structure for databases in the currently
* accessible directory file.
*/
typedef struct database_info DB_INFO;
struct database_info
{
char *name;
char *pathname;
char **hosts;
char *logpath;
char *lobpath;
DB_INFO *next;
int num_hosts;
};
extern char *cfg_os_working_directory (void);
extern char *cfg_maycreate_get_directory_filename (char *buffer);
extern int cfg_read_directory (DB_INFO ** info_p, bool write_flag);
extern void cfg_write_directory (const DB_INFO * databases);
extern int cfg_read_directory_ex (int vdes, DB_INFO ** info_p, bool write_flag);
extern void cfg_write_directory_ex (int vdes, const DB_INFO * databases);
extern void cfg_free_directory (DB_INFO * databases);
#if defined(CUBRID_DEBUG)
extern void cfg_dump_directory (const DB_INFO * databases);
#endif
extern void cfg_update_db (DB_INFO * db_info_p, const char *path, const char *logpath, const char *lobpath,
const char *host);
extern DB_INFO *cfg_new_db (const char *name, const char *path, const char *logpath, const char *lobpath,
const char **hosts);
extern DB_INFO *cfg_find_db_list (DB_INFO * dir, const char *name);
extern DB_INFO *cfg_add_db (DB_INFO ** dir, const char *name, const char *path, const char *logpath,
const char *lobpath, const char *host);
extern DB_INFO *cfg_find_db (const char *db_name);
extern bool cfg_delete_db (DB_INFO ** dir_info_p, const char *name);
extern char **cfg_get_hosts (const char *prim_host, int *count, bool include_local_host);
extern void cfg_free_hosts (char **host_array);
extern char *cfg_create_host_list (const char *primary_host_name, bool append_local_host, int *cnt);
#endif /* _DATABASES_FILE_H_ */
| 31.290323 | 107 | 0.746392 |
6b691e16e35a674d18c7e62c0c620555828869ae | 309 | h | C | ZYChat-EaseMob/ZYChat/Square/GroupCommonUI/UITableViewCell/Cell/GJGCInformationGroupShowCell.h | AnriKaede/ZY2017IM | 41dbe5fea9db735ae8dbf5b08351eea301d09276 | [
"MIT"
] | 1,323 | 2015-07-22T03:52:00.000Z | 2022-03-16T07:54:28.000Z | ZYChat-EaseMob/ZYChat/Square/GroupCommonUI/UITableViewCell/Cell/GJGCInformationGroupShowCell.h | AnriKaede/ZY2017IM | 41dbe5fea9db735ae8dbf5b08351eea301d09276 | [
"MIT"
] | 16 | 2015-08-13T06:43:03.000Z | 2019-09-24T09:01:31.000Z | ZYChat-EaseMob/ZYChat/Square/GroupCommonUI/UITableViewCell/Cell/GJGCInformationGroupShowCell.h | AnriKaede/ZY2017IM | 41dbe5fea9db735ae8dbf5b08351eea301d09276 | [
"MIT"
] | 451 | 2015-07-22T05:59:34.000Z | 2021-08-30T02:56:42.000Z | //
// GJGCInformationGroupShowCell.h
// ZYChat
//
// Created by ZYVincent QQ:1003081775 on 14-11-6.
// Copyright (c) 2014年 ZYV. All rights reserved.
//
#import "GJGCInformationTextCell.h"
#import "GJGCInformationGroupShowItem.h"
@interface GJGCInformationGroupShowCell : GJGCInformationTextCell
@end
| 18.176471 | 65 | 0.760518 |
592b63b18c49c9c7f5c03d98fe8ad5d61a4e990e | 673 | h | C | Example/Pods/JumioMobileSDK/JumioMobileSDK-3.9.5/JumioCore.framework/PrivateHeaders/JMScanMockHelper.h | astro-santiago-moreno/APKYCPod | f4d5b7d3aba74482773c058e86efb17a9d32951e | [
"MIT"
] | null | null | null | Example/Pods/JumioMobileSDK/JumioMobileSDK-3.9.5/JumioCore.framework/PrivateHeaders/JMScanMockHelper.h | astro-santiago-moreno/APKYCPod | f4d5b7d3aba74482773c058e86efb17a9d32951e | [
"MIT"
] | null | null | null | Example/Pods/JumioMobileSDK/JumioMobileSDK-3.9.5/JumioCore.framework/PrivateHeaders/JMScanMockHelper.h | astro-santiago-moreno/APKYCPod | f4d5b7d3aba74482773c058e86efb17a9d32951e | [
"MIT"
] | null | null | null | //
// JMScanMockHelper.h
//
// Copyright © 2021 Jumio Corporation. All rights reserved.
//
#import <Foundation/Foundation.h>
@class JMCaptureSessionManager;
__attribute__((visibility("default"))) @interface JMScanMockHelper : NSObject
- (instancetype _Nullable) initWithCaptureSessionManager:(JMCaptureSessionManager * _Nonnull)captureSessionManager;
- (BOOL) shouldDisplayRecordButton;
- (BOOL) isExtendedDebuggingEnabled;
- (NSString * _Nullable) videoMockWriterPath;
- (void) addRecordButtonToView:(UIView * _Nonnull)view;
- (void) recordButtonTapped;
- (void) stopRecording;
- (void) startMocking;
- (void) stopMocking;
- (NSString * _Nullable) mockPath;
@end
| 24.925926 | 115 | 0.771174 |
df65049fc010cbf24e2127a1eae5c2620f971d08 | 6,614 | c | C | u-boot-2011.09/drivers/p2wi/p2wi.c | swingflip/C64_mini_UBOOT | 69da654f6e72134df8f4efccc9240c6aaf8ccc7a | [
"Apache-2.0"
] | null | null | null | u-boot-2011.09/drivers/p2wi/p2wi.c | swingflip/C64_mini_UBOOT | 69da654f6e72134df8f4efccc9240c6aaf8ccc7a | [
"Apache-2.0"
] | null | null | null | u-boot-2011.09/drivers/p2wi/p2wi.c | swingflip/C64_mini_UBOOT | 69da654f6e72134df8f4efccc9240c6aaf8ccc7a | [
"Apache-2.0"
] | null | null | null | /*
* (C) Copyright 2007-2013
* Allwinner Technology Co., Ltd. <www.allwinnertech.com>
* Jerry Wang <wangflord@allwinnertech.com>
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <asm/io.h>
#include <asm/arch/p2wi.h>
static void p2wi_set_pmu_mode(u32 slave_addr, u32 reg, u32 data);
static void p2wi_set_clk(u32 sck);
static s32 p2wi_wait_state(void);
s32 p2wi_init(void)
{
uint reg_val;
#ifdef CONFIG_SUN6I_FPGA
//PG[24][25] used as p2wi SCK and SDA under FPGA platform.
writel(0x33, 0x01c20800 + 0xE4);
#endif
reg_val = readl(0x1f01400 + 0x28);
reg_val |= (1 << 0);
writel(reg_val, 0x1f01400 + 0x28);
reg_val = readl(0x1f02C00 + 0x00);
reg_val &= ~((0x07 << 0) | (0x07 << 4));
reg_val |= ((0x03 << 0) | (0x03 << 4));
writel(reg_val, 0x1f02C00 + 0x00);
//enbale twi clock, set reset as de-assert state.
reg_val = readl(0x1f01400 + 0x28);
reg_val |= (1 << 3);
writel(reg_val, 0x1f01400 + 0x28);
reg_val = readl(0x1f01400 + 0xb0);
reg_val |= (1 << 3);
writel(reg_val, 0x1f01400 + 0xb0);
//reset p2wi controller
writel(P2WI_SOFT_RST, P2WI_REG_CTRL);
//set p2wi clock
debug("p2wi_set_clk....\n");
p2wi_set_clk(P2WI_SCK);
//pmu initialize as p2wi mode
p2wi_set_pmu_mode(0x68, 0x3e, 0x3e);
return 0;
}
s32 p2wi_exit(void)
{
__u32 reg_val;
reg_val = readl(0x1f01400 + 0xb0);
reg_val &= ~(1 << 3);
writel(reg_val, 0x1f01400 + 0xb0);
reg_val = readl(0x1f01400 + 0x28);
reg_val &= ~(1 << 3);
writel(reg_val, 0x1f01400 + 0x28);
#ifdef CONFIG_SUN6I_FPGA
//PG[24][25] used as p2wi SCK and SDA under FPGA platform.
writel(0x0, 0x01c20800 + 0xE4);
#endif
return 0;
}
s32 p2wi_read(u8 *addr, u8 *data, u32 len)
{
u32 i;
u32 addr0 = 0, addr1 = 0;
u32 data0 = 0, data1 = 0;
if((len >= PMU_TRANS_BYTE_MAX) || (len <= 0))
{
printf("p2wi read error\n");
return -1;
}
for (i = 0; i < len; i++)
{
//debug("read data[%d] : addr = %x\n", i, addr[i]);
if (i < 4)
{
//pack 8bit addr0~addr3 into 32bit addr0
addr0 |= addr[i] << (i * 8);
}
else
{
//pack 8bit addr4~addr7 into 32bit addr1
addr1 |= addr[i] << ((i - 4) * 8);
}
}
//write address to register
writel(addr0, P2WI_REG_DADDR0);
writel(addr1, P2WI_REG_DADDR1);
writel((len - 1) | (1 << 4), P2WI_REG_DLEN);
//start transmit
writel(readl(P2WI_REG_CTRL) | P2WI_START_TRANS, P2WI_REG_CTRL);
#if 0
debug("read config finished\n");
debug("P2WI_REG_DADDR0 = %x\n", readl(P2WI_REG_DADDR0));
debug("P2WI_REG_DADDR1 = %x\n", readl(P2WI_REG_DADDR1));
debug("P2WI_REG_DLEN = %x\n", readl(P2WI_REG_DLEN));
debug("P2WI_REG_CTRL = %x\n", readl(P2WI_REG_CTRL));
debug("P2WI_REG_CCR = %x\n", readl(P2WI_REG_CCR));
#endif
//wait transfer complete
if (p2wi_wait_state() != 0)
{
printf("p2wi read failed\n");
return -1;
}
//read out data
data0 = readl(P2WI_REG_DATA0);
data1 = readl(P2WI_REG_DATA1);
#if 0
debug("P2WI_REG_DATA0 = %x\n", data0);
debug("P2WI_REG_DATA1 = %x\n", data1);
#endif
for (i = 0; i < len; i++)
{
if (i < 4)
{
data[i] = (data0 >> (i * 8)) & 0xff;
}
else
{
data[i] = (data1 >> ((i - 4) * 8)) & 0xff;
}
}
return 0;
}
s32 p2wi_write(u8 *addr, u8 *data, u32 len)
{
u32 i;
u32 addr0 = 0, addr1 = 0;
u32 data0 = 0, data1 = 0;
if((len >= PMU_TRANS_BYTE_MAX) || (len <= 0))
{
printf("p2wi write error\n");
return -1;
}
for (i = 0; i < len; i++)
{
// debug("write data[%d] : data = %x, addr = %x\n", i, data[i], addr[i]);
if (i < 4)
{
//pack 8bit data0~data3 into 32bit data0
//pack 8bit addr0~addr3 into 32bit addr0
addr0 |= addr[i] << (i * 8);
data0 |= data[i] << (i * 8);
}
else
{
//pack 8bit data4~data7 into 32bit data1
//pack 8bit addr4~addr7 into 32bit addr4
addr1 |= addr[i] << ((i - 4) * 8);
data1 |= data[i] << ((i - 4) * 8);
}
}
//write register
writel(addr0, P2WI_REG_DADDR0);
writel(addr1, P2WI_REG_DADDR1);
writel(data0, P2WI_REG_DATA0);
writel(data1, P2WI_REG_DATA1);
writel(len - 1, P2WI_REG_DLEN);
//start transfer
writel(readl(P2WI_REG_CTRL) | P2WI_START_TRANS, P2WI_REG_CTRL);
#if 0
debug("write config finished\n");
debug("P2WI_REG_DADDR0 = %x\n", readl(P2WI_REG_DADDR0));
debug("P2WI_REG_DADDR1 = %x\n", readl(P2WI_REG_DADDR1));
debug("P2WI_REG_DATA0 = %x\n", readl(P2WI_REG_DATA0));
debug("P2WI_REG_DATA1 = %x\n", readl(P2WI_REG_DATA1));
debug("P2WI_REG_DLEN = %x\n", readl(P2WI_REG_DLEN));
debug("P2WI_REG_CTRL = %x\n", readl(P2WI_REG_CTRL));
#endif
//wait transfer complete
if (p2wi_wait_state() != 0)
{
printf("p2wi write failed\n");
return -1;
}
return 0;
}
static void p2wi_set_pmu_mode(u32 slave_addr, u32 reg, u32 data)
{
//set pmu work mode
writel(P2WI_PMU_INIT | (slave_addr) | (reg << 8) | (data << 16), P2WI_REG_PMCR);
//wait pmu mode set complete
while(readl(P2WI_REG_PMCR) & P2WI_PMU_INIT)
{
;
}
}
static void p2wi_set_clk(u32 sck)
{
#ifndef CONFIG_SUN6I_FPGA
u32 src_clk = 12000000;
u32 div = src_clk / sck / 2 - 1;
u32 sda_odly = div >> 1;
u32 rval = div | (sda_odly << 8);
writel(rval, P2WI_REG_CCR);
#else
//fpga platform: apb clock = 24M, p2wi clock = 3M.
writel(0x103, P2WI_REG_CCR);
debug("P2WI_REG_CCR value = %x\n", readl(P2WI_REG_CCR));
#endif
}
static s32 p2wi_wait_state(void)
{
s32 ret = -1;
u32 stat;
while (1)
{
stat = readl(P2WI_REG_STAT);
if (stat & P2WI_TERR_INT)
{
//transfer error
printf("p2wi transfer error [%x]\n", ((stat >> 8) & 0xff));
ret = -1;
break;
}
if (stat & P2WI_TOVER_INT)
{
//transfer complete
ret = 0;
break;
}
}
//clear state flag
writel(stat, P2WI_REG_STAT);
return ret;
}
| 23.877256 | 82 | 0.623979 |
383e75edebf1fb856db5c7e1522cd0e869b12d77 | 201 | h | C | MyMusic/test.h | Codepath-Group11/MyMusic | 79d59e1d000aefc5fa3e7e280b2120a7c012770f | [
"Apache-2.0"
] | 1 | 2017-04-18T03:34:30.000Z | 2017-04-18T03:34:30.000Z | MyMusic/test.h | Codepath-Group11/Test | 79d59e1d000aefc5fa3e7e280b2120a7c012770f | [
"Apache-2.0"
] | 13 | 2017-04-26T00:35:39.000Z | 2017-05-15T05:25:12.000Z | MyMusic/test.h | Codepath-Group11/Test | 79d59e1d000aefc5fa3e7e280b2120a7c012770f | [
"Apache-2.0"
] | null | null | null | //
// test.h
// MyMusic
//
// Created by Yerneni, Naresh on 4/28/17.
// Copyright © 2017 Yerneni, Naresh. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface test : UIViewController
@end
| 14.357143 | 58 | 0.661692 |
38417bb393b0e441c88bdcfcdd67f2a28100166d | 5,512 | c | C | Library/STM32L/Middlewares/ST/STM32_BlueNRG1/STM32L1xx_HAL_BlueNRG1_Drivers/src/stm32l1xx_hal_bluenrg1_spi.c | SensiEDGE/SensiBLE-2.1 | fdbf78906a8788fd520bda4898b44178e4ee4873 | [
"Unlicense"
] | null | null | null | Library/STM32L/Middlewares/ST/STM32_BlueNRG1/STM32L1xx_HAL_BlueNRG1_Drivers/src/stm32l1xx_hal_bluenrg1_spi.c | SensiEDGE/SensiBLE-2.1 | fdbf78906a8788fd520bda4898b44178e4ee4873 | [
"Unlicense"
] | 1 | 2021-02-24T19:09:16.000Z | 2021-03-02T07:07:30.000Z | Library/STM32L/Middlewares/ST/STM32_BlueNRG1/STM32L1xx_HAL_BlueNRG1_Drivers/src/stm32l1xx_hal_bluenrg1_spi.c | SensiEDGE/SensiBLE-2.1 | fdbf78906a8788fd520bda4898b44178e4ee4873 | [
"Unlicense"
] | 1 | 2022-01-25T07:57:29.000Z | 2022-01-25T07:57:29.000Z | /**
******************************************************************************
* @file stm32l1xx_hal_bluenrg_spi.c
* @author AMS VMA RF Application Team
* @version V1.0.0
* @date 29-May-2015
* @brief HAL specific implementation for SPI communication with BlueNRG,
* BlueNRG-MS for optimizing the BLE throughput
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2015 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32l1xx_hal.h"
/* External variables --------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private defines -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
static void SPI_I2S_SendData(SPI_HandleTypeDef *hspi, uint8_t data)
{
//hspi->Instance->DR = data;
*((__IO uint8_t *)&hspi->Instance->DR) = data;
}
static uint8_t SPI_I2S_ReceiveData(SPI_HandleTypeDef *hspi)
{
//return hspi->Instance->DR;
return (uint8_t)(READ_REG(hspi->Instance->DR));
}
/* Private macros ------------------------------------------------------------*/
/* Public functions ----------------------------------------------------------*/
/**
* @brief Transmit and Receive an amount of data in blocking mode
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pTxData: pointer to transmission data buffer
* @param pRxData: pointer to reception data buffer to be
* @param Size: amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_TransmitReceive_Opt(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint8_t Size)
{
uint8_t i;
for (i = 0; i < Size; i++) {
SPI_I2S_SendData(hspi, *pTxData++);
while(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE) == RESET);
while(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE) == RESET);
*pRxData++ = SPI_I2S_ReceiveData(hspi);
}
return HAL_OK;
}
/**
* @brief Transmit an amount of data in blocking mode (optimized version)
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pData: pointer to data buffer
* @param Size: amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_Transmit_Opt(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t Size)
{
uint8_t i;
for (i = 0; i < Size; i++) {
SPI_I2S_SendData(hspi, *pTxData++);
while(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE) == RESET);
while(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE) == RESET);
SPI_I2S_ReceiveData(hspi);
}
return HAL_OK;
}
/**
* @brief Receive an amount of data in blocking mode (optimized version)
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pData: pointer to data buffer
* @param Size: amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_Receive_Opt(SPI_HandleTypeDef *hspi, uint8_t *pRxData, uint8_t Size)
{
uint8_t i;
for (i = 0; i < Size; i++) {
SPI_I2S_SendData(hspi, 0x00);
while(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE) == RESET);
while(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE) == RESET);
*pRxData++ = SPI_I2S_ReceiveData(hspi);
}
return HAL_OK;
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 40.529412 | 126 | 0.607765 |
c053ec4d4dade839c806474b94fea3abcecd28ef | 19,076 | c | C | wizard/option.c | ImageMagick/WizardsToolkit | d9d0478e7d34a6fe50c1b759b5a4205fa6717385 | [
"ImageMagick"
] | 4 | 2018-03-25T20:09:35.000Z | 2021-09-09T08:40:33.000Z | wizard/option.c | FLOOPI222/WizardsToolkit | 1309740445025cd615dec54dd58bad1d751551bf | [
"ImageMagick"
] | null | null | null | wizard/option.c | FLOOPI222/WizardsToolkit | 1309740445025cd615dec54dd58bad1d751551bf | [
"ImageMagick"
] | 6 | 2016-01-06T05:42:32.000Z | 2021-02-28T02:05:18.000Z | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% OOO PPPP TTTTT IIIII OOO N N %
% O O P P T I O O NN N %
% O O PPPP T I O O N N N %
% O O P T I O O N NN %
% OOO P T IIIII OOO N N %
% %
% %
% Wizard's Toolkit Option Methods %
% %
% Software Design %
% Cristy %
% March 2003 %
% %
% %
% Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "wizard/studio.h"
#include "wizard/authenticate.h"
#include "wizard/cipher.h"
#include "wizard/entropy.h"
#include "wizard/exception-private.h"
#include "wizard/memory_.h"
#include "wizard/mime.h"
#include "wizard/mime-private.h"
#include "wizard/option.h"
#include "wizard/resource_.h"
#include "wizard/string_.h"
#include "wizard/token.h"
/*
Option declarations.
*/
static const OptionInfo
AuthenticateOptions[] =
{
{ "Undefined", (ssize_t) UndefinedAuthenticate },
{ "Public", (ssize_t) PublicAuthenticateMethod },
{ "Secret", (ssize_t) SecretAuthenticateMethod },
{ (char *) NULL, UndefinedAuthenticate }
},
CipherOptions[] =
{
{ "Undefined", (ssize_t) UndefinedCipher },
{ "AES", (ssize_t) AESCipher },
{ "Chacha", (ssize_t) ChachaCipher },
{ "None", (ssize_t) NoCipher },
{ "Serpent", (ssize_t) SerpentCipher },
{ "Twofish", (ssize_t) TwofishCipher },
{ (char *) NULL, UndefinedCipher }
},
CommandOptions[] =
{
{ "+authenticate", 1L },
{ "-authenticate", 1L },
{ "+chunksize", 1L },
{ "-chunksize", 1L },
{ "+decipher", 0L },
{ "-decipher", 0L },
{ "+debug", 1L },
{ "-debug", 1L },
{ "+entropy", 1L },
{ "-entropy", 1L },
{ "+hash", 1L },
{ "-hash", 1L },
{ "+help", 0L },
{ "-help", 0L },
{ "+key", 1L },
{ "-key", 1L },
{ "+key-length", 1L },
{ "-key-length", 1L },
{ "+mac", 1L },
{ "-mac", 1L },
{ "+level", 1L },
{ "-level", 1L },
{ "+list", 1L },
{ "-list", 1L },
{ "+log", 1L },
{ "-log", 1L },
{ "+mode", 1L },
{ "-mode", 1L },
{ "+properties", 1L },
{ "-properties", 1L },
{ "+random", 1L },
{ "-random", 1L },
{ "+verbose", 0L },
{ "-verbose", 0L },
{ "+version", 1L },
{ "-version", 1L },
{ (char *) NULL, 0L }
},
DataTypeOptions[] =
{
{ "Undefined", (ssize_t) UndefinedData },
{ "Byte", (ssize_t) ByteData },
{ "Long", (ssize_t) LongData },
{ "Short", (ssize_t) ShortData },
{ "String", (ssize_t) StringData },
{ (char *) NULL, (ssize_t) UndefinedData }
},
EndianOptions[] =
{
{ "Undefined", (ssize_t) UndefinedEndian },
{ "LSB", (ssize_t) LSBEndian },
{ "MSB", (ssize_t) MSBEndian },
{ (char *) NULL, (ssize_t) UndefinedEndian }
},
EntropyLevelOptions[] =
{
{ "0", 0L },
{ "1", 1L },
{ "2", 2L },
{ "3", 3L },
{ "4", 4L },
{ "5", 5L },
{ "6", 6L },
{ "7", 7L },
{ "8", 8L },
{ "9", 9L },
{ (char *) NULL, 0L }
},
EntropyOptions[] =
{
{ "Undefined", (ssize_t) UndefinedEntropy },
{ "None", (ssize_t) NoEntropy },
{ "BZip", (ssize_t) BZIPEntropy },
{ "LZMA", (ssize_t) LZMAEntropy },
{ "Zip", (ssize_t) ZIPEntropy },
{ (char *) NULL, UndefinedEntropy }
},
KeyLengthOptions[] =
{
{ "256", 256L },
{ "512", 512L },
{ "1024", 1024L },
{ "2048", 2048L },
{ (char *) NULL, 0L }
},
HashOptions[] =
{
{ "Undefined", (ssize_t) UndefinedHash },
{ "CRC64", (ssize_t) CRC64Hash },
{ "MD5", (ssize_t) MD5Hash },
{ "None", (ssize_t) NoHash },
{ "SHA1", (ssize_t) SHA1Hash },
{ "SHA224", (ssize_t) SHA2224Hash },
{ "SHA256", (ssize_t) SHA2256Hash },
{ "SHA384", (ssize_t) SHA2384Hash },
{ "SHA512", (ssize_t) SHA2512Hash },
{ "SHA2", (ssize_t) SHA2Hash },
{ "SHA2-224", (ssize_t) SHA2224Hash },
{ "SHA2-256", (ssize_t) SHA2256Hash },
{ "SHA2-384", (ssize_t) SHA2384Hash },
{ "SHA2-512", (ssize_t) SHA2512Hash },
{ "SHA3", (ssize_t) SHA3Hash },
{ "SHA3-224", (ssize_t) SHA3224Hash },
{ "SHA3-256", (ssize_t) SHA3256Hash },
{ "SHA3-384", (ssize_t) SHA3384Hash },
{ "SHA3-512", (ssize_t) SHA3512Hash },
{ (char *) NULL, UndefinedHash }
},
ListOptions[] =
{
{ "Authenticate", (ssize_t) WizardAuthenticateOptions },
{ "Cipher", (ssize_t) WizardCipherOptions },
{ "Command", (ssize_t) WizardCommandOptions },
{ "DataType", (ssize_t) WizardDataTypeOptions },
{ "Debug", (ssize_t) WizardDebugOptions },
{ "Endian", (ssize_t) WizardEndianOptions },
{ "Entropy", (ssize_t) WizardEntropyOptions },
{ "EntropyLevel", (ssize_t) WizardEntropyLevelOptions },
{ "Hash", (ssize_t) WizardHashOptions },
{ "KeyLength", (ssize_t) WizardKeyLengthOptions },
{ "List", (ssize_t) WizardListOptions },
{ "Mode", (ssize_t) WizardModeOptions },
{ (char *) NULL, (ssize_t) WizardUndefinedOptions }
},
LogWizardEventOptions[] =
{
{ "All", (ssize_t) (AllEvents &~ TraceEvent) },
{ "Blob", (ssize_t) BlobEvent },
{ "Deprecate", (ssize_t) DeprecateEvent },
{ "Configure", (ssize_t) ConfigureEvent },
{ "Exception", (ssize_t) ExceptionEvent },
{ "Locale", (ssize_t) LocaleEvent },
{ "None", (ssize_t) NoEvents },
{ "Resource", (ssize_t) ResourceEvent },
{ "Trace", (ssize_t) TraceEvent },
{ "User", (ssize_t) UserEvent },
{ "Warning", (ssize_t) WarningEvent },
{ (char *) NULL, UndefinedEvents }
},
ModeOptions[] =
{
{ "Undefined", (ssize_t) UndefinedMode },
{ "CBC", (ssize_t) CBCMode },
{ "CFB", (ssize_t) CFBMode },
{ "CTR", (ssize_t) CTRMode },
{ "ECB", (ssize_t) ECBMode },
{ "OFB", (ssize_t) OFBMode },
{ (char *) NULL, UndefinedMode }
},
ResourceOptions[] =
{
{ "Undefined", (ssize_t) UndefinedResource },
{ "Area", (ssize_t) AreaResource },
{ "Disk", (ssize_t) DiskResource },
{ "File", (ssize_t) FileResource },
{ "Map", (ssize_t) MapResource },
{ "Memory", (ssize_t) MemoryResource },
{ (char *) NULL, (ssize_t) UndefinedResource }
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W i z a r d O p t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWizardOptions() returns a list of options.
%
% The format of the GetWizardOptions method is:
%
% const char **GetWizardOptions(const WizardOption option)
%
% A description of each parameter follows:
%
% o option: The option.
%
*/
static const OptionInfo *GetOptionInfo(const WizardOption option)
{
switch (option)
{
case WizardAuthenticateOptions: return(AuthenticateOptions);
case WizardCipherOptions: return(CipherOptions);
case WizardCommandOptions: return(CommandOptions);
case WizardDataTypeOptions: return(DataTypeOptions);
case WizardDebugOptions: return(LogWizardEventOptions);
case WizardEndianOptions: return(EndianOptions);
case WizardEntropyOptions: return(EntropyOptions);
case WizardEntropyLevelOptions: return(EntropyLevelOptions);
case WizardKeyLengthOptions: return(KeyLengthOptions);
case WizardHashOptions: return(HashOptions);
case WizardListOptions: return(ListOptions);
case WizardLogEventOptions: return(LogWizardEventOptions);
case WizardModeOptions: return(ModeOptions);
case WizardResourceOptions: return(ResourceOptions);
default: break;
}
return((const OptionInfo *) NULL);
}
WizardExport char **GetWizardOptions(const WizardOption option)
{
char
**options;
const OptionInfo
*option_info;
ssize_t
i;
option_info=GetOptionInfo(option);
if (option_info == (const OptionInfo *) NULL)
return((char **) NULL);
for (i=0; option_info[i].mnemonic != (const char *) NULL; i++) ;
options=(char **) AcquireQuantumMemory((size_t) i+1UL,sizeof(*options));
if (options == (char **) NULL)
ThrowFatalException(ResourceFatalError,"unable to acquire string `%s'");
for (i=0; option_info[i].mnemonic != (const char *) NULL; i++)
options[i]=AcquireString(option_info[i].mnemonic);
options[i]=(char *) NULL;
return(options);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W i z a r d O p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWizardOption() returns WizardTrue if the option begins with a - or + and
% the first character that follows is alphanumeric.
%
% The format of the IsWizardOption method is:
%
% WizardBooleanType IsWizardOption(const char *option)
%
% A description of each parameter follows:
%
% o option: The option.
%
*/
WizardExport WizardBooleanType IsWizardOption(const char *option)
{
assert(option != (const char *) NULL);
if ((*option != '-') && (*option != '+'))
return(WizardFalse);
if (strlen(option) == 1)
return(WizardFalse);
option++;
if (isalpha((int) ((unsigned char) *option)) == 0)
return(WizardFalse);
return(WizardTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i s t W i z a r d O p t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListWizardOptions() lists the contents of enumerated option type(s).
%
% The format of the ListWizardOptions method is:
%
% WizardBooleanType ListWizardOptions(FILE *file,const WizardOption option,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o file: list options to this file handle.
%
% o option: which option list to display.
%
% o exception: return any errors or warnings in this structure.
%
*/
WizardExport WizardBooleanType ListWizardOptions(FILE *file,
const WizardOption option,ExceptionInfo *wizard_unused(exception))
{
const OptionInfo
*option_info;
ssize_t
i;
if (file == (FILE *) NULL)
file=stdout;
option_info=GetOptionInfo(option);
if (option_info == (const OptionInfo *) NULL)
return(WizardFalse);
for (i=0; option_info[i].mnemonic != (char *) NULL; i++)
{
if ((i == 0) && (strcmp(option_info[i].mnemonic,"Undefined") == 0))
continue;
(void) fprintf(file,"%s\n",option_info[i].mnemonic);
}
return(WizardTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P a r s e W i z a r d O p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ParseWizardOption() parses an option string and returns an enumerated option
% type(s).
%
% The format of the ParseWizardOption method is:
%
% ssize_t ParseWizardOption(const WizardOption option,
% const WizardBooleanType list,const char *options)
%
% A description of each parameter follows:
%
% o option: The option.
%
% o list: A option other than zero permits more than one option separated by
% commas.
%
% o options: One or more options separated by commas.
%
*/
WizardExport ssize_t ParseWizardOption(const WizardOption option,
const WizardBooleanType list,const char *options)
{
char
token[WizardPathExtent];
const OptionInfo
*option_info;
ssize_t
option_types;
char
*q;
const char
*p;
ssize_t
i;
WizardBooleanType
negate;
option_info=GetOptionInfo(option);
if (option_info == (const OptionInfo *) NULL)
return(-1);
option_types=0;
for (p=options; p != (char *) NULL; p=strchr(p,','))
{
while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) &&
(*p != '\0'))
p++;
if ((*p == '-') || (*p == '+'))
p++;
negate=(*p == '!') ? WizardTrue : WizardFalse;
if (negate != WizardFalse)
p++;
q=token;
while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) &&
(*p != '\0'))
{
if ((q-token) >= (WizardPathExtent-1))
break;
*q++=(*p++);
}
*q='\0';
for (i=0; option_info[i].mnemonic != (char *) NULL; i++)
{
if (LocaleCompare(token,option_info[i].mnemonic) == 0)
{
if (*token == '!')
option_types=option_types &~ option_info[i].type;
else
option_types=option_types | option_info[i].type;
break;
}
}
if ((option_info[i].mnemonic == (char *) NULL) &&
((strchr(token+1,'-') != (char *) NULL) ||
(strchr(token+1,'_') != (char *) NULL)))
{
while ((q=strchr(token+1,'-')) != (char *) NULL)
(void) CopyWizardString(q,q+1,WizardPathExtent-strlen(q));
while ((q=strchr(token+1,'_')) != (char *) NULL)
(void) CopyWizardString(q,q+1,WizardPathExtent-strlen(q));
for (i=0; option_info[i].mnemonic != (char *) NULL; i++)
if (LocaleCompare(token,option_info[i].mnemonic) == 0)
{
if (*token == '!')
option_types=option_types &~ option_info[i].type;
else
option_types=option_types | option_info[i].type;
break;
}
}
if (option_info[i].mnemonic == (char *) NULL)
return(-1);
if (list == WizardFalse)
break;
}
return(option_types);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W i z a r d O p t i o n T o M n e m o n i c %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WizardOptionToMnemonic() returns an enumerated option as a mnemonic.
%
% The format of the WizardOptionToMnemonic method is:
%
% const char *WizardOptionToMnemonic(const WizardOption option,
% const ssize_t type)
%
% A description of each parameter follows:
%
% o option: the option.
%
% o type: one or more options separated by commas.
%
*/
WizardExport const char *WizardOptionToMnemonic(const WizardOption option,
const ssize_t type)
{
const OptionInfo
*option_info;
ssize_t
i;
option_info=GetOptionInfo(option);
if (option_info == (const OptionInfo *) NULL)
return((const char *) NULL);
for (i=0; option_info[i].mnemonic != (const char *) NULL; i++)
if (type == option_info[i].type)
break;
if (option_info[i].mnemonic == (const char *) NULL)
return("undefined");
return(option_info[i].mnemonic);
}
| 34.683636 | 80 | 0.440816 |
c08e9613e4a84adbe22bb951a6b98807103fe192 | 43,115 | h | C | include/cpg_regs.h | ariaboard-com/renesas_rzg2l_flash_writer | 510f43376fc53578ebb1d83873f04908acf2fde6 | [
"BSD-3-Clause"
] | null | null | null | include/cpg_regs.h | ariaboard-com/renesas_rzg2l_flash_writer | 510f43376fc53578ebb1d83873f04908acf2fde6 | [
"BSD-3-Clause"
] | null | null | null | include/cpg_regs.h | ariaboard-com/renesas_rzg2l_flash_writer | 510f43376fc53578ebb1d83873f04908acf2fde6 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020, Renesas Electronics Corporation. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __CPG_REGS_H__
#define __CPG_REGS_H__
#define CPG_BASE (0x11010000) /* CPG base address */
#define CPG_PLL1_STBY (CPG_BASE + 0x0000) /* PLL1 (SSCG) standby control register */
#define CPG_PLL1_CLK1 (CPG_BASE + 0x0004) /* PLL1 (SSCG) output clock setting register 1 */
#define CPG_PLL1_CLK2 (CPG_BASE + 0x0008) /* PLL1 (SSCG) output clock setting register 2 */
#define CPG_PLL1_MON (CPG_BASE + 0x000C) /* PLL1 (SSCG) monitor register */
#define CPG_PLL4_STBY (CPG_BASE + 0x0010) /* PLL4 (SSCG) standby control register */
#define CPG_PLL4_CLK1 (CPG_BASE + 0x0014) /* PLL4 (SSCG) output clock setting register 1 */
#define CPG_PLL4_CLK2 (CPG_BASE + 0x0018) /* PLL4 (SSCG) output clock setting register 2 */
#define CPG_PLL4_MON (CPG_BASE + 0x001C) /* PLL4 (SSCG) monitor register */
#define CPG_PLL6_STBY (CPG_BASE + 0x0020) /* PLL6 (SSCG) standby control register */
#define CPG_PLL6_CLK1 (CPG_BASE + 0x0024) /* PLL6 (SSCG) output clock setting register 1 */
#define CPG_PLL6_CLK2 (CPG_BASE + 0x0028) /* PLL6 (SSCG) output clock setting register 2 */
#define CPG_PLL6_MON (CPG_BASE + 0x002C) /* PLL6 (SSCG) monitor register */
#define CPG_PLL1_SETTING (CPG_BASE + 0x0040) /* PLL1_SEL_SETTING */
#define CPG_OTPPLL0_MON (CPG_BASE + 0x0044) /* OTP_OTPPLL0 monitor register */
#define CPG_OTPPLL1_MON (CPG_BASE + 0x0048) /* OTP_OTPPLL1 monitor register */
#define CPG_OTPPLL2_MON (CPG_BASE + 0x004C) /* OTP_OTPPLL2 monitor register */
#define CPG_PLL2_STBY (CPG_BASE + 0x0100) /* PLL2 (SSCG) standby control register */
#define CPG_PLL2_CLK1 (CPG_BASE + 0x0104) /* PLL2 (SSCG) output clock setting register 1 */
#define CPG_PLL2_CLK2 (CPG_BASE + 0x0108) /* PLL2 (SSCG) output clock setting register 2 */
#define CPG_PLL2_CLK3 (CPG_BASE + 0x010C) /* PLL2 (SSCG) output clock setting register 3 */
#define CPG_PLL2_CLK4 (CPG_BASE + 0x0110) /* PLL2 (SSCG) output clock setting register 4 */
#define CPG_PLL2_CLK5 (CPG_BASE + 0x0114) /* PLL2 (SSCG) output clock setting register 5 */
#define CPG_PLL2_CLK6 (CPG_BASE + 0x0118) /* PLL2 (SSCG) output clock setting register 6 */
#define CPG_PLL2_MON (CPG_BASE + 0x011C) /* PLL2 (SSCG) monitor register */
#define CPG_PLL3_STBY (CPG_BASE + 0x0120) /* PLL3 (SSCG) standby control register */
#define CPG_PLL3_CLK1 (CPG_BASE + 0x0124) /* PLL3 (SSCG) output clock setting register 1 */
#define CPG_PLL3_CLK2 (CPG_BASE + 0x0128) /* PLL3 (SSCG) output clock setting register 2 */
#define CPG_PLL3_CLK3 (CPG_BASE + 0x012C) /* PLL3 (SSCG) output clock setting register 3 */
#define CPG_PLL3_CLK4 (CPG_BASE + 0x0130) /* PLL3 (SSCG) output clock setting register 4 */
#define CPG_PLL3_CLK5 (CPG_BASE + 0x0134) /* PLL3 (SSCG) output clock setting register 5 */
#define CPG_PLL3_MON (CPG_BASE + 0x013C) /* PLL3 (SSCG) monitor register */
#define CPG_PLL5_STBY (CPG_BASE + 0x0140) /* PLL5 (SSCG) standby control register */
#define CPG_PLL5_CLK1 (CPG_BASE + 0x0144) /* PLL5 (SSCG) output clock setting register 1 */
#define CPG_PLL5_CLK2 (CPG_BASE + 0x0148) /* PLL5 (SSCG) output clock setting register 2 */
#define CPG_PLL5_CLK3 (CPG_BASE + 0x014C) /* PLL5 (SSCG) output clock setting register 3 */
#define CPG_PLL5_CLK4 (CPG_BASE + 0x0150) /* PLL5 (SSCG) output clock setting register 4 */
#define CPG_PLL5_CLK5 (CPG_BASE + 0x0154) /* PLL5 (SSCG) output clock setting register 5 */
#define CPG_PLL5_MON (CPG_BASE + 0x015C) /* PLL5 (SSCG) monitor register */
#define CPG_PL1_DDIV (CPG_BASE + 0x0200) /* Division ratio setting register */
#define CPG_PL2_DDIV (CPG_BASE + 0x0204) /* Division ratio setting register */
#define CPG_PL3A_DDIV (CPG_BASE + 0x0208) /* Division ratio setting register */
#define CPG_PL3B_DDIV (CPG_BASE + 0x020C) /* Division ratio setting register */
#define CPG_PL6_DDIV (CPG_BASE + 0x0210) /* Division ratio setting register */
#define CPG_PL2SDHI_DSEL (CPG_BASE + 0x0218) /* Source clock setting register */
#define CPG_PL4_DSEL (CPG_BASE + 0x021C) /* Source clock setting register */
#define CPG_CLKSTATUS (CPG_BASE + 0x0280) /* CLK status register */
#define CPG_PL1_CA55_SSEL (CPG_BASE + 0x0400) /* Source clock setting register */
#define CPG_PL2_SSEL (CPG_BASE + 0x0404) /* Source clock setting register */
#define CPG_PL3_SSEL (CPG_BASE + 0x0408) /* Source clock setting register */
#define CPG_PL5_SSEL (CPG_BASE + 0x0410) /* Source clock setting register */
#define CPG_PL6_SSEL (CPG_BASE + 0x0414) /* Source clock setting register */
#define CPG_PL6_ETH_SSEL (CPG_BASE + 0x0418) /* Source clock setting register */
#define CPG_PL5_SDIV (CPG_BASE + 0x0420) /* Division ratio setting register */
#define CPG_CLKON_CA55 (CPG_BASE + 0x0500) /* Clock ON / OFF register CA55 */
#define CPG_CLKON_CM33 (CPG_BASE + 0x0504) /* Clock ON / OFF register CM33 */
#define CPG_CLKON_SRAM_ACPU (CPG_BASE + 0x0508) /* Clock ON / OFF register SRAM_ACPU */
#define CPG_CLKON_SRAM_MCPU (CPG_BASE + 0x050C) /* Clock ON / OFF register SRAM_MCPU */
#define CPG_CLKON_ROM (CPG_BASE + 0x0510) /* Clock ON / OFF register ROM */
#define CPG_CLKON_GIC600 (CPG_BASE + 0x0514) /* Clock ON / OFF register GIC600 */
#define CPG_CLKON_IA55 (CPG_BASE + 0x0518) /* Clock ON / OFF register IA55 */
#define CPG_CLKON_IM33 (CPG_BASE + 0x051C) /* Clock ON / OFF register IM33 */
#define CPG_CLKON_MHU (CPG_BASE + 0x0520) /* Clock ON / OFF register MHU */
#define CPG_CLKON_CST (CPG_BASE + 0x0524) /* Clock ON / OFF register CST */
#define CPG_CLKON_SYC (CPG_BASE + 0x0528) /* Clock ON / OFF register SYC */
#define CPG_CLKON_DAMC_REG (CPG_BASE + 0x052C) /* Clock ON / OFF register DAMC_REG */
#define CPG_CLKON_SYSC (CPG_BASE + 0x0530) /* Clock ON / OFF register SYSC */
#define CPG_CLKON_OSTM (CPG_BASE + 0x0534) /* Clock ON / OFF register OSTM */
#define CPG_CLKON_MTU (CPG_BASE + 0x0538) /* Clock ON / OFF register MTU */
#define CPG_CLKON_POE3 (CPG_BASE + 0x053C) /* Clock ON / OFF register POE3 */
#define CPG_CLKON_GPT (CPG_BASE + 0x0540) /* Clock ON / OFF register GPT */
#define CPG_CLKON_POEG (CPG_BASE + 0x0544) /* Clock ON / OFF register POEG */
#define CPG_CLKON_WDT (CPG_BASE + 0x0548) /* Clock ON / OFF register WDT */
#define CPG_CLKON_DDR (CPG_BASE + 0x054C) /* Clock ON / OFF register DDR */
#define CPG_CLKON_SPI_MULTI (CPG_BASE + 0x0550) /* Clock ON / OFF register SPI_MULTI */
#define CPG_CLKON_SDHI (CPG_BASE + 0x0554) /* Clock ON / OFF register SDHI */
#define CPG_CLKON_GPU (CPG_BASE + 0x0558) /* Clock ON / OFF register GPU */
#define CPG_CLKON_ISU (CPG_BASE + 0x055C) /* Clock ON / OFF register ISU */
#define CPG_CLKON_H264 (CPG_BASE + 0x0560) /* Clock ON / OFF register H264 */
#define CPG_CLKON_CRU (CPG_BASE + 0x0564) /* Clock ON / OFF register CRU */
#define CPG_CLKON_MIPI_DSI (CPG_BASE + 0x0568) /* Clock ON / OFF register MIPI_DSI */
#define CPG_CLKON_LCDC (CPG_BASE + 0x056C) /* Clock ON / OFF register LCDC */
#define CPG_CLKON_SSI (CPG_BASE + 0x0570) /* Clock ON / OFF register SSI */
#define CPG_CLKON_SRC (CPG_BASE + 0x0574) /* Clock ON / OFF register SRC */
#define CPG_CLKON_USB (CPG_BASE + 0x0578) /* Clock ON / OFF register USB */
#define CPG_CLKON_ETH (CPG_BASE + 0x057C) /* Clock ON / OFF register ETH */
#define CPG_CLKON_I2C (CPG_BASE + 0x0580) /* Clock ON / OFF register I2C */
#define CPG_CLKON_SCIF (CPG_BASE + 0x0584) /* Clock ON / OFF register SCIF */
#define CPG_CLKON_SCI (CPG_BASE + 0x0588) /* Clock ON / OFF register SCI */
#define CPG_CLKON_IRDA (CPG_BASE + 0x058C) /* Clock ON / OFF register IRDA */
#define CPG_CLKON_RSPI (CPG_BASE + 0x0590) /* Clock ON / OFF register RSPI */
#define CPG_CLKON_CANFD (CPG_BASE + 0x0594) /* Clock ON / OFF register CANFD */
#define CPG_CLKON_GPIO (CPG_BASE + 0x0598) /* Clock ON / OFF register GPIO */
#define CPG_CLKON_TSIPG (CPG_BASE + 0x059C) /* Clock ON / OFF register TSIPG */
#define CPG_CLKON_JAUTH (CPG_BASE + 0x05A0) /* Clock ON / OFF register JAUTH */
#define CPG_CLKON_OTP (CPG_BASE + 0x05A4) /* Clock ON / OFF register OTP */
#define CPG_CLKON_ADC (CPG_BASE + 0x05A8) /* Clock ON / OFF register ADC */
#define CPG_CLKON_TSU (CPG_BASE + 0x05AC) /* Clock ON / OFF register TSU */
#define CPG_CLKON_BBGU (CPG_BASE + 0x05B0) /* Clock ON / OFF register BBGU */
#define CPG_CLKON_AXI_ACPU_BUS (CPG_BASE + 0x05B4) /* Clock ON / OFF register AXI_ACPU_BUS */
#define CPG_CLKON_AXI_MCPU_BUS (CPG_BASE + 0x05B8) /* Clock ON / OFF register AXI_MCPU_BUS */
#define CPG_CLKON_AXI_COM_BUS (CPG_BASE + 0x05BC) /* Clock ON / OFF register AXI_COM_BUS */
#define CPG_CLKON_AXI_VIDEO_BUS (CPG_BASE + 0x05C0) /* Clock ON / OFF register AXI_VIDEO_BUS */
#define CPG_CLKON_PERI_COM (CPG_BASE + 0x05C4) /* Clock ON / OFF register PERI_COM */
#define CPG_CLKON_REG1_BUS (CPG_BASE + 0x05C8) /* Clock ON / OFF register REG1_BUS */
#define CPG_CLKON_REG0_BUS (CPG_BASE + 0x05CC) /* Clock ON / OFF register REG0_BUS */
#define CPG_CLKON_PERI_CPU (CPG_BASE + 0x05D0) /* Clock ON / OFF register PERI_CPU */
#define CPG_CLKON_PERI_VIDEO (CPG_BASE + 0x05D4) /* Clock ON / OFF register PERI_VIDEO */
#define CPG_CLKON_PERI_DDR (CPG_BASE + 0x05D8) /* Clock ON / OFF register PERI_DDR */
#define CPG_CLKON_AXI_TZCDDR (CPG_BASE + 0x05DC) /* Clock ON / OFF register AXI_TZCDDR */
#define CPG_CLKON_MTGPGS (CPG_BASE + 0x05E0) /* Clock ON / OFF register MTGPGS */
#define CPG_CLKON_AXI_DEFAULT_SLV (CPG_BASE + 0x05E4) /* Clock ON / OFF register AXI_DEFAULT_SLV */
#define CPG_CLKMON_CA55 (CPG_BASE + 0x0680) /* Clock monitor register CA55 */
#define CPG_CLKMON_CM33 (CPG_BASE + 0x0684) /* Clock monitor register CM33 */
#define CPG_CLKMON_SRAM_ACPU (CPG_BASE + 0x0688) /* Clock monitor register SRAM_ACPU */
#define CPG_CLKMON_SRAM_MCPU (CPG_BASE + 0x068C) /* Clock monitor register SRAM_MCPU */
#define CPG_CLKMON_ROM (CPG_BASE + 0x0690) /* Clock monitor register ROM */
#define CPG_CLKMON_GIC600 (CPG_BASE + 0x0694) /* Clock monitor register GIC600 */
#define CPG_CLKMON_IA55 (CPG_BASE + 0x0698) /* Clock monitor register IA55 */
#define CPG_CLKMON_IM33 (CPG_BASE + 0x069C) /* Clock monitor register IM33 */
#define CPG_CLKMON_MHU (CPG_BASE + 0x06A0) /* Clock monitor register MHU */
#define CPG_CLKMON_CST (CPG_BASE + 0x06A4) /* Clock monitor register CST */
#define CPG_CLKMON_SYC (CPG_BASE + 0x06A8) /* Clock monitor register SYC */
#define CPG_CLKMON_DAMC_REG (CPG_BASE + 0x06AC) /* Clock monitor register DAMC_REG */
#define CPG_CLKMON_SYSC (CPG_BASE + 0x06B0) /* Clock monitor register SYSC */
#define CPG_CLKMON_OSTM (CPG_BASE + 0x06B4) /* Clock monitor register OSTM */
#define CPG_CLKMON_MTU (CPG_BASE + 0x06B8) /* Clock monitor register MTU */
#define CPG_CLKMON_POE3 (CPG_BASE + 0x06BC) /* Clock monitor register POE3 */
#define CPG_CLKMON_GPT (CPG_BASE + 0x06C0) /* Clock monitor register GPT */
#define CPG_CLKMON_POEG (CPG_BASE + 0x06C4) /* Clock monitor register POEG */
#define CPG_CLKMON_WDT (CPG_BASE + 0x06C8) /* Clock monitor register WDT */
#define CPG_CLKMON_DDR (CPG_BASE + 0x06CC) /* Clock monitor register DDR */
#define CPG_CLKMON_SPI_MULTI (CPG_BASE + 0x06D0) /* Clock monitor register SPI_MULTI */
#define CPG_CLKMON_SDHI (CPG_BASE + 0x06D4) /* Clock monitor register SDHI */
#define CPG_CLKMON_GPU (CPG_BASE + 0x06D8) /* Clock monitor register GPU */
#define CPG_CLKMON_ISU (CPG_BASE + 0x06DC) /* Clock monitor register ISU */
#define CPG_CLKMON_H264 (CPG_BASE + 0x06E0) /* Clock monitor register H264 */
#define CPG_CLKMON_CRU (CPG_BASE + 0x06E4) /* Clock monitor register CRU */
#define CPG_CLKMON_MIPI_DSI (CPG_BASE + 0x06E8) /* Clock monitor register MIPI_DSI */
#define CPG_CLKMON_LCDC (CPG_BASE + 0x06EC) /* Clock monitor register LCDC */
#define CPG_CLKMON_SSI (CPG_BASE + 0x06F0) /* Clock monitor register SSI */
#define CPG_CLKMON_SRC (CPG_BASE + 0x06F4) /* Clock monitor register SRC */
#define CPG_CLKMON_USB (CPG_BASE + 0x06F8) /* Clock monitor register USB */
#define CPG_CLKMON_ETH (CPG_BASE + 0x06FC) /* Clock monitor register ETH */
#define CPG_CLKMON_I2C (CPG_BASE + 0x0700) /* Clock monitor register I2C */
#define CPG_CLKMON_SCIF (CPG_BASE + 0x0704) /* Clock monitor register SCIF */
#define CPG_CLKMON_SCI (CPG_BASE + 0x0708) /* Clock monitor register SCI */
#define CPG_CLKMON_IRDA (CPG_BASE + 0x070C) /* Clock monitor register IRDA */
#define CPG_CLKMON_RSPI (CPG_BASE + 0x0710) /* Clock monitor register RSPI */
#define CPG_CLKMON_CANFD (CPG_BASE + 0x0714) /* Clock monitor register CANFD */
#define CPG_CLKMON_GPIO (CPG_BASE + 0x0718) /* Clock monitor register GPIO */
#define CPG_CLKMON_TSIPG (CPG_BASE + 0x071C) /* Clock monitor register TSIPG */
#define CPG_CLKMON_JAUTH (CPG_BASE + 0x0720) /* Clock monitor register JAUTH */
#define CPG_CLKMON_OTP (CPG_BASE + 0x0724) /* Clock monitor register OTP */
#define CPG_CLKMON_ADC (CPG_BASE + 0x0728) /* Clock monitor register ADC */
#define CPG_CLKMON_TSU (CPG_BASE + 0x072C) /* Clock monitor register TSU */
#define CPG_CLKMON_BBGU (CPG_BASE + 0x0730) /* Clock monitor register BBGU */
#define CPG_CLKMON_AXI_ACPU_BUS (CPG_BASE + 0x0734) /* Clock monitor register AXI_ACPU_BUS */
#define CPG_CLKMON_AXI_MCPU_BUS (CPG_BASE + 0x0738) /* Clock monitor register AXI_MCPU_BUS */
#define CPG_CLKMON_AXI_COM_BUS (CPG_BASE + 0x073C) /* Clock monitor register AXI_COM_BUS */
#define CPG_CLKMON_AXI_VIDEO_BUS (CPG_BASE + 0x0740) /* Clock monitor register AXI_VIDEO_BUS */
#define CPG_CLKMON_PERI_COM (CPG_BASE + 0x0744) /* Clock monitor register PERI_COM */
#define CPG_CLKMON_REG1_BUS (CPG_BASE + 0x0748) /* Clock monitor register REG1_BUS */
#define CPG_CLKMON_REG0_BUS (CPG_BASE + 0x074C) /* Clock monitor register REG0_BUS */
#define CPG_CLKMON_PERI_CPU (CPG_BASE + 0x0750) /* Clock monitor register PERI_CPU */
#define CPG_CLKMON_PERI_VIDEO (CPG_BASE + 0x0754) /* Clock monitor register PERI_VIDEO */
#define CPG_CLKMON_PERI_DDR (CPG_BASE + 0x0758) /* Clock monitor register PERI_DDR */
#define CPG_CLKMON_AXI_TZCDDR (CPG_BASE + 0x075C) /* Clock monitor register AXI_TZCDDR */
#define CPG_CLKMON_MTGPGS (CPG_BASE + 0x0760) /* Clock monitor register MTGPGS */
#define CPG_CLKMON_AXI_DEFAULT_SLV (CPG_BASE + 0x0764) /* Clock monitor register AXI_DEFAULT_SLV */
#define CPG_RST_CA55 (CPG_BASE + 0x0800) /* Reset ONOFF register CA55 */
#define CPG_RST_CM33 (CPG_BASE + 0x0804) /* Reset ONOFF register CM33 */
#define CPG_RST_SRAM_ACPU (CPG_BASE + 0x0808) /* Reset ONOFF register SRAM_ACPU */
#define CPG_RST_SRAM_MCPU (CPG_BASE + 0x080C) /* Reset ONOFF register SRAM_MCPU */
#define CPG_RST_ROM (CPG_BASE + 0x0810) /* Reset ONOFF register ROM */
#define CPG_RST_GIC600 (CPG_BASE + 0x0814) /* Reset ONOFF register GIC600 */
#define CPG_RST_IA55 (CPG_BASE + 0x0818) /* Reset ONOFF register IA55 */
#define CPG_RST_IM33 (CPG_BASE + 0x081C) /* Reset ONOFF register IM33 */
#define CPG_RST_MHU (CPG_BASE + 0x0820) /* Reset ONOFF register MHU */
#define CPG_RST_CST (CPG_BASE + 0x0824) /* Reset ONOFF register CST */
#define CPG_RST_SYC (CPG_BASE + 0x0828) /* Reset ONOFF register SYC */
#define CPG_RST_DMAC (CPG_BASE + 0x082C) /* Reset ONOFF register DMAC */
#define CPG_RST_SYSC (CPG_BASE + 0x0830) /* Reset ONOFF register SYSC */
#define CPG_RST_OSTM (CPG_BASE + 0x0834) /* Reset ONOFF register OSTM */
#define CPG_RST_MTU (CPG_BASE + 0x0838) /* Reset ONOFF register MTU */
#define CPG_RST_POE3 (CPG_BASE + 0x083C) /* Reset ONOFF register POE3 */
#define CPG_RST_GPT (CPG_BASE + 0x0840) /* Reset ONOFF register GPT */
#define CPG_RST_POEG (CPG_BASE + 0x0844) /* Reset ONOFF register POEG */
#define CPG_RST_WDT (CPG_BASE + 0x0848) /* Reset ONOFF register WDT */
#define CPG_RST_DDR (CPG_BASE + 0x084C) /* Reset ONOFF register DDR */
#define CPG_RST_SPI (CPG_BASE + 0x0850) /* Reset ONOFF register SPI */
#define CPG_RST_SDHI (CPG_BASE + 0x0854) /* Reset ONOFF register SDHI */
#define CPG_RST_GPU (CPG_BASE + 0x0858) /* Reset ONOFF register GPU */
#define CPG_RST_ISU (CPG_BASE + 0x085C) /* Reset ONOFF register ISU */
#define CPG_RST_H264 (CPG_BASE + 0x0860) /* Reset ONOFF register H264 */
#define CPG_RST_CRU (CPG_BASE + 0x0864) /* Reset ONOFF register CRU */
#define CPG_RST_MIPI_DSI (CPG_BASE + 0x0868) /* Reset ONOFF register MIPI_DSI */
#define CPG_RST_LCDC (CPG_BASE + 0x086C) /* Reset ONOFF register LCDC */
#define CPG_RST_SSIF (CPG_BASE + 0x0870) /* Reset ONOFF register SSIF */
#define CPG_RST_SRC (CPG_BASE + 0x0874) /* Reset ONOFF register SRC */
#define CPG_RST_USB (CPG_BASE + 0x0878) /* Reset ONOFF register USB */
#define CPG_RST_ETH (CPG_BASE + 0x087C) /* Reset ONOFF register ETH */
#define CPG_RST_I2C (CPG_BASE + 0x0880) /* Reset ONOFF register I2C */
#define CPG_RST_SCIF (CPG_BASE + 0x0884) /* Reset ONOFF register SCIF */
#define CPG_RST_SCI (CPG_BASE + 0x0888) /* Reset ONOFF register SCI */
#define CPG_RST_IRDA (CPG_BASE + 0x088C) /* Reset ONOFF register IRDA */
#define CPG_RST_RSPI (CPG_BASE + 0x0890) /* Reset ONOFF register RSPI */
#define CPG_RST_CANFD (CPG_BASE + 0x0894) /* Reset ONOFF register CANFD */
#define CPG_RST_GPIO (CPG_BASE + 0x0898) /* Reset ONOFF register GPIO */
#define CPG_RST_TSIPG (CPG_BASE + 0x089C) /* Reset ONOFF register TSIPG */
#define CPG_RST_JAUTH (CPG_BASE + 0x08A0) /* Reset ONOFF register JAUTH */
#define CPG_RST_OTP (CPG_BASE + 0x08A4) /* Reset ONOFF register OTP */
#define CPG_RST_ADC (CPG_BASE + 0x08A8) /* Reset ONOFF register ADC */
#define CPG_RST_TSU (CPG_BASE + 0x08AC) /* Reset ONOFF register TSU */
#define CPG_RST_BBGU (CPG_BASE + 0x08B0) /* Reset ONOFF register BBGU */
#define CPG_RST_AXI_ACPU_BUS (CPG_BASE + 0x08B4) /* Reset ONOFF register AXI_ACPU_BUS */
#define CPG_RST_AXI_MCPU_BUS (CPG_BASE + 0x08B8) /* Reset ONOFF register AXI_MCPU_BUS */
#define CPG_RST_AXI_COM_BUS (CPG_BASE + 0x08BC) /* Reset ONOFF register AXI_COM_BUS */
#define CPG_RST_AXI_VIDEO_BUS (CPG_BASE + 0x08C0) /* Reset ONOFF register AXI_VIDEO_BUS */
#define CPG_RST_PERI_COM (CPG_BASE + 0x08C4) /* Reset ONOFF register PERI_COM */
#define CPG_RST_REG1_BUS (CPG_BASE + 0x08C8) /* Reset ONOFF register REG1_BUS */
#define CPG_RST_REG0_BUS (CPG_BASE + 0x08CC) /* Reset ONOFF register REG0_BUS */
#define CPG_RST_PERI_CPU (CPG_BASE + 0x08D0) /* Reset ONOFF register PERI_CPU */
#define CPG_RST_PERI_VIDEO (CPG_BASE + 0x08D4) /* Reset ONOFF register PERI_VIDEO */
#define CPG_RST_PERI_DDR (CPG_BASE + 0x08D8) /* Reset ONOFF register PERI_DDR */
#define CPG_RST_AXI_TZCDDR (CPG_BASE + 0x08DC) /* Reset ONOFF register AXI_TZCDDR */
#define CPG_RST_MTGPGS (CPG_BASE + 0x08E0) /* Reset ONOFF register MTGPGS */
#define CPG_RST_AXI_DEFAULT_SLV (CPG_BASE + 0x08E4) /* Reset ONOFF register AXI_DEFAULT_SLV */
#define CPG_RSTMON_CA55 (CPG_BASE + 0x0980) /* Reset monitor register CA55 */
#define CPG_RSTMON_CM33 (CPG_BASE + 0x0984) /* Reset monitor register CM33 */
#define CPG_RSTMON_SRAM_ACPU (CPG_BASE + 0x0988) /* Reset monitor register SRAM_ACPU */
#define CPG_RSTMON_SRAM_MCPU (CPG_BASE + 0x098C) /* Reset monitor register SRAM_MCPU */
#define CPG_RSTMON_ROM (CPG_BASE + 0x0990) /* Reset monitor register ROM */
#define CPG_RSTMON_GIC600 (CPG_BASE + 0x0994) /* Reset monitor register GIC600 */
#define CPG_RSTMON_IA55 (CPG_BASE + 0x0998) /* Reset monitor register IA55 */
#define CPG_RSTMON_IM33 (CPG_BASE + 0x099C) /* Reset monitor register IM33 */
#define CPG_RSTMON_MHU (CPG_BASE + 0x09A0) /* Reset monitor register MHU */
#define CPG_RSTMON_CST (CPG_BASE + 0x09A4) /* Reset monitor register CST */
#define CPG_RSTMON_SYC (CPG_BASE + 0x09A8) /* Reset monitor register SYC */
#define CPG_RSTMON_DMAC (CPG_BASE + 0x09AC) /* Reset monitor register DMAC */
#define CPG_RSTMON_SYSC (CPG_BASE + 0x09B0) /* Reset monitor register SYSC */
#define CPG_RSTMON_OSTM (CPG_BASE + 0x09B4) /* Reset monitor register OSTM */
#define CPG_RSTMON_MTU (CPG_BASE + 0x09B8) /* Reset monitor register MTU */
#define CPG_RSTMON_POE3 (CPG_BASE + 0x09BC) /* Reset monitor register POE3 */
#define CPG_RSTMON_GPT (CPG_BASE + 0x09C0) /* Reset monitor register GPT */
#define CPG_RSTMON_POEG (CPG_BASE + 0x09C4) /* Reset monitor register POEG */
#define CPG_RSTMON_WDT (CPG_BASE + 0x09C8) /* Reset monitor register WDT */
#define CPG_RSTMON_DDR (CPG_BASE + 0x09CC) /* Reset monitor register DDR */
#define CPG_RSTMON_SPI (CPG_BASE + 0x09D0) /* Reset monitor register SPI */
#define CPG_RSTMON_SDHI (CPG_BASE + 0x09D4) /* Reset monitor register SDHI */
#define CPG_RSTMON_GPU (CPG_BASE + 0x09D8) /* Reset monitor register GPU */
#define CPG_RSTMON_ISU (CPG_BASE + 0x09DC) /* Reset monitor register ISU */
#define CPG_RSTMON_H264 (CPG_BASE + 0x09E0) /* Reset monitor register H264 */
#define CPG_RSTMON_CRU (CPG_BASE + 0x09E4) /* Reset monitor register CRU */
#define CPG_RSTMON_MIPI_DSI (CPG_BASE + 0x09E8) /* Reset monitor register MIPI_DSI */
#define CPG_RSTMON_LCDC (CPG_BASE + 0x09EC) /* Reset monitor register LCDC */
#define CPG_RSTMON_SSIF (CPG_BASE + 0x09F0) /* Reset monitor register SSIF */
#define CPG_RSTMON_SRC (CPG_BASE + 0x09F4) /* Reset monitor register SRC */
#define CPG_RSTMON_USB (CPG_BASE + 0x09F8) /* Reset monitor register USB */
#define CPG_RSTMON_ETH (CPG_BASE + 0x09FC) /* Reset monitor register ETH */
#define CPG_RSTMON_I2C (CPG_BASE + 0x0A00) /* Reset monitor register I2C */
#define CPG_RSTMON_SCIF (CPG_BASE + 0x0A04) /* Reset monitor register SCIF */
#define CPG_RSTMON_SCI (CPG_BASE + 0x0A08) /* Reset monitor register SCI */
#define CPG_RSTMON_IRDA (CPG_BASE + 0x0A0C) /* Reset monitor register IRDA */
#define CPG_RSTMON_RSPI (CPG_BASE + 0x0A10) /* Reset monitor register RSPI */
#define CPG_RSTMON_CANFD (CPG_BASE + 0x0A14) /* Reset monitor register CANFD */
#define CPG_RSTMON_GPIO (CPG_BASE + 0x0A18) /* Reset monitor register GPIO */
#define CPG_RSTMON_TSIPG (CPG_BASE + 0x0A1C) /* Reset monitor register TSIPG */
#define CPG_RSTMON_JAUTH (CPG_BASE + 0x0A20) /* Reset monitor register JAUTH */
#define CPG_RSTMON_OTP (CPG_BASE + 0x0A24) /* Reset monitor register OTP */
#define CPG_RSTMON_ADC (CPG_BASE + 0x0A28) /* Reset monitor register ADC */
#define CPG_RSTMON_TSU (CPG_BASE + 0x0A2C) /* Reset monitor register TSU */
#define CPG_RSTMON_BBGU (CPG_BASE + 0x0A30) /* Reset monitor register BBGU */
#define CPG_RSTMON_AXI_ACPU_BUS (CPG_BASE + 0x0A34) /* Reset monitor register AXI_ACPU_BUS */
#define CPG_RSTMON_AXI_MCPU_BUS (CPG_BASE + 0x0A38) /* Reset monitor register AXI_MCPU_BUS */
#define CPG_RSTMON_AXI_COM_BUS (CPG_BASE + 0x0A3C) /* Reset monitor register AXI_COM_BUS */
#define CPG_RSTMON_AXI_VIDEO_BUS (CPG_BASE + 0x0A40) /* Reset monitor register AXI_VIDEO_BUS */
#define CPG_RSTMON_PERI_COM (CPG_BASE + 0x0A44) /* Reset monitor register PERI_COM */
#define CPG_RSTMON_REG1_BUS (CPG_BASE + 0x0A48) /* Reset monitor register REG1_BUS */
#define CPG_RSTMON_REG0_BUS (CPG_BASE + 0x0A4C) /* Reset monitor register REG0_BUS */
#define CPG_RSTMON_PERI_CPU (CPG_BASE + 0x0A50) /* Reset monitor register PERI_CPU */
#define CPG_RSTMON_PERI_VIDEO (CPG_BASE + 0x0A54) /* Reset monitor register PERI_VIDEO */
#define CPG_RSTMON_PERI_DDR (CPG_BASE + 0x0A58) /* Reset monitor register PERI_DDR */
#define CPG_RSTMON_AXI_TZCDDR (CPG_BASE + 0x0A5C) /* Reset monitor register AXI_TZCDDR */
#define CPG_RSTMON_MTGPGS (CPG_BASE + 0x0A60) /* Reset monitor register MTGPGS */
#define CPG_RSTMON_AXI_DEFAULT_SLV (CPG_BASE + 0x0A64) /* Reset monitor register AXI_DEFAULT_SLV */
#define CPG_EN_OSTM (CPG_BASE + 0x0B00) /* Enable ONOFF register_OSTM */
#define CPG_WDTOVF_RST (CPG_BASE + 0x0B10) /* WDT overflow system reset register */
#define CPG_WDTRST_SEL (CPG_BASE + 0x0B14) /* WDT reset selector register */
#define CPG_DBGRST (CPG_BASE + 0x0B20) /* Reset ONOFF register DBGRST */
#define CPG_CLUSTER_PCHMON (CPG_BASE + 0x0B30) /* CA55 Cluster Power Status Monitor Register */
#define CPG_CLUSTER_PCHCTL (CPG_BASE + 0x0B34) /* CA55 Cluster Power Status Control Register */
#define CPG_CORE0_PCHMON (CPG_BASE + 0x0B38) /* CA55 Core0 Power Status Monitor Register */
#define CPG_CORE0_PCHCTL (CPG_BASE + 0x0B3C) /* CA55 Core0 Power Status Control Register */
#define CPG_CORE1_PCHMON (CPG_BASE + 0x0B40) /* CA55 Core1 Power Status Monitor Register */
#define CPG_CORE1_PCHCTL (CPG_BASE + 0x0B44) /* CA55 Core1 Power Status Control Register */
#define CPG_BUS_ACPU_MSTOP (CPG_BASE + 0x0B60) /* MSTOP registerBUS_ACPU */
#define CPG_BUS_MCPU1_MSTOP (CPG_BASE + 0x0B64) /* MSTOP registerBUS_MCPU1 */
#define CPG_BUS_MCPU2_MSTOP (CPG_BASE + 0x0B68) /* MSTOP registerBUS_MCPU2 */
#define CPG_BUS_PERI_COM_MSTOP (CPG_BASE + 0x0B6C) /* MSTOP registerBUS_PERI_COM */
#define CPG_BUS_PERI_CPU_MSTOP (CPG_BASE + 0x0B70) /* MSTOP registerBUS_PERI_CPU */
#define CPG_BUS_PERI_DDR_MSTOP (CPG_BASE + 0x0B74) /* MSTOP registerBUS_PERI_DDR */
#define CPG_BUS_PERI_VIDEO_MSTOP (CPG_BASE + 0x0B78) /* MSTOP registerBUS_PERI_VIDEO */
#define CPG_BUS_REG0_MSTOP (CPG_BASE + 0x0B7C) /* MSTOP registerBUS_REG0 */
#define CPG_BUS_REG1_MSTOP (CPG_BASE + 0x0B80) /* MSTOP registerBUS_REG1 */
#define CPG_BUS_TZCDDR_MSTOP (CPG_BASE + 0x0B84) /* MSTOP registerBUS_TZCDDR */
#define CPG_MHU_MSTOP (CPG_BASE + 0x0B88) /* MSTOP registerMHU */
#define CPG_BUS_PERI_STP_MSTOP (CPG_BASE + 0x0B8C) /* MSTOP registerBUS_PERI_STP */
#define CPG_OTHERFUNC1_REG (CPG_BASE + 0x0BE8) /* Other function registers1 */
#define CPG_OTHERFUNC2_REG (CPG_BASE + 0x0BEC) /* Other function registers2 */
#define PLL1_STBY_RESETB (1 << 0)
#define PLL1_STBY_SSC_EN (1 << 2)
#define PLL1_STBY_SSC_MODE0 (1 << 4)
#define PLL1_STBY_SSC_MODE1 (1 << 5)
#define PLL1_STBY_RESETB_WEN (1 << 16)
#define PLL1_STBY_SSC_EN_WEN (1 << 18)
#define PLL1_STBY_SSC_MODE_WEN (1 << 20)
#define PLL1_CLK1_DIV_P_24M (1 << 0)
#define PLL1_CLK1_DIV_P_12M (2 << 0)
#define PLL1_CLK1_DIV_P_8M (3 << 0)
#define PLL1_CLK1_DIV_P_6M (4 << 0)
#define PLL1_CLK2_DIV_S_RATIO1 (0 << 0)
#define PLL1_CLK2_DIV_S_RATIO2 (1 << 0)
#define PLL1_CLK2_DIV_S_RATIO4 (2 << 0)
#define PLL1_CLK2_DIV_S_RATIO8 (3 << 0)
#define PLL1_CLK2_DIV_S_RATIO16 (4 << 0)
#define PLL1_CLK2_DIV_S_RATIO32 (5 << 0)
#define PLL1_CLK2_DIV_S_RATIO64 (6 << 0)
#define PLL1_MON_PLL1_RESETB (1 << 0)
#define PLL1_MON_PLL1_LOCK (1 << 4)
#define PLL4_STBY_RESETB (1 << 0)
#define PLL4_STBY_SSC_EN (1 << 2)
#define PLL4_STBY_SSC_MODE0 (1 << 4)
#define PLL4_STBY_SSC_MODE1 (1 << 5)
#define PLL4_STBY_RESETB_WEN (1 << 16)
#define PLL4_STBY_SSC_EN_WEN (1 << 18)
#define PLL4_STBY_SSC_MODE_WEN (1 << 20)
#define PLL4_CLK1_DIV_P_24M (1 << 0)
#define PLL4_CLK1_DIV_P_12M (2 << 0)
#define PLL4_CLK1_DIV_P_8M (3 << 0)
#define PLL4_CLK1_DIV_P_6M (4 << 0)
#define PLL4_CLK2_DIV_S_RATIO1 (0 << 0)
#define PLL4_CLK2_DIV_S_RATIO2 (1 << 0)
#define PLL4_CLK2_DIV_S_RATIO4 (2 << 0)
#define PLL4_CLK2_DIV_S_RATIO8 (3 << 0)
#define PLL4_CLK2_DIV_S_RATIO16 (4 << 0)
#define PLL4_CLK2_DIV_S_RATIO32 (5 << 0)
#define PLL4_CLK2_DIV_S_RATIO64 (6 << 0)
#define PLL4_MON_PLL4_RESETB (1 << 0)
#define PLL4_MON_PLL4_LOCK (1 << 4)
#define PLL6_STBY_RESETB (1 << 0)
#define PLL6_STBY_SSC_EN (1 << 2)
#define PLL6_STBY_SSC_MODE0 (1 << 4)
#define PLL6_STBY_SSC_MODE1 (1 << 5)
#define PLL6_STBY_RESETB_WEN (1 << 16)
#define PLL6_STBY_SSC_EN_WEN (1 << 18)
#define PLL6_STBY_SSC_MODE_WEN (1 << 20)
#define PLL6_CLK1_DIV_P_24M (1 << 0)
#define PLL6_CLK1_DIV_P_12M (2 << 0)
#define PLL6_CLK1_DIV_P_8M (3 << 0)
#define PLL6_CLK1_DIV_P_6M (4 << 0)
#define PLL6_CLK2_DIV_S_RATIO1 (0 << 0)
#define PLL6_CLK2_DIV_S_RATIO2 (1 << 0)
#define PLL6_CLK2_DIV_S_RATIO4 (2 << 0)
#define PLL6_CLK2_DIV_S_RATIO8 (3 << 0)
#define PLL6_CLK2_DIV_S_RATIO16 (4 << 0)
#define PLL6_CLK2_DIV_S_RATIO32 (5 << 0)
#define PLL6_CLK2_DIV_S_RATIO64 (6 << 0)
#define PLL6_MON_PLL6_RESETB (1 << 0)
#define PLL6_MON_PLL6_LOCK (1 << 4)
#define PLL1_SETTING_SEL_PLL1 (1 << 0)
#define PLL1_SETTING_SEL_PLL1_WEN (1 << 16)
#define PLL_CLK_DIV_M_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 6))))
#define PLL_CLK_DIV_K_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 16))))
#define PLL_CLK_MRR_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 8))))
#define PLL_CLK_MFR_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 16))))
#define PLL2_STBY_RESETB (1 << 0)
#define PLL2_STBY_SSC_EN (1 << 2)
#define PLL2_STBY_DOWNSPREAD (1 << 4)
#define PLL2_STBY_RESETB_WEN (1 << 16)
#define PLL2_STBY_SSC_EN_WEN (1 << 18)
#define PLL2_STBY_DOWNSPREAD_WEN (1 << 20)
#define PLL2_CLK1_POSTDIV1_WEN (1 << 16)
#define PLL2_CLK1_POSTDIV2_WEN (1 << 20)
#define PLL2_CLK1_REFDIV_WEN (1 << 24)
#define PLL2_CLK2_DACPD (1 << 0)
#define PLL2_CLK2_DSMPD (1 << 2)
#define PLL2_CLK2_FOUT4PHASEPD (1 << 4)
#define PLL2_CLK2_FOUTPOSTDIVPD (1 << 6)
#define PLL2_CLK2_FOUTVCOPD (1 << 8)
#define PLL2_CLK2_DACPD_WEN (1 << 16)
#define PLL2_CLK2_DSMPD_WEN (1 << 18)
#define PLL2_CLK2_FOUT4PHASEPD_WEN (1 << 20)
#define PLL2_CLK2_FOUTPOSTDIVPD_WEN (1 << 22)
#define PLL2_CLK2_FOUTVCOPD_WEN (1 << 24)
#define PLL2_CLK6_SEL_EXTWAVE (1 << 0)
#define PLL2_CLK6_SEL_EXTWAVE_WEN (1 << 16)
#define PLL2_MON_PLL2_RESETB (1 << 0)
#define PLL2_MON_PLL2_LOCK (1 << 4)
#define PLL3_STBY_RESETB (1 << 0)
#define PLL3_STBY_SSC_EN (1 << 2)
#define PLL3_STBY_DOWNSPREAD (1 << 4)
#define PLL3_STBY_RESETB_WEN (1 << 16)
#define PLL3_STBY_SSC_EN_WEN (1 << 18)
#define PLL3_STBY_DOWNSPREAD_WEN (1 << 20)
#define PLL3_CLK1_POSTDIV1_WEN (1 << 16)
#define PLL3_CLK1_POSTDIV2_WEN (1 << 20)
#define PLL3_CLK1_REFDIV_WEN (1 << 24)
#define PLL3_CLK2_DACPD (1 << 0)
#define PLL3_CLK2_DSMPD (1 << 2)
#define PLL3_CLK2_FOUT4PHASEPD (1 << 4)
#define PLL3_CLK2_FOUTPOSTDIVPD (1 << 6)
#define PLL3_CLK2_FOUTVCOPD (1 << 8)
#define PLL3_CLK2_DACPD_WEN (1 << 16)
#define PLL3_CLK2_DSMPD_WEN (1 << 18)
#define PLL3_CLK2_FOUT4PHASEPD_WEN (1 << 20)
#define PLL3_CLK2_FOUTPOSTDIVPD_WEN (1 << 22)
#define PLL3_CLK2_FOUTVCOPD_WEN (1 << 24)
#define PLL3_CLK6_SEL_EXTWAVE (1 << 0)
#define PLL3_CLK6_SEL_EXTWAVE_WEN (1 << 16)
#define PLL3_MON_PLL3_RESETB (1 << 0)
#define PLL3_MON_PLL3_LOCK (1 << 4)
#define PLL5_STBY_RESETB (1 << 0)
#define PLL5_STBY_SSC_EN (1 << 2)
#define PLL5_STBY_DOWNSPREAD (1 << 4)
#define PLL5_STBY_RESETB_WEN (1 << 16)
#define PLL5_STBY_SSC_EN_WEN (1 << 18)
#define PLL5_STBY_DOWNSPREAD_WEN (1 << 20)
#define PLL5_CLK1_POSTDIV1_WEN (1 << 16)
#define PLL5_CLK1_POSTDIV2_WEN (1 << 20)
#define PLL5_CLK1_REFDIV_WEN (1 << 24)
#define PLL5_CLK2_DACPD (1 << 0)
#define PLL5_CLK2_DSMPD (1 << 2)
#define PLL5_CLK2_FOUT4PHASEPD (1 << 4)
#define PLL5_CLK2_FOUTPOSTDIVPD (1 << 6)
#define PLL5_CLK2_FOUTVCOPD (1 << 8)
#define PLL5_CLK2_DACPD_WEN (1 << 16)
#define PLL5_CLK2_DSMPD_WEN (1 << 18)
#define PLL5_CLK2_FOUT4PHASEPD_WEN (1 << 20)
#define PLL5_CLK2_FOUTPOSTDIVPD_WEN (1 << 22)
#define PLL5_CLK2_FOUTVCOPD_WEN (1 << 24)
#define PLL5_CLK6_SEL_EXTWAVE (1 << 0)
#define PLL5_CLK6_SEL_EXTWAVE_WEN (1 << 16)
#define PLL5_MON_PLL5_RESETB (1 << 0)
#define PLL5_MON_PLL5_LOCK (1 << 4)
#define PLL_CLK_POSTDIV1_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 0))))
#define PLL_CLK_POSTDIV2_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 4))))
#define PLL_CLK_REFDIV_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 8))))
#define PLL_CLK_DIVVAL_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 0))))
#define PLL_CLK_FRACIN_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 8))))
#define PLL_CLK_EXT_MAXADDR_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 0))))
#define PLL_CLK_INITIN_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 16))))
#define PLL_CLK_SPREAD_SET(a, b) (mmio_write_32(a, ((mmio_read_32(a)) | (b << 0))))
#define PL1_DDIV_DIVPL1_SET_1_1 (0 << 0)
#define PL1_DDIV_DIVPL1_SET_1_2 (1 << 0)
#define PL1_DDIV_DIVPL1_SET_1_4 (2 << 0)
#define PL1_DDIV_DIVPL1_SET_1_8 (3 << 0)
#define PL1_DDIV_DIVPL1_SET_WEN (1 << 16)
#define PL2_DDIV_DIVPL2A_SET_1_1 (0 << 0)
#define PL2_DDIV_DIVPL2A_SET_1_2 (1 << 0)
#define PL2_DDIV_DIVPL2A_SET_1_4 (2 << 0)
#define PL2_DDIV_DIVPL2A_SET_1_8 (3 << 0)
#define PL2_DDIV_DIVPL2A_SET_1_32 (4 << 0)
#define PL2_DDIV_DIVPL2B_SET_1_1 (0 << 4)
#define PL2_DDIV_DIVPL2B_SET_1_2 (1 << 4)
#define PL2_DDIV_DIVPL2B_SET_1_4 (2 << 4)
#define PL2_DDIV_DIVPL2B_SET_1_8 (3 << 4)
#define PL2_DDIV_DIVPL2B_SET_1_32 (4 << 4)
#define PL2_DDIV_DIVPL2C_SET_1_1 (0 << 4)
#define PL2_DDIV_DIVPL2C_SET_1_2 (1 << 4)
#define PL2_DDIV_DIVPL2C_SET_1_4 (2 << 4)
#define PL2_DDIV_DIVPL2C_SET_1_8 (3 << 4)
#define PL2_DDIV_DIVPL2C_SET_1_32 (4 << 4)
#define PL2_DDIV_DIVDSILPCLK_SET_1_16 (0 << 12)
#define PL2_DDIV_DIVDSILPCLK_SET_1_32 (1 << 12)
#define PL2_DDIV_DIVDSILPCLK_SET_1_64 (2 << 12)
#define PL2_DDIV_DIVDSILPCLK_SET_1_128 (3 << 12)
#define PL2_DDIV_DIVPL2A_WEN (1 << 16)
#define PL2_DDIV_DIVPL2B_WEN (1 << 20)
#define PL2_DDIV_DIVPL2C_WEN (1 << 24)
#define PL2_DDIV_DIVDSILPCLK_WEN (1 << 28)
#define PL3A_DDIV_DIVPL3A_SET_1_1 (0 << 0)
#define PL3A_DDIV_DIVPL3A_SET_1_2 (1 << 0)
#define PL3A_DDIV_DIVPL3A_SET_1_4 (2 << 0)
#define PL3A_DDIV_DIVPL3A_SET_1_8 (3 << 0)
#define PL3A_DDIV_DIVPL3A_SET_1_32 (4 << 0)
#define PL3A_DDIV_DIVPL3B_SET_1_1 (0 << 0)
#define PL3A_DDIV_DIVPL3B_SET_1_2 (1 << 0)
#define PL3A_DDIV_DIVPL3B_SET_1_4 (2 << 0)
#define PL3A_DDIV_DIVPL3B_SET_1_8 (3 << 0)
#define PL3A_DDIV_DIVPL3B_SET_1_32 (4 << 0)
#define PL3A_DDIV_DIVPL3C_SET_1_1 (0 << 0)
#define PL3A_DDIV_DIVPL3C_SET_1_2 (1 << 0)
#define PL3A_DDIV_DIVPL3C_SET_1_4 (2 << 0)
#define PL3A_DDIV_DIVPL3C_SET_1_8 (3 << 0)
#define PL3A_DDIV_DIVPL3C_SET_1_32 (4 << 0)
#define PL3A_DDIV_DIVPL3A_WEN (1 << 16)
#define PL3A_DDIV_DIVPL3B_WEN (1 << 20)
#define PL3A_DDIV_DIVPL3C_WEN (1 << 24)
#define PL3B_DDIV_DIVPL3CLK200FIX_SET_1_1 (0 << 0)
#define PL3B_DDIV_DIVPL3CLK200FIX_SET_1_2 (1 << 0)
#define PL3B_DDIV_DIVPL3CLK200FIX_SET_1_4 (2 << 0)
#define PL3B_DDIV_DIVPL3CLK200FIX_SET_1_8 (3 << 0)
#define PL3B_DDIV_DIVPL3CLK200FIX_SET_1_32 (4 << 0)
#define PL3B_DDIV_DIVPL3CLK200FIX_WEN (1 << 16)
#define PL6_DDIV_DIVGPU_SET_1_1 (0 << 0)
#define PL6_DDIV_DIVGPU_SET_1_2 (1 << 0)
#define PL6_DDIV_DIVGPU_SET_1_4 (2 << 0)
#define PL6_DDIV_DIVGPU_SET_1_8 (3 << 0)
#define PL6_DDIV_DIVGPU_WEN (1 << 16)
#define PL2SDHI_DSEL_SEL_SDHI0_SET_CLK533FIX_C (1 << 0)
#define PL2SDHI_DSEL_SEL_SDHI0_SET_DIV_PLL2_DIV8 (2 << 0)
#define PL2SDHI_DSEL_SEL_SDHI0_SET_DIV_PLL2_DIV12 (3 << 0)
#define PL2SDHI_DSEL_SEL_SDHI1_SET_CLK533FIX_C (1 << 4)
#define PL2SDHI_DSEL_SEL_SDHI1_SET_DIV_PLL2_DIV8 (2 << 4)
#define PL2SDHI_DSEL_SEL_SDHI1_SET_DIV_PLL2_DIV12 (3 << 4)
#define PL2SDHI_DSEL_SEL_SDHI0_WEN (1 << 16)
#define PL2SDHI_DSEL_SEL_SDHI1_WEN (1 << 20)
#define PL4_DSEL_SEL_PLL4_SET (1 << 0)
#define PL4_DSEL_SEL_PLL4_WEN (1 << 16)
#define CLKSTATUS_DIVPL1_STS (1 << 0)
#define CLKSTATUS_DIVPL2A_STS (1 << 4)
#define CLKSTATUS_DIVPL2B_STS (1 << 5)
#define CLKSTATUS_DIVPL2C_STS (1 << 6)
#define CLKSTATUS_DIVDSILPCLK_STS (1 << 7)
#define CLKSTATUS_DIVPL3A_STS (1 << 8)
#define CLKSTATUS_DIVPL3B_STS (1 << 9)
#define CLKSTATUS_DIVPL3C_STS (1 << 10)
#define CLKSTATUS_DIVPL3CLK200FIX_STS (1 << 11)
#define CLKSTATUS_DIVGPU_STS (1 << 20)
#define CLKSTATUS_SELSDHI0_STS (1 << 28)
#define CLKSTATUS_SELSDHI1_STS (1 << 29)
#define CLKSTATUS_SELPLL4_STS (1 << 31)
#define PL1_CA55_SSEL_SEL_PLL1_SET (1 << 0)
#define PL1_CA55_SSEL_SEL_PLL1_WEN (1 << 16)
#define PL2_SSEL_SEL_PLL2_1_SET (1 << 0)
#define PL2_SSEL_SEL_PLL2_2_SET (1 << 4)
#define PL2_SSEL_SEL_PLL2_1_WEN (1 << 16)
#define PL2_SSEL_SEL_PLL2_2_WEN (1 << 20)
#define PL3_SSEL_SEL_PLL3_1_SET (1 << 0)
#define PL3_SSEL_SEL_PLL3_2_SET (1 << 4)
#define PL3_SSEL_SEL_PLL3_3_SET (1 << 8)
#define PL3_SSEL_SEL_PLL3_1_WEN (1 << 16)
#define PL3_SSEL_SEL_PLL3_2_WEN (1 << 20)
#define PL3_SSEL_SEL_PLL3_3_WEN (1 << 24)
#define PL5_SSEL_SEL_PLL5_1_SET (1 << 0)
#define PL5_SSEL_SEL_PLL5_2_SET (1 << 4)
#define PL5_SSEL_SEL_PLL5_1_WEN (1 << 16)
#define PL5_SSEL_SEL_PLL5_2_WEN (1 << 20)
#define PL6_SSEL_SEL_PLL6_1_SET (1 << 0)
#define PL6_SSEL_SEL_GPU1_1_SET (1 << 4)
#define PL6_SSEL_SEL_GPU1_2_SET (1 << 8)
#define PL6_SSEL_SEL_GPU2_SET (1 << 12)
#define PL6_SSEL_SEL_PLL6_1_WEN (1 << 16)
#define PL6_SSEL_SEL_GPU1_1_WEN (1 << 20)
#define PL6_SSEL_SEL_GPU1_2_WEN (1 << 24)
#define PL6_SSEL_SEL_GPU2_WEN (1 << 28)
#define PL6_ETH_SSEL_SEL_PLL6_2_SET (1 << 0)
#define PL6_ETH_SSEL_SEL_ETH_SET (1 << 4)
#define PL6_ETH_SSEL_SEL_PLL6_2_WEN (1 << 16)
#define PL6_ETH_SSEL_SEL_ETH_WEN (1 << 20)
#define PL5_SDIV_DIVDSIA_SET_1_1 (0 << 0)
#define PL5_SDIV_DIVDSIA_SET_1_2 (1 << 0)
#define PL5_SDIV_DIVDSIA_SET_1_4 (2 << 0)
#define PL5_SDIV_DIVDSIA_SET_1_8 (3 << 0)
#define PL5_SDIV_DIVDSIB_SET_1_1 (0 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_2 (1 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_3 (2 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_4 (3 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_5 (4 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_6 (5 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_7 (6 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_8 (7 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_9 (8 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_10 (9 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_11 (10 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_12 (11 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_13 (12 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_14 (13 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_15 (14 << 8)
#define PL5_SDIV_DIVDSIB_SET_1_16 (15 << 8)
#define PL5_SDIV_DIVDSA_WEN (1 << 16)
#define PL5_SDIV_DIVSDIB_WEN (1 << 24)
#define CLKON_CLK0_ON (1 << 0)
#define CLKON_CLK0_ON_WEN (1 << 16)
#define CLKMON_UNIT0_CLK_MON (1 << 0)
#define RST_UNIT0_RSTB (1 << 0)
#define RST_UNIT0_RST_WEN (1 << 16)
#define RSTMON_UNIT0_RST_MON (1 << 0)
#define EN_OSTM_EN0_ON (1 << 0)
#define EN_OSTM_EN1_ON (1 << 1)
#define EN_OSTM_EN2_ON (1 << 2)
#define EN_OSTM_EN0_WEN (1 << 16)
#define EN_OSTM_EN1_WEN (1 << 17)
#define EN_OSTM_EN2_WEN (1 << 18)
#define WDTOVF_RST_WDTOVF0 (1 << 0)
#define WDTOVF_RST_WDTOVF1 (1 << 1)
#define WDTOVF_RST_WDTOVF2 (1 << 2)
#define WDTOVF_RST_WDTOVF3 (1 << 3)
#define WDTOVF_RST_WDTOVF0_WEN (1 << 16)
#define WDTOVF_RST_WDTOVF1_WEN (1 << 17)
#define WDTOVF_RST_WDTOVF2_WEN (1 << 18)
#define WDTOVF_RST_WDTOVF3_WEN (1 << 19)
#define WDTRST_SEL_WDTRSTSEL0 (1 << 0)
#define WDTRST_SEL_WDTRSTSEL1 (1 << 1)
#define WDTRST_SEL_WDTRSTSEL2 (1 << 2)
#define WDTRST_SEL_WDTRSTSEL3 (1 << 3)
#define WDTRST_SEL_WDTRSTSEL4 (1 << 4)
#define WDTRST_SEL_WDTRSTSEL5 (1 << 5)
#define WDTRST_SEL_WDTRSTSEL6 (1 << 6)
#define WDTRST_SEL_WDTRSTSEL7 (1 << 7)
#define WDTRST_SEL_WDTRSTSEL8 (1 << 8)
#define WDTRST_SEL_WDTRSTSEL9 (1 << 9)
#define WDTRST_SEL_WDTRSTSEL10 (1 << 10)
#define WDTRST_SEL_WDTRSTSEL0_WEN (1 << 16)
#define WDTRST_SEL_WDTRSTSEL1_WEN (1 << 17)
#define WDTRST_SEL_WDTRSTSEL2_WEN (1 << 18)
#define WDTRST_SEL_WDTRSTSEL3_WEN (1 << 19)
#define WDTRST_SEL_WDTRSTSEL4_WEN (1 << 20)
#define WDTRST_SEL_WDTRSTSEL5_WEN (1 << 21)
#define WDTRST_SEL_WDTRSTSEL6_WEN (1 << 22)
#define WDTRST_SEL_WDTRSTSEL7_WEN (1 << 23)
#define WDTRST_SEL_WDTRSTSEL8_WEN (1 << 24)
#define WDTRST_SEL_WDTRSTSEL9_WEN (1 << 25)
#define WDTRST_SEL_WDTRSTSEL10_WEN (1 << 26)
#define DBGRST_UNIT0_RSTB (1 << 0)
#define DBGRST_UNIT0_RST_WEN (1 << 16)
#define CLUSTER_PCHMON_PACCEPT_MON (1 << 0)
#define CLUSTER_PCHMON_PDENY_MON (1 << 1)
#define CLUSTER_PCHCTL_PREQ_SET (1 << 0)
#define CLUSTER_PCHCTL_PSTATE0_SET_ON (0x48 << 16)
#define CLUSTER_PCHCTL_PSTATE0_SET_OFF (0x00 << 16)
#define CORE0_PCHMON_PACCEPT0_MON (1 << 0)
#define CORE0_PCHMON_PDENY0_MON (1 << 1)
#define CORE0_PCHCTL_PREQ0_SET (1 << 0)
#define CORE0_PCHCTL_PSTATE0_SET_ON (0x08 << 16)
#define CORE0_PCHCTL_PSTATE0_SET_OFF_EMULATED (0x01 << 16)
#define CORE0_PCHCTL_PSTATE0_SET_OFF (0x00 << 16)
#define CORE1_PCHMON_PACCEPT1_MON (1 << 0)
#define CORE1_PCHMON_PDENY1_MON (1 << 1)
#define CORE1_PCHCTL_PREQ1_SET (1 << 0)
#define CORE1_PCHCTL_PSTATE1_SET_ON (0x08 << 16)
#define CORE1_PCHCTL_PSTATE1_SET_OFF_EMULATED (0x01 << 16)
#define CORE1_PCHCTL_PSTATE1_SET_OFF (0x00 << 16)
#define BUS_MSTOP_MSTOPMODE_SET (1 << 0)
#define BUS_MSTOP_MSTOPMODE_SET_WEN (1 << 16)
#define OTHERFUNC1_REG_RES0_SET (1 << 0)
#define OTHERFUNC1_REG_RES0_ON_WEN (1 << 16)
#define OTHERFUNC2_REG_RES0_SET (1 << 0)
#define OTHERFUNC2_REG_RES0_ON_WEN (1 << 16)
#define BIT0_ON (1 << 0)
#define BIT1_ON (1 << 1)
#define BIT2_ON (1 << 2)
#define BIT3_ON (1 << 3)
#define BIT4_ON (1 << 4)
#define BIT5_ON (1 << 5)
#define BIT6_ON (1 << 6)
#define BIT7_ON (1 << 7)
#define BIT8_ON (1 << 8)
#define BIT9_ON (1 << 9)
#define BIT10_ON (1 << 10)
#define BIT11_ON (1 << 11)
#define BIT12_ON (1 << 12)
#define BIT13_ON (1 << 13)
#define BIT14_ON (1 << 14)
#define BIT15_ON (1 << 15)
#define BIT16_ON (1 << 16)
#define BIT17_ON (1 << 17)
#define BIT18_ON (1 << 18)
#define BIT19_ON (1 << 19)
#define BIT20_ON (1 << 20)
#define BIT21_ON (1 << 21)
#define BIT22_ON (1 << 22)
#define BIT23_ON (1 << 23)
#define BIT24_ON (1 << 24)
#define BIT25_ON (1 << 25)
#define BIT26_ON (1 << 26)
#define BIT27_ON (1 << 27)
#define BIT28_ON (1 << 28)
#define BIT29_ON (1 << 29)
#define BIT30_ON (1 << 30)
#define BIT31_ON (1 << 31)
#endif /* __CPG_REGS_H__ */
| 60.725352 | 99 | 0.702053 |
c09d3948846ed015d2db7fd3743f8830fc8771d1 | 468 | h | C | Headers/SBLockScreenPluginOverlayViewController.h | MoTheNerd/oledlock | b1a79668a8f31d0c8cdfea11e14d5dc19654f380 | [
"MIT"
] | null | null | null | Headers/SBLockScreenPluginOverlayViewController.h | MoTheNerd/oledlock | b1a79668a8f31d0c8cdfea11e14d5dc19654f380 | [
"MIT"
] | null | null | null | Headers/SBLockScreenPluginOverlayViewController.h | MoTheNerd/oledlock | b1a79668a8f31d0c8cdfea11e14d5dc19654f380 | [
"MIT"
] | 1 | 2018-03-05T19:20:57.000Z | 2018-03-05T19:20:57.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "SBLockOverlayViewController.h"
@class SBLockScreenPlugin;
@interface SBLockScreenPluginOverlayViewController : SBLockOverlayViewController
{
SBLockScreenPlugin *_plugin;
}
+ (_Bool)_pluginNeedsOverlay:(id)arg1;
- (void).cxx_destruct;
- (id)_newOverlayView;
- (void)loadView;
- (id)initWithPlugin:(id)arg1;
@end
| 19.5 | 83 | 0.730769 |
69e259bc657f395de6958cc658d693ce787b99a2 | 220 | h | C | YReaderDemo/YReaderDemo/Other/YBaseViewController.h | yanxuewen/YReaderDemo | 0d3bccffb832a0bfb1f473e0c5cad054a8153a4f | [
"MIT"
] | 119 | 2016-12-17T16:26:05.000Z | 2021-09-07T11:03:34.000Z | Reader/Reader/Other/YBaseViewController.h | downloadDemo/ZSReader | 29dde987efa65a4e4aaa09bb9582872d4c4d7e57 | [
"Apache-2.0"
] | 4 | 2017-04-10T07:41:30.000Z | 2019-12-21T16:22:34.000Z | YReaderDemo/YReaderDemo/Other/YBaseViewController.h | yanxuewen/YReaderDemo | 0d3bccffb832a0bfb1f473e0c5cad054a8153a4f | [
"MIT"
] | 34 | 2016-12-21T08:56:31.000Z | 2021-06-18T04:43:41.000Z | //
// YBaseViewController.h
// YReaderDemo
//
// Created by yanxuewen on 2016/12/8.
// Copyright © 2016年 yxw. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface YBaseViewController : UIViewController
@end
| 15.714286 | 49 | 0.709091 |
07d9c2869ca9300c456d5bb20b8889813270c374 | 2,196 | h | C | memory/data.h | hominsu/FileCryptX | b2fe43d223f5259366a0b5c51c1d9063b4e9be68 | [
"MIT"
] | 4 | 2021-12-25T03:24:47.000Z | 2021-12-28T13:06:00.000Z | memory/data.h | hominsu/FileCryptX | b2fe43d223f5259366a0b5c51c1d9063b4e9be68 | [
"MIT"
] | null | null | null | memory/data.h | hominsu/FileCryptX | b2fe43d223f5259366a0b5c51c1d9063b4e9be68 | [
"MIT"
] | null | null | null | //
// Created by Homin Su on 2021/10/2.
//
#ifndef XFILECRYPT_DATA_DATA_H_
#define XFILECRYPT_DATA_DATA_H_
#include <memory>
#include <memory_resource>
/**
* @brief 内存池数据块
*/
class Data {
private:
void *data_ = nullptr;
bool end_ = false; ///< 是否是文件结尾
size_t size_ = 0; ///< 数据字节数
size_t memory_size_ = 0; ///< 申请内存空间字节数
std::shared_ptr<std::pmr::memory_resource> memory_resource_; ///< 内存池
private:
Data();
public:
~Data();
/**
* @brief 创建 Data 对象
* @param _memory_resource
* @return Data 的智能指针对象
*/
static std::shared_ptr<Data> Make(std::shared_ptr<std::pmr::memory_resource> _memory_resource);
/**
* @brief 创建内存空间
* @param _memory_size 占用内存字节数
* @return 创建的内存空间的指针,创建失败为空 nullptr
*/
void *New(size_t _memory_size);
/**
* @brief 获取数据块的指针
* @return 数据块的指针
*/
[[nodiscard]] void *data() const;
/**
* @brief 获取实际数据的字节数
* @return 实际数据的字节数
*/
[[nodiscard]] size_t size() const;
/**
* @brief 设置实际数据字节数
* @param size 实际数据字节数
*/
void set_size(size_t _size);
/**
* @brief 获取分配的内存大小
* @return size_t 分配的内存大小
*/
[[nodiscard]] size_t memory_size() const;
/**
* @brief 是否是文件结尾
* @return
*/
[[nodiscard]] bool end() const;
/**
* @brief 设置为文件结尾
* @param _end true or false
*/
void set_end(bool _end);
};
/**
* @brief 定义了 Byte、KB、MB、GB 的大小
*/
enum class Unit : size_t {
Byte = 1, KB = 1024 * Byte, MB = 1024 * KB, GB = 1024 * MB
};
/**
* @brief 将字节的大小换算成对应单位的大小
* @tparam size_type 输入类型,只能为算术类型
* @param _size 字节大小
* @param _unit 转换的单位
* @return 转换后的数值
*/
template<typename size_type,
class = typename std::enable_if<
std::is_arithmetic<size_type>::value>::type
>
double UnitConvert(size_type _size, Unit _unit) {
return _size / static_cast<double>(_unit);
}
constexpr size_t KB(size_t _size) {
return static_cast<size_t>(Unit::KB) * _size;
}
constexpr size_t MB(size_t _size) {
return static_cast<size_t>(Unit::MB) * _size;
}
constexpr size_t GB(size_t _size) {
return static_cast<size_t>(Unit::GB) * _size;
}
constexpr size_t LimitNum(size_t _a, size_t _b) {
return _a / _b;
}
#endif //XFILECRYPT_DATA_DATA_H_
| 18.610169 | 97 | 0.638889 |
b872fa98a7b487db3984bbe7569515c7d688fce9 | 713 | h | C | CsmCircleArea.h | waura/csm_anim | ec3d175ac28b3b87cb2c96f4ae5e1549f748130d | [
"MIT"
] | null | null | null | CsmCircleArea.h | waura/csm_anim | ec3d175ac28b3b87cb2c96f4ae5e1549f748130d | [
"MIT"
] | null | null | null | CsmCircleArea.h | waura/csm_anim | ec3d175ac28b3b87cb2c96f4ae5e1549f748130d | [
"MIT"
] | 1 | 2021-07-14T13:25:33.000Z | 2021-07-14T13:25:33.000Z | #ifndef _CSMCIRCLEAREA_H_
#define _CSMCIRCLEAREA_H_
#include <SkinMeshGL/SmgModel.h>
#include "ICsmArea.h"
class CsmCircleArea : public ICsmArea
{
public:
CsmCircleArea(){
q=0.2;
rho = 2.0;
m_pModel = NULL;
}
~CsmCircleArea(){
if(m_pModel){
ReleaseSmgModel(&m_pModel);
}
}
bool IsInArea(double x, double y);
void OnResetCsm();
double Getq(){ return q; }
void SetCsmAreaCtrl(ICsmAreaCtrl* pCsmAreaCtrl);
void SetPoints(int n, nmc::Vector<POS>& commitment_point, nmc::Vector<POS>& wave_source_point);
void DrawArea(int draw_mode);
private:
double q;
double rho;
SmgModel* m_pModel;
ICsmAreaCtrl* m_pCsmAreaCtrl;
};
#endif //_CSMCIRCLEAREA_H_ | 18.282051 | 97 | 0.685835 |
6afc61da328a292eb182ff0a0e6e77be6b7a1101 | 282 | h | C | include/layer.h | xinyandai/vqlayer | 7e959ce88e9817f9490efb9e08d8d9d7a53fe277 | [
"MIT"
] | 1 | 2020-04-18T05:56:32.000Z | 2020-04-18T05:56:32.000Z | include/layer.h | Chiaki530/vqlayer | 7e959ce88e9817f9490efb9e08d8d9d7a53fe277 | [
"MIT"
] | null | null | null | include/layer.h | Chiaki530/vqlayer | 7e959ce88e9817f9490efb9e08d8d9d7a53fe277 | [
"MIT"
] | 2 | 2020-04-18T05:56:28.000Z | 2022-01-08T02:42:55.000Z | //
// \author Xinyan DAI (xinyan.dai@outlook.com)
// Created by xinyan DAI on 17/2/2020.
//
#pragma once
#include "layer_pq.h"
#include "layer_rq.h"
#include "layer_cpq.h"
#include "layer_hash.h"
#include "layer_interface.h"
#include "layer_abstract.h"
#include "layer_standard.h"
| 20.142857 | 46 | 0.72695 |
35371e41af0b38b964fb7978ca1a90298a7e97c9 | 100,027 | c | C | netbsd/sys/arch/alpha/alpha/pmap.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | 1 | 2019-10-15T06:29:32.000Z | 2019-10-15T06:29:32.000Z | netbsd/sys/arch/alpha/alpha/pmap.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | null | null | null | netbsd/sys/arch/alpha/alpha/pmap.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | 3 | 2017-01-09T02:15:36.000Z | 2019-10-15T06:30:25.000Z | /* $NetBSD: pmap.c,v 1.191.8.1 2002/11/24 15:38:39 tron Exp $ */
/*-
* Copyright (c) 1998, 1999, 2000, 2001 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
* NASA Ames Research Center and by Chris G. Demetriou.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD 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 BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* the Systems Programming Group of the University of Utah Computer
* Science Department.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)pmap.c 8.6 (Berkeley) 5/27/94
*/
/*
* DEC Alpha physical map management code.
*
* History:
*
* This pmap started life as a Motorola 68851/68030 pmap,
* written by Mike Hibler at the University of Utah.
*
* It was modified for the DEC Alpha by Chris Demetriou
* at Carnegie Mellon University.
*
* Support for non-contiguous physical memory was added by
* Jason R. Thorpe of the Numerical Aerospace Simulation
* Facility, NASA Ames Research Center and Chris Demetriou.
*
* Page table management and a major cleanup were undertaken
* by Jason R. Thorpe, with lots of help from Ross Harvey of
* Avalon Computer Systems and from Chris Demetriou.
*
* Support for the new UVM pmap interface was written by
* Jason R. Thorpe.
*
* Support for ASNs was written by Jason R. Thorpe, again
* with help from Chris Demetriou and Ross Harvey.
*
* The locking protocol was written by Jason R. Thorpe,
* using Chuck Cranor's i386 pmap for UVM as a model.
*
* TLB shootdown code was written by Jason R. Thorpe.
*
* Notes:
*
* All page table access is done via K0SEG. The one exception
* to this is for kernel mappings. Since all kernel page
* tables are pre-allocated, we can use the Virtual Page Table
* to access PTEs that map K1SEG addresses.
*
* Kernel page table pages are statically allocated in
* pmap_bootstrap(), and are never freed. In the future,
* support for dynamically adding additional kernel page
* table pages may be added. User page table pages are
* dynamically allocated and freed.
*
* This pmap implementation only supports NBPG == PAGE_SIZE.
* In practice, this is not a problem since PAGE_SIZE is
* initialized to the hardware page size in alpha_init().
*
* Bugs/misfeatures:
*
* - Some things could be optimized.
*/
/*
* Manages physical address maps.
*
* Since the information managed by this module is
* also stored by the logical address mapping module,
* this module may throw away valid virtual-to-physical
* mappings at almost any time. However, invalidations
* of virtual-to-physical mappings must be done as
* requested.
*
* In order to cope with hardware architectures which
* make virtual-to-physical map invalidates expensive,
* this module may delay invalidate or reduced protection
* operations until such time as they are actually
* necessary. This module is given full information as
* to which processors are currently using which maps,
* and to when physical maps must be made correct.
*/
#include "opt_lockdebug.h"
#include "opt_new_scc_driver.h"
#include "opt_sysv.h"
#include "opt_multiprocessor.h"
#include <sys/cdefs.h> /* RCS ID & Copyright macro defns */
__KERNEL_RCSID(0, "$NetBSD: pmap.c,v 1.191.8.1 2002/11/24 15:38:39 tron Exp $");
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/malloc.h>
#include <sys/pool.h>
#include <sys/user.h>
#include <sys/buf.h>
#ifdef SYSVSHM
#include <sys/shm.h>
#endif
#include <uvm/uvm.h>
#include <machine/atomic.h>
#include <machine/cpu.h>
#if defined(_PMAP_MAY_USE_PROM_CONSOLE) || defined(MULTIPROCESSOR)
#include <machine/rpb.h>
#endif
#ifdef DEBUG
#define PDB_FOLLOW 0x0001
#define PDB_INIT 0x0002
#define PDB_ENTER 0x0004
#define PDB_REMOVE 0x0008
#define PDB_CREATE 0x0010
#define PDB_PTPAGE 0x0020
#define PDB_ASN 0x0040
#define PDB_BITS 0x0080
#define PDB_COLLECT 0x0100
#define PDB_PROTECT 0x0200
#define PDB_BOOTSTRAP 0x1000
#define PDB_PARANOIA 0x2000
#define PDB_WIRING 0x4000
#define PDB_PVDUMP 0x8000
int debugmap = 0;
int pmapdebug = PDB_PARANOIA;
#endif
/*
* Given a map and a machine independent protection code,
* convert to an alpha protection code.
*/
#define pte_prot(m, p) (protection_codes[m == pmap_kernel() ? 0 : 1][p])
int protection_codes[2][8];
/*
* kernel_lev1map:
*
* Kernel level 1 page table. This maps all kernel level 2
* page table pages, and is used as a template for all user
* pmap level 1 page tables. When a new user level 1 page
* table is allocated, all kernel_lev1map PTEs for kernel
* addresses are copied to the new map.
*
* The kernel also has an initial set of kernel level 2 page
* table pages. These map the kernel level 3 page table pages.
* As kernel level 3 page table pages are added, more level 2
* page table pages may be added to map them. These pages are
* never freed.
*
* Finally, the kernel also has an initial set of kernel level
* 3 page table pages. These map pages in K1SEG. More level
* 3 page table pages may be added at run-time if additional
* K1SEG address space is required. These pages are never freed.
*
* NOTE: When mappings are inserted into the kernel pmap, all
* level 2 and level 3 page table pages must already be allocated
* and mapped into the parent page table.
*/
pt_entry_t *kernel_lev1map;
/*
* Virtual Page Table.
*/
pt_entry_t *VPT;
u_long kernel_pmap_store[PMAP_SIZEOF(ALPHA_MAXPROCS) / sizeof(u_long)];
paddr_t avail_start; /* PA of first available physical page */
paddr_t avail_end; /* PA of last available physical page */
static vaddr_t virtual_end; /* VA of last avail page (end of kernel AS) */
boolean_t pmap_initialized; /* Has pmap_init completed? */
u_long pmap_pages_stolen; /* instrumentation */
/*
* This variable contains the number of CPU IDs we need to allocate
* space for when allocating the pmap structure. It is used to
* size a per-CPU array of ASN and ASN Generation number.
*/
u_long pmap_ncpuids;
#ifndef PMAP_PV_LOWAT
#define PMAP_PV_LOWAT 16
#endif
int pmap_pv_lowat = PMAP_PV_LOWAT;
/*
* List of all pmaps, used to update them when e.g. additional kernel
* page tables are allocated. This list is kept LRU-ordered by
* pmap_activate().
*/
TAILQ_HEAD(, pmap) pmap_all_pmaps;
/*
* The pools from which pmap structures and sub-structures are allocated.
*/
struct pool pmap_pmap_pool;
struct pool pmap_l1pt_pool;
struct pool_cache pmap_l1pt_cache;
struct pool pmap_pv_pool;
/*
* Address Space Numbers.
*
* On many implementations of the Alpha architecture, the TLB entries and
* I-cache blocks are tagged with a unique number within an implementation-
* specified range. When a process context becomes active, the ASN is used
* to match TLB entries; if a TLB entry for a particular VA does not match
* the current ASN, it is ignored (one could think of the processor as
* having a collection of <max ASN> separate TLBs). This allows operating
* system software to skip the TLB flush that would otherwise be necessary
* at context switch time.
*
* Alpha PTEs have a bit in them (PG_ASM - Address Space Match) that
* causes TLB entries to match any ASN. The PALcode also provides
* a TBI (Translation Buffer Invalidate) operation that flushes all
* TLB entries that _do not_ have PG_ASM. We use this bit for kernel
* mappings, so that invalidation of all user mappings does not invalidate
* kernel mappings (which are consistent across all processes).
*
* pmap_next_asn always indicates to the next ASN to use. When
* pmap_next_asn exceeds pmap_max_asn, we start a new ASN generation.
*
* When a new ASN generation is created, the per-process (i.e. non-PG_ASM)
* TLB entries and the I-cache are flushed, the generation number is bumped,
* and pmap_next_asn is changed to indicate the first non-reserved ASN.
*
* We reserve ASN #0 for pmaps that use the global kernel_lev1map. This
* prevents the following scenario:
*
* * New ASN generation starts, and process A is given ASN #0.
*
* * A new process B (and thus new pmap) is created. The ASN,
* for lack of a better value, is initialized to 0.
*
* * Process B runs. It is now using the TLB entries tagged
* by process A. *poof*
*
* In the scenario above, in addition to the processor using using incorrect
* TLB entires, the PALcode might use incorrect information to service a
* TLB miss. (The PALcode uses the recursively mapped Virtual Page Table
* to locate the PTE for a faulting address, and tagged TLB entires exist
* for the Virtual Page Table addresses in order to speed up this procedure,
* as well.)
*
* By reserving an ASN for kernel_lev1map users, we are guaranteeing that
* new pmaps will initially run with no TLB entries for user addresses
* or VPT mappings that map user page tables. Since kernel_lev1map only
* contains mappings for kernel addresses, and since those mappings
* are always made with PG_ASM, sharing an ASN for kernel_lev1map users is
* safe (since PG_ASM mappings match any ASN).
*
* On processors that do not support ASNs, the PALcode invalidates
* the TLB and I-cache automatically on swpctx. We still still go
* through the motions of assigning an ASN (really, just refreshing
* the ASN generation in this particular case) to keep the logic sane
* in other parts of the code.
*/
u_int pmap_max_asn; /* max ASN supported by the system */
/* next ASN and current ASN generation */
struct pmap_asn_info pmap_asn_info[ALPHA_MAXPROCS];
/*
* Locking:
*
* This pmap module uses two types of locks: `normal' (sleep)
* locks and `simple' (spin) locks. They are used as follows:
*
* READ/WRITE SPIN LOCKS
* ---------------------
*
* * pmap_main_lock - This lock is used to prevent deadlock and/or
* provide mutex access to the pmap module. Most operations lock
* the pmap first, then PV lists as needed. However, some operations,
* such as pmap_page_protect(), lock the PV lists before locking
* the pmaps. To prevent deadlock, we require a mutex lock on the
* pmap module if locking in the PV->pmap direction. This is
* implemented by acquiring a (shared) read lock on pmap_main_lock
* if locking pmap->PV and a (exclusive) write lock if locking in
* the PV->pmap direction. Since only one thread can hold a write
* lock at a time, this provides the mutex.
*
* SIMPLE LOCKS
* ------------
*
* * pm_slock (per-pmap) - This lock protects all of the members
* of the pmap structure itself. This lock will be asserted
* in pmap_activate() and pmap_deactivate() from a critical
* section of cpu_switch(), and must never sleep. Note that
* in the case of the kernel pmap, interrupts which cause
* memory allocation *must* be blocked while this lock is
* asserted.
*
* * pvh_slock (per-vm_page) - This lock protects the PV list
* for a specified managed page.
*
* * pmap_all_pmaps_slock - This lock protects the global list of
* all pmaps. Note that a pm_slock must never be held while this
* lock is held.
*
* * pmap_growkernel_slock - This lock protects pmap_growkernel()
* and the virtual_end variable.
*
* There is a lock ordering constraint for pmap_growkernel_slock.
* pmap_growkernel() acquires the locks in the following order:
*
* pmap_growkernel_slock -> pmap_all_pmaps_slock ->
* pmap->pm_slock
*
* But pmap_lev1map_create() is called with pmap->pm_slock held,
* and also needs to acquire the pmap_growkernel_slock. So,
* we require that the caller of pmap_lev1map_create() (currently,
* the only caller is pmap_enter()) acquire pmap_growkernel_slock
* before acquring pmap->pm_slock.
*
* Address space number management (global ASN counters and per-pmap
* ASN state) are not locked; they use arrays of values indexed
* per-processor.
*
* All internal functions which operate on a pmap are called
* with the pmap already locked by the caller (which will be
* an interface function).
*/
struct lock pmap_main_lock;
struct simplelock pmap_all_pmaps_slock;
struct simplelock pmap_growkernel_slock;
#if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
#define PMAP_MAP_TO_HEAD_LOCK() \
spinlockmgr(&pmap_main_lock, LK_SHARED, NULL)
#define PMAP_MAP_TO_HEAD_UNLOCK() \
spinlockmgr(&pmap_main_lock, LK_RELEASE, NULL)
#define PMAP_HEAD_TO_MAP_LOCK() \
spinlockmgr(&pmap_main_lock, LK_EXCLUSIVE, NULL)
#define PMAP_HEAD_TO_MAP_UNLOCK() \
spinlockmgr(&pmap_main_lock, LK_RELEASE, NULL)
#else
#define PMAP_MAP_TO_HEAD_LOCK() /* nothing */
#define PMAP_MAP_TO_HEAD_UNLOCK() /* nothing */
#define PMAP_HEAD_TO_MAP_LOCK() /* nothing */
#define PMAP_HEAD_TO_MAP_UNLOCK() /* nothing */
#endif /* MULTIPROCESSOR || LOCKDEBUG */
#if defined(MULTIPROCESSOR)
/*
* TLB Shootdown:
*
* When a mapping is changed in a pmap, the TLB entry corresponding to
* the virtual address must be invalidated on all processors. In order
* to accomplish this on systems with multiple processors, messages are
* sent from the processor which performs the mapping change to all
* processors on which the pmap is active. For other processors, the
* ASN generation numbers for that processor is invalidated, so that
* the next time the pmap is activated on that processor, a new ASN
* will be allocated (which implicitly invalidates all TLB entries).
*
* Note, we can use the pool allocator to allocate job entries
* since pool pages are mapped with K0SEG, not with the TLB.
*/
struct pmap_tlb_shootdown_job {
TAILQ_ENTRY(pmap_tlb_shootdown_job) pj_list;
vaddr_t pj_va; /* virtual address */
pmap_t pj_pmap; /* the pmap which maps the address */
pt_entry_t pj_pte; /* the PTE bits */
};
struct pmap_tlb_shootdown_q {
TAILQ_HEAD(, pmap_tlb_shootdown_job) pq_head;
int pq_pte; /* aggregate PTE bits */
int pq_count; /* number of pending requests */
int pq_tbia; /* pending global flush */
struct simplelock pq_slock; /* spin lock on queue */
} pmap_tlb_shootdown_q[ALPHA_MAXPROCS];
#define PSJQ_LOCK(pq, s) \
do { \
s = splvm(); \
simple_lock(&(pq)->pq_slock); \
} while (0)
#define PSJQ_UNLOCK(pq, s) \
do { \
simple_unlock(&(pq)->pq_slock); \
splx(s); \
} while (0)
/* If we have more pending jobs than this, we just nail the whole TLB. */
#define PMAP_TLB_SHOOTDOWN_MAXJOBS 6
struct pool pmap_tlb_shootdown_job_pool;
void pmap_tlb_shootdown_q_drain(struct pmap_tlb_shootdown_q *);
struct pmap_tlb_shootdown_job *pmap_tlb_shootdown_job_get
(struct pmap_tlb_shootdown_q *);
void pmap_tlb_shootdown_job_put(struct pmap_tlb_shootdown_q *,
struct pmap_tlb_shootdown_job *);
#endif /* MULTIPROCESSOR */
#define PAGE_IS_MANAGED(pa) (vm_physseg_find(atop(pa), NULL) != -1)
/*
* Internal routines
*/
void alpha_protection_init(void);
void pmap_do_remove(pmap_t, vaddr_t, vaddr_t, boolean_t);
boolean_t pmap_remove_mapping(pmap_t, vaddr_t, pt_entry_t *,
boolean_t, long);
void pmap_changebit(struct vm_page *, pt_entry_t, pt_entry_t, long);
/*
* PT page management functions.
*/
int pmap_lev1map_create(pmap_t, long);
void pmap_lev1map_destroy(pmap_t, long);
int pmap_ptpage_alloc(pmap_t, pt_entry_t *, int);
void pmap_ptpage_free(pmap_t, pt_entry_t *);
void pmap_l3pt_delref(pmap_t, vaddr_t, pt_entry_t *, long);
void pmap_l2pt_delref(pmap_t, pt_entry_t *, pt_entry_t *, long);
void pmap_l1pt_delref(pmap_t, pt_entry_t *, long);
void *pmap_l1pt_alloc(struct pool *, int);
void pmap_l1pt_free(struct pool *, void *);
struct pool_allocator pmap_l1pt_allocator = {
pmap_l1pt_alloc, pmap_l1pt_free, 0,
};
int pmap_l1pt_ctor(void *, void *, int);
/*
* PV table management functions.
*/
int pmap_pv_enter(pmap_t, struct vm_page *, vaddr_t, pt_entry_t *,
boolean_t);
void pmap_pv_remove(pmap_t, struct vm_page *, vaddr_t, boolean_t);
void *pmap_pv_page_alloc(struct pool *, int);
void pmap_pv_page_free(struct pool *, void *);
struct pool_allocator pmap_pv_page_allocator = {
pmap_pv_page_alloc, pmap_pv_page_free, 0,
};
#ifdef DEBUG
void pmap_pv_dump(paddr_t);
#endif
#define pmap_pv_alloc() pool_get(&pmap_pv_pool, PR_NOWAIT)
#define pmap_pv_free(pv) pool_put(&pmap_pv_pool, (pv))
/*
* ASN management functions.
*/
void pmap_asn_alloc(pmap_t, long);
/*
* Misc. functions.
*/
boolean_t pmap_physpage_alloc(int, paddr_t *);
void pmap_physpage_free(paddr_t);
int pmap_physpage_addref(void *);
int pmap_physpage_delref(void *);
/*
* PMAP_ISACTIVE{,_TEST}:
*
* Check to see if a pmap is active on the current processor.
*/
#define PMAP_ISACTIVE_TEST(pm, cpu_id) \
(((pm)->pm_cpus & (1UL << (cpu_id))) != 0)
#if defined(DEBUG) && !defined(MULTIPROCESSOR)
#define PMAP_ISACTIVE(pm, cpu_id) \
({ \
/* \
* XXX This test is not MP-safe. \
*/ \
int isactive_ = PMAP_ISACTIVE_TEST(pm, cpu_id); \
\
if (curproc != NULL && curproc->p_vmspace != NULL && \
(isactive_ ^ ((pm) == curproc->p_vmspace->vm_map.pmap))) \
panic("PMAP_ISACTIVE"); \
(isactive_); \
})
#else
#define PMAP_ISACTIVE(pm, cpu_id) PMAP_ISACTIVE_TEST(pm, cpu_id)
#endif /* DEBUG && !MULTIPROCESSOR */
/*
* PMAP_ACTIVATE_ASN_SANITY:
*
* DEBUG sanity checks for ASNs within PMAP_ACTIVATE.
*/
#ifdef DEBUG
#define PMAP_ACTIVATE_ASN_SANITY(pmap, cpu_id) \
do { \
struct pmap_asn_info *__pma = &(pmap)->pm_asni[(cpu_id)]; \
struct pmap_asn_info *__cpma = &pmap_asn_info[(cpu_id)]; \
\
if ((pmap)->pm_lev1map == kernel_lev1map) { \
/* \
* This pmap implementation also ensures that pmaps \
* referencing kernel_lev1map use a reserved ASN \
* ASN to prevent the PALcode from servicing a TLB \
* miss with the wrong PTE. \
*/ \
if (__pma->pma_asn != PMAP_ASN_RESERVED) { \
printf("kernel_lev1map with non-reserved ASN " \
"(line %d)\n", __LINE__); \
panic("PMAP_ACTIVATE_ASN_SANITY"); \
} \
} else { \
if (__pma->pma_asngen != __cpma->pma_asngen) { \
/* \
* ASN generation number isn't valid! \
*/ \
printf("pmap asngen %lu, current %lu " \
"(line %d)\n", \
__pma->pma_asngen, \
__cpma->pma_asngen, \
__LINE__); \
panic("PMAP_ACTIVATE_ASN_SANITY"); \
} \
if (__pma->pma_asn == PMAP_ASN_RESERVED) { \
/* \
* DANGER WILL ROBINSON! We're going to \
* pollute the VPT TLB entries! \
*/ \
printf("Using reserved ASN! (line %d)\n", \
__LINE__); \
panic("PMAP_ACTIVATE_ASN_SANITY"); \
} \
} \
} while (0)
#else
#define PMAP_ACTIVATE_ASN_SANITY(pmap, cpu_id) /* nothing */
#endif
/*
* PMAP_ACTIVATE:
*
* This is essentially the guts of pmap_activate(), without
* ASN allocation. This is used by pmap_activate(),
* pmap_lev1map_create(), and pmap_lev1map_destroy().
*
* This is called only when it is known that a pmap is "active"
* on the current processor; the ASN must already be valid.
*/
#define PMAP_ACTIVATE(pmap, p, cpu_id) \
do { \
PMAP_ACTIVATE_ASN_SANITY(pmap, cpu_id); \
\
(p)->p_addr->u_pcb.pcb_hw.apcb_ptbr = \
ALPHA_K0SEG_TO_PHYS((vaddr_t)(pmap)->pm_lev1map) >> PGSHIFT; \
(p)->p_addr->u_pcb.pcb_hw.apcb_asn = \
(pmap)->pm_asni[(cpu_id)].pma_asn; \
\
if ((p) == curproc) { \
/* \
* Page table base register has changed; switch to \
* our own context again so that it will take effect. \
*/ \
(void) alpha_pal_swpctx((u_long)p->p_md.md_pcbpaddr); \
} \
} while (0)
#if defined(MULTIPROCESSOR)
/*
* PMAP_LEV1MAP_SHOOTDOWN:
*
* "Shoot down" the level 1 map on other CPUs.
*/
#define PMAP_LEV1MAP_SHOOTDOWN(pmap, cpu_id) \
do { \
u_long __cpumask = (pmap)->pm_cpus & ~(1UL << (cpu_id)); \
\
if (__cpumask != 0) { \
alpha_multicast_ipi(__cpumask, \
ALPHA_IPI_PMAP_REACTIVATE); \
/* XXXSMP BARRIER OPERATION */ \
} \
} while (/*CONSTCOND*/0)
#else
#define PMAP_LEV1MAP_SHOOTDOWN(pmap, cpu_id) /* nothing */
#endif /* MULTIPROCESSOR */
/*
* PMAP_SET_NEEDISYNC:
*
* Mark that a user pmap needs an I-stream synch on its
* way back out to userspace.
*/
#define PMAP_SET_NEEDISYNC(pmap) (pmap)->pm_needisync = ~0UL
/*
* PMAP_SYNC_ISTREAM:
*
* Synchronize the I-stream for the specified pmap. For user
* pmaps, this is deferred until a process using the pmap returns
* to userspace.
*/
#if defined(MULTIPROCESSOR)
#define PMAP_SYNC_ISTREAM_KERNEL() \
do { \
alpha_pal_imb(); \
alpha_broadcast_ipi(ALPHA_IPI_IMB); \
} while (0)
#define PMAP_SYNC_ISTREAM_USER(pmap) \
do { \
alpha_multicast_ipi((pmap)->pm_cpus, ALPHA_IPI_AST); \
/* for curcpu, will happen in userret() */ \
} while (0)
#else
#define PMAP_SYNC_ISTREAM_KERNEL() alpha_pal_imb()
#define PMAP_SYNC_ISTREAM_USER(pmap) /* will happen in userret() */
#endif /* MULTIPROCESSOR */
#define PMAP_SYNC_ISTREAM(pmap) \
do { \
if ((pmap) == pmap_kernel()) \
PMAP_SYNC_ISTREAM_KERNEL(); \
else \
PMAP_SYNC_ISTREAM_USER(pmap); \
} while (0)
/*
* PMAP_INVALIDATE_ASN:
*
* Invalidate the specified pmap's ASN, so as to force allocation
* of a new one the next time pmap_asn_alloc() is called.
*
* NOTE: THIS MUST ONLY BE CALLED IF AT LEAST ONE OF THE FOLLOWING
* CONDITIONS ARE TRUE:
*
* (1) The pmap references the global kernel_lev1map.
*
* (2) The pmap is not active on the current processor.
*/
#define PMAP_INVALIDATE_ASN(pmap, cpu_id) \
do { \
(pmap)->pm_asni[(cpu_id)].pma_asn = PMAP_ASN_RESERVED; \
} while (0)
/*
* PMAP_INVALIDATE_TLB:
*
* Invalidate the TLB entry for the pmap/va pair.
*/
#define PMAP_INVALIDATE_TLB(pmap, va, hadasm, isactive, cpu_id) \
do { \
if ((hadasm) || (isactive)) { \
/* \
* Simply invalidating the TLB entry and I-cache \
* works in this case. \
*/ \
ALPHA_TBIS((va)); \
} else if ((pmap)->pm_asni[(cpu_id)].pma_asngen == \
pmap_asn_info[(cpu_id)].pma_asngen) { \
/* \
* We can't directly invalidate the TLB entry \
* in this case, so we have to force allocation \
* of a new ASN the next time this pmap becomes \
* active. \
*/ \
PMAP_INVALIDATE_ASN((pmap), (cpu_id)); \
} \
/* \
* Nothing to do in this case; the next time the \
* pmap becomes active on this processor, a new \
* ASN will be allocated anyway. \
*/ \
} while (0)
/*
* PMAP_KERNEL_PTE:
*
* Get a kernel PTE.
*
* If debugging, do a table walk. If not debugging, just use
* the Virtual Page Table, since all kernel page tables are
* pre-allocated and mapped in.
*/
#ifdef DEBUG
#define PMAP_KERNEL_PTE(va) \
({ \
pt_entry_t *l1pte_, *l2pte_; \
\
l1pte_ = pmap_l1pte(pmap_kernel(), va); \
if (pmap_pte_v(l1pte_) == 0) { \
printf("kernel level 1 PTE not valid, va 0x%lx " \
"(line %d)\n", (va), __LINE__); \
panic("PMAP_KERNEL_PTE"); \
} \
l2pte_ = pmap_l2pte(pmap_kernel(), va, l1pte_); \
if (pmap_pte_v(l2pte_) == 0) { \
printf("kernel level 2 PTE not valid, va 0x%lx " \
"(line %d)\n", (va), __LINE__); \
panic("PMAP_KERNEL_PTE"); \
} \
pmap_l3pte(pmap_kernel(), va, l2pte_); \
})
#else
#define PMAP_KERNEL_PTE(va) (&VPT[VPT_INDEX((va))])
#endif
/*
* PMAP_SET_PTE:
*
* Set a PTE to a specified value.
*/
#define PMAP_SET_PTE(ptep, val) *(ptep) = (val)
/*
* PMAP_STAT_{INCR,DECR}:
*
* Increment or decrement a pmap statistic.
*/
#define PMAP_STAT_INCR(s, v) atomic_add_ulong((unsigned long *)(&(s)), (v))
#define PMAP_STAT_DECR(s, v) atomic_sub_ulong((unsigned long *)(&(s)), (v))
/*
* pmap_bootstrap:
*
* Bootstrap the system to run with virtual memory.
*
* Note: no locking is necessary in this function.
*/
void
pmap_bootstrap(paddr_t ptaddr, u_int maxasn, u_long ncpuids)
{
vsize_t lev2mapsize, lev3mapsize;
pt_entry_t *lev2map, *lev3map;
pt_entry_t pte;
int i;
#ifdef DEBUG
if (pmapdebug & (PDB_FOLLOW|PDB_BOOTSTRAP))
printf("pmap_bootstrap(0x%lx, %u)\n", ptaddr, maxasn);
#endif
/*
* Compute the number of pages kmem_map will have.
*/
kmeminit_nkmempages();
/*
* Figure out how many initial PTE's are necessary to map the
* kernel. We also reserve space for kmem_alloc_pageable()
* for vm_fork().
*/
lev3mapsize = (VM_PHYS_SIZE + (ubc_nwins << ubc_winshift) +
nbuf * MAXBSIZE + 16 * NCARGS + PAGER_MAP_SIZE) / NBPG +
(maxproc * UPAGES) + nkmempages;
#ifdef SYSVSHM
lev3mapsize += shminfo.shmall;
#endif
lev3mapsize = roundup(lev3mapsize, NPTEPG);
/*
* Initialize `FYI' variables. Note we're relying on
* the fact that BSEARCH sorts the vm_physmem[] array
* for us.
*/
avail_start = ptoa(vm_physmem[0].start);
avail_end = ptoa(vm_physmem[vm_nphysseg - 1].end);
virtual_end = VM_MIN_KERNEL_ADDRESS + lev3mapsize * PAGE_SIZE;
#if 0
printf("avail_start = 0x%lx\n", avail_start);
printf("avail_end = 0x%lx\n", avail_end);
printf("virtual_end = 0x%lx\n", virtual_end);
#endif
/*
* Allocate a level 1 PTE table for the kernel.
* This is always one page long.
* IF THIS IS NOT A MULTIPLE OF NBPG, ALL WILL GO TO HELL.
*/
kernel_lev1map = (pt_entry_t *)
uvm_pageboot_alloc(sizeof(pt_entry_t) * NPTEPG);
/*
* Allocate a level 2 PTE table for the kernel.
* These must map all of the level3 PTEs.
* IF THIS IS NOT A MULTIPLE OF NBPG, ALL WILL GO TO HELL.
*/
lev2mapsize = roundup(howmany(lev3mapsize, NPTEPG), NPTEPG);
lev2map = (pt_entry_t *)
uvm_pageboot_alloc(sizeof(pt_entry_t) * lev2mapsize);
/*
* Allocate a level 3 PTE table for the kernel.
* Contains lev3mapsize PTEs.
*/
lev3map = (pt_entry_t *)
uvm_pageboot_alloc(sizeof(pt_entry_t) * lev3mapsize);
/*
* Set up level 1 page table
*/
/* Map all of the level 2 pte pages */
for (i = 0; i < howmany(lev2mapsize, NPTEPG); i++) {
pte = (ALPHA_K0SEG_TO_PHYS(((vaddr_t)lev2map) +
(i*PAGE_SIZE)) >> PGSHIFT) << PG_SHIFT;
pte |= PG_V | PG_ASM | PG_KRE | PG_KWE | PG_WIRED;
kernel_lev1map[l1pte_index(VM_MIN_KERNEL_ADDRESS +
(i*PAGE_SIZE*NPTEPG*NPTEPG))] = pte;
}
/* Map the virtual page table */
pte = (ALPHA_K0SEG_TO_PHYS((vaddr_t)kernel_lev1map) >> PGSHIFT)
<< PG_SHIFT;
pte |= PG_V | PG_KRE | PG_KWE; /* NOTE NO ASM */
kernel_lev1map[l1pte_index(VPTBASE)] = pte;
VPT = (pt_entry_t *)VPTBASE;
#ifdef _PMAP_MAY_USE_PROM_CONSOLE
{
extern pt_entry_t prom_pte; /* XXX */
extern int prom_mapped; /* XXX */
if (pmap_uses_prom_console()) {
/*
* XXX Save old PTE so we can remap the PROM, if
* XXX necessary.
*/
prom_pte = *(pt_entry_t *)ptaddr & ~PG_ASM;
}
prom_mapped = 0;
/*
* Actually, this code lies. The prom is still mapped, and will
* remain so until the context switch after alpha_init() returns.
*/
}
#endif
/*
* Set up level 2 page table.
*/
/* Map all of the level 3 pte pages */
for (i = 0; i < howmany(lev3mapsize, NPTEPG); i++) {
pte = (ALPHA_K0SEG_TO_PHYS(((vaddr_t)lev3map) +
(i*PAGE_SIZE)) >> PGSHIFT) << PG_SHIFT;
pte |= PG_V | PG_ASM | PG_KRE | PG_KWE | PG_WIRED;
lev2map[l2pte_index(VM_MIN_KERNEL_ADDRESS+
(i*PAGE_SIZE*NPTEPG))] = pte;
}
/* Initialize the pmap_growkernel_slock. */
simple_lock_init(&pmap_growkernel_slock);
/*
* Set up level three page table (lev3map)
*/
/* Nothing to do; it's already zero'd */
/*
* Intialize the pmap pools and list.
*/
pmap_ncpuids = ncpuids;
pool_init(&pmap_pmap_pool,
PMAP_SIZEOF(pmap_ncpuids), 0, 0, 0, "pmappl",
&pool_allocator_nointr);
pool_init(&pmap_l1pt_pool, PAGE_SIZE, 0, 0, 0, "l1ptpl",
&pmap_l1pt_allocator);
pool_cache_init(&pmap_l1pt_cache, &pmap_l1pt_pool, pmap_l1pt_ctor,
NULL, NULL);
pool_init(&pmap_pv_pool, sizeof(struct pv_entry), 0, 0, 0, "pvpl",
&pmap_pv_page_allocator);
TAILQ_INIT(&pmap_all_pmaps);
/*
* Initialize the ASN logic.
*/
pmap_max_asn = maxasn;
for (i = 0; i < ALPHA_MAXPROCS; i++) {
pmap_asn_info[i].pma_asn = 1;
pmap_asn_info[i].pma_asngen = 0;
}
/*
* Initialize the locks.
*/
spinlockinit(&pmap_main_lock, "pmaplk", 0);
simple_lock_init(&pmap_all_pmaps_slock);
/*
* Initialize kernel pmap. Note that all kernel mappings
* have PG_ASM set, so the ASN doesn't really matter for
* the kernel pmap. Also, since the kernel pmap always
* references kernel_lev1map, it always has an invalid ASN
* generation.
*/
memset(pmap_kernel(), 0, sizeof(struct pmap));
pmap_kernel()->pm_lev1map = kernel_lev1map;
pmap_kernel()->pm_count = 1;
for (i = 0; i < ALPHA_MAXPROCS; i++) {
pmap_kernel()->pm_asni[i].pma_asn = PMAP_ASN_RESERVED;
pmap_kernel()->pm_asni[i].pma_asngen =
pmap_asn_info[i].pma_asngen;
}
simple_lock_init(&pmap_kernel()->pm_slock);
TAILQ_INSERT_TAIL(&pmap_all_pmaps, pmap_kernel(), pm_list);
#if defined(MULTIPROCESSOR)
/*
* Initialize the TLB shootdown queues.
*/
pool_init(&pmap_tlb_shootdown_job_pool,
sizeof(struct pmap_tlb_shootdown_job), 0, 0, 0, "pmaptlbpl", NULL);
for (i = 0; i < ALPHA_MAXPROCS; i++) {
TAILQ_INIT(&pmap_tlb_shootdown_q[i].pq_head);
simple_lock_init(&pmap_tlb_shootdown_q[i].pq_slock);
}
#endif
/*
* Set up proc0's PCB such that the ptbr points to the right place
* and has the kernel pmap's (really unused) ASN.
*/
proc0.p_addr->u_pcb.pcb_hw.apcb_ptbr =
ALPHA_K0SEG_TO_PHYS((vaddr_t)kernel_lev1map) >> PGSHIFT;
proc0.p_addr->u_pcb.pcb_hw.apcb_asn =
pmap_kernel()->pm_asni[cpu_number()].pma_asn;
/*
* Mark the kernel pmap `active' on this processor.
*/
atomic_setbits_ulong(&pmap_kernel()->pm_cpus,
(1UL << cpu_number()));
}
#ifdef _PMAP_MAY_USE_PROM_CONSOLE
int
pmap_uses_prom_console(void)
{
#if defined(NEW_SCC_DRIVER)
return (cputype == ST_DEC_21000);
#else
return (cputype == ST_DEC_21000
|| cputype == ST_DEC_3000_300
|| cputype == ST_DEC_3000_500);
#endif /* NEW_SCC_DRIVER */
}
#endif /* _PMAP_MAY_USE_PROM_CONSOLE */
/*
* pmap_virtual_space: [ INTERFACE ]
*
* Define the initial bounds of the kernel virtual address space.
*/
void
pmap_virtual_space(vaddr_t *vstartp, vaddr_t *vendp)
{
*vstartp = VM_MIN_KERNEL_ADDRESS; /* kernel is in K0SEG */
*vendp = VM_MAX_KERNEL_ADDRESS; /* we use pmap_growkernel */
}
/*
* pmap_steal_memory: [ INTERFACE ]
*
* Bootstrap memory allocator (alternative to vm_bootstrap_steal_memory()).
* This function allows for early dynamic memory allocation until the
* virtual memory system has been bootstrapped. After that point, either
* kmem_alloc or malloc should be used. This function works by stealing
* pages from the (to be) managed page pool, then implicitly mapping the
* pages (by using their k0seg addresses) and zeroing them.
*
* It may be used once the physical memory segments have been pre-loaded
* into the vm_physmem[] array. Early memory allocation MUST use this
* interface! This cannot be used after vm_page_startup(), and will
* generate a panic if tried.
*
* Note that this memory will never be freed, and in essence it is wired
* down.
*
* We must adjust *vstartp and/or *vendp iff we use address space
* from the kernel virtual address range defined by pmap_virtual_space().
*
* Note: no locking is necessary in this function.
*/
vaddr_t
pmap_steal_memory(vsize_t size, vaddr_t *vstartp, vaddr_t *vendp)
{
int bank, npgs, x;
vaddr_t va;
paddr_t pa;
size = round_page(size);
npgs = atop(size);
#if 0
printf("PSM: size 0x%lx (npgs 0x%x)\n", size, npgs);
#endif
for (bank = 0; bank < vm_nphysseg; bank++) {
if (uvm.page_init_done == TRUE)
panic("pmap_steal_memory: called _after_ bootstrap");
#if 0
printf(" bank %d: avail_start 0x%lx, start 0x%lx, "
"avail_end 0x%lx\n", bank, vm_physmem[bank].avail_start,
vm_physmem[bank].start, vm_physmem[bank].avail_end);
#endif
if (vm_physmem[bank].avail_start != vm_physmem[bank].start ||
vm_physmem[bank].avail_start >= vm_physmem[bank].avail_end)
continue;
#if 0
printf(" avail_end - avail_start = 0x%lx\n",
vm_physmem[bank].avail_end - vm_physmem[bank].avail_start);
#endif
if ((vm_physmem[bank].avail_end - vm_physmem[bank].avail_start)
< npgs)
continue;
/*
* There are enough pages here; steal them!
*/
pa = ptoa(vm_physmem[bank].avail_start);
vm_physmem[bank].avail_start += npgs;
vm_physmem[bank].start += npgs;
/*
* Have we used up this segment?
*/
if (vm_physmem[bank].avail_start == vm_physmem[bank].end) {
if (vm_nphysseg == 1)
panic("pmap_steal_memory: out of memory!");
/* Remove this segment from the list. */
vm_nphysseg--;
for (x = bank; x < vm_nphysseg; x++) {
/* structure copy */
vm_physmem[x] = vm_physmem[x + 1];
}
}
va = ALPHA_PHYS_TO_K0SEG(pa);
memset((caddr_t)va, 0, size);
pmap_pages_stolen += npgs;
return (va);
}
/*
* If we got here, this was no memory left.
*/
panic("pmap_steal_memory: no memory to steal");
}
/*
* pmap_init: [ INTERFACE ]
*
* Initialize the pmap module. Called by vm_init(), to initialize any
* structures that the pmap system needs to map virtual memory.
*
* Note: no locking is necessary in this function.
*/
void
pmap_init(void)
{
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_init()\n");
#endif
/* initialize protection array */
alpha_protection_init();
/*
* Set a low water mark on the pv_entry pool, so that we are
* more likely to have these around even in extreme memory
* starvation.
*/
pool_setlowat(&pmap_pv_pool, pmap_pv_lowat);
/*
* Now it is safe to enable pv entry recording.
*/
pmap_initialized = TRUE;
#if 0
for (bank = 0; bank < vm_nphysseg; bank++) {
printf("bank %d\n", bank);
printf("\tstart = 0x%x\n", ptoa(vm_physmem[bank].start));
printf("\tend = 0x%x\n", ptoa(vm_physmem[bank].end));
printf("\tavail_start = 0x%x\n",
ptoa(vm_physmem[bank].avail_start));
printf("\tavail_end = 0x%x\n",
ptoa(vm_physmem[bank].avail_end));
}
#endif
}
/*
* pmap_create: [ INTERFACE ]
*
* Create and return a physical map.
*
* Note: no locking is necessary in this function.
*/
pmap_t
pmap_create(void)
{
pmap_t pmap;
int i;
#ifdef DEBUG
if (pmapdebug & (PDB_FOLLOW|PDB_CREATE))
printf("pmap_create()\n");
#endif
pmap = pool_get(&pmap_pmap_pool, PR_WAITOK);
memset(pmap, 0, sizeof(*pmap));
/*
* Defer allocation of a new level 1 page table until
* the first new mapping is entered; just take a reference
* to the kernel kernel_lev1map.
*/
pmap->pm_lev1map = kernel_lev1map;
pmap->pm_count = 1;
for (i = 0; i < pmap_ncpuids; i++) {
pmap->pm_asni[i].pma_asn = PMAP_ASN_RESERVED;
/* XXX Locking? */
pmap->pm_asni[i].pma_asngen = pmap_asn_info[i].pma_asngen;
}
simple_lock_init(&pmap->pm_slock);
simple_lock(&pmap_all_pmaps_slock);
TAILQ_INSERT_TAIL(&pmap_all_pmaps, pmap, pm_list);
simple_unlock(&pmap_all_pmaps_slock);
return (pmap);
}
/*
* pmap_destroy: [ INTERFACE ]
*
* Drop the reference count on the specified pmap, releasing
* all resources if the reference count drops to zero.
*/
void
pmap_destroy(pmap_t pmap)
{
int refs;
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_destroy(%p)\n", pmap);
#endif
PMAP_LOCK(pmap);
refs = --pmap->pm_count;
PMAP_UNLOCK(pmap);
if (refs > 0)
return;
/*
* Remove it from the global list of all pmaps.
*/
simple_lock(&pmap_all_pmaps_slock);
TAILQ_REMOVE(&pmap_all_pmaps, pmap, pm_list);
simple_unlock(&pmap_all_pmaps_slock);
#ifdef DIAGNOSTIC
/*
* Since the pmap is supposed to contain no valid
* mappings at this point, this should never happen.
*/
if (pmap->pm_lev1map != kernel_lev1map)
panic("pmap_destroy: pmap still contains valid mappings");
#endif
pool_put(&pmap_pmap_pool, pmap);
}
/*
* pmap_reference: [ INTERFACE ]
*
* Add a reference to the specified pmap.
*/
void
pmap_reference(pmap_t pmap)
{
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_reference(%p)\n", pmap);
#endif
PMAP_LOCK(pmap);
pmap->pm_count++;
PMAP_UNLOCK(pmap);
}
/*
* pmap_remove: [ INTERFACE ]
*
* Remove the given range of addresses from the specified map.
*
* It is assumed that the start and end are properly
* rounded to the page size.
*/
void
pmap_remove(pmap_t pmap, vaddr_t sva, vaddr_t eva)
{
#ifdef DEBUG
if (pmapdebug & (PDB_FOLLOW|PDB_REMOVE|PDB_PROTECT))
printf("pmap_remove(%p, %lx, %lx)\n", pmap, sva, eva);
#endif
pmap_do_remove(pmap, sva, eva, TRUE);
}
/*
* pmap_do_remove:
*
* This actually removes the range of addresses from the
* specified map. It is used by pmap_collect() (does not
* want to remove wired mappings) and pmap_remove() (does
* want to remove wired mappings).
*/
void
pmap_do_remove(pmap_t pmap, vaddr_t sva, vaddr_t eva, boolean_t dowired)
{
pt_entry_t *l1pte, *l2pte, *l3pte;
pt_entry_t *saved_l1pte, *saved_l2pte, *saved_l3pte;
vaddr_t l1eva, l2eva, vptva;
boolean_t needisync = FALSE;
long cpu_id = cpu_number();
#ifdef DEBUG
if (pmapdebug & (PDB_FOLLOW|PDB_REMOVE|PDB_PROTECT))
printf("pmap_remove(%p, %lx, %lx)\n", pmap, sva, eva);
#endif
/*
* If this is the kernel pmap, we can use a faster method
* for accessing the PTEs (since the PT pages are always
* resident).
*
* Note that this routine should NEVER be called from an
* interrupt context; pmap_kremove() is used for that.
*/
if (pmap == pmap_kernel()) {
PMAP_MAP_TO_HEAD_LOCK();
PMAP_LOCK(pmap);
KASSERT(dowired == TRUE);
while (sva < eva) {
l3pte = PMAP_KERNEL_PTE(sva);
if (pmap_pte_v(l3pte)) {
#ifdef DIAGNOSTIC
if (PAGE_IS_MANAGED(pmap_pte_pa(l3pte)) &&
pmap_pte_pv(l3pte) == 0)
panic("pmap_remove: managed page "
"without PG_PVLIST for 0x%lx",
sva);
#endif
needisync |= pmap_remove_mapping(pmap, sva,
l3pte, TRUE, cpu_id);
}
sva += PAGE_SIZE;
}
PMAP_UNLOCK(pmap);
PMAP_MAP_TO_HEAD_UNLOCK();
if (needisync)
PMAP_SYNC_ISTREAM_KERNEL();
return;
}
#ifdef DIAGNOSTIC
if (sva > VM_MAXUSER_ADDRESS || eva > VM_MAXUSER_ADDRESS)
panic("pmap_remove: (0x%lx - 0x%lx) user pmap, kernel "
"address range", sva, eva);
#endif
PMAP_MAP_TO_HEAD_LOCK();
PMAP_LOCK(pmap);
/*
* If we're already referencing the kernel_lev1map, there
* is no work for us to do.
*/
if (pmap->pm_lev1map == kernel_lev1map)
goto out;
saved_l1pte = l1pte = pmap_l1pte(pmap, sva);
/*
* Add a reference to the L1 table to it won't get
* removed from under us.
*/
pmap_physpage_addref(saved_l1pte);
for (; sva < eva; sva = l1eva, l1pte++) {
l1eva = alpha_trunc_l1seg(sva) + ALPHA_L1SEG_SIZE;
if (pmap_pte_v(l1pte)) {
saved_l2pte = l2pte = pmap_l2pte(pmap, sva, l1pte);
/*
* Add a reference to the L2 table so it won't
* get removed from under us.
*/
pmap_physpage_addref(saved_l2pte);
for (; sva < l1eva && sva < eva; sva = l2eva, l2pte++) {
l2eva =
alpha_trunc_l2seg(sva) + ALPHA_L2SEG_SIZE;
if (pmap_pte_v(l2pte)) {
saved_l3pte = l3pte =
pmap_l3pte(pmap, sva, l2pte);
/*
* Add a reference to the L3 table so
* it won't get removed from under us.
*/
pmap_physpage_addref(saved_l3pte);
/*
* Remember this sva; if the L3 table
* gets removed, we need to invalidate
* the VPT TLB entry for it.
*/
vptva = sva;
for (; sva < l2eva && sva < eva;
sva += PAGE_SIZE, l3pte++) {
if (pmap_pte_v(l3pte) &&
(dowired == TRUE ||
pmap_pte_w(l3pte) == 0)) {
needisync |=
pmap_remove_mapping(
pmap, sva,
l3pte, TRUE,
cpu_id);
}
}
/*
* Remove the reference to the L3
* table that we added above. This
* may free the L3 table.
*/
pmap_l3pt_delref(pmap, vptva,
saved_l3pte, cpu_id);
}
}
/*
* Remove the reference to the L2 table that we
* added above. This may free the L2 table.
*/
pmap_l2pt_delref(pmap, l1pte, saved_l2pte, cpu_id);
}
}
/*
* Remove the reference to the L1 table that we added above.
* This may free the L1 table.
*/
pmap_l1pt_delref(pmap, saved_l1pte, cpu_id);
if (needisync)
PMAP_SYNC_ISTREAM_USER(pmap);
out:
PMAP_UNLOCK(pmap);
PMAP_MAP_TO_HEAD_UNLOCK();
}
/*
* pmap_page_protect: [ INTERFACE ]
*
* Lower the permission for all mappings to a given page to
* the permissions specified.
*/
void
pmap_page_protect(struct vm_page *pg, vm_prot_t prot)
{
pmap_t pmap;
pv_entry_t pv, nextpv;
boolean_t needkisync = FALSE;
long cpu_id = cpu_number();
PMAP_TLB_SHOOTDOWN_CPUSET_DECL
#ifdef DEBUG
paddr_t pa = VM_PAGE_TO_PHYS(pg);
if ((pmapdebug & (PDB_FOLLOW|PDB_PROTECT)) ||
(prot == VM_PROT_NONE && (pmapdebug & PDB_REMOVE)))
printf("pmap_page_protect(%p, %x)\n", pg, prot);
#endif
switch (prot) {
case VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE:
case VM_PROT_READ|VM_PROT_WRITE:
return;
/* copy_on_write */
case VM_PROT_READ|VM_PROT_EXECUTE:
case VM_PROT_READ:
PMAP_HEAD_TO_MAP_LOCK();
simple_lock(&pg->mdpage.pvh_slock);
for (pv = pg->mdpage.pvh_list; pv != NULL; pv = pv->pv_next) {
PMAP_LOCK(pv->pv_pmap);
if (*pv->pv_pte & (PG_KWE | PG_UWE)) {
*pv->pv_pte &= ~(PG_KWE | PG_UWE);
PMAP_INVALIDATE_TLB(pv->pv_pmap, pv->pv_va,
pmap_pte_asm(pv->pv_pte),
PMAP_ISACTIVE(pv->pv_pmap, cpu_id), cpu_id);
PMAP_TLB_SHOOTDOWN(pv->pv_pmap, pv->pv_va,
pmap_pte_asm(pv->pv_pte));
}
PMAP_UNLOCK(pv->pv_pmap);
}
simple_unlock(&pg->mdpage.pvh_slock);
PMAP_HEAD_TO_MAP_UNLOCK();
PMAP_TLB_SHOOTNOW();
return;
/* remove_all */
default:
break;
}
PMAP_HEAD_TO_MAP_LOCK();
simple_lock(&pg->mdpage.pvh_slock);
for (pv = pg->mdpage.pvh_list; pv != NULL; pv = nextpv) {
nextpv = pv->pv_next;
pmap = pv->pv_pmap;
PMAP_LOCK(pmap);
#ifdef DEBUG
if (pmap_pte_v(pmap_l2pte(pv->pv_pmap, pv->pv_va, NULL)) == 0 ||
pmap_pte_pa(pv->pv_pte) != pa)
panic("pmap_page_protect: bad mapping");
#endif
if (pmap_remove_mapping(pmap, pv->pv_va, pv->pv_pte,
FALSE, cpu_id) == TRUE) {
if (pmap == pmap_kernel())
needkisync |= TRUE;
else
PMAP_SYNC_ISTREAM_USER(pmap);
}
PMAP_UNLOCK(pmap);
}
if (needkisync)
PMAP_SYNC_ISTREAM_KERNEL();
simple_unlock(&pg->mdpage.pvh_slock);
PMAP_HEAD_TO_MAP_UNLOCK();
}
/*
* pmap_protect: [ INTERFACE ]
*
* Set the physical protection on the specified range of this map
* as requested.
*/
void
pmap_protect(pmap_t pmap, vaddr_t sva, vaddr_t eva, vm_prot_t prot)
{
pt_entry_t *l1pte, *l2pte, *l3pte, bits;
boolean_t isactive;
boolean_t hadasm;
vaddr_t l1eva, l2eva;
long cpu_id = cpu_number();
PMAP_TLB_SHOOTDOWN_CPUSET_DECL
#ifdef DEBUG
if (pmapdebug & (PDB_FOLLOW|PDB_PROTECT))
printf("pmap_protect(%p, %lx, %lx, %x)\n",
pmap, sva, eva, prot);
#endif
if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
pmap_remove(pmap, sva, eva);
return;
}
if (prot & VM_PROT_WRITE)
return;
PMAP_LOCK(pmap);
bits = pte_prot(pmap, prot);
isactive = PMAP_ISACTIVE(pmap, cpu_id);
l1pte = pmap_l1pte(pmap, sva);
for (; sva < eva; sva = l1eva, l1pte++) {
l1eva = alpha_trunc_l1seg(sva) + ALPHA_L1SEG_SIZE;
if (pmap_pte_v(l1pte)) {
l2pte = pmap_l2pte(pmap, sva, l1pte);
for (; sva < l1eva && sva < eva; sva = l2eva, l2pte++) {
l2eva =
alpha_trunc_l2seg(sva) + ALPHA_L2SEG_SIZE;
if (pmap_pte_v(l2pte)) {
l3pte = pmap_l3pte(pmap, sva, l2pte);
for (; sva < l2eva && sva < eva;
sva += PAGE_SIZE, l3pte++) {
if (pmap_pte_v(l3pte) &&
pmap_pte_prot_chg(l3pte,
bits)) {
hadasm =
(pmap_pte_asm(l3pte)
!= 0);
pmap_pte_set_prot(l3pte,
bits);
PMAP_INVALIDATE_TLB(
pmap, sva, hadasm,
isactive, cpu_id);
PMAP_TLB_SHOOTDOWN(
pmap, sva,
hadasm ? PG_ASM : 0);
}
}
}
}
}
}
PMAP_TLB_SHOOTNOW();
if (prot & VM_PROT_EXECUTE)
PMAP_SYNC_ISTREAM(pmap);
PMAP_UNLOCK(pmap);
}
/*
* pmap_enter: [ INTERFACE ]
*
* Insert the given physical page (p) at
* the specified virtual address (v) in the
* target physical map with the protection requested.
*
* If specified, the page will be wired down, meaning
* that the related pte can not be reclaimed.
*
* Note: This is the only routine which MAY NOT lazy-evaluate
* or lose information. That is, this routine must actually
* insert this page into the given map NOW.
*/
int
pmap_enter(pmap_t pmap, vaddr_t va, paddr_t pa, vm_prot_t prot, int flags)
{
struct vm_page *pg; /* if != NULL, managed page */
pt_entry_t *pte, npte, opte;
paddr_t opa;
boolean_t tflush = TRUE;
boolean_t hadasm = FALSE; /* XXX gcc -Wuninitialized */
boolean_t needisync = FALSE;
boolean_t setisync = FALSE;
boolean_t isactive;
boolean_t wired;
long cpu_id = cpu_number();
int error = 0;
PMAP_TLB_SHOOTDOWN_CPUSET_DECL
#ifdef DEBUG
if (pmapdebug & (PDB_FOLLOW|PDB_ENTER))
printf("pmap_enter(%p, %lx, %lx, %x, %x)\n",
pmap, va, pa, prot, flags);
#endif
pg = PHYS_TO_VM_PAGE(pa);
isactive = PMAP_ISACTIVE(pmap, cpu_id);
wired = (flags & PMAP_WIRED) != 0;
/*
* Determine what we need to do about the I-stream. If
* VM_PROT_EXECUTE is set, we mark a user pmap as needing
* an I-sync on the way back out to userspace. We always
* need an immediate I-sync for the kernel pmap.
*/
if (prot & VM_PROT_EXECUTE) {
if (pmap == pmap_kernel())
needisync = TRUE;
else {
setisync = TRUE;
needisync = (pmap->pm_cpus != 0);
}
}
PMAP_MAP_TO_HEAD_LOCK();
PMAP_LOCK(pmap);
if (pmap == pmap_kernel()) {
#ifdef DIAGNOSTIC
/*
* Sanity check the virtual address.
*/
if (va < VM_MIN_KERNEL_ADDRESS)
panic("pmap_enter: kernel pmap, invalid va 0x%lx", va);
#endif
pte = PMAP_KERNEL_PTE(va);
} else {
pt_entry_t *l1pte, *l2pte;
#ifdef DIAGNOSTIC
/*
* Sanity check the virtual address.
*/
if (va >= VM_MAXUSER_ADDRESS)
panic("pmap_enter: user pmap, invalid va 0x%lx", va);
#endif
/*
* If we're still referencing the kernel kernel_lev1map,
* create a new level 1 page table. A reference will be
* added to the level 1 table when the level 2 table is
* created.
*/
if (pmap->pm_lev1map == kernel_lev1map) {
/*
* XXX Yuck.
* We have to unlock the pmap, lock the
* pmap_growkernel_slock, and re-lock the
* pmap here, in order to avoid a deadlock
* with pmap_growkernel().
*
* Because we unlock, we have a window for
* someone else to add a mapping, thus creating
* a level 1 map; pmap_lev1map_create() checks
* for this condition.
*/
PMAP_UNLOCK(pmap);
simple_lock(&pmap_growkernel_slock);
PMAP_LOCK(pmap);
error = pmap_lev1map_create(pmap, cpu_id);
simple_unlock(&pmap_growkernel_slock);
if (error) {
if (flags & PMAP_CANFAIL)
goto out;
panic("pmap_enter: unable to create lev1map");
}
}
/*
* Check to see if the level 1 PTE is valid, and
* allocate a new level 2 page table page if it's not.
* A reference will be added to the level 2 table when
* the level 3 table is created.
*/
l1pte = pmap_l1pte(pmap, va);
if (pmap_pte_v(l1pte) == 0) {
pmap_physpage_addref(l1pte);
error = pmap_ptpage_alloc(pmap, l1pte, PGU_L2PT);
if (error) {
pmap_l1pt_delref(pmap, l1pte, cpu_id);
if (flags & PMAP_CANFAIL)
goto out;
panic("pmap_enter: unable to create L2 PT "
"page");
}
#ifdef DEBUG
if (pmapdebug & PDB_PTPAGE)
printf("pmap_enter: new level 2 table at "
"0x%lx\n", pmap_pte_pa(l1pte));
#endif
}
/*
* Check to see if the level 2 PTE is valid, and
* allocate a new level 3 page table page if it's not.
* A reference will be added to the level 3 table when
* the mapping is validated.
*/
l2pte = pmap_l2pte(pmap, va, l1pte);
if (pmap_pte_v(l2pte) == 0) {
pmap_physpage_addref(l2pte);
error = pmap_ptpage_alloc(pmap, l2pte, PGU_L3PT);
if (error) {
pmap_l2pt_delref(pmap, l1pte, l2pte, cpu_id);
if (flags & PMAP_CANFAIL)
goto out;
panic("pmap_enter: unable to create L3 PT "
"page");
}
#ifdef DEBUG
if (pmapdebug & PDB_PTPAGE)
printf("pmap_enter: new level 3 table at "
"0x%lx\n", pmap_pte_pa(l2pte));
#endif
}
/*
* Get the PTE that will map the page.
*/
pte = pmap_l3pte(pmap, va, l2pte);
}
/* Remember all of the old PTE; used for TBI check later. */
opte = *pte;
/*
* Check to see if the old mapping is valid. If not, validate the
* new one immediately.
*/
if (pmap_pte_v(pte) == 0) {
/*
* No need to invalidate the TLB in this case; an invalid
* mapping won't be in the TLB, and a previously valid
* mapping would have been flushed when it was invalidated.
*/
tflush = FALSE;
/*
* No need to synchronize the I-stream, either, for basically
* the same reason.
*/
setisync = needisync = FALSE;
if (pmap != pmap_kernel()) {
/*
* New mappings gain a reference on the level 3
* table.
*/
pmap_physpage_addref(pte);
}
goto validate_enterpv;
}
opa = pmap_pte_pa(pte);
hadasm = (pmap_pte_asm(pte) != 0);
if (opa == pa) {
/*
* Mapping has not changed; must be a protection or
* wiring change.
*/
if (pmap_pte_w_chg(pte, wired ? PG_WIRED : 0)) {
#ifdef DEBUG
if (pmapdebug & PDB_ENTER)
printf("pmap_enter: wiring change -> %d\n",
wired);
#endif
/*
* Adjust the wiring count.
*/
if (wired)
PMAP_STAT_INCR(pmap->pm_stats.wired_count, 1);
else
PMAP_STAT_DECR(pmap->pm_stats.wired_count, 1);
}
/*
* Set the PTE.
*/
goto validate;
}
/*
* The mapping has changed. We need to invalidate the
* old mapping before creating the new one.
*/
#ifdef DEBUG
if (pmapdebug & PDB_ENTER)
printf("pmap_enter: removing old mapping 0x%lx\n", va);
#endif
if (pmap != pmap_kernel()) {
/*
* Gain an extra reference on the level 3 table.
* pmap_remove_mapping() will delete a reference,
* and we don't want the table to be erroneously
* freed.
*/
pmap_physpage_addref(pte);
}
needisync |= pmap_remove_mapping(pmap, va, pte, TRUE, cpu_id);
validate_enterpv:
/*
* Enter the mapping into the pv_table if appropriate.
*/
if (pg != NULL) {
error = pmap_pv_enter(pmap, pg, va, pte, TRUE);
if (error) {
pmap_l3pt_delref(pmap, va, pte, cpu_id);
if (flags & PMAP_CANFAIL)
goto out;
panic("pmap_enter: unable to enter mapping in PV "
"table");
}
}
/*
* Increment counters.
*/
PMAP_STAT_INCR(pmap->pm_stats.resident_count, 1);
if (wired)
PMAP_STAT_INCR(pmap->pm_stats.wired_count, 1);
validate:
/*
* Build the new PTE.
*/
npte = ((pa >> PGSHIFT) << PG_SHIFT) | pte_prot(pmap, prot) | PG_V;
if (pg != NULL) {
int attrs;
#ifdef DIAGNOSTIC
if ((flags & VM_PROT_ALL) & ~prot)
panic("pmap_enter: access type exceeds prot");
#endif
simple_lock(&pg->mdpage.pvh_slock);
if (flags & VM_PROT_WRITE)
pg->mdpage.pvh_attrs |= (PGA_REFERENCED|PGA_MODIFIED);
else if (flags & VM_PROT_ALL)
pg->mdpage.pvh_attrs |= PGA_REFERENCED;
attrs = pg->mdpage.pvh_attrs;
simple_unlock(&pg->mdpage.pvh_slock);
/*
* Set up referenced/modified emulation for new mapping.
*/
if ((attrs & PGA_REFERENCED) == 0)
npte |= PG_FOR | PG_FOW | PG_FOE;
else if ((attrs & PGA_MODIFIED) == 0)
npte |= PG_FOW;
/*
* Mapping was entered on PV list.
*/
npte |= PG_PVLIST;
}
if (wired)
npte |= PG_WIRED;
#ifdef DEBUG
if (pmapdebug & PDB_ENTER)
printf("pmap_enter: new pte = 0x%lx\n", npte);
#endif
/*
* If the PALcode portion of the new PTE is the same as the
* old PTE, no TBI is necessary.
*/
if (PG_PALCODE(opte) == PG_PALCODE(npte))
tflush = FALSE;
/*
* Set the new PTE.
*/
PMAP_SET_PTE(pte, npte);
/*
* Invalidate the TLB entry for this VA and any appropriate
* caches.
*/
if (tflush) {
PMAP_INVALIDATE_TLB(pmap, va, hadasm, isactive, cpu_id);
PMAP_TLB_SHOOTDOWN(pmap, va, hadasm ? PG_ASM : 0);
PMAP_TLB_SHOOTNOW();
}
if (setisync)
PMAP_SET_NEEDISYNC(pmap);
if (needisync)
PMAP_SYNC_ISTREAM(pmap);
out:
PMAP_UNLOCK(pmap);
PMAP_MAP_TO_HEAD_UNLOCK();
return error;
}
/*
* pmap_kenter_pa: [ INTERFACE ]
*
* Enter a va -> pa mapping into the kernel pmap without any
* physical->virtual tracking.
*
* Note: no locking is necessary in this function.
*/
void
pmap_kenter_pa(vaddr_t va, paddr_t pa, vm_prot_t prot)
{
pt_entry_t *pte, npte;
long cpu_id = cpu_number();
boolean_t needisync = FALSE;
pmap_t pmap = pmap_kernel();
PMAP_TLB_SHOOTDOWN_CPUSET_DECL
#ifdef DEBUG
if (pmapdebug & (PDB_FOLLOW|PDB_ENTER))
printf("pmap_kenter_pa(%lx, %lx, %x)\n",
va, pa, prot);
#endif
#ifdef DIAGNOSTIC
/*
* Sanity check the virtual address.
*/
if (va < VM_MIN_KERNEL_ADDRESS)
panic("pmap_kenter_pa: kernel pmap, invalid va 0x%lx", va);
#endif
pte = PMAP_KERNEL_PTE(va);
if (pmap_pte_v(pte) == 0)
PMAP_STAT_INCR(pmap->pm_stats.resident_count, 1);
if (pmap_pte_w(pte) == 0)
PMAP_STAT_DECR(pmap->pm_stats.wired_count, 1);
if ((prot & VM_PROT_EXECUTE) != 0 || pmap_pte_exec(pte))
needisync = TRUE;
/*
* Build the new PTE.
*/
npte = ((pa >> PGSHIFT) << PG_SHIFT) | pte_prot(pmap_kernel(), prot) |
PG_V | PG_WIRED;
/*
* Set the new PTE.
*/
PMAP_SET_PTE(pte, npte);
#if defined(MULTIPROCESSOR)
alpha_mb(); /* XXX alpha_wmb()? */
#endif
/*
* Invalidate the TLB entry for this VA and any appropriate
* caches.
*/
PMAP_INVALIDATE_TLB(pmap, va, TRUE, TRUE, cpu_id);
PMAP_TLB_SHOOTDOWN(pmap, va, PG_ASM);
PMAP_TLB_SHOOTNOW();
if (needisync)
PMAP_SYNC_ISTREAM_KERNEL();
}
/*
* pmap_kremove: [ INTERFACE ]
*
* Remove a mapping entered with pmap_kenter_pa() starting at va,
* for size bytes (assumed to be page rounded).
*/
void
pmap_kremove(vaddr_t va, vsize_t size)
{
pt_entry_t *pte;
boolean_t needisync = FALSE;
long cpu_id = cpu_number();
pmap_t pmap = pmap_kernel();
PMAP_TLB_SHOOTDOWN_CPUSET_DECL
#ifdef DEBUG
if (pmapdebug & (PDB_FOLLOW|PDB_ENTER))
printf("pmap_kremove(%lx, %lx)\n",
va, size);
#endif
#ifdef DIAGNOSTIC
if (va < VM_MIN_KERNEL_ADDRESS)
panic("pmap_kremove: user address");
#endif
for (; size != 0; size -= PAGE_SIZE, va += PAGE_SIZE) {
pte = PMAP_KERNEL_PTE(va);
if (pmap_pte_v(pte)) {
#ifdef DIAGNOSTIC
if (pmap_pte_pv(pte))
panic("pmap_kremove: PG_PVLIST mapping for "
"0x%lx", va);
#endif
if (pmap_pte_exec(pte))
needisync = TRUE;
/* Zap the mapping. */
PMAP_SET_PTE(pte, PG_NV);
#if defined(MULTIPROCESSOR)
alpha_mb(); /* XXX alpha_wmb()? */
#endif
PMAP_INVALIDATE_TLB(pmap, va, TRUE, TRUE, cpu_id);
PMAP_TLB_SHOOTDOWN(pmap, va, PG_ASM);
/* Update stats. */
PMAP_STAT_DECR(pmap->pm_stats.resident_count, 1);
PMAP_STAT_DECR(pmap->pm_stats.wired_count, 1);
}
}
PMAP_TLB_SHOOTNOW();
if (needisync)
PMAP_SYNC_ISTREAM_KERNEL();
}
/*
* pmap_unwire: [ INTERFACE ]
*
* Clear the wired attribute for a map/virtual-address pair.
*
* The mapping must already exist in the pmap.
*/
void
pmap_unwire(pmap_t pmap, vaddr_t va)
{
pt_entry_t *pte;
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_unwire(%p, %lx)\n", pmap, va);
#endif
PMAP_LOCK(pmap);
pte = pmap_l3pte(pmap, va, NULL);
#ifdef DIAGNOSTIC
if (pte == NULL || pmap_pte_v(pte) == 0)
panic("pmap_unwire");
#endif
/*
* If wiring actually changed (always?) clear the wire bit and
* update the wire count. Note that wiring is not a hardware
* characteristic so there is no need to invalidate the TLB.
*/
if (pmap_pte_w_chg(pte, 0)) {
pmap_pte_set_w(pte, FALSE);
PMAP_STAT_DECR(pmap->pm_stats.wired_count, 1);
}
#ifdef DIAGNOSTIC
else {
printf("pmap_unwire: wiring for pmap %p va 0x%lx "
"didn't change!\n", pmap, va);
}
#endif
PMAP_UNLOCK(pmap);
}
/*
* pmap_extract: [ INTERFACE ]
*
* Extract the physical address associated with the given
* pmap/virtual address pair.
*/
boolean_t
pmap_extract(pmap_t pmap, vaddr_t va, paddr_t *pap)
{
pt_entry_t *l1pte, *l2pte, *l3pte;
paddr_t pa;
boolean_t rv = FALSE;
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_extract(%p, %lx) -> ", pmap, va);
#endif
PMAP_LOCK(pmap);
l1pte = pmap_l1pte(pmap, va);
if (pmap_pte_v(l1pte) == 0)
goto out;
l2pte = pmap_l2pte(pmap, va, l1pte);
if (pmap_pte_v(l2pte) == 0)
goto out;
l3pte = pmap_l3pte(pmap, va, l2pte);
if (pmap_pte_v(l3pte) == 0)
goto out;
pa = pmap_pte_pa(l3pte) | (va & PGOFSET);
if (pap != NULL)
*pap = pa;
rv = TRUE;
out:
PMAP_UNLOCK(pmap);
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW) {
if (rv)
printf("0x%lx\n", pa);
else
printf("failed\n");
}
#endif
return (rv);
}
/*
* pmap_copy: [ INTERFACE ]
*
* Copy the mapping range specified by src_addr/len
* from the source map to the range dst_addr/len
* in the destination map.
*
* This routine is only advisory and need not do anything.
*/
/* call deleted in <machine/pmap.h> */
/*
* pmap_update: [ INTERFACE ]
*
* Require that all active physical maps contain no
* incorrect entries NOW, by processing any deferred
* pmap operations.
*/
/* call deleted in <machine/pmap.h> */
/*
* pmap_collect: [ INTERFACE ]
*
* Garbage collects the physical map system for pages which are no
* longer used. Success need not be guaranteed -- that is, there
* may well be pages which are not referenced, but others may be
* collected.
*
* Called by the pageout daemon when pages are scarce.
*/
void
pmap_collect(pmap_t pmap)
{
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_collect(%p)\n", pmap);
#endif
/*
* If called for the kernel pmap, just return. We
* handle this case in the event that we ever want
* to have swappable kernel threads.
*/
if (pmap == pmap_kernel())
return;
/*
* This process is about to be swapped out; free all of
* the PT pages by removing the physical mappings for its
* entire address space. Note: pmap_remove() performs
* all necessary locking.
*/
pmap_do_remove(pmap, VM_MIN_ADDRESS, VM_MAX_ADDRESS, FALSE);
}
/*
* pmap_activate: [ INTERFACE ]
*
* Activate the pmap used by the specified process. This includes
* reloading the MMU context if the current process, and marking
* the pmap in use by the processor.
*
* Note: We may use only spin locks here, since we are called
* by a critical section in cpu_switch()!
*/
void
pmap_activate(struct proc *p)
{
struct pmap *pmap = p->p_vmspace->vm_map.pmap;
long cpu_id = cpu_number();
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_activate(%p)\n", p);
#endif
PMAP_LOCK(pmap);
/*
* Mark the pmap in use by this processor.
*/
atomic_setbits_ulong(&pmap->pm_cpus, (1UL << cpu_id));
/*
* Allocate an ASN.
*/
pmap_asn_alloc(pmap, cpu_id);
PMAP_ACTIVATE(pmap, p, cpu_id);
PMAP_UNLOCK(pmap);
}
/*
* pmap_deactivate: [ INTERFACE ]
*
* Mark that the pmap used by the specified process is no longer
* in use by the processor.
*
* The comment above pmap_activate() wrt. locking applies here,
* as well. Note that we use only a single `atomic' operation,
* so no locking is necessary.
*/
void
pmap_deactivate(struct proc *p)
{
struct pmap *pmap = p->p_vmspace->vm_map.pmap;
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_deactivate(%p)\n", p);
#endif
/*
* Mark the pmap no longer in use by this processor.
*/
atomic_clearbits_ulong(&pmap->pm_cpus, (1UL << cpu_number()));
}
#if defined(MULTIPROCESSOR)
/*
* pmap_do_reactivate:
*
* Reactivate an address space when the level 1 map changes.
* We are invoked by an interprocessor interrupt.
*/
void
pmap_do_reactivate(struct cpu_info *ci, struct trapframe *framep)
{
struct pmap *pmap;
if (ci->ci_curproc == NULL)
return;
pmap = ci->ci_curproc->p_vmspace->vm_map.pmap;
pmap_asn_alloc(pmap, ci->ci_cpuid);
if (PMAP_ISACTIVE(pmap, ci->ci_cpuid))
PMAP_ACTIVATE(pmap, ci->ci_curproc, ci->ci_cpuid);
}
#endif /* MULTIPROCESSOR */
/*
* pmap_zero_page: [ INTERFACE ]
*
* Zero the specified (machine independent) page by mapping the page
* into virtual memory and clear its contents, one machine dependent
* page at a time.
*
* Note: no locking is necessary in this function.
*/
void
pmap_zero_page(paddr_t phys)
{
u_long *p0, *p1, *pend;
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_zero_page(%lx)\n", phys);
#endif
p0 = (u_long *)ALPHA_PHYS_TO_K0SEG(phys);
pend = (u_long *)((u_long)p0 + PAGE_SIZE);
/*
* Unroll the loop a bit, doing 16 quadwords per iteration.
* Do only 8 back-to-back stores, and alternate registers.
*/
do {
__asm __volatile(
"# BEGIN loop body\n"
" addq %2, (8 * 8), %1 \n"
" stq $31, (0 * 8)(%0) \n"
" stq $31, (1 * 8)(%0) \n"
" stq $31, (2 * 8)(%0) \n"
" stq $31, (3 * 8)(%0) \n"
" stq $31, (4 * 8)(%0) \n"
" stq $31, (5 * 8)(%0) \n"
" stq $31, (6 * 8)(%0) \n"
" stq $31, (7 * 8)(%0) \n"
" \n"
" addq %3, (8 * 8), %0 \n"
" stq $31, (0 * 8)(%1) \n"
" stq $31, (1 * 8)(%1) \n"
" stq $31, (2 * 8)(%1) \n"
" stq $31, (3 * 8)(%1) \n"
" stq $31, (4 * 8)(%1) \n"
" stq $31, (5 * 8)(%1) \n"
" stq $31, (6 * 8)(%1) \n"
" stq $31, (7 * 8)(%1) \n"
" # END loop body"
: "=r" (p0), "=r" (p1)
: "0" (p0), "1" (p1)
: "memory");
} while (p0 < pend);
}
/*
* pmap_copy_page: [ INTERFACE ]
*
* Copy the specified (machine independent) page by mapping the page
* into virtual memory and using memcpy to copy the page, one machine
* dependent page at a time.
*
* Note: no locking is necessary in this function.
*/
void
pmap_copy_page(paddr_t src, paddr_t dst)
{
caddr_t s, d;
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_copy_page(%lx, %lx)\n", src, dst);
#endif
s = (caddr_t)ALPHA_PHYS_TO_K0SEG(src);
d = (caddr_t)ALPHA_PHYS_TO_K0SEG(dst);
memcpy(d, s, PAGE_SIZE);
}
/*
* pmap_pageidlezero: [ INTERFACE ]
*
* Page zero'er for the idle loop. Returns TRUE if the
* page was zero'd, FLASE if we aborted for some reason.
*/
boolean_t
pmap_pageidlezero(paddr_t pa)
{
u_long *ptr;
int i, cnt = PAGE_SIZE / sizeof(u_long);
for (i = 0, ptr = (u_long *) ALPHA_PHYS_TO_K0SEG(pa); i < cnt; i++) {
if (sched_whichqs != 0) {
/*
* A process has become ready. Abort now,
* so we don't keep it waiting while we
* finish zeroing the page.
*/
return (FALSE);
}
*ptr++ = 0;
}
return (TRUE);
}
/*
* pmap_clear_modify: [ INTERFACE ]
*
* Clear the modify bits on the specified physical page.
*/
boolean_t
pmap_clear_modify(struct vm_page *pg)
{
boolean_t rv = FALSE;
long cpu_id = cpu_number();
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_clear_modify(%p)\n", pg);
#endif
PMAP_HEAD_TO_MAP_LOCK();
simple_lock(&pg->mdpage.pvh_slock);
if (pg->mdpage.pvh_attrs & PGA_MODIFIED) {
rv = TRUE;
pmap_changebit(pg, PG_FOW, ~0, cpu_id);
pg->mdpage.pvh_attrs &= ~PGA_MODIFIED;
}
simple_unlock(&pg->mdpage.pvh_slock);
PMAP_HEAD_TO_MAP_UNLOCK();
return (rv);
}
/*
* pmap_clear_reference: [ INTERFACE ]
*
* Clear the reference bit on the specified physical page.
*/
boolean_t
pmap_clear_reference(struct vm_page *pg)
{
boolean_t rv = FALSE;
long cpu_id = cpu_number();
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_clear_reference(%p)\n", pg);
#endif
PMAP_HEAD_TO_MAP_LOCK();
simple_lock(&pg->mdpage.pvh_slock);
if (pg->mdpage.pvh_attrs & PGA_REFERENCED) {
rv = TRUE;
pmap_changebit(pg, PG_FOR | PG_FOW | PG_FOE, ~0, cpu_id);
pg->mdpage.pvh_attrs &= ~PGA_REFERENCED;
}
simple_unlock(&pg->mdpage.pvh_slock);
PMAP_HEAD_TO_MAP_UNLOCK();
return (rv);
}
/*
* pmap_is_referenced: [ INTERFACE ]
*
* Return whether or not the specified physical page is referenced
* by any physical maps.
*/
/* See <machine/pmap.h> */
/*
* pmap_is_modified: [ INTERFACE ]
*
* Return whether or not the specified physical page is modified
* by any physical maps.
*/
/* See <machine/pmap.h> */
/*
* pmap_phys_address: [ INTERFACE ]
*
* Return the physical address corresponding to the specified
* cookie. Used by the device pager to decode a device driver's
* mmap entry point return value.
*
* Note: no locking is necessary in this function.
*/
paddr_t
pmap_phys_address(int ppn)
{
return (alpha_ptob(ppn));
}
/*
* Miscellaneous support routines follow
*/
/*
* alpha_protection_init:
*
* Initialize Alpha protection code array.
*
* Note: no locking is necessary in this function.
*/
void
alpha_protection_init(void)
{
int prot, *kp, *up;
kp = protection_codes[0];
up = protection_codes[1];
for (prot = 0; prot < 8; prot++) {
kp[prot] = 0; up[prot] = 0;
switch (prot) {
case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
kp[prot] |= PG_ASM;
up[prot] |= 0;
break;
case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
kp[prot] |= PG_EXEC; /* software */
up[prot] |= PG_EXEC; /* software */
/* FALLTHROUGH */
case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
kp[prot] |= PG_ASM | PG_KRE;
up[prot] |= PG_URE | PG_KRE;
break;
case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
kp[prot] |= PG_ASM | PG_KWE;
up[prot] |= PG_UWE | PG_KWE;
break;
case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
kp[prot] |= PG_EXEC; /* software */
up[prot] |= PG_EXEC; /* software */
/* FALLTHROUGH */
case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
kp[prot] |= PG_ASM | PG_KWE | PG_KRE;
up[prot] |= PG_UWE | PG_URE | PG_KWE | PG_KRE;
break;
}
}
}
/*
* pmap_remove_mapping:
*
* Invalidate a single page denoted by pmap/va.
*
* If (pte != NULL), it is the already computed PTE for the page.
*
* Note: locking in this function is complicated by the fact
* that we can be called when the PV list is already locked.
* (pmap_page_protect()). In this case, the caller must be
* careful to get the next PV entry while we remove this entry
* from beneath it. We assume that the pmap itself is already
* locked; dolock applies only to the PV list.
*
* Returns TRUE or FALSE, indicating if an I-stream sync needs
* to be initiated (for this CPU or for other CPUs).
*/
boolean_t
pmap_remove_mapping(pmap_t pmap, vaddr_t va, pt_entry_t *pte,
boolean_t dolock, long cpu_id)
{
paddr_t pa;
struct vm_page *pg; /* if != NULL, page is managed */
boolean_t onpv;
boolean_t hadasm;
boolean_t isactive;
boolean_t needisync = FALSE;
PMAP_TLB_SHOOTDOWN_CPUSET_DECL
#ifdef DEBUG
if (pmapdebug & (PDB_FOLLOW|PDB_REMOVE|PDB_PROTECT))
printf("pmap_remove_mapping(%p, %lx, %p, %d, %ld)\n",
pmap, va, pte, dolock, cpu_id);
#endif
/*
* PTE not provided, compute it from pmap and va.
*/
if (pte == PT_ENTRY_NULL) {
pte = pmap_l3pte(pmap, va, NULL);
if (pmap_pte_v(pte) == 0)
return (FALSE);
}
pa = pmap_pte_pa(pte);
onpv = (pmap_pte_pv(pte) != 0);
hadasm = (pmap_pte_asm(pte) != 0);
isactive = PMAP_ISACTIVE(pmap, cpu_id);
/*
* Determine what we need to do about the I-stream. If
* PG_EXEC was set, we mark a user pmap as needing an
* I-sync on the way out to userspace. We always need
* an immediate I-sync for the kernel pmap.
*/
if (pmap_pte_exec(pte)) {
if (pmap == pmap_kernel())
needisync = TRUE;
else {
PMAP_SET_NEEDISYNC(pmap);
needisync = (pmap->pm_cpus != 0);
}
}
/*
* Update statistics
*/
if (pmap_pte_w(pte))
PMAP_STAT_DECR(pmap->pm_stats.wired_count, 1);
PMAP_STAT_DECR(pmap->pm_stats.resident_count, 1);
/*
* Invalidate the PTE after saving the reference modify info.
*/
#ifdef DEBUG
if (pmapdebug & PDB_REMOVE)
printf("remove: invalidating pte at %p\n", pte);
#endif
PMAP_SET_PTE(pte, PG_NV);
PMAP_INVALIDATE_TLB(pmap, va, hadasm, isactive, cpu_id);
PMAP_TLB_SHOOTDOWN(pmap, va, hadasm ? PG_ASM : 0);
PMAP_TLB_SHOOTNOW();
/*
* If we're removing a user mapping, check to see if we
* can free page table pages.
*/
if (pmap != pmap_kernel()) {
/*
* Delete the reference on the level 3 table. It will
* delete references on the level 2 and 1 tables as
* appropriate.
*/
pmap_l3pt_delref(pmap, va, pte, cpu_id);
}
/*
* If the mapping wasn't enterd on the PV list, we're all done.
*/
if (onpv == FALSE)
return (needisync);
/*
* Remove it from the PV table.
*/
pg = PHYS_TO_VM_PAGE(pa);
KASSERT(pg != NULL);
pmap_pv_remove(pmap, pg, va, dolock);
return (needisync);
}
/*
* pmap_changebit:
*
* Set or clear the specified PTE bits for all mappings on the
* specified page.
*
* Note: we assume that the pv_head is already locked, and that
* the caller has acquired a PV->pmap mutex so that we can lock
* the pmaps as we encounter them.
*/
void
pmap_changebit(struct vm_page *pg, u_long set, u_long mask, long cpu_id)
{
pv_entry_t pv;
pt_entry_t *pte, npte;
vaddr_t va;
boolean_t hadasm, isactive;
PMAP_TLB_SHOOTDOWN_CPUSET_DECL
#ifdef DEBUG
if (pmapdebug & PDB_BITS)
printf("pmap_changebit(0x%p, 0x%lx, 0x%lx)\n",
pg, set, mask);
#endif
/*
* Loop over all current mappings setting/clearing as appropos.
*/
for (pv = pg->mdpage.pvh_list; pv != NULL; pv = pv->pv_next) {
va = pv->pv_va;
PMAP_LOCK(pv->pv_pmap);
pte = pv->pv_pte;
npte = (*pte | set) & mask;
if (*pte != npte) {
hadasm = (pmap_pte_asm(pte) != 0);
isactive = PMAP_ISACTIVE(pv->pv_pmap, cpu_id);
PMAP_SET_PTE(pte, npte);
PMAP_INVALIDATE_TLB(pv->pv_pmap, va, hadasm, isactive,
cpu_id);
PMAP_TLB_SHOOTDOWN(pv->pv_pmap, va,
hadasm ? PG_ASM : 0);
}
PMAP_UNLOCK(pv->pv_pmap);
}
PMAP_TLB_SHOOTNOW();
}
/*
* pmap_emulate_reference:
*
* Emulate reference and/or modified bit hits.
*/
void
pmap_emulate_reference(struct proc *p, vaddr_t v, int user, int write)
{
pt_entry_t faultoff, *pte;
struct vm_page *pg;
paddr_t pa;
boolean_t didlock = FALSE;
long cpu_id = cpu_number();
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("pmap_emulate_reference: %p, 0x%lx, %d, %d\n",
p, v, user, write);
#endif
/*
* Convert process and virtual address to physical address.
*/
if (v >= VM_MIN_KERNEL_ADDRESS) {
if (user)
panic("pmap_emulate_reference: user ref to kernel");
/*
* No need to lock here; kernel PT pages never go away.
*/
pte = PMAP_KERNEL_PTE(v);
} else {
#ifdef DIAGNOSTIC
if (p == NULL)
panic("pmap_emulate_reference: bad proc");
if (p->p_vmspace == NULL)
panic("pmap_emulate_reference: bad p_vmspace");
#endif
PMAP_LOCK(p->p_vmspace->vm_map.pmap);
didlock = TRUE;
pte = pmap_l3pte(p->p_vmspace->vm_map.pmap, v, NULL);
/*
* We'll unlock below where we're done with the PTE.
*/
}
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW) {
printf("\tpte = %p, ", pte);
printf("*pte = 0x%lx\n", *pte);
}
#endif
#ifdef DEBUG /* These checks are more expensive */
if (!pmap_pte_v(pte))
panic("pmap_emulate_reference: invalid pte");
#if 0
/*
* Can't do these, because cpu_fork and cpu_swapin call
* pmap_emulate_reference(), and the bits aren't guaranteed,
* for them...
*/
if (write) {
if (!(*pte & (user ? PG_UWE : PG_UWE | PG_KWE)))
panic("pmap_emulate_reference: write but unwritable");
if (!(*pte & PG_FOW))
panic("pmap_emulate_reference: write but not FOW");
} else {
if (!(*pte & (user ? PG_URE : PG_URE | PG_KRE)))
panic("pmap_emulate_reference: !write but unreadable");
if (!(*pte & (PG_FOR | PG_FOE)))
panic("pmap_emulate_reference: !write but not FOR|FOE");
}
#endif
/* Other diagnostics? */
#endif
pa = pmap_pte_pa(pte);
/*
* We're now done with the PTE. If it was a user pmap, unlock
* it now.
*/
if (didlock)
PMAP_UNLOCK(p->p_vmspace->vm_map.pmap);
#ifdef DEBUG
if (pmapdebug & PDB_FOLLOW)
printf("\tpa = 0x%lx\n", pa);
#endif
#ifdef DIAGNOSTIC
if (!PAGE_IS_MANAGED(pa))
panic("pmap_emulate_reference(%p, 0x%lx, %d, %d): pa 0x%lx not managed", p, v, user, write, pa);
#endif
/*
* Twiddle the appropriate bits to reflect the reference
* and/or modification..
*
* The rules:
* (1) always mark page as used, and
* (2) if it was a write fault, mark page as modified.
*/
pg = PHYS_TO_VM_PAGE(pa);
PMAP_HEAD_TO_MAP_LOCK();
simple_lock(&pg->mdpage.pvh_slock);
if (write) {
pg->mdpage.pvh_attrs |= (PGA_REFERENCED|PGA_MODIFIED);
faultoff = PG_FOR | PG_FOW | PG_FOE;
} else {
pg->mdpage.pvh_attrs |= PGA_REFERENCED;
faultoff = PG_FOR | PG_FOE;
}
pmap_changebit(pg, 0, ~faultoff, cpu_id);
simple_unlock(&pg->mdpage.pvh_slock);
PMAP_HEAD_TO_MAP_UNLOCK();
}
#ifdef DEBUG
/*
* pmap_pv_dump:
*
* Dump the physical->virtual data for the specified page.
*/
void
pmap_pv_dump(paddr_t pa)
{
struct vm_page *pg;
pv_entry_t pv;
pg = PHYS_TO_VM_PAGE(pa);
simple_lock(&pg->mdpage.pvh_slock);
printf("pa 0x%lx (attrs = 0x%x):\n", pa, pg->mdpage.pvh_attrs);
for (pv = pg->mdpage.pvh_list; pv != NULL; pv = pv->pv_next)
printf(" pmap %p, va 0x%lx\n",
pv->pv_pmap, pv->pv_va);
printf("\n");
simple_unlock(&pg->mdpage.pvh_slock);
}
#endif
/*
* vtophys:
*
* Return the physical address corresponding to the K0SEG or
* K1SEG address provided.
*
* Note: no locking is necessary in this function.
*/
paddr_t
vtophys(vaddr_t vaddr)
{
pt_entry_t *pte;
paddr_t paddr = 0;
if (vaddr < ALPHA_K0SEG_BASE)
printf("vtophys: invalid vaddr 0x%lx", vaddr);
else if (vaddr <= ALPHA_K0SEG_END)
paddr = ALPHA_K0SEG_TO_PHYS(vaddr);
else {
pte = PMAP_KERNEL_PTE(vaddr);
if (pmap_pte_v(pte))
paddr = pmap_pte_pa(pte) | (vaddr & PGOFSET);
}
#if 0
printf("vtophys(0x%lx) -> 0x%lx\n", vaddr, paddr);
#endif
return (paddr);
}
/******************** pv_entry management ********************/
/*
* pmap_pv_enter:
*
* Add a physical->virtual entry to the pv_table.
*/
int
pmap_pv_enter(pmap_t pmap, struct vm_page *pg, vaddr_t va, pt_entry_t *pte,
boolean_t dolock)
{
pv_entry_t newpv;
/*
* Allocate and fill in the new pv_entry.
*/
newpv = pmap_pv_alloc();
if (newpv == NULL)
return ENOMEM;
newpv->pv_va = va;
newpv->pv_pmap = pmap;
newpv->pv_pte = pte;
if (dolock)
simple_lock(&pg->mdpage.pvh_slock);
#ifdef DEBUG
{
pv_entry_t pv;
/*
* Make sure the entry doesn't already exist.
*/
for (pv = pg->mdpage.pvh_list; pv != NULL; pv = pv->pv_next) {
if (pmap == pv->pv_pmap && va == pv->pv_va) {
printf("pmap = %p, va = 0x%lx\n", pmap, va);
panic("pmap_pv_enter: already in pv table");
}
}
}
#endif
/*
* ...and put it in the list.
*/
newpv->pv_next = pg->mdpage.pvh_list;
pg->mdpage.pvh_list = newpv;
if (dolock)
simple_unlock(&pg->mdpage.pvh_slock);
return 0;
}
/*
* pmap_pv_remove:
*
* Remove a physical->virtual entry from the pv_table.
*/
void
pmap_pv_remove(pmap_t pmap, struct vm_page *pg, vaddr_t va, boolean_t dolock)
{
pv_entry_t pv, *pvp;
if (dolock)
simple_lock(&pg->mdpage.pvh_slock);
/*
* Find the entry to remove.
*/
for (pvp = &pg->mdpage.pvh_list, pv = *pvp;
pv != NULL; pvp = &pv->pv_next, pv = *pvp)
if (pmap == pv->pv_pmap && va == pv->pv_va)
break;
#ifdef DEBUG
if (pv == NULL)
panic("pmap_pv_remove: not in pv table");
#endif
*pvp = pv->pv_next;
if (dolock)
simple_unlock(&pg->mdpage.pvh_slock);
pmap_pv_free(pv);
}
/*
* pmap_pv_page_alloc:
*
* Allocate a page for the pv_entry pool.
*/
void *
pmap_pv_page_alloc(struct pool *pp, int flags)
{
paddr_t pg;
if (pmap_physpage_alloc(PGU_PVENT, &pg))
return ((void *)ALPHA_PHYS_TO_K0SEG(pg));
return (NULL);
}
/*
* pmap_pv_page_free:
*
* Free a pv_entry pool page.
*/
void
pmap_pv_page_free(struct pool *pp, void *v)
{
pmap_physpage_free(ALPHA_K0SEG_TO_PHYS((vaddr_t)v));
}
/******************** misc. functions ********************/
/*
* pmap_physpage_alloc:
*
* Allocate a single page from the VM system and return the
* physical address for that page.
*/
boolean_t
pmap_physpage_alloc(int usage, paddr_t *pap)
{
struct vm_page *pg;
paddr_t pa;
/*
* Don't ask for a zero'd page in the L1PT case -- we will
* properly initialize it in the constructor.
*/
pg = uvm_pagealloc(NULL, 0, NULL, usage == PGU_L1PT ?
UVM_PGA_USERESERVE : UVM_PGA_USERESERVE|UVM_PGA_ZERO);
if (pg != NULL) {
pa = VM_PAGE_TO_PHYS(pg);
simple_lock(&pg->mdpage.pvh_slock);
#ifdef DIAGNOSTIC
if (pg->wire_count != 0) {
printf("pmap_physpage_alloc: page 0x%lx has "
"%d references\n", pa, pg->wire_count);
panic("pmap_physpage_alloc");
}
#endif
simple_unlock(&pg->mdpage.pvh_slock);
*pap = pa;
return (TRUE);
}
return (FALSE);
}
/*
* pmap_physpage_free:
*
* Free the single page table page at the specified physical address.
*/
void
pmap_physpage_free(paddr_t pa)
{
struct vm_page *pg;
if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL)
panic("pmap_physpage_free: bogus physical page address");
simple_lock(&pg->mdpage.pvh_slock);
#ifdef DIAGNOSTIC
if (pg->wire_count != 0)
panic("pmap_physpage_free: page still has references");
#endif
simple_unlock(&pg->mdpage.pvh_slock);
uvm_pagefree(pg);
}
/*
* pmap_physpage_addref:
*
* Add a reference to the specified special use page.
*/
int
pmap_physpage_addref(void *kva)
{
struct vm_page *pg;
paddr_t pa;
int rval;
pa = ALPHA_K0SEG_TO_PHYS(trunc_page((vaddr_t)kva));
pg = PHYS_TO_VM_PAGE(pa);
simple_lock(&pg->mdpage.pvh_slock);
rval = ++pg->wire_count;
simple_unlock(&pg->mdpage.pvh_slock);
return (rval);
}
/*
* pmap_physpage_delref:
*
* Delete a reference to the specified special use page.
*/
int
pmap_physpage_delref(void *kva)
{
struct vm_page *pg;
paddr_t pa;
int rval;
pa = ALPHA_K0SEG_TO_PHYS(trunc_page((vaddr_t)kva));
pg = PHYS_TO_VM_PAGE(pa);
simple_lock(&pg->mdpage.pvh_slock);
#ifdef DIAGNOSTIC
/*
* Make sure we never have a negative reference count.
*/
if (pg->wire_count == 0)
panic("pmap_physpage_delref: reference count already zero");
#endif
rval = --pg->wire_count;
simple_unlock(&pg->mdpage.pvh_slock);
return (rval);
}
/******************** page table page management ********************/
/*
* pmap_growkernel: [ INTERFACE ]
*
* Grow the kernel address space. This is a hint from the
* upper layer to pre-allocate more kernel PT pages.
*/
vaddr_t
pmap_growkernel(vaddr_t maxkvaddr)
{
struct pmap *kpm = pmap_kernel(), *pm;
paddr_t ptaddr;
pt_entry_t *l1pte, *l2pte, pte;
vaddr_t va;
int l1idx;
if (maxkvaddr <= virtual_end)
goto out; /* we are OK */
simple_lock(&pmap_growkernel_slock);
va = virtual_end;
while (va < maxkvaddr) {
/*
* If there is no valid L1 PTE (i.e. no L2 PT page),
* allocate a new L2 PT page and insert it into the
* L1 map.
*/
l1pte = pmap_l1pte(kpm, va);
if (pmap_pte_v(l1pte) == 0) {
/*
* XXX PGU_NORMAL? It's not a "traditional" PT page.
*/
if (uvm.page_init_done == FALSE) {
/*
* We're growing the kernel pmap early (from
* uvm_pageboot_alloc()). This case must
* be handled a little differently.
*/
ptaddr = ALPHA_K0SEG_TO_PHYS(
pmap_steal_memory(PAGE_SIZE, NULL, NULL));
} else if (pmap_physpage_alloc(PGU_NORMAL,
&ptaddr) == FALSE)
goto die;
pte = (atop(ptaddr) << PG_SHIFT) |
PG_V | PG_ASM | PG_KRE | PG_KWE | PG_WIRED;
*l1pte = pte;
l1idx = l1pte_index(va);
/* Update all the user pmaps. */
simple_lock(&pmap_all_pmaps_slock);
for (pm = TAILQ_FIRST(&pmap_all_pmaps);
pm != NULL; pm = TAILQ_NEXT(pm, pm_list)) {
/* Skip the kernel pmap. */
if (pm == pmap_kernel())
continue;
PMAP_LOCK(pm);
if (pm->pm_lev1map == kernel_lev1map) {
PMAP_UNLOCK(pm);
continue;
}
pm->pm_lev1map[l1idx] = pte;
PMAP_UNLOCK(pm);
}
simple_unlock(&pmap_all_pmaps_slock);
}
/*
* Have an L2 PT page now, add the L3 PT page.
*/
l2pte = pmap_l2pte(kpm, va, l1pte);
KASSERT(pmap_pte_v(l2pte) == 0);
if (uvm.page_init_done == FALSE) {
/*
* See above.
*/
ptaddr = ALPHA_K0SEG_TO_PHYS(
pmap_steal_memory(PAGE_SIZE, NULL, NULL));
} else if (pmap_physpage_alloc(PGU_NORMAL, &ptaddr) == FALSE)
goto die;
*l2pte = (atop(ptaddr) << PG_SHIFT) |
PG_V | PG_ASM | PG_KRE | PG_KWE | PG_WIRED;
va += ALPHA_L2SEG_SIZE;
}
/* Invalidate the L1 PT cache. */
pool_cache_invalidate(&pmap_l1pt_cache);
virtual_end = va;
simple_unlock(&pmap_growkernel_slock);
out:
return (virtual_end);
die:
panic("pmap_growkernel: out of memory");
}
/*
* pmap_lev1map_create:
*
* Create a new level 1 page table for the specified pmap.
*
* Note: growkernel and the pmap must already be locked.
*/
int
pmap_lev1map_create(pmap_t pmap, long cpu_id)
{
pt_entry_t *l1pt;
#ifdef DIAGNOSTIC
if (pmap == pmap_kernel())
panic("pmap_lev1map_create: got kernel pmap");
#endif
if (pmap->pm_lev1map != kernel_lev1map) {
/*
* We have to briefly unlock the pmap in pmap_enter()
* do deal with a lock ordering constraint, so it's
* entirely possible for this to happen.
*/
return (0);
}
#ifdef DIAGNOSTIC
if (pmap->pm_asni[cpu_id].pma_asn != PMAP_ASN_RESERVED)
panic("pmap_lev1map_create: pmap uses non-reserved ASN");
#endif
l1pt = pool_cache_get(&pmap_l1pt_cache, PR_NOWAIT);
if (l1pt == NULL)
return (ENOMEM);
pmap->pm_lev1map = l1pt;
/*
* The page table base has changed; if the pmap was active,
* reactivate it.
*/
if (PMAP_ISACTIVE(pmap, cpu_id)) {
pmap_asn_alloc(pmap, cpu_id);
PMAP_ACTIVATE(pmap, curproc, cpu_id);
}
PMAP_LEV1MAP_SHOOTDOWN(pmap, cpu_id);
return (0);
}
/*
* pmap_lev1map_destroy:
*
* Destroy the level 1 page table for the specified pmap.
*
* Note: the pmap must already be locked.
*/
void
pmap_lev1map_destroy(pmap_t pmap, long cpu_id)
{
pt_entry_t *l1pt = pmap->pm_lev1map;
#ifdef DIAGNOSTIC
if (pmap == pmap_kernel())
panic("pmap_lev1map_destroy: got kernel pmap");
#endif
/*
* Go back to referencing the global kernel_lev1map.
*/
pmap->pm_lev1map = kernel_lev1map;
/*
* The page table base has changed; if the pmap was active,
* reactivate it. Note that allocation of a new ASN is
* not necessary here:
*
* (1) We've gotten here because we've deleted all
* user mappings in the pmap, invalidating the
* TLB entries for them as we go.
*
* (2) kernel_lev1map contains only kernel mappings, which
* were identical in the user pmap, and all of
* those mappings have PG_ASM, so the ASN doesn't
* matter.
*
* We do, however, ensure that the pmap is using the
* reserved ASN, to ensure that no two pmaps never have
* clashing TLB entries.
*/
PMAP_INVALIDATE_ASN(pmap, cpu_id);
if (PMAP_ISACTIVE(pmap, cpu_id))
PMAP_ACTIVATE(pmap, curproc, cpu_id);
PMAP_LEV1MAP_SHOOTDOWN(pmap, cpu_id);
/*
* Free the old level 1 page table page.
*/
pool_cache_put(&pmap_l1pt_cache, l1pt);
}
/*
* pmap_l1pt_ctor:
*
* Pool cache constructor for L1 PT pages.
*/
int
pmap_l1pt_ctor(void *arg, void *object, int flags)
{
pt_entry_t *l1pt = object, pte;
int i;
/*
* Initialize the new level 1 table by zeroing the
* user portion and copying the kernel mappings into
* the kernel portion.
*/
for (i = 0; i < l1pte_index(VM_MIN_KERNEL_ADDRESS); i++)
l1pt[i] = 0;
for (i = l1pte_index(VM_MIN_KERNEL_ADDRESS);
i <= l1pte_index(VM_MAX_KERNEL_ADDRESS); i++)
l1pt[i] = kernel_lev1map[i];
/*
* Now, map the new virtual page table. NOTE: NO ASM!
*/
pte = ((ALPHA_K0SEG_TO_PHYS((vaddr_t) l1pt) >> PGSHIFT) << PG_SHIFT) |
PG_V | PG_KRE | PG_KWE;
l1pt[l1pte_index(VPTBASE)] = pte;
return (0);
}
/*
* pmap_l1pt_alloc:
*
* Page alloctor for L1 PT pages.
*/
void *
pmap_l1pt_alloc(struct pool *pp, int flags)
{
paddr_t ptpa;
/*
* Attempt to allocate a free page.
*/
if (pmap_physpage_alloc(PGU_L1PT, &ptpa) == FALSE)
return (NULL);
return ((void *) ALPHA_PHYS_TO_K0SEG(ptpa));
}
/*
* pmap_l1pt_free:
*
* Page freer for L1 PT pages.
*/
void
pmap_l1pt_free(struct pool *pp, void *v)
{
pmap_physpage_free(ALPHA_K0SEG_TO_PHYS((vaddr_t) v));
}
/*
* pmap_ptpage_alloc:
*
* Allocate a level 2 or level 3 page table page, and
* initialize the PTE that references it.
*
* Note: the pmap must already be locked.
*/
int
pmap_ptpage_alloc(pmap_t pmap, pt_entry_t *pte, int usage)
{
paddr_t ptpa;
/*
* Allocate the page table page.
*/
if (pmap_physpage_alloc(usage, &ptpa) == FALSE)
return (ENOMEM);
/*
* Initialize the referencing PTE.
*/
PMAP_SET_PTE(pte, ((ptpa >> PGSHIFT) << PG_SHIFT) |
PG_V | PG_KRE | PG_KWE | PG_WIRED |
(pmap == pmap_kernel() ? PG_ASM : 0));
return (0);
}
/*
* pmap_ptpage_free:
*
* Free the level 2 or level 3 page table page referenced
* be the provided PTE.
*
* Note: the pmap must already be locked.
*/
void
pmap_ptpage_free(pmap_t pmap, pt_entry_t *pte)
{
paddr_t ptpa;
/*
* Extract the physical address of the page from the PTE
* and clear the entry.
*/
ptpa = pmap_pte_pa(pte);
PMAP_SET_PTE(pte, PG_NV);
#ifdef DEBUG
pmap_zero_page(ptpa);
#endif
pmap_physpage_free(ptpa);
}
/*
* pmap_l3pt_delref:
*
* Delete a reference on a level 3 PT page. If the reference drops
* to zero, free it.
*
* Note: the pmap must already be locked.
*/
void
pmap_l3pt_delref(pmap_t pmap, vaddr_t va, pt_entry_t *l3pte, long cpu_id)
{
pt_entry_t *l1pte, *l2pte;
PMAP_TLB_SHOOTDOWN_CPUSET_DECL
l1pte = pmap_l1pte(pmap, va);
l2pte = pmap_l2pte(pmap, va, l1pte);
#ifdef DIAGNOSTIC
if (pmap == pmap_kernel())
panic("pmap_l3pt_delref: kernel pmap");
#endif
if (pmap_physpage_delref(l3pte) == 0) {
/*
* No more mappings; we can free the level 3 table.
*/
#ifdef DEBUG
if (pmapdebug & PDB_PTPAGE)
printf("pmap_l3pt_delref: freeing level 3 table at "
"0x%lx\n", pmap_pte_pa(l2pte));
#endif
pmap_ptpage_free(pmap, l2pte);
/*
* We've freed a level 3 table, so we must
* invalidate the TLB entry for that PT page
* in the Virtual Page Table VA range, because
* otherwise the PALcode will service a TLB
* miss using the stale VPT TLB entry it entered
* behind our back to shortcut to the VA's PTE.
*/
PMAP_INVALIDATE_TLB(pmap,
(vaddr_t)(&VPT[VPT_INDEX(va)]), FALSE,
PMAP_ISACTIVE(pmap, cpu_id), cpu_id);
PMAP_TLB_SHOOTDOWN(pmap,
(vaddr_t)(&VPT[VPT_INDEX(va)]), 0);
PMAP_TLB_SHOOTNOW();
/*
* We've freed a level 3 table, so delete the reference
* on the level 2 table.
*/
pmap_l2pt_delref(pmap, l1pte, l2pte, cpu_id);
}
}
/*
* pmap_l2pt_delref:
*
* Delete a reference on a level 2 PT page. If the reference drops
* to zero, free it.
*
* Note: the pmap must already be locked.
*/
void
pmap_l2pt_delref(pmap_t pmap, pt_entry_t *l1pte, pt_entry_t *l2pte,
long cpu_id)
{
#ifdef DIAGNOSTIC
if (pmap == pmap_kernel())
panic("pmap_l2pt_delref: kernel pmap");
#endif
if (pmap_physpage_delref(l2pte) == 0) {
/*
* No more mappings in this segment; we can free the
* level 2 table.
*/
#ifdef DEBUG
if (pmapdebug & PDB_PTPAGE)
printf("pmap_l2pt_delref: freeing level 2 table at "
"0x%lx\n", pmap_pte_pa(l1pte));
#endif
pmap_ptpage_free(pmap, l1pte);
/*
* We've freed a level 2 table, so delete the reference
* on the level 1 table.
*/
pmap_l1pt_delref(pmap, l1pte, cpu_id);
}
}
/*
* pmap_l1pt_delref:
*
* Delete a reference on a level 1 PT page. If the reference drops
* to zero, free it.
*
* Note: the pmap must already be locked.
*/
void
pmap_l1pt_delref(pmap_t pmap, pt_entry_t *l1pte, long cpu_id)
{
#ifdef DIAGNOSTIC
if (pmap == pmap_kernel())
panic("pmap_l1pt_delref: kernel pmap");
#endif
if (pmap_physpage_delref(l1pte) == 0) {
/*
* No more level 2 tables left, go back to the global
* kernel_lev1map.
*/
pmap_lev1map_destroy(pmap, cpu_id);
}
}
/******************** Address Space Number management ********************/
/*
* pmap_asn_alloc:
*
* Allocate and assign an ASN to the specified pmap.
*
* Note: the pmap must already be locked. This may be called from
* an interprocessor interrupt, and in that case, the sender of
* the IPI has the pmap lock.
*/
void
pmap_asn_alloc(pmap_t pmap, long cpu_id)
{
struct pmap_asn_info *pma = &pmap->pm_asni[cpu_id];
struct pmap_asn_info *cpma = &pmap_asn_info[cpu_id];
#ifdef DEBUG
if (pmapdebug & (PDB_FOLLOW|PDB_ASN))
printf("pmap_asn_alloc(%p)\n", pmap);
#endif
/*
* If the pmap is still using the global kernel_lev1map, there
* is no need to assign an ASN at this time, because only
* kernel mappings exist in that map, and all kernel mappings
* have PG_ASM set. If the pmap eventually gets its own
* lev1map, an ASN will be allocated at that time.
*/
if (pmap->pm_lev1map == kernel_lev1map) {
#ifdef DEBUG
if (pmapdebug & PDB_ASN)
printf("pmap_asn_alloc: still references "
"kernel_lev1map\n");
#endif
#if defined(MULTIPROCESSOR)
/*
* In a multiprocessor system, it's possible to
* get here without having PMAP_ASN_RESERVED in
* pmap->pm_asni[cpu_id].pma_asn; see pmap_lev1map_destroy().
*
* So, what we do here, is simply assign the reserved
* ASN for kernel_lev1map users and let things
* continue on. We do, however, let uniprocessor
* configurations continue to make its assertion.
*/
pma->pma_asn = PMAP_ASN_RESERVED;
#else
#ifdef DIAGNOSTIC
if (pma->pma_asn != PMAP_ASN_RESERVED)
panic("pmap_asn_alloc: kernel_lev1map without "
"PMAP_ASN_RESERVED");
#endif
#endif /* MULTIPROCESSOR */
return;
}
/*
* On processors which do not implement ASNs, the swpctx PALcode
* operation will automatically invalidate the TLB and I-cache,
* so we don't need to do that here.
*/
if (pmap_max_asn == 0) {
/*
* Refresh the pmap's generation number, to
* simplify logic elsewhere.
*/
pma->pma_asngen = cpma->pma_asngen;
#ifdef DEBUG
if (pmapdebug & PDB_ASN)
printf("pmap_asn_alloc: no ASNs, using asngen %lu\n",
pma->pma_asngen);
#endif
return;
}
/*
* Hopefully, we can continue using the one we have...
*/
if (pma->pma_asn != PMAP_ASN_RESERVED &&
pma->pma_asngen == cpma->pma_asngen) {
/*
* ASN is still in the current generation; keep on using it.
*/
#ifdef DEBUG
if (pmapdebug & PDB_ASN)
printf("pmap_asn_alloc: same generation, keeping %u\n",
pma->pma_asn);
#endif
return;
}
/*
* Need to assign a new ASN. Grab the next one, incrementing
* the generation number if we have to.
*/
if (cpma->pma_asn > pmap_max_asn) {
/*
* Invalidate all non-PG_ASM TLB entries and the
* I-cache, and bump the generation number.
*/
ALPHA_TBIAP();
alpha_pal_imb();
cpma->pma_asn = 1;
cpma->pma_asngen++;
#ifdef DIAGNOSTIC
if (cpma->pma_asngen == 0) {
/*
* The generation number has wrapped. We could
* handle this scenario by traversing all of
* the pmaps, and invaldating the generation
* number on those which are not currently
* in use by this processor.
*
* However... considering that we're using
* an unsigned 64-bit integer for generation
* numbers, on non-ASN CPUs, we won't wrap
* for approx. 585 million years, or 75 billion
* years on a 128-ASN CPU (assuming 1000 switch
* operations per second).
*
* So, we don't bother.
*/
panic("pmap_asn_alloc: too much uptime");
}
#endif
#ifdef DEBUG
if (pmapdebug & PDB_ASN)
printf("pmap_asn_alloc: generation bumped to %lu\n",
cpma->pma_asngen);
#endif
}
/*
* Assign the new ASN and validate the generation number.
*/
pma->pma_asn = cpma->pma_asn++;
pma->pma_asngen = cpma->pma_asngen;
#ifdef DEBUG
if (pmapdebug & PDB_ASN)
printf("pmap_asn_alloc: assigning %u to pmap %p\n",
pma->pma_asn, pmap);
#endif
/*
* Have a new ASN, so there's no need to sync the I-stream
* on the way back out to userspace.
*/
atomic_clearbits_ulong(&pmap->pm_needisync, (1UL << cpu_id));
}
#if defined(MULTIPROCESSOR)
/******************** TLB shootdown code ********************/
/*
* pmap_tlb_shootdown:
*
* Cause the TLB entry for pmap/va to be shot down.
*
* NOTE: The pmap must be locked here.
*/
void
pmap_tlb_shootdown(pmap_t pmap, vaddr_t va, pt_entry_t pte, u_long *cpumaskp)
{
struct pmap_tlb_shootdown_q *pq;
struct pmap_tlb_shootdown_job *pj;
struct cpu_info *ci, *self = curcpu();
u_long cpumask;
CPU_INFO_ITERATOR cii;
int s;
LOCK_ASSERT((pmap == pmap_kernel()) ||
simple_lock_held(&pmap->pm_slock));
cpumask = 0;
for (CPU_INFO_FOREACH(cii, ci)) {
if (ci == self)
continue;
/*
* The pmap must be locked (unless its the kernel
* pmap, in which case it is okay for it to be
* unlocked), which prevents it from becoming
* active on any additional processors. This makes
* it safe to check for activeness. If it's not
* active on the processor in question, then just
* mark it as needing a new ASN the next time it
* does, saving the IPI. We always have to send
* the IPI for the kernel pmap.
*
* Note if it's marked active now, and it becomes
* inactive by the time the processor receives
* the IPI, that's okay, because it does the right
* thing with it later.
*/
if (pmap != pmap_kernel() &&
PMAP_ISACTIVE(pmap, ci->ci_cpuid) == 0) {
PMAP_INVALIDATE_ASN(pmap, ci->ci_cpuid);
continue;
}
pq = &pmap_tlb_shootdown_q[ci->ci_cpuid];
PSJQ_LOCK(pq, s);
pq->pq_pte |= pte;
/*
* If a global flush is already pending, we
* don't really have to do anything else.
*/
if (pq->pq_tbia) {
PSJQ_UNLOCK(pq, s);
continue;
}
pj = pmap_tlb_shootdown_job_get(pq);
if (pj == NULL) {
/*
* Couldn't allocate a job entry. Just
* tell the processor to kill everything.
*/
pq->pq_tbia = 1;
} else {
pj->pj_pmap = pmap;
pj->pj_va = va;
pj->pj_pte = pte;
TAILQ_INSERT_TAIL(&pq->pq_head, pj, pj_list);
}
cpumask |= 1UL << ci->ci_cpuid;
PSJQ_UNLOCK(pq, s);
}
*cpumaskp |= cpumask;
}
/*
* pmap_tlb_shootnow:
*
* Process the TLB shootdowns that we have been accumulating
* for the specified processor set.
*/
void
pmap_tlb_shootnow(u_long cpumask)
{
alpha_multicast_ipi(cpumask, ALPHA_IPI_SHOOTDOWN);
}
/*
* pmap_do_tlb_shootdown:
*
* Process pending TLB shootdown operations for this processor.
*/
void
pmap_do_tlb_shootdown(struct cpu_info *ci, struct trapframe *framep)
{
u_long cpu_id = ci->ci_cpuid;
u_long cpu_mask = (1UL << cpu_id);
struct pmap_tlb_shootdown_q *pq = &pmap_tlb_shootdown_q[cpu_id];
struct pmap_tlb_shootdown_job *pj;
int s;
PSJQ_LOCK(pq, s);
if (pq->pq_tbia) {
if (pq->pq_pte & PG_ASM)
ALPHA_TBIA();
else
ALPHA_TBIAP();
pq->pq_tbia = 0;
pmap_tlb_shootdown_q_drain(pq);
} else {
while ((pj = TAILQ_FIRST(&pq->pq_head)) != NULL) {
TAILQ_REMOVE(&pq->pq_head, pj, pj_list);
PMAP_INVALIDATE_TLB(pj->pj_pmap, pj->pj_va,
pj->pj_pte & PG_ASM,
pj->pj_pmap->pm_cpus & cpu_mask, cpu_id);
pmap_tlb_shootdown_job_put(pq, pj);
}
pq->pq_pte = 0;
}
PSJQ_UNLOCK(pq, s);
}
/*
* pmap_tlb_shootdown_q_drain:
*
* Drain a processor's TLB shootdown queue. We do not perform
* the shootdown operations. This is merely a convenience
* function.
*
* Note: We expect the queue to be locked.
*/
void
pmap_tlb_shootdown_q_drain(struct pmap_tlb_shootdown_q *pq)
{
struct pmap_tlb_shootdown_job *pj;
while ((pj = TAILQ_FIRST(&pq->pq_head)) != NULL) {
TAILQ_REMOVE(&pq->pq_head, pj, pj_list);
pmap_tlb_shootdown_job_put(pq, pj);
}
pq->pq_pte = 0;
}
/*
* pmap_tlb_shootdown_job_get:
*
* Get a TLB shootdown job queue entry. This places a limit on
* the number of outstanding jobs a processor may have.
*
* Note: We expect the queue to be locked.
*/
struct pmap_tlb_shootdown_job *
pmap_tlb_shootdown_job_get(struct pmap_tlb_shootdown_q *pq)
{
struct pmap_tlb_shootdown_job *pj;
if (pq->pq_count >= PMAP_TLB_SHOOTDOWN_MAXJOBS)
return (NULL);
pj = pool_get(&pmap_tlb_shootdown_job_pool, PR_NOWAIT);
if (pj != NULL)
pq->pq_count++;
return (pj);
}
/*
* pmap_tlb_shootdown_job_put:
*
* Put a TLB shootdown job queue entry onto the free list.
*
* Note: We expect the queue to be locked.
*/
void
pmap_tlb_shootdown_job_put(struct pmap_tlb_shootdown_q *pq,
struct pmap_tlb_shootdown_job *pj)
{
#ifdef DIAGNOSTIC
if (pq->pq_count == 0)
panic("pmap_tlb_shootdown_job_put: queue length inconsistency");
#endif
pool_put(&pmap_tlb_shootdown_job_pool, pj);
pq->pq_count--;
}
#endif /* MULTIPROCESSOR */
| 25.432749 | 98 | 0.676887 |
ded9f3a60e3c16cdbc6321abe8e549eb79f7ba3c | 408 | h | C | Samples/IotHubD2D/utils.h | codecentric/azure-sphere-samples | 306a93886290b031a0cd802f449e6bbe12ba8cfe | [
"MIT"
] | 3 | 2021-02-04T17:04:35.000Z | 2021-02-18T23:02:52.000Z | Samples/IotHubD2D/utils.h | codecentric/azure-sphere-samples | 306a93886290b031a0cd802f449e6bbe12ba8cfe | [
"MIT"
] | null | null | null | Samples/IotHubD2D/utils.h | codecentric/azure-sphere-samples | 306a93886290b031a0cd802f449e6bbe12ba8cfe | [
"MIT"
] | 1 | 2021-02-04T17:04:23.000Z | 2021-02-04T17:04:23.000Z | #pragma once
#include <applibs/log.h>
#include <applibs/wificonfig.h>
#include "../../Library/parson.h"
#include "../../Library/led.h"
void DebugPrintCurrentlyConnectedWiFiNetwork(void);
void ShowStartupScreen(void);
bool GetBooleanValue(const JSON_Object *object, const char *name, const bool defaultValue);
void SetLedIfExistsInJson(const JSON_Object *json, led_channels_t led, const char *ledName); | 25.5 | 92 | 0.77451 |
54dba918ddf423b05a3f65fd1ab951c9d3569bf6 | 4,432 | h | C | openbabel-2.4.1/include/OB-BGL/verbose_visitors.h | sxhexe/reaction-route-search | f7694c84ca1def4a133ade3e1e2e09705cd28312 | [
"MIT"
] | 1 | 2017-09-16T07:36:29.000Z | 2017-09-16T07:36:29.000Z | openbabel-2.4.1/include/OB-BGL/verbose_visitors.h | sxhexe/reaction-route-search | f7694c84ca1def4a133ade3e1e2e09705cd28312 | [
"MIT"
] | null | null | null | openbabel-2.4.1/include/OB-BGL/verbose_visitors.h | sxhexe/reaction-route-search | f7694c84ca1def4a133ade3e1e2e09705cd28312 | [
"MIT"
] | null | null | null | /**********************************************************************
verbose_visitors.h - visitor classes dumping a short text message for every visitor function.
Copyright (C) 2007 by Gerde Menche
This file is part of the Open Babel project.
For more information, see <http://openbabel.org/>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation 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.
***********************************************************************/
#ifndef VERBOSE_VISITORS
#define VERBOSE_VISITORS
#include<ostream>
namespace OpenBabel {
class OBVerboseDFSVisitor {
std::ostream& os;
public:
OBVerboseDFSVisitor( std::ostream& o ) : os(o) {}
template <class Vertex, class Graph>
void initialize_vertex(Vertex u, const Graph& g)
{
os << "initialize_vertex() called on: " << u->GetIdx() << "\n";
}
template <class Vertex, class Graph>
void start_vertex(Vertex u, const Graph& g)
{
os << "start_vertex() called on: " << u->GetIdx() << "\n";
}
template <class Vertex, class Graph>
void discover_vertex(Vertex u, const Graph& g)
{
os << "discover_vertex() called on: " << u->GetIdx() << "\n";
}
template <class Edge, class Graph>
void examine_edge(Edge u, const Graph& g)
{
os << "examine_edge() called on: " << u->GetIdx() << "\n";
}
template <class Edge, class Graph>
void tree_edge(Edge u, const Graph& g)
{
os << "tree_edge() called on: " << u->GetIdx() << "\n";
}
template <class Edge, class Graph>
void back_edge(Edge u, const Graph& g)
{
os << "back_edge() called on: " << u->GetIdx() << "\n";
}
template <class Edge, class Graph>
void forward_or_cross_edge(Edge u, const Graph& g)
{
os << "forward_or_cross_edge() called on: " << u->GetIdx() << "\n";
}
template <class Vertex, class Graph>
void finish_vertex(Vertex u, const Graph& g)
{
os << "finish_vertex() called on: " << u->GetIdx() << "\n";
}
};
class OBVerboseBFSVisitor
{
std::ostream& os;
public :
OBVerboseBFSVisitor( std::ostream& o ) : os(o) {}
template< typename vertex, typename graph >
void initialize_vertex( vertex e, const graph& g)
{
os << "initialize_vertex() called on: " << e->GetIdx() << "\n" ;
}
template< typename vertex, typename graph >
void discover_vertex( vertex e, const graph& g)
{
os << "discover_vertex() called on: " << e->GetIdx() << "\n" ;
}
template< typename vertex, typename graph >
void examine_vertex( vertex e, const graph& g)
{
os << "examine_vertex() called on: " << e->GetIdx() << "\n" ;
}
template< typename edge, typename graph >
void examine_edge( edge e, const graph& g)
{
os << "examine_edge() called on: " << e->GetIdx() << "\n" ;
}
template< typename edge, typename graph >
void tree_edge( edge e, const graph& g)
{
os << "tree_edge() called on: " << e->GetIdx() << "\n" ;
}
template< typename edge, typename graph >
void non_tree_edge( edge e, const graph& g)
{
os << "non_tree_edge() called on: " << e->GetIdx() << "\n" ;
}
template< typename edge, typename graph >
void cycle_edge( edge e, const graph& g)
{
os << "cycle_edge() called on: " << e->GetIdx() << "\n" ;
}
template< typename edge, typename graph >
void gray_target( edge e, const graph& g)
{
os << "gray_target() called on: " << e->GetIdx() << "\n" ;
}
template< typename edge, typename graph >
void black_target( edge e, const graph& g)
{
os << "black_target() called on: " << e->GetIdx() << "\n" ;
}
template< typename vertex, typename graph >
void finish_vertex( vertex e, const graph& g)
{
os << "finish_vertex() called on: " << e->GetIdx() << "\n" ;
}
};
} // end namespace
#endif // VERBOSE_VISITORS
| 31.657143 | 93 | 0.567238 |
728739062872d50bdf2d0ae3f5a40a951b55adfd | 1,620 | c | C | lib/core/java.lang.stubs/CompilerStub.c | hayounglee/LaTTe | b4a74510d8cbe112e1897db2de75c0ff5ab97a9b | [
"BSD-3-Clause"
] | 4 | 2016-11-02T09:56:14.000Z | 2020-10-13T04:30:02.000Z | lib/core/java.lang.stubs/CompilerStub.c | hayounglee/LaTTe | b4a74510d8cbe112e1897db2de75c0ff5ab97a9b | [
"BSD-3-Clause"
] | 1 | 2015-07-23T02:34:11.000Z | 2015-07-23T02:34:11.000Z | lib/core/java.lang.stubs/CompilerStub.c | hayounglee/LaTTe | b4a74510d8cbe112e1897db2de75c0ff5ab97a9b | [
"BSD-3-Clause"
] | 3 | 2015-07-23T02:30:48.000Z | 2019-10-06T07:31:22.000Z | /* DO NOT EDIT THIS FILE - it is machine generated */
#include <StubPreamble.h>
/* Stubs for class java_lang_Compiler */
/* SYMBOL: java_lang_Compiler_initialize()V */
void
Kaffe_java_lang_Compiler_initialize_stub(stack_item* _P_, stack_item* _R_)
{
extern void java_lang_Compiler_initialize();
java_lang_Compiler_initialize();
}
/* SYMBOL: java_lang_Compiler_compileClass(Ljava/lang/Class;)Z */
void
Kaffe_java_lang_Compiler_compileClass_stub(stack_item* _P_, stack_item* _R_)
{
extern jbool java_lang_Compiler_compileClass(void*);
jbool ret = java_lang_Compiler_compileClass(_P_[0].p);
return_int(ret);
}
/* SYMBOL: java_lang_Compiler_compileClasses(Ljava/lang/String;)Z */
void
Kaffe_java_lang_Compiler_compileClasses_stub(stack_item* _P_, stack_item* _R_)
{
extern jbool java_lang_Compiler_compileClasses(void*);
jbool ret = java_lang_Compiler_compileClasses(_P_[0].p);
return_int(ret);
}
/* SYMBOL: java_lang_Compiler_command(Ljava/lang/Object;)Ljava/lang/Object; */
void
Kaffe_java_lang_Compiler_command_stub(stack_item* _P_, stack_item* _R_)
{
extern struct Hjava_lang_Object* java_lang_Compiler_command(void*);
struct Hjava_lang_Object* ret = java_lang_Compiler_command(_P_[0].p);
return_ref(ret);
}
/* SYMBOL: java_lang_Compiler_enable()V */
void
Kaffe_java_lang_Compiler_enable_stub(stack_item* _P_, stack_item* _R_)
{
extern void java_lang_Compiler_enable();
java_lang_Compiler_enable();
}
/* SYMBOL: java_lang_Compiler_disable()V */
void
Kaffe_java_lang_Compiler_disable_stub(stack_item* _P_, stack_item* _R_)
{
extern void java_lang_Compiler_disable();
java_lang_Compiler_disable();
}
| 28.928571 | 78 | 0.804321 |
9035d5df2858b3fa9f5fd1db29dd4e5d3080f57b | 7,416 | h | C | _gr_stin.h | davidbien/dgraph | dd7fcda05e9d4c1e9a31bd46ebb3d17edb91435a | [
"BSL-1.0"
] | null | null | null | _gr_stin.h | davidbien/dgraph | dd7fcda05e9d4c1e9a31bd46ebb3d17edb91435a | [
"BSL-1.0"
] | null | null | null | _gr_stin.h | davidbien/dgraph | dd7fcda05e9d4c1e9a31bd46ebb3d17edb91435a | [
"BSL-1.0"
] | null | null | null | #ifndef __GR_STIN_H
#define __GR_STIN_H
// Copyright David Lawrence Bien 1997 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt).
// _gr_stin.h
// This module defines the input objects used to read graphs from streams.
__DGRAPH_BEGIN_NAMESPACE
// Function that knows how to read raw data to a stream:
template < class t_TyInputStream, class t_TyRead >
void
_RawReadGraphEl( t_TyInputStream & _ris, t_TyRead & _rel )
{
Assert( 0 ); // Should specialize for each stream type.
}
template < class t_TyGraphNodeBaseReadPtr,
class t_TyGraphLinkBaseReadPtr,
class t_TyStreamObject,
// This causes all available information to be read - i.e.
// the names ( pointers ) of all links and nodes - this is not needed by all readers.
// The "extra information" attribute of the writer must correspond to that of the reader.
bool t_fReadExtraInformation >
struct _binary_input_base
{
private:
typedef _binary_input_base< t_TyGraphNodeBaseReadPtr,
t_TyGraphLinkBaseReadPtr,
t_TyStreamObject,
t_fReadExtraInformation > _TyThis;
public:
typedef t_TyGraphNodeBaseReadPtr _TyGraphNodeBaseReadPtr;
typedef t_TyGraphLinkBaseReadPtr _TyGraphLinkBaseReadPtr;
typedef typename t_TyStreamObject::_TyInitArg _TyInitArg;
typedef typename t_TyStreamObject::_TyStreamPos _TyStreamPos;
typedef typename t_TyStreamObject::_TyIONodeEl _TyIONodeEl;
typedef typename t_TyStreamObject::_TyIOLinkEl _TyIOLinkEl;
typedef typename _binary_rep_tokens< std::false_type >::_TyToken _TyToken;
t_TyStreamObject m_ris; // The stream from which we are reading.
_binary_input_base( _TyInitArg _ris,
_TyIONodeEl const & _rione,
_TyIOLinkEl const & _riole )
: m_ris( _ris, _rione, _riole )
{
}
_TyStreamPos _Tell()
{
return m_ris.TellG();
}
void _Seek( _TyStreamPos _sp )
{
m_ris.SeekG( _sp );
}
void _ReadToken( _TyToken * _puc )
{
__THROWPT( e_ttFileInput );
m_ris.Read( _puc, sizeof( _TyToken ) );
}
void _ReadNodePtr( _TyGraphNodeBaseReadPtr * _pgnbr )
{
__THROWPT( e_ttFileInput );
m_ris.Read( _pgnbr, sizeof *_pgnbr );
}
void _ReadLinkPtr( _TyGraphLinkBaseReadPtr * _pglbr )
{
__THROWPT( e_ttFileInput );
m_ris.Read( _pglbr, sizeof *_pglbr );
}
void _ReadNodeHeaderData( _TyGraphNodeBaseReadPtr * _pgnbr )
{
__THROWPT( e_ttFileInput );
if ( t_fReadExtraInformation )
{
_ReadNodePtr( _pgnbr );
}
else
{
*_pgnbr = 0; // Indicate that we din't read it.
}
}
void _ReadUnfinishedHeaderData( _TyGraphNodeBaseReadPtr * _pgnbr,
_TyGraphLinkBaseReadPtr * _pglbr )
{
__THROWPT( e_ttFileInput );
_ReadNodePtr( _pgnbr );
_ReadLinkPtr( _pglbr );
}
void _ReadNodeFooter()
{
__THROWPT( e_ttFileInput );
#ifdef __GR_BINARY_WRITENODEFOOTER
_TyToken uc;
_ReadToken( &uc );
if ( _binary_rep_tokens< std::false_type >::ms_ucNodeFooter != uc )
{
throw bad_graph_stream( "_ReadNodeFooter(): Expected node footer token." );
}
#endif //__GR_BINARY_WRITENODEFOOTER
}
void _ReadLinkName( _TyGraphLinkBaseReadPtr * _pglbr )
{
__THROWPT( e_ttFileInput );
_ReadLinkPtr( _pglbr );
}
void _ReadLinkHeaderData( _TyGraphLinkBaseReadPtr * _pglbr )
{
__THROWPT( e_ttFileInput );
if ( t_fReadExtraInformation )
{
_ReadLinkPtr( _pglbr );
}
else
{
// Indicate that we didn't read it:
*_pglbr = 0;
}
}
void _ReadLinkFromUnfinishedHeaderData( _TyGraphLinkBaseReadPtr * _pglbr,
_TyGraphNodeBaseReadPtr * _pgnbr )
{
__THROWPT( e_ttFileInput );
_ReadLinkPtr( _pglbr );
if ( t_fReadExtraInformation )
{
_ReadNodePtr( _pgnbr );
}
else
{
*_pgnbr = 0;
}
}
bool _FReadLinkConstructed()
{
__THROWPT( e_ttFileInput );
_TyToken uc;
_ReadToken( &uc );
if ( _binary_rep_tokens< std::false_type >::ms_ucLinkConstructed != uc &&
_binary_rep_tokens< std::false_type >::ms_ucLinkEmpty != uc )
{
throw bad_graph_stream( "_FReadLinkConstructed(): Bad construction token." );
}
return _binary_rep_tokens< std::false_type >::ms_ucLinkConstructed == uc;
}
void _ReadLinkFooter( _TyToken * _puc )
{
__THROWPT( e_ttFileInput );
_ReadToken( _puc );
}
void _ReadUnfinishedLinkFooterData( _TyGraphLinkBaseReadPtr * _pglbr,
_TyGraphNodeBaseReadPtr * _pgnbr )
{
__THROWPT( e_ttFileInput );
_ReadNodePtr( _pgnbr );
if ( t_fReadExtraInformation )
{
Assert( *_pglbr ); // This should have been read above.
}
else
{
if ( !*_pglbr )
{
// This may have been read above ( if we had a link from an unfinished node ):
_ReadLinkPtr( _pglbr );
}
}
}
};
template < class t_TyGraphNode, class t_TyGraphLink,
class t_TyStreamObject,
bool t_fReadExtraInformation,
class t_TyGraphNodeBaseReadPtr = const typename t_TyGraphNode::_TyGraphNodeBaseBase *,
class t_TyGraphLinkBaseReadPtr = const typename t_TyGraphLink::_TyGraphLinkBaseBase * >
struct _binary_input_object
: public _binary_input_base< t_TyGraphNodeBaseReadPtr,
t_TyGraphLinkBaseReadPtr,
t_TyStreamObject,
t_fReadExtraInformation >
{
private:
typedef _binary_input_object< t_TyGraphNode, t_TyGraphLink, t_TyStreamObject,
t_fReadExtraInformation, t_TyGraphNodeBaseReadPtr,
t_TyGraphLinkBaseReadPtr > _TyThis;
typedef _binary_input_base< t_TyGraphNodeBaseReadPtr,
t_TyGraphLinkBaseReadPtr,
t_TyStreamObject,
t_fReadExtraInformation > _TyBase;
public:
typedef _TyBase _TyInputObjectBase;
typedef typename _TyBase::_TyInitArg _TyInitArg;
typedef typename _TyBase::_TyIONodeEl _TyIONodeEl;
typedef typename _TyBase::_TyIOLinkEl _TyIOLinkEl;
_binary_input_object( _TyInitArg _ris,
_TyIONodeEl const & _rione,
_TyIOLinkEl const & _riole )
: _TyBase( _ris, _rione, _riole )
{
}
void _ReadNode( t_TyGraphNode * _pgn )
{
__THROWPT( e_ttFileInput | e_ttMemory );
#ifdef __DGRAPH_COUNT_EL_ALLOC_LIFETIME
gs_iNodesConstructed++;
#endif //__DGRAPH_COUNT_EL_ALLOC_LIFETIME
_TyBase::m_ris.ReadNodeEl( _pgn->RElNonConst() );
}
void _ReadLink( t_TyGraphLink * _pgl )
{
__THROWPT( e_ttFileInput | e_ttMemory );
#ifdef __DGRAPH_COUNT_EL_ALLOC_LIFETIME
gs_iLinksConstructed++;
#endif //__DGRAPH_COUNT_EL_ALLOC_LIFETIME
_TyBase::m_ris.ReadLinkEl( _pgl->RElNonConst() );
}
};
__DGRAPH_END_NAMESPACE
#endif //__GR_STIN_H
| 30.269388 | 102 | 0.634439 |
b0dc028e6f8c4933da3b91eccc9bdd63381a7453 | 489 | c | C | src/libc/time/clock_gettime.c | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 298 | 2015-03-04T13:36:51.000Z | 2021-12-19T05:11:58.000Z | src/libc/time/clock_gettime.c | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 31 | 2015-07-27T14:51:55.000Z | 2020-09-14T15:59:57.000Z | src/libc/time/clock_gettime.c | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 18 | 2016-03-27T13:49:22.000Z | 2021-09-21T19:02:04.000Z | // Copyright (c) 2015-2016 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#include <common/clock.h>
#include <common/time.h>
#include <cloudabi_syscalls.h>
#include <errno.h>
#include <time.h>
int clock_gettime(clockid_t clock_id, struct timespec *tp) {
cloudabi_timestamp_t ts;
cloudabi_errno_t error = cloudabi_sys_clock_time_get(clock_id->id, 1, &ts);
if (error != 0) {
errno = error;
return -1;
}
*tp = timestamp_to_timespec(ts);
return 0;
}
| 22.227273 | 77 | 0.695297 |
8e99dd093f5c1434dd1bc3026cbb8dabbbba2ae7 | 51,640 | c | C | xen/xen-4.2.2/tools/qemu-xen-traditional/tcg/arm/tcg-target.c | zhiming-shen/Xen-Blanket-NG | 47e59d9bb92e8fdc60942df526790ddb983a5496 | [
"Apache-2.0"
] | 3 | 2019-08-31T19:58:24.000Z | 2020-10-02T06:50:22.000Z | xen/xen-4.2.2/tools/qemu-xen-traditional/tcg/arm/tcg-target.c | zhiming-shen/Xen-Blanket-NG | 47e59d9bb92e8fdc60942df526790ddb983a5496 | [
"Apache-2.0"
] | 1 | 2020-10-16T19:13:49.000Z | 2020-10-16T19:13:49.000Z | xen-4.6.0/tools/qemu-xen-traditional/tcg/arm/tcg-target.c | StanPlatinum/ROP-detection-inside-VMs | 7b39298dd0791711cbd78fd0730b819b755cc995 | [
"MIT"
] | 1 | 2018-10-04T18:29:18.000Z | 2018-10-04T18:29:18.000Z | /*
* Tiny Code Generator for QEMU
*
* Copyright (c) 2008 Andrzej Zaborowski
*
* 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 NDEBUG
static const char * const tcg_target_reg_names[TCG_TARGET_NB_REGS] = {
"%r0",
"%r1",
"%r2",
"%r3",
"%r4",
"%r5",
"%r6",
"%r7",
"%r8",
"%r9",
"%r10",
"%r11",
"%r12",
"%r13",
"%r14",
};
#endif
static const int tcg_target_reg_alloc_order[] = {
TCG_REG_R0,
TCG_REG_R1,
TCG_REG_R2,
TCG_REG_R3,
TCG_REG_R4,
TCG_REG_R5,
TCG_REG_R6,
TCG_REG_R7,
TCG_REG_R8,
TCG_REG_R9,
TCG_REG_R10,
TCG_REG_R11,
TCG_REG_R12,
TCG_REG_R13,
TCG_REG_R14,
};
static const int tcg_target_call_iarg_regs[4] = {
TCG_REG_R0, TCG_REG_R1, TCG_REG_R2, TCG_REG_R3
};
static const int tcg_target_call_oarg_regs[2] = {
TCG_REG_R0, TCG_REG_R1
};
static void patch_reloc(uint8_t *code_ptr, int type,
tcg_target_long value, tcg_target_long addend)
{
switch (type) {
case R_ARM_ABS32:
*(uint32_t *) code_ptr = value;
break;
case R_ARM_CALL:
case R_ARM_JUMP24:
default:
tcg_abort();
case R_ARM_PC24:
*(uint32_t *) code_ptr = ((*(uint32_t *) code_ptr) & 0xff000000) |
(((value - ((tcg_target_long) code_ptr + 8)) >> 2) & 0xffffff);
break;
}
}
/* maximum number of register used for input function arguments */
static inline int tcg_target_get_call_iarg_regs_count(int flags)
{
return 4;
}
/* parse target specific constraints */
static int target_parse_constraint(TCGArgConstraint *ct, const char **pct_str)
{
const char *ct_str;
ct_str = *pct_str;
switch (ct_str[0]) {
case 'r':
#ifndef CONFIG_SOFTMMU
case 'd':
case 'D':
case 'x':
case 'X':
#endif
ct->ct |= TCG_CT_REG;
tcg_regset_set32(ct->u.regs, 0, (1 << TCG_TARGET_NB_REGS) - 1);
break;
#ifdef CONFIG_SOFTMMU
/* qemu_ld/st inputs (unless 'X', 'd' or 'D') */
case 'x':
ct->ct |= TCG_CT_REG;
tcg_regset_set32(ct->u.regs, 0, (1 << TCG_TARGET_NB_REGS) - 1);
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R0);
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R1);
break;
/* qemu_ld64 data_reg */
case 'd':
ct->ct |= TCG_CT_REG;
tcg_regset_set32(ct->u.regs, 0, (1 << TCG_TARGET_NB_REGS) - 1);
/* r1 is still needed to load data_reg2, so don't use it. */
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R1);
break;
/* qemu_ld/st64 data_reg2 */
case 'D':
ct->ct |= TCG_CT_REG;
tcg_regset_set32(ct->u.regs, 0, (1 << TCG_TARGET_NB_REGS) - 1);
/* r0, r1 and optionally r2 will be overwritten by the address
* and the low word of data, so don't use these. */
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R0);
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R1);
# if TARGET_LONG_BITS == 64
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R2);
# endif
break;
# if TARGET_LONG_BITS == 64
/* qemu_ld/st addr_reg2 */
case 'X':
ct->ct |= TCG_CT_REG;
tcg_regset_set32(ct->u.regs, 0, (1 << TCG_TARGET_NB_REGS) - 1);
/* r0 will be overwritten by the low word of base, so don't use it. */
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R0);
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R1);
break;
# endif
#endif
case '1':
ct->ct |= TCG_CT_REG;
tcg_regset_set32(ct->u.regs, 0, (1 << TCG_TARGET_NB_REGS) - 1);
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R0);
break;
case '2':
ct->ct |= TCG_CT_REG;
tcg_regset_set32(ct->u.regs, 0, (1 << TCG_TARGET_NB_REGS) - 1);
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R0);
tcg_regset_reset_reg(ct->u.regs, TCG_REG_R1);
break;
default:
return -1;
}
ct_str++;
*pct_str = ct_str;
return 0;
}
/* Test if a constant matches the constraint.
* TODO: define constraints for:
*
* ldr/str offset: between -0xfff and 0xfff
* ldrh/strh offset: between -0xff and 0xff
* mov operand2: values represented with x << (2 * y), x < 0x100
* add, sub, eor...: ditto
*/
static inline int tcg_target_const_match(tcg_target_long val,
const TCGArgConstraint *arg_ct)
{
int ct;
ct = arg_ct->ct;
if (ct & TCG_CT_CONST)
return 1;
else
return 0;
}
enum arm_data_opc_e {
ARITH_AND = 0x0,
ARITH_EOR = 0x1,
ARITH_SUB = 0x2,
ARITH_RSB = 0x3,
ARITH_ADD = 0x4,
ARITH_ADC = 0x5,
ARITH_SBC = 0x6,
ARITH_RSC = 0x7,
ARITH_TST = 0x8,
ARITH_CMP = 0xa,
ARITH_CMN = 0xb,
ARITH_ORR = 0xc,
ARITH_MOV = 0xd,
ARITH_BIC = 0xe,
ARITH_MVN = 0xf,
};
#define TO_CPSR(opc) \
((opc == ARITH_CMP || opc == ARITH_CMN || opc == ARITH_TST) << 20)
#define SHIFT_IMM_LSL(im) (((im) << 7) | 0x00)
#define SHIFT_IMM_LSR(im) (((im) << 7) | 0x20)
#define SHIFT_IMM_ASR(im) (((im) << 7) | 0x40)
#define SHIFT_IMM_ROR(im) (((im) << 7) | 0x60)
#define SHIFT_REG_LSL(rs) (((rs) << 8) | 0x10)
#define SHIFT_REG_LSR(rs) (((rs) << 8) | 0x30)
#define SHIFT_REG_ASR(rs) (((rs) << 8) | 0x50)
#define SHIFT_REG_ROR(rs) (((rs) << 8) | 0x70)
enum arm_cond_code_e {
COND_EQ = 0x0,
COND_NE = 0x1,
COND_CS = 0x2, /* Unsigned greater or equal */
COND_CC = 0x3, /* Unsigned less than */
COND_MI = 0x4, /* Negative */
COND_PL = 0x5, /* Zero or greater */
COND_VS = 0x6, /* Overflow */
COND_VC = 0x7, /* No overflow */
COND_HI = 0x8, /* Unsigned greater than */
COND_LS = 0x9, /* Unsigned less or equal */
COND_GE = 0xa,
COND_LT = 0xb,
COND_GT = 0xc,
COND_LE = 0xd,
COND_AL = 0xe,
};
static const uint8_t tcg_cond_to_arm_cond[10] = {
[TCG_COND_EQ] = COND_EQ,
[TCG_COND_NE] = COND_NE,
[TCG_COND_LT] = COND_LT,
[TCG_COND_GE] = COND_GE,
[TCG_COND_LE] = COND_LE,
[TCG_COND_GT] = COND_GT,
/* unsigned */
[TCG_COND_LTU] = COND_CC,
[TCG_COND_GEU] = COND_CS,
[TCG_COND_LEU] = COND_LS,
[TCG_COND_GTU] = COND_HI,
};
static inline void tcg_out_bx(TCGContext *s, int cond, int rn)
{
tcg_out32(s, (cond << 28) | 0x012fff10 | rn);
}
static inline void tcg_out_b(TCGContext *s, int cond, int32_t offset)
{
tcg_out32(s, (cond << 28) | 0x0a000000 |
(((offset - 8) >> 2) & 0x00ffffff));
}
static inline void tcg_out_b_noaddr(TCGContext *s, int cond)
{
#ifdef WORDS_BIGENDIAN
tcg_out8(s, (cond << 4) | 0x0a);
s->code_ptr += 3;
#else
s->code_ptr += 3;
tcg_out8(s, (cond << 4) | 0x0a);
#endif
}
static inline void tcg_out_bl(TCGContext *s, int cond, int32_t offset)
{
tcg_out32(s, (cond << 28) | 0x0b000000 |
(((offset - 8) >> 2) & 0x00ffffff));
}
static inline void tcg_out_dat_reg(TCGContext *s,
int cond, int opc, int rd, int rn, int rm, int shift)
{
tcg_out32(s, (cond << 28) | (0 << 25) | (opc << 21) | TO_CPSR(opc) |
(rn << 16) | (rd << 12) | shift | rm);
}
static inline void tcg_out_dat_reg2(TCGContext *s,
int cond, int opc0, int opc1, int rd0, int rd1,
int rn0, int rn1, int rm0, int rm1, int shift)
{
if (rd0 == rn1 || rd0 == rm1) {
tcg_out32(s, (cond << 28) | (0 << 25) | (opc0 << 21) | (1 << 20) |
(rn0 << 16) | (8 << 12) | shift | rm0);
tcg_out32(s, (cond << 28) | (0 << 25) | (opc1 << 21) |
(rn1 << 16) | (rd1 << 12) | shift | rm1);
tcg_out_dat_reg(s, cond, ARITH_MOV,
rd0, 0, TCG_REG_R8, SHIFT_IMM_LSL(0));
} else {
tcg_out32(s, (cond << 28) | (0 << 25) | (opc0 << 21) | (1 << 20) |
(rn0 << 16) | (rd0 << 12) | shift | rm0);
tcg_out32(s, (cond << 28) | (0 << 25) | (opc1 << 21) |
(rn1 << 16) | (rd1 << 12) | shift | rm1);
}
}
static inline void tcg_out_dat_imm(TCGContext *s,
int cond, int opc, int rd, int rn, int im)
{
tcg_out32(s, (cond << 28) | (1 << 25) | (opc << 21) | TO_CPSR(opc) |
(rn << 16) | (rd << 12) | im);
}
static inline void tcg_out_movi32(TCGContext *s,
int cond, int rd, int32_t arg)
{
int offset = (uint32_t) arg - ((uint32_t) s->code_ptr + 8);
/* TODO: This is very suboptimal, we can easily have a constant
* pool somewhere after all the instructions. */
if (arg < 0 && arg > -0x100)
return tcg_out_dat_imm(s, cond, ARITH_MVN, rd, 0, (~arg) & 0xff);
if (offset < 0x100 && offset > -0x100)
return offset >= 0 ?
tcg_out_dat_imm(s, cond, ARITH_ADD, rd, 15, offset) :
tcg_out_dat_imm(s, cond, ARITH_SUB, rd, 15, -offset);
tcg_out_dat_imm(s, cond, ARITH_MOV, rd, 0, arg & 0xff);
if (arg & 0x0000ff00)
tcg_out_dat_imm(s, cond, ARITH_ORR, rd, rd,
((arg >> 8) & 0xff) | 0xc00);
if (arg & 0x00ff0000)
tcg_out_dat_imm(s, cond, ARITH_ORR, rd, rd,
((arg >> 16) & 0xff) | 0x800);
if (arg & 0xff000000)
tcg_out_dat_imm(s, cond, ARITH_ORR, rd, rd,
((arg >> 24) & 0xff) | 0x400);
}
static inline void tcg_out_mul32(TCGContext *s,
int cond, int rd, int rs, int rm)
{
if (rd != rm)
tcg_out32(s, (cond << 28) | (rd << 16) | (0 << 12) |
(rs << 8) | 0x90 | rm);
else if (rd != rs)
tcg_out32(s, (cond << 28) | (rd << 16) | (0 << 12) |
(rm << 8) | 0x90 | rs);
else {
tcg_out32(s, (cond << 28) | ( 8 << 16) | (0 << 12) |
(rs << 8) | 0x90 | rm);
tcg_out_dat_reg(s, cond, ARITH_MOV,
rd, 0, 8, SHIFT_IMM_LSL(0));
}
}
static inline void tcg_out_umull32(TCGContext *s,
int cond, int rd0, int rd1, int rs, int rm)
{
if (rd0 != rm && rd1 != rm)
tcg_out32(s, (cond << 28) | 0x800090 |
(rd1 << 16) | (rd0 << 12) | (rs << 8) | rm);
else if (rd0 != rs && rd1 != rs)
tcg_out32(s, (cond << 28) | 0x800090 |
(rd1 << 16) | (rd0 << 12) | (rm << 8) | rs);
else {
tcg_out_dat_reg(s, cond, ARITH_MOV,
TCG_REG_R8, 0, rm, SHIFT_IMM_LSL(0));
tcg_out32(s, (cond << 28) | 0x800098 |
(rd1 << 16) | (rd0 << 12) | (rs << 8));
}
}
static inline void tcg_out_smull32(TCGContext *s,
int cond, int rd0, int rd1, int rs, int rm)
{
if (rd0 != rm && rd1 != rm)
tcg_out32(s, (cond << 28) | 0xc00090 |
(rd1 << 16) | (rd0 << 12) | (rs << 8) | rm);
else if (rd0 != rs && rd1 != rs)
tcg_out32(s, (cond << 28) | 0xc00090 |
(rd1 << 16) | (rd0 << 12) | (rm << 8) | rs);
else {
tcg_out_dat_reg(s, cond, ARITH_MOV,
TCG_REG_R8, 0, rm, SHIFT_IMM_LSL(0));
tcg_out32(s, (cond << 28) | 0xc00098 |
(rd1 << 16) | (rd0 << 12) | (rs << 8));
}
}
static inline void tcg_out_ld32_12(TCGContext *s, int cond,
int rd, int rn, tcg_target_long im)
{
if (im >= 0)
tcg_out32(s, (cond << 28) | 0x05900000 |
(rn << 16) | (rd << 12) | (im & 0xfff));
else
tcg_out32(s, (cond << 28) | 0x05100000 |
(rn << 16) | (rd << 12) | ((-im) & 0xfff));
}
static inline void tcg_out_st32_12(TCGContext *s, int cond,
int rd, int rn, tcg_target_long im)
{
if (im >= 0)
tcg_out32(s, (cond << 28) | 0x05800000 |
(rn << 16) | (rd << 12) | (im & 0xfff));
else
tcg_out32(s, (cond << 28) | 0x05000000 |
(rn << 16) | (rd << 12) | ((-im) & 0xfff));
}
static inline void tcg_out_ld32_r(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x07900000 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_st32_r(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x07800000 |
(rn << 16) | (rd << 12) | rm);
}
/* Register pre-increment with base writeback. */
static inline void tcg_out_ld32_rwb(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x07b00000 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_st32_rwb(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x07a00000 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_ld16u_8(TCGContext *s, int cond,
int rd, int rn, tcg_target_long im)
{
if (im >= 0)
tcg_out32(s, (cond << 28) | 0x01d000b0 |
(rn << 16) | (rd << 12) |
((im & 0xf0) << 4) | (im & 0xf));
else
tcg_out32(s, (cond << 28) | 0x015000b0 |
(rn << 16) | (rd << 12) |
(((-im) & 0xf0) << 4) | ((-im) & 0xf));
}
static inline void tcg_out_st16u_8(TCGContext *s, int cond,
int rd, int rn, tcg_target_long im)
{
if (im >= 0)
tcg_out32(s, (cond << 28) | 0x01c000b0 |
(rn << 16) | (rd << 12) |
((im & 0xf0) << 4) | (im & 0xf));
else
tcg_out32(s, (cond << 28) | 0x014000b0 |
(rn << 16) | (rd << 12) |
(((-im) & 0xf0) << 4) | ((-im) & 0xf));
}
static inline void tcg_out_ld16u_r(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x019000b0 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_st16u_r(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x018000b0 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_ld16s_8(TCGContext *s, int cond,
int rd, int rn, tcg_target_long im)
{
if (im >= 0)
tcg_out32(s, (cond << 28) | 0x01d000f0 |
(rn << 16) | (rd << 12) |
((im & 0xf0) << 4) | (im & 0xf));
else
tcg_out32(s, (cond << 28) | 0x015000f0 |
(rn << 16) | (rd << 12) |
(((-im) & 0xf0) << 4) | ((-im) & 0xf));
}
static inline void tcg_out_st16s_8(TCGContext *s, int cond,
int rd, int rn, tcg_target_long im)
{
if (im >= 0)
tcg_out32(s, (cond << 28) | 0x01c000f0 |
(rn << 16) | (rd << 12) |
((im & 0xf0) << 4) | (im & 0xf));
else
tcg_out32(s, (cond << 28) | 0x014000f0 |
(rn << 16) | (rd << 12) |
(((-im) & 0xf0) << 4) | ((-im) & 0xf));
}
static inline void tcg_out_ld16s_r(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x019000f0 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_st16s_r(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x018000f0 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_ld8_12(TCGContext *s, int cond,
int rd, int rn, tcg_target_long im)
{
if (im >= 0)
tcg_out32(s, (cond << 28) | 0x05d00000 |
(rn << 16) | (rd << 12) | (im & 0xfff));
else
tcg_out32(s, (cond << 28) | 0x05500000 |
(rn << 16) | (rd << 12) | ((-im) & 0xfff));
}
static inline void tcg_out_st8_12(TCGContext *s, int cond,
int rd, int rn, tcg_target_long im)
{
if (im >= 0)
tcg_out32(s, (cond << 28) | 0x05c00000 |
(rn << 16) | (rd << 12) | (im & 0xfff));
else
tcg_out32(s, (cond << 28) | 0x05400000 |
(rn << 16) | (rd << 12) | ((-im) & 0xfff));
}
static inline void tcg_out_ld8_r(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x07d00000 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_st8_r(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x07c00000 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_ld8s_8(TCGContext *s, int cond,
int rd, int rn, tcg_target_long im)
{
if (im >= 0)
tcg_out32(s, (cond << 28) | 0x01d000d0 |
(rn << 16) | (rd << 12) |
((im & 0xf0) << 4) | (im & 0xf));
else
tcg_out32(s, (cond << 28) | 0x015000d0 |
(rn << 16) | (rd << 12) |
(((-im) & 0xf0) << 4) | ((-im) & 0xf));
}
static inline void tcg_out_st8s_8(TCGContext *s, int cond,
int rd, int rn, tcg_target_long im)
{
if (im >= 0)
tcg_out32(s, (cond << 28) | 0x01c000d0 |
(rn << 16) | (rd << 12) |
((im & 0xf0) << 4) | (im & 0xf));
else
tcg_out32(s, (cond << 28) | 0x014000d0 |
(rn << 16) | (rd << 12) |
(((-im) & 0xf0) << 4) | ((-im) & 0xf));
}
static inline void tcg_out_ld8s_r(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x019000d0 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_st8s_r(TCGContext *s, int cond,
int rd, int rn, int rm)
{
tcg_out32(s, (cond << 28) | 0x018000d0 |
(rn << 16) | (rd << 12) | rm);
}
static inline void tcg_out_ld32u(TCGContext *s, int cond,
int rd, int rn, int32_t offset)
{
if (offset > 0xfff || offset < -0xfff) {
tcg_out_movi32(s, cond, TCG_REG_R8, offset);
tcg_out_ld32_r(s, cond, rd, rn, TCG_REG_R8);
} else
tcg_out_ld32_12(s, cond, rd, rn, offset);
}
static inline void tcg_out_st32(TCGContext *s, int cond,
int rd, int rn, int32_t offset)
{
if (offset > 0xfff || offset < -0xfff) {
tcg_out_movi32(s, cond, TCG_REG_R8, offset);
tcg_out_st32_r(s, cond, rd, rn, TCG_REG_R8);
} else
tcg_out_st32_12(s, cond, rd, rn, offset);
}
static inline void tcg_out_ld16u(TCGContext *s, int cond,
int rd, int rn, int32_t offset)
{
if (offset > 0xff || offset < -0xff) {
tcg_out_movi32(s, cond, TCG_REG_R8, offset);
tcg_out_ld16u_r(s, cond, rd, rn, TCG_REG_R8);
} else
tcg_out_ld16u_8(s, cond, rd, rn, offset);
}
static inline void tcg_out_ld16s(TCGContext *s, int cond,
int rd, int rn, int32_t offset)
{
if (offset > 0xff || offset < -0xff) {
tcg_out_movi32(s, cond, TCG_REG_R8, offset);
tcg_out_ld16s_r(s, cond, rd, rn, TCG_REG_R8);
} else
tcg_out_ld16s_8(s, cond, rd, rn, offset);
}
static inline void tcg_out_st16u(TCGContext *s, int cond,
int rd, int rn, int32_t offset)
{
if (offset > 0xff || offset < -0xff) {
tcg_out_movi32(s, cond, TCG_REG_R8, offset);
tcg_out_st16u_r(s, cond, rd, rn, TCG_REG_R8);
} else
tcg_out_st16u_8(s, cond, rd, rn, offset);
}
static inline void tcg_out_ld8u(TCGContext *s, int cond,
int rd, int rn, int32_t offset)
{
if (offset > 0xfff || offset < -0xfff) {
tcg_out_movi32(s, cond, TCG_REG_R8, offset);
tcg_out_ld8_r(s, cond, rd, rn, TCG_REG_R8);
} else
tcg_out_ld8_12(s, cond, rd, rn, offset);
}
static inline void tcg_out_ld8s(TCGContext *s, int cond,
int rd, int rn, int32_t offset)
{
if (offset > 0xff || offset < -0xff) {
tcg_out_movi32(s, cond, TCG_REG_R8, offset);
tcg_out_ld8s_r(s, cond, rd, rn, TCG_REG_R8);
} else
tcg_out_ld8s_8(s, cond, rd, rn, offset);
}
static inline void tcg_out_st8u(TCGContext *s, int cond,
int rd, int rn, int32_t offset)
{
if (offset > 0xfff || offset < -0xfff) {
tcg_out_movi32(s, cond, TCG_REG_R8, offset);
tcg_out_st8_r(s, cond, rd, rn, TCG_REG_R8);
} else
tcg_out_st8_12(s, cond, rd, rn, offset);
}
static inline void tcg_out_goto(TCGContext *s, int cond, uint32_t addr)
{
int32_t val;
val = addr - (tcg_target_long) s->code_ptr;
if (val - 8 < 0x01fffffd && val - 8 > -0x01fffffd)
tcg_out_b(s, cond, val);
else {
#if 1
tcg_abort();
#else
if (cond == COND_AL) {
tcg_out_ld32_12(s, COND_AL, 15, 15, -4);
tcg_out32(s, addr); /* XXX: This is l->u.value, can we use it? */
} else {
tcg_out_movi32(s, cond, TCG_REG_R8, val - 8);
tcg_out_dat_reg(s, cond, ARITH_ADD,
15, 15, TCG_REG_R8, SHIFT_IMM_LSL(0));
}
#endif
}
}
static inline void tcg_out_call(TCGContext *s, int cond, uint32_t addr)
{
int32_t val;
#ifdef SAVE_LR
tcg_out_dat_reg(s, cond, ARITH_MOV, TCG_REG_R8, 0, 14, SHIFT_IMM_LSL(0));
#endif
val = addr - (tcg_target_long) s->code_ptr;
if (val < 0x01fffffd && val > -0x01fffffd)
tcg_out_bl(s, cond, val);
else {
#if 1
tcg_abort();
#else
if (cond == COND_AL) {
tcg_out_dat_imm(s, cond, ARITH_ADD, 14, 15, 4);
tcg_out_ld32_12(s, COND_AL, 15, 15, -4);
tcg_out32(s, addr); /* XXX: This is l->u.value, can we use it? */
} else {
tcg_out_movi32(s, cond, TCG_REG_R9, addr);
tcg_out_dat_imm(s, cond, ARITH_MOV, 14, 0, 15);
tcg_out_bx(s, cond, TCG_REG_R9);
}
#endif
}
#ifdef SAVE_LR
tcg_out_dat_reg(s, cond, ARITH_MOV, 14, 0, TCG_REG_R8, SHIFT_IMM_LSL(0));
#endif
}
static inline void tcg_out_callr(TCGContext *s, int cond, int arg)
{
#ifdef SAVE_LR
tcg_out_dat_reg(s, cond, ARITH_MOV, TCG_REG_R8, 0, 14, SHIFT_IMM_LSL(0));
#endif
/* TODO: on ARMv5 and ARMv6 replace with tcg_out_blx(s, cond, arg); */
tcg_out_dat_reg(s, cond, ARITH_MOV, 14, 0, 15, SHIFT_IMM_LSL(0));
tcg_out_bx(s, cond, arg);
#ifdef SAVE_LR
tcg_out_dat_reg(s, cond, ARITH_MOV, 14, 0, TCG_REG_R8, SHIFT_IMM_LSL(0));
#endif
}
static inline void tcg_out_goto_label(TCGContext *s, int cond, int label_index)
{
TCGLabel *l = &s->labels[label_index];
if (l->has_value)
tcg_out_goto(s, cond, l->u.value);
else if (cond == COND_AL) {
tcg_out_ld32_12(s, COND_AL, 15, 15, -4);
tcg_out_reloc(s, s->code_ptr, R_ARM_ABS32, label_index, 31337);
s->code_ptr += 4;
} else {
/* Probably this should be preferred even for COND_AL... */
tcg_out_reloc(s, s->code_ptr, R_ARM_PC24, label_index, 31337);
tcg_out_b_noaddr(s, cond);
}
}
static void tcg_out_div_helper(TCGContext *s, int cond, const TCGArg *args,
void *helper_div, void *helper_rem, int shift)
{
int div_reg = args[0];
int rem_reg = args[1];
/* stmdb sp!, { r0 - r3, ip, lr } */
/* (Note that we need an even number of registers as per EABI) */
tcg_out32(s, (cond << 28) | 0x092d500f);
tcg_out_dat_reg(s, cond, ARITH_MOV, 0, 0, args[2], SHIFT_IMM_LSL(0));
tcg_out_dat_reg(s, cond, ARITH_MOV, 1, 0, args[3], SHIFT_IMM_LSL(0));
tcg_out_dat_reg(s, cond, ARITH_MOV, 2, 0, args[4], SHIFT_IMM_LSL(0));
tcg_out_dat_reg(s, cond, ARITH_MOV, 3, 0, 2, shift);
tcg_out_call(s, cond, (uint32_t) helper_div);
tcg_out_dat_reg(s, cond, ARITH_MOV, 8, 0, 0, SHIFT_IMM_LSL(0));
/* ldmia sp, { r0 - r3, fp, lr } */
tcg_out32(s, (cond << 28) | 0x089d500f);
tcg_out_dat_reg(s, cond, ARITH_MOV, 0, 0, args[2], SHIFT_IMM_LSL(0));
tcg_out_dat_reg(s, cond, ARITH_MOV, 1, 0, args[3], SHIFT_IMM_LSL(0));
tcg_out_dat_reg(s, cond, ARITH_MOV, 2, 0, args[4], SHIFT_IMM_LSL(0));
tcg_out_dat_reg(s, cond, ARITH_MOV, 3, 0, 2, shift);
tcg_out_call(s, cond, (uint32_t) helper_rem);
tcg_out_dat_reg(s, cond, ARITH_MOV, rem_reg, 0, 0, SHIFT_IMM_LSL(0));
tcg_out_dat_reg(s, cond, ARITH_MOV, div_reg, 0, 8, SHIFT_IMM_LSL(0));
/* ldr r0, [sp], #4 */
if (rem_reg != 0 && div_reg != 0)
tcg_out32(s, (cond << 28) | 0x04bd0004);
/* ldr r1, [sp], #4 */
if (rem_reg != 1 && div_reg != 1)
tcg_out32(s, (cond << 28) | 0x04bd1004);
/* ldr r2, [sp], #4 */
if (rem_reg != 2 && div_reg != 2)
tcg_out32(s, (cond << 28) | 0x04bd2004);
/* ldr r3, [sp], #4 */
if (rem_reg != 3 && div_reg != 3)
tcg_out32(s, (cond << 28) | 0x04bd3004);
/* ldr ip, [sp], #4 */
if (rem_reg != 12 && div_reg != 12)
tcg_out32(s, (cond << 28) | 0x04bdc004);
/* ldr lr, [sp], #4 */
if (rem_reg != 14 && div_reg != 14)
tcg_out32(s, (cond << 28) | 0x04bde004);
}
#ifdef CONFIG_SOFTMMU
#include "../../softmmu_defs.h"
static void *qemu_ld_helpers[4] = {
__ldb_mmu,
__ldw_mmu,
__ldl_mmu,
__ldq_mmu,
};
static void *qemu_st_helpers[4] = {
__stb_mmu,
__stw_mmu,
__stl_mmu,
__stq_mmu,
};
#endif
#define TLB_SHIFT (CPU_TLB_ENTRY_BITS + CPU_TLB_BITS)
static inline void tcg_out_qemu_ld(TCGContext *s, int cond,
const TCGArg *args, int opc)
{
int addr_reg, data_reg, data_reg2;
#ifdef CONFIG_SOFTMMU
int mem_index, s_bits;
# if TARGET_LONG_BITS == 64
int addr_reg2;
# endif
uint32_t *label_ptr;
#endif
data_reg = *args++;
if (opc == 3)
data_reg2 = *args++;
else
data_reg2 = 0; /* surpress warning */
addr_reg = *args++;
#ifdef CONFIG_SOFTMMU
# if TARGET_LONG_BITS == 64
addr_reg2 = *args++;
# endif
mem_index = *args;
s_bits = opc & 3;
/* Should generate something like the following:
* shr r8, addr_reg, #TARGET_PAGE_BITS
* and r0, r8, #(CPU_TLB_SIZE - 1) @ Assumption: CPU_TLB_BITS <= 8
* add r0, env, r0 lsl #CPU_TLB_ENTRY_BITS
*/
# if CPU_TLB_BITS > 8
# error
# endif
tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
8, 0, addr_reg, SHIFT_IMM_LSR(TARGET_PAGE_BITS));
tcg_out_dat_imm(s, COND_AL, ARITH_AND,
0, 8, CPU_TLB_SIZE - 1);
tcg_out_dat_reg(s, COND_AL, ARITH_ADD,
0, TCG_AREG0, 0, SHIFT_IMM_LSL(CPU_TLB_ENTRY_BITS));
/* In the
* ldr r1 [r0, #(offsetof(CPUState, tlb_table[mem_index][0].addr_read))]
* below, the offset is likely to exceed 12 bits if mem_index != 0 and
* not exceed otherwise, so use an
* add r0, r0, #(mem_index * sizeof *CPUState.tlb_table)
* before.
*/
if (mem_index)
tcg_out_dat_imm(s, COND_AL, ARITH_ADD, 0, 0,
(mem_index << (TLB_SHIFT & 1)) |
((16 - (TLB_SHIFT >> 1)) << 8));
tcg_out_ld32_12(s, COND_AL, 1, 0,
offsetof(CPUState, tlb_table[0][0].addr_read));
tcg_out_dat_reg(s, COND_AL, ARITH_CMP,
0, 1, 8, SHIFT_IMM_LSL(TARGET_PAGE_BITS));
/* Check alignment. */
if (s_bits)
tcg_out_dat_imm(s, COND_EQ, ARITH_TST,
0, addr_reg, (1 << s_bits) - 1);
# if TARGET_LONG_BITS == 64
/* XXX: possibly we could use a block data load or writeback in
* the first access. */
tcg_out_ld32_12(s, COND_EQ, 1, 0,
offsetof(CPUState, tlb_table[0][0].addr_read) + 4);
tcg_out_dat_reg(s, COND_EQ, ARITH_CMP,
0, 1, addr_reg2, SHIFT_IMM_LSL(0));
# endif
tcg_out_ld32_12(s, COND_EQ, 1, 0,
offsetof(CPUState, tlb_table[0][0].addend));
switch (opc) {
case 0:
tcg_out_ld8_r(s, COND_EQ, data_reg, addr_reg, 1);
break;
case 0 | 4:
tcg_out_ld8s_r(s, COND_EQ, data_reg, addr_reg, 1);
break;
case 1:
tcg_out_ld16u_r(s, COND_EQ, data_reg, addr_reg, 1);
break;
case 1 | 4:
tcg_out_ld16s_r(s, COND_EQ, data_reg, addr_reg, 1);
break;
case 2:
default:
tcg_out_ld32_r(s, COND_EQ, data_reg, addr_reg, 1);
break;
case 3:
tcg_out_ld32_rwb(s, COND_EQ, data_reg, 1, addr_reg);
tcg_out_ld32_12(s, COND_EQ, data_reg2, 1, 4);
break;
}
label_ptr = (void *) s->code_ptr;
tcg_out_b(s, COND_EQ, 8);
# ifdef SAVE_LR
tcg_out_dat_reg(s, cond, ARITH_MOV, 8, 0, 14, SHIFT_IMM_LSL(0));
# endif
/* TODO: move this code to where the constants pool will be */
if (addr_reg)
tcg_out_dat_reg(s, cond, ARITH_MOV,
0, 0, addr_reg, SHIFT_IMM_LSL(0));
# if TARGET_LONG_BITS == 32
tcg_out_dat_imm(s, cond, ARITH_MOV, 1, 0, mem_index);
# else
if (addr_reg2 != 1)
tcg_out_dat_reg(s, cond, ARITH_MOV,
1, 0, addr_reg2, SHIFT_IMM_LSL(0));
tcg_out_dat_imm(s, cond, ARITH_MOV, 2, 0, mem_index);
# endif
tcg_out_bl(s, cond, (tcg_target_long) qemu_ld_helpers[s_bits] -
(tcg_target_long) s->code_ptr);
switch (opc) {
case 0 | 4:
tcg_out_dat_reg(s, cond, ARITH_MOV,
0, 0, 0, SHIFT_IMM_LSL(24));
tcg_out_dat_reg(s, cond, ARITH_MOV,
data_reg, 0, 0, SHIFT_IMM_ASR(24));
break;
case 1 | 4:
tcg_out_dat_reg(s, cond, ARITH_MOV,
0, 0, 0, SHIFT_IMM_LSL(16));
tcg_out_dat_reg(s, cond, ARITH_MOV,
data_reg, 0, 0, SHIFT_IMM_ASR(16));
break;
case 0:
case 1:
case 2:
default:
if (data_reg)
tcg_out_dat_reg(s, cond, ARITH_MOV,
data_reg, 0, 0, SHIFT_IMM_LSL(0));
break;
case 3:
if (data_reg != 0)
tcg_out_dat_reg(s, cond, ARITH_MOV,
data_reg, 0, 0, SHIFT_IMM_LSL(0));
if (data_reg2 != 1)
tcg_out_dat_reg(s, cond, ARITH_MOV,
data_reg2, 0, 1, SHIFT_IMM_LSL(0));
break;
}
# ifdef SAVE_LR
tcg_out_dat_reg(s, cond, ARITH_MOV, 14, 0, 8, SHIFT_IMM_LSL(0));
# endif
*label_ptr += ((void *) s->code_ptr - (void *) label_ptr - 8) >> 2;
#else
switch (opc) {
case 0:
tcg_out_ld8_12(s, COND_AL, data_reg, addr_reg, 0);
break;
case 0 | 4:
tcg_out_ld8s_8(s, COND_AL, data_reg, addr_reg, 0);
break;
case 1:
tcg_out_ld16u_8(s, COND_AL, data_reg, addr_reg, 0);
break;
case 1 | 4:
tcg_out_ld16s_8(s, COND_AL, data_reg, addr_reg, 0);
break;
case 2:
default:
tcg_out_ld32_12(s, COND_AL, data_reg, addr_reg, 0);
break;
case 3:
/* TODO: use block load -
* check that data_reg2 > data_reg or the other way */
tcg_out_ld32_12(s, COND_AL, data_reg, addr_reg, 0);
tcg_out_ld32_12(s, COND_AL, data_reg2, addr_reg, 4);
break;
}
#endif
}
static inline void tcg_out_qemu_st(TCGContext *s, int cond,
const TCGArg *args, int opc)
{
int addr_reg, data_reg, data_reg2;
#ifdef CONFIG_SOFTMMU
int mem_index, s_bits;
# if TARGET_LONG_BITS == 64
int addr_reg2;
# endif
uint32_t *label_ptr;
#endif
data_reg = *args++;
if (opc == 3)
data_reg2 = *args++;
else
data_reg2 = 0; /* surpress warning */
addr_reg = *args++;
#ifdef CONFIG_SOFTMMU
# if TARGET_LONG_BITS == 64
addr_reg2 = *args++;
# endif
mem_index = *args;
s_bits = opc & 3;
/* Should generate something like the following:
* shr r8, addr_reg, #TARGET_PAGE_BITS
* and r0, r8, #(CPU_TLB_SIZE - 1) @ Assumption: CPU_TLB_BITS <= 8
* add r0, env, r0 lsl #CPU_TLB_ENTRY_BITS
*/
tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
8, 0, addr_reg, SHIFT_IMM_LSR(TARGET_PAGE_BITS));
tcg_out_dat_imm(s, COND_AL, ARITH_AND,
0, 8, CPU_TLB_SIZE - 1);
tcg_out_dat_reg(s, COND_AL, ARITH_ADD,
0, TCG_AREG0, 0, SHIFT_IMM_LSL(CPU_TLB_ENTRY_BITS));
/* In the
* ldr r1 [r0, #(offsetof(CPUState, tlb_table[mem_index][0].addr_write))]
* below, the offset is likely to exceed 12 bits if mem_index != 0 and
* not exceed otherwise, so use an
* add r0, r0, #(mem_index * sizeof *CPUState.tlb_table)
* before.
*/
if (mem_index)
tcg_out_dat_imm(s, COND_AL, ARITH_ADD, 0, 0,
(mem_index << (TLB_SHIFT & 1)) |
((16 - (TLB_SHIFT >> 1)) << 8));
tcg_out_ld32_12(s, COND_AL, 1, 0,
offsetof(CPUState, tlb_table[0][0].addr_write));
tcg_out_dat_reg(s, COND_AL, ARITH_CMP,
0, 1, 8, SHIFT_IMM_LSL(TARGET_PAGE_BITS));
/* Check alignment. */
if (s_bits)
tcg_out_dat_imm(s, COND_EQ, ARITH_TST,
0, addr_reg, (1 << s_bits) - 1);
# if TARGET_LONG_BITS == 64
/* XXX: possibly we could use a block data load or writeback in
* the first access. */
tcg_out_ld32_12(s, COND_EQ, 1, 0,
offsetof(CPUState, tlb_table[0][0].addr_write)
+ 4);
tcg_out_dat_reg(s, COND_EQ, ARITH_CMP,
0, 1, addr_reg2, SHIFT_IMM_LSL(0));
# endif
tcg_out_ld32_12(s, COND_EQ, 1, 0,
offsetof(CPUState, tlb_table[0][0].addend));
switch (opc) {
case 0:
tcg_out_st8_r(s, COND_EQ, data_reg, addr_reg, 1);
break;
case 0 | 4:
tcg_out_st8s_r(s, COND_EQ, data_reg, addr_reg, 1);
break;
case 1:
tcg_out_st16u_r(s, COND_EQ, data_reg, addr_reg, 1);
break;
case 1 | 4:
tcg_out_st16s_r(s, COND_EQ, data_reg, addr_reg, 1);
break;
case 2:
default:
tcg_out_st32_r(s, COND_EQ, data_reg, addr_reg, 1);
break;
case 3:
tcg_out_st32_rwb(s, COND_EQ, data_reg, 1, addr_reg);
tcg_out_st32_12(s, COND_EQ, data_reg2, 1, 4);
break;
}
label_ptr = (void *) s->code_ptr;
tcg_out_b(s, COND_EQ, 8);
/* TODO: move this code to where the constants pool will be */
if (addr_reg)
tcg_out_dat_reg(s, cond, ARITH_MOV,
0, 0, addr_reg, SHIFT_IMM_LSL(0));
# if TARGET_LONG_BITS == 32
switch (opc) {
case 0:
tcg_out_dat_imm(s, cond, ARITH_AND, 1, data_reg, 0xff);
tcg_out_dat_imm(s, cond, ARITH_MOV, 2, 0, mem_index);
break;
case 1:
tcg_out_dat_reg(s, cond, ARITH_MOV,
1, 0, data_reg, SHIFT_IMM_LSL(16));
tcg_out_dat_reg(s, cond, ARITH_MOV,
1, 0, 1, SHIFT_IMM_LSR(16));
tcg_out_dat_imm(s, cond, ARITH_MOV, 2, 0, mem_index);
break;
case 2:
if (data_reg != 1)
tcg_out_dat_reg(s, cond, ARITH_MOV,
1, 0, data_reg, SHIFT_IMM_LSL(0));
tcg_out_dat_imm(s, cond, ARITH_MOV, 2, 0, mem_index);
break;
case 3:
if (data_reg != 1)
tcg_out_dat_reg(s, cond, ARITH_MOV,
1, 0, data_reg, SHIFT_IMM_LSL(0));
if (data_reg2 != 2)
tcg_out_dat_reg(s, cond, ARITH_MOV,
2, 0, data_reg2, SHIFT_IMM_LSL(0));
tcg_out_dat_imm(s, cond, ARITH_MOV, 3, 0, mem_index);
break;
}
# else
if (addr_reg2 != 1)
tcg_out_dat_reg(s, cond, ARITH_MOV,
1, 0, addr_reg2, SHIFT_IMM_LSL(0));
switch (opc) {
case 0:
tcg_out_dat_imm(s, cond, ARITH_AND, 2, data_reg, 0xff);
tcg_out_dat_imm(s, cond, ARITH_MOV, 3, 0, mem_index);
break;
case 1:
tcg_out_dat_reg(s, cond, ARITH_MOV,
2, 0, data_reg, SHIFT_IMM_LSL(16));
tcg_out_dat_reg(s, cond, ARITH_MOV,
2, 0, 2, SHIFT_IMM_LSR(16));
tcg_out_dat_imm(s, cond, ARITH_MOV, 3, 0, mem_index);
break;
case 2:
if (data_reg != 2)
tcg_out_dat_reg(s, cond, ARITH_MOV,
2, 0, data_reg, SHIFT_IMM_LSL(0));
tcg_out_dat_imm(s, cond, ARITH_MOV, 3, 0, mem_index);
break;
case 3:
tcg_out_dat_imm(s, cond, ARITH_MOV, 8, 0, mem_index);
tcg_out32(s, (cond << 28) | 0x052d8010); /* str r8, [sp, #-0x10]! */
if (data_reg != 2)
tcg_out_dat_reg(s, cond, ARITH_MOV,
2, 0, data_reg, SHIFT_IMM_LSL(0));
if (data_reg2 != 3)
tcg_out_dat_reg(s, cond, ARITH_MOV,
3, 0, data_reg2, SHIFT_IMM_LSL(0));
break;
}
# endif
# ifdef SAVE_LR
tcg_out_dat_reg(s, cond, ARITH_MOV, 8, 0, 14, SHIFT_IMM_LSL(0));
# endif
tcg_out_bl(s, cond, (tcg_target_long) qemu_st_helpers[s_bits] -
(tcg_target_long) s->code_ptr);
# if TARGET_LONG_BITS == 64
if (opc == 3)
tcg_out_dat_imm(s, cond, ARITH_ADD, 13, 13, 0x10);
# endif
# ifdef SAVE_LR
tcg_out_dat_reg(s, cond, ARITH_MOV, 14, 0, 8, SHIFT_IMM_LSL(0));
# endif
*label_ptr += ((void *) s->code_ptr - (void *) label_ptr - 8) >> 2;
#else
switch (opc) {
case 0:
tcg_out_st8_12(s, COND_AL, data_reg, addr_reg, 0);
break;
case 0 | 4:
tcg_out_st8s_8(s, COND_AL, data_reg, addr_reg, 0);
break;
case 1:
tcg_out_st16u_8(s, COND_AL, data_reg, addr_reg, 0);
break;
case 1 | 4:
tcg_out_st16s_8(s, COND_AL, data_reg, addr_reg, 0);
break;
case 2:
default:
tcg_out_st32_12(s, COND_AL, data_reg, addr_reg, 0);
break;
case 3:
/* TODO: use block store -
* check that data_reg2 > data_reg or the other way */
tcg_out_st32_12(s, COND_AL, data_reg, addr_reg, 0);
tcg_out_st32_12(s, COND_AL, data_reg2, addr_reg, 4);
break;
}
#endif
}
static uint8_t *tb_ret_addr;
static inline void tcg_out_op(TCGContext *s, int opc,
const TCGArg *args, const int *const_args)
{
int c;
switch (opc) {
case INDEX_op_exit_tb:
#ifdef SAVE_LR
if (args[0] >> 8)
tcg_out_ld32_12(s, COND_AL, TCG_REG_R0, 15, 0);
else
tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R0, 0, args[0]);
tcg_out_dat_reg(s, COND_AL, ARITH_MOV, 15, 0, 14, SHIFT_IMM_LSL(0));
if (args[0] >> 8)
tcg_out32(s, args[0]);
#else
{
uint8_t *ld_ptr = s->code_ptr;
if (args[0] >> 8)
tcg_out_ld32_12(s, COND_AL, 0, 15, 0);
else
tcg_out_dat_imm(s, COND_AL, ARITH_MOV, 0, 0, args[0]);
tcg_out_goto(s, COND_AL, (tcg_target_ulong) tb_ret_addr);
if (args[0] >> 8) {
*ld_ptr = (uint8_t) (s->code_ptr - ld_ptr) - 8;
tcg_out32(s, args[0]);
}
}
#endif
break;
case INDEX_op_goto_tb:
if (s->tb_jmp_offset) {
/* Direct jump method */
#if defined(USE_DIRECT_JUMP)
s->tb_jmp_offset[args[0]] = s->code_ptr - s->code_buf;
tcg_out_b(s, COND_AL, 8);
#else
tcg_out_ld32_12(s, COND_AL, 15, 15, -4);
s->tb_jmp_offset[args[0]] = s->code_ptr - s->code_buf;
tcg_out32(s, 0);
#endif
} else {
/* Indirect jump method */
#if 1
c = (int) (s->tb_next + args[0]) - ((int) s->code_ptr + 8);
if (c > 0xfff || c < -0xfff) {
tcg_out_movi32(s, COND_AL, TCG_REG_R0,
(tcg_target_long) (s->tb_next + args[0]));
tcg_out_ld32_12(s, COND_AL, 15, TCG_REG_R0, 0);
} else
tcg_out_ld32_12(s, COND_AL, 15, 15, c);
#else
tcg_out_ld32_12(s, COND_AL, TCG_REG_R0, 15, 0);
tcg_out_ld32_12(s, COND_AL, 15, TCG_REG_R0, 0);
tcg_out32(s, (tcg_target_long) (s->tb_next + args[0]));
#endif
}
s->tb_next_offset[args[0]] = s->code_ptr - s->code_buf;
break;
case INDEX_op_call:
if (const_args[0])
tcg_out_call(s, COND_AL, args[0]);
else
tcg_out_callr(s, COND_AL, args[0]);
break;
case INDEX_op_jmp:
if (const_args[0])
tcg_out_goto(s, COND_AL, args[0]);
else
tcg_out_bx(s, COND_AL, args[0]);
break;
case INDEX_op_br:
tcg_out_goto_label(s, COND_AL, args[0]);
break;
case INDEX_op_ld8u_i32:
tcg_out_ld8u(s, COND_AL, args[0], args[1], args[2]);
break;
case INDEX_op_ld8s_i32:
tcg_out_ld8s(s, COND_AL, args[0], args[1], args[2]);
break;
case INDEX_op_ld16u_i32:
tcg_out_ld16u(s, COND_AL, args[0], args[1], args[2]);
break;
case INDEX_op_ld16s_i32:
tcg_out_ld16s(s, COND_AL, args[0], args[1], args[2]);
break;
case INDEX_op_ld_i32:
tcg_out_ld32u(s, COND_AL, args[0], args[1], args[2]);
break;
case INDEX_op_st8_i32:
tcg_out_st8u(s, COND_AL, args[0], args[1], args[2]);
break;
case INDEX_op_st16_i32:
tcg_out_st16u(s, COND_AL, args[0], args[1], args[2]);
break;
case INDEX_op_st_i32:
tcg_out_st32(s, COND_AL, args[0], args[1], args[2]);
break;
case INDEX_op_mov_i32:
tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
args[0], 0, args[1], SHIFT_IMM_LSL(0));
break;
case INDEX_op_movi_i32:
tcg_out_movi32(s, COND_AL, args[0], args[1]);
break;
case INDEX_op_add_i32:
c = ARITH_ADD;
goto gen_arith;
case INDEX_op_sub_i32:
c = ARITH_SUB;
goto gen_arith;
case INDEX_op_and_i32:
c = ARITH_AND;
goto gen_arith;
case INDEX_op_or_i32:
c = ARITH_ORR;
goto gen_arith;
case INDEX_op_xor_i32:
c = ARITH_EOR;
/* Fall through. */
gen_arith:
tcg_out_dat_reg(s, COND_AL, c,
args[0], args[1], args[2], SHIFT_IMM_LSL(0));
break;
case INDEX_op_add2_i32:
tcg_out_dat_reg2(s, COND_AL, ARITH_ADD, ARITH_ADC,
args[0], args[1], args[2], args[3],
args[4], args[5], SHIFT_IMM_LSL(0));
break;
case INDEX_op_sub2_i32:
tcg_out_dat_reg2(s, COND_AL, ARITH_SUB, ARITH_SBC,
args[0], args[1], args[2], args[3],
args[4], args[5], SHIFT_IMM_LSL(0));
break;
case INDEX_op_neg_i32:
tcg_out_dat_imm(s, COND_AL, ARITH_RSB, args[0], args[1], 0);
break;
case INDEX_op_mul_i32:
tcg_out_mul32(s, COND_AL, args[0], args[1], args[2]);
break;
case INDEX_op_mulu2_i32:
tcg_out_umull32(s, COND_AL, args[0], args[1], args[2], args[3]);
break;
case INDEX_op_div2_i32:
tcg_out_div_helper(s, COND_AL, args,
tcg_helper_div_i64, tcg_helper_rem_i64,
SHIFT_IMM_ASR(31));
break;
case INDEX_op_divu2_i32:
tcg_out_div_helper(s, COND_AL, args,
tcg_helper_divu_i64, tcg_helper_remu_i64,
SHIFT_IMM_LSR(31));
break;
/* XXX: Perhaps args[2] & 0x1f is wrong */
case INDEX_op_shl_i32:
c = const_args[2] ?
SHIFT_IMM_LSL(args[2] & 0x1f) : SHIFT_REG_LSL(args[2]);
goto gen_shift32;
case INDEX_op_shr_i32:
c = const_args[2] ? (args[2] & 0x1f) ? SHIFT_IMM_LSR(args[2] & 0x1f) :
SHIFT_IMM_LSL(0) : SHIFT_REG_LSR(args[2]);
goto gen_shift32;
case INDEX_op_sar_i32:
c = const_args[2] ? (args[2] & 0x1f) ? SHIFT_IMM_ASR(args[2] & 0x1f) :
SHIFT_IMM_LSL(0) : SHIFT_REG_ASR(args[2]);
/* Fall through. */
gen_shift32:
tcg_out_dat_reg(s, COND_AL, ARITH_MOV, args[0], 0, args[1], c);
break;
case INDEX_op_brcond_i32:
tcg_out_dat_reg(s, COND_AL, ARITH_CMP, 0,
args[0], args[1], SHIFT_IMM_LSL(0));
tcg_out_goto_label(s, tcg_cond_to_arm_cond[args[2]], args[3]);
break;
case INDEX_op_brcond2_i32:
/* The resulting conditions are:
* TCG_COND_EQ --> a0 == a2 && a1 == a3,
* TCG_COND_NE --> (a0 != a2 && a1 == a3) || a1 != a3,
* TCG_COND_LT(U) --> (a0 < a2 && a1 == a3) || a1 < a3,
* TCG_COND_GE(U) --> (a0 >= a2 && a1 == a3) || (a1 >= a3 && a1 != a3),
* TCG_COND_LE(U) --> (a0 <= a2 && a1 == a3) || (a1 <= a3 && a1 != a3),
* TCG_COND_GT(U) --> (a0 > a2 && a1 == a3) || a1 > a3,
*/
tcg_out_dat_reg(s, COND_AL, ARITH_CMP, 0,
args[1], args[3], SHIFT_IMM_LSL(0));
tcg_out_dat_reg(s, COND_EQ, ARITH_CMP, 0,
args[0], args[2], SHIFT_IMM_LSL(0));
tcg_out_goto_label(s, tcg_cond_to_arm_cond[args[4]], args[5]);
break;
case INDEX_op_qemu_ld8u:
tcg_out_qemu_ld(s, COND_AL, args, 0);
break;
case INDEX_op_qemu_ld8s:
tcg_out_qemu_ld(s, COND_AL, args, 0 | 4);
break;
case INDEX_op_qemu_ld16u:
tcg_out_qemu_ld(s, COND_AL, args, 1);
break;
case INDEX_op_qemu_ld16s:
tcg_out_qemu_ld(s, COND_AL, args, 1 | 4);
break;
case INDEX_op_qemu_ld32u:
tcg_out_qemu_ld(s, COND_AL, args, 2);
break;
case INDEX_op_qemu_ld64:
tcg_out_qemu_ld(s, COND_AL, args, 3);
break;
case INDEX_op_qemu_st8:
tcg_out_qemu_st(s, COND_AL, args, 0);
break;
case INDEX_op_qemu_st16:
tcg_out_qemu_st(s, COND_AL, args, 1);
break;
case INDEX_op_qemu_st32:
tcg_out_qemu_st(s, COND_AL, args, 2);
break;
case INDEX_op_qemu_st64:
tcg_out_qemu_st(s, COND_AL, args, 3);
break;
case INDEX_op_ext8s_i32:
tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
args[0], 0, args[1], SHIFT_IMM_LSL(24));
tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
args[0], 0, args[0], SHIFT_IMM_ASR(24));
break;
case INDEX_op_ext16s_i32:
tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
args[0], 0, args[1], SHIFT_IMM_LSL(16));
tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
args[0], 0, args[0], SHIFT_IMM_ASR(16));
break;
default:
tcg_abort();
}
}
static const TCGTargetOpDef arm_op_defs[] = {
{ INDEX_op_exit_tb, { } },
{ INDEX_op_goto_tb, { } },
{ INDEX_op_call, { "ri" } },
{ INDEX_op_jmp, { "ri" } },
{ INDEX_op_br, { } },
{ INDEX_op_mov_i32, { "r", "r" } },
{ INDEX_op_movi_i32, { "r" } },
{ INDEX_op_ld8u_i32, { "r", "r" } },
{ INDEX_op_ld8s_i32, { "r", "r" } },
{ INDEX_op_ld16u_i32, { "r", "r" } },
{ INDEX_op_ld16s_i32, { "r", "r" } },
{ INDEX_op_ld_i32, { "r", "r" } },
{ INDEX_op_st8_i32, { "r", "r" } },
{ INDEX_op_st16_i32, { "r", "r" } },
{ INDEX_op_st_i32, { "r", "r" } },
/* TODO: "r", "r", "ri" */
{ INDEX_op_add_i32, { "r", "r", "r" } },
{ INDEX_op_sub_i32, { "r", "r", "r" } },
{ INDEX_op_mul_i32, { "r", "r", "r" } },
{ INDEX_op_mulu2_i32, { "r", "r", "r", "r" } },
{ INDEX_op_div2_i32, { "r", "r", "r", "1", "2" } },
{ INDEX_op_divu2_i32, { "r", "r", "r", "1", "2" } },
{ INDEX_op_and_i32, { "r", "r", "r" } },
{ INDEX_op_or_i32, { "r", "r", "r" } },
{ INDEX_op_xor_i32, { "r", "r", "r" } },
{ INDEX_op_neg_i32, { "r", "r" } },
{ INDEX_op_shl_i32, { "r", "r", "ri" } },
{ INDEX_op_shr_i32, { "r", "r", "ri" } },
{ INDEX_op_sar_i32, { "r", "r", "ri" } },
{ INDEX_op_brcond_i32, { "r", "r" } },
/* TODO: "r", "r", "r", "r", "ri", "ri" */
{ INDEX_op_add2_i32, { "r", "r", "r", "r", "r", "r" } },
{ INDEX_op_sub2_i32, { "r", "r", "r", "r", "r", "r" } },
{ INDEX_op_brcond2_i32, { "r", "r", "r", "r" } },
{ INDEX_op_qemu_ld8u, { "r", "x", "X" } },
{ INDEX_op_qemu_ld8s, { "r", "x", "X" } },
{ INDEX_op_qemu_ld16u, { "r", "x", "X" } },
{ INDEX_op_qemu_ld16s, { "r", "x", "X" } },
{ INDEX_op_qemu_ld32u, { "r", "x", "X" } },
{ INDEX_op_qemu_ld64, { "d", "r", "x", "X" } },
{ INDEX_op_qemu_st8, { "x", "x", "X" } },
{ INDEX_op_qemu_st16, { "x", "x", "X" } },
{ INDEX_op_qemu_st32, { "x", "x", "X" } },
{ INDEX_op_qemu_st64, { "x", "D", "x", "X" } },
{ INDEX_op_ext8s_i32, { "r", "r" } },
{ INDEX_op_ext16s_i32, { "r", "r" } },
{ -1 },
};
void tcg_target_init(TCGContext *s)
{
/* fail safe */
if ((1 << CPU_TLB_ENTRY_BITS) != sizeof(CPUTLBEntry))
tcg_abort();
tcg_regset_set32(tcg_target_available_regs[TCG_TYPE_I32], 0,
((2 << TCG_REG_R14) - 1) & ~(1 << TCG_REG_R8));
tcg_regset_set32(tcg_target_call_clobber_regs, 0,
((2 << TCG_REG_R3) - 1) |
(1 << TCG_REG_R12) | (1 << TCG_REG_R14));
tcg_regset_clear(s->reserved_regs);
#ifdef SAVE_LR
tcg_regset_set_reg(s->reserved_regs, TCG_REG_R14);
#endif
tcg_regset_set_reg(s->reserved_regs, TCG_REG_CALL_STACK);
tcg_regset_set_reg(s->reserved_regs, TCG_REG_R8);
tcg_add_target_add_op_defs(arm_op_defs);
}
static inline void tcg_out_ld(TCGContext *s, TCGType type, int arg,
int arg1, tcg_target_long arg2)
{
tcg_out_ld32u(s, COND_AL, arg, arg1, arg2);
}
static inline void tcg_out_st(TCGContext *s, TCGType type, int arg,
int arg1, tcg_target_long arg2)
{
tcg_out_st32(s, COND_AL, arg, arg1, arg2);
}
void tcg_out_addi(TCGContext *s, int reg, tcg_target_long val)
{
if (val > 0)
if (val < 0x100)
tcg_out_dat_imm(s, COND_AL, ARITH_ADD, reg, reg, val);
else
tcg_abort();
else if (val < 0) {
if (val > -0x100)
tcg_out_dat_imm(s, COND_AL, ARITH_SUB, reg, reg, -val);
else
tcg_abort();
}
}
static inline void tcg_out_mov(TCGContext *s, int ret, int arg)
{
tcg_out_dat_reg(s, COND_AL, ARITH_MOV, ret, 0, arg, SHIFT_IMM_LSL(0));
}
static inline void tcg_out_movi(TCGContext *s, TCGType type,
int ret, tcg_target_long arg)
{
tcg_out_movi32(s, COND_AL, ret, arg);
}
void tcg_target_qemu_prologue(TCGContext *s)
{
/* stmdb sp!, { r9 - r11, lr } */
tcg_out32(s, (COND_AL << 28) | 0x092d4e00);
tcg_out_bx(s, COND_AL, TCG_REG_R0);
tb_ret_addr = s->code_ptr;
/* ldmia sp!, { r9 - r11, pc } */
tcg_out32(s, (COND_AL << 28) | 0x08bd8e00);
}
| 32.234707 | 80 | 0.544345 |
fc61dca34a834f0927e8a55084a75dd0125ee06f | 2,553 | h | C | ITS/ITSrec/AliITSBadChannelsSPD.h | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | ITS/ITSrec/AliITSBadChannelsSPD.h | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | ITS/ITSrec/AliITSBadChannelsSPD.h | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | #ifndef ALIITSBADCHANNELSSPD_H
#define ALIITSBADCHANNELSSPD_H
/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
/* $Id$ */
///////////////////////////////////////////////////////////////////////////
// AliITSBadChannelsSPD declaration by P. Nilsson 2005
// AUTHOR/CONTACT: Paul.Nilsson@cern.ch
//
// The class is used by the AliITSPreprocessorSPD class to store the
// final noisy and dead channel objects in the calibration database for
// the SPD.
//
// (See the source file for more information)
///////////////////////////////////////////////////////////////////////////
#include "TObjArray.h"
#include "AliITSChannelSPD.h"
class AliITSBadChannelsSPD: public TObject {
public:
AliITSBadChannelsSPD(void); // Default constructor
AliITSBadChannelsSPD(const AliITSBadChannelsSPD &bc); // Default copy constructor
virtual ~AliITSBadChannelsSPD(void); // Default destructor
AliITSBadChannelsSPD& operator=(const AliITSBadChannelsSPD& bc); // Assignment operator
void Put(Int_t* &array, const Int_t &arraySize, // Add new arrays to the collection
Int_t* &index, const Int_t &indexSize);
Bool_t Get(Int_t* &array, Int_t* &index) const; // Retrieve the stored arrays (true if non empty arrays)
Int_t GetIndexArraySize(void) const // Return the size of the index array
{ return fIndexArraySize; };
Int_t GetBadChannelsArraySize(void) const // Return the size of the bad channels array
{ return fBadChannelsArraySize; };
Int_t* CreateModuleArray(Int_t module) const; // Create an array with sequential data for a given module
Int_t GetModuleArraySize(Int_t module) const // Return array size for a given module
{ return (2*fBadChannelsArray[fIndexArray[module]] + 1); };
TObjArray* CreateModuleObjArray(Int_t module) const; // Create a TObjArray with data for a given module
Int_t GetModuleObjArraySize(Int_t module) const // Return TObjArray size for a given module
{ return (fBadChannelsArray[fIndexArray[module]]); };
protected:
Int_t fIndexArraySize; // Size of the index array
Int_t fBadChannelsArraySize; // Size of the bad channels array
Int_t *fIndexArray; //[fIndexArraySize]
Int_t *fBadChannelsArray; //[fBadChannelsArraySize]
ClassDef(AliITSBadChannelsSPD,1)
};
#endif
| 41.852459 | 112 | 0.643165 |
1184c9922e04f97036ba9298a2fbb772ad4e4ea4 | 7,660 | h | C | brlycmbd/CrdBrlyFlt/CrdBrlyFlt.h | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | brlycmbd/CrdBrlyFlt/CrdBrlyFlt.h | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | brlycmbd/CrdBrlyFlt/CrdBrlyFlt.h | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | /**
* \file CrdBrlyFlt.h
* job handler for job CrdBrlyFlt (declarations)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 11 Jan 2021
*/
// IP header --- ABOVE
#ifndef CRDBRLYFLT_H
#define CRDBRLYFLT_H
// IP include.spec --- INSERT
// IP include.cust --- INSERT
#include "PnlBrlyFltList.h"
#include "PnlBrlyFltHeadbar.h"
#include "PnlBrlyFltRec.h"
#define VecVBrlyFltDo CrdBrlyFlt::VecVDo
#define VecVBrlyFltSge CrdBrlyFlt::VecVSge
#define ContInfBrlyFlt CrdBrlyFlt::ContInf
#define StatAppBrlyFlt CrdBrlyFlt::StatApp
#define StatShrBrlyFlt CrdBrlyFlt::StatShr
#define TagBrlyFlt CrdBrlyFlt::Tag
#define DpchAppBrlyFltDo CrdBrlyFlt::DpchAppDo
#define DpchEngBrlyFltData CrdBrlyFlt::DpchEngData
/**
* CrdBrlyFlt
*/
class CrdBrlyFlt : public JobBrly {
public:
/**
* VecVDo (full: VecVBrlyFltDo)
*/
class VecVDo {
public:
static const Sbecore::uint CLOSE = 1;
static const Sbecore::uint MITAPPABTCLICK = 2;
static Sbecore::uint getIx(const std::string& sref);
static std::string getSref(const Sbecore::uint ix);
};
/**
* VecVSge (full: VecVBrlyFltSge)
*/
class VecVSge {
public:
static const Sbecore::uint IDLE = 1;
static const Sbecore::uint ALRBRLYABT = 2;
static const Sbecore::uint COLLECT = 3;
static const Sbecore::uint COLDONE = 4;
static const Sbecore::uint PLOT = 5;
static const Sbecore::uint PLTDONE = 6;
static Sbecore::uint getIx(const std::string& sref);
static std::string getSref(const Sbecore::uint ix);
static void fillFeed(Sbecore::Xmlio::Feed& feed);
};
/**
* ContInf (full: ContInfBrlyFlt)
*/
class ContInf : public Sbecore::Xmlio::Block {
public:
static const Sbecore::uint NUMFSGE = 1;
static const Sbecore::uint MRLAPPHLP = 2;
static const Sbecore::uint MTXCRDFLT = 3;
public:
ContInf(const Sbecore::uint numFSge = 1, const std::string& MrlAppHlp = "", const std::string& MtxCrdFlt = "");
public:
Sbecore::uint numFSge;
std::string MrlAppHlp;
std::string MtxCrdFlt;
public:
void writeXML(xmlTextWriter* wr, std::string difftag = "", bool shorttags = true);
std::set<Sbecore::uint> comm(const ContInf* comp);
std::set<Sbecore::uint> diff(const ContInf* comp);
};
/**
* StatApp (full: StatAppBrlyFlt)
*/
class StatApp {
public:
static void writeXML(xmlTextWriter* wr, std::string difftag = "", bool shorttags = true, const Sbecore::uint ixBrlyVReqitmode = VecBrlyVReqitmode::IDLE, const Sbecore::usmallint latency = 5, const std::string& shortMenu = "", const Sbecore::uint widthMenu = 0, const bool initdoneHeadbar = false, const bool initdoneList = false, const bool initdoneRec = false);
};
/**
* StatShr (full: StatShrBrlyFlt)
*/
class StatShr : public Sbecore::Xmlio::Block {
public:
static const Sbecore::uint JREFHEADBAR = 1;
static const Sbecore::uint JREFLIST = 2;
static const Sbecore::uint JREFREC = 3;
public:
StatShr(const Sbecore::ubigint jrefHeadbar = 0, const Sbecore::ubigint jrefList = 0, const Sbecore::ubigint jrefRec = 0);
public:
Sbecore::ubigint jrefHeadbar;
Sbecore::ubigint jrefList;
Sbecore::ubigint jrefRec;
public:
void writeXML(xmlTextWriter* wr, std::string difftag = "", bool shorttags = true);
std::set<Sbecore::uint> comm(const StatShr* comp);
std::set<Sbecore::uint> diff(const StatShr* comp);
};
/**
* Tag (full: TagBrlyFlt)
*/
class Tag {
public:
static void writeXML(const Sbecore::uint ixBrlyVLocale, xmlTextWriter* wr, std::string difftag = "", bool shorttags = true);
};
/**
* DpchAppDo (full: DpchAppBrlyFltDo)
*/
class DpchAppDo : public DpchAppBrly {
public:
static const Sbecore::uint JREF = 1;
static const Sbecore::uint IXVDO = 2;
public:
DpchAppDo();
public:
Sbecore::uint ixVDo;
public:
std::string getSrefsMask();
void readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false);
};
/**
* DpchEngData (full: DpchEngBrlyFltData)
*/
class DpchEngData : public DpchEngBrly {
public:
static const Sbecore::uint JREF = 1;
static const Sbecore::uint CONTINF = 2;
static const Sbecore::uint FEEDFSGE = 3;
static const Sbecore::uint STATAPP = 4;
static const Sbecore::uint STATSHR = 5;
static const Sbecore::uint TAG = 6;
static const Sbecore::uint ALL = 7;
public:
DpchEngData(const Sbecore::ubigint jref = 0, ContInf* continf = NULL, Sbecore::Xmlio::Feed* feedFSge = NULL, StatShr* statshr = NULL, const std::set<Sbecore::uint>& mask = {NONE});
public:
ContInf continf;
Sbecore::Xmlio::Feed feedFSge;
StatShr statshr;
public:
std::string getSrefsMask();
void merge(DpchEngBrly* dpcheng);
void writeXML(const Sbecore::uint ixBrlyVLocale, xmlTextWriter* wr);
};
public:
CrdBrlyFlt(XchgBrly* xchg, DbsBrly* dbsbrly, const Sbecore::ubigint jrefSup, const Sbecore::uint ixBrlyVLocale, const Sbecore::ubigint ref = 0);
~CrdBrlyFlt();
public:
ContInf continf;
StatShr statshr;
Sbecore::Xmlio::Feed feedFMcbAlert;
Sbecore::Xmlio::Feed feedFSge;
PnlBrlyFltList* pnllist;
PnlBrlyFltHeadbar* pnlheadbar;
PnlBrlyFltRec* pnlrec;
// IP vars.cust --- IBEGIN
bool con;
bool seg;
bool capacity;
bool pReach;
std::string arena;
std::string srefsKEqptype;
Sbecore::uint start;
Sbecore::uint stop;
Sbecore::uint dt;
Sbecore::ubigint refBrlyMFile;
bool vid;
Sbecore::uint tIx;
Sbecore::uint frmrate;
bool fullsize;
bool grayscale;
double altzmax;
// IP vars.cust --- IEND
public:
// IP cust --- INSERT
public:
DpchEngBrly* getNewDpchEng(std::set<Sbecore::uint> items);
void refresh(DbsBrly* dbsbrly, std::set<Sbecore::uint>& moditems, const bool unmute = false);
void changeRef(DbsBrly* dbsbrly, const Sbecore::ubigint jrefTrig, const Sbecore::ubigint ref, const bool notif = false);
void updatePreset(DbsBrly* dbsbrly, const Sbecore::uint ixBrlyVPreset, const Sbecore::ubigint jrefTrig, const bool notif = false);
public:
public:
void handleRequest(DbsBrly* dbsbrly, ReqBrly* req);
private:
bool handleDnscollect(DbsBrly* dbsbrly);
bool handleDnsplot(DbsBrly* dbsbrly);
void handleDpchAppBrlyInit(DbsBrly* dbsbrly, DpchAppBrlyInit* dpchappbrlyinit, DpchEngBrly** dpcheng);
void handleDpchAppDoClose(DbsBrly* dbsbrly, DpchEngBrly** dpcheng);
void handleDpchAppDoMitAppAbtClick(DbsBrly* dbsbrly, DpchEngBrly** dpcheng);
void handleDpchAppBrlyAlert(DbsBrly* dbsbrly, DpchAppBrlyAlert* dpchappbrlyalert, DpchEngBrly** dpcheng);
public:
void handleCall(DbsBrly* dbsbrly, Sbecore::Call* call);
private:
bool handleCallBrlyRefPreSet(DbsBrly* dbsbrly, const Sbecore::ubigint jrefTrig, const Sbecore::uint ixInv, const Sbecore::ubigint refInv);
bool handleCallBrlyStatChg(DbsBrly* dbsbrly, const Sbecore::ubigint jrefTrig);
bool handleCallBrlyDlgClose(DbsBrly* dbsbrly, const Sbecore::ubigint jrefTrig);
private:
void changeStage(DbsBrly* dbsbrly, Sbecore::uint _ixVSge, DpchEngBrly** dpcheng = NULL);
public:
std::string getSquawk(DbsBrly* dbsbrly);
private:
Sbecore::uint enterSgeIdle(DbsBrly* dbsbrly, const bool reenter);
void leaveSgeIdle(DbsBrly* dbsbrly);
Sbecore::uint enterSgeAlrbrlyabt(DbsBrly* dbsbrly, const bool reenter);
void leaveSgeAlrbrlyabt(DbsBrly* dbsbrly);
Sbecore::uint enterSgeCollect(DbsBrly* dbsbrly, const bool reenter);
void leaveSgeCollect(DbsBrly* dbsbrly);
Sbecore::uint enterSgeColdone(DbsBrly* dbsbrly, const bool reenter);
void leaveSgeColdone(DbsBrly* dbsbrly);
Sbecore::uint enterSgePlot(DbsBrly* dbsbrly, const bool reenter);
void leaveSgePlot(DbsBrly* dbsbrly);
Sbecore::uint enterSgePltdone(DbsBrly* dbsbrly, const bool reenter);
void leaveSgePltdone(DbsBrly* dbsbrly);
};
#endif
| 27.753623 | 364 | 0.73329 |
ccebdcb0141f22fffc5d961908c49e3197686f57 | 2,015 | h | C | MathLib/MathLib_PlaneOps.h | bryanlawsmith/Raytracing | 519b3f3867e0c00b92091dd755a4a73121e22064 | [
"MIT"
] | 1 | 2016-02-17T17:03:37.000Z | 2016-02-17T17:03:37.000Z | MathLib/MathLib_PlaneOps.h | bryanlawsmith/Raytracing | 519b3f3867e0c00b92091dd755a4a73121e22064 | [
"MIT"
] | null | null | null | MathLib/MathLib_PlaneOps.h | bryanlawsmith/Raytracing | 519b3f3867e0c00b92091dd755a4a73121e22064 | [
"MIT"
] | null | null | null | #ifndef MATHLIB_PLANEOPS_H_INCLUDED
#define MATHLIB_PLANEOPS_H_INCLUDED
#include "MathLibCommon.h"
#include "MathLib_Ray.h"
#include "MathLib_Plane.h"
namespace MathLib
{
/// <summary>
/// If possible calculates the required t value used in generating the intersection point between the plane and
/// the ray. If possible, true is returned and t holds the required value. If not possible, false is returned and
/// t is undefined.
/// </summary>
MATHLIB_INLINE bool intersectRayWithPlane(const ray& ray, const plane& plane, float* t)
{
float v_dot_n = vector4_dotProduct(ray.getDirection(), plane.getNormal());
// Determine if the plane and ray direction are parallel.
if (0.0f == v_dot_n)
return false;
vector4 p_sub_r; // plane point-on-plane (p) sub ray position (r).
vector4_sub(plane.getPointOnPlane(), ray.getPosition(), p_sub_r);
// Calculate result.
*t = vector4_dotProduct(plane.getNormal(), p_sub_r) / v_dot_n;
return true;
}
MATHLIB_INLINE bool pointOnPositivePlaneSide(const plane& plane, const vector4& point)
{
vector4 planeToPoint;
vector4_sub(point, plane.getPointOnPlane(), planeToPoint);
return (vector4_dotProduct(planeToPoint, plane.getNormal()) >= 0.0f);
}
MATHLIB_INLINE float distanceToPlane(const plane& plane, const vector4& point)
{
vector4 planeToPoint;
vector4_sub(point, plane.getPointOnPlane(), planeToPoint);
return vector4_dotProduct(planeToPoint, plane.getNormal());
}
MATHLIB_INLINE bool sphereInsidePlane(const vector4& spherePosition, float sphereRadius, const plane& plane)
{
return -distanceToPlane(plane, spherePosition) > sphereRadius;
}
MATHLIB_INLINE bool sphereOutsidePlane(const vector4& spherePosition, float sphereRadius, const plane& plane)
{
return distanceToPlane(plane, spherePosition) > sphereRadius;
}
MATHLIB_INLINE bool sphereIntersectsPlane(const vector4& spherePosition, float sphereRadius, const plane& plane)
{
return fabs(distanceToPlane(plane, spherePosition)) <= sphereRadius;
}
}
#endif // MATHLIB_PLANEOPS_H_INCLUDED
| 30.074627 | 113 | 0.778164 |
0a5f97b49c22488eecfed79746054301da3f2e4f | 376 | h | C | src/api/auth.h | christofmuc/ds-client | 033fa1943715c4da935e46eb5bd7465d4694c587 | [
"MIT"
] | null | null | null | src/api/auth.h | christofmuc/ds-client | 033fa1943715c4da935e46eb5bd7465d4694c587 | [
"MIT"
] | null | null | null | src/api/auth.h | christofmuc/ds-client | 033fa1943715c4da935e46eb5bd7465d4694c587 | [
"MIT"
] | null | null | null | #ifndef AUTH_H
#define AUTH_H
#include <stdexcept>
#import <string>
class Auth
{
public:
Auth(const std::string& url);
~Auth();
bool verifyToken(const std::string& token);
std::string signIn(const std::string& email, const std::string& password);
bool signOut(const std::string& token);
protected:
private:
std::string url;
};
#endif // AUTH_H
| 14.461538 | 78 | 0.667553 |
26f284224705b5d67efc5766dff688b31eb5228e | 1,319 | h | C | extensions/browser/api/declarative_net_request/rules_count_pair.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 | extensions/browser/api/declarative_net_request/rules_count_pair.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | extensions/browser/api/declarative_net_request/rules_count_pair.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 2021 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 EXTENSIONS_BROWSER_API_DECLARATIVE_NET_REQUEST_RULES_COUNT_PAIR_H_
#define EXTENSIONS_BROWSER_API_DECLARATIVE_NET_REQUEST_RULES_COUNT_PAIR_H_
#include <cstddef>
namespace extensions {
namespace declarative_net_request {
// Represents the pair of total rule count and regex rule count for a ruleset.
struct RulesCountPair {
RulesCountPair();
RulesCountPair(size_t rule_count, size_t regex_rule_count);
RulesCountPair& operator+=(const RulesCountPair& that);
// This CHECKs that counts in |that| are smaller than or equal to the one in
// |this|.
RulesCountPair& operator-=(const RulesCountPair& that);
size_t rule_count = 0;
size_t regex_rule_count = 0;
};
RulesCountPair operator+(const RulesCountPair& lhs, const RulesCountPair& rhs);
// This CHECKs that counts in |rhs| are smaller than or equal to the one in
// |lhs|.
RulesCountPair operator-(const RulesCountPair& lhs, const RulesCountPair& rhs);
bool operator==(const RulesCountPair& lhs, const RulesCountPair& rhs);
} // namespace declarative_net_request
} // namespace extensions
#endif // EXTENSIONS_BROWSER_API_DECLARATIVE_NET_REQUEST_RULES_COUNT_PAIR_H_
| 32.975 | 79 | 0.789234 |
50a9e234281eb235083f119a50429e08d879a4e2 | 5,036 | h | C | svSolver-master/Code/FlowSolvers/ThreeDSolver/svSolver/global.h | mccsssk2/SimVascularPM3_March2020 | 3cce6cc7be66545bea5dc3915a2db50a3892bf04 | [
"BSD-3-Clause"
] | null | null | null | svSolver-master/Code/FlowSolvers/ThreeDSolver/svSolver/global.h | mccsssk2/SimVascularPM3_March2020 | 3cce6cc7be66545bea5dc3915a2db50a3892bf04 | [
"BSD-3-Clause"
] | null | null | null | svSolver-master/Code/FlowSolvers/ThreeDSolver/svSolver/global.h | mccsssk2/SimVascularPM3_March2020 | 3cce6cc7be66545bea5dc3915a2db50a3892bf04 | [
"BSD-3-Clause"
] | null | null | null | c Copyright (c) 2014-2015 The Regents of the University of California.
c All Rights Reserved.
c
c Portions of the code Copyright (c) 2009-2011 Open Source Medical
c Software Corporation, University of California, San Diego.
c
c Portions of the code Copyright (c) 2000-2007, Stanford University,
c Rensselaer Polytechnic Institute, Kenneth E. Jansen,
c Charles A. Taylor.
c
c See SimVascular Acknowledgements file for additional
c contributors to the source code.
c
c Redistribution and use in source and binary forms, with or without
c modification, are permitted provided that the following conditions
c are met:
c
c Redistributions of source code must retain the above copyright notice,
c this list of conditions and the following disclaimer.
c Redistributions in binary form must reproduce the above copyright
c notice, this list of conditions and the following disclaimer in the
c documentation and/or other materials provided with the distribution.
c Neither the name of the Stanford University or Rensselaer Polytechnic
c Institute nor the names of its contributors may be used to endorse or
c promote products derived from this software without specific prior
c written permission.
c
c THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
c "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
c LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
c FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
c COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
c INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
c BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
c OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
c AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
c OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
c THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
c DAMAGE.
c
c----------------------------------------------------------------------
c
c This file contains the global settings and global parameter declarations
c needed for the headers/fortran files.
c
c----------------------------------------------------------------------
C
C Variables are not implicitly declared
C
IMPLICIT NONE
c CONSTANTS
INTEGER MAXBLK,MAXTS,MAXSH,MAXTOP,MAXSURF,MAXQPT,MACHFL,NSD,NITR
c
c.... parameters IF YOU CHANGE THES YOU HAVE TO CHANGE THEM IN
c common_c.h ALSO
c
parameter ( MAXBLK = 5000, MAXTS = 100)
parameter ( MAXSH = 32, NSD = 3 )
parameter ( MAXQPT = 125 )
parameter ( MAXTOP = 6, MAXSURF=199 )
c
c----------------------------------------------------------------------
c
c.... parameters : machine data
c
c machin : machine type
c (set parameter)
c machfl : single precision floating point lenght in bytes
c (set parameter)
c
c----------------------------------------------------------------------
CHARACTER*8 machin
parameter ( machin = 'RS/6000 ' )
parameter ( machfl = 4 )
c
c----------------------------------------------------------------------
c.... parameters : useful constants
c
c zero : 0.0
c pt125 : 0.125
c pt25 : 0.25
c pt33 : 0.33 (1/3)
c pt39 : 2^(-4/3)
c pt5 : 0.5
c pt57 : 1/sqrt(3)
c pt66 : 0.66 (2/3)
c pt75 : 0.75
c one : 1.0
c sqt2 : sqrt(2)
c onept5 : 1.5
c two : 2.0
c three : 3.0
c four : 4.0
c five : 5.0
c pi : the magical number :-)
c
c----------------------------------------------------------------------
c
REAL*8 zero,pt25,pt125,pt33,pt39,pt5,pt57,pt66,pt75,sqt2,onept5
REAL*8 one,two,three,four,five,pi
parameter
& ( zero = 0.0000000000000000000000000000000d0,
& pt125 = 0.1250000000000000000000000000000d0,
& pt25 = 0.2500000000000000000000000000000d0,
& pt33 = 0.3333333333333333333333333333333d0,
& pt39 = 0.3968502629920498686879264098181d0,
& pt5 = 0.5000000000000000000000000000000d0,
& pt57 = 0.5773502691896257645091487805020d0,
& pt66 = 0.6666666666666666666666666666667d0,
& pt75 = 0.7500000000000000000000000000000d0,
& one = 1.0000000000000000000000000000000d0,
& sqt2 = 1.4142135623730950488016887242097d0,
& onept5 = 1.5000000000000000000000000000000d0,
& two = 2.0000000000000000000000000000000d0,
& three = 3.0000000000000000000000000000000d0,
& four = 4.0000000000000000000000000000000d0,
& five = 5.0000000000000000000000000000000d0,
& pi = 3.1415926535897932384626433832795d0)
c
| 40.612903 | 74 | 0.606235 |
f8ad926c670563c2707c943ec09a35e4455206a0 | 421 | h | C | tools/giza-align/GIZA++-v2/mymath.h | bingrao/Bug-Transformer | 9e39dc553c281f6372b7a8cfc8205aa186645899 | [
"MIT"
] | 311 | 2016-05-14T12:20:29.000Z | 2022-02-13T14:36:20.000Z | tools/giza-align/GIZA++-v2/mymath.h | bingrao/Bug-Transformer | 9e39dc553c281f6372b7a8cfc8205aa186645899 | [
"MIT"
] | 8 | 2017-04-14T06:52:35.000Z | 2021-11-08T08:29:01.000Z | tools/giza-align/GIZA++-v2/mymath.h | bingrao/Bug-Transformer | 9e39dc553c281f6372b7a8cfc8205aa186645899 | [
"MIT"
] | 96 | 2016-01-11T14:16:37.000Z | 2019-11-19T00:56:47.000Z | /* ---------------------------------------------------------------- */
/* Copyright 1998 (c) by RWTH Aachen - Lehrstuhl fuer Informatik VI */
/* Franz Josef Och */
/* ---------------------------------------------------------------- */
#ifndef HEADER_MYMATH_DEFINED
#define HEADER_MYMATH_DEFINED
inline double mfabs(double x){return (x<0)?(-x):x;}
#include <math.h>
#endif
| 42.1 | 70 | 0.401425 |
fbbbd969fc527c36dbf472c2e9c8eecfe3fbb137 | 191 | h | C | net/rras/ras/rasman/rasman/rnetcfg.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/rras/ras/rasman/rasman/rnetcfg.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/rras/ras/rasman/rasman/rnetcfg.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z |
extern "C"
{
HRESULT HrRasCreateAndInitializeINetCfg (BOOL fInitCom, INetCfg** ppnc);
HRESULT HrRasUninitializeAndReleaseINetCfg (BOOL fUninitCom, INetCfg* pnc);
}
| 17.363636 | 80 | 0.696335 |
2d5deee451f7e71fd1b07a57a6e274854f1a7e71 | 915 | h | C | ip_repo/klein_1.0/drivers/klein_v1_0/src/xklein_hw.h | emse-sas-lab/SCAbox-IP | 8f92c6a21c03fbe811c1ba1607fa39ec1f06941d | [
"MIT"
] | 4 | 2021-03-10T07:42:53.000Z | 2022-03-27T15:10:05.000Z | ip_repo/klein_1.0/drivers/klein_v1_0/src/xklein_hw.h | emse-sas-lab/SCAbox-ip | 8f92c6a21c03fbe811c1ba1607fa39ec1f06941d | [
"MIT"
] | null | null | null | ip_repo/klein_1.0/drivers/klein_v1_0/src/xklein_hw.h | emse-sas-lab/SCAbox-ip | 8f92c6a21c03fbe811c1ba1607fa39ec1f06941d | [
"MIT"
] | null | null | null | #define XKLEIN_WORDS_SIZE 4
#define XKLEIN_BYTES_SIZE 16
#define XKLEIN_DATA_IN0_OFFSET 0x00
#define XKLEIN_DATA_IN1_OFFSET 0x04
#define XKLEIN_DATA_OUT0_OFFSET 0x18
#define XKLEIN_DATA_OUT1_OFFSET 0x1C
#define XKLEIN_DATA_KEY0_OFFSET 0x20
#define XKLEIN_DATA_KEY1_OFFSET 0x24
#define XKLEIN_DATA_KEY2_OFFSET 0x28
#define XKLEIN_DATA_KEY3_OFFSET 0x2c
#define XKLEIN_STATUS_WR_OFFSET 0x30
#define XKLEIN_STATUS_RD_OFFSET 0x34
#define XKLEIN_STATUS_NULL_MASK 0x0
#define XKLEIN_STATUS_RESET_MASK 0x1
#define XKLEIN_STATUS_START_MASK 0x2
#define XKLEIN_STATUS_DONE_MASK 0x1
#define XKLEIN_SetStatus1(status, reg) \
(reg | status)
#define XKLEIN_SetStatus0(status, reg) \
(reg & ~status)
#define XKLEIN_GetStatus(status, reg) \
(reg & status)
#define XKLEIN_ReadReg(addr, offset) \
Xil_In32((addr) + (offset))
#define XKLEIN_WriteReg(addr, offset, data) \
Xil_Out32((addr) + (offset), (data)) | 27.727273 | 45 | 0.803279 |
10395ab84371e409ee442d15d1a8c1020fd7492b | 15,416 | h | C | rai/KOMO/komo.h | Zwoelf12/rai | b4e7082f3b7e8be5a0490f37e57d442047aaa020 | [
"MIT"
] | 52 | 2018-05-25T07:26:18.000Z | 2022-03-27T07:37:44.000Z | rai/KOMO/komo.h | Zwoelf12/rai | b4e7082f3b7e8be5a0490f37e57d442047aaa020 | [
"MIT"
] | 4 | 2019-04-09T19:10:27.000Z | 2021-12-09T11:11:22.000Z | rai/KOMO/komo.h | Zwoelf12/rai | b4e7082f3b7e8be5a0490f37e57d442047aaa020 | [
"MIT"
] | 32 | 2018-06-22T20:47:47.000Z | 2022-03-07T00:19:54.000Z | /* ------------------------------------------------------------------
Copyright (c) 2011-2020 Marc Toussaint
email: toussaint@tu-berlin.de
This code is distributed under the MIT License.
Please see <root-path>/LICENSE for details.
-------------------------------------------------------------- */
#pragma once
#include "objective.h"
#include "skeletonSymbol.h"
#include "../Kin/kin.h"
#include "../Optim/optimization.h"
#include "../Optim/constrained.h"
#include "../Optim/KOMO_Problem.h"
#include "../Optim/MathematicalProgram.h"
#include "../Kin/switch.h"
#include "../Kin/featureSymbols.h"
//===========================================================================
namespace rai {
struct FclInterface;
}
//===========================================================================
namespace rai {
enum KOMOsolver { KS_none=-1, KS_dense=0, KS_sparse, KS_banded, KS_sparseFactored, KS_NLopt, KS_Ipopt, KS_Ceres };
}
//===========================================================================
namespace rai {
struct KOMO_Options {
RAI_PARAM("KOMO/", int, verbose, 1)
RAI_PARAM("KOMO/", int, animateOptimization, 0)
RAI_PARAM("KOMO/", bool, mimicStable, false)
};
}//namespace
struct KOMO : NonCopyable {
//-- the problem definition
uint stepsPerPhase=0; ///< time slices per phase
uint T=0; ///< total number of time steps
double tau=0.; ///< real time duration of single step (used when evaluating feature space velocities/accelerations)
uint k_order=0; ///< the (Markov) order of the KOMO problem (default 2)
rai::Array<ptr<Objective>> objectives; ///< list of objectives
rai::Array<ptr<GroundedObjective>> objs;
rai::Array<rai::KinematicSwitch*> switches; ///< list of kinematic switches along the motion
//-- internals
rai::Configuration world; ///< original configuration; which is the blueprint for all time-slice worlds (almost const: only makeConvexHulls modifies it)
rai::Configuration pathConfig; ///< configuration containing full path (T+k_order copies of world, with switches applied)
uintA orgJointIndices; ///< set of joint IDs (IDs of frames with dofs) of the original world
FrameL timeSlices; ///< the original timeSlices of the pathConfig (when switches add frames, pathConfig.frames might differ from timeSlices - otherwise not)
bool computeCollisions; ///< whether swift or fcl (collisions/proxies) is evaluated whenever new configurations are set (needed if features read proxy list)
shared_ptr<rai::FclInterface> fcl;
shared_ptr<SwiftInterface> swift;
bool switchesWereApplied = false; //TODO: apply them directly? Would only work when no frames were added?
//-- optimizer
rai::KOMOsolver solver=rai::KS_sparse;
arr x, dual; ///< the primal and dual solution
//-- options
rai::KOMO_Options opt;
//-- verbosity only: buffers of all feature values computed on last set_x
double sos, eq, ineq;
arr featureValues; ///< storage of all features in all time slices
arrA featureJacobians; ///< storage of all features in all time slices
ObjectiveTypeA featureTypes; ///< storage of all feature-types in all time slices
StringA featureNames;
double timeTotal=0.; ///< measured run time
double timeCollisions=0., timeKinematics=0., timeNewton=0., timeFeatures=0.;
ofstream* logFile=0;
KOMO();
~KOMO();
//-- setup the problem
void setModel(const rai::Configuration& C, bool _computeCollisions=true);
void setTiming(double _phases=1., uint _stepsPerPhase=30, double durationPerPhase=5., uint _k_order=2);
//-- higher-level default setups
void setIKOpt(); ///< setTiming(1., 1, 1., 1); and velocity objective
//===========================================================================
//
// lowest level way to define objectives: basic methods to add any single objective or switch
//
/** THESE ARE THE TWO MOST IMPORTANT METHODS TO DEFINE A PROBLEM
* they allow the user to add an objective, or a kinematic switch in the problem definition
* Typically, the user does not call them directly, but uses the many methods below
* Think of all of the below as examples for how to set arbirary objectives/switches yourself */
ptr<struct Objective> addObjective(const arr& times, const ptr<Feature>& f, const StringA& frames,
ObjectiveType type, const arr& scale=NoArr, const arr& target=NoArr, int order=-1, int deltaFromStep=0, int deltaToStep=0);
ptr<struct Objective> addObjective(const arr& times, const FeatureSymbol& feat, const StringA& frames,
ObjectiveType type, const arr& scale=NoArr, const arr& target=NoArr, int order=-1, int deltaFromStep=0, int deltaToStep=0) {
return addObjective(times, symbols2feature(feat, frames, world),
NoStringA, type, scale, target, order, deltaFromStep, deltaToStep);
}
void clearObjectives(); ///< clear all objective
void addContact_slide(double startTime, double endTime, const char* from, const char* to);
void addContact_stick(double startTime, double endTime, const char* from, const char* to);
void addContact_elasticBounce(double time, const char* from, const char* to, double elasticity=.8, double stickiness=0.);
void addContact_ComplementarySlide(double startTime, double endTime, const char* from, const char* to);
// void addContact_Relaxed(double startTime, double endTime, const char *from, const char* to);
void getBounds(arr& bounds_lo, arr& bounds_up); ///< define the bounds (passed to the constrained optimization) based on the limit definitions of all DOFs
//===========================================================================
//
// mid-level ways to define objectives: typically adding one specific objective
//
ptr<struct Objective> add_qControlObjective(const arr& times, uint order, double scale=1., const arr& target=NoArr, int deltaFromStep=0, int deltaToStep=0);
void addSquaredQuaternionNorms(const arr& times=NoArr, double scale=3e0);
void add_collision(bool hardConstraint, double margin=.0, double prec=1e1);
void add_jointLimits(bool hardConstraint, double margin=.05, double prec=1.);
void setLiftDownUp(double time, const char* endeff, double timeToLift=.15);
void setSlow(double startTime, double endTime, double prec=1e1, bool hardConstrained=false);
void setSlowAround(double time, double delta, double prec=1e1, bool hardConstrained=false);
//-- core kinematic switch symbols of skeletons
//protected:
//low-level add dof switches
void addSwitch(const arr& times, bool before, rai::KinematicSwitch* sw);
rai::KinematicSwitch* addSwitch(const arr& times, bool before, rai::JointType type, rai::SwitchInitializationType init,
const char* ref1, const char* ref2,
const rai::Transformation& jFrom=NoTransformation, const rai::Transformation& jTo=NoTransformation);
public:
//add a mode switch: both, the low-level dof switches and corresponding constraints of consistency
void addModeSwitch(const arr& times, rai::SkeletonSymbol newMode, const StringA& frames, bool firstSwitch);
//1-liner specializations of setModeSwitch:
void addSwitch_stable(double time, double endTime, const char* prevFrom, const char* from, const char* to, bool firstSwitch=true);
void addSwitch_stableOn(double time, double endTime, const char* prevFrom, const char* from, const char* to, bool firstSwitch);
void addSwitch_dynamic(double time, double endTime, const char* from, const char* to, bool dampedVelocity=false);
void addSwitch_dynamicOn(double time, double endTime, const char* from, const char* to);
void addSwitch_dynamicOnNewton(double time, double endTime, const char* from, const char* to);
void addSwitch_dynamicTrans(double time, double endTime, const char* from, const char* to);
void addSwitch_magic(double time, double endTime, const char* from, const char* to, double sqrAccCost, double sqrVelCost);
void addSwitch_magicTrans(double time, double endTime, const char* from, const char* to, double sqrAccCost);
//advanced:
void setPairedTimes();
void addTimeOptimization();
//===========================================================================
//
// optimizing, getting results, and verbosity
//
//-- setting individual time slices
void setConfiguration_qAll(int t, const arr& q); ///< t<0 allows to set the prefix configurations; while 0 <= t < T allows to set all other initial configurations
void setConfiguration_qOrg(int t, const arr& q); ///< set only those DOFs that were defined in the original world (excluding extra DOFs from switches)
void setConfiguration_X(int t, const arr& X); ///< t<0 allows to set the prefix configurations; while 0 <= t < T allows to set all other initial configurations
void initWithConstant(const arr& q); ///< set all configurations EXCEPT the prefix to a particular state
void initWithWaypoints(const arrA& waypoints, uint waypointStepsPerPhase=1, bool sineProfile=true); ///< set all configurations (EXCEPT prefix) to interpolate given waypoints
void updateAndShiftPrefix(const rai::Configuration& C){
//-- joint state
//set t=0 to new joint state:
setConfiguration_qAll(0, C.getJointState());
//shift the joint state within prefix (t=-1 becomes equal to t=0, which is new state)
for(int t=-k_order; t<0; t++) setConfiguration_qOrg(t, getConfiguration_qOrg(t+1));
//-- frame state of roots only, if objects moved:
uintA roots = framesToIndices(C.getRoots());
arr X0 = C.getFrameState(roots);
//set t=0..T to new frame state:
for(uint t=0; t<T; t++) pathConfig.setFrameState(X0, roots+timeSlices(k_order+t,0)->ID);
//shift the frame states within the prefix (t=-1 becomes equal to t=0, which is new state)
for(int t=-k_order; t<0; t++){
arr Xt = pathConfig.getFrameState(roots+timeSlices(k_order+t+1,0)->ID);
pathConfig.setFrameState(Xt, roots+timeSlices(k_order+t,0)->ID);
}
}
//-- optimization
void optimize(double addInitializationNoise=.01, const OptOptions options=NOOPT); ///< run the solver (same as run_prepare(); run(); )
void reset(); ///< reset the dual variables and feature value buffers (always needed when adding/changing objectives before continuing an optimization)
//advanced
void run_prepare(double addInitializationNoise); ///< ensure the configurations are setup, decision variable is initialized, and noise added (if >0)
void run(OptOptions options=NOOPT); ///< run the solver iterations (configurations and decision variable needs to be setup before)
void setSpline(uint splineT); ///< optimize B-spline nodes instead of the path; splineT specifies the time steps per node
//-- reading results
arr getConfiguration_qAll(int t); ///< get all DOFs
arr getConfiguration_qOrg(int t); ///< get only those DOFs that were defined in the original world (excluding extra DOFs from switches)
arr getConfiguration_X(int t); ///< get frame path for selected frames
arrA getPath_qAll(); ///< get the DOFs (of potentially varying dimensionality) for each configuration
arr getPath_qOrg(); ///< get joint path, optionally for selected joints
arr getPath_X(); ///< get frame path, optionally for selected frames
arr getPath_tau();
arr getPath_times();
arr getPath_energies();
arr getActiveConstraintJacobian();
void reportProblem(ostream& os=std::cout);
rai::Graph getReport(bool gnuplt=false, int reportFeatures=0, ostream& featuresOs=std::cout); ///< return a 'dictionary' summarizing the optimization results (optional: gnuplot objective costs; output detailed cost features per time slice)
rai::Graph getProblemGraph(bool includeValues, bool includeSolution=true);
double getConstraintViolations();
double getCosts();
StringA getCollisionPairs(double belowMargin=.01); ///< report the proxies (collisions) for each time slice
void checkGradients(); ///< checks all gradients numerically
int view(bool pause=false, const char* txt=nullptr);
int view_play(bool pause=false, double delay=.2, const char* saveVideoPath=nullptr);
void plotTrajectory();
void plotPhaseTrajectory();
//===========================================================================
//
// internal (kind of private)
//
void selectJointsBySubtrees(const StringA& roots, const arr& times= {}, bool notThose=false);
void setupPathConfig();
void checkBounds(const arr& x);
void retrospectApplySwitches();
void retrospectChangeJointType(int startStep, int endStep, uint frameID, rai::JointType newJointType);
void set_x(const arr& x, const uintA& selectedConfigurationsOnly=NoUintA); ///< set the state trajectory of all configurations
//===========================================================================
//
// MP transcriptions
//
shared_ptr<MathematicalProgram> nlp_SparseNonFactored();
shared_ptr<MathematicalProgram_Factored> nlp_Factored();
//===========================================================================
//
// deprecated
//
bool displayTrajectory(double delay=1., bool watch=true, bool overlayPaths=true, const char* saveVideoPath=nullptr, const char* addText=nullptr){
DEPR; return view_play(watch, delay, saveVideoPath); }
bool displayPath(const char* txt, bool watch=true, bool full=true){
DEPR; return view(watch, txt); }
rai::Camera& displayCamera();
void add_StableRelativePose(const std::vector<int>& confs, const char* gripper, const char* object) {
DEPR;
for(uint i=1; i<confs.size(); i++)
addObjective(ARR(confs[0], confs[i]), FS_poseRel, {gripper, object}, OT_eq);
world.makeObjectsFree({object});
}
void add_StablePose(const std::vector<int>& confs, const char* object) {
DEPR;
for(uint i=1; i<confs.size(); i++)
addObjective(ARR(confs[0], confs[i]), FS_pose, {object}, OT_eq);
world.makeObjectsFree({object});
}
void add_grasp(int conf, const char* gripper, const char* object) {
DEPR;
addObjective(ARR(conf), FS_distance, {gripper, object}, OT_eq);
}
void add_place(int conf, const char* object, const char* table) {
DEPR;
addObjective(ARR(conf), FS_aboveBox, {table, object}, OT_ineq);
addObjective(ARR(conf), FS_standingAbove, {table, object}, OT_eq);
addObjective(ARR(conf), FS_vectorZ, {object}, OT_sos, {}, {0., 0., 1.});
}
void add_resting(int conf1, int conf2, const char* object) {
DEPR;
addObjective(ARR(conf1, conf2), FS_pose, {object}, OT_eq);
}
void add_restingRelative(int conf1, int conf2, const char* object, const char* tableOrGripper) {
DEPR;
addObjective(ARR(conf1, conf2), FS_poseRel, {tableOrGripper, object}, OT_eq);
}
void activateCollisions(const char* s1, const char* s2){ DEPR; HALT("see komo-21-03-06"); }
void deactivateCollisions(const char* s1, const char* s2);
arr getFrameStateX(int t){ DEPR; return getConfiguration_X(t); }
arr getPath_qAll(int t){ DEPR; return getConfiguration_qOrg(t); }
arr getConfiguration_q(int t) { DEPR; return getConfiguration_qAll(t); }
arr getPath_qOrg(uintA joints, const bool activesOnly){ DEPR; return getPath_qOrg(); }
};
| 51.731544 | 241 | 0.677543 |
bcda54afd40aabac76566f1455e9278112a6ea62 | 1,713 | c | C | src/vmi.c | fengjixuchui/kernel-fuzzer-for-xen-project | d01ed30bd7aeb312715dda253bd93037f0a11a5d | [
"MIT"
] | null | null | null | src/vmi.c | fengjixuchui/kernel-fuzzer-for-xen-project | d01ed30bd7aeb312715dda253bd93037f0a11a5d | [
"MIT"
] | null | null | null | src/vmi.c | fengjixuchui/kernel-fuzzer-for-xen-project | d01ed30bd7aeb312715dda253bd93037f0a11a5d | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2020 Intel Corporation
* SPDX-License-Identifier: MIT
*/
#include "vmi.h"
extern addr_t target_pagetable;
extern addr_t start_rip;
extern os_t os;
extern int interrupted;
extern page_mode_t pm;
extern vmi_instance_t vmi;
bool setup_vmi(vmi_instance_t *vmi, char* domain, uint64_t domid, char* json, bool init_events, bool init_paging)
{
printf("Init vmi, init_events: %i init_paging %i domain %s domid %lu json %s\n",
init_events, init_paging, domain, domid, json);
vmi_mode_t mode = (init_events ? VMI_INIT_EVENTS : 0) |
(domain ? VMI_INIT_DOMAINNAME : VMI_INIT_DOMAINID);
const void *d = domain ?: (void*)&domid;
if ( VMI_FAILURE == vmi_init(vmi, VMI_XEN, d, mode, NULL, NULL) )
return false;
if ( json )
{
if ( VMI_OS_UNKNOWN == (os = vmi_init_os(*vmi, VMI_CONFIG_JSON_PATH, json, NULL)) )
{
vmi_destroy(*vmi);
return false;
}
pm = vmi_get_page_mode(*vmi, 0);
}
else
if ( init_paging && VMI_PM_UNKNOWN == (pm = vmi_init_paging(*vmi, 0)) )
{
vmi_destroy(*vmi);
return false;
}
registers_t regs = {0};
if ( VMI_FAILURE == vmi_get_vcpuregs(*vmi, ®s, 0) )
{
vmi_destroy(*vmi);
return false;
}
target_pagetable = regs.x86.cr3;
start_rip = regs.x86.rip;
return true;
}
void loop(vmi_instance_t vmi)
{
if ( !vmi )
return;
vmi_resume_vm(vmi);
while (!interrupted)
{
if ( vmi_events_listen(vmi, 500) == VMI_FAILURE )
{
fprintf(stderr, "Error in vmi_events_listen!\n");
break;
}
}
interrupted = 0;
}
| 22.84 | 113 | 0.594863 |
4829a2a62a5b99a682907415a983ad5766217fa1 | 1,836 | h | C | DataMgr/PersistentStorageMgr/MutableCachePersistentStorageMgr.h | gitboti/omniscidb | 70db1e5ef56cbaf6ee1773f2b11afd523da83e5d | [
"Apache-2.0"
] | null | null | null | DataMgr/PersistentStorageMgr/MutableCachePersistentStorageMgr.h | gitboti/omniscidb | 70db1e5ef56cbaf6ee1773f2b11afd523da83e5d | [
"Apache-2.0"
] | 1 | 2021-02-24T03:22:29.000Z | 2021-02-24T03:22:29.000Z | DataMgr/PersistentStorageMgr/MutableCachePersistentStorageMgr.h | isabella232/omniscidb | bf83d84833710679debdf7a0484b6fbfc421cc96 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 OmniSci, 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 "PersistentStorageMgr.h"
/*
A PersistentStorageMgr with additional functionality for caching mutable tables to disk.
*/
class MutableCachePersistentStorageMgr : public PersistentStorageMgr {
public:
MutableCachePersistentStorageMgr(const std::string& data_dir,
const size_t num_reader_threads,
const DiskCacheConfig& disk_cache_config);
AbstractBuffer* createBuffer(const ChunkKey& chunk_key,
const size_t page_size,
const size_t initial_size) override;
void deleteBuffer(const ChunkKey& chunk_key, const bool purge) override;
void deleteBuffersWithPrefix(const ChunkKey& chunk_key_prefix,
const bool purge) override;
AbstractBuffer* putBuffer(const ChunkKey& chunk_key,
AbstractBuffer* source_buffer,
const size_t num_bytes) override;
void checkpoint() override;
void checkpoint(const int db_id, const int tb_id) override;
void removeTableRelatedDS(const int db_id, const int table_id) override;
private:
std::map<const ChunkKey, AbstractBuffer*> cached_buffer_map_;
};
| 40.8 | 90 | 0.691176 |
f0f342784ef11734a8cca0ad2a0d3d81bfaa3d14 | 4,444 | h | C | OpenSees/SRC/reliability/analysis/telm/SelectLoadInitialStaticAnalysis.h | kuanshi/ductile-fracture | ccb350564df54f5c5ec3a079100effe261b46650 | [
"MIT"
] | null | null | null | OpenSees/SRC/reliability/analysis/telm/SelectLoadInitialStaticAnalysis.h | kuanshi/ductile-fracture | ccb350564df54f5c5ec3a079100effe261b46650 | [
"MIT"
] | null | null | null | OpenSees/SRC/reliability/analysis/telm/SelectLoadInitialStaticAnalysis.h | kuanshi/ductile-fracture | ccb350564df54f5c5ec3a079100effe261b46650 | [
"MIT"
] | 1 | 2020-08-06T21:12:16.000Z | 2020-08-06T21:12:16.000Z | /* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 2001, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** Reliability module developed by: **
** Terje Haukaas (haukaas@ce.berkeley.edu) **
** Armen Der Kiureghian (adk@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision: 1.1 $
// $Date: 2008-02-29 19:43:53 $
// $Source: /usr/local/cvs/OpenSees/SRC/reliability/analysis/telm/SelectLoadInitialStaticAnalysis.h,v $
#ifndef SelectLoadStaticAnalysis_h
#define SelectLoadStaticAnalysis_h
#include <fstream>
#include <iomanip>
#include <iostream>
using std::ifstream;
using std::ofstream;
using std::ios;
using std::setw;
using std::setprecision;
#include<TaggedObjectStorage.h>
#include<ArrayOfTaggedObjects.h>
#include<StaticAnalysis.h>
#include<AnalysisModel.h>
#include<EquiSolnAlgo.h>
#include<ConstraintHandler.h>
#include<DOF_Numberer.h>
#include<LinearSOE.h>
#include<SensitivityAlgorithm.h>
#include<SensitivityIntegrator.h>//Abbas
#include<StaticIntegrator.h>
#include<ConvergenceTest.h>
#include<CTestNormUnbalance.h>
#include<CTestNormDispIncr.h>
#include<NewtonRaphson.h>
#include<PlainHandler.h>
#include<RCM.h>
#include<LoadControl.h>
#include<ProfileSPDLinDirectSolver.h>
#include<ProfileSPDLinSolver.h>
#include<ProfileSPDLinSOE.h>
#include<BandGenLinLapackSolver.h>
#include<BandGenLinSOE.h>
#include<ReliabilityStaticAnalysis.h>
#include<NewStaticSensitivityIntegrator.h>//Abbas
#include<NewSensitivityAlgorithm.h>//Abbas
#include <InitialStaticAnalysis.h>
#include <LoadPattern.h>
#include <LoadPatternIter.h>
#include <Node.h>
#include <NodeIter.h>
#include <RandomVariablePositioner.h>
#include <RandomVariable.h>
#include<Integrator.h>
class SelectLoadInitialStaticAnalysis : public InitialStaticAnalysis
{
public:
SelectLoadInitialStaticAnalysis(ReliabilityDomain* theReliabilityDomain,
Domain* theStructuralDomain,
int nstep,
int numLoadPatterns,
int* StaticLoadPatterns,
bool print);
~SelectLoadInitialStaticAnalysis();
void activateSensitivity(void);
void inactivateSensitivity();
void analyze(Vector x);
void analyzeMean(void);
void recoverLoads();
void constLoads(double);
void resetconstLoads(double);
void constandrecoverLoads(double);
protected:
private:
int Nstep;
int NumLoadPatterns;
int* StaticLoadPatterns;
LoadPatternIter* theOrgPatternIter;
TaggedObjectStorage* theOrgPatterns;
void saveLoads();
void createStaticAnalysis(void);
void reset();
void modifyLoads();
bool modified;
ReliabilityStaticAnalysis *theReliabilityStaticAnalysis;
AnalysisModel *theAnalysisModel;
EquiSolnAlgo *theAlgorithm;
ConstraintHandler *theHandler;
DOF_Numberer *theNumberer;
LinearSOE *theSOE;
StaticIntegrator *theStaticIntegrator;
ConvergenceTest *theTest;
bool activeSensitivity;
// SensitivityAlgorithm *theSensitivityAlgorithm;
Integrator *theSensitivityAlgorithm;
SensitivityIntegrator *theSensitivityIntegrator;//Abbas
};
#endif
| 34.71875 | 103 | 0.610036 |
51f08b2d0bf15a44732bd35a31ec18c36e5ed24c | 132 | h | C | release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/xen/xenfs/xenfs.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 55 | 2015-01-20T00:09:45.000Z | 2021-08-19T05:40:27.000Z | release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/xen/xenfs/xenfs.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 1 | 2021-02-24T05:16:58.000Z | 2021-02-24T05:16:58.000Z | release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/xen/xenfs/xenfs.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 36 | 2015-02-13T00:58:22.000Z | 2021-08-19T08:08:07.000Z | #ifndef _XENFS_XENBUS_H
#define _XENFS_XENBUS_H
extern const struct file_operations xenbus_file_ops;
#endif /* _XENFS_XENBUS_H */
| 18.857143 | 52 | 0.825758 |
8660520370ded350f49e169d71ea47d86b82cff7 | 2,787 | c | C | native/jni/external/selinux/restorecond/utmpwatcher.c | Joyoe/Magisk-nosbin_magisk-nohide | 449441921740bf85926c14f41b3532822ca0eb65 | [
"MIT"
] | 2 | 2022-01-16T00:59:54.000Z | 2022-02-09T12:00:48.000Z | native/jni/external/selinux/restorecond/utmpwatcher.c | Joyoe/Magisk-nosbin_magisk-nohide | 449441921740bf85926c14f41b3532822ca0eb65 | [
"MIT"
] | null | null | null | native/jni/external/selinux/restorecond/utmpwatcher.c | Joyoe/Magisk-nosbin_magisk-nohide | 449441921740bf85926c14f41b3532822ca0eb65 | [
"MIT"
] | 2 | 2022-02-09T12:00:39.000Z | 2022-02-21T18:34:46.000Z | /*
* utmpwatcher.c
*
* Copyright (C) 2006 Red Hat
* see file 'COPYING' for use and warranty information
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
.*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* Authors:
* Dan Walsh <dwalsh@redhat.com>
*
*
*/
#define _GNU_SOURCE
#include <sys/inotify.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
#include <limits.h>
#include <utmp.h>
#include <sys/types.h>
#include <pwd.h>
#include "restorecond.h"
#include "utmpwatcher.h"
#include "stringslist.h"
static struct stringsList *utmp_ptr = NULL;
static int utmp_wd = -1;
unsigned int utmpwatcher_handle(int inotify_fd, int wd)
{
int changed = 0;
struct utmp u;
const char *utmp_path = "/run/utmp";
struct stringsList *prev_utmp_ptr = utmp_ptr;
if (wd != utmp_wd)
return -1;
utmp_ptr = NULL;
FILE *cfg = fopen(utmp_path, "r");
if (!cfg)
exitApp("Error reading utmp file.");
while (fread(&u, sizeof(struct utmp), 1, cfg) > 0) {
if (u.ut_type == USER_PROCESS)
strings_list_add(&utmp_ptr, u.ut_user);
}
fclose(cfg);
if (utmp_wd >= 0)
inotify_rm_watch(inotify_fd, utmp_wd);
utmp_wd =
inotify_add_watch(inotify_fd, utmp_path, IN_MOVED_FROM | IN_MODIFY);
if (utmp_wd == -1)
exitApp("Error watching utmp file.");
changed = strings_list_diff(prev_utmp_ptr, utmp_ptr);
if (prev_utmp_ptr) {
strings_list_free(prev_utmp_ptr);
}
return changed;
}
static void watch_file(int inotify_fd, const char *file)
{
struct stringsList *ptr = utmp_ptr;
while (ptr) {
struct passwd *pwd = getpwnam(ptr->string);
if (pwd) {
char *path = NULL;
if (asprintf(&path, "%s%s", pwd->pw_dir, file) < 0)
exitApp("Error allocating memory.");
watch_list_add(inotify_fd, path);
free(path);
}
ptr = ptr->next;
}
}
void utmpwatcher_add(int inotify_fd, const char *path)
{
if (utmp_ptr == NULL) {
utmpwatcher_handle(inotify_fd, utmp_wd);
}
watch_file(inotify_fd, path);
}
void utmpwatcher_free(void)
{
if (utmp_ptr)
strings_list_free(utmp_ptr);
}
#ifdef TEST
int main(int argc, char **argv)
{
read_utmp();
return 0;
}
#endif
| 23.225 | 73 | 0.699318 |
b68d698a8f7095431ededd552afb0cb939ca48b2 | 2,214 | h | C | src/Emulator.h | cadaver/oldschoolengine2-emscripten | 6c578c2006254d8503e22e0d214ca7357381ea20 | [
"MIT"
] | 4 | 2018-08-06T11:03:40.000Z | 2021-12-04T13:47:38.000Z | src/Emulator.h | cadaver/oldschoolengine2-emscripten | 6c578c2006254d8503e22e0d214ca7357381ea20 | [
"MIT"
] | 2 | 2020-09-13T09:21:34.000Z | 2021-07-04T00:20:43.000Z | src/Emulator.h | cadaver/oldschoolengine2-emscripten | 6c578c2006254d8503e22e0d214ca7357381ea20 | [
"MIT"
] | 1 | 2019-06-02T20:40:38.000Z | 2019-06-02T20:40:38.000Z | // MIT License
//
// Copyright (c) 2018 Lasse Oorni
//
// 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.
#pragma once
#include <map>
#include <set>
#include "DiskImage.h"
class MOS6502;
class RAM64K;
class VIC2;
class SID;
class Emulator
{
public:
Emulator(const std::string& imageName);
~Emulator();
void Update();
void QueueAudio();
void KernalTrap(unsigned short address);
unsigned char IORead(unsigned short address, bool& handled);
void IOWrite(unsigned short address, unsigned char value);
void HandleKey(unsigned keyCode, bool down);
private:
void InitMemory();
void BootGame();
void RunFrame();
void ExecuteLine(int lineNum, bool visible);
void UpdateLineCounterAndIRQ(int lineNum);
bool IsKeyDown(unsigned keyCode);
RAM64K* _ram;
MOS6502* _processor;
VIC2* _vic2;
SID* _sid;
DiskImage* _disk;
FileHandle _fileHandle;
std::vector<unsigned char> _fileName;
std::set<unsigned> _keysDown;
std::map<unsigned, unsigned char> _keyMappings;
int _lineCounter;
int _audioCycles;
int _timer;
bool _timerIRQEnable;
bool _timerIRQFlag;
unsigned char _keyMatrix[8];
};
| 30.75 | 81 | 0.726739 |
ab2f177efbc93814a321a304520df1e4d334a18f | 10,179 | h | C | src/dpo/src/detailed_manager.h | gatecat/OpenROAD | cd7a2f497c69a77dc056e8b966daa5de7d211a58 | [
"BSD-3-Clause"
] | 1 | 2022-01-21T17:56:46.000Z | 2022-01-21T17:56:46.000Z | src/dpo/src/detailed_manager.h | gatecat/OpenROAD | cd7a2f497c69a77dc056e8b966daa5de7d211a58 | [
"BSD-3-Clause"
] | null | null | null | src/dpo/src/detailed_manager.h | gatecat/OpenROAD | cd7a2f497c69a77dc056e8b966daa5de7d211a58 | [
"BSD-3-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2021, Andrew Kennings
// 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 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.
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Description:
// Primarily for maintaining the segments.
#pragma once
////////////////////////////////////////////////////////////////////////////////
// Includes.
////////////////////////////////////////////////////////////////////////////////
#include <deque>
#include <vector>
#include "architecture.h"
#include "network.h"
#include "rectangle.h"
#include "router.h"
#include "utility.h"
namespace utl {
class Logger;
}
namespace dpo {
////////////////////////////////////////////////////////////////////////////////
// Defines.
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Forward declarations.
////////////////////////////////////////////////////////////////////////////////
class DetailedSeg;
////////////////////////////////////////////////////////////////////////////////
// Classes.
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class DetailedMgr {
public:
DetailedMgr(Architecture* arch, Network* network, RoutingParams* rt);
virtual ~DetailedMgr();
void cleanup();
Architecture* getArchitecture() const { return m_arch; }
Network* getNetwork() const { return m_network; }
RoutingParams* getRoutingParams() const { return m_rt; }
void setLogger(utl::Logger* logger) { m_logger = logger; }
utl::Logger* getLogger() const { return m_logger; }
void setSeed(int seed);
void internalError( std::string msg );
void setupObstaclesForDrc();
void findBlockages(bool includeRouteBlockages = true);
void findRegionIntervals(
int regId,
std::vector<std::vector<std::pair<double, double> > >& intervals);
void findSegments();
DetailedSeg* findClosestSegment(Node* nd);
void findClosestSpanOfSegmentsDfs(
Node* ndi, DetailedSeg* segPtr, double xmin, double xmax, int bot,
int top, std::vector<DetailedSeg*>& stack,
std::vector<std::vector<DetailedSeg*> >& candidates);
bool findClosestSpanOfSegments(Node* nd, std::vector<DetailedSeg*>& segments);
void assignCellsToSegments(std::vector<Node*>& nodesToConsider);
int checkSegments(double& worst);
int checkOverlapInSegments();
int checkEdgeSpacingInSegments();
int checkSiteAlignment();
int checkRowAlignment(int max_err_n = 0);
int checkRegionAssignment();
void removeCellFromSegmentTest(Node* nd, int seg, double& util, double& gapu);
void addCellToSegmentTest(Node* nd, int seg, double x, double& util,
double& gapu);
void removeCellFromSegment(Node* nd, int seg);
void addCellToSegment(Node* nd, int seg);
double getCellSpacing(Node* ndl, Node* ndr, bool checkPinsOnCells);
void collectSingleHeightCells();
void collectMultiHeightCells();
void moveMultiHeightCellsToFixed();
void collectFixedCells();
void collectWideCells();
void restoreOriginalPositions();
void recordOriginalPositions();
void restoreOriginalDimensions();
void recordOriginalDimensions();
void restoreBestPositions();
void recordBestPositions();
void resortSegments();
void resortSegment(DetailedSeg* segPtr);
void removeAllCellsFromSegments();
double getOrigX(Node* nd) const { return m_origX[nd->getId()]; }
double getOrigY(Node* nd) const { return m_origY[nd->getId()]; }
double getOrigW(Node* nd) const { return m_origW[nd->getId()]; }
double getOrigH(Node* nd) const { return m_origH[nd->getId()]; }
bool isNodeAlignedToRow(Node* nd);
double measureMaximumDisplacement(bool& violated);
void removeOverlapMinimumShift();
size_t getNumSegments() const { return m_segments.size(); }
DetailedSeg* getSegment(int s) const { return m_segments[s]; }
int getNumSingleHeightRows() const {
return m_numSingleHeightRows;
}
int getSingleRowHeight() const { return m_singleRowHeight; }
void getSpaceAroundCell(int seg, int ix, double& space, double& larger,
int limit = 3);
void getSpaceAroundCell(int seg, int ix, double& space_left,
double& space_right, double& large_left,
double& large_right, int limit = 3);
bool fixSegments();
void moveCellsBetweenSegments(int iteration);
void pushCellsBetweenSegments(int iteration);
void moveCellsBetweenSegments(DetailedSeg* segment, int leftRightTol,
double offsetTol, double scoringTol);
void removeSegmentOverlapSingle(int regId = -1);
void removeSegmentOverlapSingleInner(std::vector<Node*>& nodes, double l,
double r, int rowId);
void debugSegments();
double getTargetUt() const { return m_targetUt; }
void setTargetUt(double ut) { m_targetUt = ut; }
double getMaxMovement() const { return m_targetMaxMovement; }
void setTargetMaxMovement(double movement) { m_targetMaxMovement = movement; }
bool alignPos(Node* ndi, double& xi, double xl, double xr);
bool shift(std::vector<Node*>& cells, std::vector<double>& tarX,
std::vector<double>& posX, double left, double right, int segId,
int rowId);
bool tryMove1(Node* ndi, double xi, double yi, int si, double xj, double yj,
int sj);
bool tryMove2(Node* ndi, double xi, double yi, int si, double xj, double yj,
int sj);
bool tryMove3(Node* ndi, double xi, double yi, int si, double xj, double yj,
int sj);
bool trySwap1(Node* ndi, double xi, double yi, int si, double xj, double yj,
int sj);
void acceptMove();
void rejectMove();
public:
struct compareBlockages {
bool operator()(std::pair<double, double> i1,
std::pair<double, double> i2) const {
if (i1.first == i2.first) {
return i1.second < i2.second;
}
return i1.first < i2.first;
}
};
struct compareNodesX {
bool operator()(Node* p, Node* q) const {
return p->getX() < q->getX();
}
bool operator()(Node*& s, double i) const { return s->getX() < i; }
bool operator()(double i, Node*& s) const { return i < s->getX(); }
};
struct compareNodesL {
bool operator()(Node* p, Node* q) const {
return p->getX() - 0.5 * p->getWidth() < q->getX() - 0.5 * q->getWidth();
}
};
protected:
// Standard stuff.
Architecture* m_arch;
Network* m_network;
RoutingParams* m_rt;
// For output.
utl::Logger* m_logger;
// Info about rows.
int m_numSingleHeightRows;
double m_singleRowHeight;
// Generic place for utilization.
double m_targetUt;
double m_targetMaxMovement;
std::vector<Node*> m_fixedCells; // Fixed; filler, macros, temporary, etc.
public:
// Blockages and segments.
std::vector<std::vector<std::pair<double, double> > > m_blockages;
std::vector<std::vector<Node*> > m_cellsInSeg;
std::vector<std::vector<DetailedSeg*> > m_segsInRow;
std::vector<DetailedSeg*> m_segments;
std::vector<std::vector<DetailedSeg*> > m_reverseCellToSegs;
// For short and pin access stuff...
std::vector<std::vector<std::vector<Rectangle> > > m_obstacles;
// Random number generator.
Placer_RNG* m_rng;
// Info about cells.
std::vector<Node*> m_singleHeightCells; // Single height cells.
std::vector<std::vector<Node*> >
m_multiHeightCells; // Multi height cells by height.
std::vector<Node*> m_fixedMacros; // Fixed; only macros.
std::vector<Node*>
m_wideCells; // Wide movable cells. Can be single of multi.
// Info about original cell positions and dimensions.
std::vector<double> m_origX;
std::vector<double> m_origY;
std::vector<double> m_origW;
std::vector<double> m_origH;
std::vector<double> m_bestX;
std::vector<double> m_bestY;
std::vector<Rectangle> m_boxes;
// For generating a move list...
std::vector<double> m_curX;
std::vector<double> m_curY;
std::vector<double> m_newX;
std::vector<double> m_newY;
std::vector<unsigned> m_curOri;
std::vector<unsigned> m_newOri;
std::vector<std::vector<int> > m_curSeg;
std::vector<std::vector<int> > m_newSeg;
std::vector<Node*> m_movedNodes;
int m_nMoved;
int m_moveLimit;
};
} // namespace dpo
| 35.1 | 80 | 0.623244 |
bae6278d515b11d151402fea6ab230bd9392fbc5 | 149 | h | C | strategy/ia.h | TERRUSS/c-escampe | 8a90c703f4f6e14620aad8523ba32ef9ca42fc70 | [
"Unlicense"
] | null | null | null | strategy/ia.h | TERRUSS/c-escampe | 8a90c703f4f6e14620aad8523ba32ef9ca42fc70 | [
"Unlicense"
] | null | null | null | strategy/ia.h | TERRUSS/c-escampe | 8a90c703f4f6e14620aad8523ba32ef9ca42fc70 | [
"Unlicense"
] | null | null | null | #pragma once
#include "../lib/graphics.h"
#include "../utils/types.h"
#include "../display/display.h"
void ia_player(int ia_color, int * turn_pm);
| 18.625 | 44 | 0.691275 |
c7720f95dad3a24eb8a0cdcda0a252272a8b214b | 3,718 | h | C | SDK/BP_Prompt_RepairShipMast_classes.h | alxalx14/Sea-Of-Thieves-SDK | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | [
"MIT"
] | 3 | 2021-03-27T08:30:37.000Z | 2021-04-18T19:32:53.000Z | SDK/BP_Prompt_RepairShipMast_classes.h | alxalx14/Sea-Of-Thieves-SDK | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | [
"MIT"
] | null | null | null | SDK/BP_Prompt_RepairShipMast_classes.h | alxalx14/Sea-Of-Thieves-SDK | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | [
"MIT"
] | 1 | 2021-06-01T03:05:50.000Z | 2021-06-01T03:05:50.000Z | #pragma once
// Name: SeaOfThieves, Version: 2.0.23
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_Prompt_RepairShipMast.BP_Prompt_RepairShipMast_C
// 0x01AC (FullSize[0x02C4] - InheritedSize[0x0118])
class UBP_Prompt_RepairShipMast_C : public UBP_PromptCoordinator_Base_C
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0118(0x0008) (ZeroConstructor, Transient, DuplicateTransient)
bool State_ShipMastDamaged; // 0x0120(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor)
unsigned char UnknownData_WVEY[0x7]; // 0x0121(0x0007) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
struct FObjectMessagingHandle Handle_OnMastDamaged1; // 0x0128(0x0048) (Edit, BlueprintVisible, DisableEditOnInstance)
bool State_Complete; // 0x0170(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor)
unsigned char UnknownData_DGE8[0x7]; // 0x0171(0x0007) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
struct FPrioritisedPromptWithHandle Prompt_RepairShip; // 0x0178(0x0068) (Edit, BlueprintVisible, DisableEditOnInstance)
struct FObjectMessagingHandle Handle_CurrentShipChanged; // 0x01E0(0x0048) (Edit, BlueprintVisible, DisableEditOnInstance)
class AShip* CurrentShip; // 0x0228(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData, NoDestructor)
struct FObjectMessagingHandle Handle_OnMastDamaged2; // 0x0230(0x0048) (Edit, BlueprintVisible, DisableEditOnInstance)
struct FObjectMessagingHandle Handle_OnMastDamaged3; // 0x0278(0x0048) (Edit, BlueprintVisible, DisableEditOnInstance)
int NumMastsRegistered; // 0x02C0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_Prompt_RepairShipMast.BP_Prompt_RepairShipMast_C");
return ptr;
}
void UnregisterDamageEventFromCurrentShip();
void RegisterDamageEventWithCurrentShip();
void Evaluate();
void RegisterCharacterEvents_Implementable(const struct FObjectMessagingDispatcherHandle& CharacterDispatcher);
void OnCurrentShipChanged(const struct FEventCurrentShipChanged& Event);
void OnShipMastDamaged(const struct FEventMastDamageLevelChanged& Event);
void UnregisterCharacterEvents_Implementable(const struct FObjectMessagingDispatcherHandle& CharacterDispatcher);
void ExecuteUbergraph_BP_Prompt_RepairShipMast(int EntryPoint);
void AfterRead();
void BeforeDelete();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 55.492537 | 246 | 0.604626 |
67da7fccea97eaee27b859948b2b0cdeea5dc961 | 334 | h | C | src/sparql++/writer/csv.h | korczis/libsparql | e337fb29a56e6867b683851b0bd1cd3386393f54 | [
"Unlicense"
] | 1 | 2015-11-05T09:14:34.000Z | 2015-11-05T09:14:34.000Z | src/sparql++/writer/csv.h | korczis/libsparql | e337fb29a56e6867b683851b0bd1cd3386393f54 | [
"Unlicense"
] | null | null | null | src/sparql++/writer/csv.h | korczis/libsparql | e337fb29a56e6867b683851b0bd1cd3386393f54 | [
"Unlicense"
] | null | null | null | /* This is free and unencumbered software released into the public domain. */
#ifndef SPARQLXX_WRITER_CSV_H
#define SPARQLXX_WRITER_CSV_H
#include "sparql++/writer/impl.h"
sparql::writer::implementation* sparql_writer_for_csv(
FILE* stream,
const char* content_type,
const char* charset);
#endif /* SPARQLXX_WRITER_CSV_H */
| 23.857143 | 77 | 0.772455 |
80ab2a5ab0d970f501b55e7d234cedca35b9d37e | 2,847 | h | C | src/framebuffer.h | yodasoda1219/vkrollercoaster | 9a6df836bf446271a3885e3c4f86f783e1917cfe | [
"Apache-2.0"
] | 1 | 2021-12-18T00:46:50.000Z | 2021-12-18T00:46:50.000Z | src/framebuffer.h | yodasoda1219/vkrollercoaster | 9a6df836bf446271a3885e3c4f86f783e1917cfe | [
"Apache-2.0"
] | null | null | null | src/framebuffer.h | yodasoda1219/vkrollercoaster | 9a6df836bf446271a3885e3c4f86f783e1917cfe | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2021 Nora Beda and contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include "image.h"
#include "render_target.h"
namespace vkrollercoaster {
struct framebuffer_spec {
uint32_t width = 0, height = 0;
VkRenderPass render_pass = nullptr;
VkFramebuffer framebuffer =
nullptr; // passing a framebuffer gives ownership over to the framebuffer class
std::map<attachment_type, VkFormat> requested_attachments;
std::map<attachment_type, ref<image>> provided_attachments;
};
class framebuffer : public render_target {
public:
framebuffer(const framebuffer_spec& spec);
virtual ~framebuffer() override;
framebuffer(const framebuffer&) = delete;
framebuffer& operator=(const framebuffer&) = delete;
virtual render_target_type get_render_target_type() override {
return render_target_type::framebuffer;
}
virtual VkRenderPass get_render_pass() override { return this->m_render_pass; }
virtual VkFramebuffer get_framebuffer() override { return this->m_framebuffer; }
virtual VkExtent2D get_extent() override { return this->m_extent; }
virtual void add_reload_callbacks(void* id, std::function<void()> destroy,
std::function<void()> recreate) override;
virtual void remove_reload_callbacks(void* id) override;
virtual void get_attachment_types(std::set<attachment_type>& types) override;
ref<image> get_attachment(attachment_type type);
void set_attachment(attachment_type type, ref<image> attachment);
void reload();
void resize(VkExtent2D new_size);
private:
struct framebuffer_dependent {
std::function<void()> destroy, recreate;
};
void acquire_attachments(const framebuffer_spec& spec);
void create_render_pass();
void create_framebuffer();
void destroy_framebuffer(bool invoke_callbacks = true);
VkExtent2D m_extent;
VkRenderPass m_render_pass;
bool m_render_pass_owned;
VkFramebuffer m_framebuffer;
std::map<attachment_type, ref<image>> m_attachments;
std::map<void*, framebuffer_dependent> m_dependents;
};
} // namespace vkrollercoaster | 43.8 | 91 | 0.69301 |
b612ae194d8f70f1096c4916476848afcd1cfe83 | 1,772 | h | C | include/flir_spinnaker_common/image.h | berndpfrommer/flir_spinnaker_common | 09154f26057193679f22ce7d72cdbc2e41a8ac08 | [
"Apache-2.0"
] | 1 | 2022-02-03T12:53:43.000Z | 2022-02-03T12:53:43.000Z | include/flir_spinnaker_common/image.h | berndpfrommer/flir_spinnaker_common | 09154f26057193679f22ce7d72cdbc2e41a8ac08 | [
"Apache-2.0"
] | null | null | null | include/flir_spinnaker_common/image.h | berndpfrommer/flir_spinnaker_common | 09154f26057193679f22ce7d72cdbc2e41a8ac08 | [
"Apache-2.0"
] | null | null | null | // -*-c++-*--------------------------------------------------------------------
// Copyright 2020 Bernd Pfrommer <bernd.pfrommer@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef FLIR_SPINNAKER_COMMON__IMAGE_H_
#define FLIR_SPINNAKER_COMMON__IMAGE_H_
#include <flir_spinnaker_common/pixel_format.h>
#include <memory>
namespace flir_spinnaker_common
{
class Image
{
public:
Image(
uint64_t t, int16_t brightness, uint32_t et, uint32_t maxEt, float gain,
uint64_t imgT, size_t imageSize, int status, const void * data, size_t w,
size_t h, size_t stride, size_t bitsPerPixel, size_t numChan,
uint64_t frameId, pixel_format::PixelFormat pixFmt);
// ----- variables --
uint64_t time_;
int16_t brightness_;
uint32_t exposureTime_;
uint32_t maxExposureTime_;
float gain_;
uint64_t imageTime_;
size_t imageSize_;
int imageStatus_;
const void * data_;
size_t width_;
size_t height_;
size_t stride_; // in bytes
size_t bitsPerPixel_;
size_t numChan_;
uint64_t frameId_;
pixel_format::PixelFormat pixelFormat_;
private:
};
typedef std::shared_ptr<Image> ImagePtr;
typedef std::shared_ptr<const Image> ImageConstPtr;
} // namespace flir_spinnaker_common
#endif // FLIR_SPINNAKER_COMMON__IMAGE_H_
| 30.551724 | 79 | 0.726298 |
7b0573a485f9fe26a9f78f6cd30ce71f88931c11 | 1,844 | h | C | tools/kubot_ros_tool/led_strip/include/WS281X_TEST/libraries/Ros_lib/track_digital_msg_v1/rasppub1.h | kubot080301/kubot2_ros | 0075fb485c1ab17089032cea43982f1cc0c1d1e7 | [
"Apache-2.0"
] | null | null | null | tools/kubot_ros_tool/led_strip/include/WS281X_TEST/libraries/Ros_lib/track_digital_msg_v1/rasppub1.h | kubot080301/kubot2_ros | 0075fb485c1ab17089032cea43982f1cc0c1d1e7 | [
"Apache-2.0"
] | null | null | null | tools/kubot_ros_tool/led_strip/include/WS281X_TEST/libraries/Ros_lib/track_digital_msg_v1/rasppub1.h | kubot080301/kubot2_ros | 0075fb485c1ab17089032cea43982f1cc0c1d1e7 | [
"Apache-2.0"
] | null | null | null | #ifndef _ROS_track_digital_msg_v1_rasppub1_h
#define _ROS_track_digital_msg_v1_rasppub1_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
namespace track_digital_msg_v1
{
class rasppub1 : public ros::Msg
{
public:
float rasppub_data[16];
rasppub1():
rasppub_data()
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
for( uint32_t i = 0; i < 16; i++){
union {
float real;
uint32_t base;
} u_rasppub_datai;
u_rasppub_datai.real = this->rasppub_data[i];
*(outbuffer + offset + 0) = (u_rasppub_datai.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_rasppub_datai.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_rasppub_datai.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_rasppub_datai.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->rasppub_data[i]);
}
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
for( uint32_t i = 0; i < 16; i++){
union {
float real;
uint32_t base;
} u_rasppub_datai;
u_rasppub_datai.base = 0;
u_rasppub_datai.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_rasppub_datai.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_rasppub_datai.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_rasppub_datai.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->rasppub_data[i] = u_rasppub_datai.real;
offset += sizeof(this->rasppub_data[i]);
}
return offset;
}
const char * getType(){ return "track_digital_msg_v1/rasppub1"; };
const char * getMD5(){ return "2a81d54017a4c965271ef9df7cfccd41"; };
};
}
#endif | 28.369231 | 81 | 0.58731 |
dfca489cb1458c43fb2e5ae76a8f1b862cbc1c69 | 36,909 | c | C | mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx5/dr_rule.c | Hf7WCdtO/KRCore | 52369924ba175419912a274634d368d478dda501 | [
"Apache-2.0"
] | null | null | null | mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx5/dr_rule.c | Hf7WCdtO/KRCore | 52369924ba175419912a274634d368d478dda501 | [
"Apache-2.0"
] | null | null | null | mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx5/dr_rule.c | Hf7WCdtO/KRCore | 52369924ba175419912a274634d368d478dda501 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019, Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <ccan/minmax.h>
#include "mlx5dv_dr.h"
#define DR_RULE_MAX_STE_CHAIN (DR_RULE_MAX_STES + DR_ACTION_MAX_STES)
static int dr_rule_append_to_miss_list(struct dr_ste_ctx *ste_ctx,
struct dr_ste *new_last_ste,
struct list_head *miss_list,
struct list_head *send_list)
{
struct dr_ste_send_info *ste_info_last;
struct dr_ste *last_ste;
uint64_t miss_addr;
/* The new entry will be inserted after the last */
last_ste = list_tail(miss_list, struct dr_ste, miss_list_node);
assert(last_ste);
ste_info_last = calloc(1, sizeof(*ste_info_last));
if (!ste_info_last) {
errno = ENOMEM;
return errno;
}
miss_addr = dr_ste_get_icm_addr(new_last_ste);
dr_ste_set_miss_addr(ste_ctx, last_ste->hw_ste, miss_addr);
list_add_tail(miss_list, &new_last_ste->miss_list_node);
dr_send_fill_and_append_ste_send_info(last_ste, DR_STE_SIZE_CTRL,
0, last_ste->hw_ste,
ste_info_last, send_list, true);
return 0;
}
static struct dr_ste
*dr_rule_create_collision_htbl(struct mlx5dv_dr_matcher *matcher,
struct dr_matcher_rx_tx *nic_matcher,
uint8_t *hw_ste)
{
struct mlx5dv_dr_domain *dmn = matcher->tbl->dmn;
struct dr_ste_ctx *ste_ctx = dmn->ste_ctx;
struct dr_ste_htbl *new_htbl;
struct dr_ste *ste;
/* Create new table for miss entry */
new_htbl = dr_ste_htbl_alloc(dmn->ste_icm_pool,
DR_CHUNK_SIZE_1,
DR_STE_LU_TYPE_DONT_CARE,
0);
if (!new_htbl) {
dr_dbg(dmn, "Failed allocating collision table\n");
return NULL;
}
/* One and only entry, never grows */
ste = new_htbl->ste_arr;
dr_ste_set_miss_addr(ste_ctx, hw_ste, nic_matcher->e_anchor->chunk->icm_addr);
dr_htbl_get(new_htbl);
return ste;
}
static struct dr_ste *dr_rule_create_collision_entry(struct mlx5dv_dr_matcher *matcher,
struct dr_matcher_rx_tx *nic_matcher,
uint8_t *hw_ste,
struct dr_ste *orig_ste)
{
struct dr_ste *ste;
ste = dr_rule_create_collision_htbl(matcher, nic_matcher, hw_ste);
if (!ste) {
dr_dbg(matcher->tbl->dmn, "Failed creating collision entry\n");
return NULL;
}
ste->ste_chain_location = orig_ste->ste_chain_location;
/* In collision entry, all members share the same miss_list_head */
ste->htbl->miss_list = dr_ste_get_miss_list(orig_ste);
/* Next table */
if (dr_ste_create_next_htbl(matcher, nic_matcher, ste, hw_ste,
DR_CHUNK_SIZE_1)) {
dr_dbg(matcher->tbl->dmn, "Failed allocating table\n");
goto free_tbl;
}
return ste;
free_tbl:
dr_ste_free(ste, matcher, nic_matcher);
return NULL;
}
static int dr_rule_handle_one_ste_in_update_list(struct dr_ste_send_info *ste_info,
struct mlx5dv_dr_domain *dmn)
{
int ret;
list_del(&ste_info->send_list);
/* Copy data to ste, only reduced size or control, the last 16B (mask)
* is already written to the hw.
*/
if (ste_info->size == DR_STE_SIZE_CTRL)
memcpy(ste_info->ste->hw_ste, ste_info->data, DR_STE_SIZE_CTRL);
else
memcpy(ste_info->ste->hw_ste, ste_info->data, DR_STE_SIZE_REDUCED);
ret = dr_send_postsend_ste(dmn, ste_info->ste, ste_info->data,
ste_info->size, ste_info->offset);
if (ret)
goto out;
out:
free(ste_info);
return ret;
}
static int dr_rule_send_update_list(struct list_head *send_ste_list,
struct mlx5dv_dr_domain *dmn,
bool is_reverse)
{
struct dr_ste_send_info *ste_info, *tmp_ste_info;
int ret;
if (is_reverse) {
list_for_each_rev_safe(send_ste_list, ste_info, tmp_ste_info,
send_list) {
ret = dr_rule_handle_one_ste_in_update_list(ste_info,
dmn);
if (ret)
return ret;
}
} else {
list_for_each_safe(send_ste_list, ste_info, tmp_ste_info,
send_list) {
ret = dr_rule_handle_one_ste_in_update_list(ste_info,
dmn);
if (ret)
return ret;
}
}
return 0;
}
static struct dr_ste *dr_rule_find_ste_in_miss_list(struct list_head *miss_list,
uint8_t *hw_ste)
{
struct dr_ste *ste;
/* Check if hw_ste is present in the list */
list_for_each(miss_list, ste, miss_list_node)
if (dr_ste_equal_tag(ste->hw_ste, hw_ste))
return ste;
return NULL;
}
static struct dr_ste *
dr_rule_rehash_handle_collision(struct mlx5dv_dr_matcher *matcher,
struct dr_matcher_rx_tx *nic_matcher,
struct list_head *update_list,
struct dr_ste *col_ste,
uint8_t *hw_ste)
{
struct mlx5dv_dr_domain *dmn = matcher->tbl->dmn;
struct dr_ste *new_ste;
int ret;
new_ste = dr_rule_create_collision_htbl(matcher, nic_matcher, hw_ste);
if (!new_ste)
return NULL;
/* In collision entry, all members share the same miss_list_head */
new_ste->htbl->miss_list = dr_ste_get_miss_list(col_ste);
/* Update the previous from the list */
ret = dr_rule_append_to_miss_list(dmn->ste_ctx, new_ste,
dr_ste_get_miss_list(col_ste),
update_list);
if (ret) {
dr_dbg(dmn, "Failed update dup entry\n");
goto err_exit;
}
return new_ste;
err_exit:
dr_ste_free(new_ste, matcher, nic_matcher);
return NULL;
}
static void dr_rule_rehash_copy_ste_ctrl(struct mlx5dv_dr_matcher *matcher,
struct dr_matcher_rx_tx *nic_matcher,
struct dr_ste *cur_ste,
struct dr_ste *new_ste)
{
new_ste->next_htbl = cur_ste->next_htbl;
new_ste->ste_chain_location = cur_ste->ste_chain_location;
if (!dr_ste_is_last_in_rule(nic_matcher, new_ste->ste_chain_location))
new_ste->next_htbl->pointing_ste = new_ste;
/*
* We need to copy the refcount since this ste
* may have been traversed several times
*/
atomic_init(&new_ste->refcount, atomic_load(&cur_ste->refcount));
/* Link old STEs rule_mem list to the new ste */
dr_rule_update_rule_member(cur_ste, new_ste);
list_head_init(&new_ste->rule_list);
list_append_list(&new_ste->rule_list, &cur_ste->rule_list);
}
static struct dr_ste *dr_rule_rehash_copy_ste(struct mlx5dv_dr_matcher *matcher,
struct dr_matcher_rx_tx *nic_matcher,
struct dr_ste *cur_ste,
struct dr_ste_htbl *new_htbl,
struct list_head *update_list)
{
struct dr_ste_ctx *ste_ctx = matcher->tbl->dmn->ste_ctx;
uint8_t hw_ste[DR_STE_SIZE] = {};
struct dr_ste_send_info *ste_info;
bool use_update_list = false;
struct dr_ste *new_ste;
uint8_t sb_idx;
int new_idx;
/* Copy STE mask from the matcher */
sb_idx = cur_ste->ste_chain_location - 1;
dr_ste_set_bit_mask(hw_ste, nic_matcher->ste_builder[sb_idx].bit_mask);
/* Copy STE control and tag */
memcpy(hw_ste, cur_ste->hw_ste, DR_STE_SIZE_REDUCED);
dr_ste_set_miss_addr(ste_ctx, hw_ste, nic_matcher->e_anchor->chunk->icm_addr);
new_idx = dr_ste_calc_hash_index(hw_ste, new_htbl);
new_ste = &new_htbl->ste_arr[new_idx];
if (dr_ste_not_used_ste(new_ste)) {
dr_htbl_get(new_htbl);
list_add_tail(dr_ste_get_miss_list(new_ste), &new_ste->miss_list_node);
} else {
new_ste = dr_rule_rehash_handle_collision(matcher,
nic_matcher,
update_list,
new_ste,
hw_ste);
if (!new_ste) {
dr_dbg(matcher->tbl->dmn, "Failed adding collision entry, index: %d\n",
new_idx);
return NULL;
}
new_htbl->ctrl.num_of_collisions++;
use_update_list = true;
}
memcpy(new_ste->hw_ste, hw_ste, DR_STE_SIZE_REDUCED);
new_htbl->ctrl.num_of_valid_entries++;
if (use_update_list) {
ste_info = calloc(1, sizeof(*ste_info));
if (!ste_info) {
dr_dbg(matcher->tbl->dmn, "Failed allocating ste_info\n");
errno = ENOMEM;
goto err_exit;
}
dr_send_fill_and_append_ste_send_info(new_ste, DR_STE_SIZE, 0,
hw_ste, ste_info,
update_list, true);
}
dr_rule_rehash_copy_ste_ctrl(matcher, nic_matcher, cur_ste, new_ste);
return new_ste;
err_exit:
dr_ste_free(new_ste, matcher, nic_matcher);
return NULL;
}
static int dr_rule_rehash_copy_miss_list(struct mlx5dv_dr_matcher *matcher,
struct dr_matcher_rx_tx *nic_matcher,
struct list_head *cur_miss_list,
struct dr_ste_htbl *new_htbl,
struct list_head *update_list)
{
struct dr_ste *tmp_ste, *cur_ste, *new_ste;
list_for_each_safe(cur_miss_list, cur_ste, tmp_ste, miss_list_node) {
new_ste = dr_rule_rehash_copy_ste(matcher,
nic_matcher,
cur_ste,
new_htbl,
update_list);
if (!new_ste)
goto err_insert;
list_del(&cur_ste->miss_list_node);
dr_htbl_put(cur_ste->htbl);
}
return 0;
err_insert:
dr_dbg(matcher->tbl->dmn, "Fatal error during resize\n");
assert(false);
return errno;
}
static int dr_rule_rehash_copy_htbl(struct mlx5dv_dr_matcher *matcher,
struct dr_matcher_rx_tx *nic_matcher,
struct dr_ste_htbl *cur_htbl,
struct dr_ste_htbl *new_htbl,
struct list_head *update_list)
{
struct dr_ste *cur_ste;
int cur_entries;
int err = 0;
int i;
cur_entries = dr_icm_pool_chunk_size_to_entries(cur_htbl->chunk_size);
for (i = 0; i < cur_entries; i++) {
cur_ste = &cur_htbl->ste_arr[i];
if (dr_ste_not_used_ste(cur_ste)) /* Empty, nothing to copy */
continue;
err = dr_rule_rehash_copy_miss_list(matcher,
nic_matcher,
dr_ste_get_miss_list(cur_ste),
new_htbl,
update_list);
if (err)
goto clean_copy;
}
clean_copy:
return err;
}
static struct dr_ste_htbl *dr_rule_rehash_htbl(struct mlx5dv_dr_rule *rule,
struct dr_rule_rx_tx *nic_rule,
struct dr_ste_htbl *cur_htbl,
uint8_t ste_location,
struct list_head *update_list,
enum dr_icm_chunk_size new_size)
{
struct dr_matcher_rx_tx *nic_matcher = nic_rule->nic_matcher;
struct dr_domain_rx_tx *nic_dmn = nic_matcher->nic_tbl->nic_dmn;
struct mlx5dv_dr_matcher *matcher = rule->matcher;
struct mlx5dv_dr_domain *dmn = matcher->tbl->dmn;
struct dr_ste_send_info *del_ste_info, *tmp_ste_info;
uint8_t formated_ste[DR_STE_SIZE] = {};
struct dr_ste_send_info *ste_info;
struct dr_htbl_connect_info info;
LIST_HEAD(rehash_table_send_list);
struct dr_ste_htbl *new_htbl;
struct dr_ste *ste_to_update;
int err;
ste_info = calloc(1, sizeof(*ste_info));
if (!ste_info) {
errno = ENOMEM;
return NULL;
}
new_htbl = dr_ste_htbl_alloc(dmn->ste_icm_pool,
new_size,
cur_htbl->lu_type,
cur_htbl->byte_mask);
if (!new_htbl) {
dr_dbg(dmn, "Failed to allocate new hash table\n");
goto free_ste_info;
}
/* Write new table to HW */
info.type = CONNECT_MISS;
info.miss_icm_addr = nic_matcher->e_anchor->chunk->icm_addr;
dr_ste_set_formated_ste(dmn->ste_ctx,
dmn->info.caps.gvmi,
nic_dmn,
new_htbl,
formated_ste, &info);
new_htbl->pointing_ste = cur_htbl->pointing_ste;
new_htbl->pointing_ste->next_htbl = new_htbl;
err = dr_rule_rehash_copy_htbl(matcher,
nic_matcher,
cur_htbl,
new_htbl,
&rehash_table_send_list);
if (err)
goto free_new_htbl;
if (dr_send_postsend_htbl(dmn, new_htbl, formated_ste,
nic_matcher->ste_builder[ste_location - 1].bit_mask)) {
dr_dbg(dmn, "Failed writing table to HW\n");
goto free_new_htbl;
}
/*
* Writing to the hw is done in regular order of rehash_table_send_list,
* in order to have the origin data written before the miss address of
* collision entries, if exists.
*/
if (dr_rule_send_update_list(&rehash_table_send_list, dmn, false)) {
dr_dbg(dmn, "Failed updating table to HW\n");
goto free_ste_list;
}
/* Connect previous hash table to current */
if (ste_location == 1) {
/* The previous table is an anchor, anchors size is always one STE */
struct dr_ste_htbl *prev_htbl = cur_htbl->pointing_ste->htbl;
/* On matcher s_anchor we keep an extra refcount */
dr_htbl_get(new_htbl);
dr_htbl_put(cur_htbl);
nic_matcher->s_htbl = new_htbl;
/*
* It is safe to operate dr_ste_set_hit_addr on the hw_ste here
* (48B len) which works only on first 32B
*/
dr_ste_set_hit_addr(dmn->ste_ctx,
prev_htbl->ste_arr[0].hw_ste,
new_htbl->chunk->icm_addr,
new_htbl->chunk->num_of_entries);
ste_to_update = &prev_htbl->ste_arr[0];
} else {
dr_ste_set_hit_addr_by_next_htbl(dmn->ste_ctx,
cur_htbl->pointing_ste->hw_ste,
new_htbl);
ste_to_update = cur_htbl->pointing_ste;
}
dr_send_fill_and_append_ste_send_info(ste_to_update, DR_STE_SIZE_CTRL,
0, ste_to_update->hw_ste, ste_info,
update_list, false);
return new_htbl;
free_ste_list:
/* Clean all ste_info's from the new table */
list_for_each_safe(&rehash_table_send_list, del_ste_info, tmp_ste_info,
send_list) {
list_del(&del_ste_info->send_list);
free(del_ste_info);
}
free_new_htbl:
dr_ste_htbl_free(new_htbl);
free_ste_info:
free(ste_info);
return NULL;
}
static struct dr_ste_htbl *dr_rule_rehash(struct mlx5dv_dr_rule *rule,
struct dr_rule_rx_tx *nic_rule,
struct dr_ste_htbl *cur_htbl,
uint8_t ste_location,
struct list_head *update_list)
{
struct mlx5dv_dr_domain *dmn = rule->matcher->tbl->dmn;
enum dr_icm_chunk_size new_size;
new_size = dr_icm_next_higher_chunk(cur_htbl->chunk_size);
new_size = min_t(uint32_t, new_size, dmn->info.max_log_sw_icm_sz);
if (new_size == cur_htbl->chunk_size)
return NULL; /* Skip rehash, we already at the max size */
return dr_rule_rehash_htbl(rule, nic_rule, cur_htbl, ste_location,
update_list, new_size);
}
static struct dr_ste *dr_rule_handle_collision(struct mlx5dv_dr_matcher *matcher,
struct dr_matcher_rx_tx *nic_matcher,
struct dr_ste *ste,
uint8_t *hw_ste,
struct list_head *miss_list,
struct list_head *send_list)
{
struct mlx5dv_dr_domain *dmn = matcher->tbl->dmn;
struct dr_ste_ctx *ste_ctx = dmn->ste_ctx;
struct dr_ste_send_info *ste_info;
struct dr_ste *new_ste;
ste_info = calloc(1, sizeof(*ste_info));
if (!ste_info) {
dr_dbg(dmn, "Failed allocating ste_info\n");
errno = ENOMEM;
return NULL;
}
new_ste = dr_rule_create_collision_entry(matcher, nic_matcher, hw_ste, ste);
if (!new_ste) {
dr_dbg(dmn, "Failed creating collision entry\n");
goto free_send_info;
}
if (dr_rule_append_to_miss_list(ste_ctx, new_ste, miss_list, send_list)) {
dr_dbg(dmn, "Failed to update prev miss_list\n");
goto err_exit;
}
dr_send_fill_and_append_ste_send_info(new_ste, DR_STE_SIZE, 0, hw_ste,
ste_info, send_list, false);
ste->htbl->ctrl.num_of_collisions++;
ste->htbl->ctrl.num_of_valid_entries++;
return new_ste;
err_exit:
dr_ste_free(new_ste, matcher, nic_matcher);
free_send_info:
free(ste_info);
return NULL;
}
static void dr_rule_remove_action_members(struct mlx5dv_dr_rule *rule)
{
struct dr_rule_action_member *action_mem;
struct dr_rule_action_member *tmp;
list_for_each_safe(&rule->rule_actions_list, action_mem, tmp, list) {
list_del(&action_mem->list);
atomic_fetch_sub(&action_mem->action->refcount, 1);
free(action_mem);
}
}
static int dr_rule_add_action_members(struct mlx5dv_dr_rule *rule,
size_t num_actions,
struct mlx5dv_dr_action *actions[])
{
struct dr_rule_action_member *action_mem;
int i;
for (i = 0; i < num_actions; i++) {
action_mem = calloc(1, sizeof(*action_mem));
if (!action_mem) {
errno = ENOMEM;
goto free_action_members;
}
action_mem->action = actions[i];
list_node_init(&action_mem->list);
list_add_tail(&rule->rule_actions_list, &action_mem->list);
atomic_fetch_add(&action_mem->action->refcount, 1);
}
return 0;
free_action_members:
dr_rule_remove_action_members(rule);
return errno;
}
/*
* While the pointer of ste is no longer valid, like while moving ste to be
* the first in the miss_list, and to be in the origin table,
* all rule-members that are attached to this ste should update their ste member
* to the new pointer
*/
void dr_rule_update_rule_member(struct dr_ste *ste, struct dr_ste *new_ste)
{
struct dr_rule_member *rule_mem;
list_for_each(&ste->rule_list, rule_mem, use_ste_list)
rule_mem->ste = new_ste;
}
static void dr_rule_clean_rule_members(struct mlx5dv_dr_rule *rule,
struct dr_rule_rx_tx *nic_rule)
{
struct dr_rule_member *rule_mem;
struct dr_rule_member *tmp_mem;
list_for_each_safe(&nic_rule->rule_members_list, rule_mem, tmp_mem, list) {
list_del(&rule_mem->list);
list_del(&rule_mem->use_ste_list);
dr_ste_put(rule_mem->ste, rule->matcher, nic_rule->nic_matcher);
free(rule_mem);
}
}
static uint16_t dr_get_bits_per_mask(uint16_t byte_mask)
{
uint16_t bits = 0;
while (byte_mask) {
byte_mask = byte_mask & (byte_mask - 1);
bits++;
}
return bits;
}
static bool dr_rule_need_enlarge_hash(struct dr_ste_htbl *htbl,
struct mlx5dv_dr_domain *dmn,
struct dr_domain_rx_tx *nic_dmn)
{
struct dr_ste_htbl_ctrl *ctrl = &htbl->ctrl;
if (dmn->info.max_log_sw_icm_sz <= htbl->chunk_size)
return false;
if (!ctrl->may_grow)
return false;
if (dr_get_bits_per_mask(htbl->byte_mask) * CHAR_BIT <= htbl->chunk_size)
return false;
if (ctrl->num_of_collisions >= ctrl->increase_threshold &&
(ctrl->num_of_valid_entries - ctrl->num_of_collisions) >= ctrl->increase_threshold)
return true;
return false;
}
static int dr_rule_add_member(struct dr_rule_rx_tx *nic_rule,
struct dr_ste *ste)
{
struct dr_rule_member *rule_mem;
rule_mem = calloc(1, sizeof(*rule_mem));
if (!rule_mem) {
errno = ENOMEM;
return errno;
}
rule_mem->ste = ste;
list_add_tail(&nic_rule->rule_members_list, &rule_mem->list);
list_add_tail(&ste->rule_list, &rule_mem->use_ste_list);
return 0;
}
static int dr_rule_handle_action_stes(struct mlx5dv_dr_rule *rule,
struct dr_rule_rx_tx *nic_rule,
struct list_head *send_ste_list,
struct dr_ste *last_ste,
uint8_t *hw_ste_arr,
uint32_t new_hw_ste_arr_sz)
{
struct dr_matcher_rx_tx *nic_matcher = nic_rule->nic_matcher;
struct dr_ste_send_info *ste_info_arr[DR_ACTION_MAX_STES];
uint8_t num_of_builders = nic_matcher->num_of_builders;
struct mlx5dv_dr_matcher *matcher = rule->matcher;
uint8_t *curr_hw_ste, *prev_hw_ste;
struct dr_ste *action_ste;
int i, k, ret;
/* Two cases:
* 1. num_of_builders is equal to new_hw_ste_arr_sz, the action in the ste
* 2. num_of_builders is less then new_hw_ste_arr_sz, new ste was added
* to support the action.
*/
if (num_of_builders == new_hw_ste_arr_sz)
return 0;
for (i = num_of_builders, k = 0; i < new_hw_ste_arr_sz; i++, k++) {
curr_hw_ste = hw_ste_arr + i * DR_STE_SIZE;
prev_hw_ste = (i == 0) ? curr_hw_ste : hw_ste_arr + ((i - 1) * DR_STE_SIZE);
action_ste = dr_rule_create_collision_htbl(matcher,
nic_matcher,
curr_hw_ste);
if (!action_ste)
return errno;
dr_ste_get(action_ste);
/* While free ste we go over the miss list, so add this ste to the list */
list_add_tail(dr_ste_get_miss_list(action_ste),
&action_ste->miss_list_node);
ste_info_arr[k] = calloc(1, sizeof(struct dr_ste_send_info));
if (!ste_info_arr[k]) {
dr_dbg(matcher->tbl->dmn, "Failed allocate ste_info, k: %d\n", k);
errno = ENOMEM;
ret = errno;
goto err_exit;
}
/* Point current ste to the new action */
dr_ste_set_hit_addr_by_next_htbl(matcher->tbl->dmn->ste_ctx,
prev_hw_ste, action_ste->htbl);
ret = dr_rule_add_member(nic_rule, action_ste);
if (ret) {
dr_dbg(matcher->tbl->dmn, "Failed adding rule member\n");
goto free_ste_info;
}
dr_send_fill_and_append_ste_send_info(action_ste, DR_STE_SIZE, 0,
curr_hw_ste,
ste_info_arr[k],
send_ste_list, false);
}
return 0;
free_ste_info:
free(ste_info_arr[k]);
err_exit:
dr_ste_put(action_ste, matcher, nic_matcher);
return ret;
}
static int dr_rule_handle_empty_entry(struct mlx5dv_dr_matcher *matcher,
struct dr_matcher_rx_tx *nic_matcher,
struct dr_ste_htbl *cur_htbl,
struct dr_ste *ste,
uint8_t ste_location,
uint8_t *hw_ste,
struct list_head *miss_list,
struct list_head *send_list)
{
struct dr_ste_ctx *ste_ctx = matcher->tbl->dmn->ste_ctx;
struct dr_ste_send_info *ste_info;
/* Take ref on table, only on first time this ste is used */
dr_htbl_get(cur_htbl);
/* new entry -> new branch */
list_add_tail(miss_list, &ste->miss_list_node);
dr_ste_set_miss_addr(ste_ctx, hw_ste, nic_matcher->e_anchor->chunk->icm_addr);
ste->ste_chain_location = ste_location;
ste_info = calloc(1, sizeof(*ste_info));
if (!ste_info) {
dr_dbg(matcher->tbl->dmn, "Failed allocating ste_info\n");
errno = ENOMEM;
goto clean_ste_setting;
}
if (dr_ste_create_next_htbl(matcher,
nic_matcher,
ste,
hw_ste,
DR_CHUNK_SIZE_1)) {
dr_dbg(matcher->tbl->dmn, "Failed allocating table\n");
goto clean_ste_info;
}
cur_htbl->ctrl.num_of_valid_entries++;
dr_send_fill_and_append_ste_send_info(ste, DR_STE_SIZE, 0, hw_ste,
ste_info, send_list, false);
return 0;
clean_ste_info:
free(ste_info);
clean_ste_setting:
list_del_init(&ste->miss_list_node);
dr_htbl_put(cur_htbl);
return ENOMEM;
}
static struct dr_ste *dr_rule_handle_ste_branch(struct mlx5dv_dr_rule *rule,
struct dr_rule_rx_tx *nic_rule,
struct list_head *send_ste_list,
struct dr_ste_htbl *cur_htbl,
uint8_t *hw_ste,
uint8_t ste_location,
struct dr_ste_htbl **put_htbl)
{
struct dr_matcher_rx_tx *nic_matcher = nic_rule->nic_matcher;
struct dr_domain_rx_tx *nic_dmn = nic_matcher->nic_tbl->nic_dmn;
struct mlx5dv_dr_matcher *matcher = rule->matcher;
struct mlx5dv_dr_domain *dmn = matcher->tbl->dmn;
struct dr_ste_htbl *new_htbl;
struct list_head *miss_list;
struct dr_ste *matched_ste;
bool skip_rehash = false;
struct dr_ste *ste;
int index;
again:
index = dr_ste_calc_hash_index(hw_ste, cur_htbl);
miss_list = &cur_htbl->chunk->miss_list[index];
ste = &cur_htbl->ste_arr[index];
if (dr_ste_not_used_ste(ste)) {
if (dr_rule_handle_empty_entry(matcher, nic_matcher, cur_htbl,
ste, ste_location,
hw_ste, miss_list,
send_ste_list))
return NULL;
} else {
/* Hash table index in use, check if this ste is in the miss list */
matched_ste = dr_rule_find_ste_in_miss_list(miss_list, hw_ste);
if (matched_ste) {
/*
* if it is last STE in the chain, and has the same tag
* it means that all the previous stes are the same,
* if so, this rule is duplicated.
*/
if (!dr_ste_is_last_in_rule(nic_matcher, ste_location))
return matched_ste;
dr_dbg(dmn, "Duplicate rule inserted\n");
}
if (!skip_rehash && dr_rule_need_enlarge_hash(cur_htbl, dmn, nic_dmn)) {
/* Hash table index in use, try to resize of the hash */
skip_rehash = true;
/*
* Hold the table till we update.
* Release in dr_rule_create_rule_nr()
*/
*put_htbl = cur_htbl;
dr_htbl_get(cur_htbl);
new_htbl = dr_rule_rehash(rule, nic_rule, cur_htbl,
ste_location, send_ste_list);
if (!new_htbl) {
dr_htbl_put(cur_htbl);
dr_dbg(dmn, "Failed creating rehash table, htbl-log_size: %d\n",
cur_htbl->chunk_size);
} else {
cur_htbl = new_htbl;
}
goto again;
} else {
/* Hash table index in use, add another collision (miss) */
ste = dr_rule_handle_collision(matcher,
nic_matcher,
ste,
hw_ste,
miss_list,
send_ste_list);
if (!ste) {
dr_dbg(dmn, "Failed adding collision entry, index: %d\n",
index);
return NULL;
}
}
}
return ste;
}
static bool dr_rule_cmp_value_to_mask(uint8_t *mask, uint8_t *value,
uint32_t s_idx, uint32_t e_idx)
{
uint32_t i;
for (i = s_idx; i < e_idx; i++) {
if (value[i] & ~mask[i]) {
errno = EINVAL;
return false;
}
}
return true;
}
static bool dr_rule_verify(struct mlx5dv_dr_matcher *matcher,
struct mlx5dv_flow_match_parameters *value,
struct dr_match_param *param)
{
uint8_t match_criteria = matcher->match_criteria;
struct mlx5dv_dr_domain *dmn = matcher->tbl->dmn;
uint8_t *mask_p = (uint8_t *)&matcher->mask;
uint8_t *param_p = (uint8_t *)param;
size_t value_size = value->match_sz;
uint32_t s_idx, e_idx;
if (!value_size ||
(value_size > sizeof(struct dr_match_param) ||
(value_size % sizeof(uint32_t)))) {
dr_dbg(dmn, "Rule parameters length is incorrect\n");
errno = EINVAL;
return false;
}
dr_ste_copy_param(matcher->match_criteria, param, value);
if (match_criteria & DR_MATCHER_CRITERIA_OUTER) {
s_idx = offsetof(struct dr_match_param, outer);
e_idx = min(s_idx + sizeof(param->outer), value_size);
if (!dr_rule_cmp_value_to_mask(mask_p, param_p, s_idx, e_idx)) {
dr_dbg(dmn, "Rule outer parameters contains a value not specified by mask\n");
return false;
}
}
if (match_criteria & DR_MATCHER_CRITERIA_MISC) {
s_idx = offsetof(struct dr_match_param, misc);
e_idx = min(s_idx + sizeof(param->misc), value_size);
if (!dr_rule_cmp_value_to_mask(mask_p, param_p, s_idx, e_idx)) {
dr_dbg(dmn, "Rule misc parameters contains a value not specified by mask\n");
return false;
}
}
if (match_criteria & DR_MATCHER_CRITERIA_INNER) {
s_idx = offsetof(struct dr_match_param, inner);
e_idx = min(s_idx + sizeof(param->inner), value_size);
if (!dr_rule_cmp_value_to_mask(mask_p, param_p, s_idx, e_idx)) {
dr_dbg(dmn, "Rule inner parameters contains a value not specified by mask\n");
return false;
}
}
if (match_criteria & DR_MATCHER_CRITERIA_MISC2) {
s_idx = offsetof(struct dr_match_param, misc2);
e_idx = min(s_idx + sizeof(param->misc2), value_size);
if (!dr_rule_cmp_value_to_mask(mask_p, param_p, s_idx, e_idx)) {
dr_dbg(dmn, "Rule misc2 parameters contains a value not specified by mask\n");
return false;
}
}
if (match_criteria & DR_MATCHER_CRITERIA_MISC3) {
s_idx = offsetof(struct dr_match_param, misc3);
e_idx = min(s_idx + sizeof(param->misc3), value_size);
if (!dr_rule_cmp_value_to_mask(mask_p, param_p, s_idx, e_idx)) {
dr_dbg(dmn, "Rule misc3 parameters contains a value not specified by mask\n");
return false;
}
}
return true;
}
static int dr_rule_destroy_rule_nic(struct mlx5dv_dr_rule *rule,
struct dr_rule_rx_tx *nic_rule)
{
dr_rule_clean_rule_members(rule, nic_rule);
return 0;
}
static int dr_rule_destroy_rule_fdb(struct mlx5dv_dr_rule *rule)
{
dr_rule_destroy_rule_nic(rule, &rule->rx);
dr_rule_destroy_rule_nic(rule, &rule->tx);
return 0;
}
static int dr_rule_destroy_rule(struct mlx5dv_dr_rule *rule)
{
struct mlx5dv_dr_domain *dmn = rule->matcher->tbl->dmn;
switch (dmn->type) {
case MLX5DV_DR_DOMAIN_TYPE_NIC_RX:
dr_rule_destroy_rule_nic(rule, &rule->rx);
break;
case MLX5DV_DR_DOMAIN_TYPE_NIC_TX:
dr_rule_destroy_rule_nic(rule, &rule->tx);
break;
case MLX5DV_DR_DOMAIN_TYPE_FDB:
dr_rule_destroy_rule_fdb(rule);
break;
default:
errno = EINVAL;
return errno;
}
dr_rule_remove_action_members(rule);
list_del(&rule->rule_list);
free(rule);
return 0;
}
static int dr_rule_destroy_rule_root(struct mlx5dv_dr_rule *rule)
{
int ret;
ret = ibv_destroy_flow(rule->flow);
if (ret)
return ret;
dr_rule_remove_action_members(rule);
free(rule);
return 0;
}
static int dr_rule_skip(struct mlx5dv_dr_domain *dmn,
enum dr_ste_entry_type ste_type,
struct dr_match_param *mask,
struct dr_match_param *value)
{
if (dmn->type == MLX5DV_DR_DOMAIN_TYPE_FDB) {
if (mask->misc.source_port) {
if (ste_type == DR_STE_TYPE_RX)
if (value->misc.source_port != WIRE_PORT)
return 1;
if (ste_type == DR_STE_TYPE_TX)
if (value->misc.source_port == WIRE_PORT)
return 1;
}
/* Metadata C can be used to describe the source vport */
if (mask->misc2.metadata_reg_c_0) {
struct dr_devx_vport_cap *vport_cap;
uint32_t vport_metadata_c;
vport_cap = dr_get_vport_cap(&dmn->info.caps, WIRE_PORT);
if (!vport_cap || !vport_cap->valid)
return 0;
vport_metadata_c = value->misc2.metadata_reg_c_0
& vport_cap->metadata_c_mask;
if (ste_type == DR_STE_TYPE_RX)
if (vport_metadata_c != vport_cap->metadata_c)
return 1;
if (ste_type == DR_STE_TYPE_TX)
if (vport_metadata_c == vport_cap->metadata_c)
return 1;
}
}
return 0;
}
static int
dr_rule_create_rule_nic(struct mlx5dv_dr_rule *rule,
struct dr_rule_rx_tx *nic_rule,
struct dr_match_param *param,
size_t num_actions,
struct mlx5dv_dr_action *actions[])
{
uint8_t hw_ste_arr[DR_RULE_MAX_STE_CHAIN * DR_STE_SIZE] = {};
struct dr_matcher_rx_tx *nic_matcher = nic_rule->nic_matcher;
struct dr_domain_rx_tx *nic_dmn = nic_matcher->nic_tbl->nic_dmn;
struct mlx5dv_dr_matcher *matcher = rule->matcher;
struct mlx5dv_dr_domain *dmn = matcher->tbl->dmn;
struct dr_ste_send_info *ste_info, *tmp_ste_info;
struct dr_ste_htbl *htbl = NULL;
struct dr_ste_htbl *cur_htbl;
uint32_t new_hw_ste_arr_sz;
LIST_HEAD(send_ste_list);
struct dr_ste *ste = NULL; /* Fix compilation warning */
int ret, i;
list_head_init(&nic_rule->rule_members_list);
if (dr_rule_skip(dmn, nic_dmn->ste_type, &matcher->mask, param))
return 0;
/* Set the tag values inside the ste array */
ret = dr_ste_build_ste_arr(matcher, nic_matcher, param, hw_ste_arr);
if (ret)
goto out_err;
/* Set the actions values/addresses inside the ste array */
ret = dr_actions_build_ste_arr(matcher, nic_matcher, actions,
num_actions, hw_ste_arr,
&new_hw_ste_arr_sz);
if (ret)
goto out_err;
cur_htbl = nic_matcher->s_htbl;
/*
* Go over the array of STEs, and build dr_ste accordingly.
* The loop is over only the builders which are equeal or less to the
* number of stes, in case we have actions that lives in other stes.
*/
for (i = 0; i < nic_matcher->num_of_builders; i++) {
/* Calculate CRC and keep new ste entry */
uint8_t *cur_hw_ste_ent = hw_ste_arr + (i * DR_STE_SIZE);
ste = dr_rule_handle_ste_branch(rule,
nic_rule,
&send_ste_list,
cur_htbl,
cur_hw_ste_ent,
i + 1,
&htbl);
if (!ste) {
dr_dbg(dmn, "Failed creating next branch\n");
ret = errno;
goto free_rule;
}
cur_htbl = ste->next_htbl;
/* Keep all STEs in the rule struct */
ret = dr_rule_add_member(nic_rule, ste);
if (ret) {
dr_dbg(dmn, "Failed adding rule member index %d\n", i);
goto free_ste;
}
dr_ste_get(ste);
}
/* Connect actions */
ret = dr_rule_handle_action_stes(rule, nic_rule, &send_ste_list,
ste, hw_ste_arr, new_hw_ste_arr_sz);
if (ret) {
dr_dbg(dmn, "Failed apply actions\n");
goto free_rule;
}
ret = dr_rule_send_update_list(&send_ste_list, dmn, true);
if (ret) {
dr_dbg(dmn, "Failed sending ste!\n");
goto free_rule;
}
if (htbl)
dr_htbl_put(htbl);
return 0;
free_ste:
dr_ste_put(ste, matcher, nic_matcher);
free_rule:
dr_rule_clean_rule_members(rule, nic_rule);
/* Clean all ste_info's */
list_for_each_safe(&send_ste_list, ste_info, tmp_ste_info, send_list) {
list_del(&ste_info->send_list);
free(ste_info);
}
out_err:
return ret;
}
static int
dr_rule_create_rule_fdb(struct mlx5dv_dr_rule *rule,
struct dr_match_param *param,
size_t num_actions,
struct mlx5dv_dr_action *actions[])
{
struct dr_match_param copy_param = {};
int ret;
/*
* Copy match_param since they will be consumed during the first
* nic_rule insertion.
*/
memcpy(©_param, param, sizeof(struct dr_match_param));
ret = dr_rule_create_rule_nic(rule, &rule->rx, param,
num_actions, actions);
if (ret)
return ret;
ret = dr_rule_create_rule_nic(rule, &rule->tx, ©_param,
num_actions, actions);
if (ret)
goto destroy_rule_nic_rx;
return 0;
destroy_rule_nic_rx:
dr_rule_destroy_rule_nic(rule, &rule->rx);
return ret;
}
static struct mlx5dv_dr_rule *
dr_rule_create_rule(struct mlx5dv_dr_matcher *matcher,
struct mlx5dv_flow_match_parameters *value,
size_t num_actions,
struct mlx5dv_dr_action *actions[])
{
struct mlx5dv_dr_domain *dmn = matcher->tbl->dmn;
struct dr_match_param param = {};
struct mlx5dv_dr_rule *rule;
int ret;
if (!dr_rule_verify(matcher, value, ¶m))
return NULL;
rule = calloc(1, sizeof(*rule));
if (!rule) {
errno = ENOMEM;
return NULL;
}
rule->matcher = matcher;
list_head_init(&rule->rule_actions_list);
list_node_init(&rule->rule_list);
ret = dr_rule_add_action_members(rule, num_actions, actions);
if (ret)
goto free_rule;
switch (dmn->type) {
case MLX5DV_DR_DOMAIN_TYPE_NIC_RX:
rule->rx.nic_matcher = &matcher->rx;
ret = dr_rule_create_rule_nic(rule, &rule->rx, ¶m,
num_actions, actions);
break;
case MLX5DV_DR_DOMAIN_TYPE_NIC_TX:
rule->tx.nic_matcher = &matcher->tx;
ret = dr_rule_create_rule_nic(rule, &rule->tx, ¶m,
num_actions, actions);
break;
case MLX5DV_DR_DOMAIN_TYPE_FDB:
rule->rx.nic_matcher = &matcher->rx;
rule->tx.nic_matcher = &matcher->tx;
ret = dr_rule_create_rule_fdb(rule, ¶m,
num_actions, actions);
break;
default:
ret = EINVAL;
errno = ret;
break;
}
if (ret)
goto remove_action_members;
list_add_tail(&matcher->rule_list, &rule->rule_list);
return rule;
remove_action_members:
dr_rule_remove_action_members(rule);
free_rule:
free(rule);
return NULL;
}
static struct mlx5dv_dr_rule *
dr_rule_create_rule_root(struct mlx5dv_dr_matcher *matcher,
struct mlx5dv_flow_match_parameters *value,
size_t num_actions,
struct mlx5dv_dr_action *actions[])
{
struct mlx5dv_flow_action_attr *attr;
struct mlx5_flow_action_attr_aux *attr_aux;
struct mlx5dv_dr_rule *rule;
int ret;
rule = calloc(1, sizeof(*rule));
if (!rule) {
errno = ENOMEM;
return NULL;
}
rule->matcher = matcher;
list_head_init(&rule->rule_actions_list);
attr = calloc(num_actions, sizeof(*attr));
if (!attr) {
errno = ENOMEM;
goto free_rule;
}
attr_aux = calloc(num_actions, sizeof(*attr_aux));
if (!attr_aux) {
errno = ENOMEM;
goto free_attr;
}
ret = dr_actions_build_attr(matcher, actions, num_actions, attr, attr_aux);
if (ret)
goto free_attr_aux;
ret = dr_rule_add_action_members(rule, num_actions, actions);
if (ret)
goto free_attr_aux;
rule->flow = __mlx5dv_create_flow(matcher->dv_matcher,
value,
num_actions,
attr,
attr_aux);
if (!rule->flow)
goto remove_action_members;
free(attr);
free(attr_aux);
return rule;
remove_action_members:
dr_rule_remove_action_members(rule);
free_attr_aux:
free(attr_aux);
free_attr:
free(attr);
free_rule:
free(rule);
return NULL;
}
struct mlx5dv_dr_rule *mlx5dv_dr_rule_create(struct mlx5dv_dr_matcher *matcher,
struct mlx5dv_flow_match_parameters *value,
size_t num_actions,
struct mlx5dv_dr_action *actions[])
{
struct mlx5dv_dr_rule *rule;
pthread_mutex_lock(&matcher->tbl->dmn->mutex);
atomic_fetch_add(&matcher->refcount, 1);
if (dr_is_root_table(matcher->tbl))
rule = dr_rule_create_rule_root(matcher, value, num_actions, actions);
else
rule = dr_rule_create_rule(matcher, value, num_actions, actions);
if (!rule)
atomic_fetch_sub(&matcher->refcount, 1);
pthread_mutex_unlock(&matcher->tbl->dmn->mutex);
return rule;
}
int mlx5dv_dr_rule_destroy(struct mlx5dv_dr_rule *rule)
{
struct mlx5dv_dr_matcher *matcher = rule->matcher;
struct mlx5dv_dr_table *tbl = rule->matcher->tbl;
int ret;
pthread_mutex_lock(&tbl->dmn->mutex);
if (dr_is_root_table(tbl))
ret = dr_rule_destroy_rule_root(rule);
else
ret = dr_rule_destroy_rule(rule);
pthread_mutex_unlock(&tbl->dmn->mutex);
if (!ret)
atomic_fetch_sub(&matcher->refcount, 1);
return ret;
}
| 26.78447 | 88 | 0.715815 |
f1a6902d1b8e90a3a060d0087b0c149a80e1e273 | 1,345 | c | C | PSU_my_sokoban_2017/game_loop.c | ltabis/epitech-projects | e38b3f00a4ac44c969d5e4880cd65084dc2c870a | [
"MIT"
] | null | null | null | PSU_my_sokoban_2017/game_loop.c | ltabis/epitech-projects | e38b3f00a4ac44c969d5e4880cd65084dc2c870a | [
"MIT"
] | null | null | null | PSU_my_sokoban_2017/game_loop.c | ltabis/epitech-projects | e38b3f00a4ac44c969d5e4880cd65084dc2c870a | [
"MIT"
] | 1 | 2021-01-07T17:41:14.000Z | 2021-01-07T17:41:14.000Z | /*
** EPITECH PROJECT, 2017
** game_loop.c
** File description:
** game loop for my_sokoban project
*/
#include <ncurses.h>
#include <unistd.h>
#include <stdlib.h>
#include "include/my.h"
#include "include/proto.h"
void game_loop(map_t *map)
{
int input = 0;
map =setup_window(map);
map = put_targ_coords(map);
while (input != 27) {
input = wgetch(stdscr);
map = compute_gameplay(map, input);
verify_window_size(map);
if (map->boxes_stuck >= map->boxes)
display_game_loose(map);
verify_score(map);
werase(stdscr);
display_game(map);
refresh();
}
endwin();
}
void display_game(map_t *map)
{
for (int i = 0; i < map->y; i++)
mvprintw(i, 0, map->x_file[i]);
}
void display_game_win(map_t *map)
{
for (int i = 0; i < map->y - 1; i++)
free(map->x_file[i]);
for (int i = 0; i < map->y - 1; i++)
free(map->x_file_save[i]);
free(map->x_file);
free(map->x_file_save);
free(map);
refresh();
endwin();
exit(0);
}
map_t *setup_window(map_t *map)
{
initscr();
noecho();
keypad(stdscr, TRUE);
curs_set(0);
werase(stdscr);
display_game(map);
refresh();
return (map);
}
void verify_window_size(map_t *map)
{
int x = 0;
int y = 0;
char str[] = "The window is too small !";
while (y <= map->y || x <= map->x) {
getmaxyx(stdscr, y, x);
werase(stdscr);
mvprintw(y / 2, x / 2, str);
refresh();
}
}
| 17.24359 | 42 | 0.623792 |
7d6be0d938b924dd050196a2735b6669980bcfbe | 58,556 | c | C | hihope_neptune-oh_hid/00_src/v0.1/device/winnermicro/neptune/sdk_liteos/src/bt/host/stack/l2cap/l2c_ble.c | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | 1 | 2022-02-15T08:51:55.000Z | 2022-02-15T08:51:55.000Z | hihope_neptune-oh_hid/00_src/v0.3/device/winnermicro/neptune/sdk_liteos/src/bt/host/stack/l2cap/l2c_ble.c | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | hihope_neptune-oh_hid/00_src/v0.3/device/winnermicro/neptune/sdk_liteos/src/bt/host/stack/l2cap/l2c_ble.c | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
*
* Copyright (C) 2009-2012 Broadcom 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.
*
******************************************************************************/
/******************************************************************************
*
* this file contains functions relating to BLE management.
*
******************************************************************************/
#include <string.h>
#include "bt_target.h"
#include "bt_utils.h"
#include "l2cdefs.h"
#include "l2c_int.h"
#include "btu.h"
#include "btm_int.h"
#include "hcimsgs.h"
#include "bdaddr.h"
#if (BLE_INCLUDED == TRUE)
#ifdef USE_ALARM
extern fixed_queue_t *btu_general_alarm_queue;
#endif
static void l2cble_start_conn_update(tL2C_LCB *p_lcb);
/*******************************************************************************
**
** Function L2CA_CancelBleConnectReq
**
** Description Cancel a pending connection attempt to a BLE device.
**
** Parameters: BD Address of remote
**
** Return value: TRUE if connection was cancelled
**
*******************************************************************************/
uint8_t L2CA_CancelBleConnectReq(BD_ADDR rem_bda)
{
tL2C_LCB *p_lcb;
/* There can be only one BLE connection request outstanding at a time */
if(btm_ble_get_conn_st() == BLE_CONN_IDLE)
{
L2CAP_TRACE_WARNING("L2CA_CancelBleConnectReq - no connection pending");
return(FALSE);
}
if(memcmp(rem_bda, l2cb.ble_connecting_bda, BD_ADDR_LEN))
{
L2CAP_TRACE_WARNING("L2CA_CancelBleConnectReq - different BDA Connecting: %08x%04x Cancel: %08x%04x",
(l2cb.ble_connecting_bda[0] << 24) + (l2cb.ble_connecting_bda[1] << 16) + (l2cb.ble_connecting_bda[2] << 8) + l2cb.ble_connecting_bda[3],
(l2cb.ble_connecting_bda[4] << 8) + l2cb.ble_connecting_bda[5],
(rem_bda[0] << 24) + (rem_bda[1] << 16) + (rem_bda[2] << 8) + rem_bda[3], (rem_bda[4] << 8) + rem_bda[5]);
return(FALSE);
}
if(btsnd_hcic_ble_create_conn_cancel())
{
p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE);
/* Do not remove lcb if an LE link is already up as a peripheral */
if(p_lcb != NULL &&
!(p_lcb->link_role == HCI_ROLE_SLAVE && BTM_ACL_IS_CONNECTED(rem_bda)))
{
p_lcb->disc_reason = L2CAP_CONN_CANCEL;
l2cu_release_lcb(p_lcb);
}
/* update state to be cancel, wait for connection cancel complete */
btm_ble_set_conn_st(BLE_CONN_CANCEL);
return(TRUE);
}
else
{
return(FALSE);
}
}
/*******************************************************************************
**
** Function L2CA_UpdateBleConnParams
**
** Description Update BLE connection parameters.
**
** Parameters: BD Address of remote
**
** Return value: TRUE if update started
**
*******************************************************************************/
uint8_t L2CA_UpdateBleConnParams(BD_ADDR rem_bda, uint16_t min_int, uint16_t max_int,
uint16_t latency, uint16_t timeout)
{
tL2C_LCB *p_lcb;
tACL_CONN *p_acl_cb = btm_bda_to_acl(rem_bda, BT_TRANSPORT_LE);
/* See if we have a link control block for the remote device */
p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE);
/* If we don't have one, create one and accept the connection. */
if(!p_lcb || !p_acl_cb)
{
L2CAP_TRACE_WARNING("L2CA_UpdateBleConnParams - unknown BD_ADDR %08x%04x",
(rem_bda[0] << 24) + (rem_bda[1] << 16) + (rem_bda[2] << 8) + rem_bda[3],
(rem_bda[4] << 8) + rem_bda[5]);
return(FALSE);
}
if(p_lcb->transport != BT_TRANSPORT_LE)
{
L2CAP_TRACE_WARNING("L2CA_UpdateBleConnParams - BD_ADDR %08x%04x not LE",
(rem_bda[0] << 24) + (rem_bda[1] << 16) + (rem_bda[2] << 8) + rem_bda[3],
(rem_bda[4] << 8) + rem_bda[5]);
return(FALSE);
}
p_lcb->min_interval = min_int;
p_lcb->max_interval = max_int;
p_lcb->latency = latency;
p_lcb->timeout = timeout;
p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM;
l2cble_start_conn_update(p_lcb);
return(TRUE);
}
/*******************************************************************************
**
** Function L2CA_EnableUpdateBleConnParams
**
** Description Enable or disable update based on the request from the peer
**
** Parameters: BD Address of remote
**
** Return value: TRUE if update started
**
*******************************************************************************/
uint8_t L2CA_EnableUpdateBleConnParams(BD_ADDR rem_bda, uint8_t enable)
{
#ifdef PTS_CHECK
if(stack_config_get_interface()->get_pts_conn_updates_disabled())
{
return false;
}
#endif
tL2C_LCB *p_lcb;
/* See if we have a link control block for the remote device */
p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE);
if(!p_lcb)
{
L2CAP_TRACE_WARNING("L2CA_EnableUpdateBleConnParams - unknown BD_ADDR %08x%04x",
(rem_bda[0] << 24) + (rem_bda[1] << 16) + (rem_bda[2] << 8) + rem_bda[3],
(rem_bda[4] << 8) + rem_bda[5]);
return (FALSE);
}
L2CAP_TRACE_API("%s - BD_ADDR %08x%04x enable %d current upd state 0x%02x", __FUNCTION__,
(rem_bda[0] << 24) + (rem_bda[1] << 16) + (rem_bda[2] << 8) + rem_bda[3],
(rem_bda[4] << 8) + rem_bda[5], enable, p_lcb->conn_update_mask);
if(p_lcb->transport != BT_TRANSPORT_LE)
{
L2CAP_TRACE_WARNING("%s - BD_ADDR %08x%04x not LE (link role %d)", __FUNCTION__,
(rem_bda[0] << 24) + (rem_bda[1] << 16) + (rem_bda[2] << 8) + rem_bda[3],
(rem_bda[4] << 8) + rem_bda[5], p_lcb->link_role);
return (FALSE);
}
if(enable)
{
p_lcb->conn_update_mask &= ~L2C_BLE_CONN_UPDATE_DISABLE;
}
else
{
p_lcb->conn_update_mask |= L2C_BLE_CONN_UPDATE_DISABLE;
}
l2cble_start_conn_update(p_lcb);
return (TRUE);
}
/*******************************************************************************
**
** Function L2CA_GetBleConnRole
**
** Description This function returns the connection role.
**
** Returns link role.
**
*******************************************************************************/
uint8_t L2CA_GetBleConnRole(BD_ADDR bd_addr)
{
uint8_t role = HCI_ROLE_UNKNOWN;
tL2C_LCB *p_lcb;
if((p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_LE)) != NULL)
{
role = p_lcb->link_role;
}
return role;
}
/*******************************************************************************
**
** Function L2CA_GetDisconnectReason
**
** Description This function returns the disconnect reason code.
**
** Returns disconnect reason
**
*******************************************************************************/
uint16_t L2CA_GetDisconnectReason(BD_ADDR remote_bda, tBT_TRANSPORT transport)
{
tL2C_LCB *p_lcb;
uint16_t reason = 0;
if((p_lcb = l2cu_find_lcb_by_bd_addr(remote_bda, transport)) != NULL)
{
reason = p_lcb->disc_reason;
}
L2CAP_TRACE_DEBUG("L2CA_GetDisconnectReason=%d ", reason);
return reason;
}
void l2cble_use_preferred_conn_params(BD_ADDR bda)
{
tL2C_LCB *p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE);
tBTM_SEC_DEV_REC *p_dev_rec = btm_find_or_alloc_dev(bda);
/* If there are any preferred connection parameters, set them now */
if((p_dev_rec->conn_params.min_conn_int >= BTM_BLE_CONN_INT_MIN) &&
(p_dev_rec->conn_params.min_conn_int <= BTM_BLE_CONN_INT_MAX) &&
(p_dev_rec->conn_params.max_conn_int >= BTM_BLE_CONN_INT_MIN) &&
(p_dev_rec->conn_params.max_conn_int <= BTM_BLE_CONN_INT_MAX) &&
(p_dev_rec->conn_params.slave_latency <= BTM_BLE_CONN_LATENCY_MAX) &&
(p_dev_rec->conn_params.supervision_tout >= BTM_BLE_CONN_SUP_TOUT_MIN) &&
(p_dev_rec->conn_params.supervision_tout <= BTM_BLE_CONN_SUP_TOUT_MAX) &&
((p_lcb->min_interval < p_dev_rec->conn_params.min_conn_int &&
p_dev_rec->conn_params.min_conn_int != BTM_BLE_CONN_PARAM_UNDEF) ||
(p_lcb->min_interval > p_dev_rec->conn_params.max_conn_int) ||
(p_lcb->latency > p_dev_rec->conn_params.slave_latency) ||
(p_lcb->timeout > p_dev_rec->conn_params.supervision_tout)))
{
L2CAP_TRACE_DEBUG("%s: HANDLE=%d min_conn_int=%d max_conn_int=%d slave_latency=%d supervision_tout=%d", __func__,
p_lcb->handle, p_dev_rec->conn_params.min_conn_int, p_dev_rec->conn_params.max_conn_int,
p_dev_rec->conn_params.slave_latency, p_dev_rec->conn_params.supervision_tout);
p_lcb->min_interval = p_dev_rec->conn_params.min_conn_int;
p_lcb->max_interval = p_dev_rec->conn_params.max_conn_int;
p_lcb->timeout = p_dev_rec->conn_params.supervision_tout;
p_lcb->latency = p_dev_rec->conn_params.slave_latency;
btsnd_hcic_ble_upd_ll_conn_params(p_lcb->handle,
p_dev_rec->conn_params.min_conn_int,
p_dev_rec->conn_params.max_conn_int,
p_dev_rec->conn_params.slave_latency,
p_dev_rec->conn_params.supervision_tout,
0, 0);
}
}
/*******************************************************************************
**
** Function l2cble_notify_le_connection
**
** Description This function notifiy the l2cap connection to the app layer
**
** Returns none
**
*******************************************************************************/
void l2cble_notify_le_connection(BD_ADDR bda)
{
tL2C_LCB *p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE);
tACL_CONN *p_acl = btm_bda_to_acl(bda, BT_TRANSPORT_LE) ;
tL2C_CCB *p_ccb;
if(p_lcb != NULL && p_acl != NULL && p_lcb->link_state != LST_CONNECTED)
{
/* update link status */
btm_establish_continue(p_acl);
/* update l2cap link status and send callback */
p_lcb->link_state = LST_CONNECTED;
l2cu_process_fixed_chnl_resp(p_lcb);
}
/* For all channels, send the event through their FSMs */
for(p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb)
{
if(p_ccb->chnl_state == CST_CLOSED)
{
l2c_csm_execute(p_ccb, L2CEVT_LP_CONNECT_CFM, NULL);
}
}
l2cble_use_preferred_conn_params(bda);
}
/*******************************************************************************
**
** Function l2cble_scanner_conn_comp
**
** Description This function is called when an HCI Connection Complete
** event is received while we are a scanner (so we are master).
**
** Returns void
**
*******************************************************************************/
void l2cble_scanner_conn_comp(uint16_t handle, BD_ADDR bda, tBLE_ADDR_TYPE type,
uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout)
{
tL2C_LCB *p_lcb;
tBTM_SEC_DEV_REC *p_dev_rec = btm_find_or_alloc_dev(bda);
L2CAP_TRACE_DEBUG("l2cble_scanner_conn_comp: HANDLE=%d addr_type=%d conn_interval=%d slave_latency=%d supervision_tout=%d",
handle, type, conn_interval, conn_latency, conn_timeout);
l2cb.is_ble_connecting = FALSE;
/* See if we have a link control block for the remote device */
p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE);
/* If we don't have one, create one. this is auto connection complete. */
if(!p_lcb)
{
p_lcb = l2cu_allocate_lcb(bda, FALSE, BT_TRANSPORT_LE);
if(!p_lcb)
{
btm_sec_disconnect(handle, HCI_ERR_NO_CONNECTION);
L2CAP_TRACE_ERROR("l2cble_scanner_conn_comp - failed to allocate LCB");
return;
}
else
{
if(!l2cu_initialize_fixed_ccb(p_lcb, L2CAP_ATT_CID, &l2cb.fixed_reg[L2CAP_ATT_CID - L2CAP_FIRST_FIXED_CHNL].fixed_chnl_opts))
{
btm_sec_disconnect(handle, HCI_ERR_NO_CONNECTION);
L2CAP_TRACE_WARNING("l2cble_scanner_conn_comp - LCB but no CCB");
return ;
}
}
}
else
if(p_lcb->link_state != LST_CONNECTING)
{
L2CAP_TRACE_ERROR("L2CAP got BLE scanner conn_comp in bad state: %d", p_lcb->link_state);
return;
}
#ifdef USE_ALARM
alarm_cancel(p_lcb->l2c_lcb_timer);
#else
btu_stop_timer(&p_lcb->l2c_lcb_timer);
#endif
/* Save the handle */
p_lcb->handle = handle;
/* Connected OK. Change state to connected, we were scanning so we are master */
p_lcb->link_role = HCI_ROLE_MASTER;
p_lcb->transport = BT_TRANSPORT_LE;
/* update link parameter, set slave link as non-spec default upon link up */
p_lcb->min_interval = p_lcb->max_interval = conn_interval;
p_lcb->timeout = conn_timeout;
p_lcb->latency = conn_latency;
p_lcb->conn_update_mask = L2C_BLE_NOT_DEFAULT_PARAM;
/* Tell BTM Acl management about the link */
btm_acl_created(bda, NULL, p_dev_rec->sec_bd_name, handle, p_lcb->link_role, BT_TRANSPORT_LE);
p_lcb->peer_chnl_mask[0] = L2CAP_FIXED_CHNL_ATT_BIT | L2CAP_FIXED_CHNL_BLE_SIG_BIT | L2CAP_FIXED_CHNL_SMP_BIT;
btm_ble_set_conn_st(BLE_CONN_IDLE);
#if BLE_PRIVACY_SPT == TRUE
btm_ble_disable_resolving_list(BTM_BLE_RL_INIT, TRUE);
#endif
}
/*******************************************************************************
**
** Function l2cble_advertiser_conn_comp
**
** Description This function is called when an HCI Connection Complete
** event is received while we are an advertiser (so we are slave).
**
** Returns void
**
*******************************************************************************/
void l2cble_advertiser_conn_comp(uint16_t handle, BD_ADDR bda, tBLE_ADDR_TYPE type,
uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout)
{
tL2C_LCB *p_lcb;
tBTM_SEC_DEV_REC *p_dev_rec;
UNUSED(type);
UNUSED(conn_interval);
UNUSED(conn_latency);
UNUSED(conn_timeout);
/* See if we have a link control block for the remote device */
p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE);
/* If we don't have one, create one and accept the connection. */
if(!p_lcb)
{
p_lcb = l2cu_allocate_lcb(bda, FALSE, BT_TRANSPORT_LE);
if(!p_lcb)
{
btm_sec_disconnect(handle, HCI_ERR_NO_CONNECTION);
L2CAP_TRACE_ERROR("l2cble_advertiser_conn_comp - failed to allocate LCB");
return;
}
else
{
if(!l2cu_initialize_fixed_ccb(p_lcb, L2CAP_ATT_CID, &l2cb.fixed_reg[L2CAP_ATT_CID - L2CAP_FIRST_FIXED_CHNL].fixed_chnl_opts))
{
btm_sec_disconnect(handle, HCI_ERR_NO_CONNECTION);
L2CAP_TRACE_WARNING("l2cble_scanner_conn_comp - LCB but no CCB");
return ;
}
}
}
/* Save the handle */
p_lcb->handle = handle;
/* Connected OK. Change state to connected, we were advertising, so we are slave */
p_lcb->link_role = HCI_ROLE_SLAVE;
p_lcb->transport = BT_TRANSPORT_LE;
/* update link parameter, set slave link as non-spec default upon link up */
p_lcb->min_interval = p_lcb->max_interval = conn_interval;
p_lcb->timeout = conn_timeout;
p_lcb->latency = conn_latency;
p_lcb->conn_update_mask = L2C_BLE_NOT_DEFAULT_PARAM;
/* Tell BTM Acl management about the link */
p_dev_rec = btm_find_or_alloc_dev(bda);
btm_acl_created(bda, NULL, p_dev_rec->sec_bd_name, handle, p_lcb->link_role, BT_TRANSPORT_LE);
#if BLE_PRIVACY_SPT == TRUE
btm_ble_disable_resolving_list(BTM_BLE_RL_ADV, TRUE);
#endif
p_lcb->peer_chnl_mask[0] = L2CAP_FIXED_CHNL_ATT_BIT | L2CAP_FIXED_CHNL_BLE_SIG_BIT | L2CAP_FIXED_CHNL_SMP_BIT;
if(!HCI_LE_SLAVE_INIT_FEAT_EXC_SUPPORTED(btm_cb.devcb.local_le_features))
{
p_lcb->link_state = LST_CONNECTED;
l2cu_process_fixed_chnl_resp(p_lcb);
}
/* when adv and initiating are both active, cancel the direct connection */
if(l2cb.is_ble_connecting && memcmp(bda, l2cb.ble_connecting_bda, BD_ADDR_LEN) == 0)
{
L2CA_CancelBleConnectReq(bda);
}
}
/*******************************************************************************
**
** Function l2cble_conn_comp
**
** Description This function is called when an HCI Connection Complete
** event is received.
**
** Returns void
**
*******************************************************************************/
void l2cble_conn_comp(uint16_t handle, uint8_t role, BD_ADDR bda, tBLE_ADDR_TYPE type,
uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout)
{
btm_ble_update_link_topology_mask(role, TRUE);
if(role == HCI_ROLE_MASTER)
{
l2cble_scanner_conn_comp(handle, bda, type, conn_interval, conn_latency, conn_timeout);
}
else
{
l2cble_advertiser_conn_comp(handle, bda, type, conn_interval, conn_latency, conn_timeout);
}
}
/*******************************************************************************
**
** Function l2cble_start_conn_update
**
** Description start BLE connection parameter update process based on status
**
** Parameters: lcb : l2cap link control block
**
** Return value: none
**
*******************************************************************************/
static void l2cble_start_conn_update(tL2C_LCB *p_lcb)
{
uint16_t min_conn_int, max_conn_int, slave_latency, supervision_tout;
tACL_CONN *p_acl_cb = btm_bda_to_acl(p_lcb->remote_bd_addr, BT_TRANSPORT_LE);
// TODO(armansito): The return value of this call wasn't being used but the
// logic of this function might be depending on its side effects. We should
// verify if this call is needed at all and remove it otherwise.
btm_find_or_alloc_dev(p_lcb->remote_bd_addr);
if(p_lcb->conn_update_mask & L2C_BLE_UPDATE_PENDING)
{
return;
}
if(p_lcb->conn_update_mask & L2C_BLE_CONN_UPDATE_DISABLE)
{
/* application requests to disable parameters update.
If parameters are already updated, lets set them
up to what has been requested during connection establishement */
if(p_lcb->conn_update_mask & L2C_BLE_NOT_DEFAULT_PARAM &&
/* current connection interval is greater than default min */
p_lcb->min_interval > BTM_BLE_CONN_INT_MIN)
{
/* use 7.5 ms as fast connection parameter, 0 slave latency */
min_conn_int = max_conn_int = BTM_BLE_CONN_INT_MIN;
slave_latency = BTM_BLE_CONN_SLAVE_LATENCY_DEF;
supervision_tout = BTM_BLE_CONN_TIMEOUT_DEF;
/* if both side 4.1, or we are master device, send HCI command */
if(p_lcb->link_role == HCI_ROLE_MASTER
#if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE)
|| (HCI_LE_CONN_PARAM_REQ_SUPPORTED(btm_cb.devcb.local_le_features) &&
HCI_LE_CONN_PARAM_REQ_SUPPORTED(p_acl_cb->peer_le_features))
#endif
)
{
btsnd_hcic_ble_upd_ll_conn_params(p_lcb->handle, min_conn_int, max_conn_int,
slave_latency, supervision_tout, 0, 0);
p_lcb->conn_update_mask |= L2C_BLE_UPDATE_PENDING;
}
else
{
l2cu_send_peer_ble_par_req(p_lcb, min_conn_int, max_conn_int, slave_latency, supervision_tout);
}
p_lcb->conn_update_mask &= ~L2C_BLE_NOT_DEFAULT_PARAM;
p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM;
}
}
else
{
/* application allows to do update, if we were delaying one do it now */
if(p_lcb->conn_update_mask & L2C_BLE_NEW_CONN_PARAM)
{
/* if both side 4.1, or we are master device, send HCI command */
if(p_lcb->link_role == HCI_ROLE_MASTER
#if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE)
|| (HCI_LE_CONN_PARAM_REQ_SUPPORTED(btm_cb.devcb.local_le_features) &&
HCI_LE_CONN_PARAM_REQ_SUPPORTED(p_acl_cb->peer_le_features))
#endif
)
{
btsnd_hcic_ble_upd_ll_conn_params(p_lcb->handle, p_lcb->min_interval,
p_lcb->max_interval, p_lcb->latency, p_lcb->timeout, 0, 0);
p_lcb->conn_update_mask |= L2C_BLE_UPDATE_PENDING;
}
else
{
l2cu_send_peer_ble_par_req(p_lcb, p_lcb->min_interval, p_lcb->max_interval,
p_lcb->latency, p_lcb->timeout);
}
p_lcb->conn_update_mask &= ~L2C_BLE_NEW_CONN_PARAM;
p_lcb->conn_update_mask |= L2C_BLE_NOT_DEFAULT_PARAM;
}
}
}
/*******************************************************************************
**
** Function l2cble_process_conn_update_evt
**
** Description This function enables the connection update request from remote
** after a successful connection update response is received.
**
** Returns void
**
*******************************************************************************/
void l2cble_process_conn_update_evt(uint16_t handle, uint8_t status)
{
tL2C_LCB *p_lcb;
L2CAP_TRACE_DEBUG("l2cble_process_conn_update_evt");
/* See if we have a link control block for the remote device */
p_lcb = l2cu_find_lcb_by_handle(handle);
if(!p_lcb)
{
L2CAP_TRACE_WARNING("l2cble_process_conn_update_evt: Invalid handle: %d", handle);
return;
}
p_lcb->conn_update_mask &= ~L2C_BLE_UPDATE_PENDING;
if(status != HCI_SUCCESS)
{
L2CAP_TRACE_WARNING("l2cble_process_conn_update_evt: Error status: %d", status);
}
l2cble_start_conn_update(p_lcb);
L2CAP_TRACE_DEBUG("l2cble_process_conn_update_evt: conn_update_mask=%d", p_lcb->conn_update_mask);
}
/*******************************************************************************
**
** Function l2cble_process_sig_cmd
**
** Description This function is called when a signalling packet is received
** on the BLE signalling CID
**
** Returns void
**
*******************************************************************************/
void l2cble_process_sig_cmd(tL2C_LCB *p_lcb, uint8_t *p, uint16_t pkt_len)
{
uint8_t *p_pkt_end;
uint8_t cmd_code, id;
uint16_t cmd_len;
uint16_t min_interval, max_interval, latency, timeout;
tL2C_CONN_INFO con_info;
uint16_t lcid = 0, rcid = 0, mtu = 0, mps = 0, initial_credit = 0;
tL2C_CCB *p_ccb = NULL, *temp_p_ccb = NULL;
tL2C_RCB *p_rcb;
uint16_t credit;
p_pkt_end = p + pkt_len;
STREAM_TO_UINT8(cmd_code, p);
STREAM_TO_UINT8(id, p);
STREAM_TO_UINT16(cmd_len, p);
/* Check command length does not exceed packet length */
if((p + cmd_len) > p_pkt_end)
{
L2CAP_TRACE_WARNING("L2CAP - LE - format error, pkt_len: %d cmd_len: %d code: %d", pkt_len, cmd_len, cmd_code);
return;
}
switch(cmd_code)
{
case L2CAP_CMD_REJECT:
p += 2;
break;
case L2CAP_CMD_ECHO_REQ:
case L2CAP_CMD_ECHO_RSP:
case L2CAP_CMD_INFO_RSP:
case L2CAP_CMD_INFO_REQ:
l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
break;
case L2CAP_CMD_BLE_UPDATE_REQ:
STREAM_TO_UINT16(min_interval, p); /* 0x0006 - 0x0C80 */
STREAM_TO_UINT16(max_interval, p); /* 0x0006 - 0x0C80 */
STREAM_TO_UINT16(latency, p); /* 0x0000 - 0x03E8 */
STREAM_TO_UINT16(timeout, p); /* 0x000A - 0x0C80 */
/* If we are a master, the slave wants to update the parameters */
if(p_lcb->link_role == HCI_ROLE_MASTER)
{
if(min_interval < BTM_BLE_CONN_INT_MIN_LIMIT)
{
min_interval = BTM_BLE_CONN_INT_MIN_LIMIT;
}
if(min_interval < BTM_BLE_CONN_INT_MIN || min_interval > BTM_BLE_CONN_INT_MAX ||
max_interval < BTM_BLE_CONN_INT_MIN || max_interval > BTM_BLE_CONN_INT_MAX ||
latency > BTM_BLE_CONN_LATENCY_MAX ||
/*(timeout >= max_interval && latency > (timeout * 10/(max_interval * 1.25) - 1)) ||*/
timeout < BTM_BLE_CONN_SUP_TOUT_MIN || timeout > BTM_BLE_CONN_SUP_TOUT_MAX ||
max_interval < min_interval)
{
l2cu_send_peer_ble_par_rsp(p_lcb, L2CAP_CFG_UNACCEPTABLE_PARAMS, id);
}
else
{
l2cu_send_peer_ble_par_rsp(p_lcb, L2CAP_CFG_OK, id);
p_lcb->min_interval = min_interval;
p_lcb->max_interval = max_interval;
p_lcb->latency = latency;
p_lcb->timeout = timeout;
p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM;
l2cble_start_conn_update(p_lcb);
}
}
else
{
l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
}
break;
case L2CAP_CMD_BLE_UPDATE_RSP:
p += 2;
break;
case L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ:
STREAM_TO_UINT16(con_info.psm, p);
STREAM_TO_UINT16(rcid, p);
STREAM_TO_UINT16(mtu, p);
STREAM_TO_UINT16(mps, p);
STREAM_TO_UINT16(initial_credit, p);
L2CAP_TRACE_DEBUG("Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ with "
"mtu = %d, "
"mps = %d, "
"initial credit = %d", mtu, mps, initial_credit);
if((p_rcb = l2cu_find_ble_rcb_by_psm(con_info.psm)) == NULL)
{
L2CAP_TRACE_WARNING("L2CAP - rcvd conn req for unknown PSM: 0x%04x", con_info.psm);
l2cu_reject_ble_connection(p_lcb, id, L2CAP_LE_NO_PSM);
break;
}
else
{
if(!p_rcb->api.pL2CA_ConnectInd_Cb)
{
L2CAP_TRACE_WARNING("L2CAP - rcvd conn req for outgoing-only connection PSM: %d", con_info.psm);
l2cu_reject_ble_connection(p_lcb, id, L2CAP_CONN_NO_PSM);
break;
}
}
/* Allocate a ccb for this.*/
if((p_ccb = l2cu_allocate_ccb(p_lcb, 0)) == NULL)
{
L2CAP_TRACE_ERROR("L2CAP - unable to allocate CCB");
l2cu_reject_ble_connection(p_lcb, id, L2CAP_CONN_NO_RESOURCES);
break;
}
/* validate the parameters */
if(mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MPS || mps > L2CAP_LE_MAX_MPS)
{
L2CAP_TRACE_ERROR("L2CAP don't like the params");
l2cu_reject_ble_connection(p_lcb, id, L2CAP_CONN_NO_RESOURCES);
break;
}
p_ccb->remote_id = id;
p_ccb->p_rcb = p_rcb;
p_ccb->remote_cid = rcid;
p_ccb->peer_conn_cfg.mtu = mtu;
p_ccb->peer_conn_cfg.mps = mps;
p_ccb->peer_conn_cfg.credits = initial_credit;
p_ccb->tx_mps = mps;
p_ccb->ble_sdu = NULL;
p_ccb->ble_sdu_length = 0;
p_ccb->is_first_seg = TRUE;
p_ccb->peer_cfg.fcr.mode = L2CAP_FCR_LE_COC_MODE;
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_REQ, &con_info);
break;
case L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES:
L2CAP_TRACE_DEBUG("Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES");
/* For all channels, see whose identifier matches this id */
for(temp_p_ccb = p_lcb->ccb_queue.p_first_ccb; temp_p_ccb; temp_p_ccb = temp_p_ccb->p_next_ccb)
{
if(temp_p_ccb->local_id == id)
{
p_ccb = temp_p_ccb;
break;
}
}
if(p_ccb)
{
L2CAP_TRACE_DEBUG("I remember the connection req");
STREAM_TO_UINT16(p_ccb->remote_cid, p);
STREAM_TO_UINT16(p_ccb->peer_conn_cfg.mtu, p);
STREAM_TO_UINT16(p_ccb->peer_conn_cfg.mps, p);
STREAM_TO_UINT16(p_ccb->peer_conn_cfg.credits, p);
STREAM_TO_UINT16(con_info.l2cap_result, p);
con_info.remote_cid = p_ccb->remote_cid;
L2CAP_TRACE_DEBUG("remote_cid = %d, "
"mtu = %d, "
"mps = %d, "
"initial_credit = %d, "
"con_info.l2cap_result = %d",
p_ccb->remote_cid, p_ccb->peer_conn_cfg.mtu, p_ccb->peer_conn_cfg.mps,
p_ccb->peer_conn_cfg.credits, con_info.l2cap_result);
/* validate the parameters */
if(p_ccb->peer_conn_cfg.mtu < L2CAP_LE_MIN_MTU ||
p_ccb->peer_conn_cfg.mps < L2CAP_LE_MIN_MPS ||
p_ccb->peer_conn_cfg.mps > L2CAP_LE_MAX_MPS)
{
L2CAP_TRACE_ERROR("L2CAP don't like the params");
con_info.l2cap_result = L2CAP_LE_NO_RESOURCES;
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
break;
}
p_ccb->tx_mps = p_ccb->peer_conn_cfg.mps;
p_ccb->ble_sdu = NULL;
p_ccb->ble_sdu_length = 0;
p_ccb->is_first_seg = TRUE;
p_ccb->peer_cfg.fcr.mode = L2CAP_FCR_LE_COC_MODE;
if(con_info.l2cap_result == L2CAP_LE_CONN_OK)
{
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP, &con_info);
}
else
{
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
}
}
else
{
L2CAP_TRACE_DEBUG("I DO NOT remember the connection req");
con_info.l2cap_result = L2CAP_LE_INVALID_SOURCE_CID;
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
}
break;
case L2CAP_CMD_BLE_FLOW_CTRL_CREDIT:
STREAM_TO_UINT16(lcid, p);
if((p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, lcid)) == NULL)
{
L2CAP_TRACE_DEBUG("%s Credit received for unknown channel id %d", __func__, lcid);
break;
}
STREAM_TO_UINT16(credit, p);
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_RECV_FLOW_CONTROL_CREDIT, &credit);
L2CAP_TRACE_DEBUG("%s Credit received", __func__);
break;
case L2CAP_CMD_DISC_REQ:
STREAM_TO_UINT16(lcid, p);
STREAM_TO_UINT16(rcid, p);
if((p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid)) != NULL)
{
if(p_ccb->remote_cid == rcid)
{
p_ccb->remote_id = id;
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DISCONNECT_REQ, NULL);
}
}
else
{
l2cu_send_peer_disc_rsp(p_lcb, id, lcid, rcid);
}
break;
case L2CAP_CMD_DISC_RSP:
STREAM_TO_UINT16(rcid, p);
STREAM_TO_UINT16(lcid, p);
if((p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid)) != NULL)
{
if((p_ccb->remote_cid == rcid) && (p_ccb->local_id == id))
{
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DISCONNECT_RSP, NULL);
}
}
break;
default:
L2CAP_TRACE_WARNING("L2CAP - LE - unknown cmd code: %d", cmd_code);
l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
break;
}
}
/*******************************************************************************
**
** Function l2cble_init_direct_conn
**
** Description This function is to initate a direct connection
**
** Returns TRUE connection initiated, FALSE otherwise.
**
*******************************************************************************/
uint8_t l2cble_init_direct_conn(tL2C_LCB *p_lcb)
{
tBTM_SEC_DEV_REC *p_dev_rec = btm_find_or_alloc_dev(p_lcb->remote_bd_addr);
tBTM_BLE_CB *p_cb = &btm_cb.ble_ctr_cb;
uint16_t scan_int;
uint16_t scan_win;
BD_ADDR peer_addr;
uint8_t peer_addr_type = BLE_ADDR_PUBLIC;
uint8_t own_addr_type = BLE_ADDR_PUBLIC;
/* There can be only one BLE connection request outstanding at a time */
if(p_dev_rec == NULL)
{
L2CAP_TRACE_WARNING("unknown device, can not initate connection");
return(FALSE);
}
/*Give the default peer addr type by address*/
if(BTM_BLE_IS_RESOLVE_BDA(p_lcb->remote_bd_addr))
{
peer_addr_type = BLE_ADDR_RANDOM;
}
scan_int = (p_cb->scan_int == BTM_BLE_SCAN_PARAM_UNDEF) ? BTM_BLE_SCAN_FAST_INT : p_cb->scan_int;
scan_win = (p_cb->scan_win == BTM_BLE_SCAN_PARAM_UNDEF) ? BTM_BLE_SCAN_FAST_WIN : p_cb->scan_win;
peer_addr_type = p_lcb->ble_addr_type;
wm_memcpy(peer_addr, p_lcb->remote_bd_addr, BD_ADDR_LEN);
#if ( (defined BLE_PRIVACY_SPT) && (BLE_PRIVACY_SPT == TRUE))
own_addr_type = btm_cb.ble_ctr_cb.privacy_mode ? BLE_ADDR_RANDOM : BLE_ADDR_PUBLIC;
if(p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT)
{
if(btm_cb.ble_ctr_cb.privacy_mode >= BTM_PRIVACY_1_2)
{
own_addr_type |= BLE_ADDR_TYPE_ID_BIT;
}
btm_ble_enable_resolving_list(BTM_BLE_RL_INIT);
btm_random_pseudo_to_identity_addr(peer_addr, &peer_addr_type);
}
else
{
btm_ble_disable_resolving_list(BTM_BLE_RL_INIT, TRUE);
// If we have a current RPA, use that instead.
if(!bdaddr_is_empty((const tls_bt_addr_t *)p_dev_rec->ble.cur_rand_addr))
{
wm_memcpy(peer_addr, p_dev_rec->ble.cur_rand_addr, BD_ADDR_LEN);
}
}
#endif
if(!btm_ble_topology_check(BTM_BLE_STATE_INIT))
{
l2cu_release_lcb(p_lcb);
L2CAP_TRACE_ERROR("initate direct connection fail, topology limitation");
return FALSE;
}
if(!btsnd_hcic_ble_create_ll_conn(scan_int, /* uint16_t scan_int */
scan_win, /* uint16_t scan_win */
FALSE, /* uint8_t white_list */
peer_addr_type, /* uint8_t addr_type_peer */
peer_addr, /* BD_ADDR bda_peer */
own_addr_type, /* uint8_t addr_type_own */
(uint16_t)((p_dev_rec->conn_params.min_conn_int != BTM_BLE_CONN_PARAM_UNDEF) ?
p_dev_rec->conn_params.min_conn_int : BTM_BLE_CONN_INT_MIN_DEF), /* uint16_t conn_int_min */
(uint16_t)((p_dev_rec->conn_params.max_conn_int != BTM_BLE_CONN_PARAM_UNDEF) ?
p_dev_rec->conn_params.max_conn_int : BTM_BLE_CONN_INT_MAX_DEF), /* uint16_t conn_int_max */
(uint16_t)((p_dev_rec->conn_params.slave_latency != BTM_BLE_CONN_PARAM_UNDEF) ?
p_dev_rec->conn_params.slave_latency : BTM_BLE_CONN_SLAVE_LATENCY_DEF), /* uint16_t conn_latency */
(uint16_t)((p_dev_rec->conn_params.supervision_tout != BTM_BLE_CONN_PARAM_UNDEF) ?
p_dev_rec->conn_params.supervision_tout : BTM_BLE_CONN_TIMEOUT_DEF), /* conn_timeout */
BTM_BLE_CONN_EVT_MIN, /* uint16_t min_len */
BTM_BLE_CONN_EVT_MAX)) /* uint16_t max_len */
{
l2cu_release_lcb(p_lcb);
L2CAP_TRACE_ERROR("initate direct connection fail, no resources");
return (FALSE);
}
else
{
p_lcb->link_state = LST_CONNECTING;
l2cb.is_ble_connecting = TRUE;
wm_memcpy(l2cb.ble_connecting_bda, p_lcb->remote_bd_addr, BD_ADDR_LEN);
#ifdef USE_ALARM
alarm_set_on_queue(p_lcb->l2c_lcb_timer,
L2CAP_BLE_LINK_CONNECT_TIMEOUT_MS,
l2c_lcb_timer_timeout, p_lcb,
btu_general_alarm_queue);
#else
p_lcb->l2c_lcb_timer.p_cback = (TIMER_CBACK *)&l2c_lcb_timer_timeout;
p_lcb->l2c_lcb_timer.param = (TIMER_PARAM_TYPE)p_lcb;
btu_start_timer(&p_lcb->l2c_lcb_timer, BTU_TTYPE_L2CAP_LINK, L2CAP_BLE_LINK_CONNECT_TIMEOUT_MS / 1000);
#endif
btm_ble_set_conn_st(BLE_DIR_CONN);
return (TRUE);
}
}
/*******************************************************************************
**
** Function l2cble_create_conn
**
** Description This function initiates an acl connection via HCI
**
** Returns TRUE if successful, FALSE if connection not started.
**
*******************************************************************************/
uint8_t l2cble_create_conn(tL2C_LCB *p_lcb)
{
tBTM_BLE_CONN_ST conn_st = btm_ble_get_conn_st();
uint8_t rt = FALSE;
/* There can be only one BLE connection request outstanding at a time */
if(conn_st == BLE_CONN_IDLE)
{
rt = l2cble_init_direct_conn(p_lcb);
}
else
{
L2CAP_TRACE_WARNING("L2CAP - LE - cannot start new connection at conn st: %d", conn_st);
btm_ble_enqueue_direct_conn_req(p_lcb);
if(conn_st == BLE_BG_CONN)
{
btm_ble_suspend_bg_conn();
}
rt = TRUE;
}
return rt;
}
/*******************************************************************************
**
** Function l2c_link_processs_ble_num_bufs
**
** Description This function is called when a "controller buffer size"
** event is first received from the controller. It updates
** the L2CAP values.
**
** Returns void
**
*******************************************************************************/
void l2c_link_processs_ble_num_bufs(uint16_t num_lm_ble_bufs)
{
if(num_lm_ble_bufs == 0)
{
num_lm_ble_bufs = L2C_DEF_NUM_BLE_BUF_SHARED;
l2cb.num_lm_acl_bufs -= L2C_DEF_NUM_BLE_BUF_SHARED;
}
l2cb.num_lm_ble_bufs = l2cb.controller_le_xmit_window = num_lm_ble_bufs;
}
/*******************************************************************************
**
** Function l2c_ble_link_adjust_allocation
**
** Description This function is called when a link is created or removed
** to calculate the amount of packets each link may send to
** the HCI without an ack coming back.
**
** Currently, this is a simple allocation, dividing the
** number of Controller Packets by the number of links. In
** the future, QOS configuration should be examined.
**
** Returns void
**
*******************************************************************************/
void l2c_ble_link_adjust_allocation(void)
{
uint16_t qq, yy, qq_remainder;
tL2C_LCB *p_lcb;
uint16_t hi_quota, low_quota;
uint16_t num_lowpri_links = 0;
uint16_t num_hipri_links = 0;
uint16_t controller_xmit_quota = l2cb.num_lm_ble_bufs;
uint16_t high_pri_link_quota = L2CAP_HIGH_PRI_MIN_XMIT_QUOTA_A;
/* If no links active, reset buffer quotas and controller buffers */
if(l2cb.num_ble_links_active == 0)
{
l2cb.controller_le_xmit_window = l2cb.num_lm_ble_bufs;
l2cb.ble_round_robin_quota = l2cb.ble_round_robin_unacked = 0;
return;
}
/* First, count the links */
for(yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++)
{
if(p_lcb->in_use && p_lcb->transport == BT_TRANSPORT_LE)
{
if(p_lcb->acl_priority == L2CAP_PRIORITY_HIGH)
{
num_hipri_links++;
}
else
{
num_lowpri_links++;
}
}
}
/* now adjust high priority link quota */
low_quota = num_lowpri_links ? 1 : 0;
while((num_hipri_links * high_pri_link_quota + low_quota) > controller_xmit_quota)
{
high_pri_link_quota--;
}
/* Work out the xmit quota and buffer quota high and low priorities */
hi_quota = num_hipri_links * high_pri_link_quota;
low_quota = (hi_quota < controller_xmit_quota) ? controller_xmit_quota - hi_quota : 1;
/* Work out and save the HCI xmit quota for each low priority link */
/* If each low priority link cannot have at least one buffer */
if(num_lowpri_links > low_quota)
{
l2cb.ble_round_robin_quota = low_quota;
qq = qq_remainder = 0;
}
/* If each low priority link can have at least one buffer */
else
if(num_lowpri_links > 0)
{
l2cb.ble_round_robin_quota = 0;
l2cb.ble_round_robin_unacked = 0;
qq = low_quota / num_lowpri_links;
qq_remainder = low_quota % num_lowpri_links;
}
/* If no low priority link */
else
{
l2cb.ble_round_robin_quota = 0;
l2cb.ble_round_robin_unacked = 0;
qq = qq_remainder = 0;
}
L2CAP_TRACE_EVENT("l2c_ble_link_adjust_allocation num_hipri: %u num_lowpri: %u low_quota: %u round_robin_quota: %u qq: %u",
num_hipri_links, num_lowpri_links, low_quota,
l2cb.ble_round_robin_quota, qq);
/* Now, assign the quotas to each link */
for(yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++)
{
if(p_lcb->in_use && p_lcb->transport == BT_TRANSPORT_LE)
{
if(p_lcb->acl_priority == L2CAP_PRIORITY_HIGH)
{
p_lcb->link_xmit_quota = high_pri_link_quota;
}
else
{
/* Safety check in case we switched to round-robin with something outstanding */
/* if sent_not_acked is added into round_robin_unacked then don't add it again */
/* l2cap keeps updating sent_not_acked for exiting from round robin */
if((p_lcb->link_xmit_quota > 0) && (qq == 0))
{
l2cb.ble_round_robin_unacked += p_lcb->sent_not_acked;
}
p_lcb->link_xmit_quota = qq;
if(qq_remainder > 0)
{
p_lcb->link_xmit_quota++;
qq_remainder--;
}
}
L2CAP_TRACE_EVENT("l2c_ble_link_adjust_allocation LCB %d Priority: %d XmitQuota: %d",
yy, p_lcb->acl_priority, p_lcb->link_xmit_quota);
L2CAP_TRACE_EVENT(" SentNotAcked: %d RRUnacked: %d",
p_lcb->sent_not_acked, l2cb.round_robin_unacked);
/* There is a special case where we have readjusted the link quotas and */
/* this link may have sent anything but some other link sent packets so */
/* so we may need a timer to kick off this link's transmissions. */
if((p_lcb->link_state == LST_CONNECTED)
&& (!list_is_empty(p_lcb->link_xmit_data_q))
&& (p_lcb->sent_not_acked < p_lcb->link_xmit_quota))
{
#ifdef USE_ALARM
alarm_set_on_queue(p_lcb->l2c_lcb_timer,
L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS,
l2c_lcb_timer_timeout, p_lcb,
btu_general_alarm_queue);
#else
p_lcb->l2c_lcb_timer.p_cback = (TIMER_CBACK *)&l2c_lcb_timer_timeout;
p_lcb->l2c_lcb_timer.param = (TIMER_PARAM_TYPE)p_lcb;
btu_start_timer(&p_lcb->l2c_lcb_timer, BTU_TTYPE_L2CAP_LINK, L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS / 1000);
#endif
}
}
}
}
#if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE)
/*******************************************************************************
**
** Function l2cble_process_rc_param_request_evt
**
** Description process LE Remote Connection Parameter Request Event.
**
** Returns void
**
*******************************************************************************/
void l2cble_process_rc_param_request_evt(uint16_t handle, uint16_t int_min, uint16_t int_max,
uint16_t latency, uint16_t timeout)
{
tL2C_LCB *p_lcb = l2cu_find_lcb_by_handle(handle);
if(p_lcb != NULL)
{
p_lcb->min_interval = int_min;
p_lcb->max_interval = int_max;
p_lcb->latency = latency;
p_lcb->timeout = timeout;
/* if update is enabled, always accept connection parameter update */
if((p_lcb->conn_update_mask & L2C_BLE_CONN_UPDATE_DISABLE) == 0)
{
btsnd_hcic_ble_rc_param_req_reply(handle, int_min, int_max, latency, timeout, 0, 0);
}
else
{
L2CAP_TRACE_EVENT("L2CAP - LE - update currently disabled");
p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM;
btsnd_hcic_ble_rc_param_req_neg_reply(handle, HCI_ERR_UNACCEPT_CONN_INTERVAL);
}
}
else
{
L2CAP_TRACE_WARNING("No link to update connection parameter")
}
}
#endif
/*******************************************************************************
**
** Function l2cble_update_data_length
**
** Description This function update link tx data length if applicable
**
** Returns void
**
*******************************************************************************/
void l2cble_update_data_length(tL2C_LCB *p_lcb)
{
uint16_t tx_mtu = 0;
uint16_t i = 0;
L2CAP_TRACE_DEBUG("%s", __FUNCTION__);
/* See if we have a link control block for the connection */
if(p_lcb == NULL)
{
return;
}
for(i = 0; i < L2CAP_NUM_FIXED_CHNLS; i++)
{
if(i + L2CAP_FIRST_FIXED_CHNL != L2CAP_BLE_SIGNALLING_CID)
{
if((p_lcb->p_fixed_ccbs[i] != NULL) &&
(tx_mtu < (p_lcb->p_fixed_ccbs[i]->tx_data_len + L2CAP_PKT_OVERHEAD)))
{
tx_mtu = p_lcb->p_fixed_ccbs[i]->tx_data_len + L2CAP_PKT_OVERHEAD;
}
}
}
if(tx_mtu > BTM_BLE_DATA_SIZE_MAX)
{
tx_mtu = BTM_BLE_DATA_SIZE_MAX;
}
/* update TX data length if changed */
if(p_lcb->tx_data_len != tx_mtu)
{
BTM_SetBleDataLength(p_lcb->remote_bd_addr, tx_mtu);
}
}
/*******************************************************************************
**
** Function l2cble_process_data_length_change_evt
**
** Description This function process the data length change event
**
** Returns void
**
*******************************************************************************/
void l2cble_process_data_length_change_event(uint16_t handle, uint16_t tx_data_len, uint16_t rx_data_len)
{
tL2C_LCB *p_lcb = l2cu_find_lcb_by_handle(handle);
L2CAP_TRACE_DEBUG("%s TX data len = %d", __FUNCTION__, tx_data_len);
if(p_lcb == NULL)
{
return;
}
if(tx_data_len > 0)
{
p_lcb->tx_data_len = tx_data_len;
}
/* ignore rx_data len for now */
}
/*******************************************************************************
**
** Function l2cble_set_fixed_channel_tx_data_length
**
** Description This function update max fixed channel tx data length if applicable
**
** Returns void
**
*******************************************************************************/
uint8_t l2cble_set_fixed_channel_tx_data_length(BD_ADDR remote_bda, uint16_t fix_cid, uint16_t tx_mtu)
{
tL2C_LCB *p_lcb = l2cu_find_lcb_by_bd_addr(remote_bda, BT_TRANSPORT_LE);
tACL_CONN *p_acl_cb = btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE);
uint16_t cid = fix_cid - L2CAP_FIRST_FIXED_CHNL;
L2CAP_TRACE_DEBUG("%s TX MTU = %d", __FUNCTION__, tx_mtu);
if(!HCI_LE_DATA_LEN_EXT_SUPPORTED(btm_cb.devcb.local_le_features) || !HCI_LE_DATA_LEN_EXT_SUPPORTED(p_acl_cb->peer_le_features))
//if (!controller_get_interface()->supports_ble_packet_extension())
{
L2CAP_TRACE_WARNING("%s, request not supported", __FUNCTION__);
return 0;
}
/* See if we have a link control block for the connection */
if(p_lcb == NULL)
{
return 0;
}
if(p_lcb->p_fixed_ccbs[cid] != NULL)
{
if(tx_mtu > BTM_BLE_DATA_SIZE_MAX)
{
tx_mtu = BTM_BLE_DATA_SIZE_MAX;
}
p_lcb->p_fixed_ccbs[cid]->tx_data_len = tx_mtu;
}
l2cble_update_data_length(p_lcb);
return 1;
}
/*******************************************************************************
**
** Function l2cble_credit_based_conn_req
**
** Description This function sends LE Credit Based Connection Request for
** LE connection oriented channels.
**
** Returns void
**
*******************************************************************************/
void l2cble_credit_based_conn_req(tL2C_CCB *p_ccb)
{
if(!p_ccb)
{
return;
}
if(p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE)
{
L2CAP_TRACE_WARNING("LE link doesn't exist");
return;
}
l2cu_send_peer_ble_credit_based_conn_req(p_ccb);
return;
}
/*******************************************************************************
**
** Function l2cble_credit_based_conn_res
**
** Description This function sends LE Credit Based Connection Response for
** LE connection oriented channels.
**
** Returns void
**
*******************************************************************************/
void l2cble_credit_based_conn_res(tL2C_CCB *p_ccb, uint16_t result)
{
if(!p_ccb)
{
return;
}
if(p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE)
{
L2CAP_TRACE_WARNING("LE link doesn't exist");
return;
}
l2cu_send_peer_ble_credit_based_conn_res(p_ccb, result);
return;
}
/*******************************************************************************
**
** Function l2cble_send_flow_control_credit
**
** Description This function sends flow control credits for
** LE connection oriented channels.
**
** Returns void
**
*******************************************************************************/
void l2cble_send_flow_control_credit(tL2C_CCB *p_ccb, uint16_t credit_value)
{
if(!p_ccb)
{
return;
}
if(p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE)
{
L2CAP_TRACE_WARNING("LE link doesn't exist");
return;
}
l2cu_send_peer_ble_flow_control_credit(p_ccb, credit_value);
return;
}
/*******************************************************************************
**
** Function l2cble_send_peer_disc_req
**
** Description This function sends disconnect request
** to the peer LE device
**
** Returns void
**
*******************************************************************************/
void l2cble_send_peer_disc_req(tL2C_CCB *p_ccb)
{
L2CAP_TRACE_DEBUG("%s", __func__);
if(!p_ccb)
{
return;
}
if(p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE)
{
L2CAP_TRACE_WARNING("LE link doesn't exist");
return;
}
l2cu_send_peer_ble_credit_based_disconn_req(p_ccb);
return;
}
/*******************************************************************************
**
** Function l2cble_sec_comp
**
** Description This function is called when security procedure for an LE COC
** link is done
**
** Returns void
**
*******************************************************************************/
void l2cble_sec_comp(BD_ADDR p_bda, tBT_TRANSPORT transport, void *p_ref_data, uint8_t status)
{
tL2C_LCB *p_lcb = l2cu_find_lcb_by_bd_addr(p_bda, BT_TRANSPORT_LE);
tL2CAP_SEC_DATA *p_buf = NULL;
uint8_t sec_flag;
uint8_t sec_act;
if(!p_lcb)
{
L2CAP_TRACE_WARNING("%s security complete for unknown device", __func__);
return;
}
sec_act = p_lcb->sec_act;
p_lcb->sec_act = 0;
if(!fixed_queue_is_empty(p_lcb->le_sec_pending_q))
{
p_buf = (tL2CAP_SEC_DATA *) fixed_queue_dequeue(p_lcb->le_sec_pending_q);
if(!p_buf)
{
L2CAP_TRACE_WARNING("%s Security complete for request not initiated from L2CAP",
__func__);
return;
}
if(status != BTM_SUCCESS)
{
(*(p_buf->p_callback))(p_bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status);
}
else
{
if(sec_act == BTM_SEC_ENCRYPT_MITM)
{
BTM_GetSecurityFlagsByTransport(p_bda, &sec_flag, transport);
if(sec_flag & BTM_SEC_FLAG_LKEY_AUTHED)
{
(*(p_buf->p_callback))(p_bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status);
}
else
{
L2CAP_TRACE_DEBUG("%s MITM Protection Not present", __func__);
(*(p_buf->p_callback))(p_bda, BT_TRANSPORT_LE, p_buf->p_ref_data,
BTM_FAILED_ON_SECURITY);
}
}
else
{
L2CAP_TRACE_DEBUG("%s MITM Protection not required sec_act = %d",
__func__, p_lcb->sec_act);
(*(p_buf->p_callback))(p_bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status);
}
}
}
else
{
L2CAP_TRACE_WARNING("%s Security complete for request not initiated from L2CAP", __func__);
return;
}
GKI_freebuf(p_buf);
while(!fixed_queue_is_empty(p_lcb->le_sec_pending_q))
{
p_buf = (tL2CAP_SEC_DATA *) fixed_queue_dequeue(p_lcb->le_sec_pending_q);
if(status != BTM_SUCCESS)
{
(*(p_buf->p_callback))(p_bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status);
}
else
l2ble_sec_access_req(p_bda, p_buf->psm, p_buf->is_originator,
p_buf->p_callback, p_buf->p_ref_data);
GKI_freebuf(p_buf);
}
}
/*******************************************************************************
**
** Function l2ble_sec_access_req
**
** Description This function is called by LE COC link to meet the
** security requirement for the link
**
** Returns TRUE - security procedures are started
** FALSE - failure
**
*******************************************************************************/
uint8_t l2ble_sec_access_req(BD_ADDR bd_addr, uint16_t psm, uint8_t is_originator, tL2CAP_SEC_CBACK *p_callback, void *p_ref_data)
{
L2CAP_TRACE_DEBUG("%s", __func__);
uint8_t status;
tL2C_LCB *p_lcb = NULL;
if(!p_callback)
{
L2CAP_TRACE_ERROR("%s No callback function", __func__);
return FALSE;
}
p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_LE);
if(!p_lcb)
{
L2CAP_TRACE_ERROR("%s Security check for unknown device", __func__);
p_callback(bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_UNKNOWN_ADDR);
return FALSE;
}
tL2CAP_SEC_DATA *p_buf = (tL2CAP_SEC_DATA *) GKI_getbuf((uint16_t)sizeof(tL2CAP_SEC_DATA));
if(!p_buf)
{
p_callback(bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_NO_RESOURCES);
return FALSE;
}
p_buf->psm = psm;
p_buf->is_originator = is_originator;
p_buf->p_callback = p_callback;
p_buf->p_ref_data = p_ref_data;
fixed_queue_enqueue(p_lcb->le_sec_pending_q, p_buf);
status = btm_ble_start_sec_check(bd_addr, psm, is_originator, &l2cble_sec_comp, p_ref_data);
return status;
}
#endif /* (BLE_INCLUDED == TRUE) */
| 36.712226 | 165 | 0.555571 |
a49d6ea9b4f342f9beef76f0b9271a0f961d9517 | 54,436 | c | C | testsuite/EXP_4/test239.c | ishiura-compiler/CF3 | 0718aa176d0303a4ea8a46bd6c794997cbb8fabb | [
"MIT"
] | 34 | 2017-07-04T14:16:12.000Z | 2021-04-22T21:04:43.000Z | testsuite/EXP_4/test239.c | ishiura-compiler/CF3 | 0718aa176d0303a4ea8a46bd6c794997cbb8fabb | [
"MIT"
] | 1 | 2017-07-06T03:43:44.000Z | 2017-07-06T03:43:44.000Z | testsuite/EXP_4/test239.c | ishiura-compiler/CF3 | 0718aa176d0303a4ea8a46bd6c794997cbb8fabb | [
"MIT"
] | 6 | 2017-07-04T16:30:42.000Z | 2019-10-16T05:37:29.000Z |
/*
CF3
Copyright (c) 2015 ishiura-lab.
Released under the MIT license.
https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md
*/
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include"test1.h"
volatile int32_t t1 = -1932138;
int32_t t2 = -182;
uint64_t x17 = 4128753368LLU;
int64_t x19 = INT64_MIN;
uint64_t x20 = UINT64_MAX;
int32_t x21 = 4715396;
volatile int8_t x26 = -1;
static int32_t x28 = 14669;
int64_t x29 = 3500735980684886377LL;
uint8_t x30 = 1U;
uint16_t x34 = 190U;
static uint16_t x35 = 17U;
int16_t x61 = 7;
static uint8_t x73 = 0U;
uint64_t t13 = 52963496403746LLU;
static int64_t x78 = -71286226132197LL;
int8_t x82 = -6;
int64_t x86 = 435645227264541LL;
int16_t x88 = INT16_MIN;
uint64_t x89 = 1696939707103401679LLU;
volatile uint64_t t17 = 92352LLU;
volatile int32_t x93 = INT32_MIN;
uint64_t x103 = 683064LLU;
int8_t x122 = INT8_MAX;
static uint32_t x123 = 223U;
volatile uint64_t x136 = UINT64_MAX;
int32_t x144 = INT32_MIN;
int32_t t26 = 1524;
uint8_t x149 = 26U;
static int16_t x153 = INT16_MAX;
int8_t x155 = INT8_MAX;
uint32_t x170 = 173562U;
int64_t x174 = INT64_MIN;
static volatile int64_t x176 = INT64_MIN;
volatile int32_t x180 = 68;
uint64_t t34 = 5LLU;
uint8_t x188 = 0U;
static int64_t x194 = INT64_MAX;
int8_t x198 = INT8_MIN;
int16_t x200 = 0;
static int32_t x208 = -1;
uint8_t x211 = 1U;
int64_t x212 = -43LL;
int8_t x213 = INT8_MAX;
int16_t x218 = INT16_MIN;
static int8_t x224 = INT8_MIN;
volatile uint8_t x230 = 5U;
static uint16_t x234 = UINT16_MAX;
uint64_t x236 = 308440377155359238LLU;
uint64_t x237 = UINT64_MAX;
volatile uint64_t t46 = 312934273891844950LLU;
uint16_t x245 = 3560U;
uint16_t x247 = 5564U;
volatile int64_t t51 = -174721381343LL;
uint32_t x261 = 1U;
uint16_t x262 = 52U;
int8_t x263 = INT8_MAX;
int64_t t52 = 2761LL;
int64_t x265 = INT64_MIN;
static int16_t x267 = INT16_MIN;
uint32_t x270 = UINT32_MAX;
int8_t x271 = INT8_MIN;
int32_t x274 = INT32_MAX;
int32_t x275 = INT32_MAX;
int32_t x278 = INT32_MIN;
static int8_t x279 = 0;
static int64_t t56 = -31LL;
uint64_t x288 = UINT64_MAX;
uint64_t x289 = 103211LLU;
volatile uint64_t t58 = 7LLU;
static volatile int8_t x296 = INT8_MIN;
uint64_t x301 = 1407237365299302820LLU;
uint16_t x310 = UINT16_MAX;
int32_t x313 = INT32_MIN;
static int8_t x320 = 22;
int32_t t65 = 389;
static uint8_t x326 = UINT8_MAX;
static int64_t t66 = 1452LL;
volatile uint16_t x338 = 690U;
volatile int64_t x339 = -573785840421889888LL;
static volatile int64_t t68 = 503373566LL;
uint16_t x353 = UINT16_MAX;
volatile uint8_t x364 = 22U;
volatile int32_t t71 = -39;
volatile int64_t t72 = -12040667LL;
int8_t x372 = INT8_MIN;
int64_t x373 = INT64_MIN;
int16_t x387 = 372;
int64_t x390 = 109918701734053LL;
volatile int32_t x404 = INT32_MIN;
uint64_t t82 = 158762988147LLU;
volatile int32_t x421 = INT32_MAX;
static uint64_t x422 = 30764LLU;
int64_t x423 = -1LL;
int32_t x436 = INT32_MIN;
static uint64_t t85 = 2LLU;
volatile uint64_t t89 = 1LLU;
static int8_t x453 = 27;
int64_t x456 = 2939LL;
int8_t x458 = -2;
volatile int16_t x459 = INT16_MIN;
static volatile int32_t x460 = -1;
volatile uint64_t t91 = 645059708LLU;
uint16_t x463 = UINT16_MAX;
volatile uint32_t t92 = 423U;
int8_t x483 = 1;
static int32_t t97 = 42489;
int16_t x486 = -1;
uint32_t x491 = 10380063U;
int16_t x510 = INT16_MAX;
int8_t x515 = INT8_MIN;
int32_t t104 = -37;
int8_t x528 = INT8_MIN;
static volatile int32_t x529 = -1;
int32_t x541 = -1;
static int16_t x547 = INT16_MAX;
int8_t x548 = INT8_MIN;
static int16_t x562 = -1;
int8_t x563 = INT8_MIN;
static int8_t x583 = 3;
int16_t x588 = -1;
uint8_t x589 = 4U;
int16_t x592 = -1954;
int32_t t119 = 3;
volatile uint16_t x593 = 399U;
int64_t x609 = -1LL;
int8_t x610 = -1;
int64_t t124 = -205LL;
uint32_t x616 = UINT32_MAX;
int32_t x623 = -1;
uint64_t x644 = 70069LLU;
static uint16_t x654 = UINT16_MAX;
int32_t x655 = -1476119;
volatile int64_t t136 = INT64_MIN;
volatile int32_t x673 = INT32_MIN;
static volatile int32_t t137 = INT32_MIN;
int64_t t138 = 156164LL;
volatile uint32_t t139 = 241751756U;
uint8_t x704 = UINT8_MAX;
uint8_t x708 = 12U;
uint64_t x709 = 6477LLU;
uint16_t x712 = 1U;
volatile int64_t t146 = -1807936216065LL;
uint8_t x722 = 1U;
int32_t x725 = INT32_MIN;
int8_t x729 = -12;
uint64_t t149 = 31423LLU;
static int16_t x733 = 1658;
volatile int64_t t150 = 34019816947104474LL;
uint16_t x753 = UINT16_MAX;
static volatile int64_t t156 = -70844496LL;
uint32_t x763 = 3558U;
int8_t x777 = INT8_MAX;
int16_t x785 = -3;
static volatile int32_t t161 = 1755856;
uint64_t x792 = 2522361LLU;
volatile uint32_t x801 = 19323681U;
int8_t x811 = INT8_MAX;
int8_t x812 = 0;
uint8_t x820 = 69U;
volatile uint16_t x822 = 36U;
int64_t x825 = 448416872273122073LL;
int8_t x843 = INT8_MIN;
int64_t x853 = INT64_MAX;
uint32_t x854 = UINT32_MAX;
uint64_t t176 = 108898538LLU;
static volatile int8_t x886 = 21;
volatile uint16_t x892 = 414U;
int32_t x894 = -1;
uint32_t x897 = 0U;
int8_t x900 = -1;
volatile int8_t x907 = INT8_MAX;
volatile uint32_t x914 = 867U;
uint64_t x915 = UINT64_MAX;
static int32_t x917 = INT32_MIN;
volatile int8_t x918 = INT8_MIN;
int32_t x935 = 179283;
volatile int16_t x936 = INT16_MIN;
int32_t x939 = -1;
static int8_t x960 = INT8_MAX;
uint64_t t190 = 1004LLU;
int16_t x962 = 0;
uint32_t x963 = UINT32_MAX;
uint32_t t191 = 209577971U;
uint64_t t193 = 290141LLU;
volatile uint32_t x973 = 806831U;
uint32_t x975 = UINT32_MAX;
volatile uint32_t t194 = 1915999U;
static int64_t x977 = INT64_MIN;
int64_t t195 = -651134521472109634LL;
int32_t x983 = INT32_MAX;
int16_t x984 = INT16_MAX;
static int16_t x994 = 1;
int8_t x995 = 0;
void f0(void) {
int16_t x1 = -5;
int32_t x2 = -378;
volatile int32_t x3 = 0;
uint64_t x4 = 495450637LLU;
uint64_t t0 = 3000LLU;
t0 = (x1+(x2/(x3-x4)));
if (t0 != 18446744073709551612LLU) { NG(); } else { ; }
}
void f1(void) {
int8_t x5 = -1;
uint8_t x6 = 15U;
volatile int16_t x7 = INT16_MIN;
static int8_t x8 = INT8_MAX;
t1 = (x5+(x6/(x7-x8)));
if (t1 != -1) { NG(); } else { ; }
}
void f2(void) {
volatile int16_t x9 = 1;
volatile int16_t x10 = INT16_MAX;
int8_t x11 = INT8_MAX;
int32_t x12 = -6186;
t2 = (x9+(x10/(x11-x12)));
if (t2 != 6) { NG(); } else { ; }
}
void f3(void) {
static int16_t x18 = -1;
volatile uint64_t t3 = 600LLU;
t3 = (x17+(x18/(x19-x20)));
if (t3 != 4128753369LLU) { NG(); } else { ; }
}
void f4(void) {
uint32_t x22 = 6692647U;
int64_t x23 = -2174290668171401LL;
int64_t x24 = INT64_MIN;
int64_t t4 = -7543589464898489LL;
t4 = (x21+(x22/(x23-x24)));
if (t4 != 4715396LL) { NG(); } else { ; }
}
void f5(void) {
int16_t x25 = -1;
int32_t x27 = INT32_MAX;
static int32_t t5 = 10;
t5 = (x25+(x26/(x27-x28)));
if (t5 != -1) { NG(); } else { ; }
}
void f6(void) {
volatile int16_t x31 = INT16_MIN;
static volatile uint32_t x32 = 243U;
volatile int64_t t6 = 10029LL;
t6 = (x29+(x30/(x31-x32)));
if (t6 != 3500735980684886377LL) { NG(); } else { ; }
}
void f7(void) {
int16_t x33 = INT16_MIN;
static volatile uint16_t x36 = UINT16_MAX;
int32_t t7 = 44442504;
t7 = (x33+(x34/(x35-x36)));
if (t7 != -32768) { NG(); } else { ; }
}
void f8(void) {
volatile int64_t x37 = INT64_MAX;
static int32_t x38 = -1;
int16_t x39 = -1;
volatile int8_t x40 = INT8_MIN;
volatile int64_t t8 = INT64_MAX;
t8 = (x37+(x38/(x39-x40)));
if (t8 != INT64_MAX) { NG(); } else { ; }
}
void f9(void) {
volatile int16_t x49 = INT16_MIN;
volatile int64_t x50 = 6358120697734852LL;
int8_t x51 = INT8_MAX;
int64_t x52 = -1LL;
int64_t t9 = -122LL;
t9 = (x49+(x50/(x51-x52)));
if (t9 != 49672817918285LL) { NG(); } else { ; }
}
void f10(void) {
int16_t x62 = INT16_MIN;
static volatile int8_t x63 = INT8_MIN;
uint32_t x64 = 598860279U;
static uint32_t t10 = 305736U;
t10 = (x61+(x62/(x63-x64)));
if (t10 != 8U) { NG(); } else { ; }
}
void f11(void) {
uint32_t x65 = 46365U;
int32_t x66 = INT32_MIN;
uint32_t x67 = 54660662U;
uint8_t x68 = UINT8_MAX;
uint32_t t11 = 204092427U;
t11 = (x65+(x66/(x67-x68)));
if (t11 != 46404U) { NG(); } else { ; }
}
void f12(void) {
int16_t x69 = -1;
int16_t x70 = 384;
volatile int32_t x71 = -1;
uint32_t x72 = 68241837U;
static volatile uint32_t t12 = UINT32_MAX;
t12 = (x69+(x70/(x71-x72)));
if (t12 != UINT32_MAX) { NG(); } else { ; }
}
void f13(void) {
static uint64_t x74 = 337517821453LLU;
int32_t x75 = 255;
int32_t x76 = INT32_MAX;
t13 = (x73+(x74/(x75-x76)));
if (t13 != 0LLU) { NG(); } else { ; }
}
void f14(void) {
int64_t x77 = -1660261339671653LL;
int32_t x79 = 737;
uint16_t x80 = UINT16_MAX;
int64_t t14 = 43813143LL;
t14 = (x77+(x78/(x79-x80)));
if (t14 != -1660260239541617LL) { NG(); } else { ; }
}
void f15(void) {
static int16_t x81 = 12;
uint16_t x83 = UINT16_MAX;
int32_t x84 = -471192453;
static volatile int32_t t15 = -252;
t15 = (x81+(x82/(x83-x84)));
if (t15 != 12) { NG(); } else { ; }
}
void f16(void) {
static uint16_t x85 = UINT16_MAX;
static int64_t x87 = 785242111358401LL;
volatile int64_t t16 = 81895606LL;
t16 = (x85+(x86/(x87-x88)));
if (t16 != 65535LL) { NG(); } else { ; }
}
void f17(void) {
int32_t x90 = -1;
static uint64_t x91 = 166LLU;
static int32_t x92 = -109;
t17 = (x89+(x90/(x91-x92)));
if (t17 != 1764018776462345503LLU) { NG(); } else { ; }
}
void f18(void) {
uint64_t x94 = 214LLU;
int16_t x95 = INT16_MIN;
volatile uint8_t x96 = 20U;
static uint64_t t18 = 25887LLU;
t18 = (x93+(x94/(x95-x96)));
if (t18 != 18446744071562067968LLU) { NG(); } else { ; }
}
void f19(void) {
volatile int64_t x97 = INT64_MAX;
volatile uint16_t x98 = 15150U;
uint64_t x99 = UINT64_MAX;
volatile int32_t x100 = -34592713;
volatile uint64_t t19 = 123694167464LLU;
t19 = (x97+(x98/(x99-x100)));
if (t19 != 9223372036854775807LLU) { NG(); } else { ; }
}
void f20(void) {
uint32_t x101 = 1022U;
int32_t x102 = INT32_MIN;
uint64_t x104 = UINT64_MAX;
uint64_t t20 = 526005657LLU;
t20 = (x101+(x102/(x103-x104)));
if (t20 != 27005839959974LLU) { NG(); } else { ; }
}
void f21(void) {
int16_t x109 = INT16_MIN;
int16_t x110 = INT16_MAX;
volatile int8_t x111 = -10;
uint32_t x112 = UINT32_MAX;
volatile uint32_t t21 = 976147U;
t21 = (x109+(x110/(x111-x112)));
if (t21 != 4294934528U) { NG(); } else { ; }
}
void f22(void) {
static volatile int64_t x121 = INT64_MAX;
volatile int32_t x124 = -48984806;
volatile int64_t t22 = INT64_MAX;
t22 = (x121+(x122/(x123-x124)));
if (t22 != INT64_MAX) { NG(); } else { ; }
}
void f23(void) {
static int64_t x125 = 1998624154LL;
int64_t x126 = 5225367LL;
volatile uint8_t x127 = 4U;
uint64_t x128 = UINT64_MAX;
uint64_t t23 = 847355328983023LLU;
t23 = (x125+(x126/(x127-x128)));
if (t23 != 1999669227LLU) { NG(); } else { ; }
}
void f24(void) {
static volatile uint64_t x133 = UINT64_MAX;
int8_t x134 = INT8_MIN;
volatile int16_t x135 = INT16_MIN;
volatile uint64_t t24 = 5887507LLU;
t24 = (x133+(x134/(x135-x136)));
if (t24 != 0LLU) { NG(); } else { ; }
}
void f25(void) {
volatile int8_t x141 = INT8_MAX;
int16_t x142 = INT16_MIN;
uint64_t x143 = UINT64_MAX;
volatile uint64_t t25 = 81724LLU;
t25 = (x141+(x142/(x143-x144)));
if (t25 != 8589934722LLU) { NG(); } else { ; }
}
void f26(void) {
int16_t x145 = -5;
uint16_t x146 = 10355U;
uint16_t x147 = UINT16_MAX;
volatile int8_t x148 = -12;
t26 = (x145+(x146/(x147-x148)));
if (t26 != -5) { NG(); } else { ; }
}
void f27(void) {
uint16_t x150 = UINT16_MAX;
volatile int8_t x151 = 3;
static volatile int16_t x152 = INT16_MIN;
volatile int32_t t27 = 7;
t27 = (x149+(x150/(x151-x152)));
if (t27 != 27) { NG(); } else { ; }
}
void f28(void) {
int32_t x154 = INT32_MIN;
uint16_t x156 = 4U;
int32_t t28 = 127931;
t28 = (x153+(x154/(x155-x156)));
if (t28 != -17426449) { NG(); } else { ; }
}
void f29(void) {
int64_t x157 = INT64_MAX;
int8_t x158 = 19;
volatile int8_t x159 = INT8_MIN;
static volatile int32_t x160 = INT32_MIN;
int64_t t29 = INT64_MAX;
t29 = (x157+(x158/(x159-x160)));
if (t29 != INT64_MAX) { NG(); } else { ; }
}
void f30(void) {
uint32_t x161 = 1219117U;
uint16_t x162 = UINT16_MAX;
uint16_t x163 = 30U;
int8_t x164 = INT8_MIN;
volatile uint32_t t30 = 2084267975U;
t30 = (x161+(x162/(x163-x164)));
if (t30 != 1219531U) { NG(); } else { ; }
}
void f31(void) {
uint32_t x169 = 271273U;
int8_t x171 = -1;
int16_t x172 = INT16_MIN;
uint32_t t31 = 15U;
t31 = (x169+(x170/(x171-x172)));
if (t31 != 271278U) { NG(); } else { ; }
}
void f32(void) {
int64_t x173 = 22666246LL;
uint64_t x175 = 233LLU;
static uint64_t t32 = 5328LLU;
t32 = (x173+(x174/(x175-x176)));
if (t32 != 22666246LLU) { NG(); } else { ; }
}
void f33(void) {
int64_t x177 = 10LL;
int8_t x178 = -1;
volatile int32_t x179 = -1;
volatile int64_t t33 = 1924342625107LL;
t33 = (x177+(x178/(x179-x180)));
if (t33 != 10LL) { NG(); } else { ; }
}
void f34(void) {
int16_t x181 = -508;
uint64_t x182 = 57203306131LLU;
int16_t x183 = -1;
static uint64_t x184 = 538LLU;
t34 = (x181+(x182/(x183-x184)));
if (t34 != 18446744073709551108LLU) { NG(); } else { ; }
}
void f35(void) {
volatile uint64_t x185 = 13963929381332LLU;
uint64_t x186 = 21821LLU;
static volatile int32_t x187 = -100;
static volatile uint64_t t35 = 4794921LLU;
t35 = (x185+(x186/(x187-x188)));
if (t35 != 13963929381332LLU) { NG(); } else { ; }
}
void f36(void) {
static volatile int8_t x189 = INT8_MAX;
uint16_t x190 = 851U;
uint32_t x191 = UINT32_MAX;
uint16_t x192 = 4U;
uint32_t t36 = 209U;
t36 = (x189+(x190/(x191-x192)));
if (t36 != 127U) { NG(); } else { ; }
}
void f37(void) {
static uint64_t x193 = 1323004124095LLU;
uint32_t x195 = 37404039U;
int8_t x196 = 1;
static uint64_t t37 = 719250546223289459LLU;
t37 = (x193+(x194/(x195-x196)));
if (t37 != 1569591726130LLU) { NG(); } else { ; }
}
void f38(void) {
int32_t x197 = INT32_MIN;
int8_t x199 = -1;
volatile int32_t t38 = -31;
t38 = (x197+(x198/(x199-x200)));
if (t38 != -2147483520) { NG(); } else { ; }
}
void f39(void) {
int16_t x205 = 15671;
int8_t x206 = INT8_MIN;
uint8_t x207 = 0U;
volatile int32_t t39 = 72;
t39 = (x205+(x206/(x207-x208)));
if (t39 != 15543) { NG(); } else { ; }
}
void f40(void) {
static uint16_t x209 = UINT16_MAX;
uint16_t x210 = 27U;
int64_t t40 = 7161LL;
t40 = (x209+(x210/(x211-x212)));
if (t40 != 65535LL) { NG(); } else { ; }
}
void f41(void) {
uint64_t x214 = 3721589317192800LLU;
int32_t x215 = 181;
volatile uint32_t x216 = 65840792U;
volatile uint64_t t41 = 16955063LLU;
t41 = (x213+(x214/(x215-x216)));
if (t41 != 880117LLU) { NG(); } else { ; }
}
void f42(void) {
volatile int32_t x217 = INT32_MIN;
int32_t x219 = -1986080;
uint64_t x220 = 3569479839LLU;
volatile uint64_t t42 = 1802691623378746638LLU;
t42 = (x217+(x218/(x219-x220)));
if (t42 != 18446744071562067969LLU) { NG(); } else { ; }
}
void f43(void) {
int16_t x221 = -3;
int32_t x222 = -1;
int16_t x223 = -1;
volatile int32_t t43 = 1691;
t43 = (x221+(x222/(x223-x224)));
if (t43 != -3) { NG(); } else { ; }
}
void f44(void) {
uint8_t x229 = 8U;
int32_t x231 = -1;
uint32_t x232 = 1055U;
volatile uint32_t t44 = 775891933U;
t44 = (x229+(x230/(x231-x232)));
if (t44 != 8U) { NG(); } else { ; }
}
void f45(void) {
int16_t x233 = -232;
volatile int32_t x235 = INT32_MAX;
uint64_t t45 = 263LLU;
t45 = (x233+(x234/(x235-x236)));
if (t45 != 18446744073709551384LLU) { NG(); } else { ; }
}
void f46(void) {
static int64_t x238 = -1LL;
static uint64_t x239 = UINT64_MAX;
static int64_t x240 = 591572LL;
t46 = (x237+(x238/(x239-x240)));
if (t46 != 0LLU) { NG(); } else { ; }
}
void f47(void) {
static int64_t x241 = 577204541LL;
int8_t x242 = INT8_MIN;
int16_t x243 = -2;
volatile int8_t x244 = INT8_MIN;
int64_t t47 = 709600LL;
t47 = (x241+(x242/(x243-x244)));
if (t47 != 577204540LL) { NG(); } else { ; }
}
void f48(void) {
int8_t x246 = 55;
int8_t x248 = -1;
static int32_t t48 = 88388;
t48 = (x245+(x246/(x247-x248)));
if (t48 != 3560) { NG(); } else { ; }
}
void f49(void) {
volatile int8_t x249 = -14;
volatile uint16_t x250 = UINT16_MAX;
int16_t x251 = -1;
uint16_t x252 = UINT16_MAX;
volatile int32_t t49 = -8;
t49 = (x249+(x250/(x251-x252)));
if (t49 != -14) { NG(); } else { ; }
}
void f50(void) {
volatile uint32_t x253 = UINT32_MAX;
volatile uint8_t x254 = 11U;
uint16_t x255 = 2984U;
uint32_t x256 = UINT32_MAX;
uint32_t t50 = UINT32_MAX;
t50 = (x253+(x254/(x255-x256)));
if (t50 != UINT32_MAX) { NG(); } else { ; }
}
void f51(void) {
int64_t x257 = INT64_MAX;
uint16_t x258 = 4506U;
int32_t x259 = -36;
static int32_t x260 = -1;
t51 = (x257+(x258/(x259-x260)));
if (t51 != 9223372036854775679LL) { NG(); } else { ; }
}
void f52(void) {
volatile int64_t x264 = -1LL;
t52 = (x261+(x262/(x263-x264)));
if (t52 != 1LL) { NG(); } else { ; }
}
void f53(void) {
int16_t x266 = INT16_MAX;
int32_t x268 = 123;
int64_t t53 = INT64_MIN;
t53 = (x265+(x266/(x267-x268)));
if (t53 != INT64_MIN) { NG(); } else { ; }
}
void f54(void) {
int32_t x269 = -188722;
int32_t x272 = INT32_MIN;
static uint32_t t54 = 951584039U;
t54 = (x269+(x270/(x271-x272)));
if (t54 != 4294778576U) { NG(); } else { ; }
}
void f55(void) {
int64_t x273 = INT64_MIN;
uint8_t x276 = 6U;
static volatile int64_t t55 = 708227LL;
t55 = (x273+(x274/(x275-x276)));
if (t55 != -9223372036854775807LL) { NG(); } else { ; }
}
void f56(void) {
int64_t x277 = INT64_MIN;
static uint16_t x280 = 104U;
t56 = (x277+(x278/(x279-x280)));
if (t56 != -9223372036834126927LL) { NG(); } else { ; }
}
void f57(void) {
uint16_t x285 = UINT16_MAX;
int8_t x286 = -7;
int32_t x287 = -3;
uint64_t t57 = 97974LLU;
t57 = (x285+(x286/(x287-x288)));
if (t57 != 65535LLU) { NG(); } else { ; }
}
void f58(void) {
static int32_t x290 = -2517;
int8_t x291 = INT8_MAX;
uint32_t x292 = 1637145U;
t58 = (x289+(x290/(x291-x292)));
if (t58 != 103212LLU) { NG(); } else { ; }
}
void f59(void) {
uint64_t x293 = 46926552322LLU;
int32_t x294 = INT32_MIN;
uint8_t x295 = 1U;
static uint64_t t59 = 31268638LLU;
t59 = (x293+(x294/(x295-x296)));
if (t59 != 46909905162LLU) { NG(); } else { ; }
}
void f60(void) {
int16_t x297 = INT16_MIN;
static int16_t x298 = INT16_MIN;
uint32_t x299 = 28313U;
volatile int8_t x300 = -1;
static volatile uint32_t t60 = 756051U;
t60 = (x297+(x298/(x299-x300)));
if (t60 != 118921U) { NG(); } else { ; }
}
void f61(void) {
volatile int64_t x302 = 7132659048LL;
static int64_t x303 = -92901LL;
uint32_t x304 = 34784393U;
uint64_t t61 = 47689007043797695LLU;
t61 = (x301+(x302/(x303-x304)));
if (t61 != 1407237365299302616LLU) { NG(); } else { ; }
}
void f62(void) {
int8_t x305 = -60;
int16_t x306 = INT16_MAX;
volatile int8_t x307 = INT8_MAX;
int64_t x308 = INT64_MAX;
int64_t t62 = 5343101022190387LL;
t62 = (x305+(x306/(x307-x308)));
if (t62 != -60LL) { NG(); } else { ; }
}
void f63(void) {
uint8_t x309 = UINT8_MAX;
static int64_t x311 = -1606297182242005LL;
uint64_t x312 = 1625002918LLU;
volatile uint64_t t63 = 780165875LLU;
t63 = (x309+(x310/(x311-x312)));
if (t63 != 255LLU) { NG(); } else { ; }
}
void f64(void) {
int16_t x314 = -1;
static uint16_t x315 = 2942U;
int32_t x316 = 30347240;
volatile int32_t t64 = INT32_MIN;
t64 = (x313+(x314/(x315-x316)));
if (t64 != INT32_MIN) { NG(); } else { ; }
}
void f65(void) {
static volatile int8_t x317 = INT8_MIN;
static int16_t x318 = INT16_MIN;
static uint8_t x319 = 15U;
t65 = (x317+(x318/(x319-x320)));
if (t65 != 4553) { NG(); } else { ; }
}
void f66(void) {
volatile int8_t x325 = INT8_MAX;
uint32_t x327 = 779211801U;
int64_t x328 = 0LL;
t66 = (x325+(x326/(x327-x328)));
if (t66 != 127LL) { NG(); } else { ; }
}
void f67(void) {
uint64_t x337 = UINT64_MAX;
volatile uint16_t x340 = 12284U;
uint64_t t67 = UINT64_MAX;
t67 = (x337+(x338/(x339-x340)));
if (t67 != UINT64_MAX) { NG(); } else { ; }
}
void f68(void) {
static int64_t x345 = -252LL;
int8_t x346 = INT8_MAX;
volatile int8_t x347 = 1;
int16_t x348 = INT16_MIN;
t68 = (x345+(x346/(x347-x348)));
if (t68 != -252LL) { NG(); } else { ; }
}
void f69(void) {
uint64_t x349 = 13160LLU;
int32_t x350 = -1;
volatile int32_t x351 = -1;
int32_t x352 = -206;
volatile uint64_t t69 = 19518127759LLU;
t69 = (x349+(x350/(x351-x352)));
if (t69 != 13160LLU) { NG(); } else { ; }
}
void f70(void) {
uint64_t x354 = 248828226858LLU;
int16_t x355 = INT16_MIN;
int32_t x356 = INT32_MIN;
volatile uint64_t t70 = 5959718805662240LLU;
t70 = (x353+(x354/(x355-x356)));
if (t70 != 65650LLU) { NG(); } else { ; }
}
void f71(void) {
int32_t x361 = 51867929;
int16_t x362 = -1;
volatile uint8_t x363 = 3U;
t71 = (x361+(x362/(x363-x364)));
if (t71 != 51867929) { NG(); } else { ; }
}
void f72(void) {
int8_t x365 = -1;
static volatile int64_t x366 = -1LL;
int16_t x367 = INT16_MAX;
int8_t x368 = -1;
t72 = (x365+(x366/(x367-x368)));
if (t72 != -1LL) { NG(); } else { ; }
}
void f73(void) {
int32_t x369 = 785;
int16_t x370 = 3688;
static int64_t x371 = 245004432LL;
int64_t t73 = 92827710587542LL;
t73 = (x369+(x370/(x371-x372)));
if (t73 != 785LL) { NG(); } else { ; }
}
void f74(void) {
volatile int32_t x374 = INT32_MIN;
uint8_t x375 = 68U;
static int8_t x376 = INT8_MAX;
static volatile int64_t t74 = -9389765354534LL;
t74 = (x373+(x374/(x375-x376)));
if (t74 != -9223372036818377781LL) { NG(); } else { ; }
}
void f75(void) {
volatile uint32_t x377 = 0U;
int32_t x378 = 67295995;
uint64_t x379 = 1122273193LLU;
int8_t x380 = INT8_MAX;
volatile uint64_t t75 = 33444LLU;
t75 = (x377+(x378/(x379-x380)));
if (t75 != 0LLU) { NG(); } else { ; }
}
void f76(void) {
int64_t x381 = -3726LL;
volatile int8_t x382 = -4;
int16_t x383 = -1;
static volatile int16_t x384 = INT16_MIN;
int64_t t76 = -77LL;
t76 = (x381+(x382/(x383-x384)));
if (t76 != -3726LL) { NG(); } else { ; }
}
void f77(void) {
int16_t x385 = -538;
uint32_t x386 = UINT32_MAX;
static int64_t x388 = -15LL;
int64_t t77 = 1758473607LL;
t77 = (x385+(x386/(x387-x388)));
if (t77 != 11097568LL) { NG(); } else { ; }
}
void f78(void) {
int32_t x389 = -1;
int8_t x391 = -3;
int8_t x392 = 5;
int64_t t78 = 948873LL;
t78 = (x389+(x390/(x391-x392)));
if (t78 != -13739837716757LL) { NG(); } else { ; }
}
void f79(void) {
int8_t x393 = INT8_MIN;
int32_t x394 = INT32_MIN;
static int32_t x395 = -55037339;
int8_t x396 = INT8_MIN;
static volatile int32_t t79 = 106673;
t79 = (x393+(x394/(x395-x396)));
if (t79 != -89) { NG(); } else { ; }
}
void f80(void) {
int8_t x401 = -1;
int16_t x402 = 9;
uint32_t x403 = UINT32_MAX;
uint32_t t80 = UINT32_MAX;
t80 = (x401+(x402/(x403-x404)));
if (t80 != UINT32_MAX) { NG(); } else { ; }
}
void f81(void) {
uint32_t x405 = UINT32_MAX;
static uint64_t x406 = 3548790437801LLU;
static int64_t x407 = INT64_MIN;
int32_t x408 = -1;
volatile uint64_t t81 = 13994351553LLU;
t81 = (x405+(x406/(x407-x408)));
if (t81 != 4294967295LLU) { NG(); } else { ; }
}
void f82(void) {
int8_t x409 = INT8_MIN;
int32_t x410 = INT32_MIN;
static uint64_t x411 = 134189510734429LLU;
volatile uint64_t x412 = 6LLU;
t82 = (x409+(x410/(x411-x412)));
if (t82 != 137339LLU) { NG(); } else { ; }
}
void f83(void) {
int32_t x424 = INT32_MIN;
volatile uint64_t t83 = 766267542149LLU;
t83 = (x421+(x422/(x423-x424)));
if (t83 != 2147483647LLU) { NG(); } else { ; }
}
void f84(void) {
static int64_t x429 = INT64_MIN;
uint64_t x430 = UINT64_MAX;
static int32_t x431 = 0;
static int16_t x432 = INT16_MIN;
static volatile uint64_t t84 = 28387LLU;
t84 = (x429+(x430/(x431-x432)));
if (t84 != 9223934986808197119LLU) { NG(); } else { ; }
}
void f85(void) {
uint8_t x433 = 3U;
int32_t x434 = INT32_MIN;
uint64_t x435 = 294156LLU;
t85 = (x433+(x434/(x435-x436)));
if (t85 != 8588758131LLU) { NG(); } else { ; }
}
void f86(void) {
volatile int8_t x437 = -29;
int16_t x438 = INT16_MIN;
volatile uint8_t x439 = UINT8_MAX;
static uint64_t x440 = 125202802023454LLU;
volatile uint64_t t86 = 2647LLU;
t86 = (x437+(x438/(x439-x440)));
if (t86 != 18446744073709551588LLU) { NG(); } else { ; }
}
void f87(void) {
uint32_t x441 = UINT32_MAX;
static uint32_t x442 = 17796U;
static uint8_t x443 = UINT8_MAX;
static int64_t x444 = -1LL;
static int64_t t87 = 104332692977720493LL;
t87 = (x441+(x442/(x443-x444)));
if (t87 != 4294967364LL) { NG(); } else { ; }
}
void f88(void) {
static uint16_t x445 = 47U;
int64_t x446 = INT64_MIN;
static int32_t x447 = -3;
volatile int16_t x448 = -14331;
int64_t t88 = 9180953757784LL;
t88 = (x445+(x446/(x447-x448)));
if (t88 != -643730600003775LL) { NG(); } else { ; }
}
void f89(void) {
uint32_t x449 = 14535U;
int64_t x450 = INT64_MIN;
uint64_t x451 = 446886LLU;
static int64_t x452 = INT64_MIN;
t89 = (x449+(x450/(x451-x452)));
if (t89 != 14535LLU) { NG(); } else { ; }
}
void f90(void) {
int8_t x454 = INT8_MAX;
int8_t x455 = INT8_MIN;
volatile int64_t t90 = 48748462781LL;
t90 = (x453+(x454/(x455-x456)));
if (t90 != 27LL) { NG(); } else { ; }
}
void f91(void) {
uint64_t x457 = 86507035034697LLU;
t91 = (x457+(x458/(x459-x460)));
if (t91 != 86507035034697LLU) { NG(); } else { ; }
}
void f92(void) {
static int8_t x461 = INT8_MIN;
uint16_t x462 = UINT16_MAX;
uint32_t x464 = 10731U;
t92 = (x461+(x462/(x463-x464)));
if (t92 != 4294967169U) { NG(); } else { ; }
}
void f93(void) {
static int32_t x465 = INT32_MIN;
int8_t x466 = -1;
uint8_t x467 = 2U;
int64_t x468 = 3399LL;
volatile int64_t t93 = -152725866853113665LL;
t93 = (x465+(x466/(x467-x468)));
if (t93 != -2147483648LL) { NG(); } else { ; }
}
void f94(void) {
int16_t x469 = INT16_MIN;
static int32_t x470 = INT32_MAX;
volatile uint8_t x471 = 123U;
uint64_t x472 = UINT64_MAX;
volatile uint64_t t94 = 4305581537393LLU;
t94 = (x469+(x470/(x471-x472)));
if (t94 != 17285648LLU) { NG(); } else { ; }
}
void f95(void) {
int8_t x473 = -2;
int32_t x474 = -1039527300;
uint64_t x475 = 1619744719LLU;
int16_t x476 = INT16_MIN;
uint64_t t95 = 500LLU;
t95 = (x473+(x474/(x475-x476)));
if (t95 != 11388443300LLU) { NG(); } else { ; }
}
void f96(void) {
int32_t x477 = -1;
int32_t x478 = 1;
int8_t x479 = INT8_MIN;
int16_t x480 = INT16_MIN;
int32_t t96 = 3;
t96 = (x477+(x478/(x479-x480)));
if (t96 != -1) { NG(); } else { ; }
}
void f97(void) {
uint8_t x481 = 35U;
int8_t x482 = INT8_MAX;
volatile int16_t x484 = INT16_MIN;
t97 = (x481+(x482/(x483-x484)));
if (t97 != 35) { NG(); } else { ; }
}
void f98(void) {
volatile int32_t x485 = INT32_MIN;
int8_t x487 = -1;
uint32_t x488 = 9U;
static uint32_t t98 = 7937777U;
t98 = (x485+(x486/(x487-x488)));
if (t98 != 2147483649U) { NG(); } else { ; }
}
void f99(void) {
int64_t x489 = -14LL;
uint64_t x490 = UINT64_MAX;
volatile int16_t x492 = INT16_MAX;
volatile uint64_t t99 = 6236019830105792965LLU;
t99 = (x489+(x490/(x491-x492)));
if (t99 != 1782759870169LLU) { NG(); } else { ; }
}
void f100(void) {
static volatile uint8_t x493 = 94U;
int64_t x494 = -1LL;
uint64_t x495 = 2684LLU;
static int8_t x496 = -1;
uint64_t t100 = 232247258LLU;
t100 = (x493+(x494/(x495-x496)));
if (t100 != 6870295744398437LLU) { NG(); } else { ; }
}
void f101(void) {
static uint64_t x497 = 141LLU;
static int32_t x498 = -1;
uint16_t x499 = 529U;
volatile int8_t x500 = INT8_MIN;
uint64_t t101 = 1520370509799LLU;
t101 = (x497+(x498/(x499-x500)));
if (t101 != 141LLU) { NG(); } else { ; }
}
void f102(void) {
volatile uint32_t x505 = UINT32_MAX;
static int8_t x506 = INT8_MIN;
volatile int64_t x507 = INT64_MAX;
volatile uint64_t x508 = 35820878LLU;
volatile uint64_t t102 = 7479766146266871636LLU;
t102 = (x505+(x506/(x507-x508)));
if (t102 != 4294967297LLU) { NG(); } else { ; }
}
void f103(void) {
static volatile int8_t x509 = INT8_MAX;
uint32_t x511 = 122038U;
static int64_t x512 = -1LL;
volatile int64_t t103 = -19194962730196965LL;
t103 = (x509+(x510/(x511-x512)));
if (t103 != 127LL) { NG(); } else { ; }
}
void f104(void) {
int32_t x513 = INT32_MIN;
int32_t x514 = INT32_MIN;
static int16_t x516 = INT16_MAX;
t104 = (x513+(x514/(x515-x516)));
if (t104 != -2147418366) { NG(); } else { ; }
}
void f105(void) {
volatile int16_t x517 = INT16_MIN;
int16_t x518 = 180;
volatile int16_t x519 = INT16_MIN;
static int8_t x520 = -1;
volatile int32_t t105 = -959480217;
t105 = (x517+(x518/(x519-x520)));
if (t105 != -32768) { NG(); } else { ; }
}
void f106(void) {
int64_t x525 = INT64_MIN;
int8_t x526 = 0;
uint64_t x527 = UINT64_MAX;
static uint64_t t106 = 296LLU;
t106 = (x525+(x526/(x527-x528)));
if (t106 != 9223372036854775808LLU) { NG(); } else { ; }
}
void f107(void) {
int16_t x530 = -1;
int64_t x531 = INT64_MAX;
int8_t x532 = INT8_MAX;
volatile int64_t t107 = 9379698108771LL;
t107 = (x529+(x530/(x531-x532)));
if (t107 != -1LL) { NG(); } else { ; }
}
void f108(void) {
int32_t x537 = -6;
int32_t x538 = INT32_MAX;
volatile int32_t x539 = INT32_MIN;
uint64_t x540 = 176091952LLU;
volatile uint64_t t108 = 5412802098823967LLU;
t108 = (x537+(x538/(x539-x540)));
if (t108 != 18446744073709551610LLU) { NG(); } else { ; }
}
void f109(void) {
int16_t x542 = INT16_MIN;
int64_t x543 = -25LL;
uint32_t x544 = 19870U;
volatile int64_t t109 = 2671273LL;
t109 = (x541+(x542/(x543-x544)));
if (t109 != 0LL) { NG(); } else { ; }
}
void f110(void) {
static int64_t x545 = INT64_MIN;
uint32_t x546 = 14145U;
int64_t t110 = INT64_MIN;
t110 = (x545+(x546/(x547-x548)));
if (t110 != INT64_MIN) { NG(); } else { ; }
}
void f111(void) {
volatile int64_t x549 = -1LL;
uint32_t x550 = 223038U;
uint8_t x551 = UINT8_MAX;
static int16_t x552 = INT16_MIN;
int64_t t111 = 2937949409LL;
t111 = (x549+(x550/(x551-x552)));
if (t111 != 5LL) { NG(); } else { ; }
}
void f112(void) {
uint16_t x553 = 1411U;
volatile int32_t x554 = 492;
int8_t x555 = INT8_MAX;
int16_t x556 = -3833;
volatile int32_t t112 = 833;
t112 = (x553+(x554/(x555-x556)));
if (t112 != 1411) { NG(); } else { ; }
}
void f113(void) {
uint8_t x557 = 94U;
volatile uint16_t x558 = UINT16_MAX;
static int64_t x559 = INT64_MIN;
int8_t x560 = INT8_MIN;
static int64_t t113 = 794367638LL;
t113 = (x557+(x558/(x559-x560)));
if (t113 != 94LL) { NG(); } else { ; }
}
void f114(void) {
volatile uint32_t x561 = 9824U;
static volatile uint8_t x564 = UINT8_MAX;
volatile uint32_t t114 = 21152U;
t114 = (x561+(x562/(x563-x564)));
if (t114 != 9824U) { NG(); } else { ; }
}
void f115(void) {
static int8_t x569 = -1;
uint8_t x570 = 5U;
int64_t x571 = INT64_MAX;
uint16_t x572 = UINT16_MAX;
volatile int64_t t115 = -253LL;
t115 = (x569+(x570/(x571-x572)));
if (t115 != -1LL) { NG(); } else { ; }
}
void f116(void) {
volatile int8_t x573 = -1;
int8_t x574 = INT8_MAX;
uint8_t x575 = 1U;
int16_t x576 = -6411;
static volatile int32_t t116 = 699682284;
t116 = (x573+(x574/(x575-x576)));
if (t116 != -1) { NG(); } else { ; }
}
void f117(void) {
uint8_t x581 = 5U;
int64_t x582 = -1LL;
volatile uint8_t x584 = 100U;
int64_t t117 = 117LL;
t117 = (x581+(x582/(x583-x584)));
if (t117 != 5LL) { NG(); } else { ; }
}
void f118(void) {
volatile int16_t x585 = INT16_MAX;
volatile int16_t x586 = 965;
int32_t x587 = INT32_MIN;
volatile int32_t t118 = 5954;
t118 = (x585+(x586/(x587-x588)));
if (t118 != 32767) { NG(); } else { ; }
}
void f119(void) {
int32_t x590 = INT32_MAX;
static volatile int8_t x591 = INT8_MIN;
t119 = (x589+(x590/(x591-x592)));
if (t119 != 1176062) { NG(); } else { ; }
}
void f120(void) {
static int32_t x594 = INT32_MIN;
volatile uint8_t x595 = 3U;
int16_t x596 = 1535;
int32_t t120 = 25;
t120 = (x593+(x594/(x595-x596)));
if (t120 != 1402150) { NG(); } else { ; }
}
void f121(void) {
int32_t x597 = INT32_MIN;
uint32_t x598 = 2676009U;
int8_t x599 = 3;
volatile uint16_t x600 = 35U;
static uint32_t t121 = 617255454U;
t121 = (x597+(x598/(x599-x600)));
if (t121 != 2147483648U) { NG(); } else { ; }
}
void f122(void) {
int64_t x601 = INT64_MIN;
int16_t x602 = INT16_MIN;
uint16_t x603 = UINT16_MAX;
static volatile int8_t x604 = INT8_MAX;
int64_t t122 = INT64_MIN;
t122 = (x601+(x602/(x603-x604)));
if (t122 != INT64_MIN) { NG(); } else { ; }
}
void f123(void) {
static volatile int8_t x605 = INT8_MIN;
int64_t x606 = INT64_MAX;
static volatile uint64_t x607 = 1770677596769638LLU;
uint32_t x608 = 0U;
uint64_t t123 = 8885326920781175161LLU;
t123 = (x605+(x606/(x607-x608)));
if (t123 != 5080LLU) { NG(); } else { ; }
}
void f124(void) {
int64_t x611 = -1303LL;
uint32_t x612 = 1874515429U;
t124 = (x609+(x610/(x611-x612)));
if (t124 != -1LL) { NG(); } else { ; }
}
void f125(void) {
int64_t x613 = -1LL;
int16_t x614 = -238;
static uint32_t x615 = 21882715U;
volatile int64_t t125 = -6407022872795256LL;
t125 = (x613+(x614/(x615-x616)));
if (t125 != 195LL) { NG(); } else { ; }
}
void f126(void) {
int64_t x621 = -344819LL;
volatile uint8_t x622 = 123U;
int64_t x624 = INT64_MAX;
volatile int64_t t126 = -33154592756600318LL;
t126 = (x621+(x622/(x623-x624)));
if (t126 != -344819LL) { NG(); } else { ; }
}
void f127(void) {
static uint8_t x625 = UINT8_MAX;
volatile int64_t x626 = -1LL;
int8_t x627 = -1;
volatile uint16_t x628 = 44U;
volatile int64_t t127 = -39LL;
t127 = (x625+(x626/(x627-x628)));
if (t127 != 255LL) { NG(); } else { ; }
}
void f128(void) {
volatile int16_t x633 = 1;
int16_t x634 = INT16_MIN;
int64_t x635 = INT64_MAX;
uint32_t x636 = UINT32_MAX;
int64_t t128 = -6568728590006136LL;
t128 = (x633+(x634/(x635-x636)));
if (t128 != 1LL) { NG(); } else { ; }
}
void f129(void) {
int32_t x637 = INT32_MIN;
uint8_t x638 = 1U;
volatile uint64_t x639 = 2516568542LLU;
int32_t x640 = 330283;
volatile uint64_t t129 = 502587098237LLU;
t129 = (x637+(x638/(x639-x640)));
if (t129 != 18446744071562067968LLU) { NG(); } else { ; }
}
void f130(void) {
static int16_t x641 = -1;
static int16_t x642 = -1;
int64_t x643 = 1894943580LL;
uint64_t t130 = 44863401496123LLU;
t130 = (x641+(x642/(x643-x644)));
if (t130 != 9735079394LLU) { NG(); } else { ; }
}
void f131(void) {
int16_t x645 = -1;
int32_t x646 = 262886368;
volatile int64_t x647 = -26930265LL;
int16_t x648 = INT16_MAX;
volatile int64_t t131 = 3389763933356640LL;
t131 = (x645+(x646/(x647-x648)));
if (t131 != -10LL) { NG(); } else { ; }
}
void f132(void) {
int32_t x649 = -1040;
int8_t x650 = INT8_MIN;
volatile int32_t x651 = INT32_MIN;
int64_t x652 = 50528369LL;
volatile int64_t t132 = -4278LL;
t132 = (x649+(x650/(x651-x652)));
if (t132 != -1040LL) { NG(); } else { ; }
}
void f133(void) {
int32_t x653 = INT32_MIN;
static uint8_t x656 = UINT8_MAX;
volatile int32_t t133 = INT32_MIN;
t133 = (x653+(x654/(x655-x656)));
if (t133 != INT32_MIN) { NG(); } else { ; }
}
void f134(void) {
int64_t x657 = 520552751461LL;
static int32_t x658 = -5891589;
volatile int16_t x659 = 69;
uint32_t x660 = UINT32_MAX;
int64_t t134 = -1286878LL;
t134 = (x657+(x658/(x659-x660)));
if (t134 != 520614023971LL) { NG(); } else { ; }
}
void f135(void) {
int16_t x665 = INT16_MIN;
int16_t x666 = 1899;
uint64_t x667 = UINT64_MAX;
uint64_t x668 = 3LLU;
uint64_t t135 = 302LLU;
t135 = (x665+(x666/(x667-x668)));
if (t135 != 18446744073709518848LLU) { NG(); } else { ; }
}
void f136(void) {
int64_t x669 = INT64_MIN;
volatile int32_t x670 = INT32_MIN;
volatile uint32_t x671 = 6454U;
int32_t x672 = 211372682;
t136 = (x669+(x670/(x671-x672)));
if (t136 != INT64_MIN) { NG(); } else { ; }
}
void f137(void) {
int16_t x674 = INT16_MIN;
uint8_t x675 = 53U;
int32_t x676 = 169075;
t137 = (x673+(x674/(x675-x676)));
if (t137 != INT32_MIN) { NG(); } else { ; }
}
void f138(void) {
uint8_t x681 = UINT8_MAX;
static int64_t x682 = INT64_MIN;
int32_t x683 = -1;
int16_t x684 = INT16_MAX;
t138 = (x681+(x682/(x683-x684)));
if (t138 != 281474976710911LL) { NG(); } else { ; }
}
void f139(void) {
int32_t x685 = INT32_MIN;
static int16_t x686 = -1;
int8_t x687 = INT8_MIN;
static uint32_t x688 = 337630U;
t139 = (x685+(x686/(x687-x688)));
if (t139 != 2147483649U) { NG(); } else { ; }
}
void f140(void) {
int16_t x693 = -1;
volatile uint16_t x694 = UINT16_MAX;
volatile uint8_t x695 = UINT8_MAX;
volatile int64_t x696 = -199920LL;
int64_t t140 = 1LL;
t140 = (x693+(x694/(x695-x696)));
if (t140 != -1LL) { NG(); } else { ; }
}
void f141(void) {
int8_t x697 = 14;
int16_t x698 = -14144;
static volatile int8_t x699 = -1;
volatile uint32_t x700 = 107988U;
static volatile uint32_t t141 = 704060U;
t141 = (x697+(x698/(x699-x700)));
if (t141 != 15U) { NG(); } else { ; }
}
void f142(void) {
static int32_t x701 = 32716;
static uint32_t x702 = UINT32_MAX;
uint32_t x703 = 66874941U;
static volatile uint32_t t142 = 296406011U;
t142 = (x701+(x702/(x703-x704)));
if (t142 != 32780U) { NG(); } else { ; }
}
void f143(void) {
static int32_t x705 = -359207732;
uint16_t x706 = 7U;
int16_t x707 = INT16_MIN;
int32_t t143 = -4113003;
t143 = (x705+(x706/(x707-x708)));
if (t143 != -359207732) { NG(); } else { ; }
}
void f144(void) {
int32_t x710 = INT32_MAX;
int8_t x711 = INT8_MIN;
volatile uint64_t t144 = 170761960LLU;
t144 = (x709+(x710/(x711-x712)));
if (t144 != 18446744073692910933LLU) { NG(); } else { ; }
}
void f145(void) {
volatile uint8_t x713 = 0U;
int16_t x714 = -1;
volatile uint64_t x715 = 1768456862873LLU;
uint8_t x716 = 29U;
uint64_t t145 = 9183778365LLU;
t145 = (x713+(x714/(x715-x716)));
if (t145 != 10430983LLU) { NG(); } else { ; }
}
void f146(void) {
static uint16_t x717 = 139U;
static volatile int16_t x718 = INT16_MIN;
static int16_t x719 = INT16_MAX;
int64_t x720 = INT64_MAX;
t146 = (x717+(x718/(x719-x720)));
if (t146 != 139LL) { NG(); } else { ; }
}
void f147(void) {
uint32_t x721 = UINT32_MAX;
static uint8_t x723 = 46U;
int16_t x724 = INT16_MIN;
uint32_t t147 = UINT32_MAX;
t147 = (x721+(x722/(x723-x724)));
if (t147 != UINT32_MAX) { NG(); } else { ; }
}
void f148(void) {
int16_t x726 = INT16_MIN;
volatile uint64_t x727 = 7698611241232688LLU;
int8_t x728 = INT8_MIN;
uint64_t t148 = 54125219918LLU;
t148 = (x725+(x726/(x727-x728)));
if (t148 != 18446744071562070364LLU) { NG(); } else { ; }
}
void f149(void) {
uint8_t x730 = 12U;
uint64_t x731 = UINT64_MAX;
int8_t x732 = 17;
t149 = (x729+(x730/(x731-x732)));
if (t149 != 18446744073709551604LLU) { NG(); } else { ; }
}
void f150(void) {
static int16_t x734 = 3584;
volatile int64_t x735 = INT64_MIN;
volatile int64_t x736 = -65LL;
t150 = (x733+(x734/(x735-x736)));
if (t150 != 1658LL) { NG(); } else { ; }
}
void f151(void) {
int32_t x737 = INT32_MIN;
uint64_t x738 = 1201870554549LLU;
volatile int16_t x739 = 13;
uint8_t x740 = 7U;
static volatile uint64_t t151 = 4196588877LLU;
t151 = (x737+(x738/(x739-x740)));
if (t151 != 198164275443LLU) { NG(); } else { ; }
}
void f152(void) {
int32_t x741 = 229409887;
int32_t x742 = INT32_MAX;
int64_t x743 = 44LL;
int16_t x744 = INT16_MAX;
int64_t t152 = 323253LL;
t152 = (x741+(x742/(x743-x744)));
if (t152 != 229344261LL) { NG(); } else { ; }
}
void f153(void) {
int16_t x745 = INT16_MIN;
static uint8_t x746 = 9U;
volatile int8_t x747 = INT8_MIN;
int8_t x748 = 4;
int32_t t153 = 28217748;
t153 = (x745+(x746/(x747-x748)));
if (t153 != -32768) { NG(); } else { ; }
}
void f154(void) {
int8_t x749 = -57;
volatile int16_t x750 = -1;
static uint64_t x751 = UINT64_MAX;
int32_t x752 = INT32_MIN;
volatile uint64_t t154 = 27699196687102LLU;
t154 = (x749+(x750/(x751-x752)));
if (t154 != 8589934539LLU) { NG(); } else { ; }
}
void f155(void) {
int8_t x754 = INT8_MIN;
int16_t x755 = 2574;
int8_t x756 = -1;
int32_t t155 = -3;
t155 = (x753+(x754/(x755-x756)));
if (t155 != 65535) { NG(); } else { ; }
}
void f156(void) {
int32_t x757 = -263816;
int8_t x758 = -1;
int16_t x759 = 1;
int64_t x760 = INT64_MAX;
t156 = (x757+(x758/(x759-x760)));
if (t156 != -263816LL) { NG(); } else { ; }
}
void f157(void) {
static int32_t x761 = 889;
volatile int64_t x762 = 5547141337509799LL;
static uint16_t x764 = 1283U;
int64_t t157 = -568776522311LL;
t157 = (x761+(x762/(x763-x764)));
if (t157 != 2438303885508LL) { NG(); } else { ; }
}
void f158(void) {
int32_t x765 = 7656469;
uint16_t x766 = UINT16_MAX;
int8_t x767 = INT8_MAX;
int16_t x768 = -4;
int32_t t158 = 1500325;
t158 = (x765+(x766/(x767-x768)));
if (t158 != 7656969) { NG(); } else { ; }
}
void f159(void) {
volatile int8_t x769 = 1;
uint64_t x770 = UINT64_MAX;
uint64_t x771 = 17072LLU;
static int8_t x772 = INT8_MAX;
uint64_t t159 = 110171LLU;
t159 = (x769+(x770/(x771-x772)));
if (t159 != 1088624613379142LLU) { NG(); } else { ; }
}
void f160(void) {
int64_t x778 = -10059266294698629LL;
static int8_t x779 = INT8_MAX;
int64_t x780 = 8696LL;
volatile int64_t t160 = 17948LL;
t160 = (x777+(x778/(x779-x780)));
if (t160 != 1173913676716LL) { NG(); } else { ; }
}
void f161(void) {
static volatile uint8_t x786 = 3U;
static int8_t x787 = -1;
int32_t x788 = INT32_MIN;
t161 = (x785+(x786/(x787-x788)));
if (t161 != -3) { NG(); } else { ; }
}
void f162(void) {
volatile uint16_t x789 = 0U;
int32_t x790 = 8057;
int64_t x791 = -1LL;
uint64_t t162 = 67320303649617LLU;
t162 = (x789+(x790/(x791-x792)));
if (t162 != 0LLU) { NG(); } else { ; }
}
void f163(void) {
volatile int64_t x793 = 42130LL;
int16_t x794 = -203;
uint8_t x795 = UINT8_MAX;
uint16_t x796 = UINT16_MAX;
int64_t t163 = 1043935623887089LL;
t163 = (x793+(x794/(x795-x796)));
if (t163 != 42130LL) { NG(); } else { ; }
}
void f164(void) {
int8_t x797 = INT8_MIN;
volatile int16_t x798 = INT16_MAX;
int64_t x799 = INT64_MIN;
uint64_t x800 = 3LLU;
uint64_t t164 = 4721354795724043LLU;
t164 = (x797+(x798/(x799-x800)));
if (t164 != 18446744073709551488LLU) { NG(); } else { ; }
}
void f165(void) {
int32_t x802 = INT32_MIN;
static uint64_t x803 = 2851LLU;
int64_t x804 = INT64_MIN;
volatile uint64_t t165 = 258319919LLU;
t165 = (x801+(x802/(x803-x804)));
if (t165 != 19323682LLU) { NG(); } else { ; }
}
void f166(void) {
volatile int64_t x809 = -24931LL;
static int32_t x810 = -1;
volatile int64_t t166 = -236LL;
t166 = (x809+(x810/(x811-x812)));
if (t166 != -24931LL) { NG(); } else { ; }
}
void f167(void) {
int64_t x817 = INT64_MIN;
uint32_t x818 = UINT32_MAX;
uint8_t x819 = 4U;
static volatile int64_t t167 = 243LL;
t167 = (x817+(x818/(x819-x820)));
if (t167 != -9223372036854775807LL) { NG(); } else { ; }
}
void f168(void) {
int64_t x821 = INT64_MIN;
uint8_t x823 = 9U;
int64_t x824 = -3805364LL;
static volatile int64_t t168 = INT64_MIN;
t168 = (x821+(x822/(x823-x824)));
if (t168 != INT64_MIN) { NG(); } else { ; }
}
void f169(void) {
uint16_t x826 = 0U;
uint32_t x827 = 38741123U;
static uint32_t x828 = UINT32_MAX;
int64_t t169 = -34608358LL;
t169 = (x825+(x826/(x827-x828)));
if (t169 != 448416872273122073LL) { NG(); } else { ; }
}
void f170(void) {
static int8_t x837 = INT8_MAX;
static int32_t x838 = INT32_MAX;
uint16_t x839 = UINT16_MAX;
static uint16_t x840 = 22U;
volatile int32_t t170 = 0;
t170 = (x837+(x838/(x839-x840)));
if (t170 != 32906) { NG(); } else { ; }
}
void f171(void) {
int32_t x841 = INT32_MIN;
uint64_t x842 = 552524771065409196LLU;
volatile int64_t x844 = INT64_MIN;
volatile uint64_t t171 = 21LLU;
t171 = (x841+(x842/(x843-x844)));
if (t171 != 18446744071562067968LLU) { NG(); } else { ; }
}
void f172(void) {
uint32_t x845 = 2U;
uint32_t x846 = UINT32_MAX;
uint8_t x847 = 77U;
uint64_t x848 = 29978LLU;
static volatile uint64_t t172 = 1907192569299LLU;
t172 = (x845+(x846/(x847-x848)));
if (t172 != 2LLU) { NG(); } else { ; }
}
void f173(void) {
int16_t x849 = INT16_MAX;
int64_t x850 = INT64_MIN;
int8_t x851 = -1;
int32_t x852 = INT32_MIN;
static volatile int64_t t173 = -941588008LL;
t173 = (x849+(x850/(x851-x852)));
if (t173 != -4294934531LL) { NG(); } else { ; }
}
void f174(void) {
static int8_t x855 = 1;
int64_t x856 = 76LL;
int64_t t174 = 6973293LL;
t174 = (x853+(x854/(x855-x856)));
if (t174 != 9223372036797509577LL) { NG(); } else { ; }
}
void f175(void) {
static uint64_t x857 = UINT64_MAX;
int16_t x858 = -1;
uint64_t x859 = 21696796492605942LLU;
uint16_t x860 = 2247U;
volatile uint64_t t175 = 29666LLU;
t175 = (x857+(x858/(x859-x860)));
if (t175 != 849LLU) { NG(); } else { ; }
}
void f176(void) {
static volatile int64_t x869 = -52566575583LL;
int32_t x870 = INT32_MAX;
uint64_t x871 = 20488333875048LLU;
int8_t x872 = INT8_MAX;
t176 = (x869+(x870/(x871-x872)));
if (t176 != 18446744021142976033LLU) { NG(); } else { ; }
}
void f177(void) {
volatile int64_t x885 = -48LL;
volatile uint16_t x887 = UINT16_MAX;
volatile int16_t x888 = INT16_MIN;
volatile int64_t t177 = -241129147831701480LL;
t177 = (x885+(x886/(x887-x888)));
if (t177 != -48LL) { NG(); } else { ; }
}
void f178(void) {
uint32_t x889 = 21251U;
uint16_t x890 = 15U;
int16_t x891 = INT16_MIN;
static volatile uint32_t t178 = 1531343427U;
t178 = (x889+(x890/(x891-x892)));
if (t178 != 21251U) { NG(); } else { ; }
}
void f179(void) {
int8_t x893 = INT8_MAX;
int16_t x895 = -2;
int16_t x896 = INT16_MAX;
int32_t t179 = -169;
t179 = (x893+(x894/(x895-x896)));
if (t179 != 127) { NG(); } else { ; }
}
void f180(void) {
int16_t x898 = -1;
int32_t x899 = -4;
uint32_t t180 = 13U;
t180 = (x897+(x898/(x899-x900)));
if (t180 != 0U) { NG(); } else { ; }
}
void f181(void) {
static uint64_t x905 = 904808LLU;
uint8_t x906 = UINT8_MAX;
uint8_t x908 = 11U;
static volatile uint64_t t181 = 7711436767LLU;
t181 = (x905+(x906/(x907-x908)));
if (t181 != 904810LLU) { NG(); } else { ; }
}
void f182(void) {
int64_t x913 = INT64_MAX;
uint64_t x916 = 175839742477LLU;
uint64_t t182 = 100946842LLU;
t182 = (x913+(x914/(x915-x916)));
if (t182 != 9223372036854775807LLU) { NG(); } else { ; }
}
void f183(void) {
uint8_t x919 = 49U;
volatile int8_t x920 = INT8_MAX;
volatile int32_t t183 = 0;
t183 = (x917+(x918/(x919-x920)));
if (t183 != -2147483647) { NG(); } else { ; }
}
void f184(void) {
volatile uint64_t x925 = 9913855632281LLU;
volatile uint32_t x926 = 1783226U;
int16_t x927 = INT16_MIN;
int64_t x928 = -410651LL;
uint64_t t184 = 78LLU;
t184 = (x925+(x926/(x927-x928)));
if (t184 != 9913855632285LLU) { NG(); } else { ; }
}
void f185(void) {
int64_t x933 = -1LL;
static uint64_t x934 = UINT64_MAX;
uint64_t t185 = 46903212969609LLU;
t185 = (x933+(x934/(x935-x936)));
if (t185 != 86992016419207LLU) { NG(); } else { ; }
}
void f186(void) {
static uint64_t x937 = 0LLU;
int8_t x938 = -1;
static int16_t x940 = INT16_MAX;
volatile uint64_t t186 = 7LLU;
t186 = (x937+(x938/(x939-x940)));
if (t186 != 0LLU) { NG(); } else { ; }
}
void f187(void) {
uint64_t x945 = UINT64_MAX;
int32_t x946 = -18900;
volatile uint64_t x947 = 2674523351186199934LLU;
int64_t x948 = INT64_MIN;
volatile uint64_t t187 = 3514393039139194LLU;
t187 = (x945+(x946/(x947-x948)));
if (t187 != 0LLU) { NG(); } else { ; }
}
void f188(void) {
int8_t x949 = INT8_MAX;
static int16_t x950 = INT16_MAX;
static int32_t x951 = INT32_MAX;
volatile uint32_t x952 = 22338033U;
uint32_t t188 = 3U;
t188 = (x949+(x950/(x951-x952)));
if (t188 != 127U) { NG(); } else { ; }
}
void f189(void) {
int8_t x953 = -1;
static volatile int64_t x954 = -51LL;
volatile uint32_t x955 = 4901U;
int32_t x956 = INT32_MIN;
volatile int64_t t189 = -2LL;
t189 = (x953+(x954/(x955-x956)));
if (t189 != -1LL) { NG(); } else { ; }
}
void f190(void) {
int32_t x957 = 76489;
uint64_t x958 = UINT64_MAX;
int32_t x959 = -1;
t190 = (x957+(x958/(x959-x960)));
if (t190 != 76490LLU) { NG(); } else { ; }
}
void f191(void) {
volatile uint8_t x961 = UINT8_MAX;
uint8_t x964 = UINT8_MAX;
t191 = (x961+(x962/(x963-x964)));
if (t191 != 255U) { NG(); } else { ; }
}
void f192(void) {
uint8_t x965 = 0U;
uint16_t x966 = 1857U;
volatile int32_t x967 = INT32_MAX;
uint16_t x968 = UINT16_MAX;
int32_t t192 = 4049;
t192 = (x965+(x966/(x967-x968)));
if (t192 != 0) { NG(); } else { ; }
}
void f193(void) {
int16_t x969 = -1831;
int8_t x970 = -1;
static volatile uint64_t x971 = UINT64_MAX;
volatile uint8_t x972 = UINT8_MAX;
t193 = (x969+(x970/(x971-x972)));
if (t193 != 18446744073709549786LLU) { NG(); } else { ; }
}
void f194(void) {
static uint8_t x974 = 1U;
int32_t x976 = INT32_MAX;
t194 = (x973+(x974/(x975-x976)));
if (t194 != 806831U) { NG(); } else { ; }
}
void f195(void) {
int32_t x978 = INT32_MIN;
int8_t x979 = INT8_MIN;
int32_t x980 = -1;
t195 = (x977+(x978/(x979-x980)));
if (t195 != -9223372036837866488LL) { NG(); } else { ; }
}
void f196(void) {
static volatile int32_t x981 = INT32_MAX;
static int16_t x982 = INT16_MIN;
int32_t t196 = INT32_MAX;
t196 = (x981+(x982/(x983-x984)));
if (t196 != INT32_MAX) { NG(); } else { ; }
}
void f197(void) {
int32_t x985 = -1;
static int32_t x986 = 287;
int64_t x987 = -1LL;
volatile int16_t x988 = INT16_MIN;
volatile int64_t t197 = 0LL;
t197 = (x985+(x986/(x987-x988)));
if (t197 != -1LL) { NG(); } else { ; }
}
void f198(void) {
volatile uint16_t x989 = UINT16_MAX;
uint64_t x990 = 649782985553163797LLU;
static int16_t x991 = -1;
int8_t x992 = INT8_MAX;
volatile uint64_t t198 = 339776140LLU;
t198 = (x989+(x990/(x991-x992)));
if (t198 != 65535LLU) { NG(); } else { ; }
}
void f199(void) {
int64_t x993 = -102763LL;
int8_t x996 = -2;
int64_t t199 = -1871LL;
t199 = (x993+(x994/(x995-x996)));
if (t199 != -102763LL) { NG(); } else { ; }
}
int main(void) {
f0();
f1();
f2();
f3();
f4();
f5();
f6();
f7();
f8();
f9();
f10();
f11();
f12();
f13();
f14();
f15();
f16();
f17();
f18();
f19();
f20();
f21();
f22();
f23();
f24();
f25();
f26();
f27();
f28();
f29();
f30();
f31();
f32();
f33();
f34();
f35();
f36();
f37();
f38();
f39();
f40();
f41();
f42();
f43();
f44();
f45();
f46();
f47();
f48();
f49();
f50();
f51();
f52();
f53();
f54();
f55();
f56();
f57();
f58();
f59();
f60();
f61();
f62();
f63();
f64();
f65();
f66();
f67();
f68();
f69();
f70();
f71();
f72();
f73();
f74();
f75();
f76();
f77();
f78();
f79();
f80();
f81();
f82();
f83();
f84();
f85();
f86();
f87();
f88();
f89();
f90();
f91();
f92();
f93();
f94();
f95();
f96();
f97();
f98();
f99();
f100();
f101();
f102();
f103();
f104();
f105();
f106();
f107();
f108();
f109();
f110();
f111();
f112();
f113();
f114();
f115();
f116();
f117();
f118();
f119();
f120();
f121();
f122();
f123();
f124();
f125();
f126();
f127();
f128();
f129();
f130();
f131();
f132();
f133();
f134();
f135();
f136();
f137();
f138();
f139();
f140();
f141();
f142();
f143();
f144();
f145();
f146();
f147();
f148();
f149();
f150();
f151();
f152();
f153();
f154();
f155();
f156();
f157();
f158();
f159();
f160();
f161();
f162();
f163();
f164();
f165();
f166();
f167();
f168();
f169();
f170();
f171();
f172();
f173();
f174();
f175();
f176();
f177();
f178();
f179();
f180();
f181();
f182();
f183();
f184();
f185();
f186();
f187();
f188();
f189();
f190();
f191();
f192();
f193();
f194();
f195();
f196();
f197();
f198();
f199();
return 0;
}
| 19.276204 | 61 | 0.603149 |
6d5ea32c47781f56103738fa80516f8d76c7806a | 278 | c | C | lib/test/test_get_api_key.c | svagionitis/themoviedb | 7a3676b610114aa432ca3eab54e1ab36f9b80bb2 | [
"Unlicense"
] | null | null | null | lib/test/test_get_api_key.c | svagionitis/themoviedb | 7a3676b610114aa432ca3eab54e1ab36f9b80bb2 | [
"Unlicense"
] | null | null | null | lib/test/test_get_api_key.c | svagionitis/themoviedb | 7a3676b610114aa432ca3eab54e1ab36f9b80bb2 | [
"Unlicense"
] | null | null | null | #include "unity.h"
#include "tmdb-compiler.h"
#include "tmdb.h"
void setUp(void)
{
}
void tearDown(void)
{
}
void test_Is_1(void)
{
TEST_ASSERT_EQUAL_INT(1, tmdb_get_api_key());
}
int main(void)
{
UNITY_BEGIN();
RUN_TEST(test_Is_1);
return UNITY_END();
}
| 10.296296 | 49 | 0.658273 |
6d609ae6bb6d60e556c9ca4df28e6f8a08ce4e94 | 2,762 | c | C | source/dbapi.c | shrinetang/ddbm | 18845c76db9faee6448218bd59b61949c595d1e4 | [
"Apache-2.0"
] | null | null | null | source/dbapi.c | shrinetang/ddbm | 18845c76db9faee6448218bd59b61949c595d1e4 | [
"Apache-2.0"
] | null | null | null | source/dbapi.c | shrinetang/ddbm | 18845c76db9faee6448218bd59b61949c595d1e4 | [
"Apache-2.0"
] | null | null | null | /********************************************************************/
/* Copyright (C) SSE-USTC, 2012 */
/* */
/* FILE NAME : dbapi.c */
/* PRINCIPAL AUTHOR : Xiaolong &Tangxingyu */
/* SUBSYSTEM NAME : dbapi */
/* MODULE NAME : dbapi */
/* LANGUAGE : C */
/* TARGET ENVIRONMENT : LINUX */
/* DATE OF FIRST RELEASE : 2012/11/29 */
/* DESCRIPTION : database application interface (dbapi) */
/********************************************************************/
/*
* Revision log:
*
* Created by Xiaolong&Tangxingyu,2012/11/29
*
*/
#include "dbapi.h"
#include <tcutil.h>
#include <tchdb.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
/*
int dbint[100];
int count=0;
*/
/*create a database object*/
tDatabase createDB(char *dbname)
{
int ecode;
TCHDB *db;
int i;
db = tchdbnew();
tchdbsetmutex(db);
/* open the database */
if(!tchdbopen(db, dbname, HDBOWRITER | HDBOCREAT))
{
ecode = tchdbecode(db);
fprintf(stderr, "open error: %s\n", tchdberrmsg(ecode));
exit(-1);
}
return (tDatabase)db;
}
/*release the db object*/
int deleteDB(tDatabase db)
{
int ecode;
if(!tchdbclose(db))
{
ecode = tchdbecode(db);
fprintf(stderr, "close error: %s\n", tchdberrmsg(ecode));
return -1;
}
/* delete the object */
tchdbdel(db);
return 0;
}
/*put the key and value into the database*/
int setKeyValue(tDatabase db,tKey key,tValue value)
{
int ecode;
if(!tchdbput(db, &key,sizeof(tKey),value.attribute,value.len ))
{
ecode = tchdbecode(db);
fprintf(stderr, "put error: %s\n", tchdberrmsg(ecode));
return -1;
}
return 0;
}
/*get the value across the key,and store the result into the pointer of pvalue*/
int getKeyValue(tDatabase db,tKey key,tValue *pvalue)
{
int ecode;
int ret;
ret=tchdbget3(db,&key,sizeof(tKey),pvalue->attribute,pvalue->len);
if(ret)
{
pvalue->attribute[ret]='\n';
pvalue->len=ret;
return 0;
}
ecode=tchdbecode(db);
fprintf(stderr, "put error: %s\n", tchdberrmsg(ecode));
return -1;
}
/*delete a record from the database*/
int deleteKeyValue(tDatabase db ,tKey key)
{
if(tchdbout(db, &key,sizeof(tKey)))
return 1;
else
return 0;
}
| 26.815534 | 81 | 0.476828 |
28d4a423c7e02210bbf43c49234a838562a6aa17 | 4,571 | h | C | 3D/TextureManager.h | Floppy/alienation | d2fca9344f88f70f1547573bea2244f77bd23379 | [
"BSD-3-Clause"
] | null | null | null | 3D/TextureManager.h | Floppy/alienation | d2fca9344f88f70f1547573bea2244f77bd23379 | [
"BSD-3-Clause"
] | null | null | null | 3D/TextureManager.h | Floppy/alienation | d2fca9344f88f70f1547573bea2244f77bd23379 | [
"BSD-3-Clause"
] | null | null | null | // Texture.h: interface for the CTexture class.
//
//////////////////////////////////////////////////////////////////////
#ifndef TEXTURE_MANAGER_H
#define TEXTURE_MANAGER_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "config.h"
#include <map>
#include <string>
#include "3D/Texture.h"
#include <SDL_opengl.h>
using namespace std;
/**
* Texture manager class.
* Deals with all texture objects, including file loading, rendering and ownership of the data.
* It does this by having one single global instance of the class, g_oTextureManager, and keeping
* reference counts for each texture it owns. If only a single class is using a texture, then the
* reference count can be left at 1, it's default on load. If the texture ID is used in more than
* object, each object after the first should call addReference() on creation, and removeReference()
* on destruction.
*/
class CTextureManager
{
public:
/**
* Constructor.
* @param strTextureRoot The location from which to load texture files.
*/
CTextureManager(const char* strTextureRoot);
/**
* Destructor.
* Destroys all loaded textures.
*/
~CTextureManager();
/**
* Load a texture from file.
* The loaded texture will have a reference count of 1.
* You don't need to add a reference until you use the texture ID for more than one object.
* @param strFilename The texture filename to load.
* @param bMipmap Generate mipmaps for the texture.
* @return The texture ID that can be used to access the loaded texture. UINT_MAX is returned on failure.
*/
unsigned int load(const char* strFilename, bool bMipmap = true);
/**
* Create a new texture in memory
* The loaded texture will have a reference count of 1.
* You don't need to add a reference until you use the texture ID for more than one object.
* @param iX The number of pixels wide the texture should be
* @param iY The number of pixels high the texture should be
* @return The texture ID that can be used to access the loaded texture. UINT_MAX is returned on failure.
*/
unsigned int create(unsigned int iX, unsigned int iY);
/**
* Add a reference to the specified texture.
* @param uiTexture The texture ID to add the reference to.
*/
void addReference(unsigned int uiTexture);
/**
* Remove a reference from the specified texture.
* A texture will be deleted when all references are removed.
* @param uiTexture The texture ID to remove the reference from.
*/
void removeReference(unsigned int uiTexture);
/**
* Bind a texture for rendering.
* @param uiTexture The texture ID to render.
*/
void render(unsigned int uiTexture);
/**
* Access the texture itself
* @param uiTexture The texture ID to access.
* @return a pointer to the CTexture requested
*/
CTexture* texture(unsigned int uiTexture);
/**
* Access the texture directory location
* @return The directory from which textures will be loaded.
*/
const char* textureRoot() const
{ return m_strTextureRoot; }
/**
* Set texture filtering mode.
* @param eMag Magnification filter mode.
* @param eMin Minification filter mode.
*/
void textureFiltering(GLenum eMag, GLenum eMin);
/**
* Get texture magnification filter mode.
* @return Magnification filter mode.
*/
GLenum magFilter() const
{ return m_eMagFilter; }
/**
* Get texture minification filter mode.
* @return Minification filter mode.
*/
GLenum minFilter() const
{ return m_eMinFilter; }
/**
* Is mipmapping enabled for textures.
* @return True if mipmapping is enabled.
*/
bool mipmapsEnabled() const
{ return m_bMipmap; }
protected:
/**
* Texture pointers.
*/
map<unsigned int, CTexture*> m_hTextures;
/**
* Reference counts.
*/
map<unsigned int, unsigned int> m_hReferences;
/**
* Reference counts.
*/
map<string, unsigned int> m_hFiles;
/**
* Root location of textures
*/
char m_strTextureRoot[255];
/**
* Is mipmapping enabled?
*/
bool m_bMipmap;
/**
* Texture filtering mode (magnification)
*/
GLenum m_eMagFilter;
/**
* Texture filtering mode (minification)
*/
GLenum m_eMinFilter;
};
/**
* A global instance of the CTextureManager class.
* All texture access should be done through this object.
*/
extern CTextureManager g_oTextureManager;
#endif // TEXTURE_MANAGER_H
| 26.575581 | 108 | 0.66375 |
a36ca5be3aeeeb629db19cede767967a878ca51b | 584 | h | C | ios/Classes/TiBluetoothBeaconRegionProxy.h | m1ga/titanium-bluetooth | 306a75e8d27478b6956edf260733a4bfa3dd7ed1 | [
"Apache-2.0"
] | 30 | 2017-04-01T01:22:00.000Z | 2021-12-01T13:08:56.000Z | ios/Classes/TiBluetoothBeaconRegionProxy.h | m1ga/titanium-bluetooth | 306a75e8d27478b6956edf260733a4bfa3dd7ed1 | [
"Apache-2.0"
] | 35 | 2017-03-28T19:29:20.000Z | 2022-03-17T16:49:47.000Z | ios/Classes/TiBluetoothBeaconRegionProxy.h | m1ga/titanium-bluetooth | 306a75e8d27478b6956edf260733a4bfa3dd7ed1 | [
"Apache-2.0"
] | 19 | 2017-03-28T19:04:12.000Z | 2022-01-06T19:00:37.000Z | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#import "TiProxy.h"
#import <CoreLocation/CoreLocation.h>
@interface TiBluetoothBeaconRegionProxy : TiProxy {
CLBeaconRegion *_beaconRegion;
NSNumber *_measuredPower;
}
- (id)_initWithPageContext:(id<TiEvaluator>)context andBeaconRegion:(CLBeaconRegion *)__beaconRegion;
- (CLBeaconRegion *)beaconRegion;
- (NSNumber *)measuredPower;
@end
| 29.2 | 101 | 0.775685 |
d19435b5a75beef9b53ebd702de7f80b5fb8d678 | 54 | c | C | examples/boolops/ex9.c | sailikk/c_compiler | 96705adcec220499752d949c944a5c8b6d5f8c46 | [
"MIT"
] | 222 | 2017-11-16T02:29:35.000Z | 2022-03-30T10:44:02.000Z | examples/boolops/ex9.c | sailikk/c_compiler | 96705adcec220499752d949c944a5c8b6d5f8c46 | [
"MIT"
] | 11 | 2017-12-03T02:15:20.000Z | 2020-05-16T08:14:19.000Z | examples/boolops/ex9.c | sailikk/c_compiler | 96705adcec220499752d949c944a5c8b6d5f8c46 | [
"MIT"
] | 18 | 2018-02-22T02:27:47.000Z | 2022-03-22T05:08:02.000Z | int main() {
return (3+4 <= 4 || 1&&2 != 3 > 6);
} | 18 | 39 | 0.37037 |
0663977b4a48bc829a576a57a4ab3b683707a34f | 9,501 | c | C | 1. K-means/kmeans04.c | georgevangelou/parallel_programming_with_OpenMP | 0a1983b2a6be5efc6402abbc5be682234f8e9990 | [
"Apache-2.0"
] | 1 | 2021-06-27T12:53:07.000Z | 2021-06-27T12:53:07.000Z | 1. K-means/kmeans04.c | georgevangelou/parallel_programming_with_OpenMP | 0a1983b2a6be5efc6402abbc5be682234f8e9990 | [
"Apache-2.0"
] | 2 | 2021-04-20T19:16:58.000Z | 2021-04-20T19:33:02.000Z | 1. K-means/kmeans04.c | georgevangelou/parallel_programming_with_OpenMP | 0a1983b2a6be5efc6402abbc5be682234f8e9990 | [
"Apache-2.0"
] | null | null | null | /*
Description:
This program executes the K-Means algorithm for random vectors of arbitrary number
and dimensions
Author:
Georgios Evangelou (1046900)
Year: 5
Parallel Programming in Machine Learning Problems
Electrical and Computer Engineering Department, University of Patras
System Specifications:
CPU: AMD Ryzen 2600 (6 cores/12 threads, @3.8 GHz, 6786.23 bogomips)
GPU: Nvidia GTX 1050 (dual-fan, overclocked)
RAM: 8GB (dual-channel, @2666 MHz)
cat /proc/cpuinfo {
processor : 0
vendor_id : AuthenticAMD
cpu family : 23
model : 8
model name : AMD Ryzen 5 2600 Six-Core Processor
stepping : 2
microcode : 0x800820b
cpu MHz : 1374.877
cache size : 512 KB
physical id : 0
siblings : 12
core id : 0
cpu cores : 6
apicid : 0
initial apicid : 0
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb hw_pstate sme ssbd sev ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt sha_ni xsaveopt xsavec xgetbv1 xsaves clzero irperf xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif overflow_recov succor smca
bugs : sysret_ss_attrs null_seg spectre_v1 spectre_v2 spec_store_bypass
bogomips : 6786.50
TLB size : 2560 4K pages
clflush size : 64
cache_alignment : 64
address sizes : 43 bits physical, 48 bits virtual
power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14]
}
Version Notes:
Compiles with: gcc kmeans04.c -o kmeans04 -lm -fopt-info-vec-optimized
Uses indices to access array data
Uses vector processing for execution speed-up
Executes the algorithm for 10000 vectors of 100 dimensions and 10 classes
Produces correct results
Needs ~1 minute and 2 seconds to reach 16 repetitions
Profiler Output:
Flat profile:
Each sample counts as 0.01 seconds.
% cumulative self self total
time seconds seconds calls Ts/call Ts/call name
98.60 138.00 138.00 estimateClasses
1.17 139.64 1.63 estimateCenters
0.33 140.10 0.46 SetVec
*/
// *******************************************************************
#pragma GCC optimize("O3","unroll-loops","omit-frame-pointer","inline", "unsafe-math-optimizations")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
// *******************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// ***************************************************
#define N 100000
#define Nv 1000
#define Nc 100
#define THRESHOLD 0.000001
// ***************************************************
double Vectors[N][Nv]; // N vectors of Nv dimensions
double Centers[Nc][Nv]; // Nc vectors of Nv dimensions
int Class_of_Vec[N]; // Class of each Vector
// ***************************************************
// Print vectors
// ***************************************************
void printVectors(void) {
int i, j;
for (i = 0; i < N; i++) {
printf("--------------------\n");
printf(" Vector #%d is:\n", i);
for (j = 0; j < Nv; j++)
printf(" %f\n", Vectors[i][j]);
}
}
// ***************************************************
// Print centers
// ***************************************************
void printCenters(void) {
int i, j;
for (i = 0; i < Nc; i++) {
printf("--------------------\n");
printf(" Center #%d is:\n", i);
for (j = 0; j < Nv; j++)
printf(" %f\n", Centers[i][j]);
}
}
// ***************************************************
// Print the class of each vector
// ***************************************************
void printClasses(void) {
int i, j;
for (i = 0; i < N; i++) {
printf("--------------------\n");
printf(" Class of #%d is:\n", i);
printf(" %d\n", Class_of_Vec[i]);
}
}
// ***************************************************
// Check if a number is in a vector
// ***************************************************
int notIn(int Num, int Vec[Nc], int max_index){
int j;
for (j=0; j<max_index; j++)
if (Vec[j]==Num) return 0;
return 1;
}
// ***************************************************
// Choose random centers from available vectors
// ***************************************************
void initCenters( void ) {
int i = 0, j = 0, k = 0;
int Current_centers_indices[Nc] = {-1};
while(i<Nc) {
k = (int) N * (1.0 * rand())/RAND_MAX ; // Pick a random integer in range [0, N-1]
if ( notIn(k, Current_centers_indices, i) ) {
Current_centers_indices[i] = k;
for (j=0; j<Nv; j++) Centers[i][j] = Vectors[k][j];
i++;
}
}
}
// ***************************************************
// Returns the total squared minimum distance between all vectors and their closest center
// ***************************************************
float estimateClasses(void) {
double min_dist, dist, tot_min_distances = 0;
int temp_class;
int i, j, w;
for (w=0; w<N; w++) {
min_dist = 0;
temp_class = 0;
for (j=0; j<Nv; j++)
min_dist += (Vectors[w][j]-Centers[0][j]) * (Vectors[w][j]-Centers[0][j]); // Distance between Vec and Center 0
for (i=1; i<Nc; i++) {
dist = 0;
for (j=0; j<Nv; j++) {
dist = dist + (Vectors[w][j]-Centers[i][j]) * (Vectors[w][j]-Centers[i][j]); // Distance between Vec and Center i
}
if (dist < min_dist) {
temp_class = i;
min_dist = dist;
}
}
Class_of_Vec[w] = temp_class;
tot_min_distances += sqrt(min_dist);
}
return tot_min_distances;
}
// ***************************************************
// Find the new centers
// ***************************************************
void estimateCenters( void ) {
int Centers_matchings[Nc] = {0};
int i, j, w;
// Zero all center vectors
for (i = 0; i < Nc; i++) {
for (j = 0; j < Nv; j++) {
Centers[i][j] = 0;
}
}
// Add each vector's values to its corresponding center
for (w = 0; w < N; w ++) {
Centers_matchings[Class_of_Vec[w]] ++;
for (j = 0; j<Nv; j++) {
Centers[Class_of_Vec[w]][j] += Vectors[w][j];
}
}
for (i = 0; i < Nc; i++) {
if (Centers_matchings[i] != 0)
for (j = 0; j < Nv; j++)
Centers[i][j] /= Centers_matchings[i];
else
printf("\nERROR: CENTER %d HAS NO NEIGHBOURS...\n", i);
}
}
// ***************************************************
// Initializing the vectors with random values
// ***************************************************
void SetVec( void ) {
int i, j;
for( i = 0 ; i< N ; i++ )
for( j = 0 ; j < Nv ; j++ )
Vectors[i][j] = (1.0*rand())/RAND_MAX ;
}
// ***************************************************
// The main program
// ***************************************************
int main( int argc, const char* argv[] ) {
int repetitions = 0;
float totDist, prevDist, diff;
printf("--------------------------------------------------------------------------------------------------\n");
printf("This program executes the K-Means algorithm for random vectors of arbitrary number and dimensions.\n");
printf("Current configuration has %d Vectors, %d Classes and %d Elements per vector.\n", N, Nc, Nv);
printf("--------------------------------------------------------------------------------------------------\n");
printf("Now initializing vectors...\n");
SetVec() ;
printf("Now initializing centers...\n");
initCenters() ;
//printf("The vectors were initialized with these values:\n");
//printVectors();
//printf("\nThe centers were initialized with these values:\n);
//printCenters();
totDist = 1.0e30;
printf("Now running the main algorithm...\n\n");
do {
repetitions++;
prevDist = totDist ;
totDist = estimateClasses() ;
estimateCenters() ;
diff = (prevDist-totDist)/totDist ;
//printf("\nCurrent centers are:\n");
//printCenters();
printf(">> REPETITION: %3d || ", repetitions);
printf("DISTANCE IMPROVEMENT: %.8f \n", diff);
} while( diff > THRESHOLD ) ;
printf("\nProcess finished!\n");
printf("\nTotal repetitions were: %d\n", repetitions);
//printf("\nFinal centers are:\n");
//printCenters() ;
//printf("\nFinal classes are:\n");
//printClasses() ;
//printf("\n\nTotal distance is %f\n", totDist);
return 0 ;
}
//**********************************************************************************************************
| 33.22028 | 796 | 0.493422 |
ff0245460d9229d8caf814ed76cf597de8c8cca5 | 3,258 | h | C | any_op/include/dak/any_op/compare_op.h | pierrebai/dak_utility | a0cb355ec1962c46475c7cdefa64d7041dc51f5a | [
"MIT"
] | null | null | null | any_op/include/dak/any_op/compare_op.h | pierrebai/dak_utility | a0cb355ec1962c46475c7cdefa64d7041dc51f5a | [
"MIT"
] | null | null | null | any_op/include/dak/any_op/compare_op.h | pierrebai/dak_utility | a0cb355ec1962c46475c7cdefa64d7041dc51f5a | [
"MIT"
] | 1 | 2021-01-14T07:19:55.000Z | 2021-01-14T07:19:55.000Z | #pragma once
#ifndef DAK_ANY_OP_COMPARE_OP_H
#define DAK_ANY_OP_COMPARE_OP_H
#include <dak/any_op/op.h>
namespace dak::any_op
{
//////////////////////////////////////////////////////////////////////////
//
// Comparison results.
//
// Note: incomparable should result in operator== returning false,
// operator!= returning true, and all relative operators
// (<, >, <=, >=) returning false.
enum class comparison_t : int8_t
{
incomparable = 0,
equal = 1,
less = 2,
more = 4,
less_or_equal = less | equal,
more_or_equal = more | equal,
};
inline bool is(const comparison_t result, const comparison_t desired)
{
return 0 != (uint8_t(result) & uint8_t(desired));
}
//////////////////////////////////////////////////////////////////////////
//
// The compare operation compares two values.
//
// Note: returns comparison_t::incomparable if two values cannot be compared.
struct compare_op_t : op_t<compare_op_t>
{
// Note: pre-defined operations implementation are automatically registered,
// but these static variables do not get initialized by the testing framework.
// Tests need to explicitly call a function to trigger initialization.
static void register_ops();
};
//////////////////////////////////////////////////////////////////////////
//
// Comparison function.
inline comparison_t compare(const std::any& arg_a, const std::any& arg_b)
{
if (!arg_a.has_value())
{
return !arg_b.has_value() ? comparison_t::equal : comparison_t::less;
}
else if (!arg_b.has_value())
{
return comparison_t::more;
}
const std::any result = compare_op_t::call_any<>::op(arg_a, arg_b);
if (result.has_value())
return std::any_cast<comparison_t>(result);
return comparison_t::incomparable;
}
template<class A>
inline comparison_t compare(const A& arg_a, const A& arg_b)
{
const std::any result = compare_op_t::call<>::op(arg_a, arg_b);
if (result.has_value())
return std::any_cast<comparison_t>(result);
return comparison_t::incomparable;
}
//////////////////////////////////////////////////////////////////////////
//
// Comparison C++ operators.
inline bool operator==(const std::any& arg_a, const std::any& arg_b)
{
return compare(arg_a, arg_b) == comparison_t::equal;
}
inline bool operator<(const std::any& arg_a, const std::any& arg_b)
{
return compare(arg_a, arg_b) == comparison_t::less;
}
inline bool operator>(const std::any& arg_a, const std::any& arg_b)
{
return compare(arg_a, arg_b) == comparison_t::more;
}
inline bool operator!=(const std::any& arg_a, const std::any& arg_b)
{
return compare(arg_a, arg_b) != comparison_t::equal;
}
inline bool operator<=(const std::any& arg_a, const std::any& arg_b)
{
return is(compare(arg_a, arg_b), comparison_t::less_or_equal);
}
inline bool operator>=(const std::any& arg_a, const std::any& arg_b)
{
return is(compare(arg_a, arg_b), comparison_t::more_or_equal);
}
}
#endif /* DAK_ANY_OP_COMPARE_OP_H */
| 27.846154 | 90 | 0.5752 |
a224fffc95548c2cda2459cb664969148b83b12d | 57 | h | C | 09/MathExample.h | memnoth/COMP3200CodeSamples | 28c4921d9c2d5c6077cde2eb0e0e93cee7680ca4 | [
"MIT"
] | 60 | 2018-12-22T01:59:21.000Z | 2022-02-16T07:34:51.000Z | 09/MathExample.h | memnoth/COMP3200CodeSamples | 28c4921d9c2d5c6077cde2eb0e0e93cee7680ca4 | [
"MIT"
] | null | null | null | 09/MathExample.h | memnoth/COMP3200CodeSamples | 28c4921d9c2d5c6077cde2eb0e0e93cee7680ca4 | [
"MIT"
] | 32 | 2018-12-25T01:20:02.000Z | 2022-01-16T01:59:33.000Z | #pragma once
namespace samples
{
void MathExample();
}
| 8.142857 | 20 | 0.719298 |
9eb28ecc8328015f26ef3ef65c79f80eb25a48fe | 291 | h | C | Common/src/ReceptorPaquete.h | mlucero88/Fwk_Cliente_Servidor | a0bee168a2eef4755877f6244e2f9f4ae85e47d2 | [
"Apache-2.0"
] | null | null | null | Common/src/ReceptorPaquete.h | mlucero88/Fwk_Cliente_Servidor | a0bee168a2eef4755877f6244e2f9f4ae85e47d2 | [
"Apache-2.0"
] | null | null | null | Common/src/ReceptorPaquete.h | mlucero88/Fwk_Cliente_Servidor | a0bee168a2eef4755877f6244e2f9f4ae85e47d2 | [
"Apache-2.0"
] | null | null | null | /******************************
* Archivo: ReceptorPaquete.h
* Autor: Martín Lucero
*****************************/
#ifndef RECEPTORPAQUETE_H_
#define RECEPTORPAQUETE_H_
namespace FWK_CS {
class ReceptorPaquete {
public:
ReceptorPaquete();
virtual ~ReceptorPaquete();
};
}
#endif
| 15.315789 | 31 | 0.587629 |
9ee7b5cc1c9682320ed7a65d4a21411c870ff84c | 23,075 | c | C | agent/mibgroup/snmp-usm-dh-objects-mib/usmDHUserKeyTable/usmDHUserKeyTable_data_get.c | telsacolton/net-snmp | 3efb2c51a563d217aad53b36e5b46bcb6233e780 | [
"Net-SNMP"
] | 1 | 2020-07-16T06:51:23.000Z | 2020-07-16T06:51:23.000Z | agent/mibgroup/snmp-usm-dh-objects-mib/usmDHUserKeyTable/usmDHUserKeyTable_data_get.c | telsacolton/net-snmp | 3efb2c51a563d217aad53b36e5b46bcb6233e780 | [
"Net-SNMP"
] | null | null | null | agent/mibgroup/snmp-usm-dh-objects-mib/usmDHUserKeyTable/usmDHUserKeyTable_data_get.c | telsacolton/net-snmp | 3efb2c51a563d217aad53b36e5b46bcb6233e780 | [
"Net-SNMP"
] | null | null | null | /*
* Note: this file originally auto-generated by mib2c using
* version : 1.20 $ of : mfd-data-get.m2c,v $
*
* $Id$
*/
/*
* standard Net-SNMP includes
*/
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/library/snmp_openssl.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>
/*
* include our parent header
*/
#define NEED_USMDH_FUNCTIONS
#include "usmDHUserKeyTable.h"
#include "snmp-usm-dh-objects-mib/usmDHParameters/usmDHParameters.h"
DH *
usmDHGetUserDHptr(struct usmUser *user, int for_auth_key)
{
DH *dh, *dh_params;
const BIGNUM *g, *p;
void **theptr;
if (user == NULL)
return NULL;
if (for_auth_key == 1)
theptr = &user->usmDHUserAuthKeyChange;
else
theptr = &user->usmDHUserPrivKeyChange;
if (!*theptr) {
/*
* copy the system parameters to the local ones
*/
dh = DH_new();
if (!dh)
return NULL;
dh_params = get_dh_params();
if (!dh_params)
return NULL;
DH_get0_pqg(dh_params, &p, NULL, &g);
DH_set0_pqg(dh, BN_dup(p), NULL, BN_dup(g));
DH_get0_pqg(dh, &p, NULL, &g);
if (!g || !p)
return NULL;
DH_generate_key(dh);
*theptr = dh;
} else {
dh = (DH *) * theptr;
}
return dh;
}
int
usmDHGetUserKeyChange(struct usmUser *user, int for_auth_key,
u_char **keyobj, size_t *keyobj_len)
{
DH *dh;
const BIGNUM *pub_key;
dh = usmDHGetUserDHptr(user, for_auth_key);
if (!dh) {
snmp_log(LOG_ERR, "ack... shouldn't get here: %p %d\n",
user, for_auth_key);
return MFD_ERROR;
}
DH_get0_key(dh, &pub_key, NULL);
*keyobj_len = BN_num_bytes(pub_key);
*keyobj = malloc(*keyobj_len);
BN_bn2bin(pub_key, *keyobj);
return MFD_SUCCESS;
}
/** @ingroup data_access
* @defgroup data_get data_get: Routines to get data
*
* TODO:230:M: Implement usmDHUserKeyTable get routines.
* TODO:240:M: Implement usmDHUserKeyTable mapping routines (if any).
*
* These routine are used to get the value for individual objects. The
* row context is passed, along with a pointer to the memory where the
* value should be copied.
*
* @{
*/
/**********************************************************************
**********************************************************************
***
*** Table usmDHUserKeyTable
***
**********************************************************************
**********************************************************************/
/*
* SNMP-USM-DH-OBJECTS-MIB::usmDHUserKeyTable is subid 2 of usmDHPublicObjects.
* Its status is Current.
* OID: .1.3.6.1.3.101.1.1.2, length: 9
*/
/*
* ---------------------------------------------------------------------
* * TODO:200:r: Implement usmDHUserKeyTable data context functions.
*/
/*
* usmDHUserKeyTable_allocate_data
*
* Purpose: create new usmDHUserKeyTable_data.
*/
usmDHUserKeyTable_data *
usmDHUserKeyTable_allocate_data(void)
{
/*
* TODO:201:r: |-> allocate memory for the usmDHUserKeyTable data context.
*/
usmDHUserKeyTable_data *rtn =
SNMP_MALLOC_TYPEDEF(usmDHUserKeyTable_data);
DEBUGMSGTL(("verbose:usmDHUserKeyTable:usmDHUserKeyTable_allocate_data", "called\n"));
if (NULL == rtn) {
snmp_log(LOG_ERR, "unable to malloc memory for new "
"usmDHUserKeyTable_data.\n");
} else {
/*
* not real user, not in a list. mark for testing
*/
rtn->next = (struct usmUser *) -1;
rtn->prev = (struct usmUser *) -1;
}
return rtn;
} /* usmDHUserKeyTable_allocate_data */
/*
* usmDHUserKeyTable_release_data
*
* Purpose: release usmDHUserKeyTable data.
*/
void
usmDHUserKeyTable_release_data(usmDHUserKeyTable_data * data)
{
struct usmUser *user = data;
DEBUGMSGTL(("verbose:usmDHUserKeyTable:usmDHUserKeyTable_release_data",
"called\n"));
netsnmp_assert(user->next == (struct usmUser *) -1);
netsnmp_assert(user->prev == (struct usmUser *) -1);
/*
* TODO:202:r: |-> release memory for the usmDHUserKeyTable data context.
*/
if (user) {
SNMP_FREE(user->authKey);
SNMP_FREE(user->privKey);
}
free(data);
} /* usmDHUserKeyTable_release_data */
/**
* set mib index(es)
*
* @param tbl_idx mib index structure
* @param usmUserEngineID_val_ptr
* @param usmUserEngineID_val_ptr_len
* @param usmUserName_val_ptr
* @param usmUserName_val_ptr_len
*
* @retval MFD_SUCCESS : success.
* @retval MFD_ERROR : other error.
*
* @remark
* This convenience function is useful for setting all the MIB index
* components with a single function call. It is assume that the C values
* have already been mapped from their native/rawformat to the MIB format.
*/
int
usmDHUserKeyTable_indexes_set_tbl_idx(usmDHUserKeyTable_mib_index *
tbl_idx,
u_char *usmUserEngineID_val_ptr,
size_t usmUserEngineID_val_ptr_len,
char *usmUserName_val_ptr,
size_t usmUserName_val_ptr_len)
{
DEBUGMSGTL(("verbose:usmDHUserKeyTable:usmDHUserKeyTable_indexes_set_tbl_idx", "called\n"));
/*
* usmUserEngineID(1)/SnmpEngineID/ASN_OCTET_STR/char(char)//L/a/w/e/R/d/h
*/
tbl_idx->usmUserEngineID_len = sizeof(tbl_idx->usmUserEngineID) / sizeof(tbl_idx->usmUserEngineID[0]); /* max length */
/** WARNING: this code might not work for struct usmUser */
/*
* make sure there is enough space for usmUserEngineID data
*/
if ((NULL == tbl_idx->usmUserEngineID) ||
(tbl_idx->usmUserEngineID_len < (usmUserEngineID_val_ptr_len))) {
snmp_log(LOG_ERR, "not enough space for value\n");
return MFD_ERROR;
}
tbl_idx->usmUserEngineID_len = usmUserEngineID_val_ptr_len;
memcpy(tbl_idx->usmUserEngineID, usmUserEngineID_val_ptr,
usmUserEngineID_val_ptr_len *
sizeof(usmUserEngineID_val_ptr[0]));
/*
* usmUserName(2)/SnmpAdminString/ASN_OCTET_STR/char(char)//L/a/w/e/R/d/H
*/
tbl_idx->usmUserName_len = sizeof(tbl_idx->usmUserName) / sizeof(tbl_idx->usmUserName[0]); /* max length */
/** WARNING: this code might not work for struct usmUser */
/*
* make sure there is enough space for usmUserName data
*/
if ((NULL == tbl_idx->usmUserName) ||
(tbl_idx->usmUserName_len < (usmUserName_val_ptr_len))) {
snmp_log(LOG_ERR, "not enough space for value\n");
return MFD_ERROR;
}
tbl_idx->usmUserName_len = usmUserName_val_ptr_len;
memcpy(tbl_idx->usmUserName, usmUserName_val_ptr,
usmUserName_val_ptr_len * sizeof(usmUserName_val_ptr[0]));
return MFD_SUCCESS;
} /* usmDHUserKeyTable_indexes_set_tbl_idx */
/**
* @internal
* set row context indexes
*
* @param reqreq_ctx the row context that needs updated indexes
*
* @retval MFD_SUCCESS : success.
* @retval MFD_ERROR : other error.
*
* @remark
* This function sets the mib indexs, then updates the oid indexs
* from the mib index.
*/
int
usmDHUserKeyTable_indexes_set(usmDHUserKeyTable_rowreq_ctx * rowreq_ctx,
u_char *usmUserEngineID_val_ptr,
size_t usmUserEngineID_val_ptr_len,
char *usmUserName_val_ptr,
size_t usmUserName_val_ptr_len)
{
DEBUGMSGTL(("verbose:usmDHUserKeyTable:usmDHUserKeyTable_indexes_set",
"called\n"));
if (MFD_SUCCESS !=
usmDHUserKeyTable_indexes_set_tbl_idx(&rowreq_ctx->tbl_idx,
usmUserEngineID_val_ptr,
usmUserEngineID_val_ptr_len,
usmUserName_val_ptr,
usmUserName_val_ptr_len))
return MFD_ERROR;
/*
* convert mib index to oid index
*/
rowreq_ctx->oid_idx.len = sizeof(rowreq_ctx->oid_tmp) / sizeof(oid);
if (0 != usmDHUserKeyTable_index_to_oid(&rowreq_ctx->oid_idx,
&rowreq_ctx->tbl_idx)) {
return MFD_ERROR;
}
return MFD_SUCCESS;
} /* usmDHUserKeyTable_indexes_set */
/*---------------------------------------------------------------------
* SNMP-USM-DH-OBJECTS-MIB::usmDHUserKeyEntry.usmDHUserAuthKeyChange
* usmDHUserAuthKeyChange is subid 1 of usmDHUserKeyEntry.
* Its status is Current, and its access level is Create.
* OID: .1.3.6.1.3.101.1.1.2.1.1
* Description:
The object used to change any given user's Authentication Key
using a Diffie-Hellman key exchange.
The right-most n bits of the shared secret 'sk', where 'n' is the
number of bits required for the protocol defined by
usmUserAuthProtocol, are installed as the operational
authentication key for this row after a successful SET.
*
* Attributes:
* accessible 1 isscalar 0 enums 0 hasdefval 0
* readable 1 iscolumn 1 ranges 0 hashint 0
* settable 1
*
*
* Its syntax is DHKeyChange (based on perltype OCTETSTR)
* The net-snmp type is ASN_OCTET_STR. The C type decl is char (char)
* This data type requires a length.
*/
/**
* Extract the current value of the usmDHUserAuthKeyChange data.
*
* Set a value using the data context for the row.
*
* @param rowreq_ctx
* Pointer to the row request context.
* @param usmDHUserAuthKeyChange_val_ptr_ptr
* Pointer to storage for a char variable
* @param usmDHUserAuthKeyChange_val_ptr_len_ptr
* Pointer to a size_t. On entry, it will contain the size (in bytes)
* pointed to by usmDHUserAuthKeyChange.
* On exit, this value should contain the data size (in bytes).
*
* @retval MFD_SUCCESS : success
* @retval MFD_SKIP : skip this node (no value for now)
* @retval MFD_ERROR : Any other error
*
* @note If you need more than (*usmDHUserAuthKeyChange_val_ptr_len_ptr) bytes of memory,
* allocate it using malloc() and update usmDHUserAuthKeyChange_val_ptr_ptr.
* <b>DO NOT</b> free the previous pointer.
* The MFD helper will release the memory you allocate.
*
* @remark If you call this function yourself, you are responsible
* for checking if the pointer changed, and freeing any
* previously allocated memory. (Not necessary if you pass
* in a pointer to static memory, obviously.)
*/
int
usmDHUserAuthKeyChange_get(usmDHUserKeyTable_rowreq_ctx * rowreq_ctx,
u_char **usmDHUserAuthKeyChange_val_ptr_ptr,
size_t *usmDHUserAuthKeyChange_val_ptr_len_ptr)
{
/** we should have a non-NULL pointer and enough storage */
netsnmp_assert((NULL != usmDHUserAuthKeyChange_val_ptr_ptr)
&& (NULL != *usmDHUserAuthKeyChange_val_ptr_ptr));
netsnmp_assert(NULL != usmDHUserAuthKeyChange_val_ptr_len_ptr);
DEBUGMSGTL(("verbose:usmDHUserKeyTable:usmDHUserAuthKeyChange_get",
"called\n"));
netsnmp_assert(NULL != rowreq_ctx);
/*
* TODO:231:o: |-> Extract the current value of the usmDHUserAuthKeyChange data.
* copy (* usmDHUserAuthKeyChange_val_ptr_ptr ) data and (* usmDHUserAuthKeyChange_val_ptr_len_ptr ) from rowreq_ctx->data
*/
if (!rowreq_ctx || !usmDHUserAuthKeyChange_val_ptr_len_ptr ||
!usmDHUserAuthKeyChange_val_ptr_ptr ||
!*usmDHUserAuthKeyChange_val_ptr_ptr) {
return MFD_ERROR;
}
return usmDHGetUserKeyChange(rowreq_ctx->data, 1,
usmDHUserAuthKeyChange_val_ptr_ptr,
usmDHUserAuthKeyChange_val_ptr_len_ptr);
} /* usmDHUserAuthKeyChange_get */
/*---------------------------------------------------------------------
* SNMP-USM-DH-OBJECTS-MIB::usmDHUserKeyEntry.usmDHUserOwnAuthKeyChange
* usmDHUserOwnAuthKeyChange is subid 2 of usmDHUserKeyEntry.
* Its status is Current, and its access level is Create.
* OID: .1.3.6.1.3.101.1.1.2.1.2
* Description:
The object used to change the agents own Authentication Key
using a Diffie-Hellman key exchange.
The right-most n bits of the shared secret 'sk', where 'n' is the
number of bits required for the protocol defined by
usmUserAuthProtocol, are installed as the operational
authentication key for this row after a successful SET.
*
* Attributes:
* accessible 1 isscalar 0 enums 0 hasdefval 0
* readable 1 iscolumn 1 ranges 0 hashint 0
* settable 1
*
*
* Its syntax is DHKeyChange (based on perltype OCTETSTR)
* The net-snmp type is ASN_OCTET_STR. The C type decl is char (char)
* This data type requires a length.
*/
/**
* Extract the current value of the usmDHUserOwnAuthKeyChange data.
*
* Set a value using the data context for the row.
*
* @param rowreq_ctx
* Pointer to the row request context.
* @param usmDHUserOwnAuthKeyChange_val_ptr_ptr
* Pointer to storage for a char variable
* @param usmDHUserOwnAuthKeyChange_val_ptr_len_ptr
* Pointer to a size_t. On entry, it will contain the size (in bytes)
* pointed to by usmDHUserOwnAuthKeyChange.
* On exit, this value should contain the data size (in bytes).
*
* @retval MFD_SUCCESS : success
* @retval MFD_SKIP : skip this node (no value for now)
* @retval MFD_ERROR : Any other error
*
* @note If you need more than (*usmDHUserOwnAuthKeyChange_val_ptr_len_ptr) bytes of memory,
* allocate it using malloc() and update usmDHUserOwnAuthKeyChange_val_ptr_ptr.
* <b>DO NOT</b> free the previous pointer.
* The MFD helper will release the memory you allocate.
*
* @remark If you call this function yourself, you are responsible
* for checking if the pointer changed, and freeing any
* previously allocated memory. (Not necessary if you pass
* in a pointer to static memory, obviously.)
*/
int
usmDHUserOwnAuthKeyChange_get(usmDHUserKeyTable_rowreq_ctx * rowreq_ctx,
u_char **usmDHUserOwnAuthKeyChange_val_ptr_ptr,
size_t
*usmDHUserOwnAuthKeyChange_val_ptr_len_ptr)
{
/** we should have a non-NULL pointer and enough storage */
netsnmp_assert((NULL != usmDHUserOwnAuthKeyChange_val_ptr_ptr)
&& (NULL != *usmDHUserOwnAuthKeyChange_val_ptr_ptr));
netsnmp_assert(NULL != usmDHUserOwnAuthKeyChange_val_ptr_len_ptr);
DEBUGMSGTL(("verbose:usmDHUserKeyTable:usmDHUserOwnAuthKeyChange_get",
"called\n"));
netsnmp_assert(NULL != rowreq_ctx);
/*
* TODO:231:o: |-> Extract the current value of the usmDHUserOwnAuthKeyChange data.
* copy (* usmDHUserOwnAuthKeyChange_val_ptr_ptr ) data and (* usmDHUserOwnAuthKeyChange_val_ptr_len_ptr ) from rowreq_ctx->data
*/
if (!rowreq_ctx || !usmDHUserOwnAuthKeyChange_val_ptr_len_ptr ||
!usmDHUserOwnAuthKeyChange_val_ptr_ptr ||
!*usmDHUserOwnAuthKeyChange_val_ptr_ptr) {
return MFD_ERROR;
}
return usmDHGetUserKeyChange(rowreq_ctx->data, 1,
usmDHUserOwnAuthKeyChange_val_ptr_ptr,
usmDHUserOwnAuthKeyChange_val_ptr_len_ptr);
} /* usmDHUserOwnAuthKeyChange_get */
/*---------------------------------------------------------------------
* SNMP-USM-DH-OBJECTS-MIB::usmDHUserKeyEntry.usmDHUserPrivKeyChange
* usmDHUserPrivKeyChange is subid 3 of usmDHUserKeyEntry.
* Its status is Current, and its access level is Create.
* OID: .1.3.6.1.3.101.1.1.2.1.3
* Description:
The object used to change any given user's Privacy Key using
a Diffie-Hellman key exchange.
The right-most n bits of the shared secret 'sk', where 'n' is the
number of bits required for the protocol defined by
usmUserPrivProtocol, are installed as the operational privacy key
for this row after a successful SET.
*
* Attributes:
* accessible 1 isscalar 0 enums 0 hasdefval 0
* readable 1 iscolumn 1 ranges 0 hashint 0
* settable 1
*
*
* Its syntax is DHKeyChange (based on perltype OCTETSTR)
* The net-snmp type is ASN_OCTET_STR. The C type decl is char (char)
* This data type requires a length.
*/
/**
* Extract the current value of the usmDHUserPrivKeyChange data.
*
* Set a value using the data context for the row.
*
* @param rowreq_ctx
* Pointer to the row request context.
* @param usmDHUserPrivKeyChange_val_ptr_ptr
* Pointer to storage for a char variable
* @param usmDHUserPrivKeyChange_val_ptr_len_ptr
* Pointer to a size_t. On entry, it will contain the size (in bytes)
* pointed to by usmDHUserPrivKeyChange.
* On exit, this value should contain the data size (in bytes).
*
* @retval MFD_SUCCESS : success
* @retval MFD_SKIP : skip this node (no value for now)
* @retval MFD_ERROR : Any other error
*
* @note If you need more than (*usmDHUserPrivKeyChange_val_ptr_len_ptr) bytes of memory,
* allocate it using malloc() and update usmDHUserPrivKeyChange_val_ptr_ptr.
* <b>DO NOT</b> free the previous pointer.
* The MFD helper will release the memory you allocate.
*
* @remark If you call this function yourself, you are responsible
* for checking if the pointer changed, and freeing any
* previously allocated memory. (Not necessary if you pass
* in a pointer to static memory, obviously.)
*/
int
usmDHUserPrivKeyChange_get(usmDHUserKeyTable_rowreq_ctx * rowreq_ctx,
u_char **usmDHUserPrivKeyChange_val_ptr_ptr,
size_t *usmDHUserPrivKeyChange_val_ptr_len_ptr)
{
/** we should have a non-NULL pointer and enough storage */
netsnmp_assert((NULL != usmDHUserPrivKeyChange_val_ptr_ptr)
&& (NULL != *usmDHUserPrivKeyChange_val_ptr_ptr));
netsnmp_assert(NULL != usmDHUserPrivKeyChange_val_ptr_len_ptr);
DEBUGMSGTL(("verbose:usmDHUserKeyTable:usmDHUserPrivKeyChange_get",
"called\n"));
netsnmp_assert(NULL != rowreq_ctx);
/*
* TODO:231:o: |-> Extract the current value of the usmDHUserPrivKeyChange data.
* copy (* usmDHUserPrivKeyChange_val_ptr_ptr ) data and (* usmDHUserPrivKeyChange_val_ptr_len_ptr ) from rowreq_ctx->data
*/
if (!rowreq_ctx || !usmDHUserPrivKeyChange_val_ptr_len_ptr ||
!usmDHUserPrivKeyChange_val_ptr_ptr ||
!*usmDHUserPrivKeyChange_val_ptr_ptr) {
return MFD_ERROR;
}
return usmDHGetUserKeyChange(rowreq_ctx->data, 0,
usmDHUserPrivKeyChange_val_ptr_ptr,
usmDHUserPrivKeyChange_val_ptr_len_ptr);
} /* usmDHUserPrivKeyChange_get */
/*---------------------------------------------------------------------
* SNMP-USM-DH-OBJECTS-MIB::usmDHUserKeyEntry.usmDHUserOwnPrivKeyChange
* usmDHUserOwnPrivKeyChange is subid 4 of usmDHUserKeyEntry.
* Its status is Current, and its access level is Create.
* OID: .1.3.6.1.3.101.1.1.2.1.4
* Description:
The object used to change the agent's own Privacy Key using a
Diffie-Hellman key exchange.
The right-most n bits of the shared secret 'sk', where 'n' is the
number of bits required for the protocol defined by
usmUserPrivProtocol, are installed as the operational privacy key
for this row after a successful SET.
*
* Attributes:
* accessible 1 isscalar 0 enums 0 hasdefval 0
* readable 1 iscolumn 1 ranges 0 hashint 0
* settable 1
*
*
* Its syntax is DHKeyChange (based on perltype OCTETSTR)
* The net-snmp type is ASN_OCTET_STR. The C type decl is char (char)
* This data type requires a length.
*/
/**
* Extract the current value of the usmDHUserOwnPrivKeyChange data.
*
* Set a value using the data context for the row.
*
* @param rowreq_ctx
* Pointer to the row request context.
* @param usmDHUserOwnPrivKeyChange_val_ptr_ptr
* Pointer to storage for a char variable
* @param usmDHUserOwnPrivKeyChange_val_ptr_len_ptr
* Pointer to a size_t. On entry, it will contain the size (in bytes)
* pointed to by usmDHUserOwnPrivKeyChange.
* On exit, this value should contain the data size (in bytes).
*
* @retval MFD_SUCCESS : success
* @retval MFD_SKIP : skip this node (no value for now)
* @retval MFD_ERROR : Any other error
*
* @note If you need more than (*usmDHUserOwnPrivKeyChange_val_ptr_len_ptr) bytes of memory,
* allocate it using malloc() and update usmDHUserOwnPrivKeyChange_val_ptr_ptr.
* <b>DO NOT</b> free the previous pointer.
* The MFD helper will release the memory you allocate.
*
* @remark If you call this function yourself, you are responsible
* for checking if the pointer changed, and freeing any
* previously allocated memory. (Not necessary if you pass
* in a pointer to static memory, obviously.)
*/
int
usmDHUserOwnPrivKeyChange_get(usmDHUserKeyTable_rowreq_ctx * rowreq_ctx,
u_char **usmDHUserOwnPrivKeyChange_val_ptr_ptr,
size_t
*usmDHUserOwnPrivKeyChange_val_ptr_len_ptr)
{
/** we should have a non-NULL pointer and enough storage */
netsnmp_assert((NULL != usmDHUserOwnPrivKeyChange_val_ptr_ptr)
&& (NULL != *usmDHUserOwnPrivKeyChange_val_ptr_ptr));
netsnmp_assert(NULL != usmDHUserOwnPrivKeyChange_val_ptr_len_ptr);
DEBUGMSGTL(("verbose:usmDHUserKeyTable:usmDHUserOwnPrivKeyChange_get",
"called\n"));
netsnmp_assert(NULL != rowreq_ctx);
/*
* TODO:231:o: |-> Extract the current value of the usmDHUserOwnPrivKeyChange data.
* copy (* usmDHUserOwnPrivKeyChange_val_ptr_ptr ) data and (* usmDHUserOwnPrivKeyChange_val_ptr_len_ptr ) from rowreq_ctx->data
*/
if (!rowreq_ctx || !usmDHUserOwnPrivKeyChange_val_ptr_len_ptr ||
!usmDHUserOwnPrivKeyChange_val_ptr_ptr ||
!*usmDHUserOwnPrivKeyChange_val_ptr_ptr) {
return MFD_ERROR;
}
return usmDHGetUserKeyChange(rowreq_ctx->data, 0,
usmDHUserOwnPrivKeyChange_val_ptr_ptr,
usmDHUserOwnPrivKeyChange_val_ptr_len_ptr);
} /* usmDHUserOwnPrivKeyChange_get */
/** @} */
| 37.277868 | 132 | 0.636186 |
7fce867f3b829ab77b04f31b372b52065fafcb7e | 56,871 | h | C | C++/Morwenn's rewrite of Summer Dragonfly's GrailSort/grailsort.h | AceOfSpadesProduc100/Rewritten-Grailsort | 884f61b3bca8e9f429981a055f30cf53a1ee64c2 | [
"MIT"
] | 26 | 2020-10-21T01:22:46.000Z | 2021-05-13T01:50:17.000Z | C++/Morwenn's rewrite of Summer Dragonfly's GrailSort/grailsort.h | AceOfSpadesProduc100/Rewritten-Grailsort | 884f61b3bca8e9f429981a055f30cf53a1ee64c2 | [
"MIT"
] | 1 | 2021-01-08T12:18:08.000Z | 2021-03-27T17:46:34.000Z | C++/Morwenn's rewrite of Summer Dragonfly's GrailSort/grailsort.h | AceOfSpadesProduc100/Rewritten-Grailsort | 884f61b3bca8e9f429981a055f30cf53a1ee64c2 | [
"MIT"
] | 5 | 2020-10-23T10:08:37.000Z | 2021-02-12T12:52:28.000Z | /*
* MIT License
*
* Copyright (c) 2013 Andrey Astrelin
* Copyright (c) 2020-2021 The Holy Grail Sort Project
*
* 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.
*/
/*
* The Holy Grail Sort Project
* Project Manager: Summer Dragonfly
* Project Contributors: 666666t
* Anonymous0726
* aphitorite
* Control
* dani_dlg
* DeveloperSort
* EilrahcF
* Enver
* Gaming32
* lovebuny
* Morwenn
* MP
* phoenixbound
* Spex_guy
* thatsOven
* _fluffyy
*
* Special thanks to "The Studio" Discord community!
*/
#ifndef REWRITTEN_GRAILSORT_H_
#define REWRITTEN_GRAILSORT_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <algorithm>
#include <functional>
#include <iterator>
#include <type_traits>
#include <utility>
namespace grailsort_detail
{
// Credit to phoenixbound for this clever idea
enum struct Subarray
{
LEFT,
RIGHT
};
template<typename Compare>
struct ThreeWayCompare
{
Compare compare;
explicit ThreeWayCompare(Compare&& comp):
compare(std::forward<Compare>(comp))
{}
template<typename T, typename U>
int operator()(T&& lhs, U&& rhs)
{
if (compare(lhs, rhs)) {
return -1;
}
if (compare(rhs, lhs)) {
return 1;
}
return 0;
}
};
struct GrailSort
{
int currBlockLen;
Subarray currBlockOrigin;
template<typename RandomAccessIterator>
static void BlockSwap(RandomAccessIterator array, int a, int b, int blockLen) {
std::swap_ranges(array + a, array + (a + blockLen), array + b);
}
// Swaps the order of two adjacent blocks whose lengths may or may not be equal.
// Variant of the Gries-Mills algorithm, which is basically recursive block swaps
template<typename RandomAccessIterator>
static void Rotate(RandomAccessIterator array, int start, int leftLen, int rightLen) {
while(leftLen > 0 && rightLen > 0) {
if(leftLen <= rightLen) {
BlockSwap(array, start, start + leftLen, leftLen);
start += leftLen;
rightLen -= leftLen;
}
else {
BlockSwap(array, start + leftLen - rightLen, start + leftLen, rightLen);
leftLen -= rightLen;
}
}
}
// Variant of Insertion Sort that utilizes swaps instead of overwrites.
// Also known as "Optimized Gnomesort".
template<typename RandomAccessIterator, typename Compare>
static void InsertSort(RandomAccessIterator array, int start, int length, Compare comp) {
for(int item = 1; item < length; item++) {
int left = start + item - 1;
int right = start + item;
while(left >= start && comp(array[left], array[right]) > 0) {
std::iter_swap(array + left, array + right);
left--;
right--;
}
}
}
template<typename RandomAccessIterator, typename Compare, typename T>
static int BinarySearchLeft(RandomAccessIterator array, int start, int length, const T& target, Compare comp) {
int left = 0;
int right = length;
while(left < right) {
// equivalent to (left + right) / 2 with added overflow protection
int middle = left + ((right - left) / 2);
if(comp(array[start + middle], target) < 0) {
left = middle + 1;
}
else {
right = middle;
}
}
return left;
}
// Credit to Anonymous0726 for debugging
template<typename RandomAccessIterator, typename Compare, typename T>
static int BinarySearchRight(RandomAccessIterator array, int start, int length, const T& target, Compare comp) {
int left = 0;
int right = length;
while(left < right) {
// equivalent to (left + right) / 2 with added overflow protection
int middle = left + ((right - left) / 2);
if(comp(array[start + middle], target) > 0) {
right = middle;
}
else {
left = middle + 1;
}
}
// OFF-BY-ONE BUG FIXED: used to be `return right - 1;`
return right;
}
// cost: 2 * length + idealKeys^2 / 2
template<typename RandomAccessIterator, typename Compare>
static int CollectKeys(RandomAccessIterator array, int start, int length, int idealKeys, Compare comp) {
int keysFound = 1; // by itself, the first item in the array is our first unique key
int firstKey = 0; // the first item in the array is at the first position in the array
int currKey = 1; // the index used for finding potentially unique items ("keys") in the array
while(currKey < length && keysFound < idealKeys) {
// Find the location in the key-buffer where our current key can be inserted in sorted order.
// If the key at insertPos is equal to currKey, then currKey isn't unique and we move on.
int insertPos = BinarySearchLeft(array, start + firstKey, keysFound, array[start + currKey], comp);
// The second part of this conditional does the equal check we were just talking about; however,
// if currKey is larger than everything in the key-buffer (meaning insertPos == keysFound),
// then that also tells us it wasn't *equal* to anything in the key-buffer. Magic! :)
if(insertPos == keysFound || comp(array[start + currKey], array[start + firstKey + insertPos]) != 0) {
// First, rotate the key-buffer over to currKey's immediate left...
// (this helps save a TON of swaps/writes!!!)
Rotate(array, start + firstKey, keysFound, currKey - (firstKey + keysFound));
// Update the new position of firstKey...
firstKey = currKey - keysFound;
// Then, "insertion sort" currKey to its spot in the key-buffer!
Rotate(array, start + firstKey + insertPos, keysFound - insertPos, 1);
// One step closer to idealKeys.
keysFound++;
}
// Move on and test the next key...
currKey++;
}
// Bring however many keys we found back to the beginning of our array,
// and return the number of keys collected.
Rotate(array, start, firstKey, keysFound);
return keysFound;
}
template<typename RandomAccessIterator, typename Compare>
static void PairwiseSwaps(RandomAccessIterator array, int start, int length, Compare comp) {
int index;
for(index = 1; index < length; index += 2) {
int left = start + index - 1;
int right = start + index;
if(comp(array[left], array[right]) > 0) {
std::swap(array[left - 2], array[right]);
std::swap(array[right - 2], array[left]);
}
else {
std::swap(array[left - 2], array[left]);
std::swap(array[right - 2], array[right]);
}
}
int left = start + index - 1;
if(left < start + length) {
std::swap(array[left - 2], array[left]);
}
}
template<typename RandomAccessIterator, typename Compare>
static void PairwiseWrites(RandomAccessIterator array, int start, int length, Compare comp) {
int index;
for(index = 1; index < length; index += 2) {
int left = start + index - 1;
int right = start + index;
if(comp(array[left], array[right]) > 0) {
array[left - 2] = std::move(array[right]);
array[right - 2] = std::move(array[left]);
}
else {
array[left - 2] = std::move(array[left]);
array[right - 2] = std::move(array[right]);
}
}
int left = start + index - 1;
if(left < start + length) {
array[left - 2] = std::move(array[left]);
}
}
// array[buffer .. start - 1] <=> "scrolling buffer"
//
// "scrolling buffer" + array[start, middle - 1] + array[middle, end - 1]
// --> array[buffer, buffer + end - 1] + "scrolling buffer"
template<typename RandomAccessIterator, typename Compare>
static void MergeForwards(RandomAccessIterator array, int start, int leftLen, int rightLen, int bufferOffset, Compare comp) {
auto buffer = array + (start - bufferOffset);
auto left = array + start;
auto middle = array + (start + leftLen);
auto right = middle;
auto end = middle + rightLen;
while(right != end) {
if(left == middle || comp(*left, *right) > 0) {
std::iter_swap(buffer, right);
++right;
}
else {
std::iter_swap(buffer, left);
++left;
}
++buffer;
}
if(buffer != left) {
std::swap_ranges(buffer, buffer + (middle - left), left);
}
}
// credit to 666666t for thorough bug-checking/fixing
template<typename RandomAccessIterator, typename Compare>
static void MergeBackwards(RandomAccessIterator array, int start, int leftLen, int rightLen, int bufferOffset, Compare comp) {
// used to be '= start'
int end = start - 1;
// used to be '= start + leftLen - 1'
int left = end + leftLen;
int middle = left;
// OFF-BY-ONE BUG FIXED: used to be `int right = middle + rightLen - 1;`
int right = middle + rightLen;
// OFF-BY-ONE BUG FIXED: used to be `int buffer = right + bufferOffset - 1;`
int buffer = right + bufferOffset;
// used to be 'left >= end'
while(left > end) {
if(right == middle || comp(array[left], array[right]) > 0) {
std::swap(array[buffer], array[left]);
left--;
}
else {
std::swap(array[buffer], array[right]);
right--;
}
buffer--;
}
if(right != buffer) {
while(right > middle) {
std::swap(array[buffer], array[right]);
buffer--;
right--;
}
}
}
// array[buffer .. start - 1] <=> "free space"
//
// "free space" + array[start, middle - 1] + array[middle, end - 1]
// --> array[buffer, buffer + end - 1] + "free space"
//
// FUNCTION RENAMED: More consistent with "out-of-place" being at the end
template<typename RandomAccessIterator, typename Compare>
static void MergeOutOfPlace(RandomAccessIterator array, int start, int leftLen, int rightLen, int bufferOffset, Compare comp) {
int buffer = start - bufferOffset;
int left = start;
int middle = start + leftLen;
int right = middle;
int end = middle + rightLen;
while(right < end) {
if(left == middle || comp(array[left], array[right]) > 0) {
array[buffer] = std::move(array[right]);
right++;
}
else {
array[buffer] = std::move(array[left]);
left++;
}
buffer++;
}
if(buffer != left) {
while(left < middle) {
array[buffer] = std::move(array[left]);
buffer++;
left++;
}
}
}
template<typename RandomAccessIterator, typename Compare>
static void BuildInPlace(RandomAccessIterator array, int start, int length, int currentLen, int bufferLen, Compare comp) {
for(int mergeLen = currentLen; mergeLen < bufferLen; mergeLen *= 2) {
int fullMerge = 2 * mergeLen;
int mergeIndex;
int mergeEnd = start + length - fullMerge;
int bufferOffset = mergeLen;
for(mergeIndex = start; mergeIndex <= mergeEnd; mergeIndex += fullMerge) {
MergeForwards(array, mergeIndex, mergeLen, mergeLen, bufferOffset, comp);
}
int leftOver = length - (mergeIndex - start);
if(leftOver > mergeLen) {
MergeForwards(array, mergeIndex, mergeLen, leftOver - mergeLen, bufferOffset, comp);
}
else {
Rotate(array, mergeIndex - mergeLen, mergeLen, leftOver);
}
start -= mergeLen;
}
int fullMerge = 2 * bufferLen;
int lastBlock = length % fullMerge;
int lastOffset = start + length - lastBlock;
if(lastBlock <= bufferLen) {
Rotate(array, lastOffset, lastBlock, bufferLen);
}
else {
MergeBackwards(array, lastOffset, bufferLen, lastBlock - bufferLen, bufferLen, comp);
}
for(int mergeIndex = lastOffset - fullMerge; mergeIndex >= start; mergeIndex -= fullMerge) {
MergeBackwards(array, mergeIndex, bufferLen, bufferLen, bufferLen, comp);
}
}
template<typename RandomAccessIterator, typename BufferIterator, typename Compare>
void BuildOutOfPlace(RandomAccessIterator array, int start, int length, int bufferLen, int extLen,
BufferIterator extBuffer, Compare comp) {
std::move(array + (start - extLen), array + start, extBuffer);
PairwiseWrites(array, start, length, comp);
start -= 2;
int mergeLen;
for(mergeLen = 2; mergeLen < extLen; mergeLen *= 2) {
int fullMerge = 2 * mergeLen;
int mergeIndex;
int mergeEnd = start + length - fullMerge;
int bufferOffset = mergeLen;
for(mergeIndex = start; mergeIndex <= mergeEnd; mergeIndex += fullMerge) {
MergeOutOfPlace(array, mergeIndex, mergeLen, mergeLen, bufferOffset, comp);
}
int leftOver = length - (mergeIndex - start);
if(leftOver > mergeLen) {
MergeOutOfPlace(array, mergeIndex, mergeLen, leftOver - mergeLen, bufferOffset, comp);
}
else {
// MINOR CHANGE: Used to be a loop; much clearer now
std::move(array + mergeIndex, array + (mergeIndex + leftOver), array + (mergeIndex - mergeLen));
}
start -= mergeLen;
}
std::move(extBuffer, extBuffer + extLen, array + (start + length));
BuildInPlace(array, start, length, mergeLen, bufferLen, comp);
}
// build blocks of length 'bufferLen'
// input: [start - mergeLen, start - 1] elements are buffer
// output: first 'bufferLen' elements are buffer, blocks (2 * bufferLen) and last subblock sorted
template<typename RandomAccessIterator, typename BufferIterator, typename Compare>
void BuildBlocks(RandomAccessIterator array, int start, int length, int bufferLen,
BufferIterator extBuffer, int extBufferLen, Compare comp) {
if(extBufferLen != 0) {
int extLen;
if(bufferLen < extBufferLen) {
extLen = bufferLen;
}
else {
// max power of 2 -- just in case
extLen = 1;
while((extLen * 2) <= extBufferLen) {
extLen *= 2;
}
}
BuildOutOfPlace(array, start, length, bufferLen, extLen, extBuffer, comp);
}
else {
PairwiseSwaps(array, start, length, comp);
BuildInPlace(array, start - 2, length, 2, bufferLen, comp);
}
}
// Returns the final position of 'medianKey'
template<typename RandomAccessIterator, typename Compare>
static int BlockSelectSort(RandomAccessIterator array, int firstKey, int start, int medianKey, int blockCount, int blockLen, Compare comp) {
for(int firstBlock = 0; firstBlock < blockCount; firstBlock++) {
int selectBlock = firstBlock;
for(int currBlock = firstBlock + 1; currBlock < blockCount; currBlock++) {
int compare = comp(array[start + (currBlock * blockLen)],
array[start + (selectBlock * blockLen)]);
if(compare < 0 || (compare == 0 && comp(array[firstKey + currBlock],
array[firstKey + selectBlock]) < 0)) {
selectBlock = currBlock;
}
}
if(selectBlock != firstBlock) {
// Swap the left and right selected blocks...
BlockSwap(array, start + (firstBlock * blockLen), start + (selectBlock * blockLen), blockLen);
// Swap the keys...
std::swap(array[firstKey + firstBlock], array[firstKey + selectBlock]);
// ...and follow the 'medianKey' if it was swapped
// ORIGINAL LOC: if(midkey==u-1 || midkey==p) midkey^=(u-1)^p;
// MASSIVE, MASSIVE credit to lovebuny for figuring this one out!
if(medianKey == firstBlock) {
medianKey = selectBlock;
}
else if(medianKey == selectBlock) {
medianKey = firstBlock;
}
}
}
return medianKey;
}
// Swaps Grailsort's "scrolling buffer" from the right side of the array all the way back to 'start'.
// Costs O(n) swaps (amortized).
//
// OFF-BY-ONE BUG FIXED: used to be `int index = start + resetLen`; credit to 666666t for debugging
// RESTRUCTED, BETTER NAMES: 'resetLen' is now 'length' and 'bufferLen' is now 'bufferOffset'
template<typename RandomAccessIterator>
static void InPlaceBufferReset(RandomAccessIterator array, int start, int length, int bufferOffset) {
int index = start + length - 1;
int buffer = index - bufferOffset;
while(index >= start) {
std::swap(array[index], array[buffer]);
index--;
buffer--;
}
}
// Shifts entire array over 'bufferOffset' spaces to move the out-of-place merging buffer back to
// the beginning of the array.
// Costs O(n) writes (amortized).
//
// OFF-BY-ONE BUG FIXED: used to be `int index = start + resetLen`; credit to 666666t for debugging
// RESTRUCTED, BETTER NAMES: 'resetLen' is now 'length' and 'bufferLen' is now 'bufferOffset'
template<typename RandomAccessIterator>
static void OutOfPlaceBufferReset(RandomAccessIterator array, int start, int length, int bufferOffset) {
int index = start + length - 1;
int buffer = index - bufferOffset;
while(index >= start) {
array[index] = std::move(array[buffer]);
index--;
buffer--;
}
}
// Rewinds Grailsort's "scrolling buffer" to the left any items belonging to the left subarray block
// left over by a "smart merge". This is used to continue an ongoing merge that has run out of buffer space.
// Costs O(sqrt n) swaps (amortized) in the *absolute* worst-case.
//
// NAMING IMPROVED: the left over items are in the middle of the merge while the buffer is at the end
// BETTER ORDER-OF-OPERATIONS, NAMING IMPROVED: the left over items (now called 'leftBlock') are in the
// middle of the merge while the buffer is at the end
template<typename RandomAccessIterator>
static void InPlaceBufferRewind(RandomAccessIterator array, int start, int leftBlock, int buffer) {
while(leftBlock >= start) {
std::swap(array[buffer], array[leftBlock]);
leftBlock--;
buffer--;
}
}
// Rewinds Grailsort's out-of-place buffer to the left of any items belonging to the left subarray block
// left over by a "smart merge". This is used to continue an ongoing merge that has run out of buffer space.
// Costs O(sqrt n) writes (amortized) in the *absolute* worst-case.
//
// INCORRECT ORDER OF PARAMETERS BUG FIXED: `leftOvers` should be the middle, and `buffer` should be the end
// BETTER ORDER, INCORRECT ORDER OF PARAMETERS BUG FIXED: `leftOvers` (now called 'leftBlock') should be
// the middle, and `buffer` should be the end
template<typename RandomAccessIterator>
static void OutOfPlaceBufferRewind(RandomAccessIterator array, int start, int leftBlock, int buffer) {
while(leftBlock >= start) {
array[buffer] = std::move(array[leftBlock]);
leftBlock--;
buffer--;
}
}
template<typename RandomAccessIterator, typename Compare>
static Subarray GetSubarray(RandomAccessIterator array, int currKey, int medianKey, Compare comp) {
if(comp(array[currKey], array[medianKey]) < 0) {
return Subarray::LEFT;
}
else {
return Subarray::RIGHT;
}
}
// FUNCTION RE-RENAMED: last/final left blocks are used to calculate the length of the final merge
template<typename RandomAccessIterator, typename Compare>
static int CountLastMergeBlocks(RandomAccessIterator array, int offset, int blockCount, int blockLen, Compare comp) {
int blocksToMerge = 0;
int lastRightFrag = offset + (blockCount * blockLen);
int prevLeftBlock = lastRightFrag - blockLen;
while(blocksToMerge < blockCount && comp(array[lastRightFrag], array[prevLeftBlock]) < 0) {
blocksToMerge++;
prevLeftBlock -= blockLen;
}
return blocksToMerge;
}
template<typename RandomAccessIterator, typename Compare>
void SmartMerge(RandomAccessIterator array, int start, int leftLen, Subarray leftOrigin, int rightLen, int bufferOffset, Compare comp) {
auto buffer = array + (start - bufferOffset);
auto left = array + start;
auto middle = left + leftLen;
auto right = middle;
auto end = middle + rightLen;
if(leftOrigin == Subarray::LEFT) {
while(left != middle && right != end) {
if(comp(*left, *right) <= 0) {
std::iter_swap(buffer, left);
++left;
}
else {
std::iter_swap(buffer, right);
++right;
}
++buffer;
}
}
else {
while(left != middle && right != end) {
if(comp(*left, *right) < 0) {
std::iter_swap(buffer, left);
++left;
}
else {
std::iter_swap(buffer, right);
++right;
}
++buffer;
}
}
if(left < middle) {
this->currBlockLen = middle - left;
// UPDATED ARGUMENTS: 'middle' and 'end' now 'middle - 1' and 'end - 1'
InPlaceBufferRewind(array, left - array, (middle - array) - 1, (end - array) - 1);
}
else {
this->currBlockLen = end - right;
if(leftOrigin == Subarray::LEFT) {
this->currBlockOrigin = Subarray::RIGHT;
}
else {
this->currBlockOrigin = Subarray::LEFT;
}
}
}
// MINOR CHANGE: better naming -- 'insertPos' is now 'mergeLen' -- and "middle" calculation simplified
template<typename RandomAccessIterator, typename Compare>
void SmartLazyMerge(RandomAccessIterator array, int start, int leftLen, Subarray leftOrigin, int rightLen, Compare comp) {
int middle = start + leftLen;
if(leftOrigin == Subarray::LEFT) {
if(comp(array[middle - 1], array[middle]) > 0) {
while(leftLen != 0) {
int mergeLen = BinarySearchLeft(array, middle, rightLen, array[start], comp);
if(mergeLen != 0) {
Rotate(array, start, leftLen, mergeLen);
start += mergeLen;
rightLen -= mergeLen;
}
middle += mergeLen;
if(rightLen == 0) {
this->currBlockLen = leftLen;
return;
}
else {
do {
start++;
leftLen--;
} while(leftLen != 0 && comp(array[start], array[middle]) <= 0);
}
}
}
}
else {
if(comp(array[middle - 1], array[middle]) >= 0) {
while(leftLen != 0) {
int mergeLen = BinarySearchRight(array, start + leftLen, rightLen, array[start], comp);
if(mergeLen != 0) {
Rotate(array, start, leftLen, mergeLen);
start += mergeLen;
rightLen -= mergeLen;
}
middle += mergeLen;
if(rightLen == 0) {
this->currBlockLen = leftLen;
return;
}
else {
do {
start++;
leftLen--;
} while(leftLen != 0 && comp(array[start], array[middle]) < 0);
}
}
}
}
this->currBlockLen = rightLen;
if(leftOrigin == Subarray::LEFT) {
this->currBlockOrigin = Subarray::RIGHT;
}
else {
this->currBlockOrigin = Subarray::LEFT;
}
}
// FUNCTION RENAMED: more consistent with other "out-of-place" merges
template<typename RandomAccessIterator, typename Compare>
void SmartMergeOutOfPlace(RandomAccessIterator array, int start, int leftLen, Subarray leftOrigin, int rightLen, int bufferOffset, Compare comp) {
int buffer = start - bufferOffset;
int left = start;
int middle = start + leftLen;
int right = middle;
int end = middle + rightLen;
if(leftOrigin == Subarray::LEFT) {
while(left < middle && right < end) {
if(comp(array[left], array[right]) <= 0) {
array[buffer] = std::move(array[left]);
left++;
}
else {
array[buffer] = std::move(array[right]);
right++;
}
buffer++;
}
}
else {
while(left < middle && right < end) {
if(comp(array[left], array[right]) < 0) {
array[buffer] = std::move(array[left]);
left++;
}
else {
array[buffer] = std::move(array[right]);
right++;
}
buffer++;
}
}
if(left < middle) {
this->currBlockLen = middle - left;
// UPDATED ARGUMENTS: 'middle' and 'end' now 'middle - 1' and 'end - 1'
OutOfPlaceBufferRewind(array, left, middle - 1, end - 1);
}
else {
this->currBlockLen = end - right;
if(leftOrigin == Subarray::LEFT) {
this->currBlockOrigin = Subarray::RIGHT;
}
else {
this->currBlockOrigin = Subarray::LEFT;
}
}
}
// Credit to Anonymous0726 for better variable names such as "nextBlock"
// Also minor change: removed unnecessary "currBlock = nextBlock" lines
template<typename RandomAccessIterator, typename Compare>
void MergeBlocks(RandomAccessIterator array, int firstKey, int medianKey, int start, int blockCount, int blockLen,
int lastMergeBlocks, int lastLen, Compare comp) {
int buffer;
int currBlock;
int nextBlock = start + blockLen;
this->currBlockLen = blockLen;
this->currBlockOrigin = GetSubarray(array, firstKey, medianKey, comp);
Subarray nextBlockOrigin;
for(int keyIndex = 1; keyIndex < blockCount; keyIndex++, nextBlock += blockLen) {
currBlock = nextBlock - this->currBlockLen;
nextBlockOrigin = GetSubarray(array, firstKey + keyIndex, medianKey, comp);
if(nextBlockOrigin == this->currBlockOrigin) {
buffer = currBlock - blockLen;
BlockSwap(array, buffer, currBlock, this->currBlockLen);
this->currBlockLen = blockLen;
}
else {
SmartMerge(array, currBlock, this->currBlockLen, this->currBlockOrigin, blockLen, blockLen, comp);
}
}
currBlock = nextBlock - this->currBlockLen;
buffer = currBlock - blockLen;
if(lastLen != 0) {
if(this->currBlockOrigin == Subarray::RIGHT) {
BlockSwap(array, buffer, currBlock, this->currBlockLen);
currBlock = nextBlock;
this->currBlockLen = blockLen * lastMergeBlocks;
this->currBlockOrigin = Subarray::LEFT;
}
else {
this->currBlockLen += blockLen * lastMergeBlocks;
}
MergeForwards(array, currBlock, this->currBlockLen, lastLen, blockLen, comp);
}
else {
BlockSwap(array, buffer, currBlock, this->currBlockLen);
}
}
template<typename RandomAccessIterator, typename Compare>
void LazyMergeBlocks(RandomAccessIterator array, int firstKey, int medianKey, int start, int blockCount, int blockLen,
int lastMergeBlocks, int lastLen, Compare comp) {
int currBlock;
int nextBlock = start + blockLen;
this->currBlockLen = blockLen;
this->currBlockOrigin = GetSubarray(array, firstKey, medianKey, comp);
Subarray nextBlockOrigin;
for(int keyIndex = 1; keyIndex < blockCount; keyIndex++, nextBlock += blockLen) {
currBlock = nextBlock - this->currBlockLen;
nextBlockOrigin = GetSubarray(array, firstKey + keyIndex, medianKey, comp);
if(nextBlockOrigin == this->currBlockOrigin) {
this->currBlockLen = blockLen;
}
else {
// These checks were included in the original code... but why???
if(blockLen != 0 && this->currBlockLen != 0) {
SmartLazyMerge(array, currBlock, this->currBlockLen, this->currBlockOrigin, blockLen, comp);
}
}
}
currBlock = nextBlock - this->currBlockLen;
if(lastLen != 0) {
if(this->currBlockOrigin == Subarray::RIGHT) {
currBlock = nextBlock;
this->currBlockLen = blockLen * lastMergeBlocks;
this->currBlockOrigin = Subarray::LEFT;
}
else {
this->currBlockLen += blockLen * lastMergeBlocks;
}
LazyMerge(array, currBlock, this->currBlockLen, lastLen, comp);
}
}
template<typename RandomAccessIterator, typename Compare>
void MergeBlocksOutOfPlace(RandomAccessIterator array, int firstKey, int medianKey, int start, int blockCount, int blockLen,
int lastMergeBlocks, int lastLen, Compare comp) {
int buffer;
int currBlock;
int nextBlock = start + blockLen;
this->currBlockLen = blockLen;
this->currBlockOrigin = GetSubarray(array, firstKey, medianKey, comp);
Subarray nextBlockOrigin;
for(int keyIndex = 1; keyIndex < blockCount; keyIndex++, nextBlock += blockLen) {
currBlock = nextBlock - this->currBlockLen;
nextBlockOrigin = GetSubarray(array, firstKey + keyIndex, medianKey, comp);
if(nextBlockOrigin == this->currBlockOrigin) {
buffer = currBlock - blockLen;
std::move(array + currBlock, array + (currBlock + this->currBlockLen), array + buffer);
this->currBlockLen = blockLen;
}
else {
SmartMergeOutOfPlace(array, currBlock, this->currBlockLen, this->currBlockOrigin, blockLen, blockLen, comp);
}
}
currBlock = nextBlock - this->currBlockLen;
buffer = currBlock - blockLen;
if(lastLen != 0) {
if(this->currBlockOrigin == Subarray::RIGHT) {
std::move(array + currBlock, array + (currBlock + this->currBlockLen), array + buffer);
currBlock = nextBlock;
this->currBlockLen = blockLen * lastMergeBlocks;
this->currBlockOrigin = Subarray::LEFT;
}
else {
this->currBlockLen += blockLen * lastMergeBlocks;
}
MergeOutOfPlace(array, currBlock, this->currBlockLen, lastLen, blockLen, comp);
}
else {
std::move(array + currBlock, array + (currBlock + this->currBlockLen), array + buffer);
}
}
//TODO: Double-check "Merge Blocks" arguments
template<typename RandomAccessIterator, typename Compare>
void CombineInPlace(RandomAccessIterator array, int firstKey, int start, int length, int subarrayLen, int blockLen,
int mergeCount, int lastSubarrays, bool buffer, Compare comp) {
int fullMerge = 2 * subarrayLen;
// SLIGHT OPTIMIZATION: 'blockCount' only needs to be calculated once for regular merges
int blockCount = fullMerge / blockLen;
for(int mergeIndex = 0; mergeIndex < mergeCount; mergeIndex++) {
int offset = start + (mergeIndex * fullMerge);
InsertSort(array, firstKey, blockCount, comp);
// INCORRECT PARAMETER BUG FIXED: `block select sort` should be using `offset`, not `start`
int medianKey = subarrayLen / blockLen;
medianKey = BlockSelectSort(array, firstKey, offset, medianKey, blockCount, blockLen, comp);
if(buffer) {
MergeBlocks(array, firstKey, firstKey + medianKey, offset, blockCount, blockLen, 0, 0, comp);
}
else {
LazyMergeBlocks(array, firstKey, firstKey + medianKey, offset, blockCount, blockLen, 0, 0, comp);
}
}
// INCORRECT CONDITIONAL/PARAMETER BUG FIXED: Credit to 666666t for debugging.
if(lastSubarrays != 0) {
int offset = start + (mergeCount * fullMerge);
blockCount = lastSubarrays / blockLen;
InsertSort(array, firstKey, blockCount + 1, comp);
// INCORRECT PARAMETER BUG FIXED: `block select sort` should be using `offset`, not `start`
int medianKey = subarrayLen / blockLen;
medianKey = BlockSelectSort(array, firstKey, offset, medianKey, blockCount, blockLen, comp);
// MISSING BOUNDS CHECK BUG FIXED: `lastFragment` *can* be 0 if the last two subarrays are evenly
// divided into blocks. This prevents Grailsort from going out-of-bounds.
int lastFragment = lastSubarrays - (blockCount * blockLen);
int lastMergeBlocks;
if(lastFragment != 0) {
lastMergeBlocks = CountLastMergeBlocks(array, offset, blockCount, blockLen, comp);
}
else {
lastMergeBlocks = 0;
}
int smartMerges = blockCount - lastMergeBlocks;
//TODO: Double-check if this micro-optimization works correctly like the original
if(smartMerges == 0) {
int leftLen = lastMergeBlocks * blockLen;
// INCORRECT PARAMETER BUG FIXED: these merges should be using `offset`, not `start`
if(buffer) {
MergeForwards(array, offset, leftLen, lastFragment, blockLen, comp);
}
else {
LazyMerge(array, offset, leftLen, lastFragment, comp);
}
}
else {
if(buffer) {
MergeBlocks(array, firstKey, firstKey + medianKey, offset,
smartMerges, blockLen, lastMergeBlocks, lastFragment, comp);
}
else {
LazyMergeBlocks(array, firstKey, firstKey + medianKey, offset,
smartMerges, blockLen, lastMergeBlocks, lastFragment, comp);
}
}
}
if(buffer) {
InPlaceBufferReset(array, start, length, blockLen);
}
}
template<typename RandomAccessIterator, typename BufferIterator, typename Compare>
void CombineOutOfPlace(RandomAccessIterator array, int firstKey, int start, int length, int subarrayLen, int blockLen,
int mergeCount, int lastSubarrays, BufferIterator extBuffer, int extBufferLen, Compare comp) {
std::move(array + (start - blockLen), array + start, extBuffer);
int fullMerge = 2 * subarrayLen;
// SLIGHT OPTIMIZATION: 'blockCount' only needs to be calculated once for regular merges
int blockCount = fullMerge / blockLen;
for(int mergeIndex = 0; mergeIndex < mergeCount; mergeIndex++) {
int offset = start + (mergeIndex * fullMerge);
InsertSort(array, firstKey, blockCount, comp);
// INCORRECT PARAMETER BUG FIXED: `block select sort` should be using `offset`, not `start`
int medianKey = subarrayLen / blockLen;
medianKey = BlockSelectSort(array, firstKey, offset, medianKey, blockCount, blockLen, comp);
MergeBlocksOutOfPlace(array, firstKey, firstKey + medianKey, offset,
blockCount, blockLen, 0, 0, comp);
}
// INCORRECT CONDITIONAL/PARAMETER BUG FIXED: Credit to 666666t for debugging.
if(lastSubarrays != 0) {
int offset = start + (mergeCount * fullMerge);
blockCount = lastSubarrays / blockLen;
InsertSort(array, firstKey, blockCount + 1, comp);
// INCORRECT PARAMETER BUG FIXED: `block select sort` should be using `offset`, not `start`
int medianKey = subarrayLen / blockLen;
medianKey = BlockSelectSort(array, firstKey, offset, medianKey, blockCount, blockLen, comp);
// MISSING BOUNDS CHECK BUG FIXED: `lastFragment` *can* be 0 if the last two subarrays are evenly
// divided into blocks. This prevents Grailsort from going out-of-bounds.
int lastFragment = lastSubarrays - (blockCount * blockLen);
int lastMergeBlocks;
if(lastFragment != 0) {
lastMergeBlocks = CountLastMergeBlocks(array, offset, blockCount, blockLen, comp);
}
else {
lastMergeBlocks = 0;
}
int smartMerges = blockCount - lastMergeBlocks;
if(smartMerges == 0) {
// MINOR CHANGE: renamed for consistency (used to be 'leftLength')
int leftLen = lastMergeBlocks * blockLen;
// INCORRECT PARAMETER BUG FIXED: this merge should be using `offset`, not `start`
MergeOutOfPlace(array, offset, leftLen, lastFragment, blockLen, comp);
}
else {
MergeBlocksOutOfPlace(array, firstKey, firstKey + medianKey, offset,
smartMerges, blockLen, lastMergeBlocks, lastFragment, comp);
}
}
OutOfPlaceBufferReset(array, start, length, blockLen);
std::move(extBuffer, extBuffer + blockLen, array + (start - blockLen));
}
// Keys are on the left side of array. Blocks of length 'subarrayLen' combined. We'll combine them in pairs
// 'subarrayLen' is a power of 2. (2 * subarrayLen / blockLen) keys are guaranteed
//
// IMPORTANT RENAMES: 'lastSubarray' is now 'lastSubarrays' because it includes the length of the last left
// subarray AND last right subarray (if there is a right subarray at all).
//
// *Please also check everything surrounding 'if(lastSubarrays != 0)' inside
// 'combine in-/out-of-place' methods for other renames!!*
template<typename RandomAccessIterator, typename BufferIterator, typename Compare>
void CombineBlocks(RandomAccessIterator array, int firstKey, int start, int length, int subarrayLen, int blockLen,
bool buffer, BufferIterator extBuffer, int extBufferLen, Compare comp) {
int fullMerge = 2 * subarrayLen;
int mergeCount = length / fullMerge;
int lastSubarrays = length - (fullMerge * mergeCount);
if(lastSubarrays <= subarrayLen) {
length -= lastSubarrays;
lastSubarrays = 0;
}
// INCOMPLETE CONDITIONAL BUG FIXED: In order to combine blocks out-of-place, we must check if a full-sized
// block fits into our external buffer.
if(buffer && blockLen <= extBufferLen) {
CombineOutOfPlace(array, firstKey, start, length, subarrayLen, blockLen, mergeCount, lastSubarrays,
extBuffer, extBufferLen, comp);
}
else {
CombineInPlace(array, firstKey, start, length, subarrayLen, blockLen,
mergeCount, lastSubarrays, buffer, comp);
}
}
// "Classic" in-place merge sort using binary searches and rotations
//
// cost: min(leftLen, rightLen)^2 + max(leftLen, rightLen)
// MINOR CHANGES: better naming -- 'insertPos' is now 'mergeLen' -- and "middle"/"end" calculations simplified
template<typename RandomAccessIterator, typename Compare>
static void LazyMerge(RandomAccessIterator array, int start, int leftLen, int rightLen, Compare comp) {
if(leftLen < rightLen) {
int middle = start + leftLen;
while(leftLen != 0) {
int mergeLen = BinarySearchLeft(array, middle, rightLen, array[start], comp);
if(mergeLen != 0) {
Rotate(array, start, leftLen, mergeLen);
start += mergeLen;
rightLen -= mergeLen;
}
middle += mergeLen;
if(rightLen == 0) {
break;
}
else {
do {
start++;
leftLen--;
} while(leftLen != 0 && comp(array[start], array[middle]) <= 0);
}
}
}
// INDEXING BUG FIXED: Credit to Anonymous0726 for debugging.
else {
int end = start + leftLen + rightLen - 1;
while(rightLen != 0) {
int mergeLen = BinarySearchRight(array, start, leftLen, array[end], comp);
if(mergeLen != leftLen) {
Rotate(array, start + mergeLen, leftLen - mergeLen, rightLen);
end -= leftLen - mergeLen;
leftLen = mergeLen;
}
if(leftLen == 0) {
break;
}
else {
int middle = start + leftLen;
do {
rightLen--;
end--;
} while(rightLen != 0 && comp(array[middle - 1], array[end]) <= 0);
}
}
}
}
template<typename RandomAccessIterator, typename Compare>
static void LazyStableSort(RandomAccessIterator array, int start, int length, Compare comp) {
for(int index = 1; index < length; index += 2) {
int left = start + index - 1;
int right = start + index;
if(comp(array[left], array[right]) > 0) {
std::swap(array[left], array[right]);
}
}
for(int mergeLen = 2; mergeLen < length; mergeLen *= 2) {
int fullMerge = 2 * mergeLen;
int mergeIndex;
int mergeEnd = length - fullMerge;
for(mergeIndex = 0; mergeIndex <= mergeEnd; mergeIndex += fullMerge) {
LazyMerge(array, start + mergeIndex, mergeLen, mergeLen, comp);
}
int leftOver = length - mergeIndex;
if(leftOver > mergeLen) {
LazyMerge(array, start + mergeIndex, mergeLen, leftOver - mergeLen, comp);
}
}
}
// Calculates the minimum between numKeys and cbrt(2 * subarrayLen * keysFound).
// Math will be further explained later, but just like in CommonSort, this
// loop is rendered completely useless by the scrolling buffer optimization;
// minKeys will always equal numKeys.
//
// Code still here for preservation purposes.
/*static int CalcMinKeys(int numKeys, long halfSubarrKeys) {
int minKeys = 1;
while(minKeys < numKeys && halfSubarrKeys != 0) {
minKeys *= 2;
halfSubarrKeys /= 8;
}
return minKeys;
}*/
template<typename RandomAccessIterator, typename BufferIterator, typename Compare>
void CommonSort(RandomAccessIterator array, int start, int length, BufferIterator extBuf, int extBufLen, Compare comp) {
if(length < 16) {
InsertSort(array, start, length, comp);
return;
}
BufferIterator extBuffer;
int extBufferLen;
int blockLen = 1;
// find the smallest power of two greater than or equal to
// the square root of the input's length
while((blockLen * blockLen) < length) {
blockLen *= 2;
}
// '((a - 1) / b) + 1' is actually a clever and very efficient
// formula for the ceiling of (a / b)
//
// credit to Anonymous0726 for figuring this out!
int keyLen = ((length - 1) / blockLen) + 1;
// Grailsort is hoping to find `2 * sqrt(n)` unique items
// throughout the array
int idealKeys = keyLen + blockLen;
//TODO: Clean up `start +` offsets
int keysFound = CollectKeys(array, start, length, idealKeys, comp);
bool idealBuffer;
if(keysFound < idealKeys) {
if(keysFound == 1) return;
if(keysFound < 4) {
// GRAILSORT STRATEGY 3 -- No block swaps or scrolling buffer; resort to Lazy Stable Sort
LazyStableSort(array, start, length, comp);
return;
}
else {
// GRAILSORT STRATEGY 2 -- Block swaps with small scrolling buffer and/or lazy merges
keyLen = blockLen;
blockLen = 0;
idealBuffer = false;
while(keyLen > keysFound) {
keyLen /= 2;
}
}
}
else {
// GRAILSORT STRATEGY 1 -- Block swaps with scrolling buffer
idealBuffer = true;
}
int bufferEnd = blockLen + keyLen;
int subarrayLen;
if(idealBuffer) {
subarrayLen = blockLen;
}
else {
subarrayLen = keyLen;
}
if(idealBuffer && extBufLen != 0) {
// GRAILSORT + EXTRA SPACE
extBuffer = extBuf;
extBufferLen = extBufLen;
}
BuildBlocks(array, start + bufferEnd, length - bufferEnd, subarrayLen,
extBuffer, extBufferLen, comp);
while((length - bufferEnd) > (2 * subarrayLen)) {
subarrayLen *= 2;
int currBlockLen = blockLen;
bool scrollingBuffer = idealBuffer;
// Huge credit to Anonymous0726, phoenixbound, and DeveloperSort for their tireless efforts
// towards deconstructing this math.
if(!idealBuffer) {
int keyBuffer = keyLen / 2;
// TODO: Rewrite explanation for this math
if(keyBuffer >= (2 * subarrayLen) / keyBuffer) {
currBlockLen = keyBuffer;
scrollingBuffer = true;
}
else {
// This is a very recent discovery, and the math will be spelled out later, but this
// "minKeys" calculation is *completely unnecessary*. "minKeys" would be less than
// "keyLen" iff keyBuffer >= (2 * subarrayLen) / keyBuffer... but this situation is
// already covered by our scrolling buffer optimization right above!! Consequently,
// "minKeys" will *always* be equal to "keyLen" when Grailsort resorts to smart lazy
// merges. Removing this loop is by itself a decent optimization, as well!
//
// Code still here for preservation purposes.
/*long halfSubarrKeys = ((long) subarrayLen * keysFound) / 2;
int minKeys = CalcMinKeys(keyLen, halfSubarrKeys);*/
currBlockLen = (2 * subarrayLen) / keyLen;
}
}
// WRONG VARIABLE BUG FIXED: 4th argument should be `length - bufferEnd`, was `length - bufferLen` before.
// Credit to 666666t and Anonymous0726 for debugging.
CombineBlocks(array, start, start + bufferEnd, length - bufferEnd,
subarrayLen, currBlockLen, scrollingBuffer,
extBuffer, extBufferLen, comp);
}
InsertSort(array, start, bufferEnd, comp);
LazyMerge(array, start, bufferEnd, length - bufferEnd, comp);
}
};
}
template<
typename RandomAccessIterator,
typename Compare = std::less<>
>
void grailsort(RandomAccessIterator first, RandomAccessIterator last, Compare comp={})
{
using value_type = typename std::iterator_traits<RandomAccessIterator>::value_type;
grailsort_detail::GrailSort gsort;
gsort.CommonSort(first, 0, last - first,
(value_type*)nullptr, 0,
grailsort_detail::ThreeWayCompare<Compare>(std::move(comp)));
}
template<
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename Compare = std::less<>
>
void grailsort(RandomAccessIterator1 first, RandomAccessIterator1 last,
RandomAccessIterator2 buff_first, RandomAccessIterator2 buff_last,
Compare comp={})
{
grailsort_detail::GrailSort gsort;
gsort.CommonSort(first, 0, last - first,
buff_first, buff_last - buff_first,
grailsort_detail::ThreeWayCompare<Compare>(std::move(comp)));
}
#endif // REWRITTEN_GRAILSORT_H_
| 42.76015 | 154 | 0.513671 |
fa1272b797c2f102003ef1067875a54eda4ef0a6 | 3,021 | h | C | 02_Library/Include/XMCocos2D/extensions/CCArtPig/APSImageHolder.h | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 02_Library/Include/XMCocos2D/extensions/CCArtPig/APSImageHolder.h | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 02_Library/Include/XMCocos2D/extensions/CCArtPig/APSImageHolder.h | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /* --------------------------------------------------------------------------
*
* File APSImageHolder.h
* Author Young-Hwan Mun
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2012 ArtPig Software LLC
*
* http://www.artpigsoft.com
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft. All rights reserved.
*
* Contact Email: xmsoft77@gmail.com
*
* --------------------------------------------------------------------------
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or ( at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* -------------------------------------------------------------------------- */
#ifndef __APSImageHolder_h__
#define __APSImageHolder_h__
#include "APSMedium.h"
#include "../../textures/CCTexture2D.h"
NS_APS_BEGIN
class APSResourceManager;
class APSDevice;
class APSImageHolder : public APSMedium
{
public :
APSImageHolder ( const KDchar* szCode = "", APSResourceManager* pManager = KD_NULL );
APSImageHolder ( APSDictionary* pProperties );
virtual ~APSImageHolder ( KDvoid );
APS_CLASS_NAME ( APSImageHolder );
public :
virtual KDbool initWithProperties ( APSDictionary* pProperties );
/**
* Returns image file name that determined by applied device in runtime.
* Runtime file name is created when getRuntimeFilename ( ) is called for the
* first time, and it returns the same instance for later calls.
*/
const std::string& getRuntimeFilename ( KDvoid );
/** Returns image file name for a given device. */
virtual std::string getFilenameForDevice ( APSDevice* pDevice );
/** Returns image's full path that determined by applied device in runtime. */
const std::string* getRuntimeFullPath ( KDvoid );
/** preloads image before it is used. */
virtual KDvoid preloadData ( KDvoid );
virtual CCTexture2D* getTexture ( KDvoid );
protected :
APS_SYNTHESIZE_WITH_KEY ( CCSize, m_tModelTextureSize, ModelTextureSize );
protected :
std::string* m_pRuntimeFullPath;
const std::string* m_pRuntimeFileName;
};
NS_APS_END
#endif // __APSImageHolder_h__
| 31.8 | 87 | 0.59285 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.